@marktiderman/genesis-cli 1.11.2 → 1.12.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,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync, existsSync, readdirSync, mkdirSync, writeFileSync, mkdtempSync, rmSync, realpathSync, statSync, lstatSync } from 'fs';
3
- import * as path32 from 'path';
3
+ import * as path23 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
- import { createRequire } from 'module';
8
+ import { createRequire, builtinModules } from 'module';
9
9
  import { execFileSync, spawnSync } from 'child_process';
10
10
  import { buildFeatureOutputs, checkFeatureOutputs, summarizeCheck } from '@marktiderman/genesis-features/node';
11
11
  import { findFeatures } from '@marktiderman/genesis-features';
@@ -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 = path32.join(packagesDir, dir, "package.json");
29
+ const file = path23.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;
@@ -45,16 +45,16 @@ function safeRelative(value) {
45
45
  if (segments.some((s) => s === "" || s === "." || s === ".." || s.startsWith("-"))) return null;
46
46
  return value;
47
47
  }
48
- function parseManifest(home, id, raw, version) {
48
+ function parseManifest(home, id, raw, version, options = {}) {
49
49
  const problems = [];
50
50
  const at = `${home} genesis.blocks.${id}`;
51
- if (!GENESIS_PACKAGE.test(home)) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) declare blocks`);
51
+ if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
52
52
  if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
53
53
  if (!isObject(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
54
54
  const pkgOf = (value, where) => {
55
55
  if (value === void 0) return home;
56
- if (typeof value !== "string" || !GENESIS_PACKAGE.test(value)) {
57
- problems.push(`${where}: package must be a Genesis package, not ${JSON.stringify(value)}`);
56
+ if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
57
+ problems.push(`${where}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
58
58
  return home;
59
59
  }
60
60
  return value;
@@ -234,14 +234,14 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
234
234
  }
235
235
  });
236
236
  function inside(parent, child) {
237
- const rel = path32.relative(parent, child);
238
- return rel === "" || !rel.startsWith("..") && !path32.isAbsolute(rel);
237
+ const rel = path23.relative(parent, child);
238
+ return rel === "" || !rel.startsWith("..") && !path23.isAbsolute(rel);
239
239
  }
240
240
  function readPackageFile(packageDir2, rel) {
241
241
  const safe = safeRelative(rel);
242
242
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
243
243
  const root = realpathSync(packageDir2);
244
- const file = path32.join(root, ...safe.split("/"));
244
+ const file = path23.join(root, ...safe.split("/"));
245
245
  if (!existsSync(file)) return null;
246
246
  const real2 = realpathSync(file);
247
247
  if (!inside(root, real2)) throw new Error(`${rel} in ${packageDir2} points outside the package`);
@@ -252,7 +252,7 @@ function readPackageDir(packageDir2, rel, skipped = []) {
252
252
  const safe = safeRelative(rel);
253
253
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
254
254
  const root = realpathSync(packageDir2);
255
- const dir = path32.join(root, ...safe.split("/"));
255
+ const dir = path23.join(root, ...safe.split("/"));
256
256
  if (!existsSync(dir)) return null;
257
257
  const real2 = realpathSync(dir);
258
258
  if (!inside(root, real2) || !statSync(real2).isDirectory()) throw new Error(`${rel} in ${packageDir2} is not a folder inside the package`);
@@ -272,7 +272,7 @@ function appPath(root, rel) {
272
272
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the app`);
273
273
  if (safe.split("/").some((s) => s.toLowerCase() === ".git")) throw new Error(`"${rel}" is inside .git; refused`);
274
274
  const realRoot = realpathSync(root);
275
- const target = path32.join(realRoot, ...safe.split("/"));
275
+ const target = path23.join(realRoot, ...safe.split("/"));
276
276
  const there = (p) => {
277
277
  try {
278
278
  lstatSync(p);
@@ -281,13 +281,13 @@ function appPath(root, rel) {
281
281
  return false;
282
282
  }
283
283
  };
284
- let probe = path32.dirname(target);
285
- while (!there(probe)) probe = path32.dirname(probe);
284
+ let probe = path23.dirname(target);
285
+ while (!there(probe)) probe = path23.dirname(probe);
286
286
  let real2;
287
287
  try {
288
288
  real2 = realpathSync(probe);
289
289
  } catch {
290
- throw new Error(`${rel} goes through a broken symlink (${path32.relative(realRoot, probe)}); refused`);
290
+ throw new Error(`${rel} goes through a broken symlink (${path23.relative(realRoot, probe)}); refused`);
291
291
  }
292
292
  if (!inside(realRoot, real2)) throw new Error(`${rel} is outside the app (a symlinked folder?)`);
293
293
  if (there(target) && lstatSync(target).isSymbolicLink()) throw new Error(`${rel} is a symlink; left alone`);
@@ -299,20 +299,20 @@ function readApp(root, rel) {
299
299
  }
300
300
  function createApp(root, rel, content) {
301
301
  const file = appPath(root, rel);
302
- mkdirSync(path32.dirname(file), { recursive: true });
302
+ mkdirSync(path23.dirname(file), { recursive: true });
303
303
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
304
304
  }
305
305
  function replaceApp(root, rel, content) {
306
306
  const file = appPath(root, rel);
307
- mkdirSync(path32.dirname(file), { recursive: true });
307
+ mkdirSync(path23.dirname(file), { recursive: true });
308
308
  writeFileSync(file, content, "utf8");
309
309
  }
310
310
  function listApp(root, rel, options = {}) {
311
- const dir = path32.join(root, rel);
311
+ const dir = path23.join(root, rel);
312
312
  if (!existsSync(dir)) return [];
313
313
  const out = [];
314
314
  const walk2 = (r) => {
315
- for (const entry of readdirSync(path32.join(root, r), { withFileTypes: true })) {
315
+ for (const entry of readdirSync(path23.join(root, r), { withFileTypes: true })) {
316
316
  const child = `${r}/${entry.name}`;
317
317
  if (entry.isDirectory()) walk2(child);
318
318
  else if (entry.isFile() || options.symlinks && entry.isSymbolicLink()) out.push(child);
@@ -328,6 +328,102 @@ var init_files = __esm({
328
328
  sha256 = (text) => createHash("sha256").update(text).digest("hex");
329
329
  }
330
330
  });
331
+ function validateLocalPackages(raw, source = "genesis.config.json") {
332
+ if (!Array.isArray(raw)) throw new LocalPackagesError(`${source}: ${LOCAL_PACKAGES_KEY} must be a list of folders`);
333
+ return raw.map((entry, i) => {
334
+ const where = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
335
+ if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where} must be a non-empty folder`);
336
+ if (path23.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where} must be relative to the app ("${entry}")`);
337
+ const norm = path23.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
338
+ if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where} must name a package folder, not the app or a parent of it ("${entry}")`);
339
+ const parts = norm.split("/");
340
+ if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
341
+ throw new LocalPackagesError(`${where}: only a final "/*" is supported ("${entry}")`);
342
+ }
343
+ if (parts.includes("node_modules")) throw new LocalPackagesError(`${where} can't point into node_modules ("${entry}")`);
344
+ return norm;
345
+ });
346
+ }
347
+ function localPackageGlobs(root) {
348
+ const file = path23.join(root, "genesis.config.json");
349
+ if (!existsSync(file)) return [];
350
+ let raw;
351
+ try {
352
+ raw = JSON.parse(readFileSync(file, "utf8"));
353
+ } catch (err) {
354
+ throw new LocalPackagesError(`${file} is not valid JSON: ${err.message}`);
355
+ }
356
+ const value = raw && typeof raw === "object" ? raw[LOCAL_PACKAGES_KEY] : void 0;
357
+ return value === void 0 ? [] : validateLocalPackages(value, file);
358
+ }
359
+ function repositoryRoot(appRoot) {
360
+ for (let dir = appRoot; ; ) {
361
+ if (existsSync(path23.join(dir, ".git"))) return dir;
362
+ const parent = path23.dirname(dir);
363
+ if (parent === dir) return appRoot;
364
+ dir = parent;
365
+ }
366
+ }
367
+ function localPackages(root) {
368
+ const appRoot = path23.resolve(root);
369
+ const globs = localPackageGlobs(appRoot);
370
+ const key2 = `${appRoot}
371
+ ${globs.join("\n")}`;
372
+ const hit = cache.get(key2);
373
+ if (hit) return hit;
374
+ const dirs = /* @__PURE__ */ new Set();
375
+ for (const glob of globs) {
376
+ if (glob.endsWith("/*") || glob === "*") {
377
+ const parent = path23.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
378
+ if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
379
+ for (const entry of readdirSync(parent).sort()) {
380
+ if (entry.startsWith(".") || entry === "node_modules") continue;
381
+ dirs.add(path23.join(parent, entry));
382
+ }
383
+ } else {
384
+ dirs.add(path23.join(appRoot, glob));
385
+ }
386
+ }
387
+ const real2 = realpathSync(repositoryRoot(appRoot));
388
+ const out = [];
389
+ const byName = /* @__PURE__ */ new Map();
390
+ for (const dir of [...dirs].sort()) {
391
+ const manifest = path23.join(dir, "package.json");
392
+ if (!existsSync(manifest)) continue;
393
+ if (!inside(real2, realpathSync(dir))) continue;
394
+ let pkg;
395
+ try {
396
+ pkg = JSON.parse(readFileSync(manifest, "utf8"));
397
+ } catch {
398
+ continue;
399
+ }
400
+ if (typeof pkg.name !== "string" || !pkg.name) continue;
401
+ const rel = path23.relative(appRoot, dir).split(path23.sep).join("/");
402
+ const other = byName.get(pkg.name);
403
+ if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
404
+ byName.set(pkg.name, rel);
405
+ out.push({ name: pkg.name, dir, rel, ...typeof pkg.version === "string" ? { version: pkg.version } : {} });
406
+ }
407
+ cache.set(key2, out);
408
+ return out;
409
+ }
410
+ function localPackageNames(root) {
411
+ return new Set(localPackages(root).map((p) => p.name));
412
+ }
413
+ function localPackage(root, name) {
414
+ return localPackages(root).find((p) => p.name === name);
415
+ }
416
+ var LOCAL_PACKAGES_KEY, LocalPackagesError, cache;
417
+ var init_local = __esm({
418
+ "src/blocks/local.ts"() {
419
+ init_files();
420
+ LOCAL_PACKAGES_KEY = "localPackages";
421
+ LocalPackagesError = class extends Error {
422
+ name = "LocalPackagesError";
423
+ };
424
+ cache = /* @__PURE__ */ new Map();
425
+ }
426
+ });
331
427
 
332
428
  // src/blocks/discover.ts
333
429
  var discover_exports = {};
@@ -345,56 +441,58 @@ __export(discover_exports, {
345
441
  workspacePackagesDir: () => workspacePackagesDir
346
442
  });
347
443
  function cliPackageDir() {
348
- let dir = path32.dirname(fileURLToPath(import.meta.url));
444
+ let dir = path23.dirname(fileURLToPath(import.meta.url));
349
445
  for (; ; ) {
350
- const file = path32.join(dir, "package.json");
446
+ const file = path23.join(dir, "package.json");
351
447
  if (existsSync(file) && JSON.parse(readFileSync(file, "utf8")).name === CLI_PACKAGE) return dir;
352
- const parent = path32.dirname(dir);
448
+ const parent = path23.dirname(dir);
353
449
  if (parent === dir) throw new Error("Can't find the genesis-cli package folder.");
354
450
  dir = parent;
355
451
  }
356
452
  }
357
453
  function workspacePackagesDir() {
358
- const dir = path32.resolve(cliPackageDir(), "..");
359
- return existsSync(path32.join(dir, "features", "package.json")) && existsSync(path32.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
454
+ const dir = path23.resolve(cliPackageDir(), "..");
455
+ return existsSync(path23.join(dir, "features", "package.json")) && existsSync(path23.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
360
456
  }
361
457
  function readCatalog() {
362
458
  if (catalogCache) return catalogCache;
363
459
  const workspace = workspacePackagesDir();
364
460
  if (workspace) return catalogCache = buildCatalog(workspace);
365
- const file = path32.join(cliPackageDir(), "dist", "genesis-catalog.json");
461
+ const file = path23.join(cliPackageDir(), "dist", "genesis-catalog.json");
366
462
  catalogCache = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : { packages: {} };
367
463
  return catalogCache;
368
464
  }
369
465
  function installedGenesis(root) {
370
466
  const found = /* @__PURE__ */ new Map();
371
- let dir = path32.resolve(root);
467
+ let dir = path23.resolve(root);
372
468
  for (; ; ) {
373
- const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path32.join(dir, m)));
374
- const scope = path32.join(dir, "node_modules", "@marktiderman");
469
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path23.join(dir, m)));
470
+ const scope = path23.join(dir, "node_modules", "@marktiderman");
375
471
  if (existsSync(scope)) {
376
472
  for (const entry of readdirSync(scope)) {
377
473
  const name = `@marktiderman/${entry}`;
378
474
  if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
379
- if (existsSync(path32.join(scope, entry, "package.json"))) found.set(name, path32.join(scope, entry));
475
+ if (existsSync(path23.join(scope, entry, "package.json"))) found.set(name, path23.join(scope, entry));
380
476
  }
381
477
  }
382
- const parent = path32.dirname(dir);
478
+ const parent = path23.dirname(dir);
383
479
  if (atInstallRoot || parent === dir) return found;
384
480
  dir = parent;
385
481
  }
386
482
  }
387
483
  function packageDir(root, name) {
484
+ const local = localPackage(root, name);
485
+ if (local) return local.dir;
388
486
  const installed = installedGenesis(root).get(name);
389
487
  if (installed) return installed;
390
488
  if (name === CLI_PACKAGE) return cliPackageDir();
391
489
  return null;
392
490
  }
393
491
  function packageVersion(dir) {
394
- return JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8")).version;
492
+ return JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8")).version;
395
493
  }
