@marktiderman/genesis-cli 1.11.3 → 1.12.0

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