@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/vite.js CHANGED
@@ -1,28 +1,699 @@
1
- import * as path14 from 'path';
1
+ import * as path18 from 'path';
2
2
  import { spawnSync } from 'child_process';
3
- import { existsSync, readFileSync, statSync, readdirSync, realpathSync, lstatSync } from 'fs';
3
+ import { existsSync, readFileSync, statSync, realpathSync, readdirSync, lstatSync } from 'fs';
4
4
  import { builtinModules, createRequire } from 'module';
5
5
  import 'crypto';
6
6
  import { FEATURE_PLATFORMS, defineBlock, BlockError } from '@marktiderman/genesis-features/blocks';
7
7
  import { pathToFileURL } from 'url';
8
+ import 'jiti';
8
9
 
9
- // src/vite.ts
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __esm = (fn, res) => function __init() {
13
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
14
+ };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+
20
+ // src/introspect/catalog-text.ts
21
+ function tokenize(tree) {
22
+ const tokens = [];
23
+ let i = 0;
24
+ while (i < tree.length) {
25
+ const ch = tree[i];
26
+ if (ch === " " || ch === "\n" || ch === " ") {
27
+ i++;
28
+ } else if (ch === "{" || ch === "(") {
29
+ tokens.push({ kind: "open", char: ch });
30
+ i++;
31
+ } else if (ch === "}" || ch === ")") {
32
+ tokens.push({ kind: "close", char: ch });
33
+ i++;
34
+ } else {
35
+ let text = "";
36
+ while (i < tree.length) {
37
+ const c = tree[i];
38
+ if (c === "\\" && i + 1 < tree.length) {
39
+ text += tree[i + 1];
40
+ i += 2;
41
+ continue;
42
+ }
43
+ if (c === " " || c === "\n" || c === " " || c === "{" || c === "}" || c === "(" || c === ")") break;
44
+ text += c;
45
+ i++;
46
+ }
47
+ tokens.push({ kind: "atom", text });
48
+ }
49
+ }
50
+ return tokens;
51
+ }
52
+ function viewColumnOrigins(evAction) {
53
+ const tokens = tokenize(evAction);
54
+ let depth = 0;
55
+ let start = -1;
56
+ for (let i = 0; i < tokens.length; i++) {
57
+ const t = tokens[i];
58
+ if (t.kind === "open") depth++;
59
+ else if (t.kind === "close") depth--;
60
+ else if (depth === 2 && t.text === ":targetList") {
61
+ start = i + 1;
62
+ break;
63
+ }
64
+ }
65
+ if (start < 0) return [];
66
+ const origins = [];
67
+ depth = 2;
68
+ let entry = null;
69
+ let lastKey = null;
70
+ for (let i = start; i < tokens.length; i++) {
71
+ const t = tokens[i];
72
+ if (t.kind === "open") {
73
+ depth++;
74
+ if (depth === 4 && t.char === "{") {
75
+ entry = /* @__PURE__ */ new Map();
76
+ lastKey = null;
77
+ }
78
+ continue;
79
+ }
80
+ if (t.kind === "close") {
81
+ if (depth === 4 && entry) {
82
+ const relation = Number(entry.get(":resorigtbl"));
83
+ const column = Number(entry.get(":resorigcol"));
84
+ const position = Number(entry.get(":resno"));
85
+ const name = entry.get(":resname") ?? "";
86
+ if (entry.get(":resjunk") !== "true" && position > 0 && relation > 0 && column > 0) {
87
+ origins.push({ position, name, relation, column });
88
+ }
89
+ entry = null;
90
+ }
91
+ depth--;
92
+ if (depth <= 2) break;
93
+ continue;
94
+ }
95
+ if (depth !== 4 || !entry) continue;
96
+ if (t.text === "TARGETENTRY") continue;
97
+ if (t.text.startsWith(":")) lastKey = t.text;
98
+ else if (lastKey) {
99
+ entry.set(lastKey, t.text);
100
+ lastKey = null;
101
+ }
102
+ }
103
+ return origins;
104
+ }
105
+ function unwrap(expr) {
106
+ let s = expr.trim();
107
+ for (; ; ) {
108
+ if (!s.startsWith("(") || !s.endsWith(")")) return s;
109
+ let depth = 0;
110
+ let inQuote = false;
111
+ let wrapsAll = true;
112
+ for (let i = 0; i < s.length; i++) {
113
+ const c = s[i];
114
+ if (c === "'") inQuote = !inQuote;
115
+ if (inQuote) continue;
116
+ if (c === "(") depth++;
117
+ else if (c === ")") {
118
+ depth--;
119
+ if (depth === 0 && i < s.length - 1) {
120
+ wrapsAll = false;
121
+ break;
122
+ }
123
+ }
124
+ }
125
+ if (!wrapsAll) return s;
126
+ s = s.slice(1, -1).trim();
127
+ }
128
+ }
129
+ function splitTopLevel(expr, separator) {
130
+ const parts = [];
131
+ let depth = 0;
132
+ let inQuote = false;
133
+ let from = 0;
134
+ for (let i = 0; i < expr.length; i++) {
135
+ const c = expr[i];
136
+ if (c === "'") inQuote = !inQuote;
137
+ if (inQuote) continue;
138
+ if (c === "(") depth++;
139
+ else if (c === ")") depth--;
140
+ else if (depth === 0 && expr.startsWith(separator, i)) {
141
+ parts.push(expr.slice(from, i));
142
+ from = i + separator.length;
143
+ i += separator.length - 1;
144
+ }
145
+ }
146
+ parts.push(expr.slice(from));
147
+ return parts;
148
+ }
149
+ function escapeRegExp(s) {
150
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
151
+ }
152
+ function checkEnumValues(definition, column) {
153
+ const outer = /^CHECK \((.*)\)(?: NOT VALID)?$/s.exec(definition.trim());
154
+ if (!outer) return void 0;
155
+ const ident = `(?:${escapeRegExp(column)}|${escapeRegExp(`"${column.replace(/"/g, '""')}"`)})`;
156
+ const ref = String.raw`(?:${ident}|\(${ident}\)${CAST})`;
157
+ let body = unwrap(outer[1]);
158
+ const parts = splitTopLevel(body, " OR ");
159
+ if (parts.length === 2) {
160
+ const isNull = new RegExp(`^${ref} IS NULL$`);
161
+ const nullAt = parts.findIndex((p) => isNull.test(unwrap(p)));
162
+ if (nullAt < 0) return void 0;
163
+ body = unwrap(parts[1 - nullAt]);
164
+ } else if (parts.length !== 1) {
165
+ return void 0;
166
+ }
167
+ const single = new RegExp(`^${ref} = ${LITERAL}$`).exec(body);
168
+ if (single) return [single[1].replace(/''/g, "'")];
169
+ const any = new RegExp(String.raw`^${ref} = ANY \((.*)\)$`).exec(body);
170
+ if (!any) return void 0;
171
+ const list = /^\(?ARRAY\[(.*?)\](?:\)(?:::[a-z][a-z ]*(?:\(\d+\))?\[\]))?$/s.exec(unwrap(any[1]));
172
+ if (!list) return void 0;
173
+ const items = splitTopLevel(list[1], ", ");
174
+ const values = [];
175
+ const literal = new RegExp(`^${LITERAL}$`);
176
+ for (const item of items) {
177
+ const m = literal.exec(item.trim());
178
+ if (!m) return void 0;
179
+ values.push(m[1].replace(/''/g, "'"));
180
+ }
181
+ return values.length ? values : void 0;
182
+ }
183
+ var CAST, LITERAL;
184
+ var init_catalog_text = __esm({
185
+ "src/introspect/catalog-text.ts"() {
186
+ CAST = String.raw`::[a-z][a-z ]*(?:\(\d+(?:,\d+)?\))?`;
187
+ LITERAL = String.raw`'((?:[^']|'')*)'${CAST}`;
188
+ }
189
+ });
190
+
191
+ // src/introspect/comments.ts
192
+ function parse(comment, keys, where2) {
193
+ if (!comment) return {};
194
+ const at = comment.indexOf(MARKER);
195
+ if (at < 0) return { description: comment.trim() || void 0 };
196
+ const description = comment.slice(0, at).trim() || void 0;
197
+ const raw = comment.slice(at + MARKER.length).trim();
198
+ let value;
199
+ try {
200
+ value = JSON.parse(raw);
201
+ } catch {
202
+ throw new CommentSettingsError(`${where2}: the text after ${MARKER} must be one JSON object.`);
203
+ }
204
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
205
+ throw new CommentSettingsError(`${where2}: the text after ${MARKER} must be one JSON object.`);
206
+ }
207
+ const settings = {};
208
+ for (const [key2, v] of Object.entries(value)) {
209
+ const kind = keys[key2];
210
+ if (!kind) {
211
+ throw new CommentSettingsError(`${where2}: unknown ${MARKER} setting "${key2}". Allowed: ${Object.keys(keys).join(", ")}.`);
212
+ }
213
+ if (typeof v !== kind) throw new CommentSettingsError(`${where2}: ${MARKER} "${key2}" must be a ${kind}.`);
214
+ settings[key2] = v;
215
+ }
216
+ return {
217
+ ...description ? { description } : {},
218
+ ...Object.keys(settings).length ? { settings } : {}
219
+ };
220
+ }
221
+ function parseTableComment(comment, table) {
222
+ return parse(comment, TABLE_KEYS, table);
223
+ }
224
+ function parseColumnComment(comment, column) {
225
+ return parse(comment, FIELD_KEYS, column);
226
+ }
227
+ var MARKER, TABLE_KEYS, FIELD_KEYS, CommentSettingsError;
228
+ var init_comments = __esm({
229
+ "src/introspect/comments.ts"() {
230
+ MARKER = "@genesis";
231
+ TABLE_KEYS = { label: "string", labelField: "string", description: "string", noun: "string", nounPlural: "string" };
232
+ FIELD_KEYS = { label: "string", description: "string", widget: "string", readonly: "boolean", sensitive: "boolean" };
233
+ CommentSettingsError = class extends Error {
234
+ };
235
+ }
236
+ });
237
+
238
+ // src/introspect/model.ts
239
+ function storageTypeOf(dbType) {
240
+ const t = dbType.toLowerCase().replace(/\[\]$/, "");
241
+ if (/^(smallint|integer|bigint|int2|int4|int8|real|double precision|float4|float8|numeric|decimal|money)\b/.test(t)) {
242
+ return "number";
243
+ }
244
+ if (t === "boolean" || t === "bool") return "boolean";
245
+ if (/^(date|timestamp|timestamptz|time|timetz|interval)\b/.test(t)) return "datetime";
246
+ if (t === "json" || t === "jsonb") return "json";
247
+ return "string";
248
+ }
249
+ function qualifiedName(schema, table) {
250
+ const part = (p) => /[."]/.test(p) ? `"${p.replace(/"/g, '""')}"` : p;
251
+ return `${part(schema)}.${part(table)}`;
252
+ }
253
+ var init_model = __esm({
254
+ "src/introspect/model.ts"() {
255
+ }
256
+ });
257
+
258
+ // src/introspect/postgres.ts
259
+ function where(sql, scope) {
260
+ return "schemas" in scope ? sql`n.nspname = any(${scope.schemas})` : sql`c.oid = any(${scope.oids}::oid[])`;
261
+ }
262
+ async function readRelations(sql, scope, into) {
263
+ const columns = await sql`
264
+ select c.oid::text as oid, c.relkind::text as relkind, n.nspname as schema, c.relname as table,
265
+ obj_description(c.oid, 'pg_class') as table_comment,
266
+ a.attnum::int as attnum,
267
+ a.attname as column,
268
+ format_type(a.atttypid, a.atttypmod) as db_type,
269
+ t.typcategory = 'A' as is_array,
270
+ a.attnotnull as not_null,
271
+ (a.atthasdef or a.attidentity <> '') as has_default,
272
+ (a.attgenerated <> '' or a.attidentity <> '') as generated,
273
+ (select array_agg(e.enumlabel::text order by e.enumsortorder)
274
+ from pg_enum e
275
+ where e.enumtypid = case when t.typcategory = 'A' then t.typelem else t.oid end) as enum_values,
276
+ col_description(c.oid, a.attnum) as column_comment
277
+ from pg_class c
278
+ join pg_namespace n on n.oid = c.relnamespace
279
+ join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
280
+ join pg_type t on t.oid = a.atttypid
281
+ where c.relkind in ('r', 'p', 'v', 'm', 'f')
282
+ and ${where(sql, scope)}
283
+ order by n.nspname, c.relname, a.attnum`;
284
+ const keys = await sql`
285
+ select c.oid::text as oid, array_agg(k.attnum::int order by k.ord) as columns
286
+ from pg_constraint con
287
+ join pg_class c on c.oid = con.conrelid
288
+ join pg_namespace n on n.oid = c.relnamespace
289
+ cross join lateral unnest(con.conkey) with ordinality as k(attnum, ord)
290
+ where con.contype = 'p' and ${where(sql, scope)}
291
+ group by c.oid`;
292
+ const links = await sql`
293
+ select c.oid::text as oid, con.conkey[1]::int as attnum,
294
+ rn.nspname as ref_schema, rc.relname as ref_table, ra.attname as ref_column
295
+ from pg_constraint con
296
+ join pg_class c on c.oid = con.conrelid
297
+ join pg_namespace n on n.oid = c.relnamespace
298
+ join pg_class rc on rc.oid = con.confrelid
299
+ join pg_namespace rn on rn.oid = rc.relnamespace
300
+ join pg_attribute ra on ra.attrelid = rc.oid and ra.attnum = con.confkey[1]
301
+ where con.contype = 'f' and array_length(con.conkey, 1) = 1
302
+ and ${where(sql, scope)}`;
303
+ const checks = await sql`
304
+ select c.oid::text as oid, con.conkey[1]::int as attnum, a.attname as column,
305
+ pg_get_constraintdef(con.oid) as definition
306
+ from pg_constraint con
307
+ join pg_class c on c.oid = con.conrelid
308
+ join pg_namespace n on n.oid = c.relnamespace
309
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = con.conkey[1]
310
+ where con.contype = 'c' and array_length(con.conkey, 1) = 1
311
+ and ${where(sql, scope)}
312
+ order by con.conname`;
313
+ const views = await sql`
314
+ select c.oid::text as oid, r.ev_action::text as ev_action
315
+ from pg_class c
316
+ join pg_namespace n on n.oid = c.relnamespace
317
+ join pg_rewrite r on r.ev_class = c.oid and r.rulename = '_RETURN'
318
+ where c.relkind = 'v'
319
+ and (pg_relation_is_updatable(c.oid, false) & 20) = 20
320
+ and not exists (select 1 from pg_rewrite o where o.ev_class = c.oid and o.rulename <> '_RETURN')
321
+ and ${where(sql, scope)}`;
322
+ const added = [];
323
+ for (const row of columns) {
324
+ let relation = into.get(row.oid);
325
+ if (!relation) {
326
+ const name = qualifiedName(row.schema, row.table);
327
+ const comment2 = parseTableComment(row.table_comment, name);
328
+ relation = {
329
+ oid: row.oid,
330
+ table: {
331
+ name,
332
+ schema: row.schema,
333
+ table: row.table,
334
+ key: [],
335
+ columns: [],
336
+ ...comment2.description ? { description: comment2.description } : {},
337
+ ...comment2.settings ? { settings: comment2.settings } : {}
338
+ },
339
+ columns: /* @__PURE__ */ new Map(),
340
+ key: []
341
+ };
342
+ into.set(row.oid, relation);
343
+ added.push(row.oid);
344
+ }
345
+ const comment = parseColumnComment(row.column_comment, `${relation.table.name}.${row.column}`);
346
+ const column = {
347
+ name: row.column,
348
+ dbType: row.db_type,
349
+ type: storageTypeOf(row.db_type),
350
+ array: row.is_array,
351
+ nullable: !row.not_null,
352
+ // A view's columns always read as nullable: unknown until traced to a table.
353
+ ...row.relkind === "v" || row.relkind === "m" ? { nullableUnknown: true } : {},
354
+ hasDefault: row.has_default,
355
+ generated: row.generated,
356
+ ...row.enum_values ? { enumValues: row.enum_values } : {},
357
+ ...comment.description ? { description: comment.description } : {},
358
+ ...comment.settings ? { settings: comment.settings } : {}
359
+ };
360
+ relation.table.columns.push(column);
361
+ relation.columns.set(row.attnum, column);
362
+ }
363
+ for (const k of keys) {
364
+ const relation = into.get(k.oid);
365
+ if (relation) relation.key = k.columns;
366
+ }
367
+ for (const l of links) {
368
+ const column = into.get(l.oid)?.columns.get(l.attnum);
369
+ if (column) column.references = { resource: qualifiedName(l.ref_schema, l.ref_table), field: l.ref_column };
370
+ }
371
+ const listed = /* @__PURE__ */ new Map();
372
+ for (const check of checks) {
373
+ const column = into.get(check.oid)?.columns.get(check.attnum);
374
+ if (!column || column.array) continue;
375
+ const values = checkEnumValues(check.definition, check.column);
376
+ if (!values) continue;
377
+ const before = listed.get(column);
378
+ listed.set(column, before ? before.filter((v) => values.includes(v)) : values);
379
+ }
380
+ for (const [column, values] of listed) {
381
+ const allowed = column.enumValues ? column.enumValues.filter((v) => values.includes(v)) : values;
382
+ if (allowed.length > 0) column.enumValues = allowed;
383
+ }
384
+ for (const view of views) {
385
+ const relation = into.get(view.oid);
386
+ if (!relation) continue;
387
+ relation.origins = /* @__PURE__ */ new Map();
388
+ for (const origin of viewColumnOrigins(view.ev_action)) {
389
+ if (relation.columns.has(origin.position)) {
390
+ relation.origins.set(origin.position, { relation: String(origin.relation), column: origin.column });
391
+ }
392
+ }
393
+ }
394
+ return added;
395
+ }
396
+ function inherit(own, source) {
397
+ const settings = source.settings || own.settings ? { ...source.settings, ...own.settings } : void 0;
398
+ const description = own.description ?? source.description;
399
+ const both = own.enumValues && source.enumValues ? own.enumValues.filter((v) => source.enumValues.includes(v)) : void 0;
400
+ const enumValues = both?.length ? both : own.enumValues ?? source.enumValues;
401
+ return {
402
+ name: own.name,
403
+ dbType: own.dbType,
404
+ type: own.type,
405
+ array: own.array,
406
+ nullable: source.nullable,
407
+ ...source.nullableUnknown ? { nullableUnknown: true } : {},
408
+ hasDefault: own.hasDefault || source.hasDefault,
409
+ generated: source.generated,
410
+ ...enumValues ? { enumValues } : {},
411
+ ...source.references ? { references: source.references } : {},
412
+ ...description ? { description } : {},
413
+ ...settings ? { settings } : {}
414
+ };
415
+ }
416
+ function resolveViews(relations) {
417
+ const done = /* @__PURE__ */ new Set();
418
+ const resolve15 = (relation, depth) => {
419
+ if (done.has(relation.oid) || !relation.origins || depth > MAX_VIEW_DEPTH) return;
420
+ done.add(relation.oid);
421
+ const sources = new Set([...relation.origins.values()].map((o) => o.relation));
422
+ if (sources.size !== 1) return;
423
+ const source = relations.get([...sources][0]);
424
+ if (!source) return;
425
+ resolve15(source, depth + 1);
426
+ const viewAttnumOf = /* @__PURE__ */ new Map();
427
+ for (const [attnum, origin] of relation.origins) {
428
+ const own = relation.columns.get(attnum);
429
+ const from = source.columns.get(origin.column);
430
+ if (!own || !from) continue;
431
+ const merged = inherit(own, from);
432
+ relation.columns.set(attnum, merged);
433
+ relation.table.columns[relation.table.columns.indexOf(own)] = merged;
434
+ if (!viewAttnumOf.has(origin.column)) viewAttnumOf.set(origin.column, attnum);
435
+ }
436
+ if (relation.key.length === 0 && source.key.length > 0 && source.key.every((k) => viewAttnumOf.has(k))) {
437
+ relation.key = source.key.map((k) => viewAttnumOf.get(k));
438
+ }
439
+ const theirs = source.table.settings;
440
+ const viewColumns = new Set(relation.table.columns.map((c) => c.name));
441
+ const inherited = {
442
+ ...theirs?.noun ? { noun: theirs.noun } : {},
443
+ ...theirs?.nounPlural ? { nounPlural: theirs.nounPlural } : {},
444
+ ...theirs?.labelField && viewColumns.has(theirs.labelField) ? { labelField: theirs.labelField } : {}
445
+ };
446
+ if (Object.keys(inherited).length) relation.table.settings = { ...inherited, ...relation.table.settings };
447
+ };
448
+ for (const relation of relations.values()) resolve15(relation, 0);
449
+ }
450
+ async function introspectPostgres(sql, schemas) {
451
+ const relations = /* @__PURE__ */ new Map();
452
+ const wanted = await readRelations(sql, { schemas: [...schemas] }, relations);
453
+ for (let depth = 0; depth < MAX_VIEW_DEPTH; depth++) {
454
+ const missing = /* @__PURE__ */ new Set();
455
+ for (const relation of relations.values()) {
456
+ for (const origin of relation.origins?.values() ?? []) {
457
+ if (!relations.has(origin.relation)) missing.add(origin.relation);
458
+ }
459
+ }
460
+ if (missing.size === 0) break;
461
+ const added = await readRelations(sql, { oids: [...missing].sort() }, relations);
462
+ if (added.length === 0) break;
463
+ }
464
+ resolveViews(relations);
465
+ return wanted.map((oid) => {
466
+ const relation = relations.get(oid);
467
+ return { ...relation.table, key: relation.key.map((attnum) => relation.columns.get(attnum).name) };
468
+ });
469
+ }
470
+ var MAX_VIEW_DEPTH;
471
+ var init_postgres = __esm({
472
+ "src/introspect/postgres.ts"() {
473
+ init_catalog_text();
474
+ init_comments();
475
+ init_model();
476
+ MAX_VIEW_DEPTH = 8;
477
+ }
478
+ });
479
+
480
+ // src/introspect/openapi.ts
481
+ function clean(description) {
482
+ if (!description) return void 0;
483
+ return description.replace(NOTES, "").trim() || void 0;
484
+ }
485
+ function introspectOpenApi(doc, schema = "public") {
486
+ const definitions = doc.definitions ?? doc.components?.schemas;
487
+ if (!definitions) throw new Error("This OpenAPI document has no definitions. Is it a PostgREST (Supabase /rest/v1/) spec?");
488
+ return Object.keys(definitions).sort().map((tableName) => {
489
+ const def = definitions[tableName];
490
+ const name = qualifiedName(schema, tableName);
491
+ const required = new Set(def.required ?? []);
492
+ const key2 = [];
493
+ const columns = Object.entries(def.properties ?? {}).map(([column, prop]) => {
494
+ if (PK.test(prop.description ?? "")) key2.push(column);
495
+ const fk = FK.exec(prop.description ?? "");
496
+ const isArray = prop.type === "array";
497
+ const format = (isArray ? prop.items?.format : prop.format) ?? prop.type ?? "text";
498
+ const dbType = isArray ? `${format}[]` : format;
499
+ const comment2 = parseColumnComment(clean(prop.description), `${name}.${column}`);
500
+ return {
501
+ name: column,
502
+ dbType,
503
+ type: storageTypeOf(format),
504
+ array: isArray,
505
+ // PostgREST (v9 on) lists every NOT NULL column as required, with or
506
+ // without a default (`filter (not . colNullable)` in its OpenAPI.hs).
507
+ nullable: !required.has(column),
508
+ hasDefault: prop.default !== void 0,
509
+ generated: false,
510
+ ...prop.enum ? { enumValues: prop.enum.map(String) } : {},
511
+ ...fk ? { references: { resource: qualifiedName(schema, fk[1]), field: fk[2] } } : {},
512
+ ...comment2.description ? { description: comment2.description } : {},
513
+ ...comment2.settings ? { settings: comment2.settings } : {}
514
+ };
515
+ });
516
+ const comment = parseTableComment(def.description, name);
517
+ return {
518
+ name,
519
+ schema,
520
+ table: tableName,
521
+ key: key2,
522
+ columns,
523
+ ...comment.description ? { description: comment.description } : {},
524
+ ...comment.settings ? { settings: comment.settings } : {}
525
+ };
526
+ });
527
+ }
528
+ var PK, FK, NOTES;
529
+ var init_openapi = __esm({
530
+ "src/introspect/openapi.ts"() {
531
+ init_comments();
532
+ init_model();
533
+ PK = /<pk\/>/;
534
+ FK = /<fk table='([^']+)' column='([^']+)'\/>/;
535
+ NOTES = /\s*Note:\s*This is a (?:Primary|Foreign) Key[^<]*<(?:pk|fk)[^>]*\/>/g;
536
+ }
537
+ });
538
+
539
+ // src/introspect/emit.ts
540
+ function quote(value) {
541
+ return JSON.stringify(value);
542
+ }
543
+ function propKey(name) {
544
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : quote(name);
545
+ }
546
+ function typeName(table) {
547
+ const pascal = `${table.schema}_${table.table}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join("");
548
+ return `${/^[0-9]/.test(pascal) ? "T" : ""}${pascal}Row`;
549
+ }
550
+ function constName(table) {
551
+ const row = typeName(table).replace(/Row$/, "");
552
+ return row[0].toLowerCase() + row.slice(1);
553
+ }
554
+ function tsType(column) {
555
+ const base = column.enumValues?.length ? column.enumValues.map(quote).join(" | ") : TS_TYPE[column.type];
556
+ const element = column.array ? base.includes("|") ? `(${base})[]` : `${base}[]` : base;
557
+ return column.nullable ? `${element} | null` : element;
558
+ }
559
+ function field(column, indent) {
560
+ const parts = [`name: ${quote(column.name)}`, `type: ${quote(column.type)}`, `dbType: ${quote(column.dbType)}`];
561
+ if (column.array) parts.push("array: true");
562
+ if (!column.nullableUnknown) parts.push(column.nullable ? "nullable: true" : "nullable: false");
563
+ if (column.nullable || column.hasDefault || column.generated) parts.push("optional: true");
564
+ if (column.hasDefault) parts.push("hasDefault: true");
565
+ if (column.generated) parts.push("generated: true");
566
+ if (column.enumValues) parts.push(`enumValues: [${column.enumValues.map(quote).join(", ")}]`);
567
+ if (column.references) {
568
+ parts.push(`references: { resource: ${quote(column.references.resource)}, field: ${quote(column.references.field)} }`);
569
+ }
570
+ const label = column.settings?.label;
571
+ const description = column.settings?.description ?? column.description;
572
+ if (label) parts.push(`label: ${quote(label)}`);
573
+ if (description) parts.push(`description: ${quote(description)}`);
574
+ if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
575
+ if (column.settings?.readonly) parts.push("readOnly: true");
576
+ if (column.settings?.sensitive) parts.push("sensitive: true");
577
+ return `${indent}{ ${parts.join(", ")} },`;
578
+ }
579
+ function emitContracts(tables, options) {
580
+ const sorted = [...tables].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
581
+ const seen = /* @__PURE__ */ new Map();
582
+ for (const table of sorted) {
583
+ const id = typeName(table);
584
+ const other = seen.get(id);
585
+ if (other) throw new EmitError(`${other} and ${table.name} would both be named ${id}; rename one, or introspect them separately.`);
586
+ seen.set(id, table.name);
587
+ const labelField = table.settings?.labelField;
588
+ if (labelField && !table.columns.some((c) => c.name === labelField)) {
589
+ throw new EmitError(`${table.name}: @genesis labelField "${labelField}" isn't one of its columns.`);
590
+ }
591
+ }
592
+ const out = [
593
+ "// Generated by `genesis introspect` \u2014 do not edit by hand.",
594
+ `// Source: ${options.source}`,
595
+ "//",
596
+ "// Re-run `genesis introspect` after a schema change and review the diff.",
597
+ "// Labels, widgets and descriptions come from `@genesis {...}` settings in",
598
+ "// table and column comments. Pass `contracts` to createStudioHandler: it",
599
+ "// wins over discovery for presentation, while types, keys and every",
600
+ "// permission still come from the live database. Each contract goes through",
601
+ "// defineResource, so a bad @genesis setting fails to compile and views read the",
602
+ "// row type with RowOf<typeof contract>.",
603
+ "",
604
+ 'import { defineResource } from "@marktiderman/genesis-core";',
605
+ ""
606
+ ];
607
+ for (const table of sorted) {
608
+ const row = typeName(table);
609
+ out.push(`/** \`${table.name}\`. */`);
610
+ out.push(`export const ${constName(table)} = defineResource<${row}>()({`);
611
+ out.push(` name: ${quote(table.name)},`);
612
+ out.push(` key: ${table.key.length === 1 ? quote(table.key[0]) : `[${table.key.map(quote).join(", ")}]`},`);
613
+ if (table.settings?.label) out.push(` label: ${quote(table.settings.label)},`);
614
+ if (table.settings?.labelField) out.push(` labelField: ${quote(table.settings.labelField)},`);
615
+ if (table.settings?.noun) out.push(` noun: ${quote(table.settings.noun)},`);
616
+ if (table.settings?.nounPlural) out.push(` nounPlural: ${quote(table.settings.nounPlural)},`);
617
+ const description = table.settings?.description ?? table.description;
618
+ if (description) out.push(` description: ${quote(description)},`);
619
+ out.push(" fields: [");
620
+ for (const column of table.columns) out.push(field(column, " "));
621
+ out.push(" ],");
622
+ out.push("});", "");
623
+ }
624
+ out.push("export const contracts = {");
625
+ for (const table of sorted) out.push(` ${quote(table.name)}: ${constName(table)},`);
626
+ out.push("} as const;", "");
627
+ out.push("/** Every resource in this contract, `schema.table`. */");
628
+ out.push("export type GenesisResource = keyof typeof contracts;", "");
629
+ for (const table of sorted) {
630
+ out.push(`/** A row of \`${table.name}\`, as the studio handler returns it. */`);
631
+ out.push(`export type ${typeName(table)} = {`);
632
+ for (const column of table.columns) out.push(` ${propKey(column.name)}: ${tsType(column)};`);
633
+ out.push("};", "");
634
+ out.push(`/** The field names of \`${table.name}\`. */`);
635
+ out.push(`export type ${typeName(table).replace(/Row$/, "Field")} = keyof ${typeName(table)};`, "");
636
+ }
637
+ out.push("/** Row types by resource. */");
638
+ out.push("export interface GenesisRows {");
639
+ for (const table of sorted) out.push(` ${quote(table.name)}: ${typeName(table)};`);
640
+ out.push("}", "");
641
+ return out.join("\n");
642
+ }
643
+ var TS_TYPE, EmitError;
644
+ var init_emit = __esm({
645
+ "src/introspect/emit.ts"() {
646
+ TS_TYPE = {
647
+ string: "string",
648
+ number: "number",
649
+ boolean: "boolean",
650
+ // The studio handler sends dates and timestamps as Postgres text, exactly.
651
+ datetime: "string",
652
+ json: "unknown"
653
+ };
654
+ EmitError = class extends Error {
655
+ name = "EmitError";
656
+ };
657
+ }
658
+ });
659
+
660
+ // src/introspect/index.ts
661
+ var introspect_exports = {};
662
+ __export(introspect_exports, {
663
+ CommentSettingsError: () => CommentSettingsError,
664
+ EmitError: () => EmitError,
665
+ emitContracts: () => emitContracts,
666
+ introspectOpenApi: () => introspectOpenApi,
667
+ introspectPostgres: () => introspectPostgres,
668
+ parseColumnComment: () => parseColumnComment,
669
+ parseTableComment: () => parseTableComment,
670
+ qualifiedName: () => qualifiedName
671
+ });
672
+ var init_introspect = __esm({
673
+ "src/introspect/index.ts"() {
674
+ init_postgres();
675
+ init_openapi();
676
+ init_emit();
677
+ init_comments();
678
+ init_model();
679
+ }
680
+ });
10
681
  var BUILD_GUARD_ENV = "GENESIS_DOCTOR_BUILDING";
11
682
  function buildCommands(root, config) {
12
683
  if (config.build) return config.build;
13
- const pkgFile = path14.join(root, "package.json");
684
+ const pkgFile = path18.join(root, "package.json");
14
685
  const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
15
686
  const pm = packageManager(root);
16
687
  return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
17
688
  }
18
689
  function packageManager(root) {
19
- let dir = path14.resolve(root);
690
+ let dir = path18.resolve(root);
20
691
  for (; ; ) {
21
- if (existsSync(path14.join(dir, "pnpm-lock.yaml"))) return "pnpm";
22
- if (existsSync(path14.join(dir, "bun.lock")) || existsSync(path14.join(dir, "bun.lockb"))) return "bun";
23
- if (existsSync(path14.join(dir, "yarn.lock"))) return "yarn";
24
- if (existsSync(path14.join(dir, "package-lock.json"))) return "npm";
25
- const parent = path14.dirname(dir);
692
+ if (existsSync(path18.join(dir, "pnpm-lock.yaml"))) return "pnpm";
693
+ if (existsSync(path18.join(dir, "bun.lock")) || existsSync(path18.join(dir, "bun.lockb"))) return "bun";
694
+ if (existsSync(path18.join(dir, "yarn.lock"))) return "yarn";
695
+ if (existsSync(path18.join(dir, "package-lock.json"))) return "npm";
696
+ const parent = path18.dirname(dir);
26
697
  if (parent === dir) return "npm";
27
698
  dir = parent;
28
699
  }
@@ -118,44 +789,61 @@ var KNOWN = /* @__PURE__ */ new Set([
118
789
  "supabase",
119
790
  "packages",
120
791
  "routesDir",
792
+ "packageRules",
793
+ "ratchet",
794
+ "contracts",
121
795
  "$schema",
122
796
  "$comment"
123
797
  ]);
124
798
  var LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
125
- var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
799
+ var META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
800
+ var PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
801
+ var PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
802
+ var CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
126
803
  var PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
127
804
  var PACK_KEYS = {
128
805
  native: { routerRoot: "path" },
129
806
  supabase: { migrations: "path", base: "string", exposedSchemas: "list", since: "string" },
130
807
  packages: { base: "string" }
131
808
  };
132
- function appPath(v, where, fail) {
133
- if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
134
- if (path14.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
135
- const norm = path14.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
136
- if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where} must be a folder inside the app ("${v}")`);
809
+ function appPath(v, where2, fail) {
810
+ if (typeof v !== "string" || !v.trim()) return fail(`${where2} must be a non-empty path`);
811
+ if (path18.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
812
+ const norm = path18.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
813
+ if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where2} must be a folder inside the app ("${v}")`);
137
814
  return norm;
138
815
  }
139
816
  function loadConfig(root, configPath) {
140
817
  if (configPath) {
141
- const file = path14.resolve(root, configPath);
818
+ const file = path18.resolve(root, configPath);
142
819
  if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
143
820
  const json = readJson(file);
144
- const block = path14.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
145
- return { config: validateConfig(block ?? {}, file), file, dir: path14.dirname(file) };
821
+ const block = path18.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
822
+ return { config: validateConfig(block ?? {}, file), file, dir: path18.dirname(file) };
146
823
  }
147
- const own = path14.join(root, "genesis.config.json");
824
+ const own = path18.join(root, "genesis.config.json");
148
825
  if (existsSync(own)) {
149
826
  const block = readGenesisConfig(root)?.raw.doctor;
150
827
  return { config: validateConfig(block ?? {}, own), file: own, dir: root };
151
828
  }
152
- const pkg = path14.join(root, "package.json");
829
+ const pkg = path18.join(root, "package.json");
153
830
  if (existsSync(pkg)) {
154
831
  const block = readJson(pkg)?.genesis?.doctor;
155
- if (block !== void 0) return { config: validateConfig(block, pkg), file: pkg, dir: root };
832
+ if (block !== void 0 && !isPackageDeclaration(block)) return { config: validateConfig(block, pkg), file: pkg, dir: root };
156
833
  }
157
834
  return { config: {}, file: null, dir: root };
158
835
  }
836
+ function doctorBlock(json, file, explicit) {
837
+ const j = json;
838
+ if (path18.basename(file) === "package.json") return j?.genesis?.doctor;
839
+ return explicit ? j?.doctor ?? j : j?.doctor;
840
+ }
841
+ function isPackageDeclaration(block) {
842
+ if (typeof block === "string") return true;
843
+ if (!isObject(block)) return false;
844
+ const keys = Object.keys(block).filter((k) => k !== "$comment");
845
+ return keys.some((k) => ["prefer", "primitives", "plugin", "enforce"].includes(k)) && !keys.some((k) => KNOWN.has(k));
846
+ }
159
847
  function readJson(file) {
160
848
  try {
161
849
  return JSON.parse(readFileSync(file, "utf8"));
@@ -164,7 +852,7 @@ function readJson(file) {
164
852
  }
165
853
  }
166
854
  function readGenesisConfig(root) {
167
- const file = path14.join(root, "genesis.config.json");
855
+ const file = path18.join(root, "genesis.config.json");
168
856
  if (!existsSync(file)) return null;
169
857
  const raw = readJson(file);
170
858
  if (!isObject(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
@@ -194,18 +882,18 @@ function validatePrivacy(raw, source = "config") {
194
882
  if (c.collects !== void 0) {
195
883
  if (!Array.isArray(c.collects)) fail(`privacy.collects must be a list`);
196
884
  out.collects = c.collects.map((entry, i) => {
197
- const where = `privacy.collects[${i}]`;
198
- if (!isObject(entry)) return fail(`${where} must be an object`);
199
- for (const key2 of Object.keys(entry)) if (!DATA_USE_KEYS.has(key2)) fail(`${where}: unknown setting "${key2}"`);
885
+ const where2 = `privacy.collects[${i}]`;
886
+ if (!isObject(entry)) return fail(`${where2} must be an object`);
887
+ for (const key2 of Object.keys(entry)) if (!DATA_USE_KEYS.has(key2)) fail(`${where2}: unknown setting "${key2}"`);
200
888
  if (typeof entry.type !== "string" || !privacyDataType(entry.type)) {
201
- fail(`${where}.type "${String(entry.type)}" is not one of ${Object.keys(PRIVACY_DATA_TYPES).join(", ")}`);
889
+ fail(`${where2}.type "${String(entry.type)}" is not one of ${Object.keys(PRIVACY_DATA_TYPES).join(", ")}`);
202
890
  }
203
- if (!isStringList(entry.purposes) || entry.purposes.length === 0) fail(`${where}.purposes must be a non-empty list`);
891
+ if (!isStringList(entry.purposes) || entry.purposes.length === 0) fail(`${where2}.purposes must be a non-empty list`);
204
892
  for (const p of entry.purposes) {
205
- if (!(p in PRIVACY_PURPOSES)) fail(`${where}.purposes: "${p}" is not one of ${Object.keys(PRIVACY_PURPOSES).join(", ")}`);
893
+ if (!(p in PRIVACY_PURPOSES)) fail(`${where2}.purposes: "${p}" is not one of ${Object.keys(PRIVACY_PURPOSES).join(", ")}`);
206
894
  }
207
- if (typeof entry.linked !== "boolean") fail(`${where}.linked must be true or false`);
208
- if (typeof entry.tracking !== "boolean") fail(`${where}.tracking must be true or false`);
895
+ if (typeof entry.linked !== "boolean") fail(`${where2}.linked must be true or false`);
896
+ if (typeof entry.tracking !== "boolean") fail(`${where2}.tracking must be true or false`);
209
897
  return { type: entry.type, purposes: [...new Set(entry.purposes)], linked: entry.linked, tracking: entry.tracking };
210
898
  });
211
899
  }
@@ -274,6 +962,7 @@ function validateConfig(raw, source = "config") {
274
962
  if (!isObject(c.rules)) fail(`"rules" must be an object of rule \u2192 level`);
275
963
  for (const [rule, level] of Object.entries(c.rules)) {
276
964
  if (!LEVELS.has(level)) fail(`rules.${rule} must be "error", "warn", "info" or "off"`);
965
+ if (META_RULES.has(rule)) fail(`rules can't set ${rule}: it guards the config itself`);
277
966
  }
278
967
  }
279
968
  if (c.allow !== void 0) {
@@ -283,6 +972,7 @@ function validateConfig(raw, source = "config") {
283
972
  const entry = e;
284
973
  if (typeof entry.rule !== "string" || !entry.rule) fail(`allow[${i}] needs a "rule"`);
285
974
  if (typeof entry.reason !== "string" || !entry.reason.trim()) fail(`allow[${i}] (${entry.rule}) needs a "reason"`);
975
+ if (META_RULES.has(entry.rule)) fail(`allow[${i}] can't allow ${entry.rule}: it guards the allow list itself`);
286
976
  for (const k of ["file", "match"]) {
287
977
  if (entry[k] !== void 0 && typeof entry[k] !== "string") fail(`allow[${i}].${k} must be a string`);
288
978
  }
@@ -298,13 +988,42 @@ function validateConfig(raw, source = "config") {
298
988
  for (const k of ["files", "exclude"]) {
299
989
  if (rule[k] !== void 0 && !isStringList(rule[k])) fail(`patterns[${i}].${k} must be a list of globs`);
300
990
  }
991
+ if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") fail(`patterns[${i}].newOnly must be true or false`);
301
992
  });
302
993
  }
994
+ if (c.packageRules !== void 0) {
995
+ if (!isObject(c.packageRules)) fail(`"packageRules" must be an object of package rule id \u2192 { level?, files?, exclude?, reason }`);
996
+ for (const [id, v] of Object.entries(c.packageRules)) {
997
+ const where2 = `packageRules["${id}"]`;
998
+ if (!id.includes("/")) fail(`${where2}: package rule ids are namespaced by package, e.g. "ui/lists-use-resource-view"`);
999
+ if (!isObject(v)) fail(`${where2} must be an object`);
1000
+ const setting = v;
1001
+ for (const k of Object.keys(setting)) if (!PACKAGE_RULE_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: level, files, exclude, reason)`);
1002
+ if (typeof setting.reason !== "string" || !setting.reason.trim()) fail(`${where2} needs a "reason": a package rule is never changed silently`);
1003
+ if (setting.level !== void 0 && !LEVELS.has(setting.level)) fail(`${where2}.level must be "error", "warn", "info" or "off"`);
1004
+ for (const k of ["files", "exclude"]) if (setting[k] !== void 0 && !isStringList(setting[k])) fail(`${where2}.${k} must be a list of globs`);
1005
+ }
1006
+ }
1007
+ if (c.ratchet !== void 0 && typeof c.ratchet !== "boolean" && !isStringList(c.ratchet)) fail(`"ratchet" must be true, false or a list of rule ids`);
303
1008
  if (c.packs !== void 0) {
304
1009
  if (!isStringList(c.packs)) fail(`"packs" must be a list, e.g. ["native", "supabase"]`);
305
1010
  for (const p of c.packs) if (!PACKS.has(p)) fail(`packs: unknown pack "${p}" (known: ${[...PACKS].join(", ")})`);
306
1011
  if (new Set(c.packs).size !== c.packs.length) fail(`packs: lists a pack twice`);
307
1012
  }
1013
+ if (c.contracts !== void 0) {
1014
+ if (!isObject(c.contracts)) fail(`"contracts" must be an object: { out?, schemas?, databaseEnv? }`);
1015
+ const contracts = c.contracts;
1016
+ for (const k of Object.keys(contracts)) if (!CONTRACT_KEYS.has(k)) fail(`contracts: unknown setting "${k}" (known: out, schemas, databaseEnv)`);
1017
+ if (!(c.packs ?? []).includes("supabase")) fail(`"contracts" is set but the supabase pack is not in "packs"`);
1018
+ if (contracts.out !== void 0) {
1019
+ if (typeof contracts.out !== "string" || !contracts.out.trim()) fail(`contracts.out must be a file path`);
1020
+ if (path18.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1021
+ }
1022
+ if (contracts.schemas !== void 0 && !isStringList(contracts.schemas)) fail(`contracts.schemas must be a list of schema names`);
1023
+ if (contracts.databaseEnv !== void 0 && (typeof contracts.databaseEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(contracts.databaseEnv))) {
1024
+ fail(`contracts.databaseEnv must be an environment variable name`);
1025
+ }
1026
+ }
308
1027
  for (const [pack, keys] of Object.entries(PACK_KEYS)) {
309
1028
  const block = c[pack];
310
1029
  if (block === void 0) continue;
@@ -327,11 +1046,11 @@ function validateConfig(raw, source = "config") {
327
1046
  }
328
1047
  return c;
329
1048
  }
330
- function checkRegExp(source, where, fail) {
1049
+ function checkRegExp(source, where2, fail) {
331
1050
  try {
332
1051
  new RegExp(source);
333
1052
  } catch (err) {
334
- fail(`${where} is not a valid regular expression: ${err.message}`);
1053
+ fail(`${where2} is not a valid regular expression: ${err.message}`);
335
1054
  }
336
1055
  }
337
1056
  function isObject(v) {
@@ -366,7 +1085,7 @@ function globToRegExp(glob) {
366
1085
  }
367
1086
  function globMatcher(globs) {
368
1087
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
369
- return (path23) => res.some((re) => re.test(path23));
1088
+ return (path29) => res.some((re) => re.test(path29));
370
1089
  }
371
1090
  var DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
372
1091
  var NATIVE_UI_PACKAGE = "@marktiderman/genesis-ui-native";
@@ -406,11 +1125,11 @@ var TAILWIND_PALETTE = [
406
1125
  "olive"
407
1126
  ];
408
1127
  function findPackageDir(from, name) {
409
- let dir = path14.resolve(from);
1128
+ let dir = path18.resolve(from);
410
1129
  for (; ; ) {
411
- const candidate = path14.join(dir, "node_modules", name);
412
- if (existsSync(path14.join(candidate, "package.json"))) return candidate;
413
- const parent = path14.dirname(dir);
1130
+ const candidate = path18.join(dir, "node_modules", name);
1131
+ if (existsSync(path18.join(candidate, "package.json"))) return candidate;
1132
+ const parent = path18.dirname(dir);
414
1133
  if (parent === dir) return null;
415
1134
  dir = parent;
416
1135
  }
@@ -462,7 +1181,7 @@ function loadCompanions(root, config, uiPackage) {
462
1181
  function readPackageExports(root, uiPackage) {
463
1182
  const uiDir = findPackageDir(root, uiPackage);
464
1183
  if (!uiDir) return null;
465
- const uiPkg = JSON.parse(readFileSync(path14.join(uiDir, "package.json"), "utf8"));
1184
+ const uiPkg = JSON.parse(readFileSync(path18.join(uiDir, "package.json"), "utf8"));
466
1185
  const typeEntries = /* @__PURE__ */ new Set();
467
1186
  const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
468
1187
  if (typeof mainTypes === "string") typeEntries.add(mainTypes);
@@ -474,7 +1193,7 @@ function readPackageExports(root, uiPackage) {
474
1193
  const reexportedPackages = /* @__PURE__ */ new Set();
475
1194
  let readAny = false;
476
1195
  for (const entry of typeEntries) {
477
- const file = path14.join(uiDir, entry);
1196
+ const file = path18.join(uiDir, entry);
478
1197
  if (!existsSync(file)) continue;
479
1198
  readAny = true;
480
1199
  const dts = readFileSync(file, "utf8");
@@ -488,11 +1207,11 @@ function readPackageExports(root, uiPackage) {
488
1207
  }
489
1208
  const valueDecls = /* @__PURE__ */ new Set();
490
1209
  const typeDecls = /* @__PURE__ */ new Set();
491
- const declRoot = typeof mainTypes === "string" ? path14.dirname(path14.join(uiDir, mainTypes)) : uiDir;
1210
+ const declRoot = typeof mainTypes === "string" ? path18.dirname(path18.join(uiDir, mainTypes)) : uiDir;
492
1211
  const declFiles = walkDts(declRoot);
493
1212
  for (const pkg of reexportedPackages) {
494
1213
  const dir = findPackageDir(uiDir, pkg);
495
- if (dir) walkDts(path14.join(dir, "dist"), declFiles);
1214
+ if (dir) walkDts(path18.join(dir, "dist"), declFiles);
496
1215
  }
497
1216
  for (const file of declFiles) {
498
1217
  const text = readFileSync(file, "utf8");
@@ -538,7 +1257,7 @@ function walkDts(dir, out = []) {
538
1257
  if (!existsSync(dir)) return out;
539
1258
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
540
1259
  if (entry.name === "node_modules") continue;
541
- const p = path14.join(dir, entry.name);
1260
+ const p = path18.join(dir, entry.name);
542
1261
  if (entry.isDirectory()) walkDts(p, out);
543
1262
  else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
544
1263
  }
@@ -555,27 +1274,27 @@ function resolveThemeFiles(root, config, uiDir) {
555
1274
  }
556
1275
  const files = [];
557
1276
  const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
558
- const themes = ds && path14.join(ds, "dist", "themes");
1277
+ const themes = ds && path18.join(ds, "dist", "themes");
559
1278
  if (themes && existsSync(themes)) {
560
- for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path14.join(themes, name));
1279
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path18.join(themes, name));
561
1280
  }
562
1281
  if (files.length === 0) {
563
1282
  throw new DoctorConfigError(
564
1283
  `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
565
1284
  );
566
1285
  }
567
- const uiStyles = path14.join(uiDir, "dist", "styles.css");
1286
+ const uiStyles = path18.join(uiDir, "dist", "styles.css");
568
1287
  if (existsSync(uiStyles)) files.push(uiStyles);
569
1288
  return files;
570
1289
  }
571
1290
  function resolveSpec(root, spec) {
572
- const local = path14.resolve(root, spec);
573
- if (spec.startsWith(".") || path14.isAbsolute(spec)) return existsSync(local) ? local : null;
1291
+ const local = path18.resolve(root, spec);
1292
+ if (spec.startsWith(".") || path18.isAbsolute(spec)) return existsSync(local) ? local : null;
574
1293
  const parts = spec.split("/");
575
1294
  const nameLength = spec.startsWith("@") ? 2 : 1;
576
1295
  const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
577
1296
  if (dir) {
578
- const file = path14.join(dir, ...parts.slice(nameLength));
1297
+ const file = path18.join(dir, ...parts.slice(nameLength));
579
1298
  if (existsSync(file) && statSync(file).isFile()) return file;
580
1299
  }
581
1300
  return existsSync(local) ? local : null;
@@ -583,7 +1302,7 @@ function resolveSpec(root, spec) {
583
1302
  function loadPalette(root) {
584
1303
  const names = new Set(TAILWIND_PALETTE);
585
1304
  try {
586
- const req = createRequire(path14.join(root, "package.json"));
1305
+ const req = createRequire(path18.join(root, "package.json"));
587
1306
  const colors = req("tailwindcss/colors");
588
1307
  for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
589
1308
  if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
@@ -623,17 +1342,17 @@ function parseManifest(home, id, raw, version, options = {}) {
623
1342
  if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
624
1343
  if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
625
1344
  if (!isObject2(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
626
- const pkgOf = (value, where) => {
1345
+ const pkgOf = (value, where2) => {
627
1346
  if (value === void 0) return home;
628
1347
  if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
629
- problems.push(`${where}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
1348
+ problems.push(`${where2}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
630
1349
  return home;
631
1350
  }
632
1351
  return value;
633
1352
  };
634
- const pathOf = (value, where) => {
1353
+ const pathOf = (value, where2) => {
635
1354
  const safe = safeRelative(value);
636
- if (!safe) problems.push(`${where}: ${JSON.stringify(value)} is not a plain path inside the package`);
1355
+ if (!safe) problems.push(`${where2}: ${JSON.stringify(value)} is not a plain path inside the package`);
637
1356
  return safe ?? "";
638
1357
  };
639
1358
  const list = (key2) => {
@@ -665,43 +1384,43 @@ function parseManifest(home, id, raw, version, options = {}) {
665
1384
  return ok;
666
1385
  });
667
1386
  const migrations = list("migrations").map((m, i) => {
668
- const where = `${at}.migrations[${i}]`;
1387
+ const where2 = `${at}.migrations[${i}]`;
669
1388
  if (!isObject2(m)) {
670
- problems.push(`${where}: must be an object`);
1389
+ problems.push(`${where2}: must be an object`);
671
1390
  return { package: home, file: "" };
672
1391
  }
673
- const file = pathOf(m["file"], `${where}.file`);
674
- if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
675
- const out = { package: pkgOf(m["package"], where), file };
1392
+ const file = pathOf(m["file"], `${where2}.file`);
1393
+ if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where2}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
1394
+ const out = { package: pkgOf(m["package"], where2), file };
676
1395
  if (m["test"] !== void 0) {
677
- out.test = pathOf(m["test"], `${where}.test`);
678
- if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
1396
+ out.test = pathOf(m["test"], `${where2}.test`);
1397
+ 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`);
679
1398
  }
680
1399
  return out;
681
1400
  });
682
1401
  const functions = list("functions").map((f, i) => {
683
- const where = `${at}.functions[${i}]`;
1402
+ const where2 = `${at}.functions[${i}]`;
684
1403
  if (!isObject2(f)) {
685
- problems.push(`${where}: must be an object`);
1404
+ problems.push(`${where2}: must be an object`);
686
1405
  return { package: home, dir: "" };
687
1406
  }
688
- const dir = pathOf(f["dir"], `${where}.dir`);
689
- if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
690
- const out = { package: pkgOf(f["package"], where), dir };
1407
+ const dir = pathOf(f["dir"], `${where2}.dir`);
1408
+ if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where2}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
1409
+ const out = { package: pkgOf(f["package"], where2), dir };
691
1410
  if (f["verifyJwt"] !== void 0) {
692
- if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where}.verifyJwt: must be true or false`);
1411
+ if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where2}.verifyJwt: must be true or false`);
693
1412
  else out.verifyJwt = f["verifyJwt"];
694
1413
  }
695
1414
  if (f["secrets"] !== void 0) {
696
- if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where}.secrets: must be a list of UPPER_CASE names`);
1415
+ if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where2}.secrets: must be a list of UPPER_CASE names`);
697
1416
  else out.secrets = f["secrets"];
698
1417
  }
699
1418
  return out;
700
1419
  });
701
1420
  const routes = list("routes").map((r, i) => {
702
- const where = `${at}.routes[${i}]`;
1421
+ const where2 = `${at}.routes[${i}]`;
703
1422
  if (!isObject2(r) || typeof r["path"] !== "string" || !ROUTE.test(r["path"]) || r["path"].split("/").includes("..")) {
704
- problems.push(`${where}: needs a path like /settings/notifications`);
1423
+ problems.push(`${where2}: needs a path like /settings/notifications`);
705
1424
  return { path: "/" };
706
1425
  }
707
1426
  const out = { path: r["path"] };
@@ -771,8 +1490,8 @@ function rawBlocksOf(packageJson) {
771
1490
 
772
1491
  // src/blocks/files.ts
773
1492
  function inside(parent, child) {
774
- const rel = path14.relative(parent, child);
775
- return rel === "" || !rel.startsWith("..") && !path14.isAbsolute(rel);
1493
+ const rel = path18.relative(parent, child);
1494
+ return rel === "" || !rel.startsWith("..") && !path18.isAbsolute(rel);
776
1495
  }
777
1496
 
778
1497
  // src/blocks/local.ts
@@ -783,21 +1502,21 @@ var LocalPackagesError = class extends Error {
783
1502
  function validateLocalPackages(raw, source = "genesis.config.json") {
784
1503
  if (!Array.isArray(raw)) throw new LocalPackagesError(`${source}: ${LOCAL_PACKAGES_KEY} must be a list of folders`);
785
1504
  return raw.map((entry, i) => {
786
- const where = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
787
- if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where} must be a non-empty folder`);
788
- if (path14.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where} must be relative to the app ("${entry}")`);
789
- const norm = path14.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
790
- if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where} must name a package folder, not the app or a parent of it ("${entry}")`);
1505
+ const where2 = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
1506
+ if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where2} must be a non-empty folder`);
1507
+ if (path18.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
1508
+ const norm = path18.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
1509
+ if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where2} must name a package folder, not the app or a parent of it ("${entry}")`);
791
1510
  const parts = norm.split("/");
792
1511
  if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
793
- throw new LocalPackagesError(`${where}: only a final "/*" is supported ("${entry}")`);
1512
+ throw new LocalPackagesError(`${where2}: only a final "/*" is supported ("${entry}")`);
794
1513
  }
795
- if (parts.includes("node_modules")) throw new LocalPackagesError(`${where} can't point into node_modules ("${entry}")`);
1514
+ if (parts.includes("node_modules")) throw new LocalPackagesError(`${where2} can't point into node_modules ("${entry}")`);
796
1515
  return norm;
797
1516
  });
798
1517
  }
799
1518
  function localPackageGlobs(root) {
800
- const file = path14.join(root, "genesis.config.json");
1519
+ const file = path18.join(root, "genesis.config.json");
801
1520
  if (!existsSync(file)) return [];
802
1521
  let raw;
803
1522
  try {
@@ -811,14 +1530,14 @@ function localPackageGlobs(root) {
811
1530
  var cache = /* @__PURE__ */ new Map();
812
1531
  function repositoryRoot(appRoot) {
813
1532
  for (let dir = appRoot; ; ) {
814
- if (existsSync(path14.join(dir, ".git"))) return dir;
815
- const parent = path14.dirname(dir);
1533
+ if (existsSync(path18.join(dir, ".git"))) return dir;
1534
+ const parent = path18.dirname(dir);
816
1535
  if (parent === dir) return appRoot;
817
1536
  dir = parent;
818
1537
  }
819
1538
  }
820
1539
  function localPackages(root) {
821
- const appRoot = path14.resolve(root);
1540
+ const appRoot = path18.resolve(root);
822
1541
  const globs = localPackageGlobs(appRoot);
823
1542
  const key2 = `${appRoot}
824
1543
  ${globs.join("\n")}`;
@@ -827,24 +1546,24 @@ ${globs.join("\n")}`;
827
1546
  const dirs = /* @__PURE__ */ new Set();
828
1547
  for (const glob of globs) {
829
1548
  if (glob.endsWith("/*") || glob === "*") {
830
- const parent = path14.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
1549
+ const parent = path18.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
831
1550
  if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
832
1551
  for (const entry of readdirSync(parent).sort()) {
833
1552
  if (entry.startsWith(".") || entry === "node_modules") continue;
834
- dirs.add(path14.join(parent, entry));
1553
+ dirs.add(path18.join(parent, entry));
835
1554
  }
836
1555
  } else {
837
- dirs.add(path14.join(appRoot, glob));
1556
+ dirs.add(path18.join(appRoot, glob));
838
1557
  }
839
1558
  }
840
1559
  const real2 = realpathSync(repositoryRoot(appRoot));
841
1560
  const out = [];
842
1561
  const byName = /* @__PURE__ */ new Map();
843
1562
  for (const dir of [...dirs].sort()) {
844
- const manifest = path14.join(dir, "package.json");
1563
+ const manifest = path18.join(dir, "package.json");
845
1564
  if (!existsSync(manifest)) continue;
846
1565
  if (!inside(real2, realpathSync(dir))) {
847
- throw new LocalPackagesError(`${path14.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
1566
+ throw new LocalPackagesError(`${path18.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
848
1567
  }
849
1568
  let pkg;
850
1569
  try {
@@ -853,7 +1572,7 @@ ${globs.join("\n")}`;
853
1572
  continue;
854
1573
  }
855
1574
  if (typeof pkg.name !== "string" || !pkg.name) continue;
856
- const rel = path14.relative(appRoot, dir).split(path14.sep).join("/");
1575
+ const rel = path18.relative(appRoot, dir).split(path18.sep).join("/");
857
1576
  const other = byName.get(pkg.name);
858
1577
  if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
859
1578
  byName.set(pkg.name, rel);
@@ -1038,16 +1757,16 @@ var DEFAULT_IGNORE = [
1038
1757
  ];
1039
1758
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
1040
1759
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
1041
- var toPosix = (p) => p.split(path14.sep).join("/");
1760
+ var toPosix = (p) => p.split(path18.sep).join("/");
1042
1761
  function scanFiles(root, config) {
1043
1762
  const extensions = new Set(config.extensions ?? DEFAULT_EXTENSIONS);
1044
1763
  const ignored = globMatcher([...DEFAULT_IGNORE, ...config.ignore ?? []]);
1045
1764
  const files = [];
1046
1765
  const seen = /* @__PURE__ */ new Set();
1047
1766
  const visit = (abs) => {
1048
- const rel = toPosix(path14.relative(root, abs));
1767
+ const rel = toPosix(path18.relative(root, abs));
1049
1768
  if (seen.has(rel) || ignored(rel)) return;
1050
- const ext = path14.extname(abs);
1769
+ const ext = path18.extname(abs);
1051
1770
  if (!extensions.has(ext)) return;
1052
1771
  if (statSync(abs).size > MAX_FILE_BYTES) return;
1053
1772
  seen.add(rel);
@@ -1057,14 +1776,14 @@ function scanFiles(root, config) {
1057
1776
  const walk = (dir) => {
1058
1777
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1059
1778
  if (entry.isDirectory()) {
1060
- if (!SKIP_DIRS.has(entry.name)) walk(path14.join(dir, entry.name));
1779
+ if (!SKIP_DIRS.has(entry.name)) walk(path18.join(dir, entry.name));
1061
1780
  } else if (entry.isFile()) {
1062
- visit(path14.join(dir, entry.name));
1781
+ visit(path18.join(dir, entry.name));
1063
1782
  }
1064
1783
  }
1065
1784
  };
1066
1785
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
1067
- const abs = path14.resolve(root, src);
1786
+ const abs = path18.resolve(root, src);
1068
1787
  if (!existsSync(abs)) continue;
1069
1788
  if (statSync(abs).isDirectory()) walk(abs);
1070
1789
  else visit(abs);
@@ -1099,12 +1818,13 @@ function parseRulesMarkdown(markdown) {
1099
1818
  current = null;
1100
1819
  continue;
1101
1820
  }
1102
- const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message):\s*(.*)$/);
1821
+ const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message|newOnly):\s*(.*)$/);
1103
1822
  if (!current || !kv) continue;
1104
1823
  const [, key2, raw] = kv;
1105
1824
  const value = raw.trim();
1106
1825
  if (key2 === "files" || key2 === "exclude") current[key2] = value.split(",").map((s) => s.trim()).filter(Boolean);
1107
1826
  else if (key2 === "level") current.level = value;
1827
+ else if (key2 === "newOnly") current.newOnly = value === "true" ? true : value === "false" ? false : value;
1108
1828
  else current[key2] = value;
1109
1829
  }
1110
1830
  return rules;
@@ -1123,6 +1843,9 @@ function compilePatternRules(rules, source) {
1123
1843
  if (!["error", "warn", "info", "guide"].includes(level)) {
1124
1844
  throw new DoctorConfigError(`${source}: rule "${rule.id}" has level "${level}" (use error, warn, info or guide)`);
1125
1845
  }
1846
+ if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") {
1847
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" has newOnly "${String(rule.newOnly)}" (use true or false)`);
1848
+ }
1126
1849
  if (level === "guide") continue;
1127
1850
  if (!rule.files?.length) throw new DoctorConfigError(`${source}: rule "${rule.id}" needs "files" (or level: guide)`);
1128
1851
  if (!rule.forbid && !rule.require && !rule.path) {
@@ -1148,7 +1871,7 @@ function loadPatternRules(root, patterns, rulesDoc) {
1148
1871
  const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
1149
1872
  let all = compiled;
1150
1873
  if (rulesDoc) {
1151
- const file = path14.resolve(root, rulesDoc);
1874
+ const file = path18.resolve(root, rulesDoc);
1152
1875
  if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
1153
1876
  const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
1154
1877
  const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
@@ -1158,6 +1881,8 @@ function loadPatternRules(root, patterns, rulesDoc) {
1158
1881
  if (all.length === 0) return null;
1159
1882
  return {
1160
1883
  count: all.length,
1884
+ ids: all.map((r) => r.rule.id),
1885
+ newOnly: all.filter((r) => r.rule.newOnly).map((r) => r.rule.id),
1161
1886
  plugin: {
1162
1887
  name: "patterns",
1163
1888
  check(ctx) {
@@ -1204,14 +1929,14 @@ async function loadPlugins(specs, configDir) {
1204
1929
  }
1205
1930
  function resolvePlugin(id, configDir) {
1206
1931
  try {
1207
- if (id.startsWith(".") || path14.isAbsolute(id)) return resolveFrom(path14.resolve(configDir, id), configDir);
1932
+ if (id.startsWith(".") || path18.isAbsolute(id)) return resolveFrom(path18.resolve(configDir, id), configDir);
1208
1933
  return resolveFrom(id, configDir);
1209
1934
  } catch {
1210
1935
  throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
1211
1936
  }
1212
1937
  }
1213
1938
  function resolveFrom(id, from) {
1214
- return createRequire(path14.join(from, "noop.js")).resolve(id);
1939
+ return createRequire(path18.join(from, "noop.js")).resolve(id);
1215
1940
  }
1216
1941
  var BUILTIN_RULES = [
1217
1942
  "local-primitives",
@@ -1261,7 +1986,19 @@ var BUILTIN_RULES = [
1261
1986
  "package-unversioned-change",
1262
1987
  "package-export-missing",
1263
1988
  "package-block-invalid",
1264
- "package-untagged-tests"
1989
+ "package-untagged-tests",
1990
+ "package-doctor-declaration",
1991
+ // package rules (package-rules.ts): the rules themselves are namespaced, e.g. ui/lists-use-resource-view
1992
+ "package-rules-invalid",
1993
+ "package-rule-override",
1994
+ // ratchet (ratchet.ts)
1995
+ "ratchet-skipped",
1996
+ "allow-grew",
1997
+ "rules-weakened",
1998
+ // agent guide (primitives.ts)
1999
+ "agent-guide-stale",
2000
+ // supabase pack: contracts (contracts.ts)
2001
+ "contracts-stale"
1265
2002
  ];
1266
2003
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
1267
2004
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -1279,7 +2016,7 @@ function importSpecifiers(file) {
1279
2016
  }
1280
2017
  function checkProjectLayout(ctx) {
1281
2018
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
1282
- if (existsSync(path14.join(ctx.root, dir))) {
2019
+ if (existsSync(path18.join(ctx.root, dir))) {
1283
2020
  ctx.report({
1284
2021
  rule: "local-primitives",
1285
2022
  file: dir,
@@ -1289,7 +2026,7 @@ function checkProjectLayout(ctx) {
1289
2026
  }
1290
2027
  }
1291
2028
  for (const file of STARTER_LEFTOVERS) {
1292
- if (existsSync(path14.join(ctx.root, file))) {
2029
+ if (existsSync(path18.join(ctx.root, file))) {
1293
2030
  ctx.report({
1294
2031
  rule: "starter-leftover",
1295
2032
  level: "warn",
@@ -1378,7 +2115,7 @@ function checkTokens(ctx) {
1378
2115
  }
1379
2116
  for (const pattern of ctx.config.tokenFiles ?? []) {
1380
2117
  if (/[*?]/.test(pattern)) continue;
1381
- const abs = path14.join(ctx.root, pattern);
2118
+ const abs = path18.join(ctx.root, pattern);
1382
2119
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
1383
2120
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
1384
2121
  }
@@ -1480,19 +2217,34 @@ function privacyApisFor(dependencies2) {
1480
2217
  var SCRIPT_EXTS2 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
1481
2218
  var JSX_EXTS2 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
1482
2219
  var RESOLVE_EXTS = [".tsx", ".ts", ".jsx", ".js"];
2220
+ function resolveLocal(root, fromFile, spec) {
2221
+ const bases = spec.startsWith(".") ? [path18.resolve(path18.dirname(fromFile), spec)] : [path18.join(root, spec.slice(2)), path18.join(root, "src", spec.slice(2))];
2222
+ for (const base of bases) {
2223
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path18.join(base, `index${e}`))].find(
2224
+ (p) => SCRIPT_EXTS2.has(path18.extname(p)) && existsSync(p)
2225
+ );
2226
+ if (hit) return hit;
2227
+ }
2228
+ return null;
2229
+ }
1483
2230
  function localImports(root, file) {
1484
2231
  const out = [];
1485
2232
  for (const m of file.code.matchAll(/\bfrom\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g)) {
1486
- const spec = m[1];
1487
- const bases = spec.startsWith(".") ? [path14.resolve(path14.dirname(file.absolutePath), spec)] : [path14.join(root, spec.slice(2)), path14.join(root, "src", spec.slice(2))];
1488
- for (const base of bases) {
1489
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path14.join(base, `index${e}`))].find(
1490
- (p) => SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p)
1491
- );
1492
- if (hit) {
1493
- out.push(hit);
1494
- break;
1495
- }
2233
+ const hit = resolveLocal(root, file.absolutePath, m[1]);
2234
+ if (hit) out.push(hit);
2235
+ }
2236
+ return out;
2237
+ }
2238
+ function localImportedNames(root, file) {
2239
+ const out = /* @__PURE__ */ new Map();
2240
+ const re = /\bimport\s+(?:type\s+)?([\w$]+)?\s*,?\s*(?:\{([^}]*)\})?\s*from\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g;
2241
+ for (const m of file.code.matchAll(re)) {
2242
+ const target = resolveLocal(root, file.absolutePath, m[3]);
2243
+ if (!target) continue;
2244
+ if (m[1]) out.set(m[1], { file: target, name: "default" });
2245
+ for (const part of (m[2] ?? "").split(",")) {
2246
+ const [imported, local] = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/);
2247
+ if (imported) out.set(local ?? imported, { file: target, name: imported });
1496
2248
  }
1497
2249
  }
1498
2250
  return out;
@@ -1506,15 +2258,15 @@ function readSource(abs) {
1506
2258
  }
1507
2259
  function tagEnd(code, start) {
1508
2260
  let depth = 0;
1509
- let quote = null;
2261
+ let quote2 = null;
1510
2262
  for (let i = start + 1; i < code.length; i++) {
1511
2263
  const ch = code[i];
1512
- if (quote) {
2264
+ if (quote2) {
1513
2265
  if (ch === "\\") i++;
1514
- else if (ch === quote) quote = null;
2266
+ else if (ch === quote2) quote2 = null;
1515
2267
  continue;
1516
2268
  }
1517
- if (ch === '"' || ch === "'" || ch === "`") quote = ch;
2269
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
1518
2270
  else if (ch === "{") depth++;
1519
2271
  else if (ch === "}") depth--;
1520
2272
  else if (ch === ">" && depth === 0) {
@@ -1651,7 +2403,7 @@ function checkCustomHeaders(ctx, pkg) {
1651
2403
  if (!JSX_EXTS3.has(file.ext)) continue;
1652
2404
  const code = file.code;
1653
2405
  const hidden = HIDES_HEADER.exec(code);
1654
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path14.posix.dirname(file.path), file.path);
2406
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path18.posix.dirname(file.path), file.path);
1655
2407
  const own = hidden ? ownHeader(code, pkg) : null;
1656
2408
  if (hidden && own) {
1657
2409
  reported.add(file.path);
@@ -1679,7 +2431,7 @@ function checkCustomHeaders(ctx, pkg) {
1679
2431
  }
1680
2432
  for (const file of ctx.files) {
1681
2433
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
1682
- const layout = hidingLayouts.get(path14.posix.dirname(file.path));
2434
+ const layout = hidingLayouts.get(path18.posix.dirname(file.path));
1683
2435
  const own = layout ? ownHeader(file.code, pkg) : null;
1684
2436
  if (!layout || !own) continue;
1685
2437
  ctx.report({
@@ -1701,13 +2453,13 @@ function isLoadingOnlyRoute(code) {
1701
2453
  }
1702
2454
  function routerRoot(ctx) {
1703
2455
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
1704
- return existsSync(path14.join(ctx.root, "src", "app")) ? "src/app" : "app";
2456
+ return existsSync(path18.join(ctx.root, "src", "app")) ? "src/app" : "app";
1705
2457
  }
1706
2458
  function checkScreenLayouts(ctx, pkg) {
1707
2459
  const layouts = nativeLayouts(pkg);
1708
2460
  if (layouts.length === 0) return;
1709
2461
  const rootDir = routerRoot(ctx);
1710
- if (!existsSync(path14.join(ctx.root, rootDir))) {
2462
+ if (!existsSync(path18.join(ctx.root, rootDir))) {
1711
2463
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
1712
2464
  return;
1713
2465
  }
@@ -1763,7 +2515,7 @@ var GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\
1763
2515
  function readExpoConfigs(root) {
1764
2516
  const out = [];
1765
2517
  for (const name of EXPO_CONFIGS) {
1766
- const abs = path14.join(root, name);
2518
+ const abs = path18.join(root, name);
1767
2519
  if (!existsSync(abs)) continue;
1768
2520
  const text = readFileSync(abs, "utf8");
1769
2521
  let json = null;
@@ -1797,13 +2549,13 @@ function pluginOptions(json, module) {
1797
2549
  return null;
1798
2550
  }
1799
2551
  function dependencies(root) {
1800
- const file = path14.join(root, "package.json");
2552
+ const file = path18.join(root, "package.json");
1801
2553
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
1802
2554
  const pkg = JSON.parse(readFileSync(file, "utf8"));
1803
2555
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
1804
2556
  }
1805
2557
  function runtimeDependencies(root) {
1806
- const file = path14.join(root, "package.json");
2558
+ const file = path18.join(root, "package.json");
1807
2559
  if (!existsSync(file)) return {};
1808
2560
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
1809
2561
  }
@@ -2177,14 +2929,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
2177
2929
  seen.add(file);
2178
2930
  const json = readJsonc(file);
2179
2931
  if (!json) return {};
2180
- const dir = path14.dirname(file);
2932
+ const dir = path18.dirname(file);
2181
2933
  let merged = {};
2182
2934
  const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
2183
2935
  for (const ext of parents) {
2184
2936
  if (typeof ext !== "string") continue;
2185
2937
  let target = null;
2186
- if (ext.startsWith(".") || path14.isAbsolute(ext)) {
2187
- const abs = path14.resolve(dir, ext);
2938
+ if (ext.startsWith(".") || path18.isAbsolute(ext)) {
2939
+ const abs = path18.resolve(dir, ext);
2188
2940
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2189
2941
  } else {
2190
2942
  const parts = ext.split("/");
@@ -2192,14 +2944,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
2192
2944
  const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
2193
2945
  if (pkgDir) {
2194
2946
  const sub = parts.slice(nameLength).join("/");
2195
- const abs = path14.join(pkgDir, sub || "tsconfig.json");
2947
+ const abs = path18.join(pkgDir, sub || "tsconfig.json");
2196
2948
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2197
2949
  }
2198
2950
  }
2199
2951
  if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
2200
2952
  }
2201
2953
  const opts = json.compilerOptions ?? {};
2202
- if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
2954
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path18.resolve(dir, opts.baseUrl);
2203
2955
  if (opts.paths && typeof opts.paths === "object") {
2204
2956
  merged.paths = opts.paths;
2205
2957
  merged.pathsDir = dir;
@@ -2210,7 +2962,7 @@ function aliases(root) {
2210
2962
  const table = [];
2211
2963
  let baseUrl = null;
2212
2964
  for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
2213
- const file = path14.join(root, name);
2965
+ const file = path18.join(root, name);
2214
2966
  if (!existsSync(file)) continue;
2215
2967
  const config = readTsconfig(root, file);
2216
2968
  baseUrl ??= config.baseUrl ?? null;
@@ -2218,22 +2970,22 @@ function aliases(root) {
2218
2970
  for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
2219
2971
  if (!Array.isArray(targets)) continue;
2220
2972
  const exact = !pattern.endsWith("*");
2221
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
2973
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path18.join(base, String(t).replace(/\*$/, ""))) });
2222
2974
  }
2223
2975
  }
2224
- const pkg = readJsonc(path14.join(root, "package.json"));
2976
+ const pkg = readJsonc(path18.join(root, "package.json"));
2225
2977
  for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
2226
2978
  if (typeof target !== "string") continue;
2227
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
2979
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path18.join(root, target.replace(/\*.*$/, ""))] });
2228
2980
  }
2229
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
2981
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path18.join(root, "src") + path18.sep, root + path18.sep] });
2230
2982
  return { table, baseUrl };
2231
2983
  }
2232
2984
  function resolveFile(base) {
2233
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
2985
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path18.join(base, `index${e}`))];
2234
2986
  if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
2235
2987
  for (const p of tries) {
2236
- if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
2988
+ if (SCRIPT_EXTS2.has(path18.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
2237
2989
  }
2238
2990
  return null;
2239
2991
  }
@@ -2247,13 +2999,13 @@ function createTrail(ctx) {
2247
2999
  const { table, baseUrl } = aliases(ctx.root);
2248
3000
  let declared = null;
2249
3001
  try {
2250
- const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
3002
+ const pkg = JSON.parse(readFileSync(path18.join(ctx.root, "package.json"), "utf8"));
2251
3003
  declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
2252
3004
  } catch {
2253
3005
  declared = null;
2254
3006
  }
2255
3007
  const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
2256
- const read = (abs) => byPath.get(abs) ?? readSource(abs);
3008
+ const read2 = (abs) => byPath.get(abs) ?? readSource(abs);
2257
3009
  const importsCache = /* @__PURE__ */ new Map();
2258
3010
  const importsOf = (file) => {
2259
3011
  const hit = importsCache.get(file.absolutePath);
@@ -2278,17 +3030,17 @@ function createTrail(ctx) {
2278
3030
  if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
2279
3031
  let resolved = null;
2280
3032
  if (spec.startsWith(".")) {
2281
- resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
3033
+ resolved = resolveFile(path18.resolve(path18.dirname(file.absolutePath), spec));
2282
3034
  if (!resolved) lost = true;
2283
3035
  } else {
2284
3036
  const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
2285
3037
  if (alias) {
2286
3038
  for (const t of alias.targets) {
2287
- resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
3039
+ resolved = resolveFile(alias.exact ? t : path18.join(t, spec.slice(alias.prefix.length)));
2288
3040
  if (resolved) break;
2289
3041
  }
2290
3042
  }
2291
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
3043
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path18.join(baseUrl, spec));
2292
3044
  if (!resolved) {
2293
3045
  const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
2294
3046
  if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
@@ -2330,7 +3082,7 @@ function createTrail(ctx) {
2330
3082
  cut.add(abs);
2331
3083
  continue;
2332
3084
  }
2333
- const target = read(abs);
3085
+ const target = read2(abs);
2334
3086
  if (!target) {
2335
3087
  unknown = true;
2336
3088
  continue;
@@ -2360,81 +3112,585 @@ function createTrail(ctx) {
2360
3112
  return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
2361
3113
  }
2362
3114
 
2363
- // src/doctor/packages.ts
2364
- var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
2365
- var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
2366
- var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
2367
- var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
2368
- var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
2369
- function sourceFiles(dir, rel = "") {
2370
- const out = [];
2371
- for (const entry of readdirSync(path14.join(dir, rel)).sort()) {
2372
- if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
2373
- const child = rel ? `${rel}/${entry}` : entry;
2374
- const stat = lstatSync(path14.join(dir, child));
2375
- if (stat.isSymbolicLink()) continue;
2376
- if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
2377
- else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3115
+ // src/blocks/discover.ts
3116
+ var INSTALL_ROOT_MARKERS = [".git", "pnpm-lock.yaml", "pnpm-workspace.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"];
3117
+ function installedGenesis(root) {
3118
+ const found = /* @__PURE__ */ new Map();
3119
+ let dir = path18.resolve(root);
3120
+ for (; ; ) {
3121
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path18.join(dir, m)));
3122
+ const scope = path18.join(dir, "node_modules", "@marktiderman");
3123
+ if (existsSync(scope)) {
3124
+ for (const entry of readdirSync(scope)) {
3125
+ const name = `@marktiderman/${entry}`;
3126
+ if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
3127
+ if (existsSync(path18.join(scope, entry, "package.json"))) found.set(name, path18.join(scope, entry));
3128
+ }
3129
+ }
3130
+ const parent = path18.dirname(dir);
3131
+ if (atInstallRoot || parent === dir) return found;
3132
+ dir = parent;
2378
3133
  }
2379
- return out;
2380
3134
  }
2381
- function packageName2(specifier) {
2382
- const parts = specifier.split("/");
2383
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3135
+ var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3136
+ var STEMS = {
3137
+ tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
3138
+ "next-app": {
3139
+ layout: /* @__PURE__ */ new Set(["layout"]),
3140
+ index: /* @__PURE__ */ new Set(["page"]),
3141
+ skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
3142
+ },
3143
+ "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
3144
+ };
3145
+ var NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
3146
+ var HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
3147
+ var COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
3148
+ var RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
3149
+ 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;
3150
+ function routesDir(ctx) {
3151
+ if (ctx.config.routesDir) return ctx.config.routesDir;
3152
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path18.join(ctx.root, d))) ?? null;
2384
3153
  }
2385
- function git(root, args) {
2386
- const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2387
- return r.status === 0 ? r.stdout : null;
3154
+ var key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
3155
+ function flavorOf(dir, rels) {
3156
+ const stems = rels.map((r) => r.split("/").pop());
3157
+ if (stems.includes("__root")) return "tanstack";
3158
+ if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
3159
+ if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
3160
+ return "tanstack";
2388
3161
  }
2389
- function matchPattern(pattern, spec) {
2390
- const star = pattern.indexOf("*");
2391
- if (star < 0) return pattern === spec ? "" : null;
2392
- const head = pattern.slice(0, star);
2393
- const tail = pattern.slice(star + 1);
2394
- return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3162
+ function renders(code) {
3163
+ const elements = renderedElements(code);
3164
+ if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
3165
+ const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
3166
+ const named = COMPONENT_OPTION.exec(code)?.[1];
3167
+ if (named && !definedHere(named)) return true;
3168
+ if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
3169
+ const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
3170
+ return exported !== void 0 && !definedHere(exported);
2395
3171
  }
2396
- function tsconfigPaths(dir) {
2397
- const file = path14.join(dir, "tsconfig.json");
2398
- if (!existsSync(file)) return [];
2399
- try {
2400
- const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
2401
- const options = JSON.parse(text).compilerOptions ?? {};
2402
- const base = path14.resolve(dir, options.baseUrl ?? ".");
2403
- return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path14.resolve(base, t)) }));
2404
- } catch {
2405
- return [];
3172
+ function webRoutes(ctx) {
3173
+ const dir = routesDir(ctx);
3174
+ if (!dir) return [];
3175
+ 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(/\.[^.]+$/, "") }));
3176
+ const flavor = flavorOf(dir, candidates.map((c) => c.rel));
3177
+ const stems = STEMS[flavor];
3178
+ const groups = /* @__PURE__ */ new Map();
3179
+ for (const { file, rel } of candidates) {
3180
+ const parts = rel.split("/");
3181
+ if (parts.some((p) => p.startsWith("-"))) continue;
3182
+ if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
3183
+ if (flavor === "next-pages" && parts[0] === "api") continue;
3184
+ if (stems.skip.test(parts.at(-1))) continue;
3185
+ if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
3186
+ const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
3187
+ groups.set(id, [...groups.get(id) ?? [], file]);
2406
3188
  }
2407
- }
2408
- function checkImports2(ctx, pkg, json) {
2409
- const aliases2 = tsconfigPaths(pkg.dir);
2410
- const subpathImports = Object.keys(json.imports ?? {});
2411
- const viaAlias = (spec) => {
2412
- if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
2413
- for (const { pattern, targets } of aliases2) {
2414
- const hit = matchPattern(pattern, spec);
2415
- if (hit === null) continue;
2416
- return targets.some((t) => {
2417
- const rel = path14.relative(pkg.dir, t.replace("*", hit));
2418
- return !rel.startsWith("..") && !path14.isAbsolute(rel);
2419
- });
3189
+ const trail = trailFor(ctx);
3190
+ const routes = [];
3191
+ for (const [id, files] of groups) {
3192
+ const parts = id.split("/");
3193
+ const stem = parts.pop();
3194
+ const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
3195
+ const named = stems.layout.has(stem) || stems.index.has(stem);
3196
+ const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
3197
+ const segments = [...folders, ...own];
3198
+ const tree = [...parts, ...own];
3199
+ let index = stems.index.has(stem);
3200
+ if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
3201
+ segments.pop();
3202
+ tree.pop();
3203
+ index = true;
2420
3204
  }
2421
- return null;
2422
- };
2423
- const declared = /* @__PURE__ */ new Set([
2424
- json.name,
2425
- ...Object.keys(json.dependencies ?? {}),
2426
- ...Object.keys(json.peerDependencies ?? {}),
2427
- ...Object.keys(json.devDependencies ?? {}),
2428
- ...Object.keys(json.optionalDependencies ?? {})
2429
- ]);
2430
- for (const file of sourceFiles(pkg.dir)) {
2431
- const code = stripForImports(readFileSync(path14.join(pkg.dir, file), "utf8"));
2432
- if (code === null) continue;
2433
- const at = `${pkg.rel}/${file}`;
2434
- const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
2435
- let offset = 0;
2436
- code.split("\n").forEach((text, i) => {
2437
- const lineStart = offset;
3205
+ const code = files.map((f) => f.code).join("\n");
3206
+ const elements = renderedElements(code);
3207
+ const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
3208
+ const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
3209
+ const layout = stems.layout.has(stem) || pathless || outlet;
3210
+ const rendering = renders(code);
3211
+ const ownContent = new RegExp(OWN_CONTENT).test(code);
3212
+ const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
3213
+ const page = !pure && !pathless && (!layout || ownContent);
3214
+ routes.push({
3215
+ file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
3216
+ files,
3217
+ segments,
3218
+ tree,
3219
+ index,
3220
+ layout,
3221
+ page,
3222
+ detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
3223
+ redirectOnly: !rendering,
3224
+ parents: []
3225
+ });
3226
+ }
3227
+ for (const r of routes) {
3228
+ const own = r.tree;
3229
+ for (const p of routes) {
3230
+ if (p === r || !p.layout) continue;
3231
+ const n = p.tree.length;
3232
+ if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
3233
+ if (key(own.slice(0, n)) !== key(p.tree)) continue;
3234
+ if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
3235
+ r.parents.push(p);
3236
+ }
3237
+ r.parents.sort((a, b) => b.tree.length - a.tree.length);
3238
+ }
3239
+ return routes;
3240
+ }
3241
+
3242
+ // src/doctor/package-rules.ts
3243
+ var PackageDeclarationError = class extends Error {
3244
+ name = "PackageDeclarationError";
3245
+ };
3246
+ var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
3247
+ var ID = /^[a-z0-9][a-z0-9-]*$/;
3248
+ var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
3249
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
3250
+ var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
3251
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
3252
+ var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
3253
+ var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "primitives", "plugin", "$comment"]);
3254
+ var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
3255
+ function ruleNamespace(packageName3) {
3256
+ const m = GENESIS.exec(packageName3);
3257
+ if (m) return m[1] ?? "genesis";
3258
+ return packageName3;
3259
+ }
3260
+ var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3261
+ var isStringList2 = (v) => Array.isArray(v) && v.every((x) => typeof x === "string" && x.trim() !== "");
3262
+ function toRegExp2(source, flags = "") {
3263
+ if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
3264
+ return new RegExp(source, flags);
3265
+ }
3266
+ function validateDeclaration(raw, packageName3, packageDir, ignored) {
3267
+ const fail = (msg) => {
3268
+ throw new PackageDeclarationError(`${packageName3}: genesis.doctor ${msg}`);
3269
+ };
3270
+ const unknownKey = (where2, key2, known) => {
3271
+ const msg = `${where2 ? `${where2} ` : ""}has an unknown key "${key2}"${known ? ` (known: ${[...known].filter((k) => k !== "$comment").join(", ")})` : ""}`;
3272
+ if (!ignored) return fail(msg);
3273
+ ignored.push(`${packageName3}: genesis.doctor ${msg}; ignored`);
3274
+ };
3275
+ const each = (list, check) => list.flatMap((item, i) => {
3276
+ if (!ignored) return [check(item, i)];
3277
+ try {
3278
+ return [check(item, i)];
3279
+ } catch (err) {
3280
+ if (!(err instanceof PackageDeclarationError)) throw err;
3281
+ ignored.push(`${err.message}; that entry is skipped`);
3282
+ return [];
3283
+ }
3284
+ });
3285
+ if (typeof raw === "string") {
3286
+ if (!packageDir) fail(`points at ${raw}, but the package folder is unknown`);
3287
+ const file = path18.resolve(packageDir, raw);
3288
+ if (!inside(packageDir, file)) fail(`points outside the package (${raw})`);
3289
+ if (!existsSync(file)) fail(`points at ${raw}, which doesn't exist (is it in package.json "files"?)`);
3290
+ let parsed;
3291
+ try {
3292
+ parsed = JSON.parse(readFileSync(file, "utf8"));
3293
+ } catch (err) {
3294
+ return fail(`file ${raw} is not valid JSON: ${err.message}`);
3295
+ }
3296
+ return validateDeclaration(parsed, packageName3, packageDir, ignored);
3297
+ }
3298
+ if (raw === false) fail(`is false; say why with { "enforce": false, "reason": "\u2026" }`);
3299
+ if (!isObject3(raw)) fail(`must be an object (or a path to a JSON file in the package)`);
3300
+ const c = raw;
3301
+ for (const key2 of Object.keys(c)) if (!DECLARATION_KEYS.has(key2)) unknownKey("", key2, DECLARATION_KEYS);
3302
+ const enforce = c.enforce === void 0 ? true : c.enforce;
3303
+ if (typeof enforce !== "boolean") fail(`enforce must be true or false`);
3304
+ if (c.reason !== void 0 && (typeof c.reason !== "string" || !c.reason.trim())) fail(`reason must be a sentence`);
3305
+ const prefer = c.prefer === void 0 ? [] : c.prefer;
3306
+ if (!Array.isArray(prefer)) fail(`prefer must be a list`);
3307
+ const primitives = c.primitives === void 0 ? [] : c.primitives;
3308
+ if (!Array.isArray(primitives)) fail(`primitives must be a list`);
3309
+ if (c.plugin !== void 0 && (typeof c.plugin !== "string" || !c.plugin.trim())) fail(`plugin must be a module path inside the package`);
3310
+ if (!enforce) {
3311
+ if (typeof c.reason !== "string") fail(`turns enforcement off without a reason; add "reason"`);
3312
+ if (prefer.length || c.plugin) fail(`turns enforcement off but declares rules; drop "enforce": false or the rules`);
3313
+ } else if (!prefer.length && !c.plugin) {
3314
+ fail(`declares no rules; add "prefer" rules or a "plugin", or say { "enforce": false, "reason": "\u2026" }`);
3315
+ }
3316
+ const ids = /* @__PURE__ */ new Set();
3317
+ const rules = each(prefer, (r, i) => validatePrefer(r, `prefer[${i}]`, fail, unknownKey));
3318
+ for (const r of rules) {
3319
+ if (ids.has(r.id)) fail(`defines the rule "${r.id}" twice`);
3320
+ ids.add(r.id);
3321
+ }
3322
+ const entries = each(primitives, (p, i) => {
3323
+ const where2 = `primitives[${i}]`;
3324
+ if (!isObject3(p)) return fail(`${where2} must be an object`);
3325
+ for (const key2 of Object.keys(p)) if (!PRIMITIVE_KEYS.has(key2)) unknownKey(where2, key2);
3326
+ for (const key2 of ["need", "use"]) if (typeof p[key2] !== "string" || !p[key2].trim()) fail(`${where2} needs "${key2}"`);
3327
+ for (const key2 of ["import", "docs"]) if (p[key2] !== void 0 && typeof p[key2] !== "string") fail(`${where2}.${key2} must be a string`);
3328
+ return p;
3329
+ });
3330
+ let plugin;
3331
+ if (typeof c.plugin === "string") {
3332
+ if (!packageDir) plugin = c.plugin;
3333
+ else {
3334
+ plugin = path18.resolve(packageDir, c.plugin);
3335
+ if (!inside(packageDir, plugin)) fail(`plugin points outside the package (${c.plugin})`);
3336
+ }
3337
+ }
3338
+ return {
3339
+ enforce,
3340
+ ...typeof c.reason === "string" ? { reason: c.reason } : {},
3341
+ prefer: rules,
3342
+ primitives: entries,
3343
+ ...plugin ? { plugin } : {}
3344
+ };
3345
+ }
3346
+ function validatePrefer(raw, where2, fail, unknownKey) {
3347
+ if (!isObject3(raw)) return fail(`${where2} must be an object`);
3348
+ const narrowing = (at2, key2, known) => fail(`${at2} has an unknown key "${key2}" (known: ${[...known].join(", ")})`);
3349
+ for (const key2 of Object.keys(raw)) if (!PREFER_KEYS.has(key2)) narrowing(where2, key2, PREFER_KEYS);
3350
+ if (typeof raw.id !== "string" || !ID.test(raw.id)) fail(`${where2} needs an "id" of lower-case words and dashes`);
3351
+ const at = `${where2} (${raw.id})`;
3352
+ for (const key2 of ["use", "why"]) if (typeof raw[key2] !== "string" || !raw[key2].trim()) fail(`${at} needs "${key2}"`);
3353
+ for (const key2 of ["need", "import", "docs"]) if (raw[key2] !== void 0 && typeof raw[key2] !== "string") fail(`${at}.${key2} must be a string`);
3354
+ if (raw.level !== void 0 && !LEVELS2.has(raw.level)) fail(`${at}.level must be "error", "warn" or "info"`);
3355
+ if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
3356
+ if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
3357
+ for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
3358
+ if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
3359
+ const forbid = raw.forbid;
3360
+ for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
3361
+ if (!forbid.jsx && !forbid.imports && !forbid.pattern) fail(`${at}.forbid needs jsx, imports or pattern`);
3362
+ 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`);
3363
+ if (forbid.imports !== void 0 && !isStringList2(forbid.imports)) fail(`${at}.forbid.imports must be a list of import specifiers`);
3364
+ if (forbid.pattern !== void 0) checkPattern(forbid.pattern, `${at}.forbid.pattern`, fail);
3365
+ if (raw.unless !== void 0) {
3366
+ if (!isObject3(raw.unless)) fail(`${at}.unless must be an object`);
3367
+ const unless = raw.unless;
3368
+ for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
3369
+ if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
3370
+ if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
3371
+ }
3372
+ return raw;
3373
+ }
3374
+ function checkPattern(v, where2, fail) {
3375
+ if (typeof v !== "string" || !v) fail(`${where2} must be a regular expression`);
3376
+ try {
3377
+ toRegExp2(v, "g");
3378
+ } catch (err) {
3379
+ fail(`${where2} is not a valid regular expression: ${err.message}`);
3380
+ }
3381
+ }
3382
+ var discoveryCache = /* @__PURE__ */ new Map();
3383
+ function readDeclaringPackage(dir, local) {
3384
+ const file = path18.join(dir, "package.json");
3385
+ let stamp;
3386
+ let real2;
3387
+ try {
3388
+ real2 = realpathSync(dir);
3389
+ stamp = `${real2}
3390
+ ${statSync(file).mtimeMs}
3391
+ ${local}`;
3392
+ } catch {
3393
+ return null;
3394
+ }
3395
+ const hit = discoveryCache.get(stamp);
3396
+ if (hit) return hit;
3397
+ let json;
3398
+ try {
3399
+ json = JSON.parse(readFileSync(file, "utf8"));
3400
+ } catch {
3401
+ return null;
3402
+ }
3403
+ if (typeof json.name !== "string" || !json.name) return null;
3404
+ const pkg = {
3405
+ name: json.name,
3406
+ version: typeof json.version === "string" ? json.version : "0.0.0",
3407
+ dir: path18.resolve(dir),
3408
+ namespace: ruleNamespace(json.name),
3409
+ local,
3410
+ private: json.private === true,
3411
+ declaration: null
3412
+ };
3413
+ const raw = json.genesis?.doctor;
3414
+ if (raw !== void 0) {
3415
+ const ignored = [];
3416
+ try {
3417
+ pkg.declaration = validateDeclaration(raw, json.name, path18.resolve(dir), ignored);
3418
+ if (ignored.length) pkg.ignored = ignored;
3419
+ } catch (err) {
3420
+ pkg.error = err.message;
3421
+ }
3422
+ }
3423
+ discoveryCache.set(stamp, pkg);
3424
+ return pkg;
3425
+ }
3426
+ function discoverPackages(root) {
3427
+ const byName = /* @__PURE__ */ new Map();
3428
+ const installed = [...installedGenesis(root).values()];
3429
+ for (const dir of installed) {
3430
+ const pkg = readDeclaringPackage(dir, false);
3431
+ if (pkg) byName.set(pkg.name, pkg);
3432
+ }
3433
+ for (const dir of installed) {
3434
+ let scope;
3435
+ try {
3436
+ scope = path18.dirname(realpathSync(dir));
3437
+ } catch {
3438
+ continue;
3439
+ }
3440
+ if (path18.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
3441
+ for (const entry of readdirSync(scope)) {
3442
+ if (byName.has(`@marktiderman/${entry}`) || !GENESIS.test(`@marktiderman/${entry}`)) continue;
3443
+ const pkg = readDeclaringPackage(path18.join(scope, entry), false);
3444
+ if (pkg) byName.set(pkg.name, pkg);
3445
+ }
3446
+ }
3447
+ let local = [];
3448
+ try {
3449
+ local = localPackages(root);
3450
+ } catch {
3451
+ }
3452
+ for (const l of local) {
3453
+ const pkg = readDeclaringPackage(l.dir, true);
3454
+ if (pkg) byName.set(pkg.name, pkg);
3455
+ }
3456
+ return [...byName.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3457
+ }
3458
+ function preferRules(packages) {
3459
+ return packages.flatMap(
3460
+ (p) => (p.declaration?.prefer ?? []).map((r) => ({ ...r, ruleId: `${p.namespace}/${r.id}`, package: p.name, packageDir: p.dir }))
3461
+ );
3462
+ }
3463
+ var specMatcher = (s) => s.endsWith("*") ? (spec) => spec.startsWith(s.slice(0, -1)) : (spec) => spec === s;
3464
+ function compile(rule, setting, routes) {
3465
+ const expand = (globs) => globs.flatMap((g) => {
3466
+ if (!g.includes("{routes}")) return [g];
3467
+ return routes ? [g.replaceAll("{routes}", routes)] : [];
3468
+ });
3469
+ const files = expand(setting?.files ?? rule.files ?? SCRIPT_GLOBS);
3470
+ if (files.length === 0) return null;
3471
+ return {
3472
+ rule,
3473
+ level: rule.level ?? "warn",
3474
+ includes: globMatcher(files),
3475
+ excludes: globMatcher(expand(setting?.exclude ?? rule.exclude ?? [])),
3476
+ jsx: new Set(rule.forbid.jsx ?? []),
3477
+ imports: (rule.forbid.imports ?? []).map(specMatcher),
3478
+ ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
3479
+ unlessRenders: new Set(rule.unless?.renders ?? []),
3480
+ ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
3481
+ };
3482
+ }
3483
+ var JSX = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
3484
+ var ELEMENT = /(?<![\w$.])<([A-Z][\w.]*)(?=[\s>/<])/g;
3485
+ var SCRIPT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
3486
+ function messageFor(rule, found) {
3487
+ const from = rule.import ? ` (${rule.import})` : "";
3488
+ const docs = rule.docs ? ` See ${rule.docs}` : "";
3489
+ return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
3490
+ }
3491
+ var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
3492
+ var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
3493
+ var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
3494
+ function wrappersIn(file, elements, c) {
3495
+ const out = /* @__PURE__ */ new Map();
3496
+ const decls = [...file.code.matchAll(TOP_LEVEL)];
3497
+ const listed = /* @__PURE__ */ new Map();
3498
+ for (const m of file.code.matchAll(EXPORT_LIST)) {
3499
+ for (const part of m[1].split(",")) {
3500
+ const [local, exported] = part.trim().split(/\s+as\s+/);
3501
+ if (local) listed.set(local, [...listed.get(local) ?? [], exported ?? local]);
3502
+ }
3503
+ }
3504
+ for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
3505
+ decls.forEach((d, i) => {
3506
+ const name = d[3];
3507
+ if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
3508
+ const end = decls[i + 1]?.index ?? file.code.length;
3509
+ const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
3510
+ if (!hit) return;
3511
+ const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
3512
+ for (const n of names) out.set(n, hit[1]);
3513
+ });
3514
+ return out;
3515
+ }
3516
+ function runPrefer(ctx, c) {
3517
+ const own = c.rule.packageDir;
3518
+ const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
3519
+ const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
3520
+ const wrappers = /* @__PURE__ */ new Map();
3521
+ const renderedBy = /* @__PURE__ */ new Map();
3522
+ for (const file of checked) {
3523
+ if (!JSX.has(file.ext)) continue;
3524
+ const elements = [...file.code.matchAll(ELEMENT)];
3525
+ renderedBy.set(file, elements);
3526
+ if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
3527
+ const found = wrappersIn(file, elements, c);
3528
+ if (found.size) wrappers.set(file.absolutePath, found);
3529
+ }
3530
+ for (const file of checked) {
3531
+ const elements = renderedBy.get(file) ?? [];
3532
+ if (exempt(file, elements.map((m) => m[1]))) continue;
3533
+ const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
3534
+ const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
3535
+ for (const m of elements) {
3536
+ const name = m[1];
3537
+ if (c.jsx.has(name)) {
3538
+ report(lineAt(file.code, m.index), name, `renders <${name}>`);
3539
+ continue;
3540
+ }
3541
+ const from = imported?.get(name.split(".")[0]);
3542
+ const around = from && !name.includes(".") ? wrappers.get(from.file)?.get(from.name) : void 0;
3543
+ if (around) report(lineAt(file.code, m.index), name, `renders <${name}>, an app wrapper around <${around}>`);
3544
+ }
3545
+ if (c.imports.length) {
3546
+ for (const { specifier, line } of importSpecifiers(file)) {
3547
+ if (c.imports.some((t) => t(specifier))) report(line, specifier, `imports ${specifier}`);
3548
+ }
3549
+ }
3550
+ if (c.pattern) {
3551
+ c.pattern.lastIndex = 0;
3552
+ for (const m of file.code.matchAll(c.pattern)) {
3553
+ const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
3554
+ report(lineAt(file.code, m.index), text, `has ${text}`);
3555
+ }
3556
+ }
3557
+ }
3558
+ }
3559
+ var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
3560
+ async function packageRulesPlugins(packages) {
3561
+ const out = [
3562
+ {
3563
+ name: "package-rules",
3564
+ check(ctx) {
3565
+ for (const p of packages) {
3566
+ const at = { rule: "package-rules-invalid", level: "warn", file: `${p.name}/package.json`, subject: p.name };
3567
+ if (p.error) ctx.report({ ...at, message: `${p.error}; its rules don't run` });
3568
+ for (const note of p.ignored ?? []) ctx.report({ ...at, message: `${note} (a newer @marktiderman/genesis-cli may read it)` });
3569
+ }
3570
+ const routes = routesDir(ctx);
3571
+ const settings = ctx.config.packageRules ?? {};
3572
+ for (const rule of preferRules(packages)) {
3573
+ if (rule.platform === "web" && isNative(ctx)) continue;
3574
+ if (rule.platform === "native" && !isNative(ctx)) continue;
3575
+ const compiled = compile(rule, settings[rule.ruleId], routes);
3576
+ if (compiled) runPrefer(ctx, compiled);
3577
+ }
3578
+ }
3579
+ }
3580
+ ];
3581
+ for (const p of packages) {
3582
+ const file = p.declaration?.plugin;
3583
+ if (!file) continue;
3584
+ let loaded;
3585
+ try {
3586
+ loaded = await loadPlugins([file], p.dir);
3587
+ } catch (err) {
3588
+ const message = err.message;
3589
+ 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 }) });
3590
+ continue;
3591
+ }
3592
+ for (const plugin of loaded) {
3593
+ out.push({
3594
+ name: `${p.namespace}/${plugin.name}`,
3595
+ check: (ctx) => plugin.check({
3596
+ ...ctx,
3597
+ report: (f) => ctx.report({ ...f, rule: f.rule.startsWith(`${p.namespace}/`) ? f.rule : `${p.namespace}/${f.rule}` })
3598
+ })
3599
+ });
3600
+ }
3601
+ }
3602
+ return out;
3603
+ }
3604
+ function unknownPackageRuleSettings(config, packages, reported) {
3605
+ const known = /* @__PURE__ */ new Set([...packageRuleIds(packages), ...reported.map((f) => f.rule)]);
3606
+ const plugins = packages.filter((p) => p.declaration?.plugin).map((p) => `${p.namespace}/`);
3607
+ return Object.keys(config.packageRules ?? {}).filter((id) => !known.has(id) && !plugins.some((ns) => id.startsWith(ns))).map((id) => ({
3608
+ rule: "stale-exception",
3609
+ level: "warn",
3610
+ file: "genesis config",
3611
+ subject: id,
3612
+ message: `packageRules names ${id}, which no installed package declares; check the id (genesis primitives lists them) or remove it`
3613
+ }));
3614
+ }
3615
+ function packageRuleIds(packages) {
3616
+ return new Set(preferRules(packages).map((r) => r.ruleId));
3617
+ }
3618
+
3619
+ // src/doctor/packages.ts
3620
+ var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
3621
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
3622
+ var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
3623
+ var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
3624
+ var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
3625
+ function sourceFiles(dir, rel = "") {
3626
+ const out = [];
3627
+ for (const entry of readdirSync(path18.join(dir, rel)).sort()) {
3628
+ if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
3629
+ const child = rel ? `${rel}/${entry}` : entry;
3630
+ const stat = lstatSync(path18.join(dir, child));
3631
+ if (stat.isSymbolicLink()) continue;
3632
+ if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
3633
+ else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3634
+ }
3635
+ return out;
3636
+ }
3637
+ function packageName2(specifier) {
3638
+ const parts = specifier.split("/");
3639
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3640
+ }
3641
+ function git(root, args) {
3642
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3643
+ return r.status === 0 ? r.stdout : null;
3644
+ }
3645
+ function matchPattern(pattern, spec) {
3646
+ const star = pattern.indexOf("*");
3647
+ if (star < 0) return pattern === spec ? "" : null;
3648
+ const head = pattern.slice(0, star);
3649
+ const tail = pattern.slice(star + 1);
3650
+ return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3651
+ }
3652
+ function tsconfigPaths(dir) {
3653
+ const file = path18.join(dir, "tsconfig.json");
3654
+ if (!existsSync(file)) return [];
3655
+ try {
3656
+ const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
3657
+ const options = JSON.parse(text).compilerOptions ?? {};
3658
+ const base = path18.resolve(dir, options.baseUrl ?? ".");
3659
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path18.resolve(base, t)) }));
3660
+ } catch {
3661
+ return [];
3662
+ }
3663
+ }
3664
+ function checkImports2(ctx, pkg, json) {
3665
+ const aliases2 = tsconfigPaths(pkg.dir);
3666
+ const subpathImports = Object.keys(json.imports ?? {});
3667
+ const viaAlias = (spec) => {
3668
+ if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
3669
+ for (const { pattern, targets } of aliases2) {
3670
+ const hit = matchPattern(pattern, spec);
3671
+ if (hit === null) continue;
3672
+ return targets.some((t) => {
3673
+ const rel = path18.relative(pkg.dir, t.replace("*", hit));
3674
+ return !rel.startsWith("..") && !path18.isAbsolute(rel);
3675
+ });
3676
+ }
3677
+ return null;
3678
+ };
3679
+ const declared = /* @__PURE__ */ new Set([
3680
+ json.name,
3681
+ ...Object.keys(json.dependencies ?? {}),
3682
+ ...Object.keys(json.peerDependencies ?? {}),
3683
+ ...Object.keys(json.devDependencies ?? {}),
3684
+ ...Object.keys(json.optionalDependencies ?? {})
3685
+ ]);
3686
+ for (const file of sourceFiles(pkg.dir)) {
3687
+ const code = stripForImports(readFileSync(path18.join(pkg.dir, file), "utf8"));
3688
+ if (code === null) continue;
3689
+ const at = `${pkg.rel}/${file}`;
3690
+ const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
3691
+ let offset = 0;
3692
+ code.split("\n").forEach((text, i) => {
3693
+ const lineStart = offset;
2438
3694
  offset += text.length + 1;
2439
3695
  for (const m of text.matchAll(IMPORT)) {
2440
3696
  const spec = m[1];
@@ -2453,9 +3709,9 @@ function checkImports2(ctx, pkg, json) {
2453
3709
  continue;
2454
3710
  }
2455
3711
  if (spec.startsWith(".")) {
2456
- const target = path14.resolve(pkg.dir, path14.dirname(file), spec);
2457
- const rel = path14.relative(pkg.dir, target);
2458
- if (rel.startsWith("..") || path14.isAbsolute(rel)) {
3712
+ const target = path18.resolve(pkg.dir, path18.dirname(file), spec);
3713
+ const rel = path18.relative(pkg.dir, target);
3714
+ if (rel.startsWith("..") || path18.isAbsolute(rel)) {
2459
3715
  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` });
2460
3716
  }
2461
3717
  continue;
@@ -2477,12 +3733,12 @@ function checkMigrations(ctx, pkg, json) {
2477
3733
  if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
2478
3734
  if (typeof m.file === "string" && typeof m.test !== "string") {
2479
3735
  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` });
2480
- } else if (typeof m.test === "string" && !existsSync(path14.join(pkg.dir, m.test))) {
3736
+ } else if (typeof m.test === "string" && !existsSync(path18.join(pkg.dir, m.test))) {
2481
3737
  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` });
2482
3738
  }
2483
3739
  }
2484
3740
  }
2485
- const dir = path14.join(pkg.dir, "migrations");
3741
+ const dir = path18.join(pkg.dir, "migrations");
2486
3742
  if (!existsSync(dir)) return;
2487
3743
  const seen = /* @__PURE__ */ new Map();
2488
3744
  for (const name of readdirSync(dir).sort()) {
@@ -2491,7 +3747,7 @@ function checkMigrations(ctx, pkg, json) {
2491
3747
  const other = seen.get(m[1]);
2492
3748
  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` });
2493
3749
  else seen.set(m[1], name);
2494
- if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path14.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
3750
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path18.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
2495
3751
  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")})` });
2496
3752
  }
2497
3753
  }
@@ -2505,7 +3761,7 @@ function checkExports(ctx, pkg, json) {
2505
3761
  walk(json.exports);
2506
3762
  for (const t of targets) {
2507
3763
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
2508
- if (!existsSync(path14.join(pkg.dir, t))) {
3764
+ if (!existsSync(path18.join(pkg.dir, t))) {
2509
3765
  ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
2510
3766
  }
2511
3767
  }
@@ -2523,11 +3779,11 @@ function checkBlocks(ctx, pkg, json) {
2523
3779
  function checkTaggedTests(ctx, pkg) {
2524
3780
  const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
2525
3781
  if (!tests.length) return;
2526
- const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path14.join(pkg.dir, f), "utf8")));
3782
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path18.join(pkg.dir, f), "utf8")));
2527
3783
  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>` });
2528
3784
  }
2529
3785
  function checkRegistered(ctx, pkg) {
2530
- const file = path14.join(ctx.root, "features.json");
3786
+ const file = path18.join(ctx.root, "features.json");
2531
3787
  if (!existsSync(file)) return;
2532
3788
  let doc;
2533
3789
  try {
@@ -2537,7 +3793,7 @@ function checkRegistered(ctx, pkg) {
2537
3793
  }
2538
3794
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
2539
3795
  const forms = /* @__PURE__ */ new Set([pkg.rel]);
2540
- if (top) forms.add(path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/"));
3796
+ if (top) forms.add(path18.relative(top, realpathSync(pkg.dir)).split(path18.sep).join("/"));
2541
3797
  const covered = (doc.features ?? []).some(
2542
3798
  (f) => (f.links?.code ?? []).some((c) => {
2543
3799
  const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -2567,9 +3823,9 @@ function mergeBaseOf(root, base) {
2567
3823
  function checkChanges(ctx, pkg, json, base, mergeBase) {
2568
3824
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
2569
3825
  if (!top) return;
2570
- const appRelative = (fromTop) => path14.relative(realpathSync(ctx.root), path14.join(top, fromTop)).split(path14.sep).join("/");
2571
- const inRepo = path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/");
2572
- 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");
3826
+ const appRelative = (fromTop) => path18.relative(realpathSync(ctx.root), path18.join(top, fromTop)).split(path18.sep).join("/");
3827
+ const inRepo = path18.relative(top, realpathSync(pkg.dir)).split(path18.sep).join("/");
3828
+ 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");
2573
3829
  const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
2574
3830
  const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
2575
3831
  (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
@@ -2591,11 +3847,11 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
2591
3847
  const now = typeof json.version === "string" ? parseVersion(json.version) : null;
2592
3848
  const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
2593
3849
  const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
2594
- 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)) : [];
3850
+ 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)) : [];
2595
3851
  const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
2596
3852
  const named = naming.length > 0;
2597
3853
  if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
2598
- 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` });
3854
+ 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` });
2599
3855
  }
2600
3856
  let jsonBefore = null;
2601
3857
  try {
@@ -2605,7 +3861,7 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
2605
3861
  }
2606
3862
  const raw = json;
2607
3863
  if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
2608
- const appInRepo = path14.relative(top, realpathSync(ctx.root)).split(path14.sep).join("/");
3864
+ const appInRepo = path18.relative(top, realpathSync(ctx.root)).split(path18.sep).join("/");
2609
3865
  const candidates = [.../* @__PURE__ */ new Set(["features.ts", "src/features.ts", ...appInRepo ? [`${appInRepo}/features.ts`, `${appInRepo}/src/features.ts`] : []])];
2610
3866
  const registry = (git(top, ["diff", "--name-only", mergeBase, "--", ...candidates]) ?? "").trim();
2611
3867
  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` });
@@ -2622,6 +3878,26 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
2622
3878
  });
2623
3879
  }
2624
3880
  }
3881
+ var GENESIS_NAME = /^@marktiderman\/genesis(?:-[a-z0-9-]+)?$/;
3882
+ function checkDoctorDeclaration(ctx, pkg, json) {
3883
+ if (json.private === true || !GENESIS_NAME.test(json.name)) return;
3884
+ const file = `${pkg.rel}/package.json`;
3885
+ const raw = json.genesis?.doctor;
3886
+ if (raw === void 0) {
3887
+ ctx.report({
3888
+ rule: "package-doctor-declaration",
3889
+ file,
3890
+ subject: json.name,
3891
+ message: `${json.name} declares no doctor rules; add genesis.doctor with the primitives it enforces ("prefer" rules), or { "enforce": false, "reason": "\u2026" }`
3892
+ });
3893
+ return;
3894
+ }
3895
+ try {
3896
+ validateDeclaration(raw, json.name, pkg.dir);
3897
+ } catch (err) {
3898
+ ctx.report({ rule: "package-doctor-declaration", file, subject: json.name, message: err.message });
3899
+ }
3900
+ }
2625
3901
  function checkPackagesPack(ctx) {
2626
3902
  let packages;
2627
3903
  try {
@@ -2637,13 +3913,14 @@ function checkPackagesPack(ctx) {
2637
3913
  ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
2638
3914
  }
2639
3915
  for (const pkg of packages) {
2640
- const json = JSON.parse(readFileSync(path14.join(pkg.dir, "package.json"), "utf8"));
3916
+ const json = JSON.parse(readFileSync(path18.join(pkg.dir, "package.json"), "utf8"));
2641
3917
  checkImports2(ctx, pkg, json);
2642
3918
  checkExports(ctx, pkg, json);
2643
3919
  checkBlocks(ctx, pkg, json);
2644
3920
  checkMigrations(ctx, pkg, json);
2645
3921
  checkTaggedTests(ctx, pkg);
2646
3922
  checkRegistered(ctx, pkg);
3923
+ checkDoctorDeclaration(ctx, pkg, json);
2647
3924
  if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
2648
3925
  }
2649
3926
  }
@@ -2808,30 +4085,30 @@ function gitView(root, dir, base) {
2808
4085
  const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
2809
4086
  if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
2810
4087
  const sql = (p) => p !== void 0 && p.endsWith(".sql");
2811
- const touched = new Set(untracked.split("\n").filter(sql));
4088
+ const touched2 = new Set(untracked.split("\n").filter(sql));
2812
4089
  const edited = [];
2813
4090
  for (const row of diff.split("\n").filter(Boolean)) {
2814
4091
  const [status, a, b] = row.split(" ");
2815
4092
  if (status.startsWith("R")) {
2816
- if (sql(b)) touched.add(b);
4093
+ if (sql(b)) touched2.add(b);
2817
4094
  if (sql(a)) edited.push({ file: a, status: "renamed" });
2818
4095
  continue;
2819
4096
  }
2820
4097
  if (!sql(a)) continue;
2821
- if (status.startsWith("A")) touched.add(a);
4098
+ if (status.startsWith("A")) touched2.add(a);
2822
4099
  else if (status.startsWith("M") || status.startsWith("T")) {
2823
- touched.add(a);
4100
+ touched2.add(a);
2824
4101
  edited.push({ file: a, status: "modified" });
2825
4102
  } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
2826
4103
  }
2827
- return { touched, edited };
4104
+ return { touched: touched2, edited };
2828
4105
  }
2829
4106
  function checkSupabasePack(ctx) {
2830
4107
  const settings = ctx.config.supabase ?? {};
2831
4108
  const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
2832
- const abs = path14.join(ctx.root, dir);
4109
+ const abs = path18.join(ctx.root, dir);
2833
4110
  if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
2834
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
4111
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path18.join(abs, n), "utf8")) }));
2835
4112
  const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
2836
4113
  const base = settings.base ?? DEFAULT_BASE;
2837
4114
  const view = gitView(ctx.root, dir, base);
@@ -2848,7 +4125,7 @@ function checkSupabasePack(ctx) {
2848
4125
  }
2849
4126
  }
2850
4127
  const since = settings.since;
2851
- const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
4128
+ const afterSince = (file) => since === void 0 || path18.posix.basename(file) >= since;
2852
4129
  if ("reason" in view && since === void 0) {
2853
4130
  ctx.report({
2854
4131
  rule: "migration-grants",
@@ -3100,7 +4377,7 @@ function checkDefinerSearchPath(ctx, migrations) {
3100
4377
  var UMBRELLA_PACKAGE = "@marktiderman/genesis";
3101
4378
  function readReleaseManifest(root) {
3102
4379
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
3103
- const file = dir && path14.join(dir, "dist", "versions.json");
4380
+ const file = dir && path18.join(dir, "dist", "versions.json");
3104
4381
  if (!file || !existsSync(file)) return null;
3105
4382
  return JSON.parse(readFileSync(file, "utf8"));
3106
4383
  }
@@ -3110,7 +4387,7 @@ function checkVersionSkew(ctx) {
3110
4387
  for (const [name, want] of Object.entries(manifest.packages)) {
3111
4388
  const dir = findPackageDir(ctx.root, name);
3112
4389
  if (!dir) continue;
3113
- const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
4390
+ const have = JSON.parse(readFileSync(path18.join(dir, "package.json"), "utf8")).version;
3114
4391
  if (have === want) continue;
3115
4392
  ctx.report({
3116
4393
  rule: "version-skew",
@@ -3121,12 +4398,12 @@ function checkVersionSkew(ctx) {
3121
4398
  });
3122
4399
  }
3123
4400
  }
3124
- var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
4401
+ var GENESIS2 = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
3125
4402
  var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
3126
4403
  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)$/;
3127
4404
  var readManifest = (dir) => {
3128
4405
  try {
3129
- return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
4406
+ return JSON.parse(readFileSync(path18.join(dir, "package.json"), "utf8"));
3130
4407
  } catch {
3131
4408
  return null;
3132
4409
  }
@@ -3140,18 +4417,18 @@ var real = (p) => {
3140
4417
  };
3141
4418
  var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
3142
4419
  function nodeModulesOf(dir) {
3143
- const parent = path14.dirname(dir);
3144
- return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
4420
+ const parent = path18.dirname(dir);
4421
+ return path18.basename(parent).startsWith("@") ? path18.dirname(parent) : parent;
3145
4422
  }
3146
4423
  function packagesIn(nodeModules) {
3147
4424
  if (!existsSync(nodeModules)) return [];
3148
4425
  const out = [];
3149
4426
  for (const entry of readdirSync(nodeModules)) {
3150
4427
  if (entry.startsWith(".")) continue;
3151
- const p = path14.join(nodeModules, entry);
4428
+ const p = path18.join(nodeModules, entry);
3152
4429
  if (entry.startsWith("@")) {
3153
4430
  try {
3154
- for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
4431
+ for (const sub of readdirSync(p)) out.push(path18.join(p, sub));
3155
4432
  } catch {
3156
4433
  }
3157
4434
  } else {
@@ -3163,7 +4440,7 @@ function packagesIn(nodeModules) {
3163
4440
  function genesisInstalls(root) {
3164
4441
  const copies = /* @__PURE__ */ new Map();
3165
4442
  const realRoot = real(root);
3166
- const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
4443
+ const rel = (abs) => path18.relative(realRoot, abs).split(path18.sep).join("/") || ".";
3167
4444
  const via = /* @__PURE__ */ new Map();
3168
4445
  const record = (real2, manifest, by, range, root2) => {
3169
4446
  let copy = copies.get(real2);
@@ -3183,7 +4460,7 @@ function genesisInstalls(root) {
3183
4460
  if (!manifest?.name) return;
3184
4461
  if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
3185
4462
  const realDir = real(dir);
3186
- if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
4463
+ if (GENESIS2.test(manifest.name)) record(realDir, manifest, by, range, kind);
3187
4464
  if (expanded.has(realDir)) return;
3188
4465
  expanded.add(realDir);
3189
4466
  queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
@@ -3208,7 +4485,7 @@ function genesisInstalls(root) {
3208
4485
  if (!dir) return null;
3209
4486
  if (!ownInstall || name in declared) return dir;
3210
4487
  const realDir = real(dir);
3211
- if (realDir.startsWith(realRoot + path14.sep)) return dir;
4488
+ if (realDir.startsWith(realRoot + path18.sep)) return dir;
3212
4489
  return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
3213
4490
  };
3214
4491
  const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
@@ -3216,7 +4493,7 @@ function genesisInstalls(root) {
3216
4493
  return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
3217
4494
  });
3218
4495
  const app = readManifest(root);
3219
- const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
4496
+ const ownInstall = LOCKFILES.some((f) => existsSync(path18.join(root, f)));
3220
4497
  const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
3221
4498
  const declaredDev = Object.entries(app?.devDependencies ?? {});
3222
4499
  const runtimeDeps = {
@@ -3227,11 +4504,11 @@ function genesisInstalls(root) {
3227
4504
  };
3228
4505
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
3229
4506
  walk("runtime", rootsOf(runtimeDeps, "the app"));
3230
- const top = path14.join(root, "node_modules");
4507
+ const top = path18.join(root, "node_modules");
3231
4508
  walk(
3232
4509
  "hoisted",
3233
4510
  packagesIn(top).filter((dir) => {
3234
- const name = path14.relative(top, dir).split(path14.sep).join("/");
4511
+ const name = path18.relative(top, dir).split(path18.sep).join("/");
3235
4512
  return !(name in runtimeDeps) && !(name in devDeps);
3236
4513
  }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
3237
4514
  );
@@ -3273,13 +4550,13 @@ function checkDuplicatePackages(ctx) {
3273
4550
  }
3274
4551
  }
3275
4552
  function checkPeerRanges(ctx) {
3276
- const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
4553
+ const rel = (abs) => path18.relative(ctx.root, abs).split(path18.sep).join("/");
3277
4554
  for (const copies of genesisInstalls(ctx.root).values()) {
3278
4555
  for (const copy of copies) {
3279
4556
  const dir = copy.absolutePath;
3280
4557
  const peers = readManifest(dir)?.peerDependencies ?? {};
3281
4558
  for (const [peer, range] of Object.entries(peers)) {
3282
- if (!GENESIS.test(peer)) continue;
4559
+ if (!GENESIS2.test(peer)) continue;
3283
4560
  const peerDir = findPackageDir(dir, peer);
3284
4561
  const installed = peerDir && readManifest(peerDir)?.version;
3285
4562
  if (!peerDir || !installed) continue;
@@ -3296,112 +4573,6 @@ function checkPeerRanges(ctx) {
3296
4573
  }
3297
4574
  }
3298
4575
  }
3299
- var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3300
- var STEMS = {
3301
- tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
3302
- "next-app": {
3303
- layout: /* @__PURE__ */ new Set(["layout"]),
3304
- index: /* @__PURE__ */ new Set(["page"]),
3305
- skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
3306
- },
3307
- "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
3308
- };
3309
- var NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
3310
- var HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
3311
- var COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
3312
- var RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
3313
- 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;
3314
- function routesDir(ctx) {
3315
- if (ctx.config.routesDir) return ctx.config.routesDir;
3316
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path14.join(ctx.root, d))) ?? null;
3317
- }
3318
- var key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
3319
- function flavorOf(dir, rels) {
3320
- const stems = rels.map((r) => r.split("/").pop());
3321
- if (stems.includes("__root")) return "tanstack";
3322
- if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
3323
- if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
3324
- return "tanstack";
3325
- }
3326
- function renders(code) {
3327
- const elements = renderedElements(code);
3328
- if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
3329
- const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
3330
- const named = COMPONENT_OPTION.exec(code)?.[1];
3331
- if (named && !definedHere(named)) return true;
3332
- if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
3333
- const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
3334
- return exported !== void 0 && !definedHere(exported);
3335
- }
3336
- function webRoutes(ctx) {
3337
- const dir = routesDir(ctx);
3338
- if (!dir) return [];
3339
- 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(/\.[^.]+$/, "") }));
3340
- const flavor = flavorOf(dir, candidates.map((c) => c.rel));
3341
- const stems = STEMS[flavor];
3342
- const groups = /* @__PURE__ */ new Map();
3343
- for (const { file, rel } of candidates) {
3344
- const parts = rel.split("/");
3345
- if (parts.some((p) => p.startsWith("-"))) continue;
3346
- if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
3347
- if (flavor === "next-pages" && parts[0] === "api") continue;
3348
- if (stems.skip.test(parts.at(-1))) continue;
3349
- if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
3350
- const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
3351
- groups.set(id, [...groups.get(id) ?? [], file]);
3352
- }
3353
- const trail = trailFor(ctx);
3354
- const routes = [];
3355
- for (const [id, files] of groups) {
3356
- const parts = id.split("/");
3357
- const stem = parts.pop();
3358
- const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
3359
- const named = stems.layout.has(stem) || stems.index.has(stem);
3360
- const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
3361
- const segments = [...folders, ...own];
3362
- const tree = [...parts, ...own];
3363
- let index = stems.index.has(stem);
3364
- if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
3365
- segments.pop();
3366
- tree.pop();
3367
- index = true;
3368
- }
3369
- const code = files.map((f) => f.code).join("\n");
3370
- const elements = renderedElements(code);
3371
- const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
3372
- const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
3373
- const layout = stems.layout.has(stem) || pathless || outlet;
3374
- const rendering = renders(code);
3375
- const ownContent = new RegExp(OWN_CONTENT).test(code);
3376
- const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
3377
- const page = !pure && !pathless && (!layout || ownContent);
3378
- routes.push({
3379
- file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
3380
- files,
3381
- segments,
3382
- tree,
3383
- index,
3384
- layout,
3385
- page,
3386
- detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
3387
- redirectOnly: !rendering,
3388
- parents: []
3389
- });
3390
- }
3391
- for (const r of routes) {
3392
- const own = r.tree;
3393
- for (const p of routes) {
3394
- if (p === r || !p.layout) continue;
3395
- const n = p.tree.length;
3396
- if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
3397
- if (key(own.slice(0, n)) !== key(p.tree)) continue;
3398
- if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
3399
- r.parents.push(p);
3400
- }
3401
- r.parents.sort((a, b) => b.tree.length - a.tree.length);
3402
- }
3403
- return routes;
3404
- }
3405
4576
 
3406
4577
  // src/doctor/structure.ts
3407
4578
  var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/ui/SKILL.md (Sub-navigation)";
@@ -3412,7 +4583,7 @@ var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
3412
4583
  var PAGE_LAYOUT = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)|ResourceView)$/;
3413
4584
  var EMBEDDED_RESOURCE_VIEW = /<ResourceView\b[^>]*?\blayout\s*=\s*(?:(["'`]) {8}\1|\{\s*(["'`]) {8}\2\s*\})[^>]*>/g;
3414
4585
  var PACKAGE_SCREEN = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)|ResourceView)$/;
3415
- var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
4586
+ var isNative2 = (ctx) => ctx.config.packs?.includes("native") ?? false;
3416
4587
  var rendersRe = (names) => {
3417
4588
  const list = [...names];
3418
4589
  return list.length ? new RegExp(`<(?:${list.map((n) => n.replace(/[.$]/g, "\\$&")).join("|")})(?=[\\s>/])`) : null;
@@ -3434,7 +4605,7 @@ function insideShell(ctx, routes) {
3434
4605
  return (r) => !shell.has(r) && (anyShell || r.parents.some((p) => shell.has(p)));
3435
4606
  }
3436
4607
  function checkHandRolledSubNav(ctx) {
3437
- if (isNative(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
4608
+ if (isNative2(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
3438
4609
  const routes = webRoutes(ctx);
3439
4610
  if (routes.length === 0) return;
3440
4611
  const inShell = insideShell(ctx, routes);
@@ -3491,7 +4662,7 @@ function checkLocalGenesisCopies(ctx) {
3491
4662
  }
3492
4663
  }
3493
4664
  function checkResourceWorkspaces(ctx) {
3494
- if (isNative(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
4665
+ if (isNative2(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
3495
4666
  const header = /<AppShellPageHeader(?=[\s>/])/;
3496
4667
  const byFolder = /* @__PURE__ */ new Map();
3497
4668
  for (const r of webRoutes(ctx)) {
@@ -3516,7 +4687,7 @@ function checkResourceWorkspaces(ctx) {
3516
4687
  }
3517
4688
  }
3518
4689
  function checkPageLayouts(ctx) {
3519
- if (isNative(ctx)) return;
4690
+ if (isNative2(ctx)) return;
3520
4691
  const layouts = new Set(ctx.genesis.components.filter((n) => PAGE_LAYOUT.test(n)));
3521
4692
  for (const c of ctx.genesis.companions) for (const n of c.components) if (PAGE_LAYOUT.test(n)) layouts.add(n);
3522
4693
  if (layouts.size === 0) return;
@@ -3569,16 +4740,16 @@ function checkIsoDateSlices(ctx) {
3569
4740
  var IMPORTS_GENESIS = /\bfrom\s*["']@marktiderman\/genesis[\w/-]*["']/;
3570
4741
  function maskComments(text) {
3571
4742
  const out = text.split("");
3572
- let quote = null;
4743
+ let quote2 = null;
3573
4744
  for (let i = 0; i < text.length; i++) {
3574
4745
  const ch = text[i];
3575
- if (quote) {
4746
+ if (quote2) {
3576
4747
  if (ch === "\\") i++;
3577
- else if (ch === quote) quote = null;
4748
+ else if (ch === quote2) quote2 = null;
3578
4749
  continue;
3579
4750
  }
3580
4751
  if (ch === '"' || ch === "'" || ch === "`") {
3581
- quote = ch;
4752
+ quote2 = ch;
3582
4753
  continue;
3583
4754
  }
3584
4755
  if (ch === "/" && (text[i + 1] === "/" || text[i + 1] === "*")) {
@@ -3603,15 +4774,15 @@ function importedFromGenesis(text, name) {
3603
4774
  var OPEN = { "(": ")", "{": "}", "[": "]" };
3604
4775
  function matching(text, open) {
3605
4776
  const stack = [];
3606
- let quote = null;
4777
+ let quote2 = null;
3607
4778
  for (let i = open; i < text.length; i++) {
3608
4779
  const ch = text[i];
3609
- if (quote) {
4780
+ if (quote2) {
3610
4781
  if (ch === "\\") i++;
3611
- else if (ch === quote) quote = null;
4782
+ else if (ch === quote2) quote2 = null;
3612
4783
  continue;
3613
4784
  }
3614
- if (ch === '"' || ch === "'" || ch === "`") quote = ch;
4785
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
3615
4786
  else if (OPEN[ch]) stack.push(OPEN[ch]);
3616
4787
  else if (ch === ")" || ch === "}" || ch === "]") {
3617
4788
  stack.pop();
@@ -3658,16 +4829,16 @@ function tagSpans(text, tag) {
3658
4829
  const out = [];
3659
4830
  for (const m of text.matchAll(new RegExp(`<${tag}\\b`, "g"))) {
3660
4831
  let depth = 0;
3661
- let quote = null;
4832
+ let quote2 = null;
3662
4833
  let end = text.length;
3663
4834
  for (let i = m.index + 1; i < text.length; i++) {
3664
4835
  const ch = text[i];
3665
- if (quote) {
4836
+ if (quote2) {
3666
4837
  if (ch === "\\") i++;
3667
- else if (ch === quote) quote = null;
4838
+ else if (ch === quote2) quote2 = null;
3668
4839
  continue;
3669
4840
  }
3670
- if (ch === '"' || ch === "'" || ch === "`") quote = ch;
4841
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
3671
4842
  else if (ch === "{") depth++;
3672
4843
  else if (ch === "}") depth--;
3673
4844
  else if (ch === ">" && depth === 0) {
@@ -3755,17 +4926,17 @@ var PRACTICE_ID_AUGMENTATION = 'declare module "@marktiderman/genesis-core" { in
3755
4926
 
3756
4927
  // src/upgrade/codemods.ts
3757
4928
  var SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
3758
- var SCRIPT = /\.(?:[cm]?[jt]sx?)$/;
4929
+ var SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
3759
4930
  var MAX_BYTES = 2 * 1024 * 1024;
3760
4931
  function appScripts(root) {
3761
4932
  const out = [];
3762
4933
  const walk = (dir) => {
3763
4934
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
3764
- const abs = path14.join(dir, entry.name);
4935
+ const abs = path18.join(dir, entry.name);
3765
4936
  if (entry.isDirectory()) {
3766
4937
  if (!SKIP_DIRS3.has(entry.name)) walk(abs);
3767
- } else if (entry.isFile() && SCRIPT.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
3768
- out.push(path14.relative(root, abs).split(path14.sep).join("/"));
4938
+ } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
4939
+ out.push(path18.relative(root, abs).split(path18.sep).join("/"));
3769
4940
  }
3770
4941
  }
3771
4942
  };
@@ -3777,15 +4948,15 @@ function appScripts(root) {
3777
4948
  var SCRIPT_EXTS5 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
3778
4949
  function openingTag(code, start) {
3779
4950
  let depth = 0;
3780
- let quote = null;
4951
+ let quote2 = null;
3781
4952
  for (let i = start + 1; i < code.length; i++) {
3782
4953
  const ch = code[i];
3783
- if (quote) {
4954
+ if (quote2) {
3784
4955
  if (ch === "\\") i++;
3785
- else if (ch === quote) quote = null;
4956
+ else if (ch === quote2) quote2 = null;
3786
4957
  continue;
3787
4958
  }
3788
- if (ch === '"' || ch === "'" || ch === "`") quote = ch;
4959
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
3789
4960
  else if (ch === "{") depth++;
3790
4961
  else if (ch === "}") depth--;
3791
4962
  else if (ch === ">" && depth === 0) return code.slice(start, i + 1);
@@ -3794,25 +4965,25 @@ function openingTag(code, start) {
3794
4965
  }
3795
4966
  function ownAttributes(tag) {
3796
4967
  let depth = 0;
3797
- let quote = null;
4968
+ let quote2 = null;
3798
4969
  let out = "";
3799
4970
  let inner = "";
3800
4971
  for (let i = 0; i < tag.length; i++) {
3801
4972
  const ch = tag[i];
3802
4973
  if (depth > 0) inner += ch;
3803
- if (quote) {
4974
+ if (quote2) {
3804
4975
  if (ch === "\\") {
3805
4976
  i++;
3806
4977
  if (depth > 0) inner += tag[i] ?? "";
3807
4978
  else out += ch + (tag[i] ?? "");
3808
4979
  continue;
3809
4980
  }
3810
- if (ch === quote) quote = null;
4981
+ if (ch === quote2) quote2 = null;
3811
4982
  if (depth === 0) out += ch;
3812
4983
  continue;
3813
4984
  }
3814
4985
  if (ch === '"' || ch === "'" || ch === "`") {
3815
- quote = ch;
4986
+ quote2 = ch;
3816
4987
  if (depth === 0) out += ch;
3817
4988
  } else if (ch === "{") {
3818
4989
  if (depth === 0) inner = "";
@@ -3853,7 +5024,7 @@ var ROOT_REQUIRE = /\brequire\s*\(\s*["']@marktiderman\/genesis-studio-server["'
3853
5024
  function moduleFiles(ctx) {
3854
5025
  const scanned = new Set(ctx.files.map((f) => f.path));
3855
5026
  const ignored = globMatcher([...DEFAULT_IGNORE, ...ctx.config.ignore ?? []]);
3856
- 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) }));
5027
+ 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) }));
3857
5028
  return [...ctx.files.filter((f) => SCRIPT_EXTS5.has(f.ext)), ...extra];
3858
5029
  }
3859
5030
  function checkStudioServerImports(ctx) {
@@ -3889,7 +5060,7 @@ var REMOVED_WORDS = {
3889
5060
  };
3890
5061
  function checkRemovedScopeNames(ctx) {
3891
5062
  let augmentedMemo;
3892
- 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")));
5063
+ 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")));
3893
5064
  for (const file of ctx.files) {
3894
5065
  if (!SCRIPT_EXTS5.has(file.ext)) continue;
3895
5066
  for (const hit of findRemovedScopeNames(file.code)) {
@@ -3916,23 +5087,346 @@ function checkRemovedScopeNames(ctx) {
3916
5087
  }
3917
5088
  }
3918
5089
  }
3919
-
3920
- // src/doctor/index.ts
5090
+ function git3(root, args) {
5091
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
5092
+ return r.status === 0 ? r.stdout : null;
5093
+ }
5094
+ function changedSince(root, base) {
5095
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
5096
+ if (!mergeBase) return null;
5097
+ const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
5098
+ const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
5099
+ if (committed === null || untracked === null) return null;
5100
+ return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
5101
+ }
5102
+ var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
5103
+ function showAt(dir, rev, file) {
5104
+ const at = `${rev}:./${file}`;
5105
+ if (git3(dir, ["cat-file", "-e", at]) === null) return void 0;
5106
+ return git3(dir, ["show", at]);
5107
+ }
5108
+ function configAtBase(root, base, explicitFile) {
5109
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
5110
+ if (!mergeBase) return null;
5111
+ const candidates = explicitFile ? [{ dir: path18.dirname(explicitFile), file: path18.basename(explicitFile), explicit: true }] : [
5112
+ { dir: root, file: "genesis.config.json", explicit: false },
5113
+ { dir: root, file: "package.json", explicit: false }
5114
+ ];
5115
+ for (const c of candidates) {
5116
+ const text = showAt(c.dir, mergeBase, c.file);
5117
+ if (text === null) return null;
5118
+ if (text === void 0) continue;
5119
+ let block;
5120
+ try {
5121
+ block = doctorBlock(JSON.parse(text), c.file, c.explicit);
5122
+ } catch {
5123
+ return null;
5124
+ }
5125
+ if (block === void 0 || c.file === "package.json" && !c.explicit && isPackageDeclaration(block)) {
5126
+ if (c.file === "genesis.config.json") return "absent";
5127
+ continue;
5128
+ }
5129
+ const b = objectOr(block);
5130
+ return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
5131
+ }
5132
+ return "absent";
5133
+ }
5134
+ var allowKey = (a) => `${a.rule}\0${a.file ?? ""}\0${a.match ?? ""}`;
5135
+ function allowGrew(allow, before, base) {
5136
+ const had = new Set(before.map(allowKey));
5137
+ return allow.filter((a) => !had.has(allowKey(a))).map((a) => ({
5138
+ rule: "allow-grew",
5139
+ file: a.file ?? "genesis config",
5140
+ subject: a.rule,
5141
+ message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
5142
+ }));
5143
+ }
5144
+ var RANK = { off: 0, info: 1, warn: 2, error: 3 };
5145
+ function rulesWeakened(config, before, base) {
5146
+ const out = [];
5147
+ const levelIn = (c, rule) => c.rules?.[rule] ?? c.packageRules?.[rule]?.level;
5148
+ const ids = /* @__PURE__ */ new Set([...Object.keys(config.rules ?? {}), ...Object.keys(config.packageRules ?? {})]);
5149
+ for (const rule of ids) {
5150
+ const set = levelIn(config, rule);
5151
+ if (set === void 0) continue;
5152
+ const was = levelIn(before, rule);
5153
+ if (was === void 0 ? set === "off" : RANK[set] < RANK[was]) {
5154
+ 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` });
5155
+ }
5156
+ }
5157
+ for (const [rule, setting] of Object.entries(config.packageRules ?? {})) {
5158
+ const had = new Set(before.packageRules[rule]?.exclude ?? []);
5159
+ const added = (setting.exclude ?? []).filter((g) => !had.has(g));
5160
+ if (added.length) {
5161
+ 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` });
5162
+ }
5163
+ }
5164
+ return out;
5165
+ }
5166
+ function touched(file, changed) {
5167
+ if (changed.has(file)) return true;
5168
+ const prefix = file.endsWith("/") ? file : `${file}/`;
5169
+ for (const c of changed) if (c.startsWith(prefix)) return true;
5170
+ return false;
5171
+ }
5172
+ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
5173
+ ...META_RULES,
5174
+ "stale-exception",
5175
+ "package-rule-override",
5176
+ "package-rules-invalid",
5177
+ "package-doctor-declaration",
5178
+ "plugin-error",
5179
+ "build",
5180
+ "agent-guide-stale",
5181
+ "contracts-stale"
5182
+ ]);
5183
+ function applyRatchet(findings, options) {
5184
+ const { config, newOnly, changed, base, isAppPath } = options;
5185
+ const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
5186
+ return findings.map((f) => {
5187
+ if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
5188
+ return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
5189
+ });
5190
+ }
5191
+ var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
5192
+ var DEFAULT_DATABASE_ENV = "DATABASE_URL";
5193
+ var shellArg = (s) => /^[\w./,@:+=-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
5194
+ var postgresSource = (schemas) => `Postgres (${schemas.join(", ")})`;
5195
+ async function postgresContract(url, schemas) {
5196
+ const { introspectPostgres: introspectPostgres2, emitContracts: emitContracts2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
5197
+ const { default: postgres } = await import('postgres');
5198
+ const sql = postgres(url, { max: 1, prepare: false, onnotice: () => {
5199
+ } });
5200
+ try {
5201
+ const tables = await introspectPostgres2(sql, schemas);
5202
+ return { content: emitContracts2(tables, { source: postgresSource(schemas) }), tables: tables.length };
5203
+ } finally {
5204
+ await sql.end();
5205
+ }
5206
+ }
5207
+ function contractSource(content) {
5208
+ return /^\/\/ Source: (.*)$/m.exec(content.slice(0, 2e3))?.[1]?.trim() ?? null;
5209
+ }
5210
+ function sourceSchemas(source) {
5211
+ const m = source === null ? null : /^Postgres \((.*)\)$/.exec(source);
5212
+ const schemas = m?.[1].split(",").map((s) => s.trim()).filter(Boolean);
5213
+ return schemas?.length ? schemas : null;
5214
+ }
5215
+ var lf = (text) => text.replace(/\r\n/g, "\n");
5216
+ async function checkContracts(ctx, read2 = postgresContract) {
5217
+ const settings = ctx.config.contracts;
5218
+ if (!settings) return;
5219
+ const out = settings.out ?? DEFAULT_CONTRACT_OUT;
5220
+ const env = settings.databaseEnv ?? DEFAULT_DATABASE_ENV;
5221
+ let current = null;
5222
+ try {
5223
+ current = lf(readFileSync(path18.join(ctx.root, out), "utf8"));
5224
+ } catch {
5225
+ current = null;
5226
+ }
5227
+ const source = current === null ? null : contractSource(current);
5228
+ if (source !== null && !source.startsWith("Postgres (")) {
5229
+ 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` });
5230
+ return;
5231
+ }
5232
+ const schemas = settings.schemas?.length ? settings.schemas : sourceSchemas(source) ?? ["public"];
5233
+ const url = process.env[env];
5234
+ if (!url) {
5235
+ 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)` });
5236
+ return;
5237
+ }
5238
+ let expected;
5239
+ try {
5240
+ expected = lf((await read2(url, schemas)).content);
5241
+ } catch (err) {
5242
+ const generation = err.name === "EmitError";
5243
+ const message = err.message.split("\n")[0];
5244
+ 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}` });
5245
+ return;
5246
+ }
5247
+ const target = path18.relative(process.cwd(), path18.join(ctx.root, out)) || out;
5248
+ const command = `genesis introspect -o ${shellArg(target)} -s ${shellArg(schemas.join(","))}${env === DEFAULT_DATABASE_ENV ? "" : ` --database-env ${shellArg(env)}`}`;
5249
+ if (current !== expected) {
5250
+ ctx.report({
5251
+ rule: "contracts-stale",
5252
+ file: out,
5253
+ message: current === null ? `doesn't exist; run ${command} and commit it` : `is out of date with the database; run ${command} and commit the result`
5254
+ });
5255
+ }
5256
+ }
5257
+ var GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
5258
+ var CORE = [
5259
+ {
5260
+ need: "anything, before building it",
5261
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the doctor\'s "Available but unused" list',
5262
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
5263
+ from: "genesis-cli"
5264
+ },
5265
+ {
5266
+ need: "a page inside the app shell",
5267
+ use: "a Genesis page layout (`DashboardPage`, `SettingsPage`, `FormPage`, `DetailPage`, from `@marktiderman/genesis-ui`) or `ResourceView` (from `@marktiderman/genesis-ui/data`)",
5268
+ import: "@marktiderman/genesis-ui",
5269
+ rule: "page-layout",
5270
+ from: "genesis-cli"
5271
+ },
5272
+ {
5273
+ need: "a button, input, table, dialog or other component",
5274
+ use: "the Genesis component, never the raw tag or a local copy",
5275
+ import: "@marktiderman/genesis-ui/<component>",
5276
+ rule: "raw-tag",
5277
+ from: "genesis-cli"
5278
+ },
5279
+ {
5280
+ need: "colors and spacing",
5281
+ use: "semantic tokens (`bg-primary`, `text-muted-foreground`), never literal colors",
5282
+ import: "@marktiderman/genesis-design-system",
5283
+ rule: "raw-color",
5284
+ from: "genesis-cli"
5285
+ },
5286
+ {
5287
+ need: "something no primitive covers",
5288
+ use: "write the gap up for Genesis (an issue or a proposal) first, then invent in the app, on Genesis primitives",
5289
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
5290
+ from: "genesis-cli"
5291
+ }
5292
+ ];
5293
+ function primitivesCatalog(packages) {
5294
+ const rows = [...CORE];
5295
+ for (const rule of preferRules(packages)) {
5296
+ rows.push({
5297
+ need: rule.need ?? rule.id.replace(/-/g, " "),
5298
+ use: rule.use,
5299
+ ...rule.import ? { import: rule.import } : {},
5300
+ ...rule.docs ? { docs: rule.docs } : {},
5301
+ rule: rule.ruleId,
5302
+ from: rule.package
5303
+ });
5304
+ }
5305
+ for (const p of packages) {
5306
+ for (const e of p.declaration?.primitives ?? []) {
5307
+ rows.push({ need: e.need, use: e.use, ...e.import ? { import: e.import } : {}, ...e.docs ? { docs: e.docs } : {}, from: p.name });
5308
+ }
5309
+ }
5310
+ return rows;
5311
+ }
5312
+ function primitivesSummary(packages) {
5313
+ const rules = preferRules(packages);
5314
+ const withPlugin = packages.filter((p) => p.declaration?.plugin);
5315
+ return { rules: rules.length + withPlugin.length, packages: (/* @__PURE__ */ new Set([...rules.map((r) => r.package), ...withPlugin.map((p) => p.name)])).size };
5316
+ }
5317
+ var cell = (s) => (s ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ").replace(/(`[^`]*`)|<([A-Za-z][\w.]*)>/g, (m, code, name) => code ?? `\`<${name}>\``);
5318
+ var importCell = (s) => `\`${s.replace(/`/g, "").replace(/\|/g, "\\|").replace(/\n/g, " ")}\``;
5319
+ function catalogTable(rows, options = {}) {
5320
+ const head = options.docs ? "| Need | Use | Import | Enforced by | Docs |\n| --- | --- | --- | --- | --- |" : "| Need | Use | Import |\n| --- | --- | --- |";
5321
+ const body = rows.map(
5322
+ (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) : ""} |`
5323
+ );
5324
+ return [head, ...body].join("\n");
5325
+ }
5326
+ var SKILL_PATH = ".claude/skills/genesis/SKILL.md";
5327
+ var AGENTS_START = "<!-- genesis-primitives:start -->";
5328
+ var AGENTS_END = "<!-- genesis-primitives:end -->";
5329
+ var RULES = [
5330
+ "Use the Genesis primitive for the need first: reuse, then extend, then invent (docs/FRAMEWORK.md, G1 to G6).",
5331
+ "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
5332
+ "A list screen is a view (`defineView`) rendered by `ResourceView`; a record page is `ResourceWorkspace`; on the phone, `NativeResourceView`.",
5333
+ "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.",
5334
+ "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
5335
+ "Run `genesis doctor` before you finish; it enforces these rules."
5336
+ ];
5337
+ function renderSkill(rows) {
5338
+ return [
5339
+ "---",
5340
+ "name: genesis",
5341
+ "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.",
5342
+ "---",
5343
+ "",
5344
+ "<!-- Generated by `genesis agents` from the installed Genesis packages. Don't edit; run `genesis agents` after upgrading Genesis. -->",
5345
+ "",
5346
+ "# Genesis primitives",
5347
+ "",
5348
+ ...RULES.map((r) => `- ${r}`),
5349
+ "",
5350
+ "## What to use for each need",
5351
+ "",
5352
+ catalogTable(rows, { docs: true }),
5353
+ "",
5354
+ "`genesis primitives` prints the same list; `genesis doctor` enforces the rules named above.",
5355
+ ""
5356
+ ].join("\n");
5357
+ }
5358
+ function renderAgentsBlock(rows) {
5359
+ return [
5360
+ AGENTS_START,
5361
+ "## Building with Genesis",
5362
+ "",
5363
+ "Generated by `genesis agents` from the installed Genesis packages. Don't edit this block; run `genesis agents` after upgrading Genesis.",
5364
+ "",
5365
+ `Before writing a screen, read \`${SKILL_PATH}\` (or run \`genesis primitives\`).`,
5366
+ "",
5367
+ ...RULES.map((r) => `- ${r}`),
5368
+ "",
5369
+ catalogTable(rows),
5370
+ AGENTS_END
5371
+ ].join("\n");
5372
+ }
5373
+ function blockSpan(text) {
5374
+ const s = text.indexOf(AGENTS_START);
5375
+ const e = text.indexOf(AGENTS_END);
5376
+ if (s < 0 && e < 0) return "absent";
5377
+ if (s < 0 || e < 0 || e < s || text.indexOf(AGENTS_START, s + 1) >= 0 || text.indexOf(AGENTS_END, e + 1) >= 0) return "broken";
5378
+ return { start: s, end: e + AGENTS_END.length };
5379
+ }
5380
+ function currentAgentsBlock(agents) {
5381
+ if (!agents) return null;
5382
+ const span = blockSpan(agents);
5383
+ if (span === "absent") return null;
5384
+ if (span === "broken") return "broken";
5385
+ return agents.slice(span.start, span.end).replace(/\r\n/g, "\n");
5386
+ }
5387
+ var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
5388
+ function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
5389
+ const rows = primitivesCatalog(packages);
5390
+ const skill = read(path18.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
5391
+ const block = currentAgentsBlock(read(path18.join(root, agentsFile)));
5392
+ return {
5393
+ skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
5394
+ agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
5395
+ };
5396
+ }
5397
+ function checkAgentGuide(ctx) {
5398
+ const state = agentGuideState(ctx.root, ctx.packages);
5399
+ if (state.skill === "missing" && state.agents === "missing") return;
5400
+ const fix = "run genesis agents and commit the result";
5401
+ if (state.skill !== "ok") {
5402
+ 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}` });
5403
+ }
5404
+ if (state.agents !== "ok") {
5405
+ const message = {
5406
+ missing: `has no genesis-primitives block; ${fix}`,
5407
+ 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}`,
5408
+ stale: `has a genesis-primitives block that doesn't match the installed Genesis packages; ${fix}`
5409
+ }[state.agents];
5410
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
5411
+ }
5412
+ }
3921
5413
  async function runDoctor(options = {}) {
3922
- const root = path14.resolve(options.root ?? process.cwd());
5414
+ const root = path18.resolve(options.root ?? process.cwd());
3923
5415
  const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
3924
5416
  const config = loaded.config;
3925
5417
  const genesis = options.genesis ?? loadGenesis(root, config);
3926
5418
  const files = scanFiles(root, config);
3927
5419
  const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
3928
5420
  const plugins = await loadPlugins(config.plugins, loaded.dir);
5421
+ const packages = discoverPackages(root);
5422
+ const packagePlugins = await packageRulesPlugins(packages);
3929
5423
  const builtinIds = new Set(BUILTIN_RULES);
3930
5424
  for (const p of config.patterns ?? []) {
3931
- if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
5425
+ 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`);
3932
5426
  }
3933
5427
  const raw = [];
3934
- const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
3935
- for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
5428
+ const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
5429
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
3936
5430
  try {
3937
5431
  await plugin.check(ctx);
3938
5432
  } catch (err) {
@@ -3944,7 +5438,34 @@ async function runDoctor(options = {}) {
3944
5438
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
3945
5439
  if (failure) raw.push(failure);
3946
5440
  }
3947
- const findings = applyConfig(raw, config);
5441
+ raw.push(...unknownPackageRuleSettings(config, packages, raw));
5442
+ const newOnly = /* @__PURE__ */ new Set([...patterns?.newOnly ?? [], ...preferRules(packages).filter((r) => r.newOnly).map((r) => r.ruleId)]);
5443
+ let changed = null;
5444
+ let skipped = false;
5445
+ if (options.base && (newOnly.size > 0 || config.ratchet)) {
5446
+ changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
5447
+ skipped ||= !changed;
5448
+ }
5449
+ const configFile = "file" in loaded ? loaded.file : null;
5450
+ const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
5451
+ let configSkipped = false;
5452
+ if (options.base && configFile) {
5453
+ const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
5454
+ if (before && before !== "absent") {
5455
+ raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
5456
+ raw.push(...rulesWeakened(config, before, options.base));
5457
+ }
5458
+ configSkipped = !before && guarded;
5459
+ }
5460
+ if (skipped || configSkipped) {
5461
+ raw.push(
5462
+ 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` }
5463
+ );
5464
+ }
5465
+ let findings = applyConfig(raw, config, packageRuleIds(packages));
5466
+ if (options.base && changed) {
5467
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path18.join(root, f)) });
5468
+ }
3948
5469
  const errors = findings.filter((f) => f.level === "error").length;
3949
5470
  const warnings = findings.filter((f) => f.level === "warn").length;
3950
5471
  const infos = findings.length - errors - warnings;
@@ -3955,12 +5476,13 @@ async function runDoctor(options = {}) {
3955
5476
  findings,
3956
5477
  unused: unusedComponents(ctx),
3957
5478
  ruleCount: (patterns?.count ?? 0) + plugins.length,
5479
+ primitives: primitivesSummary(packages),
3958
5480
  errors,
3959
5481
  warnings,
3960
5482
  infos
3961
5483
  };
3962
5484
  }
3963
- function builtinChecks(config) {
5485
+ function builtinChecks(config, options = {}) {
3964
5486
  const packs = {
3965
5487
  native: { name: "native", check: checkNativePack },
3966
5488
  supabase: { name: "supabase", check: checkSupabasePack },
@@ -3984,14 +5506,28 @@ function builtinChecks(config) {
3984
5506
  { name: "resource-view-trees", check: checkTreeViews },
3985
5507
  { name: "studio-server-imports", check: checkStudioServerImports },
3986
5508
  { name: "removed-scope-names", check: checkRemovedScopeNames },
3987
- ...(config.packs ?? []).map((p) => packs[p])
5509
+ { name: "agent-guide", check: checkAgentGuide },
5510
+ ...(config.packs ?? []).map((p) => packs[p]),
5511
+ ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
3988
5512
  ];
3989
5513
  }
3990
- function applyConfig(raw, config) {
5514
+ function applyConfig(raw, config, packageIds) {
3991
5515
  const allow = (config.allow ?? []).map((entry) => ({ entry, file: entry.file ? globToRegExp(entry.file) : null, used: false }));
3992
5516
  const out = [];
5517
+ const levelOf = (rule) => META_RULES.has(rule) ? void 0 : config.rules?.[rule] ?? config.packageRules?.[rule]?.level;
5518
+ for (const [rule, level] of Object.entries(config.rules ?? {})) {
5519
+ if (!packageIds.has(rule) || config.packageRules?.[rule]?.reason) continue;
5520
+ out.push({
5521
+ rule: "package-rule-override",
5522
+ level: "warn",
5523
+ file: "genesis config",
5524
+ line: 0,
5525
+ subject: rule,
5526
+ message: `rules sets the package rule ${rule} to "${level}" without a reason; move it to doctor.packageRules["${rule}"] with { "level": "${level}", "reason": "\u2026" }`
5527
+ });
5528
+ }
3993
5529
  for (const input of raw) {
3994
- const setting = config.rules?.[input.rule];
5530
+ const setting = levelOf(input.rule);
3995
5531
  if (setting === "off") continue;
3996
5532
  const finding = {
3997
5533
  rule: input.rule,
@@ -4002,7 +5538,7 @@ function applyConfig(raw, config) {
4002
5538
  ...input.subject !== void 0 ? { subject: input.subject } : {}
4003
5539
  };
4004
5540
  const exception = allow.find(
4005
- (a) => a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
5541
+ (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)
4006
5542
  );
4007
5543
  if (exception) {
4008
5544
  exception.used = true;
@@ -4012,7 +5548,7 @@ function applyConfig(raw, config) {
4012
5548
  }
4013
5549
  const staleLevel = config.rules?.["stale-exception"];
4014
5550
  for (const a of allow) {
4015
- if (staleLevel === "off" || a.used || config.rules?.[a.entry.rule] === "off") continue;
5551
+ if (staleLevel === "off" || a.used || levelOf(a.entry.rule) === "off") continue;
4016
5552
  out.push({
4017
5553
  rule: "stale-exception",
4018
5554
  level: staleLevel ?? "warn",
@@ -4033,6 +5569,7 @@ function formatReport(result) {
4033
5569
  lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
4034
5570
  }
4035
5571
  lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
5572
+ lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis primitives`);
4036
5573
  const info = result.infos ? `, ${result.infos} info` : "";
4037
5574
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
4038
5575
  return lines.join("\n");
@@ -4050,7 +5587,7 @@ function genesisDoctor(options = {}) {
4050
5587
  root = options.root ?? config.root;
4051
5588
  },
4052
5589
  async buildStart() {
4053
- const result = await runDoctor({ root, configPath: options.configPath, strict: options.strict });
5590
+ const result = await runDoctor({ root, configPath: options.configPath, strict: options.strict, contracts: false });
4054
5591
  if (!result.ok) this.error(`Genesis doctor found problems:
4055
5592
  ${formatProblems(result, options.strict)}`);
4056
5593
  if (result.warnings > 0) this.warn(formatReport(result));
@@ -4083,7 +5620,7 @@ ${formatProblems(result, options.strict)}`);
4083
5620
  running = true;
4084
5621
  try {
4085
5622
  genesis ??= loadGenesis(root, loadConfig(root, options.configPath).config);
4086
- const result = await runDoctor({ root, configPath: options.configPath, genesis });
5623
+ const result = await runDoctor({ root, configPath: options.configPath, genesis, contracts: false });
4087
5624
  if (result.errors > 0) {
4088
5625
  showError(`Genesis doctor found problems:
4089
5626
  ${formatProblems(result)}`);
@@ -4103,15 +5640,15 @@ ${formatProblems(result)}`);
4103
5640
  }
4104
5641
  }
4105
5642
  };
4106
- const explicit = /* @__PURE__ */ new Set([path14.join(root, "genesis.config.json"), ...options.configPath ? [path14.resolve(root, options.configPath)] : []]);
5643
+ const explicit = /* @__PURE__ */ new Set([path18.join(root, "genesis.config.json"), ...options.configPath ? [path18.resolve(root, options.configPath)] : []]);
4107
5644
  try {
4108
5645
  const { config } = loadConfig(root, options.configPath);
4109
- if (config.rulesDoc) explicit.add(path14.resolve(root, config.rulesDoc));
5646
+ if (config.rulesDoc) explicit.add(path18.resolve(root, config.rulesDoc));
4110
5647
  } catch {
4111
5648
  }
4112
5649
  const schedule = (file) => {
4113
- if (!explicit.has(path14.resolve(file))) {
4114
- const rel = path14.relative(root, file).split(path14.sep).join("/");
5650
+ if (!explicit.has(path18.resolve(file))) {
5651
+ const rel = path18.relative(root, file).split(path18.sep).join("/");
4115
5652
  if (rel.startsWith("..") || rel.includes("node_modules/")) return;
4116
5653
  }
4117
5654
  clearTimeout(timer);