@frcloudsolutions/agent-skills 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -2
  3. package/bin/agent-skills.mjs +8 -0
  4. package/package.json +42 -4
  5. package/plugins/docs-generator/skills/docs-generator/SKILL.md +68 -0
  6. package/plugins/docs-generator/skills/docs-generator/assets/README.md +8 -0
  7. package/plugins/docs-generator/skills/docs-generator/assets/fonts/OFL.txt +93 -0
  8. package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-Bold.ttf +0 -0
  9. package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-BoldItalic.ttf +0 -0
  10. package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-Italic.ttf +0 -0
  11. package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-Regular.ttf +0 -0
  12. package/plugins/docs-generator/skills/docs-generator/assets/paged.polyfill.min.js +4 -0
  13. package/plugins/docs-generator/skills/docs-generator/locales/en.json +14 -0
  14. package/plugins/docs-generator/skills/docs-generator/locales/es.json +14 -0
  15. package/plugins/docs-generator/skills/docs-generator/locales/pt-BR.json +14 -0
  16. package/plugins/docs-generator/skills/docs-generator/package-lock.json +1697 -0
  17. package/plugins/docs-generator/skills/docs-generator/package.json +28 -0
  18. package/plugins/docs-generator/skills/docs-generator/references/from-design-system.md +48 -0
  19. package/plugins/docs-generator/skills/docs-generator/references/source-format.md +96 -0
  20. package/plugins/docs-generator/skills/docs-generator/references/theme-format.md +77 -0
  21. package/plugins/docs-generator/skills/docs-generator/references/writing-guide.md +39 -0
  22. package/plugins/docs-generator/skills/docs-generator/scripts/docs.mjs +226 -0
  23. package/plugins/docs-generator/skills/docs-generator/scripts/lib/docx.mjs +377 -0
  24. package/plugins/docs-generator/skills/docs-generator/scripts/lib/html.mjs +273 -0
  25. package/plugins/docs-generator/skills/docs-generator/scripts/lib/images.mjs +25 -0
  26. package/plugins/docs-generator/skills/docs-generator/scripts/lib/office.mjs +184 -0
  27. package/plugins/docs-generator/skills/docs-generator/scripts/lib/pdf.mjs +70 -0
  28. package/plugins/docs-generator/skills/docs-generator/scripts/lib/source.mjs +270 -0
  29. package/plugins/docs-generator/skills/docs-generator/scripts/lib/theme.mjs +219 -0
  30. package/plugins/docs-generator/skills/docs-generator/themes/clean-modern.json +36 -0
  31. package/plugins/docs-generator/skills/docs-generator/themes/docs-theme.schema.json +119 -0
  32. package/src/cli/main.mjs +222 -0
  33. package/src/cli/prompt.mjs +142 -0
  34. package/src/lib/catalog.mjs +28 -0
  35. package/src/lib/frontmatter.mjs +23 -0
  36. package/src/lib/install.mjs +67 -0
  37. package/src/lib/tools.mjs +77 -0
  38. package/src/lib/validate.mjs +86 -0
