cook-ssg 2.6.0 → 2.8.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,667 @@
1
+ /**
2
+ * @file check.js
3
+ * @description The format-1 layout checker. Says whether a layout (or an
4
+ * include fragment) is correct, why not (with line numbers), and what it
5
+ * offers: its slots, fields and parent.
6
+ */
7
+
8
+ import { parseLayoutSource, childrenOf } from './parse.js';
9
+ import {
10
+ FORMAT, PAGE_LAYOUTS, DOCUMENT_FIELDS, HEAD_ELEMENTS, HEAD_SLOT_ELEMENTS,
11
+ TEXT_ELEMENTS, INLINE_ELEMENTS, CONTAINER_ELEMENTS, LAYOUT_WRAPPERS, MENU_ELEMENTS,
12
+ LAYOUT_ELEMENTS, BODY_REGIONS, ELEMENT_ATTRS, isGlobalAttr,
13
+ } from './vocabulary.js';
14
+
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-]+)$/;
19
+ // "source | pipe:arg as item[, index]" (same grammar as repeat-collection)
20
+ const REPEAT = /^(.+?)\s+as\s+(\w+)(?:\s*,\s*(\w+))?$/;
21
+ const PIPE = /^(limit|offset)\s*:\s*\d+$/;
22
+ const PAGE_LAYOUT_FIELD = '${pageLayout}';
23
+
24
+ const tagOf = (el) => el.tagName.toLowerCase();
25
+ const isBlank = (node) => node.nodeType === 8 || (node.nodeType === 3 && !node.textContent.trim());
26
+
27
+ /**
28
+ * Best-effort scan for slots and fields, used for every layout (plain or
29
+ * not) so callers can offer regions for any layout.
30
+ * @param {string} html
31
+ * @returns {{ slots: string[], fields: string[] }}
32
+ */
33
+ function scanSource(html) {
34
+ const source = html
35
+ .replace(/<!--[\s\S]*?-->/g, '')
36
+ .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, '');
37
+
38
+ const aliases = new Set();
39
+ for (const [, , expr] of source.matchAll(/data-repeat\s*=\s*(["'])(.*?)\1/g)) {
40
+ const match = expr.trim().match(REPEAT);
41
+ if (match) [match[2], match[3]].filter(Boolean).forEach(a => aliases.add(a));
42
+ }
43
+
44
+ const slots = new Set();
45
+ const fields = new Set();
46
+ for (const [, raw] of source.matchAll(PLACEHOLDER)) {
47
+ const key = raw.trim();
48
+ const slot = key.match(SLOT_KEY);
49
+ if (slot) {
50
+ if (slot[1] !== 'head') slots.add(slot[1]);
51
+ } else if (key !== 'content' && PLAIN_KEY.test(key) && !aliases.has(key.split('.')[0])) {
52
+ fields.add(key);
53
+ }
54
+ }
55
+ return { slots: [...slots], fields: [...fields] };
56
+ }
57
+
58
+ class Checker {
59
+ constructor(html, parsed, { fields, lists }) {
60
+ this.html = html;
61
+ this.repeatRead = new WeakSet();
62
+ this.parsed = parsed;
63
+ this.document = parsed.document;
64
+ this.kind = parsed.kind;
65
+ this.known = new Set([...DOCUMENT_FIELDS, ...fields]);
66
+ this.listRoots = new Set(lists);
67
+ this.problems = [];
68
+ this.slotUses = new Map();
69
+ this.contents = [];
70
+ this.declaredSlots = null;
71
+ this.lineStarts = [0];
72
+ for (let i = 0; i < html.length; i++) if (html.charCodeAt(i) === 10) this.lineStarts.push(i + 1);
73
+ }
74
+
75
+ // REPORTING
76
+ // -----------------------------
77
+ problem(el, message) {
78
+ this.problems.push({ line: this.parsed.lineOf(el), message });
79
+ }
80
+
81
+ /** Report at the first occurrence of `needle` at or after el's line. */
82
+ problemAt(el, needle, message) {
83
+ const elLine = this.parsed.lineOf(el);
84
+ const index = this.html.indexOf(needle, this.lineStarts[elLine - 1] ?? 0);
85
+ let line = elLine;
86
+ if (index !== -1) {
87
+ line = this.lineStarts.findLastIndex(start => start <= index) + 1;
88
+ }
89
+ this.problems.push({ line, message });
90
+ }
91
+
92
+ // ENTRY
93
+ // -----------------------------
94
+ run() {
95
+ const script = this.checkInfo();
96
+ if (this.kind === 'base') this.checkBase(script);
97
+ else if (this.kind === 'child') this.checkChild(script);
98
+ else this.checkFragment();
99
+ this.checkContent();
100
+ this.checkSlotDeclarations(script);
101
+ this.problems.sort((a, b) => a.line - b.line);
102
+ }
103
+
104
+ // INFO BLOCK
105
+ // -----------------------------
106
+ checkInfo() {
107
+ const scripts = Array.from(this.document.querySelectorAll('script[data-layout-info]'));
108
+ const [script, ...extra] = scripts;
109
+ for (const other of extra) this.problem(other, 'a layout has only one info block');
110
+ if (!script) return null;
111
+
112
+ const { info, infoError } = this.parsed;
113
+ if (script.getAttribute('type') !== 'application/json') {
114
+ this.problem(script, 'the info block needs type="application/json"');
115
+ }
116
+ if (infoError) {
117
+ this.problem(script, `the info block isn't valid JSON (${infoError})`);
118
+ return script;
119
+ }
120
+ if (!info || typeof info !== 'object' || Array.isArray(info)) {
121
+ this.problem(script, 'the info block must be a JSON object');
122
+ return script;
123
+ }
124
+ if (info.format !== FORMAT) {
125
+ this.problem(script, `the info block says format ${JSON.stringify(info.format)}; this Cook reads format ${FORMAT}`);
126
+ return script;
127
+ }
128
+ const slots = info.slots ?? {};
129
+ if (!slots || typeof slots !== 'object' || Array.isArray(slots)) {
130
+ this.problem(script, 'the info block\'s "slots" must be an object');
131
+ return script;
132
+ }
133
+ this.declaredSlots = new Set(Object.keys(slots));
134
+ return script;
135
+ }
136
+
137
+ checkSlotDeclarations(script) {
138
+ if (!this.declaredSlots) return;
139
+ for (const [name, el] of this.slotUses) {
140
+ if (!this.declaredSlots.has(name)) {
141
+ this.problemAt(el, `\${slot:${name}}`, `slot "${name}" is used but not declared in the info block's "slots"`);
142
+ }
143
+ }
144
+ for (const name of this.declaredSlots) {
145
+ if (!this.slotUses.has(name)) {
146
+ this.problem(script, `slot "${name}" is declared in the info block but the layout never uses \${slot:${name}}`);
147
+ }
148
+ }
149
+ }
150
+
151
+ checkContent() {
152
+ if (this.kind === 'fragment') return;
153
+ const where = this.kind === 'base' ? 'inside <main>' : 'in the child <body>';
154
+ if (this.contents.length === 0) {
155
+ this.problem(this.document.body, `the layout has no \${content} (it needs exactly one, ${where})`);
156
+ }
157
+ for (const { el } of this.contents.slice(1)) {
158
+ this.problemAt(el, '${content}', '${content} appears more than once (a layout has exactly one)');
159
+ }
160
+ }
161
+
162
+ // BASE
163
+ // -----------------------------
164
+ checkBase(script) {
165
+ const { head, body } = this.document;
166
+ if (script && script.parentNode !== head) {
167
+ this.problem(script, 'in a base layout the info block goes in <head>');
168
+ }
169
+ this.checkAnyAttrs(this.document.documentElement, this.rootCtx());
170
+ if (head) this.checkHead(head);
171
+
172
+ const ctx = this.rootCtx();
173
+ this.checkPageLayout(body, true);
174
+ this.checkAnyAttrs(body, ctx, ['data-page-layout']);
175
+
176
+ const counts = { main: 0, nav: 0 };
177
+ for (const node of childrenOf(body)) {
178
+ if (node.nodeType !== 1) {
179
+ this.blockText(node, body, ctx);
180
+ continue;
181
+ }
182
+ const name = tagOf(node);
183
+ if (node === script) continue;
184
+ if (this.isInclude(node)) {
185
+ this.include(node, ctx);
186
+ } else if (BODY_REGIONS.includes(name)) {
187
+ if (name in counts) counts[name]++;
188
+ this.container(node, { ...ctx, inMain: name === 'main' }, { repeat: false });
189
+ } else {
190
+ this.problem(node, `<${name}> can't be a direct child of <body> (use header, nav, main, aside, footer or an include)`);
191
+ }
192
+ }
193
+ if (counts.main !== 1) {
194
+ this.problem(body, `a base layout needs exactly one <main> in <body> (found ${counts.main})`);
195
+ }
196
+ if (counts.nav > 2) {
197
+ this.problem(body, `a base layout has at most two <nav> in <body> (found ${counts.nav})`);
198
+ }
199
+ }
200
+
201
+ checkHead(head) {
202
+ const ctx = this.rootCtx();
203
+ let slotText = null;
204
+ for (const node of childrenOf(head)) {
205
+ if (node.nodeType === 8) continue;
206
+ if (node.nodeType === 3) {
207
+ const text = node.textContent.trim();
208
+ if (!text) continue;
209
+ if (text === '${slot:head}' && !slotText) {
210
+ slotText = node;
211
+ this.useSlot('head', head);
212
+ } else {
213
+ this.problemAt(head, text, `text isn't allowed in <head> ("${text.slice(0, 40)}")`);
214
+ }
215
+ continue;
216
+ }
217
+ const name = tagOf(node);
218
+ if (slotText) {
219
+ this.problem(node, '${slot:head} must be the last thing in <head>');
220
+ slotText = false;
221
+ }
222
+ if (!HEAD_ELEMENTS.includes(name)) {
223
+ this.problem(node, `<${name}> isn't allowed in <head> (use meta, link, title, script, style or base)`);
224
+ continue;
225
+ }
226
+ this.checkAnyAttrs(node, ctx);
227
+ if (name === 'title') this.fieldText(node.textContent, node, ctx);
228
+ }
229
+ }
230
+
231
+ checkPageLayout(body, allowField) {
232
+ if (!body.hasAttribute('data-page-layout')) return;
233
+ const value = body.getAttribute('data-page-layout').trim();
234
+ if (PAGE_LAYOUTS.includes(value) || (allowField && value === PAGE_LAYOUT_FIELD)) return;
235
+ const choices = PAGE_LAYOUTS.filter(Boolean).join(', ');
236
+ this.problem(body, `data-page-layout="${value}" isn't a VB page layout (use ${choices}${allowField ? ' or ${pageLayout}' : ''})`);
237
+ }
238
+
239
+ // CHILD
240
+ // -----------------------------
241
+ checkChild(script) {
242
+ const { body, documentElement } = this.document;
243
+ if (tagOf(documentElement) === 'html') {
244
+ this.checkAnyAttrs(documentElement, this.rootCtx());
245
+ const head = this.document.head;
246
+ for (const node of head ? childrenOf(head) : []) {
247
+ if (node.nodeType === 1) {
248
+ this.problem(node, 'a child layout has no <head>; fill the head slot with <template slot="head">');
249
+ }
250
+ }
251
+ }
252
+ const firstElement = childrenOf(body).find(n => n.nodeType === 1);
253
+ if (script && script !== firstElement) {
254
+ this.problem(script, 'in a child layout the info block is the first thing in <body>');
255
+ }
256
+
257
+ const ctx = this.rootCtx();
258
+ this.checkPageLayout(body, true);
259
+ this.checkAnyAttrs(body, ctx, ['data-page-layout']);
260
+
261
+ for (const node of childrenOf(body)) {
262
+ if (node === script) continue;
263
+ if (node.nodeType === 1 && tagOf(node) === 'template') this.slotTemplate(node, ctx);
264
+ else if (node.nodeType === 1) this.block(node, ctx);
265
+ else this.blockText(node, body, ctx);
266
+ }
267
+ }
268
+
269
+ slotTemplate(template, ctx) {
270
+ const name = (template.getAttribute('slot') || '').trim();
271
+ this.checkAttrs(template, ctx);
272
+ if (!name) {
273
+ this.problem(template, '<template> in a child layout needs a slot name (<template slot="name">)');
274
+ return;
275
+ }
276
+ if (name !== 'head') {
277
+ this.walkBlocks(template, { ...ctx, inSlotTemplate: true });
278
+ return;
279
+ }
280
+ for (const node of childrenOf(template)) {
281
+ if (isBlank(node)) continue;
282
+ if (node.nodeType === 3) {
283
+ this.problemAt(template, node.textContent.trim(), 'text isn\'t allowed in the head slot');
284
+ } else if (!HEAD_SLOT_ELEMENTS.includes(tagOf(node))) {
285
+ this.problem(node, `<${tagOf(node)}> isn't allowed in the head slot (use meta, link, script or style)`);
286
+ } else {
287
+ this.checkAnyAttrs(node, ctx);
288
+ }
289
+ }
290
+ }
291
+
292
+ // FRAGMENT
293
+ // -----------------------------
294
+ checkFragment() {
295
+ const { body } = this.document;
296
+ const ctx = this.rootCtx();
297
+ let wrappers = 0;
298
+ for (const node of childrenOf(body)) {
299
+ if (node.nodeType !== 1) {
300
+ this.blockText(node, body, ctx);
301
+ continue;
302
+ }
303
+ const name = tagOf(node);
304
+ if (['header', 'nav', 'footer'].includes(name)) {
305
+ wrappers++;
306
+ if (wrappers === 2) {
307
+ this.problem(node, 'a fragment has at most one header, nav or footer wrapper');
308
+ }
309
+ this.container(node, ctx, { repeat: false });
310
+ } else {
311
+ this.block(node, ctx);
312
+ }
313
+ }
314
+ }
315
+
316
+ // BLOCKS
317
+ // -----------------------------
318
+ rootCtx() {
319
+ return { aliases: new Set(), inMain: false, inSlotTemplate: false };
320
+ }
321
+
322
+ walkBlocks(parent, ctx) {
323
+ for (const node of childrenOf(parent)) {
324
+ if (node.nodeType === 1) this.block(node, ctx);
325
+ else this.blockText(node, parent, ctx);
326
+ }
327
+ }
328
+
329
+ block(el, ctx) {
330
+ const name = tagOf(el);
331
+
332
+ // data-repeat clones whatever element it sits on, so any block may carry it,
333
+ // components included (containers, menus and layout elements read it themselves).
334
+ if (el.hasAttribute('data-repeat') && !LAYOUT_ELEMENTS.includes(name) && !MENU_ELEMENTS.includes(name)
335
+ && !CONTAINER_ELEMENTS.includes(name) && !(LAYOUT_WRAPPERS.includes(name) && el.hasAttribute('data-layout'))) {
336
+ ctx = this.repeatScope(el, ctx);
337
+ this.repeatRead.add(el);
338
+ }
339
+
340
+ if (name.includes('-')) {
341
+ if (LAYOUT_ELEMENTS.includes(name)) {
342
+ const inner = this.repeatScope(el, ctx);
343
+ this.checkAnyAttrs(el, inner, ['data-repeat']);
344
+ this.walkBlocks(el, inner);
345
+ } else {
346
+ this.component(el, ctx);
347
+ }
348
+ return;
349
+ }
350
+
351
+ if (this.isInclude(el)) return this.include(el, ctx);
352
+ if (MENU_ELEMENTS.includes(name)) return this.menu(el, ctx);
353
+ if (TEXT_ELEMENTS.includes(name)) return this.textBlock(el, ctx);
354
+ if (name === 'img') return this.checkAttrs(el, ctx);
355
+ if (name === 'picture') return this.picture(el, ctx);
356
+ if (name === 'figure') return this.figure(el, ctx);
357
+ if (CONTAINER_ELEMENTS.includes(name) || (LAYOUT_WRAPPERS.includes(name) && el.hasAttribute('data-layout'))) {
358
+ return this.container(el, ctx, { repeat: true });
359
+ }
360
+
361
+ this.checkHandlers(el);
362
+ if (name === 'template') {
363
+ this.problem(el, '<template> is only allowed as <template slot="name"> at the top of a child layout\'s <body>');
364
+ } else if (LAYOUT_WRAPPERS.includes(name)) {
365
+ this.problem(el, `<${name}> isn't a layout block (add data-layout, or use a layout element)`);
366
+ } else {
367
+ this.problem(el, `<${name}> isn't a layout block`);
368
+ }
369
+ }
370
+
371
+ container(el, ctx, { repeat }) {
372
+ const inner = repeat ? this.repeatScope(el, ctx) : ctx;
373
+ this.checkAttrs(el, inner, repeat ? ['data-repeat'] : []);
374
+ this.walkBlocks(el, inner);
375
+ }
376
+
377
+ component(el, ctx) {
378
+ // Opaque: attributes are checked for handlers and fields, the inside is not
379
+ this.checkAnyAttrs(el, ctx);
380
+ }
381
+
382
+ isInclude(el) {
383
+ return tagOf(el) === 'div' && el.hasAttribute('data-include');
384
+ }
385
+
386
+ include(el, ctx) {
387
+ this.checkAttrs(el, ctx);
388
+ if (!childrenOf(el).every(isBlank)) {
389
+ this.problem(el, 'an include <div data-include> must be empty');
390
+ }
391
+ }
392
+
393
+ menu(el, ctx) {
394
+ const inner = this.repeatScope(el, ctx);
395
+ this.checkAttrs(el, inner, ['data-repeat']);
396
+ for (const node of childrenOf(el)) {
397
+ if (isBlank(node)) continue;
398
+ if (node.nodeType === 3) {
399
+ this.problemAt(el, node.textContent.trim(), `<${tagOf(el)}> holds only <li> items`);
400
+ } else if (tagOf(node) !== 'li') {
401
+ this.checkHandlers(node);
402
+ this.problem(node, `<${tagOf(node)}> can't be inside <${tagOf(el)}> (a menu holds only <li> items)`);
403
+ } else {
404
+ const item = this.repeatScope(node, inner);
405
+ this.repeatRead.add(node);
406
+ this.checkAttrs(node, item);
407
+ this.mixed(node, item);
408
+ }
409
+ }
410
+ }
411
+
412
+ /** An `li`: text-level content or blocks. */
413
+ mixed(el, ctx) {
414
+ for (const node of childrenOf(el)) {
415
+ if (node.nodeType === 3) this.fieldText(node.textContent, el, ctx);
416
+ else if (node.nodeType !== 1) continue;
417
+ else if (INLINE_ELEMENTS.includes(tagOf(node))) this.inline(node, ctx);
418
+ else this.block(node, ctx);
419
+ }
420
+ }
421
+
422
+ textBlock(el, ctx) {
423
+ this.checkAttrs(el, ctx);
424
+ this.walkInline(el, ctx);
425
+ }
426
+
427
+ walkInline(el, ctx) {
428
+ for (const node of childrenOf(el)) {
429
+ if (node.nodeType === 3) this.fieldText(node.textContent, el, ctx);
430
+ else if (node.nodeType !== 1) continue;
431
+ else if (INLINE_ELEMENTS.includes(tagOf(node))) this.inline(node, ctx);
432
+ else if (tagOf(node).includes('-')) this.component(node, ctx);
433
+ else {
434
+ this.checkHandlers(node);
435
+ this.problem(node, `<${tagOf(node)}> can't be inside <${tagOf(el)}> (only text and ${INLINE_ELEMENTS.join(', ')})`);
436
+ }
437
+ }
438
+ }
439
+
440
+ inline(el, ctx) {
441
+ this.checkAttrs(el, ctx);
442
+ this.walkInline(el, ctx);
443
+ }
444
+
445
+ picture(el, ctx) {
446
+ this.checkAttrs(el, ctx);
447
+ for (const node of childrenOf(el)) {
448
+ if (isBlank(node)) continue;
449
+ if (node.nodeType === 1 && ['source', 'img'].includes(tagOf(node))) this.checkAttrs(node, ctx);
450
+ else if (node.nodeType === 1) this.problem(node, `<${tagOf(node)}> can't be inside <picture> (only source and img)`);
451
+ else this.problemAt(el, node.textContent.trim(), '<picture> holds only source and img');
452
+ }
453
+ }
454
+
455
+ figure(el, ctx) {
456
+ this.checkAttrs(el, ctx);
457
+ for (const node of childrenOf(el)) {
458
+ if (isBlank(node)) continue;
459
+ const name = node.nodeType === 1 ? tagOf(node) : null;
460
+ if (name === 'img' || name === 'picture' || name === 'figcaption') this.block(node, ctx);
461
+ else if (name) this.problem(node, `<${name}> can't be inside <figure> (only img, picture and figcaption)`);
462
+ else this.problemAt(el, node.textContent.trim(), '<figure> holds only img, picture and figcaption');
463
+ }
464
+ }
465
+
466
+ // TEXT AND PLACEHOLDERS
467
+ // -----------------------------
468
+ /**
469
+ * Text directly inside a block container: only `${content}` and a lone
470
+ * `${slot:x}` may appear there.
471
+ */
472
+ blockText(node, parent, ctx) {
473
+ if (isBlank(node)) return;
474
+ const text = node.textContent;
475
+ let rest = text;
476
+ for (const match of text.matchAll(PLACEHOLDER)) {
477
+ const key = match[1].trim();
478
+ const slot = key.match(SLOT_KEY);
479
+ if (key === 'content') {
480
+ this.useContent(parent, ctx);
481
+ rest = rest.replace(match[0], '');
482
+ } else if (slot) {
483
+ this.useSlot(slot[1], parent);
484
+ const alone = text.trim() === match[0]
485
+ && childrenOf(parent).every(n => n === node || n.nodeType === 8 || (n.nodeType === 3 && !n.textContent.trim()));
486
+ if (!alone) this.problemAt(parent, match[0], `${match[0]} must be alone inside its element`);
487
+ rest = rest.replace(match[0], '');
488
+ }
489
+ }
490
+ rest = rest.trim();
491
+ if (rest) {
492
+ const shown = rest.length > 40 ? `${rest.slice(0, 40)}…` : rest;
493
+ this.problemAt(parent, rest.split(/\s/)[0], `text "${shown}" must be inside a text element (p, h1–h6, …)`);
494
+ }
495
+ }
496
+
497
+ /** Text where fields are allowed (text blocks, inline elements, title, attributes). */
498
+ fieldText(text, el, ctx, { attr = null } = {}) {
499
+ for (const match of text.matchAll(PLACEHOLDER)) {
500
+ const raw = match[1];
501
+ const key = raw.trim();
502
+ const where = attr ? ` in ${attr}=` : '';
503
+ if (raw.startsWith('{')) {
504
+ this.problemAt(el, match[0], `${match[0]}}${where} isn't allowed in a layout (use a plain field like \${title})`);
505
+ } else if (key === 'content' || SLOT_KEY.test(key)) {
506
+ if (key === 'content') this.useContent(el, ctx);
507
+ else this.useSlot(key.match(SLOT_KEY)[1], el);
508
+ this.problemAt(el, match[0], `${match[0]}${where} can't be inside text or an attribute; put it directly in a block`);
509
+ } else if (!PLAIN_KEY.test(key)) {
510
+ this.problemAt(el, match[0], `${match[0]}${where} isn't a plain field (layouts can't use expressions)`);
511
+ } else {
512
+ this.checkField(key, el, ctx, match[0]);
513
+ }
514
+ }
515
+ }
516
+
517
+ checkField(key, el, ctx, needle = key) {
518
+ const root = key.split('.')[0];
519
+ if (ctx.aliases.has(root) || this.known.has(root)) return;
520
+ this.problemAt(el, needle, `unknown field "${key}"`);
521
+ }
522
+
523
+ useContent(el, ctx) {
524
+ this.contents.push({ el });
525
+ if (this.kind === 'base' && !ctx.inMain) {
526
+ this.problemAt(el, '${content}', '${content} must be inside <main>');
527
+ }
528
+ if (this.kind === 'child' && ctx.inSlotTemplate) {
529
+ this.problemAt(el, '${content}', '${content} can\'t be inside a slot template');
530
+ }
531
+ }
532
+
533
+ useSlot(name, el) {
534
+ if (!this.slotUses.has(name)) this.slotUses.set(name, el);
535
+ }
536
+
537
+ // ATTRIBUTES
538
+ // -----------------------------
539
+ checkHandlers(el) {
540
+ for (const { name } of Array.from(el.attributes)) {
541
+ if (/^on/i.test(name)) {
542
+ this.problem(el, `<${tagOf(el)}> has an inline event handler (${name}); layouts can't carry script in attributes`);
543
+ }
544
+ }
545
+ }
546
+
547
+ /** Check attributes against the block vocabulary. */
548
+ checkAttrs(el, ctx, handled = []) {
549
+ this.attrs(el, ctx, handled, false);
550
+ }
551
+
552
+ /** Check attributes allowing any name (head items, components, layout elements, html/body). */
553
+ checkAnyAttrs(el, ctx, handled = []) {
554
+ this.attrs(el, ctx, handled, true);
555
+ }
556
+
557
+ attrs(el, ctx, handled, anyName) {
558
+ const name = tagOf(el);
559
+ const extra = ELEMENT_ATTRS[name] || [];
560
+ for (const { name: attr, value } of Array.from(el.attributes)) {
561
+ const lower = attr.toLowerCase();
562
+ if (/^on/.test(lower)) {
563
+ this.problem(el, `<${name}> has an inline event handler (${attr}); layouts can't carry script in attributes`);
564
+ continue;
565
+ }
566
+ if (handled.includes(lower)) continue;
567
+ if (lower === 'data-repeat' && this.repeatRead.has(el)) continue;
568
+ if (lower === 'data-repeat') {
569
+ this.problem(el, `<${name}> can't repeat here (data-repeat goes on a block, such as a container, a text block, a list, an li in a menu or a component)`);
570
+ continue;
571
+ }
572
+ if (lower === 'data-if' || lower === 'data-unless') {
573
+ this.condition(el, lower, value, ctx);
574
+ continue;
575
+ }
576
+ if (!anyName && !isGlobalAttr(lower) && !extra.includes(lower)) {
577
+ this.problem(el, `<${name}> can't carry the attribute "${attr}"`);
578
+ continue;
579
+ }
580
+ if (lower === 'data-layout-info') continue;
581
+ this.fieldText(value, el, ctx, { attr });
582
+ }
583
+ }
584
+
585
+ condition(el, attr, value, ctx) {
586
+ const key = value.trim();
587
+ const slot = key.match(SLOT_KEY);
588
+ if (slot) {
589
+ if (this.declaredSlots && !this.declaredSlots.has(slot[1])) {
590
+ this.problem(el, `${attr}="${key}" names a slot the info block doesn't declare`);
591
+ }
592
+ } else if (PLAIN_KEY.test(key)) {
593
+ this.checkField(key, el, ctx, `"${value}"`);
594
+ } else {
595
+ this.problem(el, `${attr}="${value}" must name one field, slot:name or item.field`);
596
+ }
597
+ }
598
+
599
+ /**
600
+ * Read an element's data-repeat (if any) and return the scope inside it.
601
+ */
602
+ repeatScope(el, ctx) {
603
+ if (!el.hasAttribute('data-repeat')) return ctx;
604
+ const expr = el.getAttribute('data-repeat').trim();
605
+ const match = expr.match(REPEAT);
606
+ if (!match) {
607
+ this.problem(el, `data-repeat="${expr}" must read "source as item" (optionally "| limit:N", "| offset:N", ", index")`);
608
+ return ctx;
609
+ }
610
+ const [source, ...pipes] = match[1].split('|').map(p => p.trim());
611
+ for (const pipe of pipes) {
612
+ if (!PIPE.test(pipe)) this.problem(el, `data-repeat pipe "${pipe}" isn't known (use limit:N or offset:N)`);
613
+ }
614
+ if (!this.isListSource(source, ctx)) {
615
+ this.problem(el, `data-repeat source "${source}" isn't a list (use collections.<name>, programs, programAreas.<area> or a data array)`);
616
+ }
617
+ const aliases = new Set(ctx.aliases);
618
+ aliases.add(match[2]);
619
+ if (match[3]) aliases.add(match[3]);
620
+ return { ...ctx, aliases };
621
+ }
622
+
623
+ isListSource(source, ctx) {
624
+ if (!PLAIN_KEY.test(source)) return false;
625
+ const parts = source.split('.');
626
+ const [root] = parts;
627
+ if (ctx.aliases.has(root)) return true;
628
+ if (root === 'collections' || root === 'programAreas') return parts.length === 2;
629
+ if (root === 'programs') return parts.length === 1;
630
+ return this.listRoots.has(root);
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Check a layout or include fragment against format 1.
636
+ * @param {string} html - The layout's source
637
+ * @param {Object} [opts]
638
+ * @property {string[]} [opts.fields=[]] - Extra known field names (site and declared fields)
639
+ * @property {string[]} [opts.lists=[]] - Extra list-source roots (top-level data arrays)
640
+ * @property {boolean} [opts.fragment=false] - Check the source as an include fragment
641
+ * @returns {{ ok: boolean, kind: 'base'|'child'|'fragment'|'plain', info: Object|null,
642
+ * parent: string|null, slots: string[], fields: string[], problems: Array<{ line: number, message: string }> }}
643
+ */
644
+ export function checkLayout(html, { fields = [], lists = [], fragment = false } = {}) {
645
+ const parsed = parseLayoutSource(html, { fragment });
646
+ const scan = scanSource(html);
647
+ const hasInfo = Boolean(parsed.document.querySelector('script[data-layout-info]'));
648
+
649
+ if (parsed.kind !== 'fragment' && !hasInfo) {
650
+ return {
651
+ ok: false, kind: 'plain', info: null, parent: parsed.parent,
652
+ slots: scan.slots, fields: scan.fields, problems: [],
653
+ };
654
+ }
655
+
656
+ const checker = new Checker(html, parsed, { fields, lists });
657
+ checker.run();
658
+ return {
659
+ ok: checker.problems.length === 0,
660
+ kind: parsed.kind,
661
+ info: parsed.info,
662
+ parent: parsed.parent,
663
+ slots: scan.slots,
664
+ fields: scan.fields,
665
+ problems: checker.problems,
666
+ };
667
+ }