@marktiderman/genesis-cli 1.11.3 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,276 @@ 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))) {
847
+ throw new LocalPackagesError(`${path14.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
848
+ }
849
+ let pkg;
850
+ try {
851
+ pkg = JSON.parse(readFileSync(manifest, "utf8"));
852
+ } catch {
853
+ continue;
854
+ }
855
+ if (typeof pkg.name !== "string" || !pkg.name) continue;
856
+ const rel = path14.relative(appRoot, dir).split(path14.sep).join("/");
857
+ const other = byName.get(pkg.name);
858
+ if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
859
+ byName.set(pkg.name, rel);
860
+ out.push({ name: pkg.name, dir, rel, ...typeof pkg.version === "string" ? { version: pkg.version } : {} });
861
+ }
862
+ cache.set(key2, out);
863
+ return out;
864
+ }
591
865
 
592
866
  // ../../scripts/lib/color-literals.mjs
593
867
  var LINE_COMMENT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".jsx", ".js", ".mjs", ".cjs", ".scss", ".less"]);
@@ -795,6 +1069,13 @@ function scanFiles(root, config) {
795
1069
  if (statSync(abs).isDirectory()) walk(abs);
796
1070
  else visit(abs);
797
1071
  }
1072
+ let local = [];
1073
+ try {
1074
+ local = localPackages(root);
1075
+ } catch {
1076
+ local = [];
1077
+ }
1078
+ for (const pkg of local) walk(pkg.dir);
798
1079
  return files;
799
1080
  }
800
1081
  function lineAt(text, index) {
@@ -967,7 +1248,18 @@ var BUILTIN_RULES = [
967
1248
  "migration-definer-search-path",
968
1249
  "migration-edited",
969
1250
  "migration-testing-kit",
970
- "migration-view-rls"
1251
+ "migration-view-rls",
1252
+ // packages pack
1253
+ "package-app-import",
1254
+ "package-undeclared-dependency",
1255
+ "package-migration-test",
1256
+ "package-migration-number",
1257
+ "package-migration-edited",
1258
+ "package-unregistered",
1259
+ "package-unversioned-change",
1260
+ "package-export-missing",
1261
+ "package-block-invalid",
1262
+ "package-untagged-tests"
971
1263
  ];
972
1264
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
973
1265
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -1590,1134 +1882,1416 @@ function checkStoreReadiness(ctx) {
1590
1882
  });
1591
1883
  }
1592
1884
  }
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;
1885
+
1886
+ // src/doctor/semver.ts
1887
+ var VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
1888
+ function parseVersion(v) {
1889
+ const m = VERSION.exec(v.trim());
1890
+ return m ? { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split(".") : [] } : null;
1676
1891
  }
1677
- function qualify(name) {
1678
- const n = name.trim().toLowerCase();
1679
- return n.includes(".") ? n : `public.${n}`;
1892
+ function compareVersions(a, b) {
1893
+ for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] < b[k] ? -1 : 1;
1894
+ if (!a.pre.length || !b.pre.length) return a.pre.length ? -1 : b.pre.length ? 1 : 0;
1895
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
1896
+ const x = a.pre[i];
1897
+ const y = b.pre[i];
1898
+ if (x === void 0) return -1;
1899
+ if (y === void 0) return 1;
1900
+ if (x === y) continue;
1901
+ const nx = /^\d+$/.test(x);
1902
+ const ny = /^\d+$/.test(y);
1903
+ if (nx && ny) return +x < +y ? -1 : 1;
1904
+ if (nx !== ny) return nx ? -1 : 1;
1905
+ return x < y ? -1 : 1;
1906
+ }
1907
+ return 0;
1680
1908
  }
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 };
1909
+ function partial(s) {
1910
+ const m = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(s);
1911
+ if (!m) return null;
1912
+ const nums = [];
1913
+ let wild = false;
1914
+ for (const part of [m[1], m[2], m[3]]) {
1915
+ if (wild || part === void 0 || /^[xX*]$/.test(part)) {
1916
+ wild = true;
1917
+ nums.push(null);
1918
+ } else nums.push(+part);
1687
1919
  }
1688
- return { inner: sql.slice(open + 1), end: sql.length };
1920
+ return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
1689
1921
  }
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;
1922
+ var ver = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
1923
+ function comparators(token) {
1924
+ const m = /^(\^|~>?|>=|<=|>|<|=)?\s*(.+)$/.exec(token);
1925
+ if (!m) return null;
1926
+ const op = m[1] ?? "";
1927
+ const p = partial(m[2]);
1928
+ if (!p) return null;
1929
+ const [major, mi, pa] = p.nums;
1930
+ if (major === null) return op === "<" || op === ">" ? [{ op: "<", v: ver(0, 0, 0, ["0"]) }] : [];
1931
+ const M = major;
1932
+ const lo = ver(M, mi ?? 0, pa ?? 0, p.pre);
1933
+ 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"]);
1934
+ const upper = mi === null ? next("major") : pa === null ? next("minor") : null;
1935
+ const out = switchOp();
1936
+ if (p.pre.length) {
1937
+ for (const c of out) if (c.v === lo) c.pre = true;
1697
1938
  }
1698
1939
  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;
1940
+ function switchOp() {
1941
+ switch (op) {
1942
+ case "^": {
1943
+ const bound = M > 0 || mi === null ? next("major") : (mi ?? 0) > 0 || pa === null ? next("minor") : next("patch");
1944
+ return [
1945
+ { op: ">=", v: lo },
1946
+ { op: "<", v: bound }
1947
+ ];
1948
+ }
1949
+ case "~":
1950
+ case "~>":
1951
+ return [
1952
+ { op: ">=", v: lo },
1953
+ { op: "<", v: mi === null ? next("major") : next("minor") }
1954
+ ];
1955
+ case ">":
1956
+ return upper ? [{ op: ">=", v: upper }] : [{ op: ">", v: lo }];
1957
+ case ">=":
1958
+ return [{ op: ">=", v: lo }];
1959
+ case "<":
1960
+ return [{ op: "<", v: lo.pre.length ? lo : ver(M, mi ?? 0, pa ?? 0, ["0"]) }];
1961
+ case "<=":
1962
+ return upper ? [{ op: "<", v: upper }] : [{ op: "<=", v: lo }];
1963
+ default:
1964
+ return upper ? [
1965
+ { op: ">=", v: lo },
1966
+ { op: "<", v: upper }
1967
+ ] : [{ op: "=", v: lo }];
1968
+ }
1711
1969
  }
1712
- if (cur.trim()) parts.push(cur);
1713
- return parts.map((p) => p.trim()).filter(Boolean);
1714
1970
  }
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;
1971
+ function test(c, v) {
1972
+ const d = compareVersions(v, c.v);
1973
+ return c.op === ">=" ? d >= 0 : c.op === "<=" ? d <= 0 : c.op === ">" ? d > 0 : c.op === "<" ? d < 0 : d === 0;
1742
1974
  }
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" });
1975
+ function parseRange(range) {
1976
+ const alts = [];
1977
+ for (const raw of range.trim().split("||")) {
1978
+ const alt = raw.trim();
1979
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(alt);
1980
+ if (hyphen) {
1981
+ const from = comparators(`>=${hyphen[1]}`);
1982
+ const to = comparators(`<=${hyphen[2]}`);
1983
+ if (!from || !to) return null;
1984
+ alts.push([...from, ...to]);
1761
1985
  continue;
1762
1986
  }
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
- });
1987
+ const set = [];
1988
+ for (const token of alt.replace(/(\^|~>?|>=|<=|>|<|=)\s+/g, "$1").split(/\s+/).filter(Boolean)) {
1989
+ const cs = comparators(token);
1990
+ if (!cs) return null;
1991
+ set.push(...cs);
1791
1992
  }
1993
+ alts.push(set);
1792
1994
  }
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
- }
1995
+ return alts;
1823
1996
  }
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);
1997
+ function satisfies(version, range) {
1998
+ const v = parseVersion(version);
1999
+ const alts = parseRange(range);
2000
+ if (!v || !alts) return null;
2001
+ return alts.some(
2002
+ (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))
2003
+ );
1826
2004
  }
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;
2005
+ var TRAIL_DEPTH = 6;
2006
+ var RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
2007
+ var IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
2008
+ var EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
2009
+ var DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
2010
+ function stripForImports(code) {
2011
+ const out = [];
2012
+ const blank = (ch) => ch === "\n" ? "\n" : " ";
2013
+ const n = code.length;
2014
+ const templates = [];
2015
+ let depth = 0;
2016
+ let i = 0;
2017
+ let sure = true;
2018
+ const isSpecifier = () => /(?:\bfrom|(?:^|[;{}\n])\s*import|\bimport\s*\(|\brequire\s*\()\s*$/.test(out.slice(-40).join(""));
2019
+ const before = () => out.slice(-24).join("");
2020
+ const KEYWORD = /(?:^|[^\w$.])(?:return|typeof|instanceof|case|do|else|in|of|new|delete|void|throw|yield|await|from|import|export|default|require)\s*$/;
2021
+ const startsExpression = (b) => {
2022
+ const t = b.replace(/\s+$/, "");
2023
+ if (!t) return true;
2024
+ if (KEYWORD.test(b)) return true;
2025
+ return /[([{,;:=!&|?+\-*%<>~^}]$/.test(t);
1835
2026
  };
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;
2027
+ const exprStart = () => startsExpression(before());
2028
+ const taggedTemplate = () => {
2029
+ const b = out.slice(-48).join("");
2030
+ const m = /([A-Za-z_$][\w$.]*)$/.exec(b);
2031
+ return m !== null && startsExpression(b.slice(0, b.length - m[1].length));
2032
+ };
2033
+ const templateBody = () => {
2034
+ while (i < n) {
2035
+ const ch = code[i];
2036
+ if (ch === "\\") {
2037
+ out.push(" ", blank(code[i + 1] ?? ""));
2038
+ i += 2;
2039
+ } else if (ch === "`") {
2040
+ out.push("`");
2041
+ i++;
2042
+ return;
2043
+ } else if (ch === "$" && code[i + 1] === "{") {
2044
+ out.push("${");
2045
+ i += 2;
2046
+ templates.push(depth);
2047
+ depth++;
2048
+ return;
2049
+ } else {
2050
+ out.push(blank(ch));
2051
+ i++;
1853
2052
  }
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;
2053
+ }
2054
+ sure = false;
2055
+ };
2056
+ while (i < n && sure) {
2057
+ const ch = code[i];
2058
+ const next = code[i + 1];
2059
+ if (ch === "/" && next === "/") {
2060
+ while (i < n && code[i] !== "\n") {
2061
+ out.push(" ");
2062
+ i++;
1869
2063
  }
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
- }
2064
+ } else if (ch === "/" && next === "*") {
2065
+ out.push(" ");
2066
+ i += 2;
2067
+ while (i < n && !(code[i] === "*" && code[i + 1] === "/")) {
2068
+ out.push(blank(code[i]));
2069
+ i++;
1884
2070
  }
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;
2071
+ if (i < n) {
2072
+ out.push(" ");
2073
+ i += 2;
1899
2074
  }
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);
2075
+ } else if (ch === "/" && next !== ">" && code[i - 1] !== "<" && exprStart()) {
2076
+ const afterBrace = /[}>]\s*$/.test(before());
2077
+ const start = i;
2078
+ const mark = out.length;
2079
+ out.push("/");
2080
+ i++;
2081
+ let inClass = false;
2082
+ for (; ; ) {
2083
+ const c = code[i];
2084
+ if (c === void 0 || c === "\n") {
2085
+ if (afterBrace) {
2086
+ out.length = mark;
2087
+ out.push("/");
2088
+ i = start + 1;
2089
+ } else sure = false;
2090
+ break;
1909
2091
  }
1910
- continue;
2092
+ if (c === "\\") {
2093
+ out.push(" ", blank(code[i + 1] ?? ""));
2094
+ i += 2;
2095
+ continue;
2096
+ }
2097
+ i++;
2098
+ if (c === "[") inClass = true;
2099
+ else if (c === "]") inClass = false;
2100
+ else if (c === "/" && !inClass) {
2101
+ if (afterBrace && /[<>]/.test(code.slice(start + 1, i - 1))) {
2102
+ out.length = mark;
2103
+ out.push("/");
2104
+ i = start + 1;
2105
+ break;
2106
+ }
2107
+ out.push("/");
2108
+ break;
2109
+ }
2110
+ out.push(" ");
1911
2111
  }
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;
2112
+ if (out.length > mark + 1 || i > start + 1) while (i < n && /[a-z]/.test(code[i])) out.push(code[i++]);
2113
+ } else if ((ch === '"' || ch === "'") && exprStart()) {
2114
+ const keep = isSpecifier();
2115
+ out.push(ch);
2116
+ i++;
2117
+ while (i < n && code[i] !== ch && code[i] !== "\n") {
2118
+ if (code[i] === "\\") {
2119
+ out.push(keep ? code[i] : " ", keep ? code[i + 1] ?? "" : blank(code[i + 1] ?? ""));
2120
+ i += 2;
2121
+ } else {
2122
+ out.push(keep ? code[i] : blank(code[i]));
2123
+ i++;
1919
2124
  }
1920
- continue;
1921
2125
  }
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));
2126
+ if (code[i] !== ch) sure = false;
2127
+ else {
2128
+ out.push(code[i]);
2129
+ i++;
2130
+ }
2131
+ } else if (ch === "`" && (exprStart() || taggedTemplate())) {
2132
+ out.push("`");
2133
+ i++;
2134
+ templateBody();
2135
+ } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
2136
+ templates.pop();
2137
+ depth--;
2138
+ out.push("}");
2139
+ i++;
2140
+ templateBody();
2141
+ } else {
2142
+ if (ch === "{") depth++;
2143
+ else if (ch === "}") depth--;
2144
+ out.push(ch);
2145
+ i++;
1924
2146
  }
