@barefootjs/jsx 0.39.4 → 0.39.6

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 (97) hide show
  1. package/dist/adapters/array-method.d.ts +93 -0
  2. package/dist/adapters/array-method.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts +135 -0
  4. package/dist/adapters/attr-plan.d.ts.map +1 -0
  5. package/dist/adapters/boolean-result.d.ts +84 -9
  6. package/dist/adapters/boolean-result.d.ts.map +1 -1
  7. package/dist/adapters/callback-method.d.ts +126 -0
  8. package/dist/adapters/callback-method.d.ts.map +1 -0
  9. package/dist/adapters/component-props.d.ts +99 -0
  10. package/dist/adapters/component-props.d.ts.map +1 -0
  11. package/dist/adapters/component-tree.d.ts +25 -0
  12. package/dist/adapters/component-tree.d.ts.map +1 -0
  13. package/dist/adapters/filter-capture-collisions.d.ts +17 -0
  14. package/dist/adapters/filter-capture-collisions.d.ts.map +1 -0
  15. package/dist/adapters/literal-value.d.ts +22 -0
  16. package/dist/adapters/literal-value.d.ts.map +1 -0
  17. package/dist/adapters/loop-plan.d.ts +53 -0
  18. package/dist/adapters/loop-plan.d.ts.map +1 -0
  19. package/dist/adapters/parsed-expr-emitter.d.ts +8 -0
  20. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  21. package/dist/adapters/prop-classes.d.ts +37 -0
  22. package/dist/adapters/prop-classes.d.ts.map +1 -0
  23. package/dist/adapters/template-name-collisions.d.ts +21 -0
  24. package/dist/adapters/template-name-collisions.d.ts.map +1 -0
  25. package/dist/analyzer-context.d.ts.map +1 -1
  26. package/dist/expression-parser.d.ts +48 -0
  27. package/dist/expression-parser.d.ts.map +1 -1
  28. package/dist/index.d.ts +20 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +2077 -1000
  31. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +8 -0
  33. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts +3 -2
  35. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/utils.d.ts +39 -1
  39. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  40. package/dist/jsx-to-ir.d.ts +465 -1
  41. package/dist/jsx-to-ir.d.ts.map +1 -1
  42. package/dist/nullable-signal-attr.d.ts +31 -0
  43. package/dist/nullable-signal-attr.d.ts.map +1 -1
  44. package/dist/scope/binding-scope.d.ts +10 -0
  45. package/dist/scope/binding-scope.d.ts.map +1 -1
  46. package/dist/types.d.ts +7 -0
  47. package/dist/types.d.ts.map +1 -1
  48. package/package.json +2 -2
  49. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
  50. package/src/__tests__/action-accessor.test.ts +6 -24
  51. package/src/__tests__/array-method-catalogue.test.ts +99 -0
  52. package/src/__tests__/attr-plan.test.ts +121 -0
  53. package/src/__tests__/binding-scope-ratchet.test.ts +13 -13
  54. package/src/__tests__/binding-scope.test.ts +11 -0
  55. package/src/__tests__/boolean-result-expr.test.ts +106 -0
  56. package/src/__tests__/boolean-result.test.ts +34 -1
  57. package/src/__tests__/callback-method.test.ts +189 -0
  58. package/src/__tests__/compile-without-node-process.test.ts +78 -0
  59. package/src/__tests__/component-props.test.ts +148 -0
  60. package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
  61. package/src/__tests__/doc-examples.test.ts +1 -0
  62. package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
  63. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
  64. package/src/__tests__/loop-plan.test.ts +104 -0
  65. package/src/__tests__/map-call-decisions.test.ts +521 -0
  66. package/src/__tests__/nested-row-shadowing.test.ts +57 -0
  67. package/src/__tests__/nullable-signal-attr.test.ts +45 -0
  68. package/src/__tests__/rename-free-identifiers.test.ts +26 -0
  69. package/src/__tests__/template-name-collisions.test.ts +81 -0
  70. package/src/adapters/array-method.ts +193 -0
  71. package/src/adapters/attr-plan.ts +200 -0
  72. package/src/adapters/boolean-result.ts +208 -12
  73. package/src/adapters/callback-method.ts +301 -0
  74. package/src/adapters/component-props.ts +144 -0
  75. package/src/adapters/component-tree.ts +118 -0
  76. package/src/adapters/filter-capture-collisions.ts +29 -0
  77. package/src/adapters/literal-value.ts +36 -0
  78. package/src/adapters/loop-plan.ts +88 -0
  79. package/src/adapters/parsed-expr-emitter.ts +18 -0
  80. package/src/adapters/prop-classes.ts +73 -0
  81. package/src/adapters/template-name-collisions.ts +120 -0
  82. package/src/analyzer-context.ts +15 -1
  83. package/src/expression-parser.ts +569 -374
  84. package/src/index.ts +58 -3
  85. package/src/ir-to-client-js/collect-elements.ts +11 -7
  86. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +31 -10
  87. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +12 -5
  88. package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +2 -2
  89. package/src/ir-to-client-js/control-flow/shared.ts +4 -1
  90. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
  91. package/src/ir-to-client-js/html-template.ts +13 -7
  92. package/src/ir-to-client-js/index.ts +7 -2
  93. package/src/ir-to-client-js/utils.ts +81 -7
  94. package/src/jsx-to-ir.ts +1328 -991
  95. package/src/nullable-signal-attr.ts +116 -6
  96. package/src/scope/binding-scope.ts +19 -0
  97. package/src/types.ts +7 -0
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The props a DSL adapter passes to a child component's `render_child`
3
+ * call (#3479), as data.
4
+ *
5
+ * Every DSL adapter assembles them the same way: callback props and `ref`
6
+ * are client-only and dropped; a named JSX-valued prop is captured as
7
+ * HTML; `{...props}` (the component's own props object, which no DSL scope
8
+ * holds as one value) enumerates the props params; any other spread is
9
+ * folded in at its source position, so a later entry wins on a key
10
+ * conflict, as in `{...a, ...b}`; then the compiler-controlled `_bf_slot`
11
+ * and `children` entries come last, so a spread can never override them.
12
+ * {@link planComponentProps} makes those decisions once. An adapter spells
13
+ * the entries and spreads through {@link spellComponentProps}, keeps its
14
+ * own capture mechanism (`{% set %}…{% endset %}`, `_erbout.slice!`,
15
+ * `begin … end`, a Kolon macro), and folds the spelled segments into its
16
+ * own hash literal.
17
+ */
18
+
19
+ import { resolveJsxChildrenProp } from '@barefootjs/shared'
20
+ import type { AttrValue, IRComponent, IRNode, SpreadAttr } from '../types.ts'
21
+ import { derivesScopeFromSlot } from './child-scope.ts'
22
+
23
+ /** One entry of the props hash. */
24
+ export type ComponentPropEntry =
25
+ /** An ordinary prop: the adapter lowers `value` with its `AttrValueEmitter`. */
26
+ | { kind: 'value'; name: string; value: AttrValue }
27
+ /** A named JSX-valued prop (`header={<b/>}`): captured as HTML, passed by reference. */
28
+ | { kind: 'named-slot'; name: string; children: IRNode[] }
29
+ /** One param of a spread props object (`{...props}`), read from its own template variable. */
30
+ | { kind: 'props-param'; name: string }
31
+ /** The child's mount slot, for its scope id (`derivesScopeFromSlot`). */
32
+ | { kind: 'slot-id'; slotId: string }
33
+ /** The forwarded children (nested `<Box>…</Box>`, or `children={<jsx/>}`): captured as HTML. */
34
+ | { kind: 'children'; children: IRNode[] }
35
+
36
+ /** A run of entries, or a spread folded in at its source position. */
37
+ export type ComponentPropSegment =
38
+ | { kind: 'entries'; entries: ComponentPropEntry[] }
39
+ | { kind: 'spread'; value: SpreadAttr }
40
+
41
+ export interface ComponentPropsOptions {
42
+ /** The SolidJS-style props identifier (`function C(props: P)`), if any. */
43
+ propsObjectName: string | null
44
+ /** The analyzer-extracted props params, which `{...props}` enumerates. */
45
+ propsParams: ReadonlyArray<{ name: string }>
46
+ }
47
+
48
+ /** The key an entry sets in the props hash. */
49
+ export function componentPropKey(entry: ComponentPropEntry): string {
50
+ if (entry.kind === 'slot-id') return '_bf_slot'
51
+ if (entry.kind === 'children') return 'children'
52
+ return entry.name
53
+ }
54
+
55
+ /**
56
+ * The ordered props segments for `comp`. The first segment is always an
57
+ * (possibly empty) entries segment, and a spread is followed by a new one
58
+ * only when an entry comes after it.
59
+ */
60
+ export function planComponentProps(comp: IRComponent, options: ComponentPropsOptions): ComponentPropSegment[] {
61
+ const segments: ComponentPropSegment[] = [{ kind: 'entries', entries: [] }]
62
+ const push = (entry: ComponentPropEntry) => {
63
+ const last = segments[segments.length - 1]!
64
+ if (last.kind !== 'entries') {
65
+ segments.push({ kind: 'entries', entries: [entry] })
66
+ return
67
+ }
68
+ // A repeated key keeps its first position and takes the later value, as
69
+ // in a JS object literal (`{...props, tone: 'x'}`), so no backend sees a
70
+ // duplicate key (Ruby warns on one in a hash literal).
71
+ const at = last.entries.findIndex((e) => componentPropKey(e) === componentPropKey(entry))
72
+ if (at === -1) last.entries.push(entry)
73
+ else last.entries[at] = entry
74
+ }
75
+ for (const p of comp.props) {
76
+ // Callback props and `ref` are client-only for SSR: Hono renders
77
+ // neither, and the client JS wires them at hydration.
78
+ if ((/^on[A-Z]/.test(p.name) || p.name === 'ref') && p.value.kind === 'expression') continue
79
+ if (p.value.kind === 'jsx-children') {
80
+ // `children={<jsx/>}` is forwarded as the `children` entry below.
81
+ if (p.name !== 'children') push({ kind: 'named-slot', name: p.name, children: p.value.children })
82
+ } else if (p.value.kind === 'spread') {
83
+ if (options.propsObjectName !== null && options.propsObjectName === p.value.expr.trim()) {
84
+ for (const param of options.propsParams) push({ kind: 'props-param', name: param.name })
85
+ } else {
86
+ segments.push({ kind: 'spread', value: p.value })
87
+ }
88
+ } else {
89
+ push({ kind: 'value', name: p.name, value: p.value })
90
+ }
91
+ }
92
+ // A loop row root takes a fresh scope id instead (#2444).
93
+ if (derivesScopeFromSlot(comp)) push({ kind: 'slot-id', slotId: comp.slotId! })
94
+ const children = comp.children.length > 0 ? comp.children : resolveJsxChildrenProp(comp.props)
95
+ if (children.length > 0) push({ kind: 'children', children })
96
+ return segments
97
+ }
98
+
99
+ /** A spelled segment: the entries' hash-literal parts, or the spread's expression. */
100
+ export type SpelledComponentPropSegment = { kind: 'entries'; parts: string[] } | { kind: 'spread'; expr: string }
101
+
102
+ export interface ComponentPropSpelling {
103
+ /** The hash-literal part for one entry; `''` drops it. */
104
+ entry(entry: ComponentPropEntry): string
105
+ /** The expression a spread folds in. */
106
+ spread(value: SpreadAttr): string
107
+ }
108
+
109
+ /**
110
+ * Spell a plan in source order, so the captures an entry's spelling emits
111
+ * (named slots, then the children) keep their order and counter values.
112
+ */
113
+ export function spellComponentProps(
114
+ segments: readonly ComponentPropSegment[],
115
+ spelling: ComponentPropSpelling,
116
+ ): SpelledComponentPropSegment[] {
117
+ return segments.map((segment) => {
118
+ if (segment.kind === 'spread') return { kind: 'spread', expr: spelling.spread(segment.value) }
119
+ const parts: string[] = []
120
+ for (const entry of segment.entries) {
121
+ const part = spelling.entry(entry)
122
+ if (part) parts.push(part)
123
+ }
124
+ return { kind: 'entries', parts }
125
+ })
126
+ }
127
+
128
+ /** Whether a spelled plan passes no props at all. */
129
+ export function isEmptyComponentProps(segments: readonly SpelledComponentPropSegment[]): boolean {
130
+ return segments.every((segment) => segment.kind === 'entries' && segment.parts.length === 0)
131
+ }
132
+
133
+ /**
134
+ * The template a child component renders from: the component's declared
135
+ * name, resolved through an import alias (`import { Foo as Bar }`, `<Bar/>`
136
+ * renders `foo`, #2822), in snake_case.
137
+ */
138
+ export function childTemplateName(componentName: string, importAliases: ReadonlyMap<string, string>): string {
139
+ const declaredName = importAliases.get(componentName) ?? componentName
140
+ return declaredName
141
+ .replace(/([A-Z])/g, '_$1')
142
+ .toLowerCase()
143
+ .replace(/^_/, '')
144
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Component-tree analysis shared by the DSL template adapters (#3475).
3
+ *
4
+ * Pure functions over the IR; they read no adapter instance state.
5
+ * `collectImportedLoopChildComponentErrors` returns its diagnostics instead
6
+ * of pushing onto an adapter's error list, so the adapter stays the sole
7
+ * owner of `errors`.
8
+ */
9
+
10
+ import type {
11
+ ComponentIR,
12
+ IRNode,
13
+ IRComponent,
14
+ IRElement,
15
+ IRFragment,
16
+ IRConditional,
17
+ IRLoop,
18
+ IRIfStatement,
19
+ IRProvider,
20
+ IRAsync,
21
+ CompilerError,
22
+ } from '../types.ts'
23
+
24
+ /**
25
+ * Whether the component needs the client runtime — it owns reactive state
26
+ * (signals / effects / onMount) or the analyzer flagged it as needing init.
27
+ */
28
+ export function hasClientInteractivity(ir: ComponentIR): boolean {
29
+ return (
30
+ ir.metadata.signals.length > 0 ||
31
+ ir.metadata.effects.length > 0 ||
32
+ ir.metadata.onMounts.length > 0 ||
33
+ (ir.metadata.clientAnalysis?.needsInit ?? false)
34
+ )
35
+ }
36
+
37
+ /**
38
+ * Build a `BF103` diagnostic for every component reference inside a loop body
39
+ * whose name is imported from a relative-path module. A DSL template backend
40
+ * renders such a child as a cross-template call, so the child's compiled
41
+ * template must be registered with the backend's loader alongside the
42
+ * parent at render time. `adapterName` is the display name the message
43
+ * uses ("The Jinja adapter emits …", "the resulting Jinja template").
44
+ * Returns the diagnostics so the caller pushes them onto its own error list.
45
+ */
46
+ export function collectImportedLoopChildComponentErrors(
47
+ ir: ComponentIR,
48
+ componentName: string,
49
+ adapterName: string,
50
+ ): CompilerError[] {
51
+ const errors: CompilerError[] = []
52
+ const relativeImports = new Set<string>()
53
+ for (const imp of ir.metadata.templateImports ?? ir.metadata.imports ?? []) {
54
+ if (!imp.source.startsWith('./') && !imp.source.startsWith('../')) continue
55
+ if (imp.isTypeOnly) continue
56
+ for (const spec of imp.specifiers) {
57
+ relativeImports.add(spec.alias ?? spec.name)
58
+ }
59
+ }
60
+ if (relativeImports.size === 0) return errors
61
+
62
+ const loc = { file: componentName + '.tsx', start: { line: 1, column: 0 }, end: { line: 1, column: 0 } }
63
+ const visit = (node: IRNode, inLoop: boolean): void => {
64
+ if (node.type === 'component' && inLoop && relativeImports.has(node.name)) {
65
+ errors.push(importedLoopChildError(node, loc, adapterName))
66
+ }
67
+ const childInLoop = inLoop || node.type === 'loop'
68
+ for (const child of childNodes(node)) visit(child, childInLoop)
69
+ }
70
+ visit(ir.root, false)
71
+ return errors
72
+ }
73
+
74
+ function importedLoopChildError(
75
+ comp: IRComponent,
76
+ loc: CompilerError['loc'],
77
+ adapterName: string,
78
+ ): CompilerError {
79
+ return {
80
+ code: 'BF103',
81
+ severity: 'error',
82
+ message: `Component <${comp.name}> is imported from a sibling module and used inside a loop. The ${adapterName} adapter emits a cross-template call; the child template must be registered alongside the parent at render time.`,
83
+ loc: comp.loc ?? loc,
84
+ suggestion: {
85
+ message:
86
+ `Options:\n` +
87
+ ` 1. Compile '${comp.name}' (its source file) with the same adapter and register the resulting ${adapterName} template alongside the parent at render time.\n` +
88
+ ` 2. Inline <${comp.name}> directly inside the loop body so no cross-file template lookup is needed.\n` +
89
+ ` 3. Mark the loop position as @client-only so the template is materialised on the client instead of at SSR time.`,
90
+ },
91
+ }
92
+ }
93
+
94
+ /** The child nodes the BF103 walk descends into, in render order. */
95
+ function childNodes(node: IRNode): IRNode[] {
96
+ switch (node.type) {
97
+ case 'component':
98
+ case 'element':
99
+ case 'fragment':
100
+ case 'loop':
101
+ case 'provider':
102
+ return (node as IRComponent | IRElement | IRFragment | IRLoop | IRProvider).children
103
+ case 'conditional': {
104
+ const cond = node as IRConditional
105
+ return cond.whenFalse ? [cond.whenTrue, cond.whenFalse] : [cond.whenTrue]
106
+ }
107
+ case 'if-statement': {
108
+ const stmt = node as IRIfStatement
109
+ return stmt.alternate ? [stmt.consequent, stmt.alternate] : [stmt.consequent]
110
+ }
111
+ case 'async': {
112
+ const a = node as IRAsync
113
+ return [a.fallback, ...a.children]
114
+ }
115
+ default:
116
+ return []
117
+ }
118
+ }
@@ -0,0 +1,29 @@
1
+ import type { IRLoop } from '../types.ts'
2
+ import { freeIdentifiers } from '../expression-parser.ts'
3
+
4
+ /**
5
+ * Names a `.filter().map()` loop's predicate captures from an enclosing row
6
+ * that the loop's own row binds again (its item, destructure bindings or
7
+ * index), so they shadow the capture where the predicate runs (#3402).
8
+ *
9
+ * `rows.filter(t => t === name).map(name => …)` inside a row bound as `name`:
10
+ * the predicate's `name` is the enclosing value, but adapters evaluate the
11
+ * predicate inside the `.map()` row, where `name` is the item. An adapter
12
+ * keeps each returned name under a loop-scoped alias declared before the
13
+ * loop and rewrites the predicate's reads to it.
14
+ *
15
+ * An unanalyzable predicate (`freeIdentifiers` returns null) yields no
16
+ * names, which keeps the adapter's previous emission.
17
+ */
18
+ export function filterCaptureCollisions(loop: IRLoop): string[] {
19
+ const filter = loop.filterPredicate
20
+ if (!filter?.predicate) return []
21
+ const free = freeIdentifiers(filter.predicate)
22
+ if (!free) return []
23
+ free.delete(filter.param)
24
+ const rowBound = new Set<string>(
25
+ loop.paramBindings && loop.paramBindings.length > 0 ? loop.paramBindings.map(b => b.name) : [loop.param],
26
+ )
27
+ if (loop.index) rowBound.add(loop.index)
28
+ return [...free].filter(name => rowBound.has(name)).sort()
29
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Literal-value predicates shared by the DSL template adapters (#3475).
3
+ *
4
+ * Pure functions over analyzer type info and parsed expressions. Every DSL
5
+ * adapter classifies string-typed signals, props and constants with
6
+ * {@link isStringTypeInfo} / {@link isBareStringLiteral}, and tells a
7
+ * literal index from a variable one with {@link isLiteralIndex}.
8
+ */
9
+
10
+ import type { ParsedExpr } from '../expression-parser.ts'
11
+ import type { TypeInfo } from '../types.ts'
12
+
13
+ /** True when `type` is the `string` primitive. */
14
+ export function isStringTypeInfo(type: TypeInfo | undefined): boolean {
15
+ return type?.kind === 'primitive' && type.primitive === 'string'
16
+ }
17
+
18
+ /** True when `initialValue` is a bare string-literal expression. */
19
+ export function isBareStringLiteral(initialValue: string | undefined): boolean {
20
+ if (!initialValue) return false
21
+ const v = initialValue.trim()
22
+ return (v.startsWith("'") && v.endsWith("'")) || (v.startsWith('"') && v.endsWith('"'))
23
+ }
24
+
25
+ /**
26
+ * True when a parsed index is a numeric or string literal (`arr[0]`,
27
+ * `m['k']`). The spread lowerings refuse (BF101) an indexed spread value
28
+ * they could not inline only when its index is NOT a literal: a
29
+ * variable-index record access (`sizeMap[size]`) has no static answer.
30
+ */
31
+ export function isLiteralIndex(index: ParsedExpr): boolean {
32
+ return (
33
+ index.kind === 'literal' &&
34
+ (index.literalType === 'number' || index.literalType === 'string')
35
+ )
36
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The decisions behind a DSL adapter's `renderLoop` (#3473), as data.
3
+ *
4
+ * Every DSL adapter decides the same things about a `.map()` loop before it
5
+ * spells a line of template: whether its destructure pattern lowers (BF104),
6
+ * whether the source is a static literal, whether it names a computed const
7
+ * no template binds (BF101), how its `.sort` comparator lowers, and which
8
+ * filter captures need an alias. {@link planLoop} makes those decisions once,
9
+ * against the scope outside the loop. The adapter keeps the spelling: the
10
+ * loop header, the row bindings, the diagnostics' wording, and the order it
11
+ * emits them in.
12
+ */
13
+
14
+ import { parseExpression } from '../expression-parser.ts'
15
+ import { isLowerableLoopDestructure } from '../loop-destructure.ts'
16
+ import type { BindingScope } from '../scope/binding-scope.ts'
17
+ import { resolveStaticLoopSource } from '../static-literal.ts'
18
+ import type { ConstantInfo, IRLoop } from '../types.ts'
19
+ import { type CallbackLoweringOptions, type CallbackPlan, lowerCallbackMethod } from './callback-method.ts'
20
+ import { filterCaptureCollisions } from './filter-capture-collisions.ts'
21
+
22
+ export interface LoopPlanContext<Spelled> {
23
+ /** The scope outside the loop. */
24
+ scope: BindingScope
25
+ localConstants: readonly ConstantInfo[]
26
+ /** The adapter's literal-const resolution: a literal const inlines at its use site. */
27
+ resolveLiteralConst(name: string): unknown
28
+ callbackLowering: CallbackLoweringOptions
29
+ /** The adapter's spelling of a static source's items, or `null` when the backend cannot represent one. */
30
+ spellStatic(items: unknown[]): Spelled | null
31
+ }
32
+
33
+ export interface LoopPlan<Spelled> {
34
+ /**
35
+ * The loop param's destructure pattern: none, one the adapter lowers to
36
+ * per-binding accessors, or one no template binds (BF104).
37
+ */
38
+ destructure: 'none' | 'lowerable' | 'unlowerable'
39
+ /**
40
+ * The source spelled as a template literal, when it is an inline literal or
41
+ * an unshadowed static const whose items the backend can represent.
42
+ */
43
+ staticSource: Spelled | null
44
+ /**
45
+ * The const the source names when it is not spelled statically and no
46
+ * template binds it as a literal (BF101). A loop binding that shadows the
47
+ * name is the row's value, not the const (#3473).
48
+ */
49
+ unresolvableConst: ConstantInfo | null
50
+ /** The `.sort` / `.toSorted` comparator's lowering, or `null` without one. */
51
+ sort: CallbackPlan | null
52
+ /** The filter predicate's captures that a row binding would shadow, each with its alias. */
53
+ captureAliases: Array<{ name: string; alias: string }>
54
+ }
55
+
56
+ /** Plan a loop against the scope outside it. */
57
+ export function planLoop<Spelled>(loop: IRLoop, ctx: LoopPlanContext<Spelled>): LoopPlan<Spelled> {
58
+ const staticItems = resolveStaticLoopSource(loop.arrayParsed, ctx.localConstants, {
59
+ isNameShadowed: ctx.scope.asShadowPredicate(),
60
+ })
61
+ const staticSource = staticItems !== null ? ctx.spellStatic(staticItems) : null
62
+ return {
63
+ destructure: destructureKind(loop),
64
+ staticSource,
65
+ unresolvableConst: staticSource === null ? unresolvableConst(loop, ctx) : null,
66
+ sort: loop.sortComparator ? lowerCallbackMethod('sort', loop.sortComparator.arrow, [], ctx.callbackLowering) : null,
67
+ captureAliases: filterCaptureCollisions(loop).map((name) => ({ name, alias: `__bf_cap_${loop.markerId}_${name}` })),
68
+ }
69
+ }
70
+
71
+ function destructureKind(loop: IRLoop): LoopPlan<unknown>['destructure'] {
72
+ if (!loop.paramBindings || loop.paramBindings.length === 0) return 'none'
73
+ return isLowerableLoopDestructure(loop) ? 'lowerable' : 'unlowerable'
74
+ }
75
+
76
+ /**
77
+ * The source is read from its parsed tree, which unwraps parentheses: the
78
+ * raw text of `(entries).map(…)` is no bare identifier, yet it names the
79
+ * same const.
80
+ */
81
+ function unresolvableConst(loop: IRLoop, ctx: LoopPlanContext<unknown>): ConstantInfo | null {
82
+ const source = loop.arrayParsed ?? parseExpression(loop.array.trim())
83
+ if (source?.kind !== 'identifier') return null
84
+ const name = source.name
85
+ if (ctx.scope.isBound(name)) return null
86
+ const constant = ctx.localConstants.find((c) => c.name === name)
87
+ return constant && ctx.resolveLiteralConst(name) === null ? constant : null
88
+ }
@@ -287,6 +287,24 @@ export function isStringConcatBinary(
287
287
  return op === '+' && (isStringTypedOperand(left, isStringName) || isStringTypedOperand(right, isStringName))
288
288
  }
289
289
 
290
+ /**
291
+ * Whether a top-level expression yields a JS NUMBER from arithmetic: a
292
+ * `-` / `*` / `/` / `%` binary, a `+` that is not string concatenation, or
293
+ * a unary minus. Backends that print an output expression with the host
294
+ * language's own number stringification (Perl's `%.15g`) route such a
295
+ * result through their JS `Number::toString` helper instead (#3380).
296
+ */
297
+ export function isNumericArithmeticResult(
298
+ expr: ParsedExpr | null | undefined,
299
+ isStringName: (n: string, componentProperty?: boolean) => boolean,
300
+ ): boolean {
301
+ if (!expr) return false
302
+ if (expr.kind === 'unary') return expr.op === '-'
303
+ if (expr.kind !== 'binary') return false
304
+ if (expr.op === '+') return !isStringConcatBinary(expr.op, expr.left, expr.right, isStringName)
305
+ return expr.op === '-' || expr.op === '*' || expr.op === '/' || expr.op === '%'
306
+ }
307
+
290
308
  /**
291
309
  * Wrap an emitted binary/logical/ternary OPERAND in parentheses so the
292
310
  * source grouping the `ParsedExpr` tree encodes survives infix
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Prop classification shared by the DSL template adapters (#3475).
3
+ *
4
+ * Pure functions over `ir.metadata` that derive per-compile prop sets an
5
+ * adapter consults during lowering; no adapter instance state.
6
+ */
7
+
8
+ import type { ComponentIR } from '../types.ts'
9
+
10
+ /**
11
+ * Props whose declared TS type is boolean. A bare binding of one
12
+ * (`data-active={props.isActive}`) must stringify as JS `String(boolean)`
13
+ * ("true"/"false"), not the host language's own boolean text (Python's
14
+ * `True`, Perl's `1` / `''`) (#1897, pagination's data-active).
15
+ */
16
+ export function collectBooleanTypedProps(ir: ComponentIR): Set<string> {
17
+ return new Set(
18
+ ir.metadata.propsParams
19
+ .filter(prop => prop.type?.primitive === 'boolean' || prop.type?.raw === 'boolean')
20
+ .map(prop => prop.name),
21
+ )
22
+ }
23
+
24
+ /**
25
+ * Props whose presence is uncertain: no default, and non-primitive typed OR
26
+ * declared optional (#2259, e.g. textarea's `rows`). A bare reference to one
27
+ * is absent (`None` / `nil` / `null` / `undef`) when the caller omits it, so
28
+ * each adapter guards it with its own presence test before rendering.
29
+ */
30
+ export function collectNullableOptionalProps(ir: ComponentIR): Set<string> {
31
+ return new Set([
32
+ ...ir.metadata.propsParams
33
+ .filter(
34
+ p =>
35
+ p.defaultValue === undefined &&
36
+ !p.isRest &&
37
+ (p.type?.kind !== 'primitive' || p.optional),
38
+ )
39
+ .map(p => p.name),
40
+ // A closed-type `{...rest}` key (#3057) is never destructured with its
41
+ // own default the way a normal prop can be, so it is always presence-
42
+ // uncertain the same way a no-default optional prop is — guard it the
43
+ // same way so `<span {...rest}>` omits a caller-omitted key instead of
44
+ // rendering `key=""`. Harmless for a required (non-optional) rest key
45
+ // too: the guard simply always passes for it.
46
+ ...ir.metadata.restPropsExpandedKeys,
47
+ ])
48
+ }
49
+
50
+ export interface BooleanTypedPropContext {
51
+ /** The SolidJS-style props identifier (`function C(props: P)`), if any. */
52
+ propsObjectName: string | null
53
+ /** Props typed `boolean` (`collectBooleanTypedProps`). */
54
+ booleanTypedProps: ReadonlySet<string>
55
+ /** A binding at the read site shadows `name`. */
56
+ isBound(name: string): boolean
57
+ }
58
+
59
+ /**
60
+ * Whether `expr` is a bare read of a boolean-typed prop (`open`,
61
+ * `props.open`), which renders through `bool_str`. Inside a `.map()`
62
+ * callback, a param that shares the prop's name is the row binding, not the
63
+ * prop (#2488).
64
+ */
65
+ export function isBooleanTypedPropRef(expr: string, ctx: BooleanTypedPropContext): boolean {
66
+ let bare = expr.trim()
67
+ if (ctx.propsObjectName && bare.startsWith(`${ctx.propsObjectName}.`)) {
68
+ bare = bare.slice(ctx.propsObjectName.length + 1)
69
+ }
70
+ if (!/^[A-Za-z_$][\w$]*$/.test(bare)) return false
71
+ if (ctx.isBound(bare)) return false
72
+ return ctx.booleanTypedProps.has(bare)
73
+ }
@@ -0,0 +1,120 @@
1
+ import { BindingScope } from '../scope/binding-scope.ts'
2
+ import type { CompilerError, ComponentIR, IRNode } from '../types.ts'
3
+
4
+ /**
5
+ * BF105: two distinct source names of a component that an adapter's
6
+ * identifier mangling turns into the SAME template variable (#3404).
7
+ *
8
+ * Template engines rename a source name they reserve — `loop` becomes
9
+ * `__bf_loop` on Jinja, MiniJinja, Twig, Pebble and Blade, `none` becomes
10
+ * `none_` on Jinja. The mapping is per name and must be idempotent
11
+ * (some paths mangle an already-mangled name, and the runtimes re-mangle
12
+ * prop keys), so it cannot also be injective: whatever a reserved name
13
+ * becomes is itself a name a user may write. When a component writes both,
14
+ * the two reads would silently share one value, so the adapter refuses.
15
+ *
16
+ * The names checked are the ones the adapter turns into bare template
17
+ * variables: props, local consts and functions, signal getters and setters,
18
+ * memos, and the bindings of each loop row or `.filter()` callback together
19
+ * with its enclosing rows (`BindingScope`). `ident` is the adapter's own mangling
20
+ * (`jinjaIdent`, `twigIdent`, …). One error per colliding group.
21
+ */
22
+ export function templateNameCollisionErrors(
23
+ ir: ComponentIR,
24
+ propNames: Iterable<string>,
25
+ ident: (name: string) => string,
26
+ adapterName: string,
27
+ componentName: string,
28
+ ): CompilerError[] {
29
+ const { metadata } = ir
30
+ const rootNames = new Set<string>([
31
+ ...propNames,
32
+ ...metadata.localConstants.map(c => c.name),
33
+ ...metadata.localFunctions.map(f => f.name),
34
+ ...metadata.signals.flatMap(s => (s.setter ? [s.getter, s.setter] : [s.getter])),
35
+ ...metadata.memos.map(m => m.name),
36
+ ])
37
+ const errors: CompilerError[] = []
38
+ const reported = new Set<string>()
39
+ // Only names visible at the same point can collide: the component's own
40
+ // names plus the bindings of the enclosing loop rows. Sibling loops never
41
+ // see each other's bindings, so `a.map(loop => …)` next to
42
+ // `b.map(__bf_loop => …)` is fine.
43
+ const check = (scope: BindingScope): void => {
44
+ const byTarget = new Map<string, string[]>()
45
+ for (const name of new Set([...rootNames, ...scope.boundNames()])) {
46
+ const target = ident(name)
47
+ const group = byTarget.get(target)
48
+ if (group) group.push(name)
49
+ else byTarget.set(target, [name])
50
+ }
51
+ for (const [target, group] of byTarget) {
52
+ if (group.length < 2) continue
53
+ const key = `${target}\0${[...group].sort().join('\0')}`
54
+ if (reported.has(key)) continue
55
+ reported.add(key)
56
+ const list = group.map(n => `\`${n}\``).join(' and ')
57
+ errors.push({
58
+ code: 'BF105',
59
+ severity: 'error',
60
+ message: `${list} both become the ${adapterName} template variable \`${target}\`, so they would read the same value. ${adapterName} reserves some names and renames them, and the new name collides with another name in this component.`,
61
+ loc: { file: `${componentName}.tsx`, start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
62
+ suggestion: {
63
+ message: `Rename one of ${list} so the two names stay distinct after the ${adapterName} renaming.`,
64
+ escape: [{ kind: 'rewrite' }],
65
+ },
66
+ })
67
+ }
68
+ }
69
+ const visit = (node: IRNode | null | undefined, scope: BindingScope): void => {
70
+ if (!node) return
71
+ switch (node.type) {
72
+ case 'element':
73
+ case 'component':
74
+ case 'fragment':
75
+ case 'provider':
76
+ for (const child of node.children) visit(child, scope)
77
+ break
78
+ case 'async':
79
+ visit(node.fallback, scope)
80
+ for (const child of node.children) visit(child, scope)
81
+ break
82
+ case 'loop': {
83
+ // A `.filter()` predicate is its own callback: its param sees the
84
+ // enclosing scope, not the map row it feeds.
85
+ if (node.filterPredicate) check(scope.enterCallback([node.filterPredicate.param]))
86
+ const row = scope.enterLoopRow(node)
87
+ check(row)
88
+ for (const child of node.children) visit(child, row)
89
+ if (node.childComponent) {
90
+ for (const child of node.childComponent.children) visit(child, row)
91
+ }
92
+ for (const nested of node.nestedComponents ?? []) {
93
+ for (const child of nested.children) visit(child, row)
94
+ }
95
+ for (const seg of node.flatMapCallback?.segments ?? []) {
96
+ if (seg.kind === 'jsx') visit(seg.ir, row)
97
+ }
98
+ for (const seg of node.preamble?.segments ?? []) {
99
+ if (seg.kind === 'jsx') visit(seg.ir, row)
100
+ }
101
+ break
102
+ }
103
+ case 'conditional':
104
+ visit(node.whenTrue, scope)
105
+ visit(node.whenFalse, scope)
106
+ break
107
+ case 'if-statement':
108
+ visit(node.consequent, scope)
109
+ if (node.alternate) visit(node.alternate, scope)
110
+ break
111
+ case 'text':
112
+ case 'expression':
113
+ case 'slot':
114
+ break
115
+ }
116
+ }
117
+ check(BindingScope.EMPTY)
118
+ visit(ir.root, BindingScope.EMPTY)
119
+ return errors
120
+ }
@@ -28,6 +28,20 @@ import { type ExcludeRange, collectAllTypeRanges, reconstructWithoutTypes } from
28
28
  import type { CallbackBodyAcceptor } from './adapters/interface.ts'
29
29
  import { nodeContainsJsx } from './reactivity-checker.ts'
30
30
 
31
+ /**
32
+ * Whether the getJS trust-boundary assertion is armed (BF_ASSERT_NO_JSX_IN_GETJS=1).
33
+ *
34
+ * Read through `globalThis` rather than a bare `process` identifier: the
35
+ * compiler also runs where no Node `process` exists (the site playground
36
+ * bundles it into a browser Worker), and a bare reference there throws
37
+ * ReferenceError on the first getJS call. Evaluated per call, not at module
38
+ * load, because the test harnesses that arm it set the env var in `beforeAll`.
39
+ */
40
+ function isGetJsAssertionArmed(): boolean {
41
+ const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env
42
+ return env?.BF_ASSERT_NO_JSX_IN_GETJS === '1'
43
+ }
44
+
31
45
  /**
32
46
  * The props destructuring pattern's own source location. Carries no
33
47
  * diagnostic of its own — it is the more precise location other
@@ -327,7 +341,7 @@ export function createAnalyzerContext(
327
341
  // anything, so it must not silently disarm this assertion too (#2867)
328
342
  // — only `error` severity does.
329
343
  if (
330
- process.env.BF_ASSERT_NO_JSX_IN_GETJS === '1' &&
344
+ isGetJsAssertionArmed() &&
331
345
  !this.errors.some((e) => e.severity === 'error') &&
332
346
  nodeContainsJsx(node)
333
347
  ) {