@marktiderman/genesis-cli 1.13.2 → 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/doctor.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, readdirSync, statSync, realpathSync, lstatSync } from 'fs';
3
+ import { existsSync, readFileSync, readdirSync, statSync, realpathSync, mkdirSync, writeFileSync, 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/doctor/index.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 resolve14 = (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
+ resolve14(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()) resolve14(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 (path20) => res.some((re) => re.test(path20));
1088
+ return (path28) => res.some((re) => re.test(path28));
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) {
@@ -1207,14 +1932,14 @@ async function loadPlugins(specs, configDir) {
1207
1932
  }
1208
1933
  function resolvePlugin(id, configDir) {
1209
1934
  try {
1210
- if (id.startsWith(".") || path14.isAbsolute(id)) return resolveFrom(path14.resolve(configDir, id), configDir);
1935
+ if (id.startsWith(".") || path18.isAbsolute(id)) return resolveFrom(path18.resolve(configDir, id), configDir);
1211
1936
  return resolveFrom(id, configDir);
1212
1937
  } catch {
1213
1938
  throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
1214
1939
  }
1215
1940
  }
1216
1941
  function resolveFrom(id, from) {
1217
- return createRequire(path14.join(from, "noop.js")).resolve(id);
1942
+ return createRequire(path18.join(from, "noop.js")).resolve(id);
1218
1943
  }
1219
1944
  var BUILTIN_RULES = [
1220
1945
  "local-primitives",
@@ -1236,6 +1961,11 @@ var BUILTIN_RULES = [
1236
1961
  "page-layout",
1237
1962
  // dates
1238
1963
  "iso-date-slice",
1964
+ // Genesis API usage (api-usage.ts)
1965
+ "resource-view-tree",
1966
+ "studio-server-auth-import",
1967
+ "removed-scope-name",
1968
+ "scope-practice-id",
1239
1969
  // native pack
1240
1970
  "native-raw-primitive",
1241
1971
  "native-literal-color",
@@ -1259,7 +1989,19 @@ var BUILTIN_RULES = [
1259
1989
  "package-unversioned-change",
1260
1990
  "package-export-missing",
1261
1991
  "package-block-invalid",
1262
- "package-untagged-tests"
1992
+ "package-untagged-tests",
1993
+ "package-doctor-declaration",
1994
+ // package rules (package-rules.ts): the rules themselves are namespaced, e.g. ui/lists-use-resource-view
1995
+ "package-rules-invalid",
1996
+ "package-rule-override",
1997
+ // ratchet (ratchet.ts)
1998
+ "ratchet-skipped",
1999
+ "allow-grew",
2000
+ "rules-weakened",
2001
+ // agent guide (primitives.ts)
2002
+ "agent-guide-stale",
2003
+ // supabase pack: contracts (contracts.ts)
2004
+ "contracts-stale"
1263
2005
  ];
1264
2006
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
1265
2007
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -1277,7 +2019,7 @@ function importSpecifiers(file) {
1277
2019
  }
1278
2020
  function checkProjectLayout(ctx) {
1279
2021
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
1280
- if (existsSync(path14.join(ctx.root, dir))) {
2022
+ if (existsSync(path18.join(ctx.root, dir))) {
1281
2023
  ctx.report({
1282
2024
  rule: "local-primitives",
1283
2025
  file: dir,
@@ -1287,7 +2029,7 @@ function checkProjectLayout(ctx) {
1287
2029
  }
1288
2030
  }
1289
2031
  for (const file of STARTER_LEFTOVERS) {
1290
- if (existsSync(path14.join(ctx.root, file))) {
2032
+ if (existsSync(path18.join(ctx.root, file))) {
1291
2033
  ctx.report({
1292
2034
  rule: "starter-leftover",
1293
2035
  level: "warn",
@@ -1376,7 +2118,7 @@ function checkTokens(ctx) {
1376
2118
  }
1377
2119
  for (const pattern of ctx.config.tokenFiles ?? []) {
1378
2120
  if (/[*?]/.test(pattern)) continue;
1379
- const abs = path14.join(ctx.root, pattern);
2121
+ const abs = path18.join(ctx.root, pattern);
1380
2122
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
1381
2123
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
1382
2124
  }
@@ -1478,19 +2220,34 @@ function privacyApisFor(dependencies2) {
1478
2220
  var SCRIPT_EXTS2 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
1479
2221
  var JSX_EXTS2 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
1480
2222
  var RESOLVE_EXTS = [".tsx", ".ts", ".jsx", ".js"];
2223
+ function resolveLocal(root, fromFile, spec) {
2224
+ const bases = spec.startsWith(".") ? [path18.resolve(path18.dirname(fromFile), spec)] : [path18.join(root, spec.slice(2)), path18.join(root, "src", spec.slice(2))];
2225
+ for (const base of bases) {
2226
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path18.join(base, `index${e}`))].find(
2227
+ (p) => SCRIPT_EXTS2.has(path18.extname(p)) && existsSync(p)
2228
+ );
2229
+ if (hit) return hit;
2230
+ }
2231
+ return null;
2232
+ }
1481
2233
  function localImports(root, file) {
1482
2234
  const out = [];
1483
2235
  for (const m of file.code.matchAll(/\bfrom\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g)) {
1484
- const spec = m[1];
1485
- const bases = spec.startsWith(".") ? [path14.resolve(path14.dirname(file.absolutePath), spec)] : [path14.join(root, spec.slice(2)), path14.join(root, "src", spec.slice(2))];
1486
- for (const base of bases) {
1487
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path14.join(base, `index${e}`))].find(
1488
- (p) => SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p)
1489
- );
1490
- if (hit) {
1491
- out.push(hit);
1492
- break;
1493
- }
2236
+ const hit = resolveLocal(root, file.absolutePath, m[1]);
2237
+ if (hit) out.push(hit);
2238
+ }
2239
+ return out;
2240
+ }
2241
+ function localImportedNames(root, file) {
2242
+ const out = /* @__PURE__ */ new Map();
2243
+ const re = /\bimport\s+(?:type\s+)?([\w$]+)?\s*,?\s*(?:\{([^}]*)\})?\s*from\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g;
2244
+ for (const m of file.code.matchAll(re)) {
2245
+ const target = resolveLocal(root, file.absolutePath, m[3]);
2246
+ if (!target) continue;
2247
+ if (m[1]) out.set(m[1], { file: target, name: "default" });
2248
+ for (const part of (m[2] ?? "").split(",")) {
2249
+ const [imported, local] = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/);
2250
+ if (imported) out.set(local ?? imported, { file: target, name: imported });
1494
2251
  }
1495
2252
  }
1496
2253
  return out;
@@ -1504,15 +2261,15 @@ function readSource(abs) {
1504
2261
  }
1505
2262
  function tagEnd(code, start) {
1506
2263
  let depth = 0;
1507
- let quote = null;
2264
+ let quote2 = null;
1508
2265
  for (let i = start + 1; i < code.length; i++) {
1509
2266
  const ch = code[i];
1510
- if (quote) {
2267
+ if (quote2) {
1511
2268
  if (ch === "\\") i++;
1512
- else if (ch === quote) quote = null;
2269
+ else if (ch === quote2) quote2 = null;
1513
2270
  continue;
1514
2271
  }
1515
- if (ch === '"' || ch === "'" || ch === "`") quote = ch;
2272
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
1516
2273
  else if (ch === "{") depth++;
1517
2274
  else if (ch === "}") depth--;
1518
2275
  else if (ch === ">" && depth === 0) {
@@ -1649,7 +2406,7 @@ function checkCustomHeaders(ctx, pkg) {
1649
2406
  if (!JSX_EXTS3.has(file.ext)) continue;
1650
2407
  const code = file.code;
1651
2408
  const hidden = HIDES_HEADER.exec(code);
1652
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path14.posix.dirname(file.path), file.path);
2409
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path18.posix.dirname(file.path), file.path);
1653
2410
  const own = hidden ? ownHeader(code, pkg) : null;
1654
2411
  if (hidden && own) {
1655
2412
  reported.add(file.path);
@@ -1677,7 +2434,7 @@ function checkCustomHeaders(ctx, pkg) {
1677
2434
  }
1678
2435
  for (const file of ctx.files) {
1679
2436
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
1680
- const layout = hidingLayouts.get(path14.posix.dirname(file.path));
2437
+ const layout = hidingLayouts.get(path18.posix.dirname(file.path));
1681
2438
  const own = layout ? ownHeader(file.code, pkg) : null;
1682
2439
  if (!layout || !own) continue;
1683
2440
  ctx.report({
@@ -1699,13 +2456,13 @@ function isLoadingOnlyRoute(code) {
1699
2456
  }
1700
2457
  function routerRoot(ctx) {
1701
2458
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
1702
- return existsSync(path14.join(ctx.root, "src", "app")) ? "src/app" : "app";
2459
+ return existsSync(path18.join(ctx.root, "src", "app")) ? "src/app" : "app";
1703
2460
  }
1704
2461
  function checkScreenLayouts(ctx, pkg) {
1705
2462
  const layouts = nativeLayouts(pkg);
1706
2463
  if (layouts.length === 0) return;
1707
2464
  const rootDir = routerRoot(ctx);
1708
- if (!existsSync(path14.join(ctx.root, rootDir))) {
2465
+ if (!existsSync(path18.join(ctx.root, rootDir))) {
1709
2466
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
1710
2467
  return;
1711
2468
  }
@@ -1761,7 +2518,7 @@ var GENESIS_PLUGIN_IMPORT = /\bfrom\s*["']@marktiderman\/genesis-cli[^"']*["']|\
1761
2518
  function readExpoConfigs(root) {
1762
2519
  const out = [];
1763
2520
  for (const name of EXPO_CONFIGS) {
1764
- const abs = path14.join(root, name);
2521
+ const abs = path18.join(root, name);
1765
2522
  if (!existsSync(abs)) continue;
1766
2523
  const text = readFileSync(abs, "utf8");
1767
2524
  let json = null;
@@ -1795,13 +2552,13 @@ function pluginOptions(json, module) {
1795
2552
  return null;
1796
2553
  }
1797
2554
  function dependencies(root) {
1798
- const file = path14.join(root, "package.json");
2555
+ const file = path18.join(root, "package.json");
1799
2556
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
1800
2557
  const pkg = JSON.parse(readFileSync(file, "utf8"));
1801
2558
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
1802
2559
  }
1803
2560
  function runtimeDependencies(root) {
1804
- const file = path14.join(root, "package.json");
2561
+ const file = path18.join(root, "package.json");
1805
2562
  if (!existsSync(file)) return {};
1806
2563
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
1807
2564
  }
@@ -2175,14 +2932,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
2175
2932
  seen.add(file);
2176
2933
  const json = readJsonc(file);
2177
2934
  if (!json) return {};
2178
- const dir = path14.dirname(file);
2935
+ const dir = path18.dirname(file);
2179
2936
  let merged = {};
2180
2937
  const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
2181
2938
  for (const ext of parents) {
2182
2939
  if (typeof ext !== "string") continue;
2183
2940
  let target = null;
2184
- if (ext.startsWith(".") || path14.isAbsolute(ext)) {
2185
- const abs = path14.resolve(dir, ext);
2941
+ if (ext.startsWith(".") || path18.isAbsolute(ext)) {
2942
+ const abs = path18.resolve(dir, ext);
2186
2943
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2187
2944
  } else {
2188
2945
  const parts = ext.split("/");
@@ -2190,14 +2947,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
2190
2947
  const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
2191
2948
  if (pkgDir) {
2192
2949
  const sub = parts.slice(nameLength).join("/");
2193
- const abs = path14.join(pkgDir, sub || "tsconfig.json");
2950
+ const abs = path18.join(pkgDir, sub || "tsconfig.json");
2194
2951
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
2195
2952
  }
2196
2953
  }
2197
2954
  if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
2198
2955
  }
2199
2956
  const opts = json.compilerOptions ?? {};
2200
- if (typeof opts.baseUrl === "string") merged.baseUrl = path14.resolve(dir, opts.baseUrl);
2957
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path18.resolve(dir, opts.baseUrl);
2201
2958
  if (opts.paths && typeof opts.paths === "object") {
2202
2959
  merged.paths = opts.paths;
2203
2960
  merged.pathsDir = dir;
@@ -2208,7 +2965,7 @@ function aliases(root) {
2208
2965
  const table = [];
2209
2966
  let baseUrl = null;
2210
2967
  for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
2211
- const file = path14.join(root, name);
2968
+ const file = path18.join(root, name);
2212
2969
  if (!existsSync(file)) continue;
2213
2970
  const config = readTsconfig(root, file);
2214
2971
  baseUrl ??= config.baseUrl ?? null;
@@ -2216,22 +2973,22 @@ function aliases(root) {
2216
2973
  for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
2217
2974
  if (!Array.isArray(targets)) continue;
2218
2975
  const exact = !pattern.endsWith("*");
2219
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path14.join(base, String(t).replace(/\*$/, ""))) });
2976
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path18.join(base, String(t).replace(/\*$/, ""))) });
2220
2977
  }
2221
2978
  }
2222
- const pkg = readJsonc(path14.join(root, "package.json"));
2979
+ const pkg = readJsonc(path18.join(root, "package.json"));
2223
2980
  for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
2224
2981
  if (typeof target !== "string") continue;
2225
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path14.join(root, target.replace(/\*.*$/, ""))] });
2982
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path18.join(root, target.replace(/\*.*$/, ""))] });
2226
2983
  }
2227
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path14.join(root, "src") + path14.sep, root + path14.sep] });
2984
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path18.join(root, "src") + path18.sep, root + path18.sep] });
2228
2985
  return { table, baseUrl };
2229
2986
  }
2230
2987
  function resolveFile(base) {
2231
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path14.join(base, `index${e}`))];
2988
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path18.join(base, `index${e}`))];
2232
2989
  if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
