@rse/specbook 0.9.6 → 0.9.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -10
- package/dst/specbook-api.js +19 -18
- package/dst/specbook-cli.js +9 -6
- package/dst/specbook-cmd-describe.js +1 -3
- package/dst/specbook-cmd-export.js +19 -16
- package/dst/specbook-cmd-init.d.ts +1 -1
- package/dst/specbook-cmd-init.js +5 -4
- package/dst/specbook-cmd-lint.d.ts +0 -1
- package/dst/specbook-cmd-lint.js +29 -5
- package/dst/specbook-config.d.ts +1 -1
- package/dst/specbook-config.js +80 -71
- package/dst/specbook-diagnostic.js +4 -1
- package/dst/specbook-diagram.d.ts +3 -2
- package/dst/specbook-diagram.js +75 -91
- package/dst/specbook-export-ast.d.ts +1 -1
- package/dst/specbook-export-ast.js +1 -1
- package/dst/specbook-export-common.d.ts +2 -1
- package/dst/specbook-export-common.js +12 -14
- package/dst/specbook-export-html-search.js +10 -14
- package/dst/specbook-export-html.css +24 -29
- package/dst/specbook-export-html.js +100 -83
- package/dst/specbook-export-md.d.ts +1 -1
- package/dst/specbook-export-md.js +50 -24
- package/dst/specbook-export-pdf.d.ts +4 -2
- package/dst/specbook-export-pdf.js +48 -38
- package/dst/specbook-format-schema.js +6 -3
- package/dst/specbook-format.md +34 -18
- package/dst/specbook-link.d.ts +1 -0
- package/dst/specbook-link.js +7 -4
- package/dst/specbook-mcp.js +17 -10
- package/dst/specbook-parse-common.d.ts +1 -1
- package/dst/specbook-parse-semantic.d.ts +4 -2
- package/dst/specbook-parse-semantic.js +95 -42
- package/dst/specbook-parse-syntax.js +163 -136
- package/dst/specbook-parse-value.d.ts +1 -1
- package/dst/specbook-parse-value.js +6 -3
- package/dst/specbook-parse.d.ts +2 -5
- package/dst/specbook-parse.js +27 -34
- package/dst/specbook-verbose.js +2 -1
- package/package.json +1 -1
|
@@ -9,10 +9,11 @@ import nunjucks from "nunjucks";
|
|
|
9
9
|
import nunjucksAddons from "@rse/nunjucks-addons";
|
|
10
10
|
import textframe from "textframe";
|
|
11
11
|
import { Gradia } from "@rse/gradia";
|
|
12
|
-
import { buildLinkIndex, resolveUnique, expandReferences, anchorPaths } from "./specbook-link.js";
|
|
12
|
+
import { buildLinkIndex, resolveUnique, expandReferences, anchorPaths, plainText } from "./specbook-link.js";
|
|
13
13
|
import { compileValueExpr, splitItems } from "./specbook-parse-value.js";
|
|
14
14
|
import { embeddingRegex, embeddingMimeType, embeddingThemes, embeddingVariants } from "./specbook-parse-common.js";
|
|
15
15
|
import { escapeHtml, stylesheet, searchScript, fallbackLogo, isTitleObject, titleObject, documentTitle, documentLang, documentThemeStyle } from "./specbook-export-common.js";
|
|
16
|
+
import { collectSchemas } from "./specbook-parse-semantic.js";
|
|
16
17
|
import { specDiagrams } from "./specbook-diagram.js";
|
|
17
18
|
/* ==== Templates ==== */
|
|
18
19
|
/* the built-in Nunjucks templates for the HTML export */
|
|
@@ -117,7 +118,7 @@ const templates = {
|
|
|
117
118
|
{%- if Description.block %}
|
|
118
119
|
<div class="description">{{ Description.description }}{% if Description.rationale %}
|
|
119
120
|
<p class="rationale">— <span class="keyword">BECAUSE</span> {{ Description.rationale }}</p>{% endif %}</div>
|
|
120
|
-
{%-
|
|
121
|
+
{%- elif Description.description or Description.rationale %}
|
|
121
122
|
<p class="description">{{ Description.description }}{% if Description.rationale %}
|
|
122
123
|
<span class="rationale">— <span class="keyword">BECAUSE</span> {{ Description.rationale }}</span>{% endif %}</p>
|
|
123
124
|
{%- endif %}
|
|
@@ -209,6 +210,18 @@ const marked = new Marked();
|
|
|
209
210
|
marked.use({ hooks: { postprocess: (html) => html.replace(/“/g, quotes[0]).replace(/”/g, quotes[1])
|
|
210
211
|
.replace(/&(?![a-zA-Z][a-zA-Z0-9]*;|#\d+;|#x[0-9a-fA-F]+;)/g, "&") } });
|
|
211
212
|
marked.use(markedSmartypants({ config: 1 }));
|
|
213
|
+
/* the switched-off text escaping of marked also leaves the angle
|
|
214
|
+
brackets of the inline text unescaped, which a browser then takes
|
|
215
|
+
for tags ("Map<String, Object>"), so they are escaped upfront in
|
|
216
|
+
the inline text tokenizer (registered after smartypants, as the
|
|
217
|
+
later-registered tokenizer takes precedence) */
|
|
218
|
+
marked.use({ tokenizer: { inlineText(src) {
|
|
219
|
+
const cap = this.rules.inline.text.exec(src);
|
|
220
|
+
if (cap === null)
|
|
221
|
+
return undefined;
|
|
222
|
+
return { type: "text", raw: cap[0], escaped: true,
|
|
223
|
+
text: cap[0].replace(/</g, "<").replace(/>/g, ">") };
|
|
224
|
+
} } });
|
|
212
225
|
/* the Nunjucks environment with the @rse/nunjucks-addons extensions */
|
|
213
226
|
const env = new nunjucks.Environment(null, { autoescape: true });
|
|
214
227
|
nunjucksAddons(env);
|
|
@@ -231,28 +244,33 @@ const diagramCache = new WeakMap();
|
|
|
231
244
|
const anchorOf = (object) => anchors?.get(object) ?? object.id;
|
|
232
245
|
/* expand the inline Markdown of a text (code spans, emphasis, etc.),
|
|
233
246
|
with Wiki-style references expanded upfront */
|
|
234
|
-
const inline = (text) => safe(marked.parseInline(linker !== null ? linker(text) : text));
|
|
247
|
+
const inline = (text) => safe(marked.parseInline(linker !== null ? linker(text) : text, { async: false }));
|
|
235
248
|
/* expand the full Markdown of a text, keeping its block-level
|
|
236
249
|
constructs (lists, quotes, code blocks, tables) intact */
|
|
237
|
-
const block = (text) => safe(marked.parse(linker !== null ? linker(text) : text));
|
|
250
|
+
const block = (text) => safe(marked.parse(linker !== null ? linker(text) : text, { async: false }));
|
|
238
251
|
/* check whether a text carries any block-level Markdown, i.e. is
|
|
239
252
|
anything else than the single paragraph a description usually is */
|
|
240
253
|
const isBlock = (text) => {
|
|
241
254
|
const tokens = marked.lexer(text).filter((token) => token.type !== "space");
|
|
242
255
|
return tokens.length > 0 && !(tokens.length === 1 && tokens[0].type === "paragraph");
|
|
243
256
|
};
|
|
244
|
-
/* render a single embedded image file
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
257
|
+
/* render a single embedded image file onto an <img> tag with a
|
|
258
|
+
self-contained data: URL (converting the SVG text into one, as an
|
|
259
|
+
SVG inlined as-is would leak its document-global <style> rules
|
|
260
|
+
into all other inlined SVGs sharing the same class names) */
|
|
261
|
+
const renderImage = (content, alt) => {
|
|
262
|
+
const url = content.startsWith("data:") ? content :
|
|
263
|
+
`data:image/svg+xml;base64,${Buffer.from(content, "utf8").toString("base64")}`;
|
|
264
|
+
return `<img src="${url}" alt="${escapeHtml(alt)}"/>`;
|
|
265
|
+
};
|
|
249
266
|
/* wrap the theme variants of an image into their layout-neutral theme
|
|
250
267
|
containers, of which the stylesheet shows just the one matching the
|
|
251
268
|
color theme currently active in the document */
|
|
252
269
|
const renderThemed = (images) => images.map((image, i) => `<span class="theme-${embeddingThemes[i]}-only">${image}</span>`).join("");
|
|
253
270
|
/* render the embedded image files of a text into HTML, taking the image
|
|
254
271
|
alternate texts from the corresponding "" markups and
|
|
255
|
-
pairing up the consecutive theme variants of a "{theme}" markup
|
|
272
|
+
pairing up the consecutive theme variants of a "{theme}" markup
|
|
273
|
+
(the empty entries of unreadable files are skipped) */
|
|
256
274
|
const renderEmbeddings = (text, embedding) => {
|
|
257
275
|
const result = new Array();
|
|
258
276
|
let i = 0;
|
|
@@ -261,7 +279,8 @@ const renderEmbeddings = (text, embedding) => {
|
|
|
261
279
|
if (embeddingMimeType(reference) === undefined)
|
|
262
280
|
continue;
|
|
263
281
|
const variants = embeddingVariants(reference);
|
|
264
|
-
const
|
|
282
|
+
const contents = embedding.slice(i, i + variants.length);
|
|
283
|
+
const images = contents.filter((content) => content !== "")
|
|
265
284
|
.map((content) => renderImage(content, m[1].trim()));
|
|
266
285
|
i += variants.length;
|
|
267
286
|
if (variants.length > 1 && images.length === variants.length)
|
|
@@ -271,17 +290,20 @@ const renderEmbeddings = (text, embedding) => {
|
|
|
271
290
|
}
|
|
272
291
|
return result;
|
|
273
292
|
};
|
|
293
|
+
/* the image embedding markup including the horizontal whitespace
|
|
294
|
+
before it, so that its removal leaves no double space behind */
|
|
295
|
+
const embeddingMarkup = new RegExp(`[ \\t]*${embeddingRegex.source}`, "g");
|
|
274
296
|
/* render a description into HTML, expanding its inline Markdown and
|
|
275
297
|
moving the file embeddings to the end of the description */
|
|
276
298
|
const renderDescription = (description) => {
|
|
277
299
|
const text = description.description
|
|
278
|
-
.replace(
|
|
279
|
-
.
|
|
300
|
+
.replace(embeddingMarkup, (markup, _alt, reference) => embeddingMimeType(reference.trim()) !== undefined ? "" : markup)
|
|
301
|
+
.trim();
|
|
280
302
|
const embeddings = renderEmbeddings(description.description, description.embedding ?? []).map((content) => safe(content));
|
|
281
303
|
const blocked = isBlock(text);
|
|
282
304
|
return render("Description", { Description: {
|
|
283
305
|
block: blocked,
|
|
284
|
-
description: blocked ? block(text) : inline(text),
|
|
306
|
+
description: text !== "" ? (blocked ? block(text) : inline(text)) : "",
|
|
285
307
|
rationale: description.rationale !== undefined ?
|
|
286
308
|
inline(description.rationale) : undefined,
|
|
287
309
|
embeddings
|
|
@@ -289,8 +311,8 @@ const renderDescription = (description) => {
|
|
|
289
311
|
};
|
|
290
312
|
/* collect the "enum(...)"/"tags(...)" constrained properties of the
|
|
291
313
|
schema configuration, keyed by object kind and property name */
|
|
292
|
-
const collectMembers = (
|
|
293
|
-
for (const schema of
|
|
314
|
+
const collectMembers = (nodes, result) => {
|
|
315
|
+
for (const schema of nodes) {
|
|
294
316
|
for (const property of schema.props ?? []) {
|
|
295
317
|
if (property.value === undefined)
|
|
296
318
|
continue;
|
|
@@ -307,41 +329,25 @@ const collectMembers = (schemas, result) => {
|
|
|
307
329
|
}
|
|
308
330
|
return result;
|
|
309
331
|
};
|
|
310
|
-
/* map the specification objects onto their schema configuration
|
|
311
|
-
nodes (the schema resolution mirrors the semantic validation) */
|
|
312
|
-
const collectSchemas = (specification, config) => {
|
|
313
|
-
const result = new Map();
|
|
314
|
-
const walk = (object, schema) => {
|
|
315
|
-
result.set(object, schema);
|
|
316
|
-
for (const child of object.childs) {
|
|
317
|
-
const childSchema = (schema.childs ?? []).find((c) => c.kind === child.kind);
|
|
318
|
-
if (childSchema !== undefined)
|
|
319
|
-
walk(child, childSchema);
|
|
320
|
-
}
|
|
321
|
-
};
|
|
322
|
-
for (const artifact of specification.artifacts) {
|
|
323
|
-
for (const object of artifact.objects) {
|
|
324
|
-
const schema = config.find((s) => (s.kind === object.kind && s.id === object.id) || `${s.kind}-${s.id}` === object.id) ??
|
|
325
|
-
config.find((s) => (s.name ?? "").toUpperCase() ===
|
|
326
|
-
object.name.replace(/`/g, "").toUpperCase());
|
|
327
|
-
if (schema !== undefined)
|
|
328
|
-
walk(object, schema);
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
return result;
|
|
332
|
-
};
|
|
333
332
|
/* render a property value, badging the individual members of an
|
|
334
|
-
"enum(...)" (a single member) or "tags(...)" (a member set) value
|
|
335
|
-
|
|
333
|
+
"enum(...)" (a single member) or "tags(...)" (a member set) value
|
|
334
|
+
and moving its image embeddings behind the value, rendered from the
|
|
335
|
+
embedded image contents (as for a description), not from the markup */
|
|
336
|
+
const inlineValue = (kind, { key, value, embedding }) => {
|
|
336
337
|
const member = members?.get(`${kind}${key}`);
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
338
|
+
const text = value
|
|
339
|
+
.replace(embeddingMarkup, (markup, _alt, reference) => embeddingMimeType(reference.trim()) !== undefined ? "" : markup)
|
|
340
|
+
.trim();
|
|
341
|
+
const embeddings = renderEmbeddings(value, embedding ?? [])
|
|
342
|
+
.map((content) => `<div class="embedding">${content}</div>`).join("");
|
|
343
|
+
if (member === undefined || text === "")
|
|
344
|
+
return safe(`${inline(text)}${embeddings}`);
|
|
345
|
+
const items = member === "tags" ? splitItems(text) : [text];
|
|
346
|
+
return safe(items.map((item) => `<span class="value-member">${inline(item)}</span>`).join(" ") + embeddings);
|
|
341
347
|
};
|
|
342
348
|
/* expand the inline Markdown of the property values */
|
|
343
349
|
const inlineProperties = (kind, properties) => properties.map((property) => ({ key: property.key,
|
|
344
|
-
value: inlineValue(kind, property
|
|
350
|
+
value: inlineValue(kind, property) }));
|
|
345
351
|
/* resolve the format configuration of an object */
|
|
346
352
|
const formatOf = (object) => schemas?.get(object)?.format;
|
|
347
353
|
/* determine the maximum table columns configured on an object (at
|
|
@@ -364,18 +370,11 @@ const effectiveProperties = (object) => {
|
|
|
364
370
|
"withUnusedProps" injecting the defined but still unused schema
|
|
365
371
|
properties (in schema order) as additional columns */
|
|
366
372
|
const tableShape = (childs) => {
|
|
367
|
-
let keys = new
|
|
368
|
-
for (const child of childs)
|
|
369
|
-
for (const property of child.properties)
|
|
370
|
-
if (!keys.includes(property.key))
|
|
371
|
-
keys.push(property.key);
|
|
373
|
+
let keys = [...new Set(childs.flatMap((child) => child.properties.map((property) => property.key)))];
|
|
372
374
|
const schema = schemas?.get(childs[0]);
|
|
373
375
|
if (schema?.format?.withUnusedProps === true) {
|
|
374
|
-
const
|
|
375
|
-
|
|
376
|
-
return present.length > 0 ? present : [prop.name];
|
|
377
|
-
});
|
|
378
|
-
keys = [...merged, ...keys.filter((key) => !merged.includes(key))];
|
|
376
|
+
const names = (schema.props ?? []).map((prop) => prop.name);
|
|
377
|
+
keys = [...names, ...keys.filter((key) => !names.includes(key))];
|
|
379
378
|
}
|
|
380
379
|
return { keys, desc: childs.some((child) => child.description !== undefined || child.childs.length > 0) };
|
|
381
380
|
};
|
|
@@ -441,8 +440,8 @@ const renderTable = (childs, maxColumns) => {
|
|
|
441
440
|
primary: child.primary,
|
|
442
441
|
name: inline(child.name),
|
|
443
442
|
values: keys.map((key) => {
|
|
444
|
-
const
|
|
445
|
-
return
|
|
443
|
+
const property = child.properties.find((property) => property.key === key);
|
|
444
|
+
return property !== undefined ? inlineValue(child.kind, property) : "";
|
|
446
445
|
}),
|
|
447
446
|
description: safe(renderCell(child))
|
|
448
447
|
}))
|
|
@@ -456,9 +455,9 @@ const renderTable = (childs, maxColumns) => {
|
|
|
456
455
|
width: Math.round(100 / maxColumns),
|
|
457
456
|
rows: childs.map((child) => {
|
|
458
457
|
const cells = keys.map((key) => {
|
|
459
|
-
const
|
|
458
|
+
const property = child.properties.find((property) => property.key === key);
|
|
460
459
|
return { key, desc: false, span: 1,
|
|
461
|
-
value:
|
|
460
|
+
value: property !== undefined ? inlineValue(child.kind, property) : "" };
|
|
462
461
|
});
|
|
463
462
|
if (desc)
|
|
464
463
|
cells.push({ key: "Description", desc: true, span: 1,
|
|
@@ -481,6 +480,7 @@ const renderTable = (childs, maxColumns) => {
|
|
|
481
480
|
/* recursively render an object into HTML */
|
|
482
481
|
const renderObject = (object, level, concise) => {
|
|
483
482
|
const properties = effectiveProperties(object);
|
|
483
|
+
const diagram = diagrams?.get(object);
|
|
484
484
|
return render("Object", { Object: {
|
|
485
485
|
level: Math.min(level, 6),
|
|
486
486
|
kind: object.kind,
|
|
@@ -488,8 +488,7 @@ const renderObject = (object, level, concise) => {
|
|
|
488
488
|
paren: object.paren,
|
|
489
489
|
primary: object.primary,
|
|
490
490
|
name: inline(object.name),
|
|
491
|
-
diagram:
|
|
492
|
-
safe(`<div class="diagram">${diagrams.get(object) ?? ""}</div>`) : "",
|
|
491
|
+
diagram: diagram !== undefined ? safe(`<div class="diagram">${diagram}</div>`) : "",
|
|
493
492
|
properties: properties.length > 0 ?
|
|
494
493
|
safe(render("Properties", { Properties: inlineProperties(object.kind, properties) })) : "",
|
|
495
494
|
description: object.description !== undefined ?
|
|
@@ -499,6 +498,11 @@ const renderObject = (object, level, concise) => {
|
|
|
499
498
|
safe(flowChilds(object).map((child) => renderObject(child, level + 1, concise)).join(""))
|
|
500
499
|
} });
|
|
501
500
|
};
|
|
501
|
+
/* format a timestamp as its calendar date in local time (the
|
|
502
|
+
frontmatter timestamps are parsed in local time, too, so the UTC
|
|
503
|
+
date of toISOString() could shift the day) */
|
|
504
|
+
const formatDate = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-` +
|
|
505
|
+
String(date.getDate()).padStart(2, "0");
|
|
502
506
|
/* render the title object into a title page */
|
|
503
507
|
const renderTitlePage = (object, created, modified) => {
|
|
504
508
|
const prop = (name) => object.properties.find((property) => property.key === name)?.value;
|
|
@@ -539,7 +543,7 @@ export const htmlOutline = (specification, config) => {
|
|
|
539
543
|
const paths = anchorPaths(buildLinkIndex(specification));
|
|
540
544
|
const schemaMap = config !== undefined ? collectSchemas(specification, config) : null;
|
|
541
545
|
const entry = (object) => ({
|
|
542
|
-
title: (object.kind !== "" ? `${object.kind}: ` : "") + object.name,
|
|
546
|
+
title: (object.kind !== "" ? `${object.kind}: ` : "") + plainText(object.name),
|
|
543
547
|
anchor: paths.get(object) ?? object.id,
|
|
544
548
|
childs: conciseChilds(object, schemaMap, false) ? [] : flowChilds(object).map(entry)
|
|
545
549
|
});
|
|
@@ -570,23 +574,23 @@ export const renderHtml = async (specification, config, tocPages, css) => {
|
|
|
570
574
|
canvas and would dwarf the document text at 1:1 */
|
|
571
575
|
const scale = 0.75;
|
|
572
576
|
const cached = diagramCache.get(specification);
|
|
573
|
-
|
|
577
|
+
let rendered = null;
|
|
574
578
|
if (cached !== undefined && cached.config === config)
|
|
575
|
-
|
|
579
|
+
rendered = cached.diagrams;
|
|
576
580
|
else if (config !== undefined) {
|
|
577
|
-
|
|
581
|
+
rendered = new Map();
|
|
578
582
|
for (const [object, result] of specDiagrams(specification, config)) {
|
|
579
583
|
if (result.spec === undefined)
|
|
580
584
|
continue;
|
|
581
585
|
try {
|
|
582
|
-
const svg = await Gradia.render(result.spec, { format: "svg:embedded" });
|
|
583
|
-
|
|
586
|
+
const svg = await Gradia.render(result.spec, { format: "svg:embedded", config: result.config });
|
|
587
|
+
rendered.set(object, svg.replace(/(<svg[^>]*) width="([0-9.]+)" height="([0-9.]+)"/, (_, head, w, h) => `${head} width="${Number(w) * scale}" height="${Number(h) * scale}"`));
|
|
584
588
|
}
|
|
585
589
|
catch {
|
|
586
590
|
/* intentionally omitted */
|
|
587
591
|
}
|
|
588
592
|
}
|
|
589
|
-
diagramCache.set(specification, { config, diagrams });
|
|
593
|
+
diagramCache.set(specification, { config, diagrams: rendered });
|
|
590
594
|
}
|
|
591
595
|
/* the document language selects the smart typography quote style */
|
|
592
596
|
const lang = documentLang(specification);
|
|
@@ -598,6 +602,7 @@ export const renderHtml = async (specification, config, tocPages, css) => {
|
|
|
598
602
|
anchors = anchorPaths(index);
|
|
599
603
|
members = config !== undefined ? collectMembers(config, new Map()) : null;
|
|
600
604
|
schemas = config !== undefined ? collectSchemas(specification, config) : null;
|
|
605
|
+
diagrams = rendered;
|
|
601
606
|
linker = (text) => expandReferences(text, (reference) => {
|
|
602
607
|
const target = resolveUnique(index, reference).target;
|
|
603
608
|
if (target === undefined)
|
|
@@ -612,18 +617,30 @@ export const renderHtml = async (specification, config, tocPages, css) => {
|
|
|
612
617
|
const title = titlePageObject(specification);
|
|
613
618
|
const artifacts = specification.artifacts
|
|
614
619
|
.filter((artifact) => !artifact.objects.some(isTitleObject));
|
|
615
|
-
|
|
616
|
-
.
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
620
|
+
try {
|
|
621
|
+
const entries = artifacts.flatMap((artifact) => artifact.objects)
|
|
622
|
+
.map((object) => ({ id: anchorOf(object), kind: object.kind, name: inline(object.name),
|
|
623
|
+
page: tocPages?.get(anchorOf(object)) }));
|
|
624
|
+
return render("Document", { Document: {
|
|
625
|
+
title: documentTitle(specification).title,
|
|
626
|
+
lang,
|
|
627
|
+
theme: documentThemeStyle(specification)?.toLowerCase(),
|
|
628
|
+
css: safe(css ?? stylesheet()),
|
|
629
|
+
titlepage: title !== undefined ?
|
|
630
|
+
safe(renderTitlePage(title, formatDate(created), formatDate(modified))) : "",
|
|
631
|
+
search: title !== undefined ? safe(searchScript()) : "",
|
|
632
|
+
toc: entries.length > 0 ? safe(render("Toc", { Toc: { entries } })) : "",
|
|
633
|
+
artifacts: safe(artifacts.map((artifact) => renderArtifact(artifact)).join(""))
|
|
634
|
+
} });
|
|
635
|
+
}
|
|
636
|
+
finally {
|
|
637
|
+
/* release the per-document state (also on a rendering failure),
|
|
638
|
+
as it would otherwise retain the specification (and its
|
|
639
|
+
embedded images) until the next rendering */
|
|
640
|
+
linker = null;
|
|
641
|
+
anchors = null;
|
|
642
|
+
members = null;
|
|
643
|
+
schemas = null;
|
|
644
|
+
diagrams = null;
|
|
645
|
+
}
|
|
629
646
|
};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { Spec } from "./specbook-format-spec.js";
|
|
2
2
|
import type { Schema } from "./specbook-format-schema.js";
|
|
3
|
-
export declare const renderMarkdown: (specification: Spec, config?: Schema) =>
|
|
3
|
+
export declare const renderMarkdown: (specification: Spec, config?: Schema) => string;
|
|
@@ -10,10 +10,14 @@ const formatTimestamp = (date) => {
|
|
|
10
10
|
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
|
|
11
11
|
`${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
12
12
|
};
|
|
13
|
-
/* render the properties as a value-aligned key/value list
|
|
14
|
-
|
|
13
|
+
/* render the properties as a value-aligned key/value list, wrapping a
|
|
14
|
+
value carrying ";" onto a continuation line, as only a ";"-free first
|
|
15
|
+
line lets the item be recognized as a property again on re-parsing */
|
|
16
|
+
const renderKeyValuesMd = (properties, indent = "") => {
|
|
15
17
|
const width = Math.max(...properties.map((property) => property.key.length)) + 1;
|
|
16
|
-
return properties.map((property) =>
|
|
18
|
+
return properties.map((property) => property.value.includes(";") ?
|
|
19
|
+
`${indent}- ${property.key}:\n${indent} ${property.value}` :
|
|
20
|
+
`${indent}- ${`${property.key}:`.padEnd(width)} ${property.value}`.trimEnd()).join("\n");
|
|
17
21
|
};
|
|
18
22
|
/* render a description statement with its optional rationale */
|
|
19
23
|
const renderDescriptionMd = (description) => description.description + (description.rationale !== undefined ?
|
|
@@ -23,28 +27,42 @@ const renderDescriptionMd = (description) => description.description + (descript
|
|
|
23
27
|
const nameSuffixMd = (object) => (object.primary === true ? " (*)" : "") +
|
|
24
28
|
(object.paren !== undefined ? ` (${object.paren})` : "") +
|
|
25
29
|
(object.anchor !== undefined ? ` {{${object.anchor}}}` : "");
|
|
26
|
-
/*
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
+
/* whether any descendant of an object carries a multi-line description
|
|
31
|
+
(a fenced code block, an ordered list, a blockquote, or multiple
|
|
32
|
+
paragraphs), which no Concise Format item can carry */
|
|
33
|
+
const multiLineBelowMd = (object) => object.childs.some((child) => (child.description !== undefined
|
|
34
|
+
&& renderDescriptionMd(child.description).includes("\n")) || multiLineBelowMd(child));
|
|
35
|
+
/* render an object in the Concise Format as a list item of the
|
|
36
|
+
given nesting depth, with its childs as nested list items */
|
|
37
|
+
const renderConciseMd = (object, depth = 0) => {
|
|
38
|
+
const indent = " ".repeat(depth * 4);
|
|
30
39
|
const segments = [`${object.kind}: ${object.name}${nameSuffixMd(object)}`];
|
|
31
|
-
|
|
40
|
+
/* a value carrying ";" cannot be a segment, so its property has to
|
|
41
|
+
become a nested key/value item below the item instead */
|
|
42
|
+
const wrapped = object.properties.filter((property) => property.value.includes(";"));
|
|
43
|
+
const inline = object.properties.filter((property) => !property.value.includes(";"));
|
|
44
|
+
segments.push(...inline.map((property) => `${property.key}: ${property.value}`));
|
|
32
45
|
if (object.description !== undefined)
|
|
33
46
|
segments.push(renderDescriptionMd(object.description));
|
|
34
|
-
/* a description terminates the item with ".",
|
|
35
|
-
|
|
36
|
-
|
|
47
|
+
/* a description terminates the item with ".", which on re-parsing
|
|
48
|
+
marks the last segment as the description (even one shaped like
|
|
49
|
+
"<key>: <value>"), while without one the ";" segment terminator
|
|
50
|
+
has to remain, as only it lets the item be recognized as concise */
|
|
37
51
|
const item = object.description !== undefined ?
|
|
38
52
|
`${indent}- ${segments.join("; ").replace(/\.?$/, ".")}` :
|
|
39
53
|
`${indent}- ${segments.join("; ")};`;
|
|
40
|
-
return [item,
|
|
54
|
+
return [item, renderKeyValuesMd(wrapped, `${indent} `),
|
|
55
|
+
...object.childs.map((child) => renderConciseMd(child, depth + 1))]
|
|
56
|
+
.filter((part) => part !== "").join("\n");
|
|
41
57
|
};
|
|
42
|
-
/* render an object in the Complex Format (levels 1-3),
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
58
|
+
/* render an object in the Complex Format (levels 1-3), with childs from
|
|
59
|
+
level 4 upwards in the Concise Format -- unless a descendant carries
|
|
60
|
+
a multi-line description, so all childs (as siblings have to share
|
|
61
|
+
the format) stay in the Complex Format down to heading level 6 --,
|
|
62
|
+
and the optionally derived Gradia diagram spec embedded as a
|
|
63
|
+
"gradia" fenced code block below the heading */
|
|
46
64
|
const renderObjectMd = (object, level, diagrams) => {
|
|
47
|
-
const heading = `${"#".repeat(level)}${" ".repeat(4 - level)}` +
|
|
65
|
+
const heading = `${"#".repeat(level)}${" ".repeat(Math.max(1, 4 - level))}` +
|
|
48
66
|
`${object.kind}: ${object.name}${nameSuffixMd(object)}`;
|
|
49
67
|
const parts = [heading];
|
|
50
68
|
const spec = diagrams?.get(object);
|
|
@@ -54,14 +72,16 @@ const renderObjectMd = (object, level, diagrams) => {
|
|
|
54
72
|
parts.push(renderKeyValuesMd(object.properties));
|
|
55
73
|
if (object.description !== undefined)
|
|
56
74
|
parts.push(renderDescriptionMd(object.description));
|
|
57
|
-
|
|
58
|
-
|
|
75
|
+
/* the childs share one format, as a concise item following
|
|
76
|
+
a heading would attach to the heading's object instead */
|
|
77
|
+
if (level >= 3 && !multiLineBelowMd(object))
|
|
78
|
+
parts.push(object.childs.map((child) => renderConciseMd(child)).join("\n"));
|
|
59
79
|
else
|
|
60
80
|
parts.push(...object.childs.map((child) => renderObjectMd(child, level + 1, diagrams)));
|
|
61
81
|
return parts.filter((part) => part !== "").join("\n\n");
|
|
62
82
|
};
|
|
63
83
|
/* render the entire specification into normalized Markdown */
|
|
64
|
-
export const renderMarkdown =
|
|
84
|
+
export const renderMarkdown = (specification, config) => {
|
|
65
85
|
/* derive the Gradia specs of the diagram-configured objects
|
|
66
86
|
(an invalid diagram situation omits the diagram, as it is
|
|
67
87
|
already reported as a lint diagnostic) */
|
|
@@ -70,9 +90,15 @@ export const renderMarkdown = async (specification, config) => {
|
|
|
70
90
|
for (const [object, result] of specDiagrams(specification, config))
|
|
71
91
|
if (result.spec !== undefined)
|
|
72
92
|
diagrams.set(object, result.spec);
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
93
|
+
/* the single frontmatter block (only recognized at the start of a
|
|
94
|
+
file on re-parse) carries the earliest creation and the latest
|
|
95
|
+
modification timestamp of all artifacts */
|
|
96
|
+
const created = new Date(Math.min(...specification.artifacts.map((artifact) => artifact.created.getTime())));
|
|
97
|
+
const modified = new Date(Math.max(...specification.artifacts.map((artifact) => artifact.modified.getTime())));
|
|
98
|
+
return "---\n" +
|
|
99
|
+
`Created: ${formatTimestamp(created)}\n` +
|
|
100
|
+
`Modified: ${formatTimestamp(modified)}\n` +
|
|
76
101
|
"---\n\n" +
|
|
77
|
-
|
|
102
|
+
specification.artifacts.flatMap((artifact) => artifact.objects)
|
|
103
|
+
.map((object) => renderObjectMd(object, 1, diagrams)).join("\n\n") + "\n";
|
|
78
104
|
};
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { OutlineEntry } from "./specbook-export-html.js";
|
|
2
2
|
import type { ThemeMapping } from "./specbook-theme.js";
|
|
3
|
-
|
|
3
|
+
type Heading = {
|
|
4
4
|
title: string;
|
|
5
5
|
subtitle?: string;
|
|
6
6
|
logo: string;
|
|
7
|
-
}
|
|
7
|
+
};
|
|
8
|
+
export declare const htmlToPdf: (renderHtmlPass: (tocPages?: Map<string, number>) => Promise<string>, heading: Heading, outline: OutlineEntry[], verbose: (msg: string) => void, css: string, theme: ThemeMapping, paper?: string) => Promise<Buffer>;
|
|
9
|
+
export {};
|
|
@@ -78,6 +78,49 @@ const addOutline = async (doc, entries) => {
|
|
|
78
78
|
doc.catalog.set(PDFName.of("Outlines"), root);
|
|
79
79
|
doc.catalog.set(PDFName.of("PageMode"), PDFName.of("UseOutlines"));
|
|
80
80
|
};
|
|
81
|
+
/* render the header/footer templates for the page decoration: they
|
|
82
|
+
render in an isolated context, so they need their own inline styling,
|
|
83
|
+
the regular font face embedded as a data: URI, and the special
|
|
84
|
+
"pageNumber" class for the injected page number */
|
|
85
|
+
const decorationTemplates = (heading, css, theme, left, right) => {
|
|
86
|
+
const fontFace = css.match(/@font-face\s*\{[^}]*\}/)?.[0] ?? "";
|
|
87
|
+
const subtitle = heading.subtitle?.trim();
|
|
88
|
+
const headText = escapeHtml(heading.title) +
|
|
89
|
+
(subtitle !== undefined && subtitle !== "" ? ` — ${escapeHtml(subtitle)}` : "");
|
|
90
|
+
return {
|
|
91
|
+
headerTemplate: `<style>${fontFace}</style>` +
|
|
92
|
+
"<div style=\"width: 100%; margin-top: 0.8cm;\">" +
|
|
93
|
+
`<div style="margin: 0 ${right} 0 ${left}; ` +
|
|
94
|
+
"font-family: 'Source Sans 3', sans-serif; " +
|
|
95
|
+
`font-size: 8pt; color: ${theme.symbol}; border-bottom: 1px solid ${theme.border}; ` +
|
|
96
|
+
"padding-bottom: 1mm; display: flex; justify-content: space-between; " +
|
|
97
|
+
"align-items: flex-end;\">" +
|
|
98
|
+
`<span>${headText}</span>` +
|
|
99
|
+
`<img src="${escapeHtml(heading.logo)}" alt="" style="height: 3.5mm;"/>` +
|
|
100
|
+
"</div></div>",
|
|
101
|
+
footerTemplate: `<style>${fontFace}</style>` +
|
|
102
|
+
"<div style=\"width: 100%; margin-bottom: 0.8cm;\">" +
|
|
103
|
+
`<div style="margin: 0 ${right} 0 ${left}; ` +
|
|
104
|
+
"font-family: 'Source Sans 3', sans-serif; " +
|
|
105
|
+
`font-size: 8pt; color: ${theme.symbol}; display: flex; ` +
|
|
106
|
+
`justify-content: space-between; border-top: 1px solid ${theme.border}; ` +
|
|
107
|
+
"padding-top: 1mm;\">" +
|
|
108
|
+
`<span>${headText}</span>` +
|
|
109
|
+
`<span style="color: ${theme.muted}; font-weight: bold;" class="pageNumber"></span></div></div>`
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
/* draw the vertical brand bar onto the left edge of the physical
|
|
113
|
+
paper of every page, as Chromium clips print content to the page
|
|
114
|
+
box (0.6rem at the 9pt print root) */
|
|
115
|
+
const drawBrandBar = async (doc, accent) => {
|
|
116
|
+
const { rgb } = await import("pdf-lib");
|
|
117
|
+
const hex = accent.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
|
|
118
|
+
const [r, g, b] = (hex !== null ? hex.slice(1) : ["00", "00", "00"])
|
|
119
|
+
.map((component) => parseInt(component, 16) / 255);
|
|
120
|
+
for (const page of doc.getPages())
|
|
121
|
+
page.drawRectangle({ x: 0, y: 0, width: 5.4,
|
|
122
|
+
height: page.getHeight(), color: rgb(r, g, b) });
|
|
123
|
+
};
|
|
81
124
|
/* render a self-contained HTML document into a PDF via Playwright,
|
|
82
125
|
re-rendering the HTML with the discovered ToC page numbers */
|
|
83
126
|
export const htmlToPdf = async (renderHtmlPass, heading, outline, verbose, css, theme, paper = paperSizeDefault) => {
|
|
@@ -85,11 +128,6 @@ export const htmlToPdf = async (renderHtmlPass, heading, outline, verbose, css,
|
|
|
85
128
|
/* the page geometry of the chosen paper size */
|
|
86
129
|
const setup = paperSetup(paper);
|
|
87
130
|
const margin = setup.margin;
|
|
88
|
-
/* the regular font face and the title/subtitle
|
|
89
|
-
text for the header/footer templates */
|
|
90
|
-
const fontFace = css.match(/@font-face\s*\{[^}]*\}/)?.[0] ?? "";
|
|
91
|
-
const headText = escapeHtml(heading.title) +
|
|
92
|
-
(heading.subtitle !== undefined ? ` — ${escapeHtml(heading.subtitle)}` : "");
|
|
93
131
|
/* launch the Playwright Chromium browser, falling back to a
|
|
94
132
|
system-installed Google Chrome if the Chromium download is missing */
|
|
95
133
|
let browser;
|
|
@@ -139,31 +177,10 @@ export const htmlToPdf = async (renderHtmlPass, heading, outline, verbose, css,
|
|
|
139
177
|
html = next;
|
|
140
178
|
plain = await renderPdf(html);
|
|
141
179
|
}
|
|
180
|
+
/* render the final document, decorated with header/footer */
|
|
142
181
|
const decorated = await renderPdf(html, {
|
|
143
|
-
/* the header/footer templates render in an isolated context,
|
|
144
|
-
so they need their own inline styling, the regular font face
|
|
145
|
-
embedded as a data: URI, and the special "title"/"pageNumber"
|
|
146
|
-
classes for the injected values */
|
|
147
182
|
displayHeaderFooter: true,
|
|
148
|
-
|
|
149
|
-
"<div style=\"width: 100%; margin-top: 0.8cm;\">" +
|
|
150
|
-
`<div style="margin: 0 ${paperLength(setup, margin.left)}; ` +
|
|
151
|
-
"font-family: 'Source Sans 3', sans-serif; " +
|
|
152
|
-
`font-size: 8pt; color: ${theme.symbol}; border-bottom: 1px solid ${theme.border}; ` +
|
|
153
|
-
"padding-bottom: 1mm; display: flex; justify-content: space-between; " +
|
|
154
|
-
"align-items: flex-end;\">" +
|
|
155
|
-
`<span>${headText}</span>` +
|
|
156
|
-
`<img src="${escapeHtml(heading.logo)}" alt="" style="height: 3.5mm;"/>` +
|
|
157
|
-
"</div></div>",
|
|
158
|
-
footerTemplate: `<style>${fontFace}</style>` +
|
|
159
|
-
"<div style=\"width: 100%; margin-bottom: 0.8cm;\">" +
|
|
160
|
-
`<div style="margin: 0 ${paperLength(setup, margin.left)}; ` +
|
|
161
|
-
"font-family: 'Source Sans 3', sans-serif; " +
|
|
162
|
-
`font-size: 8pt; color: ${theme.text}; display: flex; ` +
|
|
163
|
-
`justify-content: space-between; border-top: 1px solid ${theme.border}; ` +
|
|
164
|
-
"padding-top: 1mm;\">" +
|
|
165
|
-
`<span style="color: ${theme.symbol}">${headText}</span>` +
|
|
166
|
-
`<span style="color: ${theme.muted}; font-weight: bold;" class="pageNumber"></span></div></div>`
|
|
183
|
+
...decorationTemplates(heading, css, theme, paperLength(setup, margin.left), paperLength(setup, margin.right))
|
|
167
184
|
});
|
|
168
185
|
/* a title page carries no header/footer: as Chromium decorates
|
|
169
186
|
all pages unconditionally, swap the first page of the
|
|
@@ -171,7 +188,7 @@ export const htmlToPdf = async (renderHtmlPass, heading, outline, verbose, css,
|
|
|
171
188
|
the ToC page number iteration) into the decorated document
|
|
172
189
|
*in place*, which keeps the decorated document's link
|
|
173
190
|
destinations (and hence the internal hyperlinks) intact */
|
|
174
|
-
const { PDFDocument
|
|
191
|
+
const { PDFDocument } = await import("pdf-lib");
|
|
175
192
|
const merged = await PDFDocument.load(decorated);
|
|
176
193
|
if (html.includes("class=\"titlepage\"")) {
|
|
177
194
|
const source = await PDFDocument.load(plain);
|
|
@@ -182,15 +199,8 @@ export const htmlToPdf = async (renderHtmlPass, heading, outline, verbose, css,
|
|
|
182
199
|
/* attach the document outline for the viewer side-bar */
|
|
183
200
|
verbose("attaching PDF outline (bookmarks)");
|
|
184
201
|
await addOutline(merged, outline);
|
|
185
|
-
/*
|
|
186
|
-
|
|
187
|
-
content to the page box (0.6rem at the 9pt print root) */
|
|
188
|
-
const hex = theme.accent.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
|
|
189
|
-
const [r, g, b] = (hex !== null ? hex.slice(1) : ["00", "00", "00"])
|
|
190
|
-
.map((component) => parseInt(component, 16) / 255);
|
|
191
|
-
for (const pdfPage of merged.getPages())
|
|
192
|
-
pdfPage.drawRectangle({ x: 0, y: 0, width: 5.4,
|
|
193
|
-
height: pdfPage.getHeight(), color: rgb(r, g, b) });
|
|
202
|
+
/* decorate every page with the vertical brand bar */
|
|
203
|
+
await drawBrandBar(merged, theme.accent);
|
|
194
204
|
return Buffer.from(await merged.save());
|
|
195
205
|
}
|
|
196
206
|
finally {
|
|
@@ -8,9 +8,12 @@ import { Gradia } from "@rse/gradia";
|
|
|
8
8
|
/* ==== Schema ==== */
|
|
9
9
|
/* the Gradia rendering options, derived from the configuration
|
|
10
10
|
defaults of Gradia: the option names constrain the allowed keys and
|
|
11
|
-
the types of the default values constrain the allowed value types
|
|
11
|
+
the types of the default values constrain the allowed value types
|
|
12
|
+
(with the numbers restricted to the finite, non-negative values
|
|
13
|
+
Gradia honors, as it silently drops all others) */
|
|
12
14
|
const GradiaConfigSchemas = Object.fromEntries(Object.entries(Gradia.config).map(([key, value]) => [key,
|
|
13
|
-
typeof value === "boolean" ? v.boolean() :
|
|
15
|
+
typeof value === "boolean" ? v.boolean() :
|
|
16
|
+
typeof value === "number" ? v.pipe(v.number(), v.finite(), v.minValue(0)) : v.string()]));
|
|
14
17
|
const SchemaDiagramConfig = v.partial(v.strictObject(GradiaConfigSchemas, (issue) => issue.expected === "never" ? "unknown Gradia rendering option" :
|
|
15
18
|
"expected a map of Gradia rendering options"));
|
|
16
19
|
const SchemaProperty = v.strictObject({
|
|
@@ -37,7 +40,7 @@ const SchemaDiagram = v.strictObject({
|
|
|
37
40
|
});
|
|
38
41
|
const SchemaFormat = v.strictObject({
|
|
39
42
|
type: v.optional(v.picklist(["auto", "complex", "concise"])),
|
|
40
|
-
maxTableColumns: v.optional(v.pipe(v.number(), v.integer(), v.minValue(
|
|
43
|
+
maxTableColumns: v.optional(v.pipe(v.number(), v.integer(), v.minValue(2))),
|
|
41
44
|
withUnusedProps: v.optional(v.boolean())
|
|
42
45
|
});
|
|
43
46
|
const SchemaObject = v.strictObject({
|