@lifeaitools/rdc-skills 0.24.38 → 0.24.41

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.
Files changed (196) hide show
  1. package/.claude/settings.json +15 -15
  2. package/.claude-plugin/marketplace.json +21 -21
  3. package/.claude-plugin/plugin.json +1371 -1371
  4. package/.github/workflows/publish.yml +34 -34
  5. package/.github/workflows/self-test.yml +58 -58
  6. package/CHANGELOG.md +310 -310
  7. package/LICENSE +21 -21
  8. package/MANIFEST.md +221 -221
  9. package/README.md +376 -375
  10. package/README.sandbox.md +3 -3
  11. package/RELEASE.md +42 -0
  12. package/assets/watcher/viewer.html +164 -164
  13. package/bin/rdc-skills-mcp.mjs +316 -316
  14. package/commands/build.md +183 -183
  15. package/commands/collab.md +180 -180
  16. package/commands/deploy.md +152 -152
  17. package/commands/design.md +31 -31
  18. package/commands/edit.md +28 -28
  19. package/commands/fixit.md +124 -124
  20. package/commands/handoff.md +173 -173
  21. package/commands/help.md +95 -95
  22. package/commands/overnight.md +220 -220
  23. package/commands/plan.md +158 -158
  24. package/commands/preplan.md +131 -131
  25. package/commands/prototype.md +145 -145
  26. package/commands/release.md +49 -49
  27. package/commands/report.md +99 -99
  28. package/commands/review.md +120 -120
  29. package/commands/self-test.md +113 -113
  30. package/commands/status.md +86 -86
  31. package/commands/watch.md +98 -98
  32. package/commands/workitems.md +137 -137
  33. package/git-sha.json +1 -1
  34. package/guides/agent-bootstrap.md +295 -295
  35. package/guides/agents/backend.md +104 -104
  36. package/guides/agents/content.md +94 -94
  37. package/guides/agents/cs2.md +56 -56
  38. package/guides/agents/data.md +87 -87
  39. package/guides/agents/design.md +77 -77
  40. package/guides/agents/frontend.md +92 -92
  41. package/guides/agents/infrastructure.md +81 -81
  42. package/guides/agents/setup.md +281 -281
  43. package/guides/agents/verify.md +151 -151
  44. package/guides/agents/viz.md +106 -106
  45. package/guides/backend.md +146 -146
  46. package/guides/content.md +147 -147
  47. package/guides/cs2.md +190 -190
  48. package/guides/data.md +123 -123
  49. package/guides/design.md +116 -116
  50. package/guides/engineering-behavior.md +43 -43
  51. package/guides/escalation-protocol.md +125 -125
  52. package/guides/frontend.md +151 -151
  53. package/guides/history-md-spec.md +297 -297
  54. package/guides/infrastructure.md +179 -179
  55. package/guides/lessons-learned-spec.md +151 -145
  56. package/guides/output-contract.md +108 -108
  57. package/guides/publish-md-spec.md +289 -289
  58. package/guides/rdc-skills-startup.md +30 -30
  59. package/guides/verify.md +11 -11
  60. package/hooks/check-cwd.js +31 -31
  61. package/hooks/check-rdc-environment.js +164 -164
  62. package/hooks/check-services.js +6 -6
  63. package/hooks/check-stale-work-items.js +19 -19
  64. package/hooks/foreground-process-gate.js +128 -128
  65. package/hooks/gate-watchdog-selfcheck.js +257 -257
  66. package/hooks/hook-logger.js +25 -25
  67. package/hooks/lib/run-evidence-gate.mjs +241 -241
  68. package/hooks/no-stop-open-epics.js +127 -127
  69. package/hooks/post-tool-batch-gate.js +203 -203
  70. package/hooks/post-work-check.js +21 -21
  71. package/hooks/postcompact-log.js +13 -13
  72. package/hooks/precompact-log.js +13 -13
  73. package/hooks/rate-limit-retry.js +46 -46
  74. package/hooks/rdc-invocation-marker.js +157 -157
  75. package/hooks/rdc-output-contract-gate.js +94 -94
  76. package/hooks/require-work-item-on-commit.js +294 -294
  77. package/hooks/restart-brief.js +19 -19
  78. package/hooks/run-hidden-hook.ps1 +47 -47
  79. package/hooks/task-completed-gate.js +274 -274
  80. package/hooks/work-item-exit-gate.js +944 -944
  81. package/lib/catalog.mjs +236 -236
  82. package/lib/cloud-rewrite.mjs +155 -155
  83. package/package.json +57 -56
  84. package/rules/work-items-rpc.md +520 -520
  85. package/scaffold/templates/HISTORY.md.template +39 -39
  86. package/scaffold/templates/PUBLISH.md.template +21 -21
  87. package/scaffold/templates/brochure-studio-default.html +70 -70
  88. package/scripts/acceptance.mjs +502 -502
  89. package/scripts/fixtures/guides/bad-guide.md +15 -15
  90. package/scripts/fixtures/guides-clean/good-guide.md +16 -16
  91. package/scripts/install-rdc-skills.js +1289 -1289
  92. package/scripts/install.ps1 +202 -202
  93. package/scripts/install.sh +132 -132
  94. package/scripts/lib/assertions.mjs +287 -287
  95. package/scripts/lib/manifest-schema.mjs +754 -754
  96. package/scripts/lib/runner.mjs +465 -465
  97. package/scripts/lib/sandbox.mjs +435 -435
  98. package/scripts/prepack.mjs +32 -32
  99. package/scripts/rdc-brochure.mjs +482 -464
  100. package/scripts/rdc-design-cli.mjs +134 -134
  101. package/scripts/rebuild-mcp.mjs +107 -107
  102. package/scripts/self-test.mjs +1460 -1460
  103. package/scripts/stamp-git-sha.mjs +29 -29
  104. package/scripts/test-guide-validator.mjs +196 -196
  105. package/scripts/test-rdc-hooks.mjs +145 -145
  106. package/scripts/uninstall.ps1 +77 -77
  107. package/scripts/uninstall.sh +69 -69
  108. package/scripts/update.ps1 +43 -43
  109. package/scripts/update.sh +43 -43
  110. package/scripts/validate-place-histories.js +461 -461
  111. package/scripts/validate-publish-manifests.js +424 -424
  112. package/scripts/watch-init.mjs +100 -100
  113. package/skills/brochure/SKILL.md +107 -107
  114. package/skills/build/SKILL.md +563 -563
  115. package/skills/channel-formatter/SKILL.md +533 -533
  116. package/skills/co-develop/SKILL.md +196 -196
  117. package/skills/collab/SKILL.md +239 -239
  118. package/skills/convert/SKILL.md +140 -140
  119. package/skills/deploy/SKILL.md +541 -541
  120. package/skills/design/SKILL.md +211 -211
  121. package/skills/design/reference/ownership.md +16 -16
  122. package/skills/design/reference/rampa.md +92 -92
  123. package/skills/design/reference/studio-model.md +153 -153
  124. package/skills/edit/SKILL.md +98 -98
  125. package/skills/fixit/SKILL.md +165 -165
  126. package/skills/fs-mcp/SKILL.md +148 -148
  127. package/skills/handoff/SKILL.md +236 -200
  128. package/skills/help/SKILL.md +143 -143
  129. package/skills/housekeeping/SKILL.md +219 -160
  130. package/skills/lifeai-brochure-author/SKILL.md +340 -340
  131. package/skills/overnight/SKILL.md +251 -251
  132. package/skills/plan/SKILL.md +345 -345
  133. package/skills/preplan/SKILL.md +90 -90
  134. package/skills/prototype/SKILL.md +150 -150
  135. package/skills/rdc-brochurify/SKILL.md +245 -245
  136. package/skills/rdc-extract-verifier-rules/SKILL.md +191 -191
  137. package/skills/release/SKILL.md +140 -140
  138. package/skills/report/SKILL.md +100 -100
  139. package/skills/review/SKILL.md +152 -152
  140. package/skills/rpms-filemap/SKILL.cloud.md +111 -111
  141. package/skills/rpms-filemap/SKILL.md +111 -111
  142. package/skills/self-test/SKILL.md +132 -132
  143. package/skills/status/SKILL.md +99 -99
  144. package/skills/terminal-config/SKILL.md +62 -62
  145. package/skills/tests/MATRIX.md +54 -54
  146. package/skills/tests/README.md +47 -47
  147. package/skills/tests/rdc-brochure.test.json +34 -34
  148. package/skills/tests/rdc-build.test.json +36 -36
  149. package/skills/tests/rdc-channel-formatter.test.json +45 -45
  150. package/skills/tests/rdc-co-develop.test.json +29 -29
  151. package/skills/tests/rdc-collab.test.json +29 -29
  152. package/skills/tests/rdc-convert.test.json +35 -35
  153. package/skills/tests/rdc-deploy.test.json +30 -30
  154. package/skills/tests/rdc-design.test.json +27 -27
  155. package/skills/tests/rdc-edit.test.json +29 -29
  156. package/skills/tests/rdc-fixit.test.json +36 -36
  157. package/skills/tests/rdc-fs-mcp.test.json +36 -36
  158. package/skills/tests/rdc-handoff.test.json +28 -28
  159. package/skills/tests/rdc-help.test.json +29 -29
  160. package/skills/tests/rdc-housekeeping.test.json +32 -28
  161. package/skills/tests/rdc-lifeai-brochure-author.test.json +35 -35
  162. package/skills/tests/rdc-overnight.test.json +37 -37
  163. package/skills/tests/rdc-plan.test.json +27 -27
  164. package/skills/tests/rdc-preplan.test.json +31 -31
  165. package/skills/tests/rdc-prototype.test.json +28 -28
  166. package/skills/tests/rdc-rdc-brochurify.test.json +23 -23
  167. package/skills/tests/rdc-rdc-extract-verifier-rules.test.json +34 -34
  168. package/skills/tests/rdc-release.test.json +29 -29
  169. package/skills/tests/rdc-report.test.json +28 -28
  170. package/skills/tests/rdc-review.test.json +29 -29
  171. package/skills/tests/rdc-rpms-filemap.test.json +28 -28
  172. package/skills/tests/rdc-self-test.test.json +24 -24
  173. package/skills/tests/rdc-status.test.json +29 -29
  174. package/skills/tests/rdc-terminal-config.test.json +29 -29
  175. package/skills/tests/rdc-watch.test.json +24 -24
  176. package/skills/tests/rdc-workitems.test.json +27 -27
  177. package/skills/watch/SKILL.md +97 -97
  178. package/skills/workitems/SKILL.md +151 -151
  179. package/tests/acceptance.test.mjs +59 -59
  180. package/tests/channel-formatter.contract.test.mjs +251 -251
  181. package/tests/curl-surface.test.mjs +289 -289
  182. package/tests/harness-gates.test.mjs +325 -325
  183. package/tests/help-surface.test.mjs +61 -61
  184. package/tests/housekeeping-lessons-triage.test.mjs +49 -0
  185. package/tests/install-rdc-skills.test.mjs +49 -49
  186. package/tests/lessons-pipeline-contract.test.mjs +26 -0
  187. package/tests/manifest-contract-fields.test.mjs +78 -78
  188. package/tests/mcp.test.mjs +271 -271
  189. package/tests/rdc-brochure.test.mjs +125 -0
  190. package/tests/release-contract.test.mjs +16 -0
  191. package/tests/require-work-item-on-commit.test.mjs +162 -162
  192. package/tests/run-evidence-gate.test.mjs +82 -82
  193. package/tests/skill-test-matrix.test.mjs +66 -66
  194. package/tests/validate-skills.js +27 -27
  195. package/tests/work-item-exit-gate-l2.test.mjs +368 -368
  196. package/tests/work-item-exit-gate-l3.test.mjs +197 -197