2233
2990
  for (const p of tries) {
2234
- if (SCRIPT_EXTS2.has(path14.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
2991
+ if (SCRIPT_EXTS2.has(path18.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
2235
2992
  }
2236
2993
  return null;
2237
2994
  }
@@ -2245,13 +3002,13 @@ function createTrail(ctx) {
2245
3002
  const { table, baseUrl } = aliases(ctx.root);
2246
3003
  let declared = null;
2247
3004
  try {
2248
- const pkg = JSON.parse(readFileSync(path14.join(ctx.root, "package.json"), "utf8"));
3005
+ const pkg = JSON.parse(readFileSync(path18.join(ctx.root, "package.json"), "utf8"));
2249
3006
  declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
2250
3007
  } catch {
2251
3008
  declared = null;
2252
3009
  }
2253
3010
  const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
2254
- const read = (abs) => byPath.get(abs) ?? readSource(abs);
3011
+ const read2 = (abs) => byPath.get(abs) ?? readSource(abs);
2255
3012
  const importsCache = /* @__PURE__ */ new Map();
2256
3013
  const importsOf = (file) => {
2257
3014
  const hit = importsCache.get(file.absolutePath);
@@ -2276,17 +3033,17 @@ function createTrail(ctx) {
2276
3033
  if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
2277
3034
  let resolved = null;
2278
3035
  if (spec.startsWith(".")) {
2279
- resolved = resolveFile(path14.resolve(path14.dirname(file.absolutePath), spec));
3036
+ resolved = resolveFile(path18.resolve(path18.dirname(file.absolutePath), spec));
2280
3037
  if (!resolved) lost = true;
2281
3038
  } else {
2282
3039
  const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
2283
3040
  if (alias) {
2284
3041
  for (const t of alias.targets) {
2285
- resolved = resolveFile(alias.exact ? t : path14.join(t, spec.slice(alias.prefix.length)));
3042
+ resolved = resolveFile(alias.exact ? t : path18.join(t, spec.slice(alias.prefix.length)));
2286
3043
  if (resolved) break;
2287
3044
  }
2288
3045
  }
2289
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path14.join(baseUrl, spec));
3046
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path18.join(baseUrl, spec));
2290
3047
  if (!resolved) {
2291
3048
  const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
2292
3049
  if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
@@ -2328,7 +3085,7 @@ function createTrail(ctx) {
2328
3085
  cut.add(abs);
2329
3086
  continue;
2330
3087
  }
2331
- const target = read(abs);
3088
+ const target = read2(abs);
2332
3089
  if (!target) {
2333
3090
  unknown = true;
2334
3091
  continue;
@@ -2358,84 +3115,591 @@ function createTrail(ctx) {
2358
3115
  return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
2359
3116
  }
2360
3117
 
2361
- // src/doctor/packages.ts
2362
- var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
2363
- var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
2364
- var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
2365
- var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
2366
- var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
2367
- function sourceFiles(dir, rel = "") {
2368
- const out = [];
2369
- for (const entry of readdirSync(path14.join(dir, rel)).sort()) {
2370
- if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
2371
- const child = rel ? `${rel}/${entry}` : entry;
2372
- const stat = lstatSync(path14.join(dir, child));
2373
- if (stat.isSymbolicLink()) continue;
2374
- if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
2375
- else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3118
+ // src/blocks/discover.ts
3119
+ var INSTALL_ROOT_MARKERS = [".git", "pnpm-lock.yaml", "pnpm-workspace.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"];
3120
+ function installedGenesis(root) {
3121
+ const found = /* @__PURE__ */ new Map();
3122
+ let dir = path18.resolve(root);
3123
+ for (; ; ) {
3124
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path18.join(dir, m)));
3125
+ const scope = path18.join(dir, "node_modules", "@marktiderman");
3126
+ if (existsSync(scope)) {
3127
+ for (const entry of readdirSync(scope)) {
3128
+ const name = `@marktiderman/${entry}`;
3129
+ if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
3130
+ if (existsSync(path18.join(scope, entry, "package.json"))) found.set(name, path18.join(scope, entry));
3131
+ }
3132
+ }
3133
+ const parent = path18.dirname(dir);
3134
+ if (atInstallRoot || parent === dir) return found;
3135
+ dir = parent;
2376
3136
  }
2377
- return out;
2378
3137
  }
2379
- function packageName2(specifier) {
2380
- const parts = specifier.split("/");
2381
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3138
+ var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3139
+ var STEMS = {
3140
+ tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
3141
+ "next-app": {
3142
+ layout: /* @__PURE__ */ new Set(["layout"]),
3143
+ index: /* @__PURE__ */ new Set(["page"]),
3144
+ skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
3145
+ },
3146
+ "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
3147
+ };
3148
+ var NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
3149
+ var HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
3150
+ var COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
3151
+ var RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
3152
+ 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;
3153
+ function routesDir(ctx) {
3154
+ if (ctx.config.routesDir) return ctx.config.routesDir;
3155
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path18.join(ctx.root, d))) ?? null;
2382
3156
  }
2383
- function git(root, args) {
2384
- const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
2385
- return r.status === 0 ? r.stdout : null;
3157
+ var key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
3158
+ function flavorOf(dir, rels) {
3159
+ const stems = rels.map((r) => r.split("/").pop());
3160
+ if (stems.includes("__root")) return "tanstack";
3161
+ if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
3162
+ if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
3163
+ return "tanstack";
2386
3164
  }
2387
- function matchPattern(pattern, spec) {
2388
- const star = pattern.indexOf("*");
2389
- if (star < 0) return pattern === spec ? "" : null;
2390
- const head = pattern.slice(0, star);
2391
- const tail = pattern.slice(star + 1);
2392
- return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3165
+ function renders(code) {
3166
+ const elements = renderedElements(code);
3167
+ if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
3168
+ const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
3169
+ const named = COMPONENT_OPTION.exec(code)?.[1];
3170
+ if (named && !definedHere(named)) return true;
3171
+ if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
3172
+ const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
3173
+ return exported !== void 0 && !definedHere(exported);
2393
3174
  }
2394
- function tsconfigPaths(dir) {
2395
- const file = path14.join(dir, "tsconfig.json");
2396
- if (!existsSync(file)) return [];
2397
- try {
2398
- const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
2399
- const options = JSON.parse(text).compilerOptions ?? {};
2400
- const base = path14.resolve(dir, options.baseUrl ?? ".");
2401
- return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path14.resolve(base, t)) }));
2402
- } catch {
2403
- return [];
3175
+ function webRoutes(ctx) {
3176
+ const dir = routesDir(ctx);
3177
+ if (!dir) return [];
3178
+ 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(/\.[^.]+$/, "") }));
3179
+ const flavor = flavorOf(dir, candidates.map((c) => c.rel));
3180
+ const stems = STEMS[flavor];
3181
+ const groups = /* @__PURE__ */ new Map();
3182
+ for (const { file, rel } of candidates) {
3183
+ const parts = rel.split("/");
3184
+ if (parts.some((p) => p.startsWith("-"))) continue;
3185
+ if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
3186
+ if (flavor === "next-pages" && parts[0] === "api") continue;
3187
+ if (stems.skip.test(parts.at(-1))) continue;
3188
+ if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
3189
+ const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
3190
+ groups.set(id, [...groups.get(id) ?? [], file]);
2404
3191
  }
2405
- }
2406
- function checkImports2(ctx, pkg, json) {
2407
- const aliases2 = tsconfigPaths(pkg.dir);
2408
- const subpathImports = Object.keys(json.imports ?? {});
2409
- const viaAlias = (spec) => {
2410
- if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
2411
- for (const { pattern, targets } of aliases2) {
2412
- const hit = matchPattern(pattern, spec);
2413
- if (hit === null) continue;
2414
- return targets.some((t) => {
2415
- const rel = path14.relative(pkg.dir, t.replace("*", hit));
2416
- return !rel.startsWith("..") && !path14.isAbsolute(rel);
2417
- });
3192
+ const trail = trailFor(ctx);
3193
+ const routes = [];
3194
+ for (const [id, files] of groups) {
3195
+ const parts = id.split("/");
3196
+ const stem = parts.pop();
3197
+ const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
3198
+ const named = stems.layout.has(stem) || stems.index.has(stem);
3199
+ const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
3200
+ const segments = [...folders, ...own];
3201
+ const tree = [...parts, ...own];
3202
+ let index = stems.index.has(stem);
3203
+ if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
3204
+ segments.pop();
3205
+ tree.pop();
3206
+ index = true;
2418
3207
  }
2419
- return null;
2420
- };
2421
- const declared = /* @__PURE__ */ new Set([
2422
- json.name,
2423
- ...Object.keys(json.dependencies ?? {}),
2424
- ...Object.keys(json.peerDependencies ?? {}),
2425
- ...Object.keys(json.devDependencies ?? {}),
2426
- ...Object.keys(json.optionalDependencies ?? {})
2427
- ]);
2428
- for (const file of sourceFiles(pkg.dir)) {
2429
- const code = stripForImports(readFileSync(path14.join(pkg.dir, file), "utf8"));
2430
- if (code === null) continue;
2431
- const at = `${pkg.rel}/${file}`;
2432
- const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
2433
- let offset = 0;
2434
- code.split("\n").forEach((text, i) => {
2435
- const lineStart = offset;
2436
- offset += text.length + 1;
2437
- for (const m of text.matchAll(IMPORT)) {
2438
- const spec = m[1];
3208
+ const code = files.map((f) => f.code).join("\n");
3209
+ const elements = renderedElements(code);
3210
+ const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
3211
+ const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
3212
+ const layout = stems.layout.has(stem) || pathless || outlet;
3213
+ const rendering = renders(code);
3214
+ const ownContent = new RegExp(OWN_CONTENT).test(code);
3215
+ const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
3216
+ const page = !pure && !pathless && (!layout || ownContent);
3217
+ routes.push({
3218
+ file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
3219
+ files,
3220
+ segments,
3221
+ tree,
3222
+ index,
3223
+ layout,
3224
+ page,
3225
+ detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
3226
+ redirectOnly: !rendering,
3227
+ parents: []
3228
+ });
3229
+ }
3230
+ for (const r of routes) {
3231
+ const own = r.tree;
3232
+ for (const p of routes) {
3233
+ if (p === r || !p.layout) continue;
3234
+ const n = p.tree.length;
3235
+ if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
3236
+ if (key(own.slice(0, n)) !== key(p.tree)) continue;
3237
+ if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
3238
+ r.parents.push(p);
3239
+ }
3240
+ r.parents.sort((a, b) => b.tree.length - a.tree.length);
3241
+ }
3242
+ return routes;
3243
+ }
3244
+
3245
+ // src/doctor/package-rules.ts
3246
+ var PackageDeclarationError = class extends Error {
3247
+ name = "PackageDeclarationError";
3248
+ };
3249
+ var GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
3250
+ var ID = /^[a-z0-9][a-z0-9-]*$/;
3251
+ var LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
3252
+ var PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
3253
+ var FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
3254
+ var UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
3255
+ var PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
3256
+ var DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "primitives", "plugin", "$comment"]);
3257
+ var SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
3258
+ function ruleNamespace(packageName3) {
3259
+ const m = GENESIS.exec(packageName3);
3260
+ if (m) return m[1] ?? "genesis";
3261
+ return packageName3;
3262
+ }
3263
+ var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3264
+ var isStringList2 = (v) => Array.isArray(v) && v.every((x) => typeof x === "string" && x.trim() !== "");
3265
+ function toRegExp2(source, flags = "") {
3266
+ if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
3267
+ return new RegExp(source, flags);
3268
+ }
3269
+ function validateDeclaration(raw, packageName3, packageDir, ignored) {
3270
+ const fail = (msg) => {
3271
+ throw new PackageDeclarationError(`${packageName3}: genesis.doctor ${msg}`);
3272
+ };
3273
+ const unknownKey = (where2, key2, known) => {
3274
+ const msg = `${where2 ? `${where2} ` : ""}has an unknown key "${key2}"${known ? ` (known: ${[...known].filter((k) => k !== "$comment").join(", ")})` : ""}`;
3275
+ if (!ignored) return fail(msg);
3276
+ ignored.push(`${packageName3}: genesis.doctor ${msg}; ignored`);
3277
+ };
3278
+ const each = (list, check) => list.flatMap((item, i) => {
3279
+ if (!ignored) return [check(item, i)];
3280
+ try {
3281
+ return [check(item, i)];
3282
+ } catch (err) {
3283
+ if (!(err instanceof PackageDeclarationError)) throw err;
3284
+ ignored.push(`${err.message}; that entry is skipped`);
3285
+ return [];
3286
+ }
3287
+ });
3288
+ if (typeof raw === "string") {
3289
+ if (!packageDir) fail(`points at ${raw}, but the package folder is unknown`);
3290
+ const file = path18.resolve(packageDir, raw);
3291
+ if (!inside(packageDir, file)) fail(`points outside the package (${raw})`);
3292
+ if (!existsSync(file)) fail(`points at ${raw}, which doesn't exist (is it in package.json "files"?)`);
3293
+ let parsed;
3294
+ try {
3295
+ parsed = JSON.parse(readFileSync(file, "utf8"));
3296
+ } catch (err) {
3297
+ return fail(`file ${raw} is not valid JSON: ${err.message}`);
3298
+ }
3299
+ return validateDeclaration(parsed, packageName3, packageDir, ignored);
3300
+ }
3301
+ if (raw === false) fail(`is false; say why with { "enforce": false, "reason": "\u2026" }`);
3302
+ if (!isObject3(raw)) fail(`must be an object (or a path to a JSON file in the package)`);
3303
+ const c = raw;
3304
+ for (const key2 of Object.keys(c)) if (!DECLARATION_KEYS.has(key2)) unknownKey("", key2, DECLARATION_KEYS);
3305
+ const enforce = c.enforce === void 0 ? true : c.enforce;
3306
+ if (typeof enforce !== "boolean") fail(`enforce must be true or false`);
3307
+ if (c.reason !== void 0 && (typeof c.reason !== "string" || !c.reason.trim())) fail(`reason must be a sentence`);
3308
+ const prefer = c.prefer === void 0 ? [] : c.prefer;
3309
+ if (!Array.isArray(prefer)) fail(`prefer must be a list`);
3310
+ const primitives = c.primitives === void 0 ? [] : c.primitives;
3311
+ if (!Array.isArray(primitives)) fail(`primitives must be a list`);
3312
+ if (c.plugin !== void 0 && (typeof c.plugin !== "string" || !c.plugin.trim())) fail(`plugin must be a module path inside the package`);
3313
+ if (!enforce) {
3314
+ if (typeof c.reason !== "string") fail(`turns enforcement off without a reason; add "reason"`);
3315
+ if (prefer.length || c.plugin) fail(`turns enforcement off but declares rules; drop "enforce": false or the rules`);
3316
+ } else if (!prefer.length && !c.plugin) {
3317
+ fail(`declares no rules; add "prefer" rules or a "plugin", or say { "enforce": false, "reason": "\u2026" }`);
3318
+ }
3319
+ const ids = /* @__PURE__ */ new Set();
3320
+ const rules = each(prefer, (r, i) => validatePrefer(r, `prefer[${i}]`, fail, unknownKey));
3321
+ for (const r of rules) {
3322
+ if (ids.has(r.id)) fail(`defines the rule "${r.id}" twice`);
3323
+ ids.add(r.id);
3324
+ }
3325
+ const entries = each(primitives, (p, i) => {
3326
+ const where2 = `primitives[${i}]`;
3327
+ if (!isObject3(p)) return fail(`${where2} must be an object`);
3328
+ for (const key2 of Object.keys(p)) if (!PRIMITIVE_KEYS.has(key2)) unknownKey(where2, key2);
3329
+ for (const key2 of ["need", "use"]) if (typeof p[key2] !== "string" || !p[key2].trim()) fail(`${where2} needs "${key2}"`);
3330
+ for (const key2 of ["import", "docs"]) if (p[key2] !== void 0 && typeof p[key2] !== "string") fail(`${where2}.${key2} must be a string`);
3331
+ return p;
3332
+ });
3333
+ let plugin;
3334
+ if (typeof c.plugin === "string") {
3335
+ if (!packageDir) plugin = c.plugin;
3336
+ else {
3337
+ plugin = path18.resolve(packageDir, c.plugin);
3338
+ if (!inside(packageDir, plugin)) fail(`plugin points outside the package (${c.plugin})`);
3339
+ }
3340
+ }
3341
+ return {
3342
+ enforce,
3343
+ ...typeof c.reason === "string" ? { reason: c.reason } : {},
3344
+ prefer: rules,
3345
+ primitives: entries,
3346
+ ...plugin ? { plugin } : {}
3347
+ };
3348
+ }
3349
+ function validatePrefer(raw, where2, fail, unknownKey) {
3350
+ if (!isObject3(raw)) return fail(`${where2} must be an object`);
3351
+ const narrowing = (at2, key2, known) => fail(`${at2} has an unknown key "${key2}" (known: ${[...known].join(", ")})`);
3352
+ for (const key2 of Object.keys(raw)) if (!PREFER_KEYS.has(key2)) narrowing(where2, key2, PREFER_KEYS);
3353
+ if (typeof raw.id !== "string" || !ID.test(raw.id)) fail(`${where2} needs an "id" of lower-case words and dashes`);
3354
+ const at = `${where2} (${raw.id})`;
3355
+ for (const key2 of ["use", "why"]) if (typeof raw[key2] !== "string" || !raw[key2].trim()) fail(`${at} needs "${key2}"`);
3356
+ for (const key2 of ["need", "import", "docs"]) if (raw[key2] !== void 0 && typeof raw[key2] !== "string") fail(`${at}.${key2} must be a string`);
3357
+ if (raw.level !== void 0 && !LEVELS2.has(raw.level)) fail(`${at}.level must be "error", "warn" or "info"`);
3358
+ if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
3359
+ if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
3360
+ for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
3361
+ if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
3362
+ const forbid = raw.forbid;
3363
+ for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
3364
+ if (!forbid.jsx && !forbid.imports && !forbid.pattern) fail(`${at}.forbid needs jsx, imports or pattern`);
3365
+ 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`);
3366
+ if (forbid.imports !== void 0 && !isStringList2(forbid.imports)) fail(`${at}.forbid.imports must be a list of import specifiers`);
3367
+ if (forbid.pattern !== void 0) checkPattern(forbid.pattern, `${at}.forbid.pattern`, fail);
3368
+ if (raw.unless !== void 0) {
3369
+ if (!isObject3(raw.unless)) fail(`${at}.unless must be an object`);
3370
+ const unless = raw.unless;
3371
+ for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
3372
+ if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
3373
+ if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
3374
+ }
3375
+ return raw;
3376
+ }
3377
+ function checkPattern(v, where2, fail) {
3378
+ if (typeof v !== "string" || !v) fail(`${where2} must be a regular expression`);
3379
+ try {
3380
+ toRegExp2(v, "g");
3381
+ } catch (err) {
3382
+ fail(`${where2} is not a valid regular expression: ${err.message}`);
3383
+ }
3384
+ }
3385
+ var discoveryCache = /* @__PURE__ */ new Map();
3386
+ function readDeclaringPackage(dir, local) {
3387
+ const file = path18.join(dir, "package.json");
3388
+ let stamp;
3389
+ let real2;
3390
+ try {
3391
+ real2 = realpathSync(dir);
3392
+ stamp = `${real2}
3393
+ ${statSync(file).mtimeMs}
3394
+ ${local}`;
3395
+ } catch {
3396
+ return null;
3397
+ }
3398
+ const hit = discoveryCache.get(stamp);
3399
+ if (hit) return hit;
3400
+ let json;
3401
+ try {
3402
+ json = JSON.parse(readFileSync(file, "utf8"));
3403
+ } catch {
3404
+ return null;
3405
+ }
3406
+ if (typeof json.name !== "string" || !json.name) return null;
3407
+ const pkg = {
3408
+ name: json.name,
3409
+ version: typeof json.version === "string" ? json.version : "0.0.0",
3410
+ dir: path18.resolve(dir),
3411
+ namespace: ruleNamespace(json.name),
3412
+ local,
3413
+ private: json.private === true,
3414
+ declaration: null
3415
+ };
3416
+ const raw = json.genesis?.doctor;
3417
+ if (raw !== void 0) {
3418
+ const ignored = [];
3419
+ try {
3420
+ pkg.declaration = validateDeclaration(raw, json.name, path18.resolve(dir), ignored);
3421
+ if (ignored.length) pkg.ignored = ignored;
3422
+ } catch (err) {
3423
+ pkg.error = err.message;
3424
+ }
3425
+ }
3426
+ discoveryCache.set(stamp, pkg);
3427
+ return pkg;
3428
+ }
3429
+ function discoverPackages(root) {
3430
+ const byName = /* @__PURE__ */ new Map();
3431
+ const installed = [...installedGenesis(root).values()];
3432
+ for (const dir of installed) {
3433
+ const pkg = readDeclaringPackage(dir, false);
3434
+ if (pkg) byName.set(pkg.name, pkg);
3435
+ }
3436
+ for (const dir of installed) {
3437
+ let scope;
3438
+ try {
3439
+ scope = path18.dirname(realpathSync(dir));
3440
+ } catch {
3441
+ continue;
3442
+ }
3443
+ if (path18.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
3444
+ for (const entry of readdirSync(scope)) {
3445
+ if (byName.has(`@marktiderman/${entry}`) || !GENESIS.test(`@marktiderman/${entry}`)) continue;
3446
+ const pkg = readDeclaringPackage(path18.join(scope, entry), false);
3447
+ if (pkg) byName.set(pkg.name, pkg);
3448
+ }
3449
+ }
3450
+ let local = [];
3451
+ try {
3452
+ local = localPackages(root);
3453
+ } catch {
3454
+ }
3455
+ for (const l of local) {
3456
+ const pkg = readDeclaringPackage(l.dir, true);
3457
+ if (pkg) byName.set(pkg.name, pkg);
3458
+ }
3459
+ return [...byName.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3460
+ }
3461
+ function clearPackageRulesCache() {
3462
+ discoveryCache.clear();
3463
+ }
3464
+ function preferRules(packages) {
3465
+ return packages.flatMap(
3466
+ (p) => (p.declaration?.prefer ?? []).map((r) => ({ ...r, ruleId: `${p.namespace}/${r.id}`, package: p.name, packageDir: p.dir }))
3467
+ );
3468
+ }
3469
+ var specMatcher = (s) => s.endsWith("*") ? (spec) => spec.startsWith(s.slice(0, -1)) : (spec) => spec === s;
3470
+ function compile(rule, setting, routes) {
3471
+ const expand = (globs) => globs.flatMap((g) => {
3472
+ if (!g.includes("{routes}")) return [g];
3473
+ return routes ? [g.replaceAll("{routes}", routes)] : [];
3474
+ });
3475
+ const files = expand(setting?.files ?? rule.files ?? SCRIPT_GLOBS);
3476
+ if (files.length === 0) return null;
3477
+ return {
3478
+ rule,
3479
+ level: rule.level ?? "warn",
3480
+ includes: globMatcher(files),
3481
+ excludes: globMatcher(expand(setting?.exclude ?? rule.exclude ?? [])),
3482
+ jsx: new Set(rule.forbid.jsx ?? []),
3483
+ imports: (rule.forbid.imports ?? []).map(specMatcher),
3484
+ ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
3485
+ unlessRenders: new Set(rule.unless?.renders ?? []),
3486
+ ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
3487
+ };
3488
+ }
3489
+ var JSX = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
3490
+ var ELEMENT = /(?<![\w$.])<([A-Z][\w.]*)(?=[\s>/<])/g;
3491
+ var SCRIPT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
3492
+ function messageFor(rule, found) {
3493
+ const from = rule.import ? ` (${rule.import})` : "";
3494
+ const docs = rule.docs ? ` See ${rule.docs}` : "";
3495
+ return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
3496
+ }
3497
+ var TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
3498
+ var EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
3499
+ var EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
3500
+ function wrappersIn(file, elements, c) {
3501
+ const out = /* @__PURE__ */ new Map();
3502
+ const decls = [...file.code.matchAll(TOP_LEVEL)];
3503
+ const listed = /* @__PURE__ */ new Map();
3504
+ for (const m of file.code.matchAll(EXPORT_LIST)) {
3505
+ for (const part of m[1].split(",")) {
3506
+ const [local, exported] = part.trim().split(/\s+as\s+/);
3507
+ if (local) listed.set(local, [...listed.get(local) ?? [], exported ?? local]);
3508
+ }
3509
+ }
3510
+ for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
3511
+ decls.forEach((d, i) => {
3512
+ const name = d[3];
3513
+ if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
3514
+ const end = decls[i + 1]?.index ?? file.code.length;
3515
+ const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
3516
+ if (!hit) return;
3517
+ const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
3518
+ for (const n of names) out.set(n, hit[1]);
3519
+ });
3520
+ return out;
3521
+ }
3522
+ function runPrefer(ctx, c) {
3523
+ const own = c.rule.packageDir;
3524
+ const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
3525
+ const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
3526
+ const wrappers = /* @__PURE__ */ new Map();
3527
+ const renderedBy = /* @__PURE__ */ new Map();
3528
+ for (const file of checked) {
3529
+ if (!JSX.has(file.ext)) continue;
3530
+ const elements = [...file.code.matchAll(ELEMENT)];
3531
+ renderedBy.set(file, elements);
3532
+ if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
3533
+ const found = wrappersIn(file, elements, c);
3534
+ if (found.size) wrappers.set(file.absolutePath, found);
3535
+ }
3536
+ for (const file of checked) {
3537
+ const elements = renderedBy.get(file) ?? [];
3538
+ if (exempt(file, elements.map((m) => m[1]))) continue;
3539
+ const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
3540
+ const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
3541
+ for (const m of elements) {
3542
+ const name = m[1];
3543
+ if (c.jsx.has(name)) {
3544
+ report(lineAt(file.code, m.index), name, `renders <${name}>`);
3545
+ continue;
3546
+ }
3547
+ const from = imported?.get(name.split(".")[0]);
3548
+ const around = from && !name.includes(".") ? wrappers.get(from.file)?.get(from.name) : void 0;
3549
+ if (around) report(lineAt(file.code, m.index), name, `renders <${name}>, an app wrapper around <${around}>`);
3550
+ }
3551
+ if (c.imports.length) {
3552
+ for (const { specifier, line } of importSpecifiers(file)) {
3553
+ if (c.imports.some((t) => t(specifier))) report(line, specifier, `imports ${specifier}`);
3554
+ }
3555
+ }
3556
+ if (c.pattern) {
3557
+ c.pattern.lastIndex = 0;
3558
+ for (const m of file.code.matchAll(c.pattern)) {
3559
+ const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
3560
+ report(lineAt(file.code, m.index), text, `has ${text}`);
3561
+ }
3562
+ }
3563
+ }
3564
+ }
3565
+ var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
3566
+ async function packageRulesPlugins(packages) {
3567
+ const out = [
3568
+ {
3569
+ name: "package-rules",
3570
+ check(ctx) {
3571
+ for (const p of packages) {
3572
+ const at = { rule: "package-rules-invalid", level: "warn", file: `${p.name}/package.json`, subject: p.name };
3573
+ if (p.error) ctx.report({ ...at, message: `${p.error}; its rules don't run` });
3574
+ for (const note of p.ignored ?? []) ctx.report({ ...at, message: `${note} (a newer @marktiderman/genesis-cli may read it)` });
3575
+ }
3576
+ const routes = routesDir(ctx);
3577
+ const settings = ctx.config.packageRules ?? {};
3578
+ for (const rule of preferRules(packages)) {
3579
+ if (rule.platform === "web" && isNative(ctx)) continue;
3580
+ if (rule.platform === "native" && !isNative(ctx)) continue;
3581
+ const compiled = compile(rule, settings[rule.ruleId], routes);
3582
+ if (compiled) runPrefer(ctx, compiled);
3583
+ }
3584
+ }
3585
+ }
3586
+ ];
3587
+ for (const p of packages) {
3588
+ const file = p.declaration?.plugin;
3589
+ if (!file) continue;
3590
+ let loaded;
3591
+ try {
3592
+ loaded = await loadPlugins([file], p.dir);
3593
+ } catch (err) {
3594
+ const message = err.message;
3595
+ 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 }) });
3596
+ continue;
3597
+ }
3598
+ for (const plugin of loaded) {
3599
+ out.push({
3600
+ name: `${p.namespace}/${plugin.name}`,
3601
+ check: (ctx) => plugin.check({
3602
+ ...ctx,
3603
+ report: (f) => ctx.report({ ...f, rule: f.rule.startsWith(`${p.namespace}/`) ? f.rule : `${p.namespace}/${f.rule}` })
3604
+ })
3605
+ });
3606
+ }
3607
+ }
3608
+ return out;
3609
+ }
3610
+ function unknownPackageRuleSettings(config, packages, reported) {
3611
+ const known = /* @__PURE__ */ new Set([...packageRuleIds(packages), ...reported.map((f) => f.rule)]);
3612
+ const plugins = packages.filter((p) => p.declaration?.plugin).map((p) => `${p.namespace}/`);
3613
+ return Object.keys(config.packageRules ?? {}).filter((id) => !known.has(id) && !plugins.some((ns) => id.startsWith(ns))).map((id) => ({
3614
+ rule: "stale-exception",
3615
+ level: "warn",
3616
+ file: "genesis config",
3617
+ subject: id,
3618
+ message: `packageRules names ${id}, which no installed package declares; check the id (genesis primitives lists them) or remove it`
3619
+ }));
3620
+ }
3621
+ function packageRuleIds(packages) {
3622
+ return new Set(preferRules(packages).map((r) => r.ruleId));
3623
+ }
3624
+
3625
+ // src/doctor/packages.ts
3626
+ var SOURCE = /\.(?:[cm]?[jt]sx?)$/;
3627
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
3628
+ var BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
3629
+ var IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
3630
+ var TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
3631
+ function sourceFiles(dir, rel = "") {
3632
+ const out = [];
3633
+ for (const entry of readdirSync(path18.join(dir, rel)).sort()) {
3634
+ if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
3635
+ const child = rel ? `${rel}/${entry}` : entry;
3636
+ const stat = lstatSync(path18.join(dir, child));
3637
+ if (stat.isSymbolicLink()) continue;
3638
+ if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
3639
+ else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
3640
+ }
3641
+ return out;
3642
+ }
3643
+ function packageName2(specifier) {
3644
+ const parts = specifier.split("/");
3645
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3646
+ }
3647
+ function git(root, args) {
3648
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
3649
+ return r.status === 0 ? r.stdout : null;
3650
+ }
3651
+ function matchPattern(pattern, spec) {
3652
+ const star = pattern.indexOf("*");
3653
+ if (star < 0) return pattern === spec ? "" : null;
3654
+ const head = pattern.slice(0, star);
3655
+ const tail = pattern.slice(star + 1);
3656
+ return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3657
+ }
3658
+ function tsconfigPaths(dir) {
3659
+ const file = path18.join(dir, "tsconfig.json");
3660
+ if (!existsSync(file)) return [];
3661
+ try {
3662
+ const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
3663
+ const options = JSON.parse(text).compilerOptions ?? {};
3664
+ const base = path18.resolve(dir, options.baseUrl ?? ".");
3665
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path18.resolve(base, t)) }));
3666
+ } catch {
3667
+ return [];
3668
+ }
3669
+ }
3670
+ function checkImports2(ctx, pkg, json) {
3671
+ const aliases2 = tsconfigPaths(pkg.dir);
3672
+ const subpathImports = Object.keys(json.imports ?? {});
3673
+ const viaAlias = (spec) => {
3674
+ if (spec.startsWith("#")) return subpathImports.some((k) => matchPattern(k, spec) !== null) ? true : null;
3675
+ for (const { pattern, targets } of aliases2) {
3676
+ const hit = matchPattern(pattern, spec);
3677
+ if (hit === null) continue;
3678
+ return targets.some((t) => {
3679
+ const rel = path18.relative(pkg.dir, t.replace("*", hit));
3680
+ return !rel.startsWith("..") && !path18.isAbsolute(rel);
3681
+ });
3682
+ }
3683
+ return null;
3684
+ };
3685
+ const declared = /* @__PURE__ */ new Set([
3686
+ json.name,
3687
+ ...Object.keys(json.dependencies ?? {}),
3688
+ ...Object.keys(json.peerDependencies ?? {}),
3689
+ ...Object.keys(json.devDependencies ?? {}),
3690
+ ...Object.keys(json.optionalDependencies ?? {})
3691
+ ]);
3692
+ for (const file of sourceFiles(pkg.dir)) {
3693
+ const code = stripForImports(readFileSync(path18.join(pkg.dir, file), "utf8"));
3694
+ if (code === null) continue;
3695
+ const at = `${pkg.rel}/${file}`;
3696
+ const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
3697
+ let offset = 0;
3698
+ code.split("\n").forEach((text, i) => {
3699
+ const lineStart = offset;
3700
+ offset += text.length + 1;
3701
+ for (const m of text.matchAll(IMPORT)) {
3702
+ const spec = m[1];
2439
3703
  const line = i + 1;
2440
3704
  const at0 = lineStart + m.index;
2441
3705
  if (typeOnly.some(([a, b]) => at0 >= a && at0 < b)) continue;
@@ -2451,9 +3715,9 @@ function checkImports2(ctx, pkg, json) {
2451
3715
  continue;
2452
3716
  }
2453
3717
  if (spec.startsWith(".")) {
2454
- const target = path14.resolve(pkg.dir, path14.dirname(file), spec);
2455
- const rel = path14.relative(pkg.dir, target);
2456
- if (rel.startsWith("..") || path14.isAbsolute(rel)) {
3718
+ const target = path18.resolve(pkg.dir, path18.dirname(file), spec);
3719
+ const rel = path18.relative(pkg.dir, target);
3720
+ if (rel.startsWith("..") || path18.isAbsolute(rel)) {
2457
3721
  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` });
2458
3722
  }
2459
3723
  continue;
@@ -2475,12 +3739,12 @@ function checkMigrations(ctx, pkg, json) {
2475
3739
  if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
2476
3740
  if (typeof m.file === "string" && typeof m.test !== "string") {
2477
3741
  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` });
2478
- } else if (typeof m.test === "string" && !existsSync(path14.join(pkg.dir, m.test))) {
3742
+ } else if (typeof m.test === "string" && !existsSync(path18.join(pkg.dir, m.test))) {
2479
3743
  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` });
2480
3744
  }
2481
3745
  }
2482
3746
  }
2483
- const dir = path14.join(pkg.dir, "migrations");
3747
+ const dir = path18.join(pkg.dir, "migrations");
2484
3748
  if (!existsSync(dir)) return;
2485
3749
  const seen = /* @__PURE__ */ new Map();
2486
3750
  for (const name of readdirSync(dir).sort()) {
@@ -2489,7 +3753,7 @@ function checkMigrations(ctx, pkg, json) {
2489
3753
  const other = seen.get(m[1]);
2490
3754
  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` });
2491
3755
  else seen.set(m[1], name);
2492
- if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path14.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
3756
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path18.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
2493
3757
  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")})` });
2494
3758
  }
2495
3759
  }
@@ -2503,7 +3767,7 @@ function checkExports(ctx, pkg, json) {
2503
3767
  walk(json.exports);
2504
3768
  for (const t of targets) {
2505
3769
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
2506
- if (!existsSync(path14.join(pkg.dir, t))) {
3770
+ if (!existsSync(path18.join(pkg.dir, t))) {
2507
3771
  ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
2508
3772
  }
2509
3773
  }
@@ -2521,11 +3785,11 @@ function checkBlocks(ctx, pkg, json) {
2521
3785
  function checkTaggedTests(ctx, pkg) {
2522
3786
  const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
2523
3787
  if (!tests.length) return;
2524
- const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path14.join(pkg.dir, f), "utf8")));
3788
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path18.join(pkg.dir, f), "utf8")));
2525
3789
  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>` });
2526
3790
  }
2527
3791
  function checkRegistered(ctx, pkg) {
2528
- const file = path14.join(ctx.root, "features.json");
3792
+ const file = path18.join(ctx.root, "features.json");
2529
3793
  if (!existsSync(file)) return;
2530
3794
  let doc;
2531
3795
  try {
@@ -2535,7 +3799,7 @@ function checkRegistered(ctx, pkg) {
2535
3799
  }
2536
3800
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
2537
3801
  const forms = /* @__PURE__ */ new Set([pkg.rel]);
2538
- if (top) forms.add(path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/"));
3802
+ if (top) forms.add(path18.relative(top, realpathSync(pkg.dir)).split(path18.sep).join("/"));
2539
3803
  const covered = (doc.features ?? []).some(
2540
3804
  (f) => (f.links?.code ?? []).some((c) => {
2541
3805
  const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -2565,9 +3829,9 @@ function mergeBaseOf(root, base) {
2565
3829
  function checkChanges(ctx, pkg, json, base, mergeBase) {
2566
3830
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
2567
3831
  if (!top) return;
2568
- const appRelative = (fromTop) => path14.relative(realpathSync(ctx.root), path14.join(top, fromTop)).split(path14.sep).join("/");
2569
- const inRepo = path14.relative(top, realpathSync(pkg.dir)).split(path14.sep).join("/");
2570
- 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");
3832
+ const appRelative = (fromTop) => path18.relative(realpathSync(ctx.root), path18.join(top, fromTop)).split(path18.sep).join("/");
3833
+ const inRepo = path18.relative(top, realpathSync(pkg.dir)).split(path18.sep).join("/");
3834
+ 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");
2571
3835
  const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
2572
3836
  const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
2573
3837
  (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
@@ -2589,11 +3853,11 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
2589
3853
  const now = typeof json.version === "string" ? parseVersion(json.version) : null;
2590
3854
  const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
2591
3855
  const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
2592
- 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)) : [];
3856
+ 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)) : [];
2593
3857
  const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
2594
3858
  const named = naming.length > 0;
2595
3859
  if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
2596
- 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` });
3860
+ 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` });
2597
3861
  }
2598
3862
  let jsonBefore = null;
2599
3863
  try {
@@ -2603,7 +3867,7 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
2603
3867
  }
2604
3868
  const raw = json;
2605
3869
  if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
2606
- const appInRepo = path14.relative(top, realpathSync(ctx.root)).split(path14.sep).join("/");
3870
+ const appInRepo = path18.relative(top, realpathSync(ctx.root)).split(path18.sep).join("/");
2607
3871
  const candidates = [.../* @__PURE__ */ new Set(["features.ts", "src/features.ts", ...appInRepo ? [`${appInRepo}/features.ts`, `${appInRepo}/src/features.ts`] : []])];
2608
3872
  const registry = (git(top, ["diff", "--name-only", mergeBase, "--", ...candidates]) ?? "").trim();
2609
3873
  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` });
