build-catalog.mjs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. #!/usr/bin/env node
  2. // Generates references/catalog.md and the skeleton block inside each deliverable file (deck / app / page)
  3. // from design-resources/. Run: node scripts/build-catalog.mjs [--max-bytes=N] [--dir=references-dir]
  4. // Facts tied to resource names live in CONFIG; tests/design/catalog.test.ts keeps it in sync with the files.
  5. // Sections: CONFIG · resources · text helpers · catalog · skeleton blocks · main
  6. import { existsSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
  7. import { dirname, join, resolve } from "node:path";
  8. import { fileURLToPath, pathToFileURL } from "node:url";
  9. import { parseFrontmatter, splitFrontmatter } from "./frontmatter.mjs";
  10. // Byte cap per generated target; the deliverable files also carry hand-written rules, so their cap is the whole file.
  11. export const TARGETS = {
  12. catalog: { file: "catalog.md", maxBytes: 6144 },
  13. deck: { file: "deck.md", maxBytes: 6144 },
  14. app: { file: "app.md", maxBytes: 5120 },
  15. page: { file: "page.md", maxBytes: 5120 },
  16. };
  17. export const TRACKS = ["deck", "app", "page"];
  18. export const CONFIG = {
  19. // One default skeleton per deliverable track, printed in that track's file.
  20. // Skeletons kept on disk but never offered: their mandatory steps need the Open Design daemon, connectors or a
  21. // media runtime (OD_* wrappers, artifact registration, MP4 generation) that this host does not provide, so no
  22. // static workflow can follow them as written.
  23. excludeSkeletons: ["live-artifact", "live-dashboard", "hyperframes", "video-shortform"],
  24. // Every skeleton not in excludeSkeletons belongs to exactly one category, and every category to one deliverable track;
  25. // list order is priority order (former Top before Standard).
  26. categories: [
  27. {
  28. key: "deck",
  29. track: "deck",
  30. title: "Deck — specific need (match one to one first)",
  31. craft: [],
  32. members: [
  33. "html-ppt-pitch-deck", "html-ppt-hermes-cyber-terminal", "html-ppt-taste-brutalist", "html-ppt-course-module",
  34. "kami-deck", "open-design-landing-deck", "weekly-update", "ib-pitch-book",
  35. ],
  36. },
  37. {
  38. key: "zhangzara",
  39. track: "deck",
  40. title: "Deck — zhangzara family, all `self` (`html-ppt-zhangzara-<x>`; pick by mood, then use)",
  41. prefix: "html-ppt-zhangzara-",
  42. craft: [],
  43. members: [
  44. "broadside", "bold-poster", "cartesian", "coral", "editorial-tri-tone", "neo-grid-bold", "peoples-platform",
  45. "pin-and-paper", "soft-editorial", "stencil-tablet", "retro-windows", "retro-zine", "sakura-chroma",
  46. "pink-script", "8-bit-orbit", "creative-mode", "daisy-days", "biennale-yellow", "block-frame", "capsule",
  47. "grove", "mat", "monochrome", "playful", "raw-grid", "signal", "studio", "vellum",
  48. ].map((x) => `html-ppt-zhangzara-${x}`),
  49. },
  50. {
  51. key: "dashboard",
  52. track: "page",
  53. title: "Dashboard",
  54. craft: ["state-coverage"],
  55. members: ["dashboard", "trading-analysis-dashboard-template", "ai-assistant-mobile-dashboard"],
  56. },
  57. {
  58. key: "web",
  59. track: "page",
  60. title: "Web page",
  61. craft: [],
  62. members: [
  63. "web-prototype", "web-prototype-taste-soft", "web-prototype-taste-editorial", "web-prototype-taste-brutalist",
  64. "saas-landing", "kami-landing", "pricing-page",
  65. ],
  66. },
  67. {
  68. key: "app",
  69. track: "app",
  70. title: "App",
  71. craft: ["state-coverage"],
  72. members: ["mobile-app", "kanban-board", "meeting-notes", "gamified-app", "wireframe-sketch"],
  73. },
  74. {
  75. key: "document",
  76. track: "page",
  77. title: "Document / report",
  78. craft: ["typography-hierarchy"],
  79. members: [
  80. "blog-post", "docs-page", "digital-eguide", "finance-report", "dcf-valuation", "clinical-case-report",
  81. "eng-runbook", "pm-spec", "hr-onboarding", "invoice", "magazine-poster",
  82. ],
  83. },
  84. {
  85. key: "media",
  86. track: "page",
  87. title: "Media / motion",
  88. craft: ["animation-discipline"],
  89. members: ["motion-frames", "sprite-animation", "social-carousel"],
  90. },
  91. {
  92. key: "utility",
  93. track: "page",
  94. title: "Utility",
  95. craft: [],
  96. members: ["critique", "tweaks", "orbit-linear", "orbit-notion", "x-research"],
  97. },
  98. ],
  99. // Rows whose name says enough.
  100. nameOnly: [
  101. "weekly-update", "ib-pitch-book", "dashboard", "trading-analysis-dashboard-template", "saas-landing", "pricing-page",
  102. "mobile-app", "kanban-board", "meeting-notes", "wireframe-sketch", "blog-post", "docs-page", "digital-eguide",
  103. "finance-report", "dcf-valuation", "clinical-case-report", "eng-runbook", "pm-spec", "hr-onboarding", "invoice",
  104. "magazine-poster", "motion-frames", "sprite-animation", "social-carousel",
  105. ],
  106. // One-line text replacing the description's first sentence.
  107. override: {
  108. // YAML ends the description at " #0a0c10", so the parsed text stops at "deck —".
  109. "html-ppt-hermes-cyber-terminal": "Dark terminal deck for CLI / agent / dev-tool reviews",
  110. "kami-deck": "Print-grade kami deck: parchment, ink-blue, one serif",
  111. "kami-landing": "Print-grade kami one-pager or white paper",
  112. "open-design-landing-deck": "Atelier Zero brand deck: warm paper, collage plates",
  113. "web-prototype": "General responsive web page",
  114. critique: "5-dimension expert review of an HTML artifact",
  115. tweaks: "Side panel of live CSS controls to compare variants",
  116. "orbit-linear": "Daily digest from Linear data",
  117. "orbit-notion": "Daily digest from Notion data",
  118. "x-research": "X/Twitter sentiment research; Markdown first is fine",
  119. },
  120. // Warnings shown under the category of their first resource.
  121. notes: [
  122. {
  123. names: ["open-design-landing-deck"],
  124. text: "`scripts/compose.ts` needs sibling CSS and images that are not shipped; build from the skill, example, inputs and `schema.ts`, do not run it",
  125. },
  126. ],
  127. // Files that some SKILL.md files name but the package does not ship (paths under design-resources/).
  128. // `label` joins the shared warning at the end of the track's block. `inline` instead rides on its own
  129. // skeleton's row, for a skeleton whose own text would otherwise make it stop or pretend it read them:
  130. // only a task that picks that skeleton pays for the caveat.
  131. missing: [
  132. {
  133. label: "the main html-ppt skill and `full-decks.md`",
  134. usedBy: ["html-ppt-pitch-deck", "html-ppt-course-module", "html-ppt-hermes-cyber-terminal"],
  135. paths: ["design-skeletons/html-ppt/SKILL.md", "design-skeletons/html-ppt/references/full-decks.md", "skills/html-ppt"],
  136. },
  137. {
  138. label: "the `open-design-landing` CSS and images",
  139. usedBy: ["open-design-landing-deck"],
  140. paths: ["design-skeletons/open-design-landing/styles.css", "design-skeletons/open-design-landing/assets"],
  141. },
  142. {
  143. usedBy: ["ai-assistant-mobile-dashboard"],
  144. paths: [
  145. "skills/design-core-rules/references/OUTPUT_RULES.md",
  146. "skills/design-core-rules/references/DESIGN.md",
  147. "审美相关skill/design-systems",
  148. ],
  149. inline:
  150. "the rule files, resource paths and in-app preview it cites are not shipped: ignore them and its abort-if-unread rule, never claim you read them, follow [create](create.md) and [check](check.md)",
  151. },
  152. ],
  153. // Skill SKILL.md files whose name differs from their directory.
  154. nameMismatch: ["infinite-canvas"],
  155. skills: {
  156. // gstack method skills: not offered for selection and not read by default.
  157. exclude: ["design-consultation", "design-review", "plan-design-review"],
  158. override: {
  159. "brand-guidelines": "Anthropic's own brand, only when the task asks for it",
  160. "frontend-design": "production-grade frontend UI",
  161. "frontend-slides": "animation-rich HTML slides",
  162. "infinite-canvas": "infinite-canvas delivery (`scripts/adapt-canvas.mjs`)",
  163. "taste-skill": "anti-slop tuning: density, motion, variance",
  164. },
  165. },
  166. // DESIGN.md `> Category:` value -> catalog group (group order = render order).
  167. systemGroups: {
  168. "Productivity & SaaS": "Tech / SaaS",
  169. "Developer Tools": "Tech / SaaS",
  170. "Design & Creative": "Tech / SaaS",
  171. "Themed & Unique": "Tech / SaaS",
  172. "Professional & Corporate": "Tech / SaaS",
  173. "Media & Consumer": "Tech / SaaS",
  174. "E-Commerce & Retail": "Tech / SaaS",
  175. "Bold & Expressive": "Style",
  176. "Creative & Artistic": "Style",
  177. "Morphism & Effects": "Style",
  178. "Layout & Structure": "Style",
  179. "Editorial & Print": "Editorial",
  180. "Editorial · Studio": "Editorial",
  181. "Fintech & Crypto": "Fintech",
  182. Automotive: "Automotive",
  183. },
  184. systemNotes: { kami: "only via kami-* skeletons" },
  185. // Short descriptions for systems without an Agent Prompt Guide (brand systems are listed by name).
  186. systemOverride: {
  187. agentic: "AI-first, delegated task flows",
  188. application: "purple app dashboard, top nav",
  189. arc: "translucent, sidebar-first",
  190. artistic: "expressive type, bold color",
  191. bento: "modular card grid",
  192. bold: "heavy type, high contrast",
  193. brutalism: "raw anti-design",
  194. glassmorphism: "frosted translucent layers",
  195. },
  196. // craft/<name>.md -> when to read. Key set must equal the craft/ directory.
  197. craft: {
  198. typography: "baseline, always",
  199. color: "baseline, always",
  200. "anti-ai-slop": "baseline, always",
  201. "accessibility-baseline": "baseline, always",
  202. "state-coverage": "apps, dashboards: loading/empty/error",
  203. "typography-hierarchy": "text-heavy pages",
  204. "typography-hierarchy-editorial": "content sites, magazine style",
  205. "animation-discipline": "any motion; read with [references/motion.md](motion.md), which wins where the two differ",
  206. "form-validation": "forms",
  207. "laws-of-ux": "highly interactive UI",
  208. "rtl-and-bidi": "Arabic/Hebrew only, even if a skeleton lists it",
  209. },
  210. craftBaseline: ["typography", "color", "anti-ai-slop", "accessibility-baseline"],
  211. craftAlias: { "motion-discipline": "animation-discipline" },
  212. craftDrop: ["typographic-rhythm", "pixel-discipline"],
  213. craftConditional: ["rtl-and-bidi"],
  214. // Triggers shared by the whole zhangzara family carry no routing signal.
  215. stopTriggers: ["html deck", "html slides", "zhangzara"],
  216. textWidth: 52,
  217. shortTextWidth: 40,
  218. };
  219. // ---------- resources ----------
  220. const byCodePoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
  221. function subdirsWith(dir, file) {
  222. return readdirSync(dir, { withFileTypes: true })
  223. .filter((entry) => entry.isDirectory() && existsSync(join(dir, entry.name, file)))
  224. .map((entry) => entry.name)
  225. .sort(byCodePoint);
  226. }
  227. function readFrontmatter(file) {
  228. const raw = splitFrontmatter(readFileSync(file, "utf8"));
  229. if (raw === null) throw new Error(`missing frontmatter: ${file}`);
  230. return parseFrontmatter(raw);
  231. }
  232. // DESIGN.md has no frontmatter: `# Title`, then `> Category: X` and a quoted one-liner.
  233. export function parseDesignSystem(text) {
  234. const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
  235. let i = 1;
  236. while (i < lines.length && lines[i].trim() === "") i++;
  237. const quote = [];
  238. while (i < lines.length && lines[i].startsWith(">")) quote.push(lines[i++].replace(/^>\s?/, "").trim());
  239. const category = quote[0]?.match(/^Category:\s*(.+)$/)?.[1];
  240. if (!category) throw new Error("DESIGN.md lacks a `> Category:` line");
  241. return {
  242. category,
  243. description: quote.slice(1).join(" ").replace(/\s+/g, " ").trim(),
  244. full: text.includes("Agent Prompt Guide"),
  245. };
  246. }
  247. export function collectResources(resourceRoot) {
  248. const skeletonDir = join(resourceRoot, "design-skeletons");
  249. const skillDir = join(resourceRoot, "skills");
  250. const systemDir = join(resourceRoot, "design-systems");
  251. const skeletons = new Map();
  252. for (const name of subdirsWith(skeletonDir, "SKILL.md")) {
  253. skeletons.set(name, {
  254. frontmatter: readFrontmatter(join(skeletonDir, name, "SKILL.md")),
  255. hasExample: existsSync(join(skeletonDir, name, "example.html")),
  256. });
  257. }
  258. const skills = new Map();
  259. for (const name of subdirsWith(skillDir, "SKILL.md")) {
  260. skills.set(name, { frontmatter: readFrontmatter(join(skillDir, name, "SKILL.md")) });
  261. }
  262. const systems = new Map();
  263. for (const name of subdirsWith(systemDir, "DESIGN.md")) {
  264. systems.set(name, parseDesignSystem(readFileSync(join(systemDir, name, "DESIGN.md"), "utf8")));
  265. }
  266. const craft = readdirSync(join(resourceRoot, "craft"))
  267. .filter((file) => file.endsWith(".md"))
  268. .map((file) => file.slice(0, -3))
  269. .sort(byCodePoint);
  270. return { skeletons, skills, systems, craft };
  271. }
  272. // ---------- text helpers ----------
  273. export function firstSentence(description) {
  274. const text = String(description ?? "").replace(/\s+/g, " ").trim();
  275. const end = /[。!?]|[.!?]["”']?(?=\s|$)/g;
  276. let match;
  277. while ((match = end.exec(text))) {
  278. const before = text.slice(0, match.index);
  279. if (match[0] === "." && /\b(?:e\.g|i\.e|vs|etc)$/i.test(before)) continue;
  280. return before.trim();
  281. }
  282. return text;
  283. }
  284. const charWidth = (ch) => (/[\u2E80-\u9FFF\uF900-\uFAFF\uFF00-\uFFEF]/.test(ch) ? 2 : 1);
  285. const width = (s) => [...s].reduce((n, ch) => n + charWidth(ch), 0);
  286. // Shorten to `max` display columns, preferring the part before " — " when it can stand alone.
  287. export function clip(text, max) {
  288. let s = text.replace(/\*\*/g, "").replace(/["“”]/g, "").trim();
  289. const dash = s.indexOf(" — ");
  290. if (dash >= 0 && width(s.slice(0, dash)) >= 20) s = s.slice(0, dash);
  291. s = s.replace(/^An? (?=[a-z])/, "");
  292. if (width(s) <= max) return s;
  293. let out = "";
  294. let w = 0;
  295. for (const ch of s) {
  296. if (w + charWidth(ch) > max - 1) break;
  297. out += ch;
  298. w += charWidth(ch);
  299. }
  300. const atWord = out.replace(/[\s,;:/(—–-]+[^\s,;:/(—–-]*$/, "");
  301. return `${(width(atWord) > max / 2 ? atWord : out).replace(/[\s,;:/(—–-]+$/, "")}…`;
  302. }
  303. export function resolveCraft(name) {
  304. if (CONFIG.craftDrop.includes(name)) return null;
  305. return CONFIG.craftAlias[name] ?? name;
  306. }
  307. function craftExtras(frontmatter, groupCraft) {
  308. const extras = [];
  309. for (const declared of frontmatter.od?.craft?.requires ?? []) {
  310. const name = resolveCraft(declared);
  311. if (!name || CONFIG.craftBaseline.includes(name) || CONFIG.craftConditional.includes(name)) continue;
  312. if (groupCraft.includes(name) || extras.includes(name)) continue;
  313. extras.push(name);
  314. }
  315. return extras;
  316. }
  317. function zhangzaraText(name, frontmatter, prefix) {
  318. const short = name.slice(prefix.length);
  319. const triggers = (frontmatter.triggers ?? []).filter(
  320. (t) =>
  321. !CONFIG.stopTriggers.includes(t) &&
  322. !t.startsWith("zhangzara-") &&
  323. !/^[A-Z]/.test(t) &&
  324. t.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") !== short,
  325. );
  326. const moods = triggers.filter((t) => !/[ /]/.test(t)).slice(0, 3);
  327. const use = triggers.find((t) => /[ /]/.test(t));
  328. return [moods.join(", "), use].filter(Boolean).join(" · ");
  329. }
  330. const code = (name) => `\`${name}\``;
  331. // ---------- catalog ----------
  332. export function indexResources(resourceRoot) {
  333. const resources = collectResources(resourceRoot);
  334. const categoryOf = new Map();
  335. for (const name of CONFIG.excludeSkeletons) {
  336. if (!resources.skeletons.has(name)) throw new Error(`excludeSkeletons lists unknown skeleton ${name}`);
  337. }
  338. for (const category of CONFIG.categories) {
  339. if (!TRACKS.includes(category.track)) throw new Error(`category ${category.key} has unknown track ${category.track}`);
  340. for (const name of category.members) {
  341. if (!resources.skeletons.has(name)) throw new Error(`category ${category.key} lists unknown skeleton ${name}`);
  342. if (categoryOf.has(name)) throw new Error(`skeleton ${name} is in two categories`);
  343. if (CONFIG.excludeSkeletons.includes(name)) throw new Error(`skeleton ${name} is excluded but listed in ${category.key}`);
  344. categoryOf.set(name, category);
  345. }
  346. }
  347. const unassigned = [...resources.skeletons.keys()].filter(
  348. (name) => !categoryOf.has(name) && !CONFIG.excludeSkeletons.includes(name),
  349. );
  350. if (unassigned.length) throw new Error(`skeletons without a category: ${unassigned.join(", ")}`);
  351. const craftKeys = Object.keys(CONFIG.craft).sort(byCodePoint);
  352. if (craftKeys.join() !== resources.craft.join()) throw new Error("CONFIG.craft keys differ from the craft/ directory");
  353. return { ...resources, categoryOf };
  354. }
  355. // The shared half of the catalog: design systems, specialist skills, craft. Skeletons live in the deliverable files.
  356. export function buildCatalog(resourceRoot) {
  357. const { skills, systems } = indexResources(resourceRoot);
  358. const body = [];
  359. body.push("## Skills", "`design-resources/skills/<name>/SKILL.md`; only when no skeleton fits.", "");
  360. for (const [name, { frontmatter }] of skills) {
  361. if (CONFIG.skills.exclude.includes(name)) continue;
  362. const text = CONFIG.skills.override[name] ?? clip(firstSentence(frontmatter.description), CONFIG.shortTextWidth);
  363. body.push(`- ${code(name)} — ${text}`);
  364. }
  365. body.push("");
  366. body.push(
  367. "## Design systems",
  368. "`design-resources/design-systems/<name>/DESIGN.md`; read the file, not this line. With a brand system also read [BRAND-DISCLAIMER.md](../design-resources/design-systems/BRAND-DISCLAIMER.md).",
  369. "",
  370. );
  371. const groups = new Map([...new Set(Object.values(CONFIG.systemGroups))].map((group) => [group, []]));
  372. for (const [name, system] of systems) {
  373. const group = CONFIG.systemGroups[system.category];
  374. if (!group) throw new Error(`design system ${name}: unknown category ${system.category}`);
  375. let entry = code(name);
  376. if (CONFIG.systemNotes[name]) entry += ` (${CONFIG.systemNotes[name]})`;
  377. else if (CONFIG.systemOverride[name]) entry += ` ${CONFIG.systemOverride[name]}`;
  378. else if (!system.full) entry += ` ${clip(firstSentence(system.description), CONFIG.shortTextWidth)}`;
  379. groups.get(group).push(entry);
  380. }
  381. for (const [group, entries] of groups) {
  382. if (entries.length) body.push(`- **${group}**: ${entries.join("; ")}`);
  383. }
  384. body.push("");
  385. const aliases = Object.entries(CONFIG.craftAlias).map(([from, to]) => `${code(from)} = ${code(to)}`);
  386. body.push(
  387. "## Craft",
  388. `\`design-resources/craft/<name>.md\`. Metadata names: ${aliases.join("; ")}; ${CONFIG.craftDrop.map(code).join(", ")} are not shipped.`,
  389. "",
  390. );
  391. const byWhen = new Map();
  392. for (const [name, when] of Object.entries(CONFIG.craft)) byWhen.set(when, [...(byWhen.get(when) ?? []), name]);
  393. for (const [when, names] of byWhen) body.push(`- ${names.map(code).join(", ")} — ${when}`);
  394. const tracks = TRACKS.map((track) => `${track} in [${track}](${track}.md)`).join(", ");
  395. const head = [
  396. "# Resource catalog",
  397. "",
  398. "<!-- Generated by scripts/build-catalog.mjs from design-resources/; do not edit. -->",
  399. "",
  400. `The resources every deliverable shares. Paths are relative to this skill's directory; skeletons are listed per deliverable, ${tracks}.`,
  401. "Pick one skeleton (a skill only if none fits), read it, then a design system and craft; never bulk-read.",
  402. "Skeleton row flags: `self` = own visual rules, no design system needed; `+x` = extra craft; `ds:` = brand systems that skeleton suggests; `no example` = nothing beside it to open. Craft = baseline + the row's group default + its `+x`.",
  403. "",
  404. ];
  405. return `${[...head, ...body].join("\n").replace(/\n+$/, "")}\n`;
  406. }
  407. // ---------- skeleton blocks ----------
  408. export const BLOCK_BEGIN = "<!-- Skeletons generated by scripts/build-catalog.mjs; do not edit this block by hand. -->";
  409. export const BLOCK_END = "<!-- End of generated skeletons. -->";
  410. // The skeleton shortlist for one deliverable track, as it appears between the markers in that track's file.
  411. export function buildSkeletonBlock(resourceRoot, track) {
  412. const { skeletons, categoryOf } = indexResources(resourceRoot);
  413. if (!TRACKS.includes(track)) throw new Error(`unknown track ${track}`);
  414. const body = [
  415. `\`design-resources/design-skeletons/<name>/SKILL.md\`; row flags are defined in [catalog](catalog.md). Folders not listed need a runtime this host lacks; never use them.`,
  416. "",
  417. ];
  418. for (const category of CONFIG.categories.filter((c) => c.track === track)) {
  419. body.push(`### ${category.title}${category.craft.length ? ` (+${category.craft.join(", ")})` : ""}`);
  420. for (const name of category.members) {
  421. const { frontmatter, hasExample } = skeletons.get(name);
  422. const flags = [];
  423. const extras = craftExtras(frontmatter, category.craft);
  424. if (extras.length) flags.push(`+${extras.join(", ")}`);
  425. if (!category.prefix && frontmatter.od?.design_system?.requires === false) flags.push("self");
  426. const brands = frontmatter.od?.design_system?.recommended_brands;
  427. if (brands?.length) flags.push(`ds: ${brands.slice(0, 3).join("/")}`);
  428. if (!hasExample) flags.push("no example");
  429. let text;
  430. if (category.prefix) text = zhangzaraText(name, frontmatter, category.prefix);
  431. else if (CONFIG.override[name]) text = CONFIG.override[name];
  432. else if (!CONFIG.nameOnly.includes(name)) text = clip(firstSentence(frontmatter.description), CONFIG.textWidth);
  433. // Kept ahead of the flags so every row still ends in its `[...]`.
  434. const caveat = CONFIG.missing.find((entry) => entry.inline && entry.usedBy.includes(name))?.inline;
  435. if (caveat) text = text ? `${text}; ${caveat}` : caveat;
  436. const label = category.prefix ? name.slice(category.prefix.length) : name;
  437. body.push(`- ${code(label)}${text ? ` — ${text}` : ""}${flags.length ? ` [${flags.join("; ")}]` : ""}`);
  438. }
  439. for (const note of CONFIG.notes) {
  440. if (categoryOf.get(note.names[0]) === category) body.push(`- Note, ${note.names.map(code).join(", ")}: ${note.text}.`);
  441. }
  442. body.push("");
  443. }
  444. const missing = CONFIG.missing.filter((entry) => entry.label && categoryOf.get(entry.usedBy[0]).track === track);
  445. if (missing.length) {
  446. body.push(`Not shipped, though some SKILL.md files name them: ${missing.map((entry) => entry.label).join("; ")}. Do not claim to have read or run them.`);
  447. }
  448. return body.join("\n").replace(/\n+$/, "");
  449. }
  450. // Replaces the generated block in a deliverable file, leaving its hand-written rules alone.
  451. export function patchSkeletonBlock(text, block) {
  452. const start = text.indexOf(BLOCK_BEGIN);
  453. const end = text.indexOf(BLOCK_END);
  454. if (start < 0 || end < 0 || end < start) throw new Error(`file lacks the ${BLOCK_BEGIN} / ${BLOCK_END} markers`);
  455. return `${text.slice(0, start)}${BLOCK_BEGIN}\n\n${block}\n\n${text.slice(end)}`;
  456. }
  457. // Every generated file as it should be on disk, read from and keyed by its path under `referencesDir`.
  458. export function buildAll(resourceRoot, referencesDir) {
  459. const out = new Map();
  460. out.set(TARGETS.catalog.file, buildCatalog(resourceRoot));
  461. for (const track of TRACKS) {
  462. const file = TARGETS[track].file;
  463. const current = readFileSync(join(referencesDir, file), "utf8");
  464. out.set(file, patchSkeletonBlock(current, buildSkeletonBlock(resourceRoot, track)));
  465. }
  466. return out;
  467. }
  468. // Bytes per `##` / `###` section, for the over-cap report.
  469. export function sectionSizes(text) {
  470. let current = { title: "(head)", bytes: 0 };
  471. const sizes = [current];
  472. for (const line of text.replace(/\n$/, "").split("\n")) {
  473. const heading = line.match(/^#{2,3} (.+)$/);
  474. if (heading) sizes.push((current = { title: heading[1], bytes: 0 }));
  475. current.bytes += Buffer.byteLength(`${line}\n`, "utf8");
  476. }
  477. return sizes;
  478. }
  479. const skillRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
  480. export function main(argv = process.argv.slice(2)) {
  481. const option = (name) => argv.find((arg) => arg.startsWith(`--${name}=`))?.slice(name.length + 3);
  482. const override = option("max-bytes") === undefined ? null : Number(option("max-bytes"));
  483. const dir = option("dir") ?? join(skillRoot, "references");
  484. const texts = buildAll(join(skillRoot, "design-resources"), dir);
  485. const capOf = (file) => override ?? Object.values(TARGETS).find((t) => t.file === file).maxBytes;
  486. const over = [...texts].filter(([file, text]) => Buffer.byteLength(text, "utf8") > capOf(file));
  487. // All or nothing: an over-cap file would otherwise be committed while its siblings look fresh.
  488. if (over.length) {
  489. for (const [file, text] of over) {
  490. const report = sectionSizes(text).map(({ title, bytes }) => ` ${String(bytes).padStart(6)} ${title}`);
  491. process.stderr.write(`${file} is ${Buffer.byteLength(text, "utf8")} B, over the ${capOf(file)} B cap; not written.\n${report.join("\n")}\n`);
  492. }
  493. return 1;
  494. }
  495. for (const [file, text] of texts) {
  496. writeFileSync(join(dir, file), text);
  497. process.stdout.write(`wrote ${join(dir, file)}: ${Buffer.byteLength(text, "utf8")} B, ${text.split("\n").length - 1} lines\n`);
  498. }
  499. return 0;
  500. }
  501. // Compare real paths: import.meta.url is already symlink-resolved, so a run through a symlinked
  502. // install path (or a symlinked /tmp) must not silently skip main(). Synthetic entry paths need not resolve.
  503. function entryUrl(scriptPath) {
  504. if (scriptPath === undefined) return undefined;
  505. try {
  506. return pathToFileURL(realpathSync(resolve(scriptPath))).href;
  507. } catch {
  508. return undefined;
  509. }
  510. }
  511. if (import.meta.url === entryUrl(process.argv[1])) {
  512. process.exitCode = main();
  513. }