@marktiderman/genesis-cli 1.17.3 → 1.18.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,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync, mkdtempSync, rmSync, realpathSync, statSync, lstatSync } from 'fs';
3
- import * as path28 from 'path';
3
+ import * as path29 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';
7
7
  import { createJiti } from 'jiti';
8
8
  import { createRequire, builtinModules } from 'module';
9
9
  import { FEATURE_KINDS, PACKAGE_LAYERS, findFeatures, featureKind, overlayUpstream, FEATURE_STATUSES, FEATURE_PLATFORMS as FEATURE_PLATFORMS$1, readOverlayMarker } from '@marktiderman/genesis-features';
10
- import { execFileSync, spawnSync } from 'child_process';
10
+ import { execFileSync, spawnSync, spawn } from 'child_process';
11
+ import { tmpdir } from 'os';
11
12
  import { buildFeatureOutputs, checkFeatureOutputs, summarizeCheck } from '@marktiderman/genesis-features/node';
12
13
  import { studioSetupSql } from '@marktiderman/genesis-studio-server';
13
- import { tmpdir } from 'os';
14
14
  import { Command } from 'commander';
15
15
  import * as fs from 'fs/promises';
16
16
 
@@ -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 = path28.join(packagesDir, dir, "package.json");
29
+ const file = path29.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;
@@ -235,14 +235,14 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
235
235
  }
236
236
  });
237
237
  function inside(parent, child) {
238
- const rel = path28.relative(parent, child);
239
- return rel === "" || !rel.startsWith("..") && !path28.isAbsolute(rel);
238
+ const rel = path29.relative(parent, child);
239
+ return rel === "" || !rel.startsWith("..") && !path29.isAbsolute(rel);
240
240
  }
