@marktiderman/genesis-cli 1.21.0 → 1.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js CHANGED
@@ -1,18 +1,23 @@
1
- import * as path20 from 'path';
1
+ import * as path21 from 'path';
2
2
  import { spawnSync } from 'child_process';
3
3
  import { existsSync, readFileSync, statSync, realpathSync, readdirSync, lstatSync } from 'fs';
4
4
  import { builtinModules, createRequire } from 'module';
5
+ import { overlayUpstream, readOverlayMarker } from '@marktiderman/genesis-features';
5
6
  import { createHash } from 'crypto';
6
7
  import { FEATURE_PLATFORMS, defineBlock, BlockError } from '@marktiderman/genesis-features/blocks';
7
8
  import { pathToFileURL, fileURLToPath } from 'url';
8
- import { overlayUpstream, readOverlayMarker } from '@marktiderman/genesis-features';
9
9
  import { createJiti } from 'jiti';
10
10
  import 'os';
11
11
 
12
12
  var __defProp = Object.defineProperty;
13
13
  var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __esm = (fn, res) => function __init() {
15
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
14
+ var __esm = (fn, res, err) => function __init() {
15
+ if (err) throw err[0];
16
+ try {
17
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
18
+ } catch (e) {
19
+ throw err = [e], e;
20
+ }
16
21
  };
17
22
  var __export = (target, all) => {
18
23
  for (var name in all)
@@ -455,14 +460,14 @@ function inherit(own, source) {
455
460
  }
456
461
  function resolveViews(relations) {
457
462
  const done = /* @__PURE__ */ new Set();
458
- const resolve18 = (relation, depth) => {
463
+ const resolve19 = (relation, depth) => {
459
464
  if (done.has(relation.oid) || !relation.origins || depth > MAX_VIEW_DEPTH) return;
460
465
  done.add(relation.oid);
461
466
  const sources = new Set([...relation.origins.values()].map((o) => o.relation));
462
467
  if (sources.size !== 1) return;
463
468
  const source = relations.get([...sources][0]);
464
469
  if (!source) return;
465
- resolve18(source, depth + 1);
470
+ resolve19(source, depth + 1);
466
471
  const viewAttnumOf = /* @__PURE__ */ new Map();
467
472
  for (const [attnum, origin] of relation.origins) {
468
473
  const own = relation.columns.get(attnum);
@@ -485,7 +490,7 @@ function resolveViews(relations) {
485
490
  };
486
491
  if (Object.keys(inherited).length) relation.table.settings = { ...inherited, ...relation.table.settings };
487
492
  };
488
- for (const relation of relations.values()) resolve18(relation, 0);
493
+ for (const relation of relations.values()) resolve19(relation, 0);
489
494
  }
490
495
  async function introspectPostgres(sql, schemas, options = {}) {
491
496
  const relations = /* @__PURE__ */ new Map();
@@ -721,19 +726,19 @@ var init_introspect = __esm({
721
726
  var BUILD_GUARD_ENV = "GENESIS_DOCTOR_BUILDING";
722
727
  function buildCommands(root, config) {
723
728
  if (config.build) return config.build;
724
- const pkgFile = path20.join(root, "package.json");
729
+ const pkgFile = path21.join(root, "package.json");
725
730
  const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
726
731
  const pm = packageManager(root);
727
732
  return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
728
733
  }
729
734
  function packageManager(root) {
730
- let dir = path20.resolve(root);
735
+ let dir = path21.resolve(root);
731
736
  for (; ; ) {
732
- if (existsSync(path20.join(dir, "pnpm-lock.yaml"))) return "pnpm";
733
- if (existsSync(path20.join(dir, "bun.lock")) || existsSync(path20.join(dir, "bun.lockb"))) return "bun";
734
- if (existsSync(path20.join(dir, "yarn.lock"))) return "yarn";
735
- if (existsSync(path20.join(dir, "package-lock.json"))) return "npm";
736
- const parent = path20.dirname(dir);
737
+ if (existsSync(path21.join(dir, "pnpm-lock.yaml"))) return "pnpm";
738
+ if (existsSync(path21.join(dir, "bun.lock")) || existsSync(path21.join(dir, "bun.lockb"))) return "bun";
739
+ if (existsSync(path21.join(dir, "yarn.lock"))) return "yarn";
740
+ if (existsSync(path21.join(dir, "package-lock.json"))) return "npm";
741
+ const parent = path21.dirname(dir);
737
742
  if (parent === dir) return "npm";
738
743
  dir = parent;
739
744
  }
@@ -848,25 +853,25 @@ var PACK_KEYS = {
848
853
  };
849
854
  function appPath(v, where2, fail) {
850
855
  if (typeof v !== "string" || !v.trim()) return fail(`${where2} must be a non-empty path`);
851
- if (path20.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
852
- const norm = path20.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
856
+ if (path21.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
857
+ const norm = path21.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
853
858
  if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where2} must be a folder inside the app ("${v}")`);
854
859
  return norm;
855
860
  }
856
861
  function loadConfig(root, configPath) {
857
862
  if (configPath) {
858
- const file = path20.resolve(root, configPath);
863
+ const file = path21.resolve(root, configPath);
859
864
  if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
860
865
  const json = readJson(file);
861
- const block = path20.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
862
- return { config: validateConfig(block ?? {}, file), file, dir: path20.dirname(file) };
866
+ const block = path21.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
867
+ return { config: validateConfig(block ?? {}, file), file, dir: path21.dirname(file) };
863
868
  }
864
- const own = path20.join(root, "genesis.config.json");
869
+ const own = path21.join(root, "genesis.config.json");
865
870
  if (existsSync(own)) {
866
871
  const block = readGenesisConfig(root)?.raw.doctor;
867
872
  return { config: validateConfig(block ?? {}, own), file: own, dir: root };
868
873
  }
869
- const pkg = path20.join(root, "package.json");
874
+ const pkg = path21.join(root, "package.json");
870
875
  if (existsSync(pkg)) {
871
876
  const block = readJson(pkg)?.genesis?.doctor;
872
877
  if (block !== void 0 && !isPackageDeclaration(block)) return { config: validateConfig(block, pkg), file: pkg, dir: root };
@@ -875,7 +880,7 @@ function loadConfig(root, configPath) {
875
880
  }
876
881
  function doctorBlock(json, file, explicit) {
877
882
  const j = json;
878
- if (path20.basename(file) === "package.json") return j?.genesis?.doctor;
883
+ if (path21.basename(file) === "package.json") return j?.genesis?.doctor;
879
884
  return explicit ? j?.doctor ?? j : j?.doctor;
880
885
  }
881
886
  function isPackageDeclaration(block) {
@@ -892,7 +897,7 @@ function readJson(file) {
892
897
  }
893
898
  }
894
899
  function readGenesisConfig(root) {
895
- const file = path20.join(root, "genesis.config.json");
900
+ const file = path21.join(root, "genesis.config.json");
896
901
  if (!existsSync(file)) return null;
897
902
  const raw = readJson(file);
898
903
  if (!isObject(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
@@ -903,8 +908,18 @@ function readGenesisConfig(root) {
903
908
  const supabase = validateSupabase(raw.supabase, file);
904
909
  if (supabase !== true) out.supabase = supabase;
905
910
  }
911
+ if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
906
912
  return out;
907
913
  }
914
+ var PLAIN_FOLDER = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}){0,7}$/;
915
+ function isPlainFolder(value) {
916
+ return PLAIN_FOLDER.test(value) && !value.split("/").includes("..");
917
+ }
918
+ function validateAppFolder(raw, source = "config") {
919
+ const norm = typeof raw === "string" ? raw.replace(/^\.\//, "").replace(/\/+$/, "") : "";
920
+ if (!isPlainFolder(norm)) throw new GenesisConfigError(`${source}: "appFolder" must be the app's folder from the repository root, such as "mobile" or "apps/phone" (got ${JSON.stringify(raw)})`);
921
+ return norm;
922
+ }
908
923
  function validateSupabase(raw, source = "config") {
909
924
  const fail = (msg) => {
910
925
  throw new GenesisConfigError(`${source}: ${msg}`);
@@ -914,8 +929,8 @@ function validateSupabase(raw, source = "config") {
914
929
  for (const key2 of Object.keys(raw)) if (key2 !== "app" && key2 !== "$comment") fail(`supabase: unknown setting "${key2}" (known: app)`);
915
930
  const app = raw.app;
916
931
  if (typeof app !== "string" || !app.trim()) return fail(`supabase.app must be the folder of the app that holds supabase/, relative to this one (e.g. "../app")`);
917
- if (path20.isAbsolute(app) || /^[A-Za-z]:[\\/]/.test(app) || app.includes("\\")) fail(`supabase.app must be relative to this app, with forward slashes ("${app}")`);
918
- const norm = path20.posix.normalize(app).replace(/\/+$/, "");
932
+ if (path21.isAbsolute(app) || /^[A-Za-z]:[\\/]/.test(app) || app.includes("\\")) fail(`supabase.app must be relative to this app, with forward slashes ("${app}")`);
933
+ const norm = path21.posix.normalize(app).replace(/\/+$/, "");
919
934
  if (norm === "." || norm === "") fail(`supabase.app names this app itself; leave "supabase" out instead`);
920
935
  return { app: norm };
921
936
  }
@@ -1075,7 +1090,7 @@ function validateConfig(raw, source = "config") {
1075
1090
  if (!(c.packs ?? []).includes("supabase")) fail(`"contracts" is set but the supabase pack is not in "packs"`);
1076
1091
  if (contracts.out !== void 0) {
1077
1092
  if (typeof contracts.out !== "string" || !contracts.out.trim()) fail(`contracts.out must be a file path`);
1078
- if (path20.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1093
+ if (path21.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1079
1094
  }
1080
1095
  if (contracts.schemas !== void 0 && !isStringList(contracts.schemas)) fail(`contracts.schemas must be a list of schema names`);
1081
1096
  if (contracts.databaseEnv !== void 0 && (typeof contracts.databaseEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(contracts.databaseEnv))) {
@@ -1143,429 +1158,126 @@ function globToRegExp(glob) {
1143
1158
  }
1144
1159
  function globMatcher(globs) {
1145
1160
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1146
- return (path44) => res.some((re) => re.test(path44));
1161
+ return (path49) => res.some((re) => re.test(path49));
1147
1162
  }
1148
- var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
1149
- var NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
1150
- var DESIGN_SYSTEM_PACKAGE = "@marktiderman/genesis-design-system";
1151
- var DEFAULT_COMPONENT_PACKAGES = ["@marktiderman/genesis-forms-studio"];
1152
- var TAGS = ["button", "input", "textarea", "select", "label", "table", "dialog", "progress", "details", "summary"];
1153
- var TAG_ALIASES = { hr: "Separator" };
1154
- var NON_COMPONENT_SUFFIX = /(Props|Variant|Variants|Type|Types|Config|Context|Options|Status)$/;
1155
- var TAILWIND_PALETTE = [
1156
- "black",
1157
- "white",
1158
- "slate",
1159
- "gray",
1160
- "zinc",
1161
- "neutral",
1162
- "stone",
1163
- "red",
1164
- "orange",
1165
- "amber",
1166
- "yellow",
1167
- "lime",
1168
- "green",
1169
- "emerald",
1170
- "teal",
1171
- "cyan",
1172
- "sky",
1173
- "blue",
1174
- "indigo",
1175
- "violet",
1176
- "purple",
1177
- "fuchsia",
1178
- "pink",
1179
- "rose",
1180
- "taupe",
1181
- "mauve",
1182
- "mist",
1183
- "olive"
1184
- ];
1185
- function findPackageDir(from, name) {
1186
- let dir = path20.resolve(from);
1187
- for (; ; ) {
1188
- const candidate = path20.join(dir, "node_modules", name);
1189
- if (existsSync(path20.join(candidate, "package.json"))) return candidate;
1190
- const parent = path20.dirname(dir);
1191
- if (parent === dir) return null;
1192
- dir = parent;
1163
+ var GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
1164
+ var BLOCK_ID = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
1165
+ var MIGRATION_FILE = /^(\d{4})_([a-z0-9_]+)\.sql$/;
1166
+ var FUNCTION_NAME = /^[a-z0-9][a-z0-9_-]*$/;
1167
+ var ROUTE = /^\/(?:[A-Za-z0-9_\-[\]().]+\/?)*$/;
1168
+ var INSTALL_SPEC = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9.^~<>=|* -]+)?$/;
1169
+ var SECRET = /^[A-Z][A-Z0-9_]*$/;
1170
+ var SQL_FUNCTION = /^[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*$/;
1171
+ var ManifestError = class extends Error {
1172
+ constructor(problems) {
1173
+ super(`Invalid block manifest:
1174
+ ${problems.map((p) => ` - ${p}`).join("\n")}`);
1175
+ this.problems = problems;
1176
+ this.name = "ManifestError";
1193
1177
  }
1178
+ problems;
1179
+ };
1180
+ function safeRelative(value) {
1181
+ if (typeof value !== "string" || !value || value.length > 300) return null;
1182
+ if (/[\0\\:]/.test(value) || value.startsWith("/") || value.startsWith("~")) return null;
1183
+ const segments = value.split("/");
1184
+ if (segments.some((s) => s === "" || s === "." || s === ".." || s.startsWith("-"))) return null;
1185
+ return value;
1194
1186
  }
1195
- function uiPackageFor(config) {
1196
- return config.uiPackage ?? (config.packs?.includes("native") ? NATIVE_UI_PACKAGE : DEFAULT_UI_PACKAGE);
1197
- }
1198
- function loadGenesis(root, config) {
1199
- const uiPackage = uiPackageFor(config);
1200
- const pkg = readPackageExports(root, uiPackage);
1201
- if (!pkg) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
1202
- const { dir: uiDir, exports: exportNames, values, components } = pkg;
1203
- const tokens = /* @__PURE__ */ new Set();
1204
- const themeFiles = resolveThemeFiles(root, config, uiDir);
1205
- for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
1206
- const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
1207
- const rawTags = /* @__PURE__ */ new Map();
1208
- for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
1209
- for (const [tag, comp] of Object.entries(TAG_ALIASES)) if (values.has(comp)) rawTags.set(tag, comp);
1210
- for (const [tag, comp] of Object.entries(config.rawTags ?? {})) {
1211
- if (comp === false) rawTags.delete(tag);
1212
- else rawTags.set(tag, comp);
1213
- }
1214
- return {
1215
- uiPackage,
1216
- uiVersion: pkg.version,
1217
- exports: exportNames,
1218
- values,
1219
- components,
1220
- tokens,
1221
- rawTags,
1222
- palette: loadPalette(root),
1223
- companions: loadCompanions(root, config, uiPackage)
1187
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1188
+ var strings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
1189
+ function parseManifest(home, id, raw, version, options = {}) {
1190
+ const problems = [];
1191
+ const at = `${home} genesis.blocks.${id}`;
1192
+ if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
1193
+ if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
1194
+ if (!isObject2(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
1195
+ const pkgOf = (value, where2) => {
1196
+ if (value === void 0) return home;
1197
+ if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
1198
+ problems.push(`${where2}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
1199
+ return home;
1200
+ }
1201
+ return value;
1224
1202
  };
1225
- }
1226
- function loadCompanions(root, config, uiPackage) {
1227
- const out = [];
1228
- for (const name of config.componentPackages ?? DEFAULT_COMPONENT_PACKAGES) {
1229
- if (name === uiPackage) continue;
1230
- try {
1231
- const pkg = readPackageExports(root, name);
1232
- if (pkg) out.push({ package: name, version: pkg.version, components: pkg.components });
1233
- } catch (err) {
1234
- if (!(err instanceof DoctorConfigError)) throw err;
1203
+ const pathOf = (value, where2) => {
1204
+ const safe = safeRelative(value);
1205
+ if (!safe) problems.push(`${where2}: ${JSON.stringify(value)} is not a plain path inside the package`);
1206
+ return safe ?? "";
1207
+ };
1208
+ const list = (key2) => {
1209
+ const v = raw[key2];
1210
+ if (v === void 0) return [];
1211
+ if (!Array.isArray(v)) {
1212
+ problems.push(`${at}.${key2}: must be a list`);
1213
+ return [];
1235
1214
  }
1215
+ return v;
1216
+ };
1217
+ const requires = list("requires").filter((r) => {
1218
+ const ok = typeof r === "string" && BLOCK_ID.test(r);
1219
+ if (!ok) problems.push(`${at}.requires: ${JSON.stringify(r)} is not a feature id`);
1220
+ return ok;
1221
+ });
1222
+ let platforms;
1223
+ if (raw["platforms"] !== void 0) {
1224
+ platforms = list("platforms").filter((p) => {
1225
+ const ok = typeof p === "string" && FEATURE_PLATFORMS.includes(p);
1226
+ if (!ok) problems.push(`${at}.platforms: ${JSON.stringify(p)} is not one of ${FEATURE_PLATFORMS.join(", ")}`);
1227
+ return ok;
1228
+ });
1236
1229
  }
1237
- return out;
1238
- }
1239
- function readPackageExports(root, uiPackage) {
1240
- const uiDir = findPackageDir(root, uiPackage);
1241
- if (!uiDir) return null;
1242
- const uiPkg = JSON.parse(readFileSync(path20.join(uiDir, "package.json"), "utf8"));
1243
- const subpaths = Object.values(uiPkg.exports ?? {});
1244
- const declared = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
1245
- const fromSource = typeof declared !== "string" && !subpaths.some((t) => typeof exportTypes(t) === "string");
1246
- const entryOf = fromSource ? exportSource : exportTypes;
1247
- const typeEntries = /* @__PURE__ */ new Set();
1248
- const mainTypes = fromSource ? exportSource(uiPkg.exports?.["."] ?? uiPkg.exports) ?? (isTsSource(uiPkg.main) ? uiPkg.main : void 0) : declared;
1249
- if (typeof mainTypes === "string") typeEntries.add(mainTypes);
1250
- for (const target of subpaths) {
1251
- const t = entryOf(target);
1252
- if (typeof t === "string" && !t.includes("*")) typeEntries.add(t);
1253
- }
1254
- const exportNames = /* @__PURE__ */ new Set();
1255
- const reexportedPackages = /* @__PURE__ */ new Set();
1256
- let readAny = false;
1257
- const seen = /* @__PURE__ */ new Set();
1258
- const readEntry = (file) => {
1259
- if (seen.has(file) || !insidePackage(uiDir, file) || !existsSync(file)) return;
1260
- seen.add(file);
1261
- readAny = true;
1262
- const code = fromSource ? stripComments(readFileSync(file, "utf8")) : readFileSync(file, "utf8");
1263
- for (const name of fromSource ? parseSourceExportNames(code) : parseExportNames(code)) exportNames.add(name);
1264
- for (const m of code.matchAll(/export\s+(?:type\s+)?(?:\{[^}]*\}|\*)\s*from\s*["']([^"'.][^"']*)["']/g)) {
1265
- reexportedPackages.add(packageName(m[1]));
1230
+ const packages = list("packages").map((p, i) => pkgOf(p, `${at}.packages[${i}]`));
1231
+ const install = list("install").filter((s) => {
1232
+ const ok = typeof s === "string" && INSTALL_SPEC.test(s) && !s.startsWith("-");
1233
+ if (!ok) problems.push(`${at}.install: ${JSON.stringify(s)} is not a package name with an optional range`);
1234
+ return ok;
1235
+ });
1236
+ const migrations = list("migrations").map((m, i) => {
1237
+ const where2 = `${at}.migrations[${i}]`;
1238
+ if (!isObject2(m)) {
1239
+ problems.push(`${where2}: must be an object`);
1240
+ return { package: home, file: "" };
1266
1241
  }
1267
- if (fromSource) {
1268
- for (const m of code.matchAll(/export\s+\*\s+from\s*["'](\.[^"']*)["']/g)) {
1269
- const next = resolveSource(path20.dirname(file), m[1]);
1270
- if (next) readEntry(next);
1242
+ const file = pathOf(m["file"], `${where2}.file`);
1243
+ if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where2}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
1244
+ const out = { package: pkgOf(m["package"], where2), file };
1245
+ if (m["provides"] !== void 0) {
1246
+ if (!Array.isArray(m["provides"])) problems.push(`${where2}.provides: must be a list of { package, file }`);
1247
+ else {
1248
+ out.provides = m["provides"].map((p, j) => {
1249
+ const at2 = `${where2}.provides[${j}]`;
1250
+ if (!isObject2(p)) {
1251
+ problems.push(`${at2}: must be an object`);
1252
+ return { package: home, file: "" };
1253
+ }
1254
+ const provided = { package: pkgOf(p["package"], at2), file: pathOf(p["file"], `${at2}.file`) };
1255
+ if (p["functions"] !== void 0) {
1256
+ if (!Array.isArray(p["functions"])) problems.push(`${at2}.functions: must be a list of function folders`);
1257
+ else provided.functions = p["functions"].map((f, k) => pathOf(f, `${at2}.functions[${k}]`));
1258
+ }
1259
+ if (provided.file && !MIGRATION_FILE.test(provided.file.split("/").pop())) problems.push(`${at2}.file: "${provided.file}" must be named NNNN_name.sql`);
1260
+ if (provided.package === out.package && provided.file === file) problems.push(`${at2}: a migration can't provide itself`);
1261
+ return provided;
1262
+ });
1271
1263
  }
1272
1264
  }
1273
- };
1274
- for (const entry of typeEntries) readEntry(path20.join(uiDir, entry));
1275
- if (!readAny) {
1276
- const what = fromSource ? "type declarations or TypeScript source" : "type declarations";
1277
- throw new DoctorConfigError(`${uiPackage} has no ${what} to read (is it built?). Looked for: ${[...typeEntries].join(", ") || "none"}`);
1278
- }
1279
- const valueDecls = /* @__PURE__ */ new Set();
1280
- const typeDecls = /* @__PURE__ */ new Set();
1281
- const declRoot = typeof mainTypes === "string" ? path20.dirname(path20.join(uiDir, mainTypes)) : uiDir;
1282
- const declFiles = fromSource ? walkSource(declRoot) : walkDts(declRoot);
1283
- for (const pkg of reexportedPackages) {
1284
- const dir = findPackageDir(uiDir, pkg);
1285
- if (dir) walkDts(path20.join(dir, "dist"), declFiles);
1286
- }
1287
- for (const file of declFiles) {
1288
- const text = readFileSync(file, "utf8");
1289
- for (const m of text.matchAll(/\b(?:declare\s+)?(?:const|let|var|function|class|enum)\s+([A-Za-z_$][\w$]*)/g)) valueDecls.add(m[1]);
1290
- for (const m of text.matchAll(/\b(?:interface|type)\s+([A-Za-z_$][\w$]*)/g)) typeDecls.add(m[1]);
1291
- }
1292
- const isTypeOnly = (n) => typeDecls.has(n) && !valueDecls.has(n);
1293
- const values = new Set([...exportNames].filter((n) => !isTypeOnly(n)));
1294
- const components = [...values].filter((n) => /^[A-Z][A-Za-z0-9]*$/.test(n) && !(n.length > 2 && n === n.toUpperCase()) && !NON_COMPONENT_SUFFIX.test(n)).sort();
1295
- return { dir: uiDir, version: String(uiPkg.version ?? "unknown"), exports: exportNames, values, components };
1296
- }
1297
- function parseExportNames(dts) {
1298
- const names = [];
1299
- for (const m of dts.matchAll(/export\s+(?:type\s+)?\{([^}]*)\}/g)) {
1300
- for (const part of m[1].split(",")) {
1301
- const name = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/).pop()?.trim();
1302
- if (name && name !== "default") names.push(name);
1303
- }
1304
- }
1305
- for (const m of dts.matchAll(/export\s+(?:declare\s+)?(?:const|let|function|class|enum|interface|type)\s+([A-Za-z_$][\w$]*)/g)) {
1306
- names.push(m[1]);
1307
- }
1308
- return names;
1309
- }
1310
- function declaredTokens(css) {
1311
- return [...css.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)].map((m) => m[1]);
1312
- }
1313
- function packageName(specifier) {
1314
- const parts = specifier.split("/");
1315
- return parts.slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
1316
- }
1317
- function parseSourceExportNames(code) {
1318
- const names = parseExportNames(code);
1319
- for (const m of code.matchAll(/export\s+(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:var|class|function\*?)\s+([A-Za-z_$][\w$]*)/g)) names.push(m[1]);
1320
- for (const m of code.matchAll(/export\s+\*\s+as\s+([A-Za-z_$][\w$]*)/g)) names.push(m[1]);
1321
- return [...new Set(names)];
1322
- }
1323
- var TS_SOURCE = /\.(?:[cm]?tsx?)$/;
1324
- var isTsSource = (v) => typeof v === "string" && TS_SOURCE.test(v) && !/\.d\.[cm]?ts$/.test(v);
1325
- function exportSource(target) {
1326
- if (isTsSource(target)) return target;
1327
- if (!target || typeof target !== "object") return void 0;
1328
- for (const value of Object.values(target)) {
1329
- const nested = exportSource(value);
1330
- if (nested) return nested;
1331
- }
1332
- return void 0;
1333
- }
1334
- function resolveSource(dir, spec) {
1335
- const base = path20.resolve(dir, spec.replace(/\.js$/, ""));
1336
- const candidates = [base, ...[".ts", ".tsx", ".mts", ".cts"].map((e) => base + e), ...["index.ts", "index.tsx"].map((i) => path20.join(base, i))];
1337
- return candidates.find((f) => TS_SOURCE.test(f) && existsSync(f) && statSync(f).isFile()) ?? null;
1338
- }
1339
- function insidePackage(dir, file) {
1340
- const rel = path20.relative(path20.resolve(dir), path20.resolve(file));
1341
- return rel === "" || !rel.startsWith("..") && !path20.isAbsolute(rel);
1342
- }
1343
- function stripComments(code) {
1344
- let out = "";
1345
- let i = 0;
1346
- while (i < code.length) {
1347
- const c = code[i];
1348
- const next = code[i + 1];
1349
- if (c === "/" && next === "*") {
1350
- const end = code.indexOf("*/", i + 2);
1351
- const stop = end < 0 ? code.length : end + 2;
1352
- out += code.slice(i, stop).replace(/[^\n]/g, " ");
1353
- i = stop;
1354
- } else if (c === "/" && next === "/") {
1355
- const end = code.indexOf("\n", i);
1356
- i = end < 0 ? code.length : end;
1357
- } else if (c === '"' || c === "'" || c === "`") {
1358
- let j = i + 1;
1359
- while (j < code.length && code[j] !== c) {
1360
- if (code[j] === "\\") j++;
1361
- else if (c !== "`" && code[j] === "\n") break;
1362
- j++;
1363
- }
1364
- out += code.slice(i, j + 1);
1365
- i = j + 1;
1366
- } else {
1367
- out += c;
1368
- i++;
1369
- }
1370
- }
1371
- return out;
1372
- }
1373
- function walkSource(dir, out = []) {
1374
- if (!existsSync(dir)) return out;
1375
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
1376
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
1377
- const p = path20.join(dir, entry.name);
1378
- if (entry.isDirectory()) walkSource(p, out);
1379
- else if (isTsSource(entry.name) || /\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1380
- }
1381
- return out;
1382
- }
1383
- function exportTypes(target) {
1384
- if (!target || typeof target !== "object") return void 0;
1385
- const t = target;
1386
- if (typeof t.types === "string") return t.types;
1387
- for (const key2 of ["import", "default", "require"]) {
1388
- const nested = exportTypes(t[key2]);
1389
- if (nested) return nested;
1390
- }
1391
- return void 0;
1392
- }
1393
- function walkDts(dir, out = []) {
1394
- if (!existsSync(dir)) return out;
1395
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
1396
- if (entry.name === "node_modules") continue;
1397
- const p = path20.join(dir, entry.name);
1398
- if (entry.isDirectory()) walkDts(p, out);
1399
- else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1400
- }
1401
- return out;
1402
- }
1403
- function resolveThemeFiles(root, config, uiDir) {
1404
- if (config.themeCss) {
1405
- const specs = typeof config.themeCss === "string" ? [config.themeCss] : config.themeCss;
1406
- return specs.map((spec) => {
1407
- const file = resolveSpec(root, spec);
1408
- if (!file) throw new DoctorConfigError(`doctor.themeCss: cannot find ${spec}`);
1409
- return file;
1410
- });
1411
- }
1412
- const files = [];
1413
- const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
1414
- const themes = ds && path20.join(ds, "dist", "themes");
1415
- if (themes && existsSync(themes)) {
1416
- for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path20.join(themes, name));
1417
- }
1418
- if (files.length === 0) {
1419
- throw new DoctorConfigError(
1420
- `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
1421
- );
1422
- }
1423
- const uiStyles = path20.join(uiDir, "dist", "styles.css");
1424
- if (existsSync(uiStyles)) files.push(uiStyles);
1425
- return files;
1426
- }
1427
- function resolveSpec(root, spec) {
1428
- const local = path20.resolve(root, spec);
1429
- if (spec.startsWith(".") || path20.isAbsolute(spec)) return existsSync(local) ? local : null;
1430
- const parts = spec.split("/");
1431
- const nameLength = spec.startsWith("@") ? 2 : 1;
1432
- const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
1433
- if (dir) {
1434
- const file = path20.join(dir, ...parts.slice(nameLength));
1435
- if (existsSync(file) && statSync(file).isFile()) return file;
1436
- }
1437
- return existsSync(local) ? local : null;
1438
- }
1439
- function loadPalette(root) {
1440
- const names = new Set(TAILWIND_PALETTE);
1441
- try {
1442
- const req = createRequire(path20.join(root, "package.json"));
1443
- const colors = req("tailwindcss/colors");
1444
- for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
1445
- if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
1446
- }
1447
- } catch {
1448
- }
1449
- return [...names].sort();
1450
- }
1451
- var GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
1452
- var BLOCK_ID = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
1453
- var MIGRATION_FILE = /^(\d{4})_([a-z0-9_]+)\.sql$/;
1454
- var FUNCTION_NAME = /^[a-z0-9][a-z0-9_-]*$/;
1455
- var ROUTE = /^\/(?:[A-Za-z0-9_\-[\]().]+\/?)*$/;
1456
- var INSTALL_SPEC = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9.^~<>=|* -]+)?$/;
1457
- var SECRET = /^[A-Z][A-Z0-9_]*$/;
1458
- var SQL_FUNCTION = /^[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*$/;
1459
- var ManifestError = class extends Error {
1460
- constructor(problems) {
1461
- super(`Invalid block manifest:
1462
- ${problems.map((p) => ` - ${p}`).join("\n")}`);
1463
- this.problems = problems;
1464
- this.name = "ManifestError";
1465
- }
1466
- problems;
1467
- };
1468
- function safeRelative(value) {
1469
- if (typeof value !== "string" || !value || value.length > 300) return null;
1470
- if (/[\0\\:]/.test(value) || value.startsWith("/") || value.startsWith("~")) return null;
1471
- const segments = value.split("/");
1472
- if (segments.some((s) => s === "" || s === "." || s === ".." || s.startsWith("-"))) return null;
1473
- return value;
1474
- }
1475
- var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1476
- var strings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
1477
- function parseManifest(home, id, raw, version, options = {}) {
1478
- const problems = [];
1479
- const at = `${home} genesis.blocks.${id}`;
1480
- if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
1481
- if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
1482
- if (!isObject2(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
1483
- const pkgOf = (value, where2) => {
1484
- if (value === void 0) return home;
1485
- if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
1486
- problems.push(`${where2}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
1487
- return home;
1488
- }
1489
- return value;
1490
- };
1491
- const pathOf = (value, where2) => {
1492
- const safe = safeRelative(value);
1493
- if (!safe) problems.push(`${where2}: ${JSON.stringify(value)} is not a plain path inside the package`);
1494
- return safe ?? "";
1495
- };
1496
- const list = (key2) => {
1497
- const v = raw[key2];
1498
- if (v === void 0) return [];
1499
- if (!Array.isArray(v)) {
1500
- problems.push(`${at}.${key2}: must be a list`);
1501
- return [];
1502
- }
1503
- return v;
1504
- };
1505
- const requires = list("requires").filter((r) => {
1506
- const ok = typeof r === "string" && BLOCK_ID.test(r);
1507
- if (!ok) problems.push(`${at}.requires: ${JSON.stringify(r)} is not a feature id`);
1508
- return ok;
1509
- });
1510
- let platforms;
1511
- if (raw["platforms"] !== void 0) {
1512
- platforms = list("platforms").filter((p) => {
1513
- const ok = typeof p === "string" && FEATURE_PLATFORMS.includes(p);
1514
- if (!ok) problems.push(`${at}.platforms: ${JSON.stringify(p)} is not one of ${FEATURE_PLATFORMS.join(", ")}`);
1515
- return ok;
1516
- });
1517
- }
1518
- const packages = list("packages").map((p, i) => pkgOf(p, `${at}.packages[${i}]`));
1519
- const install = list("install").filter((s) => {
1520
- const ok = typeof s === "string" && INSTALL_SPEC.test(s) && !s.startsWith("-");
1521
- if (!ok) problems.push(`${at}.install: ${JSON.stringify(s)} is not a package name with an optional range`);
1522
- return ok;
1523
- });
1524
- const migrations = list("migrations").map((m, i) => {
1525
- const where2 = `${at}.migrations[${i}]`;
1526
- if (!isObject2(m)) {
1527
- problems.push(`${where2}: must be an object`);
1528
- return { package: home, file: "" };
1529
- }
1530
- const file = pathOf(m["file"], `${where2}.file`);
1531
- if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where2}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
1532
- const out = { package: pkgOf(m["package"], where2), file };
1533
- if (m["provides"] !== void 0) {
1534
- if (!Array.isArray(m["provides"])) problems.push(`${where2}.provides: must be a list of { package, file }`);
1535
- else {
1536
- out.provides = m["provides"].map((p, j) => {
1537
- const at2 = `${where2}.provides[${j}]`;
1538
- if (!isObject2(p)) {
1539
- problems.push(`${at2}: must be an object`);
1540
- return { package: home, file: "" };
1541
- }
1542
- const provided = { package: pkgOf(p["package"], at2), file: pathOf(p["file"], `${at2}.file`) };
1543
- if (p["functions"] !== void 0) {
1544
- if (!Array.isArray(p["functions"])) problems.push(`${at2}.functions: must be a list of function folders`);
1545
- else provided.functions = p["functions"].map((f, k) => pathOf(f, `${at2}.functions[${k}]`));
1546
- }
1547
- if (provided.file && !MIGRATION_FILE.test(provided.file.split("/").pop())) problems.push(`${at2}.file: "${provided.file}" must be named NNNN_name.sql`);
1548
- if (provided.package === out.package && provided.file === file) problems.push(`${at2}: a migration can't provide itself`);
1549
- return provided;
1550
- });
1551
- }
1552
- }
1553
- if (m["needs"] !== void 0) {
1554
- if (!Array.isArray(m["needs"])) problems.push(`${where2}.needs: must be a list of { function, how }`);
1555
- else {
1556
- out.needs = m["needs"].flatMap((n, j) => {
1557
- const at2 = `${where2}.needs[${j}]`;
1558
- if (!isObject2(n) || typeof n["function"] !== "string" || typeof n["how"] !== "string" || !n["how"].trim()) {
1559
- problems.push(`${at2}: must be { function: "schema.name", how: "what to add" }`);
1560
- return [];
1561
- }
1562
- if (!SQL_FUNCTION.test(n["function"])) {
1563
- problems.push(`${at2}.function: "${n["function"]}" must be a schema-qualified function name, like private.genesis_viewer_people`);
1564
- return [];
1565
- }
1566
- return [{ function: n["function"], how: n["how"].trim() }];
1567
- });
1568
- }
1265
+ if (m["needs"] !== void 0) {
1266
+ if (!Array.isArray(m["needs"])) problems.push(`${where2}.needs: must be a list of { function, how }`);
1267
+ else {
1268
+ out.needs = m["needs"].flatMap((n, j) => {
1269
+ const at2 = `${where2}.needs[${j}]`;
1270
+ if (!isObject2(n) || typeof n["function"] !== "string" || typeof n["how"] !== "string" || !n["how"].trim()) {
1271
+ problems.push(`${at2}: must be { function: "schema.name", how: "what to add" }`);
1272
+ return [];
1273
+ }
1274
+ if (!SQL_FUNCTION.test(n["function"])) {
1275
+ problems.push(`${at2}.function: "${n["function"]}" must be a schema-qualified function name, like private.genesis_viewer_people`);
1276
+ return [];
1277
+ }
1278
+ return [{ function: n["function"], how: n["how"].trim() }];
1279
+ });
1280
+ }
1569
1281
  }
1570
1282
  if (m["runsBefore"] !== void 0) {
1571
1283
  if (!Array.isArray(m["runsBefore"])) problems.push(`${where2}.runsBefore: must be a list of { package, file }`);
@@ -1697,15 +1409,15 @@ function isBlockDef(value) {
1697
1409
  // src/blocks/files.ts
1698
1410
  var sha256 = (text) => createHash("sha256").update(text).digest("hex");
1699
1411
  function inside(parent, child) {
1700
- const rel = path20.relative(parent, child);
1701
- return rel === "" || !rel.startsWith("..") && !path20.isAbsolute(rel);
1412
+ const rel = path21.relative(parent, child);
1413
+ return rel === "" || !rel.startsWith("..") && !path21.isAbsolute(rel);
1702
1414
  }
1703
1415
  function appPath2(root, rel) {
1704
1416
  const safe = safeRelative(rel.replace(/^\.\//, ""));
1705
1417
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the app`);
1706
1418
  if (safe.split("/").some((s) => s.toLowerCase() === ".git")) throw new Error(`"${rel}" is inside .git; refused`);
1707
1419
  const realRoot = realpathSync(root);
1708
- const target = path20.join(realRoot, ...safe.split("/"));
1420
+ const target = path21.join(realRoot, ...safe.split("/"));
1709
1421
  const there = (p) => {
1710
1422
  try {
1711
1423
  lstatSync(p);
@@ -1714,20 +1426,18 @@ function appPath2(root, rel) {
1714
1426
  return false;
1715
1427
  }
1716
1428
  };
1717
- let probe = path20.dirname(target);
1718
- while (!there(probe)) probe = path20.dirname(probe);
1429
+ let probe = path21.dirname(target);
1430
+ while (!there(probe)) probe = path21.dirname(probe);
1719
1431
  let real2;
1720
1432
  try {
1721
1433
  real2 = realpathSync(probe);
1722
1434
  } catch {
1723
- throw new Error(`${rel} goes through a broken symlink (${path20.relative(realRoot, probe)}); refused`);
1435
+ throw new Error(`${rel} goes through a broken symlink (${path21.relative(realRoot, probe)}); refused`);
1724
1436
  }
1725
1437
  if (!inside(realRoot, real2)) throw new Error(`${rel} is outside the app (a symlinked folder?)`);
1726
1438
  if (there(target) && lstatSync(target).isSymbolicLink()) throw new Error(`${rel} is a symlink; left alone`);
1727
1439
  return target;
1728
1440
  }
1729
-
1730
- // src/blocks/local.ts
1731
1441
  var LOCAL_PACKAGES_KEY = "localPackages";
1732
1442
  var LocalPackagesError = class extends Error {
1733
1443
  name = "LocalPackagesError";
@@ -1737,8 +1447,8 @@ function validateLocalPackages(raw, source = "genesis.config.json") {
1737
1447
  return raw.map((entry, i) => {
1738
1448
  const where2 = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
1739
1449
  if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where2} must be a non-empty folder`);
1740
- if (path20.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
1741
- const norm = path20.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
1450
+ if (path21.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
1451
+ const norm = path21.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
1742
1452
  if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where2} must name a package folder, not the app or a parent of it ("${entry}")`);
1743
1453
  const parts = norm.split("/");
1744
1454
  if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
@@ -1749,7 +1459,7 @@ function validateLocalPackages(raw, source = "genesis.config.json") {
1749
1459
  });
1750
1460
  }
1751
1461
  function localPackageGlobs(root) {
1752
- const file = path20.join(root, "genesis.config.json");
1462
+ const file = path21.join(root, "genesis.config.json");
1753
1463
  if (!existsSync(file)) return [];
1754
1464
  let raw;
1755
1465
  try {
@@ -1763,14 +1473,14 @@ function localPackageGlobs(root) {
1763
1473
  var cache = /* @__PURE__ */ new Map();
1764
1474
  function repositoryRoot(appRoot) {
1765
1475
  for (let dir = appRoot; ; ) {
1766
- if (existsSync(path20.join(dir, ".git"))) return dir;
1767
- const parent = path20.dirname(dir);
1476
+ if (existsSync(path21.join(dir, ".git"))) return dir;
1477
+ const parent = path21.dirname(dir);
1768
1478
  if (parent === dir) return appRoot;
1769
1479
  dir = parent;
1770
1480
  }
1771
1481
  }
1772
1482
  function localPackages(root) {
1773
- const appRoot = path20.resolve(root);
1483
+ const appRoot = path21.resolve(root);
1774
1484
  const globs = localPackageGlobs(appRoot);
1775
1485
  const key2 = `${appRoot}
1776
1486
  ${globs.join("\n")}`;
@@ -1779,24 +1489,24 @@ ${globs.join("\n")}`;
1779
1489
  const dirs = /* @__PURE__ */ new Set();
1780
1490
  for (const glob of globs) {
1781
1491
  if (glob.endsWith("/*") || glob === "*") {
1782
- const parent = path20.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
1492
+ const parent = path21.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
1783
1493
  if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
1784
1494
  for (const entry of readdirSync(parent).sort()) {
1785
1495
  if (entry.startsWith(".") || entry === "node_modules") continue;
1786
- dirs.add(path20.join(parent, entry));
1496
+ dirs.add(path21.join(parent, entry));
1787
1497
  }
1788
1498
  } else {
1789
- dirs.add(path20.join(appRoot, glob));
1499
+ dirs.add(path21.join(appRoot, glob));
1790
1500
  }
1791
1501
  }
1792
1502
  const real2 = realpathSync(repositoryRoot(appRoot));
1793
1503
  const out = [];
1794
1504
  const byName = /* @__PURE__ */ new Map();
1795
1505
  for (const dir of [...dirs].sort()) {
1796
- const manifest = path20.join(dir, "package.json");
1506
+ const manifest = path21.join(dir, "package.json");
1797
1507
  if (!existsSync(manifest)) continue;
1798
1508
  if (!inside(real2, realpathSync(dir))) {
1799
- throw new LocalPackagesError(`${path20.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
1509
+ throw new LocalPackagesError(`${path21.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
1800
1510
  }
1801
1511
  let pkg;
1802
1512
  try {
@@ -1805,7 +1515,7 @@ ${globs.join("\n")}`;
1805
1515
  continue;
1806
1516
  }
1807
1517
  if (typeof pkg.name !== "string" || !pkg.name) continue;
1808
- const rel = path20.relative(appRoot, dir).split(path20.sep).join("/");
1518
+ const rel = path21.relative(appRoot, dir).split(path21.sep).join("/");
1809
1519
  const other = byName.get(pkg.name);
1810
1520
  if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
1811
1521
  byName.set(pkg.name, rel);
@@ -1993,35 +1703,35 @@ var DEFAULT_IGNORE = [
1993
1703
  ];
1994
1704
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
1995
1705
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
1996
- var toPosix = (p) => p.split(path20.sep).join("/");
1706
+ var toPosix = (p) => p.split(path21.sep).join("/");
1997
1707
  function scanFiles(root, config) {
1998
1708
  const extensions = new Set(config.extensions ?? DEFAULT_EXTENSIONS);
1999
1709
  const ignored = globMatcher([...DEFAULT_IGNORE, ...config.ignore ?? []]);
2000
1710
  const files = [];
2001
1711
  const seen = /* @__PURE__ */ new Set();
2002
1712
  const visit = (abs) => {
2003
- const rel = toPosix(path20.relative(root, abs));
1713
+ const rel = toPosix(path21.relative(root, abs));
2004
1714
  if (seen.has(rel) || ignored(rel)) return;
2005
- const ext = path20.extname(abs);
1715
+ const ext = path21.extname(abs);
2006
1716
  if (!extensions.has(ext)) return;
2007
1717
  if (statSync(abs).size > MAX_FILE_BYTES) return;
2008
1718
  seen.add(rel);
2009
1719
  const text = readFileSync(abs, "utf8");
2010
1720
  files.push({ path: rel, absolutePath: abs, ext, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(ext)) });
2011
1721
  };
2012
- const walk2 = (dir) => {
1722
+ const walk3 = (dir) => {
2013
1723
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
2014
1724
  if (entry.isDirectory()) {
2015
- if (!SKIP_DIRS.has(entry.name)) walk2(path20.join(dir, entry.name));
1725
+ if (!SKIP_DIRS.has(entry.name)) walk3(path21.join(dir, entry.name));
2016
1726
  } else if (entry.isFile()) {
2017
- visit(path20.join(dir, entry.name));
1727
+ visit(path21.join(dir, entry.name));
2018
1728
  }
2019
1729
  }
2020
1730
  };
2021
1731
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
2022
- const abs = path20.resolve(root, src);
1732
+ const abs = path21.resolve(root, src);
2023
1733
  if (!existsSync(abs)) continue;
2024
- if (statSync(abs).isDirectory()) walk2(abs);
1734
+ if (statSync(abs).isDirectory()) walk3(abs);
2025
1735
  else visit(abs);
2026
1736
  }
2027
1737
  let local = [];
@@ -2030,7 +1740,7 @@ function scanFiles(root, config) {
2030
1740
  } catch {
2031
1741
  local = [];
2032
1742
  }
2033
- for (const pkg of local) walk2(pkg.dir);
1743
+ for (const pkg of local) walk3(pkg.dir);
2034
1744
  return files;
2035
1745
  }
2036
1746
  function lineAt(text, index) {
@@ -2039,142 +1749,6 @@ function lineAt(text, index) {
2039
1749
  return line;
2040
1750
  }
2041
1751
 
2042
- // src/doctor/patterns.ts
2043
- function parseRulesMarkdown(markdown) {
2044
- const rules = [];
2045
- let current = null;
2046
- for (const line of markdown.split("\n")) {
2047
- const heading = line.match(/^###\s+([A-Za-z0-9_-]+)\s*$/);
2048
- if (heading) {
2049
- current = { id: heading[1] };
2050
- rules.push(current);
2051
- continue;
2052
- }
2053
- if (/^#{1,2}\s/.test(line)) {
2054
- current = null;
2055
- continue;
2056
- }
2057
- const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message|newOnly):\s*(.*)$/);
2058
- if (!current || !kv) continue;
2059
- const [, key2, raw] = kv;
2060
- const value = raw.trim();
2061
- if (key2 === "files" || key2 === "exclude") current[key2] = value.split(",").map((s) => s.trim()).filter(Boolean);
2062
- else if (key2 === "level") current.level = value;
2063
- else if (key2 === "newOnly") current.newOnly = value === "true" ? true : value === "false" ? false : value;
2064
- else current[key2] = value;
2065
- }
2066
- return rules;
2067
- }
2068
- function toRegExp(source, flags = "") {
2069
- if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
2070
- return new RegExp(source, flags);
2071
- }
2072
- function compilePatternRules(rules, source) {
2073
- const ids = /* @__PURE__ */ new Set();
2074
- const out = [];
2075
- for (const rule of rules) {
2076
- if (ids.has(rule.id)) throw new DoctorConfigError(`${source}: rule "${rule.id}" is defined twice`);
2077
- ids.add(rule.id);
2078
- const level = rule.level ?? "error";
2079
- if (!["error", "warn", "info", "guide"].includes(level)) {
2080
- throw new DoctorConfigError(`${source}: rule "${rule.id}" has level "${level}" (use error, warn, info or guide)`);
2081
- }
2082
- if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") {
2083
- throw new DoctorConfigError(`${source}: rule "${rule.id}" has newOnly "${String(rule.newOnly)}" (use true or false)`);
2084
- }
2085
- if (level === "guide") continue;
2086
- if (!rule.files?.length) throw new DoctorConfigError(`${source}: rule "${rule.id}" needs "files" (or level: guide)`);
2087
- if (!rule.forbid && !rule.require && !rule.path) {
2088
- throw new DoctorConfigError(`${source}: rule "${rule.id}" needs forbid, require or path (or level: guide)`);
2089
- }
2090
- try {
2091
- out.push({
2092
- rule,
2093
- level,
2094
- includes: globMatcher(rule.files),
2095
- excludes: globMatcher(rule.exclude),
2096
- forbid: rule.forbid ? toRegExp(rule.forbid, "m") : void 0,
2097
- require: rule.require ? toRegExp(rule.require, "m") : void 0,
2098
- path: rule.path ? toRegExp(rule.path) : void 0
2099
- });
2100
- } catch (err) {
2101
- throw new DoctorConfigError(`${source}: rule "${rule.id}" has an invalid pattern: ${err.message}`);
2102
- }
2103
- }
2104
- return out;
2105
- }
2106
- function loadPatternRules(root, patterns, rulesDoc) {
2107
- const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
2108
- let all = compiled;
2109
- if (rulesDoc) {
2110
- const file = path20.resolve(root, rulesDoc);
2111
- if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
2112
- const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
2113
- const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
2114
- if (clash) throw new DoctorConfigError(`rule "${clash.rule.id}" is defined in both doctor.patterns and ${rulesDoc}`);
2115
- all = [...compiled, ...fromDoc];
2116
- }
2117
- if (all.length === 0) return null;
2118
- return {
2119
- count: all.length,
2120
- ids: all.map((r) => r.rule.id),
2121
- newOnly: all.filter((r) => r.rule.newOnly).map((r) => r.rule.id),
2122
- plugin: {
2123
- name: "patterns",
2124
- check(ctx) {
2125
- for (const r of all) {
2126
- const message = r.rule.message ?? "breaks a design rule";
2127
- for (const file of ctx.files) {
2128
- if (!r.includes(file.path) || r.excludes(file.path)) continue;
2129
- const report = (line) => ctx.report({ rule: r.rule.id, level: r.level, file: file.path, line, message });
2130
- if (r.path && !r.path.test(file.path)) report(0);
2131
- if (r.require && !r.require.test(file.code)) report(0);
2132
- if (r.forbid) {
2133
- const m = r.forbid.exec(file.code);
2134
- if (m) report(lineAt(file.code, m.index));
2135
- }
2136
- }
2137
- }
2138
- }
2139
- }
2140
- };
2141
- }
2142
- async function loadPlugins(specs, configDir) {
2143
- const plugins = [];
2144
- for (const spec of specs ?? []) {
2145
- const [id, options] = typeof spec === "string" ? [spec, void 0] : spec;
2146
- const file = resolvePlugin(id, configDir);
2147
- const url = `${pathToFileURL(file).href}?mtime=${statSync(file).mtimeMs}`;
2148
- let mod;
2149
- try {
2150
- mod = await import(url);
2151
- } catch (err) {
2152
- throw new DoctorConfigError(`doctor.plugins: could not load ${id}: ${err.message}`);
2153
- }
2154
- let value = mod.default;
2155
- if (typeof value === "function") value = await value(options);
2156
- const list = Array.isArray(value) ? value : [value];
2157
- for (const p of list) {
2158
- if (!p || typeof p !== "object" || typeof p.check !== "function" || typeof p.name !== "string") {
2159
- throw new DoctorConfigError(`doctor.plugins: ${id} must default-export { name, check(context) } (or an array, or a factory returning one)`);
2160
- }
2161
- plugins.push(p);
2162
- }
2163
- }
2164
- return plugins;
2165
- }
2166
- function resolvePlugin(id, configDir) {
2167
- try {
2168
- if (id.startsWith(".") || path20.isAbsolute(id)) return resolveFrom(path20.resolve(configDir, id), configDir);
2169
- return resolveFrom(id, configDir);
2170
- } catch {
2171
- throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
2172
- }
2173
- }
2174
- function resolveFrom(id, from) {
2175
- return createRequire(path20.join(from, "noop.js")).resolve(id);
2176
- }
2177
-
2178
1752
  // src/doctor/semver.ts
2179
1753
  var VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
2180
1754
  function parseVersion(v) {
@@ -2294,46 +1868,6 @@ function satisfies(version, range) {
2294
1868
  (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))
2295
1869
  );
2296
1870
  }
2297
- var UMBRELLA_PACKAGE = "@marktiderman/genesis";
2298
- function readReleaseManifest(root) {
2299
- const dir = findPackageDir(root, UMBRELLA_PACKAGE);
2300
- const file = dir && path20.join(dir, "dist", "versions.json");
2301
- if (!file || !existsSync(file)) return null;
2302
- return JSON.parse(readFileSync(file, "utf8"));
2303
- }
2304
- function checkVersionSkew(ctx) {
2305
- const manifest = readReleaseManifest(ctx.root);
2306
- if (!manifest) return;
2307
- const overlays = markedOverlays(ctx);
2308
- for (const [name, want] of Object.entries(manifest.packages)) {
2309
- const overlay = overlays.get(name);
2310
- if (overlay) {
2311
- const from = overlay.marker.upstream.slice(overlay.marker.upstream.lastIndexOf("@") + 1);
2312
- const behind = parseVersion(from) && parseVersion(want) && compareVersions(parseVersion(from), parseVersion(want)) < 0;
2313
- if (from !== want && !behind) {
2314
- ctx.report({
2315
- rule: "version-skew",
2316
- level: "warn",
2317
- file: "package.json",
2318
- subject: name,
2319
- message: `the app's overlay of ${name} was copied from ${from}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Bring the overlay onto ${want} (or promote it and adopt the release).`
2320
- });
2321
- }
2322
- continue;
2323
- }
2324
- const dir = findPackageDir(ctx.root, name);
2325
- if (!dir) continue;
2326
- const have = JSON.parse(readFileSync(path20.join(dir, "package.json"), "utf8")).version;
2327
- if (have === want) continue;
2328
- ctx.report({
2329
- rule: "version-skew",
2330
- level: "warn",
2331
- file: "package.json",
2332
- subject: name,
2333
- message: `${name} is ${have}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Install ${name}@${want}, or move every Genesis package to one release.`
2334
- });
2335
- }
2336
- }
2337
1871
 
2338
1872
  // src/doctor/overlays.ts
2339
1873
  var GENESIS_PACKAGE_NAME = /^@marktiderman\/genesis(?:-[a-z0-9-]+)?$/;
@@ -2349,7 +1883,7 @@ function overlayState(name, json) {
2349
1883
  function overlaySetupProblems(root, config, dir, name, json) {
2350
1884
  const problems = [];
2351
1885
  if (json.private !== true) problems.push(`${name}: an overlay is the app's own copy and never publishes; set "private": true`);
2352
- const rel = path20.relative(path20.resolve(root), path20.resolve(dir)).split(path20.sep).join("/");
1886
+ const rel = path21.relative(path21.resolve(root), path21.resolve(dir)).split(path21.sep).join("/");
2353
1887
  const sources = (config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)).map((s) => s.replace(/^\.\//, "").replace(/\/+$/, ""));
2354
1888
  const holds = sources.find((s) => rel === "" || s === rel || s.startsWith(`${rel}/`));
2355
1889
  if (holds !== void 0) problems.push(`${name}: an overlay lives in a package folder of its own, not in ${rel || "the app root"}, which holds the app's source (${holds})`);
@@ -2386,92 +1920,757 @@ function pinnedVersion(root, name, manifests = ["package.json"]) {
2386
1920
  for (const file of manifests) {
2387
1921
  let json;
2388
1922
  try {
2389
- json = JSON.parse(readFileSync(path20.join(root, file), "utf8"));
2390
- } catch {
2391
- continue;
1923
+ json = JSON.parse(readFileSync(path21.join(root, file), "utf8"));
1924
+ } catch {
1925
+ continue;
1926
+ }
1927
+ for (const section2 of ["dependencies", "devDependencies", "optionalDependencies"]) {
1928
+ const spec = json[section2]?.[name];
1929
+ const v = typeof spec === "string" ? /^[\^~=]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(spec)?.[1] : void 0;
1930
+ const parsed = v && parseVersion(v);
1931
+ if (parsed && (!best || compareVersions(parsed, parseVersion(best)) > 0)) best = v;
1932
+ }
1933
+ }
1934
+ return best;
1935
+ }
1936
+ function checkOverlays(ctx, now = /* @__PURE__ */ new Date()) {
1937
+ let packages;
1938
+ try {
1939
+ packages = localPackages(ctx.root);
1940
+ } catch {
1941
+ return;
1942
+ }
1943
+ for (const pkg of packages) {
1944
+ if (!GENESIS_PACKAGE_NAME.test(pkg.name)) continue;
1945
+ const file = `${pkg.rel}/package.json`;
1946
+ let json;
1947
+ try {
1948
+ json = JSON.parse(readFileSync(path21.join(pkg.dir, "package.json"), "utf8"));
1949
+ } catch {
1950
+ continue;
1951
+ }
1952
+ const state = overlayState(pkg.name, json);
1953
+ if (state.kind === "none") {
1954
+ ctx.report({
1955
+ rule: "overlay-unmarked",
1956
+ file,
1957
+ subject: pkg.name,
1958
+ message: `${pkg.name} is a local package with a Genesis package's name, so it shadows the published one, but it carries no overlay marker; add "genesis": { "overlay": { "upstream": "${pkg.name}@<version copied>", "since": "YYYY-MM-DD", "owner": "\u2026", "reason": "\u2026" } }, or rename it`
1959
+ });
1960
+ continue;
1961
+ }
1962
+ if (state.kind === "invalid") {
1963
+ for (const problem of state.problems) ctx.report({ rule: "overlay-invalid", file, subject: pkg.name, message: problem });
1964
+ continue;
1965
+ }
1966
+ const { marker } = state;
1967
+ for (const problem of overlaySetupProblems(ctx.root, ctx.config, pkg.dir, pkg.name, json)) ctx.report({ rule: "overlay-invalid", file, subject: pkg.name, message: problem });
1968
+ const age = overlayAgeDays(marker.since, now);
1969
+ if (age < -1) {
1970
+ ctx.report({ rule: "overlay-invalid", file, subject: pkg.name, message: `${pkg.name} genesis.overlay.since: ${marker.since} is in the future; use the day the overlay was made` });
1971
+ } else if (age > OVERLAY_NOTICE_DAYS) {
1972
+ ctx.report({
1973
+ rule: "overlay-age",
1974
+ level: age > OVERLAY_WARN_DAYS ? "warn" : "info",
1975
+ file,
1976
+ subject: pkg.name,
1977
+ message: `the overlay of ${marker.upstream} is ${age} days old (since ${marker.since}, owner ${marker.owner}); promote its change to Genesis and adopt the release, or drop it (an overlay is reported after ${OVERLAY_NOTICE_DAYS} days, and after ${OVERLAY_WARN_DAYS} it warns, which fails --strict)`
1978
+ });
1979
+ }
1980
+ const upstream = overlayUpstream(marker).version;
1981
+ const version = typeof json.version === "string" ? json.version : "";
1982
+ if (LOCAL_VERSION.exec(version)?.[1] !== upstream) {
1983
+ ctx.report({
1984
+ rule: "overlay-version",
1985
+ level: "warn",
1986
+ file,
1987
+ subject: version || "(none)",
1988
+ message: `the overlay of ${marker.upstream} is version ${version || "(none)"}; use ${upstream}+local.N (or ${upstream} itself) so it reads as a local build of ${upstream} and still satisfies peer ranges`
1989
+ });
1990
+ }
1991
+ const pinned = pinnedVersion(ctx.root, pkg.name);
1992
+ const from = parseVersion(upstream);
1993
+ const to = pinned ? parseVersion(pinned) : null;
1994
+ if (from && to && compareVersions(from, to) < 0) {
1995
+ ctx.report({
1996
+ rule: "overlay-behind",
1997
+ level: "warn",
1998
+ file,
1999
+ subject: pkg.name,
2000
+ message: `the overlay of ${marker.upstream} is behind ${pkg.name}@${pinned}, the version the app now pins; run genesis upgrade, which rebases the overlay onto it (dropping what Genesis now ships) and moves the marker's upstream, or rebase it by hand`
2001
+ });
2002
+ }
2003
+ }
2004
+ }
2005
+
2006
+ // src/doctor/versions.ts
2007
+ var UMBRELLA_PACKAGE = "@marktiderman/genesis";
2008
+ function readReleaseManifest(root) {
2009
+ const dir = findPackageDir(root, UMBRELLA_PACKAGE);
2010
+ const file = dir && path21.join(dir, "dist", "versions.json");
2011
+ if (!file || !existsSync(file)) return null;
2012
+ return JSON.parse(readFileSync(file, "utf8"));
2013
+ }
2014
+ function checkVersionSkew(ctx) {
2015
+ const manifest = readReleaseManifest(ctx.root);
2016
+ if (!manifest) return;
2017
+ const overlays = markedOverlays(ctx);
2018
+ for (const [name, want] of Object.entries(manifest.packages)) {
2019
+ const overlay = overlays.get(name);
2020
+ if (overlay) {
2021
+ const from = overlay.marker.upstream.slice(overlay.marker.upstream.lastIndexOf("@") + 1);
2022
+ const behind = parseVersion(from) && parseVersion(want) && compareVersions(parseVersion(from), parseVersion(want)) < 0;
2023
+ if (from !== want && !behind) {
2024
+ ctx.report({
2025
+ rule: "version-skew",
2026
+ level: "warn",
2027
+ file: "package.json",
2028
+ subject: name,
2029
+ message: `the app's overlay of ${name} was copied from ${from}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Bring the overlay onto ${want} (or promote it and adopt the release).`
2030
+ });
2031
+ }
2032
+ continue;
2033
+ }
2034
+ const dir = findPackageDir(ctx.root, name);
2035
+ if (!dir) continue;
2036
+ const have = JSON.parse(readFileSync(path21.join(dir, "package.json"), "utf8")).version;
2037
+ if (have === want) continue;
2038
+ ctx.report({
2039
+ rule: "version-skew",
2040
+ level: "warn",
2041
+ file: "package.json",
2042
+ subject: name,
2043
+ message: `${name} is ${have}, but ${UMBRELLA_PACKAGE} ${manifest.version} was released with ${want}. Install ${name}@${want}, or move every Genesis package to one release.`
2044
+ });
2045
+ }
2046
+ }
2047
+ function buildCatalog(packagesDir) {
2048
+ const packages = {};
2049
+ for (const dir of readdirSync(packagesDir).sort()) {
2050
+ const file = path21.join(packagesDir, dir, "package.json");
2051
+ if (!existsSync(file)) continue;
2052
+ const pkg = JSON.parse(readFileSync(file, "utf8"));
2053
+ if (!pkg.name || !pkg.version || pkg.private || !pkg.name.startsWith("@marktiderman/genesis")) continue;
2054
+ packages[pkg.name] = { version: pkg.version, ...pkg.genesis?.blocks ? { blocks: pkg.genesis.blocks } : {} };
2055
+ }
2056
+ return { packages };
2057
+ }
2058
+
2059
+ // src/blocks/discover.ts
2060
+ var CLI_PACKAGE = "@marktiderman/genesis-cli";
2061
+ function cliPackageDir() {
2062
+ let dir = path21.dirname(fileURLToPath(import.meta.url));
2063
+ for (; ; ) {
2064
+ const file = path21.join(dir, "package.json");
2065
+ if (existsSync(file) && JSON.parse(readFileSync(file, "utf8")).name === CLI_PACKAGE) return dir;
2066
+ const parent = path21.dirname(dir);
2067
+ if (parent === dir) throw new Error("Can't find the genesis-cli package folder.");
2068
+ dir = parent;
2069
+ }
2070
+ }
2071
+ function workspacePackagesDir() {
2072
+ const dir = path21.resolve(cliPackageDir(), "..");
2073
+ return existsSync(path21.join(dir, "features", "package.json")) && existsSync(path21.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
2074
+ }
2075
+ var catalogCache;
2076
+ function readCatalog() {
2077
+ if (catalogCache) return catalogCache;
2078
+ const workspace = workspacePackagesDir();
2079
+ if (workspace) return catalogCache = buildCatalog(workspace);
2080
+ const file = path21.join(cliPackageDir(), "dist", "genesis-catalog.json");
2081
+ catalogCache = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : { packages: {} };
2082
+ return catalogCache;
2083
+ }
2084
+ var INSTALL_ROOT_MARKERS = [".git", "pnpm-lock.yaml", "pnpm-workspace.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"];
2085
+ function installedGenesis(root) {
2086
+ const found = /* @__PURE__ */ new Map();
2087
+ let dir = path21.resolve(root);
2088
+ for (; ; ) {
2089
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path21.join(dir, m)));
2090
+ const scope = path21.join(dir, "node_modules", "@marktiderman");
2091
+ if (existsSync(scope)) {
2092
+ for (const entry of readdirSync(scope)) {
2093
+ const name = `@marktiderman/${entry}`;
2094
+ if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
2095
+ if (existsSync(path21.join(scope, entry, "package.json"))) found.set(name, path21.join(scope, entry));
2096
+ }
2097
+ }
2098
+ const parent = path21.dirname(dir);
2099
+ if (atInstallRoot || parent === dir) return found;
2100
+ dir = parent;
2101
+ }
2102
+ }
2103
+ var declarationCache = /* @__PURE__ */ new Map();
2104
+ function declarationsOf(dir, warnings) {
2105
+ const pkg = JSON.parse(readFileSync(path21.join(dir, "package.json"), "utf8"));
2106
+ const key2 = `${realpathSync(dir)}@${pkg.version ?? ""}`;
2107
+ let cached = declarationCache.get(key2);
2108
+ if (!cached) {
2109
+ cached = loadDeclarations(dir, warnings);
2110
+ declarationCache.set(key2, cached);
2111
+ }
2112
+ return cached;
2113
+ }
2114
+ async function loadDeclarations(dir, warnings) {
2115
+ const pkg = JSON.parse(readFileSync(path21.join(dir, "package.json"), "utf8"));
2116
+ const entry = pkg.exports?.["./blocks"];
2117
+ const target = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry["import"] ?? entry["default"] : void 0;
2118
+ if (typeof target !== "string") return {};
2119
+ const rel = safeRelative(target.replace(/^\.\//, ""));
2120
+ const file = rel && path21.join(dir, ...rel.split("/"));
2121
+ if (!file || !inside(dir, file) || !existsSync(file)) return {};
2122
+ try {
2123
+ const jiti = createJiti(path21.join(dir, "package.json"), { moduleCache: false });
2124
+ const mod = await jiti.import(file);
2125
+ const out = {};
2126
+ for (const value of Object.values(mod)) if (isBlockDef(value)) out[value.id] = declarationFields(value);
2127
+ return out;
2128
+ } catch (err) {
2129
+ warnings.push(`${pkg.name}/blocks didn't load in Node (${err instanceof Error ? err.message.split("\n")[0] : String(err)}); using its package.json manifest only.`);
2130
+ return {};
2131
+ }
2132
+ }
2133
+ async function blocksOfInstalled(dir, warnings = [], options = {}) {
2134
+ const pkg = JSON.parse(readFileSync(path21.join(dir, "package.json"), "utf8"));
2135
+ const raw = rawBlocksOf(pkg);
2136
+ const declared = await declarationsOf(dir, warnings);
2137
+ const ids = /* @__PURE__ */ new Set([...Object.keys(raw), ...Object.keys(declared)]);
2138
+ const out = [];
2139
+ for (const id of [...ids].sort()) {
2140
+ const fromJson = raw[id] ?? {};
2141
+ const merged = { ...fromJson, ...declared[id] };
2142
+ if (declared[id]?.["migrations"] && Array.isArray(fromJson["migrations"])) merged["migrations"] = withProvides(declared[id]["migrations"], fromJson["migrations"]);
2143
+ const manifest = tryParse(() => parseManifest(pkg.name, id, merged, pkg.version, options), warnings);
2144
+ if (manifest) out.push(manifest);
2145
+ }
2146
+ return out;
2147
+ }
2148
+ function withProvides(declared, json) {
2149
+ if (!Array.isArray(declared)) return declared;
2150
+ const fileOf = (m) => m && typeof m === "object" ? m["file"] : void 0;
2151
+ return declared.map((m) => {
2152
+ const same = json.find((j) => fileOf(j) === fileOf(m));
2153
+ return same?.["provides"] !== void 0 && m && typeof m === "object" && !("provides" in m) ? { ...m, provides: same["provides"] } : m;
2154
+ });
2155
+ }
2156
+ async function allBlocks(root, warnings = []) {
2157
+ const out = [];
2158
+ for (const local of localPackages(root)) {
2159
+ for (const manifest of await blocksOfInstalled(local.dir, warnings, { local: true })) out.push({ manifest, from: "local" });
2160
+ }
2161
+ const installed = installedGenesis(root);
2162
+ for (const [, dir] of installed) for (const manifest of await blocksOfInstalled(dir, warnings)) out.push({ manifest, from: "installed" });
2163
+ for (const [name, entry] of Object.entries(readCatalog().packages)) {
2164
+ if (installed.has(name)) continue;
2165
+ for (const [id, raw] of Object.entries(entry.blocks ?? {})) {
2166
+ const manifest = tryParse(() => parseManifest(name, id, raw, entry.version), warnings);
2167
+ if (manifest) out.push({ manifest, from: "catalog" });
2168
+ }
2169
+ }
2170
+ return out;
2171
+ }
2172
+ function tryParse(parse2, warnings) {
2173
+ try {
2174
+ return parse2();
2175
+ } catch (err) {
2176
+ if (!(err instanceof ManifestError)) throw err;
2177
+ warnings.push(err.message);
2178
+ return null;
2179
+ }
2180
+ }
2181
+ function catalogBlocks(warnings = []) {
2182
+ const out = [];
2183
+ for (const [name, entry] of Object.entries(readCatalog().packages)) {
2184
+ for (const [id, raw] of Object.entries(entry.blocks ?? {})) {
2185
+ const manifest = tryParse(() => parseManifest(name, id, raw, entry.version), warnings);
2186
+ if (manifest) out.push(manifest);
2187
+ }
2188
+ }
2189
+ return out;
2190
+ }
2191
+ async function findBlock(root, id, options = {}) {
2192
+ const all = (await allBlocks(root, options.warnings)).filter((b) => b.manifest.id === id && (!options.package || b.manifest.package === options.package));
2193
+ if (all.length === 0) {
2194
+ const known = [...new Set((await allBlocks(root)).map((b) => b.manifest.id))].sort();
2195
+ throw new Error(`No Genesis or local package declares a block "${id}"${options.package ? ` in ${options.package}` : ""}. Known blocks: ${known.join(", ") || "none"}.`);
2196
+ }
2197
+ if (all.length > 1) throw new Error(`"${id}" is declared by ${all.map((b) => b.manifest.package).join(" and ")}; pass --package to pick one.`);
2198
+ return all[0];
2199
+ }
2200
+
2201
+ // src/blocks/pm.ts
2202
+ function findLockfile(root) {
2203
+ let dir = path21.resolve(root);
2204
+ for (; ; ) {
2205
+ if (existsSync(path21.join(dir, "pnpm-lock.yaml"))) return { pm: "pnpm", dir };
2206
+ if (existsSync(path21.join(dir, "bun.lock")) || existsSync(path21.join(dir, "bun.lockb"))) return { pm: "bun", dir };
2207
+ if (existsSync(path21.join(dir, "yarn.lock"))) return { pm: "yarn", dir };
2208
+ if (existsSync(path21.join(dir, "package-lock.json"))) return { pm: "npm", dir };
2209
+ const parent = path21.dirname(dir);
2210
+ if (parent === dir) return null;
2211
+ dir = parent;
2212
+ }
2213
+ }
2214
+ function detectPackageManager(root) {
2215
+ return findLockfile(root)?.pm ?? "npm";
2216
+ }
2217
+ function installCommand(pm) {
2218
+ return pm === "yarn" ? ["yarn", "install"] : [pm, "install"];
2219
+ }
2220
+ var shellLine = (argv) => argv.map((a) => /^[\w@./:^~=-]+$/.test(a) ? a : `'${a.replace(/'/g, "'\\''")}'`).join(" ");
2221
+
2222
+ // src/doctor/genesis.ts
2223
+ var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
2224
+ var NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
2225
+ var DESIGN_SYSTEM_PACKAGE = "@marktiderman/genesis-design-system";
2226
+ var DEFAULT_COMPONENT_PACKAGES = ["@marktiderman/genesis-forms-studio"];
2227
+ var TAGS = ["button", "input", "textarea", "select", "label", "table", "dialog", "progress", "details", "summary"];
2228
+ var TAG_ALIASES = { hr: "Separator" };
2229
+ var NON_COMPONENT_SUFFIX = /(Props|Variant|Variants|Type|Types|Config|Context|Options|Status)$/;
2230
+ var TAILWIND_PALETTE = [
2231
+ "black",
2232
+ "white",
2233
+ "slate",
2234
+ "gray",
2235
+ "zinc",
2236
+ "neutral",
2237
+ "stone",
2238
+ "red",
2239
+ "orange",
2240
+ "amber",
2241
+ "yellow",
2242
+ "lime",
2243
+ "green",
2244
+ "emerald",
2245
+ "teal",
2246
+ "cyan",
2247
+ "sky",
2248
+ "blue",
2249
+ "indigo",
2250
+ "violet",
2251
+ "purple",
2252
+ "fuchsia",
2253
+ "pink",
2254
+ "rose",
2255
+ "taupe",
2256
+ "mauve",
2257
+ "mist",
2258
+ "olive"
2259
+ ];
2260
+ function findPackageDir(from, name) {
2261
+ let dir = path21.resolve(from);
2262
+ for (; ; ) {
2263
+ const candidate = path21.join(dir, "node_modules", name);
2264
+ if (existsSync(path21.join(candidate, "package.json"))) return candidate;
2265
+ const parent = path21.dirname(dir);
2266
+ if (parent === dir) return null;
2267
+ dir = parent;
2268
+ }
2269
+ }
2270
+ function uiPackageFor(config) {
2271
+ return config.uiPackage ?? (config.packs?.includes("native") ? NATIVE_UI_PACKAGE : DEFAULT_UI_PACKAGE);
2272
+ }
2273
+ function loadGenesis(root, config) {
2274
+ const uiPackage = uiPackageFor(config);
2275
+ const pkg = readPackageExports(root, uiPackage);
2276
+ if (!pkg) throw new DoctorConfigError(notInstalled(root, uiPackage));
2277
+ const { dir: uiDir, exports: exportNames, values, components } = pkg;
2278
+ const tokens = /* @__PURE__ */ new Set();
2279
+ const themeFiles = resolveThemeFiles(root, config, uiDir);
2280
+ for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
2281
+ const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
2282
+ const rawTags = /* @__PURE__ */ new Map();
2283
+ for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
2284
+ for (const [tag, comp] of Object.entries(TAG_ALIASES)) if (values.has(comp)) rawTags.set(tag, comp);
2285
+ for (const [tag, comp] of Object.entries(config.rawTags ?? {})) {
2286
+ if (comp === false) rawTags.delete(tag);
2287
+ else rawTags.set(tag, comp);
2288
+ }
2289
+ return {
2290
+ uiPackage,
2291
+ uiVersion: pkg.version,
2292
+ exports: exportNames,
2293
+ values,
2294
+ components,
2295
+ tokens,
2296
+ rawTags,
2297
+ palette: loadPalette(root),
2298
+ companions: loadCompanions(root, config, uiPackage)
2299
+ };
2300
+ }
2301
+ function notInstalled(root, uiPackage) {
2302
+ let declared = false;
2303
+ try {
2304
+ const pkg = JSON.parse(readFileSync(path21.join(root, "package.json"), "utf8"));
2305
+ declared = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].some((s) => pkg[s]?.[uiPackage] !== void 0);
2306
+ } catch {
2307
+ }
2308
+ if (!declared) return `${uiPackage} is not installed here and isn't in this app's package.json. Add it, or set doctor.uiPackage.`;
2309
+ return `${uiPackage} is in package.json but not installed, so this app's dependencies aren't installed. Run \`${shellLine(installCommand(detectPackageManager(root)))}\`, then run this again.`;
2310
+ }
2311
+ function loadCompanions(root, config, uiPackage) {
2312
+ const out = [];
2313
+ for (const name of config.componentPackages ?? DEFAULT_COMPONENT_PACKAGES) {
2314
+ if (name === uiPackage) continue;
2315
+ try {
2316
+ const pkg = readPackageExports(root, name);
2317
+ if (pkg) out.push({ package: name, version: pkg.version, components: pkg.components });
2318
+ } catch (err) {
2319
+ if (!(err instanceof DoctorConfigError)) throw err;
2320
+ }
2321
+ }
2322
+ return out;
2323
+ }
2324
+ function readPackageExports(root, uiPackage) {
2325
+ const uiDir = findPackageDir(root, uiPackage);
2326
+ if (!uiDir) return null;
2327
+ const uiPkg = JSON.parse(readFileSync(path21.join(uiDir, "package.json"), "utf8"));
2328
+ const subpaths = Object.values(uiPkg.exports ?? {});
2329
+ const declared = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
2330
+ const fromSource = typeof declared !== "string" && !subpaths.some((t) => typeof exportTypes(t) === "string");
2331
+ const entryOf = fromSource ? exportSource : exportTypes;
2332
+ const typeEntries = /* @__PURE__ */ new Set();
2333
+ const mainTypes = fromSource ? exportSource(uiPkg.exports?.["."] ?? uiPkg.exports) ?? (isTsSource(uiPkg.main) ? uiPkg.main : void 0) : declared;
2334
+ if (typeof mainTypes === "string") typeEntries.add(mainTypes);
2335
+ for (const target of subpaths) {
2336
+ const t = entryOf(target);
2337
+ if (typeof t === "string" && !t.includes("*")) typeEntries.add(t);
2338
+ }
2339
+ const exportNames = /* @__PURE__ */ new Set();
2340
+ const reexportedPackages = /* @__PURE__ */ new Set();
2341
+ let readAny = false;
2342
+ const seen = /* @__PURE__ */ new Set();
2343
+ const readEntry = (file) => {
2344
+ if (seen.has(file) || !insidePackage(uiDir, file) || !existsSync(file)) return;
2345
+ seen.add(file);
2346
+ readAny = true;
2347
+ const code = fromSource ? stripComments(readFileSync(file, "utf8")) : readFileSync(file, "utf8");
2348
+ for (const name of fromSource ? parseSourceExportNames(code) : parseExportNames(code)) exportNames.add(name);
2349
+ for (const m of code.matchAll(/export\s+(?:type\s+)?(?:\{[^}]*\}|\*)\s*from\s*["']([^"'.][^"']*)["']/g)) {
2350
+ reexportedPackages.add(packageName(m[1]));
2351
+ }
2352
+ if (fromSource) {
2353
+ for (const m of code.matchAll(/export\s+\*\s+from\s*["'](\.[^"']*)["']/g)) {
2354
+ const next = resolveSource(path21.dirname(file), m[1]);
2355
+ if (next) readEntry(next);
2356
+ }
2357
+ }
2358
+ };
2359
+ for (const entry of typeEntries) readEntry(path21.join(uiDir, entry));
2360
+ if (!readAny) {
2361
+ const what = fromSource ? "type declarations or TypeScript source" : "type declarations";
2362
+ throw new DoctorConfigError(`${uiPackage} has no ${what} to read (is it built?). Looked for: ${[...typeEntries].join(", ") || "none"}`);
2363
+ }
2364
+ const valueDecls = /* @__PURE__ */ new Set();
2365
+ const typeDecls = /* @__PURE__ */ new Set();
2366
+ const declRoot = typeof mainTypes === "string" ? path21.dirname(path21.join(uiDir, mainTypes)) : uiDir;
2367
+ const declFiles = fromSource ? walkSource(declRoot) : walkDts(declRoot);
2368
+ for (const pkg of reexportedPackages) {
2369
+ const dir = findPackageDir(uiDir, pkg);
2370
+ if (dir) walkDts(path21.join(dir, "dist"), declFiles);
2371
+ }
2372
+ for (const file of declFiles) {
2373
+ const text = readFileSync(file, "utf8");
2374
+ for (const m of text.matchAll(/\b(?:declare\s+)?(?:const|let|var|function|class|enum)\s+([A-Za-z_$][\w$]*)/g)) valueDecls.add(m[1]);
2375
+ for (const m of text.matchAll(/\b(?:interface|type)\s+([A-Za-z_$][\w$]*)/g)) typeDecls.add(m[1]);
2376
+ }
2377
+ const isTypeOnly = (n) => typeDecls.has(n) && !valueDecls.has(n);
2378
+ const values = new Set([...exportNames].filter((n) => !isTypeOnly(n)));
2379
+ const components = [...values].filter((n) => /^[A-Z][A-Za-z0-9]*$/.test(n) && !(n.length > 2 && n === n.toUpperCase()) && !NON_COMPONENT_SUFFIX.test(n)).sort();
2380
+ return { dir: uiDir, version: String(uiPkg.version ?? "unknown"), exports: exportNames, values, components };
2381
+ }
2382
+ function parseExportNames(dts) {
2383
+ const names = [];
2384
+ for (const m of dts.matchAll(/export\s+(?:type\s+)?\{([^}]*)\}/g)) {
2385
+ for (const part of m[1].split(",")) {
2386
+ const name = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/).pop()?.trim();
2387
+ if (name && name !== "default") names.push(name);
2388
+ }
2389
+ }
2390
+ for (const m of dts.matchAll(/export\s+(?:declare\s+)?(?:const|let|function|class|enum|interface|type)\s+([A-Za-z_$][\w$]*)/g)) {
2391
+ names.push(m[1]);
2392
+ }
2393
+ return names;
2394
+ }
2395
+ function declaredTokens(css) {
2396
+ return [...css.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)].map((m) => m[1]);
2397
+ }
2398
+ function packageName(specifier) {
2399
+ const parts = specifier.split("/");
2400
+ return parts.slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
2401
+ }
2402
+ function parseSourceExportNames(code) {
2403
+ const names = parseExportNames(code);
2404
+ for (const m of code.matchAll(/export\s+(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:var|class|function\*?)\s+([A-Za-z_$][\w$]*)/g)) names.push(m[1]);
2405
+ for (const m of code.matchAll(/export\s+\*\s+as\s+([A-Za-z_$][\w$]*)/g)) names.push(m[1]);
2406
+ return [...new Set(names)];
2407
+ }
2408
+ var TS_SOURCE = /\.(?:[cm]?tsx?)$/;
2409
+ var isTsSource = (v) => typeof v === "string" && TS_SOURCE.test(v) && !/\.d\.[cm]?ts$/.test(v);
2410
+ function exportSource(target) {
2411
+ if (isTsSource(target)) return target;
2412
+ if (!target || typeof target !== "object") return void 0;
2413
+ for (const value of Object.values(target)) {
2414
+ const nested = exportSource(value);
2415
+ if (nested) return nested;
2416
+ }
2417
+ return void 0;
2418
+ }
2419
+ function resolveSource(dir, spec) {
2420
+ const base = path21.resolve(dir, spec.replace(/\.js$/, ""));
2421
+ const candidates = [base, ...[".ts", ".tsx", ".mts", ".cts"].map((e) => base + e), ...["index.ts", "index.tsx"].map((i) => path21.join(base, i))];
2422
+ return candidates.find((f) => TS_SOURCE.test(f) && existsSync(f) && statSync(f).isFile()) ?? null;
2423
+ }
2424
+ function insidePackage(dir, file) {
2425
+ const rel = path21.relative(path21.resolve(dir), path21.resolve(file));
2426
+ return rel === "" || !rel.startsWith("..") && !path21.isAbsolute(rel);
2427
+ }
2428
+ function stripComments(code) {
2429
+ let out = "";
2430
+ let i = 0;
2431
+ while (i < code.length) {
2432
+ const c = code[i];
2433
+ const next = code[i + 1];
2434
+ if (c === "/" && next === "*") {
2435
+ const end = code.indexOf("*/", i + 2);
2436
+ const stop = end < 0 ? code.length : end + 2;
2437
+ out += code.slice(i, stop).replace(/[^\n]/g, " ");
2438
+ i = stop;
2439
+ } else if (c === "/" && next === "/") {
2440
+ const end = code.indexOf("\n", i);
2441
+ i = end < 0 ? code.length : end;
2442
+ } else if (c === '"' || c === "'" || c === "`") {
2443
+ let j = i + 1;
2444
+ while (j < code.length && code[j] !== c) {
2445
+ if (code[j] === "\\") j++;
2446
+ else if (c !== "`" && code[j] === "\n") break;
2447
+ j++;
2448
+ }
2449
+ out += code.slice(i, j + 1);
2450
+ i = j + 1;
2451
+ } else {
2452
+ out += c;
2453
+ i++;
2454
+ }
2455
+ }
2456
+ return out;
2457
+ }
2458
+ function walkSource(dir, out = []) {
2459
+ if (!existsSync(dir)) return out;
2460
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
2461
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
2462
+ const p = path21.join(dir, entry.name);
2463
+ if (entry.isDirectory()) walkSource(p, out);
2464
+ else if (isTsSource(entry.name) || /\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
2465
+ }
2466
+ return out;
2467
+ }
2468
+ function exportTypes(target) {
2469
+ if (!target || typeof target !== "object") return void 0;
2470
+ const t = target;
2471
+ if (typeof t.types === "string") return t.types;
2472
+ for (const key2 of ["import", "default", "require"]) {
2473
+ const nested = exportTypes(t[key2]);
2474
+ if (nested) return nested;
2475
+ }
2476
+ return void 0;
2477
+ }
2478
+ function walkDts(dir, out = []) {
2479
+ if (!existsSync(dir)) return out;
2480
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
2481
+ if (entry.name === "node_modules") continue;
2482
+ const p = path21.join(dir, entry.name);
2483
+ if (entry.isDirectory()) walkDts(p, out);
2484
+ else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
2485
+ }
2486
+ return out;
2487
+ }
2488
+ function resolveThemeFiles(root, config, uiDir) {
2489
+ if (config.themeCss) {
2490
+ const specs = typeof config.themeCss === "string" ? [config.themeCss] : config.themeCss;
2491
+ return specs.map((spec) => {
2492
+ const file = resolveSpec(root, spec);
2493
+ if (!file) throw new DoctorConfigError(`doctor.themeCss: cannot find ${spec}`);
2494
+ return file;
2495
+ });
2496
+ }
2497
+ const files = [];
2498
+ const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
2499
+ const themes = ds && path21.join(ds, "dist", "themes");
2500
+ if (themes && existsSync(themes)) {
2501
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path21.join(themes, name));
2502
+ }
2503
+ if (files.length === 0) {
2504
+ throw new DoctorConfigError(
2505
+ `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
2506
+ );
2507
+ }
2508
+ const uiStyles = path21.join(uiDir, "dist", "styles.css");
2509
+ if (existsSync(uiStyles)) files.push(uiStyles);
2510
+ return files;
2511
+ }
2512
+ function resolveSpec(root, spec) {
2513
+ const local = path21.resolve(root, spec);
2514
+ if (spec.startsWith(".") || path21.isAbsolute(spec)) return existsSync(local) ? local : null;
2515
+ const parts = spec.split("/");
2516
+ const nameLength = spec.startsWith("@") ? 2 : 1;
2517
+ const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
2518
+ if (dir) {
2519
+ const file = path21.join(dir, ...parts.slice(nameLength));
2520
+ if (existsSync(file) && statSync(file).isFile()) return file;
2521
+ }
2522
+ return existsSync(local) ? local : null;
2523
+ }
2524
+ function loadPalette(root) {
2525
+ const names = new Set(TAILWIND_PALETTE);
2526
+ try {
2527
+ const req = createRequire(path21.join(root, "package.json"));
2528
+ const colors = req("tailwindcss/colors");
2529
+ for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
2530
+ if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
2531
+ }
2532
+ } catch {
2533
+ }
2534
+ return [...names].sort();
2535
+ }
2536
+ function parseRulesMarkdown(markdown) {
2537
+ const rules = [];
2538
+ let current = null;
2539
+ for (const line of markdown.split("\n")) {
2540
+ const heading = line.match(/^###\s+([A-Za-z0-9_-]+)\s*$/);
2541
+ if (heading) {
2542
+ current = { id: heading[1] };
2543
+ rules.push(current);
2544
+ continue;
2545
+ }
2546
+ if (/^#{1,2}\s/.test(line)) {
2547
+ current = null;
2548
+ continue;
2549
+ }
2550
+ const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message|newOnly):\s*(.*)$/);
2551
+ if (!current || !kv) continue;
2552
+ const [, key2, raw] = kv;
2553
+ const value = raw.trim();
2554
+ if (key2 === "files" || key2 === "exclude") current[key2] = value.split(",").map((s) => s.trim()).filter(Boolean);
2555
+ else if (key2 === "level") current.level = value;
2556
+ else if (key2 === "newOnly") current.newOnly = value === "true" ? true : value === "false" ? false : value;
2557
+ else current[key2] = value;
2558
+ }
2559
+ return rules;
2560
+ }
2561
+ function toRegExp(source, flags = "") {
2562
+ if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
2563
+ return new RegExp(source, flags);
2564
+ }
2565
+ function compilePatternRules(rules, source) {
2566
+ const ids = /* @__PURE__ */ new Set();
2567
+ const out = [];
2568
+ for (const rule of rules) {
2569
+ if (ids.has(rule.id)) throw new DoctorConfigError(`${source}: rule "${rule.id}" is defined twice`);
2570
+ ids.add(rule.id);
2571
+ const level = rule.level ?? "error";
2572
+ if (!["error", "warn", "info", "guide"].includes(level)) {
2573
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" has level "${level}" (use error, warn, info or guide)`);
2574
+ }
2575
+ if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") {
2576
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" has newOnly "${String(rule.newOnly)}" (use true or false)`);
2577
+ }
2578
+ if (level === "guide") continue;
2579
+ if (!rule.files?.length) throw new DoctorConfigError(`${source}: rule "${rule.id}" needs "files" (or level: guide)`);
2580
+ if (!rule.forbid && !rule.require && !rule.path) {
2581
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" needs forbid, require or path (or level: guide)`);
2582
+ }
2583
+ try {
2584
+ out.push({
2585
+ rule,
2586
+ level,
2587
+ includes: globMatcher(rule.files),
2588
+ excludes: globMatcher(rule.exclude),
2589
+ forbid: rule.forbid ? toRegExp(rule.forbid, "m") : void 0,
2590
+ require: rule.require ? toRegExp(rule.require, "m") : void 0,
2591
+ path: rule.path ? toRegExp(rule.path) : void 0
2592
+ });
2593
+ } catch (err) {
2594
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" has an invalid pattern: ${err.message}`);
2595
+ }
2596
+ }
2597
+ return out;
2598
+ }
2599
+ function loadPatternRules(root, patterns, rulesDoc) {
2600
+ const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
2601
+ let all = compiled;
2602
+ if (rulesDoc) {
2603
+ const file = path21.resolve(root, rulesDoc);
2604
+ if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
2605
+ const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
2606
+ const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
2607
+ if (clash) throw new DoctorConfigError(`rule "${clash.rule.id}" is defined in both doctor.patterns and ${rulesDoc}`);
2608
+ all = [...compiled, ...fromDoc];
2609
+ }
2610
+ if (all.length === 0) return null;
2611
+ return {
2612
+ count: all.length,
2613
+ ids: all.map((r) => r.rule.id),
2614
+ newOnly: all.filter((r) => r.rule.newOnly).map((r) => r.rule.id),
2615
+ plugin: {
2616
+ name: "patterns",
2617
+ check(ctx) {
2618
+ for (const r of all) {
2619
+ const message = r.rule.message ?? "breaks a design rule";
2620
+ for (const file of ctx.files) {
2621
+ if (!r.includes(file.path) || r.excludes(file.path)) continue;
2622
+ const report = (line) => ctx.report({ rule: r.rule.id, level: r.level, file: file.path, line, message });
2623
+ if (r.path && !r.path.test(file.path)) report(0);
2624
+ if (r.require && !r.require.test(file.code)) report(0);
2625
+ if (r.forbid) {
2626
+ const m = r.forbid.exec(file.code);
2627
+ if (m) report(lineAt(file.code, m.index));
2628
+ }
2629
+ }
2630
+ }
2631
+ }
2632
+ }
2633
+ };
2634
+ }
2635
+ async function loadPlugins(specs, configDir) {
2636
+ const plugins = [];
2637
+ for (const spec of specs ?? []) {
2638
+ const [id, options] = typeof spec === "string" ? [spec, void 0] : spec;
2639
+ const file = resolvePlugin(id, configDir);
2640
+ const url = `${pathToFileURL(file).href}?mtime=${statSync(file).mtimeMs}`;
2641
+ let mod;
2642
+ try {
2643
+ mod = await import(url);
2644
+ } catch (err) {
2645
+ throw new DoctorConfigError(`doctor.plugins: could not load ${id}: ${err.message}`);
2392
2646
  }
2393
- for (const section2 of ["dependencies", "devDependencies", "optionalDependencies"]) {
2394
- const spec = json[section2]?.[name];
2395
- const v = typeof spec === "string" ? /^[\^~=]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(spec)?.[1] : void 0;
2396
- const parsed = v && parseVersion(v);
2397
- if (parsed && (!best || compareVersions(parsed, parseVersion(best)) > 0)) best = v;
2647
+ let value = mod.default;
2648
+ if (typeof value === "function") value = await value(options);
2649
+ const list = Array.isArray(value) ? value : [value];
2650
+ for (const p of list) {
2651
+ if (!p || typeof p !== "object" || typeof p.check !== "function" || typeof p.name !== "string") {
2652
+ throw new DoctorConfigError(`doctor.plugins: ${id} must default-export { name, check(context) } (or an array, or a factory returning one)`);
2653
+ }
2654
+ plugins.push(p);
2398
2655
  }
2399
2656
  }
2400
- return best;
2657
+ return plugins;
2401
2658
  }
2402
- function checkOverlays(ctx, now = /* @__PURE__ */ new Date()) {
2403
- let packages;
2659
+ function resolvePlugin(id, configDir) {
2404
2660
  try {
2405
- packages = localPackages(ctx.root);
2661
+ if (id.startsWith(".") || path21.isAbsolute(id)) return resolveFrom(path21.resolve(configDir, id), configDir);
2662
+ return resolveFrom(id, configDir);
2406
2663
  } catch {
2407
- return;
2408
- }
2409
- for (const pkg of packages) {
2410
- if (!GENESIS_PACKAGE_NAME.test(pkg.name)) continue;
2411
- const file = `${pkg.rel}/package.json`;
2412
- let json;
2413
- try {
2414
- json = JSON.parse(readFileSync(path20.join(pkg.dir, "package.json"), "utf8"));
2415
- } catch {
2416
- continue;
2417
- }
2418
- const state = overlayState(pkg.name, json);
2419
- if (state.kind === "none") {
2420
- ctx.report({
2421
- rule: "overlay-unmarked",
2422
- file,
2423
- subject: pkg.name,
2424
- message: `${pkg.name} is a local package with a Genesis package's name, so it shadows the published one, but it carries no overlay marker; add "genesis": { "overlay": { "upstream": "${pkg.name}@<version copied>", "since": "YYYY-MM-DD", "owner": "\u2026", "reason": "\u2026" } }, or rename it`
2425
- });
2426
- continue;
2427
- }
2428
- if (state.kind === "invalid") {
2429
- for (const problem of state.problems) ctx.report({ rule: "overlay-invalid", file, subject: pkg.name, message: problem });
2430
- continue;
2431
- }
2432
- const { marker } = state;
2433
- for (const problem of overlaySetupProblems(ctx.root, ctx.config, pkg.dir, pkg.name, json)) ctx.report({ rule: "overlay-invalid", file, subject: pkg.name, message: problem });
2434
- const age = overlayAgeDays(marker.since, now);
2435
- if (age < -1) {
2436
- ctx.report({ rule: "overlay-invalid", file, subject: pkg.name, message: `${pkg.name} genesis.overlay.since: ${marker.since} is in the future; use the day the overlay was made` });
2437
- } else if (age > OVERLAY_NOTICE_DAYS) {
2438
- ctx.report({
2439
- rule: "overlay-age",
2440
- level: age > OVERLAY_WARN_DAYS ? "warn" : "info",
2441
- file,
2442
- subject: pkg.name,
2443
- message: `the overlay of ${marker.upstream} is ${age} days old (since ${marker.since}, owner ${marker.owner}); promote its change to Genesis and adopt the release, or drop it (an overlay is reported after ${OVERLAY_NOTICE_DAYS} days, and after ${OVERLAY_WARN_DAYS} it warns, which fails --strict)`
2444
- });
2445
- }
2446
- const upstream = overlayUpstream(marker).version;
2447
- const version = typeof json.version === "string" ? json.version : "";
2448
- if (LOCAL_VERSION.exec(version)?.[1] !== upstream) {
2449
- ctx.report({
2450
- rule: "overlay-version",
2451
- level: "warn",
2452
- file,
2453
- subject: version || "(none)",
2454
- message: `the overlay of ${marker.upstream} is version ${version || "(none)"}; use ${upstream}+local.N (or ${upstream} itself) so it reads as a local build of ${upstream} and still satisfies peer ranges`
2455
- });
2456
- }
2457
- const pinned = pinnedVersion(ctx.root, pkg.name);
2458
- const from = parseVersion(upstream);
2459
- const to = pinned ? parseVersion(pinned) : null;
2460
- if (from && to && compareVersions(from, to) < 0) {
2461
- ctx.report({
2462
- rule: "overlay-behind",
2463
- level: "warn",
2464
- file,
2465
- subject: pkg.name,
2466
- message: `the overlay of ${marker.upstream} is behind ${pkg.name}@${pinned}, the version the app now pins; run genesis upgrade, which rebases the overlay onto it (dropping what Genesis now ships) and moves the marker's upstream, or rebase it by hand`
2467
- });
2468
- }
2664
+ throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
2469
2665
  }
2470
2666
  }
2471
-
2472
- // src/doctor/rules.ts
2667
+ function resolveFrom(id, from) {
2668
+ return createRequire(path21.join(from, "noop.js")).resolve(id);
2669
+ }
2473
2670
  var BUILTIN_RULES = [
2474
2671
  "local-primitives",
2672
+ // figma (figma/routes.ts; runs when genesis.config.json has a figma block)
2673
+ "figma-routes",
2475
2674
  "starter-leftover",
2476
2675
  "forbidden-import",
2477
2676
  "raw-tag",
@@ -2564,7 +2763,7 @@ function importSpecifiers(file) {
2564
2763
  }
2565
2764
  function checkProjectLayout(ctx) {
2566
2765
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
2567
- if (existsSync(path20.join(ctx.root, dir))) {
2766
+ if (existsSync(path21.join(ctx.root, dir))) {
2568
2767
  ctx.report({
2569
2768
  rule: "local-primitives",
2570
2769
  file: dir,
@@ -2574,7 +2773,7 @@ function checkProjectLayout(ctx) {
2574
2773
  }
2575
2774
  }
2576
2775
  for (const file of STARTER_LEFTOVERS) {
2577
- if (existsSync(path20.join(ctx.root, file))) {
2776
+ if (existsSync(path21.join(ctx.root, file))) {
2578
2777
  ctx.report({
2579
2778
  rule: "starter-leftover",
2580
2779
  level: "warn",
@@ -2664,7 +2863,7 @@ function checkTokens(ctx) {
2664
2863
  }
2665
2864
  for (const pattern of ctx.config.tokenFiles ?? []) {
2666
2865
  if (/[*?]/.test(pattern)) continue;
2667
- const abs = path20.join(ctx.root, pattern);
2866
+ const abs = path21.join(ctx.root, pattern);
2668
2867
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
2669
2868
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
2670
2869
  }
@@ -2688,7 +2887,7 @@ function checkShadowedExports(ctx) {
2688
2887
  file.code.split("\n").forEach((text, i) => {
2689
2888
  for (const m of text.matchAll(re)) {
2690
2889
  if (!ctx.genesis.values.has(m[1])) continue;
2691
- ctx.report({ rule: "shadowed-export", file: file.path, line: i + 1, subject: m[1], message: `shadows the Genesis export '${m[1]}'; reuse or extend Genesis ${m[1]}` });
2890
+ ctx.report({ rule: "shadowed-export", file: file.path, line: i + 1, subject: m[1], message: `shadows the Genesis export '${m[1]}'; reuse or extend ${m[1]} from ${ctx.genesis.uiPackage} (or rename yours if it's a different thing)` });
2692
2891
  }
2693
2892
  });
2694
2893
  }
@@ -2787,10 +2986,10 @@ var SCRIPT_EXTS2 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts"
2787
2986
  var JSX_EXTS2 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
2788
2987
  var RESOLVE_EXTS = [".tsx", ".ts", ".jsx", ".js"];
2789
2988
  function resolveLocal(root, fromFile, spec) {
2790
- const bases = spec.startsWith(".") ? [path20.resolve(path20.dirname(fromFile), spec)] : [path20.join(root, spec.slice(2)), path20.join(root, "src", spec.slice(2))];
2989
+ const bases = spec.startsWith(".") ? [path21.resolve(path21.dirname(fromFile), spec)] : [path21.join(root, spec.slice(2)), path21.join(root, "src", spec.slice(2))];
2791
2990
  for (const base of bases) {
2792
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path20.join(base, `index${e}`))].find(
2793
- (p) => SCRIPT_EXTS2.has(path20.extname(p)) && existsSync(p)
2991
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path21.join(base, `index${e}`))].find(
2992
+ (p) => SCRIPT_EXTS2.has(path21.extname(p)) && existsSync(p)
2794
2993
  );
2795
2994
  if (hit) return hit;
2796
2995
  }
@@ -2911,13 +3110,13 @@ function checkNativePack(ctx) {
2911
3110
  }
2912
3111
  function checkEasPlaceholders(ctx) {
2913
3112
  const files = [];
2914
- if (existsSync(path20.join(ctx.root, "eas.json"))) files.push("eas.json");
2915
- const workflows = path20.join(ctx.root, ".eas", "workflows");
3113
+ if (existsSync(path21.join(ctx.root, "eas.json"))) files.push("eas.json");
3114
+ const workflows = path21.join(ctx.root, ".eas", "workflows");
2916
3115
  if (existsSync(workflows)) {
2917
3116
  for (const name of readdirSync(workflows).sort()) if (/\.ya?ml$/.test(name)) files.push(`.eas/workflows/${name}`);
2918
3117
  }
2919
3118
  for (const file of files) {
2920
- for (const hit of findPlaceholders(file, readFileSync(path20.join(ctx.root, file), "utf8"))) {
3119
+ for (const hit of findPlaceholders(file, readFileSync(path21.join(ctx.root, file), "utf8"))) {
2921
3120
  const key2 = placeholderKey(hit.text, hit.placeholder);
2922
3121
  const what = EAS_PLACEHOLDERS[hit.placeholder];
2923
3122
  ctx.report({
@@ -2996,7 +3195,7 @@ function checkCustomHeaders(ctx, pkg) {
2996
3195
  if (!JSX_EXTS3.has(file.ext)) continue;
2997
3196
  const code = file.code;
2998
3197
  const hidden = HIDES_HEADER.exec(code);
2999
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path20.posix.dirname(file.path), file.path);
3198
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path21.posix.dirname(file.path), file.path);
3000
3199
  const own = hidden ? ownHeader(code, pkg) : null;
3001
3200
  if (hidden && own) {
3002
3201
  reported.add(file.path);
@@ -3024,7 +3223,7 @@ function checkCustomHeaders(ctx, pkg) {
3024
3223
  }
3025
3224
  for (const file of ctx.files) {
3026
3225
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
3027
- const layout = hidingLayouts.get(path20.posix.dirname(file.path));
3226
+ const layout = hidingLayouts.get(path21.posix.dirname(file.path));
3028
3227
  const own = layout ? ownHeader(file.code, pkg) : null;
3029
3228
  if (!layout || !own) continue;
3030
3229
  ctx.report({
@@ -3046,13 +3245,13 @@ function isLoadingOnlyRoute(code) {
3046
3245
  }
3047
3246
  function routerRoot(ctx) {
3048
3247
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
3049
- return existsSync(path20.join(ctx.root, "src", "app")) ? "src/app" : "app";
3248
+ return existsSync(path21.join(ctx.root, "src", "app")) ? "src/app" : "app";
3050
3249
  }
3051
3250
  function checkScreenLayouts(ctx, pkg) {
3052
3251
  const layouts = nativeLayouts(pkg);
3053
3252
  if (layouts.length === 0) return;
3054
3253
  const rootDir = routerRoot(ctx);
3055
- if (!existsSync(path20.join(ctx.root, rootDir))) {
3254
+ if (!existsSync(path21.join(ctx.root, rootDir))) {
3056
3255
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
3057
3256
  return;
3058
3257
  }
@@ -3108,7 +3307,7 @@ var GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\
3108
3307
  function readExpoConfigs(root) {
3109
3308
  const out = [];
3110
3309
  for (const name of EXPO_CONFIGS) {
3111
- const abs = path20.join(root, name);
3310
+ const abs = path21.join(root, name);
3112
3311
  if (!existsSync(abs)) continue;
3113
3312
  const text = readFileSync(abs, "utf8");
3114
3313
  let json = null;
@@ -3142,13 +3341,13 @@ function pluginOptions(json, module) {
3142
3341
  return null;
3143
3342
  }
3144
3343
  function dependencies(root) {
3145
- const file = path20.join(root, "package.json");
3344
+ const file = path21.join(root, "package.json");
3146
3345
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
3147
3346
  const pkg = JSON.parse(readFileSync(file, "utf8"));
3148
3347
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
3149
3348
  }
3150
3349
  function runtimeDependencies(root) {
3151
- const file = path20.join(root, "package.json");
3350
+ const file = path21.join(root, "package.json");
3152
3351
  if (!existsSync(file)) return {};
3153
3352
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
3154
3353
  }
@@ -3402,14 +3601,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3402
3601
  seen.add(file);
3403
3602
  const json = readJsonc(file);
3404
3603
  if (!json) return {};
3405
- const dir = path20.dirname(file);
3604
+ const dir = path21.dirname(file);
3406
3605
  let merged = {};
3407
3606
  const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3408
3607
  for (const ext of parents) {
3409
3608
  if (typeof ext !== "string") continue;
3410
3609
  let target = null;
3411
- if (ext.startsWith(".") || path20.isAbsolute(ext)) {
3412
- const abs = path20.resolve(dir, ext);
3610
+ if (ext.startsWith(".") || path21.isAbsolute(ext)) {
3611
+ const abs = path21.resolve(dir, ext);
3413
3612
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3414
3613
  } else {
3415
3614
  const parts = ext.split("/");
@@ -3417,14 +3616,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3417
3616
  const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3418
3617
  if (pkgDir) {
3419
3618
  const sub = parts.slice(nameLength).join("/");
3420
- const abs = path20.join(pkgDir, sub || "tsconfig.json");
3619
+ const abs = path21.join(pkgDir, sub || "tsconfig.json");
3421
3620
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3422
3621
  }
3423
3622
  }
3424
3623
  if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
3425
3624
  }
3426
3625
  const opts = json.compilerOptions ?? {};
3427
- if (typeof opts.baseUrl === "string") merged.baseUrl = path20.resolve(dir, opts.baseUrl);
3626
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path21.resolve(dir, opts.baseUrl);
3428
3627
  if (opts.paths && typeof opts.paths === "object") {
3429
3628
  merged.paths = opts.paths;
3430
3629
  merged.pathsDir = dir;
@@ -3435,7 +3634,7 @@ function aliases(root) {
3435
3634
  const table = [];
3436
3635
  let baseUrl = null;
3437
3636
  for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3438
- const file = path20.join(root, name);
3637
+ const file = path21.join(root, name);
3439
3638
  if (!existsSync(file)) continue;
3440
3639
  const config = readTsconfig(root, file);
3441
3640
  baseUrl ??= config.baseUrl ?? null;
@@ -3443,22 +3642,22 @@ function aliases(root) {
3443
3642
  for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3444
3643
  if (!Array.isArray(targets)) continue;
3445
3644
  const exact = !pattern.endsWith("*");
3446
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path20.join(base, String(t).replace(/\*$/, ""))) });
3645
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path21.join(base, String(t).replace(/\*$/, ""))) });
3447
3646
  }
3448
3647
  }
3449
- const pkg = readJsonc(path20.join(root, "package.json"));
3648
+ const pkg = readJsonc(path21.join(root, "package.json"));
3450
3649
  for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3451
3650
  if (typeof target !== "string") continue;
3452
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path20.join(root, target.replace(/\*.*$/, ""))] });
3651
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path21.join(root, target.replace(/\*.*$/, ""))] });
3453
3652
  }
3454
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path20.join(root, "src") + path20.sep, root + path20.sep] });
3653
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path21.join(root, "src") + path21.sep, root + path21.sep] });
3455
3654
  return { table, baseUrl };
3456
3655
  }
3457
3656
  function resolveFile(base) {
3458
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path20.join(base, `index${e}`))];
3657
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path21.join(base, `index${e}`))];
3459
3658
  if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3460
3659
  for (const p of tries) {
3461
- if (SCRIPT_EXTS2.has(path20.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3660
+ if (SCRIPT_EXTS2.has(path21.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3462
3661
  }
3463
3662
  return null;
3464
3663
  }
@@ -3472,7 +3671,7 @@ function createTrail(ctx) {
3472
3671
  const { table, baseUrl } = aliases(ctx.root);
3473
3672
  let declared = null;
3474
3673
  try {
3475
- const pkg = JSON.parse(readFileSync(path20.join(ctx.root, "package.json"), "utf8"));
3674
+ const pkg = JSON.parse(readFileSync(path21.join(ctx.root, "package.json"), "utf8"));
3476
3675
  declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
3477
3676
  } catch {
3478
3677
  declared = null;
@@ -3503,17 +3702,17 @@ function createTrail(ctx) {
3503
3702
  if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
3504
3703
  let resolved = null;
3505
3704
  if (spec.startsWith(".")) {
3506
- resolved = resolveFile(path20.resolve(path20.dirname(file.absolutePath), spec));
3705
+ resolved = resolveFile(path21.resolve(path21.dirname(file.absolutePath), spec));
3507
3706
  if (!resolved) lost = true;
3508
3707
  } else {
3509
3708
  const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
3510
3709
  if (alias) {
3511
3710
  for (const t of alias.targets) {
3512
- resolved = resolveFile(alias.exact ? t : path20.join(t, spec.slice(alias.prefix.length)));
3711
+ resolved = resolveFile(alias.exact ? t : path21.join(t, spec.slice(alias.prefix.length)));
3513
3712
  if (resolved) break;
3514
3713
  }
3515
3714
  }
3516
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path20.join(baseUrl, spec));
3715
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path21.join(baseUrl, spec));
3517
3716
  if (!resolved) {
3518
3717
  const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
3519
3718
  if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
@@ -3525,217 +3724,64 @@ function createTrail(ctx) {
3525
3724
  importsCache.set(file.absolutePath, out);
3526
3725
  return out;
3527
3726
  };
3528
- const strippedCache = /* @__PURE__ */ new Map();
3529
- const stripped = (file) => {
3530
- if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
3531
- return strippedCache.get(file.absolutePath);
3532
- };
3533
- const memo = /* @__PURE__ */ new WeakMap();
3534
- const reach = (file, test2, depth, seen) => {
3535
- let cache2 = memo.get(test2);
3536
- if (!cache2) memo.set(test2, cache2 = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
3537
- const k = `${file.absolutePath}\0${depth}`;
3538
- const free = cache2.free.get(k);
3539
- if (free) return [free, /* @__PURE__ */ new Set()];
3540
- const reusable = cache2.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
3541
- if (reusable) return [reusable.result, new Set(reusable.cut)];
3542
- let result;
3543
- const cut = /* @__PURE__ */ new Set();
3544
- const code = stripped(file);
3545
- if (code === null) result = "unknown";
3546
- else if (test2(code)) result = "yes";
3547
- else {
3548
- const { files, lost } = importsOf(file);
3549
- let unknown = lost && depth > 0;
3550
- result = "no";
3551
- if (depth > 0) {
3552
- seen.add(file.absolutePath);
3553
- for (const abs of files) {
3554
- if (seen.has(abs)) {
3555
- cut.add(abs);
3556
- continue;
3557
- }
3558
- const target = read2(abs);
3559
- if (!target) {
3560
- unknown = true;
3561
- continue;
3562
- }
3563
- const [r, c] = reach(target, test2, depth - 1, seen);
3564
- for (const m of c) cut.add(m);
3565
- if (r === "yes") {
3566
- result = "yes";
3567
- break;
3568
- }
3569
- if (r === "unknown") unknown = true;
3570
- }
3571
- seen.delete(file.absolutePath);
3572
- cut.delete(file.absolutePath);
3573
- }
3574
- if (result === "no" && unknown) result = "unknown";
3575
- }
3576
- if (result === "yes" || cut.size === 0) {
3577
- cache2.free.set(k, result);
3578
- return [result, /* @__PURE__ */ new Set()];
3579
- }
3580
- const entries = cache2.cut.get(k) ?? [];
3581
- entries.push({ cut: [...cut], result });
3582
- cache2.cut.set(k, entries);
3583
- return [result, cut];
3584
- };
3585
- return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
3586
- }
3587
- function buildCatalog(packagesDir) {
3588
- const packages = {};
3589
- for (const dir of readdirSync(packagesDir).sort()) {
3590
- const file = path20.join(packagesDir, dir, "package.json");
3591
- if (!existsSync(file)) continue;
3592
- const pkg = JSON.parse(readFileSync(file, "utf8"));
3593
- if (!pkg.name || !pkg.version || pkg.private || !pkg.name.startsWith("@marktiderman/genesis")) continue;
3594
- packages[pkg.name] = { version: pkg.version, ...pkg.genesis?.blocks ? { blocks: pkg.genesis.blocks } : {} };
3595
- }
3596
- return { packages };
3597
- }
3598
-
3599
- // src/blocks/discover.ts
3600
- var CLI_PACKAGE = "@marktiderman/genesis-cli";
3601
- function cliPackageDir() {
3602
- let dir = path20.dirname(fileURLToPath(import.meta.url));
3603
- for (; ; ) {
3604
- const file = path20.join(dir, "package.json");
3605
- if (existsSync(file) && JSON.parse(readFileSync(file, "utf8")).name === CLI_PACKAGE) return dir;
3606
- const parent = path20.dirname(dir);
3607
- if (parent === dir) throw new Error("Can't find the genesis-cli package folder.");
3608
- dir = parent;
3609
- }
3610
- }
3611
- function workspacePackagesDir() {
3612
- const dir = path20.resolve(cliPackageDir(), "..");
3613
- return existsSync(path20.join(dir, "features", "package.json")) && existsSync(path20.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
3614
- }
3615
- var catalogCache;
3616
- function readCatalog() {
3617
- if (catalogCache) return catalogCache;
3618
- const workspace = workspacePackagesDir();
3619
- if (workspace) return catalogCache = buildCatalog(workspace);
3620
- const file = path20.join(cliPackageDir(), "dist", "genesis-catalog.json");
3621
- catalogCache = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : { packages: {} };
3622
- return catalogCache;
3623
- }
3624
- var INSTALL_ROOT_MARKERS = [".git", "pnpm-lock.yaml", "pnpm-workspace.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"];
3625
- function installedGenesis(root) {
3626
- const found = /* @__PURE__ */ new Map();
3627
- let dir = path20.resolve(root);
3628
- for (; ; ) {
3629
- const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path20.join(dir, m)));
3630
- const scope = path20.join(dir, "node_modules", "@marktiderman");
3631
- if (existsSync(scope)) {
3632
- for (const entry of readdirSync(scope)) {
3633
- const name = `@marktiderman/${entry}`;
3634
- if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
3635
- if (existsSync(path20.join(scope, entry, "package.json"))) found.set(name, path20.join(scope, entry));
3636
- }
3637
- }
3638
- const parent = path20.dirname(dir);
3639
- if (atInstallRoot || parent === dir) return found;
3640
- dir = parent;
3641
- }
3642
- }
3643
- var declarationCache = /* @__PURE__ */ new Map();
3644
- function declarationsOf(dir, warnings) {
3645
- const pkg = JSON.parse(readFileSync(path20.join(dir, "package.json"), "utf8"));
3646
- const key2 = `${realpathSync(dir)}@${pkg.version ?? ""}`;
3647
- let cached = declarationCache.get(key2);
3648
- if (!cached) {
3649
- cached = loadDeclarations(dir, warnings);
3650
- declarationCache.set(key2, cached);
3651
- }
3652
- return cached;
3653
- }
3654
- async function loadDeclarations(dir, warnings) {
3655
- const pkg = JSON.parse(readFileSync(path20.join(dir, "package.json"), "utf8"));
3656
- const entry = pkg.exports?.["./blocks"];
3657
- const target = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry["import"] ?? entry["default"] : void 0;
3658
- if (typeof target !== "string") return {};
3659
- const rel = safeRelative(target.replace(/^\.\//, ""));
3660
- const file = rel && path20.join(dir, ...rel.split("/"));
3661
- if (!file || !inside(dir, file) || !existsSync(file)) return {};
3662
- try {
3663
- const jiti = createJiti(path20.join(dir, "package.json"), { moduleCache: false });
3664
- const mod = await jiti.import(file);
3665
- const out = {};
3666
- for (const value of Object.values(mod)) if (isBlockDef(value)) out[value.id] = declarationFields(value);
3667
- return out;
3668
- } catch (err) {
3669
- warnings.push(`${pkg.name}/blocks didn't load in Node (${err instanceof Error ? err.message.split("\n")[0] : String(err)}); using its package.json manifest only.`);
3670
- return {};
3671
- }
3672
- }
3673
- async function blocksOfInstalled(dir, warnings = [], options = {}) {
3674
- const pkg = JSON.parse(readFileSync(path20.join(dir, "package.json"), "utf8"));
3675
- const raw = rawBlocksOf(pkg);
3676
- const declared = await declarationsOf(dir, warnings);
3677
- const ids = /* @__PURE__ */ new Set([...Object.keys(raw), ...Object.keys(declared)]);
3678
- const out = [];
3679
- for (const id of [...ids].sort()) {
3680
- const fromJson = raw[id] ?? {};
3681
- const merged = { ...fromJson, ...declared[id] };
3682
- if (declared[id]?.["migrations"] && Array.isArray(fromJson["migrations"])) merged["migrations"] = withProvides(declared[id]["migrations"], fromJson["migrations"]);
3683
- const manifest = tryParse(() => parseManifest(pkg.name, id, merged, pkg.version, options), warnings);
3684
- if (manifest) out.push(manifest);
3685
- }
3686
- return out;
3687
- }
3688
- function withProvides(declared, json) {
3689
- if (!Array.isArray(declared)) return declared;
3690
- const fileOf = (m) => m && typeof m === "object" ? m["file"] : void 0;
3691
- return declared.map((m) => {
3692
- const same = json.find((j) => fileOf(j) === fileOf(m));
3693
- return same?.["provides"] !== void 0 && m && typeof m === "object" && !("provides" in m) ? { ...m, provides: same["provides"] } : m;
3694
- });
3695
- }
3696
- async function allBlocks(root, warnings = []) {
3697
- const out = [];
3698
- for (const local of localPackages(root)) {
3699
- for (const manifest of await blocksOfInstalled(local.dir, warnings, { local: true })) out.push({ manifest, from: "local" });
3700
- }
3701
- const installed = installedGenesis(root);
3702
- for (const [, dir] of installed) for (const manifest of await blocksOfInstalled(dir, warnings)) out.push({ manifest, from: "installed" });
3703
- for (const [name, entry] of Object.entries(readCatalog().packages)) {
3704
- if (installed.has(name)) continue;
3705
- for (const [id, raw] of Object.entries(entry.blocks ?? {})) {
3706
- const manifest = tryParse(() => parseManifest(name, id, raw, entry.version), warnings);
3707
- if (manifest) out.push({ manifest, from: "catalog" });
3727
+ const strippedCache = /* @__PURE__ */ new Map();
3728
+ const stripped = (file) => {
3729
+ if (!strippedCache.has(file.absolutePath)) strippedCache.set(file.absolutePath, stripForImports(file.code));
3730
+ return strippedCache.get(file.absolutePath);
3731
+ };
3732
+ const memo = /* @__PURE__ */ new WeakMap();
3733
+ const reach = (file, test2, depth, seen) => {
3734
+ let cache2 = memo.get(test2);
3735
+ if (!cache2) memo.set(test2, cache2 = { free: /* @__PURE__ */ new Map(), cut: /* @__PURE__ */ new Map() });
3736
+ const k = `${file.absolutePath}\0${depth}`;
3737
+ const free = cache2.free.get(k);
3738
+ if (free) return [free, /* @__PURE__ */ new Set()];
3739
+ const reusable = cache2.cut.get(k)?.find((e) => e.cut.every((m) => seen.has(m)));
3740
+ if (reusable) return [reusable.result, new Set(reusable.cut)];
3741
+ let result;
3742
+ const cut = /* @__PURE__ */ new Set();
3743
+ const code = stripped(file);
3744
+ if (code === null) result = "unknown";
3745
+ else if (test2(code)) result = "yes";
3746
+ else {
3747
+ const { files, lost } = importsOf(file);
3748
+ let unknown = lost && depth > 0;
3749
+ result = "no";
3750
+ if (depth > 0) {
3751
+ seen.add(file.absolutePath);
3752
+ for (const abs of files) {
3753
+ if (seen.has(abs)) {
3754
+ cut.add(abs);
3755
+ continue;
3756
+ }
3757
+ const target = read2(abs);
3758
+ if (!target) {
3759
+ unknown = true;
3760
+ continue;
3761
+ }
3762
+ const [r, c] = reach(target, test2, depth - 1, seen);
3763
+ for (const m of c) cut.add(m);
3764
+ if (r === "yes") {
3765
+ result = "yes";
3766
+ break;
3767
+ }
3768
+ if (r === "unknown") unknown = true;
3769
+ }
3770
+ seen.delete(file.absolutePath);
3771
+ cut.delete(file.absolutePath);
3772
+ }
3773
+ if (result === "no" && unknown) result = "unknown";
3708
3774
  }
3709
- }
3710
- return out;
3711
- }
3712
- function tryParse(parse2, warnings) {
3713
- try {
3714
- return parse2();
3715
- } catch (err) {
3716
- if (!(err instanceof ManifestError)) throw err;
3717
- warnings.push(err.message);
3718
- return null;
3719
- }
3720
- }
3721
- function catalogBlocks(warnings = []) {
3722
- const out = [];
3723
- for (const [name, entry] of Object.entries(readCatalog().packages)) {
3724
- for (const [id, raw] of Object.entries(entry.blocks ?? {})) {
3725
- const manifest = tryParse(() => parseManifest(name, id, raw, entry.version), warnings);
3726
- if (manifest) out.push(manifest);
3775
+ if (result === "yes" || cut.size === 0) {
3776
+ cache2.free.set(k, result);
3777
+ return [result, /* @__PURE__ */ new Set()];
3727
3778
  }
3728
- }
3729
- return out;
3730
- }
3731
- async function findBlock(root, id, options = {}) {
3732
- const all = (await allBlocks(root, options.warnings)).filter((b) => b.manifest.id === id && (!options.package || b.manifest.package === options.package));
3733
- if (all.length === 0) {
3734
- const known = [...new Set((await allBlocks(root)).map((b) => b.manifest.id))].sort();
3735
- throw new Error(`No Genesis or local package declares a block "${id}"${options.package ? ` in ${options.package}` : ""}. Known blocks: ${known.join(", ") || "none"}.`);
3736
- }
3737
- if (all.length > 1) throw new Error(`"${id}" is declared by ${all.map((b) => b.manifest.package).join(" and ")}; pass --package to pick one.`);
3738
- return all[0];
3779
+ const entries = cache2.cut.get(k) ?? [];
3780
+ entries.push({ cut: [...cut], result });
3781
+ cache2.cut.set(k, entries);
3782
+ return [result, cut];
3783
+ };
3784
+ return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
3739
3785
  }
3740
3786
  var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3741
3787
  var STEMS = {
@@ -3754,7 +3800,7 @@ var RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
3754
3800
  var OWN_CONTENT = /(?<![=-])>\s*[A-Za-z][^<>{}]*</.source + "|" + /(?<![\w$.])<(?:h[1-6]|ul|ol|table|dl|H[1-6]|[A-Z]\w*(?:Heading|Title|Table|List|Grid))(?=[\s>/])/.source;
3755
3801
  function routesDir(ctx) {
3756
3802
  if (ctx.config.routesDir) return ctx.config.routesDir;
3757
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path20.join(ctx.root, d))) ?? null;
3803
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path21.join(ctx.root, d))) ?? null;
3758
3804
  }
3759
3805
  var key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
3760
3806
  function flavorOf(dir, rels) {
@@ -3889,7 +3935,7 @@ function validateDeclaration(raw, packageName3, packageDir, ignored) {
3889
3935
  });
3890
3936
  if (typeof raw === "string") {
3891
3937
  if (!packageDir) fail(`points at ${raw}, but the package folder is unknown`);
3892
- const file = path20.resolve(packageDir, raw);
3938
+ const file = path21.resolve(packageDir, raw);
3893
3939
  if (!inside(packageDir, file)) fail(`points outside the package (${raw})`);
3894
3940
  if (!existsSync(file)) fail(`points at ${raw}, which doesn't exist (is it in package.json "files"?)`);
3895
3941
  let parsed;
@@ -3938,7 +3984,7 @@ function validateDeclaration(raw, packageName3, packageDir, ignored) {
3938
3984
  if (typeof c.plugin === "string") {
3939
3985
  if (!packageDir) plugin = c.plugin;
3940
3986
  else {
3941
- plugin = path20.resolve(packageDir, c.plugin);
3987
+ plugin = path21.resolve(packageDir, c.plugin);
3942
3988
  if (!inside(packageDir, plugin)) fail(`plugin points outside the package (${c.plugin})`);
3943
3989
  }
3944
3990
  }
@@ -3988,7 +4034,7 @@ function checkPattern(v, where2, fail) {
3988
4034
  }
3989
4035
  var discoveryCache = /* @__PURE__ */ new Map();
3990
4036
  function readDeclaringPackage(dir, local) {
3991
- const file = path20.join(dir, "package.json");
4037
+ const file = path21.join(dir, "package.json");
3992
4038
  let stamp;
3993
4039
  let real2;
3994
4040
  try {
@@ -4011,7 +4057,7 @@ ${local}`;
4011
4057
  const pkg = {
4012
4058
  name: json.name,
4013
4059
  version: typeof json.version === "string" ? json.version : "0.0.0",
4014
- dir: path20.resolve(dir),
4060
+ dir: path21.resolve(dir),
4015
4061
  namespace: ruleNamespace(json.name),
4016
4062
  local,
4017
4063
  private: json.private === true,
@@ -4025,7 +4071,7 @@ ${local}`;
4025
4071
  if (raw !== void 0) {
4026
4072
  const ignored = [];
4027
4073
  try {
4028
- pkg.declaration = validateDeclaration(raw, json.name, path20.resolve(dir), ignored);
4074
+ pkg.declaration = validateDeclaration(raw, json.name, path21.resolve(dir), ignored);
4029
4075
  if (ignored.length) pkg.ignored = ignored;
4030
4076
  } catch (err) {
4031
4077
  pkg.error = err.message;
@@ -4044,14 +4090,14 @@ function discoverPackages(root) {
4044
4090
  for (const dir of installed) {
4045
4091
  let scope;
4046
4092
  try {
4047
- scope = path20.dirname(realpathSync(dir));
4093
+ scope = path21.dirname(realpathSync(dir));
4048
4094
  } catch {
4049
4095
  continue;
4050
4096
  }
4051
- if (path20.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
4097
+ if (path21.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
4052
4098
  for (const entry of readdirSync(scope)) {
4053
4099
  if (byName.has(`@marktiderman/${entry}`) || !GENESIS.test(`@marktiderman/${entry}`)) continue;
4054
- const pkg = readDeclaringPackage(path20.join(scope, entry), false);
4100
+ const pkg = readDeclaringPackage(path21.join(scope, entry), false);
4055
4101
  if (pkg) byName.set(pkg.name, pkg);
4056
4102
  }
4057
4103
  }
@@ -4235,10 +4281,10 @@ var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([
4235
4281
  var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
4236
4282
  function sourceFiles(dir, rel = "") {
4237
4283
  const out = [];
4238
- for (const entry of readdirSync(path20.join(dir, rel)).sort()) {
4284
+ for (const entry of readdirSync(path21.join(dir, rel)).sort()) {
4239
4285
  if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
4240
4286
  const child = rel ? `${rel}/${entry}` : entry;
4241
- const stat = lstatSync(path20.join(dir, child));
4287
+ const stat = lstatSync(path21.join(dir, child));
4242
4288
  if (stat.isSymbolicLink()) continue;
4243
4289
  if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
4244
4290
  else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
@@ -4261,13 +4307,13 @@ function matchPattern(pattern, spec) {
4261
4307
  return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
4262
4308
  }
4263
4309
  function tsconfigPaths(dir) {
4264
- const file = path20.join(dir, "tsconfig.json");
4310
+ const file = path21.join(dir, "tsconfig.json");
4265
4311
  if (!existsSync(file)) return [];
4266
4312
  try {
4267
4313
  const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
4268
4314
  const options = JSON.parse(text).compilerOptions ?? {};
4269
- const base = path20.resolve(dir, options.baseUrl ?? ".");
4270
- return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path20.resolve(base, t)) }));
4315
+ const base = path21.resolve(dir, options.baseUrl ?? ".");
4316
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path21.resolve(base, t)) }));
4271
4317
  } catch {
4272
4318
  return [];
4273
4319
  }
@@ -4281,8 +4327,8 @@ function checkImports2(ctx, pkg, json) {
4281
4327
  const hit = matchPattern(pattern, spec);
4282
4328
  if (hit === null) continue;
4283
4329
  return targets.some((t) => {
4284
- const rel = path20.relative(pkg.dir, t.replace("*", hit));
4285
- return !rel.startsWith("..") && !path20.isAbsolute(rel);
4330
+ const rel = path21.relative(pkg.dir, t.replace("*", hit));
4331
+ return !rel.startsWith("..") && !path21.isAbsolute(rel);
4286
4332
  });
4287
4333
  }
4288
4334
  return null;
@@ -4295,7 +4341,7 @@ function checkImports2(ctx, pkg, json) {
4295
4341
  ...Object.keys(json.optionalDependencies ?? {})
4296
4342
  ]);
4297
4343
  for (const file of sourceFiles(pkg.dir)) {
4298
- const code = stripForImports(readFileSync(path20.join(pkg.dir, file), "utf8"));
4344
+ const code = stripForImports(readFileSync(path21.join(pkg.dir, file), "utf8"));
4299
4345
  if (code === null) continue;
4300
4346
  const at = `${pkg.rel}/${file}`;
4301
4347
  const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
@@ -4320,9 +4366,9 @@ function checkImports2(ctx, pkg, json) {
4320
4366
  continue;
4321
4367
  }
4322
4368
  if (spec.startsWith(".")) {
4323
- const target = path20.resolve(pkg.dir, path20.dirname(file), spec);
4324
- const rel = path20.relative(pkg.dir, target);
4325
- if (rel.startsWith("..") || path20.isAbsolute(rel)) {
4369
+ const target = path21.resolve(pkg.dir, path21.dirname(file), spec);
4370
+ const rel = path21.relative(pkg.dir, target);
4371
+ if (rel.startsWith("..") || path21.isAbsolute(rel)) {
4326
4372
  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` });
4327
4373
  }
4328
4374
  continue;
@@ -4359,12 +4405,12 @@ function checkMigrations(ctx, pkg, json, locals) {
4359
4405
  const from = own ? "" : ` (in ${m.package})`;
4360
4406
  if (typeof m.file === "string" && typeof m.test !== "string") {
4361
4407
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.file, message: `${pkg.name} block ${id}: ${m.file}${from} has no pgTAP test; declare one as "test" beside it` });
4362
- } else if (typeof m.test === "string" && !existsSync(path20.join(home, m.test))) {
4408
+ } else if (typeof m.test === "string" && !existsSync(path21.join(home, m.test))) {
4363
4409
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.test, message: `${pkg.name} block ${id}: its test ${m.test}${from} doesn't exist` });
4364
4410
  }
4365
4411
  }
4366
4412
  }
4367
- const dir = path20.join(pkg.dir, "migrations");
4413
+ const dir = path21.join(pkg.dir, "migrations");
4368
4414
  if (!existsSync(dir)) return;
4369
4415
  const seen = /* @__PURE__ */ new Map();
4370
4416
  for (const name of readdirSync(dir).sort()) {
@@ -4373,21 +4419,21 @@ function checkMigrations(ctx, pkg, json, locals) {
4373
4419
  const other = seen.get(m[1]);
4374
4420
  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` });
4375
4421
  else seen.set(m[1], name);
4376
- if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path20.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
4422
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path21.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
4377
4423
  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")})` });
4378
4424
  }
4379
4425
  }
4380
4426
  }
4381
4427
  function checkExports(ctx, pkg, json) {
4382
4428
  const targets = [];
4383
- const walk2 = (v) => {
4429
+ const walk3 = (v) => {
4384
4430
  if (typeof v === "string") targets.push(v);
4385
- else if (v && typeof v === "object") for (const x of Object.values(v)) walk2(x);
4431
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk3(x);
4386
4432
  };
4387
- walk2(json.exports);
4433
+ walk3(json.exports);
4388
4434
  for (const t of targets) {
4389
4435
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
4390
- if (!existsSync(path20.join(pkg.dir, t))) {
4436
+ if (!existsSync(path21.join(pkg.dir, t))) {
4391
4437
  ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
4392
4438
  }
4393
4439
  }
@@ -4405,11 +4451,11 @@ function checkBlocks(ctx, pkg, json) {
4405
4451
  function checkTaggedTests(ctx, pkg) {
4406
4452
  const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
4407
4453
  if (!tests.length) return;
4408
- const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path20.join(pkg.dir, f), "utf8")));
4454
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path21.join(pkg.dir, f), "utf8")));
4409
4455
  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>` });
4410
4456
  }
4411
4457
  function checkRegistered(ctx, pkg) {
4412
- const file = path20.join(ctx.root, "features.json");
4458
+ const file = path21.join(ctx.root, "features.json");
4413
4459
  if (!existsSync(file)) return;
4414
4460
  let doc;
4415
4461
  try {
@@ -4419,7 +4465,7 @@ function checkRegistered(ctx, pkg) {
4419
4465
  }
4420
4466
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
4421
4467
  const forms = /* @__PURE__ */ new Set([pkg.rel]);
4422
- if (top) forms.add(path20.relative(top, realpathSync(pkg.dir)).split(path20.sep).join("/"));
4468
+ if (top) forms.add(path21.relative(top, realpathSync(pkg.dir)).split(path21.sep).join("/"));
4423
4469
  const covered = (doc.features ?? []).some(
4424
4470
  (f) => (f.links?.code ?? []).some((c) => {
4425
4471
  const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -4449,8 +4495,8 @@ function mergeBaseOf(root, base) {
4449
4495
  function checkChanges(ctx, pkg, json, base, mergeBase) {
4450
4496
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
4451
4497
  if (!top) return;
4452
- const appRelative = (fromTop) => path20.relative(realpathSync(ctx.root), path20.join(top, fromTop)).split(path20.sep).join("/");
4453
- const inRepo = path20.relative(top, realpathSync(pkg.dir)).split(path20.sep).join("/");
4498
+ const appRelative = (fromTop) => path21.relative(realpathSync(ctx.root), path21.join(top, fromTop)).split(path21.sep).join("/");
4499
+ const inRepo = path21.relative(top, realpathSync(pkg.dir)).split(path21.sep).join("/");
4454
4500
  const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell2, i) => i === 0 ? cell2 : appRelative(cell2)).join(" ")).join("\n");
4455
4501
  const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
4456
4502
  const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
@@ -4473,11 +4519,11 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
4473
4519
  const now = typeof json.version === "string" ? parseVersion(json.version) : null;
4474
4520
  const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
4475
4521
  const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
4476
- 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) => path20.join(top, f)) : [];
4522
+ 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) => path21.join(top, f)) : [];
4477
4523
  const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
4478
4524
  const named = naming.length > 0;
4479
4525
  if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
4480
- ctx.report({ rule: "package-unversioned-change", level: "warn", file: path20.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
4526
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path21.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
4481
4527
  }
4482
4528
  let jsonBefore = null;
4483
4529
  try {
@@ -4487,7 +4533,7 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
4487
4533
  }
4488
4534
  const raw = json;
4489
4535
  if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
4490
- const appInRepo = path20.relative(top, realpathSync(ctx.root)).split(path20.sep).join("/");
4536
+ const appInRepo = path21.relative(top, realpathSync(ctx.root)).split(path21.sep).join("/");
4491
4537
  const candidates = [.../* @__PURE__ */ new Set(["features.ts", "src/features.ts", ...appInRepo ? [`${appInRepo}/features.ts`, `${appInRepo}/src/features.ts`] : []])];
4492
4538
  const registry = (git(top, ["diff", "--name-only", mergeBase, "--", ...candidates]) ?? "").trim();
4493
4539
  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` });
@@ -4539,7 +4585,7 @@ function checkPackagesPack(ctx) {
4539
4585
  ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
4540
4586
  }
4541
4587
  for (const pkg of packages) {
4542
- const json = JSON.parse(readFileSync(path20.join(pkg.dir, "package.json"), "utf8"));
4588
+ const json = JSON.parse(readFileSync(path21.join(pkg.dir, "package.json"), "utf8"));
4543
4589
  checkImports2(ctx, pkg, json);
4544
4590
  checkExports(ctx, pkg, json);
4545
4591
  checkBlocks(ctx, pkg, json);
@@ -4556,7 +4602,7 @@ function emptyLock() {
4556
4602
  return { version: 1, blocks: {}, files: {} };
4557
4603
  }
4558
4604
  function readLock(root) {
4559
- const file = path20.join(root, LOCK_FILE);
4605
+ const file = path21.join(root, LOCK_FILE);
4560
4606
  if (!existsSync(file)) return emptyLock();
4561
4607
  const raw = JSON.parse(readFileSync(file, "utf8"));
4562
4608
  if (raw.version !== 1) throw new Error(`${LOCK_FILE} has version ${String(raw.version)}; this CLI reads version 1.`);
@@ -4579,11 +4625,11 @@ function databaseElsewhere(root) {
4579
4625
  const setting = readGenesisConfig(root)?.supabase;
4580
4626
  if (setting === void 0) return null;
4581
4627
  if (setting === false) return { app: null, dir: null, hasSupabase: false };
4582
- const resolved = path20.resolve(root, setting.app);
4628
+ const resolved = path21.resolve(root, setting.app);
4583
4629
  const real2 = (p) => existsSync(p) ? realpathSync(p) : p;
4584
4630
  const dir = real2(resolved);
4585
- if (dir === real2(path20.resolve(root))) throw new GenesisConfigError(`${path20.join(root, "genesis.config.json")}: supabase.app "${setting.app}" is this app itself; leave "supabase" out instead`);
4586
- return { app: setting.app, dir, hasSupabase: existsSync(path20.join(dir, "supabase")) };
4631
+ if (dir === real2(path21.resolve(root))) throw new GenesisConfigError(`${path21.join(root, "genesis.config.json")}: supabase.app "${setting.app}" is this app itself; leave "supabase" out instead`);
4632
+ return { app: setting.app, dir, hasSupabase: existsSync(path21.join(dir, "supabase")) };
4587
4633
  }
4588
4634
  function isSupabasePath(rel) {
4589
4635
  return rel === "supabase" || rel.startsWith("supabase/");
@@ -4773,9 +4819,9 @@ function checkSupabasePack(ctx) {
4773
4819
  if (databaseElsewhere(ctx.root)) return;
4774
4820
  const settings = ctx.config.supabase ?? {};
4775
4821
  const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
4776
- const abs = path20.join(ctx.root, dir);
4822
+ const abs = path21.join(ctx.root, dir);
4777
4823
  if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
4778
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path20.join(abs, n), "utf8")) }));
4824
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path21.join(abs, n), "utf8")) }));
4779
4825
  const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
4780
4826
  const base = settings.base ?? DEFAULT_BASE;
4781
4827
  const view = gitView(ctx.root, dir, base);
@@ -4792,7 +4838,7 @@ function checkSupabasePack(ctx) {
4792
4838
  }
4793
4839
  }
4794
4840
  const since = settings.since;
4795
- const afterSince = (file) => since === void 0 || path20.posix.basename(file) >= since;
4841
+ const afterSince = (file) => since === void 0 || path21.posix.basename(file) >= since;
4796
4842
  if ("reason" in view && since === void 0) {
4797
4843
  ctx.report({
4798
4844
  rule: "migration-grants",
@@ -5075,7 +5121,7 @@ var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
5075
5121
  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)$/;
5076
5122
  var readManifest = (dir) => {
5077
5123
  try {
5078
- return JSON.parse(readFileSync(path20.join(dir, "package.json"), "utf8"));
5124
+ return JSON.parse(readFileSync(path21.join(dir, "package.json"), "utf8"));
5079
5125
  } catch {
5080
5126
  return null;
5081
5127
  }
@@ -5089,18 +5135,18 @@ var real = (p) => {
5089
5135
  };
5090
5136
  var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
5091
5137
  function nodeModulesOf(dir) {
5092
- const parent = path20.dirname(dir);
5093
- return path20.basename(parent).startsWith("@") ? path20.dirname(parent) : parent;
5138
+ const parent = path21.dirname(dir);
5139
+ return path21.basename(parent).startsWith("@") ? path21.dirname(parent) : parent;
5094
5140
  }
5095
5141
  function packagesIn(nodeModules) {
5096
5142
  if (!existsSync(nodeModules)) return [];
5097
5143
  const out = [];
5098
5144
  for (const entry of readdirSync(nodeModules)) {
5099
5145
  if (entry.startsWith(".")) continue;
5100
- const p = path20.join(nodeModules, entry);
5146
+ const p = path21.join(nodeModules, entry);
5101
5147
  if (entry.startsWith("@")) {
5102
5148
  try {
5103
- for (const sub of readdirSync(p)) out.push(path20.join(p, sub));
5149
+ for (const sub of readdirSync(p)) out.push(path21.join(p, sub));
5104
5150
  } catch {
5105
5151
  }
5106
5152
  } else {
@@ -5112,7 +5158,7 @@ function packagesIn(nodeModules) {
5112
5158
  function genesisInstalls(root) {
5113
5159
  const copies = /* @__PURE__ */ new Map();
5114
5160
  const realRoot = real(root);
5115
- const rel = (abs) => path20.relative(realRoot, abs).split(path20.sep).join("/") || ".";
5161
+ const rel = (abs) => path21.relative(realRoot, abs).split(path21.sep).join("/") || ".";
5116
5162
  const via = /* @__PURE__ */ new Map();
5117
5163
  const record = (real2, manifest, by, range, root2) => {
5118
5164
  let copy = copies.get(real2);
@@ -5124,7 +5170,7 @@ function genesisInstalls(root) {
5124
5170
  via.get(real2).add(root2);
5125
5171
  if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
5126
5172
  };
5127
- const walk2 = (kind, roots) => {
5173
+ const walk3 = (kind, roots) => {
5128
5174
  const expanded = /* @__PURE__ */ new Set();
5129
5175
  const queue = [];
5130
5176
  const visit = (dir, by, range) => {
@@ -5157,7 +5203,7 @@ function genesisInstalls(root) {
5157
5203
  if (!dir) return null;
5158
5204
  if (!ownInstall || name in declared) return dir;
5159
5205
  const realDir = real(dir);
5160
- if (realDir.startsWith(realRoot + path20.sep)) return dir;
5206
+ if (realDir.startsWith(realRoot + path21.sep)) return dir;
5161
5207
  return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
5162
5208
  };
5163
5209
  const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
@@ -5165,7 +5211,7 @@ function genesisInstalls(root) {
5165
5211
  return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
5166
5212
  });
5167
5213
  const app = readManifest(root);
5168
- const ownInstall = LOCKFILES.some((f) => existsSync(path20.join(root, f)));
5214
+ const ownInstall = LOCKFILES.some((f) => existsSync(path21.join(root, f)));
5169
5215
  const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
5170
5216
  const declaredDev = Object.entries(app?.devDependencies ?? {});
5171
5217
  const runtimeDeps = {
@@ -5175,18 +5221,18 @@ function genesisInstalls(root) {
5175
5221
  ...app?.dependencies
5176
5222
  };
5177
5223
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
5178
- walk2("runtime", rootsOf(runtimeDeps, "the app"));
5179
- const top = path20.join(root, "node_modules");
5180
- walk2(
5224
+ walk3("runtime", rootsOf(runtimeDeps, "the app"));
5225
+ const top = path21.join(root, "node_modules");
5226
+ walk3(
5181
5227
  "hoisted",
5182
5228
  packagesIn(top).filter((dir) => {
5183
- const name = path20.relative(top, dir).split(path20.sep).join("/");
5229
+ const name = path21.relative(top, dir).split(path21.sep).join("/");
5184
5230
  return !(name in runtimeDeps) && !(name in devDeps);
5185
5231
  }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
5186
5232
  );
5187
5233
  const devRoots = { ...devDeps };
5188
5234
  for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
5189
- walk2("dev", rootsOf(devRoots, "the app (dev)"));
5235
+ walk3("dev", rootsOf(devRoots, "the app (dev)"));
5190
5236
  for (const [key2, copy] of copies) {
5191
5237
  const kinds = via.get(key2);
5192
5238
  copy.runtime = kinds.has("runtime");
@@ -5222,7 +5268,7 @@ function checkDuplicatePackages(ctx) {
5222
5268
  }
5223
5269
  }
5224
5270
  function checkPeerRanges(ctx) {
5225
- const rel = (abs) => path20.relative(ctx.root, abs).split(path20.sep).join("/");
5271
+ const rel = (abs) => path21.relative(ctx.root, abs).split(path21.sep).join("/");
5226
5272
  for (const copies of genesisInstalls(ctx.root).values()) {
5227
5273
  for (const copy of copies) {
5228
5274
  const dir = copy.absolutePath;
@@ -5409,6 +5455,24 @@ function checkIsoDateSlices(ctx) {
5409
5455
  }
5410
5456
  }
5411
5457
  }
5458
+ var SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
5459
+ var SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
5460
+ var MAX_BYTES = 2 * 1024 * 1024;
5461
+ function appScripts(root) {
5462
+ const out = [];
5463
+ const walk3 = (dir) => {
5464
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
5465
+ const abs = path21.join(dir, entry.name);
5466
+ if (entry.isDirectory()) {
5467
+ if (!SKIP_DIRS3.has(entry.name)) walk3(abs);
5468
+ } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
5469
+ out.push(path21.relative(root, abs).split(path21.sep).join("/"));
5470
+ }
5471
+ }
5472
+ };
5473
+ walk3(root);
5474
+ return out;
5475
+ }
5412
5476
 
5413
5477
  // src/upgrade/scope-names.ts
5414
5478
  var IMPORTS_GENESIS = /\bfrom\s*["']@marktiderman\/genesis[\w/-]*["']/;
@@ -5603,11 +5667,11 @@ var ESLINT_EXPORT = "@marktiderman/genesis-cli/eslint";
5603
5667
  var TESTING_LIBRARY = "eslint-plugin-testing-library";
5604
5668
  var FLAT_CONFIG_FILES = ["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs", "eslint.config.ts", "eslint.config.mts", "eslint.config.cts"];
5605
5669
  function findEslintConfig(root) {
5606
- return FLAT_CONFIG_FILES.find((name) => existsSync(path20.join(root, name))) ?? null;
5670
+ return FLAT_CONFIG_FILES.find((name) => existsSync(path21.join(root, name))) ?? null;
5607
5671
  }
5608
5672
  function readPackageJson(root) {
5609
5673
  try {
5610
- return JSON.parse(readFileSync(path20.join(root, "package.json"), "utf8"));
5674
+ return JSON.parse(readFileSync(path21.join(root, "package.json"), "utf8"));
5611
5675
  } catch {
5612
5676
  return null;
5613
5677
  }
@@ -5623,26 +5687,6 @@ function usesGenesisLint(text) {
5623
5687
  return text.includes(ESLINT_EXPORT);
5624
5688
  }
5625
5689
 
5626
- // src/upgrade/codemods.ts
5627
- var SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
5628
- var SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
5629
- var MAX_BYTES = 2 * 1024 * 1024;
5630
- function appScripts(root) {
5631
- const out = [];
5632
- const walk2 = (dir) => {
5633
- for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
5634
- const abs = path20.join(dir, entry.name);
5635
- if (entry.isDirectory()) {
5636
- if (!SKIP_DIRS3.has(entry.name)) walk2(abs);
5637
- } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
5638
- out.push(path20.relative(root, abs).split(path20.sep).join("/"));
5639
- }
5640
- }
5641
- };
5642
- walk2(root);
5643
- return out;
5644
- }
5645
-
5646
5690
  // src/doctor/api-usage.ts
5647
5691
  var SCRIPT_EXTS5 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
5648
5692
  function openingTag(code, start) {
@@ -5723,7 +5767,7 @@ var ROOT_REQUIRE = /\brequire\s*\(\s*["']@marktiderman\/genesis-studio-server["'
5723
5767
  function moduleFiles(ctx) {
5724
5768
  const scanned = new Set(ctx.files.map((f) => f.path));
5725
5769
  const ignored = globMatcher([...DEFAULT_IGNORE, ...ctx.config.ignore ?? []]);
5726
- const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path20.join(ctx.root, rel), "utf8"), true) }));
5770
+ const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path21.join(ctx.root, rel), "utf8"), true) }));
5727
5771
  return [...ctx.files.filter((f) => SCRIPT_EXTS5.has(f.ext)), ...extra];
5728
5772
  }
5729
5773
  function checkStudioServerImports(ctx) {
@@ -5759,7 +5803,7 @@ var REMOVED_WORDS = {
5759
5803
  };
5760
5804
  function checkRemovedScopeNames(ctx) {
5761
5805
  let augmentedMemo;
5762
- const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path20.join(ctx.root, rel), "utf8")));
5806
+ const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path21.join(ctx.root, rel), "utf8")));
5763
5807
  for (const file of ctx.files) {
5764
5808
  if (!SCRIPT_EXTS5.has(file.ext)) continue;
5765
5809
  for (const hit of findRemovedScopeNames(file.code)) {
@@ -5831,16 +5875,16 @@ function genesisNamedImports(source) {
5831
5875
  }
5832
5876
  function declarationFiles(dir, out = []) {
5833
5877
  for (const name of readdirSync(dir)) {
5834
- const full = path20.join(dir, name);
5878
+ const full = path21.join(dir, name);
5835
5879
  if (statSync(full).isDirectory()) declarationFiles(full, out);
5836
5880
  else if (/\.d\.[cm]?ts$/.test(name)) out.push(full);
5837
5881
  }
5838
5882
  return out;
5839
5883
  }
5840
5884
  function readPackageTags(dir) {
5841
- const pkg = JSON.parse(readFileSync(path20.join(dir, "package.json"), "utf8"));
5885
+ const pkg = JSON.parse(readFileSync(path21.join(dir, "package.json"), "utf8"));
5842
5886
  const tags = { dir, byFile: /* @__PURE__ */ new Map(), declaredIn: /* @__PURE__ */ new Map(), exports: typeof pkg.exports === "object" && pkg.exports ? pkg.exports : {} };
5843
- const dist = path20.join(dir, "dist");
5887
+ const dist = path21.join(dir, "dist");
5844
5888
  if (!existsSync(dist)) return tags;
5845
5889
  for (const file of declarationFiles(dist)) {
5846
5890
  const text = readFileSync(file, "utf8");
@@ -5858,7 +5902,7 @@ function entryFile(tags, pkg, specifier) {
5858
5902
  const subpath = `.${specifier.slice(pkg.length)}` || ".";
5859
5903
  const target = tags.exports[subpath === "." ? "." : subpath];
5860
5904
  const types = typeof target === "object" && target ? target.types : null;
5861
- return typeof types === "string" ? path20.join(tags.dir, types) : null;
5905
+ return typeof types === "string" ? path21.join(tags.dir, types) : null;
5862
5906
  }
5863
5907
  function tagFor(tags, entry, name) {
5864
5908
  if (entry && tags.declaredIn.get(name)?.includes(entry)) return tags.byFile.get(entry)?.get(name);
@@ -5913,7 +5957,7 @@ function showAt(dir, rev, file) {
5913
5957
  function configAtBase(root, base, explicitFile) {
5914
5958
  const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
5915
5959
  if (!mergeBase) return null;
5916
- const candidates = explicitFile ? [{ dir: path20.dirname(explicitFile), file: path20.basename(explicitFile), explicit: true }] : [
5960
+ const candidates = explicitFile ? [{ dir: path21.dirname(explicitFile), file: path21.basename(explicitFile), explicit: true }] : [
5917
5961
  { dir: root, file: "genesis.config.json", explicit: false },
5918
5962
  { dir: root, file: "package.json", explicit: false }
5919
5963
  ];
@@ -6025,7 +6069,7 @@ async function checkContracts(ctx, read2 = postgresContract) {
6025
6069
  const env = settings.databaseEnv ?? DEFAULT_DATABASE_ENV;
6026
6070
  let current = null;
6027
6071
  try {
6028
- current = lf(readFileSync(path20.join(ctx.root, out), "utf8"));
6072
+ current = lf(readFileSync(path21.join(ctx.root, out), "utf8"));
6029
6073
  } catch {
6030
6074
  current = null;
6031
6075
  }
@@ -6049,7 +6093,7 @@ async function checkContracts(ctx, read2 = postgresContract) {
6049
6093
  ctx.report({ rule: "contracts-stale", level: generation ? "error" : "warn", file: out, message: generation ? `couldn't be generated: ${message}` : `couldn't read the database through ${env}: ${message}` });
6050
6094
  return;
6051
6095
  }
6052
- const target = path20.relative(process.cwd(), path20.join(ctx.root, out)) || out;
6096
+ const target = path21.relative(process.cwd(), path21.join(ctx.root, out)) || out;
6053
6097
  const command = `genesis introspect -o ${shellArg(target)} -s ${shellArg(schemas.join(","))}${env === DEFAULT_DATABASE_ENV ? "" : ` --database-env ${shellArg(env)}`}`;
6054
6098
  if (current !== expected) {
6055
6099
  ctx.report({
@@ -6063,7 +6107,7 @@ var GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
6063
6107
  var CORE = [
6064
6108
  {
6065
6109
  need: "anything, before building it",
6066
- use: 'search what exists: `genesis features find <term>`, this catalog, and the doctor\'s "Available but unused" list',
6110
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the "Available but unused" list in `genesis doctor --verbose`',
6067
6111
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6068
6112
  from: "genesis-cli"
6069
6113
  },
@@ -6192,8 +6236,8 @@ function currentAgentsBlock(agents) {
6192
6236
  var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
6193
6237
  function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
6194
6238
  const rows = primitivesCatalog(packages);
6195
- const skill = read(path20.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
6196
- const block = currentAgentsBlock(read(path20.join(root, agentsFile)));
6239
+ const skill = read(path21.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
6240
+ const block = currentAgentsBlock(read(path21.join(root, agentsFile)));
6197
6241
  return {
6198
6242
  skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
6199
6243
  agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
@@ -6215,36 +6259,14 @@ function checkAgentGuide(ctx) {
6215
6259
  ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
6216
6260
  }
6217
6261
  }
6218
- var CLI = "@marktiderman/genesis-cli";
6219
- function ownedKeyProblem(key2, source, localNames = /* @__PURE__ */ new Set()) {
6220
- let parsed;
6221
- try {
6222
- parsed = parseSource(source);
6223
- } catch (err) {
6224
- return err instanceof Error ? err.message : String(err);
6225
- }
6226
- const { package: pkg, path: rel } = parsed;
6227
- if (!GENESIS_PACKAGE.test(pkg) && !localNames.has(pkg)) return `${key2}'s source ${pkg} isn't a Genesis or local package`;
6228
- if (!safeRelative(rel) || !safeRelative(key2)) return `${key2} or its source isn't a plain path`;
6229
- if (key2.startsWith("supabase/migrations/")) return `${key2} is a migration; migrations are never refreshed`;
6230
- const base = rel.split("/").pop();
6231
- if (pkg === CLI && rel.startsWith("templates/")) {
6232
- return /^(eas\.json|\.eas\/[\w./-]+|\.maestro\/[\w./-]+|\.github\/workflows\/[\w.-]+\.ya?ml)$/.test(key2) ? null : `${key2} isn't where a template goes`;
6233
- }
6234
- const fn = /^functions\/([a-z0-9][a-z0-9_-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(rel);
6235
- if (fn) return key2 === `supabase/functions/${fn[1]}/${fn[2]}` ? null : `${key2} isn't where ${rel} goes`;
6236
- if (/\.test\.sql$/.test(base)) return key2 === `supabase/tests/database/${base.replace(/^\d{4}_/, "")}` ? null : `${key2} isn't where ${rel} goes`;
6237
- if (/^\.claude\/skills\/[a-z0-9][a-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key2) && key2.endsWith(`/${base}`)) return null;
6238
- return `${key2} doesn't match its source ${source}`;
6239
- }
6240
6262
 
6241
6263
  // src/blocks/templates.ts
6242
6264
  function starterDir() {
6243
6265
  const workspace = workspacePackagesDir();
6244
- const live = workspace && path20.join(workspace, "..", "apps", "genesis-rn-starter");
6245
- if (live && existsSync(path20.join(live, "package.json"))) return live;
6246
- const packaged = path20.join(cliPackageDir(), "dist", "starter");
6247
- if (existsSync(path20.join(packaged, "package.json"))) return packaged;
6266
+ const live = workspace && path21.join(workspace, "..", "apps", "genesis-rn-starter");
6267
+ if (live && existsSync(path21.join(live, "package.json"))) return live;
6268
+ const packaged = path21.join(cliPackageDir(), "dist", "starter");
6269
+ if (existsSync(path21.join(packaged, "package.json"))) return packaged;
6248
6270
  throw new Error("This genesis-cli has no starter (dist/starter is missing): reinstall @marktiderman/genesis-cli.");
6249
6271
  }
6250
6272
 
@@ -6318,7 +6340,7 @@ function readText(file) {
6318
6340
  }
6319
6341
  function starterBlockMap(root) {
6320
6342
  if (root) {
6321
- const file = path20.join(root, GENESIS_CONFIG);
6343
+ const file = path21.join(root, GENESIS_CONFIG);
6322
6344
  const text2 = readText(file);
6323
6345
  const own = text2 === null ? null : parseStarterBlocks(text2, file);
6324
6346
  if (own) return own;
@@ -6329,7 +6351,7 @@ function starterBlockMap(root) {
6329
6351
  } catch {
6330
6352
  return {};
6331
6353
  }
6332
- const text = readText(path20.join(dir, GENESIS_CONFIG));
6354
+ const text = readText(path21.join(dir, GENESIS_CONFIG));
6333
6355
  return (text === null ? null : parseStarterBlocks(text)) ?? {};
6334
6356
  }
6335
6357
  function blocksSwitchedOff(switches, map, manifests, present) {
@@ -6349,10 +6371,10 @@ function blocksSwitchedOff(switches, map, manifests, present) {
6349
6371
  return off;
6350
6372
  }
6351
6373
  function appBlocksSwitchedOff(root, manifests, present) {
6352
- const text = readText(path20.join(root, STARTER_CONFIG));
6374
+ const text = readText(path21.join(root, STARTER_CONFIG));
6353
6375
  const switches = text === null ? null : parseStarterFeatures(text);
6354
6376
  if (!switches) return /* @__PURE__ */ new Map();
6355
- return blocksSwitchedOff(switches, starterBlockMap(existsSync(path20.join(root, GENESIS_CONFIG)) ? root : void 0), manifests, present);
6377
+ return blocksSwitchedOff(switches, starterBlockMap(existsSync(path21.join(root, GENESIS_CONFIG)) ? root : void 0), manifests, present);
6356
6378
  }
6357
6379
  function blockOfSource(source, manifests) {
6358
6380
  const at = source.indexOf(":");
@@ -6365,6 +6387,34 @@ function blockOfSource(source, manifests) {
6365
6387
  }
6366
6388
  return null;
6367
6389
  }
6390
+
6391
+ // src/blocks/app-folder.ts
6392
+ function appFolderOf(root) {
6393
+ return readGenesisConfig(root)?.appFolder ?? null;
6394
+ }
6395
+ var isRepositoryWorkflow = (rel) => rel.startsWith(".github/workflows/");
6396
+ var CLI = "@marktiderman/genesis-cli";
6397
+ function ownedKeyProblem(key2, source, localNames = /* @__PURE__ */ new Set()) {
6398
+ let parsed;
6399
+ try {
6400
+ parsed = parseSource(source);
6401
+ } catch (err) {
6402
+ return err instanceof Error ? err.message : String(err);
6403
+ }
6404
+ const { package: pkg, path: rel } = parsed;
6405
+ if (!GENESIS_PACKAGE.test(pkg) && !localNames.has(pkg)) return `${key2}'s source ${pkg} isn't a Genesis or local package`;
6406
+ if (!safeRelative(rel) || !safeRelative(key2)) return `${key2} or its source isn't a plain path`;
6407
+ if (key2.startsWith("supabase/migrations/")) return `${key2} is a migration; migrations are never refreshed`;
6408
+ const base = rel.split("/").pop();
6409
+ if (pkg === CLI && rel.startsWith("templates/")) {
6410
+ return /^(eas\.json|\.eas\/[\w./-]+|\.maestro\/[\w./-]+|\.github\/workflows\/[\w.-]+\.ya?ml)$/.test(key2) ? null : `${key2} isn't where a template goes`;
6411
+ }
6412
+ const fn = /^functions\/([a-z0-9][a-z0-9_-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(rel);
6413
+ if (fn) return key2 === `supabase/functions/${fn[1]}/${fn[2]}` ? null : `${key2} isn't where ${rel} goes`;
6414
+ if (/\.test\.sql$/.test(base)) return key2 === `supabase/tests/database/${base.replace(/^\d{4}_/, "")}` ? null : `${key2} isn't where ${rel} goes`;
6415
+ if (/^\.claude\/skills\/[a-z0-9][a-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key2) && key2.endsWith(`/${base}`)) return null;
6416
+ return `${key2} doesn't match its source ${source}`;
6417
+ }
6368
6418
  var BUN_LOCK = "bun.lock";
6369
6419
  var GENESIS_TAIL = /(?:^|\/)(@marktiderman\/genesis(?:-[a-z0-9-]+)?)$/;
6370
6420
  var PLAIN_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;
@@ -6497,21 +6547,9 @@ function staleNestedEntries(text, want = () => null) {
6497
6547
  return out;
6498
6548
  }
6499
6549
  function readBunLock(dir) {
6500
- const file = path20.join(dir, BUN_LOCK);
6550
+ const file = path21.join(dir, BUN_LOCK);
6501
6551
  return existsSync(file) ? readFileSync(file, "utf8") : null;
6502
6552
  }
6503
- function findLockfile(root) {
6504
- let dir = path20.resolve(root);
6505
- for (; ; ) {
6506
- if (existsSync(path20.join(dir, "pnpm-lock.yaml"))) return { pm: "pnpm", dir };
6507
- if (existsSync(path20.join(dir, "bun.lock")) || existsSync(path20.join(dir, "bun.lockb"))) return { pm: "bun", dir };
6508
- if (existsSync(path20.join(dir, "yarn.lock"))) return { pm: "yarn", dir };
6509
- if (existsSync(path20.join(dir, "package-lock.json"))) return { pm: "npm", dir };
6510
- const parent = path20.dirname(dir);
6511
- if (parent === dir) return null;
6512
- dir = parent;
6513
- }
6514
- }
6515
6553
 
6516
6554
  // src/doctor/lock-files.ts
6517
6555
  function checkBunLock(ctx) {
@@ -6519,7 +6557,7 @@ function checkBunLock(ctx) {
6519
6557
  if (found?.pm !== "bun") return;
6520
6558
  const text = readBunLock(found.dir);
6521
6559
  if (text === null) return;
6522
- const file = path20.relative(ctx.root, path20.join(found.dir, BUN_LOCK)).split(path20.sep).join("/");
6560
+ const file = path21.relative(ctx.root, path21.join(found.dir, BUN_LOCK)).split(path21.sep).join("/");
6523
6561
  let stale;
6524
6562
  try {
6525
6563
  stale = staleNestedEntries(text);
@@ -6538,7 +6576,7 @@ function checkBunLock(ctx) {
6538
6576
  }
6539
6577
  async function checkLockFiles(ctx) {
6540
6578
  checkBunLock(ctx);
6541
- if (!existsSync(path20.join(ctx.root, LOCK_FILE))) return;
6579
+ if (!existsSync(path21.join(ctx.root, LOCK_FILE))) return;
6542
6580
  let lock;
6543
6581
  try {
6544
6582
  lock = readLock(ctx.root);
@@ -6571,6 +6609,11 @@ async function checkLockFiles(ctx) {
6571
6609
  home = databaseElsewhere(ctx.root);
6572
6610
  } catch {
6573
6611
  }
6612
+ let appFolder = null;
6613
+ try {
6614
+ appFolder = appFolderOf(ctx.root);
6615
+ } catch {
6616
+ }
6574
6617
  const elsewhere = home ? Object.keys(lock.files).filter(isSupabasePath) : [];
6575
6618
  if (home && elsewhere.length) {
6576
6619
  ctx.report({
@@ -6606,6 +6649,7 @@ async function checkLockFiles(ctx) {
6606
6649
  }
6607
6650
  if (text === null) {
6608
6651
  if (entry.deleted) continue;
6652
+ if (appFolder && isRepositoryWorkflow(rel)) continue;
6609
6653
  ctx.report({
6610
6654
  rule: "lock-files",
6611
6655
  level: "warn",
@@ -6640,7 +6684,7 @@ function checkDatabaseHome(ctx) {
6640
6684
  message: `supabase.app is ${home.app}, which has no supabase folder; name the app that holds this app's database (its migrations, tests and Edge Functions)`
6641
6685
  });
6642
6686
  }
6643
- if (existsSync(path20.join(ctx.root, "supabase"))) {
6687
+ if (existsSync(path21.join(ctx.root, "supabase"))) {
6644
6688
  ctx.report({
6645
6689
  rule: "database-elsewhere",
6646
6690
  level: "warn",
@@ -6658,7 +6702,7 @@ function checkEslintConfig(ctx) {
6658
6702
  if (!file) return;
6659
6703
  let text;
6660
6704
  try {
6661
- text = readFileSync(path20.join(ctx.root, file), "utf8");
6705
+ text = readFileSync(path21.join(ctx.root, file), "utf8");
6662
6706
  } catch {
6663
6707
  return;
6664
6708
  }
@@ -6678,11 +6722,353 @@ function checkEslintConfig(ctx) {
6678
6722
  subject: TESTING_LIBRARY,
6679
6723
  message: `${file} loads Genesis's native lint rules, which need ${TESTING_LIBRARY}: add it to devDependencies (pnpm add -D ${TESTING_LIBRARY}), or the lint can't load its config`
6680
6724
  });
6725
+ } else if (!findPackageDir(ctx.root, TESTING_LIBRARY)) {
6726
+ ctx.report({
6727
+ rule: "genesis-eslint-config",
6728
+ level: "warn",
6729
+ file: "package.json",
6730
+ subject: TESTING_LIBRARY,
6731
+ message: `lists ${TESTING_LIBRARY}, which ${file} needs, but it isn't installed, so the lint can't load its config: run ${shellLine(installCommand(detectPackageManager(ctx.root)))}`
6732
+ });
6733
+ }
6734
+ }
6735
+ var FigmaConfigError = class extends Error {
6736
+ };
6737
+ function validateFigmaConfig(raw, source = "genesis.config.json") {
6738
+ const obj = raw;
6739
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new FigmaConfigError(`${source}: figma must be an object`);
6740
+ if (typeof obj.file !== "string" || !/^[A-Za-z0-9]+$/.test(obj.file)) throw new FigmaConfigError(`${source}: figma.file must be the file key (letters and digits, from the file's URL)`);
6741
+ const pages = obj.pages;
6742
+ if (!pages || typeof pages !== "object" || Array.isArray(pages)) throw new FigmaConfigError(`${source}: figma.pages must be { "web"?: "<page>", "native"?: "<page>" }`);
6743
+ const out = {};
6744
+ for (const [k, v] of Object.entries(pages)) {
6745
+ if (k !== "web" && k !== "native") throw new FigmaConfigError(`${source}: figma.pages.${k}: only "web" and "native"`);
6746
+ if (typeof v !== "string" || !v) throw new FigmaConfigError(`${source}: figma.pages.${k} must be a page name`);
6747
+ out[k] = v;
6748
+ }
6749
+ if (!out.web && !out.native) throw new FigmaConfigError(`${source}: figma.pages needs "web" or "native"`);
6750
+ if (obj.proposalsPage !== void 0 && (typeof obj.proposalsPage !== "string" || !obj.proposalsPage)) throw new FigmaConfigError(`${source}: figma.proposalsPage must be a page name`);
6751
+ return { file: obj.file, pages: out, proposalsPage: obj.proposalsPage ?? "Proposals" };
6752
+ }
6753
+ function readFigmaConfig(root) {
6754
+ const file = path21.join(root, "genesis.config.json");
6755
+ if (!existsSync(file)) return null;
6756
+ let raw;
6757
+ try {
6758
+ raw = JSON.parse(readFileSync(file, "utf8"));
6759
+ } catch (err) {
6760
+ throw new FigmaConfigError(`${file} isn't valid JSON: ${err.message}`);
6761
+ }
6762
+ return raw?.figma === void 0 ? null : validateFigmaConfig(raw.figma, file);
6763
+ }
6764
+ var CODE = /\.(?:tsx|ts|jsx|js)$/;
6765
+ var FIGMA_ID = /^\s*\/\/\s*figma:\s*(\d+[:-]\d+)\s*$/;
6766
+ function walk2(dir, out = []) {
6767
+ if (!existsSync(dir)) return out;
6768
+ for (const name of readdirSync(dir).sort()) {
6769
+ if (name === "node_modules" || name.startsWith(".")) continue;
6770
+ const full = path21.join(dir, name);
6771
+ if (statSync(full).isDirectory()) walk2(full, out);
6772
+ else if (CODE.test(name) && !/\.(?:test|spec|d)\.[jt]sx?$/.test(name)) out.push(full);
6773
+ }
6774
+ return out;
6775
+ }
6776
+ function figmaIdOf(code) {
6777
+ for (const line of code.split("\n").slice(0, 5)) {
6778
+ const m = FIGMA_ID.exec(line);
6779
+ if (m) return m[1].replace("-", ":");
6780
+ }
6781
+ return void 0;
6782
+ }
6783
+ function tanstackSegments(stem) {
6784
+ const out = [];
6785
+ let cur = "";
6786
+ let depth = 0;
6787
+ for (const ch of stem) {
6788
+ if (ch === "{") depth++;
6789
+ if (ch === "}") depth--;
6790
+ if (ch === "." && depth === 0) {
6791
+ out.push(cur);
6792
+ cur = "";
6793
+ } else cur += ch;
6794
+ }
6795
+ out.push(cur);
6796
+ return out;
6797
+ }
6798
+ function expoRoot(root) {
6799
+ for (const dir of ["src/app", "app"]) if (existsSync(path21.join(root, dir))) return dir;
6800
+ return null;
6801
+ }
6802
+ function appRoutes(root) {
6803
+ const out = [];
6804
+ const rel = (f) => path21.relative(root, f).split(path21.sep).join("/");
6805
+ const expo = expoRoot(root);
6806
+ if (expo) {
6807
+ for (const f of walk2(path21.join(root, expo))) {
6808
+ const parts = path21.relative(path21.join(root, expo), f).split(path21.sep);
6809
+ const stem = parts.pop().replace(CODE, "");
6810
+ if (stem === "_layout" || stem.startsWith("+")) continue;
6811
+ if (stem !== "index") parts.push(stem);
6812
+ out.push(withId({ route: parts.join("/") || "index", platform: "native", file: rel(f) }, f));
6813
+ }
6814
+ }
6815
+ const tanstack = path21.join(root, "src/routes");
6816
+ if (existsSync(tanstack)) {
6817
+ const seen = /* @__PURE__ */ new Set();
6818
+ for (const f of walk2(tanstack)) {
6819
+ const parts = path21.relative(tanstack, f).split(path21.sep);
6820
+ const stem = parts.pop().replace(CODE, "").replace(/\.lazy$/, "");
6821
+ if (stem === "__root" || stem === "route" || stem.startsWith("-") || parts.some((p) => p.startsWith("-"))) continue;
6822
+ const segs = [...parts.flatMap(tanstackSegments), ...tanstackSegments(stem)];
6823
+ if (segs.at(-1) === "index") segs.pop();
6824
+ const route = segs.join("/") || "index";
6825
+ if (seen.has(route)) continue;
6826
+ seen.add(route);
6827
+ out.push(withId({ route, platform: "web", file: rel(f) }, f));
6828
+ }
6829
+ }
6830
+ return out;
6831
+ }
6832
+ function withId(r, file) {
6833
+ const id = figmaIdOf(readFileSync(file, "utf8"));
6834
+ return id ? { ...r, figmaId: id } : r;
6835
+ }
6836
+ function urlSegments(route) {
6837
+ return route.replace(/^\/+/, "").split("/").filter((s) => s && s !== "index" && !/^\(.*\)$/.test(s) && !/^_/.test(s)).map((s) => s.replace(/_$/, "")).map((s) => /^\{-\$.*\}$/.test(s) ? "?" : /^\[\.\.\..+\]$/.test(s) ? "**" : /^\$|^\[.*\]$/.test(s) ? "*" : s);
6838
+ }
6839
+ function routeMatches(route, target) {
6840
+ const pattern = urlSegments(route);
6841
+ const url = target.split(/[?#]/)[0].split("/").filter(Boolean);
6842
+ if (/(?:^|\/)\$$/.test(route)) {
6843
+ const head = pattern.slice(0, -1);
6844
+ return url.length >= head.length && head.every((p, i) => p === "*" || p === url[i]);
6845
+ }
6846
+ const go = (i, j) => {
6847
+ if (i === pattern.length) return j === url.length;
6848
+ const p = pattern[i];
6849
+ if (p === "?") return go(i + 1, j) || j < url.length && go(i + 1, j + 1);
6850
+ if (j === url.length) return false;
6851
+ if (p === "**") {
6852
+ for (let k = j + 1; k <= url.length; k++) if (go(i + 1, k)) return true;
6853
+ return false;
6854
+ }
6855
+ return (p === "*" || p === url[j]) && go(i + 1, j + 1);
6856
+ };
6857
+ return go(0, 0);
6858
+ }
6859
+ function sameScreen(a, b) {
6860
+ return a.replace(/^\/+/, "") === b.replace(/^\/+/, "") || urlSegments(a).join("/") === urlSegments(b).join("/");
6861
+ }
6862
+ var STR = String.raw`(?:"([^"\n]*)"|'([^'\n]*)'|` + "`([^`$\\n]*)`)";
6863
+ var NAV_PATTERNS = [
6864
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*` + STR, "g"),
6865
+ new RegExp(String.raw`<Link\b[^>]*?\b(?:href|to)=\{?\s*` + STR, "g"),
6866
+ new RegExp(String.raw`\bnavigate\(\s*\{[^}]*?\bto\s*:\s*` + STR, "g")
6867
+ ];
6868
+ var DYNAMIC_PATTERNS = [
6869
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
6870
+ new RegExp(String.raw`<Link\b[^>]*?\b(?:href|to)=\{\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
6871
+ new RegExp(String.raw`\bnavigate\(\s*\{[^}]*?\bto\s*:\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
6872
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*(\{[^}\n]*?\bpathname\b[^}\n]*\}?)`, "g"),
6873
+ new RegExp(String.raw`<Link\b[^>]*?\bhref=\{(\{[^}\n]*?\bpathname\b[^}\n]*\}?)`, "g")
6874
+ ];
6875
+ function dynamicNavTargets(code, file) {
6876
+ const out = [];
6877
+ for (const re of DYNAMIC_PATTERNS) {
6878
+ for (const m of code.matchAll(re)) {
6879
+ const raw = m[1].trim();
6880
+ out.push({ file, line: code.slice(0, m.index).split("\n").length, target: raw.length > 60 ? `${raw.slice(0, 57)}...` : raw });
6881
+ }
6882
+ }
6883
+ return out.sort((a, b) => a.line - b.line);
6884
+ }
6885
+ function navTargets(code, file) {
6886
+ const out = [];
6887
+ for (const re of NAV_PATTERNS) {
6888
+ for (const m of code.matchAll(re)) {
6889
+ const target = m[1] ?? m[2] ?? m[3];
6890
+ if (target === void 0 || /^[a-z]+:/i.test(target) || target.startsWith("#") || target.startsWith(".")) continue;
6891
+ out.push({ file, line: code.slice(0, m.index).split("\n").length, target });
6892
+ }
6893
+ }
6894
+ return out.sort((a, b) => a.line - b.line);
6895
+ }
6896
+ function appNavTargets(root) {
6897
+ const files = [.../* @__PURE__ */ new Set([...walk2(path21.join(root, "src")), ...walk2(path21.join(root, "app"))])];
6898
+ return files.flatMap((f) => navTargets(readFileSync(f, "utf8"), path21.relative(root, f).split(path21.sep).join("/")));
6899
+ }
6900
+ function appDynamicNavTargets(root) {
6901
+ const files = [.../* @__PURE__ */ new Set([...walk2(path21.join(root, "src")), ...walk2(path21.join(root, "app"))])];
6902
+ return files.flatMap((f) => dynamicNavTargets(readFileSync(f, "utf8"), path21.relative(root, f).split(path21.sep).join("/")));
6903
+ }
6904
+ var FIGMA_API = "https://api.figma.com";
6905
+ var FIGMA_TIMEOUT_MS = 3e4;
6906
+ function splitName(name) {
6907
+ const i = name.indexOf(" \xB7 ");
6908
+ return i < 0 ? { route: name.trim() } : { route: name.slice(0, i).trim(), state: name.slice(i + 3).trim() };
6909
+ }
6910
+ function destinations(node, out = /* @__PURE__ */ new Set()) {
6911
+ if (node.transitionNodeID) out.add(node.transitionNodeID);
6912
+ for (const i of node.interactions ?? []) {
6913
+ for (const a of i.actions ?? []) if (a?.type === "NODE" && a.destinationId && a.navigation !== "CHANGE_TO") out.add(a.destinationId);
6914
+ }
6915
+ for (const c of node.children ?? []) destinations(c, out);
6916
+ return out;
6917
+ }
6918
+ var SCREEN_TYPES = /* @__PURE__ */ new Set(["FRAME", "COMPONENT", "COMPONENT_SET", "INSTANCE"]);
6919
+ async function readFigma(config, token, fetchImpl = fetch, timeoutMs = FIGMA_TIMEOUT_MS) {
6920
+ const get2 = async (p) => {
6921
+ const where2 = p.split("?")[0];
6922
+ try {
6923
+ const res = await fetchImpl(`${FIGMA_API}${p}`, { headers: { "X-Figma-Token": token }, signal: AbortSignal.timeout(timeoutMs) });
6924
+ if (!res.ok) throw new Error(`Figma API ${where2} answered ${res.status}${res.status === 403 ? " (check FIGMA_ACCESS_TOKEN and its access to the file)" : ""}`);
6925
+ return await res.json();
6926
+ } catch (err) {
6927
+ const name = err?.name;
6928
+ if (name === "TimeoutError" || name === "AbortError") throw new Error(`Figma API ${where2} didn't answer within ${Math.round(timeoutMs / 1e3)}s`);
6929
+ throw err;
6930
+ }
6931
+ };
6932
+ const nodes = async (ids, depth) => {
6933
+ const out = [];
6934
+ for (let i = 0; i < ids.length; i += 50) {
6935
+ const chunk = ids.slice(i, i + 50);
6936
+ const body = await get2(`/v1/files/${config.file}/nodes?ids=${encodeURIComponent(chunk.join(","))}${depth ? `&depth=${depth}` : ""}`);
6937
+ for (const id of chunk) {
6938
+ const doc = body.nodes[id]?.document;
6939
+ if (doc) out.push(doc);
6940
+ }
6941
+ }
6942
+ return out;
6943
+ };
6944
+ const file = await get2(`/v1/files/${config.file}?depth=2`);
6945
+ const canvases = file.document.children ?? [];
6946
+ const wanted = /* @__PURE__ */ new Set([...Object.values(config.pages), config.proposalsPage]);
6947
+ const frames = [];
6948
+ const sections = [];
6949
+ for (const page of canvases) {
6950
+ if (!wanted.has(page.name)) continue;
6951
+ for (const child of page.children ?? []) {
6952
+ if (child.type === "SECTION") sections.push({ id: child.id, name: child.name, page: page.name });
6953
+ else if (SCREEN_TYPES.has(child.type)) frames.push({ id: child.id, name: child.name, page: page.name, ...splitName(child.name) });
6954
+ }
6955
+ }
6956
+ for (const s of await nodes(sections.map((x) => x.id), 1)) {
6957
+ const section2 = sections.find((x) => x.id === s.id);
6958
+ for (const child of s.children ?? []) {
6959
+ if (SCREEN_TYPES.has(child.type)) frames.push({ id: child.id, name: child.name, page: section2.page, section: section2.name, ...splitName(child.name) });
6960
+ }
6961
+ }
6962
+ const hotspots = [];
6963
+ for (const tree of await nodes(frames.filter((f) => f.page !== config.proposalsPage).map((f) => f.id))) {
6964
+ for (const to of destinations(tree)) if (to !== tree.id) hotspots.push({ from: tree.id, to });
6965
+ }
6966
+ return { pages: canvases.map((p) => p.name), frames, hotspots };
6967
+ }
6968
+ function compare(config, routes, targets, figma, dynamicTargets = []) {
6969
+ const platformOf = (page) => config.pages.web === page ? "web" : config.pages.native === page ? "native" : void 0;
6970
+ const inProposal = (f) => /^Proposal\s*·/.test(f.section ?? "");
6971
+ const routeFrames = figma.frames.filter((f) => platformOf(f.page) && !inProposal(f));
6972
+ const framesFor = (r) => routeFrames.filter((f) => platformOf(f.page) === r.platform && (sameScreen(f.route, r.route) || r.route === "index" && f.route === "/"));
6973
+ const byId = new Map(figma.frames.map((f) => [f.id, f]));
6974
+ const framed = new Set(routes.flatMap((r) => framesFor(r).map((f) => f.id)));
6975
+ const covered = routes.filter((r) => framesFor(r).length > 0);
6976
+ const routesWithoutFrame = routes.filter((r) => framesFor(r).length === 0);
6977
+ const framesWithoutRoute = routeFrames.filter((f) => !framed.has(f.id));
6978
+ const proposals = {};
6979
+ for (const f of figma.frames.filter((x) => x.page === config.proposalsPage || platformOf(x.page) && inProposal(x))) (proposals[f.section ?? "(no section)"] ??= []).push(f);
6980
+ const missingHotspots = [];
6981
+ const seen = /* @__PURE__ */ new Set();
6982
+ for (const t of targets) {
6983
+ const source = routes.find((r) => r.file === t.file);
6984
+ if (!source) continue;
6985
+ const from = framesFor(source);
6986
+ if (!from.length) continue;
6987
+ const dest = routes.find((r) => r.platform === source.platform && routeMatches(r.route, t.target));
6988
+ if (!dest || dest === source) continue;
6989
+ const key2 = `${source.route}\u2192${dest.route}`;
6990
+ if (seen.has(key2)) continue;
6991
+ seen.add(key2);
6992
+ const to = new Set(framesFor(dest).map((f) => f.id));
6993
+ const linked = figma.hotspots.some((h) => from.some((f) => f.id === h.from) && to.has(h.to));
6994
+ if (!linked) missingHotspots.push({ ...t, from: source.route, to: dest.route, targetHasFrame: to.size > 0 });
6995
+ }
6996
+ const deadHotspots = [];
6997
+ for (const h of figma.hotspots) {
6998
+ const from = byId.get(h.from);
6999
+ const to = byId.get(h.to);
7000
+ if (from && to && platformOf(to.page) && !inProposal(to) && !framed.has(to.id)) deadHotspots.push({ from, to });
7001
+ }
7002
+ const idMismatches = routes.filter((r) => r.figmaId && !framesFor(r).some((f) => f.id === r.figmaId)).map((r) => ({ ...r, frames: framesFor(r).map((f) => f.id) }));
7003
+ const wantedPages = [...Object.values(config.pages), config.proposalsPage];
7004
+ const missingPages = wantedPages.filter((p) => p !== config.proposalsPage && !figma.pages.includes(p));
7005
+ const uncheckedNavigation = dynamicTargets.filter((t) => routes.some((r) => r.file === t.file));
7006
+ return {
7007
+ file: config.file,
7008
+ summary: {
7009
+ routes: routes.length,
7010
+ frames: routeFrames.length,
7011
+ covered: covered.length,
7012
+ coveredPercent: routes.length ? Math.round(covered.length / routes.length * 100) : 100,
7013
+ hotspots: figma.hotspots.length,
7014
+ missing: missingPages.length + routesWithoutFrame.length + missingHotspots.length + idMismatches.length
7015
+ },
7016
+ missingPages,
7017
+ routesWithoutFrame,
7018
+ framesWithoutRoute,
7019
+ proposals,
7020
+ missingHotspots,
7021
+ deadHotspots,
7022
+ idMismatches,
7023
+ uncheckedNavigation
7024
+ };
7025
+ }
7026
+ async function checkFigmaRoutes(options) {
7027
+ const config = options.config ?? readFigmaConfig(options.root);
7028
+ if (!config) throw new FigmaConfigError(`no "figma" block in ${path21.join(options.root, "genesis.config.json")}`);
7029
+ const token = options.token ?? process.env.FIGMA_ACCESS_TOKEN;
7030
+ if (!token) throw new FigmaConfigError("FIGMA_ACCESS_TOKEN isn't set");
7031
+ const figma = await readFigma(config, token, options.fetch);
7032
+ return compare(config, appRoutes(options.root), appNavTargets(options.root), figma, appDynamicNavTargets(options.root));
7033
+ }
7034
+ function coverageFindings(r, strict) {
7035
+ const gap = strict ? "warn" : "info";
7036
+ return [
7037
+ ...r.missingPages.map((p) => ({ level: gap, file: `figma:${p}`, message: `the Figma file has no page "${p}" (named in genesis.config.json figma)`, subject: p })),
7038
+ ...r.routesWithoutFrame.map((x) => ({ level: gap, file: x.file, message: `route ${x.route} has no ${x.platform} frame in the Figma file`, subject: x.route })),
7039
+ ...r.missingHotspots.map((m) => ({ level: gap, file: m.file, line: m.line, message: `navigates to ${m.to}, but the ${m.from} frame has no hotspot to it${m.targetHasFrame ? "" : " (and it has no frame)"}`, subject: m.to })),
7040
+ ...r.idMismatches.map((m) => ({ level: gap, file: m.file, line: 1, message: `// figma: ${m.figmaId} isn't the frame named ${m.route} (${m.frames.join(", ") || "none"})`, subject: m.route })),
7041
+ ...r.framesWithoutRoute.map((f) => ({ level: "info", file: `figma:${f.page}`, message: `frame "${f.name}" (${f.id}) has no route: move it to Proposals, or add the route`, subject: f.route })),
7042
+ ...r.deadHotspots.map((d) => ({ level: "info", file: `figma:${d.from.page}`, message: `"${d.from.name}" links to "${d.to.name}", which has no route`, subject: d.to.route })),
7043
+ ...r.uncheckedNavigation.map((t) => ({ level: "info", file: t.file, line: t.line, message: `navigation to ${t.target} isn't a string literal, so it isn't checked against the Figma file`, subject: t.target }))
7044
+ ];
7045
+ }
7046
+
7047
+ // src/doctor/figma-routes.ts
7048
+ async function checkFigmaRoutesRule(ctx) {
7049
+ let config;
7050
+ try {
7051
+ config = readFigmaConfig(ctx.root);
7052
+ } catch (err) {
7053
+ if (!(err instanceof FigmaConfigError)) throw err;
7054
+ ctx.report({ rule: "figma-routes", level: "warn", file: "genesis.config.json", message: err.message });
7055
+ return;
7056
+ }
7057
+ if (!config) return;
7058
+ if (!process.env.FIGMA_ACCESS_TOKEN) {
7059
+ ctx.report({ rule: "figma-routes", level: "info", file: "genesis.config.json", message: "skipped: FIGMA_ACCESS_TOKEN isn't set (CI sets it from a secret)" });
7060
+ return;
7061
+ }
7062
+ try {
7063
+ const report = await checkFigmaRoutes({ root: ctx.root, config });
7064
+ for (const f of coverageFindings(report, ctx.strict ?? false)) ctx.report({ rule: "figma-routes", ...f });
7065
+ } catch (err) {
7066
+ ctx.report({ rule: "figma-routes", level: "info", file: "genesis.config.json", message: `skipped: ${err.message}` });
6681
7067
  }
6682
7068
  }
6683
7069
  var RATCHETED_BY_DEFAULT = ["deprecated-import", "genesis-eslint-config"];
6684
7070
  async function runDoctor(options = {}) {
6685
- const root = path20.resolve(options.root ?? process.cwd());
7071
+ const root = path21.resolve(options.root ?? process.cwd());
6686
7072
  const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
6687
7073
  const config = loaded.config;
6688
7074
  const genesis = options.genesis ?? loadGenesis(root, config);
@@ -6697,7 +7083,7 @@ async function runDoctor(options = {}) {
6697
7083
  }
6698
7084
  const raw = [];
6699
7085
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
6700
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
7086
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
6701
7087
  try {
6702
7088
  await plugin.check(ctx);
6703
7089
  } catch (err) {
@@ -6736,7 +7122,7 @@ async function runDoctor(options = {}) {
6736
7122
  }
6737
7123
  let findings = applyConfig(raw, config, packageRuleIds(packages));
6738
7124
  if (options.base && changed) {
6739
- findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path20.join(root, f)) });
7125
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path21.join(root, f)) });
6740
7126
  }
6741
7127
  const errors = findings.filter((f) => f.level === "error").length;
6742
7128
  const warnings = findings.filter((f) => f.level === "warn").length;
@@ -6785,6 +7171,7 @@ function builtinChecks(config, options = {}) {
6785
7171
  { name: "database-elsewhere", check: checkDatabaseHome },
6786
7172
  { name: "eslint-config", check: checkEslintConfig },
6787
7173
  ...(config.packs ?? []).map((p) => packs[p]),
7174
+ ...options.figma !== false ? [{ name: "figma-routes", check: checkFigmaRoutesRule }] : [],
6788
7175
  ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
6789
7176
  ];
6790
7177
  }
@@ -6837,7 +7224,7 @@ function applyConfig(raw, config, packageIds) {
6837
7224
  }
6838
7225
  return out.sort((x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule));
6839
7226
  }
6840
- function formatReport(result) {
7227
+ function formatReport(result, options = {}) {
6841
7228
  const g = result.genesis;
6842
7229
  const lines = [
6843
7230
  `Genesis doctor: ${g.uiPackage}@${g.uiVersion}, ${g.components.length} components, ${g.tokens.size} tokens, ${result.ruleCount} app rules; raw tags checked: ${[...g.rawTags.keys()].join(", ") || "none"}`
@@ -6845,7 +7232,7 @@ function formatReport(result) {
6845
7232
  for (const f of result.findings) {
6846
7233
  lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
6847
7234
  }
6848
- lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
7235
+ lines.push(options.verbose ? `Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}` : `Available but unused: ${result.unused.length} (genesis doctor --verbose lists them)`);
6849
7236
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
6850
7237
  const info = result.infos ? `, ${result.infos} info` : "";
6851
7238
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
@@ -6864,7 +7251,7 @@ function genesisDoctor(options = {}) {
6864
7251
  root = options.root ?? config.root;
6865
7252
  },
6866
7253
  async buildStart() {
6867
- const result = await runDoctor({ root, configPath: options.configPath, strict: options.strict, contracts: false });
7254
+ const result = await runDoctor({ root, configPath: options.configPath, strict: options.strict, contracts: false, figma: false });
6868
7255
  if (!result.ok) this.error(`Genesis doctor found problems:
6869
7256
  ${formatProblems(result, options.strict)}`);
6870
7257
  if (result.warnings > 0) this.warn(formatReport(result));
@@ -6897,7 +7284,7 @@ ${formatProblems(result, options.strict)}`);
6897
7284
  running = true;
6898
7285
  try {
6899
7286
  genesis ??= loadGenesis(root, loadConfig(root, options.configPath).config);
6900
- const result = await runDoctor({ root, configPath: options.configPath, genesis, contracts: false });
7287
+ const result = await runDoctor({ root, configPath: options.configPath, genesis, contracts: false, figma: false });
6901
7288
  if (result.errors > 0) {
6902
7289
  showError(`Genesis doctor found problems:
6903
7290
  ${formatProblems(result)}`);
@@ -6917,15 +7304,15 @@ ${formatProblems(result)}`);
6917
7304
  }
6918
7305
  }
6919
7306
  };
6920
- const explicit = /* @__PURE__ */ new Set([path20.join(root, "genesis.config.json"), ...options.configPath ? [path20.resolve(root, options.configPath)] : []]);
7307
+ const explicit = /* @__PURE__ */ new Set([path21.join(root, "genesis.config.json"), ...options.configPath ? [path21.resolve(root, options.configPath)] : []]);
6921
7308
  try {
6922
7309
  const { config } = loadConfig(root, options.configPath);
6923
- if (config.rulesDoc) explicit.add(path20.resolve(root, config.rulesDoc));
7310
+ if (config.rulesDoc) explicit.add(path21.resolve(root, config.rulesDoc));
6924
7311
  } catch {
6925
7312
  }
6926
7313
  const schedule = (file) => {
6927
- if (!explicit.has(path20.resolve(file))) {
6928
- const rel = path20.relative(root, file).split(path20.sep).join("/");
7314
+ if (!explicit.has(path21.resolve(file))) {
7315
+ const rel = path21.relative(root, file).split(path21.sep).join("/");
6929
7316
  if (rel.startsWith("..") || rel.includes("node_modules/")) return;
6930
7317
  }
6931
7318
  clearTimeout(timer);