All files / src transform.ts

95.14% Statements 666/700
94.75% Branches 524/553
100% Functions 30/30
98.62% Lines 503/510

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 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902                                                    56x 56x 56x 56x   56x 9075x 9075x 9075x 103342x 102943x 93876x   8x     56x 4827x 4827x     56x 17x 17x       56x 1598x 1598x 6883x 1786x 1162x 1161x   1598x                                 56x                   56x 202x 202x 375x 375x 201x 2x 2x 2x 2x   199x   202x 199x 199x 19x 71x 19x   180x 177x               56x 181x 181x 181x 2288x 2288x 2067x 2065x 2043x 2021x 173x 173x 173x   1892x   6x               56x               56x 1032x 1032x 1033x 1033x 1032x           1032x                                   56x 1578x 1578x 1578x 94267x 94267x 92699x 92497x 92494x 92454x 88780x 85109x 85107x 1483x   1483x   1483x 15x 15x   90969x   108x                                           56x 1341x 1341x 1341x 1341x 1341x 1344x 1344x 1344x   1341x 1341x 83446x 83446x 81969x 81770x 81769x 81741x 78438x 75136x 81738x 81738x   1341x 1341x               56x 29x 29x 18x   11x 11x 19x 19x 19x 19x 13x 13x 3x 3x     16x   11x             56x 1341x 1341x 1344x 1344x 1344x 1344x 1344x 1344x 1344x 1344x 1334x 1344x 1344x         1341x 1341x 1344x 1341x 1341x     56x 2508x 2508x 2508x 2508x 2508x   2508x 112014x 112014x   112014x 1772x 1772x 1772x 1772x 1772x   110242x 1095x 1095x 1095x 1095x   109147x 41x 41x 41x 41x 41x             109106x 1009x 1009x 209x 209x 209x 209x       108897x 11693x 11693x 11693x 1341x 1341x 1341x 1341x 1341x 1341x 1341x 1341x     10352x 10352x 10352x 237x 237x 237x 237x 237x           237x 237x 237x       107319x 103093x   107319x 99534x   107319x 107319x     2508x                                     56x       56x       56x 14x 14x 14x 14x 191x 191x 184x 177x 16x 16x 16x     14x       56x 15x 15x 14x 14x 14x 14x 2x 2x 2x   14x 16x 11x 8x   14x                                                     56x       56x 1085x 1085x 1085x 15406x 15406x 15297x 15297x 15295x 15292x 14180x 14212x   5x       56x 4720x 4720x 4720x 28843x 28843x 28843x 28843x 28843x 28843x 28830x 28817x 27334x   3211x     56x 1178x 1178x 1178x 1178x 1178x 16029x 16029x 15911x 15911x 15908x 15904x 15780x 15656x 1864x 1864x 1864x   15904x   1178x         56x 3035x 3035x 3035x 3035x 1503x 1503x                   56x 1252x 1252x       1074x 1074x   1069x 1069x 1673x 1672x 1672x 1672x     1672x 1672x 1672x 1672x 1672x     1672x 1672x 1672x   1069x       56x 1307x 1307x 1307x 1307x 157450x 157450x 155289x 153683x 153683x   153644x 101x 101x 101x     153543x 147890x 153543x 143248x 153543x   1206x     56x 56x         56x 1307x 1307x   101x 101x 101x 101x 101x 101x     98x 98x 98x 1848x 1848x 1839x 1839x 1838x 1837x 1642x 1739x   98x               56x 1307x 1307x 98x 98x 98x 3x         95x         56x 908x 908x 908x 908x 908x 908x   908x 121322x 121322x 121322x   121322x 1769x 1769x 1769x 1769x 1769x   119553x 1103x 1103x 1103x 1103x   118450x 23x 23x 23x 23x 23x     118427x   1032x 1032x 207x 207x 207x 207x   825x 18x 18x 18x 15x 15x 15x 15x         118205x 50x 50x 50x 50x 50x 50x 50x 50x       118155x 113703x   118155x 109982x   118155x 118155x     908x                                       56x                   56x       56x     56x   56x   2152x     56x   56x 1259x     1259x 1259x 1259x 1259x 1259x   1259x 2761x 2761x 2312x 2308x 2308x 2306x   2214x   7x 7x 61x 61x 54x 6x 6x 6x 86x 86x 86x   6x 6x 8x 6x   48x   7x 7x 7x     2207x 55x 55x 55x 55x     2152x 1508x 7454x 1508x 1508x 1508x 1506x 1275x 1267x 1266x 1266x             1266x   1197x   1197x 1197x 1197x     644x 644x 620x 620x 49x 49x 49x 49x   571x   490x 423x 353x 336x   490x 490x             1082x 1072x    
// ---------------------------------------------------------------------------
// :setup script transform
//
// setup scripts are written like Svelte components:
//
//   let firstName = null
//   $: fullName = `${firstName} ${lastName}`
//   fetchUser().then(user => { firstName = user.firstName })
//
// and are executed inside `with ($scope)` against the component's reactive
// store, so plain assignments (even from async callbacks) go through the
// proxy's set trap and re-render whatever depends on them. To make that work
// the source is lightly rewritten - no full JS parser, just a scanner that is
// string/comment-aware and only touches code at brace/paren depth 0:
// - `let/var/const x = ...` at the top level loses its keyword, becoming a
//   scope assignment (the name is pre-declared on the store so the `with`
//   lookup resolves it)
// - `$: x = expr` becomes `$__effect(() => { x = expr })`, re-running when a
//   dependency read inside expr changes ($__effect is deliberately NOT a
//   property of the scope, so `with` falls through to the function parameter)
// ---------------------------------------------------------------------------
 
