@marktiderman/genesis-cli 1.1.0 → 1.2.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/README.md +181 -4
- package/dist/cli.js +1145 -27
- package/dist/cli.js.map +1 -1
- package/dist/doctor.d.ts +232 -0
- package/dist/doctor.js +1021 -0
- package/dist/doctor.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1011 -13
- package/dist/index.js.map +1 -1
- package/dist/vite.d.ts +15 -0
- package/dist/vite.js +1092 -0
- package/dist/vite.js.map +1 -0
- package/package.json +21 -4
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from 'child_process';
|
|
3
|
+
import { readFileSync, existsSync, statSync, readdirSync } from 'fs';
|
|
4
|
+
import * as path3 from 'path';
|
|
2
5
|
import { createRequire } from 'module';
|
|
6
|
+
import { pathToFileURL } from 'url';
|
|
3
7
|
import { studioSetupSql } from '@marktiderman/genesis-studio-server';
|
|
4
8
|
import { Command } from 'commander';
|
|
5
9
|
import * as fs from 'fs/promises';
|
|
6
|
-
import * as path from 'path';
|
|
7
10
|
|
|
8
11
|
var __defProp = Object.defineProperty;
|
|
9
12
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
@@ -329,6 +332,1099 @@ var init_introspect = __esm({
|
|
|
329
332
|
init_comments();
|
|
330
333
|
}
|
|
331
334
|
});
|
|
335
|
+
function buildCommands(root, config) {
|
|
336
|
+
if (config.build) return config.build;
|
|
337
|
+
const pkgFile = path3.join(root, "package.json");
|
|
338
|
+
const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
|
|
339
|
+
const pm = packageManager(root);
|
|
340
|
+
return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
|
|
341
|
+
}
|
|
342
|
+
function packageManager(root) {
|
|
343
|
+
let dir = path3.resolve(root);
|
|
344
|
+
for (; ; ) {
|
|
345
|
+
if (existsSync(path3.join(dir, "pnpm-lock.yaml"))) return "pnpm";
|
|
346
|
+
if (existsSync(path3.join(dir, "bun.lock")) || existsSync(path3.join(dir, "bun.lockb"))) return "bun";
|
|
347
|
+
if (existsSync(path3.join(dir, "yarn.lock"))) return "yarn";
|
|
348
|
+
if (existsSync(path3.join(dir, "package-lock.json"))) return "npm";
|
|
349
|
+
const parent = path3.dirname(dir);
|
|
350
|
+
if (parent === dir) return "npm";
|
|
351
|
+
dir = parent;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function runBuild(root, commands, quiet) {
|
|
355
|
+
if (process.env[BUILD_GUARD_ENV]) return null;
|
|
356
|
+
if (commands.length === 0) {
|
|
357
|
+
return { rule: "build", level: "warn", file: "package.json", message: "--build found nothing to run: add typecheck/build scripts or doctor.build" };
|
|
358
|
+
}
|
|
359
|
+
for (const command of commands) {
|
|
360
|
+
const r = spawnSync(command, {
|
|
361
|
+
cwd: root,
|
|
362
|
+
shell: true,
|
|
363
|
+
stdio: quiet ? "pipe" : "inherit",
|
|
364
|
+
env: { ...process.env, [BUILD_GUARD_ENV]: "1" }
|
|
365
|
+
});
|
|
366
|
+
if (r.status !== 0) {
|
|
367
|
+
const tail = quiet ? `
|
|
368
|
+
${String(r.stderr ?? "").trim().split("\n").slice(-20).join("\n")}` : "";
|
|
369
|
+
return { rule: "build", file: command, message: `\`${command}\` failed (exit ${r.status ?? r.signal})${tail}` };
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
var BUILD_GUARD_ENV;
|
|
375
|
+
var init_build = __esm({
|
|
376
|
+
"src/doctor/build.ts"() {
|
|
377
|
+
BUILD_GUARD_ENV = "GENESIS_DOCTOR_BUILDING";
|
|
378
|
+
}
|
|
379
|
+
});
|
|
380
|
+
function loadConfig(root, configPath) {
|
|
381
|
+
if (configPath) {
|
|
382
|
+
const file = path3.resolve(root, configPath);
|
|
383
|
+
if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
|
|
384
|
+
const json = readJson(file);
|
|
385
|
+
const block = path3.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
|
|
386
|
+
return { config: validateConfig(block ?? {}, file), file, dir: path3.dirname(file) };
|
|
387
|
+
}
|
|
388
|
+
const own = path3.join(root, "genesis.config.json");
|
|
389
|
+
if (existsSync(own)) {
|
|
390
|
+
return { config: validateConfig(readJson(own)?.doctor ?? {}, own), file: own, dir: root };
|
|
391
|
+
}
|
|
392
|
+
const pkg = path3.join(root, "package.json");
|
|
393
|
+
if (existsSync(pkg)) {
|
|
394
|
+
const block = readJson(pkg)?.genesis?.doctor;
|
|
395
|
+
if (block !== void 0) return { config: validateConfig(block, pkg), file: pkg, dir: root };
|
|
396
|
+
}
|
|
397
|
+
return { config: {}, file: null, dir: root };
|
|
398
|
+
}
|
|
399
|
+
function readJson(file) {
|
|
400
|
+
try {
|
|
401
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
402
|
+
} catch (err) {
|
|
403
|
+
throw new DoctorConfigError(`${file} is not valid JSON: ${err.message}`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
function validateConfig(raw, source = "config") {
|
|
407
|
+
const fail = (msg) => {
|
|
408
|
+
throw new DoctorConfigError(`${source}: ${msg}`);
|
|
409
|
+
};
|
|
410
|
+
if (!isObject(raw)) fail("the doctor settings must be an object");
|
|
411
|
+
const c = raw;
|
|
412
|
+
for (const key of Object.keys(c)) if (!KNOWN.has(key)) fail(`unknown setting "${key}"`);
|
|
413
|
+
if (typeof c.themeCss === "string") c.themeCss = [c.themeCss];
|
|
414
|
+
if (c.themeCss !== void 0 && !isStringList(c.themeCss)) fail(`"themeCss" must be a path or a list of paths`);
|
|
415
|
+
for (const key of STRING_LISTS) {
|
|
416
|
+
if (c[key] !== void 0 && !isStringList(c[key])) fail(`"${key}" must be a list of strings`);
|
|
417
|
+
}
|
|
418
|
+
for (const key of STRINGS) {
|
|
419
|
+
if (c[key] !== void 0 && typeof c[key] !== "string") fail(`"${key}" must be a string`);
|
|
420
|
+
}
|
|
421
|
+
if (c.rawTags !== void 0) {
|
|
422
|
+
if (!isObject(c.rawTags)) fail(`"rawTags" must be an object`);
|
|
423
|
+
for (const [tag, v] of Object.entries(c.rawTags)) {
|
|
424
|
+
if (!/^[a-z][a-z0-9-]*$/.test(tag)) fail(`rawTags: "${tag}" is not an HTML tag name`);
|
|
425
|
+
if (v !== false && typeof v !== "string") fail(`rawTags.${tag} must be a component name or false`);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (c.forbiddenImports !== void 0) {
|
|
429
|
+
if (!isObject(c.forbiddenImports)) fail(`"forbiddenImports" must be an object of pattern \u2192 message`);
|
|
430
|
+
for (const [re, msg] of Object.entries(c.forbiddenImports)) {
|
|
431
|
+
if (typeof msg !== "string") fail(`forbiddenImports["${re}"] must be a message string`);
|
|
432
|
+
checkRegExp(re, `forbiddenImports["${re}"]`, fail);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
if (c.rules !== void 0) {
|
|
436
|
+
if (!isObject(c.rules)) fail(`"rules" must be an object of rule \u2192 level`);
|
|
437
|
+
for (const [rule, level] of Object.entries(c.rules)) {
|
|
438
|
+
if (!LEVELS.has(level)) fail(`rules.${rule} must be "error", "warn" or "off"`);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
if (c.allow !== void 0) {
|
|
442
|
+
if (!Array.isArray(c.allow)) fail(`"allow" must be a list`);
|
|
443
|
+
c.allow.forEach((e, i) => {
|
|
444
|
+
if (!isObject(e)) return fail(`allow[${i}] must be an object`);
|
|
445
|
+
const entry = e;
|
|
446
|
+
if (typeof entry.rule !== "string" || !entry.rule) fail(`allow[${i}] needs a "rule"`);
|
|
447
|
+
if (typeof entry.reason !== "string" || !entry.reason.trim()) fail(`allow[${i}] (${entry.rule}) needs a "reason"`);
|
|
448
|
+
for (const k of ["file", "match"]) {
|
|
449
|
+
if (entry[k] !== void 0 && typeof entry[k] !== "string") fail(`allow[${i}].${k} must be a string`);
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
if (c.patterns !== void 0) {
|
|
454
|
+
if (!Array.isArray(c.patterns)) fail(`"patterns" must be a list`);
|
|
455
|
+
c.patterns.forEach((p, i) => {
|
|
456
|
+
if (!isObject(p)) return fail(`patterns[${i}] must be an object`);
|
|
457
|
+
const rule = p;
|
|
458
|
+
for (const k of Object.keys(rule)) if (!PATTERN_KEYS.has(k)) fail(`patterns[${i}]: unknown key "${k}"`);
|
|
459
|
+
if (typeof rule.id !== "string" || !rule.id) fail(`patterns[${i}] needs an "id"`);
|
|
460
|
+
for (const k of ["files", "exclude"]) {
|
|
461
|
+
if (rule[k] !== void 0 && !isStringList(rule[k])) fail(`patterns[${i}].${k} must be a list of globs`);
|
|
462
|
+
}
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
if (c.plugins !== void 0) {
|
|
466
|
+
const ok = Array.isArray(c.plugins) && c.plugins.every((p) => typeof p === "string" || Array.isArray(p) && p.length === 2 && typeof p[0] === "string");
|
|
467
|
+
if (!ok) fail(`"plugins" must be a list of module paths or [path, options] pairs`);
|
|
468
|
+
}
|
|
469
|
+
return c;
|
|
470
|
+
}
|
|
471
|
+
function checkRegExp(source, where, fail) {
|
|
472
|
+
try {
|
|
473
|
+
new RegExp(source);
|
|
474
|
+
} catch (err) {
|
|
475
|
+
fail(`${where} is not a valid regular expression: ${err.message}`);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
function isObject(v) {
|
|
479
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
480
|
+
}
|
|
481
|
+
function isStringList(v) {
|
|
482
|
+
return Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
483
|
+
}
|
|
484
|
+
var DoctorConfigError, STRING_LISTS, STRINGS, KNOWN, LEVELS, PATTERN_KEYS;
|
|
485
|
+
var init_config = __esm({
|
|
486
|
+
"src/doctor/config.ts"() {
|
|
487
|
+
DoctorConfigError = class extends Error {
|
|
488
|
+
name = "DoctorConfigError";
|
|
489
|
+
};
|
|
490
|
+
STRING_LISTS = ["src", "extensions", "ignore", "tokenFiles", "ignoreTokenPrefixes", "localPrimitiveDirs", "build"];
|
|
491
|
+
STRINGS = ["uiPackage", "rulesDoc"];
|
|
492
|
+
KNOWN = /* @__PURE__ */ new Set([
|
|
493
|
+
...STRING_LISTS,
|
|
494
|
+
...STRINGS,
|
|
495
|
+
"themeCss",
|
|
496
|
+
"rawTags",
|
|
497
|
+
"forbiddenImports",
|
|
498
|
+
"rules",
|
|
499
|
+
"allow",
|
|
500
|
+
"patterns",
|
|
501
|
+
"plugins",
|
|
502
|
+
"$schema",
|
|
503
|
+
"$comment"
|
|
504
|
+
]);
|
|
505
|
+
LEVELS = /* @__PURE__ */ new Set(["error", "warn", "off"]);
|
|
506
|
+
PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
|
|
507
|
+
}
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
// src/doctor/glob.ts
|
|
511
|
+
function globToRegExp(glob) {
|
|
512
|
+
let g = glob.trim().replace(/^\.\//, "");
|
|
513
|
+
if (g.endsWith("/")) g += "**";
|
|
514
|
+
let out = "";
|
|
515
|
+
for (let i = 0; i < g.length; i++) {
|
|
516
|
+
const ch = g[i];
|
|
517
|
+
if (ch === "*") {
|
|
518
|
+
if (g[i + 1] === "*") {
|
|
519
|
+
const slash = g[i + 2] === "/";
|
|
520
|
+
out += slash ? "(?:.*/)?" : ".*";
|
|
521
|
+
i += slash ? 2 : 1;
|
|
522
|
+
} else {
|
|
523
|
+
out += "[^/]*";
|
|
524
|
+
}
|
|
525
|
+
} else if (ch === "?") {
|
|
526
|
+
out += "[^/]";
|
|
527
|
+
} else {
|
|
528
|
+
out += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return new RegExp(`^${out}$`);
|
|
532
|
+
}
|
|
533
|
+
function globMatcher(globs) {
|
|
534
|
+
const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
|
|
535
|
+
return (path10) => res.some((re) => re.test(path10));
|
|
536
|
+
}
|
|
537
|
+
var init_glob = __esm({
|
|
538
|
+
"src/doctor/glob.ts"() {
|
|
539
|
+
}
|
|
540
|
+
});
|
|
541
|
+
function findPackageDir(from, name) {
|
|
542
|
+
let dir = path3.resolve(from);
|
|
543
|
+
for (; ; ) {
|
|
544
|
+
const candidate = path3.join(dir, "node_modules", name);
|
|
545
|
+
if (existsSync(path3.join(candidate, "package.json"))) return candidate;
|
|
546
|
+
const parent = path3.dirname(dir);
|
|
547
|
+
if (parent === dir) return null;
|
|
548
|
+
dir = parent;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
function loadGenesis(root, config) {
|
|
552
|
+
const uiPackage = config.uiPackage ?? DEFAULT_UI_PACKAGE;
|
|
553
|
+
const uiDir = findPackageDir(root, uiPackage);
|
|
554
|
+
if (!uiDir) throw new DoctorConfigError(`${uiPackage} is not installed here. Install it, or set doctor.uiPackage.`);
|
|
555
|
+
const uiPkg = JSON.parse(readFileSync(path3.join(uiDir, "package.json"), "utf8"));
|
|
556
|
+
const typeEntries = /* @__PURE__ */ new Set();
|
|
557
|
+
const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
|
|
558
|
+
if (typeof mainTypes === "string") typeEntries.add(mainTypes);
|
|
559
|
+
for (const target of Object.values(uiPkg.exports ?? {})) {
|
|
560
|
+
const t = exportTypes(target);
|
|
561
|
+
if (typeof t === "string" && !t.includes("*")) typeEntries.add(t);
|
|
562
|
+
}
|
|
563
|
+
const exportNames = /* @__PURE__ */ new Set();
|
|
564
|
+
const reexportedPackages = /* @__PURE__ */ new Set();
|
|
565
|
+
let readAny = false;
|
|
566
|
+
for (const entry of typeEntries) {
|
|
567
|
+
const file = path3.join(uiDir, entry);
|
|
568
|
+
if (!existsSync(file)) continue;
|
|
569
|
+
readAny = true;
|
|
570
|
+
const dts = readFileSync(file, "utf8");
|
|
571
|
+
for (const name of parseExportNames(dts)) exportNames.add(name);
|
|
572
|
+
for (const m of dts.matchAll(/export\s+(?:type\s+)?(?:\{[^}]*\}|\*)\s*from\s*["']([^"'.][^"']*)["']/g)) {
|
|
573
|
+
reexportedPackages.add(packageName(m[1]));
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
if (!readAny) {
|
|
577
|
+
throw new DoctorConfigError(`${uiPackage} has no type declarations to read (is it built?). Looked for: ${[...typeEntries].join(", ") || "none"}`);
|
|
578
|
+
}
|
|
579
|
+
const valueDecls = /* @__PURE__ */ new Set();
|
|
580
|
+
const typeDecls = /* @__PURE__ */ new Set();
|
|
581
|
+
const declRoot = typeof mainTypes === "string" ? path3.dirname(path3.join(uiDir, mainTypes)) : uiDir;
|
|
582
|
+
const declFiles = walkDts(declRoot);
|
|
583
|
+
for (const pkg of reexportedPackages) {
|
|
584
|
+
const dir = findPackageDir(uiDir, pkg);
|
|
585
|
+
if (dir) walkDts(path3.join(dir, "dist"), declFiles);
|
|
586
|
+
}
|
|
587
|
+
for (const file of declFiles) {
|
|
588
|
+
const text = readFileSync(file, "utf8");
|
|
589
|
+
for (const m of text.matchAll(/\b(?:declare\s+)?(?:const|let|var|function|class|enum)\s+([A-Za-z_$][\w$]*)/g)) valueDecls.add(m[1]);
|
|
590
|
+
for (const m of text.matchAll(/\b(?:interface|type)\s+([A-Za-z_$][\w$]*)/g)) typeDecls.add(m[1]);
|
|
591
|
+
}
|
|
592
|
+
const isTypeOnly = (n) => typeDecls.has(n) && !valueDecls.has(n);
|
|
593
|
+
const values = new Set([...exportNames].filter((n) => !isTypeOnly(n)));
|
|
594
|
+
const components = [...values].filter((n) => /^[A-Z][A-Za-z0-9]*$/.test(n) && !(n.length > 2 && n === n.toUpperCase()) && !NON_COMPONENT_SUFFIX.test(n)).sort();
|
|
595
|
+
const tokens = /* @__PURE__ */ new Set();
|
|
596
|
+
const themeFiles = resolveThemeFiles(root, config, uiDir);
|
|
597
|
+
for (const file of themeFiles) for (const t of declaredTokens(readFileSync(file, "utf8"))) tokens.add(t);
|
|
598
|
+
const byLower = new Map(components.map((c) => [c.toLowerCase(), c]));
|
|
599
|
+
const rawTags = /* @__PURE__ */ new Map();
|
|
600
|
+
for (const tag of TAGS) if (byLower.has(tag)) rawTags.set(tag, byLower.get(tag));
|
|
601
|
+
for (const [tag, comp] of Object.entries(TAG_ALIASES)) if (values.has(comp)) rawTags.set(tag, comp);
|
|
602
|
+
for (const [tag, comp] of Object.entries(config.rawTags ?? {})) {
|
|
603
|
+
if (comp === false) rawTags.delete(tag);
|
|
604
|
+
else rawTags.set(tag, comp);
|
|
605
|
+
}
|
|
606
|
+
return {
|
|
607
|
+
uiPackage,
|
|
608
|
+
uiVersion: String(uiPkg.version ?? "unknown"),
|
|
609
|
+
exports: exportNames,
|
|
610
|
+
values,
|
|
611
|
+
components,
|
|
612
|
+
tokens,
|
|
613
|
+
rawTags,
|
|
614
|
+
palette: loadPalette(root)
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
function parseExportNames(dts) {
|
|
618
|
+
const names = [];
|
|
619
|
+
for (const m of dts.matchAll(/export\s+(?:type\s+)?\{([^}]*)\}/g)) {
|
|
620
|
+
for (const part of m[1].split(",")) {
|
|
621
|
+
const name = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/).pop()?.trim();
|
|
622
|
+
if (name && name !== "default") names.push(name);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
for (const m of dts.matchAll(/export\s+(?:declare\s+)?(?:const|let|function|class|enum|interface|type)\s+([A-Za-z_$][\w$]*)/g)) {
|
|
626
|
+
names.push(m[1]);
|
|
627
|
+
}
|
|
628
|
+
return names;
|
|
629
|
+
}
|
|
630
|
+
function declaredTokens(css) {
|
|
631
|
+
return [...css.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)].map((m) => m[1]);
|
|
632
|
+
}
|
|
633
|
+
function packageName(specifier) {
|
|
634
|
+
const parts = specifier.split("/");
|
|
635
|
+
return parts.slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
|
|
636
|
+
}
|
|
637
|
+
function exportTypes(target) {
|
|
638
|
+
if (!target || typeof target !== "object") return void 0;
|
|
639
|
+
const t = target;
|
|
640
|
+
if (typeof t.types === "string") return t.types;
|
|
641
|
+
for (const key of ["import", "default", "require"]) {
|
|
642
|
+
const nested = exportTypes(t[key]);
|
|
643
|
+
if (nested) return nested;
|
|
644
|
+
}
|
|
645
|
+
return void 0;
|
|
646
|
+
}
|
|
647
|
+
function walkDts(dir, out = []) {
|
|
648
|
+
if (!existsSync(dir)) return out;
|
|
649
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
650
|
+
if (entry.name === "node_modules") continue;
|
|
651
|
+
const p = path3.join(dir, entry.name);
|
|
652
|
+
if (entry.isDirectory()) walkDts(p, out);
|
|
653
|
+
else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
|
|
654
|
+
}
|
|
655
|
+
return out;
|
|
656
|
+
}
|
|
657
|
+
function resolveThemeFiles(root, config, uiDir) {
|
|
658
|
+
if (config.themeCss) {
|
|
659
|
+
const specs = typeof config.themeCss === "string" ? [config.themeCss] : config.themeCss;
|
|
660
|
+
return specs.map((spec) => {
|
|
661
|
+
const file = resolveSpec(root, spec);
|
|
662
|
+
if (!file) throw new DoctorConfigError(`doctor.themeCss: cannot find ${spec}`);
|
|
663
|
+
return file;
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
const files = [];
|
|
667
|
+
const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
|
|
668
|
+
const themes = ds && path3.join(ds, "dist", "themes");
|
|
669
|
+
if (themes && existsSync(themes)) {
|
|
670
|
+
for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path3.join(themes, name));
|
|
671
|
+
}
|
|
672
|
+
if (files.length === 0) {
|
|
673
|
+
throw new DoctorConfigError(
|
|
674
|
+
`No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
|
|
675
|
+
);
|
|
676
|
+
}
|
|
677
|
+
const uiStyles = path3.join(uiDir, "dist", "styles.css");
|
|
678
|
+
if (existsSync(uiStyles)) files.push(uiStyles);
|
|
679
|
+
return files;
|
|
680
|
+
}
|
|
681
|
+
function resolveSpec(root, spec) {
|
|
682
|
+
const local = path3.resolve(root, spec);
|
|
683
|
+
if (spec.startsWith(".") || path3.isAbsolute(spec)) return existsSync(local) ? local : null;
|
|
684
|
+
const parts = spec.split("/");
|
|
685
|
+
const nameLength = spec.startsWith("@") ? 2 : 1;
|
|
686
|
+
const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
|
|
687
|
+
if (dir) {
|
|
688
|
+
const file = path3.join(dir, ...parts.slice(nameLength));
|
|
689
|
+
if (existsSync(file) && statSync(file).isFile()) return file;
|
|
690
|
+
}
|
|
691
|
+
return existsSync(local) ? local : null;
|
|
692
|
+
}
|
|
693
|
+
function loadPalette(root) {
|
|
694
|
+
const names = new Set(TAILWIND_PALETTE);
|
|
695
|
+
try {
|
|
696
|
+
const req = createRequire(path3.join(root, "package.json"));
|
|
697
|
+
const colors = req("tailwindcss/colors");
|
|
698
|
+
for (const key of Object.keys(colors?.default ?? colors ?? {})) {
|
|
699
|
+
if (/^[a-z]+$/.test(key) && !["inherit", "current", "transparent"].includes(key)) names.add(key);
|
|
700
|
+
}
|
|
701
|
+
} catch {
|
|
702
|
+
}
|
|
703
|
+
return [...names].sort();
|
|
704
|
+
}
|
|
705
|
+
var DEFAULT_UI_PACKAGE, DESIGN_SYSTEM_PACKAGE, TAGS, TAG_ALIASES, NON_COMPONENT_SUFFIX, TAILWIND_PALETTE;
|
|
706
|
+
var init_genesis = __esm({
|
|
707
|
+
"src/doctor/genesis.ts"() {
|
|
708
|
+
init_config();
|
|
709
|
+
DEFAULT_UI_PACKAGE = "@marktiderman/genesis-ui";
|
|
710
|
+
DESIGN_SYSTEM_PACKAGE = "@marktiderman/genesis-design-system";
|
|
711
|
+
TAGS = ["button", "input", "textarea", "select", "label", "table", "dialog", "progress", "details", "summary"];
|
|
712
|
+
TAG_ALIASES = { hr: "Separator" };
|
|
713
|
+
NON_COMPONENT_SUFFIX = /(Props|Variant|Variants|Type|Types|Config|Context|Options|Status)$/;
|
|
714
|
+
TAILWIND_PALETTE = [
|
|
715
|
+
"black",
|
|
716
|
+
"white",
|
|
717
|
+
"slate",
|
|
718
|
+
"gray",
|
|
719
|
+
"zinc",
|
|
720
|
+
"neutral",
|
|
721
|
+
"stone",
|
|
722
|
+
"red",
|
|
723
|
+
"orange",
|
|
724
|
+
"amber",
|
|
725
|
+
"yellow",
|
|
726
|
+
"lime",
|
|
727
|
+
"green",
|
|
728
|
+
"emerald",
|
|
729
|
+
"teal",
|
|
730
|
+
"cyan",
|
|
731
|
+
"sky",
|
|
732
|
+
"blue",
|
|
733
|
+
"indigo",
|
|
734
|
+
"violet",
|
|
735
|
+
"purple",
|
|
736
|
+
"fuchsia",
|
|
737
|
+
"pink",
|
|
738
|
+
"rose",
|
|
739
|
+
"taupe",
|
|
740
|
+
"mauve",
|
|
741
|
+
"mist",
|
|
742
|
+
"olive"
|
|
743
|
+
];
|
|
744
|
+
}
|
|
745
|
+
});
|
|
746
|
+
|
|
747
|
+
// ../../scripts/lib/color-literals.mjs
|
|
748
|
+
function stripBlockComments(content, hasLineComments = true) {
|
|
749
|
+
let result = "";
|
|
750
|
+
let i = 0;
|
|
751
|
+
const len = content.length;
|
|
752
|
+
while (i < len) {
|
|
753
|
+
const ch = content[i];
|
|
754
|
+
const next = i + 1 < len ? content[i + 1] : "";
|
|
755
|
+
const prevIsColon = i > 0 && content[i - 1] === ":";
|
|
756
|
+
const prevIsBackslash = i > 0 && content[i - 1] === "\\";
|
|
757
|
+
if (ch === '"') {
|
|
758
|
+
result += ch;
|
|
759
|
+
i++;
|
|
760
|
+
while (i < len) {
|
|
761
|
+
const c = content[i];
|
|
762
|
+
result += c;
|
|
763
|
+
if (c === "\\" && i + 1 < len) {
|
|
764
|
+
result += content[i + 1];
|
|
765
|
+
i += 2;
|
|
766
|
+
} else if (c === '"') {
|
|
767
|
+
i++;
|
|
768
|
+
break;
|
|
769
|
+
} else {
|
|
770
|
+
i++;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
if (ch === "'") {
|
|
776
|
+
result += ch;
|
|
777
|
+
i++;
|
|
778
|
+
while (i < len) {
|
|
779
|
+
const c = content[i];
|
|
780
|
+
result += c;
|
|
781
|
+
if (c === "\\" && i + 1 < len) {
|
|
782
|
+
result += content[i + 1];
|
|
783
|
+
i += 2;
|
|
784
|
+
} else if (c === "'") {
|
|
785
|
+
i++;
|
|
786
|
+
break;
|
|
787
|
+
} else {
|
|
788
|
+
i++;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
if (ch === "`") {
|
|
794
|
+
result += ch;
|
|
795
|
+
i++;
|
|
796
|
+
while (i < len) {
|
|
797
|
+
const c = content[i];
|
|
798
|
+
result += c;
|
|
799
|
+
if (c === "\\" && i + 1 < len) {
|
|
800
|
+
result += content[i + 1];
|
|
801
|
+
i += 2;
|
|
802
|
+
} else if (c === "`") {
|
|
803
|
+
i++;
|
|
804
|
+
break;
|
|
805
|
+
} else {
|
|
806
|
+
i++;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
continue;
|
|
810
|
+
}
|
|
811
|
+
if ((ch === "u" || ch === "U") && content.slice(i, i + 4).toLowerCase() === "url(" && !/[\w$]/.test(content[i - 1] ?? "")) {
|
|
812
|
+
result += content.slice(i, i + 4);
|
|
813
|
+
i += 4;
|
|
814
|
+
while (i < len && content[i] !== ")") {
|
|
815
|
+
const c = content[i];
|
|
816
|
+
if (c === '"' || c === "'") {
|
|
817
|
+
result += c;
|
|
818
|
+
i++;
|
|
819
|
+
while (i < len) {
|
|
820
|
+
const q = content[i];
|
|
821
|
+
result += q;
|
|
822
|
+
if (q === "\\" && i + 1 < len) {
|
|
823
|
+
result += content[i + 1];
|
|
824
|
+
i += 2;
|
|
825
|
+
} else if (q === c) {
|
|
826
|
+
i++;
|
|
827
|
+
break;
|
|
828
|
+
} else {
|
|
829
|
+
i++;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
} else {
|
|
833
|
+
result += c;
|
|
834
|
+
i++;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
if (i < len && content[i] === ")") {
|
|
838
|
+
result += ")";
|
|
839
|
+
i++;
|
|
840
|
+
}
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
if (hasLineComments && ch === "/" && next === "/" && !prevIsColon && !prevIsBackslash) {
|
|
844
|
+
let j = i + 2;
|
|
845
|
+
while (j < len && content[j] !== "\n") {
|
|
846
|
+
j++;
|
|
847
|
+
}
|
|
848
|
+
const commentLen = j - i;
|
|
849
|
+
const commentText = content.slice(i, i + commentLen);
|
|
850
|
+
result += commentText.replace(/[^\n]/g, " ");
|
|
851
|
+
i += commentLen;
|
|
852
|
+
continue;
|
|
853
|
+
}
|
|
854
|
+
if (ch === "/" && next === "*") {
|
|
855
|
+
let commentLen = 2;
|
|
856
|
+
let j = i + 2;
|
|
857
|
+
while (j < len) {
|
|
858
|
+
if (content[j] === "*" && j + 1 < len && content[j + 1] === "/") {
|
|
859
|
+
commentLen = j + 2 - i;
|
|
860
|
+
break;
|
|
861
|
+
}
|
|
862
|
+
j++;
|
|
863
|
+
}
|
|
864
|
+
const commentText = content.slice(i, i + commentLen);
|
|
865
|
+
result += commentText.replace(/[^\n]/g, " ");
|
|
866
|
+
i += commentLen;
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
result += ch;
|
|
870
|
+
i++;
|
|
871
|
+
}
|
|
872
|
+
return result;
|
|
873
|
+
}
|
|
874
|
+
function stripHtmlEntities(line) {
|
|
875
|
+
return line.replace(HTML_ENTITY_RE, "");
|
|
876
|
+
}
|
|
877
|
+
function findHexLiterals(line) {
|
|
878
|
+
const cleaned = stripHtmlEntities(line);
|
|
879
|
+
const matches = [];
|
|
880
|
+
let m;
|
|
881
|
+
HEX_RE.lastIndex = 0;
|
|
882
|
+
while ((m = HEX_RE.exec(cleaned)) !== null) {
|
|
883
|
+
const digits = m[2];
|
|
884
|
+
if (digits.length <= 4 && !HEX_LETTER_RE.test(digits)) continue;
|
|
885
|
+
const literal = `#${digits}`;
|
|
886
|
+
const idx = m.index + m[1].length;
|
|
887
|
+
matches.push({ literal, column: idx + 1 });
|
|
888
|
+
}
|
|
889
|
+
return matches;
|
|
890
|
+
}
|
|
891
|
+
function findColorFunctions(line) {
|
|
892
|
+
const cleaned = stripHtmlEntities(line);
|
|
893
|
+
const matches = [];
|
|
894
|
+
let m;
|
|
895
|
+
COLOR_FN_RE.lastIndex = 0;
|
|
896
|
+
while ((m = COLOR_FN_RE.exec(cleaned)) !== null) {
|
|
897
|
+
matches.push({ literal: m[0], column: m.index + 1 });
|
|
898
|
+
}
|
|
899
|
+
return matches;
|
|
900
|
+
}
|
|
901
|
+
var LINE_COMMENT_EXTS, HTML_ENTITY_RE, HEX_RE, HEX_LETTER_RE, COLOR_FN_RE;
|
|
902
|
+
var init_color_literals = __esm({
|
|
903
|
+
"../../scripts/lib/color-literals.mjs"() {
|
|
904
|
+
LINE_COMMENT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".jsx", ".js", ".mjs", ".cjs", ".scss", ".less"]);
|
|
905
|
+
HTML_ENTITY_RE = /&#\d+;/g;
|
|
906
|
+
HEX_RE = /(^|[^\w&])#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b/g;
|
|
907
|
+
HEX_LETTER_RE = /[a-fA-F]/;
|
|
908
|
+
COLOR_FN_RE = /\b(rgba?|hsla?)\(\s*[\d.][^)\n]*\)?/gi;
|
|
909
|
+
}
|
|
910
|
+
});
|
|
911
|
+
function scanFiles(root, config) {
|
|
912
|
+
const extensions = new Set(config.extensions ?? DEFAULT_EXTENSIONS);
|
|
913
|
+
const ignored = globMatcher([...DEFAULT_IGNORE, ...config.ignore ?? []]);
|
|
914
|
+
const files = [];
|
|
915
|
+
const seen = /* @__PURE__ */ new Set();
|
|
916
|
+
const visit = (abs) => {
|
|
917
|
+
const rel = toPosix(path3.relative(root, abs));
|
|
918
|
+
if (seen.has(rel) || ignored(rel)) return;
|
|
919
|
+
const ext = path3.extname(abs);
|
|
920
|
+
if (!extensions.has(ext)) return;
|
|
921
|
+
if (statSync(abs).size > MAX_FILE_BYTES) return;
|
|
922
|
+
seen.add(rel);
|
|
923
|
+
const text = readFileSync(abs, "utf8");
|
|
924
|
+
files.push({ path: rel, absolutePath: abs, ext, text, code: stripBlockComments(text, LINE_COMMENT_EXTS.has(ext)) });
|
|
925
|
+
};
|
|
926
|
+
const walk = (dir) => {
|
|
927
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
928
|
+
if (entry.isDirectory()) {
|
|
929
|
+
if (!SKIP_DIRS.has(entry.name)) walk(path3.join(dir, entry.name));
|
|
930
|
+
} else if (entry.isFile()) {
|
|
931
|
+
visit(path3.join(dir, entry.name));
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
for (const src of config.src ?? DEFAULT_SRC) {
|
|
936
|
+
const abs = path3.resolve(root, src);
|
|
937
|
+
if (!existsSync(abs)) continue;
|
|
938
|
+
if (statSync(abs).isDirectory()) walk(abs);
|
|
939
|
+
else visit(abs);
|
|
940
|
+
}
|
|
941
|
+
return files;
|
|
942
|
+
}
|
|
943
|
+
function lineAt(text, index) {
|
|
944
|
+
let line = 1;
|
|
945
|
+
for (let i = 0; i < index && i < text.length; i++) if (text.charCodeAt(i) === 10) line++;
|
|
946
|
+
return line;
|
|
947
|
+
}
|
|
948
|
+
var DEFAULT_SRC, DEFAULT_EXTENSIONS, DEFAULT_IGNORE, SKIP_DIRS, MAX_FILE_BYTES, toPosix;
|
|
949
|
+
var init_scan = __esm({
|
|
950
|
+
"src/doctor/scan.ts"() {
|
|
951
|
+
init_color_literals();
|
|
952
|
+
init_glob();
|
|
953
|
+
DEFAULT_SRC = ["src"];
|
|
954
|
+
DEFAULT_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".css"];
|
|
955
|
+
DEFAULT_IGNORE = [
|
|
956
|
+
"**/*.d.ts",
|
|
957
|
+
"**/*.gen.*",
|
|
958
|
+
"**/*.test.*",
|
|
959
|
+
"**/*.spec.*",
|
|
960
|
+
"**/__tests__/**",
|
|
961
|
+
"**/__fixtures__/**",
|
|
962
|
+
"**/__mocks__/**"
|
|
963
|
+
];
|
|
964
|
+
SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
|
|
965
|
+
MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
966
|
+
toPosix = (p) => p.split(path3.sep).join("/");
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
function parseRulesMarkdown(markdown) {
|
|
970
|
+
const rules = [];
|
|
971
|
+
let current = null;
|
|
972
|
+
for (const line of markdown.split("\n")) {
|
|
973
|
+
const heading = line.match(/^###\s+([A-Za-z0-9_-]+)\s*$/);
|
|
974
|
+
if (heading) {
|
|
975
|
+
current = { id: heading[1] };
|
|
976
|
+
rules.push(current);
|
|
977
|
+
continue;
|
|
978
|
+
}
|
|
979
|
+
if (/^#{1,2}\s/.test(line)) {
|
|
980
|
+
current = null;
|
|
981
|
+
continue;
|
|
982
|
+
}
|
|
983
|
+
const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message):\s*(.*)$/);
|
|
984
|
+
if (!current || !kv) continue;
|
|
985
|
+
const [, key, raw] = kv;
|
|
986
|
+
const value = raw.trim();
|
|
987
|
+
if (key === "files" || key === "exclude") current[key] = value.split(",").map((s) => s.trim()).filter(Boolean);
|
|
988
|
+
else if (key === "level") current.level = value;
|
|
989
|
+
else current[key] = value;
|
|
990
|
+
}
|
|
991
|
+
return rules;
|
|
992
|
+
}
|
|
993
|
+
function toRegExp(source, flags = "") {
|
|
994
|
+
if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
|
|
995
|
+
return new RegExp(source, flags);
|
|
996
|
+
}
|
|
997
|
+
function compilePatternRules(rules, source) {
|
|
998
|
+
const ids = /* @__PURE__ */ new Set();
|
|
999
|
+
const out = [];
|
|
1000
|
+
for (const rule of rules) {
|
|
1001
|
+
if (ids.has(rule.id)) throw new DoctorConfigError(`${source}: rule "${rule.id}" is defined twice`);
|
|
1002
|
+
ids.add(rule.id);
|
|
1003
|
+
const level = rule.level ?? "error";
|
|
1004
|
+
if (!["error", "warn", "guide"].includes(level)) {
|
|
1005
|
+
throw new DoctorConfigError(`${source}: rule "${rule.id}" has level "${level}" (use error, warn or guide)`);
|
|
1006
|
+
}
|
|
1007
|
+
if (level === "guide") continue;
|
|
1008
|
+
if (!rule.files?.length) throw new DoctorConfigError(`${source}: rule "${rule.id}" needs "files" (or level: guide)`);
|
|
1009
|
+
if (!rule.forbid && !rule.require && !rule.path) {
|
|
1010
|
+
throw new DoctorConfigError(`${source}: rule "${rule.id}" needs forbid, require or path (or level: guide)`);
|
|
1011
|
+
}
|
|
1012
|
+
try {
|
|
1013
|
+
out.push({
|
|
1014
|
+
rule,
|
|
1015
|
+
level,
|
|
1016
|
+
includes: globMatcher(rule.files),
|
|
1017
|
+
excludes: globMatcher(rule.exclude),
|
|
1018
|
+
forbid: rule.forbid ? toRegExp(rule.forbid, "m") : void 0,
|
|
1019
|
+
require: rule.require ? toRegExp(rule.require, "m") : void 0,
|
|
1020
|
+
path: rule.path ? toRegExp(rule.path) : void 0
|
|
1021
|
+
});
|
|
1022
|
+
} catch (err) {
|
|
1023
|
+
throw new DoctorConfigError(`${source}: rule "${rule.id}" has an invalid pattern: ${err.message}`);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
return out;
|
|
1027
|
+
}
|
|
1028
|
+
function loadPatternRules(root, patterns, rulesDoc) {
|
|
1029
|
+
const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
|
|
1030
|
+
let all = compiled;
|
|
1031
|
+
if (rulesDoc) {
|
|
1032
|
+
const file = path3.resolve(root, rulesDoc);
|
|
1033
|
+
if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
|
|
1034
|
+
const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
|
|
1035
|
+
const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
|
|
1036
|
+
if (clash) throw new DoctorConfigError(`rule "${clash.rule.id}" is defined in both doctor.patterns and ${rulesDoc}`);
|
|
1037
|
+
all = [...compiled, ...fromDoc];
|
|
1038
|
+
}
|
|
1039
|
+
if (all.length === 0) return null;
|
|
1040
|
+
return {
|
|
1041
|
+
count: all.length,
|
|
1042
|
+
plugin: {
|
|
1043
|
+
name: "patterns",
|
|
1044
|
+
check(ctx) {
|
|
1045
|
+
for (const r of all) {
|
|
1046
|
+
const message = r.rule.message ?? "breaks a design rule";
|
|
1047
|
+
for (const file of ctx.files) {
|
|
1048
|
+
if (!r.includes(file.path) || r.excludes(file.path)) continue;
|
|
1049
|
+
const report = (line) => ctx.report({ rule: r.rule.id, level: r.level, file: file.path, line, message });
|
|
1050
|
+
if (r.path && !r.path.test(file.path)) report(0);
|
|
1051
|
+
if (r.require && !r.require.test(file.code)) report(0);
|
|
1052
|
+
if (r.forbid) {
|
|
1053
|
+
const m = r.forbid.exec(file.code);
|
|
1054
|
+
if (m) report(lineAt(file.code, m.index));
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
var init_patterns = __esm({
|
|
1063
|
+
"src/doctor/patterns.ts"() {
|
|
1064
|
+
init_config();
|
|
1065
|
+
init_glob();
|
|
1066
|
+
init_scan();
|
|
1067
|
+
}
|
|
1068
|
+
});
|
|
1069
|
+
function defineDoctorPlugin(plugin) {
|
|
1070
|
+
return plugin;
|
|
1071
|
+
}
|
|
1072
|
+
async function loadPlugins(specs, configDir) {
|
|
1073
|
+
const plugins = [];
|
|
1074
|
+
for (const spec of specs ?? []) {
|
|
1075
|
+
const [id, options] = typeof spec === "string" ? [spec, void 0] : spec;
|
|
1076
|
+
const file = resolvePlugin(id, configDir);
|
|
1077
|
+
const url = `${pathToFileURL(file).href}?mtime=${statSync(file).mtimeMs}`;
|
|
1078
|
+
let mod;
|
|
1079
|
+
try {
|
|
1080
|
+
mod = await import(url);
|
|
1081
|
+
} catch (err) {
|
|
1082
|
+
throw new DoctorConfigError(`doctor.plugins: could not load ${id}: ${err.message}`);
|
|
1083
|
+
}
|
|
1084
|
+
let value = mod.default;
|
|
1085
|
+
if (typeof value === "function") value = await value(options);
|
|
1086
|
+
const list = Array.isArray(value) ? value : [value];
|
|
1087
|
+
for (const p of list) {
|
|
1088
|
+
if (!p || typeof p !== "object" || typeof p.check !== "function" || typeof p.name !== "string") {
|
|
1089
|
+
throw new DoctorConfigError(`doctor.plugins: ${id} must default-export { name, check(context) } (or an array, or a factory returning one)`);
|
|
1090
|
+
}
|
|
1091
|
+
plugins.push(p);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return plugins;
|
|
1095
|
+
}
|
|
1096
|
+
function resolvePlugin(id, configDir) {
|
|
1097
|
+
try {
|
|
1098
|
+
if (id.startsWith(".") || path3.isAbsolute(id)) return resolveFrom(path3.resolve(configDir, id), configDir);
|
|
1099
|
+
return resolveFrom(id, configDir);
|
|
1100
|
+
} catch {
|
|
1101
|
+
throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
function resolveFrom(id, from) {
|
|
1105
|
+
return createRequire(path3.join(from, "noop.js")).resolve(id);
|
|
1106
|
+
}
|
|
1107
|
+
var init_plugins = __esm({
|
|
1108
|
+
"src/doctor/plugins.ts"() {
|
|
1109
|
+
init_config();
|
|
1110
|
+
}
|
|
1111
|
+
});
|
|
1112
|
+
function importSpecifiers(file) {
|
|
1113
|
+
const out = [];
|
|
1114
|
+
const lines = file.code.split("\n");
|
|
1115
|
+
const re = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|@import\s+)["']([^"']+)["']/g;
|
|
1116
|
+
lines.forEach((text, i) => {
|
|
1117
|
+
for (const m of text.matchAll(re)) out.push({ specifier: m[1], line: i + 1 });
|
|
1118
|
+
});
|
|
1119
|
+
return out;
|
|
1120
|
+
}
|
|
1121
|
+
function checkProjectLayout(ctx) {
|
|
1122
|
+
for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
|
|
1123
|
+
if (existsSync(path3.join(ctx.root, dir))) {
|
|
1124
|
+
ctx.report({
|
|
1125
|
+
rule: "local-primitives",
|
|
1126
|
+
file: dir,
|
|
1127
|
+
subject: dir,
|
|
1128
|
+
message: `is a local design-system primitive folder; use ${ctx.genesis.uiPackage} (or extend it upstream)`
|
|
1129
|
+
});
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
for (const file of STARTER_LEFTOVERS) {
|
|
1133
|
+
if (existsSync(path3.join(ctx.root, file))) {
|
|
1134
|
+
ctx.report({
|
|
1135
|
+
rule: "starter-leftover",
|
|
1136
|
+
level: "warn",
|
|
1137
|
+
file,
|
|
1138
|
+
subject: file,
|
|
1139
|
+
message: `is a starter leftover; Genesis ships cn and owns the components`
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
function checkImports(ctx) {
|
|
1145
|
+
const ui = ctx.genesis.uiPackage;
|
|
1146
|
+
const forbidden = [
|
|
1147
|
+
[/^@radix-ui\//, `imports Radix directly; use the Genesis wrapper from ${ui}`],
|
|
1148
|
+
[/^(?:[@~#]\/|\.{1,2}\/)(?:.*\/)?components\/ui(?:\/|$)/, `imports a local UI primitive; use ${ui}`],
|
|
1149
|
+
[/^[@~#]\/lib\/utils$/, `imports the starter's utils; use cn from ${ui}`],
|
|
1150
|
+
...Object.entries(ctx.config.forbiddenImports ?? {}).map(([re, msg]) => [new RegExp(re), msg])
|
|
1151
|
+
];
|
|
1152
|
+
for (const file of ctx.files) {
|
|
1153
|
+
if (!SCRIPT_EXTS.has(file.ext)) continue;
|
|
1154
|
+
for (const { specifier, line } of importSpecifiers(file)) {
|
|
1155
|
+
const hit = forbidden.find(([re]) => re.test(specifier));
|
|
1156
|
+
if (hit) ctx.report({ rule: "forbidden-import", file: file.path, line, subject: specifier, message: `${hit[1]} ('${specifier}')` });
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
function checkRawTags(ctx) {
|
|
1161
|
+
const tags = [...ctx.genesis.rawTags].map(([tag, component]) => [tag, component, new RegExp(`<${tag}(?=[\\s>/]|$)`)]);
|
|
1162
|
+
if (tags.length === 0) return;
|
|
1163
|
+
for (const file of ctx.files) {
|
|
1164
|
+
if (!JSX_EXTS.has(file.ext)) continue;
|
|
1165
|
+
file.code.split("\n").forEach((text, i) => {
|
|
1166
|
+
for (const [tag, component, re] of tags) {
|
|
1167
|
+
if (re.test(text)) {
|
|
1168
|
+
ctx.report({ rule: "raw-tag", file: file.path, line: i + 1, subject: tag, message: `renders a raw <${tag}>; use Genesis ${component}` });
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
function checkColors(ctx) {
|
|
1175
|
+
const palette = new RegExp(
|
|
1176
|
+
`(?<![\\w-])(?:${COLOR_UTILITIES})-(?:${ctx.genesis.palette.join("|")})(?:-\\d{2,3})?(?:\\/\\d{1,3})?(?![\\w-])`,
|
|
1177
|
+
"g"
|
|
1178
|
+
);
|
|
1179
|
+
for (const file of ctx.files) {
|
|
1180
|
+
file.code.split("\n").forEach((text, i) => {
|
|
1181
|
+
const line = i + 1;
|
|
1182
|
+
for (const m of text.matchAll(palette)) {
|
|
1183
|
+
ctx.report({ rule: "palette-color", file: file.path, line, subject: m[0], message: `uses the literal palette color '${m[0]}'; use a semantic token (bg-primary, text-muted-foreground, \u2026)` });
|
|
1184
|
+
}
|
|
1185
|
+
const arbitrary = [];
|
|
1186
|
+
for (const m of text.matchAll(ARBITRARY_COLOR_RE)) {
|
|
1187
|
+
arbitrary.push([m.index, m.index + m[0].length]);
|
|
1188
|
+
ctx.report({ rule: "arbitrary-color", file: file.path, line, subject: m[0], message: `uses the arbitrary color '${m[0]}'; define it as a brand token first` });
|
|
1189
|
+
}
|
|
1190
|
+
for (const hit of [...findHexLiterals(text), ...findColorFunctions(text)]) {
|
|
1191
|
+
const at = hit.column - 1;
|
|
1192
|
+
if (arbitrary.some(([a, b]) => at >= a && at < b)) continue;
|
|
1193
|
+
ctx.report({ rule: "raw-color", file: file.path, line, subject: hit.literal, message: `hardcodes the color ${hit.literal}; color values come from Genesis tokens` });
|
|
1194
|
+
}
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
function checkTokens(ctx) {
|
|
1199
|
+
const defined = new Set(ctx.genesis.tokens);
|
|
1200
|
+
const isTokenFile = ctx.config.tokenFiles ? globMatcher(ctx.config.tokenFiles) : (p) => p.endsWith(".css");
|
|
1201
|
+
for (const file of ctx.files) {
|
|
1202
|
+
if (isTokenFile(file.path)) for (const t of declaredTokens(file.code)) defined.add(t);
|
|
1203
|
+
for (const m of file.code.matchAll(/["'](--[A-Za-z0-9_-]+)["']\s*:/g)) defined.add(m[1]);
|
|
1204
|
+
}
|
|
1205
|
+
for (const pattern of ctx.config.tokenFiles ?? []) {
|
|
1206
|
+
if (/[*?]/.test(pattern)) continue;
|
|
1207
|
+
const abs = path3.join(ctx.root, pattern);
|
|
1208
|
+
if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
|
|
1209
|
+
for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
const ignorePrefixes = ctx.config.ignoreTokenPrefixes ?? DEFAULT_IGNORE_TOKEN_PREFIXES;
|
|
1213
|
+
for (const file of ctx.files) {
|
|
1214
|
+
file.code.split("\n").forEach((text, i) => {
|
|
1215
|
+
for (const m of text.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)/g)) {
|
|
1216
|
+
const token = m[1];
|
|
1217
|
+
if (defined.has(token) || ignorePrefixes.some((p) => token.startsWith(p))) continue;
|
|
1218
|
+
ctx.report({ rule: "undefined-token", file: file.path, line: i + 1, subject: token, message: `references the undefined token ${token}; define it in Genesis or the brand` });
|
|
1219
|
+
}
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
function checkShadowedExports(ctx) {
|
|
1224
|
+
const re = /\bexport\s+(?:default\s+)?(?:declare\s+)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([A-Z][\w$]*)/g;
|
|
1225
|
+
for (const file of ctx.files) {
|
|
1226
|
+
if (!SCRIPT_EXTS.has(file.ext)) continue;
|
|
1227
|
+
file.code.split("\n").forEach((text, i) => {
|
|
1228
|
+
for (const m of text.matchAll(re)) {
|
|
1229
|
+
if (!ctx.genesis.values.has(m[1])) continue;
|
|
1230
|
+
ctx.report({ rule: "shadowed-export", file: file.path, line: i + 1, subject: m[1], message: `shadows the Genesis export '${m[1]}'; reuse or extend Genesis ${m[1]}` });
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
function unusedComponents(ctx) {
|
|
1236
|
+
const used = /* @__PURE__ */ new Set();
|
|
1237
|
+
const pkg = ctx.genesis.uiPackage.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
|
|
1238
|
+
const re = new RegExp(`\\b(?:import|export)\\s+(?:type\\s+)?(?:[\\w$]+\\s*,\\s*)?\\{([^}]*)\\}\\s*from\\s*["']${pkg}(?:/[^"']*)?["']`, "g");
|
|
1239
|
+
for (const file of ctx.files) {
|
|
1240
|
+
for (const m of file.code.matchAll(re)) {
|
|
1241
|
+
for (const part of m[1].split(",")) {
|
|
1242
|
+
const name = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/)[0]?.trim();
|
|
1243
|
+
if (name) used.add(name);
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
return ctx.genesis.components.filter((c) => !used.has(c));
|
|
1248
|
+
}
|
|
1249
|
+
var BUILTIN_RULES, DEFAULT_LOCAL_PRIMITIVE_DIRS, STARTER_LEFTOVERS, DEFAULT_IGNORE_TOKEN_PREFIXES, JSX_EXTS, SCRIPT_EXTS, COLOR_UTILITIES, ARBITRARY_COLOR_RE;
|
|
1250
|
+
var init_rules = __esm({
|
|
1251
|
+
"src/doctor/rules.ts"() {
|
|
1252
|
+
init_color_literals();
|
|
1253
|
+
init_glob();
|
|
1254
|
+
init_genesis();
|
|
1255
|
+
BUILTIN_RULES = [
|
|
1256
|
+
"local-primitives",
|
|
1257
|
+
"starter-leftover",
|
|
1258
|
+
"forbidden-import",
|
|
1259
|
+
"raw-tag",
|
|
1260
|
+
"palette-color",
|
|
1261
|
+
"arbitrary-color",
|
|
1262
|
+
"raw-color",
|
|
1263
|
+
"undefined-token",
|
|
1264
|
+
"shadowed-export"
|
|
1265
|
+
];
|
|
1266
|
+
DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
|
|
1267
|
+
STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
|
|
1268
|
+
DEFAULT_IGNORE_TOKEN_PREFIXES = ["--tw-", "--radix-"];
|
|
1269
|
+
JSX_EXTS = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
|
|
1270
|
+
SCRIPT_EXTS = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
|
|
1271
|
+
COLOR_UTILITIES = "bg|text|border(?:-[xytrbls])?|ring|ring-offset|fill|stroke|from|to|via|outline|divide|decoration|shadow|accent|caret|placeholder";
|
|
1272
|
+
ARBITRARY_COLOR_RE = /(?<![\w-])[a-z][a-z-]*-\[(?:#|(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color)\()[^\]]*\]/g;
|
|
1273
|
+
}
|
|
1274
|
+
});
|
|
1275
|
+
|
|
1276
|
+
// src/doctor/index.ts
|
|
1277
|
+
var doctor_exports = {};
|
|
1278
|
+
__export(doctor_exports, {
|
|
1279
|
+
BUILTIN_RULES: () => BUILTIN_RULES,
|
|
1280
|
+
DoctorConfigError: () => DoctorConfigError,
|
|
1281
|
+
defineDoctorPlugin: () => defineDoctorPlugin,
|
|
1282
|
+
findPackageDir: () => findPackageDir,
|
|
1283
|
+
formatReport: () => formatReport,
|
|
1284
|
+
genesisSummary: () => genesisSummary,
|
|
1285
|
+
globToRegExp: () => globToRegExp,
|
|
1286
|
+
loadConfig: () => loadConfig,
|
|
1287
|
+
loadGenesis: () => loadGenesis,
|
|
1288
|
+
parseExportNames: () => parseExportNames,
|
|
1289
|
+
parseRulesMarkdown: () => parseRulesMarkdown,
|
|
1290
|
+
runDoctor: () => runDoctor,
|
|
1291
|
+
toJson: () => toJson,
|
|
1292
|
+
validateConfig: () => validateConfig
|
|
1293
|
+
});
|
|
1294
|
+
async function runDoctor(options = {}) {
|
|
1295
|
+
const root = path3.resolve(options.root ?? process.cwd());
|
|
1296
|
+
const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
|
|
1297
|
+
const config = loaded.config;
|
|
1298
|
+
const genesis = options.genesis ?? loadGenesis(root, config);
|
|
1299
|
+
const files = scanFiles(root, config);
|
|
1300
|
+
const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
|
|
1301
|
+
const plugins = await loadPlugins(config.plugins, loaded.dir);
|
|
1302
|
+
const builtinIds = new Set(BUILTIN_RULES);
|
|
1303
|
+
for (const p of config.patterns ?? []) {
|
|
1304
|
+
if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
|
|
1305
|
+
}
|
|
1306
|
+
const raw = [];
|
|
1307
|
+
const ctx = { root, files, genesis, config, report: (f) => raw.push(f) };
|
|
1308
|
+
const builtins = [
|
|
1309
|
+
{ name: "layout", check: checkProjectLayout },
|
|
1310
|
+
{ name: "imports", check: checkImports },
|
|
1311
|
+
{ name: "raw-tags", check: checkRawTags },
|
|
1312
|
+
{ name: "colors", check: checkColors },
|
|
1313
|
+
{ name: "tokens", check: checkTokens },
|
|
1314
|
+
{ name: "shadowed-exports", check: checkShadowedExports }
|
|
1315
|
+
];
|
|
1316
|
+
for (const plugin of [...builtins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
|
|
1317
|
+
try {
|
|
1318
|
+
await plugin.check(ctx);
|
|
1319
|
+
} catch (err) {
|
|
1320
|
+
if (err instanceof DoctorConfigError) throw err;
|
|
1321
|
+
raw.push({ rule: "plugin-error", file: plugin.name, message: `rule plugin "${plugin.name}" threw: ${err.message}` });
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
if (options.build) {
|
|
1325
|
+
const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
|
|
1326
|
+
if (failure) raw.push(failure);
|
|
1327
|
+
}
|
|
1328
|
+
const findings = applyConfig(raw, config);
|
|
1329
|
+
const errors = findings.filter((f) => f.level === "error").length;
|
|
1330
|
+
const warnings = findings.length - errors;
|
|
1331
|
+
return {
|
|
1332
|
+
ok: errors === 0 && !(options.strict && warnings > 0),
|
|
1333
|
+
root,
|
|
1334
|
+
genesis,
|
|
1335
|
+
findings,
|
|
1336
|
+
unused: unusedComponents(ctx),
|
|
1337
|
+
ruleCount: (patterns?.count ?? 0) + plugins.length,
|
|
1338
|
+
errors,
|
|
1339
|
+
warnings
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
function applyConfig(raw, config) {
|
|
1343
|
+
const allow = (config.allow ?? []).map((entry) => ({ entry, file: entry.file ? globToRegExp(entry.file) : null, used: false }));
|
|
1344
|
+
const out = [];
|
|
1345
|
+
for (const input of raw) {
|
|
1346
|
+
const setting = config.rules?.[input.rule];
|
|
1347
|
+
if (setting === "off") continue;
|
|
1348
|
+
const finding = {
|
|
1349
|
+
rule: input.rule,
|
|
1350
|
+
level: setting ?? input.level ?? "error",
|
|
1351
|
+
file: input.file,
|
|
1352
|
+
line: input.line ?? 0,
|
|
1353
|
+
message: input.message,
|
|
1354
|
+
...input.subject !== void 0 ? { subject: input.subject } : {}
|
|
1355
|
+
};
|
|
1356
|
+
const exception = allow.find(
|
|
1357
|
+
(a) => a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
|
|
1358
|
+
);
|
|
1359
|
+
if (exception) {
|
|
1360
|
+
exception.used = true;
|
|
1361
|
+
continue;
|
|
1362
|
+
}
|
|
1363
|
+
out.push(finding);
|
|
1364
|
+
}
|
|
1365
|
+
const staleLevel = config.rules?.["stale-exception"];
|
|
1366
|
+
for (const a of allow) {
|
|
1367
|
+
if (staleLevel === "off" || a.used || config.rules?.[a.entry.rule] === "off") continue;
|
|
1368
|
+
out.push({
|
|
1369
|
+
rule: "stale-exception",
|
|
1370
|
+
level: staleLevel ?? "warn",
|
|
1371
|
+
file: a.entry.file ?? "genesis config",
|
|
1372
|
+
line: 0,
|
|
1373
|
+
subject: a.entry.rule,
|
|
1374
|
+
message: `the allow entry for ${a.entry.rule}${a.entry.match ? ` (${a.entry.match})` : ""} no longer matches anything; remove it`
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
return out.sort((x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.rule.localeCompare(y.rule));
|
|
1378
|
+
}
|
|
1379
|
+
function formatReport(result) {
|
|
1380
|
+
const g = result.genesis;
|
|
1381
|
+
const lines = [
|
|
1382
|
+
`Genesis doctor: ${g.uiPackage}@${g.uiVersion}, ${g.components.length} components, ${g.tokens.size} tokens, ${result.ruleCount} app rules; raw tags checked: ${[...g.rawTags.keys()].join(", ") || "none"}`
|
|
1383
|
+
];
|
|
1384
|
+
for (const f of result.findings) {
|
|
1385
|
+
lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
|
|
1386
|
+
}
|
|
1387
|
+
lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
|
|
1388
|
+
lines.push(result.ok ? `PASS (${result.warnings} warnings)` : `FAIL (${result.errors} errors, ${result.warnings} warnings)`);
|
|
1389
|
+
return lines.join("\n");
|
|
1390
|
+
}
|
|
1391
|
+
function toJson(result) {
|
|
1392
|
+
return {
|
|
1393
|
+
ok: result.ok,
|
|
1394
|
+
genesis: `${result.genesis.uiPackage}@${result.genesis.uiVersion}`,
|
|
1395
|
+
errors: result.errors,
|
|
1396
|
+
warnings: result.warnings,
|
|
1397
|
+
findings: result.findings,
|
|
1398
|
+
unused: result.unused
|
|
1399
|
+
};
|
|
1400
|
+
}
|
|
1401
|
+
function genesisSummary(g) {
|
|
1402
|
+
return {
|
|
1403
|
+
package: `${g.uiPackage}@${g.uiVersion}`,
|
|
1404
|
+
components: g.components,
|
|
1405
|
+
tokens: [...g.tokens].sort(),
|
|
1406
|
+
rawTags: Object.fromEntries(g.rawTags),
|
|
1407
|
+
palette: g.palette
|
|
1408
|
+
};
|
|
1409
|
+
}
|
|
1410
|
+
var init_doctor = __esm({
|
|
1411
|
+
"src/doctor/index.ts"() {
|
|
1412
|
+
init_build();
|
|
1413
|
+
init_config();
|
|
1414
|
+
init_glob();
|
|
1415
|
+
init_genesis();
|
|
1416
|
+
init_patterns();
|
|
1417
|
+
init_plugins();
|
|
1418
|
+
init_rules();
|
|
1419
|
+
init_scan();
|
|
1420
|
+
init_config();
|
|
1421
|
+
init_genesis();
|
|
1422
|
+
init_patterns();
|
|
1423
|
+
init_plugins();
|
|
1424
|
+
init_rules();
|
|
1425
|
+
init_glob();
|
|
1426
|
+
}
|
|
1427
|
+
});
|
|
332
1428
|
|
|
333
1429
|
// src/studio/wire-route.ts
|
|
334
1430
|
function routeTags(source) {
|
|
@@ -366,8 +1462,8 @@ function routeTags(source) {
|
|
|
366
1462
|
}
|
|
367
1463
|
function wireStudioRoute(source, route, pageImportPath) {
|
|
368
1464
|
const tags = routeTags(source);
|
|
369
|
-
const
|
|
370
|
-
const existing = tags.find((t) => new RegExp(`path=["'](/?${
|
|
1465
|
+
const relative2 = route.replace(/^\//, "");
|
|
1466
|
+
const existing = tags.find((t) => new RegExp(`path=["'](/?${relative2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
|
|
371
1467
|
if (existing) {
|
|
372
1468
|
return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
|
|
373
1469
|
}
|
|
@@ -375,17 +1471,17 @@ function wireStudioRoute(source, route, pageImportPath) {
|
|
|
375
1471
|
const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
|
|
376
1472
|
if (roots.length !== 1) {
|
|
377
1473
|
return {
|
|
378
|
-
skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${
|
|
1474
|
+
skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative2}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
|
|
379
1475
|
};
|
|
380
1476
|
}
|
|
381
1477
|
const layout = roots[0];
|
|
382
1478
|
const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
|
|
383
|
-
if (base && !
|
|
1479
|
+
if (base && !relative2.startsWith(`${base}/`)) {
|
|
384
1480
|
return {
|
|
385
1481
|
skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
|
|
386
1482
|
};
|
|
387
1483
|
}
|
|
388
|
-
const childPath = base ?
|
|
1484
|
+
const childPath = base ? relative2.slice(base.length + 1) : relative2;
|
|
389
1485
|
const guard = GUARD.exec(source)?.[1];
|
|
390
1486
|
const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
|
|
391
1487
|
const before = source.slice(0, layout.close);
|
|
@@ -481,8 +1577,8 @@ import { supabaseStudio } from "@marktiderman/genesis-studio-server";
|
|
|
481
1577
|
export const runtime = "nodejs";
|
|
482
1578
|
|
|
483
1579
|
export const POST = supabaseStudio({
|
|
484
|
-
url: process.env
|
|
485
|
-
database: process.env
|
|
1580
|
+
url: process.env["NEXT_PUBLIC_SUPABASE_URL"]!,
|
|
1581
|
+
database: process.env["STUDIO_DATABASE_URL"]!,
|
|
486
1582
|
// Server-side details of anything that goes wrong; users only see a plain message.
|
|
487
1583
|
onError: (error) => console.error("[genesis-studio]", error),
|
|
488
1584
|
// Who may open the studio. The default is any signed-in user, who sees exactly what row-level
|
|
@@ -503,6 +1599,7 @@ import "@marktiderman/genesis-studio/standalone.css";
|
|
|
503
1599
|
|
|
504
1600
|
export default function DataStudioPage() {
|
|
505
1601
|
const provider = useMemo(() => {
|
|
1602
|
+
// Dot access: Next.js inlines a public variable into the browser bundle only for process.env.NAME.
|
|
506
1603
|
const supabase = ${ssr ? "createBrowserClient" : "createClient"}(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!);
|
|
507
1604
|
return createSupabaseStudioProvider(supabase, { url: "/api/studio" });
|
|
508
1605
|
}, []);
|
|
@@ -603,6 +1700,8 @@ function planTanstackStart(facts, route, files, steps, role) {
|
|
|
603
1700
|
content: `// The Data Studio's server: every table, as the signed-in user. Generated by \`genesis studio init\`.
|
|
604
1701
|
import { createFileRoute } from "@tanstack/react-router";
|
|
605
1702
|
|
|
1703
|
+
// One handler for the server's life. On Cloudflare Workers it opens a database connection per
|
|
1704
|
+
// request by itself, since a connection there can't outlive the request that opened it.
|
|
606
1705
|
let studio: ((request: Request) => Promise<Response>) | undefined;
|
|
607
1706
|
|
|
608
1707
|
export const Route = createFileRoute("/api/studio")({
|
|
@@ -612,8 +1711,8 @@ export const Route = createFileRoute("/api/studio")({
|
|
|
612
1711
|
// Loaded here, on the server only, so database code never reaches the browser bundle.
|
|
613
1712
|
const { supabaseStudio } = await import("@marktiderman/genesis-studio-server");
|
|
614
1713
|
studio ??= supabaseStudio({
|
|
615
|
-
url: process.env
|
|
616
|
-
database: process.env
|
|
1714
|
+
url: process.env["SUPABASE_URL"] ?? process.env["VITE_SUPABASE_URL"]!,
|
|
1715
|
+
database: process.env["STUDIO_DATABASE_URL"]!,
|
|
617
1716
|
// Server-side details of anything that goes wrong; users only see a plain message.
|
|
618
1717
|
onError: (error) => console.error("[genesis-studio]", error),
|
|
619
1718
|
// Who may open the studio. The default is any signed-in user, who sees exactly what
|
|
@@ -811,9 +1910,9 @@ async function runScaffold(opts, fs2) {
|
|
|
811
1910
|
function joinPath(...parts) {
|
|
812
1911
|
return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
|
|
813
1912
|
}
|
|
814
|
-
function dirname(
|
|
815
|
-
const idx =
|
|
816
|
-
return idx === -1 ? "." :
|
|
1913
|
+
function dirname(path10) {
|
|
1914
|
+
const idx = path10.lastIndexOf("/");
|
|
1915
|
+
return idx === -1 ? "." : path10.slice(0, idx);
|
|
817
1916
|
}
|
|
818
1917
|
function brandPackageJson(consumer, genesisVersion) {
|
|
819
1918
|
return JSON.stringify(
|
|
@@ -1125,7 +2224,7 @@ program.command("introspect").description("Write a checked-in contract (resource
|
|
|
1125
2224
|
source = `Postgres (${schemas.join(", ")})`;
|
|
1126
2225
|
}
|
|
1127
2226
|
const content = emitContracts2(tables, { source });
|
|
1128
|
-
const target =
|
|
2227
|
+
const target = path3.resolve(opts.out);
|
|
1129
2228
|
if (opts.check) {
|
|
1130
2229
|
const current = await fs.readFile(target, "utf-8").catch(() => null);
|
|
1131
2230
|
if (current !== content) {
|
|
@@ -1138,27 +2237,46 @@ program.command("introspect").description("Write a checked-in contract (resource
|
|
|
1138
2237
|
await fs.writeFile(target, content, "utf-8");
|
|
1139
2238
|
console.log(`\u2714 Wrote ${opts.out}: ${tables.length} tables.`);
|
|
1140
2239
|
});
|
|
2240
|
+
program.command("doctor").description("Check this app against the installed Genesis: components, tokens, imports, colors, plus the app's own rules").option("--strict", "Fail on warnings too", false).option("--json", "Print the report as JSON", false).option("--build", "Also run the app's typecheck and build (doctor.build, or its typecheck/build scripts)", false).option("-c, --config <path>", 'Config file (default: genesis.config.json, then package.json "genesis")').option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--print-genesis", "Print the components, tokens and raw tags read from Genesis, and exit", false).action(async (opts) => {
|
|
2241
|
+
const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
|
|
2242
|
+
const root = path3.resolve(opts.dir);
|
|
2243
|
+
try {
|
|
2244
|
+
if (opts.printGenesis) {
|
|
2245
|
+
const { config } = doctor.loadConfig(root, opts.config);
|
|
2246
|
+
console.log(JSON.stringify(doctor.genesisSummary(doctor.loadGenesis(root, config)), null, 2));
|
|
2247
|
+
return;
|
|
2248
|
+
}
|
|
2249
|
+
const result = await doctor.runDoctor({ root, configPath: opts.config, strict: opts.strict, build: opts.build, quietBuild: opts.json });
|
|
2250
|
+
console.log(opts.json ? JSON.stringify(doctor.toJson(result), null, 2) : doctor.formatReport(result));
|
|
2251
|
+
process.exitCode = result.ok ? 0 : 1;
|
|
2252
|
+
} catch (err) {
|
|
2253
|
+
if (!(err instanceof doctor.DoctorConfigError)) throw err;
|
|
2254
|
+
if (opts.json) console.log(JSON.stringify({ ok: false, error: err.message }, null, 2));
|
|
2255
|
+
else console.error(`\u2717 ${err.message}`);
|
|
2256
|
+
process.exitCode = 2;
|
|
2257
|
+
}
|
|
2258
|
+
});
|
|
1141
2259
|
var studio = program.command("studio").description("The Genesis Data Studio");
|
|
1142
2260
|
studio.command("init").description("Turn the Data Studio on in this app: a server for every table, a page, and one migration to review").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--host <host>", "next, tanstack-start or supabase-function (default: detected)").option("--route <path>", "Where the page lives", "/admin/data").option("--login-role <name>", "The studio's database login", "genesis_studio_login").option("--force", "Overwrite files that already exist", false).action(async (opts) => {
|
|
1143
2261
|
const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
|
|
1144
|
-
const root =
|
|
1145
|
-
const packageJson = JSON.parse(await fs.readFile(
|
|
1146
|
-
const
|
|
2262
|
+
const root = path3.resolve(opts.dir);
|
|
2263
|
+
const packageJson = JSON.parse(await fs.readFile(path3.join(root, "package.json"), "utf-8").catch(() => "{}"));
|
|
2264
|
+
const existsSync7 = (await import('fs')).existsSync;
|
|
1147
2265
|
const readSync = (await import('fs')).readFileSync;
|
|
1148
|
-
const
|
|
2266
|
+
const readdirSync3 = (await import('fs')).readdirSync;
|
|
1149
2267
|
if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
|
|
1150
2268
|
throw new Error("--host must be next, tanstack-start or supabase-function.");
|
|
1151
2269
|
}
|
|
1152
2270
|
const plan = planStudioInit2(
|
|
1153
2271
|
{
|
|
1154
2272
|
packageJson,
|
|
1155
|
-
exists: (p) =>
|
|
1156
|
-
read: (p) =>
|
|
2273
|
+
exists: (p) => existsSync7(path3.join(root, p)),
|
|
2274
|
+
read: (p) => existsSync7(path3.join(root, p)) ? readSync(path3.join(root, p), "utf-8") : null,
|
|
1157
2275
|
timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
|
|
1158
2276
|
listDeep: (p) => {
|
|
1159
2277
|
const out = [];
|
|
1160
2278
|
const walk = (rel) => {
|
|
1161
|
-
for (const entry of
|
|
2279
|
+
for (const entry of readdirSync3(path3.join(root, rel), { withFileTypes: true })) {
|
|
1162
2280
|
const child = `${rel}/${entry.name}`;
|
|
1163
2281
|
if (entry.isDirectory()) walk(child);
|
|
1164
2282
|
else out.push(child);
|
|
@@ -1172,7 +2290,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
|
|
|
1172
2290
|
},
|
|
1173
2291
|
list: (p) => {
|
|
1174
2292
|
try {
|
|
1175
|
-
return
|
|
2293
|
+
return readdirSync3(path3.join(root, p));
|
|
1176
2294
|
} catch {
|
|
1177
2295
|
return [];
|
|
1178
2296
|
}
|
|
@@ -1181,8 +2299,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
|
|
|
1181
2299
|
{ host: opts.host, route: opts.route, loginRole: opts.loginRole }
|
|
1182
2300
|
);
|
|
1183
2301
|
for (const file of plan.files) {
|
|
1184
|
-
const target =
|
|
1185
|
-
await fs.mkdir(
|
|
2302
|
+
const target = path3.join(root, file.path);
|
|
2303
|
+
await fs.mkdir(path3.dirname(target), { recursive: true });
|
|
1186
2304
|
if (file.edit) {
|
|
1187
2305
|
await fs.writeFile(target, file.content, "utf-8");
|
|
1188
2306
|
console.log(`~ ${file.path} (${file.edit})`);
|
|
@@ -1193,14 +2311,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
|
|
|
1193
2311
|
console.log(`+ ${file.path} (appended)`);
|
|
1194
2312
|
continue;
|
|
1195
2313
|
}
|
|
1196
|
-
if (
|
|
2314
|
+
if (existsSync7(target) && !opts.force) {
|
|
1197
2315
|
console.log(`= ${file.path} exists; left as it is (--force to replace)`);
|
|
1198
2316
|
continue;
|
|
1199
2317
|
}
|
|
1200
2318
|
await fs.writeFile(target, file.content, "utf-8");
|
|
1201
2319
|
console.log(`+ ${file.path}`);
|
|
1202
2320
|
}
|
|
1203
|
-
const pm =
|
|
2321
|
+
const pm = existsSync7(path3.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync7(path3.join(root, "yarn.lock")) ? "yarn add" : existsSync7(path3.join(root, "bun.lock")) || existsSync7(path3.join(root, "bun.lockb")) ? "bun add" : "npm install";
|
|
1204
2322
|
console.log("");
|
|
1205
2323
|
console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
|
|
1206
2324
|
console.log(` 1. ${pm} ${plan.install.join(" ")}`);
|
|
@@ -1253,7 +2371,7 @@ function redactUrl(location) {
|
|
|
1253
2371
|
const url = new URL(location);
|
|
1254
2372
|
return `${url.origin}${url.pathname}`;
|
|
1255
2373
|
} catch {
|
|
1256
|
-
return
|
|
2374
|
+
return path3.basename(location);
|
|
1257
2375
|
}
|
|
1258
2376
|
}
|
|
1259
2377
|
//# sourceMappingURL=cli.js.map
|