All files / lib/compiler/ir build.js

95.14% Statements 686/721
81.35% Branches 192/236
100% Functions 18/18
95.14% Lines 686/721

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 2001x 2001x 2001x 328x 328x 328x 328x 328x 328x 328x 2450x 2450x 2450x 2450x 2450x 2450x 653x 11x 11x 653x 653x 653x 653x 2450x 2450x 1799x 1799x 2450x 2450x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 248x 248x 248x 248x 248x 1518x 1518x 1518x 11x 11x 11x 11x 1518x 2x 2x 2x 1518x 7x 7x 7x 1518x 7x 7x 7x 1518x 1421x 1518x 246x 246x 246x 245x 245x 246x 1518x 3x 248x 328x 328x 328x 328x 328x 328x 245x 245x 245x 177x 177x 245x 245x 245x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 253x 253x 253x 253x 253x 253x 253x 253x 253x 5x 5x 248x 248x 253x 3x 3x 245x 245x 245x 245x 253x     245x 245x 253x 7x 7x 7x 7x 7x 7x 7x 238x 253x 1x 1x 237x 253x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 253x 253x 511x 511x 511x 253x 253x 253x 253x 253x 248x 248x 8x     5x 5x 253x 328x 328x 328x 328x 328x 328x 294x 294x 294x 294x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 15x 15x 15x 1x 1x 14x 15x 328x 328x 328x 328x 328x 328x 328x 1443x 1443x 1443x 1443x 1443x 1443x 1443x 8636x 6x 6x 8636x 1437x 1443x 1473x 1295x 1446x 294x 294x 294x 294x 1001x 1001x 1001x 1416x 1x 1x 1x       1000x 1416x     1000x 1000x 1416x 15x 15x 15x 985x 1282x 914x 914x 914x 71x 71x 1473x 61x 61x 61x 61x 61x 61x 61x 61x 949x 10x 10x 10x 10x 10x 10x 1473x 1436x 1436x 1443x 328x 328x 328x 328x 328x 328x 133x 133x 133x 18x       18x 18x 18x 4x 17x 4x 4x 4x 4x             14x 10x 10x 18x 133x 133x 328x 328x 328x 328x 328x 328x 1576x 1576x 1576x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 22x 22x 22x 4x 4x 4x 8x 1x 1x 5x 1x 1x 1x 1x 1x 1x 22x 328x 328x 328x 328x 328x 328x 328x 328x 18x 18x 18x 18x 18x 18x 35x 35x 35x 35x 35x 35x 2x 2x 2x       2x 2x 33x 35x 35x 35x 35x 33x 35x 22x     22x 22x     22x 22x 22x 22x 22x 11x 19x 9x     9x 9x 9x 9x 9x 2x 2x 2x 17x 17x 18x 328x 328x 328x 328x 328x 328x 328x 53x 53x 53x 53x 53x 53x 128x 4x     4x 4x 4x 124x 124x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 12x 12x 12x 12x 12x 41x 41x 41x 41x 41x 41x 41x 11x 11x     11x 10x 10x 11x 11x 30x 30x 12x 12x 12x 328x 328x 328x 328x 328x 328x 328x 328x 328x 328x 546x 2x 2x 544x 546x 546x 546x 546x 546x     544x 544x 544x 544x 544x 544x 544x 2232x 2232x 2232x 4065x 4065x 4065x 2360x 2360x 1784x 2347x 576x 576x 2360x 2360x 2360x 1705x 4065x 2x 1x 1x 1x 1x 1x 1703x 4065x 4065x 4065x 4065x 31x 31x 1672x 4063x 18x 18x 18x 18x 18x 1654x 4065x 1x 1x 1653x 4063x 53x 53x 53x 1600x 4063x 12x 12x 12x 12x 12x 12x 1588x 4063x 1x 1x 1587x 4065x 1x 1x 1586x 4063x 1x 1x 1585x 4063x 9x 9x 9x 9x 9x 1576x 4063x 133x 133x 133x 133x 133x 133x 133x 133x 1443x 1443x 1443x 1443x 1443x 1443x 1443x 4065x 4065x 4065x 4065x 4065x 4065x 2163x 2163x 2232x 544x 544x 544x 546x 44x 44x 44x     546x  
/**
 * @file build.js
 * @description Builds the template IR from template source.
 *
 * This runs on the template as the developer wrote it -- after declarations and
 * imports are removed and scoped-CSS classes are applied, but *before* any
 * directive rewriting. That ordering is the whole point: reading `<@for item in
 * items>` directly is what lets the compiler record that it is a loop over
 * `items` binding `item`, instead of rewriting it into a `<template>` element
 * and asking the runtime to work that out again.
 *
 * ## What it refuses
 *
 * A construct the IR does not model yet aborts the build of that template with
 * a {@link IRRefusal} naming the construct. The caller keeps the legacy path
 * for that component and the build reports it. There is no partial IR, for the
 * same reason there is no partial render program: two descriptions of one
 * template disagree eventually, and the disagreement is unattributable.
 * @module lib/compiler/ir/build
 */
 