@@ -0,0 +1,377 @@
1
+ // Renders the document model as a native Word document with real styles.
2
+ import { readFileSync } from "node:fs";
3
+ import {
4
+ AlignmentType, Bookmark, BorderStyle, Document, ExternalHyperlink, Footer, HeadingLevel, HeightRule, ImageRun, InternalHyperlink,
5
+ LevelFormat, Packer, PageNumber, Paragraph, SectionType, ShadingType, Table, TableCell, TableOfContents, TableRow,
6
+ TabStopType, TextRun, VerticalAlign, WidthType,
7
+ } from "docx";
8
+ import { estimatePageNumbers } from "docx/layout";
9
+ import { fontFaces, officeAccents, officeFont } from "./theme.mjs";
10
+ import { imageSize } from "./images.mjs";
11
+
12
+ const PAGE = { A4: { width: 11906, height: 16838 }, Letter: { width: 12240, height: 15840 } };
13
+ const mm = (v) => Math.round((v / 25.4) * 1440); // millimetres → twips
14
+ const pt = (v) => Math.round(v * 20); // points → twips
15
+ const half = (v) => Math.round(v * 2); // points → half-points
16
+ const hex = (c) => c.replace("#", "").toUpperCase();
17
+ const NONE = { style: BorderStyle.NONE, size: 0, color: "auto" };
18
+
19
+ /** Builds the DOCX and returns it as a Buffer. */
20
+ export async function renderDocx(model, theme) {
21
+ const m = model, t = theme, c = t.colors, ty = t.type, L = m.labels;
22
+ const page = PAGE[t.page.size];
23
+ const mg = t.page.margins;
24
+ const textWidth = page.width - mm(mg.left) - mm(mg.right); // twips
25
+ const textWidthPx = Math.floor((textWidth / 1440) * 96);
26
+ const headingFont = officeFont(t.fonts.heading), bodyFont = officeFont(t.fonts.body), monoFont = officeFont(t.fonts.mono);
27
+ let olInstance = 0;
28
+
29
+ // ---- inline content --------------------------------------------------------------------
30
+ const runs = (nodes = [], fmt = {}) =>
31
+ nodes.flatMap((n) => {
32
+ switch (n.type) {
33
+ case "text": return [new TextRun({ text: n.value, bold: fmt.bold, italics: fmt.italic, style: fmt.link ? "Hyperlink" : undefined })];
34
+ case "strong": return runs(n.children, { ...fmt, bold: true });
35
+ case "emphasis": return runs(n.children, { ...fmt, italic: true });
36
+ case "inlineCode": return [new TextRun({ text: n.value, font: monoFont, size: half(ty.body - 1), bold: fmt.bold })];
37
+ case "break": return [new TextRun({ text: "", break: 1 })];
38
+ case "link":
39
+ if (n.url.startsWith("#")) return [new InternalHyperlink({ anchor: bookmarkName(n.url.slice(1)), children: runs(n.children, { ...fmt, link: true }) })];
40
+ return [new ExternalHyperlink({ link: n.url, children: runs(n.children, { ...fmt, link: true }) })];
41
+ case "image": return [image(n, Math.min(textWidthPx, n.width))];
42
+ default: return runs(n.children, fmt);
43
+ }
44
+ });
45
+
46
+ function image(n, maxWidth) {
47
+ const scale = Math.min(1, maxWidth / n.width, 680 / n.height);
48
+ return new ImageRun({
49
+ type: n.format,
50
+ data: readFileSync(n.path),
51
+ transformation: { width: Math.round(n.width * scale), height: Math.round(n.height * scale) },
52
+ altText: { name: n.alt || "image", description: n.alt || "", title: n.alt || "" },
53
+ });
54
+ }
55
+
56
+ // ---- blocks ----------------------------------------------------------------------------
57
+ const HEADINGS = { 1: HeadingLevel.HEADING_1, 2: HeadingLevel.HEADING_2, 3: HeadingLevel.HEADING_3 };
58
+
59
+ function blocks(list, ctx = {}) {
60
+ return list.flatMap((n, i) => block(n, { ...ctx, first: i === 0 }));
61
+ }
62
+
63
+ function block(n, ctx) {
64
+ switch (n.type) {
65
+ case "heading":
66
+ {
67
+ // Bookmarked with the heading's id, so internal links (#s-…) work as in the PDF
68
+ const children = [new Bookmark({ id: bookmarkName(n.id), children: runs(n.children) })];
69
+ if (ctx.annex) return [new Paragraph({ style: `AnnexHeading${n.depth}`, children })];
70
+ return [new Paragraph({ heading: HEADINGS[n.depth], pageBreakBefore: ctx.first && ctx.breakFirst, children })];
71
+ }
72
+ case "paragraph":
73
+ if (n.children.length === 1 && n.children[0].type === "image") {
74
+ const img = n.children[0];
75
+ const out = [new Paragraph({ keepNext: Boolean(img.alt), children: [image(img, textWidthPx)] })];
76
+ if (img.alt) out.push(new Paragraph({ style: "Caption", children: [new TextRun(img.alt)] }));
77
+ return out;
78
+ }
79
+ return [new Paragraph({ style: ctx.style, children: runs(n.children) })];
80
+ case "list":
81
+ return list(n, 0);
82
+ case "blockquote":
83
+ return blocks(n.children, { ...ctx, style: "Quote", first: false });
84
+ case "code":
85
+ return [new Paragraph({ style: "Code", children: n.value.split("\n").map((line, i) => new TextRun({ text: line, break: i ? 1 : 0 })) })];
86
+ case "table":
87
+ return [table(n.children.map((r) => r.children.map((cell) => cell.children)), n.align), spacer()];
88
+ default:
89
+ return [];
90
+ }
91
+ }
92
+
93
+ function list(n, level) {
94
+ const instance = n.ordered ? ++olInstance : 0;
95
+ const out = [];
96
+ for (const li of n.children) {
97
+ li.children.forEach((child, j) => {
98
+ if (child.type === "list") out.push(...list(child, level + 1));
99
+ else if (child.type === "paragraph" && j === 0)
100
+ out.push(new Paragraph({
101
+ style: "ListParagraph",
102
+ numbering: n.ordered ? { reference: "ol", level, instance } : { reference: "ul", level },
103
+ children: runs(child.children),
104
+ }));
105
+ else out.push(...block(child, {}));
106
+ });
107
+ }
108
+ return out;
109
+ }
110
+
111
+ const spacer = () => new Paragraph({ spacing: { before: 0, after: pt(ty.paragraphSpacing) }, children: [] });
112
+
113
+ /**
114
+ * Table with a header row, thin horizontal rules and no vertical lines.
115
+ * @param rows rows of cells; each cell is a list of Markdown inline nodes
116
+ */
117
+ function table(rows, align = [], widths) {
118
+ const cellMargins = { top: pt(4), bottom: pt(4), left: pt(6), right: pt(6) };
119
+ const alignOf = (i) => ({ right: AlignmentType.RIGHT, center: AlignmentType.CENTER })[align[i]] ?? AlignmentType.LEFT;
120
+ return new Table({
121
+ width: { size: 100, type: WidthType.PERCENTAGE },
122
+ columnWidths: widths,
123
+ borders: {
124
+ top: NONE, left: NONE, right: NONE, insideVertical: NONE,
125
+ bottom: { style: BorderStyle.SINGLE, size: 4, color: hex(c.border) },
126
+ insideHorizontal: { style: BorderStyle.SINGLE, size: 4, color: hex(c.border) },
127
+ },
128
+ rows: rows.map((cells, r) =>
129
+ new TableRow({
130
+ tableHeader: r === 0,
131
+ cantSplit: true,
132
+ children: cells.map((children, i) =>
133
+ new TableCell({
134
+ margins: cellMargins,
135
+ verticalAlign: r === 0 ? VerticalAlign.BOTTOM : VerticalAlign.TOP,
136
+ shading: r === 0 ? { type: ShadingType.CLEAR, fill: hex(c.tableHeader), color: "auto" } : undefined,
137
+ borders: r === 0 ? { bottom: { style: BorderStyle.SINGLE, size: 8, color: hex(c.text) } } : undefined,
138
+ children: [new Paragraph({
139
+ style: "TableText",
140
+ alignment: alignOf(i),
141
+ children: runs(children, { bold: r === 0 }),
142
+ })],
143
+ }),
144
+ ),
145
+ }),
146
+ ),
147
+ });
148
+ }
149
+
150
+ const partTitle = (text, { pageBreak = true } = {}) => new Paragraph({ heading: HeadingLevel.HEADING_1, pageBreakBefore: pageBreak, children: [new TextRun(text)] });
151
+
152
+ // ---- parts -----------------------------------------------------------------------------
153
+ const coverBand = new Table({
154
+ width: { size: 100, type: WidthType.PERCENTAGE },
155
+ borders: { top: NONE, bottom: NONE, left: NONE, right: NONE, insideHorizontal: NONE, insideVertical: NONE },
156
+ rows: [
157
+ new TableRow({
158
+ height: { value: mm(140), rule: HeightRule.ATLEAST },
159
+ children: [
160
+ new TableCell({
161
+ verticalAlign: VerticalAlign.BOTTOM,
162
+ margins: { left: mm(mg.left), right: mm(mg.right), top: mm(20), bottom: mm(18) },
163
+ shading: t.cover.style === "accent-band" ? { type: ShadingType.CLEAR, fill: hex(c.accent), color: "auto" } : undefined,
164
+ children: [
165
+ ...(t.cover.logo ? [new Paragraph({ spacing: { after: mm(14) }, children: [logo(t.cover.logo)] })] : []),
166
+ new Paragraph({ style: "Title", children: [new TextRun(m.meta.title)] }),
167
+ ...(m.meta.subtitle ? [new Paragraph({ style: "Subtitle", children: [new TextRun(m.meta.subtitle)] })] : []),
168
+ ],
169
+ }),
170
+ ],
171
+ }),
172
+ ],
173
+ });
174
+
175
+ function logo(path) {
176
+ const buf = readFileSync(path);
177
+ const s = imageSize(buf);
178
+ const h = 68; // ~18 mm at 96 dpi
179
+ return new ImageRun({ type: s.format, data: buf, transformation: { width: Math.round((s.width / s.height) * h), height: h }, altText: { name: "logo", description: "", title: "" } });
180
+ }
181
+
182
+ const metaCell = (label, lines) =>
183
+ new TableCell({
184
+ margins: { left: 0, right: mm(10), top: 0, bottom: 0 },
185
+ children: [
186
+ new Paragraph({ style: "CoverLabel", children: [new TextRun(label.toUpperCase())] }),
187
+ ...lines.map((l) => new Paragraph({ style: "CoverValue", children: [new TextRun(l)] })),
188
+ ],
189
+ });
190
+ const coverMeta = new Table({
191
+ indent: { size: mm(mg.left), type: WidthType.DXA },
192
+ borders: { top: NONE, bottom: NONE, left: NONE, right: NONE, insideHorizontal: NONE, insideVertical: NONE },
193
+ rows: [new TableRow({ children: [metaCell(L.author, m.meta.authors), metaCell(L.date, [m.meta.dateText]), metaCell(L.version, [m.meta.version])] })],
194
+ });
195
+
196
+ const tocPart = [
197
+ new Paragraph({ style: "TOCHeading", children: [new TextRun(L.toc)] }),
198
+ new TableOfContents(L.toc, { hyperlink: true, headingStyleRange: "1-2", tabLeader: "none" }),
199
+ ];
200
+
201
+ const summaryPart = [partTitle(L.summary), ...blocks(m.summary)];
202
+ const bodyPart = blocks(m.body, { breakFirst: true });
203
+
204
+ const sourcesInstance = ++olInstance; // one numbered list for all sources
205
+ const sourcesPart = m.sources.length
206
+ ? [
207
+ partTitle(L.sources),
208
+ ...m.sources.map((s) => {
209
+ const children = [];
210
+ if (s.author) children.push(new TextRun(`${s.author}. `));
211
+ children.push(new TextRun({ text: s.title, italics: true }), new TextRun(". "));
212
+ if (s.date) children.push(new TextRun(`${s.dateText ?? s.date}. `));
213
+ if (s.url) children.push(new ExternalHyperlink({ link: s.url, children: [new TextRun({ text: s.url, style: "Hyperlink" })] }), new TextRun(" "));
214
+ if (s.accessed) children.push(new TextRun(`${L.accessed} ${s.accessedText ?? s.accessed}.`));
215
+ return new Paragraph({ style: "ListParagraph", numbering: { reference: "ol", level: 0, instance: sourcesInstance }, children });
216
+ }),
217
+ ]
218
+ : [];
219
+
220
+ const annexPart = m.annexes.flatMap((a) => [partTitle(`${L.annex} ${a.letter} — ${a.title}`), ...blocks(a.blocks, { annex: true })]);
221
+
222
+ const changesPart = [
223
+ partTitle(L.changes),
224
+ table(
225
+ [
226
+ [L.version, L.date, L.author, L.description].map(textNode),
227
+ ...m.changes.map((ch) => [ch.version, ch.dateText, ch.author ?? "", ch.description].map(textNode)),
228
+ ],
229
+ [],
230
+ [12, 26, 18, 44].map((p) => Math.round((textWidth * p) / 100)),
231
+ ),
232
+ ];
233
+
234
+ // Back cover: an accent band at the top of the page; the text sits in the footer, so it stays at the
235
+ // bottom of the page however Word lays out the rest.
236
+ const backBand = t.cover.style === "accent-band"
237
+ ? [new Table({
238
+ width: { size: 100, type: WidthType.PERCENTAGE },
239
+ borders: { top: NONE, bottom: NONE, left: NONE, right: NONE, insideHorizontal: NONE, insideVertical: NONE },
240
+ rows: [new TableRow({ height: { value: mm(8), rule: HeightRule.EXACT }, children: [new TableCell({ shading: { type: ShadingType.CLEAR, fill: hex(c.accent), color: "auto" }, children: [new Paragraph({ children: [] })] })] })],
241
+ })]
242
+ : [];
243
+ const sideIndent = { left: mm(mg.left), right: mm(mg.right) };
244
+ const backFooter = new Footer({
245
+ children: [
246
+ new Paragraph({ style: "BackTitle", indent: sideIndent, children: [new TextRun(m.meta.title)] }),
247
+ new Paragraph({ style: "BackDetail", indent: sideIndent, children: [new TextRun(`${L.version} ${m.meta.version} · ${m.meta.dateText}`)] }),
248
+ ...(t.backCover.contact ? [new Paragraph({ style: "BackDetail", indent: sideIndent, children: [new TextRun(t.backCover.contact)] })] : []),
249
+ ...(t.backCover.license ? [new Paragraph({ style: "BackDetail", indent: sideIndent, children: [new TextRun(t.backCover.license)] })] : []),
250
+ ],
251
+ });
252
+
253
+ // ---- styles ----------------------------------------------------------------------------
254
+ const heading = (size, color, before, after) => ({
255
+ run: { font: headingFont, size: half(size), bold: true, color: hex(color) },
256
+ paragraph: { spacing: { before: pt(before), after: pt(after), line: 240 }, keepNext: true, keepLines: true },
257
+ });
258
+ const styles = {
259
+ default: {
260
+ document: {
261
+ run: { font: bodyFont, size: half(ty.body), color: hex(c.text) },
262
+ paragraph: { spacing: { after: pt(ty.paragraphSpacing), line: Math.round(240 * ty.lineHeight) } },
263
+ },
264
+ heading1: heading(ty.h1, c.accent, ty.h1 * 1.2, ty.h1 * 0.5),
265
+ heading2: heading(ty.h2, c.text, ty.h2 * 1.4, ty.h2 * 0.4),
266
+ heading3: heading(ty.h3, c.text, ty.h3 * 1.4, ty.h3 * 0.3),
267
+ title: { run: { font: headingFont, size: half(ty.title), bold: true, color: hex(t.cover.style === "accent-band" ? c.onAccent : c.accent) }, paragraph: { spacing: { after: pt(10), line: 264 } } },
268
+ hyperlink: { run: { color: hex(c.accent), underline: { type: "single", color: hex(c.accent) } } },
269
+ listParagraph: { paragraph: { spacing: { after: pt(ty.paragraphSpacing / 2) } } },
270
+ },
271
+ paragraphStyles: [
272
+ { id: "Subtitle", name: "Subtitle", basedOn: "Normal", run: { size: half(ty.h2), color: hex(t.cover.style === "accent-band" ? c.onAccent : c.text) }, paragraph: { spacing: { after: 0, line: 312 } } },
273
+ { id: "AnnexHeading2", name: "Annex Heading 2", basedOn: "Normal", next: "Normal", ...heading(ty.h2, c.text, ty.h2 * 1.4, ty.h2 * 0.4) },
274
+ { id: "AnnexHeading3", name: "Annex Heading 3", basedOn: "Normal", next: "Normal", ...heading(ty.h3, c.text, ty.h3 * 1.4, ty.h3 * 0.3) },
275
+ { id: "TOCHeading", name: "TOC Heading", basedOn: "Normal", next: "Normal", ...heading(ty.h1, c.accent, 0, ty.h1 * 0.5) },
276
+ { id: "TOC1", name: "toc 1", basedOn: "Normal", next: "Normal", run: { bold: true }, paragraph: { spacing: { before: pt(8), after: pt(3) } } },
277
+ { id: "TOC2", name: "toc 2", basedOn: "Normal", next: "Normal", paragraph: { indent: { left: pt(14) }, spacing: { after: pt(3) } } },
278
+ { id: "Code", name: "Code", basedOn: "Normal", run: { font: monoFont, size: half(ty.small) }, paragraph: { spacing: { line: 252, after: pt(ty.paragraphSpacing) }, shading: { type: ShadingType.CLEAR, fill: hex(c.tableHeader), color: "auto" }, indent: { left: pt(6), right: pt(6) }, keepLines: true } },
279
+ { id: "Quote", name: "Quote", basedOn: "Normal", paragraph: { indent: { left: pt(12) }, border: { left: { style: BorderStyle.SINGLE, size: 20, color: hex(c.accent), space: 9 } } } },
280
+ { id: "Caption", name: "caption", basedOn: "Normal", run: { size: half(ty.small), color: hex(c.textMuted) }, paragraph: { spacing: { before: pt(4), after: pt(ty.paragraphSpacing * 1.5) } } },
281
+ { id: "TableText", name: "Table Text", basedOn: "Normal", run: { size: half(Math.max(ty.small, ty.body - 1)) }, paragraph: { spacing: { after: 0, line: 264 } } },
282
+ { id: "FooterText", name: "Footer Text", basedOn: "Normal", run: { size: half(ty.small), color: hex(c.textMuted) }, paragraph: { spacing: { after: 0 } } },
283
+ { id: "CoverLabel", name: "Cover Label", basedOn: "Normal", run: { size: half(ty.small), color: hex(c.textMuted), characterSpacing: 16 }, paragraph: { spacing: { after: pt(3) } } },
284
+ { id: "CoverValue", name: "Cover Value", basedOn: "Normal", paragraph: { spacing: { after: 0 } } },
285
+ { id: "BackTitle", name: "Back Cover Title", basedOn: "Normal", run: { font: headingFont, size: half(ty.h2), bold: true }, paragraph: { spacing: { after: pt(4) } } },
286
+ { id: "BackDetail", name: "Back Cover Detail", basedOn: "Normal", run: { size: half(ty.small), color: hex(c.textMuted) }, paragraph: { spacing: { after: pt(4) } } },
287
+ ],
288
+ };
289
+
290
+ const level = (lvl, format, text) => ({
291
+ level: lvl, format, text, alignment: AlignmentType.START,
292
+ style: { paragraph: { indent: { left: pt(18 + lvl * 18), hanging: pt(14) } } },
293
+ });
294
+ const numbering = {
295
+ config: [
296
+ { reference: "ol", levels: [0, 1, 2].map((l) => level(l, [LevelFormat.DECIMAL, LevelFormat.LOWER_LETTER, LevelFormat.LOWER_ROMAN][l], `%${l + 1}.`)) },
297
+ { reference: "ul", levels: [0, 1, 2].map((l) => level(l, LevelFormat.BULLET, ["•", "–", "·"][l])) },
298
+ ],
299
+ };
300
+
301
+ // ---- fonts and theme -------------------------------------------------------------------
302
+ // Word embeds TrueType/OpenType files only; WOFF/WOFF2 faces (fine for the PDF) are left out.
303
+ const fonts = [];
304
+ const embeddable = (p) => (p && /\.(ttf|otf)$/i.test(p) ? p : undefined);
305
+ for (const family of new Set([t.fonts.heading, t.fonts.body])) {
306
+ const faces = fontFaces(t, family);
307
+ const f = Object.fromEntries(Object.entries(faces).map(([k, p]) => [k, embeddable(p)]));
308
+ if (!f.regular) continue;
309
+ fonts.push({
310
+ name: family,
311
+ data: readFileSync(f.regular),
312
+ ...(f.bold && { bold: readFileSync(f.bold) }),
313
+ ...(f.italic && { italic: readFileSync(f.italic) }),
314
+ ...(f.boldItalic && { boldItalic: readFileSync(f.boldItalic) }),
315
+ });
316
+ }
317
+ const accents = officeAccents(t).map(hex);
318
+
319
+ // ---- sections --------------------------------------------------------------------------
320
+ const pageProps = (margins, footerDistance = mm(14)) => ({ size: page, margin: { ...margins, header: mm(12), footer: footerDistance } });
321
+ // Covers: no side or top margin (the bands reach the page edges); their text is in the footer, bottom-anchored
322
+ // at the same height as in the PDF.
323
+ const coverMargins = { top: 0, right: 0, bottom: mm(80), left: 0 };
324
+ const coverFooterDistance = mm(mg.bottom + 10);
325
+ const bodyMargins = { top: mm(mg.top), right: mm(mg.right), bottom: mm(mg.bottom), left: mm(mg.left) };
326
+ const footer = new Footer({
327
+ children: [
328
+ new Paragraph({
329
+ style: "FooterText",
330
+ tabStops: [{ type: TabStopType.RIGHT, position: textWidth }],
331
+ children: [new TextRun(m.meta.title), new TextRun({ children: ["\t", PageNumber.CURRENT] })],
332
+ }),
333
+ ],
334
+ });
335
+
336
+ const doc = new Document({
337
+ creator: m.meta.authors.join(", "),
338
+ title: m.meta.title,
339
+ description: m.meta.subtitle ?? "",
340
+ styles,
341
+ numbering,
342
+ fonts,
343
+ theme: {
344
+ name: t.name,
345
+ colors: {
346
+ dark1: hex(c.text), light1: hex(c.background), dark2: hex(c.textMuted), light2: hex(c.tableHeader),
347
+ accent1: hex(c.accent), accent2: accents[0], accent3: accents[1], accent4: accents[2], accent5: accents[3], accent6: accents[4],
348
+ hyperlink: hex(c.accent), followedHyperlink: hex(c.textMuted),
349
+ },
350
+ fonts: { headings: headingFont, body: bodyFont },
351
+ },
352
+ pageNumbers: estimatePageNumbers,
353
+ sections: [
354
+ {
355
+ properties: { page: pageProps(coverMargins, coverFooterDistance) },
356
+ footers: { default: new Footer({ children: [coverMeta] }) },
357
+ children: [coverBand, new Paragraph({ children: [] })],
358
+ },
359
+ {
360
+ properties: { type: SectionType.NEXT_PAGE, page: pageProps(bodyMargins) },
361
+ footers: { default: footer },
362
+ children: [...tocPart, ...summaryPart, ...bodyPart, ...sourcesPart, ...annexPart, ...changesPart],
363
+ },
364
+ {
365
+ properties: { type: SectionType.NEXT_PAGE, page: pageProps(coverMargins, coverFooterDistance) },
366
+ footers: { default: backFooter },
367
+ children: [...backBand, new Paragraph({ children: [] })],
368
+ },
369
+ ],
370
+ });
371
+ return Packer.toBuffer(doc);
372
+ }
373
+
374
+ const textNode = (value) => [{ type: "text", value: String(value) }];
375
+
376
+ /** Word bookmark names: letters, digits and underscores, at most 40 characters. */
377
+ export const bookmarkName = (id) => id.replace(/[^A-Za-z0-9_]/g, "_").slice(0, 40);
@@ -0,0 +1,273 @@
1
+ // Renders the document model as one HTML page with print CSS for Paged.js.
2
+ import { pathToFileURL } from "node:url";
3
+ import { fontFaces } from "./theme.mjs";
4
+
5
+ const esc = (s = "") => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
6
+ const fileUrl = (p) => pathToFileURL(p).href;
7
+
8
+ // ---- inline and block nodes ----------------------------------------------------------------
9
+
10
+ function inline(nodes = []) {
11
+ return nodes
12
+ .map((n) => {
13
+ switch (n.type) {
14
+ case "text": return esc(n.value);
15
+ case "strong": return `<strong>${inline(n.children)}</strong>`;
16
+ case "emphasis": return `<em>${inline(n.children)}</em>`;
17
+ case "inlineCode": return `<code>${esc(n.value)}</code>`;
18
+ case "break": return "<br>";
19
+ case "link": return `<a href="${esc(n.url)}">${inline(n.children)}</a>`;
20
+ case "image": return `<img src="${fileUrl(n.path)}" alt="${esc(n.alt)}">`;
21
+ default: return inline(n.children);
22
+ }
23
+ })
24
+ .join("");
25
+ }
26
+
27
+ function block(n) {
28
+ switch (n.type) {
29
+ case "heading":
30
+ return `<h${n.depth} id="${n.id}">${inline(n.children)}</h${n.depth}>`;
31
+ case "paragraph": {
32
+ // A paragraph that holds only an image becomes a figure with its alt text as caption
33
+ if (n.children.length === 1 && n.children[0].type === "image") {
34
+ const img = n.children[0];
35
+ return `<figure><img src="${fileUrl(img.path)}" alt="${esc(img.alt)}">${img.alt ? `<figcaption>${esc(img.alt)}</figcaption>` : ""}</figure>`;
36
+ }
37
+ return `<p>${inline(n.children)}</p>`;
38
+ }
39
+ case "list": {
40
+ const tag = n.ordered ? "ol" : "ul";
41
+ const start = n.ordered && n.start && n.start !== 1 ? ` start="${n.start}"` : "";
42
+ return `<${tag}${start}>${n.children.map((li) => `<li>${li.children.map((c) => (c.type === "paragraph" ? inline(c.children) : block(c))).join("")}</li>`).join("")}</${tag}>`;
43
+ }
44
+ case "blockquote":
45
+ return `<blockquote>${n.children.map(block).join("")}</blockquote>`;
46
+ case "code":
47
+ return `<pre><code>${esc(n.value)}</code></pre>`;
48
+ case "table": {
49
+ const align = (i) => (n.align?.[i] ? ` style="text-align:${n.align[i]}"` : "");
50
+ const [head, ...rows] = n.children;
51
+ const cells = (row, tag) => row.children.map((c, i) => `<${tag}${align(i)}>${inline(c.children)}</${tag}>`).join("");
52
+ return `<table><thead><tr>${cells(head, "th")}</tr></thead><tbody>${rows.map((r) => `<tr>${cells(r, "td")}</tr>`).join("")}</tbody></table>`;
53
+ }
54
+ default:
55
+ return "";
56
+ }
57
+ }
58
+
59
+ const blocks = (list) => list.map(block).join("\n");
60
+
61
+ // ---- parts --------------------------------------------------------------------------------
62
+
63
+ function cover(m, t) {
64
+ const L = m.labels;
65
+ const logo = t.cover.logo ? `<img class="cover-logo" src="${fileUrl(t.cover.logo)}" alt="">` : "";
66
+ return `
67
+ <section class="cover ${t.cover.style}" id="cover">
68
+ <div class="cover-head">
69
+ ${logo}
70
+ <h1 class="cover-title">${esc(m.meta.title)}</h1>
71
+ ${m.meta.subtitle ? `<p class="cover-subtitle">${esc(m.meta.subtitle)}</p>` : ""}
72
+ </div>
73
+ <dl class="cover-meta">
74
+ <div><dt>${esc(L.author)}</dt><dd>${m.meta.authors.map(esc).join("<br>")}</dd></div>
75
+ <div><dt>${esc(L.date)}</dt><dd>${esc(m.meta.dateText)}</dd></div>
76
+ <div><dt>${esc(L.version)}</dt><dd>${esc(m.meta.version)}</dd></div>
77
+ </dl>
78
+ </section>`;
79
+ }
80
+
81
+ function toc(m) {
82
+ const items = m.toc.map((e) => `<li class="toc-l${e.level}"><a href="#${e.id}"><span>${esc(e.text)}</span></a></li>`).join("\n");
83
+ return `<nav class="part toc" id="toc"><h1 class="part-title">${esc(m.labels.toc)}</h1><ol>${items}</ol></nav>`;
84
+ }
85
+
86
+ function sources(m) {
87
+ if (!m.sources.length) return "";
88
+ const L = m.labels;
89
+ const items = m.sources
90
+ .map((s) => {
91
+ const parts = [];
92
+ if (s.author) parts.push(esc(s.author));
93
+ parts.push(`<cite>${esc(s.title)}</cite>`);
94
+ if (s.date) parts.push(esc(s.dateText ?? s.date));
95
+ let line = parts.join(". ") + ".";
96
+ if (s.url) line += ` <a href="${esc(s.url)}">${esc(s.url)}</a>`;
97
+ if (s.accessed) line += ` ${esc(L.accessed)} ${esc(s.accessedText ?? s.accessed)}.`;
98
+ return `<li>${line}</li>`;
99
+ })
100
+ .join("\n");
101
+ return `<section class="part" id="sources"><h1 class="part-title">${esc(L.sources)}</h1><ol class="sources">${items}</ol></section>`;
102
+ }
103
+
104
+ function annexes(m) {
105
+ return m.annexes
106
+ .map(
107
+ (a) =>
108
+ `<section class="part annex" id="${a.id}"><h1 class="part-title">${esc(`${m.labels.annex} ${a.letter} — ${a.title}`)}</h1>\n${blocks(a.blocks)}</section>`,
109
+ )
110
+ .join("\n");
111
+ }
112
+
113
+ function changes(m) {
114
+ const L = m.labels;
115
+ const rows = m.changes
116
+ .map((c) => `<tr><td>${esc(c.version)}</td><td>${esc(c.dateText)}</td><td>${esc(c.author ?? "")}</td><td>${esc(c.description)}</td></tr>`)
117
+ .join("");
118
+ return `<section class="part" id="changes"><h1 class="part-title">${esc(L.changes)}</h1>
119
+ <table class="changes"><thead><tr><th>${esc(L.version)}</th><th>${esc(L.date)}</th><th>${esc(L.author)}</th><th>${esc(L.description)}</th></tr></thead><tbody>${rows}</tbody></table></section>`;
120
+ }
121
+
122
+ function backCover(m, t) {
123
+ return `<section class="back-cover" id="back-cover">
124
+ <p class="back-title">${esc(m.meta.title)}</p>
125
+ <p class="back-version">${esc(m.labels.version)} ${esc(m.meta.version)} · ${esc(m.meta.dateText)}</p>
126
+ ${t.backCover.contact ? `<p class="back-contact">${esc(t.backCover.contact)}</p>` : ""}
127
+ ${t.backCover.license ? `<p class="back-license">${esc(t.backCover.license)}</p>` : ""}
128
+ </section>`;
129
+ }
130
+
131
+ // ---- CSS ----------------------------------------------------------------------------------
132
+
133
+ function fontFaceCss(theme) {
134
+ const out = [];
135
+ const seen = new Set();
136
+ for (const family of [theme.fonts.heading, theme.fonts.body, theme.fonts.mono]) {
137
+ if (seen.has(family)) continue;
138
+ seen.add(family);
139
+ const faces = fontFaces(theme, family);
140
+ const add = (path, weight, style) =>
141
+ path && out.push(`@font-face { font-family: "${family}"; src: url("${fileUrl(path)}"); font-weight: ${weight}; font-style: ${style}; }`);
142
+ add(faces.regular, 400, "normal");
143
+ add(faces.bold, 700, "normal");
144
+ add(faces.italic, 400, "italic");
145
+ add(faces.boldItalic, 700, "italic");
146
+ }
147
+ return out.join("\n");
148
+ }
149
+
150
+ const family = (name) => (["sans-serif", "serif", "monospace"].includes(name) ? name : `"${name}", sans-serif`);
151
+
152
+ export function css(theme) {
153
+ const c = theme.colors, ty = theme.type, mg = theme.page.margins;
154
+ const mono = theme.fonts.mono === "monospace" ? `ui-monospace, "Cascadia Mono", Consolas, "DejaVu Sans Mono", monospace` : family(theme.fonts.mono);
155
+ return `
156
+ ${fontFaceCss(theme)}
157
+
158
+ @page {
159
+ size: ${theme.page.size};
160
+ margin: ${mg.top}mm ${mg.right}mm ${mg.bottom}mm ${mg.left}mm;
161
+ @bottom-left { content: string(doctitle); font-family: ${family(theme.fonts.body)}; font-size: ${ty.small}pt; color: ${c.textMuted}; vertical-align: top; padding-top: 6mm; }
162
+ @bottom-right { content: counter(page); font-family: ${family(theme.fonts.body)}; font-size: ${ty.small}pt; color: ${c.textMuted}; vertical-align: top; padding-top: 6mm; font-variant-numeric: tabular-nums; }
163
+ }
164
+ @page cover { margin: 0; @bottom-left { content: none; } @bottom-right { content: none; } }
165
+ @page back { margin: 0; @bottom-left { content: none; } @bottom-right { content: none; } }
166
+
167
+ html { font-family: ${family(theme.fonts.body)}; font-size: ${ty.body}pt; line-height: ${ty.lineHeight}; color: ${c.text}; background: ${c.background}; }
168
+ body { margin: 0; widows: 2; orphans: 2; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
169
+ p, ul, ol, dl, blockquote, pre, table, figure { margin: 0 0 ${ty.paragraphSpacing}pt; }
170
+ h1, h2, h3, .part-title { font-family: ${family(theme.fonts.heading)}; font-weight: 700; line-height: 1.2; break-after: avoid; break-inside: avoid; }
171
+ h1, .part-title { font-size: ${ty.h1}pt; color: ${c.accent}; margin: ${ty.h1 * 1.2}pt 0 ${ty.h1 * 0.5}pt; }
172
+ h2 { font-size: ${ty.h2}pt; margin: ${ty.h2 * 1.4}pt 0 ${ty.h2 * 0.4}pt; }
173
+ h3 { font-size: ${ty.h3}pt; margin: ${ty.h3 * 1.4}pt 0 ${ty.h3 * 0.3}pt; }
174
+ .part-title { margin-top: 0; }
175
+ ul, ol { padding-left: 1.4em; }
176
+ li { margin-bottom: ${ty.paragraphSpacing / 2}pt; }
177
+ li > ul, li > ol { margin-top: ${ty.paragraphSpacing / 2}pt; }
178
+ a { color: ${c.accent}; text-decoration: underline; text-decoration-thickness: 0.5pt; text-underline-offset: 1.5pt; }
179
+ strong { font-weight: 700; }
180
+ code { font-family: ${mono}; font-size: 0.9em; }
181
+ pre { background: ${c.tableHeader}; padding: 8pt 10pt; border-radius: 3pt; white-space: pre-wrap; break-inside: avoid; }
182
+ pre code { font-size: ${ty.small}pt; line-height: 1.45; }
183
+ blockquote { margin-left: 0; padding: 2pt 0 2pt 12pt; border-left: 2.5pt solid ${c.accent}; color: ${c.text}; }
184
+ blockquote p:last-child { margin-bottom: 0; }
185
+ figure { margin-left: 0; margin-right: 0; break-inside: avoid; }
186
+ figure img { max-width: 100%; max-height: 180mm; display: block; }
187
+ figcaption { font-size: ${ty.small}pt; color: ${c.textMuted}; margin-top: 4pt; }
188
+ img { max-width: 100%; }
189
+
190
+ table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums lining-nums; font-size: ${Math.max(ty.small, ty.body - 1)}pt; line-height: 1.35; }
191
+ thead { display: table-header-group; }
192
+ tr { break-inside: avoid; }
193
+ th { text-align: left; font-weight: 700; background: ${c.tableHeader}; border-bottom: 1pt solid ${c.text}; padding: 5pt 8pt; vertical-align: bottom; }
194
+ td { border-bottom: 0.5pt solid ${c.border}; padding: 5pt 8pt; vertical-align: top; }
195
+ table.changes td:nth-child(1), table.changes td:nth-child(2) { white-space: nowrap; }
196
+
197
+ .part { break-before: page; }
198
+ main.body > h1:first-child { margin-top: 0; }
199
+
200
+ /* Cover */
201
+ .cover { page: cover; height: ${theme.page.size === "A4" ? "296mm" : "278.4mm"}; display: flex; flex-direction: column; justify-content: space-between; box-sizing: border-box; }
202
+ .cover-head { padding: 60mm ${mg.right}mm 18mm ${mg.left}mm; }
203
+ .cover.accent-band .cover-head { background: ${c.accent}; color: ${c.onAccent}; }
204
+ .cover-title { string-set: doctitle content(text); font-family: ${family(theme.fonts.heading)}; font-size: ${ty.title}pt; line-height: 1.1; font-weight: 700; margin: 0 0 10pt; max-width: 150mm; color: inherit; }
205
+ .cover.plain .cover-title { color: ${c.accent}; }
206
+ .cover-subtitle { font-size: ${ty.h2}pt; line-height: 1.3; margin: 0; max-width: 150mm; }
207
+ .cover-logo { max-height: 18mm; max-width: 60mm; display: block; margin-bottom: 14mm; }
208
+ .cover-meta { display: flex; gap: 14mm; padding: 0 ${mg.right}mm ${mg.bottom + 10}mm ${mg.left}mm; margin: 0; font-size: ${ty.body}pt; }
209
+ .cover-meta dt { font-size: ${ty.small}pt; color: ${c.textMuted}; text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 3pt; }
210
+ .cover-meta dd { margin: 0; }
211
+
212
+ /* Table of contents */
213
+ .toc ol { list-style: none; padding: 0; margin: 0; }
214
+ .toc li { margin: 0; }
215
+ .toc a { display: flex; gap: 8pt; color: ${c.text}; text-decoration: none; padding: 3pt 0; }
216
+ .toc a::after { content: target-counter(attr(href), page); margin-left: auto; font-variant-numeric: tabular-nums; color: ${c.textMuted}; }
217
+ .toc .toc-l1 a { font-weight: 700; padding-top: 8pt; }
218
+ .toc .toc-l2 a { padding-left: 14pt; }
219
+
220
+ /* Sources */
221
+ ol.sources li { margin-bottom: ${ty.paragraphSpacing}pt; }
222
+ ol.sources a { overflow-wrap: anywhere; }
223
+
224
+ /* Back cover */
225
+ .back-cover { page: back; break-before: page; height: ${theme.page.size === "A4" ? "296mm" : "278.4mm"}; box-sizing: border-box; padding: 0 ${mg.right}mm ${mg.bottom + 10}mm ${mg.left}mm; display: flex; flex-direction: column; justify-content: flex-end; border-top: ${theme.cover.style === "accent-band" ? `8mm solid ${c.accent}` : "none"}; }
226
+ .back-cover p { margin: 0 0 4pt; }
227
+ .back-title { font-family: ${family(theme.fonts.heading)}; font-weight: 700; font-size: ${ty.h2}pt; color: ${c.text}; }
228
+ .back-version, .back-contact, .back-license { font-size: ${ty.small}pt; color: ${c.textMuted}; }
229
+ `;
230
+ }
231
+
232
+ export function renderHtml(model, theme, { pagedScript }) {
233
+ const m = model;
234
+ return `<!doctype html>
235
+ <html lang="${m.meta.lang}">
236
+ <head>
237
+ <meta charset="utf-8">
238
+ <title>${esc(m.meta.title)}</title>
239
+ <meta name="author" content="${esc(m.meta.authors.join(", "))}">
240
+ <style>${css(theme)}</style>
241
+ <script>window.PagedConfig = { auto: true, after: () => { window.__pagedDone = true; } };</script>
242
+ <script src="${fileUrl(pagedScript)}"></script>
243
+ <script>
244
+ // Repeat a table's header row on every page the table continues on (Paged.js does not).
245
+ class RepeatTableHeaders extends Paged.Handler {
246
+ afterPageLayout(pageElement, page, breakToken, chunker) {
247
+ for (const table of pageElement.querySelectorAll("table[data-split-from]")) {
248
+ if (table.querySelector("thead")) continue;
249
+ const original = chunker.source.querySelector('[data-ref="' + table.dataset.splitFrom + '"]');
250
+ const thead = original && original.querySelector("thead");
251
+ if (thead) table.insertBefore(thead.cloneNode(true), table.firstChild);
252
+ }
253
+ }
254
+ }
255
+ Paged.registerHandlers(RepeatTableHeaders);
256
+ </script>
257
+ </head>
258
+ <body>
259
+ ${cover(m, theme)}
260
+ ${toc(m)}
261
+ <section class="part" id="summary"><h1 class="part-title">${esc(m.labels.summary)}</h1>
262
+ ${blocks(m.summary)}</section>
263
+ <main class="part body">
264
+ ${blocks(m.body)}
265
+ </main>
266
+ ${sources(m)}
267
+ ${annexes(m)}
268
+ ${changes(m)}
269
+ ${backCover(m, theme)}
270
+ </body>
271
+ </html>`;
272
+ }
273
+