@barefootjs/jsx 0.5.0 → 0.5.2

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.
Files changed (57) hide show
  1. package/dist/adapters/test-adapter.d.ts.map +1 -1
  2. package/dist/analyzer-context.d.ts +8 -1
  3. package/dist/analyzer-context.d.ts.map +1 -1
  4. package/dist/analyzer.d.ts.map +1 -1
  5. package/dist/expression-parser.d.ts.map +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +250 -59
  9. package/dist/ir-to-client-js/collect-elements.d.ts +11 -1
  10. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  11. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  12. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +14 -0
  13. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  14. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  15. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  16. package/dist/ir-to-client-js/html-template.d.ts +0 -14
  17. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/imports.d.ts +2 -2
  19. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  20. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/types.d.ts +7 -0
  22. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/utils.d.ts +2 -2
  24. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  25. package/dist/types.d.ts +17 -0
  26. package/dist/types.d.ts.map +1 -1
  27. package/package.json +2 -2
  28. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +310 -188
  29. package/src/__tests__/adapter-output.test.ts +49 -0
  30. package/src/__tests__/child-components-in-map.test.ts +43 -0
  31. package/src/__tests__/client-js-generation.test.ts +5 -2
  32. package/src/__tests__/inline-jsx-callback.test.ts +95 -0
  33. package/src/__tests__/ir-jsx-props.test.ts +5 -2
  34. package/src/__tests__/loop-item-conditional-codegen.test.ts +81 -0
  35. package/src/__tests__/map-logical-jsx-helper.test.ts +159 -0
  36. package/src/__tests__/missing-key-in-list.test.ts +49 -0
  37. package/src/__tests__/reactive-attrs-in-map.test.ts +41 -0
  38. package/src/adapters/test-adapter.ts +16 -1
  39. package/src/analyzer-context.ts +59 -13
  40. package/src/analyzer.ts +8 -0
  41. package/src/expression-parser.ts +16 -1
  42. package/src/index.ts +2 -0
  43. package/src/ir-to-client-js/collect-elements.ts +37 -15
  44. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +17 -0
  45. package/src/ir-to-client-js/control-flow/plan/loop.ts +14 -0
  46. package/src/ir-to-client-js/control-flow/stringify/insert.ts +7 -2
  47. package/src/ir-to-client-js/control-flow/stringify/loop.ts +60 -0
  48. package/src/ir-to-client-js/emit-reactive.ts +12 -3
  49. package/src/ir-to-client-js/html-template.ts +29 -3
  50. package/src/ir-to-client-js/imports.ts +2 -2
  51. package/src/ir-to-client-js/reactivity.ts +17 -1
  52. package/src/ir-to-client-js/types.ts +7 -0
  53. package/src/ir-to-client-js/utils.ts +2 -1
  54. package/src/jsx-to-ir.ts +161 -12
  55. package/src/preprocess-inline-jsx-callbacks.ts +28 -10
  56. package/src/scanner/__tests__/js-scanner.fuzz.test.ts +202 -0
  57. package/src/types.ts +18 -0
package/src/jsx-to-ir.ts CHANGED
@@ -1703,6 +1703,33 @@ function containsJsxInExpression(node: ts.Node): boolean {
1703
1703
  return ts.forEachChild(node, containsJsxInExpression) ?? false
1704
1704
  }
1705
1705
 
