@marktiderman/genesis-cli 1.11.3 → 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/doctor.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import * as path14 from 'path';
2
2
  import { spawnSync } from 'child_process';
3
- import { existsSync, readFileSync, readdirSync, statSync, realpathSync } from 'fs';
4
- import { createRequire } from 'module';
3
+ import { existsSync, readFileSync, readdirSync, statSync, realpathSync, lstatSync } from 'fs';
4
+ import { builtinModules, createRequire } from 'module';
5
+ import 'crypto';
6
+ import { FEATURE_PLATFORMS, defineBlock, BlockError } from '@marktiderman/genesis-features/blocks';
5
7
  import { pathToFileURL } from 'url';
6
8
 
7
9
  // src/doctor/index.ts
@@ -114,16 +116,18 @@ var KNOWN = /* @__PURE__ */ new Set([
114
116
  "packs",
115
117
  "native",
116
118
  "supabase",
119
+ "packages",
117
120
  "routesDir",
118
121
  "$schema",
119
122
  "$comment"
120
123
  ]);
121
124
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
122
125
  var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
123
- var PACKS = /* @__PURE__ */ new Set(["native", "supabase"]);
126
+ var PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
124
127
  var PACK_KEYS = {
125
128
  native: { routerRoot: "path" },
126
- supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" }
129
+ supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
130
+ packages: { base: "string" }
127
131
  };
128
132
  function appPath(v, where, fail) {
129
133
  if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
@@ -362,7 +366,7 @@ function globToRegExp(glob) {
362
366
  }
363
367
  function globMatcher(globs) {
364
368
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
365
- return (path17) => res.some((re) => re.test(path17));
369
+ return (path20) => res.some((re) => re.test(path20));
366
370
  }
367
371
  var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
368
372
  var NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
@@ -588,6 +592,274 @@ function loadPalette(root) {
588
592
  }
589
593
  return [...names].sort();
590
594
  }
595
+ var GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
596
+ var BLOCK_ID = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
597
+ var MIGRATION_FILE = /^(\d{4})_([a-z0-9_]+)\.sql$/;
598
+ var FUNCTION_NAME = /^[a-z0-9][a-z0-9_-]*$/;
599
+ var ROUTE = /^\/(?:[A-Za-z0-9_\-[\]().]+\/?)*$/;
600
+ var INSTALL_SPEC = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9.^~<>=|* -]+)?$/;
601
+ var SECRET = /^[A-Z][A-Z0-9_]*$/;
602
+ var ManifestError = class extends Error {
603
+ constructor(problems) {
604
+ super(`Invalid block manifest:
605
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
606
+ this.problems = problems;
607
+ this.name = "ManifestError";
608
+ }
609
+ problems;
610
+ };
611
+ function safeRelative(value) {
612
+ if (typeof value !== "string" || !value || value.length > 300) return null;
613
+ if (/[\0\\:]/.test(value) || value.startsWith("/") || value.startsWith("~")) return null;
614
+ const segments = value.split("/");
615
+ if (segments.some((s) => s === "" || s === "." || s === ".." || s.startsWith("-"))) return null;
616
+ return value;
617
+ }
618
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
619
+ var strings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
620
+ function parseManifest(home, id, raw, version, options = {}) {
621
+ const problems = [];
622
+ const at = `${home} genesis.blocks.${id}`;
623
+ if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
624
+ if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
625
+ if (!isObject2(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
626
+ const pkgOf = (value, where) => {
627
+ if (value === void 0) return home;
628
+ if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
629
+ problems.push(`${where}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
630
+ return home;
631
+ }
632
+ return value;
633
+ };
634
+ const pathOf = (value, where) => {
635
+ const safe = safeRelative(value);
636
+ if (!safe) problems.push(`${where}: ${JSON.stringify(value)} is not a plain path inside the package`);
637
+ return safe ?? "";
638
+ };
639
+ const list = (key2) => {
640
+ const v = raw[key2];
641
+ if (v === void 0) return [];
642
+ if (!Array.isArray(v)) {
643
+ problems.push(`${at}.${key2}: must be a list`);
644
+ return [];
645
+ }
646
+ return v;
647
+ };
648
+ const requires = list("requires").filter((r) => {
649
+ const ok = typeof r === "string" && BLOCK_ID.test(r);
650
+ if (!ok) problems.push(`${at}.requires: ${JSON.stringify(r)} is not a feature id`);
651
+ return ok;
652
+ });
653
+ let platforms;
654
+ if (raw["platforms"] !== void 0) {
655
+ platforms = list("platforms").filter((p) => {
656
+ const ok = typeof p === "string" && FEATURE_PLATFORMS.includes(p);
657
+ if (!ok) problems.push(`${at}.platforms: ${JSON.stringify(p)} is not one of ${FEATURE_PLATFORMS.join(", ")}`);
658
+ return ok;
659
+ });
660
+ }
661
+ const packages = list("packages").map((p, i) => pkgOf(p, `${at}.packages[${i}]`));
662
+ const install = list("install").filter((s) => {
663
+ const ok = typeof s === "string" && INSTALL_SPEC.test(s) && !s.startsWith("-");
664
+ if (!ok) problems.push(`${at}.install: ${JSON.stringify(s)} is not a package name with an optional range`);
665
+ return ok;
666
+ });
667
+ const migrations = list("migrations").map((m, i) => {
668
+ const where = `${at}.migrations[${i}]`;
669
+ if (!isObject2(m)) {
670
+ problems.push(`${where}: must be an object`);
671
+ return { package: home, file: "" };
672
+ }
673
+ const file = pathOf(m["file"], `${where}.file`);
674
+ if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
675
+ const out = { package: pkgOf(m["package"], where), file };
676
+ if (m["test"] !== void 0) {
677
+ out.test = pathOf(m["test"], `${where}.test`);
678
+ if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
679
+ }
680
+ return out;
681
+ });
682
+ const functions = list("functions").map((f, i) => {
683
+ const where = `${at}.functions[${i}]`;
684
+ if (!isObject2(f)) {
685
+ problems.push(`${where}: must be an object`);
686
+ return { package: home, dir: "" };
687
+ }
688
+ const dir = pathOf(f["dir"], `${where}.dir`);
689
+ if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
690
+ const out = { package: pkgOf(f["package"], where), dir };
691
+ if (f["verifyJwt"] !== void 0) {
692
+ if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where}.verifyJwt: must be true or false`);
693
+ else out.verifyJwt = f["verifyJwt"];
694
+ }
695
+ if (f["secrets"] !== void 0) {
696
+ if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where}.secrets: must be a list of UPPER_CASE names`);
697
+ else out.secrets = f["secrets"];
698
+ }
699
+ return out;
700
+ });
701
+ const routes = list("routes").map((r, i) => {
702
+ const where = `${at}.routes[${i}]`;
703
+ if (!isObject2(r) || typeof r["path"] !== "string" || !ROUTE.test(r["path"]) || r["path"].split("/").includes("..")) {
704
+ problems.push(`${where}: needs a path like /settings/notifications`);
705
+ return { path: "/" };
706
+ }
707
+ const out = { path: r["path"] };
708
+ if (typeof r["description"] === "string") out.description = r["description"];
709
+ if (typeof r["signedIn"] === "boolean") out.signedIn = r["signedIn"];
710
+ return out;
711
+ });
712
+ const skills = list("skills").map((s, i) => {
713
+ if (isObject2(s)) return { package: pkgOf(s["package"], `${at}.skills[${i}]`), path: pathOf(s["path"], `${at}.skills[${i}].path`) };
714
+ return { package: home, path: pathOf(s, `${at}.skills[${i}]`) };
715
+ });
716
+ for (const s of skills) if (s.path && !s.path.endsWith("SKILL.md")) problems.push(`${at}.skills: "${s.path}" must point at a SKILL.md`);
717
+ let agents;
718
+ if (raw["agents"] !== void 0) {
719
+ const a = raw["agents"];
720
+ agents = isObject2(a) ? { package: pkgOf(a["package"], `${at}.agents`), path: pathOf(a["path"], `${at}.agents.path`) } : { package: home, path: pathOf(a, `${at}.agents`) };
721
+ if (agents.path && !agents.path.endsWith(".md")) problems.push(`${at}.agents: "${agents.path}" must be a Markdown file`);
722
+ }
723
+ let feature;
724
+ if (raw["feature"] !== void 0) {
725
+ const f = raw["feature"];
726
+ if (!isObject2(f) || typeof f["name"] !== "string" || typeof f["summary"] !== "string") problems.push(`${at}.feature: needs a name and a summary`);
727
+ else {
728
+ feature = { name: f["name"], summary: f["summary"] };
729
+ if (typeof f["layer"] === "string") feature.layer = f["layer"];
730
+ if (strings(f["keywords"])) feature.keywords = f["keywords"];
731
+ if (strings(f["audience"])) feature.audience = f["audience"];
732
+ }
733
+ }
734
+ const steps = list("steps").filter((s) => {
735
+ if (typeof s !== "string") problems.push(`${at}.steps: every step is a sentence`);
736
+ return typeof s === "string";
737
+ });
738
+ const privacy = isObject2(raw["privacy"]) ? raw["privacy"] : void 0;
739
+ try {
740
+ const def = { id, requires, contributes: { routes, migrations: migrations.filter((m) => m.file), skills: skills.map((s) => s.path).filter(Boolean), ...privacy ? { privacy } : {} } };
741
+ if (platforms) def.platforms = platforms;
742
+ defineBlock(def);
743
+ } catch (err) {
744
+ if (err instanceof BlockError) problems.push(...err.problems.map((p) => `${at}: ${p}`));
745
+ else throw err;
746
+ }
747
+ if (problems.length) throw new ManifestError(problems);
748
+ return {
749
+ id,
750
+ package: home,
751
+ ...version ? { version } : {},
752
+ requires,
753
+ ...platforms ? { platforms } : {},
754
+ packages: packages.length ? [...new Set(packages)] : [home],
755
+ install,
756
+ migrations,
757
+ functions,
758
+ routes,
759
+ skills,
760
+ ...agents ? { agents } : {},
761
+ ...feature ? { feature } : {},
762
+ steps,
763
+ ...privacy ? { privacy } : {}
764
+ };
765
+ }
766
+ function rawBlocksOf(packageJson) {
767
+ if (!isObject2(packageJson) || !isObject2(packageJson["genesis"])) return {};
768
+ const blocks = packageJson["genesis"]["blocks"];
769
+ return isObject2(blocks) ? blocks : {};
770
+ }
771
+
772
+ // src/blocks/files.ts
773
+ function inside(parent, child) {
774
+ const rel = path14.relative(parent, child);
775
+ return rel === "" || !rel.startsWith("..") && !path14.isAbsolute(rel);
776
+ }
777
+
778
+ // src/blocks/local.ts
779
+ var LOCAL_PACKAGES_KEY = "localPackages";
780
+ var LocalPackagesError = class extends Error {
781
+ name = "LocalPackagesError";
782
+ };
783
+ function validateLocalPackages(raw, source = "genesis.config.json") {
784
+ if (!Array.isArray(raw)) throw new LocalPackagesError(`${source}: ${LOCAL_PACKAGES_KEY} must be a list of folders`);
785
+ return raw.map((entry, i) => {
786
+ const where = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
787
+ if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where} must be a non-empty folder`);
788
+ if (path14.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where} must be relative to the app ("${entry}")`);
789
+ const norm = path14.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
790
+ if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where} must name a package folder, not the app or a parent of it ("${entry}")`);
791
+ const parts = norm.split("/");
792
+ if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
793
+ throw new LocalPackagesError(`${where}: only a final "/*" is supported ("${entry}")`);
794
+ }
795
+ if (parts.includes("node_modules")) throw new LocalPackagesError(`${where} can't point into node_modules ("${entry}")`);
796
+ return norm;
797
+ });
798
+ }
799
+ function localPackageGlobs(root) {
800
+ const file = path14.join(root, "genesis.config.json");
801
+ if (!existsSync(file)) return [];
802
+ let raw;
803
+ try {
804
+ raw = JSON.parse(readFileSync(file, "utf8"));
805
+ } catch (err) {
806
+ throw new LocalPackagesError(`${file} is not valid JSON: ${err.message}`);
807
+ }
808
+ const value = raw && typeof raw === "object" ? raw[LOCAL_PACKAGES_KEY] : void 0;
809
+ return value === void 0 ? [] : validateLocalPackages(value, file);
810
+ }
811
+ var cache = /* @__PURE__ */ new Map();
812
+ function repositoryRoot(appRoot) {
813
+ for (let dir = appRoot; ; ) {
814
+ if (existsSync(path14.join(dir, ".git"))) return dir;
815
+ const parent = path14.dirname(dir);
816
+ if (parent === dir) return appRoot;
817
+ dir = parent;
818
+ }
819
+ }
820
+ function localPackages(root) {
821
+ const appRoot = path14.resolve(root);
822
+ const globs = localPackageGlobs(appRoot);
823
+ const key2 = `${appRoot}
824
+ ${globs.join("\n")}`;
825
+ const hit = cache.get(key2);
826
+ if (hit) return hit;
827
+ const dirs = /* @__PURE__ */ new Set();
828
+ for (const glob of globs) {
829
+ if (glob.endsWith("/*") || glob === "*") {
830
+ const parent = path14.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
831
+ if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
832
+ for (const entry of readdirSync(parent).sort()) {
833
+ if (entry.startsWith(".") || entry === "node_modules") continue;
834
+ dirs.add(path14.join(parent, entry));
835
+ }
836
+ } else {
837
+ dirs.add(path14.join(appRoot, glob));
838
+ }
839
+ }
840
+ const real2 = realpathSync(repositoryRoot(appRoot));
841
+ const out = [];
842
+ const byName = /* @__PURE__ */ new Map();
843
+ for (const dir of [...dirs].sort()) {
844
+ const manifest = path14.join(dir, "package.json");
845
+ if (!existsSync(manifest)) continue;
846
+ if (!inside(real2, realpathSync(dir))) continue;
847
+ let pkg;
848
+ try {
849
+ pkg = JSON.parse(readFileSync(manifest, "utf8"));
850
+ } catch {
851
+ continue;
852
+ }
853
+ if (typeof pkg.name !== "string" || !pkg.name) continue;
854
+ const rel = path14.relative(appRoot, dir).split(path14.sep).join("/");
855
+ const other = byName.get(pkg.name);
856
+ if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
857
+ byName.set(pkg.name, rel);
858
+ out.push({ name: pkg.name, dir, rel, ...typeof pkg.version === "string" ? { version: pkg.version } : {} });
859
+ }
860
+ cache.set(key2, out);
861
+ return out;
862
+ }
591
863
 
