@marktiderman/genesis-cli 1.14.0 → 1.15.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/index.js CHANGED
@@ -1,387 +1,270 @@
1
1
  import { createRequire, builtinModules } from 'module';
2
2
  import { studioSetupSql } from '@marktiderman/genesis-studio-server';
3
- import * as path14 from 'path';
3
+ import * as path18 from 'path';
4
4
  import { spawnSync } from 'child_process';
5
- import { existsSync, readFileSync, statSync, readdirSync, realpathSync, lstatSync } from 'fs';
5
+ import { existsSync, readFileSync, statSync, realpathSync, readdirSync, lstatSync } from 'fs';
6
6
  import 'crypto';
7
7
  import { FEATURE_PLATFORMS, defineBlock, BlockError } from '@marktiderman/genesis-features/blocks';
8
8
  import { pathToFileURL } from 'url';
9
+ import 'jiti';
9
10
 
10
- // src/scaffolder.ts
11
- var VALID_NAME_PATTERN = /^[a-z][a-z0-9-]{1,30}$/;
12
- var NOOP_LOGGER = {
13
- info() {
14
- },
15
- warn() {
16
- },
17
- error() {
18
- }
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __esm = (fn, res) => function __init() {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
19
15
  };
20
- function validateConsumerName(name) {
21
- if (!VALID_NAME_PATTERN.test(name)) {
22
- throw new Error(
23
- `Invalid consumer name "${name}". Must be lowercase letters/digits/hyphens, 2-31 chars, starting with a letter (e.g., "acme", "arcade-mobile").`
24
- );
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+
21
+ // src/introspect/catalog-text.ts
22
+ function tokenize(tree) {
23
+ const tokens = [];
24
+ let i = 0;
25
+ while (i < tree.length) {
26
+ const ch = tree[i];
27
+ if (ch === " " || ch === "\n" || ch === " ") {
28
+ i++;
29
+ } else if (ch === "{" || ch === "(") {
30
+ tokens.push({ kind: "open", char: ch });
31
+ i++;
32
+ } else if (ch === "}" || ch === ")") {
33
+ tokens.push({ kind: "close", char: ch });
34
+ i++;
35
+ } else {
36
+ let text = "";
37
+ while (i < tree.length) {
38
+ const c = tree[i];
39
+ if (c === "\\" && i + 1 < tree.length) {
40
+ text += tree[i + 1];
41
+ i += 2;
42
+ continue;
43
+ }
44
+ if (c === " " || c === "\n" || c === " " || c === "{" || c === "}" || c === "(" || c === ")") break;
45
+ text += c;
46
+ i++;
47
+ }
48
+ tokens.push({ kind: "atom", text });
49
+ }
25
50
  }
51
+ return tokens;
26
52
  }
27
- function planScaffold(opts) {
28
- const consumer = opts.consumerName;
29
- const genesisVersion = opts.genesisVersion ?? "workspace:^";
30
- return [
31
- {
32
- path: `packages/${consumer}-brand/package.json`,
33
- content: brandPackageJson(consumer, genesisVersion)
34
- },
35
- {
36
- path: `packages/${consumer}-brand/src/brand.ts`,
37
- content: brandSchema(consumer)
38
- },
39
- {
40
- path: `packages/${consumer}-brand/src/index.ts`,
41
- content: `export { brand } from "./brand";
42
- export type { Brand } from "./brand";
43
- `
44
- },
45
- {
46
- path: `packages/${consumer}-brand/tsconfig.json`,
47
- content: brandTsconfig()
48
- },
49
- {
50
- path: `tailwind.config.ts`,
51
- content: tailwindConfig(consumer, opts.native ?? false)
52
- },
53
- {
54
- path: `app/global.css`,
55
- content: globalCss()
56
- },
57
- {
58
- path: `CLAUDE.md`,
59
- content: claudeMd(consumer)
53
+ function viewColumnOrigins(evAction) {
54
+ const tokens = tokenize(evAction);
55
+ let depth = 0;
56
+ let start = -1;
57
+ for (let i = 0; i < tokens.length; i++) {
58
+ const t = tokens[i];
59
+ if (t.kind === "open") depth++;
60
+ else if (t.kind === "close") depth--;
61
+ else if (depth === 2 && t.text === ":targetList") {
62
+ start = i + 1;
63
+ break;
60
64
  }
61
- ];
62
- }
63
- async function runScaffold(opts, fs) {
64
- validateConsumerName(opts.consumerName);
65
- const log = opts.logger ?? NOOP_LOGGER;
66
- const plan = planScaffold(opts);
67
- const written = [];
68
- const skipped = [];
69
- const conflicts = [];
70
- for (const file of plan) {
71
- const fullPath = joinPath(opts.targetDir, file.path);
72
- const dir = dirname(fullPath);
73
- await fs.mkdirp(dir);
74
- const exists = await fs.exists(fullPath);
75
- if (!exists) {
76
- await fs.writeFile(fullPath, file.content);
77
- written.push(file.path);
78
- log.info(`\u2714 wrote ${file.path}`);
65
+ }
66
+ if (start < 0) return [];
67
+ const origins = [];
68
+ depth = 2;
69
+ let entry = null;
70
+ let lastKey = null;
71
+ for (let i = start; i < tokens.length; i++) {
72
+ const t = tokens[i];
73
+ if (t.kind === "open") {
74
+ depth++;
75
+ if (depth === 4 && t.char === "{") {
76
+ entry = /* @__PURE__ */ new Map();
77
+ lastKey = null;
78
+ }
79
79
  continue;
80
80
  }
81
- const existing = await fs.readFile(fullPath);
82
- if (existing === file.content) {
83
- skipped.push(file.path);
84
- log.info(`= skipped ${file.path} (identical)`);
81
+ if (t.kind === "close") {
82
+ if (depth === 4 && entry) {
83
+ const relation = Number(entry.get(":resorigtbl"));
84
+ const column = Number(entry.get(":resorigcol"));
85
+ const position = Number(entry.get(":resno"));
86
+ const name = entry.get(":resname") ?? "";
87
+ if (entry.get(":resjunk") !== "true" && position > 0 && relation > 0 && column > 0) {
88
+ origins.push({ position, name, relation, column });
89
+ }
90
+ entry = null;
91
+ }
92
+ depth--;
93
+ if (depth <= 2) break;
85
94
  continue;
86
95
  }
87
- if (opts.emitConflicts) {
88
- const nextPath = `${fullPath}.genesis-next`;
89
- await fs.writeFile(nextPath, file.content);
90
- conflicts.push(`${file.path}.genesis-next`);
91
- log.warn(
92
- `! diff ${file.path} \u2014 wrote .genesis-next sibling for review`
93
- );
94
- } else {
95
- skipped.push(file.path);
96
- log.warn(
97
- `! skipped ${file.path} (exists; pass --emit-conflicts to diff)`
98
- );
96
+ if (depth !== 4 || !entry) continue;
97
+ if (t.text === "TARGETENTRY") continue;
98
+ if (t.text.startsWith(":")) lastKey = t.text;
99
+ else if (lastKey) {
100
+ entry.set(lastKey, t.text);
101
+ lastKey = null;
99
102
  }
100
103
  }
101
- return { written, skipped, conflicts };
104
+ return origins;
102
105
  }
103
- function joinPath(...parts) {
104
- return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
106
+ function unwrap(expr) {
107
+ let s = expr.trim();
108
+ for (; ; ) {
109
+ if (!s.startsWith("(") || !s.endsWith(")")) return s;
110
+ let depth = 0;
111
+ let inQuote = false;
112
+ let wrapsAll = true;
113
+ for (let i = 0; i < s.length; i++) {
114
+ const c = s[i];
115
+ if (c === "'") inQuote = !inQuote;
116
+ if (inQuote) continue;
117
+ if (c === "(") depth++;
118
+ else if (c === ")") {
119
+ depth--;
120
+ if (depth === 0 && i < s.length - 1) {
121
+ wrapsAll = false;
122
+ break;
123
+ }
124
+ }
125
+ }
126
+ if (!wrapsAll) return s;
127
+ s = s.slice(1, -1).trim();
128
+ }
105
129
  }
106
- function dirname(path22) {
107
- const idx = path22.lastIndexOf("/");
108
- return idx === -1 ? "." : path22.slice(0, idx);
130
+ function splitTopLevel(expr, separator) {
131
+ const parts = [];
132
+ let depth = 0;
133
+ let inQuote = false;
134
+ let from = 0;
135
+ for (let i = 0; i < expr.length; i++) {
136
+ const c = expr[i];
137
+ if (c === "'") inQuote = !inQuote;
138
+ if (inQuote) continue;
139
+ if (c === "(") depth++;
140
+ else if (c === ")") depth--;
141
+ else if (depth === 0 && expr.startsWith(separator, i)) {
142
+ parts.push(expr.slice(from, i));
143
+ from = i + separator.length;
144
+ i += separator.length - 1;
145
+ }
146
+ }
147
+ parts.push(expr.slice(from));
148
+ return parts;
149
+ }
150
+ function escapeRegExp(s) {
151
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
152
+ }
153
+ function checkEnumValues(definition, column) {
154
+ const outer = /^CHECK \((.*)\)(?: NOT VALID)?$/s.exec(definition.trim());
155
+ if (!outer) return void 0;
156
+ const ident = `(?:${escapeRegExp(column)}|${escapeRegExp(`"${column.replace(/"/g, '""')}"`)})`;
157
+ const ref = String.raw`(?:${ident}|\(${ident}\)${CAST})`;
158
+ let body = unwrap(outer[1]);
159
+ const parts = splitTopLevel(body, " OR ");
160
+ if (parts.length === 2) {
161
+ const isNull = new RegExp(`^${ref} IS NULL$`);
162
+ const nullAt = parts.findIndex((p) => isNull.test(unwrap(p)));
163
+ if (nullAt < 0) return void 0;
164
+ body = unwrap(parts[1 - nullAt]);
165
+ } else if (parts.length !== 1) {
166
+ return void 0;
167
+ }
168
+ const single = new RegExp(`^${ref} = ${LITERAL}$`).exec(body);
169
+ if (single) return [single[1].replace(/''/g, "'")];
170
+ const any = new RegExp(String.raw`^${ref} = ANY \((.*)\)$`).exec(body);
171
+ if (!any) return void 0;
172
+ const list = /^\(?ARRAY\[(.*?)\](?:\)(?:::[a-z][a-z ]*(?:\(\d+\))?\[\]))?$/s.exec(unwrap(any[1]));
173
+ if (!list) return void 0;
174
+ const items = splitTopLevel(list[1], ", ");
175
+ const values = [];
176
+ const literal = new RegExp(`^${LITERAL}$`);
177
+ for (const item of items) {
178
+ const m = literal.exec(item.trim());
179
+ if (!m) return void 0;
180
+ values.push(m[1].replace(/''/g, "'"));
181
+ }
182
+ return values.length ? values : void 0;
183
+ }
184
+ var CAST, LITERAL;
185
+ var init_catalog_text = __esm({
186
+ "src/introspect/catalog-text.ts"() {
187
+ CAST = String.raw`::[a-z][a-z ]*(?:\(\d+(?:,\d+)?\))?`;
188
+ LITERAL = String.raw`'((?:[^']|'')*)'${CAST}`;
189
+ }
190
+ });
191
+
192
+ // src/introspect/comments.ts
193
+ function parse(comment, keys, where2) {
194
+ if (!comment) return {};
195
+ const at = comment.indexOf(MARKER);
196
+ if (at < 0) return { description: comment.trim() || void 0 };
197
+ const description = comment.slice(0, at).trim() || void 0;
198
+ const raw = comment.slice(at + MARKER.length).trim();
199
+ let value;
200
+ try {
201
+ value = JSON.parse(raw);
202
+ } catch {
203
+ throw new CommentSettingsError(`${where2}: the text after ${MARKER} must be one JSON object.`);
204
+ }
205
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
206
+ throw new CommentSettingsError(`${where2}: the text after ${MARKER} must be one JSON object.`);
207
+ }
208
+ const settings = {};
209
+ for (const [key2, v] of Object.entries(value)) {
210
+ const kind = keys[key2];
211
+ if (!kind) {
212
+ throw new CommentSettingsError(`${where2}: unknown ${MARKER} setting "${key2}". Allowed: ${Object.keys(keys).join(", ")}.`);
213
+ }
214
+ if (typeof v !== kind) throw new CommentSettingsError(`${where2}: ${MARKER} "${key2}" must be a ${kind}.`);
215
+ settings[key2] = v;
216
+ }
217
+ return {
218
+ ...description ? { description } : {},
219
+ ...Object.keys(settings).length ? { settings } : {}
220
+ };
109
221
  }
110
- function brandPackageJson(consumer, genesisVersion) {
111
- return JSON.stringify(
112
- {
113
- name: `@${consumer}/brand`,
114
- version: "0.1.0",
115
- private: true,
116
- type: "module",
117
- main: "./src/index.ts",
118
- types: "./src/index.ts",
119
- description: `Brand tokens + extensions for the ${consumer} app. Consumed by Genesis primitives via canonical schema.`,
120
- peerDependencies: {
121
- "@marktiderman/genesis-design-system": genesisVersion
122
- }
123
- },
124
- null,
125
- 2
126
- ) + "\n";
222
+ function parseTableComment(comment, table) {
223
+ return parse(comment, TABLE_KEYS, table);
127
224
  }
128
- function brandTsconfig() {
129
- return JSON.stringify(
130
- {
131
- extends: "../../tsconfig.base.json",
132
- compilerOptions: {
133
- outDir: "dist",
134
- rootDir: "src"
135
- },
136
- include: ["src"]
137
- },
138
- null,
139
- 2
140
- ) + "\n";
225
+ function parseColumnComment(comment, column) {
226
+ return parse(comment, FIELD_KEYS, column);
141
227
  }
142
- function brandSchema(consumer) {
143
- return `/**
144
- * @${consumer}/brand \u2014 canonical brand tokens + extensions.
145
- *
146
- * Genesis primitives consume tokens from this file via the design-system
147
- * provider. Edit colors/spacing/typography here to retheme every screen
148
- * at once. Domain-specific tokens (e.g., "mood" for Acme, "rarity" for
149
- * a game app) go under \`extensions\` \u2014 Genesis primitives don't read these,
150
- * but consumer composites do via \`useGenesisExtension(key)\`.
151
- *
152
- * Schema is intentionally narrow at the top level. Add categories under
153
- * \`extensions\` rather than inventing new top-level slots.
154
- */
228
+ var MARKER, TABLE_KEYS, FIELD_KEYS, CommentSettingsError;
229
+ var init_comments = __esm({
230
+ "src/introspect/comments.ts"() {
231
+ MARKER = "@genesis";
232
+ TABLE_KEYS = { label: "string", labelField: "string", description: "string", noun: "string", nounPlural: "string" };
233
+ FIELD_KEYS = { label: "string", description: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
234
+ CommentSettingsError = class extends Error {
235
+ };
236
+ }
237
+ });
155
238
 
156
- export interface BrandColorScale {
157
- 50: string;
158
- 100: string;
159
- 200: string;
160
- 300: string;
161
- 400: string;
162
- 500: string;
163
- 600: string;
164
- 700: string;
165
- 800: string;
166
- 900: string;
239
+ // src/introspect/model.ts
240
+ function storageTypeOf(dbType) {
241
+ const t = dbType.toLowerCase().replace(/\[\]$/, "");
242
+ if (/^(smallint|integer|bigint|int2|int4|int8|real|double precision|float4|float8|numeric|decimal|money)\b/.test(t)) {
243
+ return "number";
244
+ }
245
+ if (t === "boolean" || t === "bool") return "boolean";
246
+ if (/^(date|timestamp|timestamptz|time|timetz|interval)\b/.test(t)) return "datetime";
247
+ if (t === "json" || t === "jsonb") return "json";
248
+ return "string";
167
249
  }
168
-
169
- export interface BrandColors {
170
- primary: BrandColorScale;
171
- destructive: BrandColorScale;
172
- /** Neutral / gray scale used for surfaces, text, borders. */
173
- neutral: BrandColorScale;
250
+ function qualifiedName(schema, table) {
251
+ const part = (p) => /[."]/.test(p) ? `"${p.replace(/"/g, '""')}"` : p;
252
+ return `${part(schema)}.${part(table)}`;
174
253
  }
254
+ var init_model = __esm({
255
+ "src/introspect/model.ts"() {
256
+ }
257
+ });
175
258
 
176
- export interface Brand {
177
- /** Slug used for namespacing (e.g., extensions key prefix). */
178
- name: string;
179
- colors: BrandColors;
180
- /**
181
- * Domain-specific token categories. Consumer composites read these
182
- * via \`useGenesisExtension("<key>")\`. Genesis primitives do NOT read
183
- * extensions \u2014 only canonical \`colors\`.
184
- */
185
- extensions?: Record<string, Record<string | number, unknown>>;
259
+ // src/introspect/postgres.ts
260
+ function where(sql, scope) {
261
+ return "schemas" in scope ? sql`n.nspname = any(${scope.schemas})` : sql`c.oid = any(${scope.oids}::oid[])`;
186
262
  }
187
-
188
- // ---------------------------------------------------------------------------
189
- // Default brand \u2014 replace these placeholder values with your design's
190
- // actual hex values. The canonical schema is the only contract; how you
191
- // reach it is up to you (Figma export, hand-pick, generated from a base).
192
- // ---------------------------------------------------------------------------
193
-
194
- export const brand: Brand = {
195
- name: "${consumer}",
196
- colors: {
197
- primary: {
198
- 50: "#eff6ff",
199
- 100: "#dbeafe",
200
- 200: "#bfdbfe",
201
- 300: "#93c5fd",
202
- 400: "#60a5fa",
203
- 500: "#3b82f6",
204
- 600: "#2563eb",
205
- 700: "#1d4ed8",
206
- 800: "#1e40af",
207
- 900: "#1e3a8a",
208
- },
209
- destructive: {
210
- 50: "#fef2f2",
211
- 100: "#fee2e2",
212
- 200: "#fecaca",
213
- 300: "#fca5a5",
214
- 400: "#f87171",
215
- 500: "#ef4444",
216
- 600: "#dc2626",
217
- 700: "#b91c1c",
218
- 800: "#991b1b",
219
- 900: "#7f1d1d",
220
- },
221
- neutral: {
222
- 50: "#f9fafb",
223
- 100: "#f3f4f6",
224
- 200: "#e5e7eb",
225
- 300: "#d1d5db",
226
- 400: "#9ca3af",
227
- 500: "#6b7280",
228
- 600: "#4b5563",
229
- 700: "#374151",
230
- 800: "#1f2937",
231
- 900: "#111827",
232
- },
233
- },
234
- // extensions: { mood: { ... }, rarity: { ... } },
235
- };
236
- `;
237
- }
238
- function tailwindConfig(consumer, native) {
239
- return `import type { Config } from "tailwindcss";
240
- ${native ? `// NativeWind v4 needs its preset; Genesis's goes after it. The NativeWind preset also declares
241
- // the theme variables, which NativeWind can't import from genesis.css. genesisNativewindContent
242
- // lists the Genesis React Native packages the app uses, wherever they are installed.
243
- import { fileURLToPath } from "node:url";
244
- import nativewindPreset from "nativewind/preset";
245
- import { genesisNativewindContent, genesisNativewindPreset as genesisPreset } from "@marktiderman/genesis-design-system/presets/nativewind";` : `import { genesisPreset } from "@marktiderman/genesis-design-system/presets/tailwind";`}
246
- import { brand } from "@${consumer}/brand";
247
-
248
- /**
249
- * Tailwind config \u2014 wires Genesis canonical tokens to your brand values.
250
- *
251
- * Genesis ships a tailwind preset that maps semantic class names
252
- * (\`bg-primary\`, \`text-foreground\`, etc.) to CSS variables. This config
253
- * extends that preset with your consumer's hex values, so Genesis
254
- * primitives automatically pick up your brand once the global.css import
255
- * fires.
256
- */
257
- const config: Config = {
258
- content: [
259
- "./app/**/*.{ts,tsx}",
260
- "./components/**/*.{ts,tsx}",
261
- ${native ? ` ...genesisNativewindContent({ root: fileURLToPath(new URL(".", import.meta.url)) }),
262
- ` : ""} ],
263
- presets: [${native ? "nativewindPreset, " : ""}genesisPreset],
264
- theme: {
265
- extend: {
266
- colors: {
267
- primary: {
268
- DEFAULT: brand.colors.primary[600],
269
- ...brand.colors.primary,
270
- },
271
- destructive: {
272
- DEFAULT: brand.colors.destructive[600],
273
- ...brand.colors.destructive,
274
- },
275
- },
276
- },
277
- },
278
- };
279
-
280
- export default config;
281
- `;
282
- }
283
- function globalCss() {
284
- return `/**
285
- * Genesis global stylesheet entry. Imports the Genesis theme (the CSS
286
- * variables every Genesis primitive's classes read: --background,
287
- * --foreground, --primary, \u2026) and the consumer's tailwind layers.
288
- */
289
- @import "@marktiderman/genesis-design-system/themes/genesis.css";
290
- @tailwind base;
291
- @tailwind components;
292
- @tailwind utilities;
293
- `;
294
- }
295
- function claudeMd(consumer) {
296
- return `# CLAUDE.md \u2014 ${consumer}
297
-
298
- This consumer was bootstrapped with \`@marktiderman/genesis-cli init ${consumer}\`.
299
-
300
- ## Workflow
301
-
302
- - **Reuse, then extend, then invent** (the Genesis way). Before building anything,
303
- run \`npx @marktiderman/genesis-cli features find <term>\` and read
304
- https://github.com/marktiderman/genesis/blob/main/docs/FRAMEWORK.md
305
- - **Brand changes live in \`packages/${consumer}-brand\`.** Don't fork Genesis
306
- primitives \u2014 edit your brand schema instead (Layer 1).
307
- - **Layout customization has 4 layers.** Default \u2192 named props \u2192
308
- ScreenContainer \u2192 brand schema. Reach for the lowest layer first.
309
-
310
- ## Critical rules
311
-
312
- - \`genesis doctor\` enforces the design-system rules. Don't bypass them with
313
- \`StyleSheet.create()\` or raw hex; use brand tokens and theme roles.
314
- - Run your test script before every commit.
315
- - Open RFCs in the genesis repo for missing primitives \u2014 don't fork
316
- locally and forget.
317
-
318
- ## Quick reference
319
-
320
- - \`packages/${consumer}-brand/src/brand.ts\` \u2014 your brand tokens + extensions
321
- - \`tailwind.config.ts\` \u2014 Genesis preset + brand color overrides
322
- - \`app/global.css\` \u2014 Genesis token sheet + tailwind layers
323
- `;
324
- }
325
-
326
- // src/introspect/comments.ts
327
- var MARKER = "@genesis";
328
- var TABLE_KEYS = { label: "string", labelField: "string", description: "string", noun: "string", nounPlural: "string" };
329
- var FIELD_KEYS = { label: "string", description: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
330
- var CommentSettingsError = class extends Error {
331
- };
332
- function parse(comment, keys, where) {
333
- if (!comment) return {};
334
- const at = comment.indexOf(MARKER);
335
- if (at < 0) return { description: comment.trim() || void 0 };
336
- const description = comment.slice(0, at).trim() || void 0;
337
- const raw = comment.slice(at + MARKER.length).trim();
338
- let value;
339
- try {
340
- value = JSON.parse(raw);
341
- } catch {
342
- throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
343
- }
344
- if (!value || typeof value !== "object" || Array.isArray(value)) {
345
- throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
346
- }
347
- const settings = {};
348
- for (const [key2, v] of Object.entries(value)) {
349
- const kind = keys[key2];
350
- if (!kind) {
351
- throw new CommentSettingsError(`${where}: unknown ${MARKER} setting "${key2}". Allowed: ${Object.keys(keys).join(", ")}.`);
352
- }
353
- if (typeof v !== kind) throw new CommentSettingsError(`${where}: ${MARKER} "${key2}" must be a ${kind}.`);
354
- settings[key2] = v;
355
- }
356
- return {
357
- ...description ? { description } : {},
358
- ...Object.keys(settings).length ? { settings } : {}
359
- };
360
- }
361
- function parseTableComment(comment, table) {
362
- return parse(comment, TABLE_KEYS, table);
363
- }
364
- function parseColumnComment(comment, column) {
365
- return parse(comment, FIELD_KEYS, column);
366
- }
367
-
368
- // src/introspect/model.ts
369
- function storageTypeOf(dbType) {
370
- const t = dbType.toLowerCase().replace(/\[\]$/, "");
371
- if (/^(smallint|integer|bigint|int2|int4|int8|real|double precision|float4|float8|numeric|decimal|money)\b/.test(t)) {
372
- return "number";
373
- }
374
- if (t === "boolean" || t === "bool") return "boolean";
375
- if (/^(date|timestamp|timestamptz|time|timetz|interval)\b/.test(t)) return "datetime";
376
- if (t === "json" || t === "jsonb") return "json";
377
- return "string";
378
- }
379
-
380
- // src/introspect/postgres.ts
381
- async function introspectPostgres(sql, schemas) {
263
+ async function readRelations(sql, scope, into) {
382
264
  const columns = await sql`
383
- select n.nspname as schema, c.relname as table,
265
+ select c.oid::text as oid, c.relkind::text as relkind, n.nspname as schema, c.relname as table,
384
266
  obj_description(c.oid, 'pg_class') as table_comment,
267
+ a.attnum::int as attnum,
385
268
  a.attname as column,
386
269
  format_type(a.atttypid, a.atttypmod) as db_type,
387
270
  t.typcategory = 'A' as is_array,
@@ -397,72 +280,205 @@ async function introspectPostgres(sql, schemas) {
397
280
  join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
398
281
  join pg_type t on t.oid = a.atttypid
399
282
  where c.relkind in ('r', 'p', 'v', 'm', 'f')
400
- and n.nspname = any(${schemas})
283
+ and ${where(sql, scope)}
401
284
  order by n.nspname, c.relname, a.attnum`;
402
285
  const keys = await sql`
403
- select n.nspname as schema, c.relname as table,
404
- array_agg(a.attname::text order by k.ord) as columns
286
+ select c.oid::text as oid, array_agg(k.attnum::int order by k.ord) as columns
405
287
  from pg_constraint con
406
288
  join pg_class c on c.oid = con.conrelid
407
289
  join pg_namespace n on n.oid = c.relnamespace
408
290
  cross join lateral unnest(con.conkey) with ordinality as k(attnum, ord)
409
- join pg_attribute a on a.attrelid = c.oid and a.attnum = k.attnum
410
- where con.contype = 'p' and n.nspname = any(${schemas})
411
- group by n.nspname, c.relname`;
291
+ where con.contype = 'p' and ${where(sql, scope)}
292
+ group by c.oid`;
412
293
  const links = await sql`
413
- select n.nspname as schema, c.relname as table, a.attname as column,
294
+ select c.oid::text as oid, con.conkey[1]::int as attnum,
414
295
  rn.nspname as ref_schema, rc.relname as ref_table, ra.attname as ref_column
415
296
  from pg_constraint con
416
297
  join pg_class c on c.oid = con.conrelid
417
298
  join pg_namespace n on n.oid = c.relnamespace
418
- join pg_attribute a on a.attrelid = c.oid and a.attnum = con.conkey[1]
419
299
  join pg_class rc on rc.oid = con.confrelid
420
300
  join pg_namespace rn on rn.oid = rc.relnamespace
421
301
  join pg_attribute ra on ra.attrelid = rc.oid and ra.attnum = con.confkey[1]
422
302
  where con.contype = 'f' and array_length(con.conkey, 1) = 1
423
- and n.nspname = any(${schemas})`;
424
- const keyOf = new Map(keys.map((k) => [`${k.schema}.${k.table}`, k.columns]));
425
- const linkOf = new Map(links.map((l) => [`${l.schema}.${l.table}.${l.column}`, l]));
426
- const tables = /* @__PURE__ */ new Map();
303
+ and ${where(sql, scope)}`;
304
+ const checks = await sql`
305
+ select c.oid::text as oid, con.conkey[1]::int as attnum, a.attname as column,
306
+ pg_get_constraintdef(con.oid) as definition
307
+ from pg_constraint con
308
+ join pg_class c on c.oid = con.conrelid
309
+ join pg_namespace n on n.oid = c.relnamespace
310
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = con.conkey[1]
311
+ where con.contype = 'c' and array_length(con.conkey, 1) = 1
312
+ and ${where(sql, scope)}
313
+ order by con.conname`;
314
+ const views = await sql`
315
+ select c.oid::text as oid, r.ev_action::text as ev_action
316
+ from pg_class c
317
+ join pg_namespace n on n.oid = c.relnamespace
318
+ join pg_rewrite r on r.ev_class = c.oid and r.rulename = '_RETURN'
319
+ where c.relkind = 'v'
320
+ and (pg_relation_is_updatable(c.oid, false) & 20) = 20
321
+ and not exists (select 1 from pg_rewrite o where o.ev_class = c.oid and o.rulename <> '_RETURN')
322
+ and ${where(sql, scope)}`;
323
+ const added = [];
427
324
  for (const row of columns) {
428
- const name = `${row.schema}.${row.table}`;
429
- let table = tables.get(name);
430
- if (!table) {
325
+ let relation = into.get(row.oid);
326
+ if (!relation) {
327
+ const name = qualifiedName(row.schema, row.table);
431
328
  const comment2 = parseTableComment(row.table_comment, name);
432
- table = {
433
- name,
434
- schema: row.schema,
435
- table: row.table,
436
- key: keyOf.get(name) ?? [],
437
- columns: [],
438
- ...comment2.description ? { description: comment2.description } : {},
439
- ...comment2.settings ? { settings: comment2.settings } : {}
329
+ relation = {
330
+ oid: row.oid,
331
+ table: {
332
+ name,
333
+ schema: row.schema,
334
+ table: row.table,
335
+ key: [],
336
+ columns: [],
337
+ ...comment2.description ? { description: comment2.description } : {},
338
+ ...comment2.settings ? { settings: comment2.settings } : {}
339
+ },
340
+ columns: /* @__PURE__ */ new Map(),
341
+ key: []
440
342
  };
441
- tables.set(name, table);
343
+ into.set(row.oid, relation);
344
+ added.push(row.oid);
442
345
  }
443
- const comment = parseColumnComment(row.column_comment, `${name}.${row.column}`);
444
- const link = linkOf.get(`${name}.${row.column}`);
445
- table.columns.push({
346
+ const comment = parseColumnComment(row.column_comment, `${relation.table.name}.${row.column}`);
347
+ const column = {
446
348
  name: row.column,
447
349
  dbType: row.db_type,
448
350
  type: storageTypeOf(row.db_type),
449
351
  array: row.is_array,
450
352
  nullable: !row.not_null,
353
+ // A view's columns always read as nullable: unknown until traced to a table.
354
+ ...row.relkind === "v" || row.relkind === "m" ? { nullableUnknown: true } : {},
451
355
  hasDefault: row.has_default,
452
356
  generated: row.generated,
453
357
  ...row.enum_values ? { enumValues: row.enum_values } : {},
454
- ...link ? { references: { resource: `${link.ref_schema}.${link.ref_table}`, field: link.ref_column } } : {},
455
358
  ...comment.description ? { description: comment.description } : {},
456
359
  ...comment.settings ? { settings: comment.settings } : {}
457
- });
360
+ };
361
+ relation.table.columns.push(column);
362
+ relation.columns.set(row.attnum, column);
458
363
  }
459
- return [...tables.values()];
364
+ for (const k of keys) {
365
+ const relation = into.get(k.oid);
366
+ if (relation) relation.key = k.columns;
367
+ }
368
+ for (const l of links) {
369
+ const column = into.get(l.oid)?.columns.get(l.attnum);
370
+ if (column) column.references = { resource: qualifiedName(l.ref_schema, l.ref_table), field: l.ref_column };
371
+ }
372
+ const listed = /* @__PURE__ */ new Map();
373
+ for (const check of checks) {
374
+ const column = into.get(check.oid)?.columns.get(check.attnum);
375
+ if (!column || column.array) continue;
376
+ const values = checkEnumValues(check.definition, check.column);
377
+ if (!values) continue;
378
+ const before = listed.get(column);
379
+ listed.set(column, before ? before.filter((v) => values.includes(v)) : values);
380
+ }
381
+ for (const [column, values] of listed) {
382
+ const allowed = column.enumValues ? column.enumValues.filter((v) => values.includes(v)) : values;
383
+ if (allowed.length > 0) column.enumValues = allowed;
384
+ }
385
+ for (const view of views) {
386
+ const relation = into.get(view.oid);
387
+ if (!relation) continue;
388
+ relation.origins = /* @__PURE__ */ new Map();
389
+ for (const origin of viewColumnOrigins(view.ev_action)) {
390
+ if (relation.columns.has(origin.position)) {
391
+ relation.origins.set(origin.position, { relation: String(origin.relation), column: origin.column });
392
+ }
393
+ }
394
+ }
395
+ return added;
396
+ }
397
+ function inherit(own, source) {
398
+ const settings = source.settings || own.settings ? { ...source.settings, ...own.settings } : void 0;
399
+ const description = own.description ?? source.description;
400
+ const both = own.enumValues && source.enumValues ? own.enumValues.filter((v) => source.enumValues.includes(v)) : void 0;
401
+ const enumValues = both?.length ? both : own.enumValues ?? source.enumValues;
402
+ return {
403
+ name: own.name,
404
+ dbType: own.dbType,
405
+ type: own.type,
406
+ array: own.array,
407
+ nullable: source.nullable,
408
+ ...source.nullableUnknown ? { nullableUnknown: true } : {},
409
+ hasDefault: own.hasDefault || source.hasDefault,
410
+ generated: source.generated,
411
+ ...enumValues ? { enumValues } : {},
412
+ ...source.references ? { references: source.references } : {},
413
+ ...description ? { description } : {},
414
+ ...settings ? { settings } : {}
415
+ };
460
416
  }
417
+ function resolveViews(relations) {
418
+ const done = /* @__PURE__ */ new Set();
419
+ const resolve14 = (relation, depth) => {
420
+ if (done.has(relation.oid) || !relation.origins || depth > MAX_VIEW_DEPTH) return;
421
+ done.add(relation.oid);
422
+ const sources = new Set([...relation.origins.values()].map((o) => o.relation));
423
+ if (sources.size !== 1) return;
424
+ const source = relations.get([...sources][0]);
425
+ if (!source) return;
426
+ resolve14(source, depth + 1);
427
+ const viewAttnumOf = /* @__PURE__ */ new Map();
428
+ for (const [attnum, origin] of relation.origins) {
429
+ const own = relation.columns.get(attnum);
430
+ const from = source.columns.get(origin.column);
431
+ if (!own || !from) continue;
432
+ const merged = inherit(own, from);
433
+ relation.columns.set(attnum, merged);
434
+ relation.table.columns[relation.table.columns.indexOf(own)] = merged;
435
+ if (!viewAttnumOf.has(origin.column)) viewAttnumOf.set(origin.column, attnum);
436
+ }
437
+ if (relation.key.length === 0 && source.key.length > 0 && source.key.every((k) => viewAttnumOf.has(k))) {
438
+ relation.key = source.key.map((k) => viewAttnumOf.get(k));
439
+ }
440
+ const theirs = source.table.settings;
441
+ const viewColumns = new Set(relation.table.columns.map((c) => c.name));
442
+ const inherited = {
443
+ ...theirs?.noun ? { noun: theirs.noun } : {},
444
+ ...theirs?.nounPlural ? { nounPlural: theirs.nounPlural } : {},
445
+ ...theirs?.labelField && viewColumns.has(theirs.labelField) ? { labelField: theirs.labelField } : {}
446
+ };
447
+ if (Object.keys(inherited).length) relation.table.settings = { ...inherited, ...relation.table.settings };
448
+ };
449
+ for (const relation of relations.values()) resolve14(relation, 0);
450
+ }
451
+ async function introspectPostgres(sql, schemas) {
452
+ const relations = /* @__PURE__ */ new Map();
453
+ const wanted = await readRelations(sql, { schemas: [...schemas] }, relations);
454
+ for (let depth = 0; depth < MAX_VIEW_DEPTH; depth++) {
455
+ const missing = /* @__PURE__ */ new Set();
456
+ for (const relation of relations.values()) {
457
+ for (const origin of relation.origins?.values() ?? []) {
458
+ if (!relations.has(origin.relation)) missing.add(origin.relation);
459
+ }
460
+ }
461
+ if (missing.size === 0) break;
462
+ const added = await readRelations(sql, { oids: [...missing].sort() }, relations);
463
+ if (added.length === 0) break;
464
+ }
465
+ resolveViews(relations);
466
+ return wanted.map((oid) => {
467
+ const relation = relations.get(oid);
468
+ return { ...relation.table, key: relation.key.map((attnum) => relation.columns.get(attnum).name) };
469
+ });
470
+ }
471
+ var MAX_VIEW_DEPTH;
472
+ var init_postgres = __esm({
473
+ "src/introspect/postgres.ts"() {
474
+ init_catalog_text();
475
+ init_comments();
476
+ init_model();
477
+ MAX_VIEW_DEPTH = 8;
478
+ }
479
+ });
461
480
 
462
481
  // src/introspect/openapi.ts
463
- var PK = /<pk\/>/;
464
- var FK = /<fk table='([^']+)' column='([^']+)'\/>/;
465
- var NOTES = /\s*Note:\s*This is a (?:Primary|Foreign) Key[^<]*<(?:pk|fk)[^>]*\/>/g;
466
482
  function clean(description) {
467
483
  if (!description) return void 0;
468
484
  return description.replace(NOTES, "").trim() || void 0;
@@ -472,7 +488,7 @@ function introspectOpenApi(doc, schema = "public") {
472
488
  if (!definitions) throw new Error("This OpenAPI document has no definitions. Is it a PostgREST (Supabase /rest/v1/) spec?");
473
489
  return Object.keys(definitions).sort().map((tableName) => {
474
490
  const def = definitions[tableName];
475
- const name = `${schema}.${tableName}`;
491
+ const name = qualifiedName(schema, tableName);
476
492
  const required = new Set(def.required ?? []);
477
493
  const key2 = [];
478
494
  const columns = Object.entries(def.properties ?? {}).map(([column, prop]) => {
@@ -487,13 +503,13 @@ function introspectOpenApi(doc, schema = "public") {
487
503
  dbType,
488
504
  type: storageTypeOf(format),
489
505
  array: isArray,
490
- // PostgREST lists NOT NULL columns without a default as required;
491
- // the rest may be null or are filled by the database.
506
+ // PostgREST (v9 on) lists every NOT NULL column as required, with or
507
+ // without a default (`filter (not . colNullable)` in its OpenAPI.hs).
492
508
  nullable: !required.has(column),
493
509
  hasDefault: prop.default !== void 0,
494
510
  generated: false,
495
511
  ...prop.enum ? { enumValues: prop.enum.map(String) } : {},
496
- ...fk ? { references: { resource: `${schema}.${fk[1]}`, field: fk[2] } } : {},
512
+ ...fk ? { references: { resource: qualifiedName(schema, fk[1]), field: fk[2] } } : {},
497
513
  ...comment2.description ? { description: comment2.description } : {},
498
514
  ...comment2.settings ? { settings: comment2.settings } : {}
499
515
  };
@@ -510,16 +526,18 @@ function introspectOpenApi(doc, schema = "public") {
510
526
  };
511
527
  });
512
528
  }
529
+ var PK, FK, NOTES;
530
+ var init_openapi = __esm({
531
+ "src/introspect/openapi.ts"() {
532
+ init_comments();
533
+ init_model();
534
+ PK = /<pk\/>/;
535
+ FK = /<fk table='([^']+)' column='([^']+)'\/>/;
536
+ NOTES = /\s*Note:\s*This is a (?:Primary|Foreign) Key[^<]*<(?:pk|fk)[^>]*\/>/g;
537
+ }
538
+ });
513
539
 
514
540
  // src/introspect/emit.ts
515
- var TS_TYPE = {
516
- string: "string",
517
- number: "number",
518
- boolean: "boolean",
519
- // The studio handler sends dates and timestamps as Postgres text, exactly.
520
- datetime: "string",
521
- json: "unknown"
522
- };
523
541
  function quote(value) {
524
542
  return JSON.stringify(value);
525
543
  }
@@ -542,7 +560,7 @@ function tsType(column) {
542
560
  function field(column, indent) {
543
561
  const parts = [`name: ${quote(column.name)}`, `type: ${quote(column.type)}`, `dbType: ${quote(column.dbType)}`];
544
562
  if (column.array) parts.push("array: true");
545
- if (column.nullable) parts.push("nullable: true");
563
+ if (!column.nullableUnknown) parts.push(column.nullable ? "nullable: true" : "nullable: false");
546
564
  if (column.nullable || column.hasDefault || column.generated) parts.push("optional: true");
547
565
  if (column.hasDefault) parts.push("hasDefault: true");
548
566
  if (column.generated) parts.push("generated: true");
@@ -559,8 +577,6 @@ function field(column, indent) {
559
577
  if (column.settings?.sensitive) parts.push("sensitive: true");
560
578
  return `${indent}{ ${parts.join(", ")} },`;
561
579
  }
562
- var EmitError = class extends Error {
563
- };
564
580
  function emitContracts(tables, options) {
565
581
  const sorted = [...tables].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
566
582
  const seen = /* @__PURE__ */ new Map();
@@ -625,6 +641,363 @@ function emitContracts(tables, options) {
625
641
  out.push("}", "");
626
642
  return out.join("\n");
627
643
  }
644
+ var TS_TYPE, EmitError;
645
+ var init_emit = __esm({
646
+ "src/introspect/emit.ts"() {
647
+ TS_TYPE = {
648
+ string: "string",
649
+ number: "number",
650
+ boolean: "boolean",
651
+ // The studio handler sends dates and timestamps as Postgres text, exactly.
652
+ datetime: "string",
653
+ json: "unknown"
654
+ };
655
+ EmitError = class extends Error {
656
+ name = "EmitError";
657
+ };
658
+ }
659
+ });
660
+
661
+ // src/introspect/index.ts
662
+ var introspect_exports = {};
663
+ __export(introspect_exports, {
664
+ CommentSettingsError: () => CommentSettingsError,
665
+ EmitError: () => EmitError,
666
+ emitContracts: () => emitContracts,
667
+ introspectOpenApi: () => introspectOpenApi,
668
+ introspectPostgres: () => introspectPostgres,
669
+ parseColumnComment: () => parseColumnComment,
670
+ parseTableComment: () => parseTableComment,
671
+ qualifiedName: () => qualifiedName
672
+ });
673
+ var init_introspect = __esm({
674
+ "src/introspect/index.ts"() {
675
+ init_postgres();
676
+ init_openapi();
677
+ init_emit();
678
+ init_comments();
679
+ init_model();
680
+ }
681
+ });
682
+
683
+ // src/scaffolder.ts
684
+ var VALID_NAME_PATTERN = /^[a-z][a-z0-9-]{1,30}$/;
685
+ var NOOP_LOGGER = {
686
+ info() {
687
+ },
688
+ warn() {
689
+ },
690
+ error() {
691
+ }
692
+ };
693
+ function validateConsumerName(name) {
694
+ if (!VALID_NAME_PATTERN.test(name)) {
695
+ throw new Error(
696
+ `Invalid consumer name "${name}". Must be lowercase letters/digits/hyphens, 2-31 chars, starting with a letter (e.g., "acme", "arcade-mobile").`
697
+ );
698
+ }
699
+ }
700
+ function planScaffold(opts) {
701
+ const consumer = opts.consumerName;
702
+ const genesisVersion = opts.genesisVersion ?? "workspace:^";
703
+ return [
704
+ {
705
+ path: `packages/${consumer}-brand/package.json`,
706
+ content: brandPackageJson(consumer, genesisVersion)
707
+ },
708
+ {
709
+ path: `packages/${consumer}-brand/src/brand.ts`,
710
+ content: brandSchema(consumer)
711
+ },
712
+ {
713
+ path: `packages/${consumer}-brand/src/index.ts`,
714
+ content: `export { brand } from "./brand";
715
+ export type { Brand } from "./brand";
716
+ `
717
+ },
718
+ {
719
+ path: `packages/${consumer}-brand/tsconfig.json`,
720
+ content: brandTsconfig()
721
+ },
722
+ {
723
+ path: `tailwind.config.ts`,
724
+ content: tailwindConfig(consumer, opts.native ?? false)
725
+ },
726
+ {
727
+ path: `app/global.css`,
728
+ content: globalCss()
729
+ },
730
+ {
731
+ path: `CLAUDE.md`,
732
+ content: claudeMd(consumer)
733
+ }
734
+ ];
735
+ }
736
+ async function runScaffold(opts, fs) {
737
+ validateConsumerName(opts.consumerName);
738
+ const log = opts.logger ?? NOOP_LOGGER;
739
+ const plan = planScaffold(opts);
740
+ const written = [];
741
+ const skipped = [];
742
+ const conflicts = [];
743
+ for (const file of plan) {
744
+ const fullPath = joinPath(opts.targetDir, file.path);
745
+ const dir = dirname(fullPath);
746
+ await fs.mkdirp(dir);
747
+ const exists = await fs.exists(fullPath);
748
+ if (!exists) {
749
+ await fs.writeFile(fullPath, file.content);
750
+ written.push(file.path);
751
+ log.info(`\u2714 wrote ${file.path}`);
752
+ continue;
753
+ }
754
+ const existing = await fs.readFile(fullPath);
755
+ if (existing === file.content) {
756
+ skipped.push(file.path);
757
+ log.info(`= skipped ${file.path} (identical)`);
758
+ continue;
759
+ }
760
+ if (opts.emitConflicts) {
761
+ const nextPath = `${fullPath}.genesis-next`;
762
+ await fs.writeFile(nextPath, file.content);
763
+ conflicts.push(`${file.path}.genesis-next`);
764
+ log.warn(
765
+ `! diff ${file.path} \u2014 wrote .genesis-next sibling for review`
766
+ );
767
+ } else {
768
+ skipped.push(file.path);
769
+ log.warn(
770
+ `! skipped ${file.path} (exists; pass --emit-conflicts to diff)`
771
+ );
772
+ }
773
+ }
774
+ return { written, skipped, conflicts };
775
+ }
776
+ function joinPath(...parts) {
777
+ return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
778
+ }
779
+ function dirname(path28) {
780
+ const idx = path28.lastIndexOf("/");
781
+ return idx === -1 ? "." : path28.slice(0, idx);
782
+ }
783
+ function brandPackageJson(consumer, genesisVersion) {
784
+ return JSON.stringify(
785
+ {
786
+ name: `@${consumer}/brand`,
787
+ version: "0.1.0",
788
+ private: true,
789
+ type: "module",
790
+ main: "./src/index.ts",
791
+ types: "./src/index.ts",
792
+ description: `Brand tokens + extensions for the ${consumer} app. Consumed by Genesis primitives via canonical schema.`,
793
+ peerDependencies: {
794
+ "@marktiderman/genesis-design-system": genesisVersion
795
+ }
796
+ },
797
+ null,
798
+ 2
799
+ ) + "\n";
800
+ }
801
+ function brandTsconfig() {
802
+ return JSON.stringify(
803
+ {
804
+ extends: "../../tsconfig.base.json",
805
+ compilerOptions: {
806
+ outDir: "dist",
807
+ rootDir: "src"
808
+ },
809
+ include: ["src"]
810
+ },
811
+ null,
812
+ 2
813
+ ) + "\n";
814
+ }
815
+ function brandSchema(consumer) {
816
+ return `/**
817
+ * @${consumer}/brand \u2014 canonical brand tokens + extensions.
818
+ *
819
+ * Genesis primitives consume tokens from this file via the design-system
820
+ * provider. Edit colors/spacing/typography here to retheme every screen
821
+ * at once. Domain-specific tokens (e.g., "mood" for Acme, "rarity" for
822
+ * a game app) go under \`extensions\` \u2014 Genesis primitives don't read these,
823
+ * but consumer composites do via \`useGenesisExtension(key)\`.
824
+ *
825
+ * Schema is intentionally narrow at the top level. Add categories under
826
+ * \`extensions\` rather than inventing new top-level slots.
827
+ */
828
+
829
+ export interface BrandColorScale {
830
+ 50: string;
831
+ 100: string;
832
+ 200: string;
833
+ 300: string;
834
+ 400: string;
835
+ 500: string;
836
+ 600: string;
837
+ 700: string;
838
+ 800: string;
839
+ 900: string;
840
+ }
841
+
842
+ export interface BrandColors {
843
+ primary: BrandColorScale;
844
+ destructive: BrandColorScale;
845
+ /** Neutral / gray scale used for surfaces, text, borders. */
846
+ neutral: BrandColorScale;
847
+ }
848
+
849
+ export interface Brand {
850
+ /** Slug used for namespacing (e.g., extensions key prefix). */
851
+ name: string;
852
+ colors: BrandColors;
853
+ /**
854
+ * Domain-specific token categories. Consumer composites read these
855
+ * via \`useGenesisExtension("<key>")\`. Genesis primitives do NOT read
856
+ * extensions \u2014 only canonical \`colors\`.
857
+ */
858
+ extensions?: Record<string, Record<string | number, unknown>>;
859
+ }
860
+
861
+ // ---------------------------------------------------------------------------
862
+ // Default brand \u2014 replace these placeholder values with your design's
863
+ // actual hex values. The canonical schema is the only contract; how you
864
+ // reach it is up to you (Figma export, hand-pick, generated from a base).
865
+ // ---------------------------------------------------------------------------
866
+
867
+ export const brand: Brand = {
868
+ name: "${consumer}",
869
+ colors: {
870
+ primary: {
871
+ 50: "#eff6ff",
872
+ 100: "#dbeafe",
873
+ 200: "#bfdbfe",
874
+ 300: "#93c5fd",
875
+ 400: "#60a5fa",
876
+ 500: "#3b82f6",
877
+ 600: "#2563eb",
878
+ 700: "#1d4ed8",
879
+ 800: "#1e40af",
880
+ 900: "#1e3a8a",
881
+ },
882
+ destructive: {
883
+ 50: "#fef2f2",
884
+ 100: "#fee2e2",
885
+ 200: "#fecaca",
886
+ 300: "#fca5a5",
887
+ 400: "#f87171",
888
+ 500: "#ef4444",
889
+ 600: "#dc2626",
890
+ 700: "#b91c1c",
891
+ 800: "#991b1b",
892
+ 900: "#7f1d1d",
893
+ },
894
+ neutral: {
895
+ 50: "#f9fafb",
896
+ 100: "#f3f4f6",
897
+ 200: "#e5e7eb",
898
+ 300: "#d1d5db",
899
+ 400: "#9ca3af",
900
+ 500: "#6b7280",
901
+ 600: "#4b5563",
902
+ 700: "#374151",
903
+ 800: "#1f2937",
904
+ 900: "#111827",
905
+ },
906
+ },
907
+ // extensions: { mood: { ... }, rarity: { ... } },
908
+ };
909
+ `;
910
+ }
911
+ function tailwindConfig(consumer, native) {
912
+ return `import type { Config } from "tailwindcss";
913
+ ${native ? `// NativeWind v4 needs its preset; Genesis's goes after it. The NativeWind preset also declares
914
+ // the theme variables, which NativeWind can't import from genesis.css. genesisNativewindContent
915
+ // lists the Genesis React Native packages the app uses, wherever they are installed.
916
+ import { fileURLToPath } from "node:url";
917
+ import nativewindPreset from "nativewind/preset";
918
+ import { genesisNativewindContent, genesisNativewindPreset as genesisPreset } from "@marktiderman/genesis-design-system/presets/nativewind";` : `import { genesisPreset } from "@marktiderman/genesis-design-system/presets/tailwind";`}
919
+ import { brand } from "@${consumer}/brand";
920
+
921
+ /**
922
+ * Tailwind config \u2014 wires Genesis canonical tokens to your brand values.
923
+ *
924
+ * Genesis ships a tailwind preset that maps semantic class names
925
+ * (\`bg-primary\`, \`text-foreground\`, etc.) to CSS variables. This config
926
+ * extends that preset with your consumer's hex values, so Genesis
927
+ * primitives automatically pick up your brand once the global.css import
928
+ * fires.
929
+ */
930
+ const config: Config = {
931
+ content: [
932
+ "./app/**/*.{ts,tsx}",
933
+ "./components/**/*.{ts,tsx}",
934
+ ${native ? ` ...genesisNativewindContent({ root: fileURLToPath(new URL(".", import.meta.url)) }),
935
+ ` : ""} ],
936
+ presets: [${native ? "nativewindPreset, " : ""}genesisPreset],
937
+ theme: {
938
+ extend: {
939
+ colors: {
940
+ primary: {
941
+ DEFAULT: brand.colors.primary[600],
942
+ ...brand.colors.primary,
943
+ },
944
+ destructive: {
945
+ DEFAULT: brand.colors.destructive[600],
946
+ ...brand.colors.destructive,
947
+ },
948
+ },
949
+ },
950
+ },
951
+ };
952
+
953
+ export default config;
954
+ `;
955
+ }
956
+ function globalCss() {
957
+ return `/**
958
+ * Genesis global stylesheet entry. Imports the Genesis theme (the CSS
959
+ * variables every Genesis primitive's classes read: --background,
960
+ * --foreground, --primary, \u2026) and the consumer's tailwind layers.
961
+ */
962
+ @import "@marktiderman/genesis-design-system/themes/genesis.css";
963
+ @tailwind base;
964
+ @tailwind components;
965
+ @tailwind utilities;
966
+ `;
967
+ }
968
+ function claudeMd(consumer) {
969
+ return `# CLAUDE.md \u2014 ${consumer}
970
+
971
+ This consumer was bootstrapped with \`@marktiderman/genesis-cli init ${consumer}\`.
972
+
973
+ ## Workflow
974
+
975
+ - **Reuse, then extend, then invent** (the Genesis way). Before building anything,
976
+ run \`npx @marktiderman/genesis-cli features find <term>\` and read
977
+ https://github.com/marktiderman/genesis/blob/main/docs/FRAMEWORK.md
978
+ - **Brand changes live in \`packages/${consumer}-brand\`.** Don't fork Genesis
979
+ primitives \u2014 edit your brand schema instead (Layer 1).
980
+ - **Layout customization has 4 layers.** Default \u2192 named props \u2192
981
+ ScreenContainer \u2192 brand schema. Reach for the lowest layer first.
982
+
983
+ ## Critical rules
984
+
985
+ - \`genesis doctor\` enforces the design-system rules. Don't bypass them with
986
+ \`StyleSheet.create()\` or raw hex; use brand tokens and theme roles.
987
+ - Run your test script before every commit.
988
+ - Open RFCs in the genesis repo for missing primitives \u2014 don't fork
989
+ locally and forget.
990
+
991
+ ## Quick reference
992
+
993
+ - \`packages/${consumer}-brand/src/brand.ts\` \u2014 your brand tokens + extensions
994
+ - \`tailwind.config.ts\` \u2014 Genesis preset + brand color overrides
995
+ - \`app/global.css\` \u2014 Genesis token sheet + tailwind layers
996
+ `;
997
+ }
998
+
999
+ // src/index.ts
1000
+ init_introspect();
628
1001
 
629
1002
  // src/studio/wire-route.ts
630
1003
  function routeTags(source) {
@@ -663,8 +1036,8 @@ function routeTags(source) {
663
1036
  var GUARD = /<((?:[A-Z]\w*)?(?:Admin|Staff)\w*(?:Guard|Route|Only)|RequireAdmin|RequireStaff)>/;
664
1037
  function wireStudioRoute(source, route, pageImportPath) {
665
1038
  const tags = routeTags(source);
666
- const relative7 = route.replace(/^\//, "");
667
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative7.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
1039
+ const relative8 = route.replace(/^\//, "");
1040
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative8.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
668
1041
  if (existing) {
669
1042
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
670
1043
  }
@@ -672,17 +1045,17 @@ function wireStudioRoute(source, route, pageImportPath) {
672
1045
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
673
1046
  if (roots.length !== 1) {
674
1047
  return {
675
- 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="${relative7}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
1048
+ 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="${relative8}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
676
1049
  };
677
1050
  }
678
1051
  const layout = roots[0];
679
1052
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
680
- if (base && !relative7.startsWith(`${base}/`)) {
1053
+ if (base && !relative8.startsWith(`${base}/`)) {
681
1054
  return {
682
1055
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
683
1056
  };
684
1057
  }
685
- const childPath = base ? relative7.slice(base.length + 1) : relative7;
1058
+ const childPath = base ? relative8.slice(base.length + 1) : relative8;
686
1059
  const guard = GUARD.exec(source)?.[1];
687
1060
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
688
1061
  const before = source.slice(0, layout.close);
@@ -996,19 +1369,19 @@ ${line}
996
1369
  var BUILD_GUARD_ENV = "GENESIS_DOCTOR_BUILDING";
997
1370
  function buildCommands(root, config) {
998
1371
  if (config.build) return config.build;
999
- const pkgFile = path14.join(root, "package.json");
1372
+ const pkgFile = path18.join(root, "package.json");
1000
1373
  const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
1001
1374
  const pm = packageManager(root);
1002
1375
  return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
1003
1376
  }
1004
1377
  function packageManager(root) {
1005
- let dir = path14.resolve(root);
1378
+ let dir = path18.resolve(root);
1006
1379
  for (; ; ) {
1007
- if (existsSync(path14.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1008
- if (existsSync(path14.join(dir, "bun.lock")) || existsSync(path14.join(dir, "bun.lockb"))) return "bun";
1009
- if (existsSync(path14.join(dir, "yarn.lock"))) return "yarn";
1010
- if (existsSync(path14.join(dir, "package-lock.json"))) return "npm";
1011
- const parent = path14.dirname(dir);
1380
+ if (existsSync(path18.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1381
+ if (existsSync(path18.join(dir, "bun.lock")) || existsSync(path18.join(dir, "bun.lockb"))) return "bun";
1382
+ if (existsSync(path18.join(dir, "yarn.lock"))) return "yarn";
1383
+ if (existsSync(path18.join(dir, "package-lock.json"))) return "npm";
1384
+ const parent = path18.dirname(dir);
1012
1385
  if (parent === dir) return "npm";
1013
1386
  dir = parent;
1014
1387
  }
@@ -1104,44 +1477,61 @@ var KNOWN = /* @__PURE__ */ new Set([
1104
1477
  "supabase",
1105
1478
  "packages",
1106
1479
  "routesDir",
1480
+ "packageRules",
1481
+ "ratchet",
1482
+ "contracts",
1107
1483
  "$schema",
1108
1484
  "$comment"
1109
1485
  ]);
1110
1486
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
1111
- var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
1487
+ var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
1488
+ var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
1489
+ var PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
1490
+ var CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
1112
1491
  var PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
1113
1492
  var PACK_KEYS = {
1114
1493
  native: { routerRoot: "path" },
1115
1494
  supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
1116
1495
  packages: { base: "string" }
1117
1496
  };
1118
- function appPath(v, where, fail) {
1119
- if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
1120
- if (path14.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
1121
- const norm = path14.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
1122
- if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where} must be a folder inside the app ("${v}")`);
1497
+ function appPath(v, where2, fail) {
1498
+ if (typeof v !== "string" || !v.trim()) return fail(`${where2} must be a non-empty path`);
1499
+ if (path18.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
1500
+ const norm = path18.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
1501
+ if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where2} must be a folder inside the app ("${v}")`);
1123
1502
  return norm;
1124
1503
  }
1125
1504
  function loadConfig(root, configPath) {
1126
1505
  if (configPath) {
1127
- const file = path14.resolve(root, configPath);
1506
+ const file = path18.resolve(root, configPath);
1128
1507
  if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
1129
1508
  const json = readJson(file);
1130
- const block = path14.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
1131
- return { config: validateConfig(block ?? {}, file), file, dir: path14.dirname(file) };
1509
+ const block = path18.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
1510
+ return { config: validateConfig(block ?? {}, file), file, dir: path18.dirname(file) };
1132
1511
  }
1133
- const own = path14.join(root, "genesis.config.json");
1512
+ const own = path18.join(root, "genesis.config.json");
1134
1513
  if (existsSync(own)) {
1135
1514
  const block = readGenesisConfig(root)?.raw.doctor;
1136
1515
  return { config: validateConfig(block ?? {}, own), file: own, dir: root };
1137
1516
  }
1138
- const pkg = path14.join(root, "package.json");
1517
+ const pkg = path18.join(root, "package.json");
1139
1518
  if (existsSync(pkg)) {
1140
1519
  const block = readJson(pkg)?.genesis?.doctor;
1141
- if (block !== void 0) return { config: validateConfig(block, pkg), file: pkg, dir: root };
1520
+ if (block !== void 0 && !isPackageDeclaration(block)) return { config: validateConfig(block, pkg), file: pkg, dir: root };
1142
1521
  }
1143
1522
  return { config: {}, file: null, dir: root };
1144
1523
  }
1524
+ function doctorBlock(json, file, explicit) {
1525
+ const j = json;
1526
+ if (path18.basename(file) === "package.json") return j?.genesis?.doctor;
1527
+ return explicit ? j?.doctor ?? j : j?.doctor;
1528
+ }
1529
+ function isPackageDeclaration(block) {
1530
+ if (typeof block === "string") return true;
1531
+ if (!isObject(block)) return false;
1532
+ const keys = Object.keys(block).filter((k) => k !== "$comment");
1533
+ return keys.some((k) => ["prefer", "primitives", "plugin", "enforce"].includes(k)) && !keys.some((k) => KNOWN.has(k));
1534
+ }
1145
1535
  function readJson(file) {
1146
1536
  try {
1147
1537
  return JSON.parse(readFileSync(file, "utf8"));
@@ -1150,7 +1540,7 @@ function readJson(file) {
1150
1540
  }
1151
1541
  }
1152
1542
  function readGenesisConfig(root) {
1153
- const file = path14.join(root, "genesis.config.json");
1543
+ const file = path18.join(root, "genesis.config.json");
1154
1544
  if (!existsSync(file)) return null;
1155
1545
  const raw = readJson(file);
1156
1546
  if (!isObject(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
@@ -1180,18 +1570,18 @@ function validatePrivacy(raw, source = "config") {
1180
1570
  if (c.collects !== void 0) {
1181
1571
  if (!Array.isArray(c.collects)) fail(`privacy.collects must be a list`);
1182
1572
  out.collects = c.collects.map((entry, i) => {
1183
- const where = `privacy.collects[${i}]`;
1184
- if (!isObject(entry)) return fail(`${where} must be an object`);
1185
- for (const key2 of Object.keys(entry)) if (!DATA_USE_KEYS.has(key2)) fail(`${where}: unknown setting "${key2}"`);
1573
+ const where2 = `privacy.collects[${i}]`;
1574
+ if (!isObject(entry)) return fail(`${where2} must be an object`);
1575
+ for (const key2 of Object.keys(entry)) if (!DATA_USE_KEYS.has(key2)) fail(`${where2}: unknown setting "${key2}"`);
1186
1576
  if (typeof entry.type !== "string" || !privacyDataType(entry.type)) {
1187
- fail(`${where}.type "${String(entry.type)}" is not one of ${Object.keys(PRIVACY_DATA_TYPES).join(", ")}`);
1577
+ fail(`${where2}.type "${String(entry.type)}" is not one of ${Object.keys(PRIVACY_DATA_TYPES).join(", ")}`);
1188
1578
  }
1189
- if (!isStringList(entry.purposes) || entry.purposes.length === 0) fail(`${where}.purposes must be a non-empty list`);
1579
+ if (!isStringList(entry.purposes) || entry.purposes.length === 0) fail(`${where2}.purposes must be a non-empty list`);
1190
1580
  for (const p of entry.purposes) {
1191
- if (!(p in PRIVACY_PURPOSES)) fail(`${where}.purposes: "${p}" is not one of ${Object.keys(PRIVACY_PURPOSES).join(", ")}`);
1581
+ if (!(p in PRIVACY_PURPOSES)) fail(`${where2}.purposes: "${p}" is not one of ${Object.keys(PRIVACY_PURPOSES).join(", ")}`);
1192
1582
  }
1193
- if (typeof entry.linked !== "boolean") fail(`${where}.linked must be true or false`);
1194
- if (typeof entry.tracking !== "boolean") fail(`${where}.tracking must be true or false`);
1583
+ if (typeof entry.linked !== "boolean") fail(`${where2}.linked must be true or false`);
1584
+ if (typeof entry.tracking !== "boolean") fail(`${where2}.tracking must be true or false`);
1195
1585
  return { type: entry.type, purposes: [...new Set(entry.purposes)], linked: entry.linked, tracking: entry.tracking };
1196
1586
  });
1197
1587
  }
@@ -1260,6 +1650,7 @@ function validateConfig(raw, source = "config") {
1260
1650
  if (!isObject(c.rules)) fail(`"rules" must be an object of rule \u2192 level`);
1261
1651
  for (const [rule, level] of Object.entries(c.rules)) {
1262
1652
  if (!LEVELS.has(level)) fail(`rules.${rule} must be "error", "warn", "info" or "off"`);
1653
+ if (META_RULES.has(rule)) fail(`rules can't set ${rule}: it guards the config itself`);
1263
1654
  }
1264
1655
  }
1265
1656
  if (c.allow !== void 0) {
@@ -1269,6 +1660,7 @@ function validateConfig(raw, source = "config") {
1269
1660
  const entry = e;
1270
1661
  if (typeof entry.rule !== "string" || !entry.rule) fail(`allow[${i}] needs a "rule"`);
1271
1662
  if (typeof entry.reason !== "string" || !entry.reason.trim()) fail(`allow[${i}] (${entry.rule}) needs a "reason"`);
1663
+ if (META_RULES.has(entry.rule)) fail(`allow[${i}] can't allow ${entry.rule}: it guards the allow list itself`);
1272
1664
  for (const k of ["file", "match"]) {
1273
1665
  if (entry[k] !== void 0 && typeof entry[k] !== "string") fail(`allow[${i}].${k} must be a string`);
1274
1666
  }
@@ -1284,13 +1676,42 @@ function validateConfig(raw, source = "config") {
1284
1676
  for (const k of ["files", "exclude"]) {
1285
1677
  if (rule[k] !== void 0 && !isStringList(rule[k])) fail(`patterns[${i}].${k} must be a list of globs`);
1286
1678
  }
1679
+ if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") fail(`patterns[${i}].newOnly must be true or false`);
1287
1680
  });
1288
1681
  }
1682
+ if (c.packageRules !== void 0) {
1683
+ if (!isObject(c.packageRules)) fail(`"packageRules" must be an object of package rule id \u2192 { level?, files?, exclude?, reason }`);
1684
+ for (const [id, v] of Object.entries(c.packageRules)) {
1685
+ const where2 = `packageRules["${id}"]`;
1686
+ if (!id.includes("/")) fail(`${where2}: package rule ids are namespaced by package, e.g. "ui/lists-use-resource-view"`);
1687
+ if (!isObject(v)) fail(`${where2} must be an object`);
1688
+ const setting = v;
1689
+ for (const k of Object.keys(setting)) if (!PACKAGE_RULE_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: level, files, exclude, reason)`);
1690
+ if (typeof setting.reason !== "string" || !setting.reason.trim()) fail(`${where2} needs a "reason": a package rule is never changed silently`);
1691
+ if (setting.level !== void 0 && !LEVELS.has(setting.level)) fail(`${where2}.level must be "error", "warn", "info" or "off"`);
1692
+ for (const k of ["files", "exclude"]) if (setting[k] !== void 0 && !isStringList(setting[k])) fail(`${where2}.${k} must be a list of globs`);
1693
+ }
1694
+ }
1695
+ if (c.ratchet !== void 0 && typeof c.ratchet !== "boolean" && !isStringList(c.ratchet)) fail(`"ratchet" must be true, false or a list of rule ids`);
1289
1696
  if (c.packs !== void 0) {
1290
1697
  if (!isStringList(c.packs)) fail(`"packs" must be a list, e.g. ["native", "supabase"]`);
1291
1698
  for (const p of c.packs) if (!PACKS.has(p)) fail(`packs: unknown pack "${p}" (known: ${[...PACKS].join(", ")})`);
1292
1699
  if (new Set(c.packs).size !== c.packs.length) fail(`packs: lists a pack twice`);
1293
1700
  }
1701
+ if (c.contracts !== void 0) {
1702
+ if (!isObject(c.contracts)) fail(`"contracts" must be an object: { out?, schemas?, databaseEnv? }`);
1703
+ const contracts = c.contracts;
1704
+ for (const k of Object.keys(contracts)) if (!CONTRACT_KEYS.has(k)) fail(`contracts: unknown setting "${k}" (known: out, schemas, databaseEnv)`);
1705
+ if (!(c.packs ?? []).includes("supabase")) fail(`"contracts" is set but the supabase pack is not in "packs"`);
1706
+ if (contracts.out !== void 0) {
1707
+ if (typeof contracts.out !== "string" || !contracts.out.trim()) fail(`contracts.out must be a file path`);
1708
+ if (path18.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1709
+ }
1710
+ if (contracts.schemas !== void 0 && !isStringList(contracts.schemas)) fail(`contracts.schemas must be a list of schema names`);
1711
+ if (contracts.databaseEnv !== void 0 && (typeof contracts.databaseEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(contracts.databaseEnv))) {
1712
+ fail(`contracts.databaseEnv must be an environment variable name`);
1713
+ }
1714
+ }
1294
1715
  for (const [pack, keys] of Object.entries(PACK_KEYS)) {
1295
1716
  const block = c[pack];
1296
1717
  if (block === void 0) continue;
@@ -1313,11 +1734,11 @@ function validateConfig(raw, source = "config") {
1313
1734
  }
1314
1735
  return c;
1315
1736
  }
1316
- function checkRegExp(source, where, fail) {
1737
+ function checkRegExp(source, where2, fail) {
1317
1738
  try {
1318
1739
  new RegExp(source);
1319
1740
  } catch (err) {
1320
- fail(`${where} is not a valid regular expression: ${err.message}`);
1741
+ fail(`${where2} is not a valid regular expression: ${err.message}`);
1321
1742
  }
1322
1743
  }
1323
1744
  function isObject(v) {
@@ -1352,7 +1773,7 @@ function globToRegExp(glob) {
1352
1773
  }
1353
1774
  function globMatcher(globs) {
1354
1775
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1355
- return (path22) => res.some((re) => re.test(path22));
1776
+ return (path28) => res.some((re) => re.test(path28));
1356
1777
  }
1357
1778
  var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
1358
1779
  var NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
@@ -1392,11 +1813,11 @@ var TAILWIND_PALETTE = [
1392
1813
  "olive"
1393
1814
  ];
1394
1815
  function findPackageDir(from, name) {
1395
- let dir = path14.resolve(from);
1816
+ let dir = path18.resolve(from);
1396
1817
  for (; ; ) {
1397
- const candidate = path14.join(dir, "node_modules", name);
1398
- if (existsSync(path14.join(candidate, "package.json"))) return candidate;
1399
- const parent = path14.dirname(dir);
1818
+ const candidate = path18.join(dir, "node_modules", name);
1819
+ if (existsSync(path18.join(candidate, "package.json"))) return candidate;
1820
+ const parent = path18.dirname(dir);
1400
1821
  if (parent === dir) return null;
1401
1822
  dir = parent;
1402
1823
  }
@@ -1448,7 +1869,7 @@ function loadCompanions(root, config, uiPackage) {
1448
1869
  function readPackageExports(root, uiPackage) {
1449
1870
  const uiDir = findPackageDir(root, uiPackage);
1450
1871
  if (!uiDir) return null;
1451
- const uiPkg = JSON.parse(readFileSync(path14.join(uiDir, "package.json"), "utf8"));
1872
+ const uiPkg = JSON.parse(readFileSync(path18.join(uiDir, "package.json"), "utf8"));
1452
1873
  const typeEntries = /* @__PURE__ */ new Set();
1453
1874
  const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
1454
1875
  if (typeof mainTypes === "string") typeEntries.add(mainTypes);
@@ -1460,7 +1881,7 @@ function readPackageExports(root, uiPackage) {
1460
1881
  const reexportedPackages = /* @__PURE__ */ new Set();
1461
1882
  let readAny = false;
1462
1883
  for (const entry of typeEntries) {
1463
- const file = path14.join(uiDir, entry);
1884
+ const file = path18.join(uiDir, entry);
1464
1885
  if (!existsSync(file)) continue;
1465
1886
  readAny = true;
1466
1887
  const dts = readFileSync(file, "utf8");
@@ -1474,11 +1895,11 @@ function readPackageExports(root, uiPackage) {
1474
1895
  }
1475
1896
  const valueDecls = /* @__PURE__ */ new Set();
1476
1897
  const typeDecls = /* @__PURE__ */ new Set();
1477
- const declRoot = typeof mainTypes === "string" ? path14.dirname(path14.join(uiDir, mainTypes)) : uiDir;
1898
+ const declRoot = typeof mainTypes === "string" ? path18.dirname(path18.join(uiDir, mainTypes)) : uiDir;
1478
1899
  const declFiles = walkDts(declRoot);
1479
1900
  for (const pkg of reexportedPackages) {
1480
1901
  const dir = findPackageDir(uiDir, pkg);
1481
- if (dir) walkDts(path14.join(dir, "dist"), declFiles);
1902
+ if (dir) walkDts(path18.join(dir, "dist"), declFiles);
1482
1903
  }
1483
1904
  for (const file of declFiles) {
1484
1905
  const text = readFileSync(file, "utf8");
@@ -1524,7 +1945,7 @@ function walkDts(dir, out = []) {
1524
1945
  if (!existsSync(dir)) return out;
1525
1946
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1526
1947
  if (entry.name === "node_modules") continue;
1527
- const p = path14.join(dir, entry.name);
1948
+ const p = path18.join(dir, entry.name);
1528
1949
  if (entry.isDirectory()) walkDts(p, out);
1529
1950
  else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1530
1951
  }
@@ -1541,27 +1962,27 @@ function resolveThemeFiles(root, config, uiDir) {
1541
1962
  }
1542
1963
  const files = [];
1543
1964
  const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
1544
- const themes = ds && path14.join(ds, "dist", "themes");
1965
+ const themes = ds && path18.join(ds, "dist", "themes");
1545
1966
  if (themes && existsSync(themes)) {
1546
- for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path14.join(themes, name));
1967
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path18.join(themes, name));
1547
1968
  }
1548
1969
  if (files.length === 0) {
1549
1970
  throw new DoctorConfigError(
1550
1971
  `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
1551
1972
  );
1552
1973
  }
1553
- const uiStyles = path14.join(uiDir, "dist", "styles.css");
1974
+ const uiStyles = path18.join(uiDir, "dist", "styles.css");
1554
1975
  if (existsSync(uiStyles)) files.push(uiStyles);
1555
1976
  return files;
1556
1977
  }
1557
1978
  function resolveSpec(root, spec) {
1558
- const local = path14.resolve(root, spec);
1559
- if (spec.startsWith(".") || path14.isAbsolute(spec)) return existsSync(local) ? local : null;
1979
+ const local = path18.resolve(root, spec);
1980
+ if (spec.startsWith(".") || path18.isAbsolute(spec)) return existsSync(local) ? local : null;
1560
1981
  const parts = spec.split("/");
1561
1982
  const nameLength = spec.startsWith("@") ? 2 : 1;
1562
1983
  const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
1563
1984
  if (dir) {
1564
- const file = path14.join(dir, ...parts.slice(nameLength));
1985
+ const file = path18.join(dir, ...parts.slice(nameLength));
1565
1986
  if (existsSync(file) && statSync(file).isFile()) return file;
1566
1987
  }
1567
1988
  return existsSync(local) ? local : null;
@@ -1569,7 +1990,7 @@ function resolveSpec(root, spec) {
1569
1990
  function loadPalette(root) {
1570
1991
  const names = new Set(TAILWIND_PALETTE);
1571
1992
  try {
1572
- const req = createRequire(path14.join(root, "package.json"));
1993
+ const req = createRequire(path18.join(root, "package.json"));
1573
1994
  const colors = req("tailwindcss/colors");
1574
1995
  for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
1575
1996
  if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
@@ -1609,17 +2030,17 @@ function parseManifest(home, id, raw, version, options = {}) {
1609
2030
  if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
1610
2031
  if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
1611
2032
  if (!isObject2(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
1612
- const pkgOf = (value, where) => {
2033
+ const pkgOf = (value, where2) => {
1613
2034
  if (value === void 0) return home;
1614
2035
  if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
1615
- problems.push(`${where}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
2036
+ problems.push(`${where2}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
1616
2037
  return home;
1617
2038
  }
1618
2039
  return value;
1619
2040
  };
1620
- const pathOf = (value, where) => {
2041
+ const pathOf = (value, where2) => {
1621
2042
  const safe = safeRelative(value);
1622
- if (!safe) problems.push(`${where}: ${JSON.stringify(value)} is not a plain path inside the package`);
2043
+ if (!safe) problems.push(`${where2}: ${JSON.stringify(value)} is not a plain path inside the package`);
1623
2044
  return safe ?? "";
1624
2045
  };
1625
2046
  const list = (key2) => {
@@ -1651,43 +2072,43 @@ function parseManifest(home, id, raw, version, options = {}) {
1651
2072
  return ok;
1652
2073
  });
1653
2074
  const migrations = list("migrations").map((m, i) => {
1654
- const where = `${at}.migrations[${i}]`;
2075
+ const where2 = `${at}.migrations[${i}]`;
1655
2076
  if (!isObject2(m)) {
1656
- problems.push(`${where}: must be an object`);
2077
+ problems.push(`${where2}: must be an object`);
1657
2078
  return { package: home, file: "" };
1658
2079
  }
1659
- const file = pathOf(m["file"], `${where}.file`);
1660
- if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
1661
- const out = { package: pkgOf(m["package"], where), file };
2080
+ const file = pathOf(m["file"], `${where2}.file`);
2081
+ if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where2}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
2082
+ const out = { package: pkgOf(m["package"], where2), file };
1662
2083
  if (m["test"] !== void 0) {
1663
- out.test = pathOf(m["test"], `${where}.test`);
1664
- if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
2084
+ out.test = pathOf(m["test"], `${where2}.test`);
2085
+ if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where2}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
1665
2086
  }
1666
2087
  return out;
1667
2088
  });
1668
2089
  const functions = list("functions").map((f, i) => {
1669
- const where = `${at}.functions[${i}]`;
2090
+ const where2 = `${at}.functions[${i}]`;
1670
2091
  if (!isObject2(f)) {
1671
- problems.push(`${where}: must be an object`);
2092
+ problems.push(`${where2}: must be an object`);
1672
2093
  return { package: home, dir: "" };
1673
2094
  }
1674
- const dir = pathOf(f["dir"], `${where}.dir`);
1675
- if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
1676
- const out = { package: pkgOf(f["package"], where), dir };
2095
+ const dir = pathOf(f["dir"], `${where2}.dir`);
2096
+ if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where2}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
2097
+ const out = { package: pkgOf(f["package"], where2), dir };
1677
2098
  if (f["verifyJwt"] !== void 0) {
1678
- if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where}.verifyJwt: must be true or false`);
2099
+ if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where2}.verifyJwt: must be true or false`);
1679
2100
  else out.verifyJwt = f["verifyJwt"];
1680
2101
  }
1681
2102
  if (f["secrets"] !== void 0) {
1682
- if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where}.secrets: must be a list of UPPER_CASE names`);
2103
+ if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where2}.secrets: must be a list of UPPER_CASE names`);
1683
2104
  else out.secrets = f["secrets"];
1684
2105
  }
1685
2106
  return out;
1686
2107
  });
1687
2108
  const routes = list("routes").map((r, i) => {
1688
- const where = `${at}.routes[${i}]`;
2109
+ const where2 = `${at}.routes[${i}]`;
1689
2110
  if (!isObject2(r) || typeof r["path"] !== "string" || !ROUTE.test(r["path"]) || r["path"].split("/").includes("..")) {
1690
- problems.push(`${where}: needs a path like /settings/notifications`);
2111
+ problems.push(`${where2}: needs a path like /settings/notifications`);
1691
2112
  return { path: "/" };
1692
2113
  }
1693
2114
  const out = { path: r["path"] };
@@ -1757,8 +2178,8 @@ function rawBlocksOf(packageJson) {
1757
2178
 
1758
2179
  // src/blocks/files.ts
1759
2180
  function inside(parent, child) {
1760
- const rel = path14.relative(parent, child);
1761
- return rel === "" || !rel.startsWith("..") && !path14.isAbsolute(rel);
2181
+ const rel = path18.relative(parent, child);
2182
+ return rel === "" || !rel.startsWith("..") && !path18.isAbsolute(rel);
1762
2183
  }
1763
2184
 
1764
2185
  // src/blocks/local.ts
@@ -1769,21 +2190,21 @@ var LocalPackagesError = class extends Error {
1769
2190
  function validateLocalPackages(raw, source = "genesis.config.json") {
1770
2191
  if (!Array.isArray(raw)) throw new LocalPackagesError(`${source}: ${LOCAL_PACKAGES_KEY} must be a list of folders`);
1771
2192
  return raw.map((entry, i) => {
1772
- const where = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
1773
- if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where} must be a non-empty folder`);
1774
- if (path14.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where} must be relative to the app ("${entry}")`);
1775
- const norm = path14.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
1776
- if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where} must name a package folder, not the app or a parent of it ("${entry}")`);
2193
+ const where2 = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
2194
+ if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where2} must be a non-empty folder`);
2195
+ if (path18.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
2196
+ const norm = path18.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
2197
+ if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where2} must name a package folder, not the app or a parent of it ("${entry}")`);
1777
2198
  const parts = norm.split("/");
1778
2199
  if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
1779
- throw new LocalPackagesError(`${where}: only a final "/*" is supported ("${entry}")`);
2200
+ throw new LocalPackagesError(`${where2}: only a final "/*" is supported ("${entry}")`);
1780
2201
  }
1781
- if (parts.includes("node_modules")) throw new LocalPackagesError(`${where} can't point into node_modules ("${entry}")`);
2202
+ if (parts.includes("node_modules")) throw new LocalPackagesError(`${where2} can't point into node_modules ("${entry}")`);
1782
2203
  return norm;
1783
2204
  });
1784
2205
  }
1785
2206
  function localPackageGlobs(root) {
1786
- const file = path14.join(root, "genesis.config.json");
2207
+ const file = path18.join(root, "genesis.config.json");
1787
2208
  if (!existsSync(file)) return [];
1788
2209
  let raw;
1789
2210
  try {
@@ -1797,14 +2218,14 @@ function localPackageGlobs(root) {
1797
2218
  var cache = /* @__PURE__ */ new Map();
1798
2219
  function repositoryRoot(appRoot) {
1799
2220
  for (let dir = appRoot; ; ) {
1800
- if (existsSync(path14.join(dir, ".git"))) return dir;
1801
- const parent = path14.dirname(dir);
2221
+ if (existsSync(path18.join(dir, ".git"))) return dir;
2222
+ const parent = path18.dirname(dir);
1802
2223
  if (parent === dir) return appRoot;
1803
2224
  dir = parent;
1804
2225
  }
1805
2226
  }
1806
2227
  function localPackages(root) {
1807
- const appRoot = path14.resolve(root);
2228
+ const appRoot = path18.resolve(root);
1808
2229
  const globs = localPackageGlobs(appRoot);
1809
2230
  const key2 = `${appRoot}
1810
2231
  ${globs.join("\n")}`;
@@ -1813,24 +2234,24 @@ ${globs.join("\n")}`;
1813
2234
  const dirs = /* @__PURE__ */ new Set();
1814
2235
  for (const glob of globs) {
1815
2236
  if (glob.endsWith("/*") || glob === "*") {
1816
- const parent = path14.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
2237
+ const parent = path18.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
1817
2238
  if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
1818
2239
  for (const entry of readdirSync(parent).sort()) {
1819
2240
  if (entry.startsWith(".") || entry === "node_modules") continue;
1820
- dirs.add(path14.join(parent, entry));
2241
+ dirs.add(path18.join(parent, entry));
1821
2242
  }
1822
2243
  } else {
1823
- dirs.add(path14.join(appRoot, glob));
2244
+ dirs.add(path18.join(appRoot, glob));
1824
2245
  }
1825
2246
  }
1826
2247
  const real2 = realpathSync(repositoryRoot(appRoot));
1827
2248
  const out = [];
1828
2249
  const byName = /* @__PURE__ */ new Map();
1829
2250
  for (const dir of [...dirs].sort()) {
1830
- const manifest = path14.join(dir, "package.json");
2251
+ const manifest = path18.join(dir, "package.json");
1831
2252
  if (!existsSync(manifest)) continue;
1832
2253
  if (!inside(real2, realpathSync(dir))) {
1833
- throw new LocalPackagesError(`${path14.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
2254
+ throw new LocalPackagesError(`${path18.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
1834
2255
  }
1835
2256
  let pkg;
1836
2257
  try {
@@ -1839,7 +2260,7 @@ ${globs.join("\n")}`;
1839
2260
  continue;
1840
2261
  }
1841
2262
  if (typeof pkg.name !== "string" || !pkg.name) continue;
1842
- const rel = path14.relative(appRoot, dir).split(path14.sep).join("/");
2263
+ const rel = path18.relative(appRoot, dir).split(path18.sep).join("/");
1843
2264
  const other = byName.get(pkg.name);
1844
2265
  if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
1845
2266
  byName.set(pkg.name, rel);
@@ -2024,16 +2445,16 @@ var DEFAULT_IGNORE = [
2024
2445
  ];
2025
2446
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
2026
2447
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
2027
- var toPosix = (p) => p.split(path14.sep).join("/");
2448
+ var toPosix = (p) => p.split(path18.sep).join("/");
2028
2449
  function scanFiles(root, config) {
2029
2450
  const extensions = new Set(config.extensions ?? DEFAULT_EXTENSIONS);
2030
2451
  const ignored = globMatcher([...DEFAULT_IGNORE, ...config.ignore ?? []]);
2031
2452
  const files = [];
2032
2453
  const seen = /* @__PURE__ */ new Set();
2033
2454
  const visit = (abs) => {
2034
- const rel = toPosix(path14.relative(root, abs));
2455
+ const rel = toPosix(path18.relative(root, abs));
2035
2456
  if (seen.has(rel) || ignored(rel)) return;
2036
- const ext = path14.extname(abs);
2457
+ const ext = path18.extname(abs);
2037
2458
  if (!extensions.has(ext)) return;
2038
2459
  if (statSync(abs).size > MAX_FILE_BYTES) return;
2039
2460
  seen.add(rel);
@@ -2043,14 +2464,14 @@ function scanFiles(root, config) {
2043
2464
  const walk = (dir) => {
2044
2465
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
2045
2466
  if (entry.isDirectory()) {
2046
- if (!SKIP_DIRS.has(entry.name)) walk(path14.join(dir, entry.name));
2467
+ if (!SKIP_DIRS.has(entry.name)) walk(path18.join(dir, entry.name));
2047
2468
  } else if (entry.isFile()) {
2048
- visit(path14.join(dir, entry.name));
2469
+ visit(path18.join(dir, entry.name));
2049
2470
  }
2050
2471
  }
2051
2472
  };
2052
2473
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
2053
- const abs = path14.resolve(root, src);
2474
+ const abs = path18.resolve(root, src);
2054
2475
  if (!existsSync(abs)) continue;
2055
2476
  if (statSync(abs).isDirectory()) walk(abs);
2056
2477
  else visit(abs);
@@ -2085,12 +2506,13 @@ function parseRulesMarkdown(markdown) {
2085
2506
  current = null;
2086
2507
  continue;
2087
2508
  }
2088
- const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message):\s*(.*)$/);
2509
+ const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message|newOnly):\s*(.*)$/);
2089
2510
  if (!current || !kv) continue;
2090
2511
  const [, key2, raw] = kv;
2091
2512
  const value = raw.trim();
2092
2513
  if (key2 === "files" || key2 === "exclude") current[key2] = value.split(",").map((s) => s.trim()).filter(Boolean);
2093
2514
  else if (key2 === "level") current.level = value;
2515
+ else if (key2 === "newOnly") current.newOnly = value === "true" ? true : value === "false" ? false : value;
2094
2516
  else current[key2] = value;
2095
2517
  }
2096
2518
  return rules;
@@ -2109,6 +2531,9 @@ function compilePatternRules(rules, source) {
2109
2531
  if (!["error", "warn", "info", "guide"].includes(level)) {
2110
2532
  throw new DoctorConfigError(`${source}: rule "${rule.id}" has level "${level}" (use error, warn, info or guide)`);
2111
2533
  }
2534
+ if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") {
2535
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" has newOnly "${String(rule.newOnly)}" (use true or false)`);
2536
+ }
2112
2537
  if (level === "guide") continue;
2113
2538
  if (!rule.files?.length) throw new DoctorConfigError(`${source}: rule "${rule.id}" needs "files" (or level: guide)`);
2114
2539
  if (!rule.forbid && !rule.require && !rule.path) {
@@ -2134,7 +2559,7 @@ function loadPatternRules(root, patterns, rulesDoc) {
2134
2559
  const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
2135
2560
  let all = compiled;
2136
2561
  if (rulesDoc) {
2137
- const file = path14.resolve(root, rulesDoc);
2562
+ const file = path18.resolve(root, rulesDoc);
2138
2563
  if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
2139
2564
  const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
2140
2565
  const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
@@ -2144,6 +2569,8 @@ function loadPatternRules(root, patterns, rulesDoc) {
2144
2569
  if (all.length === 0) return null;
2145
2570
  return {
2146
2571
  count: all.length,
2572
+ ids: all.map((r) => r.rule.id),
2573
+ newOnly: all.filter((r) => r.rule.newOnly).map((r) => r.rule.id),
2147
2574
  plugin: {
2148
2575
  name: "patterns",
2149
2576
  check(ctx) {
@@ -2193,14 +2620,14 @@ async function loadPlugins(specs, configDir) {
2193
2620
  }
2194
2621
  function resolvePlugin(id, configDir) {
2195
2622
  try {
2196
- if (id.startsWith(".") || path14.isAbsolute(id)) return resolveFrom(path14.resolve(configDir, id), configDir);
2623
+ if (id.startsWith(".") || path18.isAbsolute(id)) return resolveFrom(path18.resolve(configDir, id), configDir);
2197
2624
  return resolveFrom(id, configDir);
2198
2625
  } catch {
2199
2626
  throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
2200
2627
  }
2201
2628
  }
2202
2629
  function resolveFrom(id, from) {
2203
- return createRequire(path14.join(from, "noop.js")).resolve(id);
2630
+ return createRequire(path18.join(from, "noop.js")).resolve(id);
2204
2631
  }
2205
2632
  var BUILTIN_RULES = [
2206
2633
  "local-primitives",
@@ -2250,7 +2677,19 @@ var BUILTIN_RULES = [
2250
2677
  "package-unversioned-change",
2251
2678
  "package-export-missing",
2252
2679
  "package-block-invalid",
2253
- "package-untagged-tests"
2680
+ "package-untagged-tests",
2681
+ "package-doctor-declaration",
2682
+ // package rules (package-rules.ts): the rules themselves are namespaced, e.g. ui/lists-use-resource-view
2683
+ "package-rules-invalid",
2684
+ "package-rule-override",
2685
+ // ratchet (ratchet.ts)
2686
+ "ratchet-skipped",
2687
+ "allow-grew",
2688
+ "rules-weakened",
2689
+ // agent guide (primitives.ts)
2690
+ "agent-guide-stale",
2691
+ // supabase pack: contracts (contracts.ts)
2692
+ "contracts-stale"
2254
2693
  ];
2255
2694
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
2256
2695
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2268,7 +2707,7 @@ function importSpecifiers(file) {
2268
2707
  }
2269
2708
  function checkProjectLayout(ctx) {
2270
2709
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
2271
- if (existsSync(path14.join(ctx.root, dir))) {
2710
+ if (existsSync(path18.join(ctx.root, dir))) {
2272
2711
  ctx.report({
2273
2712
  rule: "local-primitives",
2274
2713
  file: dir,
@@ -2278,7 +2717,7 @@ function checkProjectLayout(ctx) {
2278
2717
  }
2279
2718
  }
2280
2719
  for (const file of STARTER_LEFTOVERS) {
2281
- if (existsSync(path14.join(ctx.root, file))) {
2720
+ if (existsSync(path18.join(ctx.root, file))) {
2282
2721
  ctx.report({
2283
2722
  rule: "starter-leftover",
2284
2723
  level: "warn",
@@ -2367,7 +2806,7 @@ function checkTokens(ctx) {
2367
2806
  }
2368
2807
  for (const pattern of ctx.config.tokenFiles ?? []) {
2369
2808
  if (/[*?]/.test(pattern)) continue;
2370
- const abs = path14.join(ctx.root, pattern);
2809
+ const abs = path18.join(ctx.root, pattern);
2371
2810
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
2372
2811
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
2373
2812
  }
@@ -2469,19 +2908,34 @@ function privacyApisFor(dependencies2) {
2469
2908
  var SCRIPT_EXTS2 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
2470
2909
  var JSX_EXTS2 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
2471
2910
  var RESOLVE_EXTS = [".tsx", ".ts", ".jsx", ".js"];
2911
+ function resolveLocal(root, fromFile, spec) {
2912
+ const bases = spec.startsWith(".") ? [path18.resolve(path18.dirname(fromFile), spec)] : [path18.join(root, spec.slice(2)), path18.join(root, "src", spec.slice(2))];
2913
+ for (const base of bases) {
2914
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path18.join(base, `index${e}`))].find(
2915
+ (p) => SCRIPT_EXTS2.has(path18.extname(p)) && existsSync(p)
2916
+ );
2917
+ if (hit) return hit;
2918
+ }
2919
+ return null;
2920
+ }
2472
2921
  function localImports(root, file) {
2473
2922
  const out = [];
2474
2923
  for (const m of file.code.matchAll(/\bfrom\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g)) {
2475
- const spec = m[1];
2476
- const bases = spec.startsWith(".") ? [path14.resolve(path14.dirname(file.absolutePath), spec)] : [path14.join(root, spec.slice(2)), path14.join(root, "src", spec.slice(2))];
2477
- for (const base of bases) {
2478
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path14.join(base, `index${e}`))].find(
2479
- (p) => SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p)
2480
- );
2481
- if (hit) {
2482
- out.push(hit);
2483
- break;
2484
- }
2924
+ const hit = resolveLocal(root, file.absolutePath, m[1]);
2925
+ if (hit) out.push(hit);
2926
+ }
2927
+ return out;
2928
+ }
2929
+ function localImportedNames(root, file) {
2930
+ const out = /* @__PURE__ */ new Map();
2931
+ const re = /\bimport\s+(?:type\s+)?([\w$]+)?\s*,?\s*(?:\{([^}]*)\})?\s*from\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g;
2932
+ for (const m of file.code.matchAll(re)) {
2933
+ const target = resolveLocal(root, file.absolutePath, m[3]);
2934
+ if (!target) continue;
2935
+ if (m[1]) out.set(m[1], { file: target, name: "default" });
2936
+ for (const part of (m[2] ?? "").split(",")) {
2937
+ const [imported, local] = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/);
2938
+ if (imported) out.set(local ?? imported, { file: target, name: imported });
2485
2939
  }
2486
2940
  }
2487
2941
  return out;
@@ -2640,7 +3094,7 @@ function checkCustomHeaders(ctx, pkg) {
2640
3094
  if (!JSX_EXTS3.has(file.ext)) continue;
2641
3095
  const code = file.code;
2642
3096
  const hidden = HIDES_HEADER.exec(code);
2643
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path14.posix.dirname(file.path), file.path);
3097
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path18.posix.dirname(file.path), file.path);
2644
3098
  const own = hidden ? ownHeader(code, pkg) : null;
2645
3099
  if (hidden && own) {
2646
3100
  reported.add(file.path);
@@ -2668,7 +3122,7 @@ function checkCustomHeaders(ctx, pkg) {
2668
3122
  }
2669
3123
  for (const file of ctx.files) {
2670
3124
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
2671
- const layout = hidingLayouts.get(path14.posix.dirname(file.path));
3125
+ const layout = hidingLayouts.get(path18.posix.dirname(file.path));
2672
3126
  const own = layout ? ownHeader(file.code, pkg) : null;
2673
3127
  if (!layout || !own) continue;
2674
3128
  ctx.report({
@@ -2690,13 +3144,13 @@ function isLoadingOnlyRoute(code) {
2690
3144
  }
2691
3145
  function routerRoot(ctx) {
2692
3146
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
2693
- return existsSync(path14.join(ctx.root, "src", "app")) ? "src/app" : "app";
3147
+ return existsSync(path18.join(ctx.root, "src", "app")) ? "src/app" : "app";
2694
3148
  }
2695
3149
  function checkScreenLayouts(ctx, pkg) {
2696
3150
  const layouts = nativeLayouts(pkg);
2697
3151
  if (layouts.length === 0) return;
2698
3152
  const rootDir = routerRoot(ctx);
2699
- if (!existsSync(path14.join(ctx.root, rootDir))) {
3153
+ if (!existsSync(path18.join(ctx.root, rootDir))) {
2700
3154
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
2701
3155
  return;
2702
3156
  }
@@ -2752,7 +3206,7 @@ var GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\
2752
3206
  function readExpoConfigs(root) {
2753
3207
  const out = [];
2754
3208
  for (const name of EXPO_CONFIGS) {
2755
- const abs = path14.join(root, name);
3209
+ const abs = path18.join(root, name);
2756
3210
  if (!existsSync(abs)) continue;
2757
3211
  const text = readFileSync(abs, "utf8");
2758
3212
  let json = null;
@@ -2786,13 +3240,13 @@ function pluginOptions(json, module) {
2786
3240
  return null;
2787
3241
  }
2788
3242
  function dependencies(root) {
2789
- const file = path14.join(root, "package.json");
3243
+ const file = path18.join(root, "package.json");
2790
3244
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
2791
3245
  const pkg = JSON.parse(readFileSync(file, "utf8"));
2792
3246
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
2793
3247
  }
2794
3248
  function runtimeDependencies(root) {
2795
- const file = path14.join(root, "package.json");
3249
+ const file = path18.join(root, "package.json");
2796
3250
  if (!existsSync(file)) return {};
2797
3251
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
2798
3252
  }
@@ -3166,14 +3620,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3166
3620
  seen.add(file);
3167
3621
  const json = readJsonc(file);
3168
3622
  if (!json) return {};
3169
- const dir = path14.dirname(file);
3623
+ const dir = path18.dirname(file);
3170
3624
  let merged = {};
3171
3625
  const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3172
3626
  for (const ext of parents) {
3173
3627
  if (typeof ext !== "string") continue;
3174
3628
  let target = null;
3175
- if (ext.startsWith(".") || path14.isAbsolute(ext)) {
3176
- const abs = path14.resolve(dir, ext);
3629
+ if (ext.startsWith(".") || path18.isAbsolute(ext)) {
3630
+ const abs = path18.resolve(dir, ext);
3177
3631
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3178
3632
  } else {
3179
3633
  const parts = ext.split("/");
@@ -3181,14 +3635,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3181
3635
  const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3182
3636
  if (pkgDir) {
3183
3637
  const sub = parts.slice(nameLength).join("/");
3184
- const abs = path14.join(pkgDir, sub || "tsconfig.json");
3638
+ const abs = path18.join(pkgDir, sub || "tsconfig.json");
3185
3639
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3186
3640
  }
3187
3641
  }
3188
3642
  if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
3189
3643
  }
3190
3644
  const opts = json.compilerOptions ?? {};
3191
- if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
3645
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path18.resolve(dir, opts.baseUrl);
3192
3646
  if (opts.paths && typeof opts.paths === "object") {
3193
3647
  merged.paths = opts.paths;
3194
3648
  merged.pathsDir = dir;
@@ -3199,7 +3653,7 @@ function aliases(root) {
3199
3653
  const table = [];
3200
3654
  let baseUrl = null;
3201
3655
  for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3202
- const file = path14.join(root, name);
3656
+ const file = path18.join(root, name);
3203
3657
  if (!existsSync(file)) continue;
3204
3658
  const config = readTsconfig(root, file);
3205
3659
  baseUrl ??= config.baseUrl ?? null;
@@ -3207,22 +3661,22 @@ function aliases(root) {
3207
3661
  for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3208
3662
  if (!Array.isArray(targets)) continue;
3209
3663
  const exact = !pattern.endsWith("*");
3210
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
3664
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path18.join(base, String(t).replace(/\*$/, ""))) });
3211
3665
  }
3212
3666
  }
3213
- const pkg = readJsonc(path14.join(root, "package.json"));
3667
+ const pkg = readJsonc(path18.join(root, "package.json"));
3214
3668
  for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3215
3669
  if (typeof target !== "string") continue;
3216
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
3670
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path18.join(root, target.replace(/\*.*$/, ""))] });
3217
3671
  }
3218
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
3672
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path18.join(root, "src") + path18.sep, root + path18.sep] });
3219
3673
  return { table, baseUrl };
3220
3674
  }
3221
3675
  function resolveFile(base) {
3222
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
3676
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path18.join(base, `index${e}`))];
3223
3677
  if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3224
3678
  for (const p of tries) {
3225
- if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3679
+ if (SCRIPT_EXTS2.has(path18.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3226
3680
  }
3227
3681
  return null;
3228
3682
  }
@@ -3236,13 +3690,13 @@ function createTrail(ctx) {
3236
3690
  const { table, baseUrl } = aliases(ctx.root);
3237
3691
  let declared = null;
3238
3692
  try {
3239
- const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
3693
+ const pkg = JSON.parse(readFileSync(path18.join(ctx.root, "package.json"), "utf8"));
3240
3694
  declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
3241
3695
  } catch {
3242
3696
  declared = null;
3243
3697
  }
3244
3698
  const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
3245
- const read = (abs) => byPath.get(abs) ?? readSource(abs);
3699
+ const read2 = (abs) => byPath.get(abs) ?? readSource(abs);
3246
3700
  const importsCache = /* @__PURE__ */ new Map();
3247
3701
  const importsOf = (file) => {
3248
3702
  const hit = importsCache.get(file.absolutePath);
@@ -3267,17 +3721,17 @@ function createTrail(ctx) {
3267
3721
  if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
3268
3722
  let resolved = null;
3269
3723
  if (spec.startsWith(".")) {
3270
- resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
3724
+ resolved = resolveFile(path18.resolve(path18.dirname(file.absolutePath), spec));
3271
3725
  if (!resolved) lost = true;
3272
3726
  } else {
3273
3727
  const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
3274
3728
  if (alias) {
3275
3729
  for (const t of alias.targets) {
3276
- resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
3730
+ resolved = resolveFile(alias.exact ? t : path18.join(t, spec.slice(alias.prefix.length)));
3277
3731
  if (resolved) break;
3278
3732
  }
3279
3733
  }
3280
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
3734
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path18.join(baseUrl, spec));
3281
3735
  if (!resolved) {
3282
3736
  const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
3283
3737
  if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
@@ -3319,7 +3773,7 @@ function createTrail(ctx) {
3319
3773
  cut.add(abs);
3320
3774
  continue;
3321
3775
  }
3322
- const target = read(abs);
3776
+ const target = read2(abs);
3323
3777
  if (!target) {
3324
3778
  unknown = true;
3325
3779
  continue;
@@ -3332,21 +3786,525 @@ function createTrail(ctx) {
3332
3786
  }
3333
3787
  if (r === "unknown") unknown = true;
3334
3788
  }
3335
- seen.delete(file.absolutePath);
3336
- cut.delete(file.absolutePath);
3789
+ seen.delete(file.absolutePath);
3790
+ cut.delete(file.absolutePath);
3791
+ }
3792
+ if (result === "no" && unknown) result = "unknown";
3793
+ }
3794
+ if (result === "yes" || cut.size === 0) {
3795
+ cache2.free.set(k, result);
3796
+ return [result, /* @__PURE__ */ new Set()];
3797
+ }
3798
+ const entries = cache2.cut.get(k) ?? [];
3799
+ entries.push({ cut: [...cut], result });
3800
+ cache2.cut.set(k, entries);
3801
+ return [result, cut];
3802
+ };
3803
+ return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
3804
+ }
3805
+
3806
+ // src/blocks/discover.ts
3807
+ var INSTALL_ROOT_MARKERS = [".git", "pnpm-lock.yaml", "pnpm-workspace.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"];
3808
+ function installedGenesis(root) {
3809
+ const found = /* @__PURE__ */ new Map();
3810
+ let dir = path18.resolve(root);
3811
+ for (; ; ) {
3812
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path18.join(dir, m)));
3813
+ const scope = path18.join(dir, "node_modules", "@marktiderman");
3814
+ if (existsSync(scope)) {
3815
+ for (const entry of readdirSync(scope)) {
3816
+ const name = `@marktiderman/${entry}`;
3817
+ if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
3818
+ if (existsSync(path18.join(scope, entry, "package.json"))) found.set(name, path18.join(scope, entry));
3819
+ }
3820
+ }
3821
+ const parent = path18.dirname(dir);
3822
+ if (atInstallRoot || parent === dir) return found;
3823
+ dir = parent;
3824
+ }
3825
+ }
3826
+ var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3827
+ var STEMS = {
3828
+ tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
3829
+ "next-app": {
3830
+ layout: /* @__PURE__ */ new Set(["layout"]),
3831
+ index: /* @__PURE__ */ new Set(["page"]),
3832
+ skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
3833
+ },
3834
+ "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
3835
+ };
3836
+ var NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
3837
+ var HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
3838
+ var COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
3839
+ var RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
3840
+ var OWN_CONTENT = /(?<![=-])>\s*[A-Za-z][^<>{}]*</.source + "|" + /(?<![\w$.])<(?:h[1-6]|ul|ol|table|dl|H[1-6]|[A-Z]\w*(?:Heading|Title|Table|List|Grid))(?=[\s>/])/.source;
3841
+ function routesDir(ctx) {
3842
+ if (ctx.config.routesDir) return ctx.config.routesDir;
3843
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path18.join(ctx.root, d))) ?? null;
3844
+ }
3845
+ var key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
3846
+ function flavorOf(dir, rels) {
3847
+ const stems = rels.map((r) => r.split("/").pop());
3848
+ if (stems.includes("__root")) return "tanstack";
3849
+ if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
3850
+ if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
3851
+ return "tanstack";
3852
+ }
3853
+ function renders(code) {
3854
+ const elements = renderedElements(code);
3855
+ if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
3856
+ const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
3857
+ const named = COMPONENT_OPTION.exec(code)?.[1];
3858
+ if (named && !definedHere(named)) return true;
3859
+ if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
3860
+ const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
3861
+ return exported !== void 0 && !definedHere(exported);
3862
+ }
3863
+ function webRoutes(ctx) {
3864
+ const dir = routesDir(ctx);
3865
+ if (!dir) return [];
3866
+ const candidates = ctx.files.filter((f) => JSX_EXTS2.has(f.ext) && f.path.startsWith(`${dir}/`)).map((file) => ({ file, rel: file.path.slice(dir.length + 1).replace(/\.[^.]+$/, "") }));
3867
+ const flavor = flavorOf(dir, candidates.map((c) => c.rel));
3868
+ const stems = STEMS[flavor];
3869
+ const groups = /* @__PURE__ */ new Map();
3870
+ for (const { file, rel } of candidates) {
3871
+ const parts = rel.split("/");
3872
+ if (parts.some((p) => p.startsWith("-"))) continue;
3873
+ if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
3874
+ if (flavor === "next-pages" && parts[0] === "api") continue;
3875
+ if (stems.skip.test(parts.at(-1))) continue;
3876
+ if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
3877
+ const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
3878
+ groups.set(id, [...groups.get(id) ?? [], file]);
3879
+ }
3880
+ const trail = trailFor(ctx);
3881
+ const routes = [];
3882
+ for (const [id, files] of groups) {
3883
+ const parts = id.split("/");
3884
+ const stem = parts.pop();
3885
+ const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
3886
+ const named = stems.layout.has(stem) || stems.index.has(stem);
3887
+ const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
3888
+ const segments = [...folders, ...own];
3889
+ const tree = [...parts, ...own];
3890
+ let index = stems.index.has(stem);
3891
+ if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
3892
+ segments.pop();
3893
+ tree.pop();
3894
+ index = true;
3895
+ }
3896
+ const code = files.map((f) => f.code).join("\n");
3897
+ const elements = renderedElements(code);
3898
+ const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
3899
+ const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
3900
+ const layout = stems.layout.has(stem) || pathless || outlet;
3901
+ const rendering = renders(code);
3902
+ const ownContent = new RegExp(OWN_CONTENT).test(code);
3903
+ const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
3904
+ const page = !pure && !pathless && (!layout || ownContent);
3905
+ routes.push({
3906
+ file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
3907
+ files,
3908
+ segments,
3909
+ tree,
3910
+ index,
3911
+ layout,
3912
+ page,
3913
+ detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
3914
+ redirectOnly: !rendering,
3915
+ parents: []
3916
+ });
3917
+ }
3918
+ for (const r of routes) {
3919
+ const own = r.tree;
3920
+ for (const p of routes) {
3921
+ if (p === r || !p.layout) continue;
3922
+ const n = p.tree.length;
3923
+ if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
3924
+ if (key(own.slice(0, n)) !== key(p.tree)) continue;
3925
+ if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
3926
+ r.parents.push(p);
3927
+ }
3928
+ r.parents.sort((a, b) => b.tree.length - a.tree.length);
3929
+ }
3930
+ return routes;
3931
+ }
3932
+
3933
+ // src/doctor/package-rules.ts
3934
+ var PackageDeclarationError = class extends Error {
3935
+ name = "PackageDeclarationError";
3936
+ };
3937
+ var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
3938
+ var ID = /^[a-z0-9][a-z0-9-]*$/;
3939
+ var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
3940
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
3941
+ var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
3942
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
3943
+ var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
3944
+ var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "primitives", "plugin", "$comment"]);
3945
+ var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
3946
+ function ruleNamespace(packageName3) {
3947
+ const m = GENESIS.exec(packageName3);
3948
+ if (m) return m[1] ?? "genesis";
3949
+ return packageName3;
3950
+ }
3951
+ var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3952
+ var isStringList2 = (v) => Array.isArray(v) && v.every((x) => typeof x === "string" && x.trim() !== "");
3953
+ function toRegExp2(source, flags = "") {
3954
+ if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
3955
+ return new RegExp(source, flags);
3956
+ }
3957
+ function validateDeclaration(raw, packageName3, packageDir, ignored) {
3958
+ const fail = (msg) => {
3959
+ throw new PackageDeclarationError(`${packageName3}: genesis.doctor ${msg}`);
3960
+ };
3961
+ const unknownKey = (where2, key2, known) => {
3962
+ const msg = `${where2 ? `${where2} ` : ""}has an unknown key "${key2}"${known ? ` (known: ${[...known].filter((k) => k !== "$comment").join(", ")})` : ""}`;
3963
+ if (!ignored) return fail(msg);
3964
+ ignored.push(`${packageName3}: genesis.doctor ${msg}; ignored`);
3965
+ };
3966
+ const each = (list, check) => list.flatMap((item, i) => {
3967
+ if (!ignored) return [check(item, i)];
3968
+ try {
3969
+ return [check(item, i)];
3970
+ } catch (err) {
3971
+ if (!(err instanceof PackageDeclarationError)) throw err;
3972
+ ignored.push(`${err.message}; that entry is skipped`);
3973
+ return [];
3974
+ }
3975
+ });
3976
+ if (typeof raw === "string") {
3977
+ if (!packageDir) fail(`points at ${raw}, but the package folder is unknown`);
3978
+ const file = path18.resolve(packageDir, raw);
3979
+ if (!inside(packageDir, file)) fail(`points outside the package (${raw})`);
3980
+ if (!existsSync(file)) fail(`points at ${raw}, which doesn't exist (is it in package.json "files"?)`);
3981
+ let parsed;
3982
+ try {
3983
+ parsed = JSON.parse(readFileSync(file, "utf8"));
3984
+ } catch (err) {
3985
+ return fail(`file ${raw} is not valid JSON: ${err.message}`);
3986
+ }
3987
+ return validateDeclaration(parsed, packageName3, packageDir, ignored);
3988
+ }
3989
+ if (raw === false) fail(`is false; say why with { "enforce": false, "reason": "\u2026" }`);
3990
+ if (!isObject3(raw)) fail(`must be an object (or a path to a JSON file in the package)`);
3991
+ const c = raw;
3992
+ for (const key2 of Object.keys(c)) if (!DECLARATION_KEYS.has(key2)) unknownKey("", key2, DECLARATION_KEYS);
3993
+ const enforce = c.enforce === void 0 ? true : c.enforce;
3994
+ if (typeof enforce !== "boolean") fail(`enforce must be true or false`);
3995
+ if (c.reason !== void 0 && (typeof c.reason !== "string" || !c.reason.trim())) fail(`reason must be a sentence`);
3996
+ const prefer = c.prefer === void 0 ? [] : c.prefer;
3997
+ if (!Array.isArray(prefer)) fail(`prefer must be a list`);
3998
+ const primitives = c.primitives === void 0 ? [] : c.primitives;
3999
+ if (!Array.isArray(primitives)) fail(`primitives must be a list`);
4000
+ if (c.plugin !== void 0 && (typeof c.plugin !== "string" || !c.plugin.trim())) fail(`plugin must be a module path inside the package`);
4001
+ if (!enforce) {
4002
+ if (typeof c.reason !== "string") fail(`turns enforcement off without a reason; add "reason"`);
4003
+ if (prefer.length || c.plugin) fail(`turns enforcement off but declares rules; drop "enforce": false or the rules`);
4004
+ } else if (!prefer.length && !c.plugin) {
4005
+ fail(`declares no rules; add "prefer" rules or a "plugin", or say { "enforce": false, "reason": "\u2026" }`);
4006
+ }
4007
+ const ids = /* @__PURE__ */ new Set();
4008
+ const rules = each(prefer, (r, i) => validatePrefer(r, `prefer[${i}]`, fail, unknownKey));
4009
+ for (const r of rules) {
4010
+ if (ids.has(r.id)) fail(`defines the rule "${r.id}" twice`);
4011
+ ids.add(r.id);
4012
+ }
4013
+ const entries = each(primitives, (p, i) => {
4014
+ const where2 = `primitives[${i}]`;
4015
+ if (!isObject3(p)) return fail(`${where2} must be an object`);
4016
+ for (const key2 of Object.keys(p)) if (!PRIMITIVE_KEYS.has(key2)) unknownKey(where2, key2);
4017
+ for (const key2 of ["need", "use"]) if (typeof p[key2] !== "string" || !p[key2].trim()) fail(`${where2} needs "${key2}"`);
4018
+ for (const key2 of ["import", "docs"]) if (p[key2] !== void 0 && typeof p[key2] !== "string") fail(`${where2}.${key2} must be a string`);
4019
+ return p;
4020
+ });
4021
+ let plugin;
4022
+ if (typeof c.plugin === "string") {
4023
+ if (!packageDir) plugin = c.plugin;
4024
+ else {
4025
+ plugin = path18.resolve(packageDir, c.plugin);
4026
+ if (!inside(packageDir, plugin)) fail(`plugin points outside the package (${c.plugin})`);
4027
+ }
4028
+ }
4029
+ return {
4030
+ enforce,
4031
+ ...typeof c.reason === "string" ? { reason: c.reason } : {},
4032
+ prefer: rules,
4033
+ primitives: entries,
4034
+ ...plugin ? { plugin } : {}
4035
+ };
4036
+ }
4037
+ function validatePrefer(raw, where2, fail, unknownKey) {
4038
+ if (!isObject3(raw)) return fail(`${where2} must be an object`);
4039
+ const narrowing = (at2, key2, known) => fail(`${at2} has an unknown key "${key2}" (known: ${[...known].join(", ")})`);
4040
+ for (const key2 of Object.keys(raw)) if (!PREFER_KEYS.has(key2)) narrowing(where2, key2, PREFER_KEYS);
4041
+ if (typeof raw.id !== "string" || !ID.test(raw.id)) fail(`${where2} needs an "id" of lower-case words and dashes`);
4042
+ const at = `${where2} (${raw.id})`;
4043
+ for (const key2 of ["use", "why"]) if (typeof raw[key2] !== "string" || !raw[key2].trim()) fail(`${at} needs "${key2}"`);
4044
+ for (const key2 of ["need", "import", "docs"]) if (raw[key2] !== void 0 && typeof raw[key2] !== "string") fail(`${at}.${key2} must be a string`);
4045
+ if (raw.level !== void 0 && !LEVELS2.has(raw.level)) fail(`${at}.level must be "error", "warn" or "info"`);
4046
+ if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
4047
+ if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
4048
+ for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
4049
+ if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
4050
+ const forbid = raw.forbid;
4051
+ for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
4052
+ if (!forbid.jsx && !forbid.imports && !forbid.pattern) fail(`${at}.forbid needs jsx, imports or pattern`);
4053
+ if (forbid.jsx !== void 0 && !(isStringList2(forbid.jsx) && forbid.jsx.every((n) => /^[A-Z][\w.]*$/.test(n)))) fail(`${at}.forbid.jsx must be a list of component names`);
4054
+ if (forbid.imports !== void 0 && !isStringList2(forbid.imports)) fail(`${at}.forbid.imports must be a list of import specifiers`);
4055
+ if (forbid.pattern !== void 0) checkPattern(forbid.pattern, `${at}.forbid.pattern`, fail);
4056
+ if (raw.unless !== void 0) {
4057
+ if (!isObject3(raw.unless)) fail(`${at}.unless must be an object`);
4058
+ const unless = raw.unless;
4059
+ for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
4060
+ if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
4061
+ if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
4062
+ }
4063
+ return raw;
4064
+ }
4065
+ function checkPattern(v, where2, fail) {
4066
+ if (typeof v !== "string" || !v) fail(`${where2} must be a regular expression`);
4067
+ try {
4068
+ toRegExp2(v, "g");
4069
+ } catch (err) {
4070
+ fail(`${where2} is not a valid regular expression: ${err.message}`);
4071
+ }
4072
+ }
4073
+ var discoveryCache = /* @__PURE__ */ new Map();
4074
+ function readDeclaringPackage(dir, local) {
4075
+ const file = path18.join(dir, "package.json");
4076
+ let stamp;
4077
+ let real2;
4078
+ try {
4079
+ real2 = realpathSync(dir);
4080
+ stamp = `${real2}
4081
+ ${statSync(file).mtimeMs}
4082
+ ${local}`;
4083
+ } catch {
4084
+ return null;
4085
+ }
4086
+ const hit = discoveryCache.get(stamp);
4087
+ if (hit) return hit;
4088
+ let json;
4089
+ try {
4090
+ json = JSON.parse(readFileSync(file, "utf8"));
4091
+ } catch {
4092
+ return null;
4093
+ }
4094
+ if (typeof json.name !== "string" || !json.name) return null;
4095
+ const pkg = {
4096
+ name: json.name,
4097
+ version: typeof json.version === "string" ? json.version : "0.0.0",
4098
+ dir: path18.resolve(dir),
4099
+ namespace: ruleNamespace(json.name),
4100
+ local,
4101
+ private: json.private === true,
4102
+ declaration: null
4103
+ };
4104
+ const raw = json.genesis?.doctor;
4105
+ if (raw !== void 0) {
4106
+ const ignored = [];
4107
+ try {
4108
+ pkg.declaration = validateDeclaration(raw, json.name, path18.resolve(dir), ignored);
4109
+ if (ignored.length) pkg.ignored = ignored;
4110
+ } catch (err) {
4111
+ pkg.error = err.message;
4112
+ }
4113
+ }
4114
+ discoveryCache.set(stamp, pkg);
4115
+ return pkg;
4116
+ }
4117
+ function discoverPackages(root) {
4118
+ const byName = /* @__PURE__ */ new Map();
4119
+ const installed = [...installedGenesis(root).values()];
4120
+ for (const dir of installed) {
4121
+ const pkg = readDeclaringPackage(dir, false);
4122
+ if (pkg) byName.set(pkg.name, pkg);
4123
+ }
4124
+ for (const dir of installed) {
4125
+ let scope;
4126
+ try {
4127
+ scope = path18.dirname(realpathSync(dir));
4128
+ } catch {
4129
+ continue;
4130
+ }
4131
+ if (path18.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
4132
+ for (const entry of readdirSync(scope)) {
4133
+ if (byName.has(`@marktiderman/${entry}`) || !GENESIS.test(`@marktiderman/${entry}`)) continue;
4134
+ const pkg = readDeclaringPackage(path18.join(scope, entry), false);
4135
+ if (pkg) byName.set(pkg.name, pkg);
4136
+ }
4137
+ }
4138
+ let local = [];
4139
+ try {
4140
+ local = localPackages(root);
4141
+ } catch {
4142
+ }
4143
+ for (const l of local) {
4144
+ const pkg = readDeclaringPackage(l.dir, true);
4145
+ if (pkg) byName.set(pkg.name, pkg);
4146
+ }
4147
+ return [...byName.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
4148
+ }
4149
+ function preferRules(packages) {
4150
+ return packages.flatMap(
4151
+ (p) => (p.declaration?.prefer ?? []).map((r) => ({ ...r, ruleId: `${p.namespace}/${r.id}`, package: p.name, packageDir: p.dir }))
4152
+ );
4153
+ }
4154
+ var specMatcher = (s) => s.endsWith("*") ? (spec) => spec.startsWith(s.slice(0, -1)) : (spec) => spec === s;
4155
+ function compile(rule, setting, routes) {
4156
+ const expand = (globs) => globs.flatMap((g) => {
4157
+ if (!g.includes("{routes}")) return [g];
4158
+ return routes ? [g.replaceAll("{routes}", routes)] : [];
4159
+ });
4160
+ const files = expand(setting?.files ?? rule.files ?? SCRIPT_GLOBS);
4161
+ if (files.length === 0) return null;
4162
+ return {
4163
+ rule,
4164
+ level: rule.level ?? "warn",
4165
+ includes: globMatcher(files),
4166
+ excludes: globMatcher(expand(setting?.exclude ?? rule.exclude ?? [])),
4167
+ jsx: new Set(rule.forbid.jsx ?? []),
4168
+ imports: (rule.forbid.imports ?? []).map(specMatcher),
4169
+ ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
4170
+ unlessRenders: new Set(rule.unless?.renders ?? []),
4171
+ ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
4172
+ };
4173
+ }
4174
+ var JSX = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
4175
+ var ELEMENT = /(?<![\w$.])<([A-Z][\w.]*)(?=[\s>/<])/g;
4176
+ var SCRIPT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
4177
+ function messageFor(rule, found) {
4178
+ const from = rule.import ? ` (${rule.import})` : "";
4179
+ const docs = rule.docs ? ` See ${rule.docs}` : "";
4180
+ return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
4181
+ }
4182
+ var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
4183
+ var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
4184
+ var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
4185
+ function wrappersIn(file, elements, c) {
4186
+ const out = /* @__PURE__ */ new Map();
4187
+ const decls = [...file.code.matchAll(TOP_LEVEL)];
4188
+ const listed = /* @__PURE__ */ new Map();
4189
+ for (const m of file.code.matchAll(EXPORT_LIST)) {
4190
+ for (const part of m[1].split(",")) {
4191
+ const [local, exported] = part.trim().split(/\s+as\s+/);
4192
+ if (local) listed.set(local, [...listed.get(local) ?? [], exported ?? local]);
4193
+ }
4194
+ }
4195
+ for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
4196
+ decls.forEach((d, i) => {
4197
+ const name = d[3];
4198
+ if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
4199
+ const end = decls[i + 1]?.index ?? file.code.length;
4200
+ const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
4201
+ if (!hit) return;
4202
+ const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4203
+ for (const n of names) out.set(n, hit[1]);
4204
+ });
4205
+ return out;
4206
+ }
4207
+ function runPrefer(ctx, c) {
4208
+ const own = c.rule.packageDir;
4209
+ const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
4210
+ const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
4211
+ const wrappers = /* @__PURE__ */ new Map();
4212
+ const renderedBy = /* @__PURE__ */ new Map();
4213
+ for (const file of checked) {
4214
+ if (!JSX.has(file.ext)) continue;
4215
+ const elements = [...file.code.matchAll(ELEMENT)];
4216
+ renderedBy.set(file, elements);
4217
+ if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
4218
+ const found = wrappersIn(file, elements, c);
4219
+ if (found.size) wrappers.set(file.absolutePath, found);
4220
+ }
4221
+ for (const file of checked) {
4222
+ const elements = renderedBy.get(file) ?? [];
4223
+ if (exempt(file, elements.map((m) => m[1]))) continue;
4224
+ const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
4225
+ const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
4226
+ for (const m of elements) {
4227
+ const name = m[1];
4228
+ if (c.jsx.has(name)) {
4229
+ report(lineAt(file.code, m.index), name, `renders <${name}>`);
4230
+ continue;
4231
+ }
4232
+ const from = imported?.get(name.split(".")[0]);
4233
+ const around = from && !name.includes(".") ? wrappers.get(from.file)?.get(from.name) : void 0;
4234
+ if (around) report(lineAt(file.code, m.index), name, `renders <${name}>, an app wrapper around <${around}>`);
4235
+ }
4236
+ if (c.imports.length) {
4237
+ for (const { specifier, line } of importSpecifiers(file)) {
4238
+ if (c.imports.some((t) => t(specifier))) report(line, specifier, `imports ${specifier}`);
4239
+ }
4240
+ }
4241
+ if (c.pattern) {
4242
+ c.pattern.lastIndex = 0;
4243
+ for (const m of file.code.matchAll(c.pattern)) {
4244
+ const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
4245
+ report(lineAt(file.code, m.index), text, `has ${text}`);
4246
+ }
4247
+ }
4248
+ }
4249
+ }
4250
+ var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
4251
+ async function packageRulesPlugins(packages) {
4252
+ const out = [
4253
+ {
4254
+ name: "package-rules",
4255
+ check(ctx) {
4256
+ for (const p of packages) {
4257
+ const at = { rule: "package-rules-invalid", level: "warn", file: `${p.name}/package.json`, subject: p.name };
4258
+ if (p.error) ctx.report({ ...at, message: `${p.error}; its rules don't run` });
4259
+ for (const note of p.ignored ?? []) ctx.report({ ...at, message: `${note} (a newer @marktiderman/genesis-cli may read it)` });
4260
+ }
4261
+ const routes = routesDir(ctx);
4262
+ const settings = ctx.config.packageRules ?? {};
4263
+ for (const rule of preferRules(packages)) {
4264
+ if (rule.platform === "web" && isNative(ctx)) continue;
4265
+ if (rule.platform === "native" && !isNative(ctx)) continue;
4266
+ const compiled = compile(rule, settings[rule.ruleId], routes);
4267
+ if (compiled) runPrefer(ctx, compiled);
4268
+ }
3337
4269
  }
3338
- if (result === "no" && unknown) result = "unknown";
3339
4270
  }
3340
- if (result === "yes" || cut.size === 0) {
3341
- cache2.free.set(k, result);
3342
- return [result, /* @__PURE__ */ new Set()];
4271
+ ];
4272
+ for (const p of packages) {
4273
+ const file = p.declaration?.plugin;
4274
+ if (!file) continue;
4275
+ let loaded;
4276
+ try {
4277
+ loaded = await loadPlugins([file], p.dir);
4278
+ } catch (err) {
4279
+ const message = err.message;
4280
+ out.push({ name: `${p.name} plugin`, check: (ctx) => ctx.report({ rule: "package-rules-invalid", level: "warn", file: `${p.name}/package.json`, subject: p.name, message }) });
4281
+ continue;
3343
4282
  }
3344
- const entries = cache2.cut.get(k) ?? [];
3345
- entries.push({ cut: [...cut], result });
3346
- cache2.cut.set(k, entries);
3347
- return [result, cut];
3348
- };
3349
- return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
4283
+ for (const plugin of loaded) {
4284
+ out.push({
4285
+ name: `${p.namespace}/${plugin.name}`,
4286
+ check: (ctx) => plugin.check({
4287
+ ...ctx,
4288
+ report: (f) => ctx.report({ ...f, rule: f.rule.startsWith(`${p.namespace}/`) ? f.rule : `${p.namespace}/${f.rule}` })
4289
+ })
4290
+ });
4291
+ }
4292
+ }
4293
+ return out;
4294
+ }
4295
+ function unknownPackageRuleSettings(config, packages, reported) {
4296
+ const known = /* @__PURE__ */ new Set([...packageRuleIds(packages), ...reported.map((f) => f.rule)]);
4297
+ const plugins = packages.filter((p) => p.declaration?.plugin).map((p) => `${p.namespace}/`);
4298
+ return Object.keys(config.packageRules ?? {}).filter((id) => !known.has(id) && !plugins.some((ns) => id.startsWith(ns))).map((id) => ({
4299
+ rule: "stale-exception",
4300
+ level: "warn",
4301
+ file: "genesis config",
4302
+ subject: id,
4303
+ message: `packageRules names ${id}, which no installed package declares; check the id (genesis primitives lists them) or remove it`
4304
+ }));
4305
+ }
4306
+ function packageRuleIds(packages) {
4307
+ return new Set(preferRules(packages).map((r) => r.ruleId));
3350
4308
  }
3351
4309
 
3352
4310
  // src/doctor/packages.ts
@@ -3357,10 +4315,10 @@ var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([
3357
4315
  var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
3358
4316
  function sourceFiles(dir, rel = "") {
3359
4317
  const out = [];
3360
- for (const entry of readdirSync(path14.join(dir, rel)).sort()) {
4318
+ for (const entry of readdirSync(path18.join(dir, rel)).sort()) {
3361
4319
  if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
3362
4320
  const child = rel ? `${rel}/${entry}` : entry;
3363
- const stat = lstatSync(path14.join(dir, child));
4321
+ const stat = lstatSync(path18.join(dir, child));
3364
4322
  if (stat.isSymbolicLink()) continue;
3365
4323
  if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
3366
4324
  else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
@@ -3383,13 +4341,13 @@ function matchPattern(pattern, spec) {
3383
4341
  return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3384
4342
  }
3385
4343
  function tsconfigPaths(dir) {
3386
- const file = path14.join(dir, "tsconfig.json");
4344
+ const file = path18.join(dir, "tsconfig.json");
3387
4345
  if (!existsSync(file)) return [];
3388
4346
  try {
3389
4347
  const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
3390
4348
  const options = JSON.parse(text).compilerOptions ?? {};
3391
- const base = path14.resolve(dir, options.baseUrl ?? ".");
3392
- return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path14.resolve(base, t)) }));
4349
+ const base = path18.resolve(dir, options.baseUrl ?? ".");
4350
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path18.resolve(base, t)) }));
3393
4351
  } catch {
3394
4352
  return [];
3395
4353
  }
@@ -3403,8 +4361,8 @@ function checkImports2(ctx, pkg, json) {
3403
4361
  const hit = matchPattern(pattern, spec);
3404
4362
  if (hit === null) continue;
3405
4363
  return targets.some((t) => {
3406
- const rel = path14.relative(pkg.dir, t.replace("*", hit));
3407
- return !rel.startsWith("..") && !path14.isAbsolute(rel);
4364
+ const rel = path18.relative(pkg.dir, t.replace("*", hit));
4365
+ return !rel.startsWith("..") && !path18.isAbsolute(rel);
3408
4366
  });
3409
4367
  }
3410
4368
  return null;
@@ -3417,7 +4375,7 @@ function checkImports2(ctx, pkg, json) {
3417
4375
  ...Object.keys(json.optionalDependencies ?? {})
3418
4376
  ]);
3419
4377
  for (const file of sourceFiles(pkg.dir)) {
3420
- const code = stripForImports(readFileSync(path14.join(pkg.dir, file), "utf8"));
4378
+ const code = stripForImports(readFileSync(path18.join(pkg.dir, file), "utf8"));
3421
4379
  if (code === null) continue;
3422
4380
  const at = `${pkg.rel}/${file}`;
3423
4381
  const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
@@ -3442,9 +4400,9 @@ function checkImports2(ctx, pkg, json) {
3442
4400
  continue;
3443
4401
  }
3444
4402
  if (spec.startsWith(".")) {
3445
- const target = path14.resolve(pkg.dir, path14.dirname(file), spec);
3446
- const rel = path14.relative(pkg.dir, target);
3447
- if (rel.startsWith("..") || path14.isAbsolute(rel)) {
4403
+ const target = path18.resolve(pkg.dir, path18.dirname(file), spec);
4404
+ const rel = path18.relative(pkg.dir, target);
4405
+ if (rel.startsWith("..") || path18.isAbsolute(rel)) {
3448
4406
  ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} reaches outside its folder (${spec}); move what it needs into the package or a dependency` });
3449
4407
  }
3450
4408
  continue;
@@ -3466,12 +4424,12 @@ function checkMigrations(ctx, pkg, json) {
3466
4424
  if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
3467
4425
  if (typeof m.file === "string" && typeof m.test !== "string") {
3468
4426
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.file, message: `${pkg.name} block ${id}: ${m.file} has no pgTAP test; declare one as "test" beside it` });
3469
- } else if (typeof m.test === "string" && !existsSync(path14.join(pkg.dir, m.test))) {
4427
+ } else if (typeof m.test === "string" && !existsSync(path18.join(pkg.dir, m.test))) {
3470
4428
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.test, message: `${pkg.name} block ${id}: its test ${m.test} doesn't exist` });
3471
4429
  }
3472
4430
  }
3473
4431
  }
3474
- const dir = path14.join(pkg.dir, "migrations");
4432
+ const dir = path18.join(pkg.dir, "migrations");
3475
4433
  if (!existsSync(dir)) return;
3476
4434
  const seen = /* @__PURE__ */ new Map();
3477
4435
  for (const name of readdirSync(dir).sort()) {
@@ -3480,7 +4438,7 @@ function checkMigrations(ctx, pkg, json) {
3480
4438
  const other = seen.get(m[1]);
3481
4439
  if (other) ctx.report({ rule: "package-migration-number", file: `${pkg.rel}/migrations/${name}`, subject: m[1], message: `${pkg.name}: ${name} and ${other} share the number ${m[1]}; give each migration its own` });
3482
4440
  else seen.set(m[1], name);
3483
- if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path14.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
4441
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path18.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
3484
4442
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/migrations/${name}`, subject: name, message: `${pkg.name}: ${name} has no pgTAP test (migrations/tests/${name.replace(/\.sql$/, ".test.sql")})` });
3485
4443
  }
3486
4444
  }
@@ -3494,7 +4452,7 @@ function checkExports(ctx, pkg, json) {
3494
4452
  walk(json.exports);
3495
4453
  for (const t of targets) {
3496
4454
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
3497
- if (!existsSync(path14.join(pkg.dir, t))) {
4455
+ if (!existsSync(path18.join(pkg.dir, t))) {
3498
4456
  ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
3499
4457
  }
3500
4458
  }
@@ -3512,11 +4470,11 @@ function checkBlocks(ctx, pkg, json) {
3512
4470
  function checkTaggedTests(ctx, pkg) {
3513
4471
  const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
3514
4472
  if (!tests.length) return;
3515
- const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path14.join(pkg.dir, f), "utf8")));
4473
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path18.join(pkg.dir, f), "utf8")));
3516
4474
  if (!tagged) ctx.report({ rule: "package-untagged-tests", level: "warn", file: pkg.rel, message: `${pkg.name}'s tests name no feature; tag them with // @feat:<feature id>` });
3517
4475
  }
3518
4476
  function checkRegistered(ctx, pkg) {
3519
- const file = path14.join(ctx.root, "features.json");
4477
+ const file = path18.join(ctx.root, "features.json");
3520
4478
  if (!existsSync(file)) return;
3521
4479
  let doc;
3522
4480
  try {
@@ -3526,7 +4484,7 @@ function checkRegistered(ctx, pkg) {
3526
4484
  }
3527
4485
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3528
4486
  const forms = /* @__PURE__ */ new Set([pkg.rel]);
3529
- if (top) forms.add(path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/"));
4487
+ if (top) forms.add(path18.relative(top, realpathSync(pkg.dir)).split(path18.sep).join("/"));
3530
4488
  const covered = (doc.features ?? []).some(
3531
4489
  (f) => (f.links?.code ?? []).some((c) => {
3532
4490
  const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -3556,9 +4514,9 @@ function mergeBaseOf(root, base) {
3556
4514
  function checkChanges(ctx, pkg, json, base, mergeBase) {
3557
4515
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3558
4516
  if (!top) return;
3559
- const appRelative = (fromTop) => path14.relative(realpathSync(ctx.root), path14.join(top, fromTop)).split(path14.sep).join("/");
3560
- const inRepo = path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/");
3561
- const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell, i) => i === 0 ? cell : appRelative(cell)).join(" ")).join("\n");
4517
+ const appRelative = (fromTop) => path18.relative(realpathSync(ctx.root), path18.join(top, fromTop)).split(path18.sep).join("/");
4518
+ const inRepo = path18.relative(top, realpathSync(pkg.dir)).split(path18.sep).join("/");
4519
+ const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell2, i) => i === 0 ? cell2 : appRelative(cell2)).join(" ")).join("\n");
3562
4520
  const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
3563
4521
  const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
3564
4522
  (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
@@ -3580,11 +4538,11 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
3580
4538
  const now = typeof json.version === "string" ? parseVersion(json.version) : null;
3581
4539
  const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
3582
4540
  const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
3583
- const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path14.join(top, f)) : [];
4541
+ const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path18.join(top, f)) : [];
3584
4542
  const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
3585
4543
  const named = naming.length > 0;
3586
4544
  if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
3587
- ctx.report({ rule: "package-unversioned-change", level: "warn", file: path14.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
4545
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path18.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
3588
4546
  }
3589
4547
  let jsonBefore = null;
3590
4548
  try {
@@ -3594,7 +4552,7 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
3594
4552
  }
3595
4553
  const raw = json;
3596
4554
  if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
3597
- const appInRepo = path14.relative(top, realpathSync(ctx.root)).split(path14.sep).join("/");
4555
+ const appInRepo = path18.relative(top, realpathSync(ctx.root)).split(path18.sep).join("/");
3598
4556
  const candidates = [.../* @__PURE__ */ new Set(["features.ts", "src/features.ts", ...appInRepo ? [`${appInRepo}/features.ts`, `${appInRepo}/src/features.ts`] : []])];
3599
4557
  const registry = (git(top, ["diff", "--name-only", mergeBase, "--", ...candidates]) ?? "").trim();
3600
4558
  if (!registry) ctx.report({ rule: "package-unversioned-change", level: "warn", file: `${pkg.rel}/package.json`, message: `${pkg.name}'s blocks or exports changed but features.ts didn't; update the features they belong to` });
@@ -3611,6 +4569,26 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
3611
4569
  });
3612
4570
  }
3613
4571
  }
4572
+ var GENESIS_NAME = /^@marktiderman\/genesis(?:-[a-z0-9-]+)?$/;
4573
+ function checkDoctorDeclaration(ctx, pkg, json) {
4574
+ if (json.private === true || !GENESIS_NAME.test(json.name)) return;
4575
+ const file = `${pkg.rel}/package.json`;
4576
+ const raw = json.genesis?.doctor;
4577
+ if (raw === void 0) {
4578
+ ctx.report({
4579
+ rule: "package-doctor-declaration",
4580
+ file,
4581
+ subject: json.name,
4582
+ message: `${json.name} declares no doctor rules; add genesis.doctor with the primitives it enforces ("prefer" rules), or { "enforce": false, "reason": "\u2026" }`
4583
+ });
4584
+ return;
4585
+ }
4586
+ try {
4587
+ validateDeclaration(raw, json.name, pkg.dir);
4588
+ } catch (err) {
4589
+ ctx.report({ rule: "package-doctor-declaration", file, subject: json.name, message: err.message });
4590
+ }
4591
+ }
3614
4592
  function checkPackagesPack(ctx) {
3615
4593
  let packages;
3616
4594
  try {
@@ -3626,13 +4604,14 @@ function checkPackagesPack(ctx) {
3626
4604
  ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
3627
4605
  }
3628
4606
  for (const pkg of packages) {
3629
- const json = JSON.parse(readFileSync(path14.join(pkg.dir, "package.json"), "utf8"));
4607
+ const json = JSON.parse(readFileSync(path18.join(pkg.dir, "package.json"), "utf8"));
3630
4608
  checkImports2(ctx, pkg, json);
3631
4609
  checkExports(ctx, pkg, json);
3632
4610
  checkBlocks(ctx, pkg, json);
3633
4611
  checkMigrations(ctx, pkg, json);
3634
4612
  checkTaggedTests(ctx, pkg);
3635
4613
  checkRegistered(ctx, pkg);
4614
+ checkDoctorDeclaration(ctx, pkg, json);
3636
4615
  if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
3637
4616
  }
3638
4617
  }
@@ -3797,30 +4776,30 @@ function gitView(root, dir, base) {
3797
4776
  const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
3798
4777
  if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
3799
4778
  const sql = (p) => p !== void 0 && p.endsWith(".sql");
3800
- const touched = new Set(untracked.split("\n").filter(sql));
4779
+ const touched2 = new Set(untracked.split("\n").filter(sql));
3801
4780
  const edited = [];
3802
4781
  for (const row of diff.split("\n").filter(Boolean)) {
3803
4782
  const [status, a, b] = row.split(" ");
3804
4783
  if (status.startsWith("R")) {
3805
- if (sql(b)) touched.add(b);
4784
+ if (sql(b)) touched2.add(b);
3806
4785
  if (sql(a)) edited.push({ file: a, status: "renamed" });
3807
4786
  continue;
3808
4787
  }
3809
4788
  if (!sql(a)) continue;
3810
- if (status.startsWith("A")) touched.add(a);
4789
+ if (status.startsWith("A")) touched2.add(a);
3811
4790
  else if (status.startsWith("M") || status.startsWith("T")) {
3812
- touched.add(a);
4791
+ touched2.add(a);
3813
4792
  edited.push({ file: a, status: "modified" });
3814
4793
  } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
3815
4794
  }
3816
- return { touched, edited };
4795
+ return { touched: touched2, edited };
3817
4796
  }
3818
4797
  function checkSupabasePack(ctx) {
3819
4798
  const settings = ctx.config.supabase ?? {};
3820
4799
  const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
3821
- const abs = path14.join(ctx.root, dir);
4800
+ const abs = path18.join(ctx.root, dir);
3822
4801
  if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
3823
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
4802
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path18.join(abs, n), "utf8")) }));
3824
4803
  const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
3825
4804
  const base = settings.base ?? DEFAULT_BASE;
3826
4805
  const view = gitView(ctx.root, dir, base);
@@ -3837,7 +4816,7 @@ function checkSupabasePack(ctx) {
3837
4816
  }
3838
4817
  }
3839
4818
  const since = settings.since;
3840
- const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
4819
+ const afterSince = (file) => since === void 0 || path18.posix.basename(file) >= since;
3841
4820
  if ("reason" in view && since === void 0) {
3842
4821
  ctx.report({
3843
4822
  rule: "migration-grants",
@@ -4089,7 +5068,7 @@ function checkDefinerSearchPath(ctx, migrations) {
4089
5068
  var UMBRELLA_PACKAGE = "@marktiderman/genesis";
4090
5069
  function readReleaseManifest(root) {
4091
5070
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
4092
- const file = dir && path14.join(dir, "dist", "versions.json");
5071
+ const file = dir && path18.join(dir, "dist", "versions.json");
4093
5072
  if (!file || !existsSync(file)) return null;
4094
5073
  return JSON.parse(readFileSync(file, "utf8"));
4095
5074
  }
@@ -4099,7 +5078,7 @@ function checkVersionSkew(ctx) {
4099
5078
  for (const [name, want] of Object.entries(manifest.packages)) {
4100
5079
  const dir = findPackageDir(ctx.root, name);
4101
5080
  if (!dir) continue;
4102
- const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
5081
+ const have = JSON.parse(readFileSync(path18.join(dir, "package.json"), "utf8")).version;
4103
5082
  if (have === want) continue;
4104
5083
  ctx.report({
4105
5084
  rule: "version-skew",
@@ -4110,12 +5089,12 @@ function checkVersionSkew(ctx) {
4110
5089
  });
4111
5090
  }
4112
5091
  }
4113
- var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
5092
+ var GENESIS2 = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
4114
5093
  var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
4115
5094
  var NON_SHIPPING = /^(?:@marktiderman\/genesis-cli|vitest|@vitest\/.+|jest|jest-.+|@jest\/.+|ts-jest|babel-jest|mocha|ava|c8|nyc|@playwright\/test|playwright|cypress|@testing-library\/.+|happy-dom|jsdom|msw|@types\/.+|typescript|tsx|ts-node|eslint|eslint-.+|@eslint\/.+|@typescript-eslint\/.+|typescript-eslint|prettier|prettier-.+|@biomejs\/.+|oxlint|vite|@vitejs\/.+|vite-plugin-.+|webpack|webpack-.+|rollup|@rollup\/.+|esbuild|tsup|turbo|@storybook\/.+|storybook|@changesets\/.+|husky|lint-staged|wrangler|knip|concurrently|npm-run-all2?|rimraf|cross-env|dotenv-cli)$/;
4116
5095
  var readManifest = (dir) => {
4117
5096
  try {
4118
- return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
5097
+ return JSON.parse(readFileSync(path18.join(dir, "package.json"), "utf8"));
4119
5098
  } catch {
4120
5099
  return null;
4121
5100
  }
@@ -4129,18 +5108,18 @@ var real = (p) => {
4129
5108
  };
4130
5109
  var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
4131
5110
  function nodeModulesOf(dir) {
4132
- const parent = path14.dirname(dir);
4133
- return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
5111
+ const parent = path18.dirname(dir);
5112
+ return path18.basename(parent).startsWith("@") ? path18.dirname(parent) : parent;
4134
5113
  }
4135
5114
  function packagesIn(nodeModules) {
4136
5115
  if (!existsSync(nodeModules)) return [];
4137
5116
  const out = [];
4138
5117
  for (const entry of readdirSync(nodeModules)) {
4139
5118
  if (entry.startsWith(".")) continue;
4140
- const p = path14.join(nodeModules, entry);
5119
+ const p = path18.join(nodeModules, entry);
4141
5120
  if (entry.startsWith("@")) {
4142
5121
  try {
4143
- for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
5122
+ for (const sub of readdirSync(p)) out.push(path18.join(p, sub));
4144
5123
  } catch {
4145
5124
  }
4146
5125
  } else {
@@ -4152,7 +5131,7 @@ function packagesIn(nodeModules) {
4152
5131
  function genesisInstalls(root) {
4153
5132
  const copies = /* @__PURE__ */ new Map();
4154
5133
  const realRoot = real(root);
4155
- const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
5134
+ const rel = (abs) => path18.relative(realRoot, abs).split(path18.sep).join("/") || ".";
4156
5135
  const via = /* @__PURE__ */ new Map();
4157
5136
  const record = (real2, manifest, by, range, root2) => {
4158
5137
  let copy = copies.get(real2);
@@ -4172,7 +5151,7 @@ function genesisInstalls(root) {
4172
5151
  if (!manifest?.name) return;
4173
5152
  if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
4174
5153
  const realDir = real(dir);
4175
- if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
5154
+ if (GENESIS2.test(manifest.name)) record(realDir, manifest, by, range, kind);
4176
5155
  if (expanded.has(realDir)) return;
4177
5156
  expanded.add(realDir);
4178
5157
  queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
@@ -4197,7 +5176,7 @@ function genesisInstalls(root) {
4197
5176
  if (!dir) return null;
4198
5177
  if (!ownInstall || name in declared) return dir;
4199
5178
  const realDir = real(dir);
4200
- if (realDir.startsWith(realRoot + path14.sep)) return dir;
5179
+ if (realDir.startsWith(realRoot + path18.sep)) return dir;
4201
5180
  return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
4202
5181
  };
4203
5182
  const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
@@ -4205,7 +5184,7 @@ function genesisInstalls(root) {
4205
5184
  return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
4206
5185
  });
4207
5186
  const app = readManifest(root);
4208
- const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
5187
+ const ownInstall = LOCKFILES.some((f) => existsSync(path18.join(root, f)));
4209
5188
  const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
4210
5189
  const declaredDev = Object.entries(app?.devDependencies ?? {});
4211
5190
  const runtimeDeps = {
@@ -4216,11 +5195,11 @@ function genesisInstalls(root) {
4216
5195
  };
4217
5196
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
4218
5197
  walk("runtime", rootsOf(runtimeDeps, "the app"));
4219
- const top = path14.join(root, "node_modules");
5198
+ const top = path18.join(root, "node_modules");
4220
5199
  walk(
4221
5200
  "hoisted",
4222
5201
  packagesIn(top).filter((dir) => {
4223
- const name = path14.relative(top, dir).split(path14.sep).join("/");
5202
+ const name = path18.relative(top, dir).split(path18.sep).join("/");
4224
5203
  return !(name in runtimeDeps) && !(name in devDeps);
4225
5204
  }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
4226
5205
  );
@@ -4262,13 +5241,13 @@ function checkDuplicatePackages(ctx) {
4262
5241
  }
4263
5242
  }
4264
5243
  function checkPeerRanges(ctx) {
4265
- const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
5244
+ const rel = (abs) => path18.relative(ctx.root, abs).split(path18.sep).join("/");
4266
5245
  for (const copies of genesisInstalls(ctx.root).values()) {
4267
5246
  for (const copy of copies) {
4268
5247
  const dir = copy.absolutePath;
4269
5248
  const peers = readManifest(dir)?.peerDependencies ?? {};
4270
5249
  for (const [peer, range] of Object.entries(peers)) {
4271
- if (!GENESIS.test(peer)) continue;
5250
+ if (!GENESIS2.test(peer)) continue;
4272
5251
  const peerDir = findPackageDir(dir, peer);
4273
5252
  const installed = peerDir && readManifest(peerDir)?.version;
4274
5253
  if (!peerDir || !installed) continue;
@@ -4285,112 +5264,6 @@ function checkPeerRanges(ctx) {
4285
5264
  }
4286
5265
  }
4287
5266
  }
4288
- var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
4289
- var STEMS = {
4290
- tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
4291
- "next-app": {
4292
- layout: /* @__PURE__ */ new Set(["layout"]),
4293
- index: /* @__PURE__ */ new Set(["page"]),
4294
- skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
4295
- },
4296
- "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
4297
- };
4298
- var NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
4299
- var HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
4300
- var COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
4301
- var RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
4302
- var OWN_CONTENT = /(?<![=-])>\s*[A-Za-z][^<>{}]*</.source + "|" + /(?<![\w$.])<(?:h[1-6]|ul|ol|table|dl|H[1-6]|[A-Z]\w*(?:Heading|Title|Table|List|Grid))(?=[\s>/])/.source;
4303
- function routesDir(ctx) {
4304
- if (ctx.config.routesDir) return ctx.config.routesDir;
4305
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path14.join(ctx.root, d))) ?? null;
4306
- }
4307
- var key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
4308
- function flavorOf(dir, rels) {
4309
- const stems = rels.map((r) => r.split("/").pop());
4310
- if (stems.includes("__root")) return "tanstack";
4311
- if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
4312
- if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
4313
- return "tanstack";
4314
- }
4315
- function renders(code) {
4316
- const elements = renderedElements(code);
4317
- if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
4318
- const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
4319
- const named = COMPONENT_OPTION.exec(code)?.[1];
4320
- if (named && !definedHere(named)) return true;
4321
- if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
4322
- const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
4323
- return exported !== void 0 && !definedHere(exported);
4324
- }
4325
- function webRoutes(ctx) {
4326
- const dir = routesDir(ctx);
4327
- if (!dir) return [];
4328
- const candidates = ctx.files.filter((f) => JSX_EXTS2.has(f.ext) && f.path.startsWith(`${dir}/`)).map((file) => ({ file, rel: file.path.slice(dir.length + 1).replace(/\.[^.]+$/, "") }));
4329
- const flavor = flavorOf(dir, candidates.map((c) => c.rel));
4330
- const stems = STEMS[flavor];
4331
- const groups = /* @__PURE__ */ new Map();
4332
- for (const { file, rel } of candidates) {
4333
- const parts = rel.split("/");
4334
- if (parts.some((p) => p.startsWith("-"))) continue;
4335
- if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
4336
- if (flavor === "next-pages" && parts[0] === "api") continue;
4337
- if (stems.skip.test(parts.at(-1))) continue;
4338
- if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
4339
- const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
4340
- groups.set(id, [...groups.get(id) ?? [], file]);
4341
- }
4342
- const trail = trailFor(ctx);
4343
- const routes = [];
4344
- for (const [id, files] of groups) {
4345
- const parts = id.split("/");
4346
- const stem = parts.pop();
4347
- const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
4348
- const named = stems.layout.has(stem) || stems.index.has(stem);
4349
- const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
4350
- const segments = [...folders, ...own];
4351
- const tree = [...parts, ...own];
4352
- let index = stems.index.has(stem);
4353
- if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
4354
- segments.pop();
4355
- tree.pop();
4356
- index = true;
4357
- }
4358
- const code = files.map((f) => f.code).join("\n");
4359
- const elements = renderedElements(code);
4360
- const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
4361
- const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
4362
- const layout = stems.layout.has(stem) || pathless || outlet;
4363
- const rendering = renders(code);
4364
- const ownContent = new RegExp(OWN_CONTENT).test(code);
4365
- const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
4366
- const page = !pure && !pathless && (!layout || ownContent);
4367
- routes.push({
4368
- file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
4369
- files,
4370
- segments,
4371
- tree,
4372
- index,
4373
- layout,
4374
- page,
4375
- detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
4376
- redirectOnly: !rendering,
4377
- parents: []
4378
- });
4379
- }
4380
- for (const r of routes) {
4381
- const own = r.tree;
4382
- for (const p of routes) {
4383
- if (p === r || !p.layout) continue;
4384
- const n = p.tree.length;
4385
- if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
4386
- if (key(own.slice(0, n)) !== key(p.tree)) continue;
4387
- if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
4388
- r.parents.push(p);
4389
- }
4390
- r.parents.sort((a, b) => b.tree.length - a.tree.length);
4391
- }
4392
- return routes;
4393
- }
4394
5267
 
4395
5268
  // src/doctor/structure.ts
4396
5269
  var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/ui/SKILL.md (Sub-navigation)";
@@ -4401,7 +5274,7 @@ var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
4401
5274
  var PAGE_LAYOUT = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)|ResourceView)$/;
4402
5275
  var EMBEDDED_RESOURCE_VIEW = /<ResourceView\b[^>]*?\blayout\s*=\s*(?:(["'`]) {8}\1|\{\s*(["'`]) {8}\2\s*\})[^>]*>/g;
4403
5276
  var PACKAGE_SCREEN = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)|ResourceView)$/;
4404
- var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
5277
+ var isNative2 = (ctx) => ctx.config.packs?.includes("native") ?? false;
4405
5278
  var rendersRe = (names) => {
4406
5279
  const list = [...names];
4407
5280
  return list.length ? new RegExp(`<(?:${list.map((n) => n.replace(/[.$]/g, "\\$&")).join("|")})(?=[\\s>/])`) : null;
@@ -4423,7 +5296,7 @@ function insideShell(ctx, routes) {
4423
5296
  return (r) => !shell.has(r) && (anyShell || r.parents.some((p) => shell.has(p)));
4424
5297
  }
4425
5298
  function checkHandRolledSubNav(ctx) {
4426
- if (isNative(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
5299
+ if (isNative2(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
4427
5300
  const routes = webRoutes(ctx);
4428
5301
  if (routes.length === 0) return;
4429
5302
  const inShell = insideShell(ctx, routes);
@@ -4480,7 +5353,7 @@ function checkLocalGenesisCopies(ctx) {
4480
5353
  }
4481
5354
  }
4482
5355
  function checkResourceWorkspaces(ctx) {
4483
- if (isNative(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
5356
+ if (isNative2(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
4484
5357
  const header = /<AppShellPageHeader(?=[\s>/])/;
4485
5358
  const byFolder = /* @__PURE__ */ new Map();
4486
5359
  for (const r of webRoutes(ctx)) {
@@ -4505,7 +5378,7 @@ function checkResourceWorkspaces(ctx) {
4505
5378
  }
4506
5379
  }
4507
5380
  function checkPageLayouts(ctx) {
4508
- if (isNative(ctx)) return;
5381
+ if (isNative2(ctx)) return;
4509
5382
  const layouts = new Set(ctx.genesis.components.filter((n) => PAGE_LAYOUT.test(n)));
4510
5383
  for (const c of ctx.genesis.companions) for (const n of c.components) if (PAGE_LAYOUT.test(n)) layouts.add(n);
4511
5384
  if (layouts.size === 0) return;
@@ -4744,17 +5617,17 @@ var PRACTICE_ID_AUGMENTATION = 'declare module "@marktiderman/genesis-core" { in
4744
5617
 
4745
5618
  // src/upgrade/codemods.ts
4746
5619
  var SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
4747
- var SCRIPT = /\.(?:[cm]?[jt]sx?)$/;
5620
+ var SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
4748
5621
  var MAX_BYTES = 2 * 1024 * 1024;
4749
5622
  function appScripts(root) {
4750
5623
  const out = [];
4751
5624
  const walk = (dir) => {
4752
5625
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
4753
- const abs = path14.join(dir, entry.name);
5626
+ const abs = path18.join(dir, entry.name);
4754
5627
  if (entry.isDirectory()) {
4755
5628
  if (!SKIP_DIRS3.has(entry.name)) walk(abs);
4756
- } else if (entry.isFile() && SCRIPT.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
4757
- out.push(path14.relative(root, abs).split(path14.sep).join("/"));
5629
+ } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
5630
+ out.push(path18.relative(root, abs).split(path18.sep).join("/"));
4758
5631
  }
4759
5632
  }
4760
5633
  };
@@ -4842,7 +5715,7 @@ var ROOT_REQUIRE = /\brequire\s*\(\s*["']@marktiderman\/genesis-studio-server["'
4842
5715
  function moduleFiles(ctx) {
4843
5716
  const scanned = new Set(ctx.files.map((f) => f.path));
4844
5717
  const ignored = globMatcher([...DEFAULT_IGNORE, ...ctx.config.ignore ?? []]);
4845
- const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path14.join(ctx.root, rel), "utf8"), true) }));
5718
+ const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path18.join(ctx.root, rel), "utf8"), true) }));
4846
5719
  return [...ctx.files.filter((f) => SCRIPT_EXTS5.has(f.ext)), ...extra];
4847
5720
  }
4848
5721
  function checkStudioServerImports(ctx) {
@@ -4878,7 +5751,7 @@ var REMOVED_WORDS = {
4878
5751
  };
4879
5752
  function checkRemovedScopeNames(ctx) {
4880
5753
  let augmentedMemo;
4881
- const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path14.join(ctx.root, rel), "utf8")));
5754
+ const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path18.join(ctx.root, rel), "utf8")));
4882
5755
  for (const file of ctx.files) {
4883
5756
  if (!SCRIPT_EXTS5.has(file.ext)) continue;
4884
5757
  for (const hit of findRemovedScopeNames(file.code)) {
@@ -4905,23 +5778,346 @@ function checkRemovedScopeNames(ctx) {
4905
5778
  }
4906
5779
  }
4907
5780
  }
4908
-
4909
- // src/doctor/index.ts
5781
+ function git3(root, args) {
5782
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
5783
+ return r.status === 0 ? r.stdout : null;
5784
+ }
5785
+ function changedSince(root, base) {
5786
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
5787
+ if (!mergeBase) return null;
5788
+ const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
5789
+ const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
5790
+ if (committed === null || untracked === null) return null;
5791
+ return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
5792
+ }
5793
+ var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
5794
+ function showAt(dir, rev, file) {
5795
+ const at = `${rev}:./${file}`;
5796
+ if (git3(dir, ["cat-file", "-e", at]) === null) return void 0;
5797
+ return git3(dir, ["show", at]);
5798
+ }
5799
+ function configAtBase(root, base, explicitFile) {
5800
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
5801
+ if (!mergeBase) return null;
5802
+ const candidates = explicitFile ? [{ dir: path18.dirname(explicitFile), file: path18.basename(explicitFile), explicit: true }] : [
5803
+ { dir: root, file: "genesis.config.json", explicit: false },
5804
+ { dir: root, file: "package.json", explicit: false }
5805
+ ];
5806
+ for (const c of candidates) {
5807
+ const text = showAt(c.dir, mergeBase, c.file);
5808
+ if (text === null) return null;
5809
+ if (text === void 0) continue;
5810
+ let block;
5811
+ try {
5812
+ block = doctorBlock(JSON.parse(text), c.file, c.explicit);
5813
+ } catch {
5814
+ return null;
5815
+ }
5816
+ if (block === void 0 || c.file === "package.json" && !c.explicit && isPackageDeclaration(block)) {
5817
+ if (c.file === "genesis.config.json") return "absent";
5818
+ continue;
5819
+ }
5820
+ const b = objectOr(block);
5821
+ return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
5822
+ }
5823
+ return "absent";
5824
+ }
5825
+ var allowKey = (a) => `${a.rule}\0${a.file ?? ""}\0${a.match ?? ""}`;
5826
+ function allowGrew(allow, before, base) {
5827
+ const had = new Set(before.map(allowKey));
5828
+ return allow.filter((a) => !had.has(allowKey(a))).map((a) => ({
5829
+ rule: "allow-grew",
5830
+ file: a.file ?? "genesis config",
5831
+ subject: a.rule,
5832
+ message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
5833
+ }));
5834
+ }
5835
+ var RANK = { off: 0, info: 1, warn: 2, error: 3 };
5836
+ function rulesWeakened(config, before, base) {
5837
+ const out = [];
5838
+ const levelIn = (c, rule) => c.rules?.[rule] ?? c.packageRules?.[rule]?.level;
5839
+ const ids = /* @__PURE__ */ new Set([...Object.keys(config.rules ?? {}), ...Object.keys(config.packageRules ?? {})]);
5840
+ for (const rule of ids) {
5841
+ const set = levelIn(config, rule);
5842
+ if (set === void 0) continue;
5843
+ const was = levelIn(before, rule);
5844
+ if (was === void 0 ? set === "off" : RANK[set] < RANK[was]) {
5845
+ out.push({ rule: "rules-weakened", file: "genesis config", subject: rule, message: `${rule} is set to "${set}"${was ? `, lower than "${was}"` : ""} since ${base}; rules only tighten, so fix what it finds instead` });
5846
+ }
5847
+ }
5848
+ for (const [rule, setting] of Object.entries(config.packageRules ?? {})) {
5849
+ const had = new Set(before.packageRules[rule]?.exclude ?? []);
5850
+ const added = (setting.exclude ?? []).filter((g) => !had.has(g));
5851
+ if (added.length) {
5852
+ out.push({ rule: "rules-weakened", file: "genesis config", subject: rule, message: `packageRules excludes ${added.join(", ")} from ${rule} since ${base}; rules only tighten, so fix what it finds instead` });
5853
+ }
5854
+ }
5855
+ return out;
5856
+ }
5857
+ function touched(file, changed) {
5858
+ if (changed.has(file)) return true;
5859
+ const prefix = file.endsWith("/") ? file : `${file}/`;
5860
+ for (const c of changed) if (c.startsWith(prefix)) return true;
5861
+ return false;
5862
+ }
5863
+ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
5864
+ ...META_RULES,
5865
+ "stale-exception",
5866
+ "package-rule-override",
5867
+ "package-rules-invalid",
5868
+ "package-doctor-declaration",
5869
+ "plugin-error",
5870
+ "build",
5871
+ "agent-guide-stale",
5872
+ "contracts-stale"
5873
+ ]);
5874
+ function applyRatchet(findings, options) {
5875
+ const { config, newOnly, changed, base, isAppPath } = options;
5876
+ const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
5877
+ return findings.map((f) => {
5878
+ if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
5879
+ return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
5880
+ });
5881
+ }
5882
+ var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
5883
+ var DEFAULT_DATABASE_ENV = "DATABASE_URL";
5884
+ var shellArg = (s) => /^[\w./,@:+=-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
5885
+ var postgresSource = (schemas) => `Postgres (${schemas.join(", ")})`;
5886
+ async function postgresContract(url, schemas) {
5887
+ const { introspectPostgres: introspectPostgres2, emitContracts: emitContracts2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
5888
+ const { default: postgres } = await import('postgres');
5889
+ const sql = postgres(url, { max: 1, prepare: false, onnotice: () => {
5890
+ } });
5891
+ try {
5892
+ const tables = await introspectPostgres2(sql, schemas);
5893
+ return { content: emitContracts2(tables, { source: postgresSource(schemas) }), tables: tables.length };
5894
+ } finally {
5895
+ await sql.end();
5896
+ }
5897
+ }
5898
+ function contractSource(content) {
5899
+ return /^\/\/ Source: (.*)$/m.exec(content.slice(0, 2e3))?.[1]?.trim() ?? null;
5900
+ }
5901
+ function sourceSchemas(source) {
5902
+ const m = source === null ? null : /^Postgres \((.*)\)$/.exec(source);
5903
+ const schemas = m?.[1].split(",").map((s) => s.trim()).filter(Boolean);
5904
+ return schemas?.length ? schemas : null;
5905
+ }
5906
+ var lf = (text) => text.replace(/\r\n/g, "\n");
5907
+ async function checkContracts(ctx, read2 = postgresContract) {
5908
+ const settings = ctx.config.contracts;
5909
+ if (!settings) return;
5910
+ const out = settings.out ?? DEFAULT_CONTRACT_OUT;
5911
+ const env = settings.databaseEnv ?? DEFAULT_DATABASE_ENV;
5912
+ let current = null;
5913
+ try {
5914
+ current = lf(readFileSync(path18.join(ctx.root, out), "utf8"));
5915
+ } catch {
5916
+ current = null;
5917
+ }
5918
+ const source = current === null ? null : contractSource(current);
5919
+ if (source !== null && !source.startsWith("Postgres (")) {
5920
+ ctx.report({ rule: "contracts-stale", level: "info", file: out, message: `not checked: it was generated from ${source.split(" ")[0]}, and the doctor compares only contracts read from Postgres; check it with genesis introspect --check and the same source` });
5921
+ return;
5922
+ }
5923
+ const schemas = settings.schemas?.length ? settings.schemas : sourceSchemas(source) ?? ["public"];
5924
+ const url = process.env[env];
5925
+ if (!url) {
5926
+ ctx.report({ rule: "contracts-stale", level: "info", file: out, message: `not checked: set ${env} to the database URL to compare it with the database (as genesis introspect --check)` });
5927
+ return;
5928
+ }
5929
+ let expected;
5930
+ try {
5931
+ expected = lf((await read2(url, schemas)).content);
5932
+ } catch (err) {
5933
+ const generation = err.name === "EmitError";
5934
+ const message = err.message.split("\n")[0];
5935
+ ctx.report({ rule: "contracts-stale", level: generation ? "error" : "warn", file: out, message: generation ? `couldn't be generated: ${message}` : `couldn't read the database through ${env}: ${message}` });
5936
+ return;
5937
+ }
5938
+ const target = path18.relative(process.cwd(), path18.join(ctx.root, out)) || out;
5939
+ const command = `genesis introspect -o ${shellArg(target)} -s ${shellArg(schemas.join(","))}${env === DEFAULT_DATABASE_ENV ? "" : ` --database-env ${shellArg(env)}`}`;
5940
+ if (current !== expected) {
5941
+ ctx.report({
5942
+ rule: "contracts-stale",
5943
+ file: out,
5944
+ message: current === null ? `doesn't exist; run ${command} and commit it` : `is out of date with the database; run ${command} and commit the result`
5945
+ });
5946
+ }
5947
+ }
5948
+ var GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
5949
+ var CORE = [
5950
+ {
5951
+ need: "anything, before building it",
5952
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the doctor\'s "Available but unused" list',
5953
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
5954
+ from: "genesis-cli"
5955
+ },
5956
+ {
5957
+ need: "a page inside the app shell",
5958
+ use: "a Genesis page layout (`DashboardPage`, `SettingsPage`, `FormPage`, `DetailPage`, from `@marktiderman/genesis-ui`) or `ResourceView` (from `@marktiderman/genesis-ui/data`)",
5959
+ import: "@marktiderman/genesis-ui",
5960
+ rule: "page-layout",
5961
+ from: "genesis-cli"
5962
+ },
5963
+ {
5964
+ need: "a button, input, table, dialog or other component",
5965
+ use: "the Genesis component, never the raw tag or a local copy",
5966
+ import: "@marktiderman/genesis-ui/<component>",
5967
+ rule: "raw-tag",
5968
+ from: "genesis-cli"
5969
+ },
5970
+ {
5971
+ need: "colors and spacing",
5972
+ use: "semantic tokens (`bg-primary`, `text-muted-foreground`), never literal colors",
5973
+ import: "@marktiderman/genesis-design-system",
5974
+ rule: "raw-color",
5975
+ from: "genesis-cli"
5976
+ },
5977
+ {
5978
+ need: "something no primitive covers",
5979
+ use: "write the gap up for Genesis (an issue or a proposal) first, then invent in the app, on Genesis primitives",
5980
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
5981
+ from: "genesis-cli"
5982
+ }
5983
+ ];
5984
+ function primitivesCatalog(packages) {
5985
+ const rows = [...CORE];
5986
+ for (const rule of preferRules(packages)) {
5987
+ rows.push({
5988
+ need: rule.need ?? rule.id.replace(/-/g, " "),
5989
+ use: rule.use,
5990
+ ...rule.import ? { import: rule.import } : {},
5991
+ ...rule.docs ? { docs: rule.docs } : {},
5992
+ rule: rule.ruleId,
5993
+ from: rule.package
5994
+ });
5995
+ }
5996
+ for (const p of packages) {
5997
+ for (const e of p.declaration?.primitives ?? []) {
5998
+ rows.push({ need: e.need, use: e.use, ...e.import ? { import: e.import } : {}, ...e.docs ? { docs: e.docs } : {}, from: p.name });
5999
+ }
6000
+ }
6001
+ return rows;
6002
+ }
6003
+ function primitivesSummary(packages) {
6004
+ const rules = preferRules(packages);
6005
+ const withPlugin = packages.filter((p) => p.declaration?.plugin);
6006
+ return { rules: rules.length + withPlugin.length, packages: (/* @__PURE__ */ new Set([...rules.map((r) => r.package), ...withPlugin.map((p) => p.name)])).size };
6007
+ }
6008
+ var cell = (s) => (s ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ").replace(/(`[^`]*`)|<([A-Za-z][\w.]*)>/g, (m, code, name) => code ?? `\`<${name}>\``);
6009
+ var importCell = (s) => `\`${s.replace(/`/g, "").replace(/\|/g, "\\|").replace(/\n/g, " ")}\``;
6010
+ function catalogTable(rows, options = {}) {
6011
+ const head = options.docs ? "| Need | Use | Import | Enforced by | Docs |\n| --- | --- | --- | --- | --- |" : "| Need | Use | Import |\n| --- | --- | --- |";
6012
+ const body = rows.map(
6013
+ (r) => options.docs ? `| ${cell(r.need)} | ${cell(r.use)} | ${r.import ? importCell(r.import) : ""} | ${r.rule ? `\`${r.rule}\`` : ""} | ${r.docs ? `[docs](${r.docs})` : ""} |` : `| ${cell(r.need)} | ${cell(r.use)} | ${r.import ? importCell(r.import) : ""} |`
6014
+ );
6015
+ return [head, ...body].join("\n");
6016
+ }
6017
+ var SKILL_PATH = ".claude/skills/genesis/SKILL.md";
6018
+ var AGENTS_START = "<!-- genesis-primitives:start -->";
6019
+ var AGENTS_END = "<!-- genesis-primitives:end -->";
6020
+ var RULES = [
6021
+ "Use the Genesis primitive for the need first: reuse, then extend, then invent (docs/FRAMEWORK.md, G1 to G6).",
6022
+ "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
6023
+ "A list screen is a view (`defineView`) rendered by `ResourceView`; a record page is `ResourceWorkspace`; on the phone, `NativeResourceView`.",
6024
+ "Screens never call the database client (`supabase.from`, `.rpc`) directly: reads go through a view or a named data function, writes through the resource's provider rules.",
6025
+ "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
6026
+ "Run `genesis doctor` before you finish; it enforces these rules."
6027
+ ];
6028
+ function renderSkill(rows) {
6029
+ return [
6030
+ "---",
6031
+ "name: genesis",
6032
+ "description: Which Genesis primitive to use for each need (list screens, record pages, forms, data access, dates and more), with its import and docs. Load before writing any screen, list, form or data access in a Genesis app.",
6033
+ "---",
6034
+ "",
6035
+ "<!-- Generated by `genesis agents` from the installed Genesis packages. Don't edit; run `genesis agents` after upgrading Genesis. -->",
6036
+ "",
6037
+ "# Genesis primitives",
6038
+ "",
6039
+ ...RULES.map((r) => `- ${r}`),
6040
+ "",
6041
+ "## What to use for each need",
6042
+ "",
6043
+ catalogTable(rows, { docs: true }),
6044
+ "",
6045
+ "`genesis primitives` prints the same list; `genesis doctor` enforces the rules named above.",
6046
+ ""
6047
+ ].join("\n");
6048
+ }
6049
+ function renderAgentsBlock(rows) {
6050
+ return [
6051
+ AGENTS_START,
6052
+ "## Building with Genesis",
6053
+ "",
6054
+ "Generated by `genesis agents` from the installed Genesis packages. Don't edit this block; run `genesis agents` after upgrading Genesis.",
6055
+ "",
6056
+ `Before writing a screen, read \`${SKILL_PATH}\` (or run \`genesis primitives\`).`,
6057
+ "",
6058
+ ...RULES.map((r) => `- ${r}`),
6059
+ "",
6060
+ catalogTable(rows),
6061
+ AGENTS_END
6062
+ ].join("\n");
6063
+ }
6064
+ function blockSpan(text) {
6065
+ const s = text.indexOf(AGENTS_START);
6066
+ const e = text.indexOf(AGENTS_END);
6067
+ if (s < 0 && e < 0) return "absent";
6068
+ if (s < 0 || e < 0 || e < s || text.indexOf(AGENTS_START, s + 1) >= 0 || text.indexOf(AGENTS_END, e + 1) >= 0) return "broken";
6069
+ return { start: s, end: e + AGENTS_END.length };
6070
+ }
6071
+ function currentAgentsBlock(agents) {
6072
+ if (!agents) return null;
6073
+ const span = blockSpan(agents);
6074
+ if (span === "absent") return null;
6075
+ if (span === "broken") return "broken";
6076
+ return agents.slice(span.start, span.end).replace(/\r\n/g, "\n");
6077
+ }
6078
+ var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
6079
+ function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
6080
+ const rows = primitivesCatalog(packages);
6081
+ const skill = read(path18.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
6082
+ const block = currentAgentsBlock(read(path18.join(root, agentsFile)));
6083
+ return {
6084
+ skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
6085
+ agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
6086
+ };
6087
+ }
6088
+ function checkAgentGuide(ctx) {
6089
+ const state = agentGuideState(ctx.root, ctx.packages);
6090
+ if (state.skill === "missing" && state.agents === "missing") return;
6091
+ const fix = "run genesis agents and commit the result";
6092
+ if (state.skill !== "ok") {
6093
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: SKILL_PATH, message: `${state.skill === "missing" ? "is missing" : "doesn't match the installed Genesis packages"}; ${fix}` });
6094
+ }
6095
+ if (state.agents !== "ok") {
6096
+ const message = {
6097
+ missing: `has no genesis-primitives block; ${fix}`,
6098
+ broken: `has a broken genesis-primitives block (a ${AGENTS_START} or ${AGENTS_END} marker is missing, repeated or out of order); fix the markers by hand, then ${fix}`,
6099
+ stale: `has a genesis-primitives block that doesn't match the installed Genesis packages; ${fix}`
6100
+ }[state.agents];
6101
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
6102
+ }
6103
+ }
4910
6104
  async function runDoctor(options = {}) {
4911
- const root = path14.resolve(options.root ?? process.cwd());
6105
+ const root = path18.resolve(options.root ?? process.cwd());
4912
6106
  const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
4913
6107
  const config = loaded.config;
4914
6108
  const genesis = options.genesis ?? loadGenesis(root, config);
4915
6109
  const files = scanFiles(root, config);
4916
6110
  const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
4917
6111
  const plugins = await loadPlugins(config.plugins, loaded.dir);
6112
+ const packages = discoverPackages(root);
6113
+ const packagePlugins = await packageRulesPlugins(packages);
4918
6114
  const builtinIds = new Set(BUILTIN_RULES);
4919
6115
  for (const p of config.patterns ?? []) {
4920
- if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
6116
+ if (builtinIds.has(p.id) || META_RULES.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
4921
6117
  }
4922
6118
  const raw = [];
4923
- const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
4924
- for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
6119
+ const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
6120
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
4925
6121
  try {
4926
6122
  await plugin.check(ctx);
4927
6123
  } catch (err) {
@@ -4933,7 +6129,34 @@ async function runDoctor(options = {}) {
4933
6129
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
4934
6130
  if (failure) raw.push(failure);
4935
6131
  }
4936
- const findings = applyConfig(raw, config);
6132
+ raw.push(...unknownPackageRuleSettings(config, packages, raw));
6133
+ const newOnly = /* @__PURE__ */ new Set([...patterns?.newOnly ?? [], ...preferRules(packages).filter((r) => r.newOnly).map((r) => r.ruleId)]);
6134
+ let changed = null;
6135
+ let skipped = false;
6136
+ if (options.base && (newOnly.size > 0 || config.ratchet)) {
6137
+ changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
6138
+ skipped ||= !changed;
6139
+ }
6140
+ const configFile = "file" in loaded ? loaded.file : null;
6141
+ const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
6142
+ let configSkipped = false;
6143
+ if (options.base && configFile) {
6144
+ const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
6145
+ if (before && before !== "absent") {
6146
+ raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
6147
+ raw.push(...rulesWeakened(config, before, options.base));
6148
+ }
6149
+ configSkipped = !before && guarded;
6150
+ }
6151
+ if (skipped || configSkipped) {
6152
+ raw.push(
6153
+ configSkipped ? { rule: "ratchet-skipped", level: "error", file: "genesis config", message: `couldn't compare allow, rules and packageRules against ${options.base} (not a git repository, or the ref isn't fetched; in CI check out with fetch-depth: 0)` } : { rule: "ratchet-skipped", level: "warn", file: "genesis config", message: `couldn't compare against ${options.base} (not a git repository, or the ref isn't fetched); every rule ran at its full level` }
6154
+ );
6155
+ }
6156
+ let findings = applyConfig(raw, config, packageRuleIds(packages));
6157
+ if (options.base && changed) {
6158
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path18.join(root, f)) });
6159
+ }
4937
6160
  const errors = findings.filter((f) => f.level === "error").length;
4938
6161
  const warnings = findings.filter((f) => f.level === "warn").length;
4939
6162
  const infos = findings.length - errors - warnings;
@@ -4944,12 +6167,13 @@ async function runDoctor(options = {}) {
4944
6167
  findings,
4945
6168
  unused: unusedComponents(ctx),
4946
6169
  ruleCount: (patterns?.count ?? 0) + plugins.length,
6170
+ primitives: primitivesSummary(packages),
4947
6171
  errors,
4948
6172
  warnings,
4949
6173
  infos
4950
6174
  };
4951
6175
  }
4952
- function builtinChecks(config) {
6176
+ function builtinChecks(config, options = {}) {
4953
6177
  const packs = {
4954
6178
  native: { name: "native", check: checkNativePack },
4955
6179
  supabase: { name: "supabase", check: checkSupabasePack },
@@ -4973,14 +6197,28 @@ function builtinChecks(config) {
4973
6197
  { name: "resource-view-trees", check: checkTreeViews },
4974
6198
  { name: "studio-server-imports", check: checkStudioServerImports },
4975
6199
  { name: "removed-scope-names", check: checkRemovedScopeNames },
4976
- ...(config.packs ?? []).map((p) => packs[p])
6200
+ { name: "agent-guide", check: checkAgentGuide },
6201
+ ...(config.packs ?? []).map((p) => packs[p]),
6202
+ ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
4977
6203
  ];
4978
6204
  }
4979
- function applyConfig(raw, config) {
6205
+ function applyConfig(raw, config, packageIds) {
4980
6206
  const allow = (config.allow ?? []).map((entry) => ({ entry, file: entry.file ? globToRegExp(entry.file) : null, used: false }));
4981
6207
  const out = [];
6208
+ const levelOf = (rule) => META_RULES.has(rule) ? void 0 : config.rules?.[rule] ?? config.packageRules?.[rule]?.level;
6209
+ for (const [rule, level] of Object.entries(config.rules ?? {})) {
6210
+ if (!packageIds.has(rule) || config.packageRules?.[rule]?.reason) continue;
6211
+ out.push({
6212
+ rule: "package-rule-override",
6213
+ level: "warn",
6214
+ file: "genesis config",
6215
+ line: 0,
6216
+ subject: rule,
6217
+ message: `rules sets the package rule ${rule} to "${level}" without a reason; move it to doctor.packageRules["${rule}"] with { "level": "${level}", "reason": "\u2026" }`
6218
+ });
6219
+ }
4982
6220
  for (const input of raw) {
4983
- const setting = config.rules?.[input.rule];
6221
+ const setting = levelOf(input.rule);
4984
6222
  if (setting === "off") continue;
4985
6223
  const finding = {
4986
6224
  rule: input.rule,
@@ -4991,7 +6229,7 @@ function applyConfig(raw, config) {
4991
6229
  ...input.subject !== void 0 ? { subject: input.subject } : {}
4992
6230
  };
4993
6231
  const exception = allow.find(
4994
- (a) => a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
6232
+ (a) => !META_RULES.has(finding.rule) && a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
4995
6233
  );
4996
6234
  if (exception) {
4997
6235
  exception.used = true;
@@ -5001,7 +6239,7 @@ function applyConfig(raw, config) {
5001
6239
  }
5002
6240
  const staleLevel = config.rules?.["stale-exception"];
5003
6241
  for (const a of allow) {
5004
- if (staleLevel === "off" || a.used || config.rules?.[a.entry.rule] === "off") continue;
6242
+ if (staleLevel === "off" || a.used || levelOf(a.entry.rule) === "off") continue;
5005
6243
  out.push({
5006
6244
  rule: "stale-exception",
5007
6245
  level: staleLevel ?? "warn",
@@ -5022,6 +6260,7 @@ function formatReport(result) {
5022
6260
  lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
5023
6261
  }
5024
6262
  lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
6263
+ lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis primitives`);
5025
6264
  const info = result.infos ? `, ${result.infos} info` : "";
5026
6265
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
5027
6266
  return lines.join("\n");