1925
2147
  }
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
- }
2148
+ return sure && templates.length === 0 ? out.join("") : null;
1936
2149
  }
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
- }
2150
+ function bindings(clause) {
2151
+ const out = [];
2152
+ const named = /\{([^}]*)\}/.exec(clause);
2153
+ for (const part of named?.[1].split(",") ?? []) {
2154
+ const p = part.trim();
2155
+ if (!p || p.startsWith("type ")) continue;
2156
+ out.push(p.split(/\s+as\s+/).pop().trim());
1969
2157
  }
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
- });
2158
+ const rest = clause.replace(/\{[^}]*\}/, "");
2159
+ const ns = /\*\s*as\s+([\w$]+)/.exec(rest);
2160
+ if (ns) out.push(ns[1]);
2161
+ const def = /^\s*([\w$]+)/.exec(rest);
2162
+ if (def && def[1] !== "as") out.push(def[1]);
2163
+ return out;
2164
+ }
2165
+ function readJsonc(file) {
2166
+ try {
2167
+ const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str ?? "").replace(/,(\s*[}\]])/g, "$1");
2168
+ return JSON.parse(text);
2169
+ } catch {
2170
+ return null;
1979
2171
  }
1980
2172
  }
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
- }
2173
+ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
2174
+ if (seen.has(file) || seen.size > 10) return {};
2175
+ seen.add(file);
2176
+ const json = readJsonc(file);
2177
+ if (!json) return {};
2178
+ const dir = path14.dirname(file);
2179
+ let merged = {};
2180
+ const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
2181
+ for (const ext of parents) {
2182
+ if (typeof ext !== "string") continue;
2183
+ let target = null;
2184
+ if (ext.startsWith(".") || path14.isAbsolute(ext)) {
2185
+ const abs = path14.resolve(dir, ext);
2186
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2187
+ } else {
2188
+ const parts = ext.split("/");
2189
+ const nameLength = ext.startsWith("@") ? 2 : 1;
2190
+ const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
2191
+ if (pkgDir) {
2192
+ const sub = parts.slice(nameLength).join("/");
2193
+ const abs = path14.join(pkgDir, sub || "tsconfig.json");
2194
+ target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2029
2195
  }
2030
2196
  }
2197
+ if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
2031
2198
  }
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
- });
2199
+ const opts = json.compilerOptions ?? {};
2200
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
2201
+ if (opts.paths && typeof opts.paths === "object") {
2202
+ merged.paths = opts.paths;
2203
+ merged.pathsDir = dir;
2041
2204
  }
2205
+ return merged;
2042
2206
  }
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
- });
2207
+ function aliases(root) {
2208
+ const table = [];
2209
+ let baseUrl = null;
2210
+ for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
2211
+ const file = path14.join(root, name);
2212
+ if (!existsSync(file)) continue;
2213
+ const config = readTsconfig(root, file);
2214
+ baseUrl ??= config.baseUrl ?? null;
2215
+ const base = config.baseUrl ?? config.pathsDir ?? root;
2216
+ for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
2217
+ if (!Array.isArray(targets)) continue;
2218
+ const exact = !pattern.endsWith("*");
2219
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
2220
+ }
2065
2221
  }
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;
2222
+ const pkg = readJsonc(path14.join(root, "package.json"));
2223
+ for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
2224
+ if (typeof target !== "string") continue;
2225
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
2088
2226
  }
