cook-ssg 2.8.0 → 2.10.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.
package/README.md CHANGED
@@ -147,6 +147,7 @@ The build process performs the following steps, in this order:
147
147
  * Repeats elements for each item in collections (`[data-repeat]`, nesting supported)
148
148
  * Replaces custom elements and `[data-component]` elements with templates (nesting supported; flat or Declarative Shadow DOM)
149
149
  * Replaces ES6 template strings (`${}`) with front matter + global data
150
+ * Fills empty `<social-links>` elements with profile links from `config/social.json`
150
151
  * Rewrites `<img>` to responsive `<picture>` elements
151
152
  * Detects custom elements and manages component JS loading (`autoComponents` config)
152
153
  * Pre-renders Declarative Shadow DOM from a manifest (`dsd` config)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cook-ssg",
3
- "version": "2.8.0",
3
+ "version": "2.10.0",
4
4
  "description": "Cook your static pages into a beautifully performing site. Static site generation the web platform way.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,7 +11,8 @@
11
11
  ".": "./scripts/build.js",
12
12
  "./build": "./scripts/build.js",
13
13
  "./dev": "./scripts/dev.js",
14
- "./layouts": "./scripts/layouts.js"
14
+ "./layouts": "./scripts/layouts.js",
15
+ "./social": "./scripts/social/index.js"
15
16
  },