241
241
  function readPackageFile(packageDir2, rel) {
242
242
  const safe = safeRelative(rel);
243
243
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
244
244
  const root = realpathSync(packageDir2);
245
- const file = path28.join(root, ...safe.split("/"));
245
+ const file = path29.join(root, ...safe.split("/"));
246
246
  if (!existsSync(file)) return null;
247
247
  const real2 = realpathSync(file);
248
248
  if (!inside(root, real2)) throw new Error(`${rel} in ${packageDir2} points outside the package`);
@@ -253,7 +253,7 @@ function readPackageDir(packageDir2, rel, skipped = []) {
253
253
  const safe = safeRelative(rel);
254
254
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
255
255
  const root = realpathSync(packageDir2);
256
- const dir = path28.join(root, ...safe.split("/"));
256
+ const dir = path29.join(root, ...safe.split("/"));
257
257
  if (!existsSync(dir)) return null;
258
258
  const real2 = realpathSync(dir);
259
259
  if (!inside(root, real2) || !statSync(real2).isDirectory()) throw new Error(`${rel} in ${packageDir2} is not a folder inside the package`);
@@ -273,7 +273,7 @@ function appPath(root, rel) {
273
273
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the app`);
274
274
  if (safe.split("/").some((s) => s.toLowerCase() === ".git")) throw new Error(`"${rel}" is inside .git; refused`);
275
275
  const realRoot = realpathSync(root);
276
- const target = path28.join(realRoot, ...safe.split("/"));
276
+ const target = path29.join(realRoot, ...safe.split("/"));
277
277
  const there = (p) => {
278
278
  try {
279
279
  lstatSync(p);
@@ -282,13 +282,13 @@ function appPath(root, rel) {
282
282
  return false;
283
283
  }
284
284
  };
285
- let probe = path28.dirname(target);
286
- while (!there(probe)) probe = path28.dirname(probe);
285
+ let probe = path29.dirname(target);
286
+ while (!there(probe)) probe = path29.dirname(probe);
287
287
  let real2;
288
288
  try {
289
289
  real2 = realpathSync(probe);
290
290
  } catch {
291
- throw new Error(`${rel} goes through a broken symlink (${path28.relative(realRoot, probe)}); refused`);
291
+ throw new Error(`${rel} goes through a broken symlink (${path29.relative(realRoot, probe)}); refused`);
292
292
  }
293
293
  if (!inside(realRoot, real2)) throw new Error(`${rel} is outside the app (a symlinked folder?)`);
294
294
  if (there(target) && lstatSync(target).isSymbolicLink()) throw new Error(`${rel} is a symlink; left alone`);
@@ -300,26 +300,26 @@ function readApp(root, rel) {
300
300
  }
301
301
  function createApp(root, rel, content) {
302
302
  const file = appPath(root, rel);
303
- mkdirSync(path28.dirname(file), { recursive: true });
303
+ mkdirSync(path29.dirname(file), { recursive: true });
304
304
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
305
305
  }
306
306
  function replaceApp(root, rel, content) {
307
307
  const file = appPath(root, rel);
308
- mkdirSync(path28.dirname(file), { recursive: true });
308
+ mkdirSync(path29.dirname(file), { recursive: true });
309
309
  writeFileSync(file, content, "utf8");
310
310
  }
311
311
  function listApp(root, rel, options = {}) {
312
- const dir = path28.join(root, rel);
312
+ const dir = path29.join(root, rel);
313
313
  if (!existsSync(dir)) return [];
314
314
  const out = [];
315
- const walk2 = (r) => {
316
- for (const entry of readdirSync(path28.join(root, r), { withFileTypes: true })) {
315
+ const walk3 = (r) => {
316
+ for (const entry of readdirSync(path29.join(root, r), { withFileTypes: true })) {
317
317
  const child = `${r}/${entry.name}`;
318
- if (entry.isDirectory()) walk2(child);
318
+ if (entry.isDirectory()) walk3(child);
319
319
  else if (entry.isFile() || options.symlinks && entry.isSymbolicLink()) out.push(child);
320
320
  }
321
321
  };
322
- walk2(rel);
322
+ walk3(rel);
323
323
  return out.sort();
324
324
  }
325
325
  var sha256;
@@ -334,8 +334,8 @@ function validateLocalPackages(raw, source = "genesis.config.json") {
334
334
  return raw.map((entry, i) => {
335
335
  const where2 = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
336
336
  if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where2} must be a non-empty folder`);
337
- if (path28.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
338
- const norm = path28.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
337
+ if (path29.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
338
+ const norm = path29.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
339
339
  if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where2} must name a package folder, not the app or a parent of it ("${entry}")`);
340
340
  const parts = norm.split("/");
341
341
  if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
@@ -346,7 +346,7 @@ function validateLocalPackages(raw, source = "genesis.config.json") {
346
346
  });
347
347
  }
348
348
  function localPackageGlobs(root) {
349
- const file = path28.join(root, "genesis.config.json");
349
+ const file = path29.join(root, "genesis.config.json");
350
350
  if (!existsSync(file)) return [];
351
351
  let raw;
352
352
  try {
@@ -359,14 +359,14 @@ function localPackageGlobs(root) {
359
359
  }
360
360
  function repositoryRoot(appRoot) {
361
361
  for (let dir = appRoot; ; ) {
362
- if (existsSync(path28.join(dir, ".git"))) return dir;
363
- const parent = path28.dirname(dir);
362
+ if (existsSync(path29.join(dir, ".git"))) return dir;
363
+ const parent = path29.dirname(dir);
364
364
  if (parent === dir) return appRoot;
365
365
  dir = parent;
366
366
  }
367
367
  }
368
368
  function localPackages(root) {
369
- const appRoot = path28.resolve(root);
369
+ const appRoot = path29.resolve(root);
370
370
  const globs = localPackageGlobs(appRoot);
371
371
  const key2 = `${appRoot}
372
372
  ${globs.join("\n")}`;
@@ -375,24 +375,24 @@ ${globs.join("\n")}`;
375
375
  const dirs = /* @__PURE__ */ new Set();
376
376
  for (const glob of globs) {
377
377
  if (glob.endsWith("/*") || glob === "*") {
378
- const parent = path28.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
378
+ const parent = path29.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
379
379
  if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
380
380
  for (const entry of readdirSync(parent).sort()) {
381
381
  if (entry.startsWith(".") || entry === "node_modules") continue;
382
- dirs.add(path28.join(parent, entry));
382
+ dirs.add(path29.join(parent, entry));
383
383
  }
384
384
  } else {
385
- dirs.add(path28.join(appRoot, glob));
385
+ dirs.add(path29.join(appRoot, glob));
386
386
  }
387
387
  }
388
388
  const real2 = realpathSync(repositoryRoot(appRoot));
389
389
  const out = [];
390
390
  const byName = /* @__PURE__ */ new Map();
391
391
  for (const dir of [...dirs].sort()) {
392
- const manifest = path28.join(dir, "package.json");
392
+ const manifest = path29.join(dir, "package.json");
393
393
  if (!existsSync(manifest)) continue;
394
394
  if (!inside(real2, realpathSync(dir))) {
395
- throw new LocalPackagesError(`${path28.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
395
+ throw new LocalPackagesError(`${path29.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
396
396
  }
397
397
  let pkg;
398
398
  try {
@@ -401,7 +401,7 @@ ${globs.join("\n")}`;
401
401
  continue;
402
402
  }
403
403
  if (typeof pkg.name !== "string" || !pkg.name) continue;
404
- const rel = path28.relative(appRoot, dir).split(path28.sep).join("/");
404
+ const rel = path29.relative(appRoot, dir).split(path29.sep).join("/");
405
405
  const other = byName.get(pkg.name);
406
406
  if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
407
407
  byName.set(pkg.name, rel);
@@ -444,41 +444,41 @@ __export(discover_exports, {
444
444
  workspacePackagesDir: () => workspacePackagesDir
445
445
  });
446
446
  function cliPackageDir() {
447
- let dir = path28.dirname(fileURLToPath(import.meta.url));
447
+ let dir = path29.dirname(fileURLToPath(import.meta.url));
448
448
  for (; ; ) {
449
- const file = path28.join(dir, "package.json");
449
+ const file = path29.join(dir, "package.json");
450
450
  if (existsSync(file) && JSON.parse(readFileSync(file, "utf8")).name === CLI_PACKAGE) return dir;
451
- const parent = path28.dirname(dir);
451
+ const parent = path29.dirname(dir);
452
452
  if (parent === dir) throw new Error("Can't find the genesis-cli package folder.");
453
453
  dir = parent;
454
454
  }
455
455
  }
456
456
  function workspacePackagesDir() {
457
- const dir = path28.resolve(cliPackageDir(), "..");
458
- return existsSync(path28.join(dir, "features", "package.json")) && existsSync(path28.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
457
+ const dir = path29.resolve(cliPackageDir(), "..");
458
+ return existsSync(path29.join(dir, "features", "package.json")) && existsSync(path29.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
459
459
  }
460
460
  function readCatalog() {
461
461
  if (catalogCache) return catalogCache;
462
462
  const workspace = workspacePackagesDir();
463
463
  if (workspace) return catalogCache = buildCatalog(workspace);
464
- const file = path28.join(cliPackageDir(), "dist", "genesis-catalog.json");
464
+ const file = path29.join(cliPackageDir(), "dist", "genesis-catalog.json");
465
465
  catalogCache = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : { packages: {} };
466
466
  return catalogCache;
467
467
  }
468
468
  function installedGenesis(root) {
469
469
  const found = /* @__PURE__ */ new Map();
470
- let dir = path28.resolve(root);
470
+ let dir = path29.resolve(root);
471
471
  for (; ; ) {
472
- const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path28.join(dir, m)));
473
- const scope = path28.join(dir, "node_modules", "@marktiderman");
472
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path29.join(dir, m)));
473
+ const scope = path29.join(dir, "node_modules", "@marktiderman");
474
474
  if (existsSync(scope)) {
475
475
  for (const entry of readdirSync(scope)) {
476
476
  const name = `@marktiderman/${entry}`;
477
477
  if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
478
- if (existsSync(path28.join(scope, entry, "package.json"))) found.set(name, path28.join(scope, entry));
478
+ if (existsSync(path29.join(scope, entry, "package.json"))) found.set(name, path29.join(scope, entry));
479
479
  }
480
480
  }
481
- const parent = path28.dirname(dir);
481
+ const parent = path29.dirname(dir);
482
482
  if (atInstallRoot || parent === dir) return found;
483
483
  dir = parent;
484
484
  }
@@ -492,10 +492,10 @@ function packageDir(root, name) {
492
492
  return null;
493
493
  }
494
494
  function packageVersion(dir) {
495
- return JSON.parse(readFileSync(path28.join(dir, "package.json"), "utf8")).version;
495
+ return JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8")).version;
496
496
  }
497
497
  function declarationsOf(dir, warnings) {
498
- const pkg = JSON.parse(readFileSync(path28.join(dir, "package.json"), "utf8"));
498
+ const pkg = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
499
499
  const key2 = `${realpathSync(dir)}@${pkg.version ?? ""}`;
500
500
  let cached = declarationCache.get(key2);
501
501
  if (!cached) {
@@ -505,15 +505,15 @@ function declarationsOf(dir, warnings) {
505
505
  return cached;
506
506
  }
507
507
  async function loadDeclarations(dir, warnings) {
508
- const pkg = JSON.parse(readFileSync(path28.join(dir, "package.json"), "utf8"));
508
+ const pkg = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
509
509
  const entry = pkg.exports?.["./blocks"];
510
510
  const target = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry["import"] ?? entry["default"] : void 0;
511
511
  if (typeof target !== "string") return {};
512
512
  const rel = safeRelative(target.replace(/^\.\//, ""));
513
- const file = rel && path28.join(dir, ...rel.split("/"));
513
+ const file = rel && path29.join(dir, ...rel.split("/"));
514
514
  if (!file || !inside(dir, file) || !existsSync(file)) return {};
515
515
  try {
516
- const jiti = createJiti(path28.join(dir, "package.json"), { moduleCache: false });
516
+ const jiti = createJiti(path29.join(dir, "package.json"), { moduleCache: false });
517
517
  const mod = await jiti.import(file);
518
518
  const out = {};
519
519
  for (const value of Object.values(mod)) if (isBlockDef(value)) out[value.id] = declarationFields(value);
@@ -524,7 +524,7 @@ async function loadDeclarations(dir, warnings) {
524
524
  }
525
525
  }
526
526
  async function blocksOfInstalled(dir, warnings = [], options = {}) {
527
- const pkg = JSON.parse(readFileSync(path28.join(dir, "package.json"), "utf8"));
527
+ const pkg = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
528
528
  const raw = rawBlocksOf(pkg);
529
529
  const declared = await declarationsOf(dir, warnings);
530
530
  const ids = /* @__PURE__ */ new Set([...Object.keys(raw), ...Object.keys(declared)]);
@@ -608,7 +608,7 @@ function emptyLock() {
608
608
  return { version: 1, blocks: {}, files: {} };
609
609
  }
610
610
  function readLock(root) {
611
- const file = path28.join(root, LOCK_FILE);
611
+ const file = path29.join(root, LOCK_FILE);
612
612
  if (!existsSync(file)) return emptyLock();
613
613
  const raw = JSON.parse(readFileSync(file, "utf8"));
614
614
  if (raw.version !== 1) throw new Error(`${LOCK_FILE} has version ${String(raw.version)}; this CLI reads version 1.`);
@@ -679,7 +679,7 @@ function migrationHeader(pkg, file, source) {
679
679
  `;
680
680
  }
681
681
  function stemOrNull(file) {
682
- return MIGRATION_FILE.exec(path28.posix.basename(file))?.[2] ?? null;
682
+ return MIGRATION_FILE.exec(path29.posix.basename(file))?.[2] ?? null;
683
683
  }
684
684
  function stemOf(file) {
685
685
  const stem = stemOrNull(file);
@@ -689,7 +689,7 @@ function stemOf(file) {
689
689
  function readAppMigrations(root, dir = MIGRATIONS_DIR) {
690
690
  return listApp(root, dir, { symlinks: true }).filter((p) => p.endsWith(".sql")).map((p) => {
691
691
  const content = readApp(root, p) ?? "";
692
- const name = path28.posix.basename(p);
692
+ const name = path29.posix.basename(p);
693
693
  const m = HEADER.exec(content);
694
694
  if (m) return { path: p, name, content, tracked: { package: m[1], file: m[2], sha256: m[3], body: content.slice(m[0].length) } };
695
695
  const f = FORWARD.exec(content);
@@ -776,7 +776,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
776
776
  detail = copy.tracked ? renamed.trim() : "copied before headers; matches the package";
777
777
  } else if (copy.tracked) {
778
778
  state = "changed-upstream";
779
- detail = `${src.package} now ships a different ${path28.posix.basename(src.file)}; the applied copy is never rewritten`;
779
+ detail = `${src.package} now ships a different ${path29.posix.basename(src.file)}; the applied copy is never rewritten`;
780
780
  } else {
781
781
  state = "differs";
782
782
  detail = "has the package migration's name but other text and no header; treated as the app's own";
@@ -798,7 +798,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
798
798
  row.target = target2;
799
799
  creates.push({ path: target2, content: migrationHeader(src.package, src.file, src.source) + src.source, kind, source: { package: src.package, file: src.file } });
800
800
  if (options.tests !== false && src.test && src.testSource != null) {
801
- const test2 = `${TESTS_DIR}/${path28.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
801
+ const test2 = `${TESTS_DIR}/${path29.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
802
802
  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 } });
803
803
  }
804
804
  return;
@@ -889,25 +889,25 @@ function privacyDataType(type) {
889
889
  }
890
890
  function appPath2(v, where2, fail) {
891
891
  if (typeof v !== "string" || !v.trim()) return fail(`${where2} must be a non-empty path`);
892
- if (path28.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
893
- const norm = path28.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
892
+ if (path29.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
893
+ const norm = path29.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
894
894
  if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where2} must be a folder inside the app ("${v}")`);
895
895
  return norm;
896
896
  }
897
897
  function loadConfig(root, configPath) {
898
898
  if (configPath) {
899
- const file = path28.resolve(root, configPath);
899
+ const file = path29.resolve(root, configPath);
900
900
  if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
901
901
  const json = readJson(file);
902
- const block = path28.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
903
- return { config: validateConfig(block ?? {}, file), file, dir: path28.dirname(file) };
902
+ const block = path29.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
903
+ return { config: validateConfig(block ?? {}, file), file, dir: path29.dirname(file) };
904
904
  }
905
- const own = path28.join(root, "genesis.config.json");
905
+ const own = path29.join(root, "genesis.config.json");
906
906
  if (existsSync(own)) {
907
907
  const block = readGenesisConfig(root)?.raw.doctor;
908
908
  return { config: validateConfig(block ?? {}, own), file: own, dir: root };
909
909
  }
910
- const pkg = path28.join(root, "package.json");
910
+ const pkg = path29.join(root, "package.json");
911
911
  if (existsSync(pkg)) {
912
912
  const block = readJson(pkg)?.genesis?.doctor;
913
913
  if (block !== void 0 && !isPackageDeclaration(block)) return { config: validateConfig(block, pkg), file: pkg, dir: root };
@@ -916,7 +916,7 @@ function loadConfig(root, configPath) {
916
916
  }
917
917
  function doctorBlock(json, file, explicit) {
918
918
  const j = json;
919
- if (path28.basename(file) === "package.json") return j?.genesis?.doctor;
919
+ if (path29.basename(file) === "package.json") return j?.genesis?.doctor;
920
920
  return explicit ? j?.doctor ?? j : j?.doctor;
921
921
  }
922
922
  function isPackageDeclaration(block) {
@@ -933,7 +933,7 @@ function readJson(file) {
933
933
  }
934
934
  }
935
935
  function readGenesisConfig(root) {
936
- const file = path28.join(root, "genesis.config.json");
936
+ const file = path29.join(root, "genesis.config.json");
937
937
  if (!existsSync(file)) return null;
938
938
  const raw = readJson(file);
939
939
  if (!isObject2(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
@@ -1094,7 +1094,7 @@ function validateConfig(raw, source = "config") {
1094
1094
  if (!(c.packs ?? []).includes("supabase")) fail(`"contracts" is set but the supabase pack is not in "packs"`);
1095
1095
  if (contracts.out !== void 0) {
1096
1096
  if (typeof contracts.out !== "string" || !contracts.out.trim()) fail(`contracts.out must be a file path`);
1097
- if (path28.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1097
+ if (path29.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1098
1098
  }
1099
1099
  if (contracts.schemas !== void 0 && !isStringList(contracts.schemas)) fail(`contracts.schemas must be a list of schema names`);
1100
1100
  if (contracts.databaseEnv !== void 0 && (typeof contracts.databaseEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(contracts.databaseEnv))) {
@@ -1231,11 +1231,11 @@ var init_config = __esm({
1231
1231
  }
1232
1232
  });
1233
1233
  function findPackageDir(from, name) {
1234
- let dir = path28.resolve(from);
1234
+ let dir = path29.resolve(from);
1235
1235
  for (; ; ) {
1236
- const candidate = path28.join(dir, "node_modules", name);
1237
- if (existsSync(path28.join(candidate, "package.json"))) return candidate;
1238
- const parent = path28.dirname(dir);
1236
+ const candidate = path29.join(dir, "node_modules", name);
1237
+ if (existsSync(path29.join(candidate, "package.json"))) return candidate;
1238
+ const parent = path29.dirname(dir);
1239
1239
  if (parent === dir) return null;
1240
1240
  dir = parent;
1241
1241
  }
@@ -1287,7 +1287,7 @@ function loadCompanions(root, config, uiPackage) {
1287
1287
  function readPackageExports(root, uiPackage) {
1288
1288
  const uiDir = findPackageDir(root, uiPackage);
1289
1289
  if (!uiDir) return null;
1290
- const uiPkg = JSON.parse(readFileSync(path28.join(uiDir, "package.json"), "utf8"));
1290
+ const uiPkg = JSON.parse(readFileSync(path29.join(uiDir, "package.json"), "utf8"));
1291
1291
  const subpaths = Object.values(uiPkg.exports ?? {});
1292
1292
  const declared = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
1293
1293
  const fromSource = typeof declared !== "string" && !subpaths.some((t) => typeof exportTypes(t) === "string");
@@ -1314,23 +1314,23 @@ function readPackageExports(root, uiPackage) {
1314
1314
  }
1315
1315
  if (fromSource) {
1316
1316
  for (const m of code.matchAll(/export\s+\*\s+from\s*["'](\.[^"']*)["']/g)) {
1317
- const next = resolveSource(path28.dirname(file), m[1]);
1317
+ const next = resolveSource(path29.dirname(file), m[1]);
1318
1318
  if (next) readEntry(next);
1319
1319
  }
1320
1320
  }
1321
1321
  };
1322
- for (const entry of typeEntries) readEntry(path28.join(uiDir, entry));
1322
+ for (const entry of typeEntries) readEntry(path29.join(uiDir, entry));
1323
1323
  if (!readAny) {
1324
1324
  const what = fromSource ? "type declarations or TypeScript source" : "type declarations";
1325
1325
  throw new DoctorConfigError(`${uiPackage} has no ${what} to read (is it built?). Looked for: ${[...typeEntries].join(", ") || "none"}`);
1326
1326
  }
1327
1327
  const valueDecls = /* @__PURE__ */ new Set();
1328
1328
  const typeDecls = /* @__PURE__ */ new Set();
1329
- const declRoot = typeof mainTypes === "string" ? path28.dirname(path28.join(uiDir, mainTypes)) : uiDir;
1329
+ const declRoot = typeof mainTypes === "string" ? path29.dirname(path29.join(uiDir, mainTypes)) : uiDir;
1330
1330
  const declFiles = fromSource ? walkSource(declRoot) : walkDts(declRoot);
1331
1331
  for (const pkg of reexportedPackages) {
1332
1332
  const dir = findPackageDir(uiDir, pkg);
1333
- if (dir) walkDts(path28.join(dir, "dist"), declFiles);
1333
+ if (dir) walkDts(path29.join(dir, "dist"), declFiles);
1334
1334
  }
1335
1335
  for (const file of declFiles) {
1336
1336
  const text = readFileSync(file, "utf8");
@@ -1378,13 +1378,13 @@ function exportSource(target) {
1378
1378
  return void 0;
1379
1379
  }
1380
1380
  function resolveSource(dir, spec) {
1381
- const base = path28.resolve(dir, spec.replace(/\.js$/, ""));
1382
- const candidates = [base, ...[".ts", ".tsx", ".mts", ".cts"].map((e) => base + e), ...["index.ts", "index.tsx"].map((i) => path28.join(base, i))];
1381
+ const base = path29.resolve(dir, spec.replace(/\.js$/, ""));
1382
+ const candidates = [base, ...[".ts", ".tsx", ".mts", ".cts"].map((e) => base + e), ...["index.ts", "index.tsx"].map((i) => path29.join(base, i))];
1383
1383
  return candidates.find((f) => TS_SOURCE.test(f) && existsSync(f) && statSync(f).isFile()) ?? null;
1384
1384
  }
1385
1385
  function insidePackage(dir, file) {
1386
- const rel = path28.relative(path28.resolve(dir), path28.resolve(file));
1387
- return rel === "" || !rel.startsWith("..") && !path28.isAbsolute(rel);
1386
+ const rel = path29.relative(path29.resolve(dir), path29.resolve(file));
1387
+ return rel === "" || !rel.startsWith("..") && !path29.isAbsolute(rel);
1388
1388
  }
1389
1389
  function stripComments(code) {
1390
1390
  let out = "";
@@ -1420,7 +1420,7 @@ function walkSource(dir, out = []) {
1420
1420
  if (!existsSync(dir)) return out;
1421
1421
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1422
1422
  if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
1423
- const p = path28.join(dir, entry.name);
1423
+ const p = path29.join(dir, entry.name);
1424
1424
  if (entry.isDirectory()) walkSource(p, out);
1425
1425
  else if (isTsSource(entry.name) || /\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1426
1426
  }
@@ -1440,7 +1440,7 @@ function walkDts(dir, out = []) {
1440
1440
  if (!existsSync(dir)) return out;
1441
1441
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1442
1442
  if (entry.name === "node_modules") continue;
1443
- const p = path28.join(dir, entry.name);
1443
+ const p = path29.join(dir, entry.name);
1444
1444
  if (entry.isDirectory()) walkDts(p, out);
1445
1445
  else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1446
1446
  }
@@ -1457,27 +1457,27 @@ function resolveThemeFiles(root, config, uiDir) {
1457
1457
  }
1458
1458
  const files = [];
1459
1459
  const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
1460
- const themes = ds && path28.join(ds, "dist", "themes");
1460
+ const themes = ds && path29.join(ds, "dist", "themes");
1461
1461
  if (themes && existsSync(themes)) {
1462
- for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path28.join(themes, name));
1462
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path29.join(themes, name));
1463
1463
  }
1464
1464
  if (files.length === 0) {
1465
1465
  throw new DoctorConfigError(
1466
1466
  `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
1467
1467
  );
1468
1468
  }
1469
- const uiStyles = path28.join(uiDir, "dist", "styles.css");
1469
+ const uiStyles = path29.join(uiDir, "dist", "styles.css");
1470
1470
  if (existsSync(uiStyles)) files.push(uiStyles);
1471
1471
  return files;
1472
1472
  }
1473
1473
  function resolveSpec(root, spec) {
1474
- const local = path28.resolve(root, spec);
1475
- if (spec.startsWith(".") || path28.isAbsolute(spec)) return existsSync(local) ? local : null;
1474
+ const local = path29.resolve(root, spec);
1475
+ if (spec.startsWith(".") || path29.isAbsolute(spec)) return existsSync(local) ? local : null;
1476
1476
  const parts = spec.split("/");
1477
1477
  const nameLength = spec.startsWith("@") ? 2 : 1;
1478
1478
  const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
1479
1479
  if (dir) {
1480
- const file = path28.join(dir, ...parts.slice(nameLength));
1480
+ const file = path29.join(dir, ...parts.slice(nameLength));
1481
1481
  if (existsSync(file) && statSync(file).isFile()) return file;
1482
1482
  }
1483
1483
  return existsSync(local) ? local : null;
@@ -1485,7 +1485,7 @@ function resolveSpec(root, spec) {
1485
1485
  function loadPalette(root) {
1486
1486
  const names = new Set(TAILWIND_PALETTE);
1487
1487
  try {
1488
- const req = createRequire(path28.join(root, "package.json"));
1488
+ const req = createRequire(path29.join(root, "package.json"));
1489
1489
  const colors = req("tailwindcss/colors");
1490
1490
  for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
1491
1491
  if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
@@ -1730,7 +1730,7 @@ function globToRegExp(glob) {
1730
1730
  }
1731
1731
  function globMatcher(globs) {
1732
1732
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1733
- return (path48) => res.some((re) => re.test(path48));
1733
+ return (path51) => res.some((re) => re.test(path51));
1734
1734
  }
1735
1735
  var init_glob = __esm({
1736
1736
  "src/doctor/glob.ts"() {
@@ -1742,28 +1742,28 @@ function scanFiles(root, config) {
1742
1742
  const files = [];
1743
1743
  const seen = /* @__PURE__ */ new Set();
1744
1744
  const visit = (abs) => {
1745
- const rel = toPosix(path28.relative(root, abs));
1745
+ const rel = toPosix(path29.relative(root, abs));
1746
1746
  if (seen.has(rel) || ignored(rel)) return;
1747
- const ext = path28.extname(abs);
1747
+ const ext = path29.extname(abs);
1748
1748
  if (!extensions.has(ext)) return;
1749
1749
  if (statSync(abs).size > MAX_FILE_BYTES) return;
1750
1750
  seen.add(rel);
1751
1751
  const text = readFileSync(abs, "utf8");
1752
1752
  files.push({ path: rel, absolutePath: abs, ext, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(ext)) });
1753
1753
  };
1754
- const walk2 = (dir) => {
1754
+ const walk3 = (dir) => {
1755
1755
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1756
1756
  if (entry.isDirectory()) {
1757
- if (!SKIP_DIRS.has(entry.name)) walk2(path28.join(dir, entry.name));
1757
+ if (!SKIP_DIRS.has(entry.name)) walk3(path29.join(dir, entry.name));
1758
1758
  } else if (entry.isFile()) {
1759
- visit(path28.join(dir, entry.name));
1759
+ visit(path29.join(dir, entry.name));
1760
1760
  }
1761
1761
  }
1762
1762
  };
1763
1763
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
1764
- const abs = path28.resolve(root, src);
1764
+ const abs = path29.resolve(root, src);
1765
1765
  if (!existsSync(abs)) continue;
1766
- if (statSync(abs).isDirectory()) walk2(abs);
1766
+ if (statSync(abs).isDirectory()) walk3(abs);
1767
1767
  else visit(abs);
1768
1768
  }
1769
1769
  let local = [];
@@ -1772,7 +1772,7 @@ function scanFiles(root, config) {
1772
1772
  } catch {
1773
1773
  local = [];
1774
1774
  }
1775
- for (const pkg of local) walk2(pkg.dir);
1775
+ for (const pkg of local) walk3(pkg.dir);
1776
1776
  return files;
1777
1777
  }
1778
1778
  function lineAt(text, index) {
@@ -1800,7 +1800,132 @@ var init_scan = __esm({
1800
1800
  ];
1801
1801
  SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
1802
1802
  MAX_FILE_BYTES = 2 * 1024 * 1024;
1803
- toPosix = (p) => p.split(path28.sep).join("/");
1803
+ toPosix = (p) => p.split(path29.sep).join("/");
1804
+ }
1805
+ });
1806
+
1807
+ // src/doctor/semver.ts
1808
+ function parseVersion(v) {
1809
+ const m = VERSION.exec(v.trim());
1810
+ return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
1811
+ }
1812
+ function compareVersions(a, b) {
1813
+ for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
1814
+ if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
1815
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
1816
+ const x = a.pre[i];
1817
+ const y = b.pre[i];
1818
+ if (x === void 0) return -1;
1819
+ if (y === void 0) return 1;
1820
+ if (x === y) continue;
1821
+ const nx = /^\d+$/.test(x);
1822
+ const ny = /^\d+$/.test(y);
1823
+ if (nx && ny) return +x < +y ? -1 : 1;
1824
+ if (nx !== ny) return nx ? -1 : 1;
1825
+ return x < y ? -1 : 1;
1826
+ }
1827
+ return 0;
1828
+ }
1829
+ function partial(s) {
1830
+ const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
1831
+ if (!m) return null;
1832
+ const nums = [];
1833
+ let wild = false;
1834
+ for (const part of [m[1], m[2], m[3]]) {
1835
+ if (wild || part === void 0 || /^[xX*]$/.test(part)) {
1836
+ wild = true;
1837
+ nums.push(null);
1838
+ } else nums.push(+part);
1839
+ }
1840
+ return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
1841
+ }
1842
+ function comparators(token) {
1843
+ const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
1844
+ if (!m) return null;
1845
+ const op = m[1] ?? "";
1846
+ const p = partial(m[2]);
1847
+ if (!p) return null;
1848
+ const [major, mi, pa] = p.nums;
1849
+ if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
1850
+ const M = major;
1851
+ const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
1852
+ const next = (kind) => kind === "major" ? ver(M + 1, 0, 0, ["0"]) : kind === "minor" ? ver(M, (mi ?? 0) + 1, 0, ["0"]) : ver(M, mi ?? 0, (pa ?? 0) + 1, ["0"]);
1853
+ const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
1854
+ const out = switchOp();
1855
+ if (p.pre.length) {
1856
+ for (const c of out) if (c.v === lo) c.pre = true;
1857
+ }
1858
+ return out;
1859
+ function switchOp() {
1860
+ switch (op) {
1861
+ case "^": {
1862
+ const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
1863
+ return [
1864
+ { op: ">=", v: lo },
1865
+ { op: "<", v: bound }
1866
+ ];
1867
+ }
1868
+ case "~":
1869
+ case "~>":
1870
+ return [
1871
+ { op: ">=", v: lo },
1872
+ { op: "<", v: mi === null ? next("major") : next("minor") }
1873
+ ];
1874
+ case ">":
1875
+ return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
1876
+ case ">=":
1877
+ return [{ op: ">=", v: lo }];
1878
+ case "<":
1879
+ return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
1880
+ case "<=":
1881
+ return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
1882
+ default:
1883
+ return upper ? [
1884
+ { op: ">=", v: lo },
1885
+ { op: "<", v: upper }
1886
+ ] : [{ op: "=", v: lo }];
1887
+ }
1888
+ }
1889
+ }
1890
+ function test(c, v) {
1891
+ const d = compareVersions(v, c.v);
1892
+ return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
1893
+ }
1894
+ function parseRange(range) {
1895
+ const alts = [];
1896
+ for (const raw of range.trim().split("||")) {
1897
+ const alt = raw.trim();
1898
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
1899
+ if (hyphen) {
1900
+ const from = comparators(`>=${hyphen[1]}`);
1901
+ const to = comparators(`<=${hyphen[2]}`);
1902
+ if (!from || !to) return null;
1903
+ alts.push([...from, ...to]);
1904
+ continue;
1905
+ }
1906
+ const set = [];
1907
+ for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
1908
+ const cs = comparators(token);
1909
+ if (!cs) return null;
1910
+ set.push(...cs);
1911
+ }
1912
+ alts.push(set);
1913
+ }
1914
+ return alts;
1915
+ }
1916
+ function satisfies(version, range) {
1917
+ const v = parseVersion(version);
1918
+ const alts = parseRange(range);
1919
+ if (!v || !alts) return null;
1920
+ return alts.some(
1921
+ (set) => set.every((c) => test(c, v)) && (!v.pre.length || set.some((c) => c.pre && c.v.major === v.major && c.v.minor === v.minor && c.v.patch === v.patch))
1922
+ );
1923
+ }
1924
+ var VERSION, ver;
1925
+ var init_semver = __esm({
1926
+ "src/doctor/semver.ts"() {
1927
+ VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
1928
+ ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
1804
1929
  }
1805
1930
  });
1806
1931
  function overlayState(name, json) {
@@ -1813,7 +1938,7 @@ function overlayState(name, json) {
1813
1938
  function overlaySetupProblems(root, config, dir, name, json) {
1814
1939
  const problems = [];
1815
1940
  if (json.private !== true) problems.push(`${name}: an overlay is the app's own copy and never publishes; set "private": true`);
1816
- const rel = path28.relative(path28.resolve(root), path28.resolve(dir)).split(path28.sep).join("/");
1941
+ const rel = path29.relative(path29.resolve(root), path29.resolve(dir)).split(path29.sep).join("/");
1817
1942
  const sources = (config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)).map((s) => s.replace(/^\.\//, "").replace(/\/+$/, ""));
1818
1943
  const holds = sources.find((s) => rel === "" || s === rel || s.startsWith(`${rel}/`));
1819
1944
  if (holds !== void 0) problems.push(`${name}: an overlay lives in a package folder of its own, not in ${rel || "the app root"}, which holds the app's source (${holds})`);
@@ -1837,6 +1962,31 @@ function overlayAgeDays(since, now = /* @__PURE__ */ new Date()) {
1837
1962
  const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
1838
1963
  return Math.floor((today - Date.UTC(y, m - 1, d)) / 864e5);
1839
1964
  }
1965
+ function pinnedVersion(root, name, manifests = ["package.json"]) {
1966
+ let manifest = null;
1967
+ try {
1968
+ manifest = readReleaseManifest(root);
1969
+ } catch {
1970
+ }
1971
+ const released = manifest?.packages[name];
1972
+ if (released && parseVersion(released)) return released;
1973
+ let best = null;
1974
+ for (const file of manifests) {
1975
+ let json;
1976
+ try {
1977
+ json = JSON.parse(readFileSync(path29.join(root, file), "utf8"));
1978
+ } catch {
1979
+ continue;
1980
+ }
1981
+ for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
1982
+ const spec = json[section]?.[name];
1983
+ const v = typeof spec === "string" ? /^[\^~=]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(spec)?.[1] : void 0;
1984
+ const parsed = v && parseVersion(v);
1985
+ if (parsed && (!best || compareVersions(parsed, parseVersion(best)) > 0)) best = v;
1986
+ }
1987
+ }
1988
+ return best;
1989
+ }
1840
1990
  function checkOverlays(ctx, now = /* @__PURE__ */ new Date()) {
1841
1991
  let packages;
1842
1992
  try {
@@ -1849,7 +1999,7 @@ function checkOverlays(ctx, now = /* @__PURE__ */ new Date()) {
1849
1999
  const file = `${pkg.rel}/package.json`;
1850
2000
  let json;
1851
2001
  try {
1852
- json = JSON.parse(readFileSync(path28.join(pkg.dir, "package.json"), "utf8"));
2002
+ json = JSON.parse(readFileSync(path29.join(pkg.dir, "package.json"), "utf8"));
1853
2003
  } catch {
1854
2004
  continue;
1855
2005
  }
@@ -1892,6 +2042,18 @@ function checkOverlays(ctx, now = /* @__PURE__ */ new Date()) {
1892
2042
  message: `the overlay of ${marker.upstream} is version ${version || "(none)"}; use ${upstream2}+local.N (or ${upstream2} itself) so it reads as a local build of ${upstream2} and still satisfies peer ranges`
1893
2043
  });
1894
2044
  }
2045
+ const pinned = pinnedVersion(ctx.root, pkg.name);
2046
+ const from = parseVersion(upstream2);
2047
+ const to = pinned ? parseVersion(pinned) : null;
2048
+ if (from && to && compareVersions(from, to) < 0) {
2049
+ ctx.report({
2050
+ rule: "overlay-behind",
2051
+ level: "warn",
2052
+ file,
2053
+ subject: pkg.name,
2054
+ message: `the overlay of ${marker.upstream} is behind ${pkg.name}@${pinned}, the version the app now pins; run genesis upgrade, which rebases the overlay onto it (dropping what Genesis now ships) and moves the marker's upstream, or rebase it by hand`
2055
+ });
2056
+ }
1895
2057
  }
1896
2058
  }
1897
2059
  var GENESIS_PACKAGE_NAME, OVERLAY_NOTICE_DAYS, OVERLAY_WARN_DAYS, LOCAL_VERSION;
@@ -1900,6 +2062,8 @@ var init_overlays = __esm({
1900
2062
  init_files();
1901
2063
  init_local();
1902
2064
  init_scan();
2065
+ init_semver();
2066
+ init_versions();
1903
2067
  GENESIS_PACKAGE_NAME = /^@marktiderman\/genesis(?:-[a-z0-9-]+)?$/;
1904
2068
  OVERLAY_NOTICE_DAYS = 14;
1905
2069
  OVERLAY_WARN_DAYS = 30;
@@ -1908,7 +2072,7 @@ var init_overlays = __esm({
1908
2072
  });
1909
2073
  function readReleaseManifest(root) {
1910
2074
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
1911
- const file = dir && path28.join(dir, "dist", "versions.json");
2075
+ const file = dir && path29.join(dir, "dist", "versions.json");
1912
2076
  if (!file || !existsSync(file)) return null;
1913
2077
  return JSON.parse(readFileSync(file, "utf8"));
1914
2078
  }
@@ -1920,7 +2084,8 @@ function checkVersionSkew(ctx) {
1920
2084
  const overlay = overlays.get(name);
1921
2085
  if (overlay) {
1922
2086
  const from = overlay.marker.upstream.slice(overlay.marker.upstream.lastIndexOf("@") + 1);
1923
- if (from !== want) {
2087
+ const behind = parseVersion(from) && parseVersion(want) && compareVersions(parseVersion(from), parseVersion(want)) < 0;
2088
+ if (from !== want && !behind) {
1924
2089
  ctx.report({
1925
2090
  rule: "version-skew",
1926
2091
  level: "warn",
@@ -1933,7 +2098,7 @@ function checkVersionSkew(ctx) {
1933
2098
  }
1934
2099
  const dir = findPackageDir(ctx.root, name);
1935
2100
  if (!dir) continue;
1936
- const have = JSON.parse(readFileSync(path28.join(dir, "package.json"), "utf8")).version;
2101
+ const have = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8")).version;
1937
2102
  if (have === want) continue;
1938
2103
  ctx.report({
1939
2104
  rule: "version-skew",
@@ -1949,17 +2114,18 @@ var init_versions = __esm({
1949
2114
  "src/doctor/versions.ts"() {
1950
2115
  init_genesis();
1951
2116
  init_overlays();
2117
+ init_semver();
1952
2118
  UMBRELLA_PACKAGE = "@marktiderman/genesis";
1953
2119
  }
1954
2120
  });
1955
2121
  function findLockfile(root) {
1956
- let dir = path28.resolve(root);
2122
+ let dir = path29.resolve(root);
1957
2123
  for (; ; ) {
1958
- if (existsSync(path28.join(dir, "pnpm-lock.yaml"))) return { pm: "pnpm", dir };
1959
- if (existsSync(path28.join(dir, "bun.lock")) || existsSync(path28.join(dir, "bun.lockb"))) return { pm: "bun", dir };
1960
- if (existsSync(path28.join(dir, "yarn.lock"))) return { pm: "yarn", dir };
1961
- if (existsSync(path28.join(dir, "package-lock.json"))) return { pm: "npm", dir };
1962
- const parent = path28.dirname(dir);
2124
+ if (existsSync(path29.join(dir, "pnpm-lock.yaml"))) return { pm: "pnpm", dir };
2125
+ if (existsSync(path29.join(dir, "bun.lock")) || existsSync(path29.join(dir, "bun.lockb"))) return { pm: "bun", dir };
2126
+ if (existsSync(path29.join(dir, "yarn.lock"))) return { pm: "yarn", dir };
2127
+ if (existsSync(path29.join(dir, "package-lock.json"))) return { pm: "npm", dir };
2128
+ const parent = path29.dirname(dir);
1963
2129
  if (parent === dir) return null;
1964
2130
  dir = parent;
1965
2131
  }
@@ -1980,7 +2146,7 @@ function dedupeCommand(pm) {
1980
2146
  if (pm === "npm") return ["npm", "dedupe"];
1981
2147
  return null;
1982
2148
  }
1983
- function pinnedVersion(root, name) {
2149
+ function pinnedVersion2(root, name) {
1984
2150
  const release = readReleaseManifest(root);
1985
2151
  const fromRelease = release?.packages[name] ?? (name === "@marktiderman/genesis" ? release?.version : void 0);
1986
2152
  if (release && fromRelease) return { version: fromRelease, from: `@marktiderman/genesis ${release.version}` };
@@ -2003,10 +2169,10 @@ var init_pm = __esm({
2003
2169
  function walk(dir, exclude = []) {
2004
2170
  const out = [];
2005
2171
  const visit = (rel) => {
2006
- for (const name of readdirSync(path28.join(dir, rel)).sort()) {
2172
+ for (const name of readdirSync(path29.join(dir, rel)).sort()) {
2007
2173
  const child = rel ? `${rel}/${name}` : name;
2008
2174
  if (exclude.some((r) => r.test(child))) continue;
2009
- const stat = statSync(path28.join(dir, child));
2175
+ const stat = statSync(path29.join(dir, child));
2010
2176
  if (stat.isDirectory()) visit(child);
2011
2177
  else if (stat.isFile()) out.push(child);
2012
2178
  }
@@ -2035,17 +2201,17 @@ var init_walk = __esm({
2035
2201
  });
2036
2202
  function starterDir() {
2037
2203
  const workspace = workspacePackagesDir();
2038
- const live = workspace && path28.join(workspace, "..", "apps", "genesis-rn-starter");
2039
- if (live && existsSync(path28.join(live, "package.json"))) return live;
2040
- const packaged = path28.join(cliPackageDir(), "dist", "starter");
2041
- if (existsSync(path28.join(packaged, "package.json"))) return packaged;
2204
+ const live = workspace && path29.join(workspace, "..", "apps", "genesis-rn-starter");
2205
+ if (live && existsSync(path29.join(live, "package.json"))) return live;
2206
+ const packaged = path29.join(cliPackageDir(), "dist", "starter");
2207
+ if (existsSync(path29.join(packaged, "package.json"))) return packaged;
2042
2208
  throw new Error("This genesis-cli has no starter (dist/starter is missing): reinstall @marktiderman/genesis-cli.");
2043
2209
  }
2044
2210
  function templatesDir(cliDir = cliPackageDir()) {
2045
2211
  const workspace = workspacePackagesDir();
2046
- const live = workspace && cliDir === cliPackageDir() ? path28.join(workspace, "..", "templates") : null;
2047
- if (live && existsSync(path28.join(live, "eas"))) return live;
2048
- const packaged = path28.join(cliDir, "dist", "templates");
2212
+ const live = workspace && cliDir === cliPackageDir() ? path29.join(workspace, "..", "templates") : null;
2213
+ if (live && existsSync(path29.join(live, "eas"))) return live;
2214
+ const packaged = path29.join(cliDir, "dist", "templates");
2049
2215
  if (existsSync(packaged)) return packaged;
2050
2216
  throw new Error(`${cliDir} has no templates (dist/templates is missing).`);
2051
2217
  }
@@ -2066,6 +2232,154 @@ var init_templates = __esm({
2066
2232
  init_walk();
2067
2233
  }
2068
2234
  });
2235
+ function featuresBody(text) {
2236
+ const m = /\bfeatures:\s*\{/.exec(text);
2237
+ if (!m) return null;
2238
+ const start = m.index + m[0].length;
2239
+ const end = text.indexOf("}", start);
2240
+ return end < 0 ? null : { start, body: text.slice(start, end) };
2241
+ }
2242
+ function parseStarterFeatures(text) {
2243
+ const found = featuresBody(text);
2244
+ if (!found) return null;
2245
+ const out = {};
2246
+ for (const line of found.body.split("\n")) {
2247
+ const m = /^\s*([a-zA-Z][a-zA-Z0-9]*)\s*:\s*(true|false)\s*,?\s*(?:\/\/.*)?$/.exec(line);
2248
+ if (m) out[m[1]] = m[2] === "true";
2249
+ }
2250
+ return out;
2251
+ }
2252
+ function setStarterFeatures(text, values) {
2253
+ const found = featuresBody(text);
2254
+ if (!found) throw new Error(`${STARTER_CONFIG} has no features block`);
2255
+ let body = found.body;
2256
+ for (const [name, on] of Object.entries(values)) {
2257
+ const re = new RegExp(`^(\\s*${name}\\s*:\\s*)(true|false)`, "m");
2258
+ if (!re.test(body)) throw new Error(`${STARTER_CONFIG} has no features.${name}`);
2259
+ body = body.replace(re, `$1${on}`);
2260
+ }
2261
+ return text.slice(0, found.start) + body + text.slice(found.start + found.body.length);
2262
+ }
2263
+ function parseStarterBlocks(json, source = GENESIS_CONFIG) {
2264
+ let raw;
2265
+ try {
2266
+ raw = JSON.parse(json);
2267
+ } catch (err) {
2268
+ throw new Error(`${source} is not valid JSON: ${err.message}`);
2269
+ }
2270
+ const starter = raw?.starter;
2271
+ if (starter === void 0) return null;
2272
+ const blocks = starter?.blocks;
2273
+ if (typeof blocks !== "object" || blocks === null || Array.isArray(blocks)) throw new Error(`${source}: starter.blocks must map each feature switch to a list of block ids`);
2274
+ const out = {};
2275
+ for (const [name, ids] of Object.entries(blocks)) {
2276
+ if (name === "$comment") continue;
2277
+ if (!SWITCH.test(name) || !Array.isArray(ids) || !ids.every((id) => typeof id === "string" && BLOCK_ID2.test(id))) {
2278
+ throw new Error(`${source}: starter.blocks.${name} must be a list of block ids`);
2279
+ }
2280
+ out[name] = ids;
2281
+ }
2282
+ return out;
2283
+ }
2284
+ function readText(file) {
2285
+ try {
2286
+ return readFileSync(file, "utf8");
2287
+ } catch {
2288
+ return null;
2289
+ }
2290
+ }
2291
+ function starterBlockMap(root) {
2292
+ if (root) {
2293
+ const file = path29.join(root, GENESIS_CONFIG);
2294
+ const text2 = readText(file);
2295
+ const own = text2 === null ? null : parseStarterBlocks(text2, file);
2296
+ if (own) return own;
2297
+ }
2298
+ let dir;
2299
+ try {
2300
+ dir = starterDir();
2301
+ } catch {
2302
+ return {};
2303
+ }
2304
+ const text = readText(path29.join(dir, GENESIS_CONFIG));
2305
+ return (text === null ? null : parseStarterBlocks(text)) ?? {};
2306
+ }
2307
+ function blocksSwitchedOff(switches, map, manifests, present) {
2308
+ const ids = new Set(present);
2309
+ const off = /* @__PURE__ */ new Map();
2310
+ for (const [name, carried] of Object.entries(map)) if (switches[name] === false) {
2311
+ for (const id of carried) if (ids.has(id)) off.set(id, name);
2312
+ }
2313
+ const requires = new Map(manifests.map((m) => [m.id, m.requires]));
2314
+ const keep = [...ids].filter((id) => !off.has(id));
2315
+ for (let i = 0; i < keep.length; i++) {
2316
+ for (const r of requires.get(keep[i]) ?? []) {
2317
+ off.delete(r);
2318
+ if (!keep.includes(r)) keep.push(r);
2319
+ }
2320
+ }
2321
+ return off;
2322
+ }
2323
+ function appBlocksSwitchedOff(root, manifests, present) {
2324
+ const text = readText(path29.join(root, STARTER_CONFIG));
2325
+ const switches = text === null ? null : parseStarterFeatures(text);
2326
+ if (!switches) return /* @__PURE__ */ new Map();
2327
+ return blocksSwitchedOff(switches, starterBlockMap(existsSync(path29.join(root, GENESIS_CONFIG)) ? root : void 0), manifests, present);
2328
+ }
2329
+ function switchedOffNote(id, feature) {
2330
+ return `${id}: features.${feature} is off in ${STARTER_CONFIG}, so it's left out (turn it on to have it again)`;
2331
+ }
2332
+ function blockOfSource(source, manifests) {
2333
+ const at = source.indexOf(":");
2334
+ if (at < 1) return null;
2335
+ const pkg = source.slice(0, at);
2336
+ const rel = source.slice(at + 1);
2337
+ for (const m of manifests) {
2338
+ if (m.functions.some((fn) => fn.package === pkg && rel.startsWith(`${fn.dir}/`))) return m.id;
2339
+ if (m.migrations.some((mig) => mig.package === pkg && mig.test === rel)) return m.id;
2340
+ }
2341
+ return null;
2342
+ }
2343
+ var STARTER_CONFIG, GENESIS_CONFIG, SWITCH, BLOCK_ID2;
2344
+ var init_starter_features = __esm({
2345
+ "src/blocks/starter-features.ts"() {
2346
+ init_templates();
2347
+ STARTER_CONFIG = "starter.config.ts";
2348
+ GENESIS_CONFIG = "genesis.config.json";
2349
+ SWITCH = /^[a-zA-Z][a-zA-Z0-9]*$/;
2350
+ BLOCK_ID2 = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
2351
+ }
2352
+ });
2353
+
2354
+ // src/eas-placeholders.ts
2355
+ function placeholderKey(line, placeholder) {
2356
+ return new RegExp(`"([A-Za-z0-9_]+)"\\s*:\\s*"${placeholder}"`).exec(line)?.[1] ?? null;
2357
+ }
2358
+ function placeholderStep(file, line, placeholder) {
2359
+ const key2 = placeholderKey(line, placeholder);
2360
+ const what = EAS_PLACEHOLDERS[placeholder];
2361
+ const where2 = key2 ? `${file} ${key2}` : file;
2362
+ return what ? `${where2}: replace ${placeholder} with ${what}.` : `${where2}: replace ${placeholder} (see docs/NATIVE-RELEASE.md in the Genesis repository).`;
2363
+ }
2364
+ function findPlaceholders(file, text) {
2365
+ const out = [];
2366
+ text.split("\n").forEach((line, i) => {
2367
+ if (!file.endsWith(".json") && /^\s*#/.test(line)) return;
2368
+ for (const m of line.matchAll(/\bREPLACE_WITH_[A-Z0-9_]+/g)) out.push({ line: i + 1, text: line, placeholder: m[0] });
2369
+ });
2370
+ return out;
2371
+ }
2372
+ var EAS_PLACEHOLDERS;
2373
+ var init_eas_placeholders = __esm({
2374
+ "src/eas-placeholders.ts"() {
2375
+ EAS_PLACEHOLDERS = {
2376
+ REPLACE_WITH_APP_STORE_CONNECT_APP_ID: "the app's Apple ID from App Store Connect (create the app there, then App Information \u2192 General Information \u2192 Apple ID, a number)",
2377
+ REPLACE_WITH_APPLE_TEAM_ID: "your Apple Developer Team ID (developer.apple.com \u2192 Account \u2192 Membership details, 10 characters)",
2378
+ REPLACE_WITH_PATH_TO_GOOGLE_SERVICE_ACCOUNT_JSON: "the path to your Google Play service account key, a JSON file kept out of git (Play Console \u2192 Setup \u2192 API access); or delete submit.production.android until you ship to Google Play",
2379
+ REPLACE_WITH_APP_FOLDER: "the app's code folder (src, or apps/<name> in a monorepo)"
2380
+ };
2381
+ }
2382
+ });
2069
2383
 
2070
2384
  // src/blocks/init-native.ts
2071
2385
  var init_native_exports = {};
@@ -2127,11 +2441,17 @@ function initNative(options) {
2127
2441
  if (!BUNDLE.test(bundleId)) throw new Error(`"${bundleId}" isn't a bundle id like com.example.app.`);
2128
2442
  if (!SCHEME.test(scheme)) throw new Error(`"${scheme}" isn't a URL scheme.`);
2129
2443
  if (/["\\\n]/.test(display)) throw new Error("The display name can't contain quotes, backslashes or new lines.");
2130
- const target = path28.resolve(options.target);
2444
+ const target = path29.resolve(options.target);
2131
2445
  if (existsSync(target) && readdirSync(target).length) throw new Error(`${target} isn't empty; init writes into a new folder and never overwrites.`);
2132
2446
  const source = starterDir();
2133
- const read2 = (rel) => readFileSync(path28.join(source, rel), "utf8");
2134
- const was = starterIdentity(read2("starter.config.ts"));
2447
+ const read2 = (rel) => readFileSync(path29.join(source, rel), "utf8");
2448
+ const was = starterIdentity(read2(STARTER_CONFIG));
2449
+ const switches = parseStarterFeatures(read2(STARTER_CONFIG)) ?? {};
2450
+ const without = [...new Set(options.without ?? [])];
2451
+ const unknown = without.filter((w) => !(w in switches));
2452
+ if (unknown.length) throw new Error(`--without: ${unknown.join(", ")} ${unknown.length > 1 ? "aren't" : "isn't"} a feature switch in ${STARTER_CONFIG} (${Object.keys(switches).join(", ")}).`);
2453
+ const features2 = { ...switches, ...Object.fromEntries(without.map((w) => [w, false])) };
2454
+ if (!features2.emailSignIn && !features2.appleSignIn && !features2.googleSignIn) throw new Error("--without: emailSignIn, appleSignIn and googleSignIn would all be off, so nobody could sign in.");
2135
2455
  const substitutions = {
2136
2456
  [was.bundleId]: bundleId,
2137
2457
  [was.slug]: slug,
@@ -2144,7 +2464,7 @@ function initNative(options) {
2144
2464
  const to = rel.replace(new RegExp(`(^|/)${PACKED_GITIGNORE}$`), "$1.gitignore");
2145
2465
  files.set(to, /^supabase\/(migrations|tests)\//.test(rel) ? read2(rel) : substitute(read2(rel), substitutions));
2146
2466
  }
2147
- const versionFor = options.versionFor ?? ((name) => pinnedVersion(target, name)?.version ?? null);
2467
+ const versionFor = options.versionFor ?? ((name) => pinnedVersion2(target, name)?.version ?? null);
2148
2468
  const pkg = JSON.parse(files.get("package.json"));
2149
2469
  pkg.name = slug;
2150
2470
  const unpinned = [];
@@ -2167,14 +2487,22 @@ function initNative(options) {
2167
2487
  files.set("package.json", `${JSON.stringify(pkg, null, 2)}
2168
2488
  `);
2169
2489
  files.set("metro.config.js", METRO);
2170
- const pnpmSettings = [path28.join(source, "pnpm-workspace.yaml"), path28.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
2490
+ const pnpmSettings = [path29.join(source, "pnpm-workspace.yaml"), path29.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
2171
2491
  if (pnpmSettings) files.set("pnpm-workspace.yaml", appPnpmSettings(readFileSync(pnpmSettings, "utf8")));
2172
2492
  files.set("README.md", readme(display, slug));
2493
+ if (without.length) files.set(STARTER_CONFIG, setStarterFeatures(files.get(STARTER_CONFIG), Object.fromEntries(without.map((w) => [w, false]))));
2494
+ const carried = options.blocks.filter((b) => carriedBy(files, b)).map((b) => b.id);
2495
+ const switchedOff = blocksSwitchedOff(features2, parseStarterBlocks(read2("genesis.config.json")) ?? {}, options.blocks, carried);
2496
+ const leftOut = options.blocks.filter((b) => switchedOff.has(b.id)).map((b) => b.id);
2497
+ if (leftOut.length) leaveOut(files, options.blocks.filter((b) => switchedOff.has(b.id)));
2498
+ const since = sinceAfter(files);
2499
+ const config = files.get("genesis.config.json");
2500
+ if (since && config && !/"since"\s*:/.test(config)) files.set("genesis.config.json", config.replace(/("supabase"\s*:\s*\{[^}]*?)(\s*\})/, `$1, "since": "${since}"$2`));
2173
2501
  const lock = { ...emptyLock(), substitutions };
2174
- const cliVersion2 = pinnedVersion(target, CLI_PACKAGE)?.version;
2502
+ const cliVersion2 = pinnedVersion2(target, CLI_PACKAGE)?.version;
2175
2503
  const templates = templatesDir();
2176
2504
  for (const rel of walk(templates)) {
2177
- const text = substitute(readFileSync(path28.join(templates, rel), "utf8"), substitutions);
2505
+ const text = substitute(readFileSync(path29.join(templates, rel), "utf8"), substitutions);
2178
2506
  const to = templateTarget(rel, text);
2179
2507
  files.set(to, text);
2180
2508
  lock.files[to] = { source: `${CLI_PACKAGE}:templates/${rel}`, sha256: sha256(text), ...cliVersion2 ? { version: cliVersion2 } : {} };
@@ -2184,15 +2512,16 @@ function initNative(options) {
2184
2512
  const steps = [];
2185
2513
  const blocks = [];
2186
2514
  for (const block of options.blocks) {
2515
+ if (switchedOff.has(block.id)) continue;
2187
2516
  const stems = block.migrations.map((m) => stemOf(m.file));
2188
- const copies = stems.map((s) => migrations.find((f) => path28.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
2517
+ const copies = stems.map((s) => migrations.find((f) => path29.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
2189
2518
  if (!stems.length || copies.some((c) => !c)) continue;
2190
2519
  blocks.push(block.id);
2191
2520
  lock.blocks[block.id] = { package: block.package, ...block.version ? { version: block.version } : {} };
2192
2521
  block.migrations.forEach((m, i) => {
2193
2522
  lock.migrations = { ...lock.migrations, [migrationKey(m.package, m.file)]: copies[i] };
2194
2523
  if (m.test) {
2195
- const test2 = `${TESTS_DIR}/${path28.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
2524
+ const test2 = `${TESTS_DIR}/${path29.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
2196
2525
  if (files.has(test2)) lock.files[test2] = { source: `${m.package}:${m.test}`, sha256: sha256(files.get(test2)) };
2197
2526
  }
2198
2527
  });
@@ -2205,17 +2534,82 @@ function initNative(options) {
2205
2534
  }
2206
2535
  mkdirSync(target, { recursive: true });
2207
2536
  for (const [rel, content] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
2208
- const file = path28.join(target, ...rel.split("/"));
2209
- mkdirSync(path28.dirname(file), { recursive: true });
2537
+ const file = path29.join(target, ...rel.split("/"));
2538
+ mkdirSync(path29.dirname(file), { recursive: true });
2210
2539
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
2211
2540
  }
2212
2541
  writeLock(target, lock);
2213
2542
  steps.push(
2214
2543
  "Replace GENESIS_SHA in .github/workflows/*.yml with the commit of the Genesis release you run.",
2215
2544
  "Run eas init and put the project id in starter.config.ts app.easProjectId (builds, previews, updates).",
2216
- "Set links.hosts in genesis.config.json to your web domain, or delete the links block."
2545
+ "Set links.hosts in genesis.config.json to your web domain, or delete the links block (no app links then).",
2546
+ ...[...files].flatMap(([rel, text]) => rel === "eas.json" || rel.startsWith(".eas/") ? findPlaceholders(rel, text).map((p) => placeholderStep(rel, p.text, p.placeholder)) : [])
2217
2547
  );
2218
- return { target, files: [...files.keys(), "genesis.lock.json"].sort(), dependencies: dependencies2, unpinned, blocks, steps };
2548
+ return { target, files: [...files.keys(), "genesis.lock.json"].sort(), dependencies: dependencies2, unpinned, blocks, leftOut, steps };
2549
+ }
2550
+ }
2551
+ function carriedBy(files, block) {
2552
+ const names = [...files.keys()].filter((f) => f.startsWith(`${MIGRATIONS_DIR}/`) && f.endsWith(".sql")).map((f) => path29.posix.basename(f).replace(/^\d+_/, ""));
2553
+ return block.migrations.length > 0 && block.migrations.every((m) => names.includes(`${stemOf(m.file)}.sql`));
2554
+ }
2555
+ function sinceAfter(files) {
2556
+ const versions = [...files.keys()].filter((f) => f.startsWith(`${MIGRATIONS_DIR}/`) && f.endsWith(".sql")).map((f) => /^(\d{14})_/.exec(path29.posix.basename(f))?.[1]).filter((v) => Boolean(v)).sort();
2557
+ const last = versions.at(-1);
2558
+ return last ? String(BigInt(last) + 1n).padStart(14, "0") : null;
2559
+ }
2560
+ function featTags(text) {
2561
+ return [...(text.split("\n", 1)[0] ?? "").matchAll(/@feat:([a-z0-9][a-z0-9-]*)/g)].map((m) => m[1]);
2562
+ }
2563
+ function leaveOut(files, blocks) {
2564
+ const ids = new Set(blocks.map((b) => b.id));
2565
+ const migrations = [...files.keys()].filter((f) => f.startsWith(`${MIGRATIONS_DIR}/`) && f.endsWith(".sql"));
2566
+ const schemas = /* @__PURE__ */ new Set();
2567
+ const functions = /* @__PURE__ */ new Set();
2568
+ for (const block of blocks) {
2569
+ for (const m of block.migrations) {
2570
+ const stem = stemOf(m.file);
2571
+ for (const copy of migrations.filter((f) => path29.posix.basename(f).replace(/^\d+_/, "") === `${stem}.sql`)) {
2572
+ for (const s of files.get(copy).matchAll(/\bcreate\s+schema\s+(?:if\s+not\s+exists\s+)?"?([a-z_][a-z0-9_]*)"?/gi)) schemas.add(s[1].toLowerCase());
2573
+ files.delete(copy);
2574
+ }
2575
+ files.delete(`${TESTS_DIR}/${stem}.test.sql`);
2576
+ if (m.test) files.delete(`${TESTS_DIR}/${path29.posix.basename(m.test).replace(/^\d{4}_/, "")}`);
2577
+ }
2578
+ for (const fn of block.functions) {
2579
+ const name = fn.dir.split("/").pop();
2580
+ functions.add(name);
2581
+ for (const f of [...files.keys()].filter((p) => p.startsWith(`supabase/functions/${name}/`))) files.delete(f);
2582
+ }
2583
+ }
2584
+ for (const [rel, text] of [...files]) {
2585
+ const tags = rel.startsWith("supabase/") ? featTags(text) : [];
2586
+ if (tags.length && tags.every((t) => ids.has(t))) files.delete(rel);
2587
+ }
2588
+ const toml = files.get("supabase/config.toml");
2589
+ if (toml !== void 0) {
2590
+ const paragraphs = toml.split(/\n{2,}/).filter((p) => ![...functions].some((name) => p.split("\n").includes(`[functions.${name}]`)));
2591
+ let out = paragraphs.join("\n\n");
2592
+ if (!out.endsWith("\n")) out += "\n";
2593
+ const served = /^schemas\s*=\s*\[([^\]]*)\]/m.exec(out)?.[1] ?? "";
2594
+ for (const schema of [...schemas].filter((s) => served.includes(`"${s}"`))) {
2595
+ out = out.replace(/^(schemas\s*=\s*\[)([^\]]*)\]/m, (_all, head, list) => `${head}${list.split(",").map((s) => s.trim()).filter((s) => s && s !== `"${schema}"`).join(", ")}]`);
2596
+ out = out.replace(new RegExp(`^#[^
2597
+ ]*\\b${schema}\\b[^
2598
+ ]*
2599
+ (?:#[^
2600
+ ]*
2601
+ )*(?=\\[api\\])`, "m"), "");
2602
+ }
2603
+ files.set("supabase/config.toml", out);
2604
+ }
2605
+ const config = files.get("genesis.config.json");
2606
+ if (config !== void 0 && schemas.size) {
2607
+ const json = JSON.parse(config);
2608
+ const exposed = json.doctor?.supabase?.exposedSchemas;
2609
+ if (exposed?.some((s) => schemas.has(s))) {
2610
+ const kept = exposed.filter((s) => !schemas.has(s));
2611
+ files.set("genesis.config.json", config.replace(/("exposedSchemas"\s*:\s*)\[[^\]]*\]/, `$1${JSON.stringify(kept).replace(/","/g, '", "')}`));
2612
+ }
2219
2613
  }
2220
2614
  }
2221
2615
  async function runInitNative(options) {
@@ -2229,6 +2623,8 @@ var init_init_native = __esm({
2229
2623
  init_lock();
2230
2624
  init_migrations();
2231
2625
  init_pm();
2626
+ init_starter_features();
2627
+ init_eas_placeholders();
2232
2628
  init_templates();
2233
2629
  init_walk();
2234
2630
  APP_FOLDER_PLACEHOLDER = "REPLACE_WITH_APP_FOLDER";
@@ -2681,14 +3077,14 @@ function inherit(own, source) {
2681
3077
  }
2682
3078
  function resolveViews(relations) {
2683
3079
  const done = /* @__PURE__ */ new Set();
2684
- const resolve25 = (relation, depth) => {
3080
+ const resolve26 = (relation, depth) => {
2685
3081
  if (done.has(relation.oid) || !relation.origins || depth > MAX_VIEW_DEPTH) return;
2686
3082
  done.add(relation.oid);
2687
3083
  const sources = new Set([...relation.origins.values()].map((o) => o.relation));
2688
3084
  if (sources.size !== 1) return;
2689
3085
  const source = relations.get([...sources][0]);
2690
3086
  if (!source) return;
2691
- resolve25(source, depth + 1);
3087
+ resolve26(source, depth + 1);
2692
3088
  const viewAttnumOf = /* @__PURE__ */ new Map();
2693
3089
  for (const [attnum, origin] of relation.origins) {
2694
3090
  const own = relation.columns.get(attnum);
@@ -2711,7 +3107,7 @@ function resolveViews(relations) {
2711
3107
  };
2712
3108
  if (Object.keys(inherited).length) relation.table.settings = { ...inherited, ...relation.table.settings };
2713
3109
  };
2714
- for (const relation of relations.values()) resolve25(relation, 0);
3110
+ for (const relation of relations.values()) resolve26(relation, 0);
2715
3111
  }
2716
3112
  async function introspectPostgres(sql, schemas, options = {}) {
2717
3113
  const relations = /* @__PURE__ */ new Map();
@@ -2983,7 +3379,7 @@ async function checkContracts(ctx, read2 = postgresContract) {
2983
3379
  const env = settings2.databaseEnv ?? DEFAULT_DATABASE_ENV;
2984
3380
  let current = null;
2985
3381
  try {
2986
- current = lf(readFileSync(path28.join(ctx.root, out), "utf8"));
3382
+ current = lf(readFileSync(path29.join(ctx.root, out), "utf8"));
2987
3383
  } catch {
2988
3384
  current = null;
2989
3385
  }
@@ -3007,7 +3403,7 @@ async function checkContracts(ctx, read2 = postgresContract) {
3007
3403
  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}` });
3008
3404
  return;
3009
3405
  }
3010
- const target = path28.relative(process.cwd(), path28.join(ctx.root, out)) || out;
3406
+ const target = path29.relative(process.cwd(), path29.join(ctx.root, out)) || out;
3011
3407
  const command = `genesis introspect -o ${shellArg(target)} -s ${shellArg(schemas.join(","))}${env === DEFAULT_DATABASE_ENV ? "" : ` --database-env ${shellArg(env)}`}`;
3012
3408
  if (current !== expected) {
3013
3409
  ctx.report({
@@ -3035,7 +3431,7 @@ __export(settings_exports, {
3035
3431
  });
3036
3432
  function introspectSettings(flags, root, contracts, readCurrent = () => null) {
3037
3433
  const out = flags.out ?? contracts?.out ?? DEFAULT_CONTRACT_OUT;
3038
- const target = path28.resolve(root, out);
3434
+ const target = path29.resolve(root, out);
3039
3435
  return { target, label: out, schemas: schemasFor(flags, target, contracts, readCurrent), databaseEnv: flags.databaseEnv ?? contracts?.databaseEnv ?? DEFAULT_DATABASE_ENV };
3040
3436
  }
3041
3437
  function schemasFor(flags, target, contracts, readCurrent) {
@@ -3051,19 +3447,19 @@ var init_settings = __esm({
3051
3447
  });
3052
3448
  function buildCommands(root, config) {
3053
3449
  if (config.build) return config.build;
3054
- const pkgFile = path28.join(root, "package.json");
3450
+ const pkgFile = path29.join(root, "package.json");
3055
3451
  const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
3056
3452
  const pm = packageManager(root);
3057
3453
  return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
3058
3454
  }
3059
3455
  function packageManager(root) {
3060
- let dir = path28.resolve(root);
3456
+ let dir = path29.resolve(root);
3061
3457
  for (; ; ) {
3062
- if (existsSync(path28.join(dir, "pnpm-lock.yaml"))) return "pnpm";
3063
- if (existsSync(path28.join(dir, "bun.lock")) || existsSync(path28.join(dir, "bun.lockb"))) return "bun";
3064
- if (existsSync(path28.join(dir, "yarn.lock"))) return "yarn";
3065
- if (existsSync(path28.join(dir, "package-lock.json"))) return "npm";
3066
- const parent = path28.dirname(dir);
3458
+ if (existsSync(path29.join(dir, "pnpm-lock.yaml"))) return "pnpm";
3459
+ if (existsSync(path29.join(dir, "bun.lock")) || existsSync(path29.join(dir, "bun.lockb"))) return "bun";
3460
+ if (existsSync(path29.join(dir, "yarn.lock"))) return "yarn";
3461
+ if (existsSync(path29.join(dir, "package-lock.json"))) return "npm";
3462
+ const parent = path29.dirname(dir);
3067
3463
  if (parent === dir) return "npm";
3068
3464
  dir = parent;
3069
3465
  }
@@ -3161,7 +3557,7 @@ function loadPatternRules(root, patterns, rulesDoc) {
3161
3557
  const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
3162
3558
  let all = compiled;
3163
3559
  if (rulesDoc) {
3164
- const file = path28.resolve(root, rulesDoc);
3560
+ const file = path29.resolve(root, rulesDoc);
3165
3561
  if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
3166
3562
  const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
3167
3563
  const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
@@ -3229,14 +3625,14 @@ async function loadPlugins(specs, configDir) {
3229
3625
  }
3230
3626
  function resolvePlugin(id, configDir) {
3231
3627
  try {
3232
- if (id.startsWith(".") || path28.isAbsolute(id)) return resolveFrom(path28.resolve(configDir, id), configDir);
3628
+ if (id.startsWith(".") || path29.isAbsolute(id)) return resolveFrom(path29.resolve(configDir, id), configDir);
3233
3629
  return resolveFrom(id, configDir);
3234
3630
  } catch {
3235
3631
  throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
3236
3632
  }
3237
3633
  }
3238
3634
  function resolveFrom(id, from) {
3239
- return createRequire(path28.join(from, "noop.js")).resolve(id);
3635
+ return createRequire(path29.join(from, "noop.js")).resolve(id);
3240
3636
  }
3241
3637
  var init_plugins = __esm({
3242
3638
  "src/doctor/plugins.ts"() {
@@ -3254,7 +3650,7 @@ function importSpecifiers(file) {
3254
3650
  }
3255
3651
  function checkProjectLayout(ctx) {
3256
3652
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
3257
- if (existsSync(path28.join(ctx.root, dir))) {
3653
+ if (existsSync(path29.join(ctx.root, dir))) {
3258
3654
  ctx.report({
3259
3655
  rule: "local-primitives",
3260
3656
  file: dir,
@@ -3264,7 +3660,7 @@ function checkProjectLayout(ctx) {
3264
3660
  }
3265
3661
  }
3266
3662
  for (const file of STARTER_LEFTOVERS) {
3267
- if (existsSync(path28.join(ctx.root, file))) {
3663
+ if (existsSync(path29.join(ctx.root, file))) {
3268
3664
  ctx.report({
3269
3665
  rule: "starter-leftover",
3270
3666
  level: "warn",
@@ -3352,7 +3748,7 @@ function checkTokens(ctx) {
3352
3748
  }
3353
3749
  for (const pattern of ctx.config.tokenFiles ?? []) {
3354
3750
  if (/[*?]/.test(pattern)) continue;
3355
- const abs = path28.join(ctx.root, pattern);
3751
+ const abs = path29.join(ctx.root, pattern);
3356
3752
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
3357
3753
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
3358
3754
  }
@@ -3461,6 +3857,7 @@ var init_rules = __esm({
3461
3857
  "overlay-invalid",
3462
3858
  "overlay-age",
3463
3859
  "overlay-version",
3860
+ "overlay-behind",
3464
3861
  // package rules (package-rules.ts): the rules themselves are namespaced, e.g. ui/lists-use-resource-view
3465
3862
  "package-rules-invalid",
3466
3863
  "package-rule-override",
@@ -3471,7 +3868,9 @@ var init_rules = __esm({
3471
3868
  // agent guide (primitives.ts)
3472
3869
  "agent-guide-stale",
3473
3870
  // supabase pack: contracts (contracts.ts)
3474
- "contracts-stale"
3871
+ "contracts-stale",
3872
+ // genesis.lock.json against the files (lock-files.ts)
3873
+ "lock-files"
3475
3874
  ];
3476
3875
  DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
3477
3876
  STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -3556,10 +3955,10 @@ var init_expo = __esm({
3556
3955
  }
3557
3956
  });
3558
3957
  function resolveLocal(root, fromFile, spec) {
3559
- const bases = spec.startsWith(".") ? [path28.resolve(path28.dirname(fromFile), spec)] : [path28.join(root, spec.slice(2)), path28.join(root, "src", spec.slice(2))];
3958
+ const bases = spec.startsWith(".") ? [path29.resolve(path29.dirname(fromFile), spec)] : [path29.join(root, spec.slice(2)), path29.join(root, "src", spec.slice(2))];
3560
3959
  for (const base of bases) {
3561
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path28.join(base, `index${e}`))].find(
3562
- (p) => SCRIPT_EXTS2.has(path28.extname(p)) && existsSync(p)
3960
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path29.join(base, `index${e}`))].find(
3961
+ (p) => SCRIPT_EXTS2.has(path29.extname(p)) && existsSync(p)
3563
3962
  );
3564
3963
  if (hit) return hit;
3565
3964
  }
@@ -3680,26 +4079,24 @@ function checkNativePack(ctx) {
3680
4079
  }
3681
4080
  function checkEasPlaceholders(ctx) {
3682
4081
  const files = [];
3683
- if (existsSync(path28.join(ctx.root, "eas.json"))) files.push("eas.json");
3684
- const workflows = path28.join(ctx.root, ".eas", "workflows");
4082
+ if (existsSync(path29.join(ctx.root, "eas.json"))) files.push("eas.json");
4083
+ const workflows = path29.join(ctx.root, ".eas", "workflows");
3685
4084
  if (existsSync(workflows)) {
3686
4085
  for (const name of readdirSync(workflows).sort()) if (/\.ya?ml$/.test(name)) files.push(`.eas/workflows/${name}`);
3687
4086
  }
3688
4087
  for (const file of files) {
3689
- const lines = readFileSync(path28.join(ctx.root, file), "utf8").split("\n");
3690
- lines.forEach((text, i) => {
3691
- if (!file.endsWith(".json") && /^\s*#/.test(text)) return;
3692
- for (const m of text.matchAll(EAS_PLACEHOLDER)) {
3693
- ctx.report({
3694
- rule: "eas-placeholder",
3695
- level: "warn",
3696
- file,
3697
- line: i + 1,
3698
- subject: m[0],
3699
- message: m[0] === "REPLACE_WITH_APP_FOLDER" ? "still names REPLACE_WITH_APP_FOLDER, so only config changes start a preview; replace it with the app's code folder (src, or apps/<name> in a monorepo)" : `still has the template placeholder ${m[0]}; replace it before the job that reads it runs (see docs/NATIVE-RELEASE.md in the Genesis repository)`
3700
- });
3701
- }
3702
- });
4088
+ for (const hit of findPlaceholders(file, readFileSync(path29.join(ctx.root, file), "utf8"))) {
4089
+ const key2 = placeholderKey(hit.text, hit.placeholder);
4090
+ const what = EAS_PLACEHOLDERS[hit.placeholder];
4091
+ ctx.report({
4092
+ rule: "eas-placeholder",
4093
+ level: "warn",
4094
+ file,
4095
+ line: hit.line,
4096
+ subject: hit.placeholder,
4097
+ message: hit.placeholder === "REPLACE_WITH_APP_FOLDER" ? `still names REPLACE_WITH_APP_FOLDER, so only config changes start a preview; replace it with ${what}` : `${key2 ? `${key2} is` : "still has"} the template placeholder ${hit.placeholder}; replace it with ${what ?? "its value (see docs/NATIVE-RELEASE.md in the Genesis repository)"} before the job that reads it runs`
4098
+ });
4099
+ }
3703
4100
  }
3704
4101
  }
3705
4102
  function checkRawPrimitives(ctx, pkg) {
@@ -3766,7 +4163,7 @@ function checkCustomHeaders(ctx, pkg) {
3766
4163
  if (!JSX_EXTS3.has(file.ext)) continue;
3767
4164
  const code = file.code;
3768
4165
  const hidden = HIDES_HEADER.exec(code);
3769
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path28.posix.dirname(file.path), file.path);
4166
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path29.posix.dirname(file.path), file.path);
3770
4167
  const own = hidden ? ownHeader(code, pkg) : null;
3771
4168
  if (hidden && own) {
3772
4169
  reported.add(file.path);
@@ -3794,7 +4191,7 @@ function checkCustomHeaders(ctx, pkg) {
3794
4191
  }
3795
4192
  for (const file of ctx.files) {
3796
4193
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
3797
- const layout = hidingLayouts.get(path28.posix.dirname(file.path));
4194
+ const layout = hidingLayouts.get(path29.posix.dirname(file.path));
3798
4195
  const own = layout ? ownHeader(file.code, pkg) : null;
3799
4196
  if (!layout || !own) continue;
3800
4197
  ctx.report({
@@ -3815,13 +4212,13 @@ function isLoadingOnlyRoute(code) {
3815
4212
  }
3816
4213
  function routerRoot(ctx) {
3817
4214
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
3818
- return existsSync(path28.join(ctx.root, "src", "app")) ? "src/app" : "app";
4215
+ return existsSync(path29.join(ctx.root, "src", "app")) ? "src/app" : "app";
3819
4216
  }
3820
4217
  function checkScreenLayouts(ctx, pkg) {
3821
4218
  const layouts = nativeLayouts(pkg);
3822
4219
  if (layouts.length === 0) return;
3823
4220
  const rootDir = routerRoot(ctx);
3824
- if (!existsSync(path28.join(ctx.root, rootDir))) {
4221
+ if (!existsSync(path29.join(ctx.root, rootDir))) {
3825
4222
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
3826
4223
  return;
3827
4224
  }
@@ -3858,7 +4255,7 @@ function checkScreenLayouts(ctx, pkg) {
3858
4255
  function readExpoConfigs(root) {
3859
4256
  const out = [];
3860
4257
  for (const name of EXPO_CONFIGS) {
3861
- const abs = path28.join(root, name);
4258
+ const abs = path29.join(root, name);
3862
4259
  if (!existsSync(abs)) continue;
3863
4260
  const text = readFileSync(abs, "utf8");
3864
4261
  let json = null;
@@ -3892,13 +4289,13 @@ function pluginOptions(json, module) {
3892
4289
  return null;
3893
4290
  }
3894
4291
  function dependencies(root) {
3895
- const file = path28.join(root, "package.json");
4292
+ const file = path29.join(root, "package.json");
3896
4293
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
3897
4294
  const pkg = JSON.parse(readFileSync(file, "utf8"));
3898
4295
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
3899
4296
  }
3900
4297
  function runtimeDependencies(root) {
3901
- const file = path28.join(root, "package.json");
4298
+ const file = path29.join(root, "package.json");
3902
4299
  if (!existsSync(file)) return {};
3903
4300
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
3904
4301
  }
@@ -3979,11 +4376,12 @@ function checkStoreReadiness(ctx) {
3979
4376
  });
3980
4377
  }
3981
4378
  }
3982
- var SCRIPT_EXTS3, JSX_EXTS3, LAYOUT_NAME, NON_SCREEN_ROUTE, PART_HEADER, HIDES_HEADER, EAS_PLACEHOLDER, RN, LOADING_ROUTE_COMPANIONS, PERMISSIONS, SOCIAL_SIGN_IN, WEAK_SOCIAL_SIGN_IN, APPLE_SIGN_IN, EXPO_CONFIGS, SUPABASE_SIGN_IN, GENESIS_PLUGIN, GENESIS_PLUGIN_TEXT, GENESIS_PLUGIN_IMPORT;
4379
+ var SCRIPT_EXTS3, JSX_EXTS3, LAYOUT_NAME, NON_SCREEN_ROUTE, PART_HEADER, HIDES_HEADER, RN, LOADING_ROUTE_COMPANIONS, PERMISSIONS, SOCIAL_SIGN_IN, WEAK_SOCIAL_SIGN_IN, APPLE_SIGN_IN, EXPO_CONFIGS, SUPABASE_SIGN_IN, GENESIS_PLUGIN, GENESIS_PLUGIN_TEXT, GENESIS_PLUGIN_IMPORT;
3983
4380
  var init_native = __esm({
3984
4381
  "src/doctor/native.ts"() {
3985
4382
  init_native_primitives();
3986
4383
  init_expo();
4384
+ init_eas_placeholders();
3987
4385
  init_config();
3988
4386
  init_genesis();
3989
4387
  init_scan();
@@ -3995,7 +4393,6 @@ var init_native = __esm({
3995
4393
  NON_SCREEN_ROUTE = /(?:^|\/)(?:_layout|\+html|\+native-intent|\+middleware)\.[jt]sx?$|\+api\.[jt]sx?$/;
3996
4394
  PART_HEADER = /(?:Section|List|Card|Dialog|Table|Group|Column|Row|Cell|Accordion|Sheet|Drawer|Modal|Popover|Menu|Panel|Form)Header$/;
3997
4395
  HIDES_HEADER = /\bheaderShown\s*(?::|=\s*\{)\s*false\b/;
3998
- EAS_PLACEHOLDER = /\bREPLACE_WITH_[A-Z0-9_]+/g;
3999
4396
  RN = String.raw`["']react-native["']`;
4000
4397
  LOADING_ROUTE_COMPANIONS = /* @__PURE__ */ new Set(["NativeLoadingState", "Stack.Screen", "Fragment", "React.Fragment"]);
4001
4398
  PERMISSIONS = [
@@ -4019,131 +4416,6 @@ var init_native = __esm({
4019
4416
  GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\b(?:require|import)\s*\(\s*["']@marktiderman\/genesis-cli[^"']*["']\s*\)/g;
4020
4417
  }
4021
4418
  });
4022
-
4023
- // src/doctor/semver.ts
4024
- function parseVersion(v) {
4025
- const m = VERSION.exec(v.trim());
4026
- return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
4027
- }
4028
- function compareVersions(a, b) {
4029
- for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
4030
- if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
4031
- for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
4032
- const x = a.pre[i];
4033
- const y = b.pre[i];
4034
- if (x === void 0) return -1;
4035
- if (y === void 0) return 1;
4036
- if (x === y) continue;
4037
- const nx = /^\d+$/.test(x);
4038
- const ny = /^\d+$/.test(y);
4039
- if (nx && ny) return +x < +y ? -1 : 1;
4040
- if (nx !== ny) return nx ? -1 : 1;
4041
- return x < y ? -1 : 1;
4042
- }
4043
- return 0;
4044
- }
4045
- function partial(s) {
4046
- const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
4047
- if (!m) return null;
4048
- const nums = [];
4049
- let wild = false;
4050
- for (const part of [m[1], m[2], m[3]]) {
4051
- if (wild || part === void 0 || /^[xX*]$/.test(part)) {
4052
- wild = true;
4053
- nums.push(null);
4054
- } else nums.push(+part);
4055
- }
4056
- return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
4057
- }
4058
- function comparators(token) {
4059
- const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
4060
- if (!m) return null;
4061
- const op = m[1] ?? "";
4062
- const p = partial(m[2]);
4063
- if (!p) return null;
4064
- const [major, mi, pa] = p.nums;
4065
- if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
4066
- const M = major;
4067
- const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
4068
- const next = (kind) => kind === "major" ? ver(M + 1, 0, 0, ["0"]) : kind === "minor" ? ver(M, (mi ?? 0) + 1, 0, ["0"]) : ver(M, mi ?? 0, (pa ?? 0) + 1, ["0"]);
4069
- const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
4070
- const out = switchOp();
4071
- if (p.pre.length) {
4072
- for (const c of out) if (c.v === lo) c.pre = true;
4073
- }
4074
- return out;
4075
- function switchOp() {
4076
- switch (op) {
4077
- case "^": {
4078
- const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
4079
- return [
4080
- { op: ">=", v: lo },
4081
- { op: "<", v: bound }
4082
- ];
4083
- }
4084
- case "~":
4085
- case "~>":
4086
- return [
4087
- { op: ">=", v: lo },
4088
- { op: "<", v: mi === null ? next("major") : next("minor") }
4089
- ];
4090
- case ">":
4091
- return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
4092
- case ">=":
4093
- return [{ op: ">=", v: lo }];
4094
- case "<":
4095
- return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
4096
- case "<=":
4097
- return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
4098
- default:
4099
- return upper ? [
4100
- { op: ">=", v: lo },
4101
- { op: "<", v: upper }
4102
- ] : [{ op: "=", v: lo }];
4103
- }
4104
- }
4105
- }
4106
- function test(c, v) {
4107
- const d = compareVersions(v, c.v);
4108
- return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
4109
- }
4110
- function parseRange(range) {
4111
- const alts = [];
4112
- for (const raw of range.trim().split("||")) {
4113
- const alt = raw.trim();
4114
- const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
4115
- if (hyphen) {
4116
- const from = comparators(`>=${hyphen[1]}`);
4117
- const to = comparators(`<=${hyphen[2]}`);
4118
- if (!from || !to) return null;
4119
- alts.push([...from, ...to]);
4120
- continue;
4121
- }
4122
- const set = [];
4123
- for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
4124
- const cs = comparators(token);
4125
- if (!cs) return null;
4126
- set.push(...cs);
4127
- }
4128
- alts.push(set);
4129
- }
4130
- return alts;
4131
- }
4132
- function satisfies(version, range) {
4133
- const v = parseVersion(version);
4134
- const alts = parseRange(range);
4135
- if (!v || !alts) return null;
4136
- return alts.some(
4137
- (set) => set.every((c) => test(c, v)) && (!v.pre.length || set.some((c) => c.pre && c.v.major === v.major && c.v.minor === v.minor && c.v.patch === v.patch))
4138
- );
4139
- }
4140
- var VERSION, ver;
4141
- var init_semver = __esm({
4142
- "src/doctor/semver.ts"() {
4143
- VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
4144
- ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
4145
- }
4146
- });
4147
4419
  function stripForImports(code) {
4148
4420
  const out = [];
4149
4421
  const blank = (ch) => ch === "\n" ? "\n" : " ";
@@ -4312,14 +4584,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
4312
4584
  seen.add(file);
4313
4585
  const json = readJsonc(file);
4314
4586
  if (!json) return {};
4315
- const dir = path28.dirname(file);
4587
+ const dir = path29.dirname(file);
4316
4588
  let merged = {};
4317
4589
  const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
4318
4590
  for (const ext of parents) {
4319
4591
  if (typeof ext !== "string") continue;
4320
4592
  let target = null;
4321
- if (ext.startsWith(".") || path28.isAbsolute(ext)) {
4322
- const abs = path28.resolve(dir, ext);
4593
+ if (ext.startsWith(".") || path29.isAbsolute(ext)) {
4594
+ const abs = path29.resolve(dir, ext);
4323
4595
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
4324
4596
  } else {
4325
4597
  const parts = ext.split("/");
@@ -4327,14 +4599,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
4327
4599
  const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
4328
4600
  if (pkgDir) {
4329
4601
  const sub = parts.slice(nameLength).join("/");
4330
- const abs = path28.join(pkgDir, sub || "tsconfig.json");
4602
+ const abs = path29.join(pkgDir, sub || "tsconfig.json");
4331
4603
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
4332
4604
  }
4333
4605
  }
4334
4606
  if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
4335
4607
  }
4336
4608
  const opts = json.compilerOptions ?? {};
4337
- if (typeof opts.baseUrl === "string") merged.baseUrl = path28.resolve(dir, opts.baseUrl);
4609
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path29.resolve(dir, opts.baseUrl);
4338
4610
  if (opts.paths && typeof opts.paths === "object") {
4339
4611
  merged.paths = opts.paths;
4340
4612
  merged.pathsDir = dir;
@@ -4345,7 +4617,7 @@ function aliases(root) {
4345
4617
  const table = [];
4346
4618
  let baseUrl = null;
4347
4619
  for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
4348
- const file = path28.join(root, name);
4620
+ const file = path29.join(root, name);
4349
4621
  if (!existsSync(file)) continue;
4350
4622
  const config = readTsconfig(root, file);
4351
4623
  baseUrl ??= config.baseUrl ?? null;
@@ -4353,22 +4625,22 @@ function aliases(root) {
4353
4625
  for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
4354
4626
  if (!Array.isArray(targets)) continue;
4355
4627
  const exact = !pattern.endsWith("*");
4356
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path28.join(base, String(t).replace(/\*$/, ""))) });
4628
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path29.join(base, String(t).replace(/\*$/, ""))) });
4357
4629
  }
4358
4630
  }
4359
- const pkg = readJsonc(path28.join(root, "package.json"));
4631
+ const pkg = readJsonc(path29.join(root, "package.json"));
4360
4632
  for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
4361
4633
  if (typeof target !== "string") continue;
4362
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path28.join(root, target.replace(/\*.*$/, ""))] });
4634
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path29.join(root, target.replace(/\*.*$/, ""))] });
4363
4635
  }
4364
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path28.join(root, "src") + path28.sep, root + path28.sep] });
4636
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path29.join(root, "src") + path29.sep, root + path29.sep] });
4365
4637
  return { table, baseUrl };
4366
4638
  }
4367
4639
  function resolveFile(base) {
4368
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path28.join(base, `index${e}`))];
4640
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path29.join(base, `index${e}`))];
4369
4641
  if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
4370
4642
  for (const p of tries) {
4371
- if (SCRIPT_EXTS2.has(path28.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
4643
+ if (SCRIPT_EXTS2.has(path29.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
4372
4644
  }
4373
4645
  return null;
4374
4646
  }
@@ -4381,7 +4653,7 @@ function createTrail(ctx) {
4381
4653
  const { table, baseUrl } = aliases(ctx.root);
4382
4654
  let declared = null;
4383
4655
  try {
4384
- const pkg = JSON.parse(readFileSync(path28.join(ctx.root, "package.json"), "utf8"));
4656
+ const pkg = JSON.parse(readFileSync(path29.join(ctx.root, "package.json"), "utf8"));
4385
4657
  declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
4386
4658
  } catch {
4387
4659
  declared = null;
@@ -4412,17 +4684,17 @@ function createTrail(ctx) {
4412
4684
  if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
4413
4685
  let resolved = null;
4414
4686
  if (spec.startsWith(".")) {
4415
- resolved = resolveFile(path28.resolve(path28.dirname(file.absolutePath), spec));
4687
+ resolved = resolveFile(path29.resolve(path29.dirname(file.absolutePath), spec));
4416
4688
  if (!resolved) lost = true;
4417
4689
  } else {
4418
4690
  const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
4419
4691
  if (alias) {
4420
4692
  for (const t of alias.targets) {
4421
- resolved = resolveFile(alias.exact ? t : path28.join(t, spec.slice(alias.prefix.length)));
4693
+ resolved = resolveFile(alias.exact ? t : path29.join(t, spec.slice(alias.prefix.length)));
4422
4694
  if (resolved) break;
4423
4695
  }
4424
4696
  }
4425
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path28.join(baseUrl, spec));
4697
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path29.join(baseUrl, spec));
4426
4698
  if (!resolved) {
4427
4699
  const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
4428
4700
  if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
@@ -4508,7 +4780,7 @@ var init_trail = __esm({
4508
4780
  });
4509
4781
  function routesDir(ctx) {
4510
4782
  if (ctx.config.routesDir) return ctx.config.routesDir;
4511
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path28.join(ctx.root, d))) ?? null;
4783
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path29.join(ctx.root, d))) ?? null;
4512
4784
  }
4513
4785
  function flavorOf(dir, rels) {
4514
4786
  const stems = rels.map((r) => r.split("/").pop());
@@ -4649,7 +4921,7 @@ function validateDeclaration(raw, packageName3, packageDir2, ignored) {
4649
4921
  });
4650
4922
  if (typeof raw === "string") {
4651
4923
  if (!packageDir2) fail(`points at ${raw}, but the package folder is unknown`);
4652
- const file = path28.resolve(packageDir2, raw);
4924
+ const file = path29.resolve(packageDir2, raw);
4653
4925
  if (!inside(packageDir2, file)) fail(`points outside the package (${raw})`);
4654
4926
  if (!existsSync(file)) fail(`points at ${raw}, which doesn't exist (is it in package.json "files"?)`);
4655
4927
  let parsed;
@@ -4698,7 +4970,7 @@ function validateDeclaration(raw, packageName3, packageDir2, ignored) {
4698
4970
  if (typeof c.plugin === "string") {
4699
4971
  if (!packageDir2) plugin = c.plugin;
4700
4972
  else {
4701
- plugin = path28.resolve(packageDir2, c.plugin);
4973
+ plugin = path29.resolve(packageDir2, c.plugin);
4702
4974
  if (!inside(packageDir2, plugin)) fail(`plugin points outside the package (${c.plugin})`);
4703
4975
  }
4704
4976
  }
@@ -4747,7 +5019,7 @@ function checkPattern(v, where2, fail) {
4747
5019
  }
4748
5020
  }
4749
5021
  function readDeclaringPackage(dir, local) {
4750
- const file = path28.join(dir, "package.json");
5022
+ const file = path29.join(dir, "package.json");
4751
5023
  let stamp;
4752
5024
  let real2;
4753
5025
  try {
@@ -4770,7 +5042,7 @@ ${local}`;
4770
5042
  const pkg = {
4771
5043
  name: json.name,
4772
5044
  version: typeof json.version === "string" ? json.version : "0.0.0",
4773
- dir: path28.resolve(dir),
5045
+ dir: path29.resolve(dir),
4774
5046
  namespace: ruleNamespace(json.name),
4775
5047
  local,
4776
5048
  private: json.private === true,
@@ -4784,7 +5056,7 @@ ${local}`;
4784
5056
  if (raw !== void 0) {
4785
5057
  const ignored = [];
4786
5058
  try {
4787
- pkg.declaration = validateDeclaration(raw, json.name, path28.resolve(dir), ignored);
5059
+ pkg.declaration = validateDeclaration(raw, json.name, path29.resolve(dir), ignored);
4788
5060
  if (ignored.length) pkg.ignored = ignored;
4789
5061
  } catch (err) {
4790
5062
  pkg.error = err.message;
@@ -4803,14 +5075,14 @@ function discoverPackages(root) {
4803
5075
  for (const dir of installed) {
4804
5076
  let scope;
4805
5077
  try {
4806
- scope = path28.dirname(realpathSync(dir));
5078
+ scope = path29.dirname(realpathSync(dir));
4807
5079
  } catch {
4808
5080
  continue;
4809
5081
  }
4810
- if (path28.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
5082
+ if (path29.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
4811
5083
  for (const entry of readdirSync(scope)) {
4812
5084
  if (byName.has(`@marktiderman/${entry}`) || !GENESIS.test(`@marktiderman/${entry}`)) continue;
4813
- const pkg = readDeclaringPackage(path28.join(scope, entry), false);
5085
+ const pkg = readDeclaringPackage(path29.join(scope, entry), false);
4814
5086
  if (pkg) byName.set(pkg.name, pkg);
4815
5087
  }
4816
5088
  }
@@ -5020,10 +5292,10 @@ var init_package_rules = __esm({
5020
5292
  });
5021
5293
  function sourceFiles(dir, rel = "") {
5022
5294
  const out = [];
5023
- for (const entry of readdirSync(path28.join(dir, rel)).sort()) {
5295
+ for (const entry of readdirSync(path29.join(dir, rel)).sort()) {
5024
5296
  if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
5025
5297
  const child = rel ? `${rel}/${entry}` : entry;
5026
- const stat = lstatSync(path28.join(dir, child));
5298
+ const stat = lstatSync(path29.join(dir, child));
5027
5299
  if (stat.isSymbolicLink()) continue;
5028
5300
  if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
5029
5301
  else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
@@ -5046,13 +5318,13 @@ function matchPattern(pattern, spec) {
5046
5318
  return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
5047
5319
  }
5048
5320
  function tsconfigPaths(dir) {
5049
- const file = path28.join(dir, "tsconfig.json");
5321
+ const file = path29.join(dir, "tsconfig.json");
5050
5322
  if (!existsSync(file)) return [];
5051
5323
  try {
5052
5324
  const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
5053
5325
  const options = JSON.parse(text).compilerOptions ?? {};
5054
- const base = path28.resolve(dir, options.baseUrl ?? ".");
5055
- return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path28.resolve(base, t)) }));
5326
+ const base = path29.resolve(dir, options.baseUrl ?? ".");
5327
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path29.resolve(base, t)) }));
5056
5328
  } catch {
5057
5329
  return [];
5058
5330
  }
@@ -5066,8 +5338,8 @@ function checkImports2(ctx, pkg, json) {
5066
5338
  const hit = matchPattern(pattern, spec);
5067
5339
  if (hit === null) continue;
5068
5340
  return targets.some((t) => {
5069
- const rel = path28.relative(pkg.dir, t.replace("*", hit));
5070
- return !rel.startsWith("..") && !path28.isAbsolute(rel);
5341
+ const rel = path29.relative(pkg.dir, t.replace("*", hit));
5342
+ return !rel.startsWith("..") && !path29.isAbsolute(rel);
5071
5343
  });
5072
5344
  }
5073
5345
  return null;
@@ -5080,7 +5352,7 @@ function checkImports2(ctx, pkg, json) {
5080
5352
  ...Object.keys(json.optionalDependencies ?? {})
5081
5353
  ]);
5082
5354
  for (const file of sourceFiles(pkg.dir)) {
5083
- const code = stripForImports(readFileSync(path28.join(pkg.dir, file), "utf8"));
5355
+ const code = stripForImports(readFileSync(path29.join(pkg.dir, file), "utf8"));
5084
5356
  if (code === null) continue;
5085
5357
  const at = `${pkg.rel}/${file}`;
5086
5358
  const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
@@ -5105,9 +5377,9 @@ function checkImports2(ctx, pkg, json) {
5105
5377
  continue;
5106
5378
  }
5107
5379
  if (spec.startsWith(".")) {
5108
- const target = path28.resolve(pkg.dir, path28.dirname(file), spec);
5109
- const rel = path28.relative(pkg.dir, target);
5110
- if (rel.startsWith("..") || path28.isAbsolute(rel)) {
5380
+ const target = path29.resolve(pkg.dir, path29.dirname(file), spec);
5381
+ const rel = path29.relative(pkg.dir, target);
5382
+ if (rel.startsWith("..") || path29.isAbsolute(rel)) {
5111
5383
  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` });
5112
5384
  }
5113
5385
  continue;
@@ -5143,12 +5415,12 @@ function checkMigrations(ctx, pkg, json, locals) {
5143
5415
  const from = own ? "" : ` (in ${m.package})`;
5144
5416
  if (typeof m.file === "string" && typeof m.test !== "string") {
5145
5417
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.file, message: `${pkg.name} block ${id}: ${m.file}${from} has no pgTAP test; declare one as "test" beside it` });
5146
- } else if (typeof m.test === "string" && !existsSync(path28.join(home, m.test))) {
5418
+ } else if (typeof m.test === "string" && !existsSync(path29.join(home, m.test))) {
5147
5419
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.test, message: `${pkg.name} block ${id}: its test ${m.test}${from} doesn't exist` });
5148
5420
  }
5149
5421
  }
5150
5422
  }
5151
- const dir = path28.join(pkg.dir, "migrations");
5423
+ const dir = path29.join(pkg.dir, "migrations");
5152
5424
  if (!existsSync(dir)) return;
5153
5425
  const seen = /* @__PURE__ */ new Map();
5154
5426
  for (const name of readdirSync(dir).sort()) {
@@ -5157,21 +5429,21 @@ function checkMigrations(ctx, pkg, json, locals) {
5157
5429
  const other = seen.get(m[1]);
5158
5430
  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` });
5159
5431
  else seen.set(m[1], name);
5160
- if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path28.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
5432
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path29.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
5161
5433
  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")})` });
5162
5434
  }
5163
5435
  }
5164
5436
  }
5165
5437
  function checkExports(ctx, pkg, json) {
5166
5438
  const targets = [];
5167
- const walk2 = (v) => {
5439
+ const walk3 = (v) => {
5168
5440
  if (typeof v === "string") targets.push(v);
5169
- else if (v && typeof v === "object") for (const x of Object.values(v)) walk2(x);
5441
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk3(x);
5170
5442
  };
5171
- walk2(json.exports);
5443
+ walk3(json.exports);
5172
5444
  for (const t of targets) {
5173
5445
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
5174
- if (!existsSync(path28.join(pkg.dir, t))) {
5446
+ if (!existsSync(path29.join(pkg.dir, t))) {
5175
5447
  ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
5176
5448
  }
5177
5449
  }
@@ -5189,11 +5461,11 @@ function checkBlocks(ctx, pkg, json) {
5189
5461
  function checkTaggedTests(ctx, pkg) {
5190
5462
  const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
5191
5463
  if (!tests.length) return;
5192
- const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path28.join(pkg.dir, f), "utf8")));
5464
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path29.join(pkg.dir, f), "utf8")));
5193
5465
  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>` });
5194
5466
  }
5195
5467
  function checkRegistered(ctx, pkg) {
5196
- const file = path28.join(ctx.root, "features.json");
5468
+ const file = path29.join(ctx.root, "features.json");
5197
5469
  if (!existsSync(file)) return;
5198
5470
  let doc;
5199
5471
  try {
@@ -5203,7 +5475,7 @@ function checkRegistered(ctx, pkg) {
5203
5475
  }
5204
5476
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
5205
5477
  const forms = /* @__PURE__ */ new Set([pkg.rel]);
5206
- if (top) forms.add(path28.relative(top, realpathSync(pkg.dir)).split(path28.sep).join("/"));
5478
+ if (top) forms.add(path29.relative(top, realpathSync(pkg.dir)).split(path29.sep).join("/"));
5207
5479
  const covered = (doc.features ?? []).some(
5208
5480
  (f) => (f.links?.code ?? []).some((c) => {
5209
5481
  const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -5233,8 +5505,8 @@ function mergeBaseOf(root, base) {
5233
5505
  function checkChanges(ctx, pkg, json, base, mergeBase) {
5234
5506
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
5235
5507
  if (!top) return;
5236
- const appRelative = (fromTop) => path28.relative(realpathSync(ctx.root), path28.join(top, fromTop)).split(path28.sep).join("/");
5237
- const inRepo = path28.relative(top, realpathSync(pkg.dir)).split(path28.sep).join("/");
5508
+ const appRelative = (fromTop) => path29.relative(realpathSync(ctx.root), path29.join(top, fromTop)).split(path29.sep).join("/");
5509
+ const inRepo = path29.relative(top, realpathSync(pkg.dir)).split(path29.sep).join("/");
5238
5510
  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");
5239
5511
  const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
5240
5512
  const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
@@ -5257,11 +5529,11 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
5257
5529
  const now = typeof json.version === "string" ? parseVersion(json.version) : null;
5258
5530
  const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
5259
5531
  const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
5260
- 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) => path28.join(top, f)) : [];
5532
+ 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) => path29.join(top, f)) : [];
5261
5533
  const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
5262
5534
  const named = naming.length > 0;
5263
5535
  if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
5264
- ctx.report({ rule: "package-unversioned-change", level: "warn", file: path28.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
5536
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path29.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
5265
5537
  }
5266
5538
  let jsonBefore = null;
5267
5539
  try {
@@ -5271,7 +5543,7 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
5271
5543
  }
5272
5544
  const raw = json;
5273
5545
  if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
5274
- const appInRepo = path28.relative(top, realpathSync(ctx.root)).split(path28.sep).join("/");
5546
+ const appInRepo = path29.relative(top, realpathSync(ctx.root)).split(path29.sep).join("/");
5275
5547
  const candidates = [.../* @__PURE__ */ new Set(["features.ts", "src/features.ts", ...appInRepo ? [`${appInRepo}/features.ts`, `${appInRepo}/src/features.ts`] : []])];
5276
5548
  const registry = (git(top, ["diff", "--name-only", mergeBase, "--", ...candidates]) ?? "").trim();
5277
5549
  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` });
@@ -5322,7 +5594,7 @@ function checkPackagesPack(ctx) {
5322
5594
  ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
5323
5595
  }
5324
5596
  for (const pkg of packages) {
5325
- const json = JSON.parse(readFileSync(path28.join(pkg.dir, "package.json"), "utf8"));
5597
+ const json = JSON.parse(readFileSync(path29.join(pkg.dir, "package.json"), "utf8"));
5326
5598
  checkImports2(ctx, pkg, json);
5327
5599
  checkExports(ctx, pkg, json);
5328
5600
  checkBlocks(ctx, pkg, json);
@@ -5520,9 +5792,9 @@ function gitView(root, dir, base) {
5520
5792
  function checkSupabasePack(ctx) {
5521
5793
  const settings2 = ctx.config.supabase ?? {};
5522
5794
  const dir = settings2.migrations ?? DEFAULT_MIGRATIONS;
5523
- const abs = path28.join(ctx.root, dir);
5795
+ const abs = path29.join(ctx.root, dir);
5524
5796
  if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
5525
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path28.join(abs, n), "utf8")) }));
5797
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path29.join(abs, n), "utf8")) }));
5526
5798
  const exposed = new Set((settings2.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
5527
5799
  const base = settings2.base ?? DEFAULT_BASE;
5528
5800
  const view = gitView(ctx.root, dir, base);
@@ -5539,7 +5811,7 @@ function checkSupabasePack(ctx) {
5539
5811
  }
5540
5812
  }
5541
5813
  const since = settings2.since;
5542
- const afterSince = (file) => since === void 0 || path28.posix.basename(file) >= since;
5814
+ const afterSince = (file) => since === void 0 || path29.posix.basename(file) >= since;
5543
5815
  if ("reason" in view && since === void 0) {
5544
5816
  ctx.report({
5545
5817
  rule: "migration-grants",
@@ -5839,18 +6111,18 @@ var init_supabase = __esm({
5839
6111
  }
5840
6112
  });
5841
6113
  function nodeModulesOf(dir) {
5842
- const parent = path28.dirname(dir);
5843
- return path28.basename(parent).startsWith("@") ? path28.dirname(parent) : parent;
6114
+ const parent = path29.dirname(dir);
6115
+ return path29.basename(parent).startsWith("@") ? path29.dirname(parent) : parent;
5844
6116
  }
5845
6117
  function packagesIn(nodeModules) {
5846
6118
  if (!existsSync(nodeModules)) return [];
5847
6119
  const out = [];
5848
6120
  for (const entry of readdirSync(nodeModules)) {
5849
6121
  if (entry.startsWith(".")) continue;
5850
- const p = path28.join(nodeModules, entry);
6122
+ const p = path29.join(nodeModules, entry);
5851
6123
  if (entry.startsWith("@")) {
5852
6124
  try {
5853
- for (const sub of readdirSync(p)) out.push(path28.join(p, sub));
6125
+ for (const sub of readdirSync(p)) out.push(path29.join(p, sub));
5854
6126
  } catch {
5855
6127
  }
5856
6128
  } else {
@@ -5862,7 +6134,7 @@ function packagesIn(nodeModules) {
5862
6134
  function genesisInstalls(root) {
5863
6135
  const copies = /* @__PURE__ */ new Map();
5864
6136
  const realRoot = real(root);
5865
- const rel = (abs) => path28.relative(realRoot, abs).split(path28.sep).join("/") || ".";
6137
+ const rel = (abs) => path29.relative(realRoot, abs).split(path29.sep).join("/") || ".";
5866
6138
  const via = /* @__PURE__ */ new Map();
5867
6139
  const record = (real2, manifest, by, range, root2) => {
5868
6140
  let copy = copies.get(real2);
@@ -5874,7 +6146,7 @@ function genesisInstalls(root) {
5874
6146
  via.get(real2).add(root2);
5875
6147
  if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
5876
6148
  };
5877
- const walk2 = (kind, roots) => {
6149
+ const walk3 = (kind, roots) => {
5878
6150
  const expanded = /* @__PURE__ */ new Set();
5879
6151
  const queue = [];
5880
6152
  const visit = (dir, by, range) => {
@@ -5907,7 +6179,7 @@ function genesisInstalls(root) {
5907
6179
  if (!dir) return null;
5908
6180
  if (!ownInstall || name in declared) return dir;
5909
6181
  const realDir = real(dir);
5910
- if (realDir.startsWith(realRoot + path28.sep)) return dir;
6182
+ if (realDir.startsWith(realRoot + path29.sep)) return dir;
5911
6183
  return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
5912
6184
  };
5913
6185
  const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
@@ -5915,7 +6187,7 @@ function genesisInstalls(root) {
5915
6187
  return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
5916
6188
  });
5917
6189
  const app = readManifest(root);
5918
- const ownInstall = LOCKFILES.some((f) => existsSync(path28.join(root, f)));
6190
+ const ownInstall = LOCKFILES.some((f) => existsSync(path29.join(root, f)));
5919
6191
  const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
5920
6192
  const declaredDev = Object.entries(app?.devDependencies ?? {});
5921
6193
  const runtimeDeps = {
@@ -5925,18 +6197,18 @@ function genesisInstalls(root) {
5925
6197
  ...app?.dependencies
5926
6198
  };
5927
6199
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
5928
- walk2("runtime", rootsOf(runtimeDeps, "the app"));
5929
- const top = path28.join(root, "node_modules");
5930
- walk2(
6200
+ walk3("runtime", rootsOf(runtimeDeps, "the app"));
6201
+ const top = path29.join(root, "node_modules");
6202
+ walk3(
5931
6203
  "hoisted",
5932
6204
  packagesIn(top).filter((dir) => {
5933
- const name = path28.relative(top, dir).split(path28.sep).join("/");
6205
+ const name = path29.relative(top, dir).split(path29.sep).join("/");
5934
6206
  return !(name in runtimeDeps) && !(name in devDeps);
5935
6207
  }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
5936
6208
  );
5937
6209
  const devRoots = { ...devDeps };
5938
6210
  for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
5939
- walk2("dev", rootsOf(devRoots, "the app (dev)"));
6211
+ walk3("dev", rootsOf(devRoots, "the app (dev)"));
5940
6212
  for (const [key2, copy] of copies) {
5941
6213
  const kinds = via.get(key2);
5942
6214
  copy.runtime = kinds.has("runtime");
@@ -5972,7 +6244,7 @@ function checkDuplicatePackages(ctx) {
5972
6244
  }
5973
6245
  }
5974
6246
  function checkPeerRanges(ctx) {
5975
- const rel = (abs) => path28.relative(ctx.root, abs).split(path28.sep).join("/");
6247
+ const rel = (abs) => path29.relative(ctx.root, abs).split(path29.sep).join("/");
5976
6248
  for (const copies of genesisInstalls(ctx.root).values()) {
5977
6249
  for (const copy of copies) {
5978
6250
  const dir = copy.absolutePath;
@@ -6005,7 +6277,7 @@ var init_installs = __esm({
6005
6277
  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)$/;
6006
6278
  readManifest = (dir) => {
6007
6279
  try {
6008
- return JSON.parse(readFileSync(path28.join(dir, "package.json"), "utf8"));
6280
+ return JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
6009
6281
  } catch {
6010
6282
  return null;
6011
6283
  }
@@ -6262,12 +6534,23 @@ function bumpSummary(version, changes, skipped) {
6262
6534
  ...skipped.length ? ["", "Left alone:", "", ...skipped.map((s) => `- \`${s.name}\` ${s.spec} in ${s.file}: ${s.why}`)] : []
6263
6535
  ].join("\n");
6264
6536
  }
6265
- function excludeReplacement(entry) {
6266
- if (entry === GENESIS_PATTERN) return GENESIS_PATTERN;
6537
+ function lockedGenesisVersions(lockText) {
6538
+ const locked = /* @__PURE__ */ new Map();
6539
+ const re = /(?<![\w/-])(@marktiderman\/genesis(?:-[a-z0-9-]+)?)@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?![0-9A-Za-z.+-])/g;
6540
+ for (const m of lockText.matchAll(re)) {
6541
+ if (!locked.has(m[1])) locked.set(m[1], /* @__PURE__ */ new Set());
6542
+ locked.get(m[1]).add(m[2]);
6543
+ }
6544
+ return locked;
6545
+ }
6546
+ function genesisEntry(entry) {
6267
6547
  const at = entry.startsWith("@") ? entry.indexOf("@", 1) : entry.indexOf("@");
6268
- const name = at === -1 ? entry : entry.slice(0, at);
6548
+ if (at === -1) return null;
6549
+ const name = entry.slice(0, at);
6269
6550
  if (!GENESIS3.test(name)) return null;
6270
- return name === UMBRELLA ? UMBRELLA : GENESIS_PATTERN;
6551
+ const parts = entry.slice(at + 1).split("||").map((v) => v.trim());
6552
+ if (parts.some((v) => !v)) return null;
6553
+ return { name, pins: parts.filter((v) => PLAIN.test(v)), ranges: parts.filter((v) => !PLAIN.test(v)) };
6271
6554
  }
6272
6555
  function unquoteScalar(raw) {
6273
6556
  const s = raw.trim();
@@ -6275,58 +6558,143 @@ function unquoteScalar(raw) {
6275
6558
  if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) return s.slice(1, -1);
6276
6559
  return s;
6277
6560
  }
6278
- function normaliseReleaseAgeExcludes(text) {
6561
+ function mergePins(items, locked) {
6562
+ const slots = /* @__PURE__ */ new Map();
6563
+ const out = /* @__PURE__ */ new Map();
6564
+ const slot = (name, index) => {
6565
+ let s = slots.get(name);
6566
+ if (!s) {
6567
+ s = { name, pins: /* @__PURE__ */ new Set(), ranges: [], sources: [], count: 0, first: null };
6568
+ slots.set(name, s);
6569
+ if (!out.has(index)) out.set(index, []);
6570
+ out.get(index).push(s);
6571
+ }
6572
+ return s;
6573
+ };
6574
+ items.forEach((item, index) => {
6575
+ const entry = unquoteScalar(item.entry);
6576
+ if (LEGACY_EXCLUDES.includes(entry) && locked) {
6577
+ const names = entry === UMBRELLA ? [UMBRELLA].filter((n) => locked.has(n)) : [...locked.keys()].filter((n) => n !== UMBRELLA).sort();
6578
+ for (const name of names) {
6579
+ const s2 = slot(name, index);
6580
+ s2.count += 2;
6581
+ for (const v of locked.get(name)) s2.pins.add(v);
6582
+ s2.sources.push({ pins: [...locked.get(name)], ranges: [], comment: item.comment });
6583
+ }
6584
+ if (!names.length && !out.has(index)) out.set(index, []);
6585
+ return;
6586
+ }
6587
+ const parsed = genesisEntry(entry);
6588
+ if (!parsed) {
6589
+ out.set(index, [{ raw: true }]);
6590
+ return;
6591
+ }
6592
+ const s = slot(parsed.name, index);
6593
+ s.count++;
6594
+ if (s.first === null) s.first = entry;
6595
+ for (const v of parsed.pins) s.pins.add(v);
6596
+ for (const r of parsed.ranges) if (!s.ranges.includes(r)) s.ranges.push(r);
6597
+ s.sources.push({ pins: parsed.pins, ranges: parsed.ranges, comment: item.comment });
6598
+ });
6599
+ const result = /* @__PURE__ */ new Map();
6600
+ for (const [index, list] of out) {
6601
+ const texts = [];
6602
+ for (const s of list) {
6603
+ if (s.raw) {
6604
+ texts.push({ text: null });
6605
+ continue;
6606
+ }
6607
+ const keep = [...s.pins].filter((v) => !locked || locked.get(s.name)?.has(v)).sort(compareVersions2);
6608
+ const parts = [...s.ranges, ...keep];
6609
+ if (!parts.length) continue;
6610
+ const entry = `${s.name}@${parts.join(" || ")}`;
6611
+ if (s.count === 1 && entry === s.first) {
6612
+ texts.push({ text: null });
6613
+ continue;
6614
+ }
6615
+ const source = s.sources.find((src) => src.ranges.length || src.pins.some((v) => keep.includes(v)));
6616
+ texts.push({ text: `'${entry}'`, comment: source?.comment ?? "" });
6617
+ }
6618
+ if (texts.length) result.set(index, texts);
6619
+ }
6620
+ return result;
6621
+ }
6622
+ function normaliseReleaseAgeExcludes(text, locked) {
6279
6623
  const eol = text.includes("\r\n") ? "\r\n" : "\n";
6280
6624
  const lines = text.split(/\r?\n/);
6281
6625
  const key2 = /^minimumReleaseAgeExclude:(.*)$/;
6282
6626
  const start = lines.findIndex((l) => key2.test(l));
6283
6627
  if (start === -1) return text;
6284
- const seen = /* @__PURE__ */ new Set();
6285
6628
  const out = lines.slice(0, start);
6286
6629
  const flow = /^(\s*)\[(.*)\](\s*(?:#.*)?)$/.exec(key2.exec(lines[start])[1]);
6287
6630
  if (flow) {
6288
- const kept = [];
6289
- for (const raw of flow[2].split(",").map((s) => s.trim()).filter(Boolean)) {
6290
- const replacement = excludeReplacement(unquoteScalar(raw));
6291
- if (replacement === null) kept.push(raw);
6292
- else if (!seen.has(replacement)) {
6293
- seen.add(replacement);
6294
- kept.push(`'${replacement}'`);
6295
- }
6296
- }
6297
- return [...out, `minimumReleaseAgeExclude:${flow[1]}[${kept.join(", ")}]${flow[3]}`, ...lines.slice(start + 1)].join(eol);
6631
+ const raws = flow[2].split(",").map((s) => s.trim()).filter(Boolean);
6632
+ const merged2 = mergePins(raws.map((raw) => ({ raw, entry: raw, comment: "" })), locked);
6633
+ const kept2 = raws.flatMap((raw, i2) => (merged2.get(i2) ?? []).map((m) => m.text ?? raw));
6634
+ const line = `minimumReleaseAgeExclude:${flow[1]}[${kept2.join(", ")}]${flow[3]}`;
6635
+ return line === lines[start] ? text : [...out, line, ...lines.slice(start + 1)].join(eol);
6298
6636
  }
6299
6637
  const item = /^(\s*-\s+)('(?:[^']|'')*'|"[^"]*"|[^#\s][^#]*?)(\s+#.*)?\s*$/;
6300
- out.push(lines[start]);
6301
6638
  let i = start + 1;
6639
+ const body = [];
6640
+ const items = [];
6302
6641
  for (; i < lines.length; i++) {
6303
6642
  const m = item.exec(lines[i]);
6304
6643
  if (!m) {
6305
6644
  if (/^\s*(#.*)?$/.test(lines[i])) {
6306
- out.push(lines[i]);
6645
+ body.push({ line: lines[i] });
6307
6646
  continue;
6308
6647
  }
6309
6648
  break;
6310
6649
  }
6311
- const replacement = excludeReplacement(unquoteScalar(m[2]));
6312
- if (replacement === null) out.push(lines[i]);
6313
- else if (!seen.has(replacement)) {
6314
- seen.add(replacement);
6315
- out.push(`${m[1]}'${replacement}'${m[3] ?? ""}`);
6316
- }
6650
+ body.push({ item: items.length, prefix: m[1] });
6651
+ items.push({ raw: lines[i], entry: m[2], comment: m[3] ?? "" });
6652
+ }
6653
+ const merged = mergePins(items, locked);
6654
+ const kept = body.flatMap((b) => {
6655
+ if (!("item" in b)) return [b.line];
6656
+ return (merged.get(b.item) ?? []).map((m) => m.text === null ? items[b.item].raw : `${b.prefix}${m.text}${m.comment}`);
6657
+ });
6658
+ const keyLine = items.length && merged.size === 0 ? "minimumReleaseAgeExclude: []" : lines[start];
6659
+ const next = [...out, keyLine, ...kept, ...lines.slice(i)].join(eol);
6660
+ return next === lines.join(eol) ? text : next;
6661
+ }
6662
+ function releaseAgeExcludeProblems(text) {
6663
+ const problems = [];
6664
+ const lines = text.split(/\r?\n/);
6665
+ const start = lines.findIndex((l) => /^minimumReleaseAgeExclude:/.test(l));
6666
+ if (start === -1) return problems;
6667
+ const flow = /^minimumReleaseAgeExclude:\s*\[(.*)\]/.exec(lines[start]);
6668
+ const entries = flow ? flow[1].split(",").map((s) => unquoteScalar(s)).filter(Boolean) : lines.slice(start + 1).map((l) => /^\s*-\s+('(?:[^']|'')*'|"[^"]*"|[^#\s][^#]*?)(\s+#.*)?\s*$/.exec(l)).filter(Boolean).map((m) => unquoteScalar(m[1]));
6669
+ for (const entry of entries) {
6670
+ if (LEGACY_EXCLUDES.includes(entry)) problems.push(`'${entry}' exempts every Genesis release from minimumReleaseAge (genesis-cli 1.17.3 wrote it); with no lockfile beside pnpm-workspace.yaml to read versions from, replace it by hand with exact versions ('@marktiderman/genesis-ui@2.26.0 || 2.27.0')`);
6671
+ const parsed = genesisEntry(entry);
6672
+ if (parsed?.ranges.length) problems.push(`'${entry}' has a range (${parsed.ranges.join(", ")}); pnpm 11 accepts only exact versions in minimumReleaseAgeExclude (ERR_PNPM_INVALID_MINIMUM_RELEASE_AGE_EXCLUDE): list the versions the app installs`);
6317
6673
  }
6318
- return [...out, ...lines.slice(i)].join(eol);
6674
+ return problems;
6319
6675
  }
6320
- function pnpmWorkspaceFile(start, fallback, fs2) {
6676
+ function pnpmReadsExactExcludes(version) {
6677
+ const m = /^(\d+)\.(\d+)\./.exec(String(version ?? "").trim());
6678
+ if (!m) return true;
6679
+ const [major, minor] = [Number(m[1]), Number(m[2])];
6680
+ return major > 10 || major === 10 && minor >= 19;
6681
+ }
6682
+ function pnpmWorkspaceFile(start, fallback, fs2, stop) {
6321
6683
  for (let dir = start; ; ) {
6322
6684
  const file = fs2.join(dir, "pnpm-workspace.yaml");
6323
6685
  if (fs2.exists(file)) return file;
6324
6686
  const parent = fs2.dirname(dir);
6325
- if (parent === dir) return fs2.join(fallback, "pnpm-workspace.yaml");
6687
+ if (parent === dir || dir === stop) return fs2.join(fallback, "pnpm-workspace.yaml");
6326
6688
  dir = parent;
6327
6689
  }
6328
6690
  }
6329
- var UMBRELLA, GENESIS3, EXACT, PLAIN, SECTIONS, GENESIS_PATTERN;
6691
+ function tidyLocked(workspaceText, lockText, npmrcText) {
6692
+ if (lockText === null || lockText === void 0) return null;
6693
+ if (/^sharedWorkspaceLockfile:\s*(['"]?)false\1\s*(#.*)?$/m.test(workspaceText)) return null;
6694
+ if (/^\s*shared-workspace-lockfile\s*=\s*(['"]?)false\1\s*([#;].*)?$/m.test(npmrcText ?? "")) return null;
6695
+ return lockedGenesisVersions(lockText);
6696
+ }
6697
+ var UMBRELLA, GENESIS3, EXACT, PLAIN, SECTIONS, LEGACY_EXCLUDES;
6330
6698
  var init_bump_core = __esm({
6331
6699
  "src/upgrade/bump-core.mjs"() {
6332
6700
  UMBRELLA = "@marktiderman/genesis";
@@ -6334,7 +6702,7 @@ var init_bump_core = __esm({
6334
6702
  EXACT = /^(\^|~|=)?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/;
6335
6703
  PLAIN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
6336
6704
  SECTIONS = ["dependencies", "devDependencies", "optionalDependencies"];
6337
- GENESIS_PATTERN = "@marktiderman/genesis-*";
6705
+ LEGACY_EXCLUDES = ["@marktiderman/genesis-*", UMBRELLA];
6338
6706
  }
6339
6707
  });
6340
6708
 
@@ -6550,17 +6918,17 @@ __export(codemods_exports, {
6550
6918
  });
6551
6919
  function appScripts(root) {
6552
6920
  const out = [];
6553
- const walk2 = (dir) => {
6921
+ const walk3 = (dir) => {
6554
6922
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
6555
- const abs = path28.join(dir, entry.name);
6923
+ const abs = path29.join(dir, entry.name);
6556
6924
  if (entry.isDirectory()) {
6557
- if (!SKIP_DIRS3.has(entry.name)) walk2(abs);
6925
+ if (!SKIP_DIRS3.has(entry.name)) walk3(abs);
6558
6926
  } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
6559
- out.push(path28.relative(root, abs).split(path28.sep).join("/"));
6927
+ out.push(path29.relative(root, abs).split(path29.sep).join("/"));
6560
6928
  }
6561
6929
  }
6562
6930
  };
6563
- walk2(root);
6931
+ walk3(root);
6564
6932
  return out;
6565
6933
  }
6566
6934
  function codemodById(id, registry = CODEMODS) {
@@ -6596,7 +6964,7 @@ var init_codemods = __esm({
6596
6964
  let readsId = false;
6597
6965
  let augmented = false;
6598
6966
  for (const rel of appScripts(root)) {
6599
- const abs = path28.join(root, rel);
6967
+ const abs = path29.join(root, rel);
6600
6968
  const text = readFileSync(abs, "utf8");
6601
6969
  if (augmentsResourceScope(text)) augmented = true;
6602
6970
  if (!IMPORTS_GENESIS.test(text)) continue;
@@ -6692,7 +7060,7 @@ function checkTreeViews(ctx) {
6692
7060
  function moduleFiles(ctx) {
6693
7061
  const scanned = new Set(ctx.files.map((f) => f.path));
6694
7062
  const ignored = globMatcher([...DEFAULT_IGNORE, ...ctx.config.ignore ?? []]);
6695
- const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path28.join(ctx.root, rel), "utf8"), true) }));
7063
+ const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path29.join(ctx.root, rel), "utf8"), true) }));
6696
7064
  return [...ctx.files.filter((f) => SCRIPT_EXTS5.has(f.ext)), ...extra];
6697
7065
  }
6698
7066
  function checkStudioServerImports(ctx) {
@@ -6722,7 +7090,7 @@ function checkStudioServerImports(ctx) {
6722
7090
  }
6723
7091
  function checkRemovedScopeNames(ctx) {
6724
7092
  let augmentedMemo;
6725
- const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path28.join(ctx.root, rel), "utf8")));
7093
+ const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path29.join(ctx.root, rel), "utf8")));
6726
7094
  for (const file of ctx.files) {
6727
7095
  if (!SCRIPT_EXTS5.has(file.ext)) continue;
6728
7096
  for (const hit of findRemovedScopeNames(file.code)) {
@@ -6811,16 +7179,16 @@ function genesisNamedImports(source) {
6811
7179
  }
6812
7180
  function declarationFiles(dir, out = []) {
6813
7181
  for (const name of readdirSync(dir)) {
6814
- const full = path28.join(dir, name);
7182
+ const full = path29.join(dir, name);
6815
7183
  if (statSync(full).isDirectory()) declarationFiles(full, out);
6816
7184
  else if (/\.d\.[cm]?ts$/.test(name)) out.push(full);
6817
7185
  }
6818
7186
  return out;
6819
7187
  }
6820
7188
  function readPackageTags(dir) {
6821
- const pkg = JSON.parse(readFileSync(path28.join(dir, "package.json"), "utf8"));
7189
+ const pkg = JSON.parse(readFileSync(path29.join(dir, "package.json"), "utf8"));
6822
7190
  const tags = { dir, byFile: /* @__PURE__ */ new Map(), declaredIn: /* @__PURE__ */ new Map(), exports: typeof pkg.exports === "object" && pkg.exports ? pkg.exports : {} };
6823
- const dist = path28.join(dir, "dist");
7191
+ const dist = path29.join(dir, "dist");
6824
7192
  if (!existsSync(dist)) return tags;
6825
7193
  for (const file of declarationFiles(dist)) {
6826
7194
  const text = readFileSync(file, "utf8");
@@ -6838,7 +7206,7 @@ function entryFile(tags, pkg, specifier) {
6838
7206
  const subpath = `.${specifier.slice(pkg.length)}` || ".";
6839
7207
  const target = tags.exports[subpath === "." ? "." : subpath];
6840
7208
  const types = typeof target === "object" && target ? target.types : null;
6841
- return typeof types === "string" ? path28.join(tags.dir, types) : null;
7209
+ return typeof types === "string" ? path29.join(tags.dir, types) : null;
6842
7210
  }
6843
7211
  function tagFor(tags, entry, name) {
6844
7212
  if (entry && tags.declaredIn.get(name)?.includes(entry)) return tags.byFile.get(entry)?.get(name);
@@ -6902,7 +7270,7 @@ function showAt(dir, rev, file) {
6902
7270
  function configAtBase(root, base, explicitFile) {
6903
7271
  const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6904
7272
  if (!mergeBase) return null;
6905
- const candidates = explicitFile ? [{ dir: path28.dirname(explicitFile), file: path28.basename(explicitFile), explicit: true }] : [
7273
+ const candidates = explicitFile ? [{ dir: path29.dirname(explicitFile), file: path29.basename(explicitFile), explicit: true }] : [
6906
7274
  { dir: root, file: "genesis.config.json", explicit: false },
6907
7275
  { dir: root, file: "package.json", explicit: false }
6908
7276
  ];
@@ -7092,13 +7460,13 @@ function currentAgentsBlock(agents) {
7092
7460
  function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
7093
7461
  const rows = primitivesCatalog(packages);
7094
7462
  const changed = [];
7095
- const agents = path28.join(root, agentsFile);
7463
+ const agents = path29.join(root, agentsFile);
7096
7464
  const before = read(agents);
7097
7465
  const after = mergeAgentsBlock(before, renderAgentsBlock(rows));
7098
- const skill = path28.join(root, SKILL_PATH);
7466
+ const skill = path29.join(root, SKILL_PATH);
7099
7467
  const skillText = renderSkill(rows);
7100
7468
  if (read(skill)?.replace(/\r\n/g, "\n") !== skillText) {
7101
- mkdirSync(path28.dirname(skill), { recursive: true });
7469
+ mkdirSync(path29.dirname(skill), { recursive: true });
7102
7470
  writeFileSync(skill, skillText);
7103
7471
  changed.push(SKILL_PATH);
7104
7472
  }
@@ -7110,8 +7478,8 @@ function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
7110
7478
  }
7111
7479
  function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
7112
7480
  const rows = primitivesCatalog(packages);
7113
- const skill = read(path28.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
7114
- const block = currentAgentsBlock(read(path28.join(root, agentsFile)));
7481
+ const skill = read(path29.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
7482
+ const block = currentAgentsBlock(read(path29.join(root, agentsFile)));
7115
7483
  return {
7116
7484
  skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
7117
7485
  agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
@@ -7189,111 +7557,305 @@ var init_primitives = __esm({
7189
7557
  read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
7190
7558
  }
7191
7559
  });
7192
-
7193
- // src/doctor/index.ts
7194
- var doctor_exports = {};
7195
- __export(doctor_exports, {
7196
- BUILTIN_RULES: () => BUILTIN_RULES,
7197
- DoctorConfigError: () => DoctorConfigError,
7198
- GenesisConfigError: () => GenesisConfigError,
7199
- PackageDeclarationError: () => PackageDeclarationError,
7200
- SKILL_PATH: () => SKILL_PATH,
7201
- agentGuideState: () => agentGuideState,
7202
- builtinChecks: () => builtinChecks,
7203
- catalogTable: () => catalogTable,
7204
- changedSince: () => changedSince,
7205
- clearPackageRulesCache: () => clearPackageRulesCache,
7206
- defineDoctorPlugin: () => defineDoctorPlugin,
7207
- discoverPackages: () => discoverPackages,
7208
- findPackageDir: () => findPackageDir,
7209
- formatPrimitives: () => formatPrimitives,
7210
- formatReport: () => formatReport,
7211
- genesisInstalls: () => genesisInstalls,
7212
- genesisSummary: () => genesisSummary,
7213
- globToRegExp: () => globToRegExp,
7214
- loadConfig: () => loadConfig,
7215
- loadGenesis: () => loadGenesis,
7216
- nativeLayouts: () => nativeLayouts,
7217
- parseExportNames: () => parseExportNames,
7218
- parseRulesMarkdown: () => parseRulesMarkdown,
7219
- postgresContract: () => postgresContract,
7220
- postgresSource: () => postgresSource,
7221
- preferRules: () => preferRules,
7222
- primitivesCatalog: () => primitivesCatalog,
7223
- primitivesSummary: () => primitivesSummary,
7224
- readGenesisConfig: () => readGenesisConfig,
7225
- readPackageExports: () => readPackageExports,
7226
- readReleaseManifest: () => readReleaseManifest,
7227
- renderAgentsBlock: () => renderAgentsBlock,
7228
- renderSkill: () => renderSkill,
7229
- routesDir: () => routesDir,
7230
- ruleNamespace: () => ruleNamespace,
7231
- runDoctor: () => runDoctor,
7232
- satisfies: () => satisfies,
7233
- sqlStatements: () => sqlStatements,
7234
- toJson: () => toJson,
7235
- validateConfig: () => validateConfig,
7236
- validateDeclaration: () => validateDeclaration,
7237
- validateLinks: () => validateLinks,
7238
- webRoutes: () => webRoutes,
7239
- writeAgentGuide: () => writeAgentGuide
7240
- });
7241
- async function runDoctor(options = {}) {
7242
- const root = path28.resolve(options.root ?? process.cwd());
7243
- const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
7244
- const config = loaded.config;
7245
- const genesis = options.genesis ?? loadGenesis(root, config);
7246
- const files = scanFiles(root, config);
7247
- const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
7248
- const plugins = await loadPlugins(config.plugins, loaded.dir);
7249
- const packages = discoverPackages(root);
7250
- const packagePlugins = await packageRulesPlugins(packages);
7251
- const builtinIds = new Set(BUILTIN_RULES);
7252
- for (const p of config.patterns ?? []) {
7253
- 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`);
7560
+ function copyOwned(root, lock, write, dryRun = false) {
7561
+ const existing = readApp(root, write.path);
7562
+ const record = () => {
7563
+ lock.files[write.path] = { source: write.source, sha256: sha256(write.content), ...write.version ? { version: write.version } : {} };
7564
+ };
7565
+ if (existing === null) {
7566
+ if (!dryRun) createApp(root, write.path, write.content);
7567
+ record();
7568
+ return "created";
7254
7569
  }
7255
- const raw = [];
7256
- const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
7257
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
7258
- try {
7259
- await plugin.check(ctx);
7260
- } catch (err) {
7261
- if (err instanceof DoctorConfigError) throw err;
7262
- raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7263
- }
7570
+ if (existing === write.content) {
7571
+ record();
7572
+ return "same";
7264
7573
  }
7265
- if (options.build) {
7266
- const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
7267
- if (failure) raw.push(failure);
7574
+ return "kept";
7575
+ }
7576
+ function ownedKeyProblem(key2, source, localNames = /* @__PURE__ */ new Set()) {
7577
+ let parsed;
7578
+ try {
7579
+ parsed = parseSource(source);
7580
+ } catch (err) {
7581
+ return err instanceof Error ? err.message : String(err);
7268
7582
  }
7269
- raw.push(...unknownPackageRuleSettings(config, packages, raw));
7270
- const newOnly = /* @__PURE__ */ new Set([...RATCHETED_BY_DEFAULT, ...patterns?.newOnly ?? [], ...preferRules(packages).filter((r) => r.newOnly).map((r) => r.ruleId)]);
7271
- let changed = null;
7272
- let skipped = false;
7273
- const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
7274
- if (options.base && (ratchetNeeded || config.ratchet)) {
7275
- changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
7276
- skipped ||= !changed;
7583
+ const { package: pkg, path: rel } = parsed;
7584
+ if (!GENESIS_PACKAGE.test(pkg) && !localNames.has(pkg)) return `${key2}'s source ${pkg} isn't a Genesis or local package`;
7585
+ if (!safeRelative(rel) || !safeRelative(key2)) return `${key2} or its source isn't a plain path`;
7586
+ if (key2.startsWith("supabase/migrations/")) return `${key2} is a migration; migrations are never refreshed`;
7587
+ const base = rel.split("/").pop();
7588
+ if (pkg === CLI && rel.startsWith("templates/")) {
7589
+ return /^(eas\.json|\.eas\/[\w./-]+|\.maestro\/[\w./-]+|\.github\/workflows\/[\w.-]+\.ya?ml)$/.test(key2) ? null : `${key2} isn't where a template goes`;
7277
7590
  }
7278
- const configFile = "file" in loaded ? loaded.file : null;
7279
- const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7280
- let configSkipped = false;
7281
- if (options.base && configFile) {
7282
- const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
7283
- if (before && before !== "absent") {
7284
- raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
7285
- raw.push(...rulesWeakened(config, before, options.base));
7591
+ const fn = /^functions\/([a-z0-9][a-z0-9_-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(rel);
7592
+ if (fn) return key2 === `supabase/functions/${fn[1]}/${fn[2]}` ? null : `${key2} isn't where ${rel} goes`;
7593
+ if (/\.test\.sql$/.test(base)) return key2 === `supabase/tests/database/${base.replace(/^\d{4}_/, "")}` ? null : `${key2} isn't where ${rel} goes`;
7594
+ if (/^\.claude\/skills\/[a-z0-9][a-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key2) && key2.endsWith(`/${base}`)) return null;
7595
+ return `${key2} doesn't match its source ${source}`;
7596
+ }
7597
+ function mergeThreeWay(mine, base, theirs) {
7598
+ const dir = mkdtempSync(path29.join(tmpdir(), "genesis-merge-"));
7599
+ try {
7600
+ const [m, b, t] = ["mine", "base", "theirs"].map((n) => path29.join(dir, n));
7601
+ writeFileSync(m, mine);
7602
+ writeFileSync(b, base);
7603
+ writeFileSync(t, theirs);
7604
+ try {
7605
+ execFileSync("git", ["merge-file", "-q", "-L", "yours", "-L", "base", "-L", "genesis", m, b, t], { stdio: "ignore" });
7606
+ return { text: readFileSync(m, "utf8"), clean: true };
7607
+ } catch (err) {
7608
+ const status = err.status;
7609
+ if (typeof status === "number" && status > 0 && status < 128) return { text: readFileSync(m, "utf8"), clean: false };
7610
+ return null;
7286
7611
  }
7287
- configSkipped = !before && guarded;
7288
- }
7289
- if (skipped || configSkipped) {
7290
- raw.push(
7291
- 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` }
7292
- );
7612
+ } finally {
7613
+ rmSync(dir, { recursive: true, force: true });
7614
+ }
7615
+ }
7616
+ function refreshOwned(root, lock, input, options = {}) {
7617
+ const entry = lock.files[input.path];
7618
+ if (!entry) throw new Error(`${input.path} isn't in genesis.lock.json`);
7619
+ const problem = ownedKeyProblem(input.path, entry.source, localPackageNames(root));
7620
+ if (problem) return { path: input.path, outcome: "refused", detail: `genesis.lock.json: ${problem}; left alone` };
7621
+ const write = (rel, text) => {
7622
+ if (!options.dryRun) replaceApp(root, rel, text);
7623
+ };
7624
+ const mine = readApp(root, input.path);
7625
+ if (input.theirs === null) return { path: input.path, outcome: "gone-upstream", detail: "no longer shipped; left as it is" };
7626
+ const theirsSha = sha256(input.theirs);
7627
+ if (theirsSha === entry.sha256) return { path: input.path, outcome: "unchanged" };
7628
+ const record = (sha) => {
7629
+ const { pending: _settled, deleted: _back, ...rest } = entry;
7630
+ lock.files[input.path] = { ...rest, sha256: sha, ...input.version ? { version: input.version } : {} };
7631
+ };
7632
+ if (mine === null) {
7633
+ return { path: input.path, outcome: "kept-deleted", detail: entry.deleted ? "deleted in the app; not brought back" : 'deleted in the app; not brought back (mark it "deleted": true in genesis.lock.json if that is on purpose)' };
7634
+ }
7635
+ const mineSha = sha256(mine);
7636
+ if (mineSha === entry.sha256 || mineSha === theirsSha) {
7637
+ write(input.path, input.theirs);
7638
+ record(theirsSha);
7639
+ return { path: input.path, outcome: "updated" };
7640
+ }
7641
+ const next = `${input.path}.genesis-next`;
7642
+ const existingNext = readApp(root, next);
7643
+ if (entry.pending === theirsSha) {
7644
+ if (existingNext === null) {
7645
+ const { pending: _done, ...rest } = entry;
7646
+ lock.files[input.path] = { ...rest, sha256: theirsSha, ...input.version ? { version: input.version } : {} };
7647
+ return { path: input.path, outcome: "resolved", detail: "your file is kept as the resolution of the last upgrade" };
7648
+ }
7649
+ return { path: input.path, outcome: "kept-mine", detail: `waiting for you: resolve ${next} into your file, then delete it` };
7650
+ }
7651
+ const writeNext = (text) => {
7652
+ if (existingNext !== null && existingNext !== text) return `${next} is already there with other text; resolve it (and delete it) first`;
7653
+ write(next, text);
7654
+ lock.files[input.path] = { ...entry, pending: theirsSha };
7655
+ return null;
7656
+ };
7657
+ if (!options.keepMine && input.base !== null && sha256(input.base) === entry.sha256) {
7658
+ const merged = mergeThreeWay(mine, input.base, input.theirs);
7659
+ if (merged?.clean) {
7660
+ write(input.path, merged.text);
7661
+ record(theirsSha);
7662
+ return { path: input.path, outcome: "merged", detail: "your edits kept on top of the new version" };
7663
+ }
7664
+ if (merged) {
7665
+ const blocked2 = writeNext(merged.text);
7666
+ return { path: input.path, outcome: "conflict", detail: blocked2 ?? `merge conflicts written to ${next}; your file is unchanged` };
7667
+ }
7668
+ }
7669
+ const blocked = writeNext(input.theirs);
7670
+ return { path: input.path, outcome: "kept-mine", detail: blocked ?? `you changed it; the new version is in ${next}` };
7671
+ }
7672
+ var CLI;
7673
+ var init_owned = __esm({
7674
+ "src/blocks/owned.ts"() {
7675
+ init_files();
7676
+ init_lock();
7677
+ init_local();
7678
+ init_manifest();
7679
+ CLI = "@marktiderman/genesis-cli";
7680
+ }
7681
+ });
7682
+ async function checkLockFiles(ctx) {
7683
+ if (!existsSync(path29.join(ctx.root, LOCK_FILE))) return;
7684
+ let lock;
7685
+ try {
7686
+ lock = readLock(ctx.root);
7687
+ } catch (err) {
7688
+ ctx.report({ rule: "lock-files", level: "warn", file: LOCK_FILE, message: `can't be read (${err instanceof Error ? err.message : String(err)}); genesis upgrade and migrate can't either` });
7689
+ return;
7690
+ }
7691
+ const catalog = catalogBlocks();
7692
+ const off = appBlocksSwitchedOff(ctx.root, catalog, Object.keys(lock.blocks));
7693
+ const offManifests = [];
7694
+ for (const [id, entry] of Object.entries(lock.blocks)) {
7695
+ const feature = off.get(id);
7696
+ if (!feature) continue;
7697
+ try {
7698
+ offManifests.push((await findBlock(ctx.root, id, { package: entry.package })).manifest);
7699
+ } catch {
7700
+ offManifests.push(...catalog.filter((m) => m.id === id));
7701
+ }
7702
+ ctx.report({
7703
+ rule: "lock-files",
7704
+ level: "info",
7705
+ file: LOCK_FILE,
7706
+ subject: id,
7707
+ message: `lists the ${id} block, but features.${feature} is off in ${STARTER_CONFIG}: genesis upgrade and migrate leave it out (delete its entry if it's gone for good)`
7708
+ });
7709
+ }
7710
+ const local = localPackageNames(ctx.root);
7711
+ for (const [rel, entry] of Object.entries(lock.files)) {
7712
+ if (ownedKeyProblem(rel, entry.source, local)) continue;
7713
+ if (offManifests.length && blockOfSource(entry.source, offManifests)) continue;
7714
+ let text;
7715
+ try {
7716
+ text = readApp(ctx.root, rel);
7717
+ } catch {
7718
+ continue;
7719
+ }
7720
+ if (text === null) {
7721
+ if (entry.deleted) continue;
7722
+ ctx.report({
7723
+ rule: "lock-files",
7724
+ level: "warn",
7725
+ file: rel,
7726
+ subject: rel,
7727
+ message: `is in ${LOCK_FILE} (from ${entry.source}) but not on disk, and genesis upgrade won't bring it back. Deleted on purpose: add "deleted": true to its entry in ${LOCK_FILE}. Otherwise restore it (git checkout, or copy it from ${entry.source})`
7728
+ });
7729
+ continue;
7730
+ }
7731
+ if (entry.deleted) {
7732
+ ctx.report({ rule: "lock-files", level: "info", file: rel, subject: rel, message: `is marked "deleted": true in ${LOCK_FILE} but is on disk; remove the marker` });
7733
+ }
7734
+ if (sha256(text) === entry.sha256) continue;
7735
+ ctx.report({
7736
+ rule: "lock-files",
7737
+ level: "info",
7738
+ file: rel,
7739
+ subject: rel,
7740
+ message: entry.pending ? `differs from ${LOCK_FILE}: the last upgrade's version is waiting in ${rel}.genesis-next; resolve it into this file and delete it` : `differs from ${LOCK_FILE} (edited in the app); genesis upgrade three-way merges the next version into your edits`
7741
+ });
7742
+ }
7743
+ }
7744
+ var init_lock_files = __esm({
7745
+ "src/doctor/lock-files.ts"() {
7746
+ init_discover();
7747
+ init_files();
7748
+ init_lock();
7749
+ init_local();
7750
+ init_owned();
7751
+ init_starter_features();
7752
+ }
7753
+ });
7754
+
7755
+ // src/doctor/index.ts
7756
+ var doctor_exports = {};
7757
+ __export(doctor_exports, {
7758
+ BUILTIN_RULES: () => BUILTIN_RULES,
7759
+ DoctorConfigError: () => DoctorConfigError,
7760
+ GenesisConfigError: () => GenesisConfigError,
7761
+ PackageDeclarationError: () => PackageDeclarationError,
7762
+ SKILL_PATH: () => SKILL_PATH,
7763
+ agentGuideState: () => agentGuideState,
7764
+ builtinChecks: () => builtinChecks,
7765
+ catalogTable: () => catalogTable,
7766
+ changedSince: () => changedSince,
7767
+ clearPackageRulesCache: () => clearPackageRulesCache,
7768
+ defineDoctorPlugin: () => defineDoctorPlugin,
7769
+ discoverPackages: () => discoverPackages,
7770
+ findPackageDir: () => findPackageDir,
7771
+ formatPrimitives: () => formatPrimitives,
7772
+ formatReport: () => formatReport,
7773
+ genesisInstalls: () => genesisInstalls,
7774
+ genesisSummary: () => genesisSummary,
7775
+ globToRegExp: () => globToRegExp,
7776
+ loadConfig: () => loadConfig,
7777
+ loadGenesis: () => loadGenesis,
7778
+ nativeLayouts: () => nativeLayouts,
7779
+ parseExportNames: () => parseExportNames,
7780
+ parseRulesMarkdown: () => parseRulesMarkdown,
7781
+ postgresContract: () => postgresContract,
7782
+ postgresSource: () => postgresSource,
7783
+ preferRules: () => preferRules,
7784
+ primitivesCatalog: () => primitivesCatalog,
7785
+ primitivesSummary: () => primitivesSummary,
7786
+ readGenesisConfig: () => readGenesisConfig,
7787
+ readPackageExports: () => readPackageExports,
7788
+ readReleaseManifest: () => readReleaseManifest,
7789
+ renderAgentsBlock: () => renderAgentsBlock,
7790
+ renderSkill: () => renderSkill,
7791
+ routesDir: () => routesDir,
7792
+ ruleNamespace: () => ruleNamespace,
7793
+ runDoctor: () => runDoctor,
7794
+ satisfies: () => satisfies,
7795
+ sqlStatements: () => sqlStatements,
7796
+ toJson: () => toJson,
7797
+ validateConfig: () => validateConfig,
7798
+ validateDeclaration: () => validateDeclaration,
7799
+ validateLinks: () => validateLinks,
7800
+ webRoutes: () => webRoutes,
7801
+ writeAgentGuide: () => writeAgentGuide
7802
+ });
7803
+ async function runDoctor(options = {}) {
7804
+ const root = path29.resolve(options.root ?? process.cwd());
7805
+ const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
7806
+ const config = loaded.config;
7807
+ const genesis = options.genesis ?? loadGenesis(root, config);
7808
+ const files = scanFiles(root, config);
7809
+ const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
7810
+ const plugins = await loadPlugins(config.plugins, loaded.dir);
7811
+ const packages = discoverPackages(root);
7812
+ const packagePlugins = await packageRulesPlugins(packages);
7813
+ const builtinIds = new Set(BUILTIN_RULES);
7814
+ for (const p of config.patterns ?? []) {
7815
+ 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`);
7816
+ }
7817
+ const raw = [];
7818
+ const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
7819
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
7820
+ try {
7821
+ await plugin.check(ctx);
7822
+ } catch (err) {
7823
+ if (err instanceof DoctorConfigError) throw err;
7824
+ raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
7825
+ }
7826
+ }
7827
+ if (options.build) {
7828
+ const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
7829
+ if (failure) raw.push(failure);
7830
+ }
7831
+ raw.push(...unknownPackageRuleSettings(config, packages, raw));
7832
+ const newOnly = /* @__PURE__ */ new Set([...RATCHETED_BY_DEFAULT, ...patterns?.newOnly ?? [], ...preferRules(packages).filter((r) => r.newOnly).map((r) => r.ruleId)]);
7833
+ let changed = null;
7834
+ let skipped = false;
7835
+ const ratchetNeeded = newOnly.size > RATCHETED_BY_DEFAULT.length || raw.some((f) => RATCHETED_BY_DEFAULT.includes(f.rule));
7836
+ if (options.base && (ratchetNeeded || config.ratchet)) {
7837
+ changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
7838
+ skipped ||= !changed;
7839
+ }
7840
+ const configFile = "file" in loaded ? loaded.file : null;
7841
+ const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
7842
+ let configSkipped = false;
7843
+ if (options.base && configFile) {
7844
+ const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
7845
+ if (before && before !== "absent") {
7846
+ raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
7847
+ raw.push(...rulesWeakened(config, before, options.base));
7848
+ }
7849
+ configSkipped = !before && guarded;
7850
+ }
7851
+ if (skipped || configSkipped) {
7852
+ raw.push(
7853
+ 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` }
7854
+ );
7293
7855
  }
7294
7856
  let findings = applyConfig(raw, config, packageRuleIds(packages));
7295
7857
  if (options.base && changed) {
7296
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path28.join(root, f)) });
7858
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path29.join(root, f)) });
7297
7859
  }
7298
7860
  const errors = findings.filter((f) => f.level === "error").length;
7299
7861
  const warnings = findings.filter((f) => f.level === "warn").length;
@@ -7338,6 +7900,7 @@ function builtinChecks(config, options = {}) {
7338
7900
  { name: "stability-imports", check: checkStabilityImports },
7339
7901
  { name: "agent-guide", check: checkAgentGuide },
7340
7902
  { name: "overlays", check: (ctx) => checkOverlays(ctx) },
7903
+ { name: "lock-files", check: checkLockFiles },
7341
7904
  ...(config.packs ?? []).map((p) => packs[p]),
7342
7905
  ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
7343
7906
  ];
@@ -7452,6 +8015,7 @@ var init_doctor = __esm({
7452
8015
  init_contracts();
7453
8016
  init_primitives();
7454
8017
  init_overlays();
8018
+ init_lock_files();
7455
8019
  init_config();
7456
8020
  init_genesis();
7457
8021
  init_patterns();
@@ -7481,12 +8045,12 @@ __export(agent_rules_exports, {
7481
8045
  runsOnPullRequestsInto: () => runsOnPullRequestsInto
7482
8046
  });
7483
8047
  function changesetBumps(root) {
7484
- const dir = path28.join(root, ".changeset");
8048
+ const dir = path29.join(root, ".changeset");
7485
8049
  const bumps = /* @__PURE__ */ new Map();
7486
8050
  if (!existsSync(dir)) return bumps;
7487
8051
  for (const name of readdirSync(dir)) {
7488
8052
  if (!name.endsWith(".md") || name === "README.md") continue;
7489
- const text = readFileSync(path28.join(dir, name), "utf8");
8053
+ const text = readFileSync(path29.join(dir, name), "utf8");
7490
8054
  const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? "";
7491
8055
  for (const line of front.split(/\r?\n/)) {
7492
8056
  const m = /^\s*["']?([^"':]+)["']?\s*:\s*(major|minor|patch)\s*$/.exec(line);
@@ -7499,13 +8063,13 @@ function changesetBumps(root) {
7499
8063
  return bumps;
7500
8064
  }
7501
8065
  function firstVersionProblems(root) {
7502
- const packagesDir = path28.join(root, "packages");
8066
+ const packagesDir = path29.join(root, "packages");
7503
8067
  if (!existsSync(packagesDir)) return [];
7504
8068
  const bumps = changesetBumps(root);
7505
8069
  const problems = [];
7506
8070
  for (const dir of readdirSync(packagesDir)) {
7507
- const file = path28.join(packagesDir, dir, "package.json");
7508
- if (!existsSync(file) || existsSync(path28.join(packagesDir, dir, "CHANGELOG.md"))) continue;
8071
+ const file = path29.join(packagesDir, dir, "package.json");
8072
+ if (!existsSync(file) || existsSync(path29.join(packagesDir, dir, "CHANGELOG.md"))) continue;
7509
8073
  const pkg = JSON.parse(readFileSync(file, "utf8"));
7510
8074
  if (pkg.private || !pkg.name) continue;
7511
8075
  if (pkg.version !== FIRST_VERSION) {
@@ -7576,12 +8140,12 @@ function runsOnPullRequestsInto(workflow, branch) {
7576
8140
  return ignore ? !ignore.some((p) => globMatches(p, branch)) : void 0;
7577
8141
  }
7578
8142
  function batchCiProblems(root, batch) {
7579
- const dir = path28.join(root, ".github", "workflows");
8143
+ const dir = path29.join(root, ".github", "workflows");
7580
8144
  if (!existsSync(dir)) return [];
7581
8145
  const problems = [];
7582
8146
  for (const name of readdirSync(dir)) {
7583
8147
  if (!/\.ya?ml$/.test(name)) continue;
7584
- const workflow = readFileSync(path28.join(dir, name), "utf8");
8148
+ const workflow = readFileSync(path29.join(dir, name), "utf8");
7585
8149
  const main = runsOnPullRequestsInto(workflow, "main");
7586
8150
  if (main && !runsOnPullRequestsInto(workflow, sampleBranch(batch))) {
7587
8151
  problems.push({ rule: "batch-ci", message: `.github/workflows/${name}: runs on pull requests into main but not into ${batch}; let pull_request's branch filter include it` });
@@ -7626,20 +8190,20 @@ function readObject(file, key2) {
7626
8190
  }
7627
8191
  }
7628
8192
  function settings(root, options) {
7629
- const fromPackage = readObject(path28.join(root, "package.json"), "genesisFeatures");
7630
- const fromConfig = readObject(path28.join(root, "genesis.config.json"), "features");
8193
+ const fromPackage = readObject(path29.join(root, "package.json"), "genesisFeatures");
8194
+ const fromConfig = readObject(path29.join(root, "genesis.config.json"), "features");
7631
8195
  const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
7632
8196
  return { ...fromPackage, ...fromConfig, ...given };
7633
8197
  }
7634
8198
  async function loadRegistry(input) {
7635
- const root = path28.resolve(input.dir);
8199
+ const root = path29.resolve(input.dir);
7636
8200
  const options = settings(root, input);
7637
- const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path28.join(root, p)));
7638
- if (!registry || !existsSync(path28.join(root, registry))) {
8201
+ const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path29.join(root, p)));
8202
+ if (!registry || !existsSync(path29.join(root, registry))) {
7639
8203
  throw new Error(`No feature registry found. Looked for ${options.registry ?? DEFAULT_REGISTRIES.join(" and ")}; pass --registry.`);
7640
8204
  }
7641
- const jiti = createJiti(path28.join(root, "package.json"), { moduleCache: false });
7642
- const load = async (file) => await jiti.import(path28.join(root, file));
8205
+ const jiti = createJiti(path29.join(root, "package.json"), { moduleCache: false });
8206
+ const load = async (file) => await jiti.import(path29.join(root, file));
7643
8207
  const mod = await load(registry);
7644
8208
  const features2 = mod.features ?? mod.default;
7645
8209
  if (!isObject4(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
@@ -7651,7 +8215,7 @@ async function loadRegistry(input) {
7651
8215
  const project = {
7652
8216
  ...rest,
7653
8217
  root,
7654
- source: options.source ?? registry.split(path28.sep).join("/"),
8218
+ source: options.source ?? registry.split(path29.sep).join("/"),
7655
8219
  features: features2,
7656
8220
  flags
7657
8221
  };
@@ -7702,23 +8266,23 @@ async function runFeaturesCheck(options) {
7702
8266
  function readFeaturePackages(root) {
7703
8267
  const found = [];
7704
8268
  const read2 = (dir, inRepo) => {
7705
- const file = path28.join(dir, "package.json");
8269
+ const file = path29.join(dir, "package.json");
7706
8270
  if (!existsSync(file)) return;
7707
8271
  try {
7708
8272
  const pkg = JSON.parse(readFileSync(file, "utf8"));
7709
8273
  const layer = pkg.genesis?.layer;
7710
8274
  if (typeof pkg.name !== "string" || !PACKAGE_LAYERS.includes(layer)) return;
7711
8275
  if (found.some((p) => p.name === pkg.name)) return;
7712
- found.push({ name: pkg.name, layer, ...inRepo ? { dir: path28.relative(root, dir).split(path28.sep).join("/") } : {} });
8276
+ found.push({ name: pkg.name, layer, ...inRepo ? { dir: path29.relative(root, dir).split(path29.sep).join("/") } : {} });
7713
8277
  } catch {
7714
8278
  }
7715
8279
  };
7716
8280
  for (const [base, inRepo] of [
7717
- [path28.join(root, "packages"), true],
7718
- [path28.join(root, "node_modules", "@marktiderman"), false]
8281
+ [path29.join(root, "packages"), true],
8282
+ [path29.join(root, "node_modules", "@marktiderman"), false]
7719
8283
  ]) {
7720
8284
  if (!existsSync(base)) continue;
7721
- for (const name of readdirSync(base)) read2(path28.join(base, name), inRepo);
8285
+ for (const name of readdirSync(base)) read2(path29.join(base, name), inRepo);
7722
8286
  }
7723
8287
  return found;
7724
8288
  }
@@ -7835,7 +8399,7 @@ function readRegister(markdown) {
7835
8399
  const need = at(row, "need");
7836
8400
  if (!need || need === "-") problems.push(`${where2}: say the need in one line`);
7837
8401
  const local = at(row, "local");
7838
- if (local && local !== "-" && localPaths(local).some((p) => path28.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p) || p.split(/[\\/]/).includes(".."))) {
8402
+ if (local && local !== "-" && localPaths(local).some((p) => path29.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p) || p.split(/[\\/]/).includes(".."))) {
7839
8403
  problems.push(`${where2}: local must be paths inside the app, relative to its root`);
7840
8404
  }
7841
8405
  const opt = (c) => at(row, c) && at(row, c) !== "-" ? at(row, c) : void 0;
@@ -7847,13 +8411,13 @@ function localPaths(local) {
7847
8411
  return (local ?? "").split(/,\s+|<br\s*\/?>/i).map((p) => p.trim()).filter((p) => p && p !== "-");
7848
8412
  }
7849
8413
  function checkUpstream(root) {
7850
- const found = REGISTER_PATHS.find((p) => existsSync(path28.join(root, p)));
8414
+ const found = REGISTER_PATHS.find((p) => existsSync(path29.join(root, p)));
7851
8415
  if (!found) return { entries: [], problems: [], warnings: [`no ${REGISTER_PATHS.join(" or ")}: nothing to check (add one when the app first needs something Genesis lacks)`], missing: true };
7852
- const { entries, problems } = readRegister(readFileSync(path28.join(root, found), "utf8"));
8416
+ const { entries, problems } = readRegister(readFileSync(path29.join(root, found), "utf8"));
7853
8417
  const warnings = [];
7854
8418
  for (const e of entries) {
7855
8419
  const paths = localPaths(e.local);
7856
- const absent = paths.filter((p) => !existsSync(path28.join(root, p)));
8420
+ const absent = paths.filter((p) => !existsSync(path29.join(root, p)));
7857
8421
  const present = paths.filter((p) => !absent.includes(p));
7858
8422
  if (absent.length && e.status !== "promoted" && e.status !== "declined") problems.push(`${e.id}: local ${absent.join(", ")} doesn't exist`);
7859
8423
  if (present.length && e.status === "promoted") {
@@ -8299,128 +8863,6 @@ var init_agents = __esm({
8299
8863
  "src/blocks/agents.ts"() {
8300
8864
  }
8301
8865
  });
8302
- function copyOwned(root, lock, write, dryRun = false) {
8303
- const existing = readApp(root, write.path);
8304
- const record = () => {
8305
- lock.files[write.path] = { source: write.source, sha256: sha256(write.content), ...write.version ? { version: write.version } : {} };
8306
- };
8307
- if (existing === null) {
8308
- if (!dryRun) createApp(root, write.path, write.content);
8309
- record();
8310
- return "created";
8311
- }
8312
- if (existing === write.content) {
8313
- record();
8314
- return "same";
8315
- }
8316
- return "kept";
8317
- }
8318
- function ownedKeyProblem(key2, source, localNames = /* @__PURE__ */ new Set()) {
8319
- let parsed;
8320
- try {
8321
- parsed = parseSource(source);
8322
- } catch (err) {
8323
- return err instanceof Error ? err.message : String(err);
8324
- }
8325
- const { package: pkg, path: rel } = parsed;
8326
- if (!GENESIS_PACKAGE.test(pkg) && !localNames.has(pkg)) return `${key2}'s source ${pkg} isn't a Genesis or local package`;
8327
- if (!safeRelative(rel) || !safeRelative(key2)) return `${key2} or its source isn't a plain path`;
8328
- if (key2.startsWith("supabase/migrations/")) return `${key2} is a migration; migrations are never refreshed`;
8329
- const base = rel.split("/").pop();
8330
- if (pkg === CLI && rel.startsWith("templates/")) {
8331
- return /^(eas\.json|\.eas\/[\w./-]+|\.maestro\/[\w./-]+|\.github\/workflows\/[\w.-]+\.ya?ml)$/.test(key2) ? null : `${key2} isn't where a template goes`;
8332
- }
8333
- const fn = /^functions\/([a-z0-9][a-z0-9_-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(rel);
8334
- if (fn) return key2 === `supabase/functions/${fn[1]}/${fn[2]}` ? null : `${key2} isn't where ${rel} goes`;
8335
- if (/\.test\.sql$/.test(base)) return key2 === `supabase/tests/database/${base.replace(/^\d{4}_/, "")}` ? null : `${key2} isn't where ${rel} goes`;
8336
- if (/^\.claude\/skills\/[a-z0-9][a-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key2) && key2.endsWith(`/${base}`)) return null;
8337
- return `${key2} doesn't match its source ${source}`;
8338
- }
8339
- function mergeThreeWay(mine, base, theirs) {
8340
- const dir = mkdtempSync(path28.join(tmpdir(), "genesis-merge-"));
8341
- try {
8342
- const [m, b, t] = ["mine", "base", "theirs"].map((n) => path28.join(dir, n));
8343
- writeFileSync(m, mine);
8344
- writeFileSync(b, base);
8345
- writeFileSync(t, theirs);
8346
- try {
8347
- execFileSync("git", ["merge-file", "-q", "-L", "yours", "-L", "base", "-L", "genesis", m, b, t], { stdio: "ignore" });
8348
- return { text: readFileSync(m, "utf8"), clean: true };
8349
- } catch (err) {
8350
- const status = err.status;
8351
- if (typeof status === "number" && status > 0 && status < 128) return { text: readFileSync(m, "utf8"), clean: false };
8352
- return null;
8353
- }
8354
- } finally {
8355
- rmSync(dir, { recursive: true, force: true });
8356
- }
8357
- }
8358
- function refreshOwned(root, lock, input, options = {}) {
8359
- const entry = lock.files[input.path];
8360
- if (!entry) throw new Error(`${input.path} isn't in genesis.lock.json`);
8361
- const problem = ownedKeyProblem(input.path, entry.source, localPackageNames(root));
8362
- if (problem) return { path: input.path, outcome: "refused", detail: `genesis.lock.json: ${problem}; left alone` };
8363
- const write = (rel, text) => {
8364
- if (!options.dryRun) replaceApp(root, rel, text);
8365
- };
8366
- const mine = readApp(root, input.path);
8367
- if (input.theirs === null) return { path: input.path, outcome: "gone-upstream", detail: "no longer shipped; left as it is" };
8368
- const theirsSha = sha256(input.theirs);
8369
- if (theirsSha === entry.sha256) return { path: input.path, outcome: "unchanged" };
8370
- const record = (sha) => {
8371
- const { pending: _settled, ...rest } = entry;
8372
- lock.files[input.path] = { ...rest, sha256: sha, ...input.version ? { version: input.version } : {} };
8373
- };
8374
- if (mine === null) {
8375
- return { path: input.path, outcome: "kept-deleted", detail: "deleted in the app; not brought back" };
8376
- }
8377
- const mineSha = sha256(mine);
8378
- if (mineSha === entry.sha256 || mineSha === theirsSha) {
8379
- write(input.path, input.theirs);
8380
- record(theirsSha);
8381
- return { path: input.path, outcome: "updated" };
8382
- }
8383
- const next = `${input.path}.genesis-next`;
8384
- const existingNext = readApp(root, next);
8385
- if (entry.pending === theirsSha) {
8386
- if (existingNext === null) {
8387
- const { pending: _done, ...rest } = entry;
8388
- lock.files[input.path] = { ...rest, sha256: theirsSha, ...input.version ? { version: input.version } : {} };
8389
- return { path: input.path, outcome: "resolved", detail: "your file is kept as the resolution of the last upgrade" };
8390
- }
8391
- return { path: input.path, outcome: "kept-mine", detail: `waiting for you: resolve ${next} into your file, then delete it` };
8392
- }
8393
- const writeNext = (text) => {
8394
- if (existingNext !== null && existingNext !== text) return `${next} is already there with other text; resolve it (and delete it) first`;
8395
- write(next, text);
8396
- lock.files[input.path] = { ...entry, pending: theirsSha };
8397
- return null;
8398
- };
8399
- if (!options.keepMine && input.base !== null && sha256(input.base) === entry.sha256) {
8400
- const merged = mergeThreeWay(mine, input.base, input.theirs);
8401
- if (merged?.clean) {
8402
- write(input.path, merged.text);
8403
- record(theirsSha);
8404
- return { path: input.path, outcome: "merged", detail: "your edits kept on top of the new version" };
8405
- }
8406
- if (merged) {
8407
- const blocked2 = writeNext(merged.text);
8408
- return { path: input.path, outcome: "conflict", detail: blocked2 ?? `merge conflicts written to ${next}; your file is unchanged` };
8409
- }
8410
- }
8411
- const blocked = writeNext(input.theirs);
8412
- return { path: input.path, outcome: "kept-mine", detail: blocked ?? `you changed it; the new version is in ${next}` };
8413
- }
8414
- var CLI;
8415
- var init_owned = __esm({
8416
- "src/blocks/owned.ts"() {
8417
- init_files();
8418
- init_lock();
8419
- init_local();
8420
- init_manifest();
8421
- CLI = "@marktiderman/genesis-cli";
8422
- }
8423
- });
8424
8866
  function literal(value, indent) {
8425
8867
  if (Array.isArray(value)) return `[${value.map((v) => literal(v, indent)).join(", ")}]`;
8426
8868
  if (value && typeof value === "object") {
@@ -8433,8 +8875,8 @@ ${indent}}`;
8433
8875
  return JSON.stringify(value);
8434
8876
  }
8435
8877
  function featureKindField(root) {
8436
- for (let dir = path28.resolve(root); ; dir = path28.dirname(dir)) {
8437
- for (const file of [path28.join(dir, "node_modules/@marktiderman/genesis-features/package.json"), path28.join(dir, "packages/features/package.json")]) {
8878
+ for (let dir = path29.resolve(root); ; dir = path29.dirname(dir)) {
8879
+ for (const file of [path29.join(dir, "node_modules/@marktiderman/genesis-features/package.json"), path29.join(dir, "packages/features/package.json")]) {
8438
8880
  try {
8439
8881
  const pkg = JSON.parse(readFileSync(file, "utf8"));
8440
8882
  if (pkg.name !== "@marktiderman/genesis-features" || !pkg.version) continue;
@@ -8443,7 +8885,7 @@ function featureKindField(root) {
8443
8885
  } catch {
8444
8886
  }
8445
8887
  }
8446
- if (path28.dirname(dir) === dir) return "layer";
8888
+ if (path29.dirname(dir) === dir) return "layer";
8447
8889
  }
8448
8890
  }
8449
8891
  function featureSnippet(manifest, owner, kindField = "kind") {
@@ -8521,12 +8963,12 @@ var init_registry_edit = __esm({
8521
8963
  });
8522
8964
  function routerRoot2(root) {
8523
8965
  try {
8524
- const config = JSON.parse(readFileSync(path28.join(root, "genesis.config.json"), "utf8"));
8966
+ const config = JSON.parse(readFileSync(path29.join(root, "genesis.config.json"), "utf8"));
8525
8967
  const configured = config.doctor?.native?.routerRoot;
8526
- if (configured && existsSync(path28.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
8968
+ if (configured && existsSync(path29.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
8527
8969
  } catch {
8528
8970
  }
8529
- for (const dir of ["src/app", "app"]) if (existsSync(path28.join(root, dir, "_layout.tsx"))) return dir;
8971
+ for (const dir of ["src/app", "app"]) if (existsSync(path29.join(root, dir, "_layout.tsx"))) return dir;
8530
8972
  return null;
8531
8973
  }
8532
8974
  function routeOf(file) {
@@ -8588,7 +9030,7 @@ __export(add_exports, {
8588
9030
  });
8589
9031
  function appDependencies(root) {
8590
9032
  try {
8591
- const pkg = JSON.parse(readFileSync(path28.join(root, "package.json"), "utf8"));
9033
+ const pkg = JSON.parse(readFileSync(path29.join(root, "package.json"), "utf8"));
8592
9034
  return { ...pkg["dependencies"], ...pkg["devDependencies"], ...pkg["optionalDependencies"] };
8593
9035
  } catch {
8594
9036
  return {};
@@ -8597,14 +9039,14 @@ function appDependencies(root) {
8597
9039
  function registryFile(root) {
8598
9040
  const read2 = (file, key2) => {
8599
9041
  try {
8600
- const v = JSON.parse(readFileSync(path28.join(root, file), "utf8"))[key2]?.registry;
9042
+ const v = JSON.parse(readFileSync(path29.join(root, file), "utf8"))[key2]?.registry;
8601
9043
  return typeof v === "string" ? v : void 0;
8602
9044
  } catch {
8603
9045
  return void 0;
8604
9046
  }
8605
9047
  };
8606
9048
  const named = read2("genesis.config.json", "features") ?? read2("package.json", "genesisFeatures");
8607
- for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path28.join(root, candidate))) return candidate;
9049
+ for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path29.join(root, candidate))) return candidate;
8608
9050
  return null;
8609
9051
  }
8610
9052
  async function registryIds(root, file) {
@@ -8692,7 +9134,7 @@ verify_jwt = false
8692
9134
  return { content: `${config.replace(/\s*$/, "\n")}${add}`, names };
8693
9135
  }
8694
9136
  async function runAdd(options) {
8695
- const root = path28.resolve(options.root);
9137
+ const root = path29.resolve(options.root);
8696
9138
  const log = options.log ?? SILENT;
8697
9139
  const now = options.now ?? /* @__PURE__ */ new Date();
8698
9140
  const warnings = [];
@@ -8705,7 +9147,7 @@ async function runAdd(options) {
8705
9147
  const local = localPackageNames(root);
8706
9148
  for (const name of found.manifest.packages) {
8707
9149
  if (deps[name] || local.has(name)) continue;
8708
- const pin = pinnedVersion(root, name);
9150
+ const pin = pinnedVersion2(root, name);
8709
9151
  specs.push(pin ? `${name}@${pin.version}` : name);
8710
9152
  }
8711
9153
  for (const spec of found.manifest.install) {
@@ -8897,7 +9339,7 @@ function notificationTypesSql(rows, registryFile2) {
8897
9339
  }
8898
9340
  function configuredRegistry(root) {
8899
9341
  try {
8900
- const raw = JSON.parse(readFileSync(path28.join(root, "genesis.config.json"), "utf8"));
9342
+ const raw = JSON.parse(readFileSync(path29.join(root, "genesis.config.json"), "utf8"));
8901
9343
  return typeof raw.notifications?.registry === "string" ? raw.notifications.registry : void 0;
8902
9344
  } catch {
8903
9345
  return void 0;
@@ -8916,14 +9358,14 @@ async function planNotificationTypes(root, options) {
8916
9358
  warnings.push(`Notification types: not checked on a dry run (loading ${file} runs app code).`);
8917
9359
  return { registry: file, warnings };
8918
9360
  }
8919
- const absolute = path28.resolve(root, file);
9361
+ const absolute = path29.resolve(root, file);
8920
9362
  if (!existsSync(absolute)) {
8921
9363
  warnings.push(`Notification types: ${file} doesn't exist (a relative path is resolved against the app's root, ${root}).`);
8922
9364
  return { registry: file, warnings };
8923
9365
  }
8924
9366
  let mod;
8925
9367
  try {
8926
- const jiti = createJiti(path28.join(root, "package.json"), { moduleCache: false });
9368
+ const jiti = createJiti(path29.join(root, "package.json"), { moduleCache: false });
8927
9369
  mod = await jiti.import(absolute);
8928
9370
  } catch (err) {
8929
9371
  warnings.push(`Notification types: couldn't load ${file} (${err instanceof Error ? err.message : String(err)}).`);
@@ -8934,8 +9376,8 @@ async function planNotificationTypes(root, options) {
8934
9376
  warnings.push(`Notification types: ${file} exports no defineNotifications registry (export it as \`notifications\`).`);
8935
9377
  return { registry: file, warnings };
8936
9378
  }
8937
- const shown = path28.isAbsolute(file) ? path28.relative(root, absolute) : file;
8938
- const content = notificationTypesSql(found.toTypeRows(), shown.split(path28.sep).join("/"));
9379
+ const shown = path29.isAbsolute(file) ? path29.relative(root, absolute) : file;
9380
+ const content = notificationTypesSql(found.toTypeRows(), shown.split(path29.sep).join("/"));
8939
9381
  const app = readAppMigrations(root);
8940
9382
  const latest = app.filter((m) => m.name.endsWith(`_${TYPES_STEM}.sql`)).sort((a, b) => a.name < b.name ? -1 : 1).pop();
8941
9383
  if (latest && payloadOf(latest.content) === payloadOf(content)) return { registry: file, warnings };
@@ -8967,10 +9409,12 @@ __export(migrate_exports, {
8967
9409
  runMigrate: () => runMigrate
8968
9410
  });
8969
9411
  async function runMigrate(options) {
8970
- const root = path28.resolve(options.root);
9412
+ const root = path29.resolve(options.root);
8971
9413
  const lock = readLock(root);
8972
9414
  const warnings = [];
8973
- const ids = [.../* @__PURE__ */ new Set([...Object.keys(lock.blocks), ...options.blocks ?? []])];
9415
+ const off = appBlocksSwitchedOff(root, catalogBlocks(), Object.keys(lock.blocks));
9416
+ const switchedOff = Object.keys(lock.blocks).filter((id) => off.has(id) && !options.blocks?.includes(id));
9417
+ const ids = [.../* @__PURE__ */ new Set([...Object.keys(lock.blocks).filter((id) => !switchedOff.includes(id)), ...options.blocks ?? []])];
8974
9418
  const sources = [];
8975
9419
  const local = localPackageNames(root);
8976
9420
  for (const id of ids) {
@@ -9010,7 +9454,7 @@ async function runMigrate(options) {
9010
9454
  }) : void 0;
9011
9455
  warnings.push(...types?.warnings ?? []);
9012
9456
  const notificationTypes = types?.create ? { notificationTypes: types.create.path } : {};
9013
- if (options.dryRun) return { plan, written: [], warnings, attention, ...notificationTypes };
9457
+ if (options.dryRun) return { plan, written: [], warnings, switchedOff: switchedOff.map((id) => switchedOffNote(id, off.get(id))), attention, ...notificationTypes };
9014
9458
  const written = applyMigrationPlan(root, plan);
9015
9459
  if (types?.create) {
9016
9460
  createApp(root, types.create.path, types.create.content);
@@ -9019,11 +9463,12 @@ async function runMigrate(options) {
9019
9463
  for (const c of plan.creates) if (c.kind === "test" && c.source) recordOwned(lock, c.path, `${c.source.package}:${c.source.file}`, c.content, root, c.source.package);
9020
9464
  const remembered = rememberMigrationCopies(lock, plan);
9021
9465
  if (remembered || plan.creates.some((c) => c.kind === "test")) writeLock(root, lock);
9022
- return { plan, written, warnings, attention, ...notificationTypes };
9466
+ return { plan, written, warnings, switchedOff: switchedOff.map((id) => switchedOffNote(id, off.get(id))), attention, ...notificationTypes };
9023
9467
  }
9024
9468
  var init_migrate = __esm({
9025
9469
  "src/blocks/migrate.ts"() {
9026
9470
  init_discover();
9471
+ init_starter_features();
9027
9472
  init_local();
9028
9473
  init_files();
9029
9474
  init_lock();
@@ -9034,11 +9479,410 @@ var init_migrate = __esm({
9034
9479
  init_notification_types();
9035
9480
  }
9036
9481
  });
9482
+ function walk2(dir, rel = "", out = /* @__PURE__ */ new Map()) {
9483
+ for (const entry of readdirSync(path29.join(dir, rel), { withFileTypes: true })) {
9484
+ if (SKIP.has(entry.name)) continue;
9485
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
9486
+ if (entry.isDirectory()) walk2(dir, child, out);
9487
+ else if (entry.isFile()) out.set(child, readFileSync(path29.join(dir, child)));
9488
+ }
9489
+ return out;
9490
+ }
9491
+ function isText(buf) {
9492
+ if (buf.subarray(0, 8e3).includes(0)) return false;
9493
+ return Buffer.from(buf.toString("utf8"), "utf8").equals(buf);
9494
+ }
9495
+ function gitUpstream(repository = GENESIS_REPOSITORY) {
9496
+ let clone = null;
9497
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
9498
+ const git4 = (args, input) => execFileSync("git", args, { cwd: clone, env, input, timeout: FETCH_TIMEOUT_MS, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 512 * 1024 * 1024 });
9499
+ const why = (err) => {
9500
+ const e = err;
9501
+ if (e.code === "ETIMEDOUT" || e.signal === "SIGTERM") return `timed out after ${FETCH_TIMEOUT_MS / 1e3}s`;
9502
+ const text = String(e.stderr || e.message || err).trim().split("\n").filter(Boolean);
9503
+ return text.slice(-2).join(" ") || "git failed";
9504
+ };
9505
+ return {
9506
+ files(name, version) {
9507
+ const tag = `${name}@${version}`;
9508
+ try {
9509
+ if (!clone) {
9510
+ clone = mkdtempSync(path29.join(tmpdir(), "genesis-upstream-"));
9511
+ git4(["init", "-q"]);
9512
+ }
9513
+ git4(["fetch", "-q", "--no-tags", "--depth", "1", repository, `+refs/tags/${tag}:refs/tags/${tag}`]);
9514
+ } catch (err) {
9515
+ return { error: `couldn't fetch the tag ${tag} from ${repository}: ${why(err)}` };
9516
+ }
9517
+ try {
9518
+ const manifests = git4(["ls-tree", "-r", "--name-only", tag]).toString("utf8").split("\n").filter((f) => /^[^/]+\/[^/]+\/package\.json$/.test(f));
9519
+ const manifest = manifests.find((f) => {
9520
+ try {
9521
+ return JSON.parse(git4(["show", `${tag}:${f}`]).toString("utf8")).name === name;
9522
+ } catch {
9523
+ return false;
9524
+ }
9525
+ });
9526
+ if (!manifest) return { error: `the tag ${tag} has no package named ${name}` };
9527
+ const dir = path29.posix.dirname(manifest);
9528
+ const entries = git4(["ls-tree", "-r", "-z", tag, "--", `${dir}/`]).toString("utf8").split("\0").filter(Boolean).map((line) => /^\d+ blob ([0-9a-f]+)\t(.*)$/s.exec(line)).filter((m) => m !== null).map((m) => ({ sha: m[1], file: m[2].slice(dir.length + 1) })).filter((e) => !e.file.split("/").some((part) => SKIP.has(part)));
9529
+ const files = /* @__PURE__ */ new Map();
9530
+ if (entries.length) {
9531
+ const out = git4(["cat-file", "--batch"], entries.map((e) => e.sha).join("\n") + "\n");
9532
+ let at = 0;
9533
+ for (const e of entries) {
9534
+ const nl = out.indexOf(10, at);
9535
+ const size = Number(out.subarray(at, nl).toString("utf8").split(" ")[2]);
9536
+ files.set(e.file, Buffer.from(out.subarray(nl + 1, nl + 1 + size)));
9537
+ at = nl + 1 + size + 1;
9538
+ }
9539
+ }
9540
+ return { files };
9541
+ } catch (err) {
9542
+ return { error: `couldn't read ${name} at the tag ${tag}: ${why(err)}` };
9543
+ }
9544
+ },
9545
+ close() {
9546
+ if (clone) rmSync(clone, { recursive: true, force: true });
9547
+ clone = null;
9548
+ }
9549
+ };
9550
+ }
9551
+ function diffHunks(before, after) {
9552
+ if (before === after) return [];
9553
+ const dir = mkdtempSync(path29.join(tmpdir(), "genesis-diff-"));
9554
+ try {
9555
+ writeFileSync(path29.join(dir, "a"), before);
9556
+ writeFileSync(path29.join(dir, "b"), after);
9557
+ let out = "";
9558
+ try {
9559
+ out = execFileSync("git", ["diff", "--no-index", "--no-color", "-U0", "a", "b"], { cwd: dir, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
9560
+ } catch (err) {
9561
+ out = String(err.stdout ?? "");
9562
+ }
9563
+ const hunks = [];
9564
+ let current = null;
9565
+ for (const line of out.split("\n")) {
9566
+ const head = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/.exec(line);
9567
+ if (head) {
9568
+ const start = Number(head[1]);
9569
+ const count = head[2] === void 0 ? 1 : Number(head[2]);
9570
+ current = { at: count === 0 ? `after ${start}` : count === 1 ? `${start}` : `${start}-${start + count - 1}`, start, count, removed: [], added: [] };
9571
+ hunks.push(current);
9572
+ } else if (current && line.startsWith("-") && !line.startsWith("---")) current.removed.push(line.slice(1));
9573
+ else if (current && line.startsWith("+") && !line.startsWith("+++")) current.added.push(line.slice(1));
9574
+ }
9575
+ return hunks;
9576
+ } finally {
9577
+ rmSync(dir, { recursive: true, force: true });
9578
+ }
9579
+ }
9580
+ function shippedBy(upstreamHunks) {
9581
+ return (h) => upstreamHunks.some((u) => u.start === h.start && u.count === h.count && u.added.length === h.added.length && u.added.every((l, i) => l === h.added[i]));
9582
+ }
9583
+ function promotions(root, name) {
9584
+ const file = REGISTER_PATHS.find((p) => existsSync(path29.join(root, p)));
9585
+ if (!file) return [];
9586
+ const text = readFileSync(path29.join(root, file), "utf8");
9587
+ const rows = text.split("\n");
9588
+ return readRegister(text).entries.filter((e) => e.status === "promoted" && e.package === name).map((e) => {
9589
+ const row = rows.find((r) => r.split("|").map((c) => c.trim())[1] === e.id) ?? "";
9590
+ const pr = /https:\/\/github\.com\/marktiderman\/genesis\/pull\/\d+/.exec(row)?.[0];
9591
+ return { id: e.id, paths: localPaths(e.local), ...pr ? { pr } : {} };
9592
+ });
9593
+ }
9594
+ function mergeJson(base, mine, theirs) {
9595
+ if (isObject5(base) && isObject5(mine) && isObject5(theirs)) {
9596
+ const out = {};
9597
+ for (const key2 of /* @__PURE__ */ new Set([...Object.keys(mine), ...Object.keys(theirs)])) {
9598
+ const inMine = key2 in mine;
9599
+ const inBase = key2 in base;
9600
+ if (!(key2 in theirs)) {
9601
+ if (inMine && (!inBase || !same(mine[key2], base[key2]))) out[key2] = mine[key2];
9602
+ continue;
9603
+ }
9604
+ if (!inMine) {
9605
+ if (!inBase) out[key2] = theirs[key2];
9606
+ continue;
9607
+ }
9608
+ out[key2] = inBase ? mergeJson(base[key2], mine[key2], theirs[key2]) : mine[key2];
9609
+ }
9610
+ return out;
9611
+ }
9612
+ return same(mine, base) ? theirs : mine;
9613
+ }
9614
+ function rebasedManifest(text, name, to, released, nextText) {
9615
+ const json = JSON.parse(text);
9616
+ const next = nextText ? JSON.parse(nextText) : {};
9617
+ const n = LOCAL_SUFFIX.exec(typeof json.version === "string" ? json.version : "")?.[1] ?? "1";
9618
+ json.version = `${to}+local.${n}`;
9619
+ if (json.genesis?.overlay) json.genesis.overlay.upstream = `${name}@${to}`;
9620
+ for (const section of ["dependencies", "peerDependencies", "optionalDependencies"]) {
9621
+ const deps = json[section];
9622
+ if (!deps) continue;
9623
+ for (const [dep, spec] of Object.entries(deps)) {
9624
+ if (!spec.startsWith("workspace:") && !next[section]?.[dep]?.startsWith("workspace:")) continue;
9625
+ const v = released(dep);
9626
+ if (v && PLAIN.test(v)) deps[dep] = `^${v}`;
9627
+ }
9628
+ }
9629
+ const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
9630
+ return JSON.stringify(json, null, indent) + (text.endsWith("\n") ? "\n" : "");
9631
+ }
9632
+ function planOverlays(root, wanted, upstream2, manifests = ["package.json"]) {
9633
+ const plans = [];
9634
+ let packages;
9635
+ try {
9636
+ packages = localPackages(root);
9637
+ } catch {
9638
+ return plans;
9639
+ }
9640
+ for (const pkg of packages) {
9641
+ if (!GENESIS_PACKAGE_NAME.test(pkg.name)) continue;
9642
+ let json;
9643
+ try {
9644
+ json = JSON.parse(readFileSync(path29.join(pkg.dir, "package.json"), "utf8"));
9645
+ } catch {
9646
+ continue;
9647
+ }
9648
+ const state = overlayState(pkg.name, json);
9649
+ if (state.kind !== "marked") continue;
9650
+ const from = overlayUpstream(state.marker).version;
9651
+ const to = wanted(pkg.name);
9652
+ if (!to || !PLAIN.test(to) || compareVersions2(to, from) <= 0) continue;
9653
+ const plan = { name: pkg.name, rel: pkg.rel, from, to, hunks: [], conflicts: [], writes: /* @__PURE__ */ new Map(), remove: false, pins: /* @__PURE__ */ new Map() };
9654
+ plans.push(plan);
9655
+ const baseRead = upstream2.files(pkg.name, from);
9656
+ const nextRead = "files" in baseRead ? upstream2.files(pkg.name, to) : baseRead;
9657
+ if (!("files" in baseRead) || !("files" in nextRead)) {
9658
+ plan.skipped = `${"error" in baseRead ? baseRead.error : nextRead.error}; the overlay is left as it is: rebase it by hand`;
9659
+ continue;
9660
+ }
9661
+ const base = baseRead.files;
9662
+ const next = nextRead.files;
9663
+ const mine = walk2(pkg.dir);
9664
+ const promoted = promotions(root, pkg.name);
9665
+ const verdict = (file) => {
9666
+ const appPath3 = `${pkg.rel}/${file}`;
9667
+ const p = promoted.find((e) => e.paths.some((q) => q === appPath3 || q === pkg.rel || appPath3.startsWith(`${q.replace(/\/+$/, "")}/`)));
9668
+ return p ? { verdict: "promoted", entry: p.id, ...p.pr ? { pr: p.pr } : {} } : { verdict: "kept" };
9669
+ };
9670
+ let own = false;
9671
+ for (const file of [.../* @__PURE__ */ new Set([...mine.keys(), ...next.keys()])].sort()) {
9672
+ const m = mine.get(file);
9673
+ const b = base.get(file);
9674
+ const t = next.get(file);
9675
+ const text = [m, b, t].every((x) => x === void 0 || isText(x));
9676
+ let result;
9677
+ if (file === "package.json" && m && t && text) {
9678
+ let merged;
9679
+ try {
9680
+ merged = rebasedManifest(JSON.stringify(mergeJson(JSON.parse(b?.toString("utf8") ?? "{}"), JSON.parse(m.toString("utf8")), JSON.parse(t.toString("utf8"))), null, 2) + "\n", pkg.name, to, wanted, t.toString("utf8"));
9681
+ } catch {
9682
+ plan.conflicts.push(file);
9683
+ continue;
9684
+ }
9685
+ const fields = ownManifestFields(merged, t.toString("utf8"));
9686
+ if (fields.length) {
9687
+ own = true;
9688
+ plan.hunks.push({ file, at: `fields ${fields.join(", ")}`, ...verdict(file) });
9689
+ }
9690
+ if (merged !== m.toString("utf8")) plan.writes.set(file, Buffer.from(merged));
9691
+ continue;
9692
+ }
9693
+ if (m && text && (b === void 0 || !m.equals(b))) {
9694
+ if (b === void 0) {
9695
+ plan.hunks.push({ file, at: "new file", ...t?.equals(m) ? { verdict: "shipped" } : verdict(file) });
9696
+ } else {
9697
+ const isShipped = shippedBy(t ? diffHunks(b.toString("utf8"), t.toString("utf8")) : []);
9698
+ for (const hunk of diffHunks(b.toString("utf8"), m.toString("utf8"))) plan.hunks.push({ file, at: hunk.at, ...isShipped(hunk) ? { verdict: "shipped" } : verdict(file) });
9699
+ }
9700
+ } else if (m && !text && (b === void 0 || !m.equals(b))) {
9701
+ plan.hunks.push({ file, at: b === void 0 ? "new file" : "binary", ...t?.equals(m) ? { verdict: "shipped" } : verdict(file) });
9702
+ }
9703
+ if (m === void 0) {
9704
+ if (b === void 0 && t !== void 0) result = t;
9705
+ } else if (t === void 0) {
9706
+ if (b !== void 0) {
9707
+ if (m.equals(b)) result = null;
9708
+ else plan.conflicts.push(file);
9709
+ }
9710
+ } else if (m.equals(t)) {
9711
+ result = void 0;
9712
+ } else if (!text) {
9713
+ if (b !== void 0 && m.equals(b)) result = t;
9714
+ else plan.conflicts.push(file);
9715
+ } else {
9716
+ const merged = mergeThreeWay(m.toString("utf8"), b?.toString("utf8") ?? "", t.toString("utf8"));
9717
+ if (!merged || !merged.clean) plan.conflicts.push(file);
9718
+ else result = Buffer.from(merged.text);
9719
+ }
9720
+ const after = result === void 0 ? m : result ?? void 0;
9721
+ if (after !== void 0 && !after.equals(t ?? Buffer.alloc(0)) || after !== void 0 && t === void 0) own = true;
9722
+ if (result !== void 0 && !(result && m && result.equals(m))) plan.writes.set(file, result);
9723
+ }
9724
+ if (plan.conflicts.length || own) continue;
9725
+ const references = folderReferences(root, plan);
9726
+ if (references.length) {
9727
+ plan.stays = `nothing of the app's own is left, but ${references.join(", ")} still name ${plan.rel}: drop that, then delete the overlay and pin ${plan.name}@${to}`;
9728
+ continue;
9729
+ }
9730
+ const pins = planPins(root, plan, manifests);
9731
+ if (typeof pins === "string") {
9732
+ plan.stays = pins;
9733
+ continue;
9734
+ }
9735
+ plan.remove = true;
9736
+ plan.pins = pins;
9737
+ plan.writes.clear();
9738
+ }
9739
+ return plans;
9740
+ }
9741
+ function ownManifestFields(mergedText, upstreamText) {
9742
+ const mine = JSON.parse(mergedText);
9743
+ const theirs = JSON.parse(upstreamText);
9744
+ for (const json of [mine, theirs]) {
9745
+ delete json.version;
9746
+ delete json.private;
9747
+ const genesis = json.genesis;
9748
+ if (genesis) {
9749
+ delete genesis.overlay;
9750
+ if (!Object.keys(genesis).length) delete json.genesis;
9751
+ }
9752
+ }
9753
+ for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
9754
+ const ours = mine[section];
9755
+ const up = theirs[section];
9756
+ if (!ours || !up) continue;
9757
+ for (const [dep, spec] of Object.entries(up)) if (typeof spec === "string" && spec.startsWith("workspace:") && typeof ours[dep] === "string") ours[dep] = spec;
9758
+ }
9759
+ const sorted2 = (v) => isObject5(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sorted2(v[k])])) : Array.isArray(v) ? v.map(sorted2) : v;
9760
+ return [.../* @__PURE__ */ new Set([...Object.keys(mine), ...Object.keys(theirs)])].filter((k) => JSON.stringify(sorted2(mine[k])) !== JSON.stringify(sorted2(theirs[k]))).sort();
9761
+ }
9762
+ function folderReferences(root, plan) {
9763
+ const found = [];
9764
+ const candidates = readdirSync(root).filter((f) => /^(pnpm-workspace\.yaml|tsconfig(\..+)?\.json|jsconfig\.json|(vite|vitest|metro)\.config\.[cm]?[jt]s|babel\.config\.[cm]?js|\.babelrc)$/.test(f));
9765
+ const folder = new RegExp(`(^|[^\\w./-])(\\.\\/)?${plan.rel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`);
9766
+ const escapedName = plan.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9767
+ for (const file of candidates.sort()) {
9768
+ let text;
9769
+ try {
9770
+ text = readFileSync(path29.join(root, file), "utf8");
9771
+ } catch {
9772
+ continue;
9773
+ }
9774
+ if (folder.test(text)) found.push(file);
9775
+ else if (file === "pnpm-workspace.yaml" && new RegExp(`['"]?${escapedName}['"]?\\s*:\\s*['"]?(workspace:|link:|file:)`).test(text)) found.push(`${file} (an override of ${plan.name})`);
9776
+ }
9777
+ return found;
9778
+ }
9779
+ function planPins(root, plan, manifests) {
9780
+ const pins = /* @__PURE__ */ new Map();
9781
+ const overlay = path29.resolve(root, plan.rel);
9782
+ for (const file of manifests) {
9783
+ const abs = path29.join(root, file);
9784
+ if (!existsSync(abs)) continue;
9785
+ const text = readFileSync(abs, "utf8");
9786
+ let json;
9787
+ try {
9788
+ json = JSON.parse(text);
9789
+ } catch {
9790
+ return `nothing of the app's own is left, but ${file} isn't valid JSON, so its dependency on ${plan.name} can't be pinned: fix it, then run genesis upgrade again`;
9791
+ }
9792
+ const here = path29.dirname(abs);
9793
+ const local = (spec) => typeof spec === "string" && (spec.startsWith("workspace:") || /^(file|link):/.test(spec) && path29.resolve(here, spec.slice(5)) === overlay);
9794
+ let touched2 = false;
9795
+ for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
9796
+ const deps = json[section];
9797
+ if (deps && local(deps[plan.name])) {
9798
+ deps[plan.name] = plan.to;
9799
+ touched2 = true;
9800
+ }
9801
+ }
9802
+ for (const o of [json.overrides, json.resolutions, json.pnpm?.overrides]) {
9803
+ if (isObject5(o) && local(o[plan.name])) {
9804
+ delete o[plan.name];
9805
+ touched2 = true;
9806
+ }
9807
+ }
9808
+ if (!touched2) continue;
9809
+ const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
9810
+ pins.set(file, JSON.stringify(json, null, indent) + (text.endsWith("\n") ? "\n" : ""));
9811
+ }
9812
+ return pins;
9813
+ }
9814
+ function applyOverlayPlans(root, plans) {
9815
+ const changed = [];
9816
+ for (const plan of plans) {
9817
+ if (plan.skipped || plan.conflicts.length) continue;
9818
+ const dir = path29.join(root, plan.rel);
9819
+ if (plan.remove) {
9820
+ for (const [file, text] of plan.pins) {
9821
+ writeFileSync(path29.join(root, file), text);
9822
+ changed.push(file);
9823
+ }
9824
+ rmSync(dir, { recursive: true, force: true });
9825
+ changed.push(`${plan.rel}/package.json`);
9826
+ continue;
9827
+ }
9828
+ for (const [file, bytes] of plan.writes) {
9829
+ const target = path29.join(dir, file);
9830
+ if (bytes === null) rmSync(target, { force: true });
9831
+ else {
9832
+ mkdirSync(path29.dirname(target), { recursive: true });
9833
+ writeFileSync(target, bytes);
9834
+ }
9835
+ changed.push(`${plan.rel}/${file}`);
9836
+ }
9837
+ }
9838
+ return changed;
9839
+ }
9840
+ function overlayChecklist(plans) {
9841
+ if (!plans.length) return [];
9842
+ const lines = ["", "Overlays (an upgrade PR isn't done until this checklist is):"];
9843
+ for (const plan of plans) {
9844
+ lines.push("", `${plan.name} (${plan.rel}), ${plan.from} \u2192 ${plan.to}:`, "");
9845
+ if (plan.skipped) {
9846
+ lines.push(`- [ ] ${plan.skipped}`);
9847
+ continue;
9848
+ }
9849
+ for (const h of plan.hunks) {
9850
+ const where2 = `\`${h.file}\` ${h.at === "new file" ? "(new file)" : h.at === "binary" ? "(not text)" : h.at.startsWith("fields ") ? `(${h.at})` : `lines ${h.at}`}`;
9851
+ if (h.verdict === "shipped") lines.push(`- [x] ${where2}: already shipped in ${plan.to}; dropped from the overlay`);
9852
+ else if (h.verdict === "promoted") lines.push(h.pr ? `- [x] ${where2}: promoted (${h.entry}, ${h.pr})` : `- [ ] ${where2}: promoted (${h.entry}); link its Genesis PR in docs/genesis-upstream.md`);
9853
+ else lines.push(`- [ ] ${where2}: kept; say why here`);
9854
+ }
9855
+ if (!plan.hunks.length) lines.push("- [x] no changes of the app's own");
9856
+ if (plan.conflicts.length) lines.push(`- [ ] rebase conflicts, nothing written; rebase by hand onto ${plan.to}: ${plan.conflicts.map((f) => `\`${plan.rel}/${f}\``).join(", ")}`);
9857
+ else if (plan.remove) lines.push(`- [x] nothing of the app's own is left: the overlay is deleted and ${plan.name} pinned to ${plan.to} (drop it from localPackages if it is listed by name)`);
9858
+ else if (plan.stays) lines.push(`- [ ] ${plan.stays}`);
9859
+ else lines.push(`- [x] rebased onto ${plan.to}; the marker's upstream is ${plan.name}@${plan.to}`);
9860
+ }
9861
+ return lines;
9862
+ }
9863
+ var GENESIS_REPOSITORY, SKIP, FETCH_TIMEOUT_MS, isObject5, same, LOCAL_SUFFIX;
9864
+ var init_overlays2 = __esm({
9865
+ "src/upgrade/overlays.ts"() {
9866
+ init_owned();
9867
+ init_local();
9868
+ init_overlays();
9869
+ init_upstream();
9870
+ init_bump_core();
9871
+ GENESIS_REPOSITORY = "https://github.com/marktiderman/genesis.git";
9872
+ SKIP = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo", ".git"]);
9873
+ FETCH_TIMEOUT_MS = 12e4;
9874
+ isObject5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
9875
+ same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
9876
+ LOCAL_SUFFIX = /[+-]local\.(0|[1-9]\d*)$/;
9877
+ }
9878
+ });
9037
9879
 
9038
9880
  // src/upgrade/index.ts
9039
9881
  var upgrade_exports = {};
9040
9882
  __export(upgrade_exports, {
9041
9883
  npmLookup: () => npmLookup,
9884
+ pnpmWorkspaceFileFor: () => pnpmWorkspaceFileFor,
9885
+ releaseAgeError: () => releaseAgeError,
9042
9886
  runUpgrade: () => runUpgrade
9043
9887
  });
9044
9888
  function npm(args, cwd) {
@@ -9051,11 +9895,11 @@ function npmLookup(cwd) {
9051
9895
  if (!EXACT_OR_TAG.test(target)) throw new Error(`--version must be an exact version or a dist-tag, not "${target}"`);
9052
9896
  const version = JSON.parse(npm(["view", `${UMBRELLA}@${target}`, "version", "--json"], cwd) || "null");
9053
9897
  if (typeof version !== "string") throw new Error(`${UMBRELLA}@${target} is not one published version`);
9054
- const tmp = mkdtempSync(path28.join(tmpdir(), "genesis-umbrella-"));
9898
+ const tmp = mkdtempSync(path29.join(tmpdir(), "genesis-umbrella-"));
9055
9899
  try {
9056
9900
  const [packed] = JSON.parse(npm(["pack", `${UMBRELLA}@${version}`, "--pack-destination", tmp, "--json"], cwd));
9057
- execFileSync("tar", ["-xzf", path28.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
9058
- const manifest = JSON.parse(readFileSync(path28.join(tmp, "package/dist/versions.json"), "utf8"));
9901
+ execFileSync("tar", ["-xzf", path29.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
9902
+ const manifest = JSON.parse(readFileSync(path29.join(tmp, "package/dist/versions.json"), "utf8"));
9059
9903
  if (manifest.version !== version) throw new Error(`${UMBRELLA}@${version} ships a versions.json for ${manifest.version}`);
9060
9904
  return manifest;
9061
9905
  } finally {
@@ -9075,7 +9919,7 @@ function npmLookup(cwd) {
9075
9919
  }
9076
9920
  };
9077
9921
  }
9078
- function readText(file) {
9922
+ function readText2(file) {
9079
9923
  try {
9080
9924
  return readFileSync(file, "utf8");
9081
9925
  } catch {
@@ -9083,13 +9927,70 @@ function readText(file) {
9083
9927
  }
9084
9928
  }
9085
9929
  function tidyReleaseAgeExcludes(file) {
9086
- const before = readText(file);
9930
+ const before = readText2(file);
9087
9931
  if (before === null) return false;
9088
- const after = normaliseReleaseAgeExcludes(before);
9932
+ const dir = path29.dirname(file);
9933
+ const after = normaliseReleaseAgeExcludes(before, tidyLocked(before, readText2(path29.join(dir, "pnpm-lock.yaml")), readText2(path29.join(dir, ".npmrc"))));
9089
9934
  if (after === before) return false;
9090
9935
  writeFileSync(file, after);
9091
9936
  return true;
9092
9937
  }
9938
+ function gitTopLevel(root) {
9939
+ try {
9940
+ const top = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
9941
+ return top ? realpathSync(top) : null;
9942
+ } catch {
9943
+ return null;
9944
+ }
9945
+ }
9946
+ function pnpmWorkspaceFileFor(root) {
9947
+ const real2 = realpathSync(root);
9948
+ const top = gitTopLevel(real2);
9949
+ const lockDir = findLockfile(real2)?.dir;
9950
+ const fallback = lockDir && (!top || inside2(top, lockDir)) ? lockDir : real2;
9951
+ return pnpmWorkspaceFile(real2, fallback, { exists: existsSync, join: path29.join, dirname: path29.dirname }, top ?? void 0);
9952
+ }
9953
+ function pnpmVersionIn(root) {
9954
+ try {
9955
+ return execFileSync("pnpm", ["--version"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
9956
+ } catch {
9957
+ return null;
9958
+ }
9959
+ }
9960
+ function releaseAgeError(output) {
9961
+ if (!output.includes(NOT_MATURE)) return null;
9962
+ const young = [...new Set([...output.matchAll(/(@marktiderman\/genesis(?:-[a-z0-9-]+)?@\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?) was published/g)].map((m) => m[1]))];
9963
+ return new Error(
9964
+ [
9965
+ `pnpm refused the new Genesis versions (${NOT_MATURE}): they are younger than this app's \`minimumReleaseAge\`, and with \`minimumReleaseAge\` set, pnpm installs nothing younger (strict mode).`,
9966
+ ...young.length ? ["", ...young.map((v) => ` ${v}`)] : [],
9967
+ "",
9968
+ "genesis upgrade doesn't loosen that for you. Either:",
9969
+ "- wait until those versions are old enough, then run genesis upgrade again; or",
9970
+ `- add them to \`minimumReleaseAgeExclude\` in pnpm-workspace.yaml, exact versions, one entry per package ('@marktiderman/genesis-ui@2.26.0 || 2.27.0'), and run genesis upgrade again.`,
9971
+ "",
9972
+ "The package.json files are already bumped; `git checkout` them to start over."
9973
+ ].join("\n")
9974
+ );
9975
+ }
9976
+ function runInstall(root, argv) {
9977
+ const [cmd, ...args] = argv;
9978
+ return new Promise((resolve26, reject) => {
9979
+ const child = spawn(cmd, args, { cwd: root, stdio: ["inherit", "pipe", "pipe"] });
9980
+ let output = "";
9981
+ const keep = (to) => (chunk) => {
9982
+ to.write(chunk);
9983
+ if (output.length < 1e6) output += chunk.toString("utf8");
9984
+ };
9985
+ child.stdout.on("data", keep(process.stdout));
9986
+ child.stderr.on("data", keep(process.stderr));
9987
+ child.on("error", reject);
9988
+ child.on("close", (code, signal) => {
9989
+ if (code === 0) return resolve26();
9990
+ reject(releaseAgeError(output) ?? new Error(`${shellLine(argv)} failed (${signal ?? `exit code ${code}`})`));
9991
+ });
9992
+ });
9993
+ }
9093
9994
  function packageJsons(root) {
9094
9995
  try {
9095
9996
  const out = execFileSync("git", ["ls-files", "-z", "--", ":(glob)**/package.json"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
@@ -9097,7 +9998,7 @@ function packageJsons(root) {
9097
9998
  if (files.length) return files;
9098
9999
  } catch {
9099
10000
  }
9100
- return existsSync(path28.join(root, "package.json")) ? ["package.json"] : [];
10001
+ return existsSync(path29.join(root, "package.json")) ? ["package.json"] : [];
9101
10002
  }
9102
10003
  function sourceText(root, source, substitutions) {
9103
10004
  const { package: pkg, path: rel } = parseSource(source);
@@ -9117,11 +10018,11 @@ function sourceText(root, source, substitutions) {
9117
10018
  }
9118
10019
  }
9119
10020
  async function runUpgrade(options) {
9120
- const root = path28.resolve(options.root);
10021
+ const root = path29.resolve(options.root);
9121
10022
  const log = options.log ?? (() => {
9122
10023
  });
9123
10024
  const lookup = options.lookup ?? npmLookup(root);
9124
- const release = options.manifest ? JSON.parse(readFileSync(path28.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
10025
+ const release = options.manifest ? JSON.parse(readFileSync(path29.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
9125
10026
  const pinned = { [UMBRELLA]: release.version, ...release.packages };
9126
10027
  const wanted = (name) => pinned[name] ?? lookup.latest(name);
9127
10028
  const prBase = options.pr && !options.dryRun ? checkPullRequest(root, release.version) : void 0;
@@ -9139,6 +10040,24 @@ async function runUpgrade(options) {
9139
10040
  }
9140
10041
  const mods = codemodsFor(changes, options.codemods ?? CODEMODS);
9141
10042
  const breaks = uncoveredBreaks(changes, options.codemods ?? CODEMODS);
10043
+ const upstream2 = options.upstream ?? gitUpstream(options.genesisRepo);
10044
+ let overlays;
10045
+ try {
10046
+ overlays = planOverlays(root, wanted, upstream2, packageJsons(root));
10047
+ } finally {
10048
+ upstream2.close?.();
10049
+ }
10050
+ const conflicted = overlays.filter((o) => o.conflicts.length);
10051
+ if (conflicted.length && !options.dryRun) {
10052
+ throw new Error(
10053
+ [
10054
+ `The rebase of ${conflicted.map((o) => `${o.name} onto ${o.to}`).join(", ")} conflicts; nothing was changed. Rebase these by hand (or drop what Genesis now ships), then run genesis upgrade again:`,
10055
+ ...conflicted.flatMap((o) => o.conflicts.map((f) => ` ${o.rel}/${f}`)),
10056
+ ...overlayChecklist(overlays)
10057
+ ].join("\n")
10058
+ );
10059
+ }
10060
+ for (const o of overlays) if (!o.skipped) bumped.delete(`${o.rel}/package.json`);
9142
10061
  const lock = readLock(root);
9143
10062
  checkSubstitutions(lock.substitutions);
9144
10063
  const bases = /* @__PURE__ */ new Map();
@@ -9154,6 +10073,7 @@ async function runUpgrade(options) {
9154
10073
  replaceApp(root, file, text);
9155
10074
  files.add(file);
9156
10075
  }
10076
+ for (const file of applyOverlayPlans(root, overlays)) files.add(file);
9157
10077
  }
9158
10078
  for (const mod of mods) {
9159
10079
  log(`codemod ${mod.id}: ${mod.description}`);
@@ -9163,18 +10083,26 @@ async function runUpgrade(options) {
9163
10083
  }
9164
10084
  const pm = detectPackageManager(root);
9165
10085
  let tidiedExcludes = null;
10086
+ const excludeWarnings = [];
9166
10087
  if (!options.dryRun && options.install !== false && bumped.size) {
9167
- const workspaceFile = pm === "pnpm" ? pnpmWorkspaceFile(path28.resolve(root), findLockfile(root)?.dir ?? root, { exists: existsSync, join: path28.join, dirname: path28.dirname }) : null;
9168
- const workspaceBefore = workspaceFile ? readText(workspaceFile) : null;
10088
+ const workspaceFile = pm === "pnpm" ? pnpmWorkspaceFileFor(root) : null;
10089
+ const relWorkspace = workspaceFile ? path29.relative(realpathSync(root), workspaceFile) : null;
10090
+ const workspaceBefore = workspaceFile ? readText2(workspaceFile) : null;
9169
10091
  const tidy = () => {
9170
10092
  if (!workspaceFile || !tidyReleaseAgeExcludes(workspaceFile)) return;
9171
- tidiedExcludes = path28.relative(root, workspaceFile);
9172
- log(`${tidiedExcludes}: minimumReleaseAgeExclude names Genesis packages by '${GENESIS_PATTERN}', not one entry per version`);
10093
+ tidiedExcludes = relWorkspace;
10094
+ log(`${tidiedExcludes}: minimumReleaseAgeExclude lists each Genesis package's pinned versions in one entry, exact versions the lockfile holds`);
9173
10095
  };
9174
- if (typeof options.install === "function") options.install(root);
9175
- else {
10096
+ if (typeof options.install === "function") {
10097
+ try {
10098
+ options.install(root);
10099
+ } catch (err) {
10100
+ const e = err;
10101
+ throw releaseAgeError([e.message, e.stdout, e.stderr].map((x) => x == null ? "" : String(x)).join("\n")) ?? err;
10102
+ }
10103
+ } else {
9176
10104
  log(`install: ${shellLine(installCommand(pm))}`);
9177
- run(root, installCommand(pm));
10105
+ await runInstall(root, installCommand(pm));
9178
10106
  }
9179
10107
  tidy();
9180
10108
  const dedupe = options.dedupe ?? (typeof options.install === "function" ? false : true);
@@ -9185,13 +10113,35 @@ async function runUpgrade(options) {
9185
10113
  run(root, dedupeArgv);
9186
10114
  }
9187
10115
  if (dedupe) tidy();
9188
- if (workspaceFile && readText(workspaceFile) !== workspaceBefore) files.add(path28.relative(root, workspaceFile));
10116
+ if (relWorkspace && readText2(workspaceFile) !== workspaceBefore) files.add(relWorkspace);
10117
+ const after = workspaceFile ? readText2(workspaceFile) : null;
10118
+ if (after !== null && /^minimumReleaseAgeExclude:/m.test(after)) {
10119
+ for (const p of releaseAgeExcludeProblems(after)) excludeWarnings.push(`${relWorkspace}: ${p}`);
10120
+ const version = (options.pnpmVersion ?? (() => pnpmVersionIn(root)))();
10121
+ if (!pnpmReadsExactExcludes(version)) {
10122
+ excludeWarnings.push(`pnpm ${version} reads minimumReleaseAgeExclude's exact versions ('name@1.0.0 || 1.1.0') as matching nothing; use pnpm 10.19 or later (packageManager in package.json), or the Genesis versions wait out minimumReleaseAge`);
10123
+ }
10124
+ }
9189
10125
  }
9190
10126
  const added = [];
9191
10127
  const newMigrations = [];
9192
- const warnings = [];
10128
+ const warnings = [...excludeWarnings];
9193
10129
  const manifests = [];
10130
+ const catalog = catalogBlocks();
10131
+ const off = appBlocksSwitchedOff(root, catalog, Object.keys(lock.blocks));
10132
+ const switchedOff = [];
10133
+ const offManifests = [];
9194
10134
  for (const [id, entry] of Object.entries(lock.blocks)) {
10135
+ const feature = off.get(id);
10136
+ if (feature) {
10137
+ switchedOff.push(switchedOffNote(id, feature));
10138
+ try {
10139
+ offManifests.push((await findBlock(root, id, { package: entry.package })).manifest);
10140
+ } catch {
10141
+ offManifests.push(...catalog.filter((m) => m.id === id));
10142
+ }
10143
+ continue;
10144
+ }
9195
10145
  try {
9196
10146
  const { manifest } = await findBlock(root, id, { package: entry.package, warnings });
9197
10147
  manifests.push(manifest);
@@ -9205,6 +10155,7 @@ async function runUpgrade(options) {
9205
10155
  }
9206
10156
  const refreshed = [];
9207
10157
  for (const [file, entry] of Object.entries(lock.files)) {
10158
+ if (offManifests.length && blockOfSource(entry.source, offManifests)) continue;
9208
10159
  if (newMigrations.length && file.startsWith(`${TESTS_DIR}/`)) {
9209
10160
  refreshed.push({ path: file, outcome: "deferred", detail: "new package migrations are waiting: run genesis migrate, then genesis upgrade again" });
9210
10161
  continue;
@@ -9263,12 +10214,14 @@ async function runUpgrade(options) {
9263
10214
  }
9264
10215
  if (next.size) lines.push("", "Review and delete these before merging (not committed by --pr):", "", ...[...next].map((n) => `- ${n}`));
9265
10216
  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(", ")}.`);
10217
+ if (switchedOff.length) lines.push("", "Blocks switched off (left out):", "", ...switchedOff.map((s) => `- ${s}`));
9266
10218
  if (newMigrations.length) lines.push("", "New package migrations (run `genesis migrate` to copy them):", "", ...newMigrations.map((m) => `- ${m}`));
9267
- if (tidiedExcludes) lines.push("", `pnpm pinned the new Genesis versions in \`${tidiedExcludes}\`'s \`minimumReleaseAgeExclude\` (they are younger than \`minimumReleaseAge\`); those entries are now \`'${GENESIS_PATTERN}'\`, which \`pnpm install --frozen-lockfile\` honours. Other entries are as they were.`);
10219
+ if (tidiedExcludes) lines.push("", `pnpm pinned the new Genesis versions in \`${tidiedExcludes}\`'s \`minimumReleaseAgeExclude\` (they are younger than \`minimumReleaseAge\`). Each Genesis package now has one entry listing its exact versions in the lockfile (\`'name@1.0.0 || 1.1.0'\`), which \`pnpm install --frozen-lockfile\` honours; versions the lockfile no longer holds were dropped. Never a pattern, so a future Genesis release still waits out \`minimumReleaseAge\`. Other entries are as they were.`);
10220
+ lines.push(...overlayChecklist(overlays));
9268
10221
  if (warnings.length) lines.push("", "Warnings:", "", ...warnings.map((w) => `- ${w}`));
9269
10222
  lines.push("", `\`genesis doctor\` ${doctor === "not run" ? "was not run" : doctor} after the upgrade.`);
9270
10223
  const summary = lines.join("\n");
9271
- const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, newMigrations, doctor, files: [...files].sort(), summary };
10224
+ const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, switchedOff, newMigrations, doctor, files: [...files].sort(), summary, overlays };
9272
10225
  if (options.pr && !options.dryRun && files.size) report.pr = openPullRequest(root, release.version, report, prBase);
9273
10226
  return report;
9274
10227
  }
@@ -9276,7 +10229,7 @@ function checkSubstitutions(substitutions) {
9276
10229
  if (!substitutions || !Object.keys(substitutions).length) return;
9277
10230
  let allowed;
9278
10231
  try {
9279
- const was = starterIdentity(readFileSync(path28.join(starterDir(), "starter.config.ts"), "utf8"));
10232
+ const was = starterIdentity(readFileSync(path29.join(starterDir(), "starter.config.ts"), "utf8"));
9280
10233
  allowed = [was.name, was.slug, was.scheme, was.bundleId];
9281
10234
  } catch {
9282
10235
  allowed = [];
@@ -9309,27 +10262,30 @@ function openPullRequest(root, version, report, base) {
9309
10262
  git4("switch", "-c", branch);
9310
10263
  const top = git4("rev-parse", "--show-toplevel");
9311
10264
  const lockfiles = [];
9312
- for (let dir = path28.resolve(root); ; dir = path28.dirname(dir)) {
9313
- for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path28.join(dir, f))) lockfiles.push(path28.relative(root, path28.join(dir, f)));
9314
- if (lockfiles.length || dir === top || path28.dirname(dir) === dir) break;
10265
+ for (let dir = path29.resolve(root); ; dir = path29.dirname(dir)) {
10266
+ for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path29.join(dir, f))) lockfiles.push(path29.relative(root, path29.join(dir, f)));
10267
+ if (lockfiles.length || dir === top || path29.dirname(dir) === dir) break;
9315
10268
  }
9316
- const paths = [...report.files.filter((f) => existsSync(path28.join(root, f))), ...lockfiles];
10269
+ const paths = [...report.files.filter((f) => existsSync(path29.join(root, f))), ...lockfiles];
9317
10270
  git4("add", "--", ...paths);
10271
+ const overlayDirs = report.overlays.filter((o) => !o.skipped && !o.conflicts.length && (o.remove || [...o.writes.values()].includes(null))).map((o) => o.rel);
10272
+ if (overlayDirs.length) git4("add", "-A", "--", ...overlayDirs);
9318
10273
  git4("commit", "-q", "-m", `chore(deps): upgrade Genesis to ${version}`);
9319
10274
  git4("push", "-u", "origin", branch);
9320
- const body = path28.join(mkdtempSync(path28.join(tmpdir(), "genesis-pr-")), "body.md");
10275
+ const body = path29.join(mkdtempSync(path29.join(tmpdir(), "genesis-pr-")), "body.md");
9321
10276
  writeFileSync(body, `${report.summary}
9322
10277
 
9323
10278
  Opened by \`genesis upgrade --pr\`.
9324
10279
  `);
9325
10280
  return execFileSync("gh", ["pr", "create", "--base", base, "--head", branch, "--title", `chore(deps): upgrade Genesis to ${version}`, "--body-file", body], { cwd: root, encoding: "utf8" }).trim();
9326
10281
  }
9327
- var EXACT_OR_TAG, SUBSTITUTION_VALUE;
10282
+ var EXACT_OR_TAG, inside2, NOT_MATURE, SUBSTITUTION_VALUE;
9328
10283
  var init_upgrade = __esm({
9329
10284
  "src/upgrade/index.ts"() {
9330
10285
  init_add();
9331
10286
  init_agents();
9332
10287
  init_discover();
10288
+ init_starter_features();
9333
10289
  init_files();
9334
10290
  init_init_native();
9335
10291
  init_lock();
@@ -9340,7 +10296,13 @@ var init_upgrade = __esm({
9340
10296
  init_templates();
9341
10297
  init_bump_core();
9342
10298
  init_codemods();
10299
+ init_overlays2();
9343
10300
  EXACT_OR_TAG = /^[0-9A-Za-z][0-9A-Za-z.+-]*$/;
10301
+ inside2 = (dir, file) => {
10302
+ const rel = path29.relative(dir, file);
10303
+ return rel === "" || rel.split(path29.sep)[0] !== ".." && !path29.isAbsolute(rel);
10304
+ };
10305
+ NOT_MATURE = "ERR_PNPM_NO_MATURE_MATCHING_VERSION";
9344
10306
  SUBSTITUTION_VALUE = /^[A-Za-z0-9][A-Za-z0-9 .+-]{0,59}$/;
9345
10307
  }
9346
10308
  });
@@ -9441,9 +10403,9 @@ async function runScaffold(opts, fs2) {
9441
10403
  function joinPath(...parts) {
9442
10404
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
9443
10405
  }
9444
- function dirname(path48) {
9445
- const idx = path48.lastIndexOf("/");
9446
- return idx === -1 ? "." : path48.slice(0, idx);
10406
+ function dirname(path51) {
10407
+ const idx = path51.lastIndexOf("/");
10408
+ return idx === -1 ? "." : path51.slice(0, idx);
9447
10409
  }
9448
10410
  function brandPackageJson(consumer, genesisVersion) {
9449
10411
  return JSON.stringify(
@@ -9668,11 +10630,11 @@ function cliVersion() {
9668
10630
  }
9669
10631
  }
9670
10632
  var program = new Command();
9671
- program.name("genesis").description("Genesis CLI \u2014 scaffolders + workspace tooling").version(cliVersion());
10633
+ program.name("genesis").description("Genesis CLI \u2014 scaffolders + workspace tooling").version(cliVersion()).enablePositionalOptions();
9672
10634
  program.command("init").description("Scaffold a new Genesis consumer (brand package + tailwind + tokens), or with --template native a new Expo app from the Genesis RN starter").argument("<consumer>", "Consumer slug (lowercase, e.g., 'acme')").option("-t, --target <dir>", "Target directory (default: cwd; with --template, ./<consumer>)").option(
9673
10635
  "--genesis-version <v>",
9674
10636
  "Pin @marktiderman/genesis-* version (default: 'workspace:^' for monorepo)"
9675
- ).option("--native", "An Expo app: add NativeWind's preset and scan genesis-ui-native", false).option("--template <name>", "Make a whole app from a template: native (the Genesis RN starter)").option("--display-name <name>", "--template: the app's name on the home screen (default: from the slug)").option("--bundle-id <id>", "--template: iOS bundle id and Android package (default com.example.<slug>)").option("--scheme <scheme>", "--template: the URL scheme (default: the slug)").option(
10637
+ ).option("--native", "An Expo app: add NativeWind's preset and scan genesis-ui-native", false).option("--template <name>", "Make a whole app from a template: native (the Genesis RN starter)").option("--display-name <name>", "--template: the app's name on the home screen (default: from the slug)").option("--bundle-id <id>", "--template: iOS bundle id and Android package (default com.example.<slug>)").option("--scheme <scheme>", "--template: the URL scheme (default: the slug)").option("--without <switches>", "--template: starter.config.ts feature switches to turn off, comma-separated (e.g. chat,support); their blocks are left out").option(
9676
10638
  "--emit-conflicts",
9677
10639
  "Emit `.genesis-next` siblings for files that already exist (so you can diff)",
9678
10640
  false
@@ -9682,17 +10644,19 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
9682
10644
  const { runInitNative: runInitNative2 } = await Promise.resolve().then(() => (init_init_native(), init_native_exports));
9683
10645
  const result2 = await runInitNative2({
9684
10646
  name: consumer,
9685
- target: path28.resolve(opts.target ?? consumer),
10647
+ target: path29.resolve(opts.target ?? consumer),
9686
10648
  ...opts.displayName ? { displayName: opts.displayName } : {},
9687
10649
  ...opts.bundleId ? { bundleId: opts.bundleId } : {},
9688
- ...opts.scheme ? { scheme: opts.scheme } : {}
10650
+ ...opts.scheme ? { scheme: opts.scheme } : {},
10651
+ ...opts.without ? { without: opts.without.split(",").map((s) => s.trim()).filter(Boolean) } : {}
9689
10652
  });
9690
10653
  console.log(`\u2714 Wrote ${result2.files.length} files to ${result2.target}`);
9691
10654
  if (result2.blocks.length) console.log(` blocks: ${result2.blocks.join(", ")}`);
10655
+ if (result2.leftOut.length) console.log(` left out (switched off): ${result2.leftOut.join(", ")}`);
9692
10656
  console.log(` Genesis packages: ${Object.entries(result2.dependencies).map(([n, v]) => `${n}@${v}`).join(", ")}`);
9693
10657
  console.log("");
9694
10658
  console.log("Next steps:");
9695
- [`cd ${path28.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
10659
+ [`cd ${path29.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
9696
10660
  return;
9697
10661
  }
9698
10662
  opts.target ??= process.cwd();
@@ -9777,7 +10741,7 @@ program.command("introspect").description("Write a checked-in contract (resource
9777
10741
  });
9778
10742
  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) => {
9779
10743
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
9780
- const root = path28.resolve(opts.dir);
10744
+ const root = path29.resolve(opts.dir);
9781
10745
  try {
9782
10746
  if (opts.printGenesis) {
9783
10747
  const { config } = doctor.loadConfig(root, opts.config);
@@ -9796,7 +10760,7 @@ program.command("doctor").description("Check this app against the installed Gene
9796
10760
  });
9797
10761
  program.command("catalog").description("Print the Genesis 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) => {
9798
10762
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
9799
- const packages = doctor.discoverPackages(path28.resolve(opts.dir));
10763
+ const packages = doctor.discoverPackages(path29.resolve(opts.dir));
9800
10764
  const rows = doctor.primitivesCatalog(packages);
9801
10765
  const broken = packages.filter((p) => p.error);
9802
10766
  if (opts.json) {
@@ -9811,7 +10775,7 @@ program.command("catalog").description("Print the Genesis catalog: for each need
9811
10775
  program.command("primitives").description("Deprecated name of `genesis catalog` (same output; JSON keeps the `primitives` key until the next major)").option("--json", "Print the catalog as JSON", false).option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
9812
10776
  console.error("! `genesis primitives` is now `genesis catalog`; the old name works until the next major.");
9813
10777
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
9814
- const packages = doctor.discoverPackages(path28.resolve(opts.dir));
10778
+ const packages = doctor.discoverPackages(path29.resolve(opts.dir));
9815
10779
  const rows = doctor.primitivesCatalog(packages);
9816
10780
  const broken = packages.filter((p) => p.error);
9817
10781
  if (opts.json) {
@@ -9824,10 +10788,10 @@ program.command("primitives").description("Deprecated name of `genesis catalog`
9824
10788
  if (broken.length) process.exitCode = 1;
9825
10789
  });
9826
10790
  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("--rules", "Check the repo against the agent rules of engagement a script can check (docs/agents/RULES.md); exit 1 on a break", false).option("--batch <pattern>", "With --rules: the branch pattern staging batches use in workflow filters", "staging/**").option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
9827
- const root = path28.resolve(opts.dir);
10791
+ const root = path29.resolve(opts.dir);
9828
10792
  if (opts.rules && opts.check) return program.error("--rules checks the repo, --check the agent guide: run them one at a time");
9829
10793
  if (opts.rules) {
9830
- if (!existsSync(path28.join(root, "packages")) && !existsSync(path28.join(root, ".github", "workflows"))) {
10794
+ if (!existsSync(path29.join(root, "packages")) && !existsSync(path29.join(root, ".github", "workflows"))) {
9831
10795
  return program.error(`--rules checks a repository: ${root} has no packages/ or .github/workflows/. Run it from the repo root or pass --dir.`);
9832
10796
  }
9833
10797
  const { checkAgentRules: checkAgentRules2 } = await Promise.resolve().then(() => (init_agent_rules(), agent_rules_exports));
@@ -9905,7 +10869,7 @@ featureOptions(
9905
10869
  var upstream = program.command("upstream").description("The app's register of what it needed from Genesis (docs/genesis-upstream.md)");
9906
10870
  upstream.command("check").description("Check docs/genesis-upstream.md: kinds, statuses, local paths, and promoted entries whose local copy is still there").option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
9907
10871
  const { checkUpstream: checkUpstream2 } = await Promise.resolve().then(() => (init_upstream(), upstream_exports));
9908
- const result = checkUpstream2(path28.resolve(opts.dir));
10872
+ const result = checkUpstream2(path29.resolve(opts.dir));
9909
10873
  for (const w of result.warnings) console.warn(`! ${w}`);
9910
10874
  for (const p of result.problems) console.error(`\u2717 ${p}`);
9911
10875
  if (result.problems.length) process.exitCode = 1;
@@ -9913,7 +10877,7 @@ upstream.command("check").description("Check docs/genesis-upstream.md: kinds, st
9913
10877
  });
9914
10878
  upstream.command("export").description("Print the link that files a register entry with Genesis through the gap form (sends nothing)").argument("<id>", "The entry's id").option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (id, opts) => {
9915
10879
  const { checkUpstream: checkUpstream2, exportIssueUrl: exportIssueUrl2 } = await Promise.resolve().then(() => (init_upstream(), upstream_exports));
9916
- const register = checkUpstream2(path28.resolve(opts.dir));
10880
+ const register = checkUpstream2(path29.resolve(opts.dir));
9917
10881
  if (register.missing) return program.error("There is no docs/genesis-upstream.md or genesis-upstream.md here; add the register first (see genesis upstream check).");
9918
10882
  const entry = register.entries.find((e) => e.id === id);
9919
10883
  if (!entry) return program.error(`No register entry "${id}" in ${register.file}.`);
@@ -9926,38 +10890,38 @@ ${exportIssueUrl2(entry)}`);
9926
10890
  var studio = program.command("studio").description("The Genesis Data Studio");
9927
10891
  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) => {
9928
10892
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
9929
- const root = path28.resolve(opts.dir);
9930
- const packageJson = JSON.parse(await fs.readFile(path28.join(root, "package.json"), "utf-8").catch(() => "{}"));
9931
- const existsSync36 = (await import('fs')).existsSync;
10893
+ const root = path29.resolve(opts.dir);
10894
+ const packageJson = JSON.parse(await fs.readFile(path29.join(root, "package.json"), "utf-8").catch(() => "{}"));
10895
+ const existsSync39 = (await import('fs')).existsSync;
9932
10896
  const readSync = (await import('fs')).readFileSync;
9933
- const readdirSync18 = (await import('fs')).readdirSync;
10897
+ const readdirSync19 = (await import('fs')).readdirSync;
9934
10898
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
9935
10899
  throw new Error("--host must be next, tanstack-start or supabase-function.");
9936
10900
  }
9937
10901
  const plan = planStudioInit2(
9938
10902
  {
9939
10903
  packageJson,
9940
- exists: (p) => existsSync36(path28.join(root, p)),
9941
- read: (p) => existsSync36(path28.join(root, p)) ? readSync(path28.join(root, p), "utf-8") : null,
10904
+ exists: (p) => existsSync39(path29.join(root, p)),
10905
+ read: (p) => existsSync39(path29.join(root, p)) ? readSync(path29.join(root, p), "utf-8") : null,
9942
10906
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
9943
10907
  listDeep: (p) => {
9944
10908
  const out = [];
9945
- const walk2 = (rel) => {
9946
- for (const entry of readdirSync18(path28.join(root, rel), { withFileTypes: true })) {
10909
+ const walk3 = (rel) => {
10910
+ for (const entry of readdirSync19(path29.join(root, rel), { withFileTypes: true })) {
9947
10911
  const child = `${rel}/${entry.name}`;
9948
- if (entry.isDirectory()) walk2(child);
10912
+ if (entry.isDirectory()) walk3(child);
9949
10913
  else out.push(child);
9950
10914
  }
9951
10915
  };
9952
10916
  try {
9953
- walk2(p);
10917
+ walk3(p);
9954
10918
  } catch {
9955
10919
  }
9956
10920
  return out;
9957
10921
  },
9958
10922
  list: (p) => {
9959
10923
  try {
9960
- return readdirSync18(path28.join(root, p));
10924
+ return readdirSync19(path29.join(root, p));
9961
10925
  } catch {
9962
10926
  return [];
9963
10927
  }
@@ -9966,8 +10930,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
9966
10930
  { host: opts.host, route: opts.route, loginRole: opts.loginRole }
9967
10931
  );
9968
10932
  for (const file of plan.files) {
9969
- const target = path28.join(root, file.path);
9970
- await fs.mkdir(path28.dirname(target), { recursive: true });
10933
+ const target = path29.join(root, file.path);
10934
+ await fs.mkdir(path29.dirname(target), { recursive: true });
9971
10935
  if (file.edit) {
9972
10936
  await fs.writeFile(target, file.content, "utf-8");
9973
10937
  console.log(`~ ${file.path} (${file.edit})`);
@@ -9978,14 +10942,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
9978
10942
  console.log(`+ ${file.path} (appended)`);
9979
10943
  continue;
9980
10944
  }
9981
- if (existsSync36(target) && !opts.force) {
10945
+ if (existsSync39(target) && !opts.force) {
9982
10946
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
9983
10947
  continue;
9984
10948
  }
9985
10949
  await fs.writeFile(target, file.content, "utf-8");
9986
10950
  console.log(`+ ${file.path}`);
9987
10951
  }
9988
- const pm = existsSync36(path28.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync36(path28.join(root, "yarn.lock")) ? "yarn add" : existsSync36(path28.join(root, "bun.lock")) || existsSync36(path28.join(root, "bun.lockb")) ? "bun add" : "npm install";
10952
+ const pm = existsSync39(path29.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync39(path29.join(root, "yarn.lock")) ? "yarn add" : existsSync39(path29.join(root, "bun.lock")) || existsSync39(path29.join(root, "bun.lockb")) ? "bun add" : "npm install";
9989
10953
  console.log("");
9990
10954
  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:`);
9991
10955
  console.log(` 1. ${pm} ${plan.install.map((p) => /[\s<>|]/.test(p) ? `"${p}"` : p).join(" ")}`);
@@ -10003,7 +10967,7 @@ async function confirm(question) {
10003
10967
  }
10004
10968
  var logger = { info: (m) => console.log(m), warn: (m) => console.warn(`! ${m}`) };
10005
10969
  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) => {
10006
- const root = path28.resolve(opts.dir);
10970
+ const root = path29.resolve(opts.dir);
10007
10971
  if (opts.list || !block) {
10008
10972
  const { allBlocks: allBlocks2 } = await Promise.resolve().then(() => (init_discover(), discover_exports));
10009
10973
  const { readLock: readLock2 } = await Promise.resolve().then(() => (init_lock(), lock_exports));
@@ -10033,13 +10997,14 @@ program.command("migrate").description("Copy new package migrations of the app's
10033
10997
  const { runMigrate: runMigrate2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
10034
10998
  const { formatMigrationRows: formatMigrationRows2 } = await Promise.resolve().then(() => (init_migrations(), migrations_exports));
10035
10999
  const report = await runMigrate2({
10036
- root: path28.resolve(opts.dir),
11000
+ root: path29.resolve(opts.dir),
10037
11001
  ...opts.block ? { blocks: opts.block } : {},
10038
11002
  ...opts.notifications ? { notifications: opts.notifications } : {},
10039
11003
  dryRun: opts.dryRun,
10040
11004
  forward: opts.forward
10041
11005
  });
10042
11006
  for (const w of report.warnings) logger.warn(w);
11007
+ for (const s of report.switchedOff) console.log(`- skipped ${s}`);
10043
11008
  console.log(formatMigrationRows2(report.plan.rows));
10044
11009
  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"})`);
10045
11010
  if (report.notificationTypes) console.log(`+ ${report.notificationTypes} (the notification types, from the registry)`);
@@ -10051,10 +11016,10 @@ program.command("migrate").description("Copy new package migrations of the app's
10051
11016
  process.exitCode = 1;
10052
11017
  }
10053
11018
  });
10054
- 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) => {
11019
+ 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).option("--genesis-repo <url>", "The Genesis git repository whose <package>@<version> tags overlays are rebased from (default: the public one)").action(async (opts) => {
10055
11020
  const { runUpgrade: runUpgrade2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
10056
11021
  const report = await runUpgrade2({
10057
- root: path28.resolve(opts.dir),
11022
+ root: path29.resolve(opts.dir),
10058
11023
  version: opts.version,
10059
11024
  ...opts.manifest ? { manifest: opts.manifest } : {},
10060
11025
  dryRun: opts.dryRun,
@@ -10062,6 +11027,7 @@ program.command("upgrade").description("Move every @marktiderman/genesis* depend
10062
11027
  doctor: opts.doctor,
10063
11028
  keepMine: opts.keepMine,
10064
11029
  pr: opts.pr,
11030
+ ...opts.genesisRepo ? { genesisRepo: opts.genesisRepo } : {},
10065
11031
  log: (m) => console.log(m)
10066
11032
  });
10067
11033
  console.log("");
@@ -10080,7 +11046,7 @@ program.command("codemod [id]").description("Run one of Genesis's codemods by ha
10080
11046
  }
10081
11047
  const mod = codemodById2(id);
10082
11048
  if (!mod) throw new Error(`No codemod "${id}". Run genesis codemod to list them.`);
10083
- const changed = await mod.run({ root: path28.resolve(opts.dir), dryRun: opts.dryRun, log: (m) => console.log(m) });
11049
+ const changed = await mod.run({ root: path29.resolve(opts.dir), dryRun: opts.dryRun, log: (m) => console.log(m) });
10084
11050
  console.log(changed.length ? `${opts.dryRun ? "Would change" : "\u2714 Changed"} ${changed.length} file${changed.length === 1 ? "" : "s"}:
10085
11051
  ${changed.map((f) => ` ${f}`).join("\n")}` : "Nothing to change.");
10086
11052
  });
@@ -10131,7 +11097,7 @@ function redactUrl(location) {
10131
11097
  const url = new URL(location);
10132
11098
  return `${url.origin}${url.pathname}`;
10133
11099
  } catch {
10134
- return path28.basename(location);
11100
+ return path29.basename(location);
10135
11101
  }
10136
11102
  }
10137
11103
  //# sourceMappingURL=cli.js.map