import { parseHTML } from '../parser/htmlTree.js';
import { createInterpolationRegex } from '../../core/utils/templateUtils.js';
import { isBooleanAttribute } from '../../core/renderer/constants.js';
import {
  BindingKind,
  IRRefusal,
  RefusalReason,
  comment,
  component,
  conditional,
  element,
  fragment,
  deferred,
  interpolation,
  iteration,
  slot,
  text,
} from './nodes.js';
 
/**
 * Directive tags the IR does not model yet, mapped to the reason reported.
 * @type {Map<string, string>}
 */
const UNMODELLED_TAGS = new Map([
  ['@suspense', RefusalReason.SUSPENSE],
  ['@fallback', RefusalReason.SUSPENSE],
  ['@errorboundary', RefusalReason.ERROR_BOUNDARY],
  ['@deadlock', RefusalReason.DEADLOCK],
  ['transition', RefusalReason.TRANSITION],
  ['resource', RefusalReason.RESOURCE],
  ['virtuallist', RefusalReason.VIRTUAL_LIST],
  ['routerview', RefusalReason.ROUTER_VIEW],
]);
 
/**
 * Attributes whose presence means the element needs machinery the IR does not
 * model, mapped to the reason reported.
 * @type {Array<string[]>}
 */
const UNMODELLED_ATTRS = [
  ['data-ax-ref', RefusalReason.REF],
  ['data-ax-validate', RefusalReason.VALIDATION],
  ['data-ax-router-view', RefusalReason.ROUTER_VIEW],
  ['data-ax-dyn-attrs', RefusalReason.DYNAMIC_ATTR],
  ['data-avenx-comp-dynamic', RefusalReason.DYNAMIC_COMPONENT],
  ['data-ax-transition', RefusalReason.TRANSITION],
];
 
/**
 * Directive attributes that become bindings rather than markup.
 * @type {Map<string, string>}
 */
const DIRECTIVE_BINDINGS = new Map([
  ['data-ax-show', BindingKind.SHOW],
  ['data-ax-class', BindingKind.CLASS],
  ['data-ax-html', BindingKind.HTML],
  ['data-ax-style', BindingKind.STYLE],
]);
 
/**
 * Whether a string contains a template interpolation.
 * @param {string} value - The text to test.
 * @returns {boolean} True when it contains `{{ }}` or `{{{ }}}`.
 */
function hasInterpolation(value) {
  return typeof value === 'string' && value.includes('{{');
}
 
/**
 * Splits text into literal and expression segments, in order.
 * @param {string} source - The source text.
 * @returns {Array<{expr: string|null, raw: boolean, value: string}>} The segments.
 */
export function splitInterpolations(source) {
  const segments = [];
  const regex = createInterpolationRegex();
  let last = 0;
  let match;
 
  while ((match = regex.exec(source)) !== null) {
    if (match.index > last) {
      segments.push({ expr: null, raw: false, value: source.slice(last, match.index) });
    }
    const raw = match[1] !== undefined;
    segments.push({ expr: (raw ? match[1] : match[2]).trim(), raw, value: '' });
    last = regex.lastIndex;
  }
 
  if (last < source.length) {
    segments.push({ expr: null, raw: false, value: source.slice(last) });
  }
  return segments;
}
 
