cook-ssg 2.7.0 → 2.9.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.
@@ -0,0 +1,309 @@
1
+ /**
2
+ * @file render.js
3
+ * @description Render a page through a layout and, for a child layout
4
+ * (`data-template="parent"` on its `<html>` or `<body>`), through each
5
+ * parent in turn.
6
+ *
7
+ * Everything here works on source strings, never on a re-serialized DOM,
8
+ * so a layout's markup reaches the output exactly as the author wrote it.
9
+ * Each layer's pieces are split from the RAW layout source and then filled;
10
+ * filled output is never re-scanned. Page content that contains `<main>`,
11
+ * `<template>`, `<template slot>` or `${...}` is therefore only ever a
12
+ * value, never layout structure (the interpolator never rescans inserted
13
+ * values).
14
+ *
15
+ * A layout with no `data-template` and no info block takes an early exit
16
+ * and renders exactly as before.
17
+ */
18
+
19
+ import chalk from 'chalk';
20
+ import { renderTemplate } from '../interpolate/interpolate.js';
21
+
22
+ export const MAX_DEPTH = 5;
23
+
24
+ // The exact opening form the old slot regex accepted
25
+ const SLOT_OPEN = /<template\s+slot="([^"]+)">/gi;
26
+ // Any template open or close tag, for depth counting
27
+ const TEMPLATE_TAG = /<(\/?)template(?=[\s>/])[^>]*>/gi;
28
+
29
+ // A child layout: data-template on <html> or <body> (same test as
30
+ // apply-template), its value double-quoted, single-quoted or unquoted.
31
+ // Groups: 1 tag, 2 attributes, 3/4/5 the value in each quoting.
32
+ const TEMPLATED_TAG = /<(html|body)(\s(?:[^>]*?\s)?data-template\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s"'>]+))[^>]*)>/i;
33
+
34
+ // One attribute in a start tag's attribute string, any quoting
35
+ const ATTR = /([^\s"'>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
36
+
37
+ /**
38
+ * Find the `<html>` or `<body>` start tag carrying data-template.
39
+ * @param {string} src
40
+ * @returns {{ index: number, length: number, name: string, attrs: string }|null}
41
+ * `name` is the template name, `attrs` the tag's attribute string
42
+ */
43
+ export function findTemplatedTag(src) {
44
+ const m = src.match(TEMPLATED_TAG);
45
+ if (!m) return null;
46
+ return { index: m.index, length: m[0].length, name: m[3] ?? m[4] ?? m[5], attrs: m[2] };
47
+ }
48
+
49
+ /**
50
+ * The data-* attributes (data-template excepted) of an attribute string,
51
+ * keyed by camelCase name, values in any quoting.
52
+ * @param {string} attrs
53
+ * @returns {Record<string, string>}
54
+ */
55
+ export function templateDataAttrs(attrs) {
56
+ const out = {};
57
+ ATTR.lastIndex = 0;
58
+ let m;
59
+ while ((m = ATTR.exec(attrs)) !== null) {
60
+ const attr = m[1].toLowerCase();
61
+ if (!/^data-[a-z][a-z0-9-]*$/.test(attr) || attr === 'data-template') continue;
62
+ const key = attr.slice('data-'.length).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
63
+ out[key] = m[2] ?? m[3] ?? m[4] ?? '';
64
+ }
65
+ return out;
66
+ }
67
+
68
+ // The info block element: its body never crosses a `</script`, so the
69
+ // match ends at the info script's own close tag. Leading indent and the
70
+ // trailing line break are captured so a line holding only the block can
71
+ // go whole.
72
+ const INFO = /([ \t]*)<script\b[^>]*\bdata-layout-info\b[^>]*>(?:(?!<\/script)[\s\S])*<\/script\s*>([ \t]*(?:\r?\n|$))?/gi;
73
+ const HAS_INFO = /<script\b[^>]*\bdata-layout-info\b/i;
74
+
75
+ // A `slot` attribute inside a start tag's attributes, any quoting
76
+ const SLOT_ATTR = /(?:^|\s)slot\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i;
77
+
78
+ /**
79
+ * Thrown for a layout cycle or a chain deeper than MAX_DEPTH. Always a
80
+ * build error, whatever kind of page hit it.
81
+ */
82
+ export class LayoutChainError extends Error {
83
+ constructor(message) {
84
+ super(message);
85
+ this.name = 'LayoutChainError';
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Index just past the `</template>` that closes a template opened before
91
+ * `from`, counting nested templates. -1 when it never closes.
92
+ * @param {string} html
93
+ * @param {number} from - Index just after the opening tag
94
+ * @returns {{ innerEnd: number, end: number }|null}
95
+ */
96
+ function findClose(html, from) {
97
+ let depth = 1;
98
+ TEMPLATE_TAG.lastIndex = from;
99
+ let m;
100
+ while ((m = TEMPLATE_TAG.exec(html))) {
101
+ if (m[1]) depth--;
102
+ else depth++;
103
+ if (depth === 0) return { innerEnd: m.index, end: TEMPLATE_TAG.lastIndex };
104
+ }
105
+ return null;
106
+ }
107
+
108
+ /**
109
+ * Split top-level `<template slot="x">…</template>` elements out of HTML.
110
+ * Nested `<template>`s inside a slot are kept whole. Without nesting the
111
+ * result is byte-identical to the old non-greedy regex: each slot's inner
112
+ * HTML trimmed, a later slot of the same name winning, and the remaining
113
+ * content trimmed.
114
+ * @param {string} html
115
+ * @returns {{ content: string, slots: Record<string, string> }}
116
+ */
117
+ export function extractSlots(html) {
118
+ const slots = {};
119
+ let content = '';
120
+ let pos = 0;
121
+
122
+ SLOT_OPEN.lastIndex = 0;
123
+ let open;
124
+ while ((open = SLOT_OPEN.exec(html))) {
125
+ const close = findClose(html, SLOT_OPEN.lastIndex);
126
+ if (!close) continue; // never closed: not a slot, leave it in place
127
+ slots[open[1]] = html.slice(SLOT_OPEN.lastIndex, close.innerEnd).trim();
128
+ content += html.slice(pos, open.index);
129
+ pos = close.end;
130
+ SLOT_OPEN.lastIndex = close.end;
131
+ }
132
+ content += html.slice(pos);
133
+
134
+ return { content: content.trim(), slots };
135
+ }
136
+
137
+ /**
138
+ * Remove the info block from layout source.
139
+ * @param {string} html
140
+ * @returns {string}
141
+ */
142
+ export function stripInfo(html) {
143
+ if (!HAS_INFO.test(html)) return html;
144
+ return html.replace(INFO, (match, lead, trail, offset) => {
145
+ const atLineStart = offset === 0 || html[offset - 1] === '\n';
146
+ // Alone on its line: the whole line goes
147
+ if (atLineStart && trail !== undefined) return '';
148
+ // Shares the line: only the element goes
149
+ return lead + (trail || '');
150
+ });
151
+ }
152
+
153
+ /**
154
+ * Split a child layout's body into its top-level slot templates and the
155
+ * rest. Any top-level `<template …>` with a `slot` attribute counts, in any
156
+ * attribute order and quoting. Each piece is the WHOLE element (opening tag
157
+ * included) so the conditionals hook can see attributes such as `data-if`.
158
+ * @param {string} html
159
+ * @returns {{ body: string, pieces: Array<{ name: string, element: string }> }}
160
+ */
161
+ export function splitChildSlots(html) {
162
+ const pieces = [];
163
+ let body = '';
164
+ let pos = 0;
165
+
166
+ TEMPLATE_TAG.lastIndex = 0;
167
+ let m;
168
+ while ((m = TEMPLATE_TAG.exec(html))) {
169
+ if (m[1]) continue; // a stray close tag at top level
170
+ const openEnd = TEMPLATE_TAG.lastIndex;
171
+ const close = findClose(html, openEnd);
172
+ if (!close) break; // never closed: leave the rest as body
173
+ const attrs = m[0].slice('<template'.length, -1);
174
+ const slot = attrs.match(SLOT_ATTR);
175
+ if (slot) {
176
+ const name = (slot[1] ?? slot[2] ?? slot[3]).trim();
177
+ if (name) {
178
+ pieces.push({ name, element: html.slice(m.index, close.end) });
179
+ body += html.slice(pos, m.index);
180
+ pos = close.end;
181
+ }
182
+ }
183
+ // Skip the whole element: templates inside it are not top level
184
+ TEMPLATE_TAG.lastIndex = close.end;
185
+ }
186
+ body += html.slice(pos);
187
+
188
+ return { body: body.trim(), pieces };
189
+ }
190
+
191
+ /**
192
+ * The inner HTML of a slot template element, after the conditionals hook
193
+ * has run on it. A hook that removed the element leaves nothing.
194
+ * @param {string} element
195
+ * @returns {string}
196
+ */
197
+ function innerOf(element) {
198
+ const open = element.match(/^\s*<template\b[^>]*>/i);
199
+ if (!open) return element;
200
+ const close = element.match(/<\/template\s*>\s*$/i);
201
+ return element.slice(open[0].length, close ? close.index : element.length);
202
+ }
203
+
204
+ /**
205
+ * Split a child layout's raw source into its parts.
206
+ * @param {string} src
207
+ * @returns {{ parent: string, attrs: Record<string,string>, body: string }|null}
208
+ */
209
+ function splitChild(src) {
210
+ const tag = findTemplatedTag(src);
211
+ if (!tag) return null;
212
+
213
+ // data-* attributes on the templated element, data-template excepted
214
+ const attrs = templateDataAttrs(tag.attrs);
215
+
216
+ // The body: inside <body> when there is one, else inside <html>
217
+ let body;
218
+ const bodyOpen = src.match(/<body(?:\s[^>]*)?>/i);
219
+ if (bodyOpen) {
220
+ const start = bodyOpen.index + bodyOpen[0].length;
221
+ const end = src.toLowerCase().lastIndexOf('</body');
222
+ body = src.slice(start, end === -1 || end < start ? src.length : end);
223
+ } else {
224
+ const start = tag.index + tag.length;
225
+ const end = src.toLowerCase().lastIndexOf('</html');
226
+ body = src.slice(start, end === -1 || end < start ? src.length : end)
227
+ .replace(/<head(?:\s[^>]*)?>[\s\S]*?<\/head\s*>/i, '');
228
+ }
229
+
230
+ return { parent: tag.name.trim(), attrs, body: stripInfo(body) };
231
+ }
232
+
233
+ /**
234
+ * Render a page through a layout and its parents.
235
+ * @param {string} name - Layout name
236
+ * @param {Object} pageData - Variables, including `content` and `slot:x` keys
237
+ * @param {Object} opts
238
+ * @property {(name: string) => Promise<string|null>} opts.loadLayout
239
+ * @property {Object} [opts.data] - Site data, passed to `conditionals`
240
+ * @property {(html: string, pageData: Object, data: Object) => string} [opts.conditionals]
241
+ * @property {(message: string) => void} [opts.onMissingParent] - Told when a
242
+ * child layout's parent isn't found (the render still returns null).
243
+ * Defaults to a yellow console warning.
244
+ * @property {boolean} [opts.removeUnmatchedSlots=true] - For a plain layout
245
+ * only (no info block, no parent): remove unfilled `${slot:x}`. Layouts in
246
+ * the new format always remove them.
247
+ * @returns {Promise<string|null>} null when `name` (or a parent) is not found
248
+ */
249
+ export async function renderLayout(name, pageData, opts) {
250
+ return renderChain(name, pageData, opts, []);
251
+ }
252
+
253
+ async function renderChain(name, pageData, opts, chain) {
254
+ const { loadLayout, data = {}, conditionals = (html) => html, removeUnmatchedSlots = true } = opts;
255
+
256
+ if (chain.includes(name)) {
257
+ throw new LayoutChainError(`Layout cycle: ${[...chain, name].join(' → ')}`);
258
+ }
259
+ if (chain.length >= MAX_DEPTH) {
260
+ throw new LayoutChainError(`Layout chain too deep (more than ${MAX_DEPTH}): ${[...chain, name].join(' → ')}`);
261
+ }
262
+ chain = [...chain, name];
263
+
264
+ // Missing (or empty, as callers have always treated it): not found
265
+ const src = await loadLayout(name);
266
+ if (!src) {
267
+ if (chain.length > 1) {
268
+ const child = chain[chain.length - 2];
269
+ let message = `Layout "${child}" extends "${name}", which wasn't found`;
270
+ if (chain.length > 2) message += ` (${chain.join(' → ')})`;
271
+ const warn = opts.onMissingParent || ((m) => console.log(chalk.yellow(` ${m}`)));
272
+ warn(message);
273
+ }
274
+ return null;
275
+ }
276
+
277
+ const child = TEMPLATED_TAG.test(src) ? splitChild(src) : null;
278
+
279
+ // Base (or plain) layout
280
+ if (!child) {
281
+ // Early exit: a plain layout reached directly renders exactly as before
282
+ const plain = chain.length === 1 && !HAS_INFO.test(src);
283
+ const layout = conditionals(stripInfo(src), pageData, data);
284
+ return renderTemplate(layout, pageData, {
285
+ removeUnmatchedSlots: plain ? removeUnmatchedSlots : true,
286
+ });
287
+ }
288
+
289
+ // Child layout: fill each piece of the raw child source, then the parent
290
+ const { body, pieces } = splitChildSlots(child.body);
291
+ const fill = (piece) => renderTemplate(piece, pageData, { removeUnmatchedSlots: true });
292
+
293
+ const parentData = {};
294
+ for (const [key, value] of Object.entries(pageData)) {
295
+ if (!key.startsWith('slot:')) parentData[key] = value;
296
+ }
297
+ for (const [key, value] of Object.entries(child.attrs)) {
298
+ parentData[key] = renderTemplate(value, pageData);
299
+ }
300
+ parentData.content = fill(conditionals(body, pageData, data));
301
+ for (const { name: slot, element } of pieces) {
302
+ // The hook sees the whole <template slot …> element, attributes included
303
+ const rendered = fill(innerOf(conditionals(element, pageData, data)).trim());
304
+ if (rendered.trim()) parentData[`slot:${slot}`] = rendered;
305
+ else delete parentData[`slot:${slot}`];
306
+ }
307
+
308
+ return renderChain(child.parent, parentData, opts, chain);
309
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * @file serialize.js
3
+ * @description Write a layout tree (see tree.js) as canonical format-1 HTML:
4
+ * two-space indent, one block per line, the info block first as pretty
5
+ * JSON, double-quoted attributes in a fixed order (data-template,
6
+ * data-page-layout, the rest as the tree has them, then data-repeat,
7
+ * data-if, data-unless), text blocks on one line. Component inner HTML,
8
+ * comments, picture sources and inline script and style text are written
9
+ * exactly as the tree holds them.
10
+ */
11
+
12
+ const INDENT = ' ';
13
+
14
+ const escapeAttr = (value) => String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
15
+ const escapeMarkup = (text) => text
16
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\u00a0/g, '&nbsp;');
17
+ // A text run is literal: a `${` in it must not become a placeholder
18
+ const escapeText = (text) => escapeMarkup(text).replace(/\$\{/g, '&#36;{');
19
+
20
+ /** ` name="value"` for each pair. */
21
+ const attrString = (pairs) => pairs.map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join('');
22
+
23
+ /** A data-repeat value from its parts. */
24
+ function repeatValue({ source, pipes = [], alias, index }) {
25
+ return `${[source, ...pipes].join(' | ')} as ${alias}${index ? `, ${index}` : ''}`;
26
+ }
27
+
28
+ /**
29
+ * The attributes of a block or item, in canonical order.
30
+ * @param {Object} node - has `attrs` and optional `repeat`, `if`, `unless`
31
+ * @param {Array<[string, string]>} [lead] - attributes that go first
32
+ */
33
+ function blockAttrs(node, lead = []) {
34
+ const pairs = [...lead, ...(node.attrs || [])];
35
+ if (node.repeat) pairs.push(['data-repeat', repeatValue(node.repeat)]);
36
+ if (node.if !== undefined) pairs.push(['data-if', node.if]);
37
+ if (node.unless !== undefined) pairs.push(['data-unless', node.unless]);
38
+ return attrString(pairs);
39
+ }
40
+
41
+ /** The info block's lines, JSON indented with the script. */
42
+ function infoLines(info, indent) {
43
+ const json = JSON.stringify(info, null, 2).replace(/</g, '\\u003c');
44
+ return [
45
+ `${indent}<script type="application/json" data-layout-info>`,
46
+ ...json.split('\n').map(line => indent + line),
47
+ `${indent}</script>`,
48
+ ];
49
+ }
50
+
51
+ // INLINE
52
+ // -----------------------------
53
+ function inlineHtml(runs = []) {
54
+ return runs.map((run) => {
55
+ if ('field' in run) return `\${${run.field}}`;
56
+ if ('text' in run) return escapeText(run.text);
57
+ if ('component' in run) return `<${run.component}${attrString(run.attrs || [])}>${run.html ?? ''}</${run.component}>`;
58
+ const open = `<${run.tag}${attrString(run.attrs || [])}>`;
59
+ if (run.tag === 'br' || run.tag === 'img') return open;
60
+ return `${open}${inlineHtml(run.inline)}</${run.tag}>`;
61
+ }).join('');
62
+ }
63
+
64
+ // HEAD
65
+ // -----------------------------
66
+ function headLine(item, indent) {
67
+ if (item.slot) return `${indent}\${slot:${item.slot}}`;
68
+ const open = `<${item.tag}${blockAttrs(item)}>`;
69
+ if (item.tag === 'title') return `${indent}${open}${escapeMarkup(item.text ?? '').replace(/&gt;/g, '>')}</title>`;
70
+ if (item.tag === 'script' || item.tag === 'style') return `${indent}${open}${item.text ?? ''}</${item.tag}>`;
71
+ return indent + open;
72
+ }
73
+
74
+ // BLOCKS
75
+ // -----------------------------
76
+ /** Open tag, children one level in, close tag; or one line when empty. */
77
+ function wrap(open, close, children, indent) {
78
+ if (children.length === 0) return [`${indent}${open}${close}`];
79
+ return [`${indent}${open}`, ...children, `${indent}${close}`];
80
+ }
81
+
82
+ function blockLines(block, indent) {
83
+ const inner = indent + INDENT;
84
+ switch (block.type) {
85
+ case 'content':
86
+ return [`${indent}\${content}`];
87
+ case 'slot':
88
+ return [`${indent}\${slot:${block.name}}`];
89
+ case 'comment':
90
+ return [`${indent}<!--${block.text}-->`];
91
+ case 'text':
92
+ return [`${indent}<${block.tag}${blockAttrs(block)}>${inlineHtml(block.inline)}</${block.tag}>`];
93
+ case 'image':
94
+ if (block.tag === 'picture') return [`${indent}<picture${blockAttrs(block)}>${block.html ?? ''}</picture>`];
95
+ return [`${indent}<img${blockAttrs(block)}>`];
96
+ case 'container':
97
+ return wrap(`<${block.tag}${blockAttrs(block)}>`, `</${block.tag}>`, blocksLines(block.body, inner), indent);
98
+ case 'menu':
99
+ return wrap(`<${block.tag}${blockAttrs(block)}>`, `</${block.tag}>`,
100
+ (block.items || []).flatMap(item => itemLines(item, inner)), indent);
101
+ case 'include':
102
+ return [`${indent}<div${blockAttrs(block, [['data-include', block.path]])}></div>`];
103
+ case 'component':
104
+ return [`${indent}<${block.tag}${blockAttrs(block)}>${block.html ?? ''}</${block.tag}>`];
105
+ default:
106
+ throw new Error(`serializeLayout: unknown block type "${block.type}"`);
107
+ }
108
+ }
109
+
110
+ function itemLines(item, indent) {
111
+ const open = `<li${blockAttrs(item)}>`;
112
+ if (item.body) return wrap(open, '</li>', blocksLines(item.body, indent + INDENT), indent);
113
+ return [`${indent}${open}${inlineHtml(item.inline)}</li>`];
114
+ }
115
+
116
+ const blocksLines = (blocks = [], indent) => blocks.flatMap(block => blockLines(block, indent));
117
+
118
+ function slotLines(slot, indent) {
119
+ const open = `<template${blockAttrs(slot, [['slot', slot.name]])}>`;
120
+ const children = slot.name === 'head'
121
+ ? (slot.body || []).map(item => headLine(item, indent + INDENT))
122
+ : blocksLines(slot.body, indent + INDENT);
123
+ return wrap(open, '</template>', children, indent);
124
+ }
125
+
126
+ /**
127
+ * Write a layout tree as canonical format-1 HTML.
128
+ * @param {Object} tree - A tree from parseLayout (or edited from one)
129
+ * @returns {string}
130
+ */
131
+ export function serializeLayout(tree) {
132
+ const lines = [];
133
+ if (tree.kind === 'base') {
134
+ lines.push('<!doctype html>', `<html${attrString(tree.htmlAttrs || [])}>`, '<head>');
135
+ if (tree.info) lines.push(...infoLines(tree.info, INDENT));
136
+ lines.push(...(tree.head || []).map(item => headLine(item, INDENT)), '</head>');
137
+ const body = [];
138
+ if (tree.pageLayout !== null && tree.pageLayout !== undefined) body.push(['data-page-layout', tree.pageLayout]);
139
+ lines.push(`<body${attrString(body)}>`, ...blocksLines(tree.body, INDENT), '</body>', '</html>');
140
+ } else if (tree.kind === 'child') {
141
+ // Variables are raw strings, as render.js reads them: only `"` is escaped
142
+ const vars = (tree.vars || []).map(([name, value]) =>
143
+ ` data-${name.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}="${String(value).replace(/"/g, '&quot;')}"`).join('');
144
+ const pageLayout = tree.pageLayout !== null && tree.pageLayout !== undefined
145
+ ? ` data-page-layout="${String(tree.pageLayout).replace(/"/g, '&quot;')}"` : '';
146
+ lines.push(`<body data-template="${escapeAttr(tree.parent ?? '')}"${pageLayout}${vars}>`);
147
+ if (tree.info) lines.push(...infoLines(tree.info, INDENT));
148
+ lines.push(...blocksLines(tree.body, INDENT));
149
+ for (const slot of tree.slots || []) lines.push(...slotLines(slot, INDENT));
150
+ lines.push('</body>');
151
+ } else {
152
+ lines.push('<!-- layout-fragment -->', ...blocksLines(tree.body, ''));
153
+ }
154
+ return `${lines.join('\n')}\n`;
155
+ }