592
864
  // ../../scripts/lib/color-literals.mjs
593
865
  var LINE_COMMENT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".jsx", ".js", ".mjs", ".cjs", ".scss", ".less"]);
@@ -795,6 +1067,13 @@ function scanFiles(root, config) {
795
1067
  if (statSync(abs).isDirectory()) walk(abs);
796
1068
  else visit(abs);
797
1069
  }
1070
+ let local = [];
1071
+ try {
1072
+ local = localPackages(root);
1073
+ } catch {
1074
+ local = [];
1075
+ }
1076
+ for (const pkg of local) walk(pkg.dir);
798
1077
  return files;
799
1078
  }
800
1079
  function lineAt(text, index) {
@@ -967,7 +1246,18 @@ var BUILTIN_RULES = [
967
1246
  "migration-definer-search-path",
968
1247
  "migration-edited",
969
1248
  "migration-testing-kit",
970
- "migration-view-rls"
1249
+ "migration-view-rls",
1250
+ // packages pack
1251
+ "package-app-import",
1252
+ "package-undeclared-dependency",
1253
+ "package-migration-test",
1254
+ "package-migration-number",
1255
+ "package-migration-edited",
1256
+ "package-unregistered",
1257
+ "package-unversioned-change",
1258
+ "package-export-missing",
1259
+ "package-block-invalid",
1260
+ "package-untagged-tests"
971
1261
  ];
972
1262
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
973
1263
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -1590,1134 +1880,1407 @@ function checkStoreReadiness(ctx) {
1590
1880
  });
1591
1881
  }
1592
1882
  }
1593
- var DEFAULT_MIGRATIONS = "supabase/migrations";
1594
- var DEFAULT_BASE = "origin/main";
1595
- var DEFAULT_EXPOSED = ["public"];
1596
- function sqlStatements(text) {
1597
- const out = [];
1598
- let buf = "";
1599
- let bodies = [];
1600
- let line = 1;
1601
- let start = 0;
1602
- const flush = () => {
1603
- const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
1604
- if (sql) out.push({ sql, line: start, bodies });
1605
- buf = "";
1606
- bodies = [];
1607
- start = 0;
1608
- };
1609
- const put = (s) => {
1610
- if (!start && /\S/.test(s)) start = line;
1611
- buf += s;
1612
- };
1613
- let i = 0;
1614
- while (i < text.length) {
1615
- const ch = text[i];
1616
- const two = text.slice(i, i + 2);
1617
- if (ch === "\n") {
1618
- buf += " ";
1619
- line++;
1620
- i++;
1621
- } else if (two === "--") {
1622
- while (i < text.length && text[i] !== "\n") i++;
1623
- } else if (two === "/*") {
1624
- let depth = 0;
1625
- while (i < text.length) {
1626
- if (text.startsWith("/*", i)) {
1627
- depth++;
1628
- i += 2;
1629
- } else if (text.startsWith("*/", i)) {
1630
- depth--;
1631
- i += 2;
1632
- if (depth === 0) break;
1633
- } else {
1634
- if (text[i] === "\n") line++;
1635
- i++;
1636
- }
1637
- }
1638
- buf += " ";
1639
- } else if (ch === "'") {
1640
- const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
1641
- put("'");
1642
- i++;
1643
- while (i < text.length) {
1644
- if (escapes && text[i] === "\\") i += 2;
1645
- else if (text[i] === "'" && text[i + 1] === "'") i += 2;
1646
- else if (text[i] === "'") break;
1647
- else {
1648
- if (text[i] === "\n") line++;
1649
- i++;
1650
- }
1651
- }
1652
- put("'");
1653
- i++;
1654
- } else if (ch === '"') {
1655
- i++;
1656
- while (i < text.length && text[i] !== '"') put(text[i++]);
1657
- i++;
1658
- } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
1659
- const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
1660
- const end = text.indexOf(tag, i + tag.length);
1661
- const stop = end === -1 ? text.length : end + tag.length;
1662
- bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
1663
- for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
1664
- put(`${tag} ${tag}`);
1665
- i = stop;
1666
- } else if (ch === ";") {
1667
- flush();
1668
- i++;
1669
- } else {
1670
- put(ch);
1671
- i++;
1672
- }
1673
- }
1674
- flush();
1675
- return out;
1883
+
1884
+ // src/doctor/semver.ts
1885
+ var VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
1886
+ function parseVersion(v) {
1887
+ const m = VERSION.exec(v.trim());
1888
+ return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
1676
1889
  }
1677
- function qualify(name) {
1678
- const n = name.trim().toLowerCase();
1679
- return n.includes(".") ? n : `public.${n}`;
1890
+ function compareVersions(a, b) {
1891
+ for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
1892
+ if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
1893
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
1894
+ const x = a.pre[i];
1895
+ const y = b.pre[i];
1896
+ if (x === void 0) return -1;
1897
+ if (y === void 0) return 1;
1898
+ if (x === y) continue;
1899
+ const nx = /^\d+$/.test(x);
1900
+ const ny = /^\d+$/.test(y);
1901
+ if (nx && ny) return +x < +y ? -1 : 1;
1902
+ if (nx !== ny) return nx ? -1 : 1;
1903
+ return x < y ? -1 : 1;
1904
+ }
1905
+ return 0;
1680
1906
  }