396
494
  function declarationsOf(dir, warnings) {
397
- const pkg = JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8"));
495
+ const pkg = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
398
496
  const key2 = `${realpathSync(dir)}@${pkg.version ?? ""}`;
399
497
  let cached = declarationCache.get(key2);
400
498
  if (!cached) {
@@ -404,15 +502,15 @@ function declarationsOf(dir, warnings) {
404
502
  return cached;
405
503
  }
406
504
  async function loadDeclarations(dir, warnings) {
407
- const pkg = JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8"));
505
+ const pkg = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
408
506
  const entry = pkg.exports?.["./blocks"];
409
507
  const target = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry["import"] ?? entry["default"] : void 0;
410
508
  if (typeof target !== "string") return {};
411
509
  const rel = safeRelative(target.replace(/^\.\//, ""));
412
- const file = rel && path32.join(dir, ...rel.split("/"));
510
+ const file = rel && path23.join(dir, ...rel.split("/"));
413
511
  if (!file || !inside(dir, file) || !existsSync(file)) return {};
414
512
  try {
415
- const jiti = createJiti(path32.join(dir, "package.json"), { moduleCache: false });
513
+ const jiti = createJiti(path23.join(dir, "package.json"), { moduleCache: false });
416
514
  const mod = await jiti.import(file);
417
515
  const out = {};
418
516
  for (const value of Object.values(mod)) if (isBlockDef(value)) out[value.id] = declarationFields(value);
@@ -422,21 +520,24 @@ async function loadDeclarations(dir, warnings) {
422
520
  return {};
423
521
  }
424
522
  }
425
- async function blocksOfInstalled(dir, warnings = []) {
426
- const pkg = JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8"));
523
+ async function blocksOfInstalled(dir, warnings = [], options = {}) {
524
+ const pkg = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
427
525
  const raw = rawBlocksOf(pkg);
428
526
  const declared = await declarationsOf(dir, warnings);
429
527
  const ids = /* @__PURE__ */ new Set([...Object.keys(raw), ...Object.keys(declared)]);
430
528
  const out = [];
431
529
  for (const id of [...ids].sort()) {
432
530
  const fromJson = raw[id] ?? {};
433
- const manifest = tryParse(() => parseManifest(pkg.name, id, { ...fromJson, ...declared[id] }, pkg.version), warnings);
531
+ const manifest = tryParse(() => parseManifest(pkg.name, id, { ...fromJson, ...declared[id] }, pkg.version, options), warnings);
434
532
  if (manifest) out.push(manifest);
435
533
  }
436
534
  return out;
437
535
  }
438
536
  async function allBlocks(root, warnings = []) {
439
537
  const out = [];
538
+ for (const local of localPackages(root)) {
539
+ for (const manifest of await blocksOfInstalled(local.dir, warnings, { local: true })) out.push({ manifest, from: "local" });
540
+ }
440
541
  const installed = installedGenesis(root);
441
542
  for (const [, dir] of installed) for (const manifest of await blocksOfInstalled(dir, warnings)) out.push({ manifest, from: "installed" });
442
543
  for (const [name, entry] of Object.entries(readCatalog().packages)) {
@@ -471,7 +572,7 @@ async function findBlock(root, id, options = {}) {
471
572
  const all = (await allBlocks(root, options.warnings)).filter((b) => b.manifest.id === id && (!options.package || b.manifest.package === options.package));
472
573
  if (all.length === 0) {
473
574
  const known = [...new Set((await allBlocks(root)).map((b) => b.manifest.id))].sort();
474
- throw new Error(`No Genesis package declares a block "${id}"${options.package ? ` in ${options.package}` : ""}. Known blocks: ${known.join(", ") || "none"}.`);
575
+ throw new Error(`No Genesis or local package declares a block "${id}"${options.package ? ` in ${options.package}` : ""}. Known blocks: ${known.join(", ") || "none"}.`);
475
576
  }
476
577
  if (all.length > 1) throw new Error(`"${id}" is declared by ${all.map((b) => b.manifest.package).join(" and ")}; pass --package to pick one.`);
477
578
  return all[0];
@@ -481,6 +582,7 @@ var init_discover = __esm({
481
582
  "src/blocks/discover.ts"() {
482
583
  init_catalog();
483
584
  init_files();
585
+ init_local();
484
586
  init_manifest();
485
587
  CLI_PACKAGE = "@marktiderman/genesis-cli";
486
588
  INSTALL_ROOT_MARKERS = [".git", "pnpm-lock.yaml", "pnpm-workspace.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"];
@@ -502,7 +604,7 @@ function emptyLock() {
502
604
  return { version: 1, blocks: {}, files: {} };
503
605
  }
504
606
  function readLock(root) {
505
- const file = path32.join(root, LOCK_FILE);
607
+ const file = path23.join(root, LOCK_FILE);
506
608
  if (!existsSync(file)) return emptyLock();
507
609
  const raw = JSON.parse(readFileSync(file, "utf8"));
508
610
  if (raw.version !== 1) throw new Error(`${LOCK_FILE} has version ${String(raw.version)}; this CLI reads version 1.`);
@@ -557,7 +659,7 @@ function migrationHeader(pkg, file, source) {
557
659
  `;
558
660
  }
559
661
  function stemOrNull(file) {
560
- return MIGRATION_FILE.exec(path32.posix.basename(file))?.[2] ?? null;
662
+ return MIGRATION_FILE.exec(path23.posix.basename(file))?.[2] ?? null;
561
663
  }
562
664
  function stemOf(file) {
563
665
  const stem = stemOrNull(file);
@@ -567,7 +669,7 @@ function stemOf(file) {
567
669
  function readAppMigrations(root, dir = MIGRATIONS_DIR) {
568
670
  return listApp(root, dir, { symlinks: true }).filter((p) => p.endsWith(".sql")).map((p) => {
569
671
  const content = readApp(root, p) ?? "";
570
- const name = path32.posix.basename(p);
672
+ const name = path23.posix.basename(p);
571
673
  const m = HEADER.exec(content);
572
674
  if (m) return { path: p, name, content, tracked: { package: m[1], file: m[2], sha256: m[3], body: content.slice(m[0].length) } };
573
675
  const f = FORWARD.exec(content);
@@ -649,7 +751,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
649
751
  detail = copy.tracked ? renamed.trim() : "copied before headers; matches the package";
650
752
  } else if (copy.tracked) {
651
753
  state = "changed-upstream";
652
- detail = `${src.package} now ships a different ${path32.posix.basename(src.file)}; the applied copy is never rewritten`;
754
+ detail = `${src.package} now ships a different ${path23.posix.basename(src.file)}; the applied copy is never rewritten`;
653
755
  } else {
654
756
  state = "differs";
655
757
  detail = "has the package migration's name but other text and no header; treated as the app's own";
@@ -671,7 +773,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
671
773
  row.target = target2;
672
774
  creates.push({ path: target2, content: migrationHeader(src.package, src.file, src.source) + src.source, kind, source: { package: src.package, file: src.file } });
673
775
  if (options.tests !== false && src.test && src.testSource != null) {
674
- const test2 = `${TESTS_DIR}/${path32.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
776
+ const test2 = `${TESTS_DIR}/${path23.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
675
777
  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 } });
676
778
  }
677
779
  return;
@@ -731,25 +833,25 @@ function privacyDataType(type) {
731
833
  }
732
834
  function appPath2(v, where, fail) {
733
835
  if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
734
- if (path32.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
735
- const norm = path32.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
836
+ if (path23.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
837
+ const norm = path23.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
736
838
  if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where} must be a folder inside the app ("${v}")`);
737
839
  return norm;
738
840
  }
739
841
  function loadConfig(root, configPath) {
740
842
  if (configPath) {
741
- const file = path32.resolve(root, configPath);
843
+ const file = path23.resolve(root, configPath);
742
844
  if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
743
845
  const json = readJson(file);
744
- const block = path32.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
745
- return { config: validateConfig(block ?? {}, file), file, dir: path32.dirname(file) };
846
+ const block = path23.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
847
+ return { config: validateConfig(block ?? {}, file), file, dir: path23.dirname(file) };
746
848
  }
747
- const own = path32.join(root, "genesis.config.json");
849
+ const own = path23.join(root, "genesis.config.json");
748
850
  if (existsSync(own)) {
749
851
  const block = readGenesisConfig(root)?.raw.doctor;
750
852
  return { config: validateConfig(block ?? {}, own), file: own, dir: root };
751
853
  }
752
- const pkg = path32.join(root, "package.json");
854
+ const pkg = path23.join(root, "package.json");
753
855
  if (existsSync(pkg)) {
754
856
  const block = readJson(pkg)?.genesis?.doctor;
755
857
  if (block !== void 0) return { config: validateConfig(block, pkg), file: pkg, dir: root };
@@ -764,7 +866,7 @@ function readJson(file) {
764
866
  }
765
867
  }
766
868
  function readGenesisConfig(root) {
767
- const file = path32.join(root, "genesis.config.json");
869
+ const file = path23.join(root, "genesis.config.json");
768
870
  if (!existsSync(file)) return null;
769
871
  const raw = readJson(file);
770
872
  if (!isObject2(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
@@ -1005,16 +1107,18 @@ var init_config = __esm({
1005
1107
  "packs",
1006
1108
  "native",
1007
1109
  "supabase",
1110
+ "packages",
1008
1111
  "routesDir",
1009
1112
  "$schema",
1010
1113
  "$comment"
1011
1114
  ]);
1012
1115
  LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
1013
1116
  PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
1014
- PACKS = /* @__PURE__ */ new Set(["native", "supabase"]);
1117
+ PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
1015
1118
  PACK_KEYS = {
1016
1119
  native: { routerRoot: "path" },
1017
- supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" }
1120
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
1121
+ packages: { base: "string" }
1018
1122
  };
1019
1123
  PRIVACY_KEYS = /* @__PURE__ */ new Set(["blocks", "collects", "tracking"]);
1020
1124
  DATA_USE_KEYS = /* @__PURE__ */ new Set(["type", "purposes", "linked", "tracking"]);
@@ -1023,11 +1127,11 @@ var init_config = __esm({
1023
1127
  }
1024
1128
  });
1025
1129
  function findPackageDir(from, name) {
1026
- let dir = path32.resolve(from);
1130
+ let dir = path23.resolve(from);
1027
1131
  for (; ; ) {
1028
- const candidate = path32.join(dir, "node_modules", name);
1029
- if (existsSync(path32.join(candidate, "package.json"))) return candidate;
1030
- const parent = path32.dirname(dir);
1132
+ const candidate = path23.join(dir, "node_modules", name);
1133
+ if (existsSync(path23.join(candidate, "package.json"))) return candidate;
1134
+ const parent = path23.dirname(dir);
1031
1135
  if (parent === dir) return null;
1032
1136
  dir = parent;
1033
1137
  }
@@ -1079,7 +1183,7 @@ function loadCompanions(root, config, uiPackage) {
1079
1183
  function readPackageExports(root, uiPackage) {
1080
1184
  const uiDir = findPackageDir(root, uiPackage);
1081
1185
  if (!uiDir) return null;
1082
- const uiPkg = JSON.parse(readFileSync(path32.join(uiDir, "package.json"), "utf8"));
1186
+ const uiPkg = JSON.parse(readFileSync(path23.join(uiDir, "package.json"), "utf8"));
1083
1187
  const typeEntries = /* @__PURE__ */ new Set();
1084
1188
  const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
1085
1189
  if (typeof mainTypes === "string") typeEntries.add(mainTypes);
@@ -1091,7 +1195,7 @@ function readPackageExports(root, uiPackage) {
1091
1195
  const reexportedPackages = /* @__PURE__ */ new Set();
1092
1196
  let readAny = false;
1093
1197
  for (const entry of typeEntries) {
1094
- const file = path32.join(uiDir, entry);
1198
+ const file = path23.join(uiDir, entry);
1095
1199
  if (!existsSync(file)) continue;
1096
1200
  readAny = true;
1097
1201
  const dts = readFileSync(file, "utf8");
@@ -1105,11 +1209,11 @@ function readPackageExports(root, uiPackage) {
1105
1209
  }
1106
1210
  const valueDecls = /* @__PURE__ */ new Set();
1107
1211
  const typeDecls = /* @__PURE__ */ new Set();
1108
- const declRoot = typeof mainTypes === "string" ? path32.dirname(path32.join(uiDir, mainTypes)) : uiDir;
1212
+ const declRoot = typeof mainTypes === "string" ? path23.dirname(path23.join(uiDir, mainTypes)) : uiDir;
1109
1213
  const declFiles = walkDts(declRoot);
1110
1214
  for (const pkg of reexportedPackages) {
1111
1215
  const dir = findPackageDir(uiDir, pkg);
1112
- if (dir) walkDts(path32.join(dir, "dist"), declFiles);
1216
+ if (dir) walkDts(path23.join(dir, "dist"), declFiles);
1113
1217
  }
1114
1218
  for (const file of declFiles) {
1115
1219
  const text = readFileSync(file, "utf8");
@@ -1155,7 +1259,7 @@ function walkDts(dir, out = []) {
1155
1259
  if (!existsSync(dir)) return out;
1156
1260
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1157
1261
  if (entry.name === "node_modules") continue;
1158
- const p = path32.join(dir, entry.name);
1262
+ const p = path23.join(dir, entry.name);
1159
1263
  if (entry.isDirectory()) walkDts(p, out);
1160
1264
  else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1161
1265
  }
@@ -1172,27 +1276,27 @@ function resolveThemeFiles(root, config, uiDir) {
1172
1276
  }
1173
1277
  const files = [];
1174
1278
  const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
1175
- const themes = ds && path32.join(ds, "dist", "themes");
1279
+ const themes = ds && path23.join(ds, "dist", "themes");
1176
1280
  if (themes && existsSync(themes)) {
1177
- for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path32.join(themes, name));
1281
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path23.join(themes, name));
1178
1282
  }
1179
1283
  if (files.length === 0) {
1180
1284
  throw new DoctorConfigError(
1181
1285
  `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
1182
1286
  );
1183
1287
  }
1184
- const uiStyles = path32.join(uiDir, "dist", "styles.css");
1288
+ const uiStyles = path23.join(uiDir, "dist", "styles.css");
1185
1289
  if (existsSync(uiStyles)) files.push(uiStyles);
1186
1290
  return files;
1187
1291
  }
1188
1292
  function resolveSpec(root, spec) {
1189
- const local = path32.resolve(root, spec);
1190
- if (spec.startsWith(".") || path32.isAbsolute(spec)) return existsSync(local) ? local : null;
1293
+ const local = path23.resolve(root, spec);
1294
+ if (spec.startsWith(".") || path23.isAbsolute(spec)) return existsSync(local) ? local : null;
1191
1295
  const parts = spec.split("/");
1192
1296
  const nameLength = spec.startsWith("@") ? 2 : 1;
1193
1297
  const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
1194
1298
  if (dir) {
1195
- const file = path32.join(dir, ...parts.slice(nameLength));
1299
+ const file = path23.join(dir, ...parts.slice(nameLength));
1196
1300
  if (existsSync(file) && statSync(file).isFile()) return file;
1197
1301
  }
1198
1302
  return existsSync(local) ? local : null;
@@ -1200,7 +1304,7 @@ function resolveSpec(root, spec) {
1200
1304
  function loadPalette(root) {
1201
1305
  const names = new Set(TAILWIND_PALETTE);
1202
1306
  try {
1203
- const req = createRequire(path32.join(root, "package.json"));
1307
+ const req = createRequire(path23.join(root, "package.json"));
1204
1308
  const colors = req("tailwindcss/colors");
1205
1309
  for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
1206
1310
  if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
@@ -1254,7 +1358,7 @@ var init_genesis = __esm({
1254
1358
  });
1255
1359
  function readReleaseManifest(root) {
1256
1360
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
1257
- const file = dir && path32.join(dir, "dist", "versions.json");
1361
+ const file = dir && path23.join(dir, "dist", "versions.json");
1258
1362
  if (!file || !existsSync(file)) return null;
1259
1363
  return JSON.parse(readFileSync(file, "utf8"));
1260
1364
  }
@@ -1264,7 +1368,7 @@ function checkVersionSkew(ctx) {
1264
1368
  for (const [name, want] of Object.entries(manifest.packages)) {
1265
1369
  const dir = findPackageDir(ctx.root, name);
1266
1370
  if (!dir) continue;
1267
- const have = JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8")).version;
1371
+ const have = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8")).version;
1268
1372
  if (have === want) continue;
1269
1373
  ctx.report({
1270
1374
  rule: "version-skew",
@@ -1283,13 +1387,13 @@ var init_versions = __esm({
1283
1387
  }
1284
1388
  });
1285
1389
  function detectPackageManager(root) {
1286
- let dir = path32.resolve(root);
1390
+ let dir = path23.resolve(root);
1287
1391
  for (; ; ) {
1288
- if (existsSync(path32.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1289
- if (existsSync(path32.join(dir, "bun.lock")) || existsSync(path32.join(dir, "bun.lockb"))) return "bun";
1290
- if (existsSync(path32.join(dir, "yarn.lock"))) return "yarn";
1291
- if (existsSync(path32.join(dir, "package-lock.json"))) return "npm";
1292
- const parent = path32.dirname(dir);
1392
+ if (existsSync(path23.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1393
+ if (existsSync(path23.join(dir, "bun.lock")) || existsSync(path23.join(dir, "bun.lockb"))) return "bun";
1394
+ if (existsSync(path23.join(dir, "yarn.lock"))) return "yarn";
1395
+ if (existsSync(path23.join(dir, "package-lock.json"))) return "npm";
1396
+ const parent = path23.dirname(dir);
1293
1397
  if (parent === dir) return "npm";
1294
1398
  dir = parent;
1295
1399
  }
@@ -1325,10 +1429,10 @@ var init_pm = __esm({
1325
1429
  function walk(dir, exclude = []) {
1326
1430
  const out = [];
1327
1431
  const visit = (rel) => {
1328
- for (const name of readdirSync(path32.join(dir, rel)).sort()) {
1432
+ for (const name of readdirSync(path23.join(dir, rel)).sort()) {
1329
1433
  const child = rel ? `${rel}/${name}` : name;
1330
1434
  if (exclude.some((r) => r.test(child))) continue;
1331
- const stat = statSync(path32.join(dir, child));
1435
+ const stat = statSync(path23.join(dir, child));
1332
1436
  if (stat.isDirectory()) visit(child);
1333
1437
  else if (stat.isFile()) out.push(child);
1334
1438
  }
@@ -1357,17 +1461,17 @@ var init_walk = __esm({
1357
1461
  });
1358
1462
  function starterDir() {
1359
1463
  const workspace = workspacePackagesDir();
1360
- const live = workspace && path32.join(workspace, "..", "apps", "genesis-rn-starter");
1361
- if (live && existsSync(path32.join(live, "package.json"))) return live;
1362
- const packaged = path32.join(cliPackageDir(), "dist", "starter");
1363
- if (existsSync(path32.join(packaged, "package.json"))) return packaged;
1464
+ const live = workspace && path23.join(workspace, "..", "apps", "genesis-rn-starter");
1465
+ if (live && existsSync(path23.join(live, "package.json"))) return live;
1466
+ const packaged = path23.join(cliPackageDir(), "dist", "starter");
1467
+ if (existsSync(path23.join(packaged, "package.json"))) return packaged;
1364
1468
  throw new Error("This genesis-cli has no starter (dist/starter is missing): reinstall @marktiderman/genesis-cli.");
1365
1469
  }
1366
1470
  function templatesDir(cliDir = cliPackageDir()) {
1367
1471
  const workspace = workspacePackagesDir();
1368
- const live = workspace && cliDir === cliPackageDir() ? path32.join(workspace, "..", "templates") : null;
1369
- if (live && existsSync(path32.join(live, "eas"))) return live;
1370
- const packaged = path32.join(cliDir, "dist", "templates");
1472
+ const live = workspace && cliDir === cliPackageDir() ? path23.join(workspace, "..", "templates") : null;
1473
+ if (live && existsSync(path23.join(live, "eas"))) return live;
1474
+ const packaged = path23.join(cliDir, "dist", "templates");
1371
1475
  if (existsSync(packaged)) return packaged;
1372
1476
  throw new Error(`${cliDir} has no templates (dist/templates is missing).`);
1373
1477
  }
@@ -1448,10 +1552,10 @@ function initNative(options) {
1448
1552
  if (!BUNDLE.test(bundleId)) throw new Error(`"${bundleId}" isn't a bundle id like com.example.app.`);
1449
1553
  if (!SCHEME.test(scheme)) throw new Error(`"${scheme}" isn't a URL scheme.`);
1450
1554
  if (/["\\\n]/.test(display)) throw new Error("The display name can't contain quotes, backslashes or new lines.");
1451
- const target = path32.resolve(options.target);
1555
+ const target = path23.resolve(options.target);
1452
1556
  if (existsSync(target) && readdirSync(target).length) throw new Error(`${target} isn't empty; init writes into a new folder and never overwrites.`);
1453
1557
  const source = starterDir();
1454
- const read = (rel) => readFileSync(path32.join(source, rel), "utf8");
1558
+ const read = (rel) => readFileSync(path23.join(source, rel), "utf8");
1455
1559
  const was = starterIdentity(read("starter.config.ts"));
1456
1560
  const substitutions = { [was.bundleId]: bundleId, [was.slug]: slug, [was.scheme]: scheme, [was.name]: display };
1457
1561
  const files = /* @__PURE__ */ new Map();
@@ -1482,14 +1586,14 @@ function initNative(options) {
1482
1586
  files.set("package.json", `${JSON.stringify(pkg, null, 2)}
1483
1587
  `);
1484
1588
  files.set("metro.config.js", METRO);
1485
- const pnpmSettings = [path32.join(source, "pnpm-workspace.yaml"), path32.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
1589
+ const pnpmSettings = [path23.join(source, "pnpm-workspace.yaml"), path23.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
1486
1590
  if (pnpmSettings) files.set("pnpm-workspace.yaml", appPnpmSettings(readFileSync(pnpmSettings, "utf8")));
1487
1591
  files.set("README.md", readme(display, slug));
1488
1592
  const lock = { ...emptyLock(), substitutions };
1489
1593
  const cliVersion2 = pinnedVersion(target, CLI_PACKAGE)?.version;
1490
1594
  const templates = templatesDir();
1491
1595
  for (const rel of walk(templates)) {
1492
- const text = substitute(readFileSync(path32.join(templates, rel), "utf8"), substitutions);
1596
+ const text = substitute(readFileSync(path23.join(templates, rel), "utf8"), substitutions);
1493
1597
  const to = templateTarget(rel, text);
1494
1598
  files.set(to, text);
1495
1599
  lock.files[to] = { source: `${CLI_PACKAGE}:templates/${rel}`, sha256: sha256(text), ...cliVersion2 ? { version: cliVersion2 } : {} };
@@ -1500,13 +1604,13 @@ function initNative(options) {
1500
1604
  const blocks = [];
1501
1605
  for (const block of options.blocks) {
1502
1606
  const stems = block.migrations.map((m) => stemOf(m.file));
1503
- const copies = stems.map((s) => migrations.find((f) => path32.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
1607
+ const copies = stems.map((s) => migrations.find((f) => path23.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
1504
1608
  if (!stems.length || copies.some((c) => !c)) continue;
1505
1609
  blocks.push(block.id);
1506
1610
  lock.blocks[block.id] = { package: block.package, ...block.version ? { version: block.version } : {} };
1507
1611
  block.migrations.forEach((m) => {
1508
1612
  if (m.test) {
1509
- const test2 = `${TESTS_DIR}/${path32.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
1613
+ const test2 = `${TESTS_DIR}/${path23.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
1510
1614
  if (files.has(test2)) lock.files[test2] = { source: `${m.package}:${m.test}`, sha256: sha256(files.get(test2)) };
1511
1615
  }
1512
1616
  });
@@ -1519,8 +1623,8 @@ function initNative(options) {
1519
1623
  }
1520
1624
  mkdirSync(target, { recursive: true });
1521
1625
  for (const [rel, content] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
1522
- const file = path32.join(target, ...rel.split("/"));
1523
- mkdirSync(path32.dirname(file), { recursive: true });
1626
+ const file = path23.join(target, ...rel.split("/"));
1627
+ mkdirSync(path23.dirname(file), { recursive: true });
1524
1628
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
1525
1629
  }
1526
1630
  writeLock(target, lock);
@@ -1874,19 +1978,19 @@ var init_introspect = __esm({
1874
1978
  });
1875
1979
  function buildCommands(root, config) {
1876
1980
  if (config.build) return config.build;
1877
- const pkgFile = path32.join(root, "package.json");
1981
+ const pkgFile = path23.join(root, "package.json");
1878
1982
  const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
1879
1983
  const pm = packageManager(root);
1880
1984
  return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
1881
1985
  }
1882
1986
  function packageManager(root) {
1883
- let dir = path32.resolve(root);
1987
+ let dir = path23.resolve(root);
1884
1988
  for (; ; ) {
1885
- if (existsSync(path32.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1886
- if (existsSync(path32.join(dir, "bun.lock")) || existsSync(path32.join(dir, "bun.lockb"))) return "bun";
1887
- if (existsSync(path32.join(dir, "yarn.lock"))) return "yarn";
1888
- if (existsSync(path32.join(dir, "package-lock.json"))) return "npm";
1889
- const parent = path32.dirname(dir);
1989
+ if (existsSync(path23.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1990
+ if (existsSync(path23.join(dir, "bun.lock")) || existsSync(path23.join(dir, "bun.lockb"))) return "bun";
1991
+ if (existsSync(path23.join(dir, "yarn.lock"))) return "yarn";
1992
+ if (existsSync(path23.join(dir, "package-lock.json"))) return "npm";
1993
+ const parent = path23.dirname(dir);
1890
1994
  if (parent === dir) return "npm";
1891
1995
  dir = parent;
1892
1996
  }
@@ -1943,7 +2047,7 @@ function globToRegExp(glob) {
1943
2047
  }
1944
2048
  function globMatcher(globs) {
1945
2049
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1946
- return (path33) => res.some((re) => re.test(path33));
2050
+ return (path35) => res.some((re) => re.test(path35));
1947
2051
  }
1948
2052
  var init_glob = __esm({
1949
2053
  "src/doctor/glob.ts"() {
@@ -2120,9 +2224,9 @@ function scanFiles(root, config) {
2120
2224
  const files = [];
2121
2225
  const seen = /* @__PURE__ */ new Set();
2122
2226
  const visit = (abs) => {
2123
- const rel = toPosix(path32.relative(root, abs));
2227
+ const rel = toPosix(path23.relative(root, abs));
2124
2228
  if (seen.has(rel) || ignored(rel)) return;
2125
- const ext = path32.extname(abs);
2229
+ const ext = path23.extname(abs);
2126
2230
  if (!extensions.has(ext)) return;
2127
2231
  if (statSync(abs).size > MAX_FILE_BYTES) return;
2128
2232
  seen.add(rel);
@@ -2132,18 +2236,25 @@ function scanFiles(root, config) {
2132
2236
  const walk2 = (dir) => {
2133
2237
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
2134
2238
  if (entry.isDirectory()) {
2135
- if (!SKIP_DIRS.has(entry.name)) walk2(path32.join(dir, entry.name));
2239
+ if (!SKIP_DIRS.has(entry.name)) walk2(path23.join(dir, entry.name));
2136
2240
  } else if (entry.isFile()) {
2137
- visit(path32.join(dir, entry.name));
2241
+ visit(path23.join(dir, entry.name));
2138
2242
  }
2139
2243
  }
2140
2244
  };
2141
2245
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
2142
- const abs = path32.resolve(root, src);
2246
+ const abs = path23.resolve(root, src);
2143
2247
  if (!existsSync(abs)) continue;
2144
2248
  if (statSync(abs).isDirectory()) walk2(abs);
2145
2249
  else visit(abs);
2146
2250
  }
2251
+ let local = [];
2252
+ try {
2253
+ local = localPackages(root);
2254
+ } catch {
2255
+ local = [];
2256
+ }
2257
+ for (const pkg of local) walk2(pkg.dir);
2147
2258
  return files;
2148
2259
  }
2149
2260
  function lineAt(text, index) {
@@ -2154,6 +2265,7 @@ function lineAt(text, index) {
2154
2265
  var DEFAULT_SRC, DEFAULT_NATIVE_SRC, DEFAULT_EXTENSIONS, DEFAULT_IGNORE, SKIP_DIRS, MAX_FILE_BYTES, toPosix;
2155
2266
  var init_scan = __esm({
2156
2267
  "src/doctor/scan.ts"() {
2268
+ init_local();
2157
2269
  init_color_literals();
2158
2270
  init_glob();
2159
2271
  DEFAULT_SRC = ["src"];
@@ -2170,7 +2282,7 @@ var init_scan = __esm({
2170
2282
  ];
2171
2283
  SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
2172
2284
  MAX_FILE_BYTES = 2 * 1024 * 1024;
2173
- toPosix = (p) => p.split(path32.sep).join("/");
2285
+ toPosix = (p) => p.split(path23.sep).join("/");
2174
2286
  }
2175
2287
  });
2176
2288
  function parseRulesMarkdown(markdown) {
@@ -2236,7 +2348,7 @@ function loadPatternRules(root, patterns, rulesDoc) {
2236
2348
  const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
2237
2349
  let all = compiled;
2238
2350
  if (rulesDoc) {
2239
- const file = path32.resolve(root, rulesDoc);
2351
+ const file = path23.resolve(root, rulesDoc);
2240
2352
  if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
2241
2353
  const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
2242
2354
  const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
@@ -2302,14 +2414,14 @@ async function loadPlugins(specs, configDir) {
2302
2414
  }
2303
2415
  function resolvePlugin(id, configDir) {
2304
2416
  try {
2305
- if (id.startsWith(".") || path32.isAbsolute(id)) return resolveFrom(path32.resolve(configDir, id), configDir);
2417
+ if (id.startsWith(".") || path23.isAbsolute(id)) return resolveFrom(path23.resolve(configDir, id), configDir);
2306
2418
  return resolveFrom(id, configDir);
2307
2419
  } catch {
2308
2420
  throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
2309
2421
  }
2310
2422
  }
2311
2423
  function resolveFrom(id, from) {
2312
- return createRequire(path32.join(from, "noop.js")).resolve(id);
2424
+ return createRequire(path23.join(from, "noop.js")).resolve(id);
2313
2425
  }
2314
2426
  var init_plugins = __esm({
2315
2427
  "src/doctor/plugins.ts"() {
@@ -2327,7 +2439,7 @@ function importSpecifiers(file) {
2327
2439
  }
2328
2440
  function checkProjectLayout(ctx) {
2329
2441
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
2330
- if (existsSync(path32.join(ctx.root, dir))) {
2442
+ if (existsSync(path23.join(ctx.root, dir))) {
2331
2443
  ctx.report({
2332
2444
  rule: "local-primitives",
2333
2445
  file: dir,
@@ -2337,7 +2449,7 @@ function checkProjectLayout(ctx) {
2337
2449
  }
2338
2450
  }
2339
2451
  for (const file of STARTER_LEFTOVERS) {
2340
- if (existsSync(path32.join(ctx.root, file))) {
2452
+ if (existsSync(path23.join(ctx.root, file))) {
2341
2453
  ctx.report({
2342
2454
  rule: "starter-leftover",
2343
2455
  level: "warn",
@@ -2424,7 +2536,7 @@ function checkTokens(ctx) {
2424
2536
  }
2425
2537
  for (const pattern of ctx.config.tokenFiles ?? []) {
2426
2538
  if (/[*?]/.test(pattern)) continue;
2427
- const abs = path32.join(ctx.root, pattern);
2539
+ const abs = path23.join(ctx.root, pattern);
2428
2540
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
2429
2541
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
2430
2542
  }
@@ -2504,7 +2616,18 @@ var init_rules = __esm({
2504
2616
  "migration-definer-search-path",
2505
2617
  "migration-edited",
2506
2618
  "migration-testing-kit",
2507
- "migration-view-rls"
2619
+ "migration-view-rls",
2620
+ // packages pack
2621
+ "package-app-import",
2622
+ "package-undeclared-dependency",
2623
+ "package-migration-test",
2624
+ "package-migration-number",
2625
+ "package-migration-edited",
2626
+ "package-unregistered",
2627
+ "package-unversioned-change",
2628
+ "package-export-missing",
2629
+ "package-block-invalid",
2630
+ "package-untagged-tests"
2508
2631
  ];
2509
2632
  DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
2510
2633
  STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2592,10 +2715,10 @@ function localImports(root, file) {
2592
2715
  const out = [];
2593
2716
  for (const m of file.code.matchAll(/\bfrom\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g)) {
2594
2717
  const spec = m[1];
2595
- const bases = spec.startsWith(".") ? [path32.resolve(path32.dirname(file.absolutePath), spec)] : [path32.join(root, spec.slice(2)), path32.join(root, "src", spec.slice(2))];
2718
+ const bases = spec.startsWith(".") ? [path23.resolve(path23.dirname(file.absolutePath), spec)] : [path23.join(root, spec.slice(2)), path23.join(root, "src", spec.slice(2))];
2596
2719
  for (const base of bases) {
2597
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path32.join(base, `index${e}`))].find(
2598
- (p) => SCRIPT_EXTS2.has(path32.extname(p)) && existsSync(p)
2720
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path23.join(base, `index${e}`))].find(
2721
+ (p) => SCRIPT_EXTS2.has(path23.extname(p)) && existsSync(p)
2599
2722
  );
2600
2723
  if (hit) {
2601
2724
  out.push(hit);
@@ -2758,7 +2881,7 @@ function checkCustomHeaders(ctx, pkg) {
2758
2881
  if (!JSX_EXTS3.has(file.ext)) continue;
2759
2882
  const code = file.code;
2760
2883
  const hidden = HIDES_HEADER.exec(code);
2761
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path32.posix.dirname(file.path), file.path);
2884
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path23.posix.dirname(file.path), file.path);
2762
2885
  const own = hidden ? ownHeader(code, pkg) : null;
2763
2886
  if (hidden && own) {
2764
2887
  reported.add(file.path);
@@ -2786,7 +2909,7 @@ function checkCustomHeaders(ctx, pkg) {
2786
2909
  }
2787
2910
  for (const file of ctx.files) {
2788
2911
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
2789
- const layout = hidingLayouts.get(path32.posix.dirname(file.path));
2912
+ const layout = hidingLayouts.get(path23.posix.dirname(file.path));
2790
2913
  const own = layout ? ownHeader(file.code, pkg) : null;
2791
2914
  if (!layout || !own) continue;
2792
2915
  ctx.report({
@@ -2807,13 +2930,13 @@ function isLoadingOnlyRoute(code) {
2807
2930
  }
2808
2931
  function routerRoot(ctx) {
2809
2932
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
2810
- return existsSync(path32.join(ctx.root, "src", "app")) ? "src/app" : "app";
2933
+ return existsSync(path23.join(ctx.root, "src", "app")) ? "src/app" : "app";
2811
2934
  }
2812
2935
  function checkScreenLayouts(ctx, pkg) {
2813
2936
  const layouts = nativeLayouts(pkg);
2814
2937
  if (layouts.length === 0) return;
2815
2938
  const rootDir = routerRoot(ctx);
2816
- if (!existsSync(path32.join(ctx.root, rootDir))) {
2939
+ if (!existsSync(path23.join(ctx.root, rootDir))) {
2817
2940
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
2818
2941
  return;
2819
2942
  }
@@ -2850,7 +2973,7 @@ function checkScreenLayouts(ctx, pkg) {
2850
2973
  function readExpoConfigs(root) {
2851
2974
  const out = [];
2852
2975
  for (const name of EXPO_CONFIGS) {
2853
- const abs = path32.join(root, name);
2976
+ const abs = path23.join(root, name);
2854
2977
  if (!existsSync(abs)) continue;
2855
2978
  const text = readFileSync(abs, "utf8");
2856
2979
  let json = null;
@@ -2884,13 +3007,13 @@ function pluginOptions(json, module) {
2884
3007
  return null;
2885
3008
  }
2886
3009
  function dependencies(root) {
2887
- const file = path32.join(root, "package.json");
3010
+ const file = path23.join(root, "package.json");
2888
3011
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
2889
3012
  const pkg = JSON.parse(readFileSync(file, "utf8"));
2890
3013
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
2891
3014
  }
2892
3015
  function runtimeDependencies(root) {
2893
- const file = path32.join(root, "package.json");
3016
+ const file = path23.join(root, "package.json");
2894
3017
  if (!existsSync(file)) return {};
2895
3018
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
2896
3019
  }
@@ -3009,1134 +3132,1418 @@ var init_native = __esm({
3009
3132
  GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\b(?:require|import)\s*\(\s*["']@marktiderman\/genesis-cli[^"']*["']\s*\)/g;
3010
3133
  }
3011
3134
  });
3012
- function sqlStatements(text) {
3013
- const out = [];
3014
- let buf = "";
3015
- let bodies = [];
3016
- let line = 1;
3017
- let start = 0;
3018
- const flush = () => {
3019
- const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
3020
- if (sql) out.push({ sql, line: start, bodies });
3021
- buf = "";
3022
- bodies = [];
3023
- start = 0;
3024
- };
3025
- const put = (s) => {
3026
- if (!start && /\S/.test(s)) start = line;
3027
- buf += s;
3028
- };
3029
- let i = 0;
3030
- while (i < text.length) {
3031
- const ch = text[i];
3032
- const two = text.slice(i, i + 2);
3033
- if (ch === "\n") {
3034
- buf += " ";
3035
- line++;
3036
- i++;
3037
- } else if (two === "--") {
3038
- while (i < text.length && text[i] !== "\n") i++;
3039
- } else if (two === "/*") {
3040
- let depth = 0;
3041
- while (i < text.length) {
3042
- if (text.startsWith("/*", i)) {
3043
- depth++;
3044
- i += 2;
3045
- } else if (text.startsWith("*/", i)) {
3046
- depth--;
3047
- i += 2;
3048
- if (depth === 0) break;
3049
- } else {
3050
- if (text[i] === "\n") line++;
3051
- i++;
3052
- }
3053
- }
3054
- buf += " ";
3055
- } else if (ch === "'") {
3056
- const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
3057
- put("'");
3058
- i++;
3059
- while (i < text.length) {
3060
- if (escapes && text[i] === "\\") i += 2;
3061
- else if (text[i] === "'" && text[i + 1] === "'") i += 2;
3062
- else if (text[i] === "'") break;
3063
- else {
3064
- if (text[i] === "\n") line++;
3065
- i++;
3066
- }
3067
- }
3068
- put("'");
3069
- i++;
3070
- } else if (ch === '"') {
3071
- i++;
3072
- while (i < text.length && text[i] !== '"') put(text[i++]);
3073
- i++;
3074
- } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
3075
- const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
3076
- const end = text.indexOf(tag, i + tag.length);
3077
- const stop = end === -1 ? text.length : end + tag.length;
3078
- bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
3079
- for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
3080
- put(`${tag} ${tag}`);
3081
- i = stop;
3082
- } else if (ch === ";") {
3083
- flush();
3084
- i++;
3085
- } else {
3086
- put(ch);
3087
- i++;
3088
- }
3089
- }
3090
- flush();
3091
- return out;
3135
+
3136
+ // src/doctor/semver.ts
3137
+ function parseVersion(v) {
3138
+ const m = VERSION.exec(v.trim());
3139
+ return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
3092
3140
  }
3093
- function qualify(name) {
3094
- const n = name.trim().toLowerCase();
3095
- return n.includes(".") ? n : `public.${n}`;
3141
+ function compareVersions(a, b) {
3142
+ for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
3143
+ if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
3144
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
3145
+ const x = a.pre[i];
3146
+ const y = b.pre[i];
3147
+ if (x === void 0) return -1;
3148
+ if (y === void 0) return 1;
3149
+ if (x === y) continue;
3150
+ const nx = /^\d+$/.test(x);
3151
+ const ny = /^\d+$/.test(y);
3152
+ if (nx && ny) return +x < +y ? -1 : 1;
3153
+ if (nx !== ny) return nx ? -1 : 1;
3154
+ return x < y ? -1 : 1;
3155
+ }
3156
+ return 0;
3096
3157
  }
3097
- function parenthesized(sql, open) {
3098
- let depth = 0;
3099
- for (let k = open; k < sql.length; k++) {
3100
- if (sql[k] === "(") depth++;
3101
- else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
3158
+ function partial(s) {
3159
+ const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
3160
+ if (!m) return null;
3161
+ const nums = [];
3162
+ let wild = false;
3163
+ for (const part of [m[1], m[2], m[3]]) {
3164
+ if (wild || part === void 0 || /^[xX*]$/.test(part)) {
3165
+ wild = true;
3166
+ nums.push(null);
3167
+ } else nums.push(+part);
3102
3168
  }
3103
- return { inner: sql.slice(open + 1), end: sql.length };
3169
+ return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
3104
3170
  }
3105
- function stripParens(s) {
3106
- let out = "";
3107
- let depth = 0;
3108
- for (const c of s) {
3109
- if (c === "(") depth++;
3110
- else if (c === ")") depth = Math.max(0, depth - 1);
3111
- else if (depth === 0) out += c;
3171
+ function comparators(token) {
3172
+ const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
3173
+ if (!m) return null;
3174
+ const op = m[1] ?? "";
3175
+ const p = partial(m[2]);
3176
+ if (!p) return null;
3177
+ const [major, mi, pa] = p.nums;
3178
+ if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
3179
+ const M = major;
3180
+ const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
3181
+ 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"]);
3182
+ const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
3183
+ const out = switchOp();
3184
+ if (p.pre.length) {
3185
+ for (const c of out) if (c.v === lo) c.pre = true;
3112
3186
  }
3113
3187
  return out;
3114
- }
3115
- function splitTop(s) {
3116
- const parts = [];
3117
- let depth = 0;
3118
- let cur = "";
3119
- for (const c of s) {
3120
- if (c === "(") depth++;
3121
- if (c === ")") depth--;
3122
- if (c === "," && depth === 0) {
3123
- parts.push(cur);
3124
- cur = "";
3125
- } else cur += c;
3188
+ function switchOp() {
3189
+ switch (op) {
3190
+ case "^": {
3191
+ const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
3192
+ return [
3193
+ { op: ">=", v: lo },
3194
+ { op: "<", v: bound }
3195
+ ];
3196
+ }
3197
+ case "~":
3198
+ case "~>":
3199
+ return [
3200
+ { op: ">=", v: lo },
3201
+ { op: "<", v: mi === null ? next("major") : next("minor") }
3202
+ ];
3203
+ case ">":
3204
+ return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
3205
+ case ">=":
3206
+ return [{ op: ">=", v: lo }];
3207
+ case "<":
3208
+ return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
3209
+ case "<=":
3210
+ return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
3211
+ default:
3212
+ return upper ? [
3213
+ { op: ">=", v: lo },
3214
+ { op: "<", v: upper }
3215
+ ] : [{ op: "=", v: lo }];
3216
+ }
3126
3217
  }
3127
- if (cur.trim()) parts.push(cur);
3128
- return parts.map((p) => p.trim()).filter(Boolean);
3129
3218
  }
3130
- function argTypes(args) {
3131
- const types = [];
3132
- for (const raw of splitTop(args)) {
3133
- let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
3134
- const mode = tokens[0];
3135
- if (mode === "out") continue;
3136
- if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
3137
- const joined = tokens.join(" ");
3138
- const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
3139
- types.push(TYPE_ALIASES[type] ?? type);
3219
+ function test(c, v) {
3220
+ const d = compareVersions(v, c.v);
3221
+ return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
3222
+ }
3223
+ function parseRange(range) {
3224
+ const alts = [];
3225
+ for (const raw of range.trim().split("||")) {
3226
+ const alt = raw.trim();
3227
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
3228
+ if (hyphen) {
3229
+ const from = comparators(`>=${hyphen[1]}`);
3230
+ const to = comparators(`<=${hyphen[2]}`);
3231
+ if (!from || !to) return null;
3232
+ alts.push([...from, ...to]);
3233
+ continue;
3234
+ }
3235
+ const set = [];
3236
+ for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
3237
+ const cs = comparators(token);
3238
+ if (!cs) return null;
3239
+ set.push(...cs);
3240
+ }
3241
+ alts.push(set);
3140
3242
  }
3141
- return types;
3243
+ return alts;
3142
3244
  }
3143
- function git(root, args) {
3144
- const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3145
- return r.status === 0 ? r.stdout : null;
3245
+ function satisfies(version, range) {
3246
+ const v = parseVersion(version);
3247
+ const alts = parseRange(range);
3248
+ if (!v || !alts) return null;
3249
+ return alts.some(
3250
+ (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))
3251
+ );
3146
3252
  }
3147
- function gitView(root, dir, base) {
3148
- if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
3149
- if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
3150
- return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
3151
- }
3152
- const mergeBase = git(root, ["merge-base", "HEAD", base])?.trim();
3153
- if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
3154
- const diff = git(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
3155
- const untracked = git(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
3156
- if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
3157
- const sql = (p) => p !== void 0 && p.endsWith(".sql");
3158
- const touched = new Set(untracked.split("\n").filter(sql));
3159
- const edited = [];
3160
- for (const row of diff.split("\n").filter(Boolean)) {
3161
- const [status, a, b] = row.split(" ");
3162
- if (status.startsWith("R")) {
3163
- if (sql(b)) touched.add(b);
3164
- if (sql(a)) edited.push({ file: a, status: "renamed" });
3165
- continue;
3166
- }
3167
- if (!sql(a)) continue;
3168
- if (status.startsWith("A")) touched.add(a);
3169
- else if (status.startsWith("M") || status.startsWith("T")) {
3170
- touched.add(a);
3171
- edited.push({ file: a, status: "modified" });
3172
- } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
3253
+ var VERSION, ver;
3254
+ var init_semver = __esm({
3255
+ "src/doctor/semver.ts"() {
3256
+ VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
3257
+ ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
3173
3258
  }
3174
- return { touched, edited };
3175
- }
3176
- function checkSupabasePack(ctx) {
3177
- const settings2 = ctx.config.supabase ?? {};
3178
- const dir = settings2.migrations ?? DEFAULT_MIGRATIONS;
3179
- const abs = path32.join(ctx.root, dir);
3180
- if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
3181
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path32.join(abs, n), "utf8")) }));
3182
- const exposed = new Set((settings2.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
3183
- const base = settings2.base ?? DEFAULT_BASE;
3184
- const view = gitView(ctx.root, dir, base);
3185
- if ("reason" in view) {
3186
- if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
3187
- } else {
3188
- for (const e of view.edited) {
3189
- ctx.report({
3190
- rule: "migration-edited",
3191
- file: e.file,
3192
- subject: e.file,
3193
- message: `${e.status === "modified" ? "edits" : e.status === "deleted" ? "deletes" : "renames"} a migration that already exists on ${base}, so it has been applied; put the change in a new migration instead`
3194
- });
3259
+ });
3260
+ function stripForImports(code) {
3261
+ const out = [];
3262
+ const blank = (ch) => ch === "\n" ? "\n" : " ";
3263
+ const n = code.length;
3264
+ const templates = [];
3265
+ let depth = 0;
3266
+ let i = 0;
3267
+ let sure = true;
3268
+ const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
3269
+ const before = () => out.slice(-24).join("");
3270
+ const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
3271
+ const startsExpression = (b) => {
3272
+ const t = b.replace(/\s+$/, "");
3273
+ if (!t) return true;
3274
+ if (KEYWORD.test(b)) return true;
3275
+ return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
3276
+ };
3277
+ const exprStart = () => startsExpression(before());
3278
+ const taggedTemplate = () => {
3279
+ const b = out.slice(-48).join("");
3280
+ const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
3281
+ return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
3282
+ };
3283
+ const templateBody = () => {
3284
+ while (i < n) {
3285
+ const ch = code[i];
3286
+ if (ch === "\\") {
3287
+ out.push(" ", blank(code[i + 1] ?? ""));
3288
+ i += 2;
3289
+ } else if (ch === "`") {
3290
+ out.push("`");
3291
+ i++;
3292
+ return;
3293
+ } else if (ch === "$" && code[i + 1] === "{") {
3294
+ out.push("${");
3295
+ i += 2;
3296
+ templates.push(depth);
3297
+ depth++;
3298
+ return;
3299
+ } else {
3300
+ out.push(blank(ch));
3301
+ i++;
3302
+ }
3195
3303
  }
3196
- }
3197
- const since = settings2.since;
3198
- const afterSince = (file) => since === void 0 || path32.posix.basename(file) >= since;
3199
- if ("reason" in view && since === void 0) {
3200
- ctx.report({
3201
- rule: "migration-grants",
3202
- level: "warn",
3203
- file: dir,
3204
- message: `skipped: can't tell new migrations from applied ones (${view.reason}); fetch the base ref (CI: fetch-depth 0) or set doctor.supabase.since`
3205
- });
3206
- } else {
3207
- const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
3208
- checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
3209
- }
3210
- checkRls(ctx, migrations, exposed);
3211
- checkViewInvoker(ctx, migrations, exposed);
3212
- checkDefinerSearchPath(ctx, migrations);
3213
- checkTestingKit(ctx, migrations);
3214
- }
3215
- function checkTestingKit(ctx, migrations) {
3216
- for (const { file, statements } of migrations) {
3217
- const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
3218
- if (!hit) continue;
3219
- ctx.report({
3220
- rule: "migration-testing-kit",
3221
- file,
3222
- line: hit.line,
3223
- subject: "genesis_testing",
3224
- message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
3225
- });
3226
- }
3227
- }
3228
- function granteesOf(s) {
3229
- return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
3230
- }
3231
- function checkGrants(ctx, migrations, exposed) {
3232
- const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
3233
- const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
3234
- const blanket = (roles) => {
3235
- const o = open(roles);
3236
- if (o.length) return { level: "error", who: o.join(" and ") };
3237
- if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
3238
- return null;
3304
+ sure = false;
3239
3305
  };
3240
- for (const { file, statements } of migrations) {
3241
- for (const { sql, line } of statements) {
3242
- const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
3243
- if (all) {
3244
- const hit = blanket(granteesOf(all[1]));
3245
- if (hit) {
3246
- ctx.report({ rule: "migration-grants", level: hit.level, file, line, subject: "on all functions", message: `grants every function in a schema to ${hit.who}, which re-grants functions an earlier migration revoked; ${fix}` });
3247
- }
3248
- continue;
3306
+ while (i < n && sure) {
3307
+ const ch = code[i];
3308
+ const next = code[i + 1];
3309
+ if (ch === "/" && next === "/") {
3310
+ while (i < n && code[i] !== "\n") {
3311
+ out.push(" ");
3312
+ i++;
3249
3313
  }
3250
- const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
3251
- if (defaults) {
3252
- const hit = blanket(granteesOf(defaults[1]));
3253
- if (hit) {
3254
- ctx.report({ rule: "migration-grants", level: hit.level, file, line, subject: "alter default privileges", message: `grants default privileges on functions to ${hit.who}, so every future function is callable by them; ${fix}` });
3255
- }
3256
- continue;
3314
+ } else if (ch === "/" && next === "*") {
3315
+ out.push(" ");
3316
+ i += 2;
3317
+ while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
3318
+ out.push(blank(code[i]));
3319
+ i++;
3257
3320
  }
3258
- const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
3259
- if (fn) {
3260
- const roles = open(granteesOf(fn[2]));
3261
- if (!roles.length) continue;
3262
- for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
3263
- if (exposed.has(schemaOf(name))) continue;
3264
- ctx.report({
3265
- rule: "migration-grants",
3266
- file,
3267
- line,
3268
- subject: name,
3269
- message: `grants ${name} to ${roles.join(" and ")}; a function outside the exposed schemas is never callable by anon or public (grant it to authenticated, or expose a wrapper)`
3270
- });
3271
- }
3272
- continue;
3321
+ if (i < n) {
3322
+ out.push(" ");
3323
+ i += 2;
3273
3324
  }
3274
- const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
3275
- if (schema) {
3276
- const roles = open(granteesOf(schema[2]));
3277
- if (!roles.length) continue;
3278
- for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
3279
- if (exposed.has(s)) continue;
3280
- ctx.report({
3281
- rule: "migration-grants",
3282
- file,
3283
- line,
3284
- subject: `schema ${s}`,
3285
- message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
3286
- });
3325
+ } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
3326
+ const afterBrace = /[}>]\s*$/.test(before());
3327
+ const start = i;
3328
+ const mark = out.length;
3329
+ out.push("/");
3330
+ i++;
3331
+ let inClass = false;
3332
+ for (; ; ) {
3333
+ const c = code[i];
3334
+ if (c === void 0 || c === "\n") {
3335
+ if (afterBrace) {
3336
+ out.length = mark;
3337
+ out.push("/");
3338
+ i = start + 1;
3339
+ } else sure = false;
3340
+ break;
3287
3341
  }
3342
+ if (c === "\\") {
3343
+ out.push(" ", blank(code[i + 1] ?? ""));
3344
+ i += 2;
3345
+ continue;
3346
+ }
3347
+ i++;
3348
+ if (c === "[") inClass = true;
3349
+ else if (c === "]") inClass = false;
3350
+ else if (c === "/" && !inClass) {
3351
+ if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
3352
+ out.length = mark;
3353
+ out.push("/");
3354
+ i = start + 1;
3355
+ break;
3356
+ }
3357
+ out.push("/");
3358
+ break;
3359
+ }
3360
+ out.push(" ");
3288
3361
  }
3289
- }
3290
- }
3291
- }
3292
- function checkRls(ctx, migrations, exposed) {
3293
- const tables = /* @__PURE__ */ new Map();
3294
- const name = String.raw`([\w$.]+)`;
3295
- const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
3296
- for (const { file, statements } of migrations) {
3297
- for (const { sql, line, bodies } of statements) {
3298
- if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
3299
- const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
3300
- if (create) {
3301
- if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
3302
- continue;
3303
- }
3304
- const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
3305
- const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
3306
- if (rename || move) {
3307
- const from = qualify((rename ?? move)[1]);
3308
- const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
3309
- const state = tables.get(from);
3310
- if (state) {
3311
- tables.delete(from);
3312
- tables.set(to, state);
3362
+ if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
3363
+ } else if ((ch === '"' || ch === "'") && exprStart()) {
3364
+ const keep = isSpecifier();
3365
+ out.push(ch);
3366
+ i++;
3367
+ while (i < n && code[i] !== ch && code[i] !== "\n") {
3368
+ if (code[i] === "\\") {
3369
+ out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
3370
+ i += 2;
3371
+ } else {
3372
+ out.push(keep ? code[i] : blank(code[i]));
3373
+ i++;
3313
3374
  }
3314
- continue;
3315
3375
  }
3316
- const alter = new RegExp(target).exec(sql);
3317
- if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
3318
- const t = qualify(alter[1]);
3319
- if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
3320
- else {
3321
- const state = tables.get(t);
3322
- if (state) state.rls = true;
3323
- }
3324
- continue;
3376
+ if (code[i] !== ch) sure = false;
3377
+ else {
3378
+ out.push(code[i]);
3379
+ i++;
3325
3380
  }
3326
- const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3327
- if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
3381
+ } else if (ch === "`" && (exprStart() || taggedTemplate())) {
3382
+ out.push("`");
3383
+ i++;
3384
+ templateBody();
3385
+ } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
3386
+ templates.pop();
3387
+ depth--;
3388
+ out.push("}");
3389
+ i++;
3390
+ templateBody();
3391
+ } else {
3392
+ if (ch === "{") depth++;
3393
+ else if (ch === "}") depth--;
3394
+ out.push(ch);
3395
+ i++;
3328
3396
  }
3329
3397
  }
3330
- for (const [t, at] of tables) {
3331
- if (at.rls || !exposed.has(schemaOf(t))) continue;
3332
- ctx.report({
3333
- rule: "migration-rls",
3334
- file: at.file,
3335
- line: at.line,
3336
- subject: t,
3337
- message: at.disabled ? `disables row level security on ${t}, and no later migration turns it back on; anyone with the API key can read and write it` : `creates ${t} without enabling row level security in any migration; add "alter table ${t} enable row level security;" and its policies`
3338
- });
3398
+ return sure && templates.length === 0 ? out.join("") : null;
3399
+ }
3400
+ function bindings(clause) {
3401
+ const out = [];
3402
+ const named = /\{([^}]*)\}/.exec(clause);
3403
+ for (const part of named?.[1].split(",") ?? []) {
3404
+ const p = part.trim();
3405
+ if (!p || p.startsWith("type ")) continue;
3406
+ out.push(p.split(/\s+as\s+/).pop().trim());
3339
3407
  }
3408
+ const rest = clause.replace(/\{[^}]*\}/, "");
3409
+ const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
3410
+ if (ns) out.push(ns[1]);
3411
+ const def = /^\s*([\w$]+)/.exec(rest);
3412
+ if (def && def[1] !== "as") out.push(def[1]);
3413
+ return out;
3340
3414
  }
3341
- function checkViewInvoker(ctx, migrations, exposed) {
3342
- const views = /* @__PURE__ */ new Map();
3343
- const name = String.raw`([\w$.]+)`;
3344
- const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
3345
- for (const { file, statements } of migrations) {
3346
- for (const { sql, line } of statements) {
3347
- const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
3348
- if (create) {
3349
- if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
3350
- const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
3351
- views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
3352
- continue;
3415
+ function readJsonc(file) {
3416
+ try {
3417
+ const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
3418
+ return JSON.parse(text);
3419
+ } catch {
3420
+ return null;
3421
+ }
3422
+ }
3423
+ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3424
+ if (seen.has(file) || seen.size > 10) return {};
3425
+ seen.add(file);
3426
+ const json = readJsonc(file);
3427
+ if (!json) return {};
3428
+ const dir = path23.dirname(file);
3429
+ let merged = {};
3430
+ const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3431
+ for (const ext of parents) {
3432
+ if (typeof ext !== "string") continue;
3433
+ let target = null;
3434
+ if (ext.startsWith(".") || path23.isAbsolute(ext)) {
3435
+ const abs = path23.resolve(dir, ext);
3436
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3437
+ } else {
3438
+ const parts = ext.split("/");
3439
+ const nameLength = ext.startsWith("@") ? 2 : 1;
3440
+ const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3441
+ if (pkgDir) {
3442
+ const sub = parts.slice(nameLength).join("/");
3443
+ const abs = path23.join(pkgDir, sub || "tsconfig.json");
3444
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3353
3445
  }
3354
- const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
3355
- if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
3356
- const state = views.get(qualify(alter[1]));
3357
- if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
3358
- continue;
3446
+ }
3447
+ if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
3448
+ }
3449
+ const opts = json.compilerOptions ?? {};
3450
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path23.resolve(dir, opts.baseUrl);
3451
+ if (opts.paths && typeof opts.paths === "object") {
3452
+ merged.paths = opts.paths;
3453
+ merged.pathsDir = dir;
3454
+ }
3455
+ return merged;
3456
+ }
3457
+ function aliases(root) {
3458
+ const table = [];
3459
+ let baseUrl = null;
3460
+ for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3461
+ const file = path23.join(root, name);
3462
+ if (!existsSync(file)) continue;
3463
+ const config = readTsconfig(root, file);
3464
+ baseUrl ??= config.baseUrl ?? null;
3465
+ const base = config.baseUrl ?? config.pathsDir ?? root;
3466
+ for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3467
+ if (!Array.isArray(targets)) continue;
3468
+ const exact = !pattern.endsWith("*");
3469
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path23.join(base, String(t).replace(/\*$/, ""))) });
3470
+ }
3471
+ }
3472
+ const pkg = readJsonc(path23.join(root, "package.json"));
3473
+ for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3474
+ if (typeof target !== "string") continue;
3475
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path23.join(root, target.replace(/\*.*$/, ""))] });
3476
+ }
3477
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path23.join(root, "src") + path23.sep, root + path23.sep] });
3478
+ return { table, baseUrl };
3479
+ }
3480
+ function resolveFile(base) {
3481
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path23.join(base, `index${e}`))];
3482
+ if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3483
+ for (const p of tries) {
3484
+ if (SCRIPT_EXTS2.has(path23.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3485
+ }
3486
+ return null;
3487
+ }
3488
+ function trailFor(ctx) {
3489
+ let t = trails.get(ctx.files);
3490
+ if (!t) trails.set(ctx.files, t = createTrail(ctx));
3491
+ return t;
3492
+ }
3493
+ function createTrail(ctx) {
3494
+ const { table, baseUrl } = aliases(ctx.root);
3495
+ let declared = null;
3496
+ try {
3497
+ const pkg = JSON.parse(readFileSync(path23.join(ctx.root, "package.json"), "utf8"));
3498
+ declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
3499
+ } catch {
3500
+ declared = null;
3501
+ }
3502
+ const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
3503
+ const read = (abs) => byPath.get(abs) ?? readSource(abs);
3504
+ const importsCache = /* @__PURE__ */ new Map();
3505
+ const importsOf = (file) => {
3506
+ const hit = importsCache.get(file.absolutePath);
3507
+ if (hit) return hit;
3508
+ const files = [];
3509
+ let lost = false;
3510
+ const code = stripped(file);
3511
+ if (code === null) {
3512
+ const out2 = { files: [], lost: true };
3513
+ importsCache.set(file.absolutePath, out2);
3514
+ return out2;
3515
+ }
3516
+ const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
3517
+ for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3518
+ for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
3519
+ for (const m of code.matchAll(/\bexport\s*\{([^}]*)\}\s*;/g)) for (const n of m[1].split(",")) used.add(n.trim().split(/\s+as\s+/)[0]);
3520
+ const specs = [];
3521
+ for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
3522
+ for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
3523
+ for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
3524
+ for (const spec of specs) {
3525
+ if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
3526
+ let resolved = null;
3527
+ if (spec.startsWith(".")) {
3528
+ resolved = resolveFile(path23.resolve(path23.dirname(file.absolutePath), spec));
3529
+ if (!resolved) lost = true;
3530
+ } else {
3531
+ const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
3532
+ if (alias) {
3533
+ for (const t of alias.targets) {
3534
+ resolved = resolveFile(alias.exact ? t : path23.join(t, spec.slice(alias.prefix.length)));
3535
+ if (resolved) break;
3536
+ }
3537
+ }
3538
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path23.join(baseUrl, spec));
3539
+ if (!resolved) {
3540
+ const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
3541
+ if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
3542
+ }
3359
3543
  }
3360
- const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
3361
- if (rename) {
3362
- const from = qualify(rename[1]);
3363
- const state = views.get(from);
3364
- if (state) {
3365
- views.delete(from);
3366
- views.set(`${schemaOf(from)}.${rename[2]}`, state);
3544
+ if (resolved && !files.includes(resolved)) files.push(resolved);
3545
+ }
3546
+ const out = { files, lost };
3547
+ importsCache.set(file.absolutePath, out);
3548
+ return out;
3549
+ };
3550
+ const strippedCache = /* @__PURE__ */ new Map();
3551
+ const stripped = (file) => {
3552
+ if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
3553
+ return strippedCache.get(file.absolutePath);
3554
+ };
3555
+ const memo = /* @__PURE__ */ new WeakMap();
3556
+ const reach = (file, test2, depth, seen) => {
3557
+ let cache2 = memo.get(test2);
3558
+ if (!cache2) memo.set(test2, cache2 = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
3559
+ const k = `${file.absolutePath}\0${depth}`;
3560
+ const free = cache2.free.get(k);
3561
+ if (free) return [free, /* @__PURE__ */ new Set()];
3562
+ const reusable = cache2.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
3563
+ if (reusable) return [reusable.result, new Set(reusable.cut)];
3564
+ let result;
3565
+ const cut = /* @__PURE__ */ new Set();
3566
+ const code = stripped(file);
3567
+ if (code === null) result = "unknown";
3568
+ else if (test2(code)) result = "yes";
3569
+ else {
3570
+ const { files, lost } = importsOf(file);
3571
+ let unknown = lost && depth > 0;
3572
+ result = "no";
3573
+ if (depth > 0) {
3574
+ seen.add(file.absolutePath);
3575
+ for (const abs of files) {
3576
+ if (seen.has(abs)) {
3577
+ cut.add(abs);
3578
+ continue;
3579
+ }
3580
+ const target = read(abs);
3581
+ if (!target) {
3582
+ unknown = true;
3583
+ continue;
3584
+ }
3585
+ const [r, c] = reach(target, test2, depth - 1, seen);
3586
+ for (const m of c) cut.add(m);
3587
+ if (r === "yes") {
3588
+ result = "yes";
3589
+ break;
3590
+ }
3591
+ if (r === "unknown") unknown = true;
3367
3592
  }
3368
- continue;
3593
+ seen.delete(file.absolutePath);
3594
+ cut.delete(file.absolutePath);
3369
3595
  }
3370
- const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3371
- if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
3596
+ if (result === "no" && unknown) result = "unknown";
3372
3597
  }
3598
+ if (result === "yes" || cut.size === 0) {
3599
+ cache2.free.set(k, result);
3600
+ return [result, /* @__PURE__ */ new Set()];
3601
+ }
3602
+ const entries = cache2.cut.get(k) ?? [];
3603
+ entries.push({ cut: [...cut], result });
3604
+ cache2.cut.set(k, entries);
3605
+ return [result, cut];
3606
+ };
3607
+ return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
3608
+ }
3609
+ var TRAIL_DEPTH, RESOLVE_EXTS2, IMPORT_FROM, EXPORT_FROM, DYNAMIC, trails;
3610
+ var init_trail = __esm({
3611
+ "src/doctor/trail.ts"() {
3612
+ init_genesis();
3613
+ init_source();
3614
+ TRAIL_DEPTH = 6;
3615
+ RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
3616
+ IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
3617
+ EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
3618
+ DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
3619
+ trails = /* @__PURE__ */ new WeakMap();
3373
3620
  }
3374
- for (const [v, at] of views) {
3375
- if (at.invoker || !exposed.has(schemaOf(v))) continue;
3376
- ctx.report({
3377
- rule: "migration-view-rls",
3378
- file: at.file,
3379
- line: at.line,
3380
- subject: v,
3381
- message: `${v} runs as its owner, so it reads past row level security; create it "with (security_invoker = true)" or add "alter view ${v} set (security_invoker = true);"`
3382
- });
3621
+ });
3622
+ function sourceFiles(dir, rel = "") {
3623
+ const out = [];
3624
+ for (const entry of readdirSync(path23.join(dir, rel)).sort()) {
3625
+ if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
3626
+ const child = rel ? `${rel}/${entry}` : entry;
3627
+ const stat = lstatSync(path23.join(dir, child));
3628
+ if (stat.isSymbolicLink()) continue;
3629
+ if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
3630
+ else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3383
3631
  }
3632
+ return out;
3384
3633
  }
3385
- function checkDefinerSearchPath(ctx, migrations) {
3386
- const fns = /* @__PURE__ */ new Map();
3387
- const keysFor = (sql, nameEnd, fnName) => {
3388
- const rest = sql.slice(nameEnd).trimStart();
3389
- if (rest.startsWith("(")) {
3390
- const { inner } = parenthesized(rest, 0);
3391
- return [`${fnName}(${argTypes(inner).join(",")})`];
3634
+ function packageName2(specifier) {
3635
+ const parts = specifier.split("/");
3636
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3637
+ }
3638
+ function git(root, args) {
3639
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3640
+ return r.status === 0 ? r.stdout : null;
3641
+ }
3642
+ function matchPattern(pattern, spec) {
3643
+ const star = pattern.indexOf("*");
3644
+ if (star < 0) return pattern === spec ? "" : null;
3645
+ const head = pattern.slice(0, star);
3646
+ const tail = pattern.slice(star + 1);
3647
+ return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3648
+ }
3649
+ function tsconfigPaths(dir) {
3650
+ const file = path23.join(dir, "tsconfig.json");
3651
+ if (!existsSync(file)) return [];
3652
+ try {
3653
+ const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
3654
+ const options = JSON.parse(text).compilerOptions ?? {};
3655
+ const base = path23.resolve(dir, options.baseUrl ?? ".");
3656
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path23.resolve(base, t)) }));
3657
+ } catch {
3658
+ return [];
3659
+ }
3660
+ }
3661
+ function checkImports2(ctx, pkg, json) {
3662
+ const aliases2 = tsconfigPaths(pkg.dir);
3663
+ const subpathImports = Object.keys(json.imports ?? {});
3664
+ const viaAlias = (spec) => {
3665
+ if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
3666
+ for (const { pattern, targets } of aliases2) {
3667
+ const hit = matchPattern(pattern, spec);
3668
+ if (hit === null) continue;
3669
+ return targets.some((t) => {
3670
+ const rel = path23.relative(pkg.dir, t.replace("*", hit));
3671
+ return !rel.startsWith("..") && !path23.isAbsolute(rel);
3672
+ });
3392
3673
  }
3393
- return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
3674
+ return null;
3394
3675
  };
3395
- for (const { file, statements } of migrations) {
3396
- for (const { sql, line } of statements) {
3397
- const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
3398
- if (create) {
3399
- const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
3400
- fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
3401
- continue;
3402
- }
3403
- const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
3404
- if (alter) {
3405
- const fnName = qualify(alter[1]);
3406
- const keys = keysFor(sql, alter[0].length, fnName);
3407
- const rename = / rename to ([\w$]+)$/.exec(sql);
3408
- const move = / set schema ([\w$]+)$/.exec(sql);
3409
- for (const key2 of keys) {
3410
- const state = fns.get(key2);
3411
- if (rename || move) {
3412
- if (!state) continue;
3413
- fns.delete(key2);
3414
- const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
3415
- fns.set(newName + key2.slice(fnName.length), state);
3416
- continue;
3676
+ const declared = /* @__PURE__ */ new Set([
3677
+ json.name,
3678
+ ...Object.keys(json.dependencies ?? {}),
3679
+ ...Object.keys(json.peerDependencies ?? {}),
3680
+ ...Object.keys(json.devDependencies ?? {}),
3681
+ ...Object.keys(json.optionalDependencies ?? {})
3682
+ ]);
3683
+ for (const file of sourceFiles(pkg.dir)) {
3684
+ const code = stripForImports(readFileSync(path23.join(pkg.dir, file), "utf8"));
3685
+ if (code === null) continue;
3686
+ const at = `${pkg.rel}/${file}`;
3687
+ const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
3688
+ let offset = 0;
3689
+ code.split("\n").forEach((text, i) => {
3690
+ const lineStart = offset;
3691
+ offset += text.length + 1;
3692
+ for (const m of text.matchAll(IMPORT)) {
3693
+ const spec = m[1];
3694
+ const line = i + 1;
3695
+ const at0 = lineStart + m.index;
3696
+ if (typeOnly.some(([a, b]) => at0 >= a && at0 < b)) continue;
3697
+ const alias = viaAlias(spec);
3698
+ if (alias === true) continue;
3699
+ if (alias === false) {
3700
+ ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} imports ${spec}, an alias that points outside the package` });
3701
+ continue;
3702
+ }
3703
+ if (spec.startsWith("#")) continue;
3704
+ if (spec.startsWith("@/") || spec.startsWith("~/")) {
3705
+ ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} imports the app's own code (${spec}); a package may only use its own files and its declared dependencies` });
3706
+ continue;
3707
+ }
3708
+ if (spec.startsWith(".")) {
3709
+ const target = path23.resolve(pkg.dir, path23.dirname(file), spec);
3710
+ const rel = path23.relative(pkg.dir, target);
3711
+ if (rel.startsWith("..") || path23.isAbsolute(rel)) {
3712
+ 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` });
3417
3713
  }
3418
- const next = state ?? { definer: false, searchPath: false, file, line };
3419
- if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
3420
- if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
3421
- if (/\bset search_path\b/.test(sql)) next.searchPath = true;
3422
- if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
3423
- fns.set(key2, next);
3714
+ continue;
3424
3715
  }
3425
- continue;
3426
- }
3427
- const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3428
- if (drop) {
3429
- for (const part of splitTop(drop[1])) {
3430
- const m = /^([\w$.]+)\s*/.exec(part);
3431
- if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
3716
+ if (BUILTINS.has(spec) || spec.startsWith("node:") || spec.startsWith("virtual:") || /^[a-z]+:/.test(spec)) continue;
3717
+ const name = packageName2(spec);
3718
+ if (!declared.has(name)) {
3719
+ ctx.report({ rule: "package-undeclared-dependency", file: at, line, subject: name, message: `${pkg.name} imports ${name}, which its package.json doesn't list; add it to dependencies or peerDependencies` });
3432
3720
  }
3433
3721
  }
3722
+ });
3723
+ }
3724
+ }
3725
+ function checkMigrations(ctx, pkg, json) {
3726
+ const declaredFiles = /* @__PURE__ */ new Set();
3727
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
3728
+ const migrations = raw.migrations ?? [];
3729
+ for (const m of migrations) {
3730
+ if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
3731
+ if (typeof m.file === "string" && typeof m.test !== "string") {
3732
+ ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.file, message: `${pkg.name} block ${id}: ${m.file} has no pgTAP test; declare one as "test" beside it` });
3733
+ } else if (typeof m.test === "string" && !existsSync(path23.join(pkg.dir, m.test))) {
3734
+ ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.test, message: `${pkg.name} block ${id}: its test ${m.test} doesn't exist` });
3735
+ }
3434
3736
  }
3435
3737
  }
3436
- for (const [key2, at] of fns) {
3437
- if (!at.definer || at.searchPath) continue;
3438
- ctx.report({
3439
- rule: "migration-definer-search-path",
3440
- file: at.file,
3441
- line: at.line,
3442
- subject: key2,
3443
- message: `${key2} is security definer without "set search_path"; add set search_path = '' and schema-qualify the names in its body, so a caller's objects can't stand in for yours`
3444
- });
3738
+ const dir = path23.join(pkg.dir, "migrations");
3739
+ if (!existsSync(dir)) return;
3740
+ const seen = /* @__PURE__ */ new Map();
3741
+ for (const name of readdirSync(dir).sort()) {
3742
+ const m = MIGRATION_FILE.exec(name);
3743
+ if (!m) continue;
3744
+ const other = seen.get(m[1]);
3745
+ 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` });
3746
+ else seen.set(m[1], name);
3747
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path23.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
3748
+ 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")})` });
3749
+ }
3445
3750
  }
3446
3751
  }
3447
- var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, MULTIWORD_TYPE;
3448
- var init_supabase = __esm({
3449
- "src/doctor/supabase.ts"() {
3450
- init_config();
3451
- DEFAULT_MIGRATIONS = "supabase/migrations";
3452
- DEFAULT_BASE = "origin/main";
3453
- DEFAULT_EXPOSED = ["public"];
3454
- schemaOf = (name) => name.split(".")[0];
3455
- TYPE_ALIASES = {
3456
- int: "integer",
3457
- int4: "integer",
3458
- int8: "bigint",
3459
- int2: "smallint",
3460
- bool: "boolean",
3461
- varchar: "character varying",
3462
- timestamptz: "timestamp with time zone",
3463
- float8: "double precision"
3464
- };
3465
- MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
3752
+ function checkExports(ctx, pkg, json) {
3753
+ const targets = [];
3754
+ const walk2 = (v) => {
3755
+ if (typeof v === "string") targets.push(v);
3756
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk2(x);
3757
+ };
3758
+ walk2(json.exports);
3759
+ for (const t of targets) {
3760
+ if (!t.startsWith("./") || t.includes("*") || /^\.\/(dist|build)\//.test(t)) continue;
3761
+ if (!existsSync(path23.join(pkg.dir, t))) {
3762
+ ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
3763
+ }
3466
3764
  }
3467
- });
3468
-
3469
- // src/doctor/semver.ts
3470
- function parseVersion(v) {
3471
- const m = VERSION.exec(v.trim());
3472
- return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
3473
3765
  }
3474
- function compareVersions(a, b) {
3475
- for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
3476
- if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
3477
- for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
3478
- const x = a.pre[i];
3479
- const y = b.pre[i];
3480
- if (x === void 0) return -1;
3481
- if (y === void 0) return 1;
3482
- if (x === y) continue;
3483
- const nx = /^\d+$/.test(x);
3484
- const ny = /^\d+$/.test(y);
3485
- if (nx && ny) return +x < +y ? -1 : 1;
3486
- if (nx !== ny) return nx ? -1 : 1;
3487
- return x < y ? -1 : 1;
3766
+ function checkBlocks(ctx, pkg, json) {
3767
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
3768
+ try {
3769
+ parseManifest(json.name, id, raw, json.version, { local: true });
3770
+ } catch (err) {
3771
+ if (!(err instanceof ManifestError)) throw err;
3772
+ for (const problem of err.problems) ctx.report({ rule: "package-block-invalid", file: `${pkg.rel}/package.json`, subject: id, message: problem });
3773
+ }
3488
3774
  }
3489
- return 0;
3490
3775
  }
3491
- function partial(s) {
3492
- const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
3493
- if (!m) return null;
3494
- const nums = [];
3495
- let wild = false;
3496
- for (const part of [m[1], m[2], m[3]]) {
3497
- if (wild || part === void 0 || /^[xX*]$/.test(part)) {
3498
- wild = true;
3499
- nums.push(null);
3500
- } else nums.push(+part);
3776
+ function checkTaggedTests(ctx, pkg) {
3777
+ const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
3778
+ if (!tests.length) return;
3779
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path23.join(pkg.dir, f), "utf8")));
3780
+ 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>` });
3781
+ }
3782
+ function checkRegistered(ctx, pkg) {
3783
+ const file = path23.join(ctx.root, "features.json");
3784
+ if (!existsSync(file)) return;
3785
+ let doc;
3786
+ try {
3787
+ doc = JSON.parse(readFileSync(file, "utf8"));
3788
+ } catch {
3789
+ return;
3790
+ }
3791
+ const covered = (doc.features ?? []).some(
3792
+ (f) => (f.links?.code ?? []).some((c) => {
3793
+ const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
3794
+ return norm === pkg.rel || norm.startsWith(`${pkg.rel}/`) || pkg.rel.startsWith(`${norm}/`);
3795
+ })
3796
+ );
3797
+ if (!covered) {
3798
+ ctx.report({ rule: "package-unregistered", level: "warn", file: pkg.rel, message: `no feature in features.ts lists ${pkg.rel} in links.code; add the package to the feature it implements` });
3501
3799
  }
3502
- return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
3503
3800
  }
3504
- function comparators(token) {
3505
- const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
3506
- if (!m) return null;
3507
- const op = m[1] ?? "";
3508
- const p = partial(m[2]);
3509
- if (!p) return null;
3510
- const [major, mi, pa] = p.nums;
3511
- if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
3512
- const M = major;
3513
- const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
3514
- 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"]);
3515
- const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
3516
- const out = switchOp();
3517
- if (p.pre.length) {
3518
- for (const c of out) if (c.v === lo) c.pre = true;
3801
+ function changesetNames(text) {
3802
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
3803
+ const names = /* @__PURE__ */ new Set();
3804
+ if (!m) return names;
3805
+ for (const line of m[1].split(/\r?\n/)) {
3806
+ const entry = /^\s*(?:"([^"]+)"|'([^']+)'|([^\s:'"]+))\s*:\s*(major|minor|patch)\s*$/.exec(line);
3807
+ if (entry) names.add(entry[1] ?? entry[2] ?? entry[3]);
3519
3808
  }
3520
- return out;
3521
- function switchOp() {
3522
- switch (op) {
3523
- case "^": {
3524
- const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
3525
- return [
3526
- { op: ">=", v: lo },
3527
- { op: "<", v: bound }
3528
- ];
3809
+ return names;
3810
+ }
3811
+ function mergeBaseOf(root, base) {
3812
+ if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository" };
3813
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) return { reason: `the git ref ${base} isn't available (fetch it)` };
3814
+ const sha = git(root, ["merge-base", "HEAD", base])?.trim();
3815
+ return sha ? { sha } : { reason: `HEAD has no merge base with ${base} (fetch with depth 0)` };
3816
+ }
3817
+ function checkChanges(ctx, pkg, json, base, mergeBase) {
3818
+ const diff = git(ctx.root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", pkg.rel]) ?? "";
3819
+ const untracked = (git(ctx.root, ["ls-files", "--others", "--exclude-standard", "--", pkg.rel]) ?? "").split("\n").filter(Boolean);
3820
+ const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
3821
+ (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
3822
+ );
3823
+ for (const row of diff.split("\n").filter(Boolean)) {
3824
+ const [status, a] = row.split(" ");
3825
+ if (a && /\/migrations\/\d{4}_[a-z0-9_]+\.sql$/.test(a) && /^[MDRT]/.test(status)) {
3826
+ ctx.report({ rule: "package-migration-edited", level: "warn", file: a, message: `${a} existed on ${base} and was ${status.startsWith("D") ? "deleted" : "changed"}; once a migration may have been applied, add a new one instead` });
3827
+ }
3828
+ }
3829
+ if (!changed.length) return;
3830
+ const before = git(ctx.root, ["show", `${mergeBase}:./${pkg.rel}/package.json`]);
3831
+ let versionBefore;
3832
+ try {
3833
+ versionBefore = before ? JSON.parse(before).version : void 0;
3834
+ } catch {
3835
+ versionBefore = void 0;
3836
+ }
3837
+ const now = typeof json.version === "string" ? parseVersion(json.version) : null;
3838
+ const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
3839
+ const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
3840
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3841
+ const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path23.join(top, f)) : [];
3842
+ const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
3843
+ const named = naming.length > 0;
3844
+ if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
3845
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path23.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
3846
+ }
3847
+ let jsonBefore = null;
3848
+ try {
3849
+ jsonBefore = before ? JSON.parse(before) : null;
3850
+ } catch {
3851
+ jsonBefore = null;
3852
+ }
3853
+ const raw = json;
3854
+ if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
3855
+ const registry = (git(ctx.root, ["diff", "--relative", "--name-only", mergeBase, "--", "features.ts", "src/features.ts"]) ?? "").trim();
3856
+ 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` });
3857
+ }
3858
+ if (!bumped && !named) {
3859
+ ctx.report({
3860
+ rule: "package-unversioned-change",
3861
+ level: "warn",
3862
+ file: `${pkg.rel}/package.json`,
3863
+ message: `${pkg.name} changed since ${base} (${changed.length} file${changed.length === 1 ? "" : "s"}) but neither its version nor a new changeset naming it did; add a changeset (or bump "version") saying what changed`
3864
+ });
3865
+ }
3866
+ }
3867
+ function checkPackagesPack(ctx) {
3868
+ let packages;
3869
+ try {
3870
+ packages = localPackages(ctx.root);
3871
+ } catch (err) {
3872
+ ctx.report({ rule: "package-block-invalid", file: "genesis.config.json", message: err.message });
3873
+ return;
3874
+ }
3875
+ if (!packages.length) return;
3876
+ const base = ctx.base ?? ctx.config.packages?.base;
3877
+ const merge = base ? mergeBaseOf(ctx.root, base) : { reason: "no base ref (pass --base <ref>, e.g. --base origin/main)" };
3878
+ if ("reason" in merge) {
3879
+ ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
3880
+ }
3881
+ for (const pkg of packages) {
3882
+ const json = JSON.parse(readFileSync(path23.join(pkg.dir, "package.json"), "utf8"));
3883
+ checkImports2(ctx, pkg, json);
3884
+ checkExports(ctx, pkg, json);
3885
+ checkBlocks(ctx, pkg, json);
3886
+ checkMigrations(ctx, pkg, json);
3887
+ checkTaggedTests(ctx, pkg);
3888
+ checkRegistered(ctx, pkg);
3889
+ if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
3890
+ }
3891
+ }
3892
+ var SOURCE, SKIP_DIRS2, BUILTINS, IMPORT, TYPE_ONLY;
3893
+ var init_packages = __esm({
3894
+ "src/doctor/packages.ts"() {
3895
+ init_local();
3896
+ init_manifest();
3897
+ init_semver();
3898
+ init_trail();
3899
+ SOURCE = /\.(?:[cm]?[jt]sx?)$/;
3900
+ SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
3901
+ BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
3902
+ IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
3903
+ TYPE_ONLY = /\b(?:import|export)\s+type\b[^;"'`]*?\bfrom\s*["'][^"']+["']/g;
3904
+ }
3905
+ });
3906
+ function sqlStatements(text) {
3907
+ const out = [];
3908
+ let buf = "";
3909
+ let bodies = [];
3910
+ let line = 1;
3911
+ let start = 0;
3912
+ const flush = () => {
3913
+ const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
3914
+ if (sql) out.push({ sql, line: start, bodies });
3915
+ buf = "";
3916
+ bodies = [];
3917
+ start = 0;
3918
+ };
3919
+ const put = (s) => {
3920
+ if (!start && /\S/.test(s)) start = line;
3921
+ buf += s;
3922
+ };
3923
+ let i = 0;
3924
+ while (i < text.length) {
3925
+ const ch = text[i];
3926
+ const two = text.slice(i, i + 2);
3927
+ if (ch === "\n") {
3928
+ buf += " ";
3929
+ line++;
3930
+ i++;
3931
+ } else if (two === "--") {
3932
+ while (i < text.length && text[i] !== "\n") i++;
3933
+ } else if (two === "/*") {
3934
+ let depth = 0;
3935
+ while (i < text.length) {
3936
+ if (text.startsWith("/*", i)) {
3937
+ depth++;
3938
+ i += 2;
3939
+ } else if (text.startsWith("*/", i)) {
3940
+ depth--;
3941
+ i += 2;
3942
+ if (depth === 0) break;
3943
+ } else {
3944
+ if (text[i] === "\n") line++;
3945
+ i++;
3946
+ }
3947
+ }
3948
+ buf += " ";
3949
+ } else if (ch === "'") {
3950
+ const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
3951
+ put("'");
3952
+ i++;
3953
+ while (i < text.length) {
3954
+ if (escapes && text[i] === "\\") i += 2;
3955
+ else if (text[i] === "'" && text[i + 1] === "'") i += 2;
3956
+ else if (text[i] === "'") break;
3957
+ else {
3958
+ if (text[i] === "\n") line++;
3959
+ i++;
3960
+ }
3529
3961
  }
3530
- case "~":
3531
- case "~>":
3532
- return [
3533
- { op: ">=", v: lo },
3534
- { op: "<", v: mi === null ? next("major") : next("minor") }
3535
- ];
3536
- case ">":
3537
- return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
3538
- case ">=":
3539
- return [{ op: ">=", v: lo }];
3540
- case "<":
3541
- return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
3542
- case "<=":
3543
- return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
3544
- default:
3545
- return upper ? [
3546
- { op: ">=", v: lo },
3547
- { op: "<", v: upper }
3548
- ] : [{ op: "=", v: lo }];
3962
+ put("'");
3963
+ i++;
3964
+ } else if (ch === '"') {
3965
+ i++;
3966
+ while (i < text.length && text[i] !== '"') put(text[i++]);
3967
+ i++;
3968
+ } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
3969
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
3970
+ const end = text.indexOf(tag, i + tag.length);
3971
+ const stop = end === -1 ? text.length : end + tag.length;
3972
+ bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
3973
+ for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
3974
+ put(`${tag} ${tag}`);
3975
+ i = stop;
3976
+ } else if (ch === ";") {
3977
+ flush();
3978
+ i++;
3979
+ } else {
3980
+ put(ch);
3981
+ i++;
3549
3982
  }
3550
3983
  }
3984
+ flush();
3985
+ return out;
3551
3986
  }
3552
- function test(c, v) {
3553
- const d = compareVersions(v, c.v);
3554
- return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
3987
+ function qualify(name) {
3988
+ const n = name.trim().toLowerCase();
3989
+ return n.includes(".") ? n : `public.${n}`;
3555
3990
  }
3556
- function parseRange(range) {
3557
- const alts = [];
3558
- for (const raw of range.trim().split("||")) {
3559
- const alt = raw.trim();
3560
- const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
3561
- if (hyphen) {
3562
- const from = comparators(`>=${hyphen[1]}`);
3563
- const to = comparators(`<=${hyphen[2]}`);
3564
- if (!from || !to) return null;
3565
- alts.push([...from, ...to]);
3566
- continue;
3567
- }
3568
- const set = [];
3569
- for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
3570
- const cs = comparators(token);
3571
- if (!cs) return null;
3572
- set.push(...cs);
3573
- }
3574
- alts.push(set);
3991
+ function parenthesized(sql, open) {
3992
+ let depth = 0;
3993
+ for (let k = open; k < sql.length; k++) {
3994
+ if (sql[k] === "(") depth++;
3995
+ else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
3575
3996
  }
3576
- return alts;
3997
+ return { inner: sql.slice(open + 1), end: sql.length };
3577
3998
  }
3578
- function satisfies(version, range) {
3579
- const v = parseVersion(version);
3580
- const alts = parseRange(range);
3581
- if (!v || !alts) return null;
3582
- return alts.some(
3583
- (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))
3584
- );
3999
+ function stripParens(s) {
4000
+ let out = "";
4001
+ let depth = 0;
4002
+ for (const c of s) {
4003
+ if (c === "(") depth++;
4004
+ else if (c === ")") depth = Math.max(0, depth - 1);
4005
+ else if (depth === 0) out += c;
4006
+ }
4007
+ return out;
3585
4008
  }
3586
- var VERSION, ver;
3587
- var init_semver = __esm({
3588
- "src/doctor/semver.ts"() {
3589
- VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
3590
- ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
4009
+ function splitTop(s) {
4010
+ const parts = [];
4011
+ let depth = 0;
4012
+ let cur = "";
4013
+ for (const c of s) {
4014
+ if (c === "(") depth++;
4015
+ if (c === ")") depth--;
4016
+ if (c === "," && depth === 0) {
4017
+ parts.push(cur);
4018
+ cur = "";
4019
+ } else cur += c;
3591
4020
  }
3592
- });
3593
- function nodeModulesOf(dir) {
3594
- const parent = path32.dirname(dir);
3595
- return path32.basename(parent).startsWith("@") ? path32.dirname(parent) : parent;
4021
+ if (cur.trim()) parts.push(cur);
4022
+ return parts.map((p) => p.trim()).filter(Boolean);
3596
4023
  }
3597
- function packagesIn(nodeModules) {
3598
- if (!existsSync(nodeModules)) return [];
3599
- const out = [];
3600
- for (const entry of readdirSync(nodeModules)) {
3601
- if (entry.startsWith(".")) continue;
3602
- const p = path32.join(nodeModules, entry);
3603
- if (entry.startsWith("@")) {
3604
- try {
3605
- for (const sub of readdirSync(p)) out.push(path32.join(p, sub));
3606
- } catch {
3607
- }
3608
- } else {
3609
- out.push(p);
3610
- }
4024
+ function argTypes(args) {
4025
+ const types = [];
4026
+ for (const raw of splitTop(args)) {
4027
+ let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
4028
+ const mode = tokens[0];
4029
+ if (mode === "out") continue;
4030
+ if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
4031
+ const joined = tokens.join(" ");
4032
+ const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
4033
+ types.push(TYPE_ALIASES[type] ?? type);
3611
4034
  }
3612
- return out;
4035
+ return types;
3613
4036
  }
3614
- function genesisInstalls(root) {
3615
- const copies = /* @__PURE__ */ new Map();
3616
- const realRoot = real(root);
3617
- const rel = (abs) => path32.relative(realRoot, abs).split(path32.sep).join("/") || ".";
3618
- const via = /* @__PURE__ */ new Map();
3619
- const record = (real2, manifest, by, range, root2) => {
3620
- let copy = copies.get(real2);
3621
- if (!copy) {
3622
- copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
3623
- copies.set(real2, copy);
3624
- via.set(real2, /* @__PURE__ */ new Set());
3625
- }
3626
- via.get(real2).add(root2);
3627
- if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
3628
- };
3629
- const walk2 = (kind, roots) => {
3630
- const expanded = /* @__PURE__ */ new Set();
3631
- const queue = [];
3632
- const visit = (dir, by, range) => {
3633
- const manifest = readManifest(dir);
3634
- if (!manifest?.name) return;
3635
- if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
3636
- const realDir = real(dir);
3637
- if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
3638
- if (expanded.has(realDir)) return;
3639
- expanded.add(realDir);
3640
- queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
3641
- };
3642
- for (const r of roots) visit(r.dir, r.by, r.range);
3643
- while (queue.length) {
3644
- const { real: from, manifest, label } = queue.shift();
3645
- const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
3646
- for (const [name, range] of Object.entries(deps)) {
3647
- const dir = findPackageDir(from, name);
3648
- if (dir) visit(dir, label, range);
3649
- }
3650
- for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
3651
- if (name in deps) continue;
3652
- const dir = peerOf(from, name);
3653
- if (dir) visit(dir, label, range);
3654
- }
4037
+ function git2(root, args) {
4038
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
4039
+ return r.status === 0 ? r.stdout : null;
4040
+ }
4041
+ function gitView(root, dir, base) {
4042
+ if (git2(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
4043
+ if (git2(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
4044
+ return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
4045
+ }
4046
+ const mergeBase = git2(root, ["merge-base", "HEAD", base])?.trim();
4047
+ if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
4048
+ const diff = git2(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
4049
+ const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
4050
+ if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
4051
+ const sql = (p) => p !== void 0 && p.endsWith(".sql");
4052
+ const touched = new Set(untracked.split("\n").filter(sql));
4053
+ const edited = [];
4054
+ for (const row of diff.split("\n").filter(Boolean)) {
4055
+ const [status, a, b] = row.split(" ");
4056
+ if (status.startsWith("R")) {
4057
+ if (sql(b)) touched.add(b);
4058
+ if (sql(a)) edited.push({ file: a, status: "renamed" });
4059
+ continue;
3655
4060
  }
3656
- };
3657
- const peerOf = (from, name) => {
3658
- const dir = findPackageDir(from, name);
3659
- if (!dir) return null;
3660
- if (!ownInstall || name in declared) return dir;
3661
- const realDir = real(dir);
3662
- if (realDir.startsWith(realRoot + path32.sep)) return dir;
3663
- return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
3664
- };
3665
- const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
3666
- const dir = findPackageDir(root, name);
3667
- return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
3668
- });
3669
- const app = readManifest(root);
3670
- const ownInstall = LOCKFILES.some((f) => existsSync(path32.join(root, f)));
3671
- const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
3672
- const declaredDev = Object.entries(app?.devDependencies ?? {});
3673
- const runtimeDeps = {
3674
- ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
3675
- ...app?.peerDependencies,
3676
- ...app?.optionalDependencies,
3677
- ...app?.dependencies
3678
- };
3679
- const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
3680
- walk2("runtime", rootsOf(runtimeDeps, "the app"));
3681
- const top = path32.join(root, "node_modules");
3682
- walk2(
3683
- "hoisted",
3684
- packagesIn(top).filter((dir) => {
3685
- const name = path32.relative(top, dir).split(path32.sep).join("/");
3686
- return !(name in runtimeDeps) && !(name in devDeps);
3687
- }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
3688
- );
3689
- const devRoots = { ...devDeps };
3690
- for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
3691
- walk2("dev", rootsOf(devRoots, "the app (dev)"));
3692
- for (const [key2, copy] of copies) {
3693
- const kinds = via.get(key2);
3694
- copy.runtime = kinds.has("runtime");
3695
- copy.devOnly = kinds.size === 1 && kinds.has("dev");
4061
+ if (!sql(a)) continue;
4062
+ if (status.startsWith("A")) touched.add(a);
4063
+ else if (status.startsWith("M") || status.startsWith("T")) {
4064
+ touched.add(a);
4065
+ edited.push({ file: a, status: "modified" });
4066
+ } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
3696
4067
  }
3697
- const byName = /* @__PURE__ */ new Map();
3698
- for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
3699
- for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
3700
- return byName;
4068
+ return { touched, edited };
3701
4069
  }
3702
- function checkDuplicatePackages(ctx) {
3703
- const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
3704
- for (const [name, copies] of genesisInstalls(ctx.root)) {
3705
- if (copies.length < 2) continue;
3706
- const shipping = copies.filter((c) => c.runtime);
3707
- if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
4070
+ function checkSupabasePack(ctx) {
4071
+ const settings2 = ctx.config.supabase ?? {};
4072
+ const dir = settings2.migrations ?? DEFAULT_MIGRATIONS;
4073
+ const abs = path23.join(ctx.root, dir);
4074
+ if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
4075
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path23.join(abs, n), "utf8")) }));
4076
+ const exposed = new Set((settings2.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
4077
+ const base = settings2.base ?? DEFAULT_BASE;
4078
+ const view = gitView(ctx.root, dir, base);
4079
+ if ("reason" in view) {
4080
+ if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
4081
+ } else {
4082
+ for (const e of view.edited) {
3708
4083
  ctx.report({
3709
- rule: "duplicate-genesis-package",
3710
- level: "warn",
3711
- file: "package.json",
3712
- subject: name,
3713
- message: `${name} is installed ${copies.length} times: ${copies.map((c) => `${describe(c)}${c.devOnly ? " [dev only]" : ""}`).join(", ")}. Each copy is its own module, so a provider from one (DataProvider, the shell's contexts) is invisible to hooks from another. Align the ranges so one copy satisfies them all, or add an override/resolution`
4084
+ rule: "migration-edited",
4085
+ file: e.file,
4086
+ subject: e.file,
4087
+ message: `${e.status === "modified" ? "edits" : e.status === "deleted" ? "deletes" : "renames"} a migration that already exists on ${base}, so it has been applied; put the change in a new migration instead`
3714
4088
  });
3715
- continue;
3716
4089
  }
4090
+ }
4091
+ const since = settings2.since;
4092
+ const afterSince = (file) => since === void 0 || path23.posix.basename(file) >= since;
4093
+ if ("reason" in view && since === void 0) {
3717
4094
  ctx.report({
3718
- rule: "duplicate-genesis-package",
3719
- level: "info",
3720
- file: "package.json",
3721
- subject: name,
3722
- message: `${name} has dev-only copies beside the one the app loads: ${copies.filter((c) => c.devOnly).map(describe).join(", ")}. They run in tooling, not the app, so they can't split its contexts; upgrade the tool to drop them`
4095
+ rule: "migration-grants",
4096
+ level: "warn",
4097
+ file: dir,
4098
+ message: `skipped: can't tell new migrations from applied ones (${view.reason}); fetch the base ref (CI: fetch-depth 0) or set doctor.supabase.since`
3723
4099
  });
4100
+ } else {
4101
+ const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
4102
+ checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
3724
4103
  }
4104
+ checkRls(ctx, migrations, exposed);
4105
+ checkViewInvoker(ctx, migrations, exposed);
4106
+ checkDefinerSearchPath(ctx, migrations);
4107
+ checkTestingKit(ctx, migrations);
3725
4108
  }
3726
- function checkPeerRanges(ctx) {
3727
- const rel = (abs) => path32.relative(ctx.root, abs).split(path32.sep).join("/");
3728
- for (const copies of genesisInstalls(ctx.root).values()) {
3729
- for (const copy of copies) {
3730
- const dir = copy.absolutePath;
3731
- const peers = readManifest(dir)?.peerDependencies ?? {};
3732
- for (const [peer, range] of Object.entries(peers)) {
3733
- if (!GENESIS.test(peer)) continue;
3734
- const peerDir = findPackageDir(dir, peer);
3735
- const installed = peerDir && readManifest(peerDir)?.version;
3736
- if (!peerDir || !installed) continue;
3737
- if (satisfies(installed, range) !== false) continue;
3738
- ctx.report({
3739
- rule: "peer-range-mismatch",
3740
- // A dev tool's own tree (the CLI's) doesn't run in the app.
3741
- level: copy.devOnly ? "info" : "warn",
3742
- file: "package.json",
3743
- subject: `${copy.name}>${peer}`,
3744
- message: `${copy.name}@${copy.version} (${copy.dir}) wants ${peer} ${range}, but ${installed} is installed (${rel(peerDir)}). Install a ${peer} in that range, or a ${copy.name} release built against ${installed}`
3745
- });
4109
+ function checkTestingKit(ctx, migrations) {
4110
+ for (const { file, statements } of migrations) {
4111
+ const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
4112
+ if (!hit) continue;
4113
+ ctx.report({
4114
+ rule: "migration-testing-kit",
4115
+ file,
4116
+ line: hit.line,
4117
+ subject: "genesis_testing",
4118
+ message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
4119
+ });
4120
+ }
4121
+ }
4122
+ function granteesOf(s) {
4123
+ return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
4124
+ }
4125
+ function checkGrants(ctx, migrations, exposed) {
4126
+ const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
4127
+ const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
4128
+ const blanket = (roles) => {
4129
+ const o = open(roles);
4130
+ if (o.length) return { level: "error", who: o.join(" and ") };
4131
+ if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
4132
+ return null;
4133
+ };
4134
+ for (const { file, statements } of migrations) {
4135
+ for (const { sql, line } of statements) {
4136
+ const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
4137
+ if (all) {
4138
+ const hit = blanket(granteesOf(all[1]));
4139
+ if (hit) {
4140
+ ctx.report({ rule: "migration-grants", level: hit.level, file, line, subject: "on all functions", message: `grants every function in a schema to ${hit.who}, which re-grants functions an earlier migration revoked; ${fix}` });
4141
+ }
4142
+ continue;
4143
+ }
4144
+ const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
4145
+ if (defaults) {
4146
+ const hit = blanket(granteesOf(defaults[1]));
4147
+ if (hit) {
4148
+ ctx.report({ rule: "migration-grants", level: hit.level, file, line, subject: "alter default privileges", message: `grants default privileges on functions to ${hit.who}, so every future function is callable by them; ${fix}` });
4149
+ }
4150
+ continue;
4151
+ }
4152
+ const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
4153
+ if (fn) {
4154
+ const roles = open(granteesOf(fn[2]));
4155
+ if (!roles.length) continue;
4156
+ for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
4157
+ if (exposed.has(schemaOf(name))) continue;
4158
+ ctx.report({
4159
+ rule: "migration-grants",
4160
+ file,
4161
+ line,
4162
+ subject: name,
4163
+ message: `grants ${name} to ${roles.join(" and ")}; a function outside the exposed schemas is never callable by anon or public (grant it to authenticated, or expose a wrapper)`
4164
+ });
4165
+ }
4166
+ continue;
4167
+ }
4168
+ const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
4169
+ if (schema) {
4170
+ const roles = open(granteesOf(schema[2]));
4171
+ if (!roles.length) continue;
4172
+ for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
4173
+ if (exposed.has(s)) continue;
4174
+ ctx.report({
4175
+ rule: "migration-grants",
4176
+ file,
4177
+ line,
4178
+ subject: `schema ${s}`,
4179
+ message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
4180
+ });
4181
+ }
3746
4182
  }
3747
4183
  }
3748
4184
  }
3749
4185
  }
3750
- var GENESIS, DEV_TOOLS, NON_SHIPPING, readManifest, real, LOCKFILES;
3751
- var init_installs = __esm({
3752
- "src/doctor/installs.ts"() {
3753
- init_genesis();
3754
- init_semver();
3755
- GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
3756
- DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
3757
- 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)$/;
3758
- readManifest = (dir) => {
3759
- try {
3760
- return JSON.parse(readFileSync(path32.join(dir, "package.json"), "utf8"));
3761
- } catch {
3762
- return null;
4186
+ function checkRls(ctx, migrations, exposed) {
4187
+ const tables = /* @__PURE__ */ new Map();
4188
+ const name = String.raw`([\w$.]+)`;
4189
+ const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
4190
+ for (const { file, statements } of migrations) {
4191
+ for (const { sql, line, bodies } of statements) {
4192
+ if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
4193
+ const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
4194
+ if (create) {
4195
+ if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
4196
+ continue;
3763
4197
  }
3764
- };
3765
- real = (p) => {
3766
- try {
3767
- return realpathSync(p);
3768
- } catch {
3769
- return p;
4198
+ const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
4199
+ const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
4200
+ if (rename || move) {
4201
+ const from = qualify((rename ?? move)[1]);
4202
+ const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
4203
+ const state = tables.get(from);
4204
+ if (state) {
4205
+ tables.delete(from);
4206
+ tables.set(to, state);
4207
+ }
4208
+ continue;
3770
4209
  }
3771
- };
3772
- LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
4210
+ const alter = new RegExp(target).exec(sql);
4211
+ if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
4212
+ const t = qualify(alter[1]);
4213
+ if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
4214
+ else {
4215
+ const state = tables.get(t);
4216
+ if (state) state.rls = true;
4217
+ }
4218
+ continue;
4219
+ }
4220
+ const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
4221
+ if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
4222
+ }
3773
4223
  }
3774
- });
3775
- function stripForImports(code) {
3776
- const out = [];
3777
- const blank = (ch) => ch === "\n" ? "\n" : " ";
3778
- const n = code.length;
3779
- const templates = [];
3780
- let depth = 0;
3781
- let i = 0;
3782
- let sure = true;
3783
- const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
3784
- const before = () => out.slice(-24).join("");
3785
- const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
3786
- const startsExpression = (b) => {
3787
- const t = b.replace(/\s+$/, "");
3788
- if (!t) return true;
3789
- if (KEYWORD.test(b)) return true;
3790
- return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
3791
- };
3792
- const exprStart = () => startsExpression(before());
3793
- const taggedTemplate = () => {
3794
- const b = out.slice(-48).join("");
3795
- const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
3796
- return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
3797
- };
3798
- const templateBody = () => {
3799
- while (i < n) {
3800
- const ch = code[i];
3801
- if (ch === "\\") {
3802
- out.push(" ", blank(code[i + 1] ?? ""));
3803
- i += 2;
3804
- } else if (ch === "`") {
3805
- out.push("`");
3806
- i++;
3807
- return;
3808
- } else if (ch === "$" && code[i + 1] === "{") {
3809
- out.push("${");
3810
- i += 2;
3811
- templates.push(depth);
3812
- depth++;
3813
- return;
3814
- } else {
3815
- out.push(blank(ch));
3816
- i++;
4224
+ for (const [t, at] of tables) {
4225
+ if (at.rls || !exposed.has(schemaOf(t))) continue;
4226
+ ctx.report({
4227
+ rule: "migration-rls",
4228
+ file: at.file,
4229
+ line: at.line,
4230
+ subject: t,
4231
+ message: at.disabled ? `disables row level security on ${t}, and no later migration turns it back on; anyone with the API key can read and write it` : `creates ${t} without enabling row level security in any migration; add "alter table ${t} enable row level security;" and its policies`
4232
+ });
4233
+ }
4234
+ }
4235
+ function checkViewInvoker(ctx, migrations, exposed) {
4236
+ const views = /* @__PURE__ */ new Map();
4237
+ const name = String.raw`([\w$.]+)`;
4238
+ const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
4239
+ for (const { file, statements } of migrations) {
4240
+ for (const { sql, line } of statements) {
4241
+ const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
4242
+ if (create) {
4243
+ if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
4244
+ const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
4245
+ views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
4246
+ continue;
4247
+ }
4248
+ const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
4249
+ if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
4250
+ const state = views.get(qualify(alter[1]));
4251
+ if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
4252
+ continue;
4253
+ }
4254
+ const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
4255
+ if (rename) {
4256
+ const from = qualify(rename[1]);
4257
+ const state = views.get(from);
4258
+ if (state) {
4259
+ views.delete(from);
4260
+ views.set(`${schemaOf(from)}.${rename[2]}`, state);
4261
+ }
4262
+ continue;
3817
4263
  }
4264
+ const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
4265
+ if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
3818
4266
  }
3819
- sure = false;
4267
+ }
4268
+ for (const [v, at] of views) {
4269
+ if (at.invoker || !exposed.has(schemaOf(v))) continue;
4270
+ ctx.report({
4271
+ rule: "migration-view-rls",
4272
+ file: at.file,
4273
+ line: at.line,
4274
+ subject: v,
4275
+ message: `${v} runs as its owner, so it reads past row level security; create it "with (security_invoker = true)" or add "alter view ${v} set (security_invoker = true);"`
4276
+ });
4277
+ }
4278
+ }
4279
+ function checkDefinerSearchPath(ctx, migrations) {
4280
+ const fns = /* @__PURE__ */ new Map();
4281
+ const keysFor = (sql, nameEnd, fnName) => {
4282
+ const rest = sql.slice(nameEnd).trimStart();
4283
+ if (rest.startsWith("(")) {
4284
+ const { inner } = parenthesized(rest, 0);
4285
+ return [`${fnName}(${argTypes(inner).join(",")})`];
4286
+ }
4287
+ return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
3820
4288
  };
3821
- while (i < n && sure) {
3822
- const ch = code[i];
3823
- const next = code[i + 1];
3824
- if (ch === "/" && next === "/") {
3825
- while (i < n && code[i] !== "\n") {
3826
- out.push(" ");
3827
- i++;
3828
- }
3829
- } else if (ch === "/" && next === "*") {
3830
- out.push(" ");
3831
- i += 2;
3832
- while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
3833
- out.push(blank(code[i]));
3834
- i++;
3835
- }
3836
- if (i < n) {
3837
- out.push(" ");
3838
- i += 2;
4289
+ for (const { file, statements } of migrations) {
4290
+ for (const { sql, line } of statements) {
4291
+ const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
4292
+ if (create) {
4293
+ const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
4294
+ fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
4295
+ continue;
3839
4296
  }
3840
- } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
3841
- const afterBrace = /[}>]\s*$/.test(before());
3842
- const start = i;
3843
- const mark = out.length;
3844
- out.push("/");
3845
- i++;
3846
- let inClass = false;
3847
- for (; ; ) {
3848
- const c = code[i];
3849
- if (c === void 0 || c === "\n") {
3850
- if (afterBrace) {
3851
- out.length = mark;
3852
- out.push("/");
3853
- i = start + 1;
3854
- } else sure = false;
3855
- break;
3856
- }
3857
- if (c === "\\") {
3858
- out.push(" ", blank(code[i + 1] ?? ""));
3859
- i += 2;
3860
- continue;
3861
- }
3862
- i++;
3863
- if (c === "[") inClass = true;
3864
- else if (c === "]") inClass = false;
3865
- else if (c === "/" && !inClass) {
3866
- if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
3867
- out.length = mark;
3868
- out.push("/");
3869
- i = start + 1;
3870
- break;
4297
+ const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
4298
+ if (alter) {
4299
+ const fnName = qualify(alter[1]);
4300
+ const keys = keysFor(sql, alter[0].length, fnName);
4301
+ const rename = / rename to ([\w$]+)$/.exec(sql);
4302
+ const move = / set schema ([\w$]+)$/.exec(sql);
4303
+ for (const key2 of keys) {
4304
+ const state = fns.get(key2);
4305
+ if (rename || move) {
4306
+ if (!state) continue;
4307
+ fns.delete(key2);
4308
+ const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
4309
+ fns.set(newName + key2.slice(fnName.length), state);
4310
+ continue;
3871
4311
  }
3872
- out.push("/");
3873
- break;
4312
+ const next = state ?? { definer: false, searchPath: false, file, line };
4313
+ if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
4314
+ if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
4315
+ if (/\bset search_path\b/.test(sql)) next.searchPath = true;
4316
+ if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
4317
+ fns.set(key2, next);
3874
4318
  }
3875
- out.push(" ");
4319
+ continue;
3876
4320
  }
3877
- if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
3878
- } else if ((ch === '"' || ch === "'") && exprStart()) {
3879
- const keep = isSpecifier();
3880
- out.push(ch);
3881
- i++;
3882
- while (i < n && code[i] !== ch && code[i] !== "\n") {
3883
- if (code[i] === "\\") {
3884
- out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
3885
- i += 2;
3886
- } else {
3887
- out.push(keep ? code[i] : blank(code[i]));
3888
- i++;
4321
+ const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
4322
+ if (drop) {
4323
+ for (const part of splitTop(drop[1])) {
4324
+ const m = /^([\w$.]+)\s*/.exec(part);
4325
+ if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
3889
4326
  }
3890
4327
  }
3891
- if (code[i] !== ch) sure = false;
3892
- else {
3893
- out.push(code[i]);
3894
- i++;
3895
- }
3896
- } else if (ch === "`" && (exprStart() || taggedTemplate())) {
3897
- out.push("`");
3898
- i++;
3899
- templateBody();
3900
- } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
3901
- templates.pop();
3902
- depth--;
3903
- out.push("}");
3904
- i++;
3905
- templateBody();
3906
- } else {
3907
- if (ch === "{") depth++;
3908
- else if (ch === "}") depth--;
3909
- out.push(ch);
3910
- i++;
3911
4328
  }
3912
4329
  }
3913
- return sure && templates.length === 0 ? out.join("") : null;
3914
- }
3915
- function bindings(clause) {
3916
- const out = [];
3917
- const named = /\{([^}]*)\}/.exec(clause);
3918
- for (const part of named?.[1].split(",") ?? []) {
3919
- const p = part.trim();
3920
- if (!p || p.startsWith("type ")) continue;
3921
- out.push(p.split(/\s+as\s+/).pop().trim());
4330
+ for (const [key2, at] of fns) {
4331
+ if (!at.definer || at.searchPath) continue;
4332
+ ctx.report({
4333
+ rule: "migration-definer-search-path",
4334
+ file: at.file,
4335
+ line: at.line,
4336
+ subject: key2,
4337
+ message: `${key2} is security definer without "set search_path"; add set search_path = '' and schema-qualify the names in its body, so a caller's objects can't stand in for yours`
4338
+ });
3922
4339
  }
3923
- const rest = clause.replace(/\{[^}]*\}/, "");
3924
- const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
3925
- if (ns) out.push(ns[1]);
3926
- const def = /^\s*([\w$]+)/.exec(rest);
3927
- if (def && def[1] !== "as") out.push(def[1]);
3928
- return out;
3929
4340
  }
3930
- function readJsonc(file) {
3931
- try {
3932
- const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
3933
- return JSON.parse(text);
3934
- } catch {
3935
- return null;
4341
+ var DEFAULT_MIGRATIONS, DEFAULT_BASE, DEFAULT_EXPOSED, schemaOf, TYPE_ALIASES, MULTIWORD_TYPE;
4342
+ var init_supabase = __esm({
4343
+ "src/doctor/supabase.ts"() {
4344
+ init_config();
4345
+ DEFAULT_MIGRATIONS = "supabase/migrations";
4346
+ DEFAULT_BASE = "origin/main";
4347
+ DEFAULT_EXPOSED = ["public"];
4348
+ schemaOf = (name) => name.split(".")[0];
4349
+ TYPE_ALIASES = {
4350
+ int: "integer",
4351
+ int4: "integer",
4352
+ int8: "bigint",
4353
+ int2: "smallint",
4354
+ bool: "boolean",
4355
+ varchar: "character varying",
4356
+ timestamptz: "timestamp with time zone",
4357
+ float8: "double precision"
4358
+ };
4359
+ MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
3936
4360
  }
4361
+ });
4362
+ function nodeModulesOf(dir) {
4363
+ const parent = path23.dirname(dir);
4364
+ return path23.basename(parent).startsWith("@") ? path23.dirname(parent) : parent;
3937
4365
  }
3938
- function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3939
- if (seen.has(file) || seen.size > 10) return {};
3940
- seen.add(file);
3941
- const json = readJsonc(file);
3942
- if (!json) return {};
3943
- const dir = path32.dirname(file);
3944
- let merged = {};
3945
- const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3946
- for (const ext of parents) {
3947
- if (typeof ext !== "string") continue;
3948
- let target = null;
3949
- if (ext.startsWith(".") || path32.isAbsolute(ext)) {
3950
- const abs = path32.resolve(dir, ext);
3951
- target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
4366
+ function packagesIn(nodeModules) {
4367
+ if (!existsSync(nodeModules)) return [];
4368
+ const out = [];
4369
+ for (const entry of readdirSync(nodeModules)) {
4370
+ if (entry.startsWith(".")) continue;
4371
+ const p = path23.join(nodeModules, entry);
4372
+ if (entry.startsWith("@")) {
4373
+ try {
4374
+ for (const sub of readdirSync(p)) out.push(path23.join(p, sub));
4375
+ } catch {
4376
+ }
3952
4377
  } else {
3953
- const parts = ext.split("/");
3954
- const nameLength = ext.startsWith("@") ? 2 : 1;
3955
- const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3956
- if (pkgDir) {
3957
- const sub = parts.slice(nameLength).join("/");
3958
- const abs = path32.join(pkgDir, sub || "tsconfig.json");
3959
- target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
4378
+ out.push(p);
4379
+ }
4380
+ }
4381
+ return out;
4382
+ }
4383
+ function genesisInstalls(root) {
4384
+ const copies = /* @__PURE__ */ new Map();
4385
+ const realRoot = real(root);
4386
+ const rel = (abs) => path23.relative(realRoot, abs).split(path23.sep).join("/") || ".";
4387
+ const via = /* @__PURE__ */ new Map();
4388
+ const record = (real2, manifest, by, range, root2) => {
4389
+ let copy = copies.get(real2);
4390
+ if (!copy) {
4391
+ copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
4392
+ copies.set(real2, copy);
4393
+ via.set(real2, /* @__PURE__ */ new Set());
4394
+ }
4395
+ via.get(real2).add(root2);
4396
+ if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
4397
+ };
4398
+ const walk2 = (kind, roots) => {
4399
+ const expanded = /* @__PURE__ */ new Set();
4400
+ const queue = [];
4401
+ const visit = (dir, by, range) => {
4402
+ const manifest = readManifest(dir);
4403
+ if (!manifest?.name) return;
4404
+ if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
4405
+ const realDir = real(dir);
4406
+ if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
4407
+ if (expanded.has(realDir)) return;
4408
+ expanded.add(realDir);
4409
+ queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
4410
+ };
4411
+ for (const r of roots) visit(r.dir, r.by, r.range);
4412
+ while (queue.length) {
4413
+ const { real: from, manifest, label } = queue.shift();
4414
+ const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
4415
+ for (const [name, range] of Object.entries(deps)) {
4416
+ const dir = findPackageDir(from, name);
4417
+ if (dir) visit(dir, label, range);
4418
+ }
4419
+ for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
4420
+ if (name in deps) continue;
4421
+ const dir = peerOf(from, name);
4422
+ if (dir) visit(dir, label, range);
3960
4423
  }
3961
4424
  }
3962
- if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
3963
- }
3964
- const opts = json.compilerOptions ?? {};
3965
- if (typeof opts.baseUrl === "string") merged.baseUrl = path32.resolve(dir, opts.baseUrl);
3966
- if (opts.paths && typeof opts.paths === "object") {
3967
- merged.paths = opts.paths;
3968
- merged.pathsDir = dir;
4425
+ };
4426
+ const peerOf = (from, name) => {
4427
+ const dir = findPackageDir(from, name);
4428
+ if (!dir) return null;
4429
+ if (!ownInstall || name in declared) return dir;
4430
+ const realDir = real(dir);
4431
+ if (realDir.startsWith(realRoot + path23.sep)) return dir;
4432
+ return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
4433
+ };
4434
+ const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
4435
+ const dir = findPackageDir(root, name);
4436
+ return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
4437
+ });
4438
+ const app = readManifest(root);
4439
+ const ownInstall = LOCKFILES.some((f) => existsSync(path23.join(root, f)));
4440
+ const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
4441
+ const declaredDev = Object.entries(app?.devDependencies ?? {});
4442
+ const runtimeDeps = {
4443
+ ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
4444
+ ...app?.peerDependencies,
4445
+ ...app?.optionalDependencies,
4446
+ ...app?.dependencies
4447
+ };
4448
+ const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
4449
+ walk2("runtime", rootsOf(runtimeDeps, "the app"));
4450
+ const top = path23.join(root, "node_modules");
4451
+ walk2(
4452
+ "hoisted",
4453
+ packagesIn(top).filter((dir) => {
4454
+ const name = path23.relative(top, dir).split(path23.sep).join("/");
4455
+ return !(name in runtimeDeps) && !(name in devDeps);
4456
+ }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
4457
+ );
4458
+ const devRoots = { ...devDeps };
4459
+ for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
4460
+ walk2("dev", rootsOf(devRoots, "the app (dev)"));
4461
+ for (const [key2, copy] of copies) {
4462
+ const kinds = via.get(key2);
4463
+ copy.runtime = kinds.has("runtime");
4464
+ copy.devOnly = kinds.size === 1 && kinds.has("dev");
3969
4465
  }
3970
- return merged;
4466
+ const byName = /* @__PURE__ */ new Map();
4467
+ for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
4468
+ for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
4469
+ return byName;
3971
4470
  }
3972
- function aliases(root) {
3973
- const table = [];
3974
- let baseUrl = null;
3975
- for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3976
- const file = path32.join(root, name);
3977
- if (!existsSync(file)) continue;
3978
- const config = readTsconfig(root, file);
3979
- baseUrl ??= config.baseUrl ?? null;
3980
- const base = config.baseUrl ?? config.pathsDir ?? root;
3981
- for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3982
- if (!Array.isArray(targets)) continue;
3983
- const exact = !pattern.endsWith("*");
3984
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path32.join(base, String(t).replace(/\*$/, ""))) });
4471
+ function checkDuplicatePackages(ctx) {
4472
+ const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
4473
+ for (const [name, copies] of genesisInstalls(ctx.root)) {
4474
+ if (copies.length < 2) continue;
4475
+ const shipping = copies.filter((c) => c.runtime);
4476
+ if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
4477
+ ctx.report({
4478
+ rule: "duplicate-genesis-package",
4479
+ level: "warn",
4480
+ file: "package.json",
4481
+ subject: name,
4482
+ message: `${name} is installed ${copies.length} times: ${copies.map((c) => `${describe(c)}${c.devOnly ? " [dev only]" : ""}`).join(", ")}. Each copy is its own module, so a provider from one (DataProvider, the shell's contexts) is invisible to hooks from another. Align the ranges so one copy satisfies them all, or add an override/resolution`
4483
+ });
4484
+ continue;
3985
4485
  }
4486
+ ctx.report({
4487
+ rule: "duplicate-genesis-package",
4488
+ level: "info",
4489
+ file: "package.json",
4490
+ subject: name,
4491
+ message: `${name} has dev-only copies beside the one the app loads: ${copies.filter((c) => c.devOnly).map(describe).join(", ")}. They run in tooling, not the app, so they can't split its contexts; upgrade the tool to drop them`
4492
+ });
3986
4493
  }
3987
- const pkg = readJsonc(path32.join(root, "package.json"));
3988
- for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3989
- if (typeof target !== "string") continue;
3990
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path32.join(root, target.replace(/\*.*$/, ""))] });
3991
- }
3992
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path32.join(root, "src") + path32.sep, root + path32.sep] });
3993
- return { table, baseUrl };
3994
- }
3995
- function resolveFile(base) {
3996
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path32.join(base, `index${e}`))];
3997
- if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3998
- for (const p of tries) {
3999
- if (SCRIPT_EXTS2.has(path32.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
4000
- }
4001
- return null;
4002
- }
4003
- function trailFor(ctx) {
4004
- let t = trails.get(ctx.files);
4005
- if (!t) trails.set(ctx.files, t = createTrail(ctx));
4006
- return t;
4007
4494
  }
4008
- function createTrail(ctx) {
4009
- const { table, baseUrl } = aliases(ctx.root);
4010
- let declared = null;
4011
- try {
4012
- const pkg = JSON.parse(readFileSync(path32.join(ctx.root, "package.json"), "utf8"));
4013
- declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
4014
- } catch {
4015
- declared = null;
4016
- }
4017
- const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
4018
- const read = (abs) => byPath.get(abs) ?? readSource(abs);
4019
- const importsCache = /* @__PURE__ */ new Map();
4020
- const importsOf = (file) => {
4021
- const hit = importsCache.get(file.absolutePath);
4022
- if (hit) return hit;
4023
- const files = [];
4024
- let lost = false;
4025
- const code = stripped(file);
4026
- if (code === null) {
4027
- const out2 = { files: [], lost: true };
4028
- importsCache.set(file.absolutePath, out2);
4029
- return out2;
4030
- }
4031
- const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
4032
- for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
4033
- for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
4034
- for (const m of code.matchAll(/\bexport\s*\{([^}]*)\}\s*;/g)) for (const n of m[1].split(",")) used.add(n.trim().split(/\s+as\s+/)[0]);
4035
- const specs = [];
4036
- for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
4037
- for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
4038
- for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
4039
- for (const spec of specs) {
4040
- if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
4041
- let resolved = null;
4042
- if (spec.startsWith(".")) {
4043
- resolved = resolveFile(path32.resolve(path32.dirname(file.absolutePath), spec));
4044
- if (!resolved) lost = true;
4045
- } else {
4046
- const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
4047
- if (alias) {
4048
- for (const t of alias.targets) {
4049
- resolved = resolveFile(alias.exact ? t : path32.join(t, spec.slice(alias.prefix.length)));
4050
- if (resolved) break;
4051
- }
4052
- }
4053
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path32.join(baseUrl, spec));
4054
- if (!resolved) {
4055
- const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
4056
- if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
4057
- }
4058
- }
4059
- if (resolved && !files.includes(resolved)) files.push(resolved);
4060
- }
4061
- const out = { files, lost };
4062
- importsCache.set(file.absolutePath, out);
4063
- return out;
4064
- };
4065
- const strippedCache = /* @__PURE__ */ new Map();
4066
- const stripped = (file) => {
4067
- if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
4068
- return strippedCache.get(file.absolutePath);
4069
- };
4070
- const memo = /* @__PURE__ */ new WeakMap();
4071
- const reach = (file, test2, depth, seen) => {
4072
- let cache = memo.get(test2);
4073
- if (!cache) memo.set(test2, cache = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
4074
- const k = `${file.absolutePath}\0${depth}`;
4075
- const free = cache.free.get(k);
4076
- if (free) return [free, /* @__PURE__ */ new Set()];
4077
- const reusable = cache.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
4078
- if (reusable) return [reusable.result, new Set(reusable.cut)];
4079
- let result;
4080
- const cut = /* @__PURE__ */ new Set();
4081
- const code = stripped(file);
4082
- if (code === null) result = "unknown";
4083
- else if (test2(code)) result = "yes";
4084
- else {
4085
- const { files, lost } = importsOf(file);
4086
- let unknown = lost && depth > 0;
4087
- result = "no";
4088
- if (depth > 0) {
4089
- seen.add(file.absolutePath);
4090
- for (const abs of files) {
4091
- if (seen.has(abs)) {
4092
- cut.add(abs);
4093
- continue;
4094
- }
4095
- const target = read(abs);
4096
- if (!target) {
4097
- unknown = true;
4098
- continue;
4099
- }
4100
- const [r, c] = reach(target, test2, depth - 1, seen);
4101
- for (const m of c) cut.add(m);
4102
- if (r === "yes") {
4103
- result = "yes";
4104
- break;
4105
- }
4106
- if (r === "unknown") unknown = true;
4107
- }
4108
- seen.delete(file.absolutePath);
4109
- cut.delete(file.absolutePath);
4495
+ function checkPeerRanges(ctx) {
4496
+ const rel = (abs) => path23.relative(ctx.root, abs).split(path23.sep).join("/");
4497
+ for (const copies of genesisInstalls(ctx.root).values()) {
4498
+ for (const copy of copies) {
4499
+ const dir = copy.absolutePath;
4500
+ const peers = readManifest(dir)?.peerDependencies ?? {};
4501
+ for (const [peer, range] of Object.entries(peers)) {
4502
+ if (!GENESIS.test(peer)) continue;
4503
+ const peerDir = findPackageDir(dir, peer);
4504
+ const installed = peerDir && readManifest(peerDir)?.version;
4505
+ if (!peerDir || !installed) continue;
4506
+ if (satisfies(installed, range) !== false) continue;
4507
+ ctx.report({
4508
+ rule: "peer-range-mismatch",
4509
+ // A dev tool's own tree (the CLI's) doesn't run in the app.
4510
+ level: copy.devOnly ? "info" : "warn",
4511
+ file: "package.json",
4512
+ subject: `${copy.name}>${peer}`,
4513
+ message: `${copy.name}@${copy.version} (${copy.dir}) wants ${peer} ${range}, but ${installed} is installed (${rel(peerDir)}). Install a ${peer} in that range, or a ${copy.name} release built against ${installed}`
4514
+ });
4110
4515
  }
4111
- if (result === "no" && unknown) result = "unknown";
4112
- }
4113
- if (result === "yes" || cut.size === 0) {
4114
- cache.free.set(k, result);
4115
- return [result, /* @__PURE__ */ new Set()];
4116
4516
  }
4117
- const entries = cache.cut.get(k) ?? [];
4118
- entries.push({ cut: [...cut], result });
4119
- cache.cut.set(k, entries);
4120
- return [result, cut];
4121
- };
4122
- return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
4517
+ }
4123
4518
  }
4124
- var TRAIL_DEPTH, RESOLVE_EXTS2, IMPORT_FROM, EXPORT_FROM, DYNAMIC, trails;
4125
- var init_trail = __esm({
4126
- "src/doctor/trail.ts"() {
4519
+ var GENESIS, DEV_TOOLS, NON_SHIPPING, readManifest, real, LOCKFILES;
4520
+ var init_installs = __esm({
4521
+ "src/doctor/installs.ts"() {
4127
4522
  init_genesis();
4128
- init_source();
4129
- TRAIL_DEPTH = 6;
4130
- RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
4131
- IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
4132
- EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
4133
- DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
4134
- trails = /* @__PURE__ */ new WeakMap();
4523
+ init_semver();
4524
+ GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
4525
+ DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
4526
+ 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)$/;
4527
+ readManifest = (dir) => {
4528
+ try {
4529
+ return JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
4530
+ } catch {
4531
+ return null;
4532
+ }
4533
+ };
4534
+ real = (p) => {
4535
+ try {
4536
+ return realpathSync(p);
4537
+ } catch {
4538
+ return p;
4539
+ }
4540
+ };
4541
+ LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
4135
4542
  }
4136
4543
  });
4137
4544
  function routesDir(ctx) {
4138
4545
  if (ctx.config.routesDir) return ctx.config.routesDir;
4139
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path32.join(ctx.root, d))) ?? null;
4546
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path23.join(ctx.root, d))) ?? null;
4140
4547
  }
4141
4548
  function flavorOf(dir, rels) {
4142
4549
  const stems = rels.map((r) => r.split("/").pop());
@@ -4358,10 +4765,10 @@ function checkPageLayouts(ctx) {
4358
4765
  for (const n of namedImportsFrom(code, GENESIS_PACKAGE2)) if (PACKAGE_SCREEN.test(n)) names.add(n);
4359
4766
  return rendersRe(names)?.test(code) ?? false;
4360
4767
  };
4361
- const cache = /* @__PURE__ */ new Map();
4768
+ const cache2 = /* @__PURE__ */ new Map();
4362
4769
  const provides = (r) => {
4363
- if (!cache.has(r)) cache.set(r, routeReach(ctx, r, rendersLayout));
4364
- return cache.get(r);
4770
+ if (!cache2.has(r)) cache2.set(r, routeReach(ctx, r, rendersLayout));
4771
+ return cache2.get(r);
4365
4772
  };
4366
4773
  const list = [...layouts].sort();
4367
4774
  const named = list.length > 4 ? `${list.slice(0, 4).join(", ")}, \u2026` : list.join(", ");
@@ -4455,7 +4862,7 @@ __export(doctor_exports, {
4455
4862
  webRoutes: () => webRoutes
4456
4863
  });
4457
4864
  async function runDoctor(options = {}) {
4458
- const root = path32.resolve(options.root ?? process.cwd());
4865
+ const root = path23.resolve(options.root ?? process.cwd());
4459
4866
  const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
4460
4867
  const config = loaded.config;
4461
4868
  const genesis = options.genesis ?? loadGenesis(root, config);
@@ -4467,7 +4874,7 @@ async function runDoctor(options = {}) {
4467
4874
  if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
4468
4875
  }
4469
4876
  const raw = [];
4470
- const ctx = { root, files, genesis, config, report: (f) => raw.push(f) };
4877
+ const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
4471
4878
  for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
4472
4879
  try {
4473
4880
  await plugin.check(ctx);
@@ -4499,7 +4906,8 @@ async function runDoctor(options = {}) {
4499
4906
  function builtinChecks(config) {
4500
4907
  const packs = {
4501
4908
  native: { name: "native", check: checkNativePack },
4502
- supabase: { name: "supabase", check: checkSupabasePack }
4909
+ supabase: { name: "supabase", check: checkSupabasePack },
4910
+ packages: { name: "packages", check: checkPackagesPack }
4503
4911
  };
4504
4912
  return [
4505
4913
  { name: "layout", check: checkProjectLayout },
@@ -4601,6 +5009,7 @@ var init_doctor = __esm({
4601
5009
  init_rules();
4602
5010
  init_native();
4603
5011
  init_scan();
5012
+ init_packages();
4604
5013
  init_supabase();
4605
5014
  init_versions();
4606
5015
  init_installs();
@@ -4643,20 +5052,20 @@ function readObject(file, key2) {
4643
5052
  }
4644
5053
  }
4645
5054
  function settings(root, options) {
4646
- const fromPackage = readObject(path32.join(root, "package.json"), "genesisFeatures");
4647
- const fromConfig = readObject(path32.join(root, "genesis.config.json"), "features");
5055
+ const fromPackage = readObject(path23.join(root, "package.json"), "genesisFeatures");
5056
+ const fromConfig = readObject(path23.join(root, "genesis.config.json"), "features");
4648
5057
  const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
4649
5058
  return { ...fromPackage, ...fromConfig, ...given };
4650
5059
  }
4651
5060
  async function loadRegistry(input) {
4652
- const root = path32.resolve(input.dir);
5061
+ const root = path23.resolve(input.dir);
4653
5062
  const options = settings(root, input);
4654
- const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path32.join(root, p)));
4655
- if (!registry || !existsSync(path32.join(root, registry))) {
5063
+ const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path23.join(root, p)));
5064
+ if (!registry || !existsSync(path23.join(root, registry))) {
4656
5065
  throw new Error(`No feature registry found. Looked for ${options.registry ?? DEFAULT_REGISTRIES.join(" and ")}; pass --registry.`);
4657
5066
  }
4658
- const jiti = createJiti(path32.join(root, "package.json"), { moduleCache: false });
4659
- const load = async (file) => await jiti.import(path32.join(root, file));
5067
+ const jiti = createJiti(path23.join(root, "package.json"), { moduleCache: false });
5068
+ const load = async (file) => await jiti.import(path23.join(root, file));
4660
5069
  const mod = await load(registry);
4661
5070
  const features2 = mod.features ?? mod.default;
4662
5071
  if (!isObject3(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
@@ -4668,7 +5077,7 @@ async function loadRegistry(input) {
4668
5077
  const project = {
4669
5078
  ...rest,
4670
5079
  root,
4671
- source: options.source ?? registry.split(path32.sep).join("/"),
5080
+ source: options.source ?? registry.split(path23.sep).join("/"),
4672
5081
  features: features2,
4673
5082
  flags
4674
5083
  };
@@ -4778,8 +5187,8 @@ function routeTags(source) {
4778
5187
  }
4779
5188
  function wireStudioRoute(source, route, pageImportPath) {
4780
5189
  const tags = routeTags(source);
4781
- const relative6 = route.replace(/^\//, "");
4782
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative6.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
5190
+ const relative8 = route.replace(/^\//, "");
5191
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative8.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
4783
5192
  if (existing) {
4784
5193
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
4785
5194
  }
@@ -4787,17 +5196,17 @@ function wireStudioRoute(source, route, pageImportPath) {
4787
5196
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
4788
5197
  if (roots.length !== 1) {
4789
5198
  return {
4790
- skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative6}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
5199
+ skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative8}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
4791
5200
  };
4792
5201
  }
4793
5202
  const layout = roots[0];
4794
5203
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
4795
- if (base && !relative6.startsWith(`${base}/`)) {
5204
+ if (base && !relative8.startsWith(`${base}/`)) {
4796
5205
  return {
4797
5206
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
4798
5207
  };
4799
5208
  }
4800
- const childPath = base ? relative6.slice(base.length + 1) : relative6;
5209
+ const childPath = base ? relative8.slice(base.length + 1) : relative8;
4801
5210
  const guard = GUARD.exec(source)?.[1];
4802
5211
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
4803
5212
  const before = source.slice(0, layout.close);
@@ -5175,7 +5584,7 @@ function copyOwned(root, lock, write, dryRun = false) {
5175
5584
  }
5176
5585
  return "kept";
5177
5586
  }
5178
- function ownedKeyProblem(key2, source) {
5587
+ function ownedKeyProblem(key2, source, localNames = /* @__PURE__ */ new Set()) {
5179
5588
  let parsed;
5180
5589
  try {
5181
5590
  parsed = parseSource(source);
@@ -5183,7 +5592,7 @@ function ownedKeyProblem(key2, source) {
5183
5592
  return err instanceof Error ? err.message : String(err);
5184
5593
  }
5185
5594
  const { package: pkg, path: rel } = parsed;
5186
- if (!GENESIS_PACKAGE.test(pkg)) return `${key2}'s source ${pkg} isn't a Genesis package`;
5595
+ if (!GENESIS_PACKAGE.test(pkg) && !localNames.has(pkg)) return `${key2}'s source ${pkg} isn't a Genesis or local package`;
5187
5596
  if (!safeRelative(rel) || !safeRelative(key2)) return `${key2} or its source isn't a plain path`;
5188
5597
  if (key2.startsWith("supabase/migrations/")) return `${key2} is a migration; migrations are never refreshed`;
5189
5598
  const base = rel.split("/").pop();
@@ -5197,9 +5606,9 @@ function ownedKeyProblem(key2, source) {
5197
5606
  return `${key2} doesn't match its source ${source}`;
5198
5607
  }
5199
5608
  function mergeThreeWay(mine, base, theirs) {
5200
- const dir = mkdtempSync(path32.join(tmpdir(), "genesis-merge-"));
5609
+ const dir = mkdtempSync(path23.join(tmpdir(), "genesis-merge-"));
5201
5610
  try {
5202
- const [m, b, t] = ["mine", "base", "theirs"].map((n) => path32.join(dir, n));
5611
+ const [m, b, t] = ["mine", "base", "theirs"].map((n) => path23.join(dir, n));
5203
5612
  writeFileSync(m, mine);
5204
5613
  writeFileSync(b, base);
5205
5614
  writeFileSync(t, theirs);
@@ -5218,7 +5627,7 @@ function mergeThreeWay(mine, base, theirs) {
5218
5627
  function refreshOwned(root, lock, input, options = {}) {
5219
5628
  const entry = lock.files[input.path];
5220
5629
  if (!entry) throw new Error(`${input.path} isn't in genesis.lock.json`);
5221
- const problem = ownedKeyProblem(input.path, entry.source);
5630
+ const problem = ownedKeyProblem(input.path, entry.source, localPackageNames(root));
5222
5631
  if (problem) return { path: input.path, outcome: "refused", detail: `genesis.lock.json: ${problem}; left alone` };
5223
5632
  const write = (rel, text) => {
5224
5633
  if (!options.dryRun) replaceApp(root, rel, text);
@@ -5276,6 +5685,7 @@ var init_owned = __esm({
5276
5685
  "src/blocks/owned.ts"() {
5277
5686
  init_files();
5278
5687
  init_lock();
5688
+ init_local();
5279
5689
  init_manifest();
5280
5690
  CLI = "@marktiderman/genesis-cli";
5281
5691
  }
@@ -5368,12 +5778,12 @@ var init_registry_edit = __esm({
5368
5778
  });
5369
5779
  function routerRoot2(root) {
5370
5780
  try {
5371
- const config = JSON.parse(readFileSync(path32.join(root, "genesis.config.json"), "utf8"));
5781
+ const config = JSON.parse(readFileSync(path23.join(root, "genesis.config.json"), "utf8"));
5372
5782
  const configured = config.doctor?.native?.routerRoot;
5373
- if (configured && existsSync(path32.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
5783
+ if (configured && existsSync(path23.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
5374
5784
  } catch {
5375
5785
  }
5376
- for (const dir of ["src/app", "app"]) if (existsSync(path32.join(root, dir, "_layout.tsx"))) return dir;
5786
+ for (const dir of ["src/app", "app"]) if (existsSync(path23.join(root, dir, "_layout.tsx"))) return dir;
5377
5787
  return null;
5378
5788
  }
5379
5789
  function routeOf(file) {
@@ -5434,7 +5844,7 @@ __export(add_exports, {
5434
5844
  });
5435
5845
  function appDependencies(root) {
5436
5846
  try {
5437
- const pkg = JSON.parse(readFileSync(path32.join(root, "package.json"), "utf8"));
5847
+ const pkg = JSON.parse(readFileSync(path23.join(root, "package.json"), "utf8"));
5438
5848
  return { ...pkg["dependencies"], ...pkg["devDependencies"], ...pkg["optionalDependencies"] };
5439
5849
  } catch {
5440
5850
  return {};
@@ -5443,14 +5853,14 @@ function appDependencies(root) {
5443
5853
  function registryFile(root) {
5444
5854
  const read = (file, key2) => {
5445
5855
  try {
5446
- const v = JSON.parse(readFileSync(path32.join(root, file), "utf8"))[key2]?.registry;
5856
+ const v = JSON.parse(readFileSync(path23.join(root, file), "utf8"))[key2]?.registry;
5447
5857
  return typeof v === "string" ? v : void 0;
5448
5858
  } catch {
5449
5859
  return void 0;
5450
5860
  }
5451
5861
  };
5452
5862
  const named = read("genesis.config.json", "features") ?? read("package.json", "genesisFeatures");
5453
- for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path32.join(root, candidate))) return candidate;
5863
+ for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path23.join(root, candidate))) return candidate;
5454
5864
  return null;
5455
5865
  }
5456
5866
  async function registryIds(root, file) {
@@ -5527,7 +5937,7 @@ verify_jwt = false
5527
5937
  return { content: `${config.replace(/\s*$/, "\n")}${add}`, names };
5528
5938
  }
5529
5939
  async function runAdd(options) {
5530
- const root = path32.resolve(options.root);
5940
+ const root = path23.resolve(options.root);
5531
5941
  const log = options.log ?? SILENT;
5532
5942
  const now = options.now ?? /* @__PURE__ */ new Date();
5533
5943
  const warnings = [];
@@ -5537,8 +5947,9 @@ async function runAdd(options) {
5537
5947
  const deps = appDependencies(root);
5538
5948
  const pm = detectPackageManager(root);
5539
5949
  const specs = [];
5950
+ const local = localPackageNames(root);
5540
5951
  for (const name of found.manifest.packages) {
5541
- if (deps[name]) continue;
5952
+ if (deps[name] || local.has(name)) continue;
5542
5953
  const pin = pinnedVersion(root, name);
5543
5954
  specs.push(pin ? `${name}@${pin.version}` : name);
5544
5955
  }
@@ -5574,7 +5985,7 @@ async function runAdd(options) {
5574
5985
  if (registry) registryEdit2 = addFeatureEntry(readApp(root, registry) ?? "", snippet2);
5575
5986
  }
5576
5987
  const print = (mark, p, note = "") => log.info(` ${mark} ${p}${note ? ` ${note}` : ""}`);
5577
- log.info(`${manifest2.id}: from ${manifest2.package}${manifest2.version ? ` ${manifest2.version}` : ""} (${from === "installed" ? "installed" : "not installed yet: files are read after the install"})`);
5988
+ log.info(`${manifest2.id}: from ${manifest2.package}${manifest2.version ? ` ${manifest2.version}` : ""} (${from === "local" ? "local package" : from === "installed" ? "installed" : "not installed yet: files are read after the install"})`);
5578
5989
  if (command) log.info(` install: ${shellLine(command)}${install ? "" : " (skipped: --no-install)"}`);
5579
5990
  log.info(formatMigrationRows(migrations2.rows).replace(/^/gm, " "));
5580
5991
  for (const c of migrations2.creates) if (c.kind === "test") print("+", c.path, "(pgTAP test)");
@@ -5656,7 +6067,7 @@ ${snippet}`);
5656
6067
  ${snippet}`);
5657
6068
  } else edited.push(registry);
5658
6069
  }
5659
- if (found.from === "installed") lock.blocks[manifest.id] = { package: manifest.package, ...manifest.version ? { version: manifest.version } : {} };
6070
+ if (found.from === "installed" || found.from === "local") lock.blocks[manifest.id] = { package: manifest.package, ...manifest.version ? { version: manifest.version } : {} };
5660
6071
  else steps.unshift(`Install ${manifest.packages.join(" and ")}, then run genesis add ${manifest.id} again to copy its files.`);
5661
6072
  const lockBefore = readApp(root, LOCK_FILE);
5662
6073
  writeLock(root, lock);
@@ -5681,6 +6092,7 @@ function recordOwned(lock, appRel, source, content, root, pkg) {
5681
6092
  var SILENT;
5682
6093
  var init_add = __esm({
5683
6094
  "src/blocks/add.ts"() {
6095
+ init_local();
5684
6096
  init_agents();
5685
6097
  init_discover();
5686
6098
  init_files();
@@ -5702,11 +6114,12 @@ __export(migrate_exports, {
5702
6114
  runMigrate: () => runMigrate
5703
6115
  });
5704
6116
  async function runMigrate(options) {
5705
- const root = path32.resolve(options.root);
6117
+ const root = path23.resolve(options.root);
5706
6118
  const lock = readLock(root);
5707
6119
  const warnings = [];
5708
6120
  const ids = [.../* @__PURE__ */ new Set([...Object.keys(lock.blocks), ...options.blocks ?? []])];
5709
6121
  const sources = [];
6122
+ const local = localPackageNames(root);
5710
6123
  for (const id of ids) {
5711
6124
  const pkg = lock.blocks[id]?.package;
5712
6125
  try {
@@ -5719,8 +6132,8 @@ async function runMigrate(options) {
5719
6132
  for (const copy of readAppMigrations(root)) {
5720
6133
  const t = copy.tracked;
5721
6134
  if (!t || sources.some((s) => s.package === t.package && s.file === t.file)) continue;
5722
- if (!GENESIS_PACKAGE.test(t.package) || !validHeaderFile(t.file)) {
5723
- warnings.push(`${copy.path}: its genesis-migration header names ${t.package} ${t.file}, which isn't a Genesis package's NNNN_name.sql; skipped.`);
6135
+ if (!(GENESIS_PACKAGE.test(t.package) || local.has(t.package)) || !validHeaderFile(t.file)) {
6136
+ warnings.push(`${copy.path}: its genesis-migration header names ${t.package} ${t.file}, which isn't a Genesis or local package's NNNN_name.sql; skipped.`);
5724
6137
  continue;
5725
6138
  }
5726
6139
  const dir = packageDir(root, t.package);
@@ -5744,6 +6157,7 @@ async function runMigrate(options) {
5744
6157
  var init_migrate = __esm({
5745
6158
  "src/blocks/migrate.ts"() {
5746
6159
  init_discover();
6160
+ init_local();
5747
6161
  init_files();
5748
6162
  init_lock();
5749
6163
  init_manifest();
@@ -5862,11 +6276,11 @@ function npmLookup(cwd) {
5862
6276
  if (!EXACT_OR_TAG.test(target)) throw new Error(`--version must be an exact version or a dist-tag, not "${target}"`);
5863
6277
  const version = JSON.parse(npm(["view", `${UMBRELLA}@${target}`, "version", "--json"], cwd) || "null");
5864
6278
  if (typeof version !== "string") throw new Error(`${UMBRELLA}@${target} is not one published version`);
5865
- const tmp = mkdtempSync(path32.join(tmpdir(), "genesis-umbrella-"));
6279
+ const tmp = mkdtempSync(path23.join(tmpdir(), "genesis-umbrella-"));
5866
6280
  try {
5867
6281
  const [packed] = JSON.parse(npm(["pack", `${UMBRELLA}@${version}`, "--pack-destination", tmp, "--json"], cwd));
5868
- execFileSync("tar", ["-xzf", path32.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
5869
- const manifest = JSON.parse(readFileSync(path32.join(tmp, "package/dist/versions.json"), "utf8"));
6282
+ execFileSync("tar", ["-xzf", path23.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
6283
+ const manifest = JSON.parse(readFileSync(path23.join(tmp, "package/dist/versions.json"), "utf8"));
5870
6284
  if (manifest.version !== version) throw new Error(`${UMBRELLA}@${version} ships a versions.json for ${manifest.version}`);
5871
6285
  return manifest;
5872
6286
  } finally {
@@ -5893,7 +6307,7 @@ function packageJsons(root) {
5893
6307
  if (files.length) return files;
5894
6308
  } catch {
5895
6309
  }
5896
- return existsSync(path32.join(root, "package.json")) ? ["package.json"] : [];
6310
+ return existsSync(path23.join(root, "package.json")) ? ["package.json"] : [];
5897
6311
  }
5898
6312
  function sourceText(root, source, substitutions) {
5899
6313
  const { package: pkg, path: rel } = parseSource(source);
@@ -5912,11 +6326,11 @@ function sourceText(root, source, substitutions) {
5912
6326
  }
5913
6327
  }
5914
6328
  async function runUpgrade(options) {
5915
- const root = path32.resolve(options.root);
6329
+ const root = path23.resolve(options.root);
5916
6330
  const log = options.log ?? (() => {
5917
6331
  });
5918
6332
  const lookup = options.lookup ?? npmLookup(root);
5919
- const release = options.manifest ? JSON.parse(readFileSync(path32.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
6333
+ const release = options.manifest ? JSON.parse(readFileSync(path23.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
5920
6334
  const pinned = { [UMBRELLA]: release.version, ...release.packages };
5921
6335
  const wanted = (name) => pinned[name] ?? lookup.latest(name);
5922
6336
  const prBase = options.pr && !options.dryRun ? checkPullRequest(root, release.version) : void 0;
@@ -5938,7 +6352,7 @@ async function runUpgrade(options) {
5938
6352
  checkSubstitutions(lock.substitutions);
5939
6353
  const bases = /* @__PURE__ */ new Map();
5940
6354
  for (const [file, entry] of Object.entries(lock.files)) {
5941
- if (ownedKeyProblem(file, entry.source)) continue;
6355
+ if (ownedKeyProblem(file, entry.source, localPackageNames(root))) continue;
5942
6356
  const text = sourceText(root, entry.source, lock.substitutions);
5943
6357
  if (text !== null && sha256(text) === entry.sha256) bases.set(file, text);
5944
6358
  }
@@ -5986,7 +6400,7 @@ async function runUpgrade(options) {
5986
6400
  refreshed.push({ path: file, outcome: "deferred", detail: "new package migrations are waiting: run genesis migrate, then genesis upgrade again" });
5987
6401
  continue;
5988
6402
  }
5989
- const problem = ownedKeyProblem(file, entry.source);
6403
+ const problem = ownedKeyProblem(file, entry.source, localPackageNames(root));
5990
6404
  const theirs = problem ? null : sourceText(root, entry.source, lock.substitutions);
5991
6405
  const dir = problem ? null : packageDir(root, parseSource(entry.source).package);
5992
6406
  const version = dir ? packageVersion(dir) : void 0;
@@ -6052,7 +6466,7 @@ function checkSubstitutions(substitutions) {
6052
6466
  if (!substitutions || !Object.keys(substitutions).length) return;
6053
6467
  let allowed;
6054
6468
  try {
6055
- const was = starterIdentity(readFileSync(path32.join(starterDir(), "starter.config.ts"), "utf8"));
6469
+ const was = starterIdentity(readFileSync(path23.join(starterDir(), "starter.config.ts"), "utf8"));
6056
6470
  allowed = [was.name, was.slug, was.scheme, was.bundleId];
6057
6471
  } catch {
6058
6472
  allowed = [];
@@ -6064,15 +6478,15 @@ function checkSubstitutions(substitutions) {
6064
6478
  }
6065
6479
  }
6066
6480
  function checkPullRequest(root, version) {
6067
- const git2 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6068
- if (git2("status", "--porcelain")) throw new Error("--pr needs a clean working tree (commit or stash your changes first).");
6069
- const base = git2("rev-parse", "--abbrev-ref", "HEAD");
6481
+ const git3 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6482
+ if (git3("status", "--porcelain")) throw new Error("--pr needs a clean working tree (commit or stash your changes first).");
6483
+ const base = git3("rev-parse", "--abbrev-ref", "HEAD");
6070
6484
  if (base === "HEAD") throw new Error("--pr needs a branch checked out, not a detached HEAD.");
6071
6485
  const branch = `genesis-upgrade/${version}`;
6072
- git2("check-ref-format", "--branch", branch);
6486
+ git3("check-ref-format", "--branch", branch);
6073
6487
  let exists = true;
6074
6488
  try {
6075
- git2("rev-parse", "--verify", "--quiet", `refs/heads/${branch}`);
6489
+ git3("rev-parse", "--verify", "--quiet", `refs/heads/${branch}`);
6076
6490
  } catch {
6077
6491
  exists = false;
6078
6492
  }
@@ -6080,20 +6494,20 @@ function checkPullRequest(root, version) {
6080
6494
  return base;
6081
6495
  }
6082
6496
  function openPullRequest(root, version, report, base) {
6083
- const git2 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6497
+ const git3 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6084
6498
  const branch = `genesis-upgrade/${version}`;
6085
- git2("switch", "-c", branch);
6086
- const top = git2("rev-parse", "--show-toplevel");
6499
+ git3("switch", "-c", branch);
6500
+ const top = git3("rev-parse", "--show-toplevel");
6087
6501
  const lockfiles = [];
6088
- for (let dir = path32.resolve(root); ; dir = path32.dirname(dir)) {
6089
- for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path32.join(dir, f))) lockfiles.push(path32.relative(root, path32.join(dir, f)));
6090
- if (lockfiles.length || dir === top || path32.dirname(dir) === dir) break;
6091
- }
6092
- const paths = [...report.files.filter((f) => existsSync(path32.join(root, f))), ...lockfiles];
6093
- git2("add", "--", ...paths);
6094
- git2("commit", "-q", "-m", `chore(deps): upgrade Genesis to ${version}`);
6095
- git2("push", "-u", "origin", branch);
6096
- const body = path32.join(mkdtempSync(path32.join(tmpdir(), "genesis-pr-")), "body.md");
6502
+ for (let dir = path23.resolve(root); ; dir = path23.dirname(dir)) {
6503
+ for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path23.join(dir, f))) lockfiles.push(path23.relative(root, path23.join(dir, f)));
6504
+ if (lockfiles.length || dir === top || path23.dirname(dir) === dir) break;
6505
+ }
6506
+ const paths = [...report.files.filter((f) => existsSync(path23.join(root, f))), ...lockfiles];
6507
+ git3("add", "--", ...paths);
6508
+ git3("commit", "-q", "-m", `chore(deps): upgrade Genesis to ${version}`);
6509
+ git3("push", "-u", "origin", branch);
6510
+ const body = path23.join(mkdtempSync(path23.join(tmpdir(), "genesis-pr-")), "body.md");
6097
6511
  writeFileSync(body, `${report.summary}
6098
6512
 
6099
6513
  Opened by \`genesis upgrade --pr\`.
@@ -6111,6 +6525,7 @@ var init_upgrade = __esm({
6111
6525
  init_lock();
6112
6526
  init_migrations();
6113
6527
  init_owned();
6528
+ init_local();
6114
6529
  init_pm();
6115
6530
  init_templates();
6116
6531
  init_bump_core();
@@ -6216,9 +6631,9 @@ async function runScaffold(opts, fs2) {
6216
6631
  function joinPath(...parts) {
6217
6632
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
6218
6633
  }
6219
- function dirname(path33) {
6220
- const idx = path33.lastIndexOf("/");
6221
- return idx === -1 ? "." : path33.slice(0, idx);
6634
+ function dirname(path35) {
6635
+ const idx = path35.lastIndexOf("/");
6636
+ return idx === -1 ? "." : path35.slice(0, idx);
6222
6637
  }
6223
6638
  function brandPackageJson(consumer, genesisVersion) {
6224
6639
  return JSON.stringify(
@@ -6412,7 +6827,7 @@ This consumer was bootstrapped with \`@marktiderman/genesis-cli init ${consumer}
6412
6827
 
6413
6828
  ## Workflow
6414
6829
 
6415
- - **Reuse before extend, extend before create.** Before building anything,
6830
+ - **Reuse, then extend, then invent** (the Genesis way). Before building anything,
6416
6831
  run \`npx @marktiderman/genesis-cli features find <term>\` and read
6417
6832
  https://github.com/marktiderman/genesis/blob/main/docs/FRAMEWORK.md
6418
6833
  - **Brand changes live in \`packages/${consumer}-brand\`.** Don't fork Genesis
@@ -6457,7 +6872,7 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
6457
6872
  const { runInitNative: runInitNative2 } = await Promise.resolve().then(() => (init_init_native(), init_native_exports));
6458
6873
  const result2 = await runInitNative2({
6459
6874
  name: consumer,
6460
- target: path32.resolve(opts.target ?? consumer),
6875
+ target: path23.resolve(opts.target ?? consumer),
6461
6876
  ...opts.displayName ? { displayName: opts.displayName } : {},
6462
6877
  ...opts.bundleId ? { bundleId: opts.bundleId } : {},
6463
6878
  ...opts.scheme ? { scheme: opts.scheme } : {}
@@ -6467,7 +6882,7 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
6467
6882
  console.log(` Genesis packages: ${Object.entries(result2.dependencies).map(([n, v]) => `${n}@${v}`).join(", ")}`);
6468
6883
  console.log("");
6469
6884
  console.log("Next steps:");
6470
- [`cd ${path32.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
6885
+ [`cd ${path23.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
6471
6886
  return;
6472
6887
  }
6473
6888
  opts.target ??= process.cwd();
@@ -6533,7 +6948,7 @@ program.command("introspect").description("Write a checked-in contract (resource
6533
6948
  source = `Postgres (${schemas.join(", ")})`;
6534
6949
  }
6535
6950
  const content = emitContracts2(tables, { source });
6536
- const target = path32.resolve(opts.out);
6951
+ const target = path23.resolve(opts.out);
6537
6952
  if (opts.check) {
6538
6953
  const current = await fs.readFile(target, "utf-8").catch(() => null);
6539
6954
  if (current !== content) {
@@ -6546,16 +6961,16 @@ program.command("introspect").description("Write a checked-in contract (resource
6546
6961
  await fs.writeFile(target, content, "utf-8");
6547
6962
  console.log(`\u2714 Wrote ${opts.out}: ${tables.length} tables.`);
6548
6963
  });
6549
- 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).action(async (opts) => {
6964
+ program.command("doctor").description("Check this app against the installed Genesis: components, tokens, imports, colors, plus the app's own rules").option("--strict", "Fail on warnings too", false).option("--json", "Print the report as JSON", false).option("--build", "Also run the app's typecheck and build (doctor.build, or its typecheck/build scripts)", false).option("-c, --config <path>", 'Config file (default: genesis.config.json, then package.json "genesis")').option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--print-genesis", "Print the components, tokens and raw tags read from Genesis, and exit", false).option("--base <ref>", "The git ref change checks compare against (the packages pack's change gate), e.g. origin/main").action(async (opts) => {
6550
6965
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
6551
- const root = path32.resolve(opts.dir);
6966
+ const root = path23.resolve(opts.dir);
6552
6967
  try {
6553
6968
  if (opts.printGenesis) {
6554
6969
  const { config } = doctor.loadConfig(root, opts.config);
6555
6970
  console.log(JSON.stringify(doctor.genesisSummary(doctor.loadGenesis(root, config)), null, 2));
6556
6971
  return;
6557
6972
  }
6558
- const result = await doctor.runDoctor({ root, configPath: opts.config, strict: opts.strict, build: opts.build, quietBuild: opts.json });
6973
+ const result = await doctor.runDoctor({ root, configPath: opts.config, strict: opts.strict, build: opts.build, quietBuild: opts.json, ...opts.base ? { base: opts.base } : {} });
6559
6974
  console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result));
6560
6975
  process.exitCode = result.ok ? 0 : 1;
6561
6976
  } catch (err) {
@@ -6613,24 +7028,24 @@ featureOptions(
6613
7028
  var studio = program.command("studio").description("The Genesis Data Studio");
6614
7029
  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) => {
6615
7030
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
6616
- const root = path32.resolve(opts.dir);
6617
- const packageJson = JSON.parse(await fs.readFile(path32.join(root, "package.json"), "utf-8").catch(() => "{}"));
6618
- const existsSync26 = (await import('fs')).existsSync;
7031
+ const root = path23.resolve(opts.dir);
7032
+ const packageJson = JSON.parse(await fs.readFile(path23.join(root, "package.json"), "utf-8").catch(() => "{}"));
7033
+ const existsSync28 = (await import('fs')).existsSync;
6619
7034
  const readSync = (await import('fs')).readFileSync;
6620
- const readdirSync10 = (await import('fs')).readdirSync;
7035
+ const readdirSync12 = (await import('fs')).readdirSync;
6621
7036
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
6622
7037
  throw new Error("--host must be next, tanstack-start or supabase-function.");
6623
7038
  }
6624
7039
  const plan = planStudioInit2(
6625
7040
  {
6626
7041
  packageJson,
6627
- exists: (p) => existsSync26(path32.join(root, p)),
6628
- read: (p) => existsSync26(path32.join(root, p)) ? readSync(path32.join(root, p), "utf-8") : null,
7042
+ exists: (p) => existsSync28(path23.join(root, p)),
7043
+ read: (p) => existsSync28(path23.join(root, p)) ? readSync(path23.join(root, p), "utf-8") : null,
6629
7044
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
6630
7045
  listDeep: (p) => {
6631
7046
  const out = [];
6632
7047
  const walk2 = (rel) => {
6633
- for (const entry of readdirSync10(path32.join(root, rel), { withFileTypes: true })) {
7048
+ for (const entry of readdirSync12(path23.join(root, rel), { withFileTypes: true })) {
6634
7049
  const child = `${rel}/${entry.name}`;
6635
7050
  if (entry.isDirectory()) walk2(child);
6636
7051
  else out.push(child);
@@ -6644,7 +7059,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
6644
7059
  },
6645
7060
  list: (p) => {
6646
7061
  try {
6647
- return readdirSync10(path32.join(root, p));
7062
+ return readdirSync12(path23.join(root, p));
6648
7063
  } catch {
6649
7064
  return [];
6650
7065
  }
@@ -6653,8 +7068,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
6653
7068
  { host: opts.host, route: opts.route, loginRole: opts.loginRole }
6654
7069
  );
6655
7070
  for (const file of plan.files) {
6656
- const target = path32.join(root, file.path);
6657
- await fs.mkdir(path32.dirname(target), { recursive: true });
7071
+ const target = path23.join(root, file.path);
7072
+ await fs.mkdir(path23.dirname(target), { recursive: true });
6658
7073
  if (file.edit) {
6659
7074
  await fs.writeFile(target, file.content, "utf-8");
6660
7075
  console.log(`~ ${file.path} (${file.edit})`);
@@ -6665,14 +7080,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
6665
7080
  console.log(`+ ${file.path} (appended)`);
6666
7081
  continue;
6667
7082
  }
6668
- if (existsSync26(target) && !opts.force) {
7083
+ if (existsSync28(target) && !opts.force) {
6669
7084
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
6670
7085
  continue;
6671
7086
  }
6672
7087
  await fs.writeFile(target, file.content, "utf-8");
6673
7088
  console.log(`+ ${file.path}`);
6674
7089
  }
6675
- const pm = existsSync26(path32.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync26(path32.join(root, "yarn.lock")) ? "yarn add" : existsSync26(path32.join(root, "bun.lock")) || existsSync26(path32.join(root, "bun.lockb")) ? "bun add" : "npm install";
7090
+ const pm = existsSync28(path23.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync28(path23.join(root, "yarn.lock")) ? "yarn add" : existsSync28(path23.join(root, "bun.lock")) || existsSync28(path23.join(root, "bun.lockb")) ? "bun add" : "npm install";
6676
7091
  console.log("");
6677
7092
  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:`);
6678
7093
  console.log(` 1. ${pm} ${plan.install.join(" ")}`);
@@ -6690,7 +7105,7 @@ async function confirm(question) {
6690
7105
  }
6691
7106
  var logger = { info: (m) => console.log(m), warn: (m) => console.warn(`! ${m}`) };
6692
7107
  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) => {
6693
- const root = path32.resolve(opts.dir);
7108
+ const root = path23.resolve(opts.dir);
6694
7109
  if (opts.list || !block) {
6695
7110
  const { allBlocks: allBlocks2 } = await Promise.resolve().then(() => (init_discover(), discover_exports));
6696
7111
  const { readLock: readLock2 } = await Promise.resolve().then(() => (init_lock(), lock_exports));
@@ -6719,7 +7134,7 @@ program.command("add").description("Add a block (a feature an app adds whole) fr
6719
7134
  program.command("migrate").description("Copy new package migrations of the app's blocks in as new timestamped files; report edited or changed ones (never rewritten)").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--block <id...>", "Also check these blocks (beyond genesis.lock.json's)").option("--dry-run", "Report only", false).option("--forward", "Write a forward migration stub for each edited or changed migration", false).action(async (opts) => {
6720
7135
  const { runMigrate: runMigrate2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
6721
7136
  const { formatMigrationRows: formatMigrationRows2 } = await Promise.resolve().then(() => (init_migrations(), migrations_exports));
6722
- const report = await runMigrate2({ root: path32.resolve(opts.dir), ...opts.block ? { blocks: opts.block } : {}, dryRun: opts.dryRun, forward: opts.forward });
7137
+ const report = await runMigrate2({ root: path23.resolve(opts.dir), ...opts.block ? { blocks: opts.block } : {}, dryRun: opts.dryRun, forward: opts.forward });
6723
7138
  for (const w of report.warnings) logger.warn(w);
6724
7139
  console.log(formatMigrationRows2(report.plan.rows));
6725
7140
  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"})`);
@@ -6734,7 +7149,7 @@ program.command("migrate").description("Copy new package migrations of the app's
6734
7149
  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) => {
6735
7150
  const { runUpgrade: runUpgrade2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
6736
7151
  const report = await runUpgrade2({
6737
- root: path32.resolve(opts.dir),
7152
+ root: path23.resolve(opts.dir),
6738
7153
  version: opts.version,
6739
7154
  ...opts.manifest ? { manifest: opts.manifest } : {},
6740
7155
  dryRun: opts.dryRun,
@@ -6798,7 +7213,7 @@ function redactUrl(location) {
6798
7213
  const url = new URL(location);
6799
7214
  return `${url.origin}${url.pathname}`;
6800
7215
  } catch {
6801
- return path32.basename(location);
7216
+ return path23.basename(location);
6802
7217
  }
6803
7218
  }
6804
7219
  //# sourceMappingURL=cli.js.map