/**
 * Finds the offset of a top-level occurrence of a keyword in an expression.
 *
 * "Top level" means outside quotes and outside every bracket pair, so the `in`
 * of `<@for k in Object.keys(map)>` is found and the `in` of an `x in y`
 * written inside a call's arguments is not.
 * @param {string} source - The text to scan.
 * @param {string} word - The keyword to find.
 * @returns {number} The offset, or -1.
 */
function findTopLevelWord(source, word) {
  let quote = null;
  let depth = 0;
 
  for (let i = 0; i < source.length; i++) {
    const ch = source[i];
 
    if (quote) {
      if (ch === '\\') i++;
      else if (ch === quote) quote = null;
      continue;
    }
    if (ch === '"' || ch === "'" || ch === '`') {
      quote = ch;
      continue;
    }
    if (ch === '(' || ch === '[' || ch === '{') {
      depth++;
      continue;
    }
    if (ch === ')' || ch === ']' || ch === '}') {
      if (depth > 0) depth--;
      continue;
    }
    if (depth !== 0) continue;
 
    if (source.startsWith(word, i)) {
      const before = i === 0 ? ' ' : source[i - 1];
      const after = source[i + word.length] === undefined ? ' ' : source[i + word.length];
      if (/\s/.test(before) && /\s/.test(after)) {
        return i;
      }
    }
  }
  return -1;
}
 
/**
 * Strips a trailing `key="..."` clause from a `<@for>` header.
 * @param {string} header - The header text after the list expression.
 * @returns {{list: string, key: string|null}} The list source and the key source.
 */
function splitListAndKey(header) {
  const match = header.match(/\skey\s*=\s*("([^"]*)"|'([^']*)')\s*$/);
  if (!match) {
    return { list: header.trim(), key: null };
  }
  const key = match[2] !== undefined ? match[2] : match[3];
  return { list: header.slice(0, match.index).trim(), key: key.trim() || null };
}
 
/**
 * Parses a `<@for>` header into its parts.
 *
 * Two binding forms, both pre-existing and both preserved exactly:
 *
 * - `item in list` binds each element to `item`.
 * - `[a, b] in pairs` destructures each *element* -- which is an array -- into
 *   `a` and `b`. It does not mean `(item, index)`, however much it looks like
 *   the JavaScript it resembles.
 *
 * Either form also binds `index` implicitly, which is how the loop index has
 * always been reached. Both facts are load-bearing for existing applications,
 * so they are read out of the previous implementation rather than redesigned
 * here; changing either belongs in its own change, with its own migration.
 * @param {string} header - The raw header text.
 * @returns {{item: string|null, destructure: string[]|null, list: string, key: string|null}} The parts.
 * @throws {IRRefusal} When the header is not a loop header.
 */
export function parseForHeader(header) {
  const source = (header || '').trim();
 
  // The attribute spelling, `<@for item="user" in="users" key="user.id">`,
  // which api-reference/component.md and troubleshooting/errors.md both use.
  // It is the same loop as the header spelling and lowers identically; the IR
  // refused it as malformed, so every component written that way fell back to
  // the string renderer.
  const attributeForm = readForAttributes(source);
  if (attributeForm) {
    return attributeForm;
  }
 
  const inAt = findTopLevelWord(source, 'in');
  if (inAt === -1) {
    throw new IRRefusal(RefusalReason.MALFORMED, `<@for ${source}> has no "in" clause`);
  }
 
  const binding = source.slice(0, inAt).trim();
  const { list, key } = splitListAndKey(source.slice(inAt + 2));
 
  if (list === '') {
    throw new IRRefusal(RefusalReason.MALFORMED, `<@for ${source}> iterates nothing`);
  }
 
  const destructured = binding.match(/^\[\s*([A-Za-z_$][\w$]*)\s*(?:,\s*([A-Za-z_$][\w$]*)\s*)?\]$/);
  if (destructured) {
    return {
      item: null,
      destructure: destructured[2] ? [destructured[1], destructured[2]] : [destructured[1]],
      list,
      key,
    };
  }
 
  if (!/^[A-Za-z_$][\w$]*$/.test(binding)) {
    throw new IRRefusal(RefusalReason.MALFORMED, `<@for ${source}> does not bind a name`);
  }
  return { item: binding, destructure: null, list, key };
}
 