16
17
  "files": [
17
18
  "bin/",
package/scripts/build.js CHANGED
@@ -38,6 +38,7 @@ import processHtmlFrontmatter from './plugins/process-html-frontmatter.js';
38
38
  import replaceInclude from './plugins/replace-include.js';
39
39
  import replaceInline from './plugins/replace-inline.js';
40
40
  import replaceMissingExternalLinkProtocol from './plugins/replace-external-link-protocol.js';
41
+ import { socialData, fillSocialLinks } from './plugins/social-links.js';
41
42
  import replaceTemplateStrings from './plugins/replace-template-strings.js';
42
43
  import conditionalSections from './plugins/conditional-sections.js';
43
44
  import setActiveLinks from './plugins/set-active-links.js';
@@ -107,6 +108,9 @@ class Build {
107
108
  // PLUGIN: Programs: `programs` / `programAreas` data from config/programs.json
108
109
  await programsData({data});
109
110
 
111
+ // PLUGIN: Social: `social` data from config/social.json (or main.js `social`)
112
+ await socialData({data});
113
+
110
114
  // PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
111
115
  await optimizeImagesGenerate({store});
112
116
 
@@ -191,6 +195,9 @@ class Build {
191
195
  const templateData = file.frontMatter ? { ...data, ...file.frontMatter } : data;
192
196
  replaceTemplateStrings({file, data: templateData, allowType: ['.html', '.json', '.webmanifest']});
193
197
 
198
+ // PLUGIN: Fill empty <social-links> elements with the site's profile links
199
+ fillSocialLinks({file, data, allowType: ['.html']});
200
+
194
201
  // PLUGIN: Rewrite <img> to <picture> with responsive srcset
195
202
  await optimizeImagesRewrite({file, store, allowType: ['.html']});
196
203
 
package/scripts/dev.js CHANGED
@@ -173,3 +173,7 @@ browserSync.watch(themeJson).on('change', file => { rebuild(file); }).on('add',
173
173
  // config/programs.json (Vanilla Press) feeds the programs data: rebuild on change.
174
174
  const programsJson = `${process.cwd()}/config/programs.json`;
175
175
  browserSync.watch(programsJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
176
+
177
+ // config/social.json (Vanilla Press) feeds <social-links>: rebuild on change.
178
+ const socialJson = `${process.cwd()}/config/social.json`;
179
+ browserSync.watch(socialJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
@@ -1,9 +1,13 @@
1
1
  /**
2
2
  * @file layouts.js
3
3
  * @description Public entry point (`cook-ssg/layouts`): the layout checker,
4
- * the layout lister and the format constants.
4
+ * the layout lister, the layout tree (parse and serialize) and the format
5
+ * constants.
5
6
  */
6
7
 
7
8
  export { checkLayout } from './utils/layouts/check.js';
8
9
  export { listLayouts, loadSiteNames } from './utils/layouts/list.js';
10
+ export { parseLayout } from './utils/layouts/tree.js';
11
+ export { serializeLayout } from './utils/layouts/serialize.js';
12
+ export { layoutUsage } from './utils/layouts/usage.js';
9
13
  export { FORMAT, PAGE_LAYOUTS, DOCUMENT_FIELDS } from './utils/layouts/vocabulary.js';
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @file social-links.js
3
+ * @description Social accounts: reads config/social.json (or main.js `social`),
4
+ * exposes `social.accounts` / `social.allAccounts` data, and fills each empty
5
+ * `<social-links>` element with a `<ul>` of profile links at build time.
6
+ */
7
+
8
+ import chalk from 'chalk';
9
+ import Util from '../utils/util/util.js';
10
+ import { getSocial } from '../utils/config/config.js';
11
+ import { normalizeAccounts, renderSocialLinks } from '../social/index.js';
12
+
13
+ const TAG = '[social] ';
14
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
15
+ const SKIP_INSIDE = 'pre, code, template, textarea';
16
+
17
+ let visibleAccounts = [];
18
+
19
+ /** Set `social` on the data store when a social config exists. */
20
+ export async function socialData({ data }) {
21
+ visibleAccounts = [];
22
+ const raw = getSocial();
23
+ if (raw === undefined) return;
24
+ const { all, visible, warnings } = normalizeAccounts(raw);
25
+ for (const w of warnings) console.log(chalk.yellow(`${TAG}${w}`));
26
+ visibleAccounts = visible;
27
+ data.social = { ...(isObj(raw) ? raw : {}), accounts: visible, allAccounts: all };
28
+ }
29
+
30
+ /**
31
+ * Fill each `<social-links>` that has no element child. Leaves the page's bytes
32
+ * alone when it has no live `<social-links>`.
33
+ */
34
+ export function fillSocialLinks({ file, allowType }) {
35
+ if (!Util.isAllowedType({ file, allowType })) return;
36
+ if (typeof file.src !== 'string' || !file.src.includes('<social-links')) return;
37
+ const dom = Util.fileDom(file);
38
+ const live = [...dom.window.document.querySelectorAll('social-links')]
39
+ .filter((el) => !el.closest(SKIP_INSIDE) && el.children.length === 0);
40
+ let changed = false;
41
+ for (const el of live) {
42
+ const html = renderSocialLinks(visibleAccounts, { services: el.getAttribute('services') ?? undefined });
43
+ if (!html) continue;
44
+ el.innerHTML = html;
45
+ changed = true;
46
+ }
47
+ Util.commitDom(file, dom, changed);
48
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * @file accounts.js
3
+ * @description Parse and validate social account handles, build profile URLs and
4
+ * normalize the `accounts` list from config/social.json. Pure: no fs, no config.
5
+ */
6
+
7
+ import { serviceById } from './catalog.js';
8
+
9
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
10
+
11
+ const DOMAIN = /^(?=.{3,253}$)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
12
+ const GITHUB = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;
13
+ const MASTODON_USER = /^[A-Za-z0-9_](?:[A-Za-z0-9_.-]*[A-Za-z0-9_])?$/;
14
+ const LINKEDIN_SLUG = /^[A-Za-z0-9_%-]+$/;
15
+ const YOUTUBE = /^@[A-Za-z0-9._-]+$/;
16
+
17
+ /**
18
+ * If `s` is a pasted URL on `host` (optional `https?://` and `www.`, optional trailing
19
+ * slash), return the path after the host; otherwise null. Bare handles never match.
20
+ */
21
+ const urlPath = (s, host) => {
22
+ const m = s.match(new RegExp(`^(?:https?://)?(?:www\\.)?${host.replace(/\./g, '\\.')}/(.+?)/*$`, 'i'));
23
+ return m ? m[1] : null;
24
+ };
25
+
26
+ const fail = (error) => ({ error });
27
+
28
+ /** @param {string} v */
29
+ function isHttpsUrl(v) {
30
+ if (!/^https:\/\//i.test(v)) return false;
31
+ try {
32
+ return new URL(v).protocol === 'https:';
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Turn what a person typed (or pasted) into the stored handle.
40
+ * @param {string} service
41
+ * @param {string} input
42
+ * @returns {{ handle: string } | { error: string }}
43
+ */
44
+ export function parseHandle(service, input) {
45
+ if (typeof input !== 'string') return fail('Enter a handle');
46
+ const raw = input.trim();
47
+ if (!raw) return fail('Enter a handle');
48
+
49
+ switch (service) {
50
+ case 'bluesky': {
51
+ const m = (urlPath(raw, 'bsky.app') || '').match(/^profile\/([^/]+)$/i);
52
+ const handle = (m ? m[1] : raw).replace(/^@/, '').toLowerCase();
53
+ return DOMAIN.test(handle) ? { handle } : fail('Bluesky handles look like name.bsky.social');
54
+ }
55
+ case 'mastodon': {
56
+ const s = raw;
57
+ const m = s.match(/^(?:https?:\/\/)?([^/@\s]+)\/@([^/@]+)\/*$/i);
58
+ let user;
59
+ let instance;
60
+ if (m) {
61
+ [, instance, user] = m;
62
+ } else {
63
+ const parts = s.replace(/^@/, '').split('@');
64
+ if (parts.length !== 2) return fail('Mastodon handles look like @user@instance');
65
+ [user, instance] = parts;
66
+ }
67
+ instance = instance.toLowerCase();
68
+ if (!MASTODON_USER.test(user) || !DOMAIN.test(instance)) return fail('Mastodon handles look like @user@instance');
69
+ return { handle: `@${user}@${instance}` };
70
+ }
71
+ case 'github': {
72
+ const p = urlPath(raw, 'github.com');
73
+ const handle = (p && !p.includes('/') ? p : raw).replace(/^@/, '');
74
+ return GITHUB.test(handle) ? { handle } : fail('GitHub usernames are 1 to 39 letters, digits or single hyphens');
75
+ }
76
+ case 'linkedin': {
77
+ const m = (urlPath(raw, 'linkedin.com') || '').match(/^in\/([^/]+)$/i) || raw.match(/^in\/([^/]+?)\/*$/i);
78
+ const slug = m ? m[1] : raw;
79
+ return LINKEDIN_SLUG.test(slug) ? { handle: slug } : fail('Use the part after linkedin.com/in/');
80
+ }
81
+ case 'youtube': {
82
+ const p = urlPath(raw, 'youtube.com');
83
+ const handle = p && !p.includes('/') ? p : raw;
84
+ return YOUTUBE.test(handle) ? { handle } : fail('YouTube handles look like @name');
85
+ }
86
+ case 'link':
87
+ return isHttpsUrl(raw) ? { handle: raw } : fail('Links must start with https://');
88
+ default:
89
+ return fail(`Unknown service "${service}"`);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * The public profile URL for an account, or null when it can't be built.
95
+ * @param {{ service?: string, handle?: string, url?: string } | null | undefined} account
96
+ * @returns {string | null}
97
+ */
98
+ export function profileUrl(account) {
99
+ if (!isObj(account)) return null;
100
+ const { service, handle, url } = account;
101
+ if (service === 'link') return typeof url === 'string' && isHttpsUrl(url) ? url : null;
102
+ if (typeof handle !== 'string' || !handle) return null;
103
+ switch (service) {
104
+ case 'bluesky': return `https://bsky.app/profile/${handle}`;
105
+ case 'mastodon': {
106
+ const m = handle.match(/^@([^@]+)@([^@]+)$/);
107
+ return m ? `https://${m[2]}/@${m[1]}` : null;
108
+ }
109
+ case 'github': return `https://github.com/${handle}`;
110
+ case 'linkedin': return `https://www.linkedin.com/in/${handle}`;
111
+ case 'youtube': return `https://www.youtube.com/${handle}`;
112
+ default: return null;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Validate the raw contents of config/social.json. A bad entry is skipped with a
118
+ * warning; the rest still build.
119
+ * @param {unknown} raw
120
+ * @returns {{ all: object[], visible: object[], warnings: string[] }}
121
+ */
122
+ export function normalizeAccounts(raw) {
123
+ const warnings = [];
124
+ const all = [];
125
+ const list = isObj(raw) ? raw.accounts : undefined;
126
+ if (list !== undefined && !Array.isArray(list)) warnings.push('accounts must be an array; ignoring it');
127
+
128
+ (Array.isArray(list) ? list : []).forEach((entry, i) => {
129
+ const at = `accounts[${i}]`;
130
+ if (!isObj(entry)) return void warnings.push(`${at}: not an object; skipped`);
131
+ const svc = typeof entry.service === 'string' ? serviceById(entry.service) : undefined;
132
+ if (!svc) return void warnings.push(`${at}: unknown service ${JSON.stringify(entry.service)}; skipped`);
133
+
134
+ const hidden = entry.hidden === true;
135
+ if (svc.id === 'link') {
136
+ const label = typeof entry.label === 'string' ? entry.label.trim() : '';
137
+ const url = typeof entry.url === 'string' ? entry.url.trim() : '';
138
+ if (!label) return void warnings.push(`${at}: link needs a label; skipped`);
139
+ if (!isHttpsUrl(url)) return void warnings.push(`${at}: link url must be https:; skipped`);
140
+ all.push({ service: 'link', handle: '', url, name: label, icon: 'link', hidden });
141
+ return;
142
+ }
143
+
144
+ const parsed = parseHandle(svc.id, entry.handle);
145
+ if ('error' in parsed) return void warnings.push(`${at}: ${svc.id} handle ${JSON.stringify(entry.handle)}: ${parsed.error}; skipped`);
146
+ const account = {
147
+ service: svc.id,
148
+ handle: parsed.handle,
149
+ url: profileUrl({ service: svc.id, handle: parsed.handle }),
150
+ name: svc.name,
151
+ icon: svc.id,
152
+ hidden,
153
+ };
154
+ if (svc.id === 'bluesky' && typeof entry.did === 'string' && entry.did.startsWith('did:')) account.did = entry.did;
155
+ all.push(account);
156
+ });
157
+
158
+ return { all, visible: all.filter((a) => !a.hidden), warnings };
159
+ }
160
+
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @file catalog.js
3
+ * @description The services Cook knows how to link to: ids, display names and
4
+ * whether Vanilla Press can check a handle against the service. Pure data, no
5
+ * dependencies.
6
+ */
7
+
8
+ /** @type {Array<{ id: string, name: string, checkable: boolean }>} */
9
+ export const SERVICES = [
10
+ { id: 'bluesky', name: 'Bluesky', checkable: true },
11
+ { id: 'mastodon', name: 'Mastodon', checkable: true },
12
+ { id: 'github', name: 'GitHub', checkable: true },
13
+ { id: 'linkedin', name: 'LinkedIn', checkable: false },
14
+ { id: 'youtube', name: 'YouTube', checkable: false },
15
+ { id: 'link', name: 'Link', checkable: false },
16
+ ];
17
+
18
+ /** @param {string} id */
19
+ export const serviceById = (id) => SERVICES.find((s) => s.id === id);
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @file index.js
3
+ * @description Public entry for `cook-ssg/social`: the service catalog, account
4
+ * parsing and the profile-links renderer. Pure and dependency-free.
5
+ */
6
+
7
+ export { SERVICES } from './catalog.js';
8
+ export { parseHandle, profileUrl, normalizeAccounts } from './accounts.js';
9
+ export { renderSocialLinks } from './render.js';
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @file render.js
3
+ * @description Render normalized accounts as the `<ul>` of profile links that
4
+ * goes inside `<social-links>`. Pure: no fs, no config.
5
+ */
6
+
7
+ const escapeHtml = (s) =>
8
+ String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
9
+
10
+ /**
11
+ * @param {Array<{ service: string, url: string, name: string, icon?: string }>} accounts
12
+ * @param {{ services?: string, variant?: string }} [options] `variant` is for CSS and
13
+ * is copied onto the element by the fill step; it does not change the list.
14
+ * @returns {string} the `<ul>…</ul>`, or '' when nothing matches
15
+ */
16
+ export function renderSocialLinks(accounts, { services } = {}) {
17
+ if (!Array.isArray(accounts)) return '';
18
+ const wanted = typeof services === 'string' && services.trim()
19
+ ? new Set(services.split(',').map((s) => s.trim()).filter(Boolean))
20
+ : null;
21
+ const items = accounts
22
+ .filter((a) => a && a.url && (!wanted || wanted.has(a.service)))
23
+ .map((a) => {
24
+ const rel = a.service === 'mastodon' ? ' rel="me"' : '';
25
+ return `<li><a href="${escapeHtml(a.url)}"${rel}><span class="social-icon" data-service="${escapeHtml(a.service)}" aria-hidden="true"></span><span>${escapeHtml(a.name)}</span></a></li>`;
26
+ });
27
+ return items.length ? `<ul>${items.join('')}</ul>` : '';
28
+ }
@@ -49,6 +49,21 @@ function getPrograms() {
49
49
  }
50
50
  }
51
51
 
52
+ // config/social.json (written by Vanilla Press): the site's social accounts; main.js `social` wins when defined
53
+ const socialJsonPath = `${cwd}/config/social.json`;
54
+
55
+ /** The social config. Re-read on every call, like getTheme. */
56
+ function getSocial() {
57
+ if (userConfig.social !== undefined) return userConfig.social;
58
+ if (!fs.existsSync(socialJsonPath)) return undefined;
59
+ try {
60
+ return JSON.parse(fs.readFileSync(socialJsonPath, 'utf8'));
61
+ } catch (err) {
62
+ console.log(chalk.yellow(`[social] config/social.json: ${err.message}`));
63
+ return undefined;
64
+ }
65
+ }
66
+
52
67
 
53
68
  // DEFINE DEFAULT CONFIG
54
69
  // -----------------------------
@@ -349,7 +364,7 @@ const config = mergeConfigs(defaultConfig, userConfig);
349
364
  export default config;
350
365
 
351
366
  // Named exports for destructuring imports
352
- export { getTheme, getPrograms };
367
+ export { getTheme, getPrograms, getSocial };
353
368
  export const {
354
369
  activeLink,
355
370
  autoComponents,
@@ -13,16 +13,18 @@ import {
13
13
  } from './vocabulary.js';
14
14
 
15
15
  // `${…}` placeholders, including `${{…}}` so expressions are caught
16
- const PLACEHOLDER = /\$\{([^}]*)\}/g;
17
- const PLAIN_KEY = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/;
18
- const SLOT_KEY = /^slot:([\w-]+)$/;
16
+ export const PLACEHOLDER = /\$\{([^}]*)\}/g;
17
+ export const PLAIN_KEY = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/;
18
+ export const SLOT_KEY = /^slot:([\w-]+)$/;
19
19
  // "source | pipe:arg as item[, index]" (same grammar as repeat-collection)
20
- const REPEAT = /^(.+?)\s+as\s+(\w+)(?:\s*,\s*(\w+))?$/;
20
+ export const REPEAT = /^(.+?)\s+as\s+(\w+)(?:\s*,\s*(\w+))?$/;
21
21
  const PIPE = /^(limit|offset)\s*:\s*\d+$/;
22
22
  const PAGE_LAYOUT_FIELD = '${pageLayout}';
23
23
 
24
- const tagOf = (el) => el.tagName.toLowerCase();
25
- const isBlank = (node) => node.nodeType === 8 || (node.nodeType === 3 && !node.textContent.trim());
24
+ export const tagOf = (el) => el.tagName.toLowerCase();
25
+ export const isBlank = (node) => node.nodeType === 8 || (node.nodeType === 3 && !node.textContent.trim());
26
+ /** An include block: an empty `<div data-include>`. */
27
+ export const isIncludeElement = (el) => tagOf(el) === 'div' && el.hasAttribute('data-include');
26
28
 
27
29
  /**
28
30
  * Best-effort scan for slots and fields, used for every layout (plain or
@@ -380,7 +382,7 @@ class Checker {
380
382
  }
381
383
 
382
384
  isInclude(el) {
383
- return tagOf(el) === 'div' && el.hasAttribute('data-include');
385
+ return isIncludeElement(el);
384
386
  }
385
387
 
386
388
  include(el, ctx) {
@@ -0,0 +1,158 @@
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
+ // Invisible characters are written as references, so they show in the file
16
+ const INVISIBLE_REFS = { '\u00a0': '&nbsp;', '\u00ad': '&shy;', '\u200b': '&#8203;', '\u2060': '&#8288;' };
17
+ const escapeMarkup = (text) => text
18
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
19
+ .replace(/[\u00a0\u00ad\u200b\u2060]/g, (c) => INVISIBLE_REFS[c]);
20
+ // A text run is literal: a `${` in it must not become a placeholder
21
+ const escapeText = (text) => escapeMarkup(text).replace(/\$\{/g, '&#36;{');
22
+
23
+ /** ` name="value"` for each pair. */
24
+ const attrString = (pairs) => pairs.map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join('');
25
+
26
+ /** A data-repeat value from its parts. */
27
+ function repeatValue({ source, pipes = [], alias, index }) {
28
+ return `${[source, ...pipes].join(' | ')} as ${alias}${index ? `, ${index}` : ''}`;
29
+ }
30
+
31
+ /**
32
+ * The attributes of a block or item, in canonical order.
33
+ * @param {Object} node - has `attrs` and optional `repeat`, `if`, `unless`
34
+ * @param {Array<[string, string]>} [lead] - attributes that go first
35
+ */
36
+ function blockAttrs(node, lead = []) {
37
+ const pairs = [...lead, ...(node.attrs || [])];
38
+ if (node.repeat) pairs.push(['data-repeat', repeatValue(node.repeat)]);
39
+ if (node.if !== undefined) pairs.push(['data-if', node.if]);
40
+ if (node.unless !== undefined) pairs.push(['data-unless', node.unless]);
41
+ return attrString(pairs);
42
+ }
43
+
44
+ /** The info block's lines, JSON indented with the script. */
45
+ function infoLines(info, indent) {
46
+ const json = JSON.stringify(info, null, 2).replace(/</g, '\\u003c');
47
+ return [
48
+ `${indent}<script type="application/json" data-layout-info>`,
49
+ ...json.split('\n').map(line => indent + line),
50
+ `${indent}</script>`,
51
+ ];
52
+ }
53
+
54
+ // INLINE
55
+ // -----------------------------
56
+ function inlineHtml(runs = []) {
57
+ return runs.map((run) => {
58
+ if ('field' in run) return `\${${run.field}}`;
59
+ if ('text' in run) return escapeText(run.text);
60
+ if ('component' in run) return `<${run.component}${attrString(run.attrs || [])}>${run.html ?? ''}</${run.component}>`;
61
+ const open = `<${run.tag}${attrString(run.attrs || [])}>`;
62
+ if (run.tag === 'br' || run.tag === 'img') return open;
63
+ return `${open}${inlineHtml(run.inline)}</${run.tag}>`;
64
+ }).join('');
65
+ }
66
+
67
+ // HEAD
68
+ // -----------------------------
69
+ function headLine(item, indent) {
70
+ if (item.slot) return `${indent}\${slot:${item.slot}}`;
71
+ const open = `<${item.tag}${blockAttrs(item)}>`;
72
+ if (item.tag === 'title') return `${indent}${open}${escapeMarkup(item.text ?? '').replace(/&gt;/g, '>')}</title>`;
73
+ if (item.tag === 'script' || item.tag === 'style') return `${indent}${open}${item.text ?? ''}</${item.tag}>`;
74
+ return indent + open;
75
+ }
76
+
77
+ // BLOCKS
78
+ // -----------------------------
79
+ /** Open tag, children one level in, close tag; or one line when empty. */
80
+ function wrap(open, close, children, indent) {
81
+ if (children.length === 0) return [`${indent}${open}${close}`];
82
+ return [`${indent}${open}`, ...children, `${indent}${close}`];
83
+ }
84
+
85
+ function blockLines(block, indent) {
86
+ const inner = indent + INDENT;
87
+ switch (block.type) {
88
+ case 'content':
89
+ return [`${indent}\${content}`];
90
+ case 'slot':
91
+ return [`${indent}\${slot:${block.name}}`];
92
+ case 'comment':
93
+ return [`${indent}<!--${block.text}-->`];
94
+ case 'text':
95
+ return [`${indent}<${block.tag}${blockAttrs(block)}>${inlineHtml(block.inline)}</${block.tag}>`];
96
+ case 'image':
97
+ if (block.tag === 'picture') return [`${indent}<picture${blockAttrs(block)}>${block.html ?? ''}</picture>`];
98
+ return [`${indent}<img${blockAttrs(block)}>`];
99
+ case 'container':
100
+ return wrap(`<${block.tag}${blockAttrs(block)}>`, `</${block.tag}>`, blocksLines(block.body, inner), indent);
101
+ case 'menu':
102
+ return wrap(`<${block.tag}${blockAttrs(block)}>`, `</${block.tag}>`,
103
+ (block.items || []).flatMap(item => itemLines(item, inner)), indent);
104
+ case 'include':
105
+ return [`${indent}<div${blockAttrs(block, [['data-include', block.path]])}></div>`];
106
+ case 'component':
107
+ return [`${indent}<${block.tag}${blockAttrs(block)}>${block.html ?? ''}</${block.tag}>`];
108
+ default:
109
+ throw new Error(`serializeLayout: unknown block type "${block.type}"`);
110
+ }
111
+ }
112
+
113
+ function itemLines(item, indent) {
114
+ const open = `<li${blockAttrs(item)}>`;
115
+ if (item.body) return wrap(open, '</li>', blocksLines(item.body, indent + INDENT), indent);
116
+ return [`${indent}${open}${inlineHtml(item.inline)}</li>`];
117
+ }
118
+
119
+ const blocksLines = (blocks = [], indent) => blocks.flatMap(block => blockLines(block, indent));
120
+
121
+ function slotLines(slot, indent) {
122
+ const open = `<template${blockAttrs(slot, [['slot', slot.name]])}>`;
123
+ const children = slot.name === 'head'
124
+ ? (slot.body || []).map(item => headLine(item, indent + INDENT))
125
+ : blocksLines(slot.body, indent + INDENT);
126
+ return wrap(open, '</template>', children, indent);
127
+ }
128
+
129
+ /**
130
+ * Write a layout tree as canonical format-1 HTML.
131
+ * @param {Object} tree - A tree from parseLayout (or edited from one)
132
+ * @returns {string}
133
+ */
134
+ export function serializeLayout(tree) {
135
+ const lines = [];
136
+ if (tree.kind === 'base') {
137
+ lines.push('<!doctype html>', `<html${attrString(tree.htmlAttrs || [])}>`, '<head>');
138
+ if (tree.info) lines.push(...infoLines(tree.info, INDENT));
139
+ lines.push(...(tree.head || []).map(item => headLine(item, INDENT)), '</head>');
140
+ const body = [];
141
+ if (tree.pageLayout !== null && tree.pageLayout !== undefined) body.push(['data-page-layout', tree.pageLayout]);
142
+ lines.push(`<body${attrString(body)}>`, ...blocksLines(tree.body, INDENT), '</body>', '</html>');
143
+ } else if (tree.kind === 'child') {
144
+ // Variables are raw strings, as render.js reads them: only `"` is escaped
145
+ const vars = (tree.vars || []).map(([name, value]) =>
146
+ ` data-${name.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}="${String(value).replace(/"/g, '&quot;')}"`).join('');
147
+ const pageLayout = tree.pageLayout !== null && tree.pageLayout !== undefined
148
+ ? ` data-page-layout="${String(tree.pageLayout).replace(/"/g, '&quot;')}"` : '';
149
+ lines.push(`<body data-template="${escapeAttr(tree.parent ?? '')}"${pageLayout}${vars}>`);
150
+ if (tree.info) lines.push(...infoLines(tree.info, INDENT));
151
+ lines.push(...blocksLines(tree.body, INDENT));
152
+ for (const slot of tree.slots || []) lines.push(...slotLines(slot, INDENT));
153
+ lines.push('</body>');
154
+ } else {
155
+ lines.push('<!-- layout-fragment -->', ...blocksLines(tree.body, ''));
156
+ }
157
+ return `${lines.join('\n')}\n`;
158
+ }
@@ -0,0 +1,522 @@
1
+ /**
2
+ * @file tree.js
3
+ * @description Parse a correct format-1 layout (or include fragment) into a
4
+ * layout tree: plain JSON that an editor can change and `serializeLayout`
5
+ * can write back. Only layouts that `checkLayout` passes get a tree; the
6
+ * walk follows the checker's classification block by block.
7
+ *
8
+ * What the tree keeps exactly as written comes from the raw source, not the
9
+ * DOM: a component's inner HTML, a picture's sources, and the text of inline
10
+ * scripts and styles. Comments become comment blocks where a block may
11
+ * stand. A correct layout holding something the tree has no place for (a
12
+ * comment in <head>, a comment inside a text block, …) is refused with a
13
+ * problem rather than opened with that part lost.
14
+ */
15
+
16
+ import { parseLayoutSource, childrenOf } from './parse.js';
17
+ import {
18
+ checkLayout, PLACEHOLDER, SLOT_KEY, REPEAT, tagOf, isIncludeElement,
19
+ } from './check.js';
20
+ import {
21
+ TEXT_ELEMENTS, INLINE_ELEMENTS, CONTAINER_ELEMENTS, LAYOUT_WRAPPERS, MENU_ELEMENTS,
22
+ LAYOUT_ELEMENTS,
23
+ } from './vocabulary.js';
24
+ import { findTemplatedTag, templateDataAttrs } from './render.js';
25
+
26
+ const RAW_TEXT = new Set(['script', 'style', 'textarea', 'title']);
27
+ // Comments, declarations, and start/end tags whose attributes may quote `>`
28
+ const TOKEN = /<!--[\s\S]*?(?:-->|$)|<![^>]*>|<(\/?)([a-zA-Z][a-zA-Z0-9-]*)(?:"[^"]*"|'[^']*'|[^>"'])*>/g;
29
+ const FRAGMENT_MARKER = /^\s*<!--\s*layout-fragment\s*-->/;
30
+ const MARKER_TEXT = /^\s*layout-fragment\s*$/;
31
+ const SPACE = /[ \t\n\r\f]+/g;
32
+ // A character reference for `$` or `{`: decoded, it could read as `${…}`
33
+ const ENCODED_PLACEHOLDER = /&(?:#0*36|#x0*24|dollar|#0*123|#x0*7b|lbrace|lcub)(?![\w])/i;
34
+ // One attribute in a start tag, any quoting (as render.js reads them)
35
+ const ATTR = /([^\s"'>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
36
+ const camel = (attr) => attr.slice('data-'.length).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
37
+
38
+ const BLOCK_ATTRS = ['data-repeat', 'data-if', 'data-unless'];
39
+
40
+ // SOURCE OFFSETS
41
+ // -----------------------------
42
+ /**
43
+ * Every start and end tag in the source, in order. Comments and the raw
44
+ * text of script, style, textarea and title are skipped.
45
+ * @param {string} html
46
+ * @returns {Array<{ name: string, close: boolean, start: number, end: number }>}
47
+ */
48
+ function scanTags(html) {
49
+ const lower = html.toLowerCase();
50
+ const tags = [];
51
+ TOKEN.lastIndex = 0;
52
+ let m;
53
+ while ((m = TOKEN.exec(html))) {
54
+ if (!m[2]) continue;
55
+ const name = m[2].toLowerCase();
56
+ const close = m[1] === '/';
57
+ tags.push({ name, close, start: m.index, end: TOKEN.lastIndex });
58
+ if (!close && RAW_TEXT.has(name)) {
59
+ const at = lower.indexOf(`</${name}`, TOKEN.lastIndex);
60
+ TOKEN.lastIndex = at === -1 ? html.length : at;
61
+ }
62
+ }
63
+ return tags;
64
+ }
65
+
66
+ /**
67
+ * Pair each element, in document order, with the next unused start tag of
68
+ * the same name (as parse.js does for lines), so an element's raw inner
69
+ * HTML can be sliced from the source.
70
+ * @param {string} html
71
+ * @param {Element} root
72
+ * @returns {{ inner: (el: Element) => string|null, openTag: (el: Element) => string|null }}
73
+ * the raw inner source and the raw start tag, or null when unpaired
74
+ */
75
+ function sourceIndex(html, root) {
76
+ const tags = scanTags(html);
77
+ const starts = new Map();
78
+ tags.forEach((tag, i) => {
79
+ if (tag.close) return;
80
+ if (!starts.has(tag.name)) starts.set(tag.name, []);
81
+ starts.get(tag.name).push(i);
82
+ });
83
+
84
+ const index = new WeakMap();
85
+ const used = new Map();
86
+ const visit = (el) => {
87
+ const name = tagOf(el);
88
+ const queue = starts.get(name) || [];
89
+ const next = used.get(name) || 0;
90
+ if (next < queue.length) {
91
+ index.set(el, queue[next]);
92
+ used.set(name, next + 1);
93
+ }
94
+ for (const node of childrenOf(el)) if (node.nodeType === 1) visit(node);
95
+ };
96
+ visit(root);
97
+
98
+ const openTag = (el) => {
99
+ const i = index.get(el);
100
+ return i === undefined ? null : html.slice(tags[i].start, tags[i].end);
101
+ };
102
+ const inner = (el) => {
103
+ const i = index.get(el);
104
+ if (i === undefined) return null;
105
+ const open = tags[i];
106
+ let depth = 1;
107
+ for (let j = i + 1; j < tags.length; j++) {
108
+ if (tags[j].name !== open.name) continue;
109
+ depth += tags[j].close ? -1 : 1;
110
+ if (depth === 0) return html.slice(open.end, tags[j].start);
111
+ }
112
+ return null;
113
+ };
114
+ return { inner, openTag };
115
+ }
116
+
117
+ // HELPERS
118
+ // -----------------------------
119
+ const isComponent = (el) => tagOf(el).includes('-') && !LAYOUT_ELEMENTS.includes(tagOf(el));
120
+
121
+ const attrList = (el, skip = []) => Array.from(el.attributes)
122
+ .filter(a => !skip.includes(a.name.toLowerCase()))
123
+ .map(a => [a.name, a.value]);
124
+
125
+ /**
126
+ * Read a data-repeat expression the way the checker does.
127
+ * @param {string} expr
128
+ * @returns {{ source: string, pipes: string[], alias: string, index?: string }}
129
+ */
130
+ function parseRepeat(expr) {
131
+ const match = expr.trim().match(REPEAT);
132
+ const [source, ...pipes] = match[1].split('|').map(p => p.trim());
133
+ const repeat = { source, pipes, alias: match[2] };
134
+ if (match[3]) repeat.index = match[3];
135
+ return repeat;
136
+ }
137
+
138
+ /** Conditions on an element: `{ if?, unless? }`. */
139
+ function conditions(el) {
140
+ const out = {};
141
+ if (el.hasAttribute('data-if')) out.if = el.getAttribute('data-if');
142
+ if (el.hasAttribute('data-unless')) out.unless = el.getAttribute('data-unless');
143
+ return out;
144
+ }
145
+
146
+ /**
147
+ * Text with fields: split into `{ text }` and `{ field }` runs, whitespace
148
+ * collapsed.
149
+ * @param {string} text - decoded text
150
+ * @returns {Array<{ text: string }|{ field: string }>}
151
+ */
152
+ function textRuns(text) {
153
+ const runs = [];
154
+ let pos = 0;
155
+ for (const match of text.matchAll(PLACEHOLDER)) {
156
+ if (match.index > pos) runs.push({ text: text.slice(pos, match.index).replace(SPACE, ' ') });
157
+ runs.push({ field: match[1].trim() });
158
+ pos = match.index + match[0].length;
159
+ }
160
+ if (pos < text.length) runs.push({ text: text.slice(pos).replace(SPACE, ' ') });
161
+ return runs;
162
+ }
163
+
164
+ /** Merge adjacent text runs; trim the outer edges of a whole run list. */
165
+ function tidyRuns(runs, { trim }) {
166
+ const out = [];
167
+ for (const run of runs) {
168
+ const last = out.at(-1);
169
+ if ('text' in run && last && 'text' in last) last.text += run.text;
170
+ else out.push(run);
171
+ }
172
+ if (trim) {
173
+ const first = out[0];
174
+ if (first && 'text' in first) first.text = first.text.replace(/^ /, '');
175
+ const last = out.at(-1);
176
+ if (last && 'text' in last) last.text = last.text.replace(/ $/, '');
177
+ }
178
+ return out.filter(run => !('text' in run) || run.text !== '');
179
+ }
180
+
181
+ // BUILDER
182
+ // -----------------------------
183
+ class TreeBuilder {
184
+ constructor(html, parsed) {
185
+ this.html = html;
186
+ this.parsed = parsed;
187
+ this.document = parsed.document;
188
+ this.source = sourceIndex(html, this.document.documentElement);
189
+ this.problems = [];
190
+ this.keptComments = new Set();
191
+ this.rawElements = new Set();
192
+ }
193
+
194
+ refuse(el, message) {
195
+ this.problems.push({ line: this.parsed.lineOf(el), message });
196
+ }
197
+
198
+ raw(el) {
199
+ this.rawElements.add(el);
200
+ const inner = this.source.inner(el);
201
+ return inner ?? el.innerHTML;
202
+ }
203
+
204
+ build() {
205
+ const { kind } = this.parsed;
206
+ const tree = {
207
+ kind,
208
+ info: this.info(),
209
+ parent: kind === 'child' ? this.parsed.parent : null,
210
+ vars: [],
211
+ pageLayout: null,
212
+ htmlAttrs: [],
213
+ head: [],
214
+ body: [],
215
+ slots: [],
216
+ };
217
+ if (kind === 'base') this.base(tree);
218
+ else if (kind === 'child') this.child(tree);
219
+ else tree.body = this.blocks(this.document.body, { skipMarker: FRAGMENT_MARKER.test(this.html) });
220
+ this.sweepComments();
221
+ this.sweepEncodedPlaceholders();
222
+ if (kind === 'child') this.checkVars();
223
+ return tree;
224
+ }
225
+
226
+ info() {
227
+ const raw = this.parsed.info;
228
+ if (!raw) return null;
229
+ const { format, label, description, abstract, slots, ...rest } = raw;
230
+ const info = { format, label: label ?? '' };
231
+ if (description !== undefined) info.description = description;
232
+ if (abstract !== undefined) info.abstract = abstract;
233
+ info.slots = slots ?? {};
234
+ return Object.assign(info, rest);
235
+ }
236
+
237
+ // ROOTS
238
+ // -----------------------------
239
+ base(tree) {
240
+ const { documentElement, head, body } = this.document;
241
+ tree.htmlAttrs = attrList(documentElement);
242
+ if (head && head.attributes.length) this.refuse(head, `<head> attributes can't be edited here (${head.attributes[0].name})`);
243
+ tree.head = head ? this.headItems(head) : [];
244
+
245
+ if (body.hasAttribute('data-page-layout')) tree.pageLayout = body.getAttribute('data-page-layout');
246
+ const extra = attrList(body, ['data-page-layout']);
247
+ if (extra.length) this.refuse(body, `<body> attributes besides data-page-layout can't be edited here (${extra.map(a => a[0]).join(', ')})`);
248
+
249
+ tree.body = this.blocks(body, { region: true });
250
+ }
251
+
252
+ child(tree) {
253
+ const { documentElement, body } = this.document;
254
+ const templated = documentElement.hasAttribute('data-template') ? documentElement : body;
255
+
256
+ // The body's variables, read as render.js reads them
257
+ const tag = findTemplatedTag(this.html);
258
+ const vars = tag
259
+ ? Object.entries(templateDataAttrs(tag.attrs))
260
+ : attrList(templated, ['data-template']).filter(([name]) => /^data-/.test(name))
261
+ .map(([name, value]) => [camel(name), value]);
262
+ this.templated = { el: templated, read: Boolean(tag), vars };
263
+ const pageLayout = vars.find(([name]) => name === 'pageLayout');
264
+ tree.pageLayout = pageLayout ? pageLayout[1] : null;
265
+ tree.vars = vars.filter(([name]) => name !== 'pageLayout');
266
+
267
+ for (const node of childrenOf(body)) {
268
+ if (node.nodeType === 1 && tagOf(node) === 'template') tree.slots.push(this.slotTemplate(node));
269
+ }
270
+ tree.body = this.blocks(body, { skipTemplates: true });
271
+ }
272
+
273
+ slotTemplate(template) {
274
+ const slot = {
275
+ name: template.getAttribute('slot').trim(),
276
+ attrs: attrList(template, ['slot', 'data-if', 'data-unless']),
277
+ ...conditions(template),
278
+ };
279
+ slot.body = slot.name === 'head' ? this.headItems(template, { slotHead: true }) : this.blocks(template);
280
+ return slot;
281
+ }
282
+
283
+ // HEAD
284
+ // -----------------------------
285
+ headItems(parent, { slotHead = false } = {}) {
286
+ const items = [];
287
+ for (const node of childrenOf(parent)) {
288
+ if (node.nodeType === 3) {
289
+ if (!slotHead && node.textContent.trim() === '${slot:head}') items.push({ slot: 'head' });
290
+ continue;
291
+ }
292
+ if (node.nodeType !== 1 || node.hasAttribute('data-layout-info')) continue;
293
+ items.push(this.headItem(node));
294
+ }
295
+ return items;
296
+ }
297
+
298
+ headItem(el) {
299
+ const tag = tagOf(el);
300
+ const item = { tag, attrs: attrList(el, ['data-if', 'data-unless']), ...conditions(el) };
301
+ if (tag === 'title') item.text = el.textContent;
302
+ else if (tag === 'script' || tag === 'style') item.text = this.raw(el);
303
+ return item;
304
+ }
305
+
306
+ // BLOCKS
307
+ // -----------------------------
308
+ /**
309
+ * The blocks inside a block container. Placeholders in text become
310
+ * content and slot blocks; comments become comment blocks.
311
+ */
312
+ blocks(parent, { region = false, skipTemplates = false, skipMarker = false } = {}) {
313
+ const out = [];
314
+ let first = true;
315
+ for (const node of childrenOf(parent)) {
316
+ if (node.nodeType === 3) {
317
+ for (const match of node.textContent.matchAll(PLACEHOLDER)) {
318
+ const key = match[1].trim();
319
+ const slot = key.match(SLOT_KEY);
320
+ if (key === 'content') out.push({ type: 'content', attrs: [] });
321
+ else if (slot) out.push({ type: 'slot', name: slot[1], attrs: [] });
322
+ }
323
+ if (node.textContent.trim()) first = false;
324
+ continue;
325
+ }
326
+ if (node.nodeType === 8) {
327
+ this.keptComments.add(node);
328
+ if (!(skipMarker && first && MARKER_TEXT.test(node.data))) {
329
+ out.push({ type: 'comment', attrs: [], text: node.data });
330
+ }
331
+ first = false;
332
+ continue;
333
+ }
334
+ first = false;
335
+ if (node.nodeType !== 1) continue;
336
+ if (node.hasAttribute('data-layout-info') && tagOf(node) === 'script') continue;
337
+ if (skipTemplates && tagOf(node) === 'template') continue;
338
+ if (region && tagOf(node) === 'main') out.push(this.container(node));
339
+ else out.push(this.block(node));
340
+ }
341
+ return out;
342
+ }
343
+
344
+ /** Common fields: attributes (block attributes excepted), conditions, repeat. */
345
+ common(el, skip = []) {
346
+ const out = { attrs: attrList(el, [...BLOCK_ATTRS, ...skip]), ...conditions(el) };
347
+ if (el.hasAttribute('data-repeat')) out.repeat = parseRepeat(el.getAttribute('data-repeat'));
348
+ return out;
349
+ }
350
+
351
+ block(el) {
352
+ const name = tagOf(el);
353
+ if (name.includes('-')) {
354
+ if (LAYOUT_ELEMENTS.includes(name)) return this.container(el);
355
+ return { type: 'component', tag: name, ...this.common(el), html: this.raw(el) };
356
+ }
357
+ if (isIncludeElement(el)) {
358
+ return { type: 'include', path: el.getAttribute('data-include'), ...this.common(el, ['data-include']) };
359
+ }
360
+ if (MENU_ELEMENTS.includes(name)) return this.menu(el);
361
+ if (TEXT_ELEMENTS.includes(name)) {
362
+ return { type: 'text', tag: name, ...this.common(el), inline: this.inline(el, true) };
363
+ }
364
+ if (name === 'img') return { type: 'image', tag: 'img', ...this.common(el) };
365
+ if (name === 'picture') return { type: 'image', tag: 'picture', ...this.common(el), html: this.raw(el) };
366
+ // figure, sectioning, header/footer, div[data-layout]
367
+ return this.container(el);
368
+ }
369
+
370
+ container(el) {
371
+ return { type: 'container', tag: tagOf(el), ...this.common(el), body: this.blocks(el) };
372
+ }
373
+
374
+ menu(el) {
375
+ const items = [];
376
+ for (const node of childrenOf(el)) {
377
+ if (node.nodeType === 1) items.push(this.item(node));
378
+ }
379
+ return { type: 'menu', tag: tagOf(el), ...this.common(el), items };
380
+ }
381
+
382
+ /** An `li`: text-level content, or blocks, never both. */
383
+ item(li) {
384
+ const item = this.common(li);
385
+ let text = false;
386
+ let blocks = false;
387
+ let components = false;
388
+ for (const node of childrenOf(li)) {
389
+ if (node.nodeType === 3 && node.textContent.trim()) text = true;
390
+ else if (node.nodeType === 1 && INLINE_ELEMENTS.includes(tagOf(node))) text = true;
391
+ else if (node.nodeType === 1 && isComponent(node)) components = true;
392
+ else if (node.nodeType === 1) blocks = true;
393
+ }
394
+ // Components alone are blocks; beside text they are inline components
395
+ if (components && !text) blocks = true;
396
+ if (text && blocks) {
397
+ this.refuse(li, 'an <li> that mixes text and blocks can\'t be edited here (wrap the text in a <p>, or move the blocks out)');
398
+ item.inline = [];
399
+ } else if (blocks) {
400
+ item.body = this.blocks(li);
401
+ } else {
402
+ item.inline = this.inline(li, true);
403
+ }
404
+ return item;
405
+ }
406
+
407
+ // INLINE
408
+ // -----------------------------
409
+ inline(el, top = false) {
410
+ const runs = [];
411
+ for (const node of childrenOf(el)) {
412
+ if (node.nodeType === 3) runs.push(...textRuns(node.textContent));
413
+ else if (node.nodeType !== 1) continue; // comments: reported by the sweep
414
+ else if (INLINE_ELEMENTS.includes(tagOf(node))) {
415
+ const tag = tagOf(node);
416
+ if (tag === 'br' || tag === 'img') runs.push({ tag, attrs: attrList(node) });
417
+ else runs.push({ tag, attrs: attrList(node), inline: this.inline(node) });
418
+ } else {
419
+ // The checker allows only components here: kept whole, like a block component
420
+ runs.push({ component: tagOf(node), attrs: attrList(node), html: this.raw(node) });
421
+ }
422
+ }
423
+ return tidyRuns(runs, { trim: top });
424
+ }
425
+
426
+ // SOURCE CHECKS
427
+ // -----------------------------
428
+ /**
429
+ * Refuse an attribute whose source spells `$` or `{` as a character
430
+ * reference: the tree holds decoded values, and written back the value
431
+ * would become a live `${…}` placeholder. A title is checked the same way.
432
+ */
433
+ sweepEncodedPlaceholders() {
434
+ const visit = (el) => {
435
+ const open = this.source.openTag(el);
436
+ if (open && ENCODED_PLACEHOLDER.test(open)) {
437
+ ATTR.lastIndex = open.indexOf(' ') === -1 ? open.length : open.indexOf(' ');
438
+ let m;
439
+ while ((m = ATTR.exec(open))) {
440
+ const value = m[2] ?? m[3] ?? m[4] ?? '';
441
+ if (ENCODED_PLACEHOLDER.test(value)) {
442
+ this.refuse(el, `the ${m[1]} attribute of <${tagOf(el)}> spells $ or { as a character reference, which the layout editor can't keep; write it plainly`);
443
+ }
444
+ }
445
+ }
446
+ if (tagOf(el) === 'title' && ENCODED_PLACEHOLDER.test(this.source.inner(el) ?? '')) {
447
+ this.refuse(el, '<title> spells $ or { as a character reference, which the layout editor can\'t keep; write it plainly');
448
+ }
449
+ if (this.rawElements.has(el)) return;
450
+ for (const node of childrenOf(el)) if (node.nodeType === 1) visit(node);
451
+ };
452
+ visit(this.document.documentElement);
453
+ }
454
+
455
+ /**
456
+ * Refuse a child's body variables unless render.js reads each one exactly
457
+ * as the DOM does (a `>` or `"` in a value, or a character reference,
458
+ * would be lost or changed on the way back).
459
+ */
460
+ checkVars() {
461
+ const { el, read, vars } = this.templated;
462
+ if (!read) {
463
+ this.refuse(el, 'the data-template tag can\'t be read the way Cook renders it');
464
+ return;
465
+ }
466
+ const raw = new Map(vars);
467
+ const dom = new Map();
468
+ const names = new Map();
469
+ for (const { name, value } of Array.from(el.attributes)) {
470
+ const lower = name.toLowerCase();
471
+ if (!lower.startsWith('data-') || lower === 'data-template') continue;
472
+ dom.set(camel(lower), value);
473
+ names.set(camel(lower), lower);
474
+ }
475
+ for (const key of new Set([...raw.keys(), ...dom.keys()])) {
476
+ // A `"` can't be written back inside the canonical double quotes
477
+ if (raw.get(key) !== dom.get(key) || dom.get(key).includes('"')) {
478
+ const attr = names.get(key) ?? `data-${key.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}`;
479
+ this.refuse(el, `the ${attr} value can't be kept by the layout editor (avoid >, " and character references in body variables)`);
480
+ }
481
+ }
482
+ }
483
+
484
+ // COMMENTS
485
+ // -----------------------------
486
+ /** Refuse any comment the tree didn't keep (outside raw-kept elements). */
487
+ sweepComments() {
488
+ const visit = (parent, owner) => {
489
+ const holder = parent.nodeType === 1 ? childrenOf(parent) : Array.from(parent.childNodes);
490
+ for (const node of holder) {
491
+ if (node.nodeType === 8 && !this.keptComments.has(node)) {
492
+ this.refuse(owner, `a comment here can't be kept by the layout editor (<!--${node.data.slice(0, 30)}-->); move it between blocks or remove it`);
493
+ } else if (node.nodeType === 1 && !this.rawElements.has(node)) {
494
+ visit(node, node);
495
+ }
496
+ }
497
+ };
498
+ visit(this.document, this.document.documentElement);
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Parse a format-1 layout or include fragment into a layout tree.
504
+ * @param {string} html - The layout's source
505
+ * @param {Object} [opts]
506
+ * @property {boolean} [opts.fragment=false] - Parse the source as an include fragment
507
+ * @property {string[]} [opts.fields=[]] - Extra known field names (see checkLayout)
508
+ * @property {string[]} [opts.lists=[]] - Extra list-source roots (see checkLayout)
509
+ * @returns {{ ok: boolean, tree: Object|null, problems: Array<{ line: number, message: string }> }}
510
+ * `tree` only when the layout passes checkLayout and the tree can hold all of it
511
+ */
512
+ export function parseLayout(html, { fragment = false, fields = [], lists = [] } = {}) {
513
+ const check = checkLayout(html, { fragment, fields, lists });
514
+ if (!check.ok) return { ok: false, tree: null, problems: check.problems };
515
+
516
+ const builder = new TreeBuilder(html, parseLayoutSource(html, { fragment }));
517
+ const tree = builder.build();
518
+ if (builder.problems.length) {
519
+ return { ok: false, tree: null, problems: builder.problems.sort((a, b) => a.line - b.line) };
520
+ }
521
+ return { ok: true, tree, problems: [] };
522
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @file usage.js
3
+ * @description Finds which pages use which layouts, and which layouts are
4
+ * built on which, so a tool can show "used by N pages" before an edit.
5
+ */
6
+
7
+ import { existsSync, statSync, promises as fs } from 'node:fs';
8
+ import path from 'node:path';
9
+ import { pathToFileURL } from 'node:url';
10
+ import matter from 'gray-matter';
11
+
12
+ import { findTemplatedTag } from './render.js';
13
+
14
+ // Folders under src/ that are not pages
15
+ const SKIP_DIRS = new Set(['layouts', 'includes', 'components']);
16
+
17
+ /** Import config/main.js the way list.js does; null when absent or broken. */
18
+ async function loadMain(siteDir) {
19
+ const file = path.join(siteDir, 'config', 'main.js');
20
+ if (!existsSync(file)) return null;
21
+ try {
22
+ const mod = await import(`${pathToFileURL(file).href}?t=${statSync(file).mtimeMs}`);
23
+ let value = mod.default ?? mod;
24
+ if (typeof value === 'function') value = await value();
25
+ return value && typeof value === 'object' ? value : null;
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ /** The area paths whose subfolders are program folders (valid or colliding). */
32
+ async function loadProgramAreas(siteDir, buildOnlyPaths) {
33
+ const file = path.join(siteDir, 'config', 'programs.json');
34
+ if (!existsSync(file)) return [];
35
+ try {
36
+ const raw = JSON.parse(await fs.readFile(file, 'utf8'));
37
+ const { normalizePrograms } = await import('../../plugins/programs.js');
38
+ const { areas, protectedAreas } = normalizePrograms(raw, { buildOnlyPaths });
39
+ return [...areas, ...protectedAreas].map(a => a.path);
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+
45
+ async function readDirSafe(dir) {
46
+ try {
47
+ return await fs.readdir(dir, { withFileTypes: true });
48
+ } catch {
49
+ return [];
50
+ }
51
+ }
52
+
53
+ /** Page files (.html, .md) under src/, as src-relative paths. */
54
+ async function findPages(srcDir, programAreas) {
55
+ const found = [];
56
+ const walk = async (dir, rel) => {
57
+ for (const entry of await readDirSafe(dir)) {
58
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
59
+ if (entry.isDirectory()) {
60
+ if (!rel && SKIP_DIRS.has(entry.name)) continue;
61
+ // <area>/<program>/... is a program folder
62
+ if (rel && !rel.includes('/') && programAreas.includes(rel)) continue;
63
+ await walk(path.join(dir, entry.name), childRel);
64
+ } else if (entry.isFile() && /\.(html|md)$/.test(entry.name)) {
65
+ found.push(childRel);
66
+ }
67
+ }
68
+ };
69
+ await walk(srcDir, '');
70
+ return found.sort();
71
+ }
72
+
73
+ const bareName = (value) => (typeof value === 'string' && value.trim()
74
+ ? value.trim().replace(/\.html$/, '')
75
+ : null);
76
+
77
+ /** The layout name a page file uses, or null. */
78
+ function pageLayout(rel, source, defaultLayout) {
79
+ const isMarkdown = rel.endsWith('.md');
80
+ let body = source;
81
+ let layout = null;
82
+ if (isMarkdown || source.startsWith('---')) {
83
+ const parsed = matter(source);
84
+ body = parsed.content;
85
+ layout = bareName(parsed.data?.layout);
86
+ }
87
+ if (isMarkdown) return layout ?? bareName(defaultLayout);
88
+ const tag = findTemplatedTag(body);
89
+ return bareName(tag?.name) ?? layout;
90
+ }
91
+
92
+ function add(map, name, value) {
93
+ (map[name] ??= []).push(value);
94
+ }
95
+
96
+ /**
97
+ * Which pages use which layouts, and which layouts are built on which.
98
+ * Never throws; files that can't be read are skipped.
99
+ * @param {string} siteDir - The site's root directory (contains src/)
100
+ * @returns {Promise<{ pages: Record<string, string[]>, layouts: Record<string, string[]> }>}
101
+ * `pages[name]`: site-relative paths (`src/blog/a.md`) of pages using layout `name`;
102
+ * `layouts[name]`: names of layouts whose `data-template` is `name`
103
+ */
104
+ export async function layoutUsage(siteDir) {
105
+ const pages = {};
106
+ const layouts = {};
107
+ try {
108
+ const main = await loadMain(siteDir);
109
+ const defaultLayout = main?.markdown?.layout ?? null;
110
+ const programAreas = await loadProgramAreas(siteDir, main?.buildOnlyPaths ?? []);
111
+ const srcDir = path.join(siteDir, 'src');
112
+
113
+ for (const rel of await findPages(srcDir, programAreas)) {
114
+ try {
115
+ const name = pageLayout(rel, await fs.readFile(path.join(srcDir, rel), 'utf8'), defaultLayout);
116
+ if (name) add(pages, name, `src/${rel}`);
117
+ } catch { /* unreadable or malformed: skipped */ }
118
+ }
119
+
120
+ const layoutDir = path.join(srcDir, 'layouts');
121
+ for (const entry of await readDirSafe(layoutDir)) {
122
+ let name = null;
123
+ let file = null;
124
+ if (entry.isFile() && entry.name.endsWith('.html')) {
125
+ name = entry.name.slice(0, -5);
126
+ file = entry.name;
127
+ } else if (entry.isDirectory() && existsSync(path.join(layoutDir, entry.name, 'index.html'))) {
128
+ name = entry.name;
129
+ file = `${entry.name}/index.html`;
130
+ }
131
+ if (!name) continue;
132
+ try {
133
+ const parent = bareName(findTemplatedTag(await fs.readFile(path.join(layoutDir, file), 'utf8'))?.name);
134
+ if (parent) add(layouts, parent, name);
135
+ } catch { /* skipped */ }
136
+ }
137
+ for (const list of Object.values(layouts)) list.sort();
138
+ } catch { /* never throws */ }
139
+ return { pages, layouts };
140
+ }