2089
- return 0;
2227
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
2228
+ return { table, baseUrl };
2090
2229
  }
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);
2230
+ function resolveFile(base) {
2231
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
2232
+ if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
2233
+ for (const p of tries) {
2234
+ if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
2101
2235
  }
2102
- return { nums, pre: m[4] && !wild ? m[4].split(".") : [] };
2236
+ return null;
2103
2237
  }
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;
2238
+ var trails = /* @__PURE__ */ new WeakMap();
2239
+ function trailFor(ctx) {
2240
+ let t = trails.get(ctx.files);
2241
+ if (!t) trails.set(ctx.files, t = createTrail(ctx));
2242
+ return t;
2243
+ }
2244
+ function createTrail(ctx) {
2245
+ const { table, baseUrl } = aliases(ctx.root);
2246
+ let declared = null;
2247
+ try {
2248
+ const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
2249
+ declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
2250
+ } catch {
2251
+ declared = null;
2120
2252
  }
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
- ];
2253
+ const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
2254
+ const read = (abs) => byPath.get(abs) ?? readSource(abs);
2255
+ const importsCache = /* @__PURE__ */ new Map();
2256
+ const importsOf = (file) => {
2257
+ const hit = importsCache.get(file.absolutePath);
2258
+ if (hit) return hit;
2259
+ const files = [];
2260
+ let lost = false;
2261
+ const code = stripped(file);
2262
+ if (code === null) {
2263
+ const out2 = { files: [], lost: true };
2264
+ importsCache.set(file.absolutePath, out2);
2265
+ return out2;
2266
+ }
2267
+ const used = new Set(renderedElements(code).map((e) => e.split(".")[0]));
2268
+ for (const m of code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
2269
+ for (const m of code.matchAll(/\bexport\s+default\s+([A-Za-z_$][\w$]*)/g)) used.add(m[1]);
2270
+ 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]);
2271
+ const specs = [];
2272
+ for (const m of code.matchAll(IMPORT_FROM)) if (!m[1] && bindings(m[2]).some((b) => used.has(b))) specs.push(m[3]);
2273
+ for (const m of code.matchAll(EXPORT_FROM)) if (!m[1]) specs.push(m[2]);
2274
+ for (const m of code.matchAll(DYNAMIC)) specs.push(m[1]);
2275
+ for (const spec of specs) {
2276
+ if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
2277
+ let resolved = null;
2278
+ if (spec.startsWith(".")) {
2279
+ resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
2280
+ if (!resolved) lost = true;
2281
+ } else {
2282
+ const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
2283
+ if (alias) {
2284
+ for (const t of alias.targets) {
2285
+ resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
2286
+ if (resolved) break;
2287
+ }
2288
+ }
2289
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
2290
+ if (!resolved) {
2291
+ const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
2292
+ if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
2293
+ }
2130
2294
  }
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 }];
2295
+ if (resolved && !files.includes(resolved)) files.push(resolved);
2150
2296
  }
2151
- }
2152
- }
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;
2297
+ const out = { files, lost };
2298
+ importsCache.set(file.absolutePath, out);
2299
+ return out;
2300
+ };
2301
+ const strippedCache = /* @__PURE__ */ new Map();
2302
+ const stripped = (file) => {
2303
+ if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
2304
+ return strippedCache.get(file.absolutePath);
2305
+ };
2306
+ const memo = /* @__PURE__ */ new WeakMap();
2307
+ const reach = (file, test2, depth, seen) => {
2308
+ let cache2 = memo.get(test2);
2309
+ if (!cache2) memo.set(test2, cache2 = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
2310
+ const k = `${file.absolutePath}\0${depth}`;
2311
+ const free = cache2.free.get(k);
2312
+ if (free) return [free, /* @__PURE__ */ new Set()];
2313
+ const reusable = cache2.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
2314
+ if (reusable) return [reusable.result, new Set(reusable.cut)];
2315
+ let result;
2316
+ const cut = /* @__PURE__ */ new Set();
2317
+ const code = stripped(file);
2318
+ if (code === null) result = "unknown";
2319
+ else if (test2(code)) result = "yes";
2320
+ else {
2321
+ const { files, lost } = importsOf(file);
2322
+ let unknown = lost && depth > 0;
2323
+ result = "no";
2324
+ if (depth > 0) {
2325
+ seen.add(file.absolutePath);
2326
+ for (const abs of files) {
2327
+ if (seen.has(abs)) {
2328
+ cut.add(abs);
2329
+ continue;
2330
+ }
2331
+ const target = read(abs);
2332
+ if (!target) {
2333
+ unknown = true;
2334
+ continue;
2335
+ }
2336
+ const [r, c] = reach(target, test2, depth - 1, seen);
2337
+ for (const m of c) cut.add(m);
2338
+ if (r === "yes") {
2339
+ result = "yes";
2340
+ break;
2341
+ }
2342
+ if (r === "unknown") unknown = true;
2343
+ }
2344
+ seen.delete(file.absolutePath);
2345
+ cut.delete(file.absolutePath);
2346
+ }
2347
+ if (result === "no" && unknown) result = "unknown";
2168
2348
  }
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);
2349
+ if (result === "yes" || cut.size === 0) {
2350
+ cache2.free.set(k, result);
2351
+ return [result, /* @__PURE__ */ new Set()];
2174
2352
  }
2175
- alts.push(set);
2176
- }
2177
- return alts;
2178
- }
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
- );
2353
+ const entries = cache2.cut.get(k) ?? [];
2354
+ entries.push({ cut: [...cut], result });
2355
+ cache2.cut.set(k, entries);
2356
+ return [result, cut];
2357
+ };
2358
+ return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
2186
2359
  }
2187
2360
 
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;
2361
+ // src/doctor/packages.ts
2362
+ var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
2363
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
2364
+ var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
2365
+ var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
2366
+ var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
2367
+ function sourceFiles(dir, rel = "") {
2368
+ const out = [];
2369
+ for (const entry of readdirSync(path14.join(dir, rel)).sort()) {
2370
+ if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
2371
+ const child = rel ? `${rel}/${entry}` : entry;
2372
+ const stat = lstatSync(path14.join(dir, child));
2373
+ if (stat.isSymbolicLink()) continue;
2374
+ if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
2375
+ else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
2197
2376
  }
2198
- };
2199
- var real = (p) => {
2377
+ return out;
2378
+ }
2379
+ function packageName2(specifier) {
2380
+ const parts = specifier.split("/");
2381
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
2382
+ }
2383
+ function git(root, args) {
2384
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2385
+ return r.status === 0 ? r.stdout : null;
2386
+ }
2387
+ function matchPattern(pattern, spec) {
2388
+ const star = pattern.indexOf("*");
2389
+ if (star < 0) return pattern === spec ? "" : null;
2390
+ const head = pattern.slice(0, star);
2391
+ const tail = pattern.slice(star + 1);
2392
+ return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
2393
+ }
2394
+ function tsconfigPaths(dir) {
2395
+ const file = path14.join(dir, "tsconfig.json");
2396
+ if (!existsSync(file)) return [];
2200
2397
  try {
2201
- return realpathSync(p);
2398
+ const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
2399
+ const options = JSON.parse(text).compilerOptions ?? {};
2400
+ const base = path14.resolve(dir, options.baseUrl ?? ".");
2401
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path14.resolve(base, t)) }));
2202
2402
  } catch {
2203
- return p;
2403
+ return [];
2404
+ }
2405
+ }
2406
+ function checkImports2(ctx, pkg, json) {
2407
+ const aliases2 = tsconfigPaths(pkg.dir);
2408
+ const subpathImports = Object.keys(json.imports ?? {});
2409
+ const viaAlias = (spec) => {
2410
+ if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
2411
+ for (const { pattern, targets } of aliases2) {
2412
+ const hit = matchPattern(pattern, spec);
2413
+ if (hit === null) continue;
2414
+ return targets.some((t) => {
2415
+ const rel = path14.relative(pkg.dir, t.replace("*", hit));
2416
+ return !rel.startsWith("..") && !path14.isAbsolute(rel);
2417
+ });
2418
+ }
2419
+ return null;
2420
+ };
2421
+ const declared = /* @__PURE__ */ new Set([
2422
+ json.name,
2423
+ ...Object.keys(json.dependencies ?? {}),
2424
+ ...Object.keys(json.peerDependencies ?? {}),
2425
+ ...Object.keys(json.devDependencies ?? {}),
2426
+ ...Object.keys(json.optionalDependencies ?? {})
2427
+ ]);
2428
+ for (const file of sourceFiles(pkg.dir)) {
2429
+ const code = stripForImports(readFileSync(path14.join(pkg.dir, file), "utf8"));
2430
+ if (code === null) continue;
2431
+ const at = `${pkg.rel}/${file}`;
2432
+ const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
2433
+ let offset = 0;
2434
+ code.split("\n").forEach((text, i) => {
2435
+ const lineStart = offset;
2436
+ offset += text.length + 1;
2437
+ for (const m of text.matchAll(IMPORT)) {
2438
+ const spec = m[1];
2439
+ const line = i + 1;
2440
+ const at0 = lineStart + m.index;
2441
+ if (typeOnly.some(([a, b]) => at0 >= a && at0 < b)) continue;
2442
+ const alias = viaAlias(spec);
2443
+ if (alias === true) continue;
2444
+ if (alias === false) {
2445
+ ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} imports ${spec}, an alias that points outside the package` });
2446
+ continue;
2447
+ }
2448
+ if (spec.startsWith("#")) continue;
2449
+ if (spec.startsWith("@/") || spec.startsWith("~/")) {
2450
+ 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` });
2451
+ continue;
2452
+ }
2453
+ if (spec.startsWith(".")) {
2454
+ const target = path14.resolve(pkg.dir, path14.dirname(file), spec);
2455
+ const rel = path14.relative(pkg.dir, target);
2456
+ if (rel.startsWith("..") || path14.isAbsolute(rel)) {
2457
+ 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` });
2458
+ }
2459
+ continue;
2460
+ }
2461
+ if (BUILTINS.has(spec) || spec.startsWith("node:") || spec.startsWith("virtual:") || /^[a-z]+:/.test(spec)) continue;
2462
+ const name = packageName2(spec);
2463
+ if (!declared.has(name)) {
2464
+ 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` });
2465
+ }
2466
+ }
2467
+ });
2204
2468
  }
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
2469
  }
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 {
2470
+ function checkMigrations(ctx, pkg, json) {
2471
+ const declaredFiles = /* @__PURE__ */ new Set();
2472
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
2473
+ const migrations = raw.migrations ?? [];
2474
+ for (const m of migrations) {
2475
+ if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
2476
+ if (typeof m.file === "string" && typeof m.test !== "string") {
2477
+ 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` });
2478
+ } else if (typeof m.test === "string" && !existsSync(path14.join(pkg.dir, m.test))) {
2479
+ 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` });
2221
2480
  }
2222
- } else {
2223
- out.push(p);
2224
2481
  }