@@ -1,464 +1,482 @@
1
- #!/usr/bin/env node
2
- /**
3
- * rdc:brochure — zip/folder/html/url/markdown → PDF via Puppeteer.
4
- * See skills/brochure/SKILL.md for the contract.
5
- */
6
- import { execSync, spawnSync } from 'node:child_process';
7
- import { createHash } from 'node:crypto';
8
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, copyFileSync } from 'node:fs';
9
- import { homedir, tmpdir } from 'node:os';
10
- import { dirname, basename, extname, join, resolve, relative, sep } from 'node:path';
11
- import { pathToFileURL, fileURLToPath } from 'node:url';
12
- import { createRequire } from 'node:module';
13
-
14
- const AUTO_FIT_CSS = `
15
- /* rdc:brochure --auto-fit corrective stylesheet
16
- Generic print-overflow safety net. Applied AFTER document stylesheets. */
17
- @media print, screen {
18
- html, body { overflow: visible !important; }
19
- body { max-width: 100% !important; }
20
- *, *::before, *::after { box-sizing: border-box; }
21
-
22
- img, svg, video, canvas, iframe, object, embed {
23
- max-width: 100% !important;
24
- height: auto !important;
25
- object-fit: contain;
26
- }
27
- figure, .figure, picture { break-inside: avoid; page-break-inside: avoid; max-width: 100%; }
28
-
29
- table {
30
- table-layout: fixed !important;
31
- width: 100% !important;
32
- max-width: 100% !important;
33
- word-wrap: break-word;
34
- overflow-wrap: anywhere;
35
- border-collapse: collapse;
36
- }
37
- th, td { word-wrap: break-word; overflow-wrap: anywhere; max-width: 100%; }
38
- thead { display: table-header-group; }
39
- tr, td, th { break-inside: avoid; page-break-inside: avoid; }
40
-
41
- pre, code, kbd, samp { white-space: pre-wrap !important; word-break: break-word; overflow-wrap: anywhere; max-width: 100%; }
42
- pre { break-inside: avoid; page-break-inside: avoid; }
43
-
44
- h1, h2, h3, h4, h5, h6 { break-after: avoid; page-break-after: avoid; }
45
- h1 + *, h2 + *, h3 + *, h4 + * { break-before: avoid; }
46
- p, li { orphans: 3; widows: 3; }
47
-
48
- /* Generic wide-content sentinels */
49
- .wide, .full-bleed, .panorama { max-width: 100% !important; }
50
-
51
- /* Avoid blank-page artifacts from oversized flex/grid containers */
52
- [style*="position: fixed"], [style*="position:fixed"] { position: static !important; }
53
- }
54
- `;
55
-
56
- const HERE = dirname(fileURLToPath(import.meta.url));
57
- const REPO_ROOT = resolve(HERE, '..');
58
- const TEMPLATES_DIR = join(REPO_ROOT, 'scaffold', 'templates');
59
-
60
- // --- args ------------------------------------------------------------------
61
- const argv = process.argv.slice(2);
62
- const opts = { template: 'studio-default', format: 'Letter', printEmulate: true, keepWorkdir: false, autoFit: false, scale: 1 };
63
- let input;
64
- for (let i = 0; i < argv.length; i++) {
65
- const a = argv[i];
66
- if (a === '--out') opts.out = argv[++i];
67
- else if (a === '--template') opts.template = argv[++i];
68
- else if (a === '--format') opts.format = argv[++i];
69
- else if (a === '--margin') opts.margin = argv[++i];
70
- else if (a === '--no-print-emulate') opts.printEmulate = false;
71
- else if (a === '--keep-workdir') opts.keepWorkdir = true;
72
- else if (a === '--auto-fit') opts.autoFit = true;
73
- else if (a === '--scale') opts.scale = parseFloat(argv[++i]);
74
- else if (!input) input = a;
75
- }
76
- if (!input) {
77
- console.error('usage: rdc-brochure.mjs <zip|folder|html|md|url> [--out path] [--template name] [--format Letter|A4]');
78
- process.exit(2);
79
- }
80
-
81
- // --- helpers ---------------------------------------------------------------
82
- const isUrl = /^https?:\/\//i.test(input);
83
- const hash = createHash('sha1').update(input).digest('hex').slice(0, 10);
84
- const workRoot = join(tmpdir(), 'rdc-brochure', hash);
85
- mkdirSync(workRoot, { recursive: true });
86
-
87
- const log = (...a) => console.log('[brochure]', ...a);
88
-
89
- function human(n) {
90
- const u = ['B', 'KB', 'MB', 'GB'];
91
- let i = 0;
92
- while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
93
- return `${n.toFixed(1)} ${u[i]}`;
94
- }
95
-
96
- function walk(dir) {
97
- const out = [];
98
- for (const e of readdirSync(dir, { withFileTypes: true })) {
99
- const p = join(dir, e.name);
100
- if (e.isDirectory()) out.push(...walk(p));
101
- else out.push(p);
102
- }
103
- return out;
104
- }
105
-
106
- // --- ensure puppeteer ------------------------------------------------------
107
- async function loadPuppeteer() {
108
- try { return (await import('puppeteer')).default; } catch {}
109
- // Try a local cache install.
110
- const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
111
- mkdirSync(cacheDir, { recursive: true });
112
- if (!existsSync(join(cacheDir, 'package.json'))) {
113
- writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
114
- }
115
- if (!existsSync(join(cacheDir, 'node_modules', 'puppeteer'))) {
116
- log('installing puppeteer into', cacheDir);
117
- execSync('npm install puppeteer --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
118
- }
119
- const req = createRequire(join(cacheDir, 'package.json'));
120
- const mod = req('puppeteer');
121
- return mod.default || mod;
122
- }
123
-
124
- // --- cross-platform unzip --------------------------------------------------
125
- // Pure-Node first (adm-zip — works on every platform, no external binary).
126
- // If the lib cannot be resolved or installed, fall back to a platform-native
127
- // extractor: `unzip` on POSIX, PowerShell `Expand-Archive` on win32.
128
- function loadAdmZip() {
129
- try { return createRequire(import.meta.url)('adm-zip'); } catch {}
130
- // Reuse the puppeteer on-demand cache dir for an isolated local install.
131
- const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
132
- mkdirSync(cacheDir, { recursive: true });
133
- if (!existsSync(join(cacheDir, 'package.json'))) {
134
- writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
135
- }
136
- if (!existsSync(join(cacheDir, 'node_modules', 'adm-zip'))) {
137
- try {
138
- log('installing adm-zip into', cacheDir);
139
- execSync('npm install adm-zip --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
140
- } catch { return null; }
141
- }
142
- try { return createRequire(join(cacheDir, 'package.json'))('adm-zip'); } catch { return null; }
143
- }
144
-
145
- // Reject any archive member that resolves outside destDir (zip-slip / path
146
- // traversal). Returns the validated absolute destination path. Throws on escape.
147
- function safeJoinOrThrow(destDir, entryName) {
148
- const root = resolve(destDir);
149
- const dest = resolve(root, entryName);
150
- if (dest !== root && !dest.startsWith(root + sep)) {
151
- throw new Error(`zip-slip: entry "${entryName}" escapes destination directory`);
152
- }
153
- return dest;
154
- }
155
-
156
- function extractZip(zipPath, destDir) {
157
- mkdirSync(destDir, { recursive: true });
158
- const root = resolve(destDir);
159
- const AdmZip = loadAdmZip();
160
- if (AdmZip) {
161
- const zip = new AdmZip(zipPath);
162
- const entries = zip.getEntries();
163
- // First pass: validate every entry resolves inside destDir. A brochure
164
- // source zip must never contain `..` or absolute members — reject the whole
165
- // archive rather than silently skipping (fail-closed).
166
- for (const entry of entries) {
167
- safeJoinOrThrow(root, entry.entryName);
168
- }
169
- // Second pass: extract validated entries individually. Do NOT use the
170
- // blanket extractAllTo adm-zip does not sanitize entry paths.
171
- for (const entry of entries) {
172
- if (entry.isDirectory) {
173
- mkdirSync(safeJoinOrThrow(root, entry.entryName), { recursive: true });
174
- continue;
175
- }
176
- const dest = safeJoinOrThrow(root, entry.entryName);
177
- mkdirSync(dirname(dest), { recursive: true });
178
- zip.extractEntryTo(entry, root, /* maintainEntryPath */ true, /* overwrite */ true);
179
- }
180
- return;
181
- }
182
- // Fallback: platform-native extractor. Validate members via a listing pass
183
- // BEFORE extracting, since the bulk extract commands cannot apply per-entry
184
- // guards. Reject any `..` segment or absolute/leading-slash member.
185
- log('adm-zip unavailable falling back to platform unzip');
186
- assertNativeZipSafe(zipPath);
187
- let r;
188
- if (process.platform === 'win32') {
189
- r = spawnSync('powershell', ['-NoProfile', '-Command',
190
- `Expand-Archive -Path '${zipPath}' -DestinationPath '${destDir}' -Force`], { stdio: 'inherit' });
191
- } else {
192
- r = spawnSync('unzip', ['-o', '-q', zipPath, '-d', destDir], { stdio: 'inherit' });
193
- }
194
- if (!r || r.status !== 0) throw new Error('unzip failed (no pure-Node lib and platform extractor failed)');
195
- }
196
-
197
- // List archive members with a native tool and reject any traversal/absolute
198
- // entry. Throws if a member is unsafe or the listing cannot be produced.
199
- function assertNativeZipSafe(zipPath) {
200
- let names = [];
201
- if (process.platform === 'win32') {
202
- const ps = spawnSync('powershell', ['-NoProfile', '-Command',
203
- `Add-Type -AssemblyName System.IO.Compression.FileSystem; ` +
204
- `[System.IO.Compression.ZipFile]::OpenRead('${zipPath}').Entries | ForEach-Object { $_.FullName }`],
205
- { encoding: 'utf8' });
206
- if (ps.status !== 0) throw new Error('cannot list zip members for traversal check (PowerShell)');
207
- names = String(ps.stdout || '').split(/\r?\n/);
208
- } else {
209
- const zi = spawnSync('zipinfo', ['-1', zipPath], { encoding: 'utf8' });
210
- if (zi.status === 0) {
211
- names = String(zi.stdout || '').split(/\r?\n/);
212
- } else {
213
- const ul = spawnSync('unzip', ['-Z1', zipPath], { encoding: 'utf8' });
214
- if (ul.status !== 0) throw new Error('cannot list zip members for traversal check (unzip -Z1)');
215
- names = String(ul.stdout || '').split(/\r?\n/);
216
- }
217
- }
218
- for (const raw of names) {
219
- const name = raw.trim();
220
- if (!name) continue;
221
- const norm = name.replace(/\\/g, '/');
222
- if (norm.startsWith('/') || /^[A-Za-z]:/.test(norm) || norm.split('/').some((seg) => seg === '..')) {
223
- throw new Error(`zip-slip: entry "${name}" escapes destination directory`);
224
- }
225
- }
226
- }
227
-
228
- // --- stage input -----------------------------------------------------------
229
- function stageInput() {
230
- const stageDir = join(workRoot, 'src');
231
- mkdirSync(stageDir, { recursive: true });
232
- if (isUrl) return { kind: 'url', url: input, stageDir };
233
- const abs = resolve(input);
234
- if (!existsSync(abs)) throw new Error(`not found: ${abs}`);
235
- const st = statSync(abs);
236
- if (st.isDirectory()) return { kind: 'folder', root: abs, stageDir: abs };
237
- const ext = extname(abs).toLowerCase();
238
- if (ext === '.zip') {
239
- log('extracting zip to', stageDir);
240
- extractZip(abs, stageDir);
241
- return { kind: 'folder', root: stageDir, stageDir };
242
- }
243
- if (ext === '.html' || ext === '.htm') return { kind: 'html', file: abs, stageDir: dirname(abs) };
244
- if (ext === '.md' || ext === '.markdown') return { kind: 'md', file: abs, stageDir: dirname(abs) };
245
- throw new Error(`unsupported input: ${ext || '(no extension)'}`);
246
- }
247
-
248
- // --- pick HTML in render mode ----------------------------------------------
249
- function pickHtml(rootDir) {
250
- const htmls = walk(rootDir).filter((p) => /\.html?$/i.test(p));
251
- if (!htmls.length) return null;
252
- const scored = htmls.map((p) => {
253
- const text = readFileSync(p, 'utf8');
254
- const size = statSync(p).size;
255
- let score = 0;
256
- if (/@page\b/.test(text)) score += 1000;
257
- if (/@media\s+print/i.test(text)) score += 500;
258
- if (/-print\.html?$/i.test(p)) score += 300;
259
- if (/brochure\.html?$/i.test(p)) score += 250;
260
- if (/(^|[\\/])print\.html?$/i.test(p)) score += 250;
261
- if (/standalone/i.test(basename(p))) score -= 50; // usually huge embedded duplicate
262
- score += Math.min(size / 1024, 200); // size as tiebreaker, capped
263
- return { p, score, size };
264
- }).sort((a, b) => b.score - a.score);
265
- return scored[0].p;
266
- }
267
-
268
- // --- compose mode ----------------------------------------------------------
269
- function listTemplates() {
270
- if (!existsSync(TEMPLATES_DIR)) return [];
271
- return readdirSync(TEMPLATES_DIR)
272
- .map((f) => /^brochure-(.+)\.html$/i.exec(f))
273
- .filter(Boolean)
274
- .map((m) => m[1])
275
- .sort();
276
- }
277
-
278
- async function composeFromFolder(root, file) {
279
- const tpl = join(TEMPLATES_DIR, `brochure-${opts.template}.html`);
280
- if (!existsSync(tpl)) {
281
- const available = listTemplates();
282
- const list = available.length ? available.join(', ') : '(none found)';
283
- throw new Error(`unknown template "${opts.template}". Available template(s): ${list}`);
284
- }
285
- let html = readFileSync(tpl, 'utf8');
286
-
287
- let mdFiles = [];
288
- if (file) mdFiles = [file];
289
- else mdFiles = walk(root).filter((p) => /\.(md|markdown)$/i.test(p)).sort();
290
-
291
- const title = (() => {
292
- for (const p of mdFiles) {
293
- const m = readFileSync(p, 'utf8').match(/^#\s+(.+)$/m);
294
- if (m) return m[1].trim();
295
- }
296
- return basename(file || root);
297
- })();
298
-
299
- const sections = mdFiles.map((p) => {
300
- const md = readFileSync(p, 'utf8');
301
- // Only prepend the filename heading when the markdown has no leading ATX heading
302
- // of its own. Avoids a redundant <h2>filename</h2> stacked above a "# Title".
303
- const firstNonEmpty = md.replace(/\r\n/g, '\n').split('\n').find((l) => l.trim() !== '') || '';
304
- const hasLeadingHeading = /^#{1,6}\s+\S/.test(firstNonEmpty.trim());
305
- const heading = hasLeadingHeading ? '' : `<h2>${escapeHtml(basename(p, extname(p)))}</h2>`;
306
- return `<section class="brochure-section">${heading}${mdToHtml(md, dirname(p))}</section>`;
307
- }).join('\n');
308
-
309
- html = html.replace(/\{\{TITLE\}\}/g, escapeHtml(title)).replace(/\{\{SECTIONS\}\}/g, sections);
310
-
311
- const tokensCss = findSibling(root || dirname(file), 'tokens.css');
312
- if (tokensCss) html = html.replace('/* TOKENS_INJECT */', readFileSync(tokensCss, 'utf8'));
313
-
314
- const outHtml = join(workRoot, 'composed.html');
315
- writeFileSync(outHtml, html);
316
- return outHtml;
317
- }
318
-
319
- function findSibling(dir, name) {
320
- if (!dir) return null;
321
- const p = join(dir, name);
322
- return existsSync(p) ? p : null;
323
- }
324
-
325
- function escapeHtml(s) {
326
- return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
327
- }
328
-
329
- // Minimal markdown — headings, paragraphs, lists, bold/italic, inline code, fenced code, images.
330
- function mdToHtml(md, baseDir) {
331
- let out = md.replace(/\r\n/g, '\n');
332
- out = out.replace(/```([a-z]*)\n([\s\S]*?)```/g, (_, lang, body) => `<pre><code class="lang-${escapeHtml(lang)}">${escapeHtml(body)}</code></pre>`);
333
- out = out.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_, alt, src) => `<img alt="${escapeHtml(alt)}" src="${resolveImg(src, baseDir)}"/>`);
334
- out = out.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>')
335
- .replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>')
336
- .replace(/^####\s+(.+)$/gm, '<h4>$1</h4>')
337
- .replace(/^###\s+(.+)$/gm, '<h3>$1</h3>')
338
- .replace(/^##\s+(.+)$/gm, '<h2>$1</h2>')
339
- .replace(/^#\s+(.+)$/gm, '<h1>$1</h1>');
340
- out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/\*([^*]+)\*/g, '<em>$1</em>').replace(/`([^`]+)`/g, '<code>$1</code>');
341
- out = out.replace(/(?:^|\n)((?:[-*]\s+.+\n?)+)/g, (_, block) => `\n<ul>${block.trim().split(/\n/).map((l) => `<li>${l.replace(/^[-*]\s+/, '')}</li>`).join('')}</ul>\n`);
342
- out = out.split(/\n{2,}/).map((b) => /^<(h\d|ul|ol|pre|img|section|div)/.test(b.trim()) ? b : `<p>${b.trim()}</p>`).join('\n');
343
- return out;
344
- }
345
-
346
- function resolveImg(src, baseDir) {
347
- if (/^https?:|^data:/.test(src)) return src;
348
- const p = resolve(baseDir, src);
349
- if (!existsSync(p)) return src;
350
- return pathToFileURL(p).href;
351
- }
352
-
353
- // --- render ----------------------------------------------------------------
354
- async function render(htmlSource) {
355
- const puppeteer = await loadPuppeteer();
356
- const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox', '--font-render-hinting=none'] });
357
- try {
358
- const page = await browser.newPage();
359
- page.on('pageerror', (e) => log('pageerror:', e.message));
360
- const url = htmlSource.startsWith('http') ? htmlSource : pathToFileURL(htmlSource).href;
361
- log('loading', url);
362
- await page.goto(url, { waitUntil: 'networkidle0', timeout: 180_000 });
363
- await page.evaluateHandle('document.fonts.ready');
364
- await new Promise((r) => setTimeout(r, 1500));
365
- if (opts.printEmulate) await page.emulateMediaType('print');
366
-
367
- if (opts.autoFit) {
368
- await page.addStyleTag({ content: AUTO_FIT_CSS });
369
- const report = await page.evaluate(() => {
370
- const issues = [];
371
- const all = document.body.querySelectorAll('*');
372
- const pageWidthPx = document.documentElement.clientWidth;
373
- for (const el of all) {
374
- const r = el.getBoundingClientRect();
375
- if (r.width > pageWidthPx + 4) {
376
- issues.push({ tag: el.tagName, cls: el.className?.toString().slice(0, 60) || '', width: Math.round(r.width), pageWidth: pageWidthPx });
377
- if (issues.length >= 25) break;
378
- }
379
- }
380
- return issues;
381
- });
382
- if (report.length) {
383
- log(`auto-fit: ${report.length} overflow element(s) detected — corrective CSS applied`);
384
- for (const r of report.slice(0, 8)) log(` · ${r.tag}${r.cls ? '.' + r.cls : ''} width=${r.width}px (page=${r.pageWidth}px)`);
385
- } else {
386
- log('auto-fit: no overflow detected after corrective CSS');
387
- }
388
- await new Promise((r) => setTimeout(r, 400));
389
- }
390
-
391
- const outPath = resolve(opts.out || defaultOutPath());
392
- mkdirSync(dirname(outPath), { recursive: true });
393
-
394
- const pdfOpts = {
395
- path: outPath,
396
- format: opts.format,
397
- printBackground: true,
398
- preferCSSPageSize: true,
399
- displayHeaderFooter: false,
400
- scale: opts.scale && opts.scale !== 1 ? opts.scale : undefined,
401
- };
402
- if (opts.margin) {
403
- const m = opts.margin;
404
- pdfOpts.margin = { top: m, bottom: m, left: m, right: m };
405
- pdfOpts.preferCSSPageSize = false;
406
- } else if (!htmlSource.startsWith('http')) {
407
- const text = readFileSync(htmlSource, 'utf8');
408
- if (!/@page\b/.test(text)) {
409
- pdfOpts.margin = { top: '0.6in', bottom: '0.6in', left: '0.7in', right: '0.7in' };
410
- pdfOpts.preferCSSPageSize = false;
411
- }
412
- }
413
-
414
- await page.pdf(pdfOpts);
415
- return outPath;
416
- } finally {
417
- await browser.close();
418
- }
419
- }
420
-
421
- function defaultOutPath() {
422
- if (isUrl) return resolve('brochure.pdf');
423
- const abs = resolve(input);
424
- const base = basename(abs, extname(abs));
425
- return resolve(dirname(abs), `${base}.pdf`);
426
- }
427
-
428
- // --- main ------------------------------------------------------------------
429
- (async () => {
430
- const staged = stageInput();
431
- let htmlSource;
432
-
433
- if (staged.kind === 'url') {
434
- htmlSource = staged.url;
435
- } else if (staged.kind === 'html') {
436
- htmlSource = staged.file;
437
- } else if (staged.kind === 'md') {
438
- htmlSource = await composeFromFolder(null, staged.file);
439
- } else { // folder
440
- const picked = pickHtml(staged.stageDir);
441
- if (picked) {
442
- log('picked html:', relative(staged.stageDir, picked));
443
- htmlSource = picked;
444
- } else {
445
- log('no html found — composing from markdown');
446
- htmlSource = await composeFromFolder(staged.stageDir);
447
- }
448
- }
449
-
450
- const outPath = await render(htmlSource);
451
- const size = statSync(outPath).size;
452
- let pages = '?';
453
- try {
454
- const buf = readFileSync(outPath);
455
- const m = buf.toString('latin1').match(/\/Type\s*\/Page[^s]/g);
456
- if (m) pages = String(m.length);
457
- } catch {}
458
-
459
- console.log('');
460
- console.log(`PDF: ${outPath}`);
461
- console.log(`Pages: ${pages}`);
462
- console.log(`Size: ${human(size)}`);
463
- console.log(`Source: ${input} → ${htmlSource.startsWith('http') ? htmlSource : relative(process.cwd(), htmlSource)}`);
464
- })().catch((err) => { console.error('[brochure] error:', err.message); process.exit(1); });
1
+ #!/usr/bin/env node
2
+ /**
3
+ * rdc:brochure — zip/folder/html/url/markdown → PDF via Puppeteer.
4
+ * See skills/brochure/SKILL.md for the contract.
5
+ */
6
+ import { execSync, spawnSync } from 'node:child_process';
7
+ import { createHash } from 'node:crypto';
8
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, copyFileSync } from 'node:fs';
9
+ import { homedir, tmpdir } from 'node:os';
10
+ import { dirname, basename, extname, join, resolve, relative, sep } from 'node:path';
11
+ import { pathToFileURL, fileURLToPath } from 'node:url';
12
+ import { createRequire } from 'node:module';
13
+
14
+ const AUTO_FIT_CSS = `
15
+ /* rdc:brochure --auto-fit corrective stylesheet
16
+ Generic print-overflow safety net. Applied AFTER document stylesheets. */
17
+ @media print, screen {
18
+ html, body { overflow: visible !important; }
19
+ body { max-width: 100% !important; }
20
+ *, *::before, *::after { box-sizing: border-box; }
21
+
22
+ img, svg, video, canvas, iframe, object, embed {
23
+ max-width: 100% !important;
24
+ height: auto !important;
25
+ object-fit: contain;
26
+ }
27
+ figure, .figure, picture { break-inside: avoid; page-break-inside: avoid; max-width: 100%; }
28
+
29
+ table {
30
+ table-layout: fixed !important;
31
+ width: 100% !important;
32
+ max-width: 100% !important;
33
+ word-wrap: break-word;
34
+ overflow-wrap: anywhere;
35
+ border-collapse: collapse;
36
+ }
37
+ th, td { word-wrap: break-word; overflow-wrap: anywhere; max-width: 100%; }
38
+ thead { display: table-header-group; }
39
+ tr, td, th { break-inside: avoid; page-break-inside: avoid; }
40
+
41
+ pre, code, kbd, samp { white-space: pre-wrap !important; word-break: break-word; overflow-wrap: anywhere; max-width: 100%; }
42
+ pre { break-inside: avoid; page-break-inside: avoid; }
43
+
44
+ h1, h2, h3, h4, h5, h6 { break-after: avoid; page-break-after: avoid; }
45
+ h1 + *, h2 + *, h3 + *, h4 + * { break-before: avoid; }
46
+ p, li { orphans: 3; widows: 3; }
47
+
48
+ /* Generic wide-content sentinels */
49
+ .wide, .full-bleed, .panorama { max-width: 100% !important; }
50
+
51
+ /* Avoid blank-page artifacts from oversized flex/grid containers */
52
+ [style*="position: fixed"], [style*="position:fixed"] { position: static !important; }
53
+ }
54
+ `;
55
+
56
+ const HERE = dirname(fileURLToPath(import.meta.url));
57
+ const REPO_ROOT = resolve(HERE, '..');
58
+ const TEMPLATES_DIR = join(REPO_ROOT, 'scaffold', 'templates');
59
+
60
+ // --- args ------------------------------------------------------------------
61
+ const argv = process.argv.slice(2);
62
+ const opts = { template: 'studio-default', format: 'Letter', printEmulate: true, keepWorkdir: false, autoFit: false, scale: 1 };
63
+ let input;
64
+ for (let i = 0; i < argv.length; i++) {
65
+ const a = argv[i];
66
+ if (a === '--out') opts.out = argv[++i];
67
+ else if (a === '--template') opts.template = argv[++i];
68
+ else if (a === '--format') opts.format = argv[++i];
69
+ else if (a === '--margin') opts.margin = argv[++i];
70
+ else if (a === '--no-print-emulate') opts.printEmulate = false;
71
+ else if (a === '--keep-workdir') opts.keepWorkdir = true;
72
+ else if (a === '--auto-fit') opts.autoFit = true;
73
+ else if (a === '--scale') opts.scale = parseFloat(argv[++i]);
74
+ else if (!input) input = a;
75
+ }
76
+ if (!input) {
77
+ console.error('usage: rdc-brochure.mjs <zip|folder|html|md|url> [--out path] [--template name] [--format Letter|A4]');
78
+ process.exit(2);
79
+ }
80
+
81
+ // --- helpers ---------------------------------------------------------------
82
+ const isUrl = /^https?:\/\//i.test(input);
83
+ const hash = createHash('sha1').update(input).digest('hex').slice(0, 10);
84
+ const workRoot = join(tmpdir(), 'rdc-brochure', hash);
85
+ mkdirSync(workRoot, { recursive: true });
86
+
87
+ const log = (...a) => console.log('[brochure]', ...a);
88
+
89
+ function human(n) {
90
+ const u = ['B', 'KB', 'MB', 'GB'];
91
+ let i = 0;
92
+ while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
93
+ return `${n.toFixed(1)} ${u[i]}`;
94
+ }
95
+
96
+ function walk(dir) {
97
+ const out = [];
98
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
99
+ const p = join(dir, e.name);
100
+ if (e.isDirectory()) out.push(...walk(p));
101
+ else out.push(p);
102
+ }
103
+ return out;
104
+ }
105
+
106
+ // --- ensure puppeteer ------------------------------------------------------
107
+ async function loadPuppeteer() {
108
+ try { return (await import('puppeteer')).default; } catch {}
109
+ // Try a local cache install.
110
+ const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
111
+ mkdirSync(cacheDir, { recursive: true });
112
+ if (!existsSync(join(cacheDir, 'package.json'))) {
113
+ writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
114
+ }
115
+ if (!existsSync(join(cacheDir, 'node_modules', 'puppeteer'))) {
116
+ log('installing puppeteer into', cacheDir);
117
+ execSync('npm install puppeteer --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
118
+ }
119
+ const req = createRequire(join(cacheDir, 'package.json'));
120
+ const mod = req('puppeteer');
121
+ return mod.default || mod;
122
+ }
123
+
124
+ // --- cross-platform unzip --------------------------------------------------
125
+ // Pure-Node first (adm-zip — works on every platform, no external binary).
126
+ // If the lib cannot be resolved or installed, fall back to a platform-native
127
+ // extractor: `unzip` on POSIX, PowerShell `Expand-Archive` on win32.
128
+ function loadAdmZip() {
129
+ if (process.env.RDC_BROCHURE_DISABLE_ADM_ZIP === '1') return null;
130
+ try { return createRequire(import.meta.url)('adm-zip'); } catch {}
131
+ // Reuse the puppeteer on-demand cache dir for an isolated local install.
132
+ const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
133
+ mkdirSync(cacheDir, { recursive: true });
134
+ if (!existsSync(join(cacheDir, 'package.json'))) {
135
+ writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
136
+ }
137
+ if (!existsSync(join(cacheDir, 'node_modules', 'adm-zip'))) {
138
+ try {
139
+ log('installing adm-zip into', cacheDir);
140
+ execSync('npm install adm-zip --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
141
+ } catch { return null; }
142
+ }
143
+ try { return createRequire(join(cacheDir, 'package.json'))('adm-zip'); } catch { return null; }
144
+ }
145
+
146
+ // Reject any archive member that resolves outside destDir (zip-slip / path
147
+ // traversal). Returns the validated absolute destination path. Throws on escape.
148
+ function safeJoinOrThrow(destDir, entryName) {
149
+ const root = resolve(destDir);
150
+ const dest = resolve(root, entryName);
151
+ if (dest !== root && !dest.startsWith(root + sep)) {
152
+ throw new Error(`zip-slip: entry "${entryName}" escapes destination directory`);
153
+ }
154
+ return dest;
155
+ }
156
+
157
+ function extractZip(zipPath, destDir) {
158
+ mkdirSync(destDir, { recursive: true });
159
+ const root = resolve(destDir);
160
+ const AdmZip = loadAdmZip();
161
+ if (AdmZip) {
162
+ const zip = new AdmZip(zipPath);
163
+ const entries = zip.getEntries();
164
+ // First pass: validate every entry resolves inside destDir. A brochure
165
+ // source zip must never contain `..` or absolute members — reject the whole
166
+ // archive rather than silently skipping (fail-closed).
167
+ for (const entry of entries) {
168
+ safeJoinOrThrow(root, entry.entryName);
169
+ }
170
+ // Second pass: extract validated entries individually. Do NOT use the
171
+ // blanket extractAllTo adm-zip does not sanitize entry paths.
172
+ for (const entry of entries) {
173
+ if (entry.isDirectory) {
174
+ mkdirSync(safeJoinOrThrow(root, entry.entryName), { recursive: true });
175
+ continue;
176
+ }
177
+ const dest = safeJoinOrThrow(root, entry.entryName);
178
+ mkdirSync(dirname(dest), { recursive: true });
179
+ zip.extractEntryTo(entry, root, /* maintainEntryPath */ true, /* overwrite */ true);
180
+ }
181
+ return;
182
+ }
183
+ // Fallback: platform-native extractor. Validate members via a listing pass
184
+ // BEFORE extracting, since the bulk extract commands cannot apply per-entry
185
+ // guards. Reject any `..` segment or absolute/leading-slash member.
186
+ log('adm-zip unavailable — falling back to platform unzip');
187
+ assertNativeZipSafe(zipPath);
188
+ let r;
189
+ if (process.platform === 'win32') {
190
+ r = spawnSync('powershell', ['-NoProfile', '-Command',
191
+ `Expand-Archive -Path '${zipPath}' -DestinationPath '${destDir}' -Force`], { stdio: 'inherit' });
192
+ } else {
193
+ r = spawnSync('unzip', ['-o', '-q', zipPath, '-d', destDir], { stdio: 'inherit' });
194
+ }
195
+ if (!r || r.status !== 0) throw new Error('unzip failed (no pure-Node lib and platform extractor failed)');
196
+ }
197
+
198
+ // List archive members with a native tool and reject any traversal/absolute
199
+ // entry. Throws if a member is unsafe or the listing cannot be produced.
200
+ function assertNativeZipSafe(zipPath) {
201
+ let names = [];
202
+ if (process.platform === 'win32') {
203
+ const ps = spawnSync('powershell', ['-NoProfile', '-Command',
204
+ `Add-Type -AssemblyName System.IO.Compression.FileSystem; ` +
205
+ `[System.IO.Compression.ZipFile]::OpenRead('${zipPath}').Entries | ForEach-Object { $_.FullName }`],
206
+ { encoding: 'utf8' });
207
+ if (ps.status !== 0) throw new Error('cannot list zip members for traversal check (PowerShell)');
208
+ names = String(ps.stdout || '').split(/\r?\n/);
209
+ } else {
210
+ const zi = spawnSync('zipinfo', ['-1', zipPath], { encoding: 'utf8' });
211
+ if (zi.status === 0) {
212
+ names = String(zi.stdout || '').split(/\r?\n/);
213
+ } else {
214
+ const ul = spawnSync('unzip', ['-Z1', zipPath], { encoding: 'utf8' });
215
+ if (ul.status !== 0) throw new Error('cannot list zip members for traversal check (unzip -Z1)');
216
+ names = String(ul.stdout || '').split(/\r?\n/);
217
+ }
218
+ }
219
+ for (const raw of names) {
220
+ const name = raw.trim();
221
+ if (!name) continue;
222
+ const norm = name.replace(/\\/g, '/');
223
+ if (norm.startsWith('/') || /^[A-Za-z]:/.test(norm) || norm.split('/').some((seg) => seg === '..')) {
224
+ throw new Error(`zip-slip: entry "${name}" escapes destination directory`);
225
+ }
226
+ }
227
+ }
228
+
229
+ // --- stage input -----------------------------------------------------------
230
+ function stageInput() {
231
+ const stageDir = join(workRoot, 'src');
232
+ mkdirSync(stageDir, { recursive: true });
233
+ if (isUrl) return { kind: 'url', url: input, stageDir };
234
+ const abs = resolve(input);
235
+ if (!existsSync(abs)) throw new Error(`not found: ${abs}`);
236
+ const st = statSync(abs);
237
+ if (st.isDirectory()) return { kind: 'folder', root: abs, stageDir: abs };
238
+ const ext = extname(abs).toLowerCase();
239
+ if (ext === '.zip') {
240
+ log('extracting zip to', stageDir);
241
+ extractZip(abs, stageDir);
242
+ return { kind: 'folder', root: stageDir, stageDir };
243
+ }
244
+ if (ext === '.html' || ext === '.htm') return { kind: 'html', file: abs, stageDir: dirname(abs) };
245
+ if (ext === '.md' || ext === '.markdown') return { kind: 'md', file: abs, stageDir: dirname(abs) };
246
+ throw new Error(`unsupported input: ${ext || '(no extension)'}`);
247
+ }
248
+
249
+ // --- pick HTML in render mode ----------------------------------------------
250
+ function pickHtml(rootDir) {
251
+ const htmls = walk(rootDir).filter((p) => /\.html?$/i.test(p));
252
+ if (!htmls.length) return null;
253
+ const scored = htmls.map((p) => {
254
+ const text = readFileSync(p, 'utf8');
255
+ const size = statSync(p).size;
256
+ let score = 0;
257
+ if (/@page\b/.test(text)) score += 1000;
258
+ if (/@media\s+print/i.test(text)) score += 500;
259
+ if (/-print\.html?$/i.test(p)) score += 300;
260
+ if (/brochure\.html?$/i.test(p)) score += 250;
261
+ if (/(^|[\\/])print\.html?$/i.test(p)) score += 250;
262
+ if (/standalone/i.test(basename(p))) score -= 50; // usually huge embedded duplicate
263
+ score += Math.min(size / 1024, 200); // size as tiebreaker, capped
264
+ return { p, score, size };
265
+ }).sort((a, b) => b.score - a.score);
266
+ return scored[0].p;
267
+ }
268
+
269
+ // --- compose mode ----------------------------------------------------------
270
+ function listTemplates() {
271
+ if (!existsSync(TEMPLATES_DIR)) return [];
272
+ return readdirSync(TEMPLATES_DIR)
273
+ .map((f) => /^brochure-(.+)\.html$/i.exec(f))
274
+ .filter(Boolean)
275
+ .map((m) => m[1])
276
+ .sort();
277
+ }
278
+
279
+ function stripLeadingYamlFrontMatter(md) {
280
+ const text = md.replace(/\r\n/g, '\n');
281
+ if (!text.startsWith('---\n')) return text;
282
+ const lines = text.split('\n');
283
+ for (let i = 1; i < lines.length; i++) {
284
+ if (/^---\s*$/.test(lines[i])) return lines.slice(i + 1).join('\n');
285
+ }
286
+ return text;
287
+ }
288
+
289
+ async function composeFromFolder(root, file) {
290
+ const tpl = join(TEMPLATES_DIR, `brochure-${opts.template}.html`);
291
+ if (!existsSync(tpl)) {
292
+ const available = listTemplates();
293
+ const list = available.length ? available.join(', ') : '(none found)';
294
+ throw new Error(`unknown template "${opts.template}". Available template(s): ${list}`);
295
+ }
296
+ let html = readFileSync(tpl, 'utf8');
297
+
298
+ let mdFiles = [];
299
+ if (file) mdFiles = [file];
300
+ else mdFiles = walk(root).filter((p) => /\.(md|markdown)$/i.test(p)).sort();
301
+
302
+ const title = (() => {
303
+ for (const p of mdFiles) {
304
+ const m = readFileSync(p, 'utf8').match(/^#\s+(.+)$/m);
305
+ if (m) return m[1].trim();
306
+ }
307
+ return basename(file || root);
308
+ })();
309
+
310
+ const sections = mdFiles.map((p) => {
311
+ const md = readFileSync(p, 'utf8');
312
+ const bodyMd = stripLeadingYamlFrontMatter(md);
313
+ // Only prepend the filename heading when the markdown has no leading ATX heading
314
+ // of its own. Avoids a redundant <h2>filename</h2> stacked above a "# Title".
315
+ const firstNonEmpty = bodyMd.replace(/\r\n/g, '\n').split('\n').find((l) => l.trim() !== '') || '';
316
+ const hasLeadingHeading = /^#{1,6}\s+\S/.test(firstNonEmpty.trim());
317
+ const heading = hasLeadingHeading ? '' : `<h2>${escapeHtml(basename(p, extname(p)))}</h2>`;
318
+ return `<section class="brochure-section">${heading}${mdToHtml(bodyMd, dirname(p))}</section>`;
319
+ }).join('\n');
320
+
321
+ html = html.replace(/\{\{TITLE\}\}/g, escapeHtml(title)).replace(/\{\{SECTIONS\}\}/g, sections);
322
+
323
+ const tokensCss = findSibling(root || dirname(file), 'tokens.css');
324
+ if (tokensCss) html = html.replace('/* TOKENS_INJECT */', readFileSync(tokensCss, 'utf8'));
325
+
326
+ const outHtml = join(workRoot, 'composed.html');
327
+ writeFileSync(outHtml, html);
328
+ return outHtml;
329
+ }
330
+
331
+ function findSibling(dir, name) {
332
+ if (!dir) return null;
333
+ const p = join(dir, name);
334
+ return existsSync(p) ? p : null;
335
+ }
336
+
337
+ function escapeHtml(s) {
338
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
339
+ }
340
+
341
+ // Minimal markdown — headings, paragraphs, lists, bold/italic, inline code, fenced code, images.
342
+ function mdToHtml(md, baseDir) {
343
+ let out = md.replace(/\r\n/g, '\n');
344
+ out = out.replace(/```([a-z]*)\n([\s\S]*?)```/g, (_, lang, body) => `<pre><code class="lang-${escapeHtml(lang)}">${escapeHtml(body)}</code></pre>`);
345
+ out = out.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_, alt, src) => `<img alt="${escapeHtml(alt)}" src="${resolveImg(src, baseDir)}"/>`);
346
+ out = out.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>')
347
+ .replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>')
348
+ .replace(/^####\s+(.+)$/gm, '<h4>$1</h4>')
349
+ .replace(/^###\s+(.+)$/gm, '<h3>$1</h3>')
350
+ .replace(/^##\s+(.+)$/gm, '<h2>$1</h2>')
351
+ .replace(/^#\s+(.+)$/gm, '<h1>$1</h1>');
352
+ out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/\*([^*]+)\*/g, '<em>$1</em>').replace(/`([^`]+)`/g, '<code>$1</code>');
353
+ out = out.replace(/(?:^|\n)((?:[-*]\s+.+\n?)+)/g, (_, block) => `\n<ul>${block.trim().split(/\n/).map((l) => `<li>${l.replace(/^[-*]\s+/, '')}</li>`).join('')}</ul>\n`);
354
+ out = out.split(/\n{2,}/).map((b) => /^<(h\d|ul|ol|pre|img|section|div)/.test(b.trim()) ? b : `<p>${b.trim()}</p>`).join('\n');
355
+ return out;
356
+ }
357
+
358
+ function resolveImg(src, baseDir) {
359
+ if (/^https?:|^data:/.test(src)) return src;
360
+ const p = resolve(baseDir, src);
361
+ if (!existsSync(p)) return src;
362
+ return pathToFileURL(p).href;
363
+ }
364
+
365
+ // --- render ----------------------------------------------------------------
366
+ async function render(htmlSource) {
367
+ const puppeteer = await loadPuppeteer();
368
+ const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox', '--font-render-hinting=none'] });
369
+ try {
370
+ const page = await browser.newPage();
371
+ page.on('pageerror', (e) => log('pageerror:', e.message));
372
+ const url = htmlSource.startsWith('http') ? htmlSource : pathToFileURL(htmlSource).href;
373
+ log('loading', url);
374
+ await page.goto(url, { waitUntil: 'networkidle0', timeout: 180_000 });
375
+ await page.evaluateHandle('document.fonts.ready');
376
+ await new Promise((r) => setTimeout(r, 1500));
377
+ if (opts.printEmulate) await page.emulateMediaType('print');
378
+
379
+ if (opts.autoFit) {
380
+ await page.addStyleTag({ content: AUTO_FIT_CSS });
381
+ const report = await page.evaluate(() => {
382
+ const issues = [];
383
+ const all = document.body.querySelectorAll('*');
384
+ const pageWidthPx = document.documentElement.clientWidth;
385
+ for (const el of all) {
386
+ const r = el.getBoundingClientRect();
387
+ if (r.width > pageWidthPx + 4) {
388
+ issues.push({ tag: el.tagName, cls: el.className?.toString().slice(0, 60) || '', width: Math.round(r.width), pageWidth: pageWidthPx });
389
+ if (issues.length >= 25) break;
390
+ }
391
+ }
392
+ return issues;
393
+ });
394
+ if (report.length) {
395
+ log(`auto-fit: ${report.length} overflow element(s) detected — corrective CSS applied`);
396
+ for (const r of report.slice(0, 8)) log(` · ${r.tag}${r.cls ? '.' + r.cls : ''} width=${r.width}px (page=${r.pageWidth}px)`);
397
+ } else {
398
+ log('auto-fit: no overflow detected after corrective CSS');
399
+ }
400
+ await new Promise((r) => setTimeout(r, 400));
401
+ }
402
+
403
+ const outPath = resolve(opts.out || defaultOutPath());
404
+ mkdirSync(dirname(outPath), { recursive: true });
405
+
406
+ const pdfOpts = {
407
+ path: outPath,
408
+ format: opts.format,
409
+ printBackground: true,
410
+ preferCSSPageSize: true,
411
+ displayHeaderFooter: false,
412
+ scale: opts.scale && opts.scale !== 1 ? opts.scale : undefined,
413
+ };
414
+ if (opts.margin) {
415
+ const m = opts.margin;
416
+ pdfOpts.margin = { top: m, bottom: m, left: m, right: m };
417
+ pdfOpts.preferCSSPageSize = false;
418
+ } else if (!htmlSource.startsWith('http')) {
419
+ const text = readFileSync(htmlSource, 'utf8');
420
+ if (!/@page\b/.test(text)) {
421
+ pdfOpts.margin = { top: '0.6in', bottom: '0.6in', left: '0.7in', right: '0.7in' };
422
+ pdfOpts.preferCSSPageSize = false;
423
+ }
424
+ }
425
+
426
+ await page.pdf(pdfOpts);
427
+ return outPath;
428
+ } finally {
429
+ await browser.close();
430
+ }
431
+ }
432
+
433
+ function defaultOutPath() {
434
+ if (isUrl) return resolve('brochure.pdf');
435
+ const abs = resolve(input);
436
+ const base = basename(abs, extname(abs));
437
+ return resolve(dirname(abs), `${base}.pdf`);
438
+ }
439
+
440
+ // --- main ------------------------------------------------------------------
441
+ (async () => {
442
+ const staged = stageInput();
443
+ let htmlSource;
444
+
445
+ if (staged.kind === 'url') {
446
+ htmlSource = staged.url;
447
+ } else if (staged.kind === 'html') {
448
+ htmlSource = staged.file;
449
+ } else if (staged.kind === 'md') {
450
+ htmlSource = await composeFromFolder(null, staged.file);
451
+ } else { // folder
452
+ const picked = pickHtml(staged.stageDir);
453
+ if (picked) {
454
+ log('picked html:', relative(staged.stageDir, picked));
455
+ htmlSource = picked;
456
+ } else {
457
+ log('no html found — composing from markdown');
458
+ htmlSource = await composeFromFolder(staged.stageDir);
459
+ }
460
+ }
461
+
462
+ if (process.env.RDC_BROCHURE_COMPOSE_ONLY === '1') {
463
+ console.log(`HTML: ${htmlSource}`);
464
+ console.log(`Source: ${input} → ${htmlSource.startsWith('http') ? htmlSource : relative(process.cwd(), htmlSource)}`);
465
+ return;
466
+ }
467
+
468
+ const outPath = await render(htmlSource);
469
+ const size = statSync(outPath).size;
470
+ let pages = '?';
471
+ try {
472
+ const buf = readFileSync(outPath);
473
+ const m = buf.toString('latin1').match(/\/Type\s*\/Page[^s]/g);
474
+ if (m) pages = String(m.length);
475
+ } catch {}
476
+
477
+ console.log('');
478
+ console.log(`PDF: ${outPath}`);
479
+ console.log(`Pages: ${pages}`);
480
+ console.log(`Size: ${human(size)}`);
481
+ console.log(`Source: ${input} → ${htmlSource.startsWith('http') ? htmlSource : relative(process.cwd(), htmlSource)}`);
482
+ })().catch((err) => { console.error('[brochure] error:', err.message); process.exit(1); });