/**
 * Reads the attribute spelling of a loop header.
 *
 * `item="user" in="users" key="user.id"` means exactly what
 * `user in users key="user.id"` means. Only the fully-quoted form is accepted,
 * so a header that merely contains the word `in` is still read by the header
 * parser.
 * @param {string} source - The raw header text.
 * @returns {{item: string, destructure: null, list: string, key: string|null}|null}
 *   The parts, or null when this is not the attribute spelling.
 */
function readForAttributes(source) {
  const read = (name) => {
    const match = source.match(new RegExp(`(?:^|\\s)${name}\\s*=\\s*("([^"]*)"|'([^']*)')`));
    if (!match) return null;
    return (match[2] !== undefined ? match[2] : match[3]).trim();
  };
 
  const item = read('item');
  const list = read('in');
  if (!item || !list) {
    return null;
  }
  if (!/^[A-Za-z_$][\w$]*$/.test(item)) {
    throw new IRRefusal(RefusalReason.MALFORMED, `<@for ${source}> does not bind a name`);
  }
 
  return { item, destructure: null, list, key: read('key') };
}
 
/**
 * Parses an event attribute name into its event and modifiers.
 * @param {string} name - The attribute name, including the leading `@`.
 * @returns {{event: string, modifiers: string[]}} The parsed parts.
 */
function parseEventName(name) {
  const [event, ...modifiers] = name.slice(1).split('.');
  return { event, modifiers };
}
 
/**
 * Reads a directive attribute's expression, with or without `{{ }}` around it.
 *
 * Both spellings are documented and both appear in the wild:
 *
 * ```html
 * <p data-ax-show="isOpen">
 * <p data-ax-style="{{ { fontWeight: bold ? '700' : '400' } }}">
 * ```
 *
 * The braces are how an author writes an object literal without it looking
 * like an attribute value, so they are stripped here rather than handed to the
 * expression parser, which would read `{{` as the start of a block.
 * @param {string} value - The attribute value as written.
 * @returns {string} The expression source.
 */
function unwrapDirectiveValue(value) {
  const segments = splitInterpolations(value);
  if (segments.length === 1 && segments[0].expr !== null) {
    return segments[0].expr;
  }
  return value;
}
 
/**
 * Builds an element's bindings and events from its attribute map.
 * @param {object} node - The parsed HTML node.
 * @returns {{attrs: object, bindings: object[], events: object[]}} The element parts.
 * @throws {IRRefusal} When an attribute needs machinery the IR does not model.
 */
function buildAttributes(node) {
  const source = node.attrs || {};
  const attrs = {};
  const bindings = [];
  const events = [];
 
  for (const [name, reason] of UNMODELLED_ATTRS) {
    if (source[name] !== undefined) {
      throw new IRRefusal(reason, `<${node.tagName} ${name}>`);
    }
  }
 
  for (const [name, value] of Object.entries(source)) {
    if (name === 'data-ax-static') continue;
 
    if (name.startsWith('@')) {
      const { event, modifiers } = parseEventName(name);
      events.push({ event, modifiers, expr: value });
      continue;
    }
 
    // `:prop="expr"` binds a value; `:[expr]="v"` binds an attribute *name*,
    // which has no fixed attribute for a program to address.
    if (name.startsWith(':')) {
      if (name.includes('[')) {
        throw new IRRefusal(RefusalReason.DYNAMIC_ATTR, `<${node.tagName} ${name}>`);
      }
      bindings.push({ type: BindingKind.ATTR, name: name.slice(1), expr: value });
      continue;
    }
 
    if (hasInterpolation(name)) {
      throw new IRRefusal(RefusalReason.DYNAMIC_ATTR, `<${node.tagName}> interpolated attribute name`);
    }
 
    const directive = DIRECTIVE_BINDINGS.get(name);
    if (directive) {
      bindings.push({ type: directive, name, expr: unwrapDirectiveValue(value) });
      continue;
    }
 
    if (!hasInterpolation(value)) {
      attrs[name] = value;
      continue;
    }
 
    const segments = splitInterpolations(value);
    if (segments.length === 1 && segments[0].expr !== null) {
      // One whole expression, so the value keeps its type: a boolean attribute
      // can be toggled and null can remove the attribute, neither of which
      // survives concatenation into a string.
      bindings.push({
        type: isBooleanAttribute(name) ? BindingKind.BOOL : BindingKind.ATTR,
        name,
        expr: segments[0].expr,
      });
    } else {
      bindings.push({
        type: BindingKind.ATTR_PARTS,
        name,
        parts: segments.map((segment) => (segment.expr === null ? segment.value : { expr: segment.expr })),
      });
    }
  }
 
  return { attrs, bindings, events };
}
 