1706
+ /**
1707
+ * Check if an expression calls a module/local JSX-returning helper (one
1708
+ * tracked in `jsxFunctions` / `jsxMultiReturnFunctions` for IR-level
1709
+ * inlining). Used alongside `containsJsxInExpression` so a map callback
1710
+ * body like `cond && themeLogo(t.id)` is recognised as renderable JSX
1711
+ * control flow even though it has no inline JSX literal (#1665).
1712
+ */
1713
+ function callsJsxHelper(node: ts.Node, ctx: TransformContext): boolean {
1714
+ let found = false
1715
+ const visit = (n: ts.Node): void => {
1716
+ if (found) return
1717
+ if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
1718
+ const name = n.expression.text
1719
+ if (
1720
+ ctx.analyzer.jsxFunctions.has(name) ||
1721
+ ctx.analyzer.jsxMultiReturnFunctions.has(name)
1722
+ ) {
1723
+ found = true
1724
+ return
1725
+ }
1726
+ }
1727
+ ts.forEachChild(n, visit)
1728
+ }
1729
+ visit(node)
1730
+ return found
1731
+ }
1732
+
1706
1733
  function containsAwaitExpression(node: ts.Node): boolean {
1707
1734
  if (ts.isAwaitExpression(node)) return true
1708
1735
  if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)) return false