@@ -2620,6 +3884,26 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
2620
3884
  });
2621
3885
  }
2622
3886
  }
3887
+ var GENESIS_NAME = /^@marktiderman\/genesis(?:-[a-z0-9-]+)?$/;
3888
+ function checkDoctorDeclaration(ctx, pkg, json) {
3889
+ if (json.private === true || !GENESIS_NAME.test(json.name)) return;
3890
+ const file = `${pkg.rel}/package.json`;
3891
+ const raw = json.genesis?.doctor;
3892
+ if (raw === void 0) {
3893
+ ctx.report({
3894
+ rule: "package-doctor-declaration",
3895
+ file,
3896
+ subject: json.name,
3897
+ message: `${json.name} declares no doctor rules; add genesis.doctor with the primitives it enforces ("prefer" rules), or { "enforce": false, "reason": "\u2026" }`
3898
+ });
3899
+ return;
3900
+ }
3901
+ try {
3902
+ validateDeclaration(raw, json.name, pkg.dir);
3903
+ } catch (err) {
3904
+ ctx.report({ rule: "package-doctor-declaration", file, subject: json.name, message: err.message });
3905
+ }
3906
+ }
2623
3907
  function checkPackagesPack(ctx) {
2624
3908
  let packages;
2625
3909
  try {
@@ -2635,13 +3919,14 @@ function checkPackagesPack(ctx) {
2635
3919
  ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
2636
3920
  }
2637
3921
  for (const pkg of packages) {
2638
- const json = JSON.parse(readFileSync(path14.join(pkg.dir, "package.json"), "utf8"));
3922
+ const json = JSON.parse(readFileSync(path18.join(pkg.dir, "package.json"), "utf8"));
2639
3923
  checkImports2(ctx, pkg, json);
2640
3924
  checkExports(ctx, pkg, json);
2641
3925
  checkBlocks(ctx, pkg, json);
2642
3926
  checkMigrations(ctx, pkg, json);
2643
3927
  checkTaggedTests(ctx, pkg);
2644
3928
  checkRegistered(ctx, pkg);
3929
+ checkDoctorDeclaration(ctx, pkg, json);
2645
3930
  if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
2646
3931
  }
2647
3932
  }
@@ -2806,30 +4091,30 @@ function gitView(root, dir, base) {
2806
4091
  const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
2807
4092
  if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
2808
4093
  const sql = (p) => p !== void 0 && p.endsWith(".sql");
2809
- const touched = new Set(untracked.split("\n").filter(sql));
4094
+ const touched2 = new Set(untracked.split("\n").filter(sql));
2810
4095
  const edited = [];
2811
4096
  for (const row of diff.split("\n").filter(Boolean)) {
2812
4097
  const [status, a, b] = row.split(" ");
2813
4098
  if (status.startsWith("R")) {
2814
- if (sql(b)) touched.add(b);
4099
+ if (sql(b)) touched2.add(b);
2815
4100
  if (sql(a)) edited.push({ file: a, status: "renamed" });
2816
4101
  continue;
2817
4102
  }
2818
4103
  if (!sql(a)) continue;
2819
- if (status.startsWith("A")) touched.add(a);
4104
+ if (status.startsWith("A")) touched2.add(a);
2820
4105
  else if (status.startsWith("M") || status.startsWith("T")) {
2821
- touched.add(a);
4106
+ touched2.add(a);
2822
4107
  edited.push({ file: a, status: "modified" });
2823
4108
  } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
2824
4109
  }
2825
- return { touched, edited };
4110
+ return { touched: touched2, edited };
2826
4111
  }
2827
4112
  function checkSupabasePack(ctx) {
2828
4113
  const settings = ctx.config.supabase ?? {};
2829
4114
  const dir = settings.migrations ?? DEFAULT_MIGRATIONS;
2830
- const abs = path14.join(ctx.root, dir);
4115
+ const abs = path18.join(ctx.root, dir);
2831
4116
  if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
2832
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path14.join(abs, n), "utf8")) }));
4117
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path18.join(abs, n), "utf8")) }));
2833
4118
  const exposed = new Set((settings.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
2834
4119
  const base = settings.base ?? DEFAULT_BASE;
2835
4120
  const view = gitView(ctx.root, dir, base);
@@ -2846,7 +4131,7 @@ function checkSupabasePack(ctx) {
2846
4131
  }
2847
4132
  }
2848
4133
  const since = settings.since;
2849
- const afterSince = (file) => since === void 0 || path14.posix.basename(file) >= since;
4134
+ const afterSince = (file) => since === void 0 || path18.posix.basename(file) >= since;
2850
4135
  if ("reason" in view && since === void 0) {
2851
4136
  ctx.report({
2852
4137
  rule: "migration-grants",
@@ -3098,7 +4383,7 @@ function checkDefinerSearchPath(ctx, migrations) {
3098
4383
  var UMBRELLA_PACKAGE = "@marktiderman/genesis";
3099
4384
  function readReleaseManifest(root) {
3100
4385
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
3101
- const file = dir && path14.join(dir, "dist", "versions.json");
4386
+ const file = dir && path18.join(dir, "dist", "versions.json");
3102
4387
  if (!file || !existsSync(file)) return null;
3103
4388
  return JSON.parse(readFileSync(file, "utf8"));
3104
4389
  }
@@ -3108,7 +4393,7 @@ function checkVersionSkew(ctx) {
3108
4393
  for (const [name, want] of Object.entries(manifest.packages)) {
3109
4394
  const dir = findPackageDir(ctx.root, name);
3110
4395
  if (!dir) continue;
3111
- const have = JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8")).version;
4396
+ const have = JSON.parse(readFileSync(path18.join(dir, "package.json"), "utf8")).version;
3112
4397
  if (have === want) continue;
3113
4398
  ctx.report({
3114
4399
  rule: "version-skew",
@@ -3119,12 +4404,12 @@ function checkVersionSkew(ctx) {
3119
4404
  });
3120
4405
  }
3121
4406
  }
3122
- var GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
4407
+ var GENESIS2 = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
3123
4408
  var DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
3124
4409
  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)$/;
3125
4410
  var readManifest = (dir) => {
3126
4411
  try {
3127
- return JSON.parse(readFileSync(path14.join(dir, "package.json"), "utf8"));
4412
+ return JSON.parse(readFileSync(path18.join(dir, "package.json"), "utf8"));
3128
4413
  } catch {
3129
4414
  return null;
3130
4415
  }
@@ -3138,18 +4423,18 @@ var real = (p) => {
3138
4423
  };
3139
4424
  var LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
3140
4425
  function nodeModulesOf(dir) {
3141
- const parent = path14.dirname(dir);
3142
- return path14.basename(parent).startsWith("@") ? path14.dirname(parent) : parent;
4426
+ const parent = path18.dirname(dir);
4427
+ return path18.basename(parent).startsWith("@") ? path18.dirname(parent) : parent;
3143
4428
  }
3144
4429
  function packagesIn(nodeModules) {
3145
4430
  if (!existsSync(nodeModules)) return [];
3146
4431
  const out = [];
3147
4432
  for (const entry of readdirSync(nodeModules)) {
3148
4433
  if (entry.startsWith(".")) continue;
3149
- const p = path14.join(nodeModules, entry);
4434
+ const p = path18.join(nodeModules, entry);
3150
4435
  if (entry.startsWith("@")) {
3151
4436
  try {
3152
- for (const sub of readdirSync(p)) out.push(path14.join(p, sub));
4437
+ for (const sub of readdirSync(p)) out.push(path18.join(p, sub));
3153
4438
  } catch {
3154
4439
  }
3155
4440
  } else {
@@ -3161,7 +4446,7 @@ function packagesIn(nodeModules) {
3161
4446
  function genesisInstalls(root) {
3162
4447
  const copies = /* @__PURE__ */ new Map();
3163
4448
  const realRoot = real(root);
3164
- const rel = (abs) => path14.relative(realRoot, abs).split(path14.sep).join("/") || ".";
4449
+ const rel = (abs) => path18.relative(realRoot, abs).split(path18.sep).join("/") || ".";
3165
4450
  const via = /* @__PURE__ */ new Map();
3166
4451
  const record = (real2, manifest, by, range, root2) => {
3167
4452
  let copy = copies.get(real2);
@@ -3181,7 +4466,7 @@ function genesisInstalls(root) {
3181
4466
  if (!manifest?.name) return;
3182
4467
  if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
3183
4468
  const realDir = real(dir);
3184
- if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
4469
+ if (GENESIS2.test(manifest.name)) record(realDir, manifest, by, range, kind);
3185
4470
  if (expanded.has(realDir)) return;
3186
4471
  expanded.add(realDir);
3187
4472
  queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
@@ -3206,7 +4491,7 @@ function genesisInstalls(root) {
3206
4491
  if (!dir) return null;
3207
4492
  if (!ownInstall || name in declared) return dir;
3208
4493
  const realDir = real(dir);
3209
- if (realDir.startsWith(realRoot + path14.sep)) return dir;
4494
+ if (realDir.startsWith(realRoot + path18.sep)) return dir;
3210
4495
  return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
3211
4496
  };
3212
4497
  const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
@@ -3214,7 +4499,7 @@ function genesisInstalls(root) {
3214
4499
  return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
3215
4500
  });
3216
4501
  const app = readManifest(root);
3217
- const ownInstall = LOCKFILES.some((f) => existsSync(path14.join(root, f)));
4502
+ const ownInstall = LOCKFILES.some((f) => existsSync(path18.join(root, f)));
3218
4503
  const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
3219
4504
  const declaredDev = Object.entries(app?.devDependencies ?? {});
3220
4505
  const runtimeDeps = {
@@ -3225,11 +4510,11 @@ function genesisInstalls(root) {
3225
4510
  };
3226
4511
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
3227
4512
  walk("runtime", rootsOf(runtimeDeps, "the app"));
3228
- const top = path14.join(root, "node_modules");
4513
+ const top = path18.join(root, "node_modules");
3229
4514
  walk(
3230
4515
  "hoisted",
3231
4516
  packagesIn(top).filter((dir) => {
3232
- const name = path14.relative(top, dir).split(path14.sep).join("/");
4517
+ const name = path18.relative(top, dir).split(path18.sep).join("/");
3233
4518
  return !(name in runtimeDeps) && !(name in devDeps);
3234
4519
  }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
3235
4520
  );
@@ -3271,13 +4556,13 @@ function checkDuplicatePackages(ctx) {
3271
4556
  }
3272
4557
  }
3273
4558
  function checkPeerRanges(ctx) {
3274
- const rel = (abs) => path14.relative(ctx.root, abs).split(path14.sep).join("/");
4559
+ const rel = (abs) => path18.relative(ctx.root, abs).split(path18.sep).join("/");
3275
4560
  for (const copies of genesisInstalls(ctx.root).values()) {
3276
4561
  for (const copy of copies) {
3277
4562
  const dir = copy.absolutePath;
3278
4563
  const peers = readManifest(dir)?.peerDependencies ?? {};
3279
4564
  for (const [peer, range] of Object.entries(peers)) {
3280
- if (!GENESIS.test(peer)) continue;
4565
+ if (!GENESIS2.test(peer)) continue;
3281
4566
  const peerDir = findPackageDir(dir, peer);
3282
4567
  const installed = peerDir && readManifest(peerDir)?.version;
3283
4568
  if (!peerDir || !installed) continue;
@@ -3294,126 +4579,20 @@ function checkPeerRanges(ctx) {
3294
4579
  }
3295
4580
  }
3296
4581
  }
3297
- var ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
3298
- var STEMS = {
3299
- tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
3300
- "next-app": {
3301
- layout: /* @__PURE__ */ new Set(["layout"]),
3302
- index: /* @__PURE__ */ new Set(["page"]),
3303
- skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
3304
- },
3305
- "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
3306
- };
3307
- var NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
3308
- var HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
3309
- var COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
3310
- var RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
3311
- 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;
3312
- function routesDir(ctx) {
3313
- if (ctx.config.routesDir) return ctx.config.routesDir;
3314
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path14.join(ctx.root, d))) ?? null;
3315
- }
3316
- var key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
3317
- function flavorOf(dir, rels) {
3318
- const stems = rels.map((r) => r.split("/").pop());
3319
- if (stems.includes("__root")) return "tanstack";
3320
- if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
3321
- if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
3322
- return "tanstack";
3323
- }
3324
- function renders(code) {
3325
- const elements = renderedElements(code);
3326
- if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
3327
- const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
3328
- const named = COMPONENT_OPTION.exec(code)?.[1];
3329
- if (named && !definedHere(named)) return true;
3330
- if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
3331
- const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
3332
- return exported !== void 0 && !definedHere(exported);
3333
- }
3334
- function webRoutes(ctx) {
3335
- const dir = routesDir(ctx);
3336
- if (!dir) return [];
3337
- 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(/\.[^.]+$/, "") }));
3338
- const flavor = flavorOf(dir, candidates.map((c) => c.rel));
3339
- const stems = STEMS[flavor];
3340
- const groups = /* @__PURE__ */ new Map();
3341
- for (const { file, rel } of candidates) {
3342
- const parts = rel.split("/");
3343
- if (parts.some((p) => p.startsWith("-"))) continue;
3344
- if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
3345
- if (flavor === "next-pages" && parts[0] === "api") continue;
3346
- if (stems.skip.test(parts.at(-1))) continue;
3347
- if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
3348
- const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
3349
- groups.set(id, [...groups.get(id) ?? [], file]);
3350
- }
3351
- const trail = trailFor(ctx);
3352
- const routes = [];
3353
- for (const [id, files] of groups) {
3354
- const parts = id.split("/");
3355
- const stem = parts.pop();
3356
- const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
3357
- const named = stems.layout.has(stem) || stems.index.has(stem);
3358
- const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
3359
- const segments = [...folders, ...own];
3360
- const tree = [...parts, ...own];
3361
- let index = stems.index.has(stem);
3362
- if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
3363
- segments.pop();
3364
- tree.pop();
3365
- index = true;
3366
- }
3367
- const code = files.map((f) => f.code).join("\n");
3368
- const elements = renderedElements(code);
3369
- const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
3370
- const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
3371
- const layout = stems.layout.has(stem) || pathless || outlet;
3372
- const rendering = renders(code);
3373
- const ownContent = new RegExp(OWN_CONTENT).test(code);
3374
- const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
3375
- const page = !pure && !pathless && (!layout || ownContent);
3376
- routes.push({
3377
- file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
3378
- files,
3379
- segments,
3380
- tree,
3381
- index,
3382
- layout,
3383
- page,
3384
- detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
3385
- redirectOnly: !rendering,
3386
- parents: []
3387
- });
3388
- }
3389
- for (const r of routes) {
3390
- const own = r.tree;
3391
- for (const p of routes) {
3392
- if (p === r || !p.layout) continue;
3393
- const n = p.tree.length;
3394
- if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
3395
- if (key(own.slice(0, n)) !== key(p.tree)) continue;
3396
- if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
3397
- r.parents.push(p);
3398
- }
3399
- r.parents.sort((a, b) => b.tree.length - a.tree.length);
3400
- }
3401
- return routes;
3402
- }
3403
-
3404
- // src/doctor/structure.ts
3405
- var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/ui/SKILL.md (Sub-navigation)";
3406
- var CONTAINER = /(?:Card|CardContent|Dialog|DialogContent|Sheet|SheetContent|Drawer|DrawerContent|Popover|PopoverContent|Modal|Accordion|AccordionContent|AccordionItem|Collapsible|CollapsibleContent|Tooltip|Menu|MenuContent|Panel|Table|TabsContent)$/;
3407
- var SWITCHER = /<(TabsList|SubNavTabs)(?=[\s>/])/g;
3408
- var SHELL = /<AppShell(?=[\s>/])/;
3409
- var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
3410
- var PAGE_LAYOUT = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)|ResourceView)$/;
3411
- var EMBEDDED_RESOURCE_VIEW = /<ResourceView\b[^>]*?\blayout\s*=\s*(?:(["'`]) {8}\1|\{\s*(["'`]) {8}\2\s*\})[^>]*>/g;
3412
- var PACKAGE_SCREEN = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)|ResourceView)$/;
3413
- var isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
3414
- var rendersRe = (names) => {
3415
- const list = [...names];
3416
- return list.length ? new RegExp(`<(?:${list.map((n) => n.replace(/[.$]/g, "\\$&")).join("|")})(?=[\\s>/])`) : null;
4582
+
4583
+ // src/doctor/structure.ts
4584
+ var SUB_NAV_DOCS = "https://github.com/marktiderman/genesis/blob/main/packages/ui/SKILL.md (Sub-navigation)";
4585
+ var CONTAINER = /(?:Card|CardContent|Dialog|DialogContent|Sheet|SheetContent|Drawer|DrawerContent|Popover|PopoverContent|Modal|Accordion|AccordionContent|AccordionItem|Collapsible|CollapsibleContent|Tooltip|Menu|MenuContent|Panel|Table|TabsContent)$/;
4586
+ var SWITCHER = /<(TabsList|SubNavTabs)(?=[\s>/])/g;
4587
+ var SHELL = /<AppShell(?=[\s>/])/;
4588
+ var GENESIS_PACKAGE2 = /^@marktiderman\/genesis(?:-[\w-]+)?(?:\/|$)/;
4589
+ var PAGE_LAYOUT = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)|ResourceView)$/;
4590
+ var EMBEDDED_RESOURCE_VIEW = /<ResourceView\b[^>]*?\blayout\s*=\s*(?:(["'`]) {8}\1|\{\s*(["'`]) {8}\2\s*\})[^>]*>/g;
4591
+ var PACKAGE_SCREEN = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)|ResourceView)$/;
4592
+ var isNative2 = (ctx) => ctx.config.packs?.includes("native") ?? false;
4593
+ var rendersRe = (names) => {
4594
+ const list = [...names];
4595
+ return list.length ? new RegExp(`<(?:${list.map((n) => n.replace(/[.$]/g, "\\$&")).join("|")})(?=[\\s>/])`) : null;
3417
4596
  };
3418
4597
  function routeReach(ctx, r, test2) {
3419
4598
  const trail = trailFor(ctx);
@@ -3432,7 +4611,7 @@ function insideShell(ctx, routes) {
3432
4611
  return (r) => !shell.has(r) && (anyShell || r.parents.some((p) => shell.has(p)));
3433
4612
  }
3434
4613
  function checkHandRolledSubNav(ctx) {
3435
- if (isNative(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
4614
+ if (isNative2(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
3436
4615
  const routes = webRoutes(ctx);
3437
4616
  if (routes.length === 0) return;
3438
4617
  const inShell = insideShell(ctx, routes);
@@ -3489,7 +4668,7 @@ function checkLocalGenesisCopies(ctx) {
3489
4668
  }
3490
4669
  }
3491
4670
  function checkResourceWorkspaces(ctx) {
3492
- if (isNative(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
4671
+ if (isNative2(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
3493
4672
  const header = /<AppShellPageHeader(?=[\s>/])/;
3494
4673
  const byFolder = /* @__PURE__ */ new Map();
3495
4674
  for (const r of webRoutes(ctx)) {
@@ -3514,7 +4693,7 @@ function checkResourceWorkspaces(ctx) {
3514
4693
  }
3515
4694
  }
3516
4695
  function checkPageLayouts(ctx) {
3517
- if (isNative(ctx)) return;
4696
+ if (isNative2(ctx)) return;
3518
4697
  const layouts = new Set(ctx.genesis.components.filter((n) => PAGE_LAYOUT.test(n)));
3519
4698
  for (const c of ctx.genesis.companions) for (const n of c.components) if (PAGE_LAYOUT.test(n)) layouts.add(n);
3520
4699
  if (layouts.size === 0) return;
@@ -3563,22 +4742,735 @@ function checkIsoDateSlices(ctx) {
3563
4742
  }
3564
4743
  }
3565
4744
 
3566
- // src/doctor/index.ts
4745
+ // src/upgrade/scope-names.ts
4746
+ var IMPORTS_GENESIS = /\bfrom\s*["']@marktiderman\/genesis[\w/-]*["']/;
4747
+ function maskComments(text) {
4748
+ const out = text.split("");
4749
+ let quote2 = null;
4750
+ for (let i = 0; i < text.length; i++) {
4751
+ const ch = text[i];
4752
+ if (quote2) {
4753
+ if (ch === "\\") i++;
4754
+ else if (ch === quote2) quote2 = null;
4755
+ continue;
4756
+ }
4757
+ if (ch === '"' || ch === "'" || ch === "`") {
4758
+ quote2 = ch;
4759
+ continue;
4760
+ }
4761
+ if (ch === "/" && (text[i + 1] === "/" || text[i + 1] === "*")) {
4762
+ const line = text[i + 1] === "/";
4763
+ const end = line ? text.indexOf("\n", i) === -1 ? text.length : text.indexOf("\n", i) : text.indexOf("*/", i + 2) === -1 ? text.length : text.indexOf("*/", i + 2) + 2;
4764
+ for (let k = i; k < end; k++) if (out[k] !== "\n") out[k] = " ";
4765
+ i = end - 1;
4766
+ }
4767
+ }
4768
+ return out.join("");
4769
+ }
4770
+ var within = (spans, at) => spans.some(([a, b]) => at >= a && at < b);
4771
+ function importedFromGenesis(text, name) {
4772
+ for (const m of text.matchAll(/\bimport\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']@marktiderman\/genesis[\w/-]*["']/g)) {
4773
+ for (const part of m[1].split(",")) {
4774
+ const local = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/).pop()?.trim();
4775
+ if (local === name) return true;
4776
+ }
4777
+ }
4778
+ return false;
4779
+ }
4780
+ var OPEN = { "(": ")", "{": "}", "[": "]" };
4781
+ function matching(text, open) {
4782
+ const stack = [];
4783
+ let quote2 = null;
4784
+ for (let i = open; i < text.length; i++) {
4785
+ const ch = text[i];
4786
+ if (quote2) {
4787
+ if (ch === "\\") i++;
4788
+ else if (ch === quote2) quote2 = null;
4789
+ continue;
4790
+ }
4791
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
4792
+ else if (OPEN[ch]) stack.push(OPEN[ch]);
4793
+ else if (ch === ")" || ch === "}" || ch === "]") {
4794
+ stack.pop();
4795
+ if (stack.length === 0) return i + 1;
4796
+ }
4797
+ }
4798
+ return text.length;
4799
+ }
4800
+ function matchingBack(text, close) {
4801
+ let depth = 0;
4802
+ for (let i = close; i >= 0; i--) {
4803
+ const ch = text[i];
4804
+ if (ch === "}") depth++;
4805
+ else if (ch === "{") {
4806
+ depth--;
4807
+ if (depth === 0) return i;
4808
+ }
4809
+ }
4810
+ return 0;
4811
+ }
4812
+ function callSpans(text, name) {
4813
+ const out = [];
4814
+ for (const m of text.matchAll(new RegExp(`\\b${name}\\s*(?:<[^()]*?>)?\\s*\\(`, "g"))) {
4815
+ const open = m.index + m[0].length - 1;
4816
+ out.push([open, matching(text, open)]);
4817
+ }
4818
+ return out;
4819
+ }
4820
+ function typedObjectSpans(text, types) {
4821
+ const out = [];
4822
+ if (types.length === 0) return out;
4823
+ const names = `(?:(?:Partial|Readonly|Required|Pick|Omit)\\s*<\\s*)?(?:${types.join("|")})`;
4824
+ for (const m of text.matchAll(new RegExp(`:\\s*${names}\\b(?:<[^=]*?>)?[^=;{]*?=\\s*\\{`, "g"))) {
4825
+ const open = m.index + m[0].length - 1;
4826
+ out.push([open, matching(text, open)]);
4827
+ }
4828
+ for (const m of text.matchAll(new RegExp(`\\}\\s*(?:satisfies|as)\\s+${names}\\b`, "g"))) {
4829
+ const close = m.index;
4830
+ out.push([matchingBack(text, close), close + 1]);
4831
+ }
4832
+ return out;
4833
+ }
4834
+ function tagSpans(text, tag) {
4835
+ const out = [];
4836
+ for (const m of text.matchAll(new RegExp(`<${tag}\\b`, "g"))) {
4837
+ let depth = 0;
4838
+ let quote2 = null;
4839
+ let end = text.length;
4840
+ for (let i = m.index + 1; i < text.length; i++) {
4841
+ const ch = text[i];
4842
+ if (quote2) {
4843
+ if (ch === "\\") i++;
4844
+ else if (ch === quote2) quote2 = null;
4845
+ continue;
4846
+ }
4847
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
4848
+ else if (ch === "{") depth++;
4849
+ else if (ch === "}") depth--;
4850
+ else if (ch === ">" && depth === 0) {
4851
+ end = i + 1;
4852
+ break;
4853
+ }
4854
+ }
4855
+ out.push([m.index, end]);
4856
+ }
4857
+ return out;
4858
+ }
4859
+ function attributeObjectSpans(text, tag, attr) {
4860
+ const out = [];
4861
+ for (const [a, b] of tagSpans(text, tag)) {
4862
+ const inTag = text.slice(a, b);
4863
+ for (const m of inTag.matchAll(new RegExp(`\\s${attr}\\s*=\\s*\\{\\s*\\{`, "g"))) {
4864
+ const open = a + m.index + m[0].length - 1;
4865
+ out.push([open, matching(text, open)]);
4866
+ }
4867
+ }
4868
+ return out;
4869
+ }
4870
+ function zoneBindings(text, hook, type) {
4871
+ const names = /* @__PURE__ */ new Set();
4872
+ if (hook) {
4873
+ for (const m of text.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::\s*DisplayTimeZones\s*)?=\s*useDisplayTimeZones\(\)/g)) names.add(m[1]);
4874
+ }
4875
+ if (type) for (const m of text.matchAll(/\b([A-Za-z_$][\w$]*)\s*\??\s*:\s*DisplayTimeZones\b/g)) names.add(m[1]);
4876
+ return [...names];
4877
+ }
4878
+ var escape = (name) => name.replace(/\$/g, "\\$");
4879
+ function findRemovedScopeNames(source) {
4880
+ const text = maskComments(source);
4881
+ if (!IMPORTS_GENESIS.test(text)) return [];
4882
+ const out = [];
4883
+ const has = (name) => importedFromGenesis(text, name);
4884
+ const viewSpans = [
4885
+ ...has("defineView") ? callSpans(text, "defineView") : [],
4886
+ ...typedObjectSpans(text, ["ViewDefinition", "ViewField"].filter(has))
4887
+ ];
4888
+ for (const m of text.matchAll(/(\btimeZone\s*:\s*)(["'`])practice\2/g)) {
4889
+ const at = m.index + m[1].length;
4890
+ if (!within(viewSpans, at)) continue;
4891
+ out.push({ index: m.index, what: "timeZone-practice", instead: 'timeZone: "scope"', start: at + 1, end: at + 1 + "practice".length, replacement: "scope" });
4892
+ }
4893
+ if (has("resolveZone")) {
4894
+ for (const m of text.matchAll(/(\bresolveZone\(\s*)(["'`])practice\2/g)) {
4895
+ const at = m.index + m[1].length + 1;
4896
+ out.push({ index: m.index, what: "resolveZone-practice", instead: 'resolveZone("scope", \u2026)', start: at, end: at + "practice".length, replacement: "scope" });
4897
+ }
4898
+ }
4899
+ const propSpans = [
4900
+ ...has("NativeResourceView") ? tagSpans(text, "NativeResourceView") : [],
4901
+ ...typedObjectSpans(text, ["NativeResourceViewProps"].filter(has))
4902
+ ];
4903
+ for (const m of text.matchAll(/(^|[\s{,(])practiceTimeZone(\s*[=:])/gm)) {
4904
+ const at = m.index + m[1].length;
4905
+ if (!within(propSpans, at)) continue;
4906
+ out.push({ index: at, what: "practiceTimeZone", instead: "scopeTimeZone", start: at, end: at + "practiceTimeZone".length, replacement: "scopeTimeZone" });
4907
+ }
4908
+ const zoneSpans = [
4909
+ ...has("DisplayTimeZonesProvider") ? attributeObjectSpans(text, "DisplayTimeZonesProvider", "value") : [],
4910
+ ...typedObjectSpans(text, ["DisplayTimeZones"].filter(has))
4911
+ ];
4912
+ for (const m of text.matchAll(/(^|[\s{,])practice(\s*:)/gm)) {
4913
+ const at = m.index + m[1].length;
4914
+ if (!within(zoneSpans, at)) continue;
4915
+ out.push({ index: at, what: "DisplayTimeZones.practice", instead: "scope", start: at, end: at + "practice".length, replacement: "scope" });
4916
+ }
4917
+ for (const name of zoneBindings(text, has("useDisplayTimeZones"), has("DisplayTimeZones"))) {
4918
+ for (const m of text.matchAll(new RegExp(`(?<![\\w$])${escape(name)}\\s*\\??\\.\\s*(practice)(?![\\w$])`, "g"))) {
4919
+ const at = m.index + m[0].length - "practice".length;
4920
+ out.push({ index: m.index, what: "DisplayTimeZones.practice", instead: `${name}.scope`, start: at, end: at + "practice".length, replacement: "scope" });
4921
+ }
4922
+ }
4923
+ const seen = /* @__PURE__ */ new Set();
4924
+ return out.filter((f) => seen.has(f.start) ? false : (seen.add(f.start), true)).sort((a, b) => a.start - b.start);
4925
+ }
4926
+ function readsPracticeId(text) {
4927
+ if (!IMPORTS_GENESIS.test(text)) return [];
4928
+ return [...text.matchAll(/\bscope\s*\??\.\s*practiceId\b/g)].map((m) => m.index);
4929
+ }
4930
+ var augmentsResourceScope = (text) => /\binterface\s+ResourceScope\b/.test(text);
4931
+ var PRACTICE_ID_AUGMENTATION = 'declare module "@marktiderman/genesis-core" { interface ResourceScope { practiceId?: string } }';
4932
+
4933
+ // src/upgrade/codemods.ts
4934
+ var SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
4935
+ var SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
4936
+ var MAX_BYTES = 2 * 1024 * 1024;
4937
+ function appScripts(root) {
4938
+ const out = [];
4939
+ const walk = (dir) => {
4940
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
4941
+ const abs = path18.join(dir, entry.name);
4942
+ if (entry.isDirectory()) {
4943
+ if (!SKIP_DIRS3.has(entry.name)) walk(abs);
4944
+ } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
4945
+ out.push(path18.relative(root, abs).split(path18.sep).join("/"));
4946
+ }
4947
+ }
4948
+ };
4949
+ walk(root);
4950
+ return out;
4951
+ }
4952
+
4953
+ // src/doctor/api-usage.ts
4954
+ var SCRIPT_EXTS5 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
4955
+ function openingTag(code, start) {
4956
+ let depth = 0;
4957
+ let quote2 = null;
4958
+ for (let i = start + 1; i < code.length; i++) {
4959
+ const ch = code[i];
4960
+ if (quote2) {
4961
+ if (ch === "\\") i++;
4962
+ else if (ch === quote2) quote2 = null;
4963
+ continue;
4964
+ }
4965
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
4966
+ else if (ch === "{") depth++;
4967
+ else if (ch === "}") depth--;
4968
+ else if (ch === ">" && depth === 0) return code.slice(start, i + 1);
4969
+ }
4970
+ return code.slice(start);
4971
+ }
4972
+ function ownAttributes(tag) {
4973
+ let depth = 0;
4974
+ let quote2 = null;
4975
+ let out = "";
4976
+ let inner = "";
4977
+ for (let i = 0; i < tag.length; i++) {
4978
+ const ch = tag[i];
4979
+ if (depth > 0) inner += ch;
4980
+ if (quote2) {
4981
+ if (ch === "\\") {
4982
+ i++;
4983
+ if (depth > 0) inner += tag[i] ?? "";
4984
+ else out += ch + (tag[i] ?? "");
4985
+ continue;
4986
+ }
4987
+ if (ch === quote2) quote2 = null;
4988
+ if (depth === 0) out += ch;
4989
+ continue;
4990
+ }
4991
+ if (ch === '"' || ch === "'" || ch === "`") {
4992
+ quote2 = ch;
4993
+ if (depth === 0) out += ch;
4994
+ } else if (ch === "{") {
4995
+ if (depth === 0) inner = "";
4996
+ depth++;
4997
+ } else if (ch === "}") {
4998
+ depth--;
4999
+ if (depth === 0) {
5000
+ const body = inner.slice(0, -1).trim();
5001
+ out += /^(["'`])[^"'`]*\1$/.test(body) ? `{${body}}` : "{}";
5002
+ }
5003
+ } else if (depth === 0) out += ch;
5004
+ }
5005
+ return out;
5006
+ }
5007
+ function checkTreeViews(ctx) {
5008
+ for (const file of ctx.files) {
5009
+ if (!SCRIPT_EXTS5.has(file.ext) || !/\btree\s*=/.test(file.code)) continue;
5010
+ for (const m of file.code.matchAll(/<(ResourceView|ResourcePage)\b(?:\s*<[^<>]*>)?/g)) {
5011
+ const tag = openingTag(file.code, (m.index ?? 0) + m[0].length - 1);
5012
+ const attrs = ownAttributes(tag);
5013
+ if (!/\stree\s*=/.test(attrs) || !/\spagination\s*=/.test(attrs)) continue;
5014
+ const paging = attrs.match(/\spagination\s*=\s*(?:\{\s*)?["'`](server|cursor)["'`]/);
5015
+ if (!paging) continue;
5016
+ ctx.report({
5017
+ rule: "resource-view-tree",
5018
+ level: "error",
5019
+ file: file.path,
5020
+ line: lineAt(file.code, m.index ?? 0),
5021
+ subject: m[1],
5022
+ message: `${m[1]} has \`tree\` with pagination="${paging[1]}", which throws when it renders: a tree is built from every row on the client. Leave pagination unset (docs/RESOURCE-VIEW.md, "Tree mode")`
5023
+ });
5024
+ }
5025
+ }
5026
+ }
5027
+ var STUDIO_SERVER = "@marktiderman/genesis-studio-server";
5028
+ var DEEP = /\b(?:from|import|require)\s*\(?\s*["']@marktiderman\/genesis-studio-server\/(dist|src|lib)\/[^"']*["']/g;
5029
+ var ROOT_REQUIRE = /\brequire\s*\(\s*["']@marktiderman\/genesis-studio-server["']\s*\)/g;
5030
+ function moduleFiles(ctx) {
5031
+ const scanned = new Set(ctx.files.map((f) => f.path));
5032
+ const ignored = globMatcher([...DEFAULT_IGNORE, ...ctx.config.ignore ?? []]);
5033
+ 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) }));
5034
+ return [...ctx.files.filter((f) => SCRIPT_EXTS5.has(f.ext)), ...extra];
5035
+ }
5036
+ function checkStudioServerImports(ctx) {
5037
+ for (const file of moduleFiles(ctx)) {
5038
+ if (!file.code.includes(STUDIO_SERVER)) continue;
5039
+ for (const m of file.code.matchAll(DEEP)) {
5040
+ ctx.report({
5041
+ rule: "studio-server-auth-import",
5042
+ level: "warn",
5043
+ file: file.path,
5044
+ line: lineAt(file.code, m.index ?? 0),
5045
+ subject: `${STUDIO_SERVER}/${m[1]}`,
5046
+ message: `imports a studio-server file the package doesn't export, which fails at run time; the token checks and switchToUser are in ${STUDIO_SERVER}/auth (import or require)`
5047
+ });
5048
+ }
5049
+ for (const m of file.code.matchAll(ROOT_REQUIRE)) {
5050
+ ctx.report({
5051
+ rule: "studio-server-auth-import",
5052
+ level: "warn",
5053
+ file: file.path,
5054
+ line: lineAt(file.code, m.index ?? 0),
5055
+ subject: STUDIO_SERVER,
5056
+ message: `requires ${STUDIO_SERVER}, which is ESM-only and fails under require(); ${STUDIO_SERVER}/auth (the token checks and switchToUser) ships for require too`
5057
+ });
5058
+ }
5059
+ }
5060
+ }
5061
+ var REMOVED_WORDS = {
5062
+ "timeZone-practice": 'timeZone "practice"',
5063
+ "resolveZone-practice": 'resolveZone("practice")',
5064
+ practiceTimeZone: "practiceTimeZone",
5065
+ "DisplayTimeZones.practice": "DisplayTimeZones.practice"
5066
+ };
5067
+ function checkRemovedScopeNames(ctx) {
5068
+ let augmentedMemo;
5069
+ 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")));
5070
+ for (const file of ctx.files) {
5071
+ if (!SCRIPT_EXTS5.has(file.ext)) continue;
5072
+ for (const hit of findRemovedScopeNames(file.code)) {
5073
+ ctx.report({
5074
+ rule: "removed-scope-name",
5075
+ level: "error",
5076
+ file: file.path,
5077
+ line: lineAt(file.code, hit.index),
5078
+ subject: REMOVED_WORDS[hit.what] ?? hit.what,
5079
+ message: `${REMOVED_WORDS[hit.what] ?? hit.what} was removed in genesis-core 2; use ${hit.instead}. \`genesis codemod genesis-core-2-scope-names\` rewrites every one`
5080
+ });
5081
+ }
5082
+ const reads = readsPracticeId(file.code);
5083
+ if (!reads.length || augmented()) continue;
5084
+ for (const index of reads) {
5085
+ ctx.report({
5086
+ rule: "scope-practice-id",
5087
+ level: "info",
5088
+ file: file.path,
5089
+ line: lineAt(file.code, index),
5090
+ subject: "practiceId",
5091
+ message: `scope.practiceId is the app's own scope key now, read as unknown; type it once: ${PRACTICE_ID_AUGMENTATION}`
5092
+ });
5093
+ }
5094
+ }
5095
+ }
5096
+ function git3(root, args) {
5097
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
5098
+ return r.status === 0 ? r.stdout : null;
5099
+ }
5100
+ function changedSince(root, base) {
5101
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
5102
+ if (!mergeBase) return null;
5103
+ const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
5104
+ const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
5105
+ if (committed === null || untracked === null) return null;
5106
+ return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
5107
+ }
5108
+ var objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
5109
+ function showAt(dir, rev, file) {
5110
+ const at = `${rev}:./${file}`;
5111
+ if (git3(dir, ["cat-file", "-e", at]) === null) return void 0;
5112
+ return git3(dir, ["show", at]);
5113
+ }
5114
+ function configAtBase(root, base, explicitFile) {
5115
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
5116
+ if (!mergeBase) return null;
5117
+ const candidates = explicitFile ? [{ dir: path18.dirname(explicitFile), file: path18.basename(explicitFile), explicit: true }] : [
5118
+ { dir: root, file: "genesis.config.json", explicit: false },
5119
+ { dir: root, file: "package.json", explicit: false }
5120
+ ];
5121
+ for (const c of candidates) {
5122
+ const text = showAt(c.dir, mergeBase, c.file);
5123
+ if (text === null) return null;
5124
+ if (text === void 0) continue;
5125
+ let block;
5126
+ try {
5127
+ block = doctorBlock(JSON.parse(text), c.file, c.explicit);
5128
+ } catch {
5129
+ return null;
5130
+ }
5131
+ if (block === void 0 || c.file === "package.json" && !c.explicit && isPackageDeclaration(block)) {
5132
+ if (c.file === "genesis.config.json") return "absent";
5133
+ continue;
5134
+ }
5135
+ const b = objectOr(block);
5136
+ return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
5137
+ }
5138
+ return "absent";
5139
+ }
5140
+ var allowKey = (a) => `${a.rule}\0${a.file ?? ""}\0${a.match ?? ""}`;
5141
+ function allowGrew(allow, before, base) {
5142
+ const had = new Set(before.map(allowKey));
5143
+ return allow.filter((a) => !had.has(allowKey(a))).map((a) => ({
5144
+ rule: "allow-grew",
5145
+ file: a.file ?? "genesis config",
5146
+ subject: a.rule,
5147
+ message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
5148
+ }));
5149
+ }
5150
+ var RANK = { off: 0, info: 1, warn: 2, error: 3 };
5151
+ function rulesWeakened(config, before, base) {
5152
+ const out = [];
5153
+ const levelIn = (c, rule) => c.rules?.[rule] ?? c.packageRules?.[rule]?.level;
5154
+ const ids = /* @__PURE__ */ new Set([...Object.keys(config.rules ?? {}), ...Object.keys(config.packageRules ?? {})]);
5155
+ for (const rule of ids) {
5156
+ const set = levelIn(config, rule);
5157
+ if (set === void 0) continue;
5158
+ const was = levelIn(before, rule);
5159
+ if (was === void 0 ? set === "off" : RANK[set] < RANK[was]) {
5160
+ 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` });
5161
+ }
5162
+ }
5163
+ for (const [rule, setting] of Object.entries(config.packageRules ?? {})) {
5164
+ const had = new Set(before.packageRules[rule]?.exclude ?? []);
5165
+ const added = (setting.exclude ?? []).filter((g) => !had.has(g));
5166
+ if (added.length) {
5167
+ 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` });
5168
+ }
5169
+ }
5170
+ return out;
5171
+ }
5172
+ function touched(file, changed) {
5173
+ if (changed.has(file)) return true;
5174
+ const prefix = file.endsWith("/") ? file : `${file}/`;
5175
+ for (const c of changed) if (c.startsWith(prefix)) return true;
5176
+ return false;
5177
+ }
5178
+ var NEVER_RATCHETED = /* @__PURE__ */ new Set([
5179
+ ...META_RULES,
5180
+ "stale-exception",
5181
+ "package-rule-override",
5182
+ "package-rules-invalid",
5183
+ "package-doctor-declaration",
5184
+ "plugin-error",
5185
+ "build",
5186
+ "agent-guide-stale",
5187
+ "contracts-stale"
5188
+ ]);
5189
+ function applyRatchet(findings, options) {
5190
+ const { config, newOnly, changed, base, isAppPath } = options;
5191
+ const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
5192
+ return findings.map((f) => {
5193
+ if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
5194
+ return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
5195
+ });
5196
+ }
5197
+ var DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
5198
+ var DEFAULT_DATABASE_ENV = "DATABASE_URL";
5199
+ var shellArg = (s) => /^[\w./,@:+=-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
5200
+ var postgresSource = (schemas) => `Postgres (${schemas.join(", ")})`;
5201
+ async function postgresContract(url, schemas) {
5202
+ const { introspectPostgres: introspectPostgres2, emitContracts: emitContracts2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
5203
+ const { default: postgres } = await import('postgres');
5204
+ const sql = postgres(url, { max: 1, prepare: false, onnotice: () => {
5205
+ } });
5206
+ try {
5207
+ const tables = await introspectPostgres2(sql, schemas);
5208
+ return { content: emitContracts2(tables, { source: postgresSource(schemas) }), tables: tables.length };
5209
+ } finally {
5210
+ await sql.end();
5211
+ }
5212
+ }
5213
+ function contractSource(content) {
5214
+ return /^\/\/ Source: (.*)$/m.exec(content.slice(0, 2e3))?.[1]?.trim() ?? null;
5215
+ }
5216
+ function sourceSchemas(source) {
5217
+ const m = source === null ? null : /^Postgres \((.*)\)$/.exec(source);
5218
+ const schemas = m?.[1].split(",").map((s) => s.trim()).filter(Boolean);
5219
+ return schemas?.length ? schemas : null;
5220
+ }
5221
+ var lf = (text) => text.replace(/\r\n/g, "\n");
5222
+ async function checkContracts(ctx, read2 = postgresContract) {
5223
+ const settings = ctx.config.contracts;
5224
+ if (!settings) return;
5225
+ const out = settings.out ?? DEFAULT_CONTRACT_OUT;
5226
+ const env = settings.databaseEnv ?? DEFAULT_DATABASE_ENV;
5227
+ let current = null;
5228
+ try {
5229
+ current = lf(readFileSync(path18.join(ctx.root, out), "utf8"));
5230
+ } catch {
5231
+ current = null;
5232
+ }
5233
+ const source = current === null ? null : contractSource(current);
5234
+ if (source !== null && !source.startsWith("Postgres (")) {
5235
+ 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` });
5236
+ return;
5237
+ }
5238
+ const schemas = settings.schemas?.length ? settings.schemas : sourceSchemas(source) ?? ["public"];
5239
+ const url = process.env[env];
5240
+ if (!url) {
5241
+ 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)` });
5242
+ return;
5243
+ }
5244
+ let expected;
5245
+ try {
5246
+ expected = lf((await read2(url, schemas)).content);
5247
+ } catch (err) {
5248
+ const generation = err.name === "EmitError";
5249
+ const message = err.message.split("\n")[0];
5250
+ 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}` });
5251
+ return;
5252
+ }
5253
+ const target = path18.relative(process.cwd(), path18.join(ctx.root, out)) || out;
5254
+ const command = `genesis introspect -o ${shellArg(target)} -s ${shellArg(schemas.join(","))}${env === DEFAULT_DATABASE_ENV ? "" : ` --database-env ${shellArg(env)}`}`;
5255
+ if (current !== expected) {
5256
+ ctx.report({
5257
+ rule: "contracts-stale",
5258
+ file: out,
5259
+ message: current === null ? `doesn't exist; run ${command} and commit it` : `is out of date with the database; run ${command} and commit the result`
5260
+ });
5261
+ }
5262
+ }
5263
+ var GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
5264
+ var CORE = [
5265
+ {
5266
+ need: "anything, before building it",
5267
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the doctor\'s "Available but unused" list',
5268
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
5269
+ from: "genesis-cli"
5270
+ },
5271
+ {
5272
+ need: "a page inside the app shell",
5273
+ use: "a Genesis page layout (`DashboardPage`, `SettingsPage`, `FormPage`, `DetailPage`, from `@marktiderman/genesis-ui`) or `ResourceView` (from `@marktiderman/genesis-ui/data`)",
5274
+ import: "@marktiderman/genesis-ui",
5275
+ rule: "page-layout",
5276
+ from: "genesis-cli"
5277
+ },
5278
+ {
5279
+ need: "a button, input, table, dialog or other component",
5280
+ use: "the Genesis component, never the raw tag or a local copy",
5281
+ import: "@marktiderman/genesis-ui/<component>",
5282
+ rule: "raw-tag",
5283
+ from: "genesis-cli"
5284
+ },
5285
+ {
5286
+ need: "colors and spacing",
5287
+ use: "semantic tokens (`bg-primary`, `text-muted-foreground`), never literal colors",
5288
+ import: "@marktiderman/genesis-design-system",
5289
+ rule: "raw-color",
5290
+ from: "genesis-cli"
5291
+ },
5292
+ {
5293
+ need: "something no primitive covers",
5294
+ use: "write the gap up for Genesis (an issue or a proposal) first, then invent in the app, on Genesis primitives",
5295
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
5296
+ from: "genesis-cli"
5297
+ }
5298
+ ];
5299
+ function primitivesCatalog(packages) {
5300
+ const rows = [...CORE];
5301
+ for (const rule of preferRules(packages)) {
5302
+ rows.push({
5303
+ need: rule.need ?? rule.id.replace(/-/g, " "),
5304
+ use: rule.use,
5305
+ ...rule.import ? { import: rule.import } : {},
5306
+ ...rule.docs ? { docs: rule.docs } : {},
5307
+ rule: rule.ruleId,
5308
+ from: rule.package
5309
+ });
5310
+ }
5311
+ for (const p of packages) {
5312
+ for (const e of p.declaration?.primitives ?? []) {
5313
+ rows.push({ need: e.need, use: e.use, ...e.import ? { import: e.import } : {}, ...e.docs ? { docs: e.docs } : {}, from: p.name });
5314
+ }
5315
+ }
5316
+ return rows;
5317
+ }
5318
+ function primitivesSummary(packages) {
5319
+ const rules = preferRules(packages);
5320
+ const withPlugin = packages.filter((p) => p.declaration?.plugin);
5321
+ return { rules: rules.length + withPlugin.length, packages: (/* @__PURE__ */ new Set([...rules.map((r) => r.package), ...withPlugin.map((p) => p.name)])).size };
5322
+ }
5323
+ var cell = (s) => (s ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ").replace(/(`[^`]*`)|<([A-Za-z][\w.]*)>/g, (m, code, name) => code ?? `\`<${name}>\``);
5324
+ var importCell = (s) => `\`${s.replace(/`/g, "").replace(/\|/g, "\\|").replace(/\n/g, " ")}\``;
5325
+ function catalogTable(rows, options = {}) {
5326
+ const head = options.docs ? "| Need | Use | Import | Enforced by | Docs |\n| --- | --- | --- | --- | --- |" : "| Need | Use | Import |\n| --- | --- | --- |";
5327
+ const body = rows.map(
5328
+ (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) : ""} |`
5329
+ );
5330
+ return [head, ...body].join("\n");
5331
+ }
5332
+ function formatPrimitives(rows) {
5333
+ const lines = ["Genesis primitives: what to use for each need (reuse, then extend, then invent).", ""];
5334
+ for (const r of rows) {
5335
+ lines.push(`- ${r.need}: ${r.use}`);
5336
+ if (r.import) lines.push(` import ${r.import}`);
5337
+ if (r.rule) lines.push(` rule ${r.rule}`);
5338
+ if (r.docs) lines.push(` docs ${r.docs}`);
5339
+ }
5340
+ return lines.join("\n");
5341
+ }
5342
+ var SKILL_PATH = ".claude/skills/genesis/SKILL.md";
5343
+ var AGENTS_START = "<!-- genesis-primitives:start -->";
5344
+ var AGENTS_END = "<!-- genesis-primitives:end -->";
5345
+ var RULES = [
5346
+ "Use the Genesis primitive for the need first: reuse, then extend, then invent (docs/FRAMEWORK.md, G1 to G6).",
5347
+ "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
5348
+ "A list screen is a view (`defineView`) rendered by `ResourceView`; a record page is `ResourceWorkspace`; on the phone, `NativeResourceView`.",
5349
+ "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.",
5350
+ "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
5351
+ "Run `genesis doctor` before you finish; it enforces these rules."
5352
+ ];
5353
+ function renderSkill(rows) {
5354
+ return [
5355
+ "---",
5356
+ "name: genesis",
5357
+ "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.",
5358
+ "---",
5359
+ "",
5360
+ "<!-- Generated by `genesis agents` from the installed Genesis packages. Don't edit; run `genesis agents` after upgrading Genesis. -->",
5361
+ "",
5362
+ "# Genesis primitives",
5363
+ "",
5364
+ ...RULES.map((r) => `- ${r}`),
5365
+ "",
5366
+ "## What to use for each need",
5367
+ "",
5368
+ catalogTable(rows, { docs: true }),
5369
+ "",
5370
+ "`genesis primitives` prints the same list; `genesis doctor` enforces the rules named above.",
5371
+ ""
5372
+ ].join("\n");
5373
+ }
5374
+ function renderAgentsBlock(rows) {
5375
+ return [
5376
+ AGENTS_START,
5377
+ "## Building with Genesis",
5378
+ "",
5379
+ "Generated by `genesis agents` from the installed Genesis packages. Don't edit this block; run `genesis agents` after upgrading Genesis.",
5380
+ "",
5381
+ `Before writing a screen, read \`${SKILL_PATH}\` (or run \`genesis primitives\`).`,
5382
+ "",
5383
+ ...RULES.map((r) => `- ${r}`),
5384
+ "",
5385
+ catalogTable(rows),
5386
+ AGENTS_END
5387
+ ].join("\n");
5388
+ }
5389
+ function blockSpan(text) {
5390
+ const s = text.indexOf(AGENTS_START);
5391
+ const e = text.indexOf(AGENTS_END);
5392
+ if (s < 0 && e < 0) return "absent";
5393
+ if (s < 0 || e < 0 || e < s || text.indexOf(AGENTS_START, s + 1) >= 0 || text.indexOf(AGENTS_END, e + 1) >= 0) return "broken";
5394
+ return { start: s, end: e + AGENTS_END.length };
5395
+ }
5396
+ function mergeAgentsBlock(agents, block) {
5397
+ const text = agents ?? "# Agent notes\n";
5398
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
5399
+ const own = block.replace(/\n/g, eol);
5400
+ const span = blockSpan(text);
5401
+ if (span === "broken") throw new Error(`AGENTS.md has a broken ${AGENTS_START} \u2026 ${AGENTS_END} block; fix it by hand.`);
5402
+ if (span === "absent") return `${text.replace(/\s*$/, "")}${eol}${eol}${own}${eol}`;
5403
+ return `${text.slice(0, span.start)}${own}${text.slice(span.end)}`;
5404
+ }
5405
+ function currentAgentsBlock(agents) {
5406
+ if (!agents) return null;
5407
+ const span = blockSpan(agents);
5408
+ if (span === "absent") return null;
5409
+ if (span === "broken") return "broken";
5410
+ return agents.slice(span.start, span.end).replace(/\r\n/g, "\n");
5411
+ }
5412
+ var read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
5413
+ function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
5414
+ const rows = primitivesCatalog(packages);
5415
+ const changed = [];
5416
+ const agents = path18.join(root, agentsFile);
5417
+ const before = read(agents);
5418
+ const after = mergeAgentsBlock(before, renderAgentsBlock(rows));
5419
+ const skill = path18.join(root, SKILL_PATH);
5420
+ const skillText = renderSkill(rows);
5421
+ if (read(skill)?.replace(/\r\n/g, "\n") !== skillText) {
5422
+ mkdirSync(path18.dirname(skill), { recursive: true });
5423
+ writeFileSync(skill, skillText);
5424
+ changed.push(SKILL_PATH);
5425
+ }
5426
+ if (before !== after) {
5427
+ writeFileSync(agents, after);
5428
+ changed.push(agentsFile);
5429
+ }
5430
+ return changed;
5431
+ }
5432
+ function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
5433
+ const rows = primitivesCatalog(packages);
5434
+ const skill = read(path18.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
5435
+ const block = currentAgentsBlock(read(path18.join(root, agentsFile)));
5436
+ return {
5437
+ skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
5438
+ agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
5439
+ };
5440
+ }
5441
+ function checkAgentGuide(ctx) {
5442
+ const state = agentGuideState(ctx.root, ctx.packages);
5443
+ if (state.skill === "missing" && state.agents === "missing") return;
5444
+ const fix = "run genesis agents and commit the result";
5445
+ if (state.skill !== "ok") {
5446
+ 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}` });
5447
+ }
5448
+ if (state.agents !== "ok") {
5449
+ const message = {
5450
+ missing: `has no genesis-primitives block; ${fix}`,
5451
+ 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}`,
5452
+ stale: `has a genesis-primitives block that doesn't match the installed Genesis packages; ${fix}`
5453
+ }[state.agents];
5454
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
5455
+ }
5456
+ }
3567
5457
  async function runDoctor(options = {}) {
3568
- const root = path14.resolve(options.root ?? process.cwd());
5458
+ const root = path18.resolve(options.root ?? process.cwd());
3569
5459
  const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
3570
5460
  const config = loaded.config;
3571
5461
  const genesis = options.genesis ?? loadGenesis(root, config);
3572
5462
  const files = scanFiles(root, config);
3573
5463
  const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
3574
5464
  const plugins = await loadPlugins(config.plugins, loaded.dir);
5465
+ const packages = discoverPackages(root);
5466
+ const packagePlugins = await packageRulesPlugins(packages);
3575
5467
  const builtinIds = new Set(BUILTIN_RULES);
3576
5468
  for (const p of config.patterns ?? []) {
3577
- if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
5469
+ 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`);
3578
5470
  }
3579
5471
  const raw = [];
3580
- const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
3581
- for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
5472
+ const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
5473
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
3582
5474
  try {
3583
5475
  await plugin.check(ctx);
3584
5476
  } catch (err) {
@@ -3590,7 +5482,34 @@ async function runDoctor(options = {}) {
3590
5482
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
3591
5483
  if (failure) raw.push(failure);
3592
5484
  }
3593
- const findings = applyConfig(raw, config);
5485
+ raw.push(...unknownPackageRuleSettings(config, packages, raw));
5486
+ const newOnly = /* @__PURE__ */ new Set([...patterns?.newOnly ?? [], ...preferRules(packages).filter((r) => r.newOnly).map((r) => r.ruleId)]);
5487
+ let changed = null;
5488
+ let skipped = false;
5489
+ if (options.base && (newOnly.size > 0 || config.ratchet)) {
5490
+ changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
5491
+ skipped ||= !changed;
5492
+ }
5493
+ const configFile = "file" in loaded ? loaded.file : null;
5494
+ const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
5495
+ let configSkipped = false;
5496
+ if (options.base && configFile) {
5497
+ const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
5498
+ if (before && before !== "absent") {
5499
+ raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
5500
+ raw.push(...rulesWeakened(config, before, options.base));
5501
+ }
5502
+ configSkipped = !before && guarded;
5503
+ }
5504
+ if (skipped || configSkipped) {
5505
+ raw.push(
5506
+ 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` }
5507
+ );
5508
+ }
5509
+ let findings = applyConfig(raw, config, packageRuleIds(packages));
5510
+ if (options.base && changed) {
5511
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path18.join(root, f)) });
5512
+ }
3594
5513
  const errors = findings.filter((f) => f.level === "error").length;
3595
5514
  const warnings = findings.filter((f) => f.level === "warn").length;
3596
5515
  const infos = findings.length - errors - warnings;
@@ -3601,12 +5520,13 @@ async function runDoctor(options = {}) {
3601
5520
  findings,
3602
5521
  unused: unusedComponents(ctx),
3603
5522
  ruleCount: (patterns?.count ?? 0) + plugins.length,
5523
+ primitives: primitivesSummary(packages),
3604
5524
  errors,
3605
5525
  warnings,
3606
5526
  infos
3607
5527
  };
3608
5528
  }
3609
- function builtinChecks(config) {
5529
+ function builtinChecks(config, options = {}) {
3610
5530
  const packs = {
3611
5531
  native: { name: "native", check: checkNativePack },
3612
5532
  supabase: { name: "supabase", check: checkSupabasePack },
@@ -3627,14 +5547,31 @@ function builtinChecks(config) {
3627
5547
  { name: "resource-workspaces", check: checkResourceWorkspaces },
3628
5548
  { name: "page-layouts", check: checkPageLayouts },
3629
5549
  { name: "iso-date-slices", check: checkIsoDateSlices },
3630
- ...(config.packs ?? []).map((p) => packs[p])
5550
+ { name: "resource-view-trees", check: checkTreeViews },
5551
+ { name: "studio-server-imports", check: checkStudioServerImports },
5552
+ { name: "removed-scope-names", check: checkRemovedScopeNames },
5553
+ { name: "agent-guide", check: checkAgentGuide },
5554
+ ...(config.packs ?? []).map((p) => packs[p]),
5555
+ ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
3631
5556
  ];
3632
5557
  }
3633
- function applyConfig(raw, config) {
5558
+ function applyConfig(raw, config, packageIds) {
3634
5559
  const allow = (config.allow ?? []).map((entry) => ({ entry, file: entry.file ? globToRegExp(entry.file) : null, used: false }));
3635
5560
  const out = [];
5561
+ const levelOf = (rule) => META_RULES.has(rule) ? void 0 : config.rules?.[rule] ?? config.packageRules?.[rule]?.level;
5562
+ for (const [rule, level] of Object.entries(config.rules ?? {})) {
5563
+ if (!packageIds.has(rule) || config.packageRules?.[rule]?.reason) continue;
5564
+ out.push({
5565
+ rule: "package-rule-override",
5566
+ level: "warn",
5567
+ file: "genesis config",
5568
+ line: 0,
5569
+ subject: rule,
5570
+ message: `rules sets the package rule ${rule} to "${level}" without a reason; move it to doctor.packageRules["${rule}"] with { "level": "${level}", "reason": "\u2026" }`
5571
+ });
5572
+ }
3636
5573
  for (const input of raw) {
3637
- const setting = config.rules?.[input.rule];
5574
+ const setting = levelOf(input.rule);
3638
5575
  if (setting === "off") continue;
3639
5576
  const finding = {
3640
5577
  rule: input.rule,
@@ -3645,7 +5582,7 @@ function applyConfig(raw, config) {
3645
5582
  ...input.subject !== void 0 ? { subject: input.subject } : {}
3646
5583
  };
3647
5584
  const exception = allow.find(
3648
- (a) => a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
5585
+ (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)
3649
5586
  );
3650
5587
  if (exception) {
3651
5588
  exception.used = true;
@@ -3655,7 +5592,7 @@ function applyConfig(raw, config) {
3655
5592
  }
3656
5593
  const staleLevel = config.rules?.["stale-exception"];
3657
5594
  for (const a of allow) {
3658
- if (staleLevel === "off" || a.used || config.rules?.[a.entry.rule] === "off") continue;
5595
+ if (staleLevel === "off" || a.used || levelOf(a.entry.rule) === "off") continue;
3659
5596
  out.push({
3660
5597
  rule: "stale-exception",
3661
5598
  level: staleLevel ?? "warn",
@@ -3676,6 +5613,7 @@ function formatReport(result) {
3676
5613
  lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
3677
5614
  }
3678
5615
  lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
5616
+ lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis primitives`);
3679
5617
  const info = result.infos ? `, ${result.infos} info` : "";
3680
5618
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
3681
5619
  return lines.join("\n");
@@ -3688,7 +5626,8 @@ function toJson(result) {
3688
5626
  warnings: result.warnings,
3689
5627
  infos: result.infos,
3690
5628
  findings: result.findings,
3691
- unused: result.unused
5629
+ unused: result.unused,
5630
+ primitives: result.primitives
3692
5631
  };
3693
5632
  }
3694
5633
  function genesisSummary(g) {
@@ -3702,6 +5641,6 @@ function genesisSummary(g) {
3702
5641
  };
3703
5642
  }
3704
5643
 
3705
- export { BUILTIN_RULES, DoctorConfigError, GenesisConfigError, builtinChecks, defineDoctorPlugin, findPackageDir, formatReport, genesisInstalls, genesisSummary, globToRegExp, loadConfig, loadGenesis, nativeLayouts, parseExportNames, parseRulesMarkdown, readGenesisConfig, readPackageExports, readReleaseManifest, routesDir, runDoctor, satisfies, sqlStatements, toJson, validateConfig, validateLinks, webRoutes };
5644
+ export { BUILTIN_RULES, DoctorConfigError, GenesisConfigError, PackageDeclarationError, SKILL_PATH, agentGuideState, builtinChecks, catalogTable, changedSince, clearPackageRulesCache, defineDoctorPlugin, discoverPackages, findPackageDir, formatPrimitives, formatReport, genesisInstalls, genesisSummary, globToRegExp, loadConfig, loadGenesis, nativeLayouts, parseExportNames, parseRulesMarkdown, postgresContract, postgresSource, preferRules, primitivesCatalog, primitivesSummary, readGenesisConfig, readPackageExports, readReleaseManifest, renderAgentsBlock, renderSkill, routesDir, ruleNamespace, runDoctor, satisfies, sqlStatements, toJson, validateConfig, validateDeclaration, validateLinks, webRoutes, writeAgentGuide };
3706
5645
  //# sourceMappingURL=doctor.js.map
3707
5646
  //# sourceMappingURL=doctor.js.map