/**
 * Builds the props of a child component from its attribute map.
 * @param {object} node - The parsed HTML node.
 * @returns {object[]} Prop descriptors.
 */
function buildProps(node) {
  const props = [];
  for (const [name, value] of Object.entries(node.attrs || {})) {
    if (name.startsWith('@')) {
      props.push({ name, kind: 'event', expr: value });
      continue;
    }
    const bound = name.startsWith(':');
    const propName = bound ? name.slice(1) : name;
    if (bound) {
      props.push({ name: propName, kind: 'bound', expr: value });
    } else if (hasInterpolation(value)) {
      const segments = splitInterpolations(value);
      if (segments.length === 1 && segments[0].expr !== null) {
        props.push({ name: propName, kind: 'bound', expr: segments[0].expr });
      } else {
        props.push({
          name: propName,
          kind: 'parts',
          parts: segments.map((s) => (s.expr === null ? s.value : { expr: s.expr })),
        });
      }
    } else {
      props.push({ name: propName, kind: 'static', value });
    }
  }
  return props;
}
 
/**
 * Whether a tag name refers to a child component rather than an element.
 * @param {string} tag - The tag name as written.
 * @returns {boolean} True for a PascalCase reference.
 */
function isComponentTag(tag) {
  return /^[A-Z][A-Za-z0-9_]*$/.test(tag);
}
 
/**
 * Rejects a conditional header that the tag scan cut in half.
 *
 * `<@if count > 3>` cannot be read unambiguously: the `>` that means "greater
 * than" and the `>` that means "end of tag" are the same character, and nothing
 * in the surrounding text distinguishes them. Bracket depth rescues
 * `<@for x in xs.filter(a => a.n > 1)>` because the comparison is inside a call;
 * a bare comparison has nothing to hide behind.
 *
 * So the compiler does not guess. A header that was truncated leaves the rest
 * of the expression as the first text node of the branch body -- `" 3>"` above
 * -- and that shape is what this detects. The author gets the parenthesised
 * form, which the scanner reads correctly, rather than a condition that
 * silently tests the wrong thing.
 * @param {object} node - The parsed directive node.
 * @param {string} test - The header text as scanned.
 * @throws {IRRefusal} When the header was cut at a comparison.
 */
function assertHeaderNotTruncated(node, test) {
  const first = (node.children || [])[0];
  if (!first || first.type !== 'text') return;
 
  // A leftover fragment reaches the next `>` without opening an element first.
  const leftover = first.content.match(/^([^<]*?)>/);
  if (!leftover) return;
 
  const tail = leftover[1].trim();
  if (tail === '') return;
 
  throw new IRRefusal(
    RefusalReason.MALFORMED,
    `<${node.tagName} ${test}> was cut at a ">" -- write it as ` +
      `<${node.tagName} (${test} > ${tail})> so the comparison is inside brackets`,
  );
}
 
/**
 * Collects an `<@if>` chain starting at `index`, consuming its continuations.
 * @param {object[]} siblings - The sibling list being walked.
 * @param {number} index - Index of the `<@if>` node.
 * @param {function(object[]): object[]} buildChildren - Recursive child builder.
 * @returns {{node: object, next: number}} The conditional node and the index to resume at.
 */