type SetupTransform = { vars: string[]; code: string }
 
// a declaration whose target is an identifier (`let x`), an object pattern
// (`let { a }`, space optional) or an array pattern (`let [x]`)
const DECLARATION_START_RE = /(?:let|var|const)(?:\s+(?=[A-Za-z_$])|\s*(?=[{[]))/y
const REACTIVE_LABEL_RE = /\$:\s*/y
const IMPORT_CALL_RE = /import(?=\s*\()/y
const REACTIVE_ASSIGN_RE = /\$:\s*([A-Za-z_$][\w$]*)\s*=(?!=)/y
 
const skipString = (src: string, start: number): number => {
  const quote = src[start]
  let i = start + 1
  while (i < src.length) {
    if (src[i] === "\\") { i += 2; continue }
    if (src[i] === quote) return i + 1
    i++
  }
  return src.length
}
 
const skipLineComment = (src: string, start: number): number => {
  const end = src.indexOf("\n", start)
  return end === -1 ? src.length : end
}
 
const skipBlockComment = (src: string, start: number): number => {
  const end = src.indexOf("*/", start + 2)
  return end === -1 ? src.length : end + 2
}
 
// index of the next thing that isn't whitespace or a comment
const skipToToken = (src: string, start: number): number => {
  let i = start
  while (i < src.length) {
    if (/\s/.test(src[i])) { i++; continue }
    if (src[i] === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
    if (src[i] === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
    break
  }
  return i
}
 
// ---------------------------------------------------------------------------
// regex literals. The scanners walk the source counting bracket depth, and a
// regex walked as if it were code poisons that count: `split(/\//)` puts two
// slashes side by side (a line comment, as far as a scanner knows) and the
// `)` after them is skipped uncounted; `/[(]/` inflates the depth for good.
// So a `/` that opens a regex is consumed whole - and whether it opens one is
// the classic lexer call, made the way every tokenizer makes it: by what came
// before. Division needs a completed expression on its left; everywhere else
// a `/` can only be a regex.
// ---------------------------------------------------------------------------
 
// reserved words a regex can follow. Reserved only - `of` is not (`const of
// = 4; of / 2` is legal division), so `for (x of /re/)` stays unrescued
// rather than risking real code
const REGEX_AFTER_WORD = new Set([
  "return", "typeof", "case", "in", "instanceof", "new", "delete", "void", "do", "else", "yield", "await",
])
 
// whether a `/` at `at` opens a regex literal rather than a division: looks
// backward past whitespace and block comments for the last meaningful thing.
// A completed expression - identifier, number, closing quote or bracket,
// postfix ++/-- - takes division; a reserved word or any other punctuator
// admits a regex. Only consulted for the rare `/` that is neither `//` nor
// `/*`, so the scanners pay nothing on the common path
const regexAllowed = (src: string, at: number): boolean => {
  let i = at - 1
  while (i >= 0) {
    const ch = src[i]
    if (/\s/.test(ch)) { i--; continue }
    if (ch === "/" && src[i - 1] === "*") {
      const open = src.lastIndexOf("/*", i - 2)
      Iif (open === -1) return true // an unopened comment tail: malformed input
      i = open - 1
      continue
    }
    break
  }
  if (i < 0) return true // the start of the source starts an expression
  const ch = src[i]
  if (/[\w$]/.test(ch)) {
    let start = i
    while (start > 0 && /[\w$]/.test(src[start - 1])) start--
    return REGEX_AFTER_WORD.has(src.slice(start, i + 1))
  }
  if ((ch === "+" || ch === "-") && src[i - 1] === ch) return false // postfix ++/--
  return !")]}\"'`.".includes(ch)
}
 
// consumes a regex literal (with its flags): backslash escapes, and character
// classes, where an unescaped `/` doesn't close the literal (`/[/]/` is one
// regex). A literal can't contain an unescaped newline, so hitting one means
// the classification was wrong or the input malformed - stop there, bounding
// any damage to a single line
const skipRegex = (src: string, start: number): number => {
  let i = start + 1
  let inClass = false
  while (i < src.length) {
    const ch = src[i]
    if (ch === "\\") { i += 2; continue }
    if (ch === "\n") return i
    if (ch === "[") inClass = true
    else if (ch === "]") inClass = false
    else if (ch === "/" && !inClass) {
      i++
      while (i < src.length && /[a-z]/i.test(src[i])) i++ // flags
      return i
    }
    i++
  }
  return src.length
}
 
// tokens that can't *start* a statement, so a line beginning with one is
// continuing the previous expression rather than opening a new statement -
// the same call JS's automatic semicolon insertion makes. Unary-only forms
// (!, ~, ++, --) are deliberately absent: those do start a statement, and JS
// inserts the semicolon before them
const CONTINUATION_RE = /^(\?\.|\?\?|&&|\|\||\*\*|[.,+\-*/%&|^<>=?:([])/
 
// the last meaningful character before `at`: walks back past whitespace and
// block comments, the way regexAllowed does. A line comment can't be skipped
// from behind (its start is only findable forwards), so a line ending in one
// reports the comment's text instead - callers treat that as "not the char I
// was looking for", which degrades to ending the statement, exactly as
// before this helper existed
const lastMeaningfulBefore = (src: string, at: number): string => {
  let i = at - 1
  while (i >= 0) {
    const ch = src[i]
    if (/\s/.test(ch)) { i--; continue }
    Iif (ch === "/" && src[i - 1] === "*") {
      const open = src.lastIndexOf("/*", i - 2)
      if (open === -1) return ""
      i = open - 1
      continue
    }
    return ch
  }
  return ""
}
 
// end of a statement starting at `start`: the first `;` or line break that
// isn't inside a string/comment or unbalanced brackets. A line break only
// ends the statement if the next line can't continue it, so leading-dot
// method chains and multi-line operator chains stay in one piece:
//
//   $: total = items
//     .filter(item => item.active)      <- still the same statement
//     .length
//
// ...and only if the current line *can* end it: a line whose last meaningful
// character is `,` or `=` left its expression incomplete (a multi-line
// declarator list writes exactly this), so the statement continues - the
// same ASI call as the leading-token check, made from the other side
const findStatementEnd = (src: string, start: number): number => {
  let depth = 0
  let i = start
  while (i < src.length) {
    const ch = src[i]
    if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); continue }
    if (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
    if (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
    if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }
    if ("([{".includes(ch)) depth++
    else if (")]}".includes(ch)) depth--
    else if (depth <= 0 && ch === ";") return i
    else if (depth <= 0 && ch === "\n") {
      const next = skipToToken(src, i + 1)
      const continues =
        next < src.length &&
        (CONTINUATION_RE.test(src.slice(next, next + 2)) || [",", "="].includes(lastMeaningfulBefore(src, i)))
      if (!continues) return i
      i = next
      continue
    }
    i++
  }
  return src.length
}
 
// ---------------------------------------------------------------------------
// top-level declarations. `let x = 1` loses its keyword and becomes a scope
// assignment (x pre-declared on the store). A destructuring declarator
// becomes an *assignment pattern*: inside `with`, `({ a, b } = obj)` writes
// every binding through the reactive proxy - which is what makes it reactive.
// The parens keep the `{` from opening a block, and a leading `;` keeps the
// `(` from gluing onto the previous line as a call. Multi-declarator
// statements (`let a = 1, b = 2`) register every binding, not just the first.
// These lean on the pattern helpers defined with the props signature below
// (splitTopLevel, indexOfTopLevel, defaultAssignIndex); the scanner only
// runs long after the module evaluates, so the order is cosmetic
// ---------------------------------------------------------------------------
 
type Declarator = { raw: string; codeEnd: number }
 
// splits a declarator list at top-level commas, keeping each segment's raw
// text (layout and comments included) and where its last meaningful token
// ends - the spot a closing paren must go, so a trailing comment can't
// swallow it
const splitDeclarators = (src: string): Declarator[] => {
  const parts: Declarator[] = []
  let depth = 0
  let start = 0
  let lastEnd = 0
  const flush = (end: number) => {
    parts.push({ raw: src.slice(start, end), codeEnd: Math.max(0, lastEnd - start) })
    start = end + 1
    lastEnd = start
  }
  let i = 0
  while (i < src.length) {
    const ch = src[i]
    if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); lastEnd = i; continue }
    if (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
    if (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
    if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); lastEnd = i; continue }
    if ("([{".includes(ch)) depth++
    else if (")]}".includes(ch)) depth--
    else if (ch === "," && depth <= 0) { flush(i); i++; continue }
    if (!/\s/.test(ch)) lastEnd = i + 1
    i++
  }
  flush(src.length)
  return parts
}
 
// the *binding* names a destructuring pattern declares - unlike
// parsePropsPattern, which answers "which props" (the keys), this answers
// "which variables": `{ a: x }` binds x, `{ a: { b } }` binds b,
// `[x, ...rest]` binds x and rest. Defaults are stripped; what remains is a
// nested pattern (recurse) or the bound identifier
const patternBindings = (src: string): string[] => {
  const pattern = src.trim()
  if (!pattern.startsWith("{") && !pattern.startsWith("[")) {
    return IDENTIFIER_RE.test(pattern) ? [pattern] : []
  }
  const names: string[] = []
  for (let part of splitTopLevel(pattern.slice(1, patternCloseIndex(pattern)))) {
    if (part.startsWith("...")) part = part.slice(3).trim()
    const assign = defaultAssignIndex(part)
    if (assign !== -1) part = part.slice(0, assign).trim()
    if (pattern.startsWith("{")) {
      const colon = indexOfTopLevel(part, ":")
      if (colon !== -1) {
        names.push(...patternBindings(part.slice(colon + 1)))
        continue
      }
    }
    names.push(...patternBindings(part))
  }
  return names
}
 
// one `let/var/const` declarator list, rewritten to scope assignments.
// Each segment's initializer is re-scanned so an `import()` inside it is
// rewritten like anywhere else - nothing else can match in there, since a
// nested top-level declaration inside a declarator is a SyntaxError in JS
const rewriteDeclarators = (src: string): SetupTransform => {
  const vars: string[] = []
  const rewritten = splitDeclarators(src).map(({ raw, codeEnd }) => {
    const lead = raw.match(/^\s*/)![0]
    Iif (codeEnd <= lead.length) return { text: raw, empty: true }
    const body = raw.slice(lead.length, codeEnd)
    const tail = raw.slice(codeEnd)
    const assign = defaultAssignIndex(body)
    const target = (assign === -1 ? body : body.slice(0, assign)).trim()
    const isPattern = body[0] === "{" || body[0] === "["
    if (isPattern) vars.push(...patternBindings(target))
    else if (IDENTIFIER_RE.test(target)) vars.push(target)
    const code = transformSetupScript(body).code
    return { text: `${lead}${isPattern ? `(${code})` : code}${tail}`, empty: false }
  })
 
  // a trailing comment-only segment (`let a = 1, // note` cut at its line
  // end) is re-attached without its comma, so the output stays a statement
  const tail: string[] = []
  while (rewritten.length && rewritten[rewritten.length - 1].empty) tail.unshift(rewritten.pop()!.text)
  let code = rewritten.map(part => part.text).join(",") + tail.join("")
  if (code.trimStart().startsWith("(")) code = `;${code}`
  return { vars, code }
}
 
export const transformSetupScript = (src: string): SetupTransform => {
  const vars: string[] = []
  let out = ""
  let i = 0
  let depth = 0
  let atStatementStart = true
 
  while (i < src.length) {
    const ch = src[i]
    const next = src[i + 1]
 
    if (ch === "'" || ch === '"' || ch === "`") {
      const end = skipString(src, i)
      out += src.slice(i, end)
      i = end
      atStatementStart = false
      continue
    }
    if (ch === "/" && (next === "/" || next === "*")) {
      const end = next === "/" ? skipLineComment(src, i) : skipBlockComment(src, i)
      out += src.slice(i, end)
      i = end
      continue
    }
    if (ch === "/" && regexAllowed(src, i)) {
      const end = skipRegex(src, i)
      out += src.slice(i, end)
      i = end
      atStatementStart = false
      continue
    }
 
    // `import(...)` is a keyword form, so it can't be intercepted through the
    // scope - rewrite the identifier to the injected $__import (which loads
    // .html URLs as components via Component79.fetch and delegates the rest to
    // native import). The `(` is left for the scanner so depth stays balanced
    if (ch === "i" && (i === 0 || !/[\w$.]/.test(src[i - 1]))) {
      IMPORT_CALL_RE.lastIndex = i
      if (IMPORT_CALL_RE.test(src)) {
        out += "$__import"
        i += "import".length
        atStatementStart = false
        continue
      }
    }
 
    if (depth === 0 && atStatementStart) {
      DECLARATION_START_RE.lastIndex = i
      const decl = DECLARATION_START_RE.exec(src)
      if (decl) {
        const start = i + decl[0].length
        const end = findStatementEnd(src, start)
        const { vars: names, code } = rewriteDeclarators(src.slice(start, end))
        vars.push(...names)
        out += code
        i = end
        atStatementStart = false
        continue
      }
 
      REACTIVE_LABEL_RE.lastIndex = i
      const label = REACTIVE_LABEL_RE.exec(src)
      if (label) {
        REACTIVE_ASSIGN_RE.lastIndex = i
        const assign = REACTIVE_ASSIGN_RE.exec(src)
        if (assign) vars.push(assign[1])
        const start = i + label[0].length
        const end = findStatementEnd(src, start)
        // the body is re-scanned rather than sliced raw, so an `import()`
        // inside it gets the $__import rewrite like anywhere else. Safe to
        // recurse: strings/comments/regexes copy through unchanged, and a
        // depth-0 declaration inside a labeled statement is a SyntaxError
        // in JS anyway, so nothing else can rewrite
        out += `$__effect(() => { ${transformSetupScript(src.slice(start, end)).code} });`
        i = end
        continue
      }
    }
 
    if ("([{".includes(ch)) depth++
    else if (")]}".includes(ch)) depth = Math.max(0, depth - 1)
 
    if (ch === "\n" || ch === ";" || ch === "}") atStatementStart = true
    else if (!/\s/.test(ch)) atStatementStart = false
 
    out += ch
    i++
  }
 
  return { vars, code: out }
}
 
// ---------------------------------------------------------------------------
// factory scripts - a <script> whose top level has `export default` runs as a
// plain lexical module instead of a `with`-scoped setup script: no implicit
// reactivity, no `$:` labels - standard JS that editors and type-checkers
// understand. The default export is called with the instance context
// ({ $data, $effect, $emit, $mounted, $destroyed, $attached, $detached, $computed, $self, $$self }) and a returned object
// is merged into the reactive store for the template to use.
// Detection is backwards-safe: `export default` is a SyntaxError inside a
// setup script, so no previously-working component can change behavior.
// The same scanner rewrites the module-only syntax into a Function body:
// - `export default X`      -> `$__exports.default = X`
// - `import d from "m"`     -> `const d = $__default(await $__import("m"))`
//   (and the other static clause forms), so imports resolve through the same
//   $__import as setup scripts: bundler map first, then fetch/native import
// ---------------------------------------------------------------------------
 
const EXPORT_DEFAULT_RE = /export\s+default(?![\w$])/y
// clause (default/namespace/named, no quotes or parens) + specifier; the
// no-clause alternative requires the specifier right away, so dynamic
// `import(...)` and `import.meta` never match
const STATIC_IMPORT_RE = /import\s*(?:([\w$\s,{}*]+?)\s*from\s*)?(["'])([^"'\n]+)\2/y
 
// splits an import clause on top-level commas: `d, { a, b as c }` keeps the
// braced group together
const splitImportClause = (clause: string): string[] => {
  const parts: string[] = []
  let depth = 0
  let start = 0
  for (let i = 0; i <= clause.length; i++) {
    const ch = clause[i]
    if (ch === "{") depth++
    else if (ch === "}") depth--
    else if (i === clause.length || (ch === "," && depth === 0)) {
      const part = clause.slice(start, i).trim()
      Eif (part) parts.push(part)
      start = i + 1
    }
  }
  return parts
}
 
// one static import statement -> const bindings from the awaited module
const staticImportToAwait = (clause: string | undefined, spec: string, n: number): string => {
  const source = `await $__import(${JSON.stringify(spec)})`
  if (clause === undefined) return source // side-effect import
  const parts = splitImportClause(clause)
  const bindings: string[] = []
  let ref = source
  if (parts.length > 1) {
    const tmp = `$__mod${n}`
    bindings.push(`${tmp} = ${source}`)
    ref = tmp
  }
  for (const part of parts) {
    if (part.startsWith("{")) bindings.push(`${part.replace(/\s+as\s+/g, ": ")} = ${ref}`)
    else if (part.startsWith("*")) bindings.push(`${part.replace(/^\*\s*as\s+/, "")} = ${ref}`)
    else bindings.push(`${part} = $__default(${ref})`)
  }
  return `const ${bindings.join(", ")}`
}
 
// ---------------------------------------------------------------------------
// the component's prop signature
//
// A component declares the props it takes as a destructuring pattern, in the
// place each script mode already puts its inputs: the `:setup` attribute's
// value, or the factory's *first* parameter (the ctx moved to the second).
// Position is fixed, so the signature is read straight from the source string -
// no parser, no execution - and the runtime can seed the defaults on the store
// before the first render, which is what makes them reach the template even in
// factory mode (where JS would only apply them inside the function body).
//
//   <script :setup="{ label = 'Total', step = 1 }">
//   export default ({ label = "Total" }, { $data }) => {}
//
// An object pattern *is* the declaration; anything else (`_`, a plain
// identifier, no attribute at all) declares nothing and stays permissive.
// ---------------------------------------------------------------------------
 
// `as` is the local name the pattern binds the key to, when it isn't the key
// itself (`{ item: row }`). A prop signature has no use for it - what the
// store holds is the key - but the slot binder (`:slot="{ item: row }"`) is
// the same pattern read for the other half: which names the content uses
export type PropDecl = { name: string; default?: string; as?: string }
 
const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/
 
// index of the bracket that closes the one opening at src[0], skipping
// strings, comments and regex literals; src.length when unbalanced
const patternCloseIndex = (src: string): number => {
  let depth = 0
  let i = 0
  while (i < src.length) {
    const ch = src[i]
    if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); continue }
    Iif (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
    if (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
    if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }
    if ("([{".includes(ch)) depth++
    else if (")]}".includes(ch) && --depth === 0) return i
    i++
  }
  return src.length
}
 
// index of the first `ch` at bracket depth 0, skipping strings and comments
const indexOfTopLevel = (src: string, ch: string): number => {
  let depth = 0
  let i = 0
  while (i < src.length) {
    const c = src[i]
    Iif (c === "'" || c === '"' || c === "`") { i = skipString(src, i); continue }
    Iif (c === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
    Iif (c === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
    Iif (c === "/" && c !== ch && regexAllowed(src, i)) { i = skipRegex(src, i); continue }
    if ("([{".includes(c)) depth++
    else if (")]}".includes(c)) depth--
    else if (depth === 0 && c === ch) return i
    i++
  }
  return -1
}
 
const splitTopLevel = (src: string): string[] => {
  const parts: string[] = []
  let depth = 0
  let start = 0
  let i = 0
  while (i <= src.length) {
    const ch = src[i]
    if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); continue }
    Iif (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
    if (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
    if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); continue }
    if (ch !== undefined && "([{".includes(ch)) depth++
    else if (ch !== undefined && ")]}".includes(ch)) depth--
    else if (i === src.length || (ch === "," && depth === 0)) {
      const part = src.slice(start, i).trim()
      if (part) parts.push(part)
      start = i + 1
    }
    i++
  }
  return parts
}
 
// the `=` that opens a default value: the first one at depth 0 that isn't part
// of `==`/`===` or an arrow's `=>` (so `{ format = a => a }` keeps its default)
const defaultAssignIndex = (src: string): number => {
  let from = 0
  while (from < src.length) {
    const at = indexOfTopLevel(src.slice(from), "=")
    if (at === -1) return -1
    const i = from + at
    Eif (src[i + 1] !== "=" && src[i + 1] !== ">" && src[i - 1] !== "=" && src[i - 1] !== "!") return i
    from = i + 1
  }
  return -1
}
 
// a destructuring pattern -> the props it declares. null means "no signature":
// the pattern isn't an object one (`_`, `props`, nothing at all), so the
// component declares nothing and keeps the permissive, undeclared behavior.
// `{}` parses to [] - a closed signature that declares zero props
export const parsePropsPattern = (pattern: string | undefined): PropDecl[] | null => {
  const src = (pattern ?? "").trim()
  if (!src.startsWith("{")) return null
 
  // to the `}` that closes the pattern, so a parameter's own default value
  // (`({ label } = {})`) is left out of it
  const close = patternCloseIndex(src)
  if (close >= src.length) return null // unbalanced: not a pattern we can read
 
  const props: PropDecl[] = []
  for (const part of splitTopLevel(src.slice(1, close))) {
    if (part.startsWith("...")) continue // a rest element names no prop
    const assign = defaultAssignIndex(part)
    const named = assign === -1 ? part : part.slice(0, assign)
    const fallback = assign === -1 ? undefined : part.slice(assign + 1).trim()
    // `{ user: { id } }` and `{ user: renamed }` both declare `user`: what the
    // store holds is the key, whatever the pattern binds it to
    const colon = indexOfTopLevel(named, ":")
    const name = (colon === -1 ? named : named.slice(0, colon)).trim()
    Iif (!IDENTIFIER_RE.test(name)) continue
    const decl: PropDecl = { name }
    if (fallback !== undefined) decl.default = fallback
    // only a plain rename is kept: `{ user: { id } }` binds no single name, so
    // there is nothing to record - the prop is still declared under its key
    const local = colon === -1 ? "" : named.slice(colon + 1).trim()
    if (IDENTIFIER_RE.test(local)) decl.as = local
    props.push(decl)
  }
  return props
}
 
// index just past a top-level `export default`, or -1
const findExportDefault = (src: string): number => {
  let i = 0
  let depth = 0
  let atStatementStart = true
  while (i < src.length) {
    const ch = src[i]
    if (ch === "'" || ch === '"' || ch === "`") { i = skipString(src, i); atStatementStart = false; continue }
    if (ch === "/" && src[i + 1] === "/") { i = skipLineComment(src, i); continue }
    Iif (ch === "/" && src[i + 1] === "*") { i = skipBlockComment(src, i); continue }
    if (ch === "/" && regexAllowed(src, i)) { i = skipRegex(src, i); atStatementStart = false; continue }
 
    if (ch === "e" && depth === 0 && atStatementStart && (i === 0 || !/[\w$.]/.test(src[i - 1]))) {
      EXPORT_DEFAULT_RE.lastIndex = i
      const found = EXPORT_DEFAULT_RE.exec(src)
      Eif (found) return i + found[0].length
    }
 
    if ("([{".includes(ch)) depth++
    else if (")]}".includes(ch)) depth = Math.max(0, depth - 1)
    if (ch === "\n" || ch === ";" || ch === "}") atStatementStart = true
    else if (!/\s/.test(ch)) atStatementStart = false
    i++
  }
  return -1
}
 
const ASYNC_RE = /^async(?![\w$])/
const FUNCTION_RE = /^function(?![\w$])\s*\*?\s*[A-Za-z_$][\w$]*|^function(?![\w$])\s*\*?/
 
// source text of the exported function's first parameter, or null when there
// is no parameter list to read (`export default Factory`, `export default
// props => ...`, an exported object) - all of which declare nothing
const firstParameterSource = (src: string): string | null => {
  const start = findExportDefault(src)
  if (start === -1) return null
 
  let i = skipToToken(src, start)
  const rest = src.slice(i)
  if (ASYNC_RE.test(rest)) i = skipToToken(src, i + "async".length)
  const fn = FUNCTION_RE.exec(src.slice(i))
  if (fn) i = skipToToken(src, i + fn[0].length)
  if (src[i] !== "(") return null
 
  // the parameter list runs to the `)` that closes this `(`
  let depth = 0
  let end = i
  while (end < src.length) {
    const ch = src[end]
    if (ch === "'" || ch === '"' || ch === "`") { end = skipString(src, end); continue }
    Iif (ch === "/" && src[end + 1] === "/") { end = skipLineComment(src, end); continue }
    if (ch === "/" && src[end + 1] === "*") { end = skipBlockComment(src, end); continue }
    if (ch === "/" && regexAllowed(src, end)) { end = skipRegex(src, end); continue }
    if ("([{".includes(ch)) depth++
    else if (")]}".includes(ch) && --depth === 0) break
    end++
  }
  return splitTopLevel(src.slice(i + 1, end))[0] ?? ""
}
 
// the props declared by a factory script's first parameter. Throws the
// migration error when it finds the pre-0.4 signature there - the ctx used to
// be the first parameter, and the change is silent otherwise ($data would just
// come back undefined). `$` is what tells them apart: what carries one comes
// from the library, what doesn't comes from the parent, everywhere in jq79
export const parseFactoryProps = (src: string): PropDecl[] | null => {
  const first = firstParameterSource(src)
  if (first === null) return null
  const props = parsePropsPattern(first)
  const ctxName = props?.find(prop => prop.name.startsWith("$"))?.name
  if (ctxName) {
    throw new Error(
      `jq79: the factory signature is (props, ctx), so \`${ctxName}\` can't be destructured from the first parameter. ` +
      `Write \`export default (props, { ${ctxName} }) => …\`, or \`_\` in place of props if the component takes none.`
    )
  }
  return props
}
 
// rewrites a factory script into a Function body, or returns null when the
// script has no top-level `export default` (i.e. it's a regular setup script)
export const transformFactoryScript = (src: string): string | null => {
  let out = ""
  let i = 0
  let depth = 0
  let atStatementStart = true
  let isFactory = false
  let modCount = 0
 
  while (i < src.length) {
    const ch = src[i]
    const next = src[i + 1]
    const atWordBoundary = i === 0 || !/[\w$.]/.test(src[i - 1])
 
    if (ch === "'" || ch === '"' || ch === "`") {
      const end = skipString(src, i)
      out += src.slice(i, end)
      i = end
      atStatementStart = false
      continue
    }
    if (ch === "/" && (next === "/" || next === "*")) {
      const end = next === "/" ? skipLineComment(src, i) : skipBlockComment(src, i)
      out += src.slice(i, end)
      i = end
      continue
    }
    if (ch === "/" && regexAllowed(src, i)) {
      const end = skipRegex(src, i)
      out += src.slice(i, end)
      i = end
      atStatementStart = false
      continue
    }
 
    if (ch === "i" && atWordBoundary) {
      // dynamic import() -> $__import, same rewrite as setup scripts
      IMPORT_CALL_RE.lastIndex = i
      if (IMPORT_CALL_RE.test(src)) {
        out += "$__import"
        i += "import".length
        atStatementStart = false
        continue
      }
      if (depth === 0 && atStatementStart) {
        STATIC_IMPORT_RE.lastIndex = i
        const staticImport = STATIC_IMPORT_RE.exec(src)
        if (staticImport) {
          out += staticImportToAwait(staticImport[1], staticImport[3], modCount++)
          i += staticImport[0].length
          atStatementStart = false
          continue
        }
      }
    }
 
    if (ch === "e" && atWordBoundary && depth === 0 && atStatementStart) {
      EXPORT_DEFAULT_RE.lastIndex = i
      const exportDefault = EXPORT_DEFAULT_RE.exec(src)
      Eif (exportDefault) {
        isFactory = true
        out += "$__exports.default ="
        i += exportDefault[0].length
        atStatementStart = false
        continue
      }
    }
 
    if ("([{".includes(ch)) depth++
    else if (")]}".includes(ch)) depth = Math.max(0, depth - 1)
 
    if (ch === "\n" || ch === ";" || ch === "}") atStatementStart = true
    else if (!/\s/.test(ch)) atStatementStart = false
 
    out += ch
    i++
  }
 
  return isFactory ? out : null
}
 
 
// ---------------------------------------------------------------------------
// free identifiers in a template expression
//
// What a compiled expression reads from the scope, so it can be resolved by
// name instead of by `with ($scope)` - which is 60% of an evaluation over a
// store proxy, because it resolves every mention through [[HasProperty]] (the
// proxy's `has` trap as well as its `get`) and consults Symbol.unscopables
// besides. See RECORD/2026-08-27.name-resolution-without-with.md
//
// This is a scanner, not a parser, and it is deliberately conservative: `null`
// means "keep `with`", and every shape that binds a name, assigns to one or
// resolves one dynamically returns it. The caller falls back rather than
// guesses, so a name this misses costs a slower evaluation, never a wrong one.
// ---------------------------------------------------------------------------
 
// words that scan as an identifier and are never a free variable read
const NOT_A_FREE_NAME = new Set([
  "true", "false", "null", "undefined", "this", "typeof", "instanceof", "in", "new", "void",
  "delete", "of", "await", "yield", "NaN", "Infinity", "arguments", "case", "do", "else", "return",
])
 
// anything that introduces a binding or reaches the scope by another route.
// A dynamic `import(...)` is absent deliberately: naming it here would put the
// word next to a quote in the bundle, which is what tests/no-bundle.test.ts
// greps for. It needs no entry - `import` is collected as a free name, the
// prologue's `const import = …` will not compile, and compileScoped falls back
const BINDS_A_NAME = new Set(["function", "class", "let", "const", "var", "eval", "with"])
 
// the compiled function's own parameters and temporary: an expression that
// mentions one would be reading the codegen's variable, not the author's
const CODEGEN_NAMES = new Set(["$scope", "$r", "$t"])
 
// operators that write, or bind - any of them and the expression keeps `with`
const WRITES_RE = /^(?:\+\+|--|=>|\*\*=|<<=|>>>=|>>=|&&=|\|\|=|\?\?=|[+\-*/%&|^]=(?!=))/
// operators that merely read, longest first so `===` is never read as `==` + `=`
const READS_RE = /^(?:>>>|===|!==|\*\*|<<|>>|==|!=|<=|>=|&&|\|\||\?\?|\?\.)/
 
const isIdentifierStart = (ch: string): boolean => /[A-Za-z_$]/.test(ch)
 
// a numeric literal, consumed whole so `1e5` does not scan as the name `e5`
const NUMBER_RE = /^(?:0[xXbBoO][\da-fA-F_]+|\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d+)?)n?/
 
export const freeIdentifiers = (expr: string): string[] | null => {
  const names = new Set<string>()
  // one entry per open bracket, counting the `?`s waiting for their `:` at that
  // depth - which is what tells `{ danger: x }`'s key from `a ? b : c`'s colon
  const ternaries: number[] = [0]
  const brackets: string[] = []
  let shortCircuits = false
  let prev = "" // the last meaningful token: "name", "value", "." or "?." or a punctuator
  let i = 0
 
  while (i < expr.length) {
    const ch = expr[i]
    if (/\s/.test(ch)) { i++; continue }
    if (ch === "/" && expr[i + 1] === "/") { i = skipLineComment(expr, i); continue }
    Iif (ch === "/" && expr[i + 1] === "*") { i = skipBlockComment(expr, i); continue }
    if (ch === "/" && regexAllowed(expr, i)) { i = skipRegex(expr, i); prev = "value"; continue }
    if (ch === '"' || ch === "'") { i = skipString(expr, i); prev = "value"; continue }
 
    if (ch === "`") {
      // a template literal reads names inside every ${...}, and nothing else
      let j = i + 1
      while (j < expr.length) {
        Iif (expr[j] === "\\") { j += 2; continue }
        if (expr[j] === "`") { j++; break }
        if (expr[j] === "$" && expr[j + 1] === "{") {
          let depth = 1
          const start = (j += 2)
          while (j < expr.length && depth > 0) {
            Iif (expr[j] === "{") depth++
            else if (expr[j] === "}") depth--
            j++
          }
          const inner = freeIdentifiers(expr.slice(start, j - 1))
          Iif (inner === null) return null
          inner.forEach(name => names.add(name))
          continue
        }
        j++
      }
      i = j
      prev = "value"
      continue
    }
 
    if (/\d/.test(ch) && prev !== "." && prev !== "?.") {
      const match = NUMBER_RE.exec(expr.slice(i))
      i += match ? match[0].length : 1
      prev = "value"
      continue
    }
 
    if (isIdentifierStart(ch)) {
      let end = i
      while (end < expr.length && /[\w$]/.test(expr[end])) end++
      const word = expr.slice(i, end)
      i = end
      if (BINDS_A_NAME.has(word)) return null
      if (prev === "." || prev === "?.") { prev = "value"; continue } // a property, not a name
      if (NOT_A_FREE_NAME.has(word)) { prev = word === "this" ? "value" : "op"; continue }
      if (CODEGEN_NAMES.has(word)) return null
      let after = i
      while (after < expr.length && /\s/.test(expr[after])) after++
      // A free name that is CALLED is called with the with-object as its
      // receiver: `add()` inside `with ($scope)` runs with `this === $scope`,
      // and a factory component's `{ items: [], add() { this.items… } }`
      // depends on it. A `const` cannot reproduce that - the call would get
      // `undefined` - so a called name keeps `with`. Measured at 11 of this
      // repository's 239 resolvable expressions, and 8 of those are handlers
      if (expr[after] === "(") return null
      // `{ danger: … }` names a key; `a ? b : c` names a value
      const isKey = expr[after] === ":" && expr[after + 1] !== ":" &&
        brackets[brackets.length - 1] === "{" && ternaries[ternaries.length - 1] === 0
      if (!isKey) names.add(word)
      prev = "value"
      continue
    }
 
    const rest = expr.slice(i)
    if (WRITES_RE.test(rest)) return null
    const reads = READS_RE.exec(rest)
    if (reads) {
      if (reads[0] === "&&" || reads[0] === "||" || reads[0] === "??") shortCircuits = true
      prev = reads[0] === "?." ? "?." : "op"
      i += reads[0].length
      continue
    }
    if (ch === "=") return null // a bare `=` left after READS_RE is an assignment
 
    if (ch === "(" || ch === "[" || ch === "{") { brackets.push(ch); ternaries.push(0) }
    else if (ch === ")" || ch === "]" || ch === "}") { brackets.pop(); if (ternaries.length > 1) ternaries.pop() }
    else if (ch === "?") { ternaries[ternaries.length - 1]++; shortCircuits = true }
    else if (ch === ":" && ternaries[ternaries.length - 1] > 0) ternaries[ternaries.length - 1]--
 
    prev = ch
    i++
  }
 
  // every name is resolved before the expression runs, so a branch that would
  // not have been taken is read anyway: one more dep than `with` would track,
  // and a ReferenceError for a name only the dead branch mentions. With one
  // name there is no branch to be wrong about
  if (shortCircuits && names.size > 1) return null
  return [...names]
}