@@ -1893,7 +1920,7 @@ function transformJsxExpression(
1893
1920
  if (
1894
1921
  (node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken ||
1895
1922
  node.operatorToken.kind === ts.SyntaxKind.BarBarToken) &&
1896
- containsJsxInExpression(node.right)
1923
+ (containsJsxInExpression(node.right) || callsJsxHelper(node.right, ctx))
1897
1924
  ) {
1898
1925
  return transformNullishCoalescing(node, ctx)
1899
1926
  }
@@ -2642,18 +2669,34 @@ function checkLoopKey(
2642
2669
  }
2643
2670
  while (ts.isParenthesizedExpression(body)) body = body.expression
2644
2671
 
2672
+ // Check a JSX operand (unwrapping parentheses) if it is an element.
2673
+ function checkJsxOperand(node: ts.Node): void {
2674
+ let n = node
2675
+ while (ts.isParenthesizedExpression(n)) n = n.expression
2676
+ if (ts.isJsxElement(n)) checkOpening(n.openingElement)
2677
+ else if (ts.isJsxSelfClosingElement(n)) checkOpening(n)
2678
+ }
2679
+
2645
2680
  if (ts.isConditionalExpression(body)) {
2646
2681
  // Check both branches independently
2647
- const whenTrue = body.whenTrue
2648
- const whenFalse = body.whenFalse
2649
- let wt: ts.Node = whenTrue
2650
- let wf: ts.Node = whenFalse
2651
- while (ts.isParenthesizedExpression(wt)) wt = wt.expression
2652
- while (ts.isParenthesizedExpression(wf)) wf = wf.expression
2653
- if (ts.isJsxElement(wt)) checkOpening(wt.openingElement)
2654
- else if (ts.isJsxSelfClosingElement(wt)) checkOpening(wt)
2655
- if (ts.isJsxElement(wf)) checkOpening(wf.openingElement)
2656
- else if (ts.isJsxSelfClosingElement(wf)) checkOpening(wf)
2682
+ checkJsxOperand(body.whenTrue)
2683
+ checkJsxOperand(body.whenFalse)
2684
+ return
2685
+ }
2686
+
2687
+ // Logical `cond && <jsx>` / `cond || <jsx>` / `a ?? <jsx>` whole-item
2688
+ // conditionals (#1665). The JSX operand renders 0-or-1 element per
2689
+ // iteration and still needs a key for correct reconciliation, exactly
2690
+ // like a ternary branch. Without this case the binary-expression body
2691
+ // silently skipped key validation.
2692
+ if (
2693
+ ts.isBinaryExpression(body) &&
2694
+ (body.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
2695
+ body.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
2696
+ body.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken)
2697
+ ) {
2698
+ checkJsxOperand(body.left)
2699
+ checkJsxOperand(body.right)
2657
2700
  return
2658
2701
  }
2659
2702
 
@@ -2679,6 +2722,69 @@ function loopBodyIsMultiRoot(children: IRNode[]): boolean {
2679
2722
  return loopBodyIsMultiRoot(only.children)
2680
2723
  }
2681
2724
 
2725
+ /**
2726
+ * True when a conditional branch does NOT render exactly one root element —
2727
+ * the element-less side of a whole-item conditional. Covers the empty branch
2728
+ * of `cond && <li/>` (`null`) and `cond ? <li/> : null`, and the scalar side
2729
+ * of `expr || <li/>` / `expr ?? <li/>` (the left operand renders as text or
2730
+ * nothing, never a tracked element). Any such branch makes the loop item
2731
+ * render 0-or-1 element across states, which the element-tracking `mapArray`
2732
+ * cannot represent — the loop must use anchored emission instead.
2733
+ *
2734
+ * Element / component branches return `false`; a fragment is element-like
2735
+ * only when it flattens to exactly one element child.
2736
+ */
2737
+ function branchHasNoElement(node: IRNode): boolean {
2738
+ if (node.type === 'element' || node.type === 'component') return false
2739
+ if (node.type === 'conditional') {
2740
+ return branchHasNoElement(node.whenTrue) || branchHasNoElement(node.whenFalse)
2741
+ }
2742
+ if (node.type === 'fragment') {
2743
+ const real = node.children.filter(
2744
+ (c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim())
2745
+ )
2746
+ return real.length !== 1 || branchHasNoElement(real[0])
2747
+ }
2748
+ // expression, text, and everything else: not a single tracked element.
2749
+ return true
2750
+ }
2751
+
2752
+ /**
2753
+ * When the loop body is a single whole-item conditional with an element-less
2754
+ * branch (the #1665 shapes: `&&`, `|| <jsx>`, `?? <jsx>`, `? <jsx> : null`),
2755
+ * return that conditional so the caller can route the loop through anchored
2756
+ * emission. Returns `null` for single-element bodies and for both-branch-
2757
+ * element ternaries (which always render exactly one element and stay on the
2758
+ * legacy `mapArray` path).
2759
+ */
2760
+ function loopBodyItemConditional(children: IRNode[]): IRConditional | null {
2761
+ const real = children.filter(
2762
+ (c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim())
2763
+ )
2764
+ if (real.length !== 1) return null
2765
+ const only = real[0]
2766
+ if (only.type !== 'conditional') return null
2767
+ if (branchHasNoElement(only.whenTrue) || branchHasNoElement(only.whenFalse)) {
2768
+ return only
2769
+ }
2770
+ return null
2771
+ }
2772
+
2773
+ /**
2774
+ * Hoist a key expression out of a whole-item conditional for `mapArray`'s
2775
+ * keyFn. Ignores element-less branches (they carry no element and thus no
2776
+ * key) and requires the rendering branch(es) to agree on the key expression.
2777
+ * Returns `null` when no key can be determined.
2778
+ */
2779
+ function extractItemConditionalKey(cond: IRConditional): string | null {
2780
+ const a = branchHasNoElement(cond.whenTrue) ? null : extractLoopKey(cond.whenTrue)
2781
+ const b = branchHasNoElement(cond.whenFalse) ? null : extractLoopKey(cond.whenFalse)
2782
+ if (a !== null && b !== null) {
2783
+ return normalizeKeyExpr(a) === normalizeKeyExpr(b) ? a : null
2784
+ }
2785
+ return a ?? b
2786
+ }
2787
+
2682
2788
  function transformMapCall(
2683
2789
  node: ts.CallExpression,
2684
2790
  ctx: TransformContext,
@@ -2947,6 +3053,36 @@ function transformMapCall(
2947
3053
  }
2948
3054
  if (index) ctx.loopParams.add(index)
2949
3055
 
3056
+ // Logical control flow (`cond && <X/>`, `a ?? themeLogo()`) as the map
3057
+ // body. This is not a JSX literal, ternary, or block, so without this
3058
+ // the dispatch below leaves `children` empty and the whole `.map(...)`
3059
+ // falls through to the reactive-text path — emitting the callback
3060
+ // verbatim. That left inline JSX uncompiled and module-level JSX
3061
+ // helpers undeclared (ReferenceError at hydration, #1665). Route the
3062
+ // logical body through the shared JSX expression transformer, which
3063
+ // lowers it into an IRConditional and inlines any JSX helper, exactly
3064
+ // like the ternary form.
3065
+ //
3066
+ // Scoped deliberately to logical operators that actually render JSX
3067
+ // (inline literal or a tracked helper call): a bare call body
3068
+ // (`map(t => renderItem(t))`) stays on the existing reactive-text path
3069
+ // that #546 owns, and a scalar logical body (`t.active && t.label`)
3070
+ // keeps rendering its value.
3071
+ const tryTransformRenderableBody = (expr: ts.Expression): void => {
3072
+ if (!ts.isBinaryExpression(expr)) return
3073
+ const op = expr.operatorToken.kind
3074
+ if (
3075
+ op !== ts.SyntaxKind.AmpersandAmpersandToken &&
3076
+ op !== ts.SyntaxKind.BarBarToken &&
3077
+ op !== ts.SyntaxKind.QuestionQuestionToken
3078
+ ) {
3079
+ return
3080
+ }
3081
+ if (!containsJsxInExpression(expr) && !callsJsxHelper(expr, ctx)) return
3082
+ const transformed = transformJsxExpression(expr, ctx, isClientOnly)
3083
+ if (transformed) children = [transformed]
3084
+ }
3085
+
2950
3086
  // Transform callback body
2951
3087
  const body = callback.body
2952
3088
  if (ts.isJsxElement(body) || ts.isJsxSelfClosingElement(body) || ts.isJsxFragment(body)) {
@@ -2973,6 +3109,8 @@ function transformMapCall(
2973
3109
  } else if (method === 'flatMap' && ts.isArrayLiteralExpression(inner)) {
2974
3110
  // flatMap arrow with array literal: items.flatMap(item => ([<A/>, <B/>]))
2975
3111
  children = transformArrayLiteralChildren(inner, ctx)
3112
+ } else {
3113
+ tryTransformRenderableBody(inner)
2976
3114
  }
2977
3115
  } else if (method === 'flatMap' && ts.isArrayLiteralExpression(body)) {
2978
3116
  // flatMap arrow with array literal: items.flatMap(item => [<A/>, <B/>])
@@ -3025,6 +3163,8 @@ function transformMapCall(
3025
3163
  if (method === 'flatMap' && children.length === 0) {
3026
3164
  flatMapCallback = buildFlatMapCallback(callback, body, ctx)
3027
3165
  }
3166
+ } else {
3167
+ tryTransformRenderableBody(body)
3028
3168
  }
3029
3169
 
3030
3170
  // Unregister loop params
@@ -3055,7 +3195,15 @@ function transformMapCall(
3055
3195
  // same `key={EXPR}`, that EXPR is lifted out to mapArray's keyFn so a
3056
3196
  // shape change (e.g. `<polygon>` ↔ `<circle>`) replaces the DOM node
3057
3197
  // instead of mutating attributes on the wrong tag.
3058
- const key = children.length > 0 ? extractLoopKey(children[0]) : null
3198
+ // Whole-item conditional bodies (#1665): the loop item is a single
3199
+ // conditional whose at-least-one branch renders nothing, so an item shows
3200
+ // 0-or-1 element. The key lives inside the rendering branch, so hoist it
3201
+ // from there; a flag routes the loop through anchored emission downstream.
3202
+ const itemConditional = children.length > 0 ? loopBodyItemConditional(children) : null
3203
+ const bodyIsItemConditional = itemConditional !== null
3204
+ const key = bodyIsItemConditional
3205
+ ? extractItemConditionalKey(itemConditional!)
3206
+ : (children.length > 0 ? extractLoopKey(children[0]) : null)
3059
3207
 
3060
3208
  // Extract childComponent info if the loop body is a single component
3061
3209
  // This enables createComponent-based rendering with proper prop passing
@@ -3137,6 +3285,7 @@ function transformMapCall(
3137
3285
  callsReactiveGetters: callsReactive || undefined,
3138
3286
  hasFunctionCalls: hasCalls || undefined,
3139
3287
  bodyIsMultiRoot: bodyIsMultiRoot || undefined,
3288
+ bodyIsItemConditional: bodyIsItemConditional || undefined,
3140
3289
  childComponent,
3141
3290
  nestedComponents,
3142
3291
  filterPredicate,
@@ -128,22 +128,40 @@ function runSinglePass(
128
128
  }
129
129
 
130
130
  function visit(node: ts.Node): void {
131
+ // `renderNode={(n) => <div/>}` — arrow in JsxAttribute position.
131
132
  if (ts.isJsxAttribute(node) && node.initializer && ts.isJsxExpression(node.initializer) && node.initializer.expression) {
132
- let expr: ts.Expression = node.initializer.expression
133
- while (ts.isParenthesizedExpression(expr)) expr = expr.expression
134
- if (ts.isArrowFunction(expr) && arrowBodyContainsJsx(expr)) {
135
- const handled = handleInlineArrow(expr)
136
- if (handled) {
137
- // Don't dive into the arrow's body in this pass — the next
138
- // fixpoint iteration will see the synthesized component at
139
- // module scope and process any nested inline arrows there.
140
- return
141
- }
133
+ if (tryHandleArrowValue(node.initializer.expression)) {
134
+ // Don't dive into the arrow's body in this pass — the next
135
+ // fixpoint iteration will see the synthesized component at
136
+ // module scope and process any nested inline arrows there.
137
+ return
142
138
  }
143
139
  }
140
+ // `{ piconic: () => <BrandLogo/> }` — arrow as an object-literal
141
+ // property value (e.g. a `Record<K, () => JSX>` lookup map). Without
142
+ // this the JSX leaks untransformed into both the SSR template and the
143
+ // client bundle (#1663).
144
+ if (ts.isPropertyAssignment(node) && node.initializer) {
145
+ if (tryHandleArrowValue(node.initializer)) return
146
+ }
144
147
  ts.forEachChild(node, visit)
145
148
  }
146
149
 
150
+ /**
151
+ * If `initializer` is (a parenthesized chain wrapping) an arrow function
152
+ * whose body contains JSX, hoist it into a synthesized component and
153
+ * record the replacement. Returns true when the arrow was successfully
154
+ * hoisted, so the caller can skip recursing into the arrow body.
155
+ */
156
+ function tryHandleArrowValue(initializer: ts.Expression): boolean {
157
+ let expr: ts.Expression = initializer
158
+ while (ts.isParenthesizedExpression(expr)) expr = expr.expression
159
+ if (ts.isArrowFunction(expr) && arrowBodyContainsJsx(expr)) {
160
+ return handleInlineArrow(expr)
161
+ }
162
+ return false
163
+ }
164
+
147
165
  function handleInlineArrow(arrow: ts.ArrowFunction): boolean {
148
166
  const paramNames = collectArrowParamNames(arrow)
149
167
  const free = collectFreeIdentifiers(arrow)
@@ -0,0 +1,202 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import {
3
+ replaceInExprContexts,
4
+ findInterpolationEnd,
5
+ findTopLevelTemplateLiterals,
6
+ } from '../js-scanner'
7
+ import { tokenContainsIdent, wrapLoopParamAsAccessor } from '../../ir-to-client-js/utils'
8
+
9
+ /**
10
+ * Fuzz harness for the shared `ts.createScanner`-based JS-text scanner (#1370).
11
+ *
12
+ * The bug class this issue targets — hand-rolled char-by-char scanners that
13
+ * disagree about where "code context" ends — only shows up on inputs that mix
14
+ * quotes, comments, escapes and regex tokens in adversarial ways. The
15
+ * example-based suite in `js-scanner.test.ts` pins specific known cases; this
16
+ * file generates random combinations and asserts that *every* consumer of the
17
+ * shared lexer honours the same invariant:
18
+ *
19
+ * a bare `MARK` identifier is a real code reference **iff** it sits in
20
+ * expression context — never when it appears inside a string, template
21
+ * string body, comment or regex literal.
22
+ *
23
+ * Each generated input is paired with an exact oracle computed from the atoms
24
+ * it was assembled from, so the assertions are precise (not just "didn't
25
+ * throw"). Generation is seeded per-iteration with a deterministic PRNG, and
26
+ * the seed + input are surfaced on failure so any regression reproduces.
27
+ */
28
+
29
+ // --- deterministic PRNG (mulberry32) ---------------------------------------
30
+ function mulberry32(seed: number): () => number {
31
+ let a = seed >>> 0
32
+ return () => {
33
+ a = (a + 0x6d2b79f5) | 0
34
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
35
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
36
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
37
+ }
38
+ }
39
+
40
+ const pick = <T>(rng: () => number, arr: readonly T[]): T => arr[Math.floor(rng() * arr.length)]!
41
+
42
+ // Alphabet deliberately loaded with the delimiters that fooled the old
43
+ // per-consumer scanners: every quote flavour, comment markers, regex slashes,
44
+ // braces, escapes and the marker letters themselves.
45
+ const NOISE_ALPHABET = [
46
+ 'a', 'M', 'A', 'R', 'K', 'q', 'z', ' ',
47
+ "'", '"', '`', '/', '*', '{', '}', '$', '\\', ';', '(', ')', '[', ']',
48
+ ] as const
49
+
50
+ function randNoise(rng: () => number, maxLen = 10): string {
51
+ const len = Math.floor(rng() * (maxLen + 1))
52
+ let s = ''
53
+ for (let i = 0; i < len; i++) s += pick(rng, NOISE_ALPHABET)
54
+ return s
55
+ }
56
+
57
+ // --- per-context sanitizers: make `raw` safe to embed without changing how it
58
+ // lexes, so the embedded text round-trips byte-for-byte in the oracle. ---
59
+ const escDouble = (raw: string) => raw.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/[\r\n]/g, '')
60
+ const escSingle = (raw: string) => raw.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/[\r\n]/g, '')
61
+ // No-substitution template: kill backticks and any `${` interpolation opener.
62
+ const escTemplate = (raw: string) => raw.replace(/\\/g, '\\\\').replace(/`/g, '').replace(/\$/g, '').replace(/[\r\n]/g, '')
63
+ const escLine = (raw: string) => raw.replace(/[\r\n]/g, '')
64
+ const escBlock = (raw: string) => raw.replace(/[\r\n]/g, '').replace(/\*\//g, '* /')
65
+ // Regex body: escape the delimiter and drop char-class brackets so the literal
66
+ // always terminates at the next `/`. Prefix a literal char so it is never empty
67
+ // (which would read as `//` line comment) nor start with `*`.
68
+ const escRegex = (raw: string) =>
69
+ 'x' + raw.replace(/\\/g, '\\\\').replace(/\//g, '\\/').replace(/\[/g, '\\[').replace(/\]/g, '\\]').replace(/[\r\n]/g, '')
70
+
71
+ interface Atom {
72
+ /** Source text of the atom as it appears in the input. */
73
+ src: string
74
+ /** What this atom becomes after a `MARK` -> `MARK()` expression-context rewrite. */
75
+ rewritten: string
76
+ /** True only for a bare-identifier `MARK` sitting in code context. */
77
+ isCodeMarker: boolean
78
+ }
79
+
80
+ // Plain code fragments that carry no `MARK` and no structural `{`/`}` (so the
81
+ // only top-level braces in any input come from the `${...}` wrap we add later).
82
+ const CODE_PLAIN = ['a', 'b.c', 'foo(1)', 'arr[0]', 'n / 2', 'x + y', 'obj.prop', '1.5'] as const
83
+
84
+ function makeAtom(rng: () => number): Atom {
85
+ const kind = pick(rng, [
86
+ 'codeMarker', 'codeMarker', 'codePlain',
87
+ 'dq', 'sq', 'tmpl', 'line', 'block', 'regex',
88
+ ] as const)
89
+ switch (kind) {
90
+ case 'codeMarker':
91
+ return { src: 'MARK', rewritten: 'MARK()', isCodeMarker: true }
92
+ case 'codePlain': {
93
+ const src = pick(rng, CODE_PLAIN)
94
+ return { src, rewritten: src, isCodeMarker: false }
95
+ }
96
+ case 'dq': {
97
+ const src = '"' + escDouble(randNoise(rng)) + '"'
98
+ return { src, rewritten: src, isCodeMarker: false }
99
+ }
100
+ case 'sq': {
101
+ const src = "'" + escSingle(randNoise(rng)) + "'"
102
+ return { src, rewritten: src, isCodeMarker: false }
103
+ }
104
+ case 'tmpl': {
105
+ const src = '`' + escTemplate(randNoise(rng)) + '`'
106
+ return { src, rewritten: src, isCodeMarker: false }
107
+ }
108
+ case 'line': {
109
+ // Trailing newline terminates the comment so the joining ` + ` that
110
+ // follows stays in code context.
111
+ const src = '// ' + escLine(randNoise(rng)) + '\n'
112
+ return { src, rewritten: src, isCodeMarker: false }
113
+ }
114
+ case 'block': {
115
+ const src = '/* ' + escBlock(randNoise(rng)) + ' */'
116
+ return { src, rewritten: src, isCodeMarker: false }
117
+ }
118
+ case 'regex': {
119
+ const src = '/' + escRegex(randNoise(rng)) + '/' + pick(rng, ['', 'g', 'i', 'gi', 'm'])
120
+ return { src, rewritten: src, isCodeMarker: false }
121
+ }
122
+ }
123
+ }
124
+
125
+ interface Generated {
126
+ input: string
127
+ /** Input after every code-context `MARK` is rewritten to `MARK()`. */
128
+ expected: string
129
+ /** Whether at least one `MARK` reference lives in code context. */
130
+ hasCodeMarker: boolean
131
+ }
132
+
133
+ function generate(rng: () => number): Generated {
134
+ const count = 1 + Math.floor(rng() * 8)
135
+ const atoms: Atom[] = []
136
+ for (let i = 0; i < count; i++) atoms.push(makeAtom(rng))
137
+ // ` + ` keeps the stream lexable and puts every regex atom in a
138
+ // regex-start position (after an operator).
139
+ const input = atoms.map(a => a.src).join(' + ')
140
+ const expected = atoms.map(a => a.rewritten).join(' + ')
141
+ const hasCodeMarker = atoms.some(a => a.isCodeMarker)
142
+ return { input, expected, hasCodeMarker }
143
+ }
144
+
145
+ const ITERATIONS = 600
146
+
147
+ describe('js-scanner fuzz: code-context opacity holds across all consumers', () => {
148
+ test('replaceInExprContexts rewrites MARK only outside strings/comments/regex/templates', () => {
149
+ for (let i = 0; i < ITERATIONS; i++) {
150
+ const seed = (0x9e3779b9 ^ i) >>> 0
151
+ const { input, expected } = generate(mulberry32(seed))
152
+ const got = replaceInExprContexts(input, /\bMARK\b/g, 'MARK()')
153
+ expect(got, `seed=${seed} input=${JSON.stringify(input)}`).toBe(expected)
154
+ }
155
+ })
156
+
157
+ test('wrapLoopParamAsAccessor agrees with replaceInExprContexts on the same inputs', () => {
158
+ for (let i = 0; i < ITERATIONS; i++) {
159
+ const seed = (0x85ebca6b ^ i) >>> 0
160
+ const { input, expected } = generate(mulberry32(seed))
161
+ const got = wrapLoopParamAsAccessor(input, 'MARK')
162
+ expect(got, `seed=${seed} input=${JSON.stringify(input)}`).toBe(expected)
163
+ }
164
+ })
165
+
166
+ test('tokenContainsIdent reports MARK iff a code-context occurrence exists', () => {
167
+ for (let i = 0; i < ITERATIONS; i++) {
168
+ const seed = (0xc2b2ae35 ^ i) >>> 0
169
+ const { input, hasCodeMarker } = generate(mulberry32(seed))
170
+ const got = tokenContainsIdent(input, 'MARK')
171
+ expect(got, `seed=${seed} input=${JSON.stringify(input)}`).toBe(hasCodeMarker)
172
+ }
173
+ })
174
+
175
+ test('findInterpolationEnd finds the real closing brace despite braces in noise', () => {
176
+ for (let i = 0; i < ITERATIONS; i++) {
177
+ const seed = (0x27d4eb2f ^ i) >>> 0
178
+ const { input } = generate(mulberry32(seed))
179
+ // Braces only appear inside opaque tokens (strings/regex/comments/
180
+ // templates) of `input`; the wrap adds the single top-level pair.
181
+ const wrapped = '${' + input + '}'
182
+ const end = findInterpolationEnd(wrapped, 2)
183
+ expect(end, `seed=${seed} wrapped=${JSON.stringify(wrapped)}`).toBe(wrapped.length - 1)
184
+ }
185
+ })
186
+ })
187
+
188
+ // findTopLevelTemplateLiterals operates on a ternary shape; fuzz its branch
189
+ // bodies with noise that must stay inside the backtick literals.
190
+ describe('js-scanner fuzz: findTopLevelTemplateLiterals extracts noisy branches', () => {
191
+ test('returns both backtick branches verbatim regardless of embedded delimiters', () => {
192
+ for (let i = 0; i < ITERATIONS; i++) {
193
+ const seed = (0x165667b1 ^ i) >>> 0
194
+ const rng = mulberry32(seed)
195
+ const a = escTemplate(randNoise(rng))
196
+ const b = escTemplate(randNoise(rng))
197
+ const src = 'cond ? `' + a + '` : `' + b + '`'
198
+ const got = findTopLevelTemplateLiterals(src)
199
+ expect(got, `seed=${seed} src=${JSON.stringify(src)}`).toEqual([a, b])
200
+ }
201
+ })
202
+ })
package/src/types.ts CHANGED
@@ -532,6 +532,18 @@ export interface IRLoop {
532
532
  */
533
533
  bodyIsMultiRoot?: boolean
534
534
 
535
+ /**
536
+ * True when the loop body is a single whole-item conditional whose at
537
+ * least one branch renders no element (`arr.map(t => cond && <li/>)` or
538
+ * `cond ? <li/> : null`), so an item renders 0-or-1 element per pass
539
+ * (#1665). Drives anchored emission: per-item `<!--bf-loop-i:KEY-->`
540
+ * anchors in the template and a `mapArrayAnchored` call whose renderItem
541
+ * lets `insert()` own the (possibly empty) content. Single-element bodies
542
+ * and both-branch-element ternaries set this false and keep the legacy
543
+ * `mapArray` emission.
544
+ */
545
+ bodyIsItemConditional?: boolean
546
+
535
547
  /**
536
548
  * Raw JS of pre-return statements in block body .map() callback.
537
549
  * Example: `items.map(item => { const label = item.name.toUpperCase(); return <li>{label}</li> })`
@@ -1279,6 +1291,12 @@ export interface TypeDefinition {
1279
1291
  kind: 'interface' | 'type'
1280
1292
  name: string
1281
1293
  definition: string // Original TypeScript definition
1294
+ /**
1295
+ * Structured fields for object/interface shapes, so adapters can consume the
1296
+ * field set (names + types) without re-parsing `definition`. Absent for
1297
+ * type aliases that aren't object types (e.g. string-literal unions).
1298
+ */
1299
+ properties?: PropertyInfo[]
1282
1300
  loc: SourceLocation
1283
1301
  }
1284
1302