function buildConditional(siblings, index, buildChildren) {
  const branches = [];
  let i = index;
  let sawElse = false;
 
  while (i < siblings.length) {
    const node = siblings[i];
 
    // Whitespace between `</@if>` and `<@elseif>` is formatting, not content.
    // Breaking the chain on it would make an author's indentation decide
    // whether their `<@else>` belongs to the `<@if>` above it.
    if (node && node.type === 'text' && node.content.trim() === '' && branches.length > 0) {
      const following = siblings[i + 1];
      const followingTag = following && following.type === 'element' ? (following.tagName || '').toLowerCase() : '';
      if (followingTag === '@elseif' || followingTag === '@elif' || followingTag === '@else') {
        i++;
        continue;
      }
      break;
    }
 
    if (!node || node.type !== 'element') break;
    const tag = (node.tagName || '').toLowerCase();
 
    if (tag === '@if' && i !== index) break;
 
    if (tag === '@if' || tag === '@elseif' || tag === '@elif') {
      if (sawElse) {
        throw new IRRefusal(RefusalReason.MALFORMED, `<${node.tagName}> follows <@else>`);
      }
      const test = (node.rawAttrs || '').trim();
      if (test === '') {
        throw new IRRefusal(RefusalReason.MALFORMED, `<${node.tagName}> has no condition`);
      }
      assertHeaderNotTruncated(node, test);
      branches.push({ test, body: fragment(buildChildren(node.children || [])) });
      i++;
      continue;
    }
 
    if (tag === '@else') {
      if (sawElse) {
        throw new IRRefusal(RefusalReason.MALFORMED, 'two <@else> branches in one chain');
      }
      sawElse = true;
      branches.push({ test: null, body: fragment(buildChildren(node.children || [])) });
      i++;
      continue;
    }
 
    break;
  }
 
  return { node: conditional(branches), next: i };
}
 
/**
 * Builds an iteration node from a `<@for>` element.
 * @param {object} node - The parsed `<@for>` node.
 * @param {function(object[]): object[]} buildChildren - Recursive child builder.
 * @returns {object} The iteration node.
 */
function buildIteration(node, buildChildren) {
  const parts = parseForHeader(node.rawAttrs);
 
  const body = [];
  let empty = null;
  for (const child of node.children || []) {
    if (child.type === 'element' && (child.tagName || '').toLowerCase() === '@empty') {
      if (empty) {
        throw new IRRefusal(RefusalReason.MALFORMED, 'two <@empty> blocks in one <@for>');
      }
      empty = fragment(buildChildren(child.children || []));
      continue;
    }
    body.push(child);
  }
 
  return iteration({
    list: parts.list,
    item: parts.item,
    destructure: parts.destructure,
    key: parts.key,
    body: fragment(buildChildren(body)),
    empty,
  });
}
 
/**
 * Builds a deferred block from a `<@defer>` element.
 *
 * `<@placeholder>` is a sibling of the deferred content rather than a wrapper
 * around it, so it is separated out here the same way `<@empty>` is separated
 * from a loop body.
 * @param {object} node - The parsed `<@defer>` node.
 * @param {string} when - The resolved trigger.
 * @param {function(object[]): object[]} buildChildren - Recursive child builder.
 * @returns {object} The defer node.
 */
function buildDefer(node, when, buildChildren) {
  const body = [];
  let placeholder = null;
 
  for (const child of node.children || []) {
    const tag = child.type === 'element' ? (child.tagName || '').toLowerCase() : '';
    // `<@loading>` is the spelling core-concepts/defer.md documents; the string
    // renderer has always accepted both, and the IR refusing one sent every
    // template written that way to the fallback renderer. `<@placeholder>`
    // wins when a template somehow carries both, which is the order the
    // previous implementation resolved them in.
    if (tag === '@placeholder' || tag === '@loading') {
      const block = fragment(buildChildren(child.children || []));
      if (placeholder && tag === '@placeholder') {
        throw new IRRefusal(RefusalReason.MALFORMED, 'two <@placeholder> blocks in one <@defer>');
      }
      if (!placeholder || tag === '@placeholder') {
        placeholder = block;
      }
      continue;
    }
    body.push(child);
  }
 
  return deferred(when, fragment(buildChildren(body)), placeholder);
}
 
/**
 * Builds the IR for a template.
 * @param {string} template - The template source, before directive rewriting.
 * @param {object} [options] - Build options.
 * @param {string[]} [options.voidTags] - Project-specific void tag names.
 * @returns {{ir: object|null, refusal: {reason: string, detail: string}|null}}
 *   The root fragment, or the reason the template could not be represented.
 */
