@marktiderman/genesis-cli 1.21.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -16,8 +16,13 @@ import * as fs from 'fs/promises';
16
16
 
17
17
  var __defProp = Object.defineProperty;
18
18
  var __getOwnPropNames = Object.getOwnPropertyNames;
19
- var __esm = (fn, res) => function __init() {
20
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
19
+ var __esm = (fn, res, err) => function __init() {
20
+ if (err) throw err[0];
21
+ try {
22
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
23
+ } catch (e) {
24
+ throw err = [e], e;
25
+ }
21
26
  };
22
27
  var __export = (target, all) => {
23
28
  for (var name in all)
@@ -366,14 +371,14 @@ function listApp(root, rel, options = {}) {
366
371
  const dir = path30.join(root, rel);
367
372
  if (!existsSync(dir)) return [];
368
373
  const out = [];
369
- const walk3 = (r) => {
374
+ const walk4 = (r) => {
370
375
  for (const entry of readdirSync(path30.join(root, r), { withFileTypes: true })) {
371
376
  const child = `${r}/${entry.name}`;
372
- if (entry.isDirectory()) walk3(child);
377
+ if (entry.isDirectory()) walk4(child);
373
378
  else if (entry.isFile() || options.symlinks && entry.isSymbolicLink()) out.push(child);
374
379
  }
375
380
  };
376
- walk3(rel);
381
+ walk4(rel);
377
382
  return out.sort();
378
383
  }
379
384
  var sha256;
@@ -1031,9 +1036,11 @@ __export(config_exports, {
1031
1036
  checkRegExp: () => checkRegExp,
1032
1037
  doctorBlock: () => doctorBlock,
1033
1038
  isPackageDeclaration: () => isPackageDeclaration,
1039
+ isPlainFolder: () => isPlainFolder,
1034
1040
  loadConfig: () => loadConfig,
1035
1041
  privacyDataType: () => privacyDataType,
1036
1042
  readGenesisConfig: () => readGenesisConfig,
1043
+ validateAppFolder: () => validateAppFolder,
1037
1044
  validateConfig: () => validateConfig,
1038
1045
  validateLinks: () => validateLinks,
1039
1046
  validatePrivacy: () => validatePrivacy,
@@ -1099,8 +1106,17 @@ function readGenesisConfig(root) {
1099
1106
  const supabase = validateSupabase(raw.supabase, file);
1100
1107
  if (supabase !== true) out.supabase = supabase;
1101
1108
  }
1109
+ if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
1102
1110
  return out;
1103
1111
  }
1112
+ function isPlainFolder(value) {
1113
+ return PLAIN_FOLDER.test(value) && !value.split("/").includes("..");
1114
+ }
1115
+ function validateAppFolder(raw, source = "config") {
1116
+ const norm = typeof raw === "string" ? raw.replace(/^\.\//, "").replace(/\/+$/, "") : "";
1117
+ 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)})`);
1118
+ return norm;
1119
+ }
1104
1120
  function validateSupabase(raw, source = "config") {
1105
1121
  const fail = (msg) => {
1106
1122
  throw new GenesisConfigError(`${source}: ${msg}`);
@@ -1309,7 +1325,7 @@ function isObject2(v) {
1309
1325
  function isStringList(v) {
1310
1326
  return Array.isArray(v) && v.every((x) => typeof x === "string");
1311
1327
  }
1312
- var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, STRING_LISTS, STRINGS, KNOWN, LEVELS, META_RULES, PATTERN_KEYS, PACKAGE_RULE_KEYS, CONTRACT_KEYS, PACKS, PACK_KEYS, PRIVACY_KEYS, DATA_USE_KEYS, LINK_KEYS, HOST;
1328
+ var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, STRING_LISTS, STRINGS, KNOWN, LEVELS, META_RULES, PATTERN_KEYS, PACKAGE_RULE_KEYS, CONTRACT_KEYS, PACKS, PACK_KEYS, PLAIN_FOLDER, PRIVACY_KEYS, DATA_USE_KEYS, LINK_KEYS, HOST;
1313
1329
  var init_config = __esm({
1314
1330
  "src/doctor/config.ts"() {
1315
1331
  GenesisConfigError = class extends Error {
@@ -1397,6 +1413,7 @@ var init_config = __esm({
1397
1413
  supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
1398
1414
  packages: { base: "string" }
1399
1415
  };
1416
+ PLAIN_FOLDER = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}){0,7}$/;
1400
1417
  PRIVACY_KEYS = /* @__PURE__ */ new Set(["blocks", "collects", "tracking"]);
1401
1418
  DATA_USE_KEYS = /* @__PURE__ */ new Set(["type", "purposes", "linked", "tracking"]);
1402
1419
  LINK_KEYS = /* @__PURE__ */ new Set(["hosts", "paths", "webcredentials"]);
@@ -1511,7 +1528,7 @@ function uiPackageFor(config) {
1511
1528
  function loadGenesis(root, config) {
1512
1529
  const uiPackage = uiPackageFor(config);
1513
1530
  const pkg = readPackageExports(root, uiPackage);
1514
- if (!pkg) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
1531
+ if (!pkg) throw new DoctorConfigError(notInstalled(root, uiPackage));
1515
1532
  const { dir: uiDir, exports: exportNames, values, components } = pkg;
1516
1533
  const tokens = /* @__PURE__ */ new Set();
1517
1534
  const themeFiles = resolveThemeFiles(root, config, uiDir);
@@ -1536,6 +1553,16 @@ function loadGenesis(root, config) {
1536
1553
  companions: loadCompanions(root, config, uiPackage)
1537
1554
  };
1538
1555
  }
1556
+ function notInstalled(root, uiPackage) {
1557
+ let declared = false;
1558
+ try {
1559
+ const pkg = JSON.parse(readFileSync(path30.join(root, "package.json"), "utf8"));
1560
+ declared = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].some((s) => pkg[s]?.[uiPackage] !== void 0);
1561
+ } catch {
1562
+ }
1563
+ if (!declared) return `${uiPackage} is not installed here and isn't in this app's package.json. Add it, or set doctor.uiPackage.`;
1564
+ 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.`;
1565
+ }
1539
1566
  function loadCompanions(root, config, uiPackage) {
1540
1567
  const out = [];
1541
1568
  for (const name of config.componentPackages ?? DEFAULT_COMPONENT_PACKAGES) {
@@ -1762,6 +1789,7 @@ function loadPalette(root) {
1762
1789
  var DEFAULT_UI_PACKAGE, NATIVE_UI_PACKAGE, DESIGN_SYSTEM_PACKAGE, DEFAULT_COMPONENT_PACKAGES, TAGS, TAG_ALIASES, NON_COMPONENT_SUFFIX, TAILWIND_PALETTE, TS_SOURCE, isTsSource;
1763
1790
  var init_genesis = __esm({
1764
1791
  "src/doctor/genesis.ts"() {
1792
+ init_pm();
1765
1793
  init_config();
1766
1794
  DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
1767
1795
  NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
@@ -1995,7 +2023,7 @@ function globToRegExp(glob) {
1995
2023
  }
1996
2024
  function globMatcher(globs) {
1997
2025
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1998
- return (path56) => res.some((re) => re.test(path56));
2026
+ return (path61) => res.some((re) => re.test(path61));
1999
2027
  }
2000
2028
  var init_glob = __esm({
2001
2029
  "src/doctor/glob.ts"() {
@@ -2016,10 +2044,10 @@ function scanFiles(root, config) {
2016
2044
  const text = readFileSync(abs, "utf8");
2017
2045
  files.push({ path: rel, absolutePath: abs, ext, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(ext)) });
2018
2046
  };
2019
- const walk3 = (dir) => {
2047
+ const walk4 = (dir) => {
2020
2048
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
2021
2049
  if (entry.isDirectory()) {
2022
- if (!SKIP_DIRS.has(entry.name)) walk3(path30.join(dir, entry.name));
2050
+ if (!SKIP_DIRS.has(entry.name)) walk4(path30.join(dir, entry.name));
2023
2051
  } else if (entry.isFile()) {
2024
2052
  visit(path30.join(dir, entry.name));
2025
2053
  }
@@ -2028,7 +2056,7 @@ function scanFiles(root, config) {
2028
2056
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
2029
2057
  const abs = path30.resolve(root, src);
2030
2058
  if (!existsSync(abs)) continue;
2031
- if (statSync(abs).isDirectory()) walk3(abs);
2059
+ if (statSync(abs).isDirectory()) walk4(abs);
2032
2060
  else visit(abs);
2033
2061
  }
2034
2062
  let local = [];
@@ -2037,7 +2065,7 @@ function scanFiles(root, config) {
2037
2065
  } catch {
2038
2066
  local = [];
2039
2067
  }
2040
- for (const pkg of local) walk3(pkg.dir);
2068
+ for (const pkg of local) walk4(pkg.dir);
2041
2069
  return files;
2042
2070
  }
2043
2071
  function lineAt(text, index) {
@@ -4104,7 +4132,7 @@ function checkShadowedExports(ctx) {
4104
4132
  file.code.split("\n").forEach((text, i) => {
4105
4133
  for (const m of text.matchAll(re)) {
4106
4134
  if (!ctx.genesis.values.has(m[1])) continue;
4107
- 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]}` });
4135
+ 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)` });
4108
4136
  }
4109
4137
  });
4110
4138
  }
@@ -4132,6 +4160,8 @@ var init_rules = __esm({
4132
4160
  init_overlays();
4133
4161
  BUILTIN_RULES = [
4134
4162
  "local-primitives",
4163
+ // figma (figma/routes.ts; runs when genesis.config.json has a figma block)
4164
+ "figma-routes",
4135
4165
  "starter-leftover",
4136
4166
  "forbidden-import",
4137
4167
  "raw-tag",
@@ -5772,11 +5802,11 @@ function checkMigrations(ctx, pkg, json, locals) {
5772
5802
  }
5773
5803
  function checkExports(ctx, pkg, json) {
5774
5804
  const targets = [];
5775
- const walk3 = (v) => {
5805
+ const walk4 = (v) => {
5776
5806
  if (typeof v === "string") targets.push(v);
5777
- else if (v && typeof v === "object") for (const x of Object.values(v)) walk3(x);
5807
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk4(x);
5778
5808
  };
5779
- walk3(json.exports);
5809
+ walk4(json.exports);
5780
5810
  for (const t of targets) {
5781
5811
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
5782
5812
  if (!existsSync(path30.join(pkg.dir, t))) {
@@ -6484,7 +6514,7 @@ function genesisInstalls(root) {
6484
6514
  via.get(real2).add(root2);
6485
6515
  if (!copy.requiredBy.some((r) => r.by === by)) copy.requiredBy.push({ by, ...range ? { range } : {} });
6486
6516
  };
6487
- const walk3 = (kind, roots) => {
6517
+ const walk4 = (kind, roots) => {
6488
6518
  const expanded = /* @__PURE__ */ new Set();
6489
6519
  const queue = [];
6490
6520
  const visit = (dir, by, range) => {
@@ -6535,9 +6565,9 @@ function genesisInstalls(root) {
6535
6565
  ...app?.dependencies
6536
6566
  };
6537
6567
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
6538
- walk3("runtime", rootsOf(runtimeDeps, "the app"));
6568
+ walk4("runtime", rootsOf(runtimeDeps, "the app"));
6539
6569
  const top = path30.join(root, "node_modules");
6540
- walk3(
6570
+ walk4(
6541
6571
  "hoisted",
6542
6572
  packagesIn(top).filter((dir) => {
6543
6573
  const name = path30.relative(top, dir).split(path30.sep).join("/");
@@ -6546,7 +6576,7 @@ function genesisInstalls(root) {
6546
6576
  );
6547
6577
  const devRoots = { ...devDeps };
6548
6578
  for (const tool of DEV_TOOLS) if (!(tool in devRoots) && tool in runtimeDeps) devRoots[tool] = runtimeDeps[tool];
6549
- walk3("dev", rootsOf(devRoots, "the app (dev)"));
6579
+ walk4("dev", rootsOf(devRoots, "the app (dev)"));
6550
6580
  for (const [key2, copy] of copies) {
6551
6581
  const kinds = via.get(key2);
6552
6582
  copy.runtime = kinds.has("runtime");
@@ -6810,6 +6840,29 @@ var init_dates = __esm({
6810
6840
  ISO_DAY_CUT = /\.toISOString\(\)\s*\.\s*(?:slice\(\s*0\s*,\s*10\s*\)|substring\(\s*0\s*,\s*10\s*\)|substr\(\s*0\s*,\s*10\s*\)|split\(\s*(["'`])T\1\s*\)\s*\[\s*0\s*\]|split\(\s*(["'`])T\2\s*\)\s*\.\s*at\(\s*0\s*\))/g;
6811
6841
  }
6812
6842
  });
6843
+ function appScripts(root) {
6844
+ const out = [];
6845
+ const walk4 = (dir) => {
6846
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
6847
+ const abs = path30.join(dir, entry.name);
6848
+ if (entry.isDirectory()) {
6849
+ if (!SKIP_DIRS3.has(entry.name)) walk4(abs);
6850
+ } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
6851
+ out.push(path30.relative(root, abs).split(path30.sep).join("/"));
6852
+ }
6853
+ }
6854
+ };
6855
+ walk4(root);
6856
+ return out;
6857
+ }
6858
+ var SKIP_DIRS3, SCRIPT2, MAX_BYTES;
6859
+ var init_app_scripts = __esm({
6860
+ "src/upgrade/app-scripts.ts"() {
6861
+ SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
6862
+ SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
6863
+ MAX_BYTES = 2 * 1024 * 1024;
6864
+ }
6865
+ });
6813
6866
 
6814
6867
  // src/upgrade/bump-core.mjs
6815
6868
  function compareVersions2(a, b) {
@@ -7043,6 +7096,113 @@ var init_bump_core = __esm({
7043
7096
  LEGACY_EXCLUDES = ["@marktiderman/genesis-*", UMBRELLA];
7044
7097
  }
7045
7098
  });
7099
+ function capsOnlyFitTheScreen(tag) {
7100
+ if (OWN_HEIGHT.test(tag) || BOTTOM_SHEET.test(tag)) return false;
7101
+ return [...tag.matchAll(ANY_MAX_H)].every((m) => {
7102
+ const vh = /^\[(\d+(?:\.\d+)?)vh\]$/.exec(m[1]);
7103
+ return vh !== null && Number(vh[1]) >= CHOSEN_CAP_BELOW;
7104
+ });
7105
+ }
7106
+ function rewriteOverlayHeights(text) {
7107
+ return text.replace(OVERLAY_TAG, (tag) => {
7108
+ const drop = capsOnlyFitTheScreen(tag);
7109
+ const next = tag.replace(VH_CLASS, (_all, lead, variants, kind, size) => kind === "max-h" && drop ? lead : `${lead}${variants}${kind}-[${size}dvh]`);
7110
+ if (next === tag) return tag;
7111
+ return next.replace(/\bclassName=(["'])([^"']*)\1/, (_all, quote2, classes) => `className=${quote2}${classes.trim().replace(/\s+/g, " ")}${quote2}`).replace(/\s+className=(["'])\1/, "");
7112
+ });
7113
+ }
7114
+ function inComment(text, at) {
7115
+ const lineStart = text.lastIndexOf("\n", at - 1) + 1;
7116
+ if (/^\s*(?:\/\/|\*)/.test(text.slice(lineStart, at)) || /(?:^|[\s;{}()])\/\/[^"'`]*$/.test(text.slice(lineStart, at))) return true;
7117
+ return text.lastIndexOf("/*", at) > text.lastIndexOf("*/", at);
7118
+ }
7119
+ function rewriteHaptics(text) {
7120
+ const ns = NAMESPACE.exec(text)?.[1];
7121
+ if (!ns) return { text, left: /from\s*["']expo-haptics["']/.test(text) && ANY_CALL.test(text) };
7122
+ const call = (method, argument) => new RegExp(`(?:\\bawait\\s+)?\\b${ns}\\??\\.${method}\\(\\s*${argument}\\s*\\)(?!\\s*\\.(?:then|catch|finally)\\b)`, "g");
7123
+ let used = false;
7124
+ const rewrite = (source, method, argument, kindOf) => source.replace(call(method, argument), (all, ...rest) => {
7125
+ const captured = typeof rest[0] === "string" ? rest[0] : void 0;
7126
+ const offset = rest.find((r) => typeof r === "number");
7127
+ if (inComment(source, offset)) return all;
7128
+ used = true;
7129
+ return `playHaptic(${ns}, "${kindOf(captured)}")`;
7130
+ });
7131
+ let next = rewrite(text, "impactAsync", `(?:${ns}\\.ImpactFeedbackStyle\\.(Light|Medium|Heavy))?`, (style) => (style ?? "Medium").toLowerCase());
7132
+ next = rewrite(next, "selectionAsync", "", () => "select");
7133
+ next = rewrite(next, "notificationAsync", `(?:${ns}\\.NotificationFeedbackType\\.(Success|Warning|Error))?`, (type) => (type ?? "Success").toLowerCase());
7134
+ const left = new RegExp(`\\b${ns}\\??\\.(?:impactAsync|selectionAsync|notificationAsync)\\(`).test(stripComments(next));
7135
+ if (!used) return { text, left };
7136
+ if (!/\bimport\s*\{[^}]*\bplayHaptic\b[^}]*\}/.test(next)) {
7137
+ const existing = new RegExp(`\\bimport\\s*\\{([^}]*)\\}\\s*from\\s*(["'])${NATIVE_UI}\\2`).exec(next);
7138
+ if (existing) next = next.replace(existing[0], existing[0].replace(`{${existing[1]}}`, `{ ${existing[1].trim().replace(/,$/, "")}, playHaptic }`));
7139
+ else next = next.replace(NAMESPACE, (line) => `${line}
7140
+ import { playHaptic } from "${NATIVE_UI}";`);
7141
+ }
7142
+ return { text: next, left };
7143
+ }
7144
+ var IMPORTS_GENESIS_UI, OVERLAY_TAG, VH_CLASS, CHOSEN_CAP_BELOW, OWN_HEIGHT, BOTTOM_SHEET, ANY_MAX_H, overlaysFitThePhone, NATIVE_UI, NAMESPACE, ANY_CALL, hapticsUseGenesis;
7145
+ var init_doctor_rule_codemods = __esm({
7146
+ "src/upgrade/doctor-rule-codemods.ts"() {
7147
+ init_genesis();
7148
+ init_app_scripts();
7149
+ IMPORTS_GENESIS_UI = /from\s*["']@marktiderman\/genesis-ui(?:\/[^"']*)?["']/;
7150
+ OVERLAY_TAG = /<(?:Dialog|AlertDialog|Sheet)Content\b[^>]*>/g;
7151
+ VH_CLASS = /(^|[\s"'`{])((?:[\w-]+:)*)(max-h|min-h|h)-\[(\d+(?:\.\d+)?)vh\]/g;
7152
+ CHOSEN_CAP_BELOW = 80;
7153
+ OWN_HEIGHT = /(?:^|[\s"'`{:])h-[\w[]/;
7154
+ BOTTOM_SHEET = /\bside=(?:\{\s*)?["']bottom["']/;
7155
+ ANY_MAX_H = /(?:^|[\s"'`{:])max-h-([^\s"'`}]+)/g;
7156
+ overlaysFitThePhone = {
7157
+ id: "genesis-ui-overlays-fit-the-phone",
7158
+ package: "@marktiderman/genesis-ui",
7159
+ version: "2.31.0",
7160
+ description: "In Genesis's DialogContent, AlertDialogContent and SheetContent, drops a screen-sized max-h-[\u2026vh] of 80 or more (they cap themselves to the screen) and moves anything else in vh to dvh.",
7161
+ run({ root, dryRun, log }) {
7162
+ const changed = [];
7163
+ for (const rel of appScripts(root).filter((f) => /\.[jt]sx$/.test(f))) {
7164
+ const abs = path30.join(root, rel);
7165
+ const text = readFileSync(abs, "utf8");
7166
+ const next = rewriteOverlayHeights(text);
7167
+ if (next === text) continue;
7168
+ if (!IMPORTS_GENESIS_UI.test(text)) {
7169
+ log(` ${rel}: sizes an overlay in vh but doesn't import genesis-ui; left as it is`);
7170
+ continue;
7171
+ }
7172
+ changed.push(rel);
7173
+ if (!dryRun) writeFileSync(abs, next);
7174
+ }
7175
+ if (changed.length) log(' Remove any doctor.allow entry for ui/overlays-fit-the-phone these files had (stale-exception names it). A long form may want mobileLayout="fullscreen".');
7176
+ return changed;
7177
+ }
7178
+ };
7179
+ NATIVE_UI = "@marktiderman/genesis-ui-native";
7180
+ NAMESPACE = /\bimport\s*\*\s*as\s+(\w+)\s+from\s*(["'])expo-haptics\2;?/;
7181
+ ANY_CALL = /\b(?:impactAsync|selectionAsync|notificationAsync)\s*\(/;
7182
+ hapticsUseGenesis = {
7183
+ id: "genesis-ui-native-haptics",
7184
+ package: NATIVE_UI,
7185
+ version: "3.7.0",
7186
+ description: `Turns direct expo-haptics calls into playHaptic(Haptics, "light"), with Genesis's named kinds.`,
7187
+ run({ root, dryRun, log }) {
7188
+ const changed = [];
7189
+ for (const rel of appScripts(root)) {
7190
+ if (/(?:^|\/)__tests__\/|\.test\.[jt]sx?$/.test(rel)) continue;
7191
+ const abs = path30.join(root, rel);
7192
+ const text = readFileSync(abs, "utf8");
7193
+ if (!text.includes("expo-haptics")) continue;
7194
+ const result = rewriteHaptics(text);
7195
+ if (result.left) log(` ${rel}: has expo-haptics calls this can't rewrite (a Soft or Rigid style, a style in a variable, a chained call, named imports); use useHaptics() there`);
7196
+ if (result.text === text) continue;
7197
+ changed.push(rel);
7198
+ if (!dryRun) writeFileSync(abs, result.text);
7199
+ }
7200
+ if (changed.length) log(" Inside a component, useHaptics() (with expo-haptics passed once as GenesisModules.haptics) is the shorter form.");
7201
+ return changed;
7202
+ }
7203
+ };
7204
+ }
7205
+ });
7046
7206
 
7047
7207
  // src/upgrade/scope-names.ts
7048
7208
  function maskComments(text) {
@@ -7375,25 +7535,71 @@ __export(codemods_exports, {
7375
7535
  CODEMODS: () => CODEMODS,
7376
7536
  appScripts: () => appScripts,
7377
7537
  codemodById: () => codemodById,
7538
+ codemodInstallNote: () => codemodInstallNote,
7378
7539
  codemodsFor: () => codemodsFor,
7540
+ composerBarHasContent: () => composerBarHasContent,
7379
7541
  genesisEslintConfig: () => genesisEslintConfig,
7542
+ rewriteComposerBarEmpty: () => rewriteComposerBarEmpty,
7380
7543
  scopeNeutralNames: () => scopeNeutralNames,
7381
7544
  uncoveredBreaks: () => uncoveredBreaks
7382
7545
  });
7383
- function appScripts(root) {
7384
- const out = [];
7385
- const walk3 = (dir) => {
7386
- for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
7387
- const abs = path30.join(dir, entry.name);
7388
- if (entry.isDirectory()) {
7389
- if (!SKIP_DIRS3.has(entry.name)) walk3(abs);
7390
- } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
7391
- out.push(path30.relative(root, abs).split(path30.sep).join("/"));
7546
+ function rewriteComposerBarEmpty(text) {
7547
+ const open = /<NativeComposerBar\b/g;
7548
+ let out = "";
7549
+ let at = 0;
7550
+ for (let m = open.exec(text); m; m = open.exec(text)) {
7551
+ out += text.slice(at, m.index) + m[0];
7552
+ let i = m.index + m[0].length;
7553
+ let depth = 0;
7554
+ let quote2 = null;
7555
+ for (; i < text.length; i++) {
7556
+ const c = text[i];
7557
+ if (quote2) {
7558
+ if (c === quote2) quote2 = null;
7559
+ } else if (depth === 0 && (c === '"' || c === "'")) {
7560
+ quote2 = c;
7561
+ } else if (c === "{") {
7562
+ depth++;
7563
+ } else if (c === "}") {
7564
+ depth--;
7565
+ } else if (c === ">" && depth === 0) {
7566
+ break;
7567
+ } else if (depth === 0 && /\s/.test(c)) {
7568
+ const attr = /^empty(?![\w-])/.exec(text.slice(i + 1, i + 7));
7569
+ if (attr) {
7570
+ const after = i + 1 + "empty".length;
7571
+ const value = text.startsWith("={", after) ? closingBrace(text, after + 1) : -1;
7572
+ if (value >= 0) {
7573
+ const expr = text.slice(after + 2, value);
7574
+ out += `${c}${expr.trim() === "false" ? "hasContent" : expr.trim() === "true" ? "hasContent={false}" : `hasContent={!(${expr})}`}`;
7575
+ i = value;
7576
+ continue;
7577
+ }
7578
+ if (text[after] !== "=") {
7579
+ out += `${c}hasContent={false}`;
7580
+ i = after - 1;
7581
+ continue;
7582
+ }
7583
+ }
7392
7584
  }
7585
+ out += c;
7393
7586
  }
7394
- };
7395
- walk3(root);
7396
- return out;
7587
+ at = i;
7588
+ open.lastIndex = i;
7589
+ }
7590
+ return out + text.slice(at);
7591
+ }
7592
+ function closingBrace(text, start) {
7593
+ let depth = 0;
7594
+ for (let i = start; i < text.length; i++) {
7595
+ if (text[i] === "{") depth++;
7596
+ else if (text[i] === "}" && --depth === 0) return i;
7597
+ }
7598
+ return -1;
7599
+ }
7600
+ function codemodInstallNote(root, changed, dryRun) {
7601
+ if (dryRun || !changed.includes("package.json")) return null;
7602
+ return `Not installed yet: package.json changed and nothing was installed. Run \`${shellLine(installCommand(detectPackageManager(root)))}\`; until then, what it added isn't there (the lint can't load its config, say).`;
7397
7603
  }
7398
7604
  function codemodById(id, registry = CODEMODS) {
7399
7605
  return registry.find((mod) => mod.id === id);
@@ -7408,17 +7614,19 @@ function uncoveredBreaks(changes, registry = CODEMODS) {
7408
7614
  const [a, b] = bare(v).split(".").map(Number);
7409
7615
  return a === 0 ? `0.${b}` : String(a);
7410
7616
  };
7411
- return changes.filter((c) => major(c.from) !== major(c.to) && codemodsFor([c], registry).length === 0);
7617
+ const startsMajor = (v) => bare(v).split(".").map(Number)[0] === 0 ? bare(v).split(".")[2] === "0" : /^\d+\.0\.0$/.test(bare(v));
7618
+ const covers = (mod, c) => startsMajor(mod.version) && major(mod.version) === major(c.to);
7619
+ return changes.filter((c) => major(c.from) !== major(c.to) && !codemodsFor([c], registry).some((mod) => covers(mod, c)));
7412
7620
  }
7413
- var SKIP_DIRS3, SCRIPT2, MAX_BYTES, scopeNeutralNames, genesisEslintConfig, CODEMODS, bare;
7621
+ var scopeNeutralNames, genesisEslintConfig, composerBarHasContent, CODEMODS, bare;
7414
7622
  var init_codemods = __esm({
7415
7623
  "src/upgrade/codemods.ts"() {
7624
+ init_pm();
7625
+ init_app_scripts();
7416
7626
  init_bump_core();
7627
+ init_doctor_rule_codemods();
7417
7628
  init_eslint_config();
7418
7629
  init_scope_names();
7419
- SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
7420
- SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
7421
- MAX_BYTES = 2 * 1024 * 1024;
7422
7630
  scopeNeutralNames = {
7423
7631
  id: "genesis-core-2-scope-names",
7424
7632
  package: "@marktiderman/genesis-core",
@@ -7483,12 +7691,31 @@ ${manualLines(result.kind, platform).map((l) => ` ${l}`).join("\n")}`);
7483
7691
  json.devDependencies = Object.fromEntries(sorted2 ? dev.sort(([a], [b]) => a.localeCompare(b)) : dev);
7484
7692
  changed.push("package.json");
7485
7693
  if (!dryRun) writeFileSync(pkgFile, `${JSON.stringify(json, null, indent)}${raw.endsWith("\n") ? "\n" : ""}`);
7486
- log(` package.json: added ${TESTING_LIBRARY}@${TESTING_LIBRARY_RANGE} to devDependencies (Genesis's native lint rules use it); install to fetch it.`);
7694
+ log(` package.json: added ${TESTING_LIBRARY}@${TESTING_LIBRARY_RANGE} to devDependencies (Genesis's native lint rules use it).`);
7487
7695
  }
7488
7696
  return changed;
7489
7697
  }
7490
7698
  };
7491
- CODEMODS = [scopeNeutralNames, genesisEslintConfig];
7699
+ composerBarHasContent = {
7700
+ id: "genesis-ui-native-3-8-composer-has-content",
7701
+ package: "@marktiderman/genesis-ui-native",
7702
+ version: "3.8.0",
7703
+ description: "NativeComposerBar's empty is now hasContent, with the opposite sense: empty={false} \u2192 hasContent.",
7704
+ run({ root, dryRun }) {
7705
+ const changed = [];
7706
+ for (const rel of appScripts(root)) {
7707
+ const abs = path30.join(root, rel);
7708
+ const text = readFileSync(abs, "utf8");
7709
+ if (!text.includes("NativeComposerBar")) continue;
7710
+ const next = rewriteComposerBarEmpty(text);
7711
+ if (next === text) continue;
7712
+ changed.push(rel);
7713
+ if (!dryRun) writeFileSync(abs, next);
7714
+ }
7715
+ return changed;
7716
+ }
7717
+ };
7718
+ CODEMODS = [scopeNeutralNames, genesisEslintConfig, overlaysFitThePhone, hapticsUseGenesis, composerBarHasContent];
7492
7719
  bare = (spec) => spec.replace(/^[\^~=]/, "");
7493
7720
  }
7494
7721
  });
@@ -8016,7 +8243,7 @@ var init_primitives = __esm({
8016
8243
  CORE = [
8017
8244
  {
8018
8245
  need: "anything, before building it",
8019
- use: 'search what exists: `genesis features find <term>`, this catalog, and the doctor\'s "Available but unused" list',
8246
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the "Available but unused" list in `genesis doctor --verbose`',
8020
8247
  docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
8021
8248
  from: "genesis-cli"
8022
8249
  },
@@ -8064,6 +8291,58 @@ var init_primitives = __esm({
8064
8291
  read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
8065
8292
  }
8066
8293
  });
8294
+ function appFolderOf(root) {
8295
+ return readGenesisConfig(root)?.appFolder ?? null;
8296
+ }
8297
+ function folderSubstitutions(substitutions, folder) {
8298
+ if (!folder || substitutions?.[APP_FOLDER_PLACEHOLDER]) return substitutions;
8299
+ return { [APP_FOLDER_PLACEHOLDER]: "src", ...substitutions };
8300
+ }
8301
+ function fromRepositoryRoot(entry, folder) {
8302
+ const negated = entry.startsWith("!");
8303
+ const body = negated ? entry.slice(1) : entry;
8304
+ return `${negated ? "!" : ""}${body === folder || body.startsWith(`${folder}/`) ? body : `${folder}/${body}`}`;
8305
+ }
8306
+ function unprefixedTemplatePaths(root, rel, mine, template, folder) {
8307
+ const rendered = renderOwned(rel, template, folder).split("\n");
8308
+ const lines = new Set(mine.split("\n"));
8309
+ const lockfileElsewhere = (line) => {
8310
+ const name = PATH_ITEM.exec(line)?.[3];
8311
+ return name !== void 0 && LOCKFILES2.has(name) && !existsSync(path30.join(root, name));
8312
+ };
8313
+ return template.split("\n").filter((line, i) => line !== rendered[i] && !/^\s*#/.test(line) && lines.has(line) && !lockfileElsewhere(line)).map((line) => line.trim());
8314
+ }
8315
+ function renderOwned(rel, text, folder) {
8316
+ if (!folder || !EAS_WORKFLOW.test(rel)) return text;
8317
+ let inList = false;
8318
+ return text.split("\n").map((line) => {
8319
+ const inline = INLINE_PATHS.exec(line);
8320
+ if (inline) return `${inline[1]}${inline[2].replace(/(["'])([^"']+)\1/g, (_all, quote2, entry) => `${quote2}${fromRepositoryRoot(entry, folder)}${quote2}`)}${inline[3]}`;
8321
+ if (/^\s*paths:\s*$/.test(line)) {
8322
+ inList = true;
8323
+ return line;
8324
+ }
8325
+ if (!inList || /^\s*#/.test(line)) return line;
8326
+ const item = PATH_ITEM.exec(line);
8327
+ if (!item) {
8328
+ inList = false;
8329
+ return line;
8330
+ }
8331
+ return `${item[1]}${item[2]}${fromRepositoryRoot(item[3], folder)}${item[2]}${item[4]}`;
8332
+ }).join("\n");
8333
+ }
8334
+ var LOCKFILES2, EAS_WORKFLOW, PATH_ITEM, INLINE_PATHS, isRepositoryWorkflow;
8335
+ var init_app_folder = __esm({
8336
+ "src/blocks/app-folder.ts"() {
8337
+ init_config();
8338
+ init_init_native();
8339
+ LOCKFILES2 = /* @__PURE__ */ new Set(["pnpm-lock.yaml", "yarn.lock", "package-lock.json", "bun.lock", "bun.lockb"]);
8340
+ EAS_WORKFLOW = /^\.eas\/workflows\/[^/]+\.ya?ml$/;
8341
+ PATH_ITEM = /^(\s*-\s*)(["']?)([^"'#\s]+)\2(\s*(?:#.*)?)$/;
8342
+ INLINE_PATHS = /^(\s*(?:#\s*)?paths:\s*\[)(.*)(\]\s*)$/;
8343
+ isRepositoryWorkflow = (rel) => rel.startsWith(".github/workflows/");
8344
+ }
8345
+ });
8067
8346
  function copyOwned(root, lock, write, dryRun = false) {
8068
8347
  const existing = readApp(root, write.path);
8069
8348
  const record = () => {
@@ -8133,7 +8412,7 @@ function refreshOwned(root, lock, input, options = {}) {
8133
8412
  const theirsSha = sha256(input.theirs);
8134
8413
  if (theirsSha === entry.sha256) return { path: input.path, outcome: "unchanged" };
8135
8414
  const record = (sha) => {
8136
- const { pending: _settled, deleted: _back, ...rest } = entry;
8415
+ const { pending: _settled, pendingMine: _was, deleted: _back, ...rest } = entry;
8137
8416
  lock.files[input.path] = { ...rest, sha256: sha, ...input.version ? { version: input.version } : {} };
8138
8417
  };
8139
8418
  if (mine === null) {
@@ -8148,25 +8427,25 @@ function refreshOwned(root, lock, input, options = {}) {
8148
8427
  const next = `${input.path}.genesis-next`;
8149
8428
  const existingNext = readApp(root, next);
8150
8429
  if (entry.pending === theirsSha) {
8151
- if (existingNext === null) {
8152
- const { pending: _done, ...rest } = entry;
8430
+ if (existingNext !== null) return { path: input.path, outcome: "kept-mine", detail: `waiting for you: resolve ${next} into your file, then delete it` };
8431
+ if (mineSha !== entry.pendingMine) {
8432
+ const { pending: _done, pendingMine: _was, ...rest } = entry;
8153
8433
  lock.files[input.path] = { ...rest, sha256: theirsSha, ...input.version ? { version: input.version } : {} };
8154
- return { path: input.path, outcome: "resolved", detail: "your file is kept as the resolution of the last upgrade" };
8434
+ return { path: input.path, outcome: "resolved", detail: `your file is kept as the resolution of the last upgrade because it changed since; if that was unrelated, compare with ${entry.source}` };
8155
8435
  }
8156
- return { path: input.path, outcome: "kept-mine", detail: `waiting for you: resolve ${next} into your file, then delete it` };
8157
8436
  }
8158
8437
  const writeNext = (text) => {
8159
8438
  if (existingNext !== null && existingNext !== text) return `${next} is already there with other text; resolve it (and delete it) first`;
8160
8439
  write(next, text);
8161
- lock.files[input.path] = { ...entry, pending: theirsSha };
8440
+ lock.files[input.path] = { ...entry, pending: theirsSha, pendingMine: mineSha };
8162
8441
  return null;
8163
8442
  };
8164
- if (!options.keepMine && input.base !== null && sha256(input.base) === entry.sha256) {
8443
+ if (!options.keepMine && input.base !== null) {
8165
8444
  const merged = mergeThreeWay(mine, input.base, input.theirs);
8166
8445
  if (merged?.clean) {
8167
8446
  write(input.path, merged.text);
8168
8447
  record(theirsSha);
8169
- return { path: input.path, outcome: "merged", detail: "your edits kept on top of the new version" };
8448
+ return { path: input.path, outcome: "merged", detail: input.baseIsPending ? `merged on the version the last .genesis-next held, because this file changed since; if that was unrelated, compare with ${entry.source}` : "your edits kept on top of the new version" };
8170
8449
  }
8171
8450
  if (merged) {
8172
8451
  const blocked2 = writeNext(merged.text);
@@ -8437,6 +8716,11 @@ async function checkLockFiles(ctx) {
8437
8716
  home = databaseElsewhere(ctx.root);
8438
8717
  } catch {
8439
8718
  }
8719
+ let appFolder = null;
8720
+ try {
8721
+ appFolder = appFolderOf(ctx.root);
8722
+ } catch {
8723
+ }
8440
8724
  const elsewhere = home ? Object.keys(lock.files).filter(isSupabasePath) : [];
8441
8725
  if (home && elsewhere.length) {
8442
8726
  ctx.report({
@@ -8472,6 +8756,7 @@ async function checkLockFiles(ctx) {
8472
8756
  }
8473
8757
  if (text === null) {
8474
8758
  if (entry.deleted) continue;
8759
+ if (appFolder && isRepositoryWorkflow(rel)) continue;
8475
8760
  ctx.report({
8476
8761
  rule: "lock-files",
8477
8762
  level: "warn",
@@ -8496,6 +8781,7 @@ async function checkLockFiles(ctx) {
8496
8781
  }
8497
8782
  var init_lock_files = __esm({
8498
8783
  "src/doctor/lock-files.ts"() {
8784
+ init_app_folder();
8499
8785
  init_discover();
8500
8786
  init_files();
8501
8787
  init_lock();
@@ -8562,11 +8848,407 @@ function checkEslintConfig(ctx) {
8562
8848
  subject: TESTING_LIBRARY,
8563
8849
  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`
8564
8850
  });
8851
+ } else if (!findPackageDir(ctx.root, TESTING_LIBRARY)) {
8852
+ ctx.report({
8853
+ rule: "genesis-eslint-config",
8854
+ level: "warn",
8855
+ file: "package.json",
8856
+ subject: TESTING_LIBRARY,
8857
+ 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)))}`
8858
+ });
8565
8859
  }
8566
8860
  }
8567
8861
  var init_eslint_config2 = __esm({
8568
8862
  "src/doctor/eslint-config.ts"() {
8863
+ init_pm();
8569
8864
  init_eslint_config();
8865
+ init_genesis();
8866
+ }
8867
+ });
8868
+
8869
+ // src/figma/routes.ts
8870
+ var routes_exports = {};
8871
+ __export(routes_exports, {
8872
+ FIGMA_API: () => FIGMA_API,
8873
+ FIGMA_TIMEOUT_MS: () => FIGMA_TIMEOUT_MS,
8874
+ FigmaConfigError: () => FigmaConfigError,
8875
+ appDynamicNavTargets: () => appDynamicNavTargets,
8876
+ appNavTargets: () => appNavTargets,
8877
+ appRoutes: () => appRoutes,
8878
+ checkFigmaRoutes: () => checkFigmaRoutes,
8879
+ compare: () => compare,
8880
+ coverageFindings: () => coverageFindings,
8881
+ destinations: () => destinations,
8882
+ dynamicNavTargets: () => dynamicNavTargets,
8883
+ expoRoot: () => expoRoot,
8884
+ figmaIdOf: () => figmaIdOf,
8885
+ formatCoverage: () => formatCoverage,
8886
+ navTargets: () => navTargets,
8887
+ readFigma: () => readFigma,
8888
+ readFigmaConfig: () => readFigmaConfig,
8889
+ routeMatches: () => routeMatches,
8890
+ validateFigmaConfig: () => validateFigmaConfig
8891
+ });
8892
+ function validateFigmaConfig(raw, source = "genesis.config.json") {
8893
+ const obj = raw;
8894
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new FigmaConfigError(`${source}: figma must be an object`);
8895
+ 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)`);
8896
+ const pages = obj.pages;
8897
+ if (!pages || typeof pages !== "object" || Array.isArray(pages)) throw new FigmaConfigError(`${source}: figma.pages must be { "web"?: "<page>", "native"?: "<page>" }`);
8898
+ const out = {};
8899
+ for (const [k, v] of Object.entries(pages)) {
8900
+ if (k !== "web" && k !== "native") throw new FigmaConfigError(`${source}: figma.pages.${k}: only "web" and "native"`);
8901
+ if (typeof v !== "string" || !v) throw new FigmaConfigError(`${source}: figma.pages.${k} must be a page name`);
8902
+ out[k] = v;
8903
+ }
8904
+ if (!out.web && !out.native) throw new FigmaConfigError(`${source}: figma.pages needs "web" or "native"`);
8905
+ if (obj.proposalsPage !== void 0 && (typeof obj.proposalsPage !== "string" || !obj.proposalsPage)) throw new FigmaConfigError(`${source}: figma.proposalsPage must be a page name`);
8906
+ return { file: obj.file, pages: out, proposalsPage: obj.proposalsPage ?? "Proposals" };
8907
+ }
8908
+ function readFigmaConfig(root) {
8909
+ const file = path30.join(root, "genesis.config.json");
8910
+ if (!existsSync(file)) return null;
8911
+ let raw;
8912
+ try {
8913
+ raw = JSON.parse(readFileSync(file, "utf8"));
8914
+ } catch (err) {
8915
+ throw new FigmaConfigError(`${file} isn't valid JSON: ${err.message}`);
8916
+ }
8917
+ return raw?.figma === void 0 ? null : validateFigmaConfig(raw.figma, file);
8918
+ }
8919
+ function walk2(dir, out = []) {
8920
+ if (!existsSync(dir)) return out;
8921
+ for (const name of readdirSync(dir).sort()) {
8922
+ if (name === "node_modules" || name.startsWith(".")) continue;
8923
+ const full = path30.join(dir, name);
8924
+ if (statSync(full).isDirectory()) walk2(full, out);
8925
+ else if (CODE.test(name) && !/\.(?:test|spec|d)\.[jt]sx?$/.test(name)) out.push(full);
8926
+ }
8927
+ return out;
8928
+ }
8929
+ function figmaIdOf(code) {
8930
+ for (const line of code.split("\n").slice(0, 5)) {
8931
+ const m = FIGMA_ID.exec(line);
8932
+ if (m) return m[1].replace("-", ":");
8933
+ }
8934
+ return void 0;
8935
+ }
8936
+ function tanstackSegments(stem) {
8937
+ const out = [];
8938
+ let cur = "";
8939
+ let depth = 0;
8940
+ for (const ch of stem) {
8941
+ if (ch === "{") depth++;
8942
+ if (ch === "}") depth--;
8943
+ if (ch === "." && depth === 0) {
8944
+ out.push(cur);
8945
+ cur = "";
8946
+ } else cur += ch;
8947
+ }
8948
+ out.push(cur);
8949
+ return out;
8950
+ }
8951
+ function expoRoot(root) {
8952
+ for (const dir of ["src/app", "app"]) if (existsSync(path30.join(root, dir))) return dir;
8953
+ return null;
8954
+ }
8955
+ function appRoutes(root) {
8956
+ const out = [];
8957
+ const rel = (f) => path30.relative(root, f).split(path30.sep).join("/");
8958
+ const expo = expoRoot(root);
8959
+ if (expo) {
8960
+ for (const f of walk2(path30.join(root, expo))) {
8961
+ const parts = path30.relative(path30.join(root, expo), f).split(path30.sep);
8962
+ const stem = parts.pop().replace(CODE, "");
8963
+ if (stem === "_layout" || stem.startsWith("+")) continue;
8964
+ if (stem !== "index") parts.push(stem);
8965
+ out.push(withId({ route: parts.join("/") || "index", platform: "native", file: rel(f) }, f));
8966
+ }
8967
+ }
8968
+ const tanstack = path30.join(root, "src/routes");
8969
+ if (existsSync(tanstack)) {
8970
+ const seen = /* @__PURE__ */ new Set();
8971
+ for (const f of walk2(tanstack)) {
8972
+ const parts = path30.relative(tanstack, f).split(path30.sep);
8973
+ const stem = parts.pop().replace(CODE, "").replace(/\.lazy$/, "");
8974
+ if (stem === "__root" || stem === "route" || stem.startsWith("-") || parts.some((p) => p.startsWith("-"))) continue;
8975
+ const segs = [...parts.flatMap(tanstackSegments), ...tanstackSegments(stem)];
8976
+ if (segs.at(-1) === "index") segs.pop();
8977
+ const route = segs.join("/") || "index";
8978
+ if (seen.has(route)) continue;
8979
+ seen.add(route);
8980
+ out.push(withId({ route, platform: "web", file: rel(f) }, f));
8981
+ }
8982
+ }
8983
+ return out;
8984
+ }
8985
+ function withId(r, file) {
8986
+ const id = figmaIdOf(readFileSync(file, "utf8"));
8987
+ return id ? { ...r, figmaId: id } : r;
8988
+ }
8989
+ function urlSegments(route) {
8990
+ 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);
8991
+ }
8992
+ function routeMatches(route, target) {
8993
+ const pattern = urlSegments(route);
8994
+ const url = target.split(/[?#]/)[0].split("/").filter(Boolean);
8995
+ if (/(?:^|\/)\$$/.test(route)) {
8996
+ const head = pattern.slice(0, -1);
8997
+ return url.length >= head.length && head.every((p, i) => p === "*" || p === url[i]);
8998
+ }
8999
+ const go = (i, j) => {
9000
+ if (i === pattern.length) return j === url.length;
9001
+ const p = pattern[i];
9002
+ if (p === "?") return go(i + 1, j) || j < url.length && go(i + 1, j + 1);
9003
+ if (j === url.length) return false;
9004
+ if (p === "**") {
9005
+ for (let k = j + 1; k <= url.length; k++) if (go(i + 1, k)) return true;
9006
+ return false;
9007
+ }
9008
+ return (p === "*" || p === url[j]) && go(i + 1, j + 1);
9009
+ };
9010
+ return go(0, 0);
9011
+ }
9012
+ function sameScreen(a, b) {
9013
+ return a.replace(/^\/+/, "") === b.replace(/^\/+/, "") || urlSegments(a).join("/") === urlSegments(b).join("/");
9014
+ }
9015
+ function dynamicNavTargets(code, file) {
9016
+ const out = [];
9017
+ for (const re of DYNAMIC_PATTERNS) {
9018
+ for (const m of code.matchAll(re)) {
9019
+ const raw = m[1].trim();
9020
+ out.push({ file, line: code.slice(0, m.index).split("\n").length, target: raw.length > 60 ? `${raw.slice(0, 57)}...` : raw });
9021
+ }
9022
+ }
9023
+ return out.sort((a, b) => a.line - b.line);
9024
+ }
9025
+ function navTargets(code, file) {
9026
+ const out = [];
9027
+ for (const re of NAV_PATTERNS) {
9028
+ for (const m of code.matchAll(re)) {
9029
+ const target = m[1] ?? m[2] ?? m[3];
9030
+ if (target === void 0 || /^[a-z]+:/i.test(target) || target.startsWith("#") || target.startsWith(".")) continue;
9031
+ out.push({ file, line: code.slice(0, m.index).split("\n").length, target });
9032
+ }
9033
+ }
9034
+ return out.sort((a, b) => a.line - b.line);
9035
+ }
9036
+ function appNavTargets(root) {
9037
+ const files = [.../* @__PURE__ */ new Set([...walk2(path30.join(root, "src")), ...walk2(path30.join(root, "app"))])];
9038
+ return files.flatMap((f) => navTargets(readFileSync(f, "utf8"), path30.relative(root, f).split(path30.sep).join("/")));
9039
+ }
9040
+ function appDynamicNavTargets(root) {
9041
+ const files = [.../* @__PURE__ */ new Set([...walk2(path30.join(root, "src")), ...walk2(path30.join(root, "app"))])];
9042
+ return files.flatMap((f) => dynamicNavTargets(readFileSync(f, "utf8"), path30.relative(root, f).split(path30.sep).join("/")));
9043
+ }
9044
+ function splitName(name) {
9045
+ const i = name.indexOf(" \xB7 ");
9046
+ return i < 0 ? { route: name.trim() } : { route: name.slice(0, i).trim(), state: name.slice(i + 3).trim() };
9047
+ }
9048
+ function destinations(node, out = /* @__PURE__ */ new Set()) {
9049
+ if (node.transitionNodeID) out.add(node.transitionNodeID);
9050
+ for (const i of node.interactions ?? []) {
9051
+ for (const a of i.actions ?? []) if (a?.type === "NODE" && a.destinationId && a.navigation !== "CHANGE_TO") out.add(a.destinationId);
9052
+ }
9053
+ for (const c of node.children ?? []) destinations(c, out);
9054
+ return out;
9055
+ }
9056
+ async function readFigma(config, token, fetchImpl = fetch, timeoutMs = FIGMA_TIMEOUT_MS) {
9057
+ const get2 = async (p) => {
9058
+ const where2 = p.split("?")[0];
9059
+ try {
9060
+ const res = await fetchImpl(`${FIGMA_API}${p}`, { headers: { "X-Figma-Token": token }, signal: AbortSignal.timeout(timeoutMs) });
9061
+ 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)" : ""}`);
9062
+ return await res.json();
9063
+ } catch (err) {
9064
+ const name = err?.name;
9065
+ if (name === "TimeoutError" || name === "AbortError") throw new Error(`Figma API ${where2} didn't answer within ${Math.round(timeoutMs / 1e3)}s`);
9066
+ throw err;
9067
+ }
9068
+ };
9069
+ const nodes = async (ids, depth) => {
9070
+ const out = [];
9071
+ for (let i = 0; i < ids.length; i += 50) {
9072
+ const chunk = ids.slice(i, i + 50);
9073
+ const body = await get2(`/v1/files/${config.file}/nodes?ids=${encodeURIComponent(chunk.join(","))}${depth ? `&depth=${depth}` : ""}`);
9074
+ for (const id of chunk) {
9075
+ const doc = body.nodes[id]?.document;
9076
+ if (doc) out.push(doc);
9077
+ }
9078
+ }
9079
+ return out;
9080
+ };
9081
+ const file = await get2(`/v1/files/${config.file}?depth=2`);
9082
+ const canvases = file.document.children ?? [];
9083
+ const wanted = /* @__PURE__ */ new Set([...Object.values(config.pages), config.proposalsPage]);
9084
+ const frames = [];
9085
+ const sections = [];
9086
+ for (const page of canvases) {
9087
+ if (!wanted.has(page.name)) continue;
9088
+ for (const child of page.children ?? []) {
9089
+ if (child.type === "SECTION") sections.push({ id: child.id, name: child.name, page: page.name });
9090
+ else if (SCREEN_TYPES.has(child.type)) frames.push({ id: child.id, name: child.name, page: page.name, ...splitName(child.name) });
9091
+ }
9092
+ }
9093
+ for (const s of await nodes(sections.map((x) => x.id), 1)) {
9094
+ const section2 = sections.find((x) => x.id === s.id);
9095
+ for (const child of s.children ?? []) {
9096
+ if (SCREEN_TYPES.has(child.type)) frames.push({ id: child.id, name: child.name, page: section2.page, section: section2.name, ...splitName(child.name) });
9097
+ }
9098
+ }
9099
+ const hotspots = [];
9100
+ for (const tree of await nodes(frames.filter((f) => f.page !== config.proposalsPage).map((f) => f.id))) {
9101
+ for (const to of destinations(tree)) if (to !== tree.id) hotspots.push({ from: tree.id, to });
9102
+ }
9103
+ return { pages: canvases.map((p) => p.name), frames, hotspots };
9104
+ }
9105
+ function compare(config, routes, targets, figma, dynamicTargets = []) {
9106
+ const platformOf = (page) => config.pages.web === page ? "web" : config.pages.native === page ? "native" : void 0;
9107
+ const routeFrames = figma.frames.filter((f) => platformOf(f.page));
9108
+ const framesFor = (r) => routeFrames.filter((f) => platformOf(f.page) === r.platform && (sameScreen(f.route, r.route) || r.route === "index" && f.route === "/"));
9109
+ const byId = new Map(figma.frames.map((f) => [f.id, f]));
9110
+ const framed = new Set(routes.flatMap((r) => framesFor(r).map((f) => f.id)));
9111
+ const covered = routes.filter((r) => framesFor(r).length > 0);
9112
+ const routesWithoutFrame = routes.filter((r) => framesFor(r).length === 0);
9113
+ const framesWithoutRoute = routeFrames.filter((f) => !framed.has(f.id));
9114
+ const proposals = {};
9115
+ for (const f of figma.frames.filter((x) => x.page === config.proposalsPage)) (proposals[f.section ?? "(no section)"] ??= []).push(f);
9116
+ const missingHotspots = [];
9117
+ const seen = /* @__PURE__ */ new Set();
9118
+ for (const t of targets) {
9119
+ const source = routes.find((r) => r.file === t.file);
9120
+ if (!source) continue;
9121
+ const from = framesFor(source);
9122
+ if (!from.length) continue;
9123
+ const dest = routes.find((r) => r.platform === source.platform && routeMatches(r.route, t.target));
9124
+ if (!dest || dest === source) continue;
9125
+ const key2 = `${source.route}\u2192${dest.route}`;
9126
+ if (seen.has(key2)) continue;
9127
+ seen.add(key2);
9128
+ const to = new Set(framesFor(dest).map((f) => f.id));
9129
+ const linked = figma.hotspots.some((h) => from.some((f) => f.id === h.from) && to.has(h.to));
9130
+ if (!linked) missingHotspots.push({ ...t, from: source.route, to: dest.route, targetHasFrame: to.size > 0 });
9131
+ }
9132
+ const deadHotspots = [];
9133
+ for (const h of figma.hotspots) {
9134
+ const from = byId.get(h.from);
9135
+ const to = byId.get(h.to);
9136
+ if (from && to && platformOf(to.page) && !framed.has(to.id)) deadHotspots.push({ from, to });
9137
+ }
9138
+ 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) }));
9139
+ const wantedPages = [...Object.values(config.pages), config.proposalsPage];
9140
+ const missingPages = wantedPages.filter((p) => !figma.pages.includes(p));
9141
+ const uncheckedNavigation = dynamicTargets.filter((t) => routes.some((r) => r.file === t.file));
9142
+ return {
9143
+ file: config.file,
9144
+ summary: {
9145
+ routes: routes.length,
9146
+ frames: routeFrames.length,
9147
+ covered: covered.length,
9148
+ coveredPercent: routes.length ? Math.round(covered.length / routes.length * 100) : 100,
9149
+ hotspots: figma.hotspots.length,
9150
+ missing: missingPages.length + routesWithoutFrame.length + missingHotspots.length + idMismatches.length
9151
+ },
9152
+ missingPages,
9153
+ routesWithoutFrame,
9154
+ framesWithoutRoute,
9155
+ proposals,
9156
+ missingHotspots,
9157
+ deadHotspots,
9158
+ idMismatches,
9159
+ uncheckedNavigation
9160
+ };
9161
+ }
9162
+ async function checkFigmaRoutes(options) {
9163
+ const config = options.config ?? readFigmaConfig(options.root);
9164
+ if (!config) throw new FigmaConfigError(`no "figma" block in ${path30.join(options.root, "genesis.config.json")}`);
9165
+ const token = options.token ?? process.env.FIGMA_ACCESS_TOKEN;
9166
+ if (!token) throw new FigmaConfigError("FIGMA_ACCESS_TOKEN isn't set");
9167
+ const figma = await readFigma(config, token, options.fetch);
9168
+ return compare(config, appRoutes(options.root), appNavTargets(options.root), figma, appDynamicNavTargets(options.root));
9169
+ }
9170
+ function formatCoverage(r) {
9171
+ const s = r.summary;
9172
+ const lines = [`Figma route coverage (file ${r.file}): ${s.routes} routes, ${s.frames} frames, ${s.covered} covered (${s.coveredPercent}%), ${s.hotspots} hotspots, ${s.missing} missing`];
9173
+ const table = (title, head, rows) => {
9174
+ if (!rows.length) return;
9175
+ const widths = head.map((h, i) => Math.max(h.length, ...rows.map((row) => row[i].length)));
9176
+ const fmt = (row) => ` ${row.map((c, i) => c.padEnd(widths[i])).join(" ")}`.trimEnd();
9177
+ lines.push("", `${title} (${rows.length})`, fmt(head), fmt(widths.map((w) => "-".repeat(w))), ...rows.map(fmt));
9178
+ };
9179
+ if (r.missingPages.length) lines.push("", `Pages not in the file: ${r.missingPages.join(", ")}`);
9180
+ table("Routes with no frame", ["platform", "route", "file"], r.routesWithoutFrame.map((x) => [x.platform, x.route, x.file]));
9181
+ table("Frames with no route (move to Proposals, or add the route)", ["page", "frame", "id"], r.framesWithoutRoute.map((f) => [f.page, f.name, f.id]));
9182
+ table("Navigation with no hotspot", ["from", "to", "at"], r.missingHotspots.map((m) => [m.from, `${m.to}${m.targetHasFrame ? "" : " (no frame)"}`, `${m.file}:${m.line}`]));
9183
+ table("Hotspots to a frame with no route", ["from", "to"], r.deadHotspots.map((d) => [d.from.name, d.to.name]));
9184
+ table("figma: ids that don't match the route's frame", ["route", "comment", "frames"], r.idMismatches.map((m) => [m.route, m.figmaId, m.frames.join(", ") || "none"]));
9185
+ table("Navigation not checked (not a string literal)", ["at", "target"], r.uncheckedNavigation.map((t) => [`${t.file}:${t.line}`, t.target]));
9186
+ table("Proposals", ["section", "frame", "id"], Object.entries(r.proposals).flatMap(([sec, fs2]) => fs2.map((f) => [sec, f.name, f.id])));
9187
+ return lines.join("\n");
9188
+ }
9189
+ function coverageFindings(r, strict) {
9190
+ const gap = strict ? "warn" : "info";
9191
+ return [
9192
+ ...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 })),
9193
+ ...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 })),
9194
+ ...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 })),
9195
+ ...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 })),
9196
+ ...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 })),
9197
+ ...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 })),
9198
+ ...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 }))
9199
+ ];
9200
+ }
9201
+ var FigmaConfigError, CODE, FIGMA_ID, STR, NAV_PATTERNS, DYNAMIC_PATTERNS, FIGMA_API, FIGMA_TIMEOUT_MS, SCREEN_TYPES;
9202
+ var init_routes2 = __esm({
9203
+ "src/figma/routes.ts"() {
9204
+ FigmaConfigError = class extends Error {
9205
+ };
9206
+ CODE = /\.(?:tsx|ts|jsx|js)$/;
9207
+ FIGMA_ID = /^\s*\/\/\s*figma:\s*(\d+[:-]\d+)\s*$/;
9208
+ STR = String.raw`(?:"([^"\n]*)"|'([^'\n]*)'|` + "`([^`$\\n]*)`)";
9209
+ NAV_PATTERNS = [
9210
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*` + STR, "g"),
9211
+ new RegExp(String.raw`<Link\b[^>]*?\b(?:href|to)=\{?\s*` + STR, "g"),
9212
+ new RegExp(String.raw`\bnavigate\(\s*\{[^}]*?\bto\s*:\s*` + STR, "g")
9213
+ ];
9214
+ DYNAMIC_PATTERNS = [
9215
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
9216
+ new RegExp(String.raw`<Link\b[^>]*?\b(?:href|to)=\{\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
9217
+ new RegExp(String.raw`\bnavigate\(\s*\{[^}]*?\bto\s*:\s*` + "(`[^`\\n]*\\$\\{[^`\\n]*`)", "g"),
9218
+ new RegExp(String.raw`\brouter\.(?:push|replace|navigate)\(\s*(\{[^}\n]*?\bpathname\b[^}\n]*\}?)`, "g"),
9219
+ new RegExp(String.raw`<Link\b[^>]*?\bhref=\{(\{[^}\n]*?\bpathname\b[^}\n]*\}?)`, "g")
9220
+ ];
9221
+ FIGMA_API = "https://api.figma.com";
9222
+ FIGMA_TIMEOUT_MS = 3e4;
9223
+ SCREEN_TYPES = /* @__PURE__ */ new Set(["FRAME", "COMPONENT", "COMPONENT_SET", "INSTANCE"]);
9224
+ }
9225
+ });
9226
+
9227
+ // src/doctor/figma-routes.ts
9228
+ async function checkFigmaRoutesRule(ctx) {
9229
+ let config;
9230
+ try {
9231
+ config = readFigmaConfig(ctx.root);
9232
+ } catch (err) {
9233
+ if (!(err instanceof FigmaConfigError)) throw err;
9234
+ ctx.report({ rule: "figma-routes", level: "warn", file: "genesis.config.json", message: err.message });
9235
+ return;
9236
+ }
9237
+ if (!config) return;
9238
+ if (!process.env.FIGMA_ACCESS_TOKEN) {
9239
+ 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)" });
9240
+ return;
9241
+ }
9242
+ try {
9243
+ const report = await checkFigmaRoutes({ root: ctx.root, config });
9244
+ for (const f of coverageFindings(report, ctx.strict ?? false)) ctx.report({ rule: "figma-routes", ...f });
9245
+ } catch (err) {
9246
+ ctx.report({ rule: "figma-routes", level: "info", file: "genesis.config.json", message: `skipped: ${err.message}` });
9247
+ }
9248
+ }
9249
+ var init_figma_routes = __esm({
9250
+ "src/doctor/figma-routes.ts"() {
9251
+ init_routes2();
8570
9252
  }
8571
9253
  });
8572
9254
 
@@ -8634,7 +9316,7 @@ async function runDoctor(options = {}) {
8634
9316
  }
8635
9317
  const raw = [];
8636
9318
  const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, ...options.strict ? { strict: true } : {}, report: (f) => raw.push(f) };
8637
- for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
9319
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true, figma: options.figma ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
8638
9320
  try {
8639
9321
  await plugin.check(ctx);
8640
9322
  } catch (err) {
@@ -8722,6 +9404,7 @@ function builtinChecks(config, options = {}) {
8722
9404
  { name: "database-elsewhere", check: checkDatabaseHome },
8723
9405
  { name: "eslint-config", check: checkEslintConfig },
8724
9406
  ...(config.packs ?? []).map((p) => packs[p]),
9407
+ ...options.figma !== false ? [{ name: "figma-routes", check: checkFigmaRoutesRule }] : [],
8725
9408
  ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
8726
9409
  ];
8727
9410
  }
@@ -8774,7 +9457,7 @@ function applyConfig(raw, config, packageIds) {
8774
9457
  }
8775
9458
  return out.sort((x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule));
8776
9459
  }
8777
- function formatReport(result) {
9460
+ function formatReport(result, options = {}) {
8778
9461
  const g = result.genesis;
8779
9462
  const lines = [
8780
9463
  `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"}`
@@ -8782,7 +9465,7 @@ function formatReport(result) {
8782
9465
  for (const f of result.findings) {
8783
9466
  lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
8784
9467
  }
8785
- lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
9468
+ 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)`);
8786
9469
  lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis catalog`);
8787
9470
  const info = result.infos ? `, ${result.infos} info` : "";
8788
9471
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
@@ -8838,6 +9521,7 @@ var init_doctor = __esm({
8838
9521
  init_lock_files();
8839
9522
  init_database2();
8840
9523
  init_eslint_config2();
9524
+ init_figma_routes();
8841
9525
  init_config();
8842
9526
  init_genesis();
8843
9527
  init_patterns();
@@ -9304,8 +9988,8 @@ function routeTags(source) {
9304
9988
  }
9305
9989
  function wireStudioRoute(source, route, pageImportPath) {
9306
9990
  const tags = routeTags(source);
9307
- const relative17 = route.replace(/^\//, "");
9308
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative17.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
9991
+ const relative18 = route.replace(/^\//, "");
9992
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative18.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
9309
9993
  if (existing) {
9310
9994
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
9311
9995
  }
@@ -9313,17 +9997,17 @@ function wireStudioRoute(source, route, pageImportPath) {
9313
9997
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
9314
9998
  if (roots.length !== 1) {
9315
9999
  return {
9316
- skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative17}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
10000
+ skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative18}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
9317
10001
  };
9318
10002
  }
9319
10003
  const layout = roots[0];
9320
10004
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
9321
- if (base && !relative17.startsWith(`${base}/`)) {
10005
+ if (base && !relative18.startsWith(`${base}/`)) {
9322
10006
  return {
9323
10007
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
9324
10008
  };
9325
10009
  }
9326
- const childPath = base ? relative17.slice(base.length + 1) : relative17;
10010
+ const childPath = base ? relative18.slice(base.length + 1) : relative18;
9327
10011
  const guard = GUARD.exec(source)?.[1];
9328
10012
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
9329
10013
  const before = source.slice(0, layout.close);
@@ -9833,7 +10517,7 @@ export default function Screen() {
9833
10517
  }
9834
10518
  `;
9835
10519
  }
9836
- var init_routes2 = __esm({
10520
+ var init_routes3 = __esm({
9837
10521
  "src/blocks/routes.ts"() {
9838
10522
  init_files();
9839
10523
  }
@@ -10155,7 +10839,7 @@ var init_add = __esm({
10155
10839
  init_owned();
10156
10840
  init_pm();
10157
10841
  init_registry_edit();
10158
- init_routes2();
10842
+ init_routes3();
10159
10843
  SILENT = { info() {
10160
10844
  }, warn() {
10161
10845
  } };
@@ -10351,11 +11035,120 @@ var init_migrate = __esm({
10351
11035
  init_notification_types();
10352
11036
  }
10353
11037
  });
10354
- function walk2(dir, rel = "", out = /* @__PURE__ */ new Map()) {
11038
+ async function fetchChangelog(directory) {
11039
+ try {
11040
+ const res = await fetch(`https://raw.githubusercontent.com/${REPOSITORY}/main/${directory}/CHANGELOG.md`, { signal: AbortSignal.timeout(5e3) });
11041
+ return res.ok ? await res.text() : null;
11042
+ } catch {
11043
+ return null;
11044
+ }
11045
+ }
11046
+ function breakingEntries(changelog, from, to) {
11047
+ const low = bare2(from);
11048
+ const high = bare2(to);
11049
+ const heading = low.startsWith("0.") ? /^### (?:Major|Minor) Changes\s*$/ : /^### Major Changes\s*$/;
11050
+ const parts = changelog.split(/^## (?=\d)/m).slice(1);
11051
+ let matched = false;
11052
+ const entries = [];
11053
+ for (const part of parts) {
11054
+ const version = part.split("\n", 1)[0].trim();
11055
+ if (compareVersions2(version, low) <= 0 || compareVersions2(version, high) > 0) continue;
11056
+ if (compareVersions2(version, high) === 0) matched = true;
11057
+ let inside3 = false;
11058
+ for (const line of part.split("\n")) {
11059
+ if (line.startsWith("### ")) inside3 = heading.test(line);
11060
+ else if (inside3 && line.startsWith("- ")) entries.push(firstLine(line));
11061
+ }
11062
+ }
11063
+ return matched ? entries : null;
11064
+ }
11065
+ function repositoryDirectory(root, name) {
11066
+ const dir = packageDir(root, name);
11067
+ if (!dir) return null;
11068
+ try {
11069
+ const { repository } = JSON.parse(readFileSync(path30.join(dir, "package.json"), "utf8"));
11070
+ return typeof repository?.directory === "string" ? repository.directory : null;
11071
+ } catch {
11072
+ return null;
11073
+ }
11074
+ }
11075
+ async function breakLines(root, breaks, reader) {
11076
+ const lowest = /* @__PURE__ */ new Map();
11077
+ for (const b of breaks) {
11078
+ const key2 = `${b.name}@${b.to}`;
11079
+ const held = lowest.get(key2);
11080
+ if (!held || compareVersions2(bare2(b.from), bare2(held.from)) < 0) lowest.set(key2, b);
11081
+ }
11082
+ const lines = [];
11083
+ for (const b of lowest.values()) {
11084
+ const directory = repositoryDirectory(root, b.name);
11085
+ const url = directory ? `https://github.com/${REPOSITORY}/blob/main/${directory}/CHANGELOG.md#${bare2(b.to).replace(/\D/g, "")}` : `https://www.npmjs.com/package/${b.name}`;
11086
+ const head = `- \`${b.name}\` ${b.from} \u2192 ${b.to}`;
11087
+ const text = directory && reader.changelog ? await reader.changelog(directory) : null;
11088
+ const entries = text === null ? null : breakingEntries(text, b.from, b.to);
11089
+ if (entries === null) lines.push(`${head}: read [its changelog](${url})`);
11090
+ else if (!entries.length) lines.push(`${head}: no breaking changes of its own; moved with its dependencies, see [its changelog](${url})`);
11091
+ else lines.push(`${head}: [changelog](${url})`, ...entries.slice(0, 5).map((e) => ` - ${e}`), ...entries.length > 5 ? [` - and ${entries.length - 5} more`] : []);
11092
+ }
11093
+ return lines;
11094
+ }
11095
+ var REPOSITORY, bare2, firstLine;
11096
+ var init_changelog = __esm({
11097
+ "src/upgrade/changelog.ts"() {
11098
+ init_discover();
11099
+ init_bump_core();
11100
+ REPOSITORY = "marktiderman/genesis";
11101
+ bare2 = (spec) => spec.replace(/^[\^~=]/, "");
11102
+ firstLine = (entry) => {
11103
+ const line = entry.replace(/^-\s*(?:[0-9a-f]{7,}:\s*)?/, "").split("\n")[0].trim();
11104
+ return line.length > 160 ? `${line.slice(0, 157)}\u2026` : line;
11105
+ };
11106
+ }
11107
+ });
11108
+
11109
+ // src/upgrade/new-exports.ts
11110
+ function componentValues(root) {
11111
+ try {
11112
+ const { config } = loadConfig(root);
11113
+ return readPackageExports(root, uiPackageFor(config))?.values ?? null;
11114
+ } catch {
11115
+ return null;
11116
+ }
11117
+ }
11118
+ function handBuiltSwaps(root, before) {
11119
+ if (!before) return [];
11120
+ try {
11121
+ const { config } = loadConfig(root);
11122
+ if (config.rules?.["shadowed-export"] === "off") return [];
11123
+ const uiPackage = uiPackageFor(config);
11124
+ const after = readPackageExports(root, uiPackage)?.values;
11125
+ const gained = new Set([...after ?? []].filter((name) => !before.has(name)));
11126
+ if (!gained.size) return [];
11127
+ clearPackageRulesCache();
11128
+ const found = [];
11129
+ checkShadowedExports({ root, config, files: scanFiles(root, config), packages: discoverPackages(root), genesis: { uiPackage, values: gained }, report: (f) => found.push(f) });
11130
+ return found.map((f) => ({ name: f.subject, file: f.file, line: f.line ?? 0, package: uiPackage }));
11131
+ } catch {
11132
+ return [];
11133
+ }
11134
+ }
11135
+ function swapLines(swaps) {
11136
+ return swaps.map((s) => `- \`${s.name}\` in ${s.file}${s.line ? `:${s.line}` : ""}: ${s.package} now exports it. Compare the two and swap to \`import { ${s.name} } from "${s.package}"\`, or rename yours if it's a different thing.`);
11137
+ }
11138
+ var init_new_exports = __esm({
11139
+ "src/upgrade/new-exports.ts"() {
11140
+ init_config();
11141
+ init_genesis();
11142
+ init_package_rules();
11143
+ init_rules();
11144
+ init_scan();
11145
+ }
11146
+ });
11147
+ function walk3(dir, rel = "", out = /* @__PURE__ */ new Map()) {
10355
11148
  for (const entry of readdirSync(path30.join(dir, rel), { withFileTypes: true })) {
10356
11149
  if (SKIP.has(entry.name)) continue;
10357
11150
  const child = rel ? `${rel}/${entry.name}` : entry.name;
10358
- if (entry.isDirectory()) walk2(dir, child, out);
11151
+ if (entry.isDirectory()) walk3(dir, child, out);
10359
11152
  else if (entry.isFile()) out.set(child, readFileSync(path30.join(dir, child)));
10360
11153
  }
10361
11154
  return out;
@@ -10532,7 +11325,7 @@ function planOverlays(root, wanted, upstream2, manifests = ["package.json"]) {
10532
11325
  }
10533
11326
  const base = baseRead.files;
10534
11327
  const next = nextRead.files;
10535
- const mine = walk2(pkg.dir);
11328
+ const mine = walk3(pkg.dir);
10536
11329
  const promoted = promotions(root, pkg.name);
10537
11330
  const verdict = (file) => {
10538
11331
  const appPath3 = `${pkg.rel}/${file}`;
@@ -10801,6 +11594,7 @@ var init_overlays2 = __esm({
10801
11594
  // src/upgrade/index.ts
10802
11595
  var upgrade_exports = {};
10803
11596
  __export(upgrade_exports, {
11597
+ checkSubstitutions: () => checkSubstitutions,
10804
11598
  npmLookup: () => npmLookup,
10805
11599
  pnpmWorkspaceFileFor: () => pnpmWorkspaceFileFor,
10806
11600
  releaseAgeError: () => releaseAgeError,
@@ -10852,9 +11646,25 @@ function npmLookup(cwd) {
10852
11646
  latest.set(name, typeof v === "string" ? v : null);
10853
11647
  }
10854
11648
  return latest.get(name);
10855
- }
11649
+ },
11650
+ changelog: fetchChangelog
10856
11651
  };
10857
11652
  }
11653
+ function checkInstalled(root, options) {
11654
+ const noInstall = options.install === false || options.dryRun;
11655
+ if (!Object.keys(readLock(root).files).length && !(noInstall && options.doctor !== false)) return;
11656
+ const text = readApp(root, "package.json");
11657
+ if (text === null) return;
11658
+ let pkg;
11659
+ try {
11660
+ pkg = JSON.parse(text);
11661
+ } catch {
11662
+ return;
11663
+ }
11664
+ const declared = ["dependencies", "devDependencies", "optionalDependencies"].some((s) => Object.keys(pkg[s] ?? {}).some((name) => name.startsWith("@marktiderman/genesis")));
11665
+ if (!declared || installedGenesis(root).size) return;
11666
+ throw new Error(`This app's dependencies aren't installed: package.json lists Genesis packages, but none is in node_modules. Run \`${shellLine(installCommand(detectPackageManager(root)))}\`, then genesis upgrade again. Nothing was changed. (The upgrade merges your edits to owned files against the installed versions, and the doctor reads them.)`);
11667
+ }
10858
11668
  function readText2(file) {
10859
11669
  try {
10860
11670
  return readFileSync(file, "utf8");
@@ -10879,6 +11689,11 @@ function gitTopLevel(root) {
10879
11689
  return null;
10880
11690
  }
10881
11691
  }
11692
+ function folderBelowTopLevel(root) {
11693
+ const real2 = realpathSync(root);
11694
+ const top = gitTopLevel(real2);
11695
+ return top === null ? null : path30.relative(top, real2).split(path30.sep).join("/");
11696
+ }
10882
11697
  function pnpmWorkspaceFileFor(root) {
10883
11698
  const real2 = realpathSync(root);
10884
11699
  const top = gitTopLevel(real2);
@@ -10957,6 +11772,7 @@ async function runUpgrade(options) {
10957
11772
  const root = path30.resolve(options.root);
10958
11773
  const log = options.log ?? (() => {
10959
11774
  });
11775
+ checkInstalled(root, options);
10960
11776
  const lookup = options.lookup ?? npmLookup(root);
10961
11777
  const release = options.manifest ? JSON.parse(readFileSync(path30.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
10962
11778
  const pinned = { [UMBRELLA]: release.version, ...release.packages };
@@ -10997,12 +11813,29 @@ async function runUpgrade(options) {
10997
11813
  const lock = readLock(root);
10998
11814
  const home = databaseElsewhere(root);
10999
11815
  checkSubstitutions(lock.substitutions);
11816
+ const appFolder = appFolderOf(root);
11817
+ const written = folderSubstitutions(lock.substitutions, appFolder);
11818
+ const ownedText = (file, source) => {
11819
+ const text = sourceText(root, source, written);
11820
+ return text === null ? null : renderOwned(file, text, appFolder);
11821
+ };
11000
11822
  const bases = /* @__PURE__ */ new Map();
11823
+ const basesFromPending = /* @__PURE__ */ new Set();
11001
11824
  for (const [file, entry] of Object.entries(lock.files)) {
11002
11825
  if (ownedKeyProblem(file, entry.source, localPackageNames(root))) continue;
11003
- const text = sourceText(root, entry.source, lock.substitutions);
11004
- if (text !== null && sha256(text) === entry.sha256) bases.set(file, text);
11826
+ const text = ownedText(file, entry.source);
11827
+ if (text === null) continue;
11828
+ const was = sourceText(root, entry.source, lock.substitutions);
11829
+ const taken = [sha256(text), ...was === null ? [] : [sha256(was)]];
11830
+ const mine = entry.pending && entry.pendingMine && taken.includes(entry.pending) && readApp(root, `${file}.genesis-next`) === null ? readApp(root, file) : null;
11831
+ const resolved = mine !== null && sha256(mine) !== entry.pendingMine;
11832
+ if (taken.includes(entry.sha256)) bases.set(file, text);
11833
+ else if (resolved) {
11834
+ bases.set(file, text);
11835
+ basesFromPending.add(file);
11836
+ }
11005
11837
  }
11838
+ const valuesBefore = options.dryRun ? null : componentValues(root);
11006
11839
  const files = /* @__PURE__ */ new Set();
11007
11840
  const lockEdits = [];
11008
11841
  const codemodRuns = [];
@@ -11019,6 +11852,7 @@ async function runUpgrade(options) {
11019
11852
  codemodRuns.push({ id: mod.id, files: changed });
11020
11853
  for (const f of changed) files.add(f);
11021
11854
  }
11855
+ const codemodNeedsInstall = options.install === false ? codemodInstallNote(root, codemodRuns.flatMap((c) => c.files), Boolean(options.dryRun)) : null;
11022
11856
  let bunLock;
11023
11857
  const prune = (want) => {
11024
11858
  const result = pruneBunLock(root, want, Boolean(options.dryRun));
@@ -11085,7 +11919,7 @@ async function runUpgrade(options) {
11085
11919
  }
11086
11920
  const added = [];
11087
11921
  const newMigrations = [];
11088
- const warnings = [...excludeWarnings];
11922
+ const warnings = [...excludeWarnings, ...codemodNeedsInstall ? [codemodNeedsInstall] : []];
11089
11923
  const manifests = [];
11090
11924
  const catalog = catalogBlocks();
11091
11925
  const off = appBlocksSwitchedOff(root, catalog, Object.keys(lock.blocks));
@@ -11130,14 +11964,35 @@ async function runUpgrade(options) {
11130
11964
  continue;
11131
11965
  }
11132
11966
  const problem = ownedKeyProblem(file, entry.source, localPackageNames(root));
11133
- const theirs = problem ? null : sourceText(root, entry.source, lock.substitutions);
11967
+ const theirs = problem ? null : ownedText(file, entry.source);
11134
11968
  const dir = problem ? null : packageDir(root, parseSource(entry.source).package);
11135
11969
  const version = dir ? packageVersion(dir) : void 0;
11136
- const outcome = refreshOwned(root, lock, { path: file, theirs, base: bases.get(file) ?? null, ...version ? { version } : {} }, { ...options.dryRun ? { dryRun: true } : {}, ...options.keepMine ? { keepMine: true } : {} });
11970
+ if (appFolder && !problem && isRepositoryWorkflow(file)) {
11971
+ if (theirs !== null && sha256(theirs) !== entry.sha256) {
11972
+ lock.files[file] = { ...entry, sha256: sha256(theirs), ...version ? { version } : {} };
11973
+ refreshed.push({ path: file, outcome: "repository", detail: `the template changed; your copy is in the repository's own .github/workflows (with working-directory: ${appFolder}), so compare it with ${entry.source}` });
11974
+ } else refreshed.push({ path: file, outcome: "unchanged" });
11975
+ continue;
11976
+ }
11977
+ const outcome = refreshOwned(root, lock, { path: file, theirs, base: bases.get(file) ?? null, ...basesFromPending.has(file) ? { baseIsPending: true } : {}, ...version ? { version } : {} }, { ...options.dryRun ? { dryRun: true } : {}, ...options.keepMine ? { keepMine: true } : {} });
11137
11978
  refreshed.push(outcome);
11979
+ if (appFolder && outcome.outcome !== "updated" && !problem) {
11980
+ const template = sourceText(root, entry.source, written);
11981
+ const mine = template === null ? null : readApp(root, file);
11982
+ const stale = mine === null ? [] : unprefixedTemplatePaths(root, file, mine, template, appFolder);
11983
+ if (stale.length) warnings.push(`${file} keeps your edits, so these paths are still from the app's folder and never match: ${stale.join(", ")}. Start them with ${appFolder}/ by hand.`);
11984
+ }
11138
11985
  if (outcome.outcome === "updated" || outcome.outcome === "merged") files.add(file);
11139
11986
  if ((outcome.outcome === "conflict" || outcome.outcome === "kept-mine") && !outcome.detail?.includes("already there")) next.add(`${file}.genesis-next`);
11140
11987
  }
11988
+ const folderInRepo = appFolder ? null : folderBelowTopLevel(root);
11989
+ if (folderInRepo && refreshed.some((r) => (r.outcome === "conflict" || r.outcome === "kept-mine") && /^\.(?:eas|github)\/workflows\//.test(r.path))) {
11990
+ warnings.push(`This app sits in ${folderInRepo}/ in its repository. Set "appFolder": "${folderInRepo}" in genesis.config.json, and the next upgrade writes the EAS workflows' paths from the repository root, so they stop conflicting.`);
11991
+ }
11992
+ if (appFolder) {
11993
+ const actual = folderBelowTopLevel(root);
11994
+ if (actual !== null && actual !== appFolder) warnings.push(`genesis.config.json says "appFolder": "${appFolder}", but this app is at ${actual || "the repository's root"}.`);
11995
+ }
11141
11996
  const functionsLeft = [];
11142
11997
  for (const manifest of manifests) {
11143
11998
  for (const w of ownedWrites(root, manifest, warnings)) {
@@ -11168,21 +12023,56 @@ async function runUpgrade(options) {
11168
12023
  writeLock(root, lock);
11169
12024
  if (readApp(root, LOCK_FILE) !== before) files.add(LOCK_FILE);
11170
12025
  }
12026
+ const generated = /* @__PURE__ */ new Set();
12027
+ if (!options.dryRun) {
12028
+ clearPackageRulesCache();
12029
+ if (options.agents !== false) {
12030
+ try {
12031
+ const packages = discoverPackages(root);
12032
+ const state = agentGuideState(root, packages);
12033
+ if (state.skill !== "missing" || state.agents !== "missing") {
12034
+ const broken = packages.filter((p) => p.error);
12035
+ if (broken.length) warnings.push(`The agent guide wasn't regenerated: ${broken.map((p) => p.error).join("; ")}`);
12036
+ else for (const f of writeAgentGuide(root, packages)) generated.add(f);
12037
+ }
12038
+ } catch (err) {
12039
+ warnings.push(`genesis agents failed: ${err instanceof Error ? err.message : String(err)}`);
12040
+ }
12041
+ }
12042
+ if (options.featuresBuild !== false && registryFile(root)) {
12043
+ try {
12044
+ const { runFeaturesBuild: runFeaturesBuild2 } = await Promise.resolve().then(() => (init_features(), features_exports));
12045
+ for (const f of await runFeaturesBuild2({ dir: root })) generated.add(f);
12046
+ } catch (err) {
12047
+ warnings.push(`features build failed: ${err instanceof Error ? err.message : String(err)}`);
12048
+ }
12049
+ }
12050
+ }
12051
+ for (const f of generated) files.add(f);
12052
+ const swaps = handBuiltSwaps(root, valuesBefore);
12053
+ if (swaps.length) log(["", `This release adds exports the app builds by hand; genesis doctor's shadowed-export reports each:`, ...swapLines(swaps), ""].join("\n"));
11171
12054
  let doctor = "not run";
12055
+ let doctorProblem;
11172
12056
  if (options.doctor !== false) {
11173
12057
  try {
11174
12058
  const { runDoctor: runDoctor2, formatReport: formatReport2 } = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
11175
- const result = await runDoctor2({ root });
12059
+ const result = await runDoctor2({ root, figma: false });
11176
12060
  log(formatReport2(result));
11177
12061
  doctor = result.ok ? "passed" : "failed";
11178
12062
  } catch (err) {
11179
- log(`genesis doctor couldn't run: ${err instanceof Error ? err.message : String(err)}`);
12063
+ doctorProblem = err instanceof Error ? err.message : String(err);
12064
+ log(`genesis doctor couldn't run: ${doctorProblem}`);
11180
12065
  doctor = "failed";
11181
12066
  }
11182
12067
  }
12068
+ const ignored = options.pr && !options.dryRun ? gitIgnored(root, [...files, ...lockfilesFor(root)]) : [];
12069
+ for (const f of ignored) files.delete(f);
11183
12070
  const lines = [bumpSummary(release.version, changes, skipped)];
12071
+ if (ignored.length) lines.push("", `Changed but gitignored, so not in the pull request: ${ignored.join(", ")}.`);
11184
12072
  if (codemodRuns.length) lines.push("", "Codemods:", "", ...codemodRuns.map((c) => `- ${c.id}${c.files.length ? `: ${c.files.join(", ")}` : ""}`));
11185
- if (breaks.length) lines.push("", "Major moves with no codemod (read their changelogs):", "", ...breaks.map((b) => `- \`${b.name}\` ${b.from} \u2192 ${b.to}`));
12073
+ if (breaks.length) lines.push("", "Major moves with no codemod:", "", ...await breakLines(root, breaks, lookup));
12074
+ if (swaps.length) lines.push("", "New exports this app builds by hand (`shadowed-export` reports each until it's swapped or renamed):", "", ...swapLines(swaps));
12075
+ if (generated.size) lines.push("", `Regenerated from the installed packages: ${[...generated].join(", ")}.`);
11186
12076
  const touched2 = refreshed.filter((r) => r.outcome !== "unchanged");
11187
12077
  if (touched2.length || added.length) {
11188
12078
  lines.push("", options.dryRun ? "Files Genesis owns (against the packages installed now; a real run compares with the new versions after the install):" : "Files Genesis owns:", "", ...touched2.map((r) => `- ${r.path}: ${r.outcome}${r.detail ? ` (${r.detail})` : ""}`), ...added.map((a) => `- ${a}: added`));
@@ -11205,27 +12095,43 @@ async function runUpgrade(options) {
11205
12095
  }
11206
12096
  lines.push(...overlayChecklist(overlays));
11207
12097
  if (warnings.length) lines.push("", "Warnings:", "", ...warnings.map((w) => `- ${w}`));
11208
- lines.push("", `\`genesis doctor\` ${doctor === "not run" ? "was not run" : doctor} after the upgrade.`);
12098
+ lines.push("", doctorProblem ? `\`genesis doctor\` couldn't run after the upgrade: ${doctorProblem}` : `\`genesis doctor\` ${doctor === "not run" ? "was not run" : doctor} after the upgrade.`);
11209
12099
  const summary = lines.join("\n");
11210
- const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, switchedOff, newMigrations, doctor, files: [...files].sort(), summary, overlays, ...bunLock ? { bunLock } : {} };
12100
+ const report = { version: release.version, changes, skipped, codemods: codemodRuns, breaks, refreshed, added, switchedOff, newMigrations, swaps, doctor, files: [...files].sort(), summary, overlays, ...bunLock ? { bunLock } : {} };
11211
12101
  if (options.pr && !options.dryRun && files.size) report.pr = openPullRequest(root, release.version, report, prBase);
11212
12102
  return report;
11213
12103
  }
11214
12104
  function checkSubstitutions(substitutions) {
11215
12105
  if (!substitutions || !Object.keys(substitutions).length) return;
11216
- let allowed;
12106
+ let names;
11217
12107
  try {
11218
12108
  const was = starterIdentity(readFileSync(path30.join(starterDir(), "starter.config.ts"), "utf8"));
11219
- allowed = [was.name, was.slug, was.scheme, was.bundleId, APP_FOLDER_PLACEHOLDER];
12109
+ names = [was.name, was.slug, was.scheme, was.bundleId];
11220
12110
  } catch {
11221
- allowed = [];
12111
+ names = [];
11222
12112
  }
11223
12113
  for (const [from, to] of Object.entries(substitutions)) {
11224
- if (!allowed.includes(from) || !SUBSTITUTION_VALUE.test(to)) {
12114
+ if (from === APP_FOLDER_PLACEHOLDER) {
12115
+ if (!isPlainFolder(to)) throw new Error(`genesis.lock.json: the substitution ${from} \u2192 ${JSON.stringify(to)} isn't a plain folder inside the repository (src, or apps/web); fix the lock by hand.`);
12116
+ } else if (!names.includes(from) || !SUBSTITUTION_VALUE.test(to)) {
11225
12117
  throw new Error(`genesis.lock.json: the substitution ${JSON.stringify(from)} \u2192 ${JSON.stringify(to)} isn't one of the starter's names with a plain value; fix the lock by hand.`);
11226
12118
  }
11227
12119
  }
11228
12120
  }
12121
+ function lockfilesFor(root) {
12122
+ const top = gitTopLevel(root);
12123
+ const lockfiles = [];
12124
+ for (let dir = realpathSync(root); ; dir = path30.dirname(dir)) {
12125
+ for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path30.join(dir, f))) lockfiles.push(path30.relative(realpathSync(root), path30.join(dir, f)));
12126
+ if (lockfiles.length || dir === top || path30.dirname(dir) === dir) break;
12127
+ }
12128
+ return lockfiles;
12129
+ }
12130
+ function gitIgnored(root, files) {
12131
+ if (!files.length) return [];
12132
+ const result = spawnSync("git", ["check-ignore", "--stdin", "-z"], { cwd: root, input: files.join("\0"), encoding: "utf8" });
12133
+ return result.status === 0 ? result.stdout.split("\0").filter(Boolean) : [];
12134
+ }
11229
12135
  function checkPullRequest(root, version) {
11230
12136
  const git4 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
11231
12137
  if (git4("status", "--porcelain")) throw new Error("--pr needs a clean working tree (commit or stash your changes first).");
@@ -11246,13 +12152,9 @@ function openPullRequest(root, version, report, base) {
11246
12152
  const git4 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
11247
12153
  const branch = `genesis-upgrade/${version}`;
11248
12154
  git4("switch", "-c", branch);
11249
- const top = git4("rev-parse", "--show-toplevel");
11250
- const lockfiles = [];
11251
- for (let dir = path30.resolve(root); ; dir = path30.dirname(dir)) {
11252
- for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path30.join(dir, f))) lockfiles.push(path30.relative(root, path30.join(dir, f)));
11253
- if (lockfiles.length || dir === top || path30.dirname(dir) === dir) break;
11254
- }
11255
- const paths = [...report.files.filter((f) => existsSync(path30.join(root, f))), ...lockfiles];
12155
+ const lockfiles = lockfilesFor(root);
12156
+ const ignoredLocks = gitIgnored(root, lockfiles);
12157
+ const paths = [...report.files.filter((f) => existsSync(path30.join(root, f))), ...lockfiles.filter((f) => !ignoredLocks.includes(f))];
11256
12158
  git4("add", "--", ...paths);
11257
12159
  const overlayDirs = report.overlays.filter((o) => !o.skipped && !o.conflicts.length && (o.remove || [...o.writes.values()].includes(null))).map((o) => o.rel);
11258
12160
  if (overlayDirs.length) git4("add", "-A", "--", ...overlayDirs);
@@ -11270,7 +12172,11 @@ var init_upgrade = __esm({
11270
12172
  "src/upgrade/index.ts"() {
11271
12173
  init_add();
11272
12174
  init_agents();
12175
+ init_app_folder();
11273
12176
  init_discover();
12177
+ init_config();
12178
+ init_primitives();
12179
+ init_package_rules();
11274
12180
  init_starter_features();
11275
12181
  init_files();
11276
12182
  init_init_native();
@@ -11282,7 +12188,9 @@ var init_upgrade = __esm({
11282
12188
  init_pm();
11283
12189
  init_templates();
11284
12190
  init_bump_core();
12191
+ init_changelog();
11285
12192
  init_codemods();
12193
+ init_new_exports();
11286
12194
  init_overlays2();
11287
12195
  init_bun_lock();
11288
12196
  EXACT_OR_TAG = /^[0-9A-Za-z][0-9A-Za-z.+-]*$/;
@@ -11391,9 +12299,9 @@ async function runScaffold(opts, fs2) {
11391
12299
  function joinPath(...parts) {
11392
12300
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
11393
12301
  }
11394
- function dirname(path56) {
11395
- const idx = path56.lastIndexOf("/");
11396
- return idx === -1 ? "." : path56.slice(0, idx);
12302
+ function dirname(path61) {
12303
+ const idx = path61.lastIndexOf("/");
12304
+ return idx === -1 ? "." : path61.slice(0, idx);
11397
12305
  }
11398
12306
  function brandPackageJson(consumer, genesisVersion) {
11399
12307
  return JSON.stringify(
@@ -11729,7 +12637,7 @@ program.command("introspect").description("Write a checked-in contract (resource
11729
12637
  await fs.writeFile(target, content, "utf-8");
11730
12638
  console.log(`\u2714 Wrote ${label}: ${tables.length} tables.`);
11731
12639
  });
11732
- program.command("doctor").description("Check this app against the installed Genesis: components, tokens, imports, colors, plus the app's own rules").option("--strict", "Fail on warnings too", false).option("--json", "Print the report as JSON", false).option("--build", "Also run the app's typecheck and build (doctor.build, or its typecheck/build scripts)", false).option("-c, --config <path>", 'Config file (default: genesis.config.json, then package.json "genesis")').option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--print-genesis", "Print the components, tokens and raw tags read from Genesis, and exit", false).option("--base <ref>", "The git ref change checks compare against (the packages pack's change gate, and the ratchet: newOnly rules report unchanged files as info), e.g. origin/main").action(async (opts) => {
12640
+ program.command("doctor").description("Check this app against the installed Genesis: components, tokens, imports, colors, plus the app's own rules").option("--strict", "Fail on warnings too", false).option("--json", "Print the report as JSON", false).option("--verbose", "List the Genesis components no file imports (otherwise only their count)", false).option("--build", "Also run the app's typecheck and build (doctor.build, or its typecheck/build scripts)", false).option("-c, --config <path>", 'Config file (default: genesis.config.json, then package.json "genesis")').option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--print-genesis", "Print the components, tokens and raw tags read from Genesis, and exit", false).option("--base <ref>", "The git ref change checks compare against (the packages pack's change gate, and the ratchet: newOnly rules report unchanged files as info), e.g. origin/main").action(async (opts) => {
11733
12641
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
11734
12642
  const root = path30.resolve(opts.dir);
11735
12643
  try {
@@ -11739,7 +12647,7 @@ program.command("doctor").description("Check this app against the installed Gene
11739
12647
  return;
11740
12648
  }
11741
12649
  const result = await doctor.runDoctor({ root, configPath: opts.config, strict: opts.strict, build: opts.build, quietBuild: opts.json, ...opts.base ? { base: opts.base } : {} });
11742
- console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result));
12650
+ console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result, { verbose: opts.verbose }));
11743
12651
  process.exitCode = result.ok ? 0 : 1;
11744
12652
  } catch (err) {
11745
12653
  if (!(err instanceof doctor.GenesisConfigError)) throw err;
@@ -11856,6 +12764,18 @@ featureOptions(
11856
12764
  const what = term ? `"${term}"` : "those filters";
11857
12765
  console.log(hits.length ? hits.map(formatFeature2).join("\n\n") : `No feature matches ${what}. If this is new work, add it to the registry first (an idea is enough).`);
11858
12766
  });
12767
+ program.command("figma:routes").description("Report drift between this app's routes and its Figma app file (read-only; genesis.config.json figma block, FIGMA_ACCESS_TOKEN)").option("--json", "Print the report as JSON", false).option("--strict", "Exit 1 when a route, hotspot or figma: id is missing", false).option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
12768
+ const figma = await Promise.resolve().then(() => (init_routes2(), routes_exports));
12769
+ try {
12770
+ const report = await figma.checkFigmaRoutes({ root: path30.resolve(opts.dir) });
12771
+ console.log(opts.json ? JSON.stringify(report, null, 2) : figma.formatCoverage(report));
12772
+ process.exitCode = opts.strict && report.summary.missing > 0 ? 1 : 0;
12773
+ } catch (err) {
12774
+ if (opts.json) console.log(JSON.stringify({ ok: false, error: err.message }, null, 2));
12775
+ else console.error(`\u2717 ${err.message}`);
12776
+ process.exitCode = 2;
12777
+ }
12778
+ });
11859
12779
  var upstream = program.command("upstream").description("The app's register of what it needed from Genesis (docs/genesis-upstream.md)");
11860
12780
  upstream.command("check").description("Check docs/genesis-upstream.md: kinds, statuses, local paths, and promoted entries whose local copy is still there").option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
11861
12781
  const { checkUpstream: checkUpstream2 } = await Promise.resolve().then(() => (init_upstream(), upstream_exports));
@@ -11882,36 +12802,36 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
11882
12802
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
11883
12803
  const root = path30.resolve(opts.dir);
11884
12804
  const packageJson = JSON.parse(await fs.readFile(path30.join(root, "package.json"), "utf-8").catch(() => "{}"));
11885
- const existsSync43 = (await import('fs')).existsSync;
12805
+ const existsSync45 = (await import('fs')).existsSync;
11886
12806
  const readSync = (await import('fs')).readFileSync;
11887
- const readdirSync19 = (await import('fs')).readdirSync;
12807
+ const readdirSync20 = (await import('fs')).readdirSync;
11888
12808
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
11889
12809
  throw new Error("--host must be next, tanstack-start or supabase-function.");
11890
12810
  }
11891
12811
  const plan = planStudioInit2(
11892
12812
  {
11893
12813
  packageJson,
11894
- exists: (p) => existsSync43(path30.join(root, p)),
11895
- read: (p) => existsSync43(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
12814
+ exists: (p) => existsSync45(path30.join(root, p)),
12815
+ read: (p) => existsSync45(path30.join(root, p)) ? readSync(path30.join(root, p), "utf-8") : null,
11896
12816
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
11897
12817
  listDeep: (p) => {
11898
12818
  const out = [];
11899
- const walk3 = (rel) => {
11900
- for (const entry of readdirSync19(path30.join(root, rel), { withFileTypes: true })) {
12819
+ const walk4 = (rel) => {
12820
+ for (const entry of readdirSync20(path30.join(root, rel), { withFileTypes: true })) {
11901
12821
  const child = `${rel}/${entry.name}`;
11902
- if (entry.isDirectory()) walk3(child);
12822
+ if (entry.isDirectory()) walk4(child);
11903
12823
  else out.push(child);
11904
12824
  }
11905
12825
  };
11906
12826
  try {
11907
- walk3(p);
12827
+ walk4(p);
11908
12828
  } catch {
11909
12829
  }
11910
12830
  return out;
11911
12831
  },
11912
12832
  list: (p) => {
11913
12833
  try {
11914
- return readdirSync19(path30.join(root, p));
12834
+ return readdirSync20(path30.join(root, p));
11915
12835
  } catch {
11916
12836
  return [];
11917
12837
  }
@@ -11932,14 +12852,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
11932
12852
  console.log(`+ ${file.path} (appended)`);
11933
12853
  continue;
11934
12854
  }
11935
- if (existsSync43(target) && !opts.force) {
12855
+ if (existsSync45(target) && !opts.force) {
11936
12856
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
11937
12857
  continue;
11938
12858
  }
11939
12859
  await fs.writeFile(target, file.content, "utf-8");
11940
12860
  console.log(`+ ${file.path}`);
11941
12861
  }
11942
- const pm = existsSync43(path30.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync43(path30.join(root, "yarn.lock")) ? "yarn add" : existsSync43(path30.join(root, "bun.lock")) || existsSync43(path30.join(root, "bun.lockb")) ? "bun add" : "npm install";
12862
+ const pm = existsSync45(path30.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync45(path30.join(root, "yarn.lock")) ? "yarn add" : existsSync45(path30.join(root, "bun.lock")) || existsSync45(path30.join(root, "bun.lockb")) ? "bun add" : "npm install";
11943
12863
  console.log("");
11944
12864
  console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
11945
12865
  console.log(` 1. ${pm} ${plan.install.map((p) => /[\s<>|]/.test(p) ? `"${p}"` : p).join(" ")}`);
@@ -12010,7 +12930,7 @@ program.command("migrate").description("Copy new package migrations of the app's
12010
12930
  process.exitCode = 1;
12011
12931
  }
12012
12932
  });
12013
- program.command("upgrade").description("Move every @marktiderman/genesis* dependency to one Genesis release, refresh the files Genesis owns, run codemods and the doctor").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--version <v>", "The @marktiderman/genesis release: an exact version or a dist-tag", "latest").option("--manifest <file>", "Read the release from this versions.json instead of npm").option("--dry-run", "Report the bump, and owned files compared with the packages installed now; change nothing", false).option("--no-install", "Don't reinstall after the bump").option("--no-doctor", "Don't run genesis doctor after").option("--keep-mine", "Never merge an owned file you changed; write the new text to .genesis-next", false).option("--pr", "Commit to a genesis-upgrade/<version> branch, push it and open a pull request", false).option("--genesis-repo <url>", "The Genesis git repository whose <package>@<version> tags overlays are rebased from (default: the public one)").action(async (opts) => {
12933
+ program.command("upgrade").description("Move every @marktiderman/genesis* dependency to one Genesis release, refresh the files Genesis owns and what's generated, run codemods and the doctor").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--version <v>", "The @marktiderman/genesis release: an exact version or a dist-tag", "latest").option("--manifest <file>", "Read the release from this versions.json instead of npm").option("--dry-run", "Report the bump, and owned files compared with the packages installed now; change nothing", false).option("--no-install", "Don't reinstall after the bump").option("--no-doctor", "Don't run genesis doctor after").option("--no-agents", "Don't regenerate the agent guide (genesis agents) after").option("--no-features-build", "Don't run features build after").option("--keep-mine", "Never merge an owned file you changed; write the new text to .genesis-next", false).option("--pr", "Commit to a genesis-upgrade/<version> branch, push it and open a pull request", false).option("--genesis-repo <url>", "The Genesis git repository whose <package>@<version> tags overlays are rebased from (default: the public one)").action(async (opts) => {
12014
12934
  const { runUpgrade: runUpgrade2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
12015
12935
  const report = await runUpgrade2({
12016
12936
  root: path30.resolve(opts.dir),
@@ -12019,6 +12939,8 @@ program.command("upgrade").description("Move every @marktiderman/genesis* depend
12019
12939
  dryRun: opts.dryRun,
12020
12940
  install: opts.install,
12021
12941
  doctor: opts.doctor,
12942
+ agents: opts.agents,
12943
+ featuresBuild: opts.featuresBuild,
12022
12944
  keepMine: opts.keepMine,
12023
12945
  pr: opts.pr,
12024
12946
  ...opts.genesisRepo ? { genesisRepo: opts.genesisRepo } : {},
@@ -12032,7 +12954,7 @@ program.command("upgrade").description("Move every @marktiderman/genesis* depend
12032
12954
  if (report.doctor === "failed") process.exitCode = 1;
12033
12955
  });
12034
12956
  program.command("codemod [id]").description("Run one of Genesis's codemods by hand (genesis upgrade runs them for you); without an id, list them").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--dry-run", "List the files it would change; change nothing", false).action(async (id, opts) => {
12035
- const { CODEMODS: CODEMODS2, codemodById: codemodById2 } = await Promise.resolve().then(() => (init_codemods(), codemods_exports));
12957
+ const { CODEMODS: CODEMODS2, codemodById: codemodById2, codemodInstallNote: codemodInstallNote2 } = await Promise.resolve().then(() => (init_codemods(), codemods_exports));
12036
12958
  if (!id) {
12037
12959
  for (const mod2 of CODEMODS2) console.log(`${mod2.id} (${mod2.package} ${mod2.version})
12038
12960
  ${mod2.description}`);
@@ -12043,6 +12965,8 @@ program.command("codemod [id]").description("Run one of Genesis's codemods by ha
12043
12965
  const changed = await mod.run({ root: path30.resolve(opts.dir), dryRun: opts.dryRun, log: (m) => console.log(m) });
12044
12966
  console.log(changed.length ? `${opts.dryRun ? "Would change" : "\u2714 Changed"} ${changed.length} file${changed.length === 1 ? "" : "s"}:
12045
12967
  ${changed.map((f) => ` ${f}`).join("\n")}` : "Nothing to change.");
12968
+ const note = codemodInstallNote2(path30.resolve(opts.dir), changed, opts.dryRun);
12969
+ if (note) console.log(`! ${note}`);
12046
12970
  });
12047
12971
  program.parseAsync(process.argv).catch((err) => {
12048
12972
  const message = err instanceof Error ? err.message : String(err);