@lifeaitools/rdc-skills 0.24.41 → 0.25.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.
Files changed (198) hide show
  1. package/.claude/settings.json +15 -15
  2. package/.claude-plugin/marketplace.json +21 -21
  3. package/.claude-plugin/plugin.json +1518 -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 +375 -376
  10. package/README.sandbox.md +3 -3
  11. package/assets/watcher/viewer.html +164 -164
  12. package/bin/rdc-skills-mcp.mjs +316 -316
  13. package/commands/build.md +183 -183
  14. package/commands/collab.md +180 -180
  15. package/commands/deploy.md +152 -152
  16. package/commands/design.md +31 -31
  17. package/commands/edit.md +28 -28
  18. package/commands/fixit.md +150 -124
  19. package/commands/handoff.md +173 -173
  20. package/commands/help.md +95 -95
  21. package/commands/overnight.md +220 -220
  22. package/commands/plan.md +158 -158
  23. package/commands/preplan.md +131 -131
  24. package/commands/prototype.md +145 -145
  25. package/commands/release.md +49 -49
  26. package/commands/report.md +99 -99
  27. package/commands/review.md +120 -120
  28. package/commands/self-test.md +113 -113
  29. package/commands/status.md +86 -86
  30. package/commands/watch.md +98 -98
  31. package/commands/workitems.md +137 -137
  32. package/git-sha.json +1 -1
  33. package/guides/agent-bootstrap.md +295 -295
  34. package/guides/agents/backend.md +104 -104
  35. package/guides/agents/content.md +94 -94
  36. package/guides/agents/cs2.md +56 -56
  37. package/guides/agents/data.md +87 -87
  38. package/guides/agents/design.md +77 -77
  39. package/guides/agents/frontend.md +92 -92
  40. package/guides/agents/infrastructure.md +81 -81
  41. package/guides/agents/setup.md +281 -281
  42. package/guides/agents/verify.md +151 -151
  43. package/guides/agents/viz.md +106 -106
  44. package/guides/backend.md +146 -146
  45. package/guides/content.md +147 -147
  46. package/guides/cs2.md +190 -190
  47. package/guides/data.md +123 -123
  48. package/guides/design.md +116 -116
  49. package/guides/engineering-behavior.md +43 -43
  50. package/guides/escalation-protocol.md +125 -125
  51. package/guides/frontend.md +151 -151
  52. package/guides/history-md-spec.md +297 -297
  53. package/guides/infrastructure.md +179 -179
  54. package/guides/lessons-learned-spec.md +145 -151
  55. package/guides/output-contract.md +108 -108
  56. package/guides/publish-md-spec.md +289 -289
  57. package/guides/rdc-skills-startup.md +30 -30
  58. package/guides/verify.md +11 -11
  59. package/hooks/check-cwd.js +31 -31
  60. package/hooks/check-rdc-environment.js +164 -164
  61. package/hooks/check-services.js +6 -6
  62. package/hooks/check-stale-work-items.js +19 -19
  63. package/hooks/foreground-process-gate.js +128 -128
  64. package/hooks/gate-watchdog-selfcheck.js +257 -257
  65. package/hooks/hook-logger.js +25 -25
  66. package/hooks/lib/run-evidence-gate.mjs +241 -241
  67. package/hooks/no-stop-open-epics.js +127 -127
  68. package/hooks/post-tool-batch-gate.js +203 -203
  69. package/hooks/post-work-check.js +21 -21
  70. package/hooks/postcompact-log.js +13 -13
  71. package/hooks/precompact-log.js +13 -13
  72. package/hooks/rate-limit-retry.js +46 -46
  73. package/hooks/rdc-invocation-marker.js +157 -157
  74. package/hooks/rdc-output-contract-gate.js +94 -94
  75. package/hooks/require-work-item-on-commit.js +294 -294
  76. package/hooks/restart-brief.js +19 -19
  77. package/hooks/run-hidden-hook.ps1 +47 -47
  78. package/hooks/task-completed-gate.js +274 -274
  79. package/hooks/work-item-exit-gate.js +944 -944
  80. package/lib/catalog.mjs +236 -236
  81. package/lib/cloud-rewrite.mjs +155 -155
  82. package/package.json +57 -57
  83. package/rules/work-items-rpc.md +520 -520
  84. package/scaffold/templates/HISTORY.md.template +39 -39
  85. package/scaffold/templates/PUBLISH.md.template +21 -21
  86. package/scaffold/templates/brochure-studio-default.html +70 -70
  87. package/scripts/acceptance.mjs +502 -502
  88. package/scripts/fixtures/guides/bad-guide.md +15 -15
  89. package/scripts/fixtures/guides-clean/good-guide.md +16 -16
  90. package/scripts/install-rdc-skills.js +1289 -1289
  91. package/scripts/install.ps1 +202 -202
  92. package/scripts/install.sh +132 -132
  93. package/scripts/lib/assertions.mjs +287 -287
  94. package/scripts/lib/manifest-schema.mjs +754 -754
  95. package/scripts/lib/runner.mjs +465 -465
  96. package/scripts/lib/sandbox.mjs +435 -435
  97. package/scripts/prepack.mjs +32 -32
  98. package/scripts/rdc-brochure.mjs +482 -482
  99. package/scripts/rdc-design-cli.mjs +134 -134
  100. package/scripts/rebuild-mcp.mjs +107 -107
  101. package/scripts/self-test.mjs +1460 -1460
  102. package/scripts/stamp-git-sha.mjs +29 -29
  103. package/scripts/test-guide-validator.mjs +196 -196
  104. package/scripts/test-rdc-hooks.mjs +145 -145
  105. package/scripts/uninstall.ps1 +77 -77
  106. package/scripts/uninstall.sh +69 -69
  107. package/scripts/update.ps1 +43 -43
  108. package/scripts/update.sh +43 -43
  109. package/scripts/validate-place-histories.js +461 -461
  110. package/scripts/validate-publish-manifests.js +502 -424
  111. package/scripts/watch-init.mjs +100 -100
  112. package/skills/brochure/SKILL.md +107 -107
  113. package/skills/build/SKILL.md +563 -563
  114. package/skills/channel-formatter/SKILL.md +538 -533
  115. package/skills/co-develop/SKILL.md +196 -196
  116. package/skills/collab/SKILL.md +239 -239
  117. package/skills/convert/SKILL.md +167 -140
  118. package/skills/deploy/SKILL.md +541 -541
  119. package/skills/design/SKILL.md +211 -211
  120. package/skills/design/reference/ownership.md +16 -16
  121. package/skills/design/reference/rampa.md +92 -92
  122. package/skills/design/reference/studio-model.md +153 -153
  123. package/skills/edit/SKILL.md +98 -98
  124. package/skills/fixit/SKILL.md +203 -165
  125. package/skills/fs-mcp/SKILL.md +148 -148
  126. package/skills/handoff/SKILL.md +236 -236
  127. package/skills/help/SKILL.md +143 -143
  128. package/skills/housekeeping/SKILL.md +160 -219
  129. package/skills/lifeai-brochure-author/SKILL.md +340 -340
  130. package/skills/onramp/SKILL.md +248 -0
  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/onramp.test.json +87 -0
  148. package/skills/tests/rdc-brochure.test.json +34 -34
  149. package/skills/tests/rdc-build.test.json +36 -36
  150. package/skills/tests/rdc-channel-formatter.test.json +45 -45
  151. package/skills/tests/rdc-co-develop.test.json +29 -29
  152. package/skills/tests/rdc-collab.test.json +29 -29
  153. package/skills/tests/rdc-convert.test.json +35 -35
  154. package/skills/tests/rdc-deploy.test.json +30 -30
  155. package/skills/tests/rdc-design.test.json +27 -27
  156. package/skills/tests/rdc-edit.test.json +29 -29
  157. package/skills/tests/rdc-fixit.test.json +36 -36
  158. package/skills/tests/rdc-fs-mcp.test.json +36 -36
  159. package/skills/tests/rdc-handoff.test.json +28 -28
  160. package/skills/tests/rdc-help.test.json +29 -29
  161. package/skills/tests/rdc-housekeeping.test.json +28 -32
  162. package/skills/tests/rdc-lifeai-brochure-author.test.json +35 -35
  163. package/skills/tests/rdc-overnight.test.json +37 -37
  164. package/skills/tests/rdc-plan.test.json +27 -27
  165. package/skills/tests/rdc-preplan.test.json +31 -31
  166. package/skills/tests/rdc-prototype.test.json +28 -28
  167. package/skills/tests/rdc-rdc-brochurify.test.json +23 -23
  168. package/skills/tests/rdc-rdc-extract-verifier-rules.test.json +34 -34
  169. package/skills/tests/rdc-release.test.json +29 -29
  170. package/skills/tests/rdc-report.test.json +28 -28
  171. package/skills/tests/rdc-review.test.json +29 -29
  172. package/skills/tests/rdc-rpms-filemap.test.json +28 -28
  173. package/skills/tests/rdc-self-test.test.json +24 -24
  174. package/skills/tests/rdc-status.test.json +29 -29
  175. package/skills/tests/rdc-terminal-config.test.json +29 -29
  176. package/skills/tests/rdc-watch.test.json +24 -24
  177. package/skills/tests/rdc-workitems.test.json +27 -27
  178. package/skills/watch/SKILL.md +97 -97
  179. package/skills/workitems/SKILL.md +151 -151
  180. package/tests/acceptance.test.mjs +59 -59
  181. package/tests/channel-formatter.contract.test.mjs +251 -251
  182. package/tests/curl-surface.test.mjs +289 -289
  183. package/tests/harness-gates.test.mjs +325 -325
  184. package/tests/help-surface.test.mjs +61 -61
  185. package/tests/install-rdc-skills.test.mjs +49 -49
  186. package/tests/manifest-contract-fields.test.mjs +78 -78
  187. package/tests/mcp.test.mjs +271 -271
  188. package/tests/rdc-brochure.test.mjs +125 -125
  189. package/tests/require-work-item-on-commit.test.mjs +162 -162
  190. package/tests/run-evidence-gate.test.mjs +82 -82
  191. package/tests/skill-test-matrix.test.mjs +66 -66
  192. package/tests/validate-skills.js +27 -27
  193. package/tests/work-item-exit-gate-l2.test.mjs +368 -368
  194. package/tests/work-item-exit-gate-l3.test.mjs +197 -197
  195. package/RELEASE.md +0 -42
  196. package/tests/housekeeping-lessons-triage.test.mjs +0 -49
  197. package/tests/lessons-pipeline-contract.test.mjs +0 -26
  198. package/tests/release-contract.test.mjs +0 -16
@@ -1,482 +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
- 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); });
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); });