1681
- var schemaOf = (name) => name.split(".")[0];
1682
- function parenthesized(sql, open) {
1683
- let depth = 0;
1684
- for (let k = open; k < sql.length; k++) {
1685
- if (sql[k] === "(") depth++;
1686
- else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
1907
+ function partial(s) {
1908
+ const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
1909
+ if (!m) return null;
1910
+ const nums = [];
1911
+ let wild = false;
1912
+ for (const part of [m[1], m[2], m[3]]) {
1913
+ if (wild || part === void 0 || /^[xX*]$/.test(part)) {
1914
+ wild = true;
1915
+ nums.push(null);
1916
+ } else nums.push(+part);
1687
1917
  }
1688
- return { inner: sql.slice(open + 1), end: sql.length };
1918
+ return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
1689
1919
  }
1690
- function stripParens(s) {
1691
- let out = "";
1692
- let depth = 0;
1693
- for (const c of s) {
1694
- if (c === "(") depth++;
1695
- else if (c === ")") depth = Math.max(0, depth - 1);
1696
- else if (depth === 0) out += c;
1920
+ var ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
1921
+ function comparators(token) {
1922
+ const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
1923
+ if (!m) return null;
1924
+ const op = m[1] ?? "";
1925
+ const p = partial(m[2]);
1926
+ if (!p) return null;
1927
+ const [major, mi, pa] = p.nums;
1928
+ if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
1929
+ const M = major;
1930
+ const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
1931
+ 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"]);
1932
+ const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
1933
+ const out = switchOp();
1934
+ if (p.pre.length) {
1935
+ for (const c of out) if (c.v === lo) c.pre = true;
1697
1936
  }
1698
1937
  return out;
1699
- }
1700
- function splitTop(s) {
1701
- const parts = [];
1702
- let depth = 0;
1703
- let cur = "";
1704
- for (const c of s) {
1705
- if (c === "(") depth++;
1706
- if (c === ")") depth--;
1707
- if (c === "," && depth === 0) {
1708
- parts.push(cur);
1709
- cur = "";
1710
- } else cur += c;
1938
+ function switchOp() {
1939
+ switch (op) {
1940
+ case "^": {
1941
+ const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
1942
+ return [
1943
+ { op: ">=", v: lo },
1944
+ { op: "<", v: bound }
1945
+ ];
1946
+ }
1947
+ case "~":
1948
+ case "~>":
1949
+ return [
1950
+ { op: ">=", v: lo },
1951
+ { op: "<", v: mi === null ? next("major") : next("minor") }
1952
+ ];
1953
+ case ">":
1954
+ return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
1955
+ case ">=":
1956
+ return [{ op: ">=", v: lo }];
1957
+ case "<":
1958
+ return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
1959
+ case "<=":
1960
+ return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
1961
+ default:
1962
+ return upper ? [
1963
+ { op: ">=", v: lo },
1964
+ { op: "<", v: upper }
1965
+ ] : [{ op: "=", v: lo }];
1966
+ }
1711
1967
  }
1712
- if (cur.trim()) parts.push(cur);
1713
- return parts.map((p) => p.trim()).filter(Boolean);
1714
1968
  }
1715
- var TYPE_ALIASES = {
1716
- int: "integer",
1717
- int4: "integer",
1718
- int8: "bigint",
1719
- int2: "smallint",
1720
- bool: "boolean",
1721
- varchar: "character varying",
1722
- timestamptz: "timestamp with time zone",
1723
- float8: "double precision"
1724
- };
1725
- var MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
1726
- function argTypes(args) {
1727
- const types = [];
1728
- for (const raw of splitTop(args)) {
1729
- let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
1730
- const mode = tokens[0];
1731
- if (mode === "out") continue;
1732
- if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
1733
- const joined = tokens.join(" ");
1734
- const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
1735
- types.push(TYPE_ALIASES[type] ?? type);
1736
- }
1737
- return types;
1738
- }
1739
- function git(root, args) {
1740
- const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
1741
- return r.status === 0 ? r.stdout : null;
1969
+ function test(c, v) {
1970
+ const d = compareVersions(v, c.v);
1971
+ return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
1742
1972
  }
1743
- function gitView(root, dir, base) {
1744
- if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
1745
- if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
1746
- return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
1747
- }
1748
- const mergeBase = git(root, ["merge-base", "HEAD", base])?.trim();
1749
- if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
1750
- const diff = git(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
1751
- const untracked = git(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
1752
- if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
1753
- const sql = (p) => p !== void 0 && p.endsWith(".sql");
1754
- const touched = new Set(untracked.split("\n").filter(sql));
1755
- const edited = [];
1756
- for (const row of diff.split("\n").filter(Boolean)) {
1757
- const [status, a, b] = row.split(" ");
1758
- if (status.startsWith("R")) {
1759
- if (sql(b)) touched.add(b);
1760
- if (sql(a)) edited.push({ file: a, status: "renamed" });
1973
+ function parseRange(range) {
1974
+ const alts = [];
1975
+ for (const raw of range.trim().split("||")) {
1976
+ const alt = raw.trim();
1977
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
1978
+ if (hyphen) {
1979
+ const from = comparators(`>=${hyphen[1]}`);
1980
+ const to = comparators(`<=${hyphen[2]}`);
1981
+ if (!from || !to) return null;
1982
+ alts.push([...from, ...to]);
1761
1983
  continue;
1762
1984
  }
1763
- if (!sql(a)) continue;
1764
- if (status.startsWith("A")) touched.add(a);
1765
- else if (status.startsWith("M") || status.startsWith("T")) {
1766
- touched.add(a);
1767
- edited.push({ file: a, status: "modified" });
1768
- } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
1769
- }
1770
- return { touched, edited };
1771
- }
1772
- function checkSupabasePack(ctx) {
1773
- const settings = ctx.config.supabase ?? {};
1774
- const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
1775
- const abs = path14.join(ctx.root, dir);
1776
- if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
1777
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
1778
- const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
1779
- const base = settings.base ?? DEFAULT_BASE;
1780
- const view = gitView(ctx.root, dir, base);
1781
- if ("reason" in view) {
1782
- if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
1783
- } else {
1784
- for (const e of view.edited) {
1785
- ctx.report({
1786
- rule: "migration-edited",
1787
- file: e.file,
1788
- subject: e.file,
1789
- 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`
1790
- });
1985
+ const set = [];
1986
+ for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
1987
+ const cs = comparators(token);
1988
+ if (!cs) return null;
1989
+ set.push(...cs);
1791
1990
  }
1991
+ alts.push(set);
1792
1992
  }
1793
- const since = settings.since;
1794
- const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
1795
- if ("reason" in view && since === void 0) {
1796
- ctx.report({
1797
- rule: "migration-grants",
1798
- level: "warn",
1799
- file: dir,
1800
- 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`
1801
- });
1802
- } else {
1803
- const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
1804
- checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
1805
- }
1806
- checkRls(ctx, migrations, exposed);
1807
- checkViewInvoker(ctx, migrations, exposed);
1808
- checkDefinerSearchPath(ctx, migrations);
1809
- checkTestingKit(ctx, migrations);
1810
- }
1811
- function checkTestingKit(ctx, migrations) {
1812
- for (const { file, statements } of migrations) {
1813
- const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
1814
- if (!hit) continue;
1815
- ctx.report({
1816
- rule: "migration-testing-kit",
1817
- file,
1818
- line: hit.line,
1819
- subject: "genesis_testing",
1820
- message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
1821
- });
1822
- }
1993
+ return alts;
1823
1994
  }
1824
- function granteesOf(s) {
1825
- return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
1995
+ function satisfies(version, range) {
1996
+ const v = parseVersion(version);
1997
+ const alts = parseRange(range);
1998
+ if (!v || !alts) return null;
1999
+ return alts.some(
2000
+ (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))
2001
+ );
1826
2002
  }
1827
- function checkGrants(ctx, migrations, exposed) {
1828
- const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
1829
- const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
1830
- const blanket = (roles) => {
1831
- const o = open(roles);
1832
- if (o.length) return { level: "error", who: o.join(" and ") };
1833
- if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
1834
- return null;
2003
+ var TRAIL_DEPTH = 6;
2004
+ var RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
2005
+ var IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
2006
+ var EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
2007
+ var DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
2008
+ function stripForImports(code) {
2009
+ const out = [];
2010
+ const blank = (ch) => ch === "\n" ? "\n" : " ";
2011
+ const n = code.length;
2012
+ const templates = [];
2013
+ let depth = 0;
2014
+ let i = 0;
2015
+ let sure = true;
2016
+ const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
2017
+ const before = () => out.slice(-24).join("");
2018
+ const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
2019
+ const startsExpression = (b) => {
2020
+ const t = b.replace(/\s+$/, "");
2021
+ if (!t) return true;
2022
+ if (KEYWORD.test(b)) return true;
2023
+ return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
1835
2024
  };
1836
- for (const { file, statements } of migrations) {
1837
- for (const { sql, line } of statements) {
1838
- const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
1839
- if (all) {
1840
- const hit = blanket(granteesOf(all[1]));
1841
- if (hit) {
1842
- 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}` });
1843
- }
1844
- continue;
1845
- }
1846
- const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
1847
- if (defaults) {
1848
- const hit = blanket(granteesOf(defaults[1]));
1849
- if (hit) {
1850
- 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}` });
1851
- }
1852
- continue;
2025
+ const exprStart = () => startsExpression(before());
2026
+ const taggedTemplate = () => {
2027
+ const b = out.slice(-48).join("");
2028
+ const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
2029
+ return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
2030
+ };
2031
+ const templateBody = () => {
2032
+ while (i < n) {
2033
+ const ch = code[i];
2034
+ if (ch === "\\") {
2035
+ out.push(" ", blank(code[i + 1] ?? ""));
2036
+ i += 2;
2037
+ } else if (ch === "`") {
2038
+ out.push("`");
2039
+ i++;
2040
+ return;
2041
+ } else if (ch === "$" && code[i + 1] === "{") {
2042
+ out.push("${");
2043
+ i += 2;
2044
+ templates.push(depth);
2045
+ depth++;
2046
+ return;
2047
+ } else {
2048
+ out.push(blank(ch));
2049
+ i++;
1853
2050
  }
1854
- const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
1855
- if (fn) {
1856
- const roles = open(granteesOf(fn[2]));
1857
- if (!roles.length) continue;
1858
- for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
1859
- if (exposed.has(schemaOf(name))) continue;
1860
- ctx.report({
1861
- rule: "migration-grants",
1862
- file,
1863
- line,
1864
- subject: name,
1865
- 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)`
1866
- });
1867
- }
1868
- continue;
2051
+ }
2052
+ sure = false;
2053
+ };
2054
+ while (i < n && sure) {
2055
+ const ch = code[i];
2056
+ const next = code[i + 1];
2057
+ if (ch === "/" && next === "/") {
2058
+ while (i < n && code[i] !== "\n") {
2059
+ out.push(" ");
2060
+ i++;
1869
2061
  }
1870
- const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
1871
- if (schema) {
1872
- const roles = open(granteesOf(schema[2]));
1873
- if (!roles.length) continue;
1874
- for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
1875
- if (exposed.has(s)) continue;
1876
- ctx.report({
1877
- rule: "migration-grants",
1878
- file,
1879
- line,
1880
- subject: `schema ${s}`,
1881
- message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
1882
- });
1883
- }
2062
+ } else if (ch === "/" && next === "*") {
2063
+ out.push(" ");
2064
+ i += 2;
2065
+ while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
2066
+ out.push(blank(code[i]));
2067
+ i++;
1884
2068
  }
1885
- }
1886
- }
1887
- }
1888
- function checkRls(ctx, migrations, exposed) {
1889
- const tables = /* @__PURE__ */ new Map();
1890
- const name = String.raw`([\w$.]+)`;
1891
- const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
1892
- for (const { file, statements } of migrations) {
1893
- for (const { sql, line, bodies } of statements) {
1894
- if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
1895
- const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
1896
- if (create) {
1897
- if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
1898
- continue;
2069
+ if (i < n) {
2070
+ out.push(" ");
2071
+ i += 2;
1899
2072
  }
1900
- const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
1901
- const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
1902
- if (rename || move) {
1903
- const from = qualify((rename ?? move)[1]);
1904
- const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
1905
- const state = tables.get(from);
1906
- if (state) {
1907
- tables.delete(from);
1908
- tables.set(to, state);
2073
+ } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
2074
+ const afterBrace = /[}>]\s*$/.test(before());
2075
+ const start = i;
2076
+ const mark = out.length;
2077
+ out.push("/");
2078
+ i++;
2079
+ let inClass = false;
2080
+ for (; ; ) {
2081
+ const c = code[i];
2082
+ if (c === void 0 || c === "\n") {
2083
+ if (afterBrace) {
2084
+ out.length = mark;
2085
+ out.push("/");
2086
+ i = start + 1;
2087
+ } else sure = false;
2088
+ break;
1909
2089
  }
1910
- continue;
2090
+ if (c === "\\") {
2091
+ out.push(" ", blank(code[i + 1] ?? ""));
2092
+ i += 2;
2093
+ continue;
2094
+ }
2095
+ i++;
2096
+ if (c === "[") inClass = true;
2097
+ else if (c === "]") inClass = false;
2098
+ else if (c === "/" && !inClass) {
2099
+ if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
2100
+ out.length = mark;
2101
+ out.push("/");
2102
+ i = start + 1;
2103
+ break;
2104
+ }
2105
+ out.push("/");
2106
+ break;
2107
+ }
2108
+ out.push(" ");
1911
2109
  }
1912
- const alter = new RegExp(target).exec(sql);
1913
- if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
1914
- const t = qualify(alter[1]);
1915
- if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
1916
- else {
1917
- const state = tables.get(t);
1918
- if (state) state.rls = true;
2110
+ if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
2111
+ } else if ((ch === '"' || ch === "'") && exprStart()) {
2112
+ const keep = isSpecifier();
2113
+ out.push(ch);
2114
+ i++;
2115
+ while (i < n && code[i] !== ch && code[i] !== "\n") {
2116
+ if (code[i] === "\\") {
2117
+ out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
2118
+ i += 2;
2119
+ } else {
2120
+ out.push(keep ? code[i] : blank(code[i]));
2121
+ i++;
1919
2122
  }
1920
- continue;
1921
2123
  }
1922
- const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
1923
- if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
2124
+ if (code[i] !== ch) sure = false;
2125
+ else {
2126
+ out.push(code[i]);
2127
+ i++;
2128
+ }
2129
+ } else if (ch === "`" && (exprStart() || taggedTemplate())) {
2130
+ out.push("`");
2131
+ i++;
2132
+ templateBody();
2133
+ } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
2134
+ templates.pop();
2135
+ depth--;
2136
+ out.push("}");
2137
+ i++;
2138
+ templateBody();
2139
+ } else {
2140
+ if (ch === "{") depth++;
2141
+ else if (ch === "}") depth--;
2142
+ out.push(ch);
2143
+ i++;
1924
2144
  }
1925
2145
  }
1926
- for (const [t, at] of tables) {
1927
- if (at.rls || !exposed.has(schemaOf(t))) continue;
1928
- ctx.report({
1929
- rule: "migration-rls",
1930
- file: at.file,
1931
- line: at.line,
1932
- subject: t,
1933
- 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`
1934
- });
1935
- }
2146
+ return sure && templates.length === 0 ? out.join("") : null;
1936
2147
  }
1937
- function checkViewInvoker(ctx, migrations, exposed) {
1938
- const views = /* @__PURE__ */ new Map();
1939
- const name = String.raw`([\w$.]+)`;
1940
- const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
1941
- for (const { file, statements } of migrations) {
1942
- for (const { sql, line } of statements) {
1943
- const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
1944
- if (create) {
1945
- if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
1946
- const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
1947
- views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
1948
- continue;
1949
- }
1950
- const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
1951
- if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
1952
- const state = views.get(qualify(alter[1]));
1953
- if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
1954
- continue;
1955
- }
1956
- const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
1957
- if (rename) {
1958
- const from = qualify(rename[1]);
1959
- const state = views.get(from);
1960
- if (state) {
1961
- views.delete(from);
1962
- views.set(`${schemaOf(from)}.${rename[2]}`, state);
1963
- }
1964
- continue;
1965
- }
1966
- const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
1967
- if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
1968
- }
2148
+ function bindings(clause) {
2149
+ const out = [];
2150
+ const named = /\{([^}]*)\}/.exec(clause);
2151
+ for (const part of named?.[1].split(",") ?? []) {
2152
+ const p = part.trim();
2153
+ if (!p || p.startsWith("type ")) continue;
2154
+ out.push(p.split(/\s+as\s+/).pop().trim());
1969
2155
  }
1970
- for (const [v, at] of views) {
1971
- if (at.invoker || !exposed.has(schemaOf(v))) continue;
1972
- ctx.report({
1973
- rule: "migration-view-rls",
1974
- file: at.file,
1975
- line: at.line,
1976
- subject: v,
1977
- 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);"`
1978
- });
2156
+ const rest = clause.replace(/\{[^}]*\}/, "");
2157
+ const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
2158
+ if (ns) out.push(ns[1]);
2159
+ const def = /^\s*([\w$]+)/.exec(rest);
2160
+ if (def && def[1] !== "as") out.push(def[1]);
2161
+ return out;
2162
+ }
2163
+ function readJsonc(file) {
2164
+ try {
2165
+ const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
2166
+ return JSON.parse(text);
2167
+ } catch {
2168
+ return null;
1979
2169
  }
1980
2170
  }
1981
- function checkDefinerSearchPath(ctx, migrations) {
1982
- const fns = /* @__PURE__ */ new Map();
1983
- const keysFor = (sql, nameEnd, fnName) => {
1984
- const rest = sql.slice(nameEnd).trimStart();
1985
- if (rest.startsWith("(")) {
1986
- const { inner } = parenthesized(rest, 0);
1987
- return [`${fnName}(${argTypes(inner).join(",")})`];
1988
- }
1989
- return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
1990
- };
1991
- for (const { file, statements } of migrations) {
1992
- for (const { sql, line } of statements) {
1993
- const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
1994
- if (create) {
1995
- const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
1996
- fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
1997
- continue;
1998
- }
1999
- const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
2000
- if (alter) {
2001
- const fnName = qualify(alter[1]);
2002
- const keys = keysFor(sql, alter[0].length, fnName);
2003
- const rename = / rename to ([\w$]+)$/.exec(sql);
2004
- const move = / set schema ([\w$]+)$/.exec(sql);
2005
- for (const key2 of keys) {
2006
- const state = fns.get(key2);
2007
- if (rename || move) {
2008
- if (!state) continue;
2009
- fns.delete(key2);
2010
- const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
2011
- fns.set(newName + key2.slice(fnName.length), state);
2012
- continue;
2013
- }
2014
- const next = state ?? { definer: false, searchPath: false, file, line };
2015
- if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
2016
- if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
2017
- if (/\bset search_path\b/.test(sql)) next.searchPath = true;
2018
- if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
2019
- fns.set(key2, next);
2020
- }
2021
- continue;
2022
- }
2023
- const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2024
- if (drop) {
2025
- for (const part of splitTop(drop[1])) {
2026
- const m = /^([\w$.]+)\s*/.exec(part);
2027
- if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
2028
- }
2171
+ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
2172
+ if (seen.has(file) || seen.size > 10) return {};
2173
+ seen.add(file);
2174
+ const json = readJsonc(file);
2175
+ if (!json) return {};
2176
+ const dir = path14.dirname(file);
2177
+ let merged = {};
2178
+ const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
2179
+ for (const ext of parents) {
2180
+ if (typeof ext !== "string") continue;
2181
+ let target = null;
2182
+ if (ext.startsWith(".") || path14.isAbsolute(ext)) {
2183
+ const abs = path14.resolve(dir, ext);
2184
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2185
+ } else {
2186
+ const parts = ext.split("/");
2187
+ const nameLength = ext.startsWith("@") ? 2 : 1;
2188
+ const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
2189
+ if (pkgDir) {
2190
+ const sub = parts.slice(nameLength).join("/");
2191
+ const abs = path14.join(pkgDir, sub || "tsconfig.json");
2192
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2029
2193
  }
2030
2194
  }
2195
+ if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
2031
2196
  }
2032
- for (const [key2, at] of fns) {
2033
- if (!at.definer || at.searchPath) continue;
2034
- ctx.report({
2035
- rule: "migration-definer-search-path",
2036
- file: at.file,
2037
- line: at.line,
2038
- subject: key2,
2039
- 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`
2040
- });
2197
+ const opts = json.compilerOptions ?? {};
2198
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
2199
+ if (opts.paths && typeof opts.paths === "object") {
2200
+ merged.paths = opts.paths;
2201
+ merged.pathsDir = dir;
2041
2202
  }
2203
+ return merged;
2042
2204
  }
2043
- var UMBRELLA_PACKAGE = "@marktiderman/genesis";
2044
- function readReleaseManifest(root) {
2045
- const dir = findPackageDir(root, UMBRELLA_PACKAGE);
2046
- const file = dir && path14.join(dir, "dist", "versions.json");
2047
- if (!file || !existsSync(file)) return null;
2048
- return JSON.parse(readFileSync(file, "utf8"));
2049
- }
2050
- function checkVersionSkew(ctx) {
2051
- const manifest = readReleaseManifest(ctx.root);
2052
- if (!manifest) return;
2053
- for (const [name, want] of Object.entries(manifest.packages)) {
2054
- const dir = findPackageDir(ctx.root, name);
2055
- if (!dir) continue;
2056
- const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
2057
- if (have === want) continue;
2058
- ctx.report({
2059
- rule: "version-skew",
2060
- level: "warn",
2061
- file: "package.json",
2062
- subject: name,
2063
- message: `${name} is ${have}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Install ${name}@${want}, or move every Genesis package to one release.`
2064
- });
2065
- }
2066
- }
2067
-
2068
- // src/doctor/semver.ts
2069
- var VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
2070
- function parseVersion(v) {
2071
- const m = VERSION.exec(v.trim());
2072
- return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
2073
- }
2074
- function compareVersions(a, b) {
2075
- for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
2076
- if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
2077
- for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
2078
- const x = a.pre[i];
2079
- const y = b.pre[i];
2080
- if (x === void 0) return -1;
2081
- if (y === void 0) return 1;
2082
- if (x === y) continue;
2083
- const nx = /^\d+$/.test(x);
2084
- const ny = /^\d+$/.test(y);
2085
- if (nx && ny) return +x < +y ? -1 : 1;
2086
- if (nx !== ny) return nx ? -1 : 1;
2087
- return x < y ? -1 : 1;
2088
- }
2089
- return 0;
2090
- }
2091
- function partial(s) {
2092
- const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
2093
- if (!m) return null;
2094
- const nums = [];
2095
- let wild = false;
2096
- for (const part of [m[1], m[2], m[3]]) {
2097
- if (wild || part === void 0 || /^[xX*]$/.test(part)) {
2098
- wild = true;
2099
- nums.push(null);
2100
- } else nums.push(+part);
2101
- }
2102
- return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
2103
- }
2104
- var ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
2105
- function comparators(token) {
2106
- const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
2107
- if (!m) return null;
2108
- const op = m[1] ?? "";
2109
- const p = partial(m[2]);
2110
- if (!p) return null;
2111
- const [major, mi, pa] = p.nums;
2112
- if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
2113
- const M = major;
2114
- const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
2115
- 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"]);
2116
- const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
2117
- const out = switchOp();
2118
- if (p.pre.length) {
2119
- for (const c of out) if (c.v === lo) c.pre = true;
2120
- }
2121
- return out;
2122
- function switchOp() {
2123
- switch (op) {
2124
- case "^": {
2125
- const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
2126
- return [
2127
- { op: ">=", v: lo },
2128
- { op: "<", v: bound }
2129
- ];
2130
- }
2131
- case "~":
2132
- case "~>":
2133
- return [
2134
- { op: ">=", v: lo },
2135
- { op: "<", v: mi === null ? next("major") : next("minor") }
2136
- ];
2137
- case ">":
2138
- return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
2139
- case ">=":
2140
- return [{ op: ">=", v: lo }];
2141
- case "<":
2142
- return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
2143
- case "<=":
2144
- return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
2145
- default:
2146
- return upper ? [
2147
- { op: ">=", v: lo },
2148
- { op: "<", v: upper }
2149
- ] : [{ op: "=", v: lo }];
2205
+ function aliases(root) {
2206
+ const table = [];
2207
+ let baseUrl = null;
2208
+ for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
2209
+ const file = path14.join(root, name);
2210
+ if (!existsSync(file)) continue;
2211
+ const config = readTsconfig(root, file);
2212
+ baseUrl ??= config.baseUrl ?? null;
2213
+ const base = config.baseUrl ?? config.pathsDir ?? root;
2214
+ for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
2215
+ if (!Array.isArray(targets)) continue;
2216
+ const exact = !pattern.endsWith("*");
2217
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
2150
2218
  }
2151
2219
  }
2220
+ const pkg = readJsonc(path14.join(root, "package.json"));
2221
+ for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
2222
+ if (typeof target !== "string") continue;
2223
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
2224
+ }
2225
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
2226
+ return { table, baseUrl };
2152
2227
  }
2153
- function test(c, v) {
2154
- const d = compareVersions(v, c.v);
2155
- return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
2156
- }
2157
- function parseRange(range) {
2158
- const alts = [];
2159
- for (const raw of range.trim().split("||")) {
2160
- const alt = raw.trim();
2161
- const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
2162
- if (hyphen) {
2163
- const from = comparators(`>=${hyphen[1]}`);
2164
- const to = comparators(`<=${hyphen[2]}`);
2165
- if (!from || !to) return null;
2166
- alts.push([...from, ...to]);
2167
- continue;
2168
- }
2169
- const set = [];
2170
- for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
2171
- const cs = comparators(token);
2172
- if (!cs) return null;
2173
- set.push(...cs);
2174
- }
2175
- alts.push(set);
2228
+ function resolveFile(base) {
2229
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
2230
+ if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
2231
+ for (const p of tries) {
2232
+ if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
2176
2233
  }
2177
- return alts;
2234
+ return null;
2178
2235
  }
2179
- function satisfies(version, range) {
2180
- const v = parseVersion(version);
2181
- const alts = parseRange(range);
2182
- if (!v || !alts) return null;
2183
- return alts.some(
2184
- (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))
2185
- );
2236
+ var trails = /* @__PURE__ */ new WeakMap();
2237
+ function trailFor(ctx) {
2238
+ let t = trails.get(ctx.files);
2239
+ if (!t) trails.set(ctx.files, t = createTrail(ctx));
2240
+ return t;
2186
2241
  }
2187
-
2188
- // src/doctor/installs.ts
2189
- var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
2190
- var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
2191
- var 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)$/;
2192
- var readManifest = (dir) => {
2193
- try {
2194
- return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
2195
- } catch {
2196
- return null;
2197
- }
2198
- };
2199
- var real = (p) => {
2242
+ function createTrail(ctx) {
2243
+ const { table, baseUrl } = aliases(ctx.root);
2244
+ let declared = null;
2200
2245
  try {
2201
- return realpathSync(p);
2246
+ const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
2247
+ declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
2202
2248
  } catch {
2203
- return p;
2249
+ declared = null;
2204
2250
  }
2205
- };
2206
- var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
2207
- function nodeModulesOf(dir) {
2208
- const parent = path14.dirname(dir);
2209
- return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
2210
- }
2211
- function packagesIn(nodeModules) {
2212
- if (!existsSync(nodeModules)) return [];
2213
- const out = [];
2214
- for (const entry of readdirSync(nodeModules)) {
2215
- if (entry.startsWith(".")) continue;
2216
- const p = path14.join(nodeModules, entry);
2217
- if (entry.startsWith("@")) {
2218
- try {
2219
- for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
2220
- } catch {
2221
- }
2222
- } else {
2223
- out.push(p);
2251
+ const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
2252
+ const read = (abs) => byPath.get(abs) ?? readSource(abs);
2253
+ const importsCache = /* @__PURE__ */ new Map();
2254
+ const importsOf = (file) => {
2255
+ const hit = importsCache.get(file.absolutePath);
2256
+ if (hit) return hit;
2257
+ const files = [];
2258
+ let lost = false;
2259
+ const code = stripped(file);
2260
+ if (code === null) {
2261
+ const out2 = { files: [], lost: true };
2262
+ importsCache.set(file.absolutePath, out2);
2263
+ return out2;
2224
2264
  }
2225
- }
2226
- return out;
2227
- }
2228
- function genesisInstalls(root) {
2229
- const copies = /* @__PURE__ */ new Map();
2230
- const realRoot = real(root);
2231
- const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
2232
- const via = /* @__PURE__ */ new Map();
2233
- const record = (real2, manifest, by, range, root2) => {
2234
- let copy = copies.get(real2);
2235
- if (!copy) {
2236
- copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
2237
- copies.set(real2, copy);
2238
- via.set(real2, /* @__PURE__ */ new Set());
2265
+ const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
2266
+ for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
2267
+ for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
2268
+ 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]);
2269
+ const specs = [];
2270
+ for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
2271
+ for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
2272
+ for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
2273
+ for (const spec of specs) {
2274
+ if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
2275
+ let resolved = null;
2276
+ if (spec.startsWith(".")) {
2277
+ resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
2278
+ if (!resolved) lost = true;
2279
+ } else {
2280
+ const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
2281
+ if (alias) {
2282
+ for (const t of alias.targets) {
2283
+ resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
2284
+ if (resolved) break;
2285
+ }
2286
+ }
2287
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
2288
+ if (!resolved) {
2289
+ const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
2290
+ if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
2291
+ }
2292
+ }
2293
+ if (resolved && !files.includes(resolved)) files.push(resolved);
2239
2294
  }
2240
- via.get(real2).add(root2);
2241
- if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
2295
+ const out = { files, lost };
2296
+ importsCache.set(file.absolutePath, out);
2297
+ return out;
2242
2298
  };
2243
- const walk = (kind, roots) => {
2244
- const expanded = /* @__PURE__ */ new Set();
2245
- const queue = [];
2246
- const visit = (dir, by, range) => {
2247
- const manifest = readManifest(dir);
2248
- if (!manifest?.name) return;
2249
- if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
2250
- const realDir = real(dir);
2251
- if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
2252
- if (expanded.has(realDir)) return;
2253
- expanded.add(realDir);
2254
- queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
2255
- };
2256
- for (const r of roots) visit(r.dir, r.by, r.range);
2257
- while (queue.length) {
2258
- const { real: from, manifest, label } = queue.shift();
2259
- const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
2260
- for (const [name, range] of Object.entries(deps)) {
2261
- const dir = findPackageDir(from, name);
2262
- if (dir) visit(dir, label, range);
2263
- }
2264
- for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
2265
- if (name in deps) continue;
2266
- const dir = peerOf(from, name);
2267
- if (dir) visit(dir, label, range);
2299
+ const strippedCache = /* @__PURE__ */ new Map();
2300
+ const stripped = (file) => {
2301
+ if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
2302
+ return strippedCache.get(file.absolutePath);
2303
+ };
2304
+ const memo = /* @__PURE__ */ new WeakMap();
2305
+ const reach = (file, test2, depth, seen) => {
2306
+ let cache2 = memo.get(test2);
2307
+ if (!cache2) memo.set(test2, cache2 = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
2308
+ const k = `${file.absolutePath}\0${depth}`;
2309
+ const free = cache2.free.get(k);
2310
+ if (free) return [free, /* @__PURE__ */ new Set()];
2311
+ const reusable = cache2.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
2312
+ if (reusable) return [reusable.result, new Set(reusable.cut)];
2313
+ let result;
2314
+ const cut = /* @__PURE__ */ new Set();
2315
+ const code = stripped(file);
2316
+ if (code === null) result = "unknown";
2317
+ else if (test2(code)) result = "yes";
2318
+ else {
2319
+ const { files, lost } = importsOf(file);
2320
+ let unknown = lost && depth > 0;
2321
+ result = "no";
2322
+ if (depth > 0) {
2323
+ seen.add(file.absolutePath);
2324
+ for (const abs of files) {
2325
+ if (seen.has(abs)) {
2326
+ cut.add(abs);
2327
+ continue;
2328
+ }
2329
+ const target = read(abs);
2330
+ if (!target) {
2331
+ unknown = true;
2332
+ continue;
2333
+ }
2334
+ const [r, c] = reach(target, test2, depth - 1, seen);
2335
+ for (const m of c) cut.add(m);
2336
+ if (r === "yes") {
2337
+ result = "yes";
2338
+ break;
2339
+ }
2340
+ if (r === "unknown") unknown = true;
2341
+ }
2342
+ seen.delete(file.absolutePath);
2343
+ cut.delete(file.absolutePath);
2268
2344
  }
2345
+ if (result === "no" && unknown) result = "unknown";
2346
+ }
2347
+ if (result === "yes" || cut.size === 0) {
2348
+ cache2.free.set(k, result);
2349
+ return [result, /* @__PURE__ */ new Set()];
2269
2350
  }
2351
+ const entries = cache2.cut.get(k) ?? [];
2352
+ entries.push({ cut: [...cut], result });
2353
+ cache2.cut.set(k, entries);
2354
+ return [result, cut];
2270
2355
  };
2271
- const peerOf = (from, name) => {
2272
- const dir = findPackageDir(from, name);
2273
- if (!dir) return null;
2274
- if (!ownInstall || name in declared) return dir;
2275
- const realDir = real(dir);
2276
- if (realDir.startsWith(realRoot + path14.sep)) return dir;
2277
- return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
2356
+ return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
2357
+ }
2358
+
2359
+ // src/doctor/packages.ts
2360
+ var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
2361
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
2362
+ var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
2363
+ var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
2364
+ var TYPE_ONLY = /\b(?:import|export)\s+type\b[^;"'`]*?\bfrom\s*["'][^"']+["']/g;
2365
+ function sourceFiles(dir, rel = "") {
2366
+ const out = [];
2367
+ for (const entry of readdirSync(path14.join(dir, rel)).sort()) {
2368
+ if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
2369
+ const child = rel ? `${rel}/${entry}` : entry;
2370
+ const stat = lstatSync(path14.join(dir, child));
2371
+ if (stat.isSymbolicLink()) continue;
2372
+ if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
2373
+ else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
2374
+ }
2375
+ return out;
2376
+ }
2377
+ function packageName2(specifier) {
2378
+ const parts = specifier.split("/");
2379
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
2380
+ }
2381
+ function git(root, args) {
2382
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2383
+ return r.status === 0 ? r.stdout : null;
2384
+ }
2385
+ function matchPattern(pattern, spec) {
2386
+ const star = pattern.indexOf("*");
2387
+ if (star < 0) return pattern === spec ? "" : null;
2388
+ const head = pattern.slice(0, star);
2389
+ const tail = pattern.slice(star + 1);
2390
+ return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
2391
+ }
2392
+ function tsconfigPaths(dir) {
2393
+ const file = path14.join(dir, "tsconfig.json");
2394
+ if (!existsSync(file)) return [];
2395
+ try {
2396
+ const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
2397
+ const options = JSON.parse(text).compilerOptions ?? {};
2398
+ const base = path14.resolve(dir, options.baseUrl ?? ".");
2399
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path14.resolve(base, t)) }));
2400
+ } catch {
2401
+ return [];
2402
+ }
2403
+ }
2404
+ function checkImports2(ctx, pkg, json) {
2405
+ const aliases2 = tsconfigPaths(pkg.dir);
2406
+ const subpathImports = Object.keys(json.imports ?? {});
2407
+ const viaAlias = (spec) => {
2408
+ if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
2409
+ for (const { pattern, targets } of aliases2) {
2410
+ const hit = matchPattern(pattern, spec);
2411
+ if (hit === null) continue;
2412
+ return targets.some((t) => {
2413
+ const rel = path14.relative(pkg.dir, t.replace("*", hit));
2414
+ return !rel.startsWith("..") && !path14.isAbsolute(rel);
2415
+ });
2416
+ }
2417
+ return null;
2278
2418
  };
2279
- const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
2280
- const dir = findPackageDir(root, name);
2281
- return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
2282
- });
2283
- const app = readManifest(root);
2284
- const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
2285
- const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
2286
- const declaredDev = Object.entries(app?.devDependencies ?? {});
2287
- const runtimeDeps = {
2288
- ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
2289
- ...app?.peerDependencies,
2290
- ...app?.optionalDependencies,
2291
- ...app?.dependencies
2419
+ const declared = /* @__PURE__ */ new Set([
2420
+ json.name,
2421
+ ...Object.keys(json.dependencies ?? {}),
2422
+ ...Object.keys(json.peerDependencies ?? {}),
2423
+ ...Object.keys(json.devDependencies ?? {}),
2424
+ ...Object.keys(json.optionalDependencies ?? {})
2425
+ ]);
2426
+ for (const file of sourceFiles(pkg.dir)) {
2427
+ const code = stripForImports(readFileSync(path14.join(pkg.dir, file), "utf8"));
2428
+ if (code === null) continue;
2429
+ const at = `${pkg.rel}/${file}`;
2430
+ const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
2431
+ let offset = 0;
2432
+ code.split("\n").forEach((text, i) => {
2433
+ const lineStart = offset;
2434
+ offset += text.length + 1;
2435
+ for (const m of text.matchAll(IMPORT)) {
2436
+ const spec = m[1];
2437
+ const line = i + 1;
2438
+ const at0 = lineStart + m.index;
2439
+ if (typeOnly.some(([a, b]) => at0 >= a && at0 < b)) continue;
2440
+ const alias = viaAlias(spec);
2441
+ if (alias === true) continue;
2442
+ if (alias === false) {
2443
+ ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} imports ${spec}, an alias that points outside the package` });
2444
+ continue;
2445
+ }
2446
+ if (spec.startsWith("#")) continue;
2447
+ if (spec.startsWith("@/") || spec.startsWith("~/")) {
2448
+ 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` });
2449
+ continue;
2450
+ }
2451
+ if (spec.startsWith(".")) {
2452
+ const target = path14.resolve(pkg.dir, path14.dirname(file), spec);
2453
+ const rel = path14.relative(pkg.dir, target);
2454
+ if (rel.startsWith("..") || path14.isAbsolute(rel)) {
2455
+ 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` });
2456
+ }
2457
+ continue;
2458
+ }
2459
+ if (BUILTINS.has(spec) || spec.startsWith("node:") || spec.startsWith("virtual:") || /^[a-z]+:/.test(spec)) continue;
2460
+ const name = packageName2(spec);
2461
+ if (!declared.has(name)) {
2462
+ 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` });
2463
+ }
2464
+ }
2465
+ });
2466
+ }
2467
+ }
2468
+ function checkMigrations(ctx, pkg, json) {
2469
+ const declaredFiles = /* @__PURE__ */ new Set();
2470
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
2471
+ const migrations = raw.migrations ?? [];
2472
+ for (const m of migrations) {
2473
+ if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
2474
+ if (typeof m.file === "string" && typeof m.test !== "string") {
2475
+ 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` });
2476
+ } else if (typeof m.test === "string" && !existsSync(path14.join(pkg.dir, m.test))) {
2477
+ 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` });
2478
+ }
2479
+ }
2480
+ }
2481
+ const dir = path14.join(pkg.dir, "migrations");
2482
+ if (!existsSync(dir)) return;
2483
+ const seen = /* @__PURE__ */ new Map();
2484
+ for (const name of readdirSync(dir).sort()) {
2485
+ const m = MIGRATION_FILE.exec(name);
2486
+ if (!m) continue;
2487
+ const other = seen.get(m[1]);
2488
+ 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` });
2489
+ else seen.set(m[1], name);
2490
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path14.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
2491
+ 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")})` });
2492
+ }
2493
+ }
2494
+ }
2495
+ function checkExports(ctx, pkg, json) {
2496
+ const targets = [];
2497
+ const walk = (v) => {
2498
+ if (typeof v === "string") targets.push(v);
2499
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk(x);
2292
2500
  };
2293
- const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
2294
- walk("runtime", rootsOf(runtimeDeps, "the app"));
2295
- const top = path14.join(root, "node_modules");
2296
- walk(
2297
- "hoisted",
2298
- packagesIn(top).filter((dir) => {
2299
- const name = path14.relative(top, dir).split(path14.sep).join("/");
2300
- return !(name in runtimeDeps) && !(name in devDeps);
2301
- }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
2501
+ walk(json.exports);
2502
+ for (const t of targets) {
2503
+ if (!t.startsWith("./") || t.includes("*") || /^\.\/(dist|build)\//.test(t)) continue;
2504
+ if (!existsSync(path14.join(pkg.dir, t))) {
2505
+ ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
2506
+ }
2507
+ }
2508
+ }
2509
+ function checkBlocks(ctx, pkg, json) {
2510
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
2511
+ try {
2512
+ parseManifest(json.name, id, raw, json.version, { local: true });
2513
+ } catch (err) {
2514
+ if (!(err instanceof ManifestError)) throw err;
2515
+ for (const problem of err.problems) ctx.report({ rule: "package-block-invalid", file: `${pkg.rel}/package.json`, subject: id, message: problem });
2516
+ }
2517
+ }
2518
+ }
2519
+ function checkTaggedTests(ctx, pkg) {
2520
+ const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
2521
+ if (!tests.length) return;
2522
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path14.join(pkg.dir, f), "utf8")));
2523
+ 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>` });
2524
+ }
2525
+ function checkRegistered(ctx, pkg) {
2526
+ const file = path14.join(ctx.root, "features.json");
2527
+ if (!existsSync(file)) return;
2528
+ let doc;
2529
+ try {
2530
+ doc = JSON.parse(readFileSync(file, "utf8"));
2531
+ } catch {
2532
+ return;
2533
+ }
2534
+ const covered = (doc.features ?? []).some(
2535
+ (f) => (f.links?.code ?? []).some((c) => {
2536
+ const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
2537
+ return norm === pkg.rel || norm.startsWith(`${pkg.rel}/`) || pkg.rel.startsWith(`${norm}/`);
2538
+ })
2302
2539
  );
2303
- const devRoots = { ...devDeps };
2304
- for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
2305
- walk("dev", rootsOf(devRoots, "the app (dev)"));
2306
- for (const [key2, copy] of copies) {
2307
- const kinds = via.get(key2);
2308
- copy.runtime = kinds.has("runtime");
2309
- copy.devOnly = kinds.size === 1 && kinds.has("dev");
2540
+ if (!covered) {
2541
+ 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` });
2310
2542
  }
2311
- const byName = /* @__PURE__ */ new Map();
2312
- for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
2313
- for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
2314
- return byName;
2315
2543
  }
2316
- function checkDuplicatePackages(ctx) {
2317
- const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
2318
- for (const [name, copies] of genesisInstalls(ctx.root)) {
2319
- if (copies.length < 2) continue;
2320
- const shipping = copies.filter((c) => c.runtime);
2321
- if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
2322
- ctx.report({
2323
- rule: "duplicate-genesis-package",
2324
- level: "warn",
2325
- file: "package.json",
2326
- subject: name,
2327
- 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`
2328
- });
2329
- continue;
2544
+ function changesetNames(text) {
2545
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
2546
+ const names = /* @__PURE__ */ new Set();
2547
+ if (!m) return names;
2548
+ for (const line of m[1].split(/\r?\n/)) {
2549
+ const entry = /^\s*(?:"([^"]+)"|'([^']+)'|([^\s:'"]+))\s*:\s*(major|minor|patch)\s*$/.exec(line);
2550
+ if (entry) names.add(entry[1] ?? entry[2] ?? entry[3]);
2551
+ }
2552
+ return names;
2553
+ }
2554
+ function mergeBaseOf(root, base) {
2555
+ if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository" };
2556
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) return { reason: `the git ref ${base} isn't available (fetch it)` };
2557
+ const sha = git(root, ["merge-base", "HEAD", base])?.trim();
2558
+ return sha ? { sha } : { reason: `HEAD has no merge base with ${base} (fetch with depth 0)` };
2559
+ }
2560
+ function checkChanges(ctx, pkg, json, base, mergeBase) {
2561
+ const diff = git(ctx.root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", pkg.rel]) ?? "";
2562
+ const untracked = (git(ctx.root, ["ls-files", "--others", "--exclude-standard", "--", pkg.rel]) ?? "").split("\n").filter(Boolean);
2563
+ const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
2564
+ (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
2565
+ );
2566
+ for (const row of diff.split("\n").filter(Boolean)) {
2567
+ const [status, a] = row.split(" ");
2568
+ if (a && /\/migrations\/\d{4}_[a-z0-9_]+\.sql$/.test(a) && /^[MDRT]/.test(status)) {
2569
+ 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` });
2330
2570
  }
2571
+ }
2572
+ if (!changed.length) return;
2573
+ const before = git(ctx.root, ["show", `${mergeBase}:./${pkg.rel}/package.json`]);
2574
+ let versionBefore;
2575
+ try {
2576
+ versionBefore = before ? JSON.parse(before).version : void 0;
2577
+ } catch {
2578
+ versionBefore = void 0;
2579
+ }
2580
+ const now = typeof json.version === "string" ? parseVersion(json.version) : null;
2581
+ const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
2582
+ const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
2583
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
2584
+ 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) => path14.join(top, f)) : [];
2585
+ const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
2586
+ const named = naming.length > 0;
2587
+ if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
2588
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path14.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
2589
+ }
2590
+ let jsonBefore = null;
2591
+ try {
2592
+ jsonBefore = before ? JSON.parse(before) : null;
2593
+ } catch {
2594
+ jsonBefore = null;
2595
+ }
2596
+ const raw = json;
2597
+ if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
2598
+ const registry = (git(ctx.root, ["diff", "--relative", "--name-only", mergeBase, "--", "features.ts", "src/features.ts"]) ?? "").trim();
2599
+ 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` });
2600
+ }
2601
+ if (!bumped && !named) {
2331
2602
  ctx.report({
2332
- rule: "duplicate-genesis-package",
2333
- level: "info",
2334
- file: "package.json",
2335
- subject: name,
2336
- 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`
2603
+ rule: "package-unversioned-change",
2604
+ level: "warn",
2605
+ file: `${pkg.rel}/package.json`,
2606
+ 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`
2337
2607
  });
2338
2608
  }
2339
2609
  }
2340
- function checkPeerRanges(ctx) {
2341
- const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
2342
- for (const copies of genesisInstalls(ctx.root).values()) {
2343
- for (const copy of copies) {
2344
- const dir = copy.absolutePath;
2345
- const peers = readManifest(dir)?.peerDependencies ?? {};
2346
- for (const [peer, range] of Object.entries(peers)) {
2347
- if (!GENESIS.test(peer)) continue;
2348
- const peerDir = findPackageDir(dir, peer);
2349
- const installed = peerDir && readManifest(peerDir)?.version;
2350
- if (!peerDir || !installed) continue;
2351
- if (satisfies(installed, range) !== false) continue;
2352
- ctx.report({
2353
- rule: "peer-range-mismatch",
2354
- // A dev tool's own tree (the CLI's) doesn't run in the app.
2355
- level: copy.devOnly ? "info" : "warn",
2356
- file: "package.json",
2357
- subject: `${copy.name}>${peer}`,
2358
- 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}`
2359
- });
2360
- }
2361
- }
2610
+ function checkPackagesPack(ctx) {
2611
+ let packages;
2612
+ try {
2613
+ packages = localPackages(ctx.root);
2614
+ } catch (err) {
2615
+ ctx.report({ rule: "package-block-invalid", file: "genesis.config.json", message: err.message });
2616
+ return;
2617
+ }
2618
+ if (!packages.length) return;
2619
+ const base = ctx.base ?? ctx.config.packages?.base;
2620
+ const merge = base ? mergeBaseOf(ctx.root, base) : { reason: "no base ref (pass --base <ref>, e.g. --base origin/main)" };
2621
+ if ("reason" in merge) {
2622
+ ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
2623
+ }
2624
+ for (const pkg of packages) {
2625
+ const json = JSON.parse(readFileSync(path14.join(pkg.dir, "package.json"), "utf8"));
2626
+ checkImports2(ctx, pkg, json);
2627
+ checkExports(ctx, pkg, json);
2628
+ checkBlocks(ctx, pkg, json);
2629
+ checkMigrations(ctx, pkg, json);
2630
+ checkTaggedTests(ctx, pkg);
2631
+ checkRegistered(ctx, pkg);
2632
+ if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
2362
2633
  }
2363
2634
  }
2364
- var TRAIL_DEPTH = 6;
2365
- var RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
2366
- var IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
2367
- var EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
2368
- var DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
2369
- function stripForImports(code) {
2635
+ var DEFAULT_MIGRATIONS = "supabase/migrations";
2636
+ var DEFAULT_BASE = "origin/main";
2637
+ var DEFAULT_EXPOSED = ["public"];
2638
+ function sqlStatements(text) {
2370
2639
  const out = [];
2371
- const blank = (ch) => ch === "\n" ? "\n" : " ";
2372
- const n = code.length;
2373
- const templates = [];
2374
- let depth = 0;
2375
- let i = 0;
2376
- let sure = true;
2377
- const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
2378
- const before = () => out.slice(-24).join("");
2379
- const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
2380
- const startsExpression = (b) => {
2381
- const t = b.replace(/\s+$/, "");
2382
- if (!t) return true;
2383
- if (KEYWORD.test(b)) return true;
2384
- return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
2640
+ let buf = "";
2641
+ let bodies = [];
2642
+ let line = 1;
2643
+ let start = 0;
2644
+ const flush = () => {
2645
+ const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
2646
+ if (sql) out.push({ sql, line: start, bodies });
2647
+ buf = "";
2648
+ bodies = [];
2649
+ start = 0;
2385
2650
  };
2386
- const exprStart = () => startsExpression(before());
2387
- const taggedTemplate = () => {
2388
- const b = out.slice(-48).join("");
2389
- const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
2390
- return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
2391
- };
2392
- const templateBody = () => {
2393
- while (i < n) {
2394
- const ch = code[i];
2395
- if (ch === "\\") {
2396
- out.push(" ", blank(code[i + 1] ?? ""));
2397
- i += 2;
2398
- } else if (ch === "`") {
2399
- out.push("`");
2400
- i++;
2401
- return;
2402
- } else if (ch === "$" && code[i + 1] === "{") {
2403
- out.push("${");
2404
- i += 2;
2405
- templates.push(depth);
2406
- depth++;
2407
- return;
2408
- } else {
2409
- out.push(blank(ch));
2410
- i++;
2411
- }
2412
- }
2413
- sure = false;
2651
+ const put = (s) => {
2652
+ if (!start && /\S/.test(s)) start = line;
2653
+ buf += s;
2414
2654
  };
2415
- while (i < n && sure) {
2416
- const ch = code[i];
2417
- const next = code[i + 1];
2418
- if (ch === "/" && next === "/") {
2419
- while (i < n && code[i] !== "\n") {
2420
- out.push(" ");
2421
- i++;
2422
- }
2423
- } else if (ch === "/" && next === "*") {
2424
- out.push(" ");
2425
- i += 2;
2426
- while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
2427
- out.push(blank(code[i]));
2428
- i++;
2429
- }
2430
- if (i < n) {
2431
- out.push(" ");
2432
- i += 2;
2433
- }
2434
- } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
2435
- const afterBrace = /[}>]\s*$/.test(before());
2436
- const start = i;
2437
- const mark = out.length;
2438
- out.push("/");
2655
+ let i = 0;
2656
+ while (i < text.length) {
2657
+ const ch = text[i];
2658
+ const two = text.slice(i, i + 2);
2659
+ if (ch === "\n") {
2660
+ buf += " ";
2661
+ line++;
2439
2662
  i++;
2440
- let inClass = false;
2441
- for (; ; ) {
2442
- const c = code[i];
2443
- if (c === void 0 || c === "\n") {
2444
- if (afterBrace) {
2445
- out.length = mark;
2446
- out.push("/");
2447
- i = start + 1;
2448
- } else sure = false;
2449
- break;
2450
- }
2451
- if (c === "\\") {
2452
- out.push(" ", blank(code[i + 1] ?? ""));
2663
+ } else if (two === "--") {
2664
+ while (i < text.length && text[i] !== "\n") i++;
2665
+ } else if (two === "/*") {
2666
+ let depth = 0;
2667
+ while (i < text.length) {
2668
+ if (text.startsWith("/*", i)) {
2669
+ depth++;
2453
2670
  i += 2;
2454
- continue;
2455
- }
2456
- i++;
2457
- if (c === "[") inClass = true;
2458
- else if (c === "]") inClass = false;
2459
- else if (c === "/" && !inClass) {
2460
- if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
2461
- out.length = mark;
2462
- out.push("/");
2463
- i = start + 1;
2464
- break;
2465
- }
2466
- out.push("/");
2467
- break;
2468
- }
2469
- out.push(" ");
2470
- }
2471
- if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
2472
- } else if ((ch === '"' || ch === "'") && exprStart()) {
2473
- const keep = isSpecifier();
2474
- out.push(ch);
2475
- i++;
2476
- while (i < n && code[i] !== ch && code[i] !== "\n") {
2477
- if (code[i] === "\\") {
2478
- out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
2671
+ } else if (text.startsWith("*/", i)) {
2672
+ depth--;
2479
2673
  i += 2;
2674
+ if (depth === 0) break;
2480
2675
  } else {
2481
- out.push(keep ? code[i] : blank(code[i]));
2676
+ if (text[i] === "\n") line++;
2482
2677
  i++;
2483
2678
  }
2484
2679
  }
2485
- if (code[i] !== ch) sure = false;
2486
- else {
2487
- out.push(code[i]);
2488
- i++;
2680
+ buf += " ";
2681
+ } else if (ch === "'") {
2682
+ const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
2683
+ put("'");
2684
+ i++;
2685
+ while (i < text.length) {
2686
+ if (escapes && text[i] === "\\") i += 2;
2687
+ else if (text[i] === "'" && text[i + 1] === "'") i += 2;
2688
+ else if (text[i] === "'") break;
2689
+ else {
2690
+ if (text[i] === "\n") line++;
2691
+ i++;
2692
+ }
2489
2693
  }
2490
- } else if (ch === "`" && (exprStart() || taggedTemplate())) {
2491
- out.push("`");
2694
+ put("'");
2492
2695
  i++;
2493
- templateBody();
2494
- } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
2495
- templates.pop();
2496
- depth--;
2497
- out.push("}");
2696
+ } else if (ch === '"') {
2697
+ i++;
2698
+ while (i < text.length && text[i] !== '"') put(text[i++]);
2699
+ i++;
2700
+ } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
2701
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
2702
+ const end = text.indexOf(tag, i + tag.length);
2703
+ const stop = end === -1 ? text.length : end + tag.length;
2704
+ bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
2705
+ for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
2706
+ put(`${tag} ${tag}`);
2707
+ i = stop;
2708
+ } else if (ch === ";") {
2709
+ flush();
2498
2710
  i++;
2499
- templateBody();
2500
2711
  } else {
2501
- if (ch === "{") depth++;
2502
- else if (ch === "}") depth--;
2503
- out.push(ch);
2712
+ put(ch);
2504
2713
  i++;
2505
2714
  }
2506
2715
  }
2507
- return sure && templates.length === 0 ? out.join("") : null;
2508
- }
2509
- function bindings(clause) {
2510
- const out = [];
2511
- const named = /\{([^}]*)\}/.exec(clause);
2512
- for (const part of named?.[1].split(",") ?? []) {
2513
- const p = part.trim();
2514
- if (!p || p.startsWith("type ")) continue;
2515
- out.push(p.split(/\s+as\s+/).pop().trim());
2516
- }
2517
- const rest = clause.replace(/\{[^}]*\}/, "");
2518
- const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
2519
- if (ns) out.push(ns[1]);
2520
- const def = /^\s*([\w$]+)/.exec(rest);
2521
- if (def && def[1] !== "as") out.push(def[1]);
2716
+ flush();
2522
2717
  return out;
2523
2718
  }
2524
- function readJsonc(file) {
2525
- try {
2526
- const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
2527
- return JSON.parse(text);
2528
- } catch {
2529
- return null;
2530
- }
2719
+ function qualify(name) {
2720
+ const n = name.trim().toLowerCase();
2721
+ return n.includes(".") ? n : `public.${n}`;
2531
2722
  }
2532
- function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
2533
- if (seen.has(file) || seen.size > 10) return {};
2534
- seen.add(file);
2535
- const json = readJsonc(file);
2536
- if (!json) return {};
2537
- const dir = path14.dirname(file);
2538
- let merged = {};
2539
- const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
2540
- for (const ext of parents) {
2541
- if (typeof ext !== "string") continue;
2542
- let target = null;
2543
- if (ext.startsWith(".") || path14.isAbsolute(ext)) {
2544
- const abs = path14.resolve(dir, ext);
2545
- target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2546
- } else {
2547
- const parts = ext.split("/");
2548
- const nameLength = ext.startsWith("@") ? 2 : 1;
2549
- const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
2550
- if (pkgDir) {
2551
- const sub = parts.slice(nameLength).join("/");
2552
- const abs = path14.join(pkgDir, sub || "tsconfig.json");
2553
- target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2554
- }
2555
- }
2556
- if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
2557
- }
2558
- const opts = json.compilerOptions ?? {};
2559
- if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
2560
- if (opts.paths && typeof opts.paths === "object") {
2561
- merged.paths = opts.paths;
2562
- merged.pathsDir = dir;
2723
+ var schemaOf = (name) => name.split(".")[0];
2724
+ function parenthesized(sql, open) {
2725
+ let depth = 0;
2726
+ for (let k = open; k < sql.length; k++) {
2727
+ if (sql[k] === "(") depth++;
2728
+ else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
2563
2729
  }
2564
- return merged;
2730
+ return { inner: sql.slice(open + 1), end: sql.length };
2565
2731
  }
2566
- function aliases(root) {
2567
- const table = [];
2568
- let baseUrl = null;
2569
- for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
2570
- const file = path14.join(root, name);
2571
- if (!existsSync(file)) continue;
2572
- const config = readTsconfig(root, file);
2573
- baseUrl ??= config.baseUrl ?? null;
2574
- const base = config.baseUrl ?? config.pathsDir ?? root;
2575
- for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
2576
- if (!Array.isArray(targets)) continue;
2577
- const exact = !pattern.endsWith("*");
2578
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
2579
- }
2580
- }
2581
- const pkg = readJsonc(path14.join(root, "package.json"));
2582
- for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
2583
- if (typeof target !== "string") continue;
2584
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
2732
+ function stripParens(s) {
2733
+ let out = "";
2734
+ let depth = 0;
2735
+ for (const c of s) {
2736
+ if (c === "(") depth++;
2737
+ else if (c === ")") depth = Math.max(0, depth - 1);
2738
+ else if (depth === 0) out += c;
2585
2739
  }
2586
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
2587
- return { table, baseUrl };
2740
+ return out;
2588
2741
  }
2589
- function resolveFile(base) {
2590
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
2591
- if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
2592
- for (const p of tries) {
2593
- if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
2594
- }
2595
- return null;
2742
+ function splitTop(s) {
2743
+ const parts = [];
2744
+ let depth = 0;
2745
+ let cur = "";
2746
+ for (const c of s) {
2747
+ if (c === "(") depth++;
2748
+ if (c === ")") depth--;
2749
+ if (c === "," && depth === 0) {
2750
+ parts.push(cur);
2751
+ cur = "";
2752
+ } else cur += c;
2753
+ }
2754
+ if (cur.trim()) parts.push(cur);
2755
+ return parts.map((p) => p.trim()).filter(Boolean);
2596
2756
  }
2597
- var trails = /* @__PURE__ */ new WeakMap();
2598
- function trailFor(ctx) {
2599
- let t = trails.get(ctx.files);
2600
- if (!t) trails.set(ctx.files, t = createTrail(ctx));
2601
- return t;
2757
+ var TYPE_ALIASES = {
2758
+ int: "integer",
2759
+ int4: "integer",
2760
+ int8: "bigint",
2761
+ int2: "smallint",
2762
+ bool: "boolean",
2763
+ varchar: "character varying",
2764
+ timestamptz: "timestamp with time zone",
2765
+ float8: "double precision"
2766
+ };
2767
+ var MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
2768
+ function argTypes(args) {
2769
+ const types = [];
2770
+ for (const raw of splitTop(args)) {
2771
+ let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
2772
+ const mode = tokens[0];
2773
+ if (mode === "out") continue;
2774
+ if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
2775
+ const joined = tokens.join(" ");
2776
+ const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
2777
+ types.push(TYPE_ALIASES[type] ?? type);
2778
+ }
2779
+ return types;
2602
2780
  }
2603
- function createTrail(ctx) {
2604
- const { table, baseUrl } = aliases(ctx.root);
2605
- let declared = null;
2781
+ function git2(root, args) {
2782
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2783
+ return r.status === 0 ? r.stdout : null;
2784
+ }
2785
+ function gitView(root, dir, base) {
2786
+ if (git2(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
2787
+ if (git2(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
2788
+ return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
2789
+ }
2790
+ const mergeBase = git2(root, ["merge-base", "HEAD", base])?.trim();
2791
+ if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
2792
+ const diff = git2(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
2793
+ const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
2794
+ if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
2795
+ const sql = (p) => p !== void 0 && p.endsWith(".sql");
2796
+ const touched = new Set(untracked.split("\n").filter(sql));
2797
+ const edited = [];
2798
+ for (const row of diff.split("\n").filter(Boolean)) {
2799
+ const [status, a, b] = row.split(" ");
2800
+ if (status.startsWith("R")) {
2801
+ if (sql(b)) touched.add(b);
2802
+ if (sql(a)) edited.push({ file: a, status: "renamed" });
2803
+ continue;
2804
+ }
2805
+ if (!sql(a)) continue;
2806
+ if (status.startsWith("A")) touched.add(a);
2807
+ else if (status.startsWith("M") || status.startsWith("T")) {
2808
+ touched.add(a);
2809
+ edited.push({ file: a, status: "modified" });
2810
+ } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
2811
+ }
2812
+ return { touched, edited };
2813
+ }
2814
+ function checkSupabasePack(ctx) {
2815
+ const settings = ctx.config.supabase ?? {};
2816
+ const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
2817
+ const abs = path14.join(ctx.root, dir);
2818
+ if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
2819
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
2820
+ const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
2821
+ const base = settings.base ?? DEFAULT_BASE;
2822
+ const view = gitView(ctx.root, dir, base);
2823
+ if ("reason" in view) {
2824
+ if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
2825
+ } else {
2826
+ for (const e of view.edited) {
2827
+ ctx.report({
2828
+ rule: "migration-edited",
2829
+ file: e.file,
2830
+ subject: e.file,
2831
+ 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`
2832
+ });
2833
+ }
2834
+ }
2835
+ const since = settings.since;
2836
+ const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
2837
+ if ("reason" in view && since === void 0) {
2838
+ ctx.report({
2839
+ rule: "migration-grants",
2840
+ level: "warn",
2841
+ file: dir,
2842
+ 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`
2843
+ });
2844
+ } else {
2845
+ const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
2846
+ checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
2847
+ }
2848
+ checkRls(ctx, migrations, exposed);
2849
+ checkViewInvoker(ctx, migrations, exposed);
2850
+ checkDefinerSearchPath(ctx, migrations);
2851
+ checkTestingKit(ctx, migrations);
2852
+ }
2853
+ function checkTestingKit(ctx, migrations) {
2854
+ for (const { file, statements } of migrations) {
2855
+ const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
2856
+ if (!hit) continue;
2857
+ ctx.report({
2858
+ rule: "migration-testing-kit",
2859
+ file,
2860
+ line: hit.line,
2861
+ subject: "genesis_testing",
2862
+ message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
2863
+ });
2864
+ }
2865
+ }
2866
+ function granteesOf(s) {
2867
+ return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
2868
+ }
2869
+ function checkGrants(ctx, migrations, exposed) {
2870
+ const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
2871
+ const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
2872
+ const blanket = (roles) => {
2873
+ const o = open(roles);
2874
+ if (o.length) return { level: "error", who: o.join(" and ") };
2875
+ if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
2876
+ return null;
2877
+ };
2878
+ for (const { file, statements } of migrations) {
2879
+ for (const { sql, line } of statements) {
2880
+ const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
2881
+ if (all) {
2882
+ const hit = blanket(granteesOf(all[1]));
2883
+ if (hit) {
2884
+ 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}` });
2885
+ }
2886
+ continue;
2887
+ }
2888
+ const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
2889
+ if (defaults) {
2890
+ const hit = blanket(granteesOf(defaults[1]));
2891
+ if (hit) {
2892
+ 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}` });
2893
+ }
2894
+ continue;
2895
+ }
2896
+ const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
2897
+ if (fn) {
2898
+ const roles = open(granteesOf(fn[2]));
2899
+ if (!roles.length) continue;
2900
+ for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
2901
+ if (exposed.has(schemaOf(name))) continue;
2902
+ ctx.report({
2903
+ rule: "migration-grants",
2904
+ file,
2905
+ line,
2906
+ subject: name,
2907
+ 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)`
2908
+ });
2909
+ }
2910
+ continue;
2911
+ }
2912
+ const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
2913
+ if (schema) {
2914
+ const roles = open(granteesOf(schema[2]));
2915
+ if (!roles.length) continue;
2916
+ for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
2917
+ if (exposed.has(s)) continue;
2918
+ ctx.report({
2919
+ rule: "migration-grants",
2920
+ file,
2921
+ line,
2922
+ subject: `schema ${s}`,
2923
+ message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
2924
+ });
2925
+ }
2926
+ }
2927
+ }
2928
+ }
2929
+ }
2930
+ function checkRls(ctx, migrations, exposed) {
2931
+ const tables = /* @__PURE__ */ new Map();
2932
+ const name = String.raw`([\w$.]+)`;
2933
+ const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
2934
+ for (const { file, statements } of migrations) {
2935
+ for (const { sql, line, bodies } of statements) {
2936
+ if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
2937
+ const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
2938
+ if (create) {
2939
+ if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
2940
+ continue;
2941
+ }
2942
+ const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
2943
+ const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
2944
+ if (rename || move) {
2945
+ const from = qualify((rename ?? move)[1]);
2946
+ const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
2947
+ const state = tables.get(from);
2948
+ if (state) {
2949
+ tables.delete(from);
2950
+ tables.set(to, state);
2951
+ }
2952
+ continue;
2953
+ }
2954
+ const alter = new RegExp(target).exec(sql);
2955
+ if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
2956
+ const t = qualify(alter[1]);
2957
+ if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
2958
+ else {
2959
+ const state = tables.get(t);
2960
+ if (state) state.rls = true;
2961
+ }
2962
+ continue;
2963
+ }
2964
+ const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2965
+ if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
2966
+ }
2967
+ }
2968
+ for (const [t, at] of tables) {
2969
+ if (at.rls || !exposed.has(schemaOf(t))) continue;
2970
+ ctx.report({
2971
+ rule: "migration-rls",
2972
+ file: at.file,
2973
+ line: at.line,
2974
+ subject: t,
2975
+ 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`
2976
+ });
2977
+ }
2978
+ }
2979
+ function checkViewInvoker(ctx, migrations, exposed) {
2980
+ const views = /* @__PURE__ */ new Map();
2981
+ const name = String.raw`([\w$.]+)`;
2982
+ const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
2983
+ for (const { file, statements } of migrations) {
2984
+ for (const { sql, line } of statements) {
2985
+ const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
2986
+ if (create) {
2987
+ if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
2988
+ const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
2989
+ views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
2990
+ continue;
2991
+ }
2992
+ const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
2993
+ if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
2994
+ const state = views.get(qualify(alter[1]));
2995
+ if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
2996
+ continue;
2997
+ }
2998
+ const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
2999
+ if (rename) {
3000
+ const from = qualify(rename[1]);
3001
+ const state = views.get(from);
3002
+ if (state) {
3003
+ views.delete(from);
3004
+ views.set(`${schemaOf(from)}.${rename[2]}`, state);
3005
+ }
3006
+ continue;
3007
+ }
3008
+ const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3009
+ if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
3010
+ }
3011
+ }
3012
+ for (const [v, at] of views) {
3013
+ if (at.invoker || !exposed.has(schemaOf(v))) continue;
3014
+ ctx.report({
3015
+ rule: "migration-view-rls",
3016
+ file: at.file,
3017
+ line: at.line,
3018
+ subject: v,
3019
+ 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);"`
3020
+ });
3021
+ }
3022
+ }
3023
+ function checkDefinerSearchPath(ctx, migrations) {
3024
+ const fns = /* @__PURE__ */ new Map();
3025
+ const keysFor = (sql, nameEnd, fnName) => {
3026
+ const rest = sql.slice(nameEnd).trimStart();
3027
+ if (rest.startsWith("(")) {
3028
+ const { inner } = parenthesized(rest, 0);
3029
+ return [`${fnName}(${argTypes(inner).join(",")})`];
3030
+ }
3031
+ return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
3032
+ };
3033
+ for (const { file, statements } of migrations) {
3034
+ for (const { sql, line } of statements) {
3035
+ const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
3036
+ if (create) {
3037
+ const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
3038
+ fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
3039
+ continue;
3040
+ }
3041
+ const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
3042
+ if (alter) {
3043
+ const fnName = qualify(alter[1]);
3044
+ const keys = keysFor(sql, alter[0].length, fnName);
3045
+ const rename = / rename to ([\w$]+)$/.exec(sql);
3046
+ const move = / set schema ([\w$]+)$/.exec(sql);
3047
+ for (const key2 of keys) {
3048
+ const state = fns.get(key2);
3049
+ if (rename || move) {
3050
+ if (!state) continue;
3051
+ fns.delete(key2);
3052
+ const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
3053
+ fns.set(newName + key2.slice(fnName.length), state);
3054
+ continue;
3055
+ }
3056
+ const next = state ?? { definer: false, searchPath: false, file, line };
3057
+ if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
3058
+ if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
3059
+ if (/\bset search_path\b/.test(sql)) next.searchPath = true;
3060
+ if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
3061
+ fns.set(key2, next);
3062
+ }
3063
+ continue;
3064
+ }
3065
+ const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3066
+ if (drop) {
3067
+ for (const part of splitTop(drop[1])) {
3068
+ const m = /^([\w$.]+)\s*/.exec(part);
3069
+ if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
3070
+ }
3071
+ }
3072
+ }
3073
+ }
3074
+ for (const [key2, at] of fns) {
3075
+ if (!at.definer || at.searchPath) continue;
3076
+ ctx.report({
3077
+ rule: "migration-definer-search-path",
3078
+ file: at.file,
3079
+ line: at.line,
3080
+ subject: key2,
3081
+ 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`
3082
+ });
3083
+ }
3084
+ }
3085
+ var UMBRELLA_PACKAGE = "@marktiderman/genesis";
3086
+ function readReleaseManifest(root) {
3087
+ const dir = findPackageDir(root, UMBRELLA_PACKAGE);
3088
+ const file = dir && path14.join(dir, "dist", "versions.json");
3089
+ if (!file || !existsSync(file)) return null;
3090
+ return JSON.parse(readFileSync(file, "utf8"));
3091
+ }
3092
+ function checkVersionSkew(ctx) {
3093
+ const manifest = readReleaseManifest(ctx.root);
3094
+ if (!manifest) return;
3095
+ for (const [name, want] of Object.entries(manifest.packages)) {
3096
+ const dir = findPackageDir(ctx.root, name);
3097
+ if (!dir) continue;
3098
+ const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
3099
+ if (have === want) continue;
3100
+ ctx.report({
3101
+ rule: "version-skew",
3102
+ level: "warn",
3103
+ file: "package.json",
3104
+ subject: name,
3105
+ message: `${name} is ${have}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Install ${name}@${want}, or move every Genesis package to one release.`
3106
+ });
3107
+ }
3108
+ }
3109
+ var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
3110
+ var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
3111
+ var 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)$/;
3112
+ var readManifest = (dir) => {
2606
3113
  try {
2607
- const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
2608
- declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
3114
+ return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
2609
3115
  } catch {
2610
- declared = null;
3116
+ return null;
2611
3117
  }
2612
- const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
2613
- const read = (abs) => byPath.get(abs) ?? readSource(abs);
2614
- const importsCache = /* @__PURE__ */ new Map();
2615
- const importsOf = (file) => {
2616
- const hit = importsCache.get(file.absolutePath);
2617
- if (hit) return hit;
2618
- const files = [];
2619
- let lost = false;
2620
- const code = stripped(file);
2621
- if (code === null) {
2622
- const out2 = { files: [], lost: true };
2623
- importsCache.set(file.absolutePath, out2);
2624
- return out2;
3118
+ };
3119
+ var real = (p) => {
3120
+ try {
3121
+ return realpathSync(p);
3122
+ } catch {
3123
+ return p;
3124
+ }
3125
+ };
3126
+ var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
3127
+ function nodeModulesOf(dir) {
3128
+ const parent = path14.dirname(dir);
3129
+ return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
3130
+ }
3131
+ function packagesIn(nodeModules) {
3132
+ if (!existsSync(nodeModules)) return [];
3133
+ const out = [];
3134
+ for (const entry of readdirSync(nodeModules)) {
3135
+ if (entry.startsWith(".")) continue;
3136
+ const p = path14.join(nodeModules, entry);
3137
+ if (entry.startsWith("@")) {
3138
+ try {
3139
+ for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
3140
+ } catch {
3141
+ }
3142
+ } else {
3143
+ out.push(p);
2625
3144
  }
2626
- const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
2627
- for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
2628
- for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
2629
- 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]);
2630
- const specs = [];
2631
- for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
2632
- for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
2633
- for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
2634
- for (const spec of specs) {
2635
- if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
2636
- let resolved = null;
2637
- if (spec.startsWith(".")) {
2638
- resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
2639
- if (!resolved) lost = true;
2640
- } else {
2641
- const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
2642
- if (alias) {
2643
- for (const t of alias.targets) {
2644
- resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
2645
- if (resolved) break;
2646
- }
2647
- }
2648
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
2649
- if (!resolved) {
2650
- const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
2651
- if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
2652
- }
3145
+ }
3146
+ return out;
3147
+ }
3148
+ function genesisInstalls(root) {
3149
+ const copies = /* @__PURE__ */ new Map();
3150
+ const realRoot = real(root);
3151
+ const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
3152
+ const via = /* @__PURE__ */ new Map();
3153
+ const record = (real2, manifest, by, range, root2) => {
3154
+ let copy = copies.get(real2);
3155
+ if (!copy) {
3156
+ copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
3157
+ copies.set(real2, copy);
3158
+ via.set(real2, /* @__PURE__ */ new Set());
3159
+ }
3160
+ via.get(real2).add(root2);
3161
+ if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
3162
+ };
3163
+ const walk = (kind, roots) => {
3164
+ const expanded = /* @__PURE__ */ new Set();
3165
+ const queue = [];
3166
+ const visit = (dir, by, range) => {
3167
+ const manifest = readManifest(dir);
3168
+ if (!manifest?.name) return;
3169
+ if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
3170
+ const realDir = real(dir);
3171
+ if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
3172
+ if (expanded.has(realDir)) return;
3173
+ expanded.add(realDir);
3174
+ queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
3175
+ };
3176
+ for (const r of roots) visit(r.dir, r.by, r.range);
3177
+ while (queue.length) {
3178
+ const { real: from, manifest, label } = queue.shift();
3179
+ const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
3180
+ for (const [name, range] of Object.entries(deps)) {
3181
+ const dir = findPackageDir(from, name);
3182
+ if (dir) visit(dir, label, range);
3183
+ }
3184
+ for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
3185
+ if (name in deps) continue;
3186
+ const dir = peerOf(from, name);
3187
+ if (dir) visit(dir, label, range);
2653
3188
  }
2654
- if (resolved && !files.includes(resolved)) files.push(resolved);
2655
3189
  }
2656
- const out = { files, lost };
2657
- importsCache.set(file.absolutePath, out);
2658
- return out;
2659
3190
  };
2660
- const strippedCache = /* @__PURE__ */ new Map();
2661
- const stripped = (file) => {
2662
- if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
2663
- return strippedCache.get(file.absolutePath);
3191
+ const peerOf = (from, name) => {
3192
+ const dir = findPackageDir(from, name);
3193
+ if (!dir) return null;
3194
+ if (!ownInstall || name in declared) return dir;
3195
+ const realDir = real(dir);
3196
+ if (realDir.startsWith(realRoot + path14.sep)) return dir;
3197
+ return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
2664
3198
  };
2665
- const memo = /* @__PURE__ */ new WeakMap();
2666
- const reach = (file, test2, depth, seen) => {
2667
- let cache = memo.get(test2);
2668
- if (!cache) memo.set(test2, cache = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
2669
- const k = `${file.absolutePath}\0${depth}`;
2670
- const free = cache.free.get(k);
2671
- if (free) return [free, /* @__PURE__ */ new Set()];
2672
- const reusable = cache.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
2673
- if (reusable) return [reusable.result, new Set(reusable.cut)];
2674
- let result;
2675
- const cut = /* @__PURE__ */ new Set();
2676
- const code = stripped(file);
2677
- if (code === null) result = "unknown";
2678
- else if (test2(code)) result = "yes";
2679
- else {
2680
- const { files, lost } = importsOf(file);
2681
- let unknown = lost && depth > 0;
2682
- result = "no";
2683
- if (depth > 0) {
2684
- seen.add(file.absolutePath);
2685
- for (const abs of files) {
2686
- if (seen.has(abs)) {
2687
- cut.add(abs);
2688
- continue;
2689
- }
2690
- const target = read(abs);
2691
- if (!target) {
2692
- unknown = true;
2693
- continue;
2694
- }
2695
- const [r, c] = reach(target, test2, depth - 1, seen);
2696
- for (const m of c) cut.add(m);
2697
- if (r === "yes") {
2698
- result = "yes";
2699
- break;
2700
- }
2701
- if (r === "unknown") unknown = true;
2702
- }
2703
- seen.delete(file.absolutePath);
2704
- cut.delete(file.absolutePath);
2705
- }
2706
- if (result === "no" && unknown) result = "unknown";
3199
+ const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
3200
+ const dir = findPackageDir(root, name);
3201
+ return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
3202
+ });
3203
+ const app = readManifest(root);
3204
+ const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
3205
+ const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
3206
+ const declaredDev = Object.entries(app?.devDependencies ?? {});
3207
+ const runtimeDeps = {
3208
+ ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
3209
+ ...app?.peerDependencies,
3210
+ ...app?.optionalDependencies,
3211
+ ...app?.dependencies
3212
+ };
3213
+ const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
3214
+ walk("runtime", rootsOf(runtimeDeps, "the app"));
3215
+ const top = path14.join(root, "node_modules");
3216
+ walk(
3217
+ "hoisted",
3218
+ packagesIn(top).filter((dir) => {
3219
+ const name = path14.relative(top, dir).split(path14.sep).join("/");
3220
+ return !(name in runtimeDeps) && !(name in devDeps);
3221
+ }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
3222
+ );
3223
+ const devRoots = { ...devDeps };
3224
+ for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
3225
+ walk("dev", rootsOf(devRoots, "the app (dev)"));
3226
+ for (const [key2, copy] of copies) {
3227
+ const kinds = via.get(key2);
3228
+ copy.runtime = kinds.has("runtime");
3229
+ copy.devOnly = kinds.size === 1 && kinds.has("dev");
3230
+ }
3231
+ const byName = /* @__PURE__ */ new Map();
3232
+ for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
3233
+ for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
3234
+ return byName;
3235
+ }
3236
+ function checkDuplicatePackages(ctx) {
3237
+ const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
3238
+ for (const [name, copies] of genesisInstalls(ctx.root)) {
3239
+ if (copies.length < 2) continue;
3240
+ const shipping = copies.filter((c) => c.runtime);
3241
+ if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
3242
+ ctx.report({
3243
+ rule: "duplicate-genesis-package",
3244
+ level: "warn",
3245
+ file: "package.json",
3246
+ subject: name,
3247
+ 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`
3248
+ });
3249
+ continue;
2707
3250
  }
2708
- if (result === "yes" || cut.size === 0) {
2709
- cache.free.set(k, result);
2710
- return [result, /* @__PURE__ */ new Set()];
3251
+ ctx.report({
3252
+ rule: "duplicate-genesis-package",
3253
+ level: "info",
3254
+ file: "package.json",
3255
+ subject: name,
3256
+ 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`
3257
+ });
3258
+ }
3259
+ }
3260
+ function checkPeerRanges(ctx) {
3261
+ const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
3262
+ for (const copies of genesisInstalls(ctx.root).values()) {
3263
+ for (const copy of copies) {
3264
+ const dir = copy.absolutePath;
3265
+ const peers = readManifest(dir)?.peerDependencies ?? {};
3266
+ for (const [peer, range] of Object.entries(peers)) {
3267
+ if (!GENESIS.test(peer)) continue;
3268
+ const peerDir = findPackageDir(dir, peer);
3269
+ const installed = peerDir && readManifest(peerDir)?.version;
3270
+ if (!peerDir || !installed) continue;
3271
+ if (satisfies(installed, range) !== false) continue;
3272
+ ctx.report({
3273
+ rule: "peer-range-mismatch",
3274
+ // A dev tool's own tree (the CLI's) doesn't run in the app.
3275
+ level: copy.devOnly ? "info" : "warn",
3276
+ file: "package.json",
3277
+ subject: `${copy.name}>${peer}`,
3278
+ 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}`
3279
+ });
3280
+ }
2711
3281
  }
2712
- const entries = cache.cut.get(k) ?? [];
2713
- entries.push({ cut: [...cut], result });
2714
- cache.cut.set(k, entries);
2715
- return [result, cut];
2716
- };
2717
- return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
3282
+ }
2718
3283
  }
2719
-
2720
- // src/doctor/routes.ts
2721
3284
  var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
2722
3285
  var STEMS = {
2723
3286
  tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
@@ -2830,7 +3393,7 @@ var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/u
2830
3393
  var CONTAINER = /(?:Card|CardContent|Dialog|DialogContent|Sheet|SheetContent|Drawer|DrawerContent|Popover|PopoverContent|Modal|Accordion|AccordionContent|AccordionItem|Collapsible|CollapsibleContent|Tooltip|Menu|MenuContent|Panel|Table|TabsContent)$/;
2831
3394
  var SWITCHER = /<(TabsList|SubNavTabs)(?=[\s>/])/g;
2832
3395
  var SHELL = /<AppShell(?=[\s>/])/;
2833
- var GENESIS_PACKAGE = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
3396
+ var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
2834
3397
  var PAGE_LAYOUT = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)$/;
2835
3398
  var PACKAGE_SCREEN = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)$/;
2836
3399
  var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
@@ -2886,7 +3449,7 @@ function checkLocalGenesisCopies(ctx) {
2886
3449
  const routes = routesDir(ctx);
2887
3450
  for (const file of ctx.files) {
2888
3451
  if (!JSX_EXTS2.has(file.ext)) continue;
2889
- const imported = new Set(namedImportsFrom(file.code, GENESIS_PACKAGE));
3452
+ const imported = new Set(namedImportsFrom(file.code, GENESIS_PACKAGE2));
2890
3453
  const inRoutes = routes !== null && file.path.startsWith(`${routes}/`);
2891
3454
  const routeComponents = new Set([...file.code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Z][\w$]*)\b/g)].map((r) => r[1]));
2892
3455
  const decls = [...file.code.matchAll(decl)];
@@ -2945,13 +3508,13 @@ function checkPageLayouts(ctx) {
2945
3508
  const inShell = insideShell(ctx, routes);
2946
3509
  const rendersLayout = (code) => {
2947
3510
  const names = new Set(layouts);
2948
- for (const n of namedImportsFrom(code, GENESIS_PACKAGE)) if (PACKAGE_SCREEN.test(n)) names.add(n);
3511
+ for (const n of namedImportsFrom(code, GENESIS_PACKAGE2)) if (PACKAGE_SCREEN.test(n)) names.add(n);
2949
3512
  return rendersRe(names)?.test(code) ?? false;
2950
3513
  };
2951
- const cache = /* @__PURE__ */ new Map();
3514
+ const cache2 = /* @__PURE__ */ new Map();
2952
3515
  const provides = (r) => {
2953
- if (!cache.has(r)) cache.set(r, routeReach(ctx, r, rendersLayout));
2954
- return cache.get(r);
3516
+ if (!cache2.has(r)) cache2.set(r, routeReach(ctx, r, rendersLayout));
3517
+ return cache2.get(r);
2955
3518
  };
2956
3519
  const list = [...layouts].sort();
2957
3520
  const named = list.length > 4 ? `${list.slice(0, 4).join(", ")}, \u2026` : list.join(", ");
@@ -3000,7 +3563,7 @@ async function runDoctor(options = {}) {
3000
3563
  if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
3001
3564
  }
3002
3565
  const raw = [];
3003
- const ctx = { root, files, genesis, config, report: (f) => raw.push(f) };
3566
+ const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
3004
3567
  for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
3005
3568
  try {
3006
3569
  await plugin.check(ctx);
@@ -3032,7 +3595,8 @@ async function runDoctor(options = {}) {
3032
3595
  function builtinChecks(config) {
3033
3596
  const packs = {
3034
3597
  native: { name: "native", check: checkNativePack },
3035
- supabase: { name: "supabase", check: checkSupabasePack }
3598
+ supabase: { name: "supabase", check: checkSupabasePack },
3599
+ packages: { name: "packages", check: checkPackagesPack }
3036
3600
  };
3037
3601
  return [
3038
3602
  { name: "layout", check: checkProjectLayout },