export function buildTemplateIR(template, options = {}) {
  if (typeof template !== 'string' || template.trim() === '') {
    return { ir: null, refusal: { reason: RefusalReason.MALFORMED, detail: 'empty template' } };
  }
 
  const voidTags = options.voidTags || [];
  let parsed;
  try {
    parsed = parseHTML(template, voidTags);
  } catch (error) {
    return { ir: null, refusal: { reason: RefusalReason.MALFORMED, detail: `template did not parse: ${error.message}` } };
  }
 
  /**
   * Builds IR for a sibling list.
   * @param {object[]} siblings - Parsed sibling nodes.
   * @returns {object[]} IR nodes.
   */
  function buildChildren(siblings) {
    const out = [];
 
    for (let i = 0; i < siblings.length; i++) {
      const node = siblings[i];
 
      if (node.type === 'text') {
        for (const segment of splitInterpolations(node.content)) {
          if (segment.expr === null) {
            if (segment.value !== '') out.push(text(segment.value));
          } else {
            out.push(interpolation(segment.expr, segment.raw));
          }
        }
        continue;
      }
 
      if (node.type === 'comment') {
        if (hasInterpolation(node.content)) {
          throw new IRRefusal(RefusalReason.UNKNOWN_DIRECTIVE, 'an interpolation inside an HTML comment');
        }
        out.push(comment(node.content));
        continue;
      }
 
      const tag = (node.tagName || '').toLowerCase();
 
      const unmodelled = UNMODELLED_TAGS.get(tag);
      if (unmodelled) {
        throw new IRRefusal(unmodelled, `<${node.tagName}>`);
      }
 
      if (tag === '@if') {
        const built = buildConditional(siblings, i, buildChildren);
        out.push(built.node);
        i = built.next - 1;
        continue;
      }
 
      if (tag === '@elseif' || tag === '@elif' || tag === '@else') {
        throw new IRRefusal(RefusalReason.MALFORMED, `<${node.tagName}> without a preceding <@if>`);
      }
 
      if (tag === '@for') {
        out.push(buildIteration(node, buildChildren));
        continue;
      }
 
      if (tag === '@defer') {
        // `when` is the documented spelling; a bare header is accepted too so
        // `<@defer visible>` reads the way the other directives do.
        const when = ((node.attrs && node.attrs.when) || (node.rawAttrs || '').trim() || 'idle').trim();
        out.push(buildDefer(node, when, buildChildren));
        continue;
      }
 
      if (tag === '@empty') {
        throw new IRRefusal(RefusalReason.MALFORMED, '<@empty> outside a <@for>');
      }
 
      if (tag === '@placeholder' || tag === '@loading') {
        throw new IRRefusal(RefusalReason.MALFORMED, `<${tag}> outside a <@defer>`);
      }
 
      if (tag.startsWith('@')) {
        throw new IRRefusal(RefusalReason.UNKNOWN_DIRECTIVE, `<${node.tagName}>`);
      }
 
      if (tag === 'slot') {
        const name = (node.attrs && node.attrs.name) || 'default';
        const fallbackChildren = buildChildren(node.children || []);
        out.push(slot(name, fallbackChildren.length > 0 ? fragment(fallbackChildren) : null));
        continue;
      }
 
      if (isComponentTag(node.tagName)) {
        out.push(
          component(node.tagName, {
            props: buildProps(node),
            children: buildChildren(node.children || []),
          }),
        );
        continue;
      }
 
      const { attrs, bindings, events } = buildAttributes(node);
      out.push(
        element(node.tagName, {
          attrs,
          bindings,
          events,
          children: buildChildren(node.children || []),
          selfClosing: node.isSelfClosing === true,
          isStatic: node.attrs && node.attrs['data-ax-static'] !== undefined,
        }),
      );
    }
 
    return out;
  }
 
  try {
    return { ir: fragment(buildChildren(parsed)), refusal: null };
  } catch (error) {
    if (error instanceof IRRefusal) {
      return { ir: null, refusal: { reason: error.reason, detail: error.detail } };
    }
    throw error;
  }
}