2225
2482
  }
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());
2483
+ const dir = path14.join(pkg.dir, "migrations");
2484
+ if (!existsSync(dir)) return;
2485
+ const seen = /* @__PURE__ */ new Map();
2486
+ for (const name of readdirSync(dir).sort()) {
2487
+ const m = MIGRATION_FILE.exec(name);
2488
+ if (!m) continue;
2489
+ const other = seen.get(m[1]);
2490
+ 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` });
2491
+ else seen.set(m[1], name);
2492
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path14.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
2493
+ 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")})` });
2239
2494
  }
2240
- via.get(real2).add(root2);
2241
- if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
2495
+ }
2496
+ }
2497
+ function checkExports(ctx, pkg, json) {
2498
+ const targets = [];
2499
+ const walk = (v) => {
2500
+ if (typeof v === "string") targets.push(v);
2501
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk(x);
2242
2502
  };
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);
2268
- }
2503
+ walk(json.exports);
2504
+ for (const t of targets) {
2505
+ if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
2506
+ if (!existsSync(path14.join(pkg.dir, t))) {
2507
+ ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
2269
2508
  }
2270
- };
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;
2278
- };
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
2292
- };
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" }))
2509
+ }
2510
+ }
2511
+ function checkBlocks(ctx, pkg, json) {
2512
+ for (const [id, raw] of Object.entries(rawBlocksOf(json))) {
2513
+ try {
2514
+ parseManifest(json.name, id, raw, json.version, { local: true });
2515
+ } catch (err) {
2516
+ if (!(err instanceof ManifestError)) throw err;
2517
+ for (const problem of err.problems) ctx.report({ rule: "package-block-invalid", file: `${pkg.rel}/package.json`, subject: id, message: problem });
2518
+ }
2519
+ }
2520
+ }
2521
+ function checkTaggedTests(ctx, pkg) {
2522
+ const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
2523
+ if (!tests.length) return;
2524
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path14.join(pkg.dir, f), "utf8")));
2525
+ 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>` });
2526
+ }
2527
+ function checkRegistered(ctx, pkg) {
2528
+ const file = path14.join(ctx.root, "features.json");
2529
+ if (!existsSync(file)) return;
2530
+ let doc;
2531
+ try {
2532
+ doc = JSON.parse(readFileSync(file, "utf8"));
2533
+ } catch {
2534
+ return;
2535
+ }
2536
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
2537
+ const forms = /* @__PURE__ */ new Set([pkg.rel]);
2538
+ if (top) forms.add(path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/"));
2539
+ const covered = (doc.features ?? []).some(
2540
+ (f) => (f.links?.code ?? []).some((c) => {
2541
+ const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
2542
+ return [...forms].some((rel) => norm === rel || norm.startsWith(`${rel}/`) || rel.startsWith(`${norm}/`));
2543
+ })
2302
2544
  );
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");
2545
+ if (!covered) {
2546
+ 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
2547
  }
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
2548
  }
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;
2549
+ function changesetNames(text) {
2550
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
2551
+ const names = /* @__PURE__ */ new Set();
2552
+ if (!m) return names;
2553
+ for (const line of m[1].split(/\r?\n/)) {
2554
+ const entry = /^\s*(?:"([^"]+)"|'([^']+)'|([^\s:'"]+))\s*:\s*(major|minor|patch)\s*$/.exec(line);
2555
+ if (entry) names.add(entry[1] ?? entry[2] ?? entry[3]);
2556
+ }
2557
+ return names;
2558
+ }
2559
+ function mergeBaseOf(root, base) {
2560
+ if (git(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository" };
2561
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) return { reason: `the git ref ${base} isn't available (fetch it)` };
2562
+ const sha = git(root, ["merge-base", "HEAD", base])?.trim();
2563
+ return sha ? { sha } : { reason: `HEAD has no merge base with ${base} (fetch with depth 0)` };
2564
+ }
2565
+ function checkChanges(ctx, pkg, json, base, mergeBase) {
2566
+ const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
2567
+ if (!top) return;
2568
+ const appRelative = (fromTop) => path14.relative(realpathSync(ctx.root), path14.join(top, fromTop)).split(path14.sep).join("/");
2569
+ const inRepo = path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/");
2570
+ const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell, i) => i === 0 ? cell : appRelative(cell)).join(" ")).join("\n");
2571
+ const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
2572
+ const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
2573
+ (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
2574
+ );
2575
+ for (const row of diff.split("\n").filter(Boolean)) {
2576
+ const [status, a] = row.split(" ");
2577
+ if (a && /\/migrations\/\d{4}_[a-z0-9_]+\.sql$/.test(a) && /^[MDRT]/.test(status)) {
2578
+ 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
2579
  }
2580
+ }
2581
+ if (!changed.length) return;
2582
+ const before = git(ctx.root, ["show", `${mergeBase}:./${pkg.rel}/package.json`]);
2583
+ let versionBefore;
2584
+ try {
2585
+ versionBefore = before ? JSON.parse(before).version : void 0;
2586
+ } catch {
2587
+ versionBefore = void 0;
2588
+ }
2589
+ const now = typeof json.version === "string" ? parseVersion(json.version) : null;
2590
+ const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
2591
+ const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
2592
+ 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)) : [];
2593
+ const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
2594
+ const named = naming.length > 0;
2595
+ if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
2596
+ 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` });
2597
+ }
2598
+ let jsonBefore = null;
2599
+ try {
2600
+ jsonBefore = before ? JSON.parse(before) : null;
2601
+ } catch {
2602
+ jsonBefore = null;
2603
+ }
2604
+ const raw = json;
2605
+ if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
2606
+ const registry = (git(ctx.root, ["diff", "--relative", "--name-only", mergeBase, "--", "features.ts", "src/features.ts"]) ?? "").trim();
2607
+ 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` });
2608
+ }
2609
+ if (bumped && !named && before !== null) {
2610
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: `${pkg.rel}/package.json`, message: `${pkg.name}'s version went up without a changeset; add one with a "Features:" line so the change is recorded` });
2611
+ }
2612
+ if (!bumped && !named) {
2331
2613
  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`
2614
+ rule: "package-unversioned-change",
2615
+ level: "warn",
2616
+ file: `${pkg.rel}/package.json`,
2617
+ 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
2618
  });
2338
2619
  }
2339
2620
  }
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
- }
2621
+ function checkPackagesPack(ctx) {
2622
+ let packages;
2623
+ try {
2624
+ packages = localPackages(ctx.root);
2625
+ } catch (err) {
2626
+ ctx.report({ rule: "package-block-invalid", file: "genesis.config.json", message: err.message });
2627
+ return;
2628
+ }
2629
+ if (!packages.length) return;
2630
+ const base = ctx.base ?? ctx.config.packages?.base;
2631
+ const merge = base ? mergeBaseOf(ctx.root, base) : { reason: "no base ref (pass --base <ref>, e.g. --base origin/main)" };
2632
+ if ("reason" in merge) {
2633
+ ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
2634
+ }
2635
+ for (const pkg of packages) {
2636
+ const json = JSON.parse(readFileSync(path14.join(pkg.dir, "package.json"), "utf8"));
2637
+ checkImports2(ctx, pkg, json);
2638
+ checkExports(ctx, pkg, json);
2639
+ checkBlocks(ctx, pkg, json);
2640
+ checkMigrations(ctx, pkg, json);
2641
+ checkTaggedTests(ctx, pkg);
2642
+ checkRegistered(ctx, pkg);
2643
+ if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
2362
2644
  }
2363
2645
  }
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) {
2646
+ var DEFAULT_MIGRATIONS = "supabase/migrations";
2647
+ var DEFAULT_BASE = "origin/main";
2648
+ var DEFAULT_EXPOSED = ["public"];
2649
+ function sqlStatements(text) {
2370
2650
  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);
2651
+ let buf = "";
2652
+ let bodies = [];
2653
+ let line = 1;
2654
+ let start = 0;
2655
+ const flush = () => {
2656
+ const sql = buf.replace(/\s+/g, " ").trim().toLowerCase();
2657
+ if (sql) out.push({ sql, line: start, bodies });
2658
+ buf = "";
2659
+ bodies = [];
2660
+ start = 0;
2385
2661
  };
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));
2662
+ const put = (s) => {
2663
+ if (!start && /\S/.test(s)) start = line;
2664
+ buf += s;
2391
2665
  };
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;
2414
- };
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("/");
2666
+ let i = 0;
2667
+ while (i < text.length) {
2668
+ const ch = text[i];
2669
+ const two = text.slice(i, i + 2);
2670
+ if (ch === "\n") {
2671
+ buf += " ";
2672
+ line++;
2439
2673
  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] ?? ""));
2674
+ } else if (two === "--") {
2675
+ while (i < text.length && text[i] !== "\n") i++;
2676
+ } else if (two === "/*") {
2677
+ let depth = 0;
2678
+ while (i < text.length) {
2679
+ if (text.startsWith("/*", i)) {
2680
+ depth++;
2453
2681
  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] ?? ""));
2682
+ } else if (text.startsWith("*/", i)) {
2683
+ depth--;
2479
2684
  i += 2;
2685
+ if (depth === 0) break;
2480
2686
  } else {
2481
- out.push(keep ? code[i] : blank(code[i]));
2687
+ if (text[i] === "\n") line++;
2482
2688
  i++;
2483
2689
  }
2484
2690
  }
2485
- if (code[i] !== ch) sure = false;
2486
- else {
2487
- out.push(code[i]);
2488
- i++;
2691
+ buf += " ";
2692
+ } else if (ch === "'") {
2693
+ const escapes = /[eE]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i - 2] ?? "");
2694
+ put("'");
2695
+ i++;
2696
+ while (i < text.length) {
2697
+ if (escapes && text[i] === "\\") i += 2;
2698
+ else if (text[i] === "'" && text[i + 1] === "'") i += 2;
2699
+ else if (text[i] === "'") break;
2700
+ else {
2701
+ if (text[i] === "\n") line++;
2702
+ i++;
2703
+ }
2489
2704
  }
2490
- } else if (ch === "`" && (exprStart() || taggedTemplate())) {
2491
- out.push("`");
2705
+ put("'");
2492
2706
  i++;
2493
- templateBody();
2494
- } else if (ch === "}" && templates.length && depth - 1 === templates[templates.length - 1]) {
2495
- templates.pop();
2496
- depth--;
2497
- out.push("}");
2707
+ } else if (ch === '"') {
2708
+ i++;
2709
+ while (i < text.length && text[i] !== '"') put(text[i++]);
2710
+ i++;
2711
+ } else if (ch === "$" && !/[\w$]/.test(text[i - 1] ?? "") && /^\$(?:[A-Za-z_]\w*)?\$/.test(text.slice(i))) {
2712
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(text.slice(i))[0];
2713
+ const end = text.indexOf(tag, i + tag.length);
2714
+ const stop = end === -1 ? text.length : end + tag.length;
2715
+ bodies.push(text.slice(i + tag.length, end === -1 ? text.length : end).toLowerCase());
2716
+ for (let k = i; k < stop; k++) if (text[k] === "\n") line++;
2717
+ put(`${tag} ${tag}`);
2718
+ i = stop;
2719
+ } else if (ch === ";") {
2720
+ flush();
2498
2721
  i++;
2499
- templateBody();
2500
2722
  } else {
2501
- if (ch === "{") depth++;
2502
- else if (ch === "}") depth--;
2503
- out.push(ch);
2723
+ put(ch);
2504
2724
  i++;
2505
2725
  }
2506
2726
  }
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]);
2727
+ flush();
2522
2728
  return out;
2523
2729
  }
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
- }
2730
+ function qualify(name) {
2731
+ const n = name.trim().toLowerCase();
2732
+ return n.includes(".") ? n : `public.${n}`;
2531
2733
  }
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;
2734
+ var schemaOf = (name) => name.split(".")[0];
2735
+ function parenthesized(sql, open) {
2736
+ let depth = 0;
2737
+ for (let k = open; k < sql.length; k++) {
2738
+ if (sql[k] === "(") depth++;
2739
+ else if (sql[k] === ")" && --depth === 0) return { inner: sql.slice(open + 1, k), end: k + 1 };
2563
2740
  }
2564
- return merged;
2741
+ return { inner: sql.slice(open + 1), end: sql.length };
2565
2742
  }
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(/\*.*$/, ""))] });
2743
+ function stripParens(s) {
2744
+ let out = "";
2745
+ let depth = 0;
2746
+ for (const c of s) {
2747
+ if (c === "(") depth++;
2748
+ else if (c === ")") depth = Math.max(0, depth - 1);
2749
+ else if (depth === 0) out += c;
2585
2750
  }
2586
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
2587
- return { table, baseUrl };
2751
+ return out;
2588
2752
  }
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;
2753
+ function splitTop(s) {
2754
+ const parts = [];
2755
+ let depth = 0;
2756
+ let cur = "";
2757
+ for (const c of s) {
2758
+ if (c === "(") depth++;
2759
+ if (c === ")") depth--;
2760
+ if (c === "," && depth === 0) {
2761
+ parts.push(cur);
2762
+ cur = "";
2763
+ } else cur += c;
2594
2764
  }
2595
- return null;
2765
+ if (cur.trim()) parts.push(cur);
2766
+ return parts.map((p) => p.trim()).filter(Boolean);
2596
2767
  }
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;
2768
+ var TYPE_ALIASES = {
2769
+ int: "integer",
2770
+ int4: "integer",
2771
+ int8: "bigint",
2772
+ int2: "smallint",
2773
+ bool: "boolean",
2774
+ varchar: "character varying",
2775
+ timestamptz: "timestamp with time zone",
2776
+ float8: "double precision"
2777
+ };
2778
+ var MULTIWORD_TYPE = /^(?:double precision|character varying|character|bit varying|timestamp|time|interval)\b/;
2779
+ function argTypes(args) {
2780
+ const types = [];
2781
+ for (const raw of splitTop(args)) {
2782
+ let tokens = stripParens(raw.replace(/\s+(?:default\b|=).*$/, "")).trim().split(/\s+/).filter(Boolean);
2783
+ const mode = tokens[0];
2784
+ if (mode === "out") continue;
2785
+ if (mode === "in" || mode === "inout" || mode === "variadic") tokens = tokens.slice(1);
2786
+ const joined = tokens.join(" ");
2787
+ const type = tokens.length > 1 && !MULTIWORD_TYPE.test(joined) ? tokens.slice(1).join(" ") : joined;
2788
+ types.push(TYPE_ALIASES[type] ?? type);
2789
+ }
2790
+ return types;
2602
2791
  }
2603
- function createTrail(ctx) {
2604
- const { table, baseUrl } = aliases(ctx.root);
2605
- let declared = null;
2792
+ function git2(root, args) {
2793
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2794
+ return r.status === 0 ? r.stdout : null;
2795
+ }
2796
+ function gitView(root, dir, base) {
2797
+ if (git2(root, ["rev-parse", "--is-inside-work-tree"])?.trim() !== "true") return { reason: "not a git repository", repo: false };
2798
+ if (git2(root, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]) === null) {
2799
+ return { reason: `the git ref ${base} isn't available (fetch it, or set doctor.supabase.base)`, repo: true };
2800
+ }
2801
+ const mergeBase = git2(root, ["merge-base", "HEAD", base])?.trim();
2802
+ if (!mergeBase) return { reason: `HEAD has no merge base with ${base} (a shallow clone? fetch with depth 0)`, repo: true };
2803
+ const diff = git2(root, ["diff", "--relative", "--name-status", "-M", mergeBase, "--", dir]);
2804
+ const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
2805
+ if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
2806
+ const sql = (p) => p !== void 0 && p.endsWith(".sql");
2807
+ const touched = new Set(untracked.split("\n").filter(sql));
2808
+ const edited = [];
2809
+ for (const row of diff.split("\n").filter(Boolean)) {
2810
+ const [status, a, b] = row.split(" ");
2811
+ if (status.startsWith("R")) {
2812
+ if (sql(b)) touched.add(b);
2813
+ if (sql(a)) edited.push({ file: a, status: "renamed" });
2814
+ continue;
2815
+ }
2816
+ if (!sql(a)) continue;
2817
+ if (status.startsWith("A")) touched.add(a);
2818
+ else if (status.startsWith("M") || status.startsWith("T")) {
2819
+ touched.add(a);
2820
+ edited.push({ file: a, status: "modified" });
2821
+ } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
2822
+ }
2823
+ return { touched, edited };
2824
+ }
2825
+ function checkSupabasePack(ctx) {
2826
+ const settings = ctx.config.supabase ?? {};
2827
+ const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
2828
+ const abs = path14.join(ctx.root, dir);
2829
+ if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
2830
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
2831
+ const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
2832
+ const base = settings.base ?? DEFAULT_BASE;
2833
+ const view = gitView(ctx.root, dir, base);
2834
+ if ("reason" in view) {
2835
+ if (view.repo) ctx.report({ rule: "migration-edited", level: "warn", file: dir, message: `can't check for edited migrations: ${view.reason}` });
2836
+ } else {
2837
+ for (const e of view.edited) {
2838
+ ctx.report({
2839
+ rule: "migration-edited",
2840
+ file: e.file,
2841
+ subject: e.file,
2842
+ 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`
2843
+ });
2844
+ }
2845
+ }
2846
+ const since = settings.since;
2847
+ const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
2848
+ if ("reason" in view && since === void 0) {
2849
+ ctx.report({
2850
+ rule: "migration-grants",
2851
+ level: "warn",
2852
+ file: dir,
2853
+ 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`
2854
+ });
2855
+ } else {
2856
+ const isNew = (file) => afterSince(file) && ("reason" in view || view.touched.has(file));
2857
+ checkGrants(ctx, migrations.filter((m) => isNew(m.file)), exposed);
2858
+ }
2859
+ checkRls(ctx, migrations, exposed);
2860
+ checkViewInvoker(ctx, migrations, exposed);
2861
+ checkDefinerSearchPath(ctx, migrations);
2862
+ checkTestingKit(ctx, migrations);
2863
+ }
2864
+ function checkTestingKit(ctx, migrations) {
2865
+ for (const { file, statements } of migrations) {
2866
+ const hit = statements.find(({ sql }) => /\bgenesis_testing\b/.test(sql));
2867
+ if (!hit) continue;
2868
+ ctx.report({
2869
+ rule: "migration-testing-kit",
2870
+ file,
2871
+ line: hit.line,
2872
+ subject: "genesis_testing",
2873
+ message: "a migration uses genesis_testing, the pgTAP kit for test databases only; move it to supabase/tests/database/000_genesis_testing.test.sql"
2874
+ });
2875
+ }
2876
+ }
2877
+ function granteesOf(s) {
2878
+ return s.replace(/\s+granted by .*$/, "").replace(/\s+with grant option$/, "").split(/\s*,\s*/).map((r) => r.replace(/^group\s+/, "").trim()).filter(Boolean);
2879
+ }
2880
+ function checkGrants(ctx, migrations, exposed) {
2881
+ const fix = "grant by name (grant execute on function schema.fn(args) to role) so an earlier revoke survives";
2882
+ const open = (roles) => roles.filter((r) => r === "anon" || r === "public");
2883
+ const blanket = (roles) => {
2884
+ const o = open(roles);
2885
+ if (o.length) return { level: "error", who: o.join(" and ") };
2886
+ if (roles.includes("authenticated")) return { level: "warn", who: "authenticated" };
2887
+ return null;
2888
+ };
2889
+ for (const { file, statements } of migrations) {
2890
+ for (const { sql, line } of statements) {
2891
+ const all = /^grant\b.*\bon all (?:functions|routines|procedures) in schema .+? to (.+)$/.exec(sql);
2892
+ if (all) {
2893
+ const hit = blanket(granteesOf(all[1]));
2894
+ if (hit) {
2895
+ 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}` });
2896
+ }
2897
+ continue;
2898
+ }
2899
+ const defaults = /^alter default privileges\b.*?\bgrant\b.*\bon (?:functions|routines) to (.+)$/.exec(sql);
2900
+ if (defaults) {
2901
+ const hit = blanket(granteesOf(defaults[1]));
2902
+ if (hit) {
2903
+ 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}` });
2904
+ }
2905
+ continue;
2906
+ }
2907
+ const fn = /^grant\b.*?\bon (?:function|procedure|routine)s? (.+?) to (.+)$/.exec(sql);
2908
+ if (fn) {
2909
+ const roles = open(granteesOf(fn[2]));
2910
+ if (!roles.length) continue;
2911
+ for (const name of splitTop(fn[1]).map((n) => qualify(stripParens(n)))) {
2912
+ if (exposed.has(schemaOf(name))) continue;
2913
+ ctx.report({
2914
+ rule: "migration-grants",
2915
+ file,
2916
+ line,
2917
+ subject: name,
2918
+ 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)`
2919
+ });
2920
+ }
2921
+ continue;
2922
+ }
2923
+ const schema = /^grant\b.*?\bon schema (.+?) to (.+)$/.exec(sql);
2924
+ if (schema) {
2925
+ const roles = open(granteesOf(schema[2]));
2926
+ if (!roles.length) continue;
2927
+ for (const s of schema[1].split(/\s*,\s*/).map((x) => x.trim())) {
2928
+ if (exposed.has(s)) continue;
2929
+ ctx.report({
2930
+ rule: "migration-grants",
2931
+ file,
2932
+ line,
2933
+ subject: `schema ${s}`,
2934
+ message: `grants schema ${s} to ${roles.join(" and ")}; a schema outside the exposed ones stays closed to anon and public`
2935
+ });
2936
+ }
2937
+ }
2938
+ }
2939
+ }
2940
+ }
2941
+ function checkRls(ctx, migrations, exposed) {
2942
+ const tables = /* @__PURE__ */ new Map();
2943
+ const name = String.raw`([\w$.]+)`;
2944
+ const target = String.raw`^alter table (?:if exists )?(?:only )?${name}`;
2945
+ for (const { file, statements } of migrations) {
2946
+ for (const { sql, line, bodies } of statements) {
2947
+ if (bodies.some((b) => /\benable row level security\b/.test(b))) for (const t of tables.values()) t.rls = true;
2948
+ const create = new RegExp(String.raw`^create (?:(?:global |local )?(?:temp|temporary) |unlogged )?table (?:if not exists )?${name}`).exec(sql);
2949
+ if (create) {
2950
+ if (!/^create (?:global |local )?(?:temp|temporary) /.test(sql)) tables.set(qualify(create[1]), { rls: false, file, line, disabled: false });
2951
+ continue;
2952
+ }
2953
+ const rename = new RegExp(`${target} rename to ([\\w$]+)$`).exec(sql);
2954
+ const move = new RegExp(`${target} set schema ([\\w$]+)$`).exec(sql);
2955
+ if (rename || move) {
2956
+ const from = qualify((rename ?? move)[1]);
2957
+ const to = rename ? `${schemaOf(from)}.${rename[2]}` : `${move[2]}.${from.split(".")[1]}`;
2958
+ const state = tables.get(from);
2959
+ if (state) {
2960
+ tables.delete(from);
2961
+ tables.set(to, state);
2962
+ }
2963
+ continue;
2964
+ }
2965
+ const alter = new RegExp(target).exec(sql);
2966
+ if (alter && /\b(?:enable|disable) row level security\b/.test(sql)) {
2967
+ const t = qualify(alter[1]);
2968
+ if (/\bdisable row level security\b/.test(sql)) tables.set(t, { rls: false, file, line, disabled: true });
2969
+ else {
2970
+ const state = tables.get(t);
2971
+ if (state) state.rls = true;
2972
+ }
2973
+ continue;
2974
+ }
2975
+ const drop = /^drop table (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
2976
+ if (drop) for (const n of drop[1].split(",")) tables.delete(qualify(n));
2977
+ }
2978
+ }
2979
+ for (const [t, at] of tables) {
2980
+ if (at.rls || !exposed.has(schemaOf(t))) continue;
2981
+ ctx.report({
2982
+ rule: "migration-rls",
2983
+ file: at.file,
2984
+ line: at.line,
2985
+ subject: t,
2986
+ 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`
2987
+ });
2988
+ }
2989
+ }
2990
+ function checkViewInvoker(ctx, migrations, exposed) {
2991
+ const views = /* @__PURE__ */ new Map();
2992
+ const name = String.raw`([\w$.]+)`;
2993
+ const invokerOn = /\bsecurity_invoker\s*(?:=\s*(?:true|on|yes|1|'true'|'on'))?\s*(?:,|\))/;
2994
+ for (const { file, statements } of migrations) {
2995
+ for (const { sql, line } of statements) {
2996
+ const create = new RegExp(String.raw`^create (?:or replace )?(?:temp |temporary )?(?:recursive )?view ${name}`).exec(sql);
2997
+ if (create) {
2998
+ if (/^create (?:or replace )?(?:temp|temporary) /.test(sql)) continue;
2999
+ const options = /^[^(]*?\bwith\s*(\([^)]*\))\s*as\b/.exec(sql)?.[1] ?? "";
3000
+ views.set(qualify(create[1]), { invoker: invokerOn.test(options), file, line });
3001
+ continue;
3002
+ }
3003
+ const alter = new RegExp(String.raw`^alter view (?:if exists )?${name} (set|reset) (\([^)]*\))`).exec(sql);
3004
+ if (alter && /\bsecurity_invoker\b/.test(alter[3])) {
3005
+ const state = views.get(qualify(alter[1]));
3006
+ if (state) state.invoker = alter[2] === "set" && invokerOn.test(alter[3]);
3007
+ continue;
3008
+ }
3009
+ const rename = new RegExp(String.raw`^alter view (?:if exists )?${name} rename to ([\w$]+)$`).exec(sql);
3010
+ if (rename) {
3011
+ const from = qualify(rename[1]);
3012
+ const state = views.get(from);
3013
+ if (state) {
3014
+ views.delete(from);
3015
+ views.set(`${schemaOf(from)}.${rename[2]}`, state);
3016
+ }
3017
+ continue;
3018
+ }
3019
+ const drop = /^drop view (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3020
+ if (drop) for (const n of drop[1].split(",")) views.delete(qualify(n));
3021
+ }
3022
+ }
3023
+ for (const [v, at] of views) {
3024
+ if (at.invoker || !exposed.has(schemaOf(v))) continue;
3025
+ ctx.report({
3026
+ rule: "migration-view-rls",
3027
+ file: at.file,
3028
+ line: at.line,
3029
+ subject: v,
3030
+ 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);"`
3031
+ });
3032
+ }
3033
+ }
3034
+ function checkDefinerSearchPath(ctx, migrations) {
3035
+ const fns = /* @__PURE__ */ new Map();
3036
+ const keysFor = (sql, nameEnd, fnName) => {
3037
+ const rest = sql.slice(nameEnd).trimStart();
3038
+ if (rest.startsWith("(")) {
3039
+ const { inner } = parenthesized(rest, 0);
3040
+ return [`${fnName}(${argTypes(inner).join(",")})`];
3041
+ }
3042
+ return [...fns.keys()].filter((k) => k.startsWith(`${fnName}(`));
3043
+ };
3044
+ for (const { file, statements } of migrations) {
3045
+ for (const { sql, line } of statements) {
3046
+ const create = /^create (?:or replace )?(?:function|procedure) ([\w$.]+)\s*/.exec(sql);
3047
+ if (create) {
3048
+ const [key2] = keysFor(sql, create[0].length, qualify(create[1]));
3049
+ fns.set(key2, { definer: /\bsecurity definer\b/.test(sql), searchPath: /\bset search_path\b/.test(sql), file, line });
3050
+ continue;
3051
+ }
3052
+ const alter = /^alter (?:function|procedure|routine) ([\w$.]+)\s*/.exec(sql);
3053
+ if (alter) {
3054
+ const fnName = qualify(alter[1]);
3055
+ const keys = keysFor(sql, alter[0].length, fnName);
3056
+ const rename = / rename to ([\w$]+)$/.exec(sql);
3057
+ const move = / set schema ([\w$]+)$/.exec(sql);
3058
+ for (const key2 of keys) {
3059
+ const state = fns.get(key2);
3060
+ if (rename || move) {
3061
+ if (!state) continue;
3062
+ fns.delete(key2);
3063
+ const newName = rename ? `${schemaOf(fnName)}.${rename[1]}` : `${move[1]}.${fnName.split(".")[1]}`;
3064
+ fns.set(newName + key2.slice(fnName.length), state);
3065
+ continue;
3066
+ }
3067
+ const next = state ?? { definer: false, searchPath: false, file, line };
3068
+ if (/\bsecurity definer\b/.test(sql)) Object.assign(next, { definer: true, file, line });
3069
+ if (/\bsecurity invoker\b/.test(sql)) next.definer = false;
3070
+ if (/\bset search_path\b/.test(sql)) next.searchPath = true;
3071
+ if (/\breset (?:search_path|all)\b/.test(sql)) Object.assign(next, { searchPath: false, file, line });
3072
+ fns.set(key2, next);
3073
+ }
3074
+ continue;
3075
+ }
3076
+ const drop = /^drop (?:function|procedure|routine) (?:if exists )?(.+?)(?: cascade| restrict)?$/.exec(sql);
3077
+ if (drop) {
3078
+ for (const part of splitTop(drop[1])) {
3079
+ const m = /^([\w$.]+)\s*/.exec(part);
3080
+ if (m) for (const key2 of keysFor(part, m[0].length, qualify(m[1]))) fns.delete(key2);
3081
+ }
3082
+ }
3083
+ }
3084
+ }
3085
+ for (const [key2, at] of fns) {
3086
+ if (!at.definer || at.searchPath) continue;
3087
+ ctx.report({
3088
+ rule: "migration-definer-search-path",
3089
+ file: at.file,
3090
+ line: at.line,
3091
+ subject: key2,
3092
+ 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`
3093
+ });
3094
+ }
3095
+ }
3096
+ var UMBRELLA_PACKAGE = "@marktiderman/genesis";
3097
+ function readReleaseManifest(root) {
3098
+ const dir = findPackageDir(root, UMBRELLA_PACKAGE);
3099
+ const file = dir && path14.join(dir, "dist", "versions.json");
3100
+ if (!file || !existsSync(file)) return null;
3101
+ return JSON.parse(readFileSync(file, "utf8"));
3102
+ }
3103
+ function checkVersionSkew(ctx) {
3104
+ const manifest = readReleaseManifest(ctx.root);
3105
+ if (!manifest) return;
3106
+ for (const [name, want] of Object.entries(manifest.packages)) {
3107
+ const dir = findPackageDir(ctx.root, name);
3108
+ if (!dir) continue;
3109
+ const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
3110
+ if (have === want) continue;
3111
+ ctx.report({
3112
+ rule: "version-skew",
3113
+ level: "warn",
3114
+ file: "package.json",
3115
+ subject: name,
3116
+ message: `${name} is ${have}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Install ${name}@${want}, or move every Genesis package to one release.`
3117
+ });
3118
+ }
3119
+ }
3120
+ var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
3121
+ var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
3122
+ 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)$/;
3123
+ var readManifest = (dir) => {
2606
3124
  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] ?? {})));
3125
+ return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
2609
3126
  } catch {
2610
- declared = null;
3127
+ return null;
2611
3128
  }
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;
3129
+ };
3130
+ var real = (p) => {
3131
+ try {
3132
+ return realpathSync(p);
3133
+ } catch {
3134
+ return p;
3135
+ }
3136
+ };
3137
+ var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
3138
+ function nodeModulesOf(dir) {
3139
+ const parent = path14.dirname(dir);
3140
+ return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
3141
+ }
3142
+ function packagesIn(nodeModules) {
3143
+ if (!existsSync(nodeModules)) return [];
3144
+ const out = [];
3145
+ for (const entry of readdirSync(nodeModules)) {
3146
+ if (entry.startsWith(".")) continue;
3147
+ const p = path14.join(nodeModules, entry);
3148
+ if (entry.startsWith("@")) {
3149
+ try {
3150
+ for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
3151
+ } catch {
3152
+ }
3153
+ } else {
3154
+ out.push(p);
2625
3155
  }
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
- }
3156
+ }
3157
+ return out;
3158
+ }
3159
+ function genesisInstalls(root) {
3160
+ const copies = /* @__PURE__ */ new Map();
3161
+ const realRoot = real(root);
3162
+ const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
3163
+ const via = /* @__PURE__ */ new Map();
3164
+ const record = (real2, manifest, by, range, root2) => {
3165
+ let copy = copies.get(real2);
3166
+ if (!copy) {
3167
+ copy = { name: manifest.name, version: String(manifest.version ?? "unknown"), dir: rel(real2), absolutePath: real2, requiredBy: [], devOnly: false, runtime: false };
3168
+ copies.set(real2, copy);
3169
+ via.set(real2, /* @__PURE__ */ new Set());
3170
+ }
3171
+ via.get(real2).add(root2);
3172
+ if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
3173
+ };
3174
+ const walk = (kind, roots) => {
3175
+ const expanded = /* @__PURE__ */ new Set();
3176
+ const queue = [];
3177
+ const visit = (dir, by, range) => {
3178
+ const manifest = readManifest(dir);
3179
+ if (!manifest?.name) return;
3180
+ if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
3181
+ const realDir = real(dir);
3182
+ if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
3183
+ if (expanded.has(realDir)) return;
3184
+ expanded.add(realDir);
3185
+ queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
3186
+ };
3187
+ for (const r of roots) visit(r.dir, r.by, r.range);
3188
+ while (queue.length) {
3189
+ const { real: from, manifest, label } = queue.shift();
3190
+ const deps = { ...manifest.optionalDependencies, ...manifest.dependencies };
3191
+ for (const [name, range] of Object.entries(deps)) {
3192
+ const dir = findPackageDir(from, name);
3193
+ if (dir) visit(dir, label, range);
3194
+ }
3195
+ for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
3196
+ if (name in deps) continue;
3197
+ const dir = peerOf(from, name);
3198
+ if (dir) visit(dir, label, range);
2653
3199
  }
2654
- if (resolved && !files.includes(resolved)) files.push(resolved);
2655
3200
  }
2656
- const out = { files, lost };
2657
- importsCache.set(file.absolutePath, out);
2658
- return out;
2659
3201
  };
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);
3202
+ const peerOf = (from, name) => {
3203
+ const dir = findPackageDir(from, name);
3204
+ if (!dir) return null;
3205
+ if (!ownInstall || name in declared) return dir;
3206
+ const realDir = real(dir);
3207
+ if (realDir.startsWith(realRoot + path14.sep)) return dir;
3208
+ return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
2664
3209
  };
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";
3210
+ const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
3211
+ const dir = findPackageDir(root, name);
3212
+ return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
3213
+ });
3214
+ const app = readManifest(root);
3215
+ const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
3216
+ const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
3217
+ const declaredDev = Object.entries(app?.devDependencies ?? {});
3218
+ const runtimeDeps = {
3219
+ ...Object.fromEntries(declaredDev.filter(([n]) => !NON_SHIPPING.test(n))),
3220
+ ...app?.peerDependencies,
3221
+ ...app?.optionalDependencies,
3222
+ ...app?.dependencies
3223
+ };
3224
+ const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
3225
+ walk("runtime", rootsOf(runtimeDeps, "the app"));
3226
+ const top = path14.join(root, "node_modules");
3227
+ walk(
3228
+ "hoisted",
3229
+ packagesIn(top).filter((dir) => {
3230
+ const name = path14.relative(top, dir).split(path14.sep).join("/");
3231
+ return !(name in runtimeDeps) && !(name in devDeps);
3232
+ }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
3233
+ );
3234
+ const devRoots = { ...devDeps };
3235
+ for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
3236
+ walk("dev", rootsOf(devRoots, "the app (dev)"));
3237
+ for (const [key2, copy] of copies) {
3238
+ const kinds = via.get(key2);
3239
+ copy.runtime = kinds.has("runtime");
3240
+ copy.devOnly = kinds.size === 1 && kinds.has("dev");
3241
+ }
3242
+ const byName = /* @__PURE__ */ new Map();
3243
+ for (const copy of copies.values()) byName.set(copy.name, [...byName.get(copy.name) ?? [], copy]);
3244
+ for (const list of byName.values()) list.sort((a, b) => a.dir.split("/").length - b.dir.split("/").length || a.dir.localeCompare(b.dir));
3245
+ return byName;
3246
+ }
3247
+ function checkDuplicatePackages(ctx) {
3248
+ const describe = (c) => `${c.version} at ${c.dir} (${c.requiredBy.map((r) => `${r.by}${r.range ? ` wants ${r.range}` : ""}`).join("; ")})`;
3249
+ for (const [name, copies] of genesisInstalls(ctx.root)) {
3250
+ if (copies.length < 2) continue;
3251
+ const shipping = copies.filter((c) => c.runtime);
3252
+ if (!(shipping.length === 1 && copies.every((c) => c === shipping[0] || c.devOnly))) {
3253
+ ctx.report({
3254
+ rule: "duplicate-genesis-package",
3255
+ level: "warn",
3256
+ file: "package.json",
3257
+ subject: name,
3258
+ 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`
3259
+ });
3260
+ continue;
2707
3261
  }
2708
- if (result === "yes" || cut.size === 0) {
2709
- cache.free.set(k, result);
2710
- return [result, /* @__PURE__ */ new Set()];
3262
+ ctx.report({
3263
+ rule: "duplicate-genesis-package",
3264
+ level: "info",
3265
+ file: "package.json",
3266
+ subject: name,
3267
+ 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`
3268
+ });
3269
+ }
3270
+ }
3271
+ function checkPeerRanges(ctx) {
3272
+ const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
3273
+ for (const copies of genesisInstalls(ctx.root).values()) {
3274
+ for (const copy of copies) {
3275
+ const dir = copy.absolutePath;
3276
+ const peers = readManifest(dir)?.peerDependencies ?? {};
3277
+ for (const [peer, range] of Object.entries(peers)) {
3278
+ if (!GENESIS.test(peer)) continue;
3279
+ const peerDir = findPackageDir(dir, peer);
3280
+ const installed = peerDir && readManifest(peerDir)?.version;
3281
+ if (!peerDir || !installed) continue;
3282
+ if (satisfies(installed, range) !== false) continue;
3283
+ ctx.report({
3284
+ rule: "peer-range-mismatch",
3285
+ // A dev tool's own tree (the CLI's) doesn't run in the app.
3286
+ level: copy.devOnly ? "info" : "warn",
3287
+ file: "package.json",
3288
+ subject: `${copy.name}>${peer}`,
3289
+ 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}`
3290
+ });
3291
+ }
2711
3292
  }
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] };
3293
+ }
2718
3294
  }
2719
-
2720
- // src/doctor/routes.ts
2721
3295
  var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
2722
3296
  var STEMS = {
2723
3297
  tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
@@ -2830,7 +3404,7 @@ var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/u
2830
3404
  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
3405
  var SWITCHER = /<(TabsList|SubNavTabs)(?=[\s>/])/g;
2832
3406
  var SHELL = /<AppShell(?=[\s>/])/;
2833
- var GENESIS_PACKAGE = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
3407
+ var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
2834
3408
  var PAGE_LAYOUT = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)$/;
2835
3409
  var PACKAGE_SCREEN = /^(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)$/;
2836
3410
  var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
@@ -2886,7 +3460,7 @@ function checkLocalGenesisCopies(ctx) {
2886
3460
  const routes = routesDir(ctx);
2887
3461
  for (const file of ctx.files) {
2888
3462
  if (!JSX_EXTS2.has(file.ext)) continue;
2889
- const imported = new Set(namedImportsFrom(file.code, GENESIS_PACKAGE));
3463
+ const imported = new Set(namedImportsFrom(file.code, GENESIS_PACKAGE2));
2890
3464
  const inRoutes = routes !== null && file.path.startsWith(`${routes}/`);
2891
3465
  const routeComponents = new Set([...file.code.matchAll(/\b\w*[cC]omponent\s*:\s*([A-Z][\w$]*)\b/g)].map((r) => r[1]));
2892
3466
  const decls = [...file.code.matchAll(decl)];
@@ -2945,13 +3519,13 @@ function checkPageLayouts(ctx) {
2945
3519
  const inShell = insideShell(ctx, routes);
2946
3520
  const rendersLayout = (code) => {
2947
3521
  const names = new Set(layouts);
2948
- for (const n of namedImportsFrom(code, GENESIS_PACKAGE)) if (PACKAGE_SCREEN.test(n)) names.add(n);
3522
+ for (const n of namedImportsFrom(code, GENESIS_PACKAGE2)) if (PACKAGE_SCREEN.test(n)) names.add(n);
2949
3523
  return rendersRe(names)?.test(code) ?? false;
2950
3524
  };
2951
- const cache = /* @__PURE__ */ new Map();
3525
+ const cache2 = /* @__PURE__ */ new Map();
2952
3526
  const provides = (r) => {
2953
- if (!cache.has(r)) cache.set(r, routeReach(ctx, r, rendersLayout));
2954
- return cache.get(r);
3527
+ if (!cache2.has(r)) cache2.set(r, routeReach(ctx, r, rendersLayout));
3528
+ return cache2.get(r);
2955
3529
  };
2956
3530
  const list = [...layouts].sort();
2957
3531
  const named = list.length > 4 ? `${list.slice(0, 4).join(", ")}, \u2026` : list.join(", ");
@@ -3000,7 +3574,7 @@ async function runDoctor(options = {}) {
3000
3574
  if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
3001
3575
  }
3002
3576
  const raw = [];
3003
- const ctx = { root, files, genesis, config, report: (f) => raw.push(f) };
3577
+ const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
3004
3578
  for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
3005
3579
  try {
3006
3580
  await plugin.check(ctx);
@@ -3032,7 +3606,8 @@ async function runDoctor(options = {}) {
3032
3606
  function builtinChecks(config) {
3033
3607
  const packs = {
3034
3608
  native: { name: "native", check: checkNativePack },
3035
- supabase: { name: "supabase", check: checkSupabasePack }
3609
+ supabase: { name: "supabase", check: checkSupabasePack },
3610
+ packages: { name: "packages", check: checkPackagesPack }
3036
3611
  };
3037
3612
  return [
3038
3613
  { name: "layout", check: checkProjectLayout },