@barefootjs/jsx 0.39.6 → 0.39.7

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 (89) hide show
  1. package/dist/adapters/attr-plan.d.ts +8 -1
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +27 -0
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/computed-const.d.ts +52 -0
  6. package/dist/adapters/computed-const.d.ts.map +1 -0
  7. package/dist/adapters/dangerous-inner-html.d.ts +10 -0
  8. package/dist/adapters/dangerous-inner-html.d.ts.map +1 -1
  9. package/dist/adapters/element-shell.d.ts +44 -0
  10. package/dist/adapters/element-shell.d.ts.map +1 -0
  11. package/dist/adapters/interface.d.ts +2 -0
  12. package/dist/adapters/interface.d.ts.map +1 -1
  13. package/dist/analyzer.d.ts.map +1 -1
  14. package/dist/augment-inherited-props.d.ts +7 -0
  15. package/dist/augment-inherited-props.d.ts.map +1 -1
  16. package/dist/fold-render-reassignments.d.ts +43 -0
  17. package/dist/fold-render-reassignments.d.ts.map +1 -0
  18. package/dist/free-refs.d.ts +9 -0
  19. package/dist/free-refs.d.ts.map +1 -1
  20. package/dist/index.d.ts +8 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2285 -1583
  23. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/csr-substitute.d.ts +0 -13
  25. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/html-template.d.ts +9 -10
  28. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +5 -0
  31. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/prop-handling.d.ts +11 -12
  33. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/utils.d.ts +13 -0
  35. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  36. package/dist/jsx-to-ir.d.ts.map +1 -1
  37. package/dist/nullable-signal-attr.d.ts +3 -2
  38. package/dist/nullable-signal-attr.d.ts.map +1 -1
  39. package/dist/props-binding.d.ts +34 -5
  40. package/dist/props-binding.d.ts.map +1 -1
  41. package/dist/relocate.d.ts +16 -0
  42. package/dist/relocate.d.ts.map +1 -1
  43. package/dist/ssr-seed-plan.d.ts +0 -6
  44. package/dist/ssr-seed-plan.d.ts.map +1 -1
  45. package/dist/types.d.ts +54 -2
  46. package/dist/types.d.ts.map +1 -1
  47. package/package.json +2 -2
  48. package/src/__tests__/block-memo-type.test.ts +51 -0
  49. package/src/__tests__/callback-method.test.ts +75 -0
  50. package/src/__tests__/client-only-date-lowering.test.ts +2 -2
  51. package/src/__tests__/computed-const.test.ts +101 -0
  52. package/src/__tests__/element-shell.test.ts +78 -0
  53. package/src/__tests__/fold-render-reassignments.test.ts +96 -0
  54. package/src/__tests__/inlinable-local-method-call.test.ts +81 -0
  55. package/src/__tests__/memo-body-expr.test.ts +120 -0
  56. package/src/__tests__/prop-handling.test.ts +35 -16
  57. package/src/__tests__/props-alias-const.test.ts +65 -0
  58. package/src/__tests__/signal-prop-seed.test.ts +90 -0
  59. package/src/__tests__/ssr-seed-plan.test.ts +54 -1
  60. package/src/__tests__/static-template-reachability.test.ts +137 -0
  61. package/src/adapters/attr-plan.ts +29 -1
  62. package/src/adapters/callback-method.ts +62 -0
  63. package/src/adapters/computed-const.ts +185 -0
  64. package/src/adapters/dangerous-inner-html.ts +33 -0
  65. package/src/adapters/element-shell.ts +160 -0
  66. package/src/adapters/interface.ts +8 -0
  67. package/src/analyzer.ts +271 -82
  68. package/src/augment-inherited-props.ts +12 -0
  69. package/src/fold-render-reassignments.ts +314 -0
  70. package/src/free-refs.ts +49 -0
  71. package/src/index.ts +9 -2
  72. package/src/ir-to-client-js/compute-inlinability.ts +93 -17
  73. package/src/ir-to-client-js/csr-substitute.ts +13 -35
  74. package/src/ir-to-client-js/emit-registration.ts +3 -2
  75. package/src/ir-to-client-js/html-template.ts +26 -70
  76. package/src/ir-to-client-js/index.ts +3 -2
  77. package/src/ir-to-client-js/init-declarations.ts +1 -1
  78. package/src/ir-to-client-js/plan/build-declaration-emit.ts +25 -51
  79. package/src/ir-to-client-js/plan/declaration-emit.ts +5 -0
  80. package/src/ir-to-client-js/prop-handling.ts +13 -54
  81. package/src/ir-to-client-js/rewrite-destructured-props.ts +6 -5
  82. package/src/ir-to-client-js/stringify/declaration-emit.ts +1 -1
  83. package/src/ir-to-client-js/utils.ts +11 -0
  84. package/src/jsx-to-ir.ts +39 -52
  85. package/src/nullable-signal-attr.ts +7 -4
  86. package/src/props-binding.ts +100 -5
  87. package/src/relocate.ts +40 -8
  88. package/src/ssr-seed-plan.ts +18 -6
  89. package/src/types.ts +50 -2
@@ -22,6 +22,7 @@ import {
22
22
  readsNestedCallbackIndex,
23
23
  serializeParsedExpr,
24
24
  sortComparatorFromArrow,
25
+ stringifyParsedExpr,
25
26
  type ParsedExpr,
26
27
  type SortComparator,
27
28
  } from '../expression-parser.ts'
@@ -289,6 +290,67 @@ export function emitCallbackEval(
289
290
  return spelling.call(plan.helper, operands)
290
291
  }
291
292
 
293
+ /**
294
+ * Whether a call that reached an adapter's generic fallback has no lowering
295
+ * (#3493). A zero-arg call reads a getter (`props.value()`, a getter passed
296
+ * as a prop, a context getter `ctx.open()`), unless its receiver is rooted at
297
+ * a JavaScript global (`Date.now()`, `window.performance.now()`): `isGlobal`
298
+ * answers that from the component's bindings and the live loop scope, and a
299
+ * global has no binding in template scope (#3505). A call to a
300
+ * function-valued prop (`props.renderNode(node)`, a render prop) names a
301
+ * value a backend caller never passes, so the guard around it is never taken
302
+ * there; it keeps the callee read. Any other call with arguments
303
+ * (`s().localeCompare('m')`) would lose the call and its arguments.
304
+ * `propsObjectName` is the undestructured props parameter (`props`), `null`
305
+ * when the props are destructured: a destructured render prop is a
306
+ * bare-name call, which the adapters refuse on their own.
307
+ */
308
+ export function isUnloweredCall(
309
+ callee: ParsedExpr,
310
+ args: readonly ParsedExpr[],
311
+ propsObjectName: string | null,
312
+ isGlobal: (name: string) => boolean,
313
+ ): boolean {
314
+ if (args.length === 0) {
315
+ const root = memberRoot(callee)
316
+ return root !== null && isGlobal(root)
317
+ }
318
+ return !(callee.kind === 'member' && callee.object.kind === 'identifier' && callee.object.name === propsObjectName)
319
+ }
320
+
321
+ /**
322
+ * The identifier a member chain is rooted at, through literal and computed
323
+ * access alike (`window.performance.now`, `Date[key]`,
324
+ * `globalThis[name].now`); `null` for any other callee.
325
+ */
326
+ function memberRoot(callee: ParsedExpr): string | null {
327
+ if (callee.kind !== 'member' && callee.kind !== 'index-access') return null
328
+ let object = callee.object
329
+ while (object.kind === 'member' || object.kind === 'index-access') object = object.object
330
+ return object.kind === 'identifier' ? object.name : null
331
+ }
332
+
333
+ /**
334
+ * The BF101 for a call no template lowers: a method outside the array-method
335
+ * catalogue (`s().localeCompare('m')`), a zero-arg call on a JavaScript
336
+ * global (`Date.now()`), or any other callee that is not a getter, a template
337
+ * primitive or a lowering plugin's call. Read as its callee, the call and its
338
+ * arguments would silently disappear (#3493, #3505).
339
+ */
340
+ export function unloweredCallRefusal(
341
+ callee: ParsedExpr,
342
+ args: readonly ParsedExpr[],
343
+ adapterName: string,
344
+ ): { message: string; suggestion: string } {
345
+ const name = stringifyParsedExpr(callee)
346
+ return {
347
+ message: args.length === 0
348
+ ? `Call '${name}()' reads a JavaScript global, which has no ${adapterName} template binding; read as a value it would drop the call`
349
+ : `Call '${name}(...)' has no ${adapterName} template lowering; read as a value it would drop the call and its arguments`,
350
+ suggestion: 'Pre-compute the value in the backend and pass it as a prop, or add /* @client */ for client-only evaluation (no SSR).',
351
+ }
352
+ }
353
+
292
354
  /**
293
355
  * The BF101 for a callback method nested inside a filter predicate, which a
294
356
  * predicate emitter has no scalar form for.
@@ -0,0 +1,185 @@
1
+ /**
2
+ * A component- or module-scope `const` computed from props, signals or other
3
+ * consts (`const cls = 'btn ' + variant`, `const twice = props.n * 2`) has no
4
+ * binding in a template: the backend receives the props, not the
5
+ * component's locals. Every template adapter read such a const as a template
6
+ * variable nothing defines, so it rendered empty, a prop of the same name, or
7
+ * failed the render (#3494).
8
+ *
9
+ * `inlineComputedConsts` substitutes each such read with the const's
10
+ * initializer tree, exactly as if the source had written the expression in
11
+ * place; the adapter then lowers it like any other expression, refusing what
12
+ * it cannot lower (`Object.keys(labels)` has no template form, BF101) instead
13
+ * of reading an unbound name. The substitution is structural
14
+ * (`inlineBinding`), so precedence, string literals and callback params that
15
+ * shadow the name are respected.
16
+ */
17
+
18
+ import { collectContextConsumers, lookupLiteralConst } from '../augment-inherited-props.ts'
19
+ import { freeIdentifiers, inlineBinding, parseExpression, stringifyParsedExpr, type ParsedExpr } from '../expression-parser.ts'
20
+ import type { ConstantInfo, ExpressionAttr, IRMetadata } from '../types.ts'
21
+ import { componentBindings } from '../relocate.ts'
22
+
23
+ export interface ComputedConstContext {
24
+ constants: IRMetadata['localConstants'] | undefined
25
+ /** Signal getters and memo names: the zero-arg calls a template reads as values. */
26
+ getters: ReadonlySet<string>
27
+ /** Context consumers (`const theme = useContext(ThemeContext)`), which the adapter seeds itself. */
28
+ contextConsumers: ReadonlySet<string>
29
+ /** Consts a props destructure binds, which the adapter binds as props params. */
30
+ propsBindings: ReadonlySet<string>
31
+ /** Whether a loop row or callback binds `name` where the expression is read. */
32
+ isShadowed(name: string): boolean
33
+ /** Whether the adapter binds the const `name` itself, so a read of it stays as written. */
34
+ isAdapterBound(name: string): boolean
35
+ /**
36
+ * Whether `name` read where the expression is read is a JavaScript global:
37
+ * bound by neither the component nor its module (`componentBindings`), nor
38
+ * the rest props, nor an enclosing loop or callback.
39
+ */
40
+ isGlobal(name: string): boolean
41
+ }
42
+
43
+ /** The {@link ComputedConstContext} fields that come from the component's metadata. */
44
+ export function computedConstContext(
45
+ metadata: IRMetadata,
46
+ isShadowed: (name: string) => boolean,
47
+ isAdapterBound: (name: string) => boolean = () => false,
48
+ ): ComputedConstContext {
49
+ const bindings = componentBindings(metadata)
50
+ return {
51
+ constants: metadata.localConstants,
52
+ getters: new Set([...metadata.signals.map(s => s.getter), ...metadata.memos.map(m => m.name)]),
53
+ contextConsumers: new Set(collectContextConsumers(metadata).map(c => c.localName)),
54
+ propsBindings: propsBindingNames(metadata),
55
+ isShadowed,
56
+ isAdapterBound,
57
+ isGlobal: name => !bindings.has(name) && name !== metadata.restPropsName && !isShadowed(name),
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Consts a props destructure binds (`const { label: text = 'none' } = props`).
63
+ * The analyzer records each as a props param, renamed and defaulted, and the
64
+ * adapters bind it as one: its default applies to `undefined` alone, which
65
+ * the `??` of its recorded value would not keep on a backend whose `??`
66
+ * also tests `''`. A const merely named like a prop
67
+ * (`const label = props.label ?? 'Default'`, the prop itself carrying no
68
+ * default) is not one.
69
+ */
70
+ function propsBindingNames(metadata: IRMetadata): Set<string> {
71
+ const names = new Set<string>()
72
+ const props = metadata.propsObjectName
73
+ if (!props) return names
74
+ for (const constant of metadata.localConstants ?? []) {
75
+ const param = metadata.propsParams.find(p => p.name === constant.name)
76
+ const value = constant.value?.trim()
77
+ if (!param || value === undefined) continue
78
+ const read = `${props}.${param.sourceName ?? param.name}`
79
+ if (value === read || (param.defaultValue !== undefined && value === `${read} ?? ${param.defaultValue}`)) {
80
+ names.add(constant.name)
81
+ }
82
+ }
83
+ return names
84
+ }
85
+
86
+ /** Upper bound on const-of-const chains, a guard against a malformed cycle. */
87
+ const MAX_DEPTH = 16
88
+
89
+ /**
90
+ * `expr` with each read of a computed const replaced by its initializer,
91
+ * repeated so a const read inside an initializer is replaced too.
92
+ */
93
+ export function inlineComputedConsts(expr: ParsedExpr, ctx: ComputedConstContext | null): ParsedExpr {
94
+ if (!ctx?.constants?.length) return expr
95
+ let current = expr
96
+ for (let depth = 0; depth < MAX_DEPTH; depth++) {
97
+ const next = inlineOnce(current, ctx)
98
+ if (next === current) return current
99
+ current = next
100
+ }
101
+ return current
102
+ }
103
+
104
+ function inlineOnce(expr: ParsedExpr, ctx: ComputedConstContext): ParsedExpr {
105
+ const free = freeIdentifiers(expr)
106
+ if (!free) return expr
107
+ let result = expr
108
+ for (const name of free) {
109
+ const init = inlinableInitializer(name, ctx)
110
+ if (!init) continue
111
+ result = inlineBinding(result, name, init) ?? result
112
+ }
113
+ return result
114
+ }
115
+
116
+ /**
117
+ * An `{expr}` attribute value read through {@link inlineComputedConsts}, so
118
+ * the attribute's own plan (a nullable prop read drops the attribute) sees
119
+ * the const's initializer, not its name: `title={label}` with
120
+ * `const label = props.label ?? 'Default'` is not a bare read of `label`.
121
+ */
122
+ export function inlineComputedConstAttr(value: ExpressionAttr, ctx: ComputedConstContext | null): ExpressionAttr {
123
+ if (!ctx) return value
124
+ const parsed = value.parsed ?? parseExpression(value.expr.trim())
125
+ const inlined = inlineComputedConsts(parsed, ctx)
126
+ if (inlined === parsed) return value
127
+ // `templateExpr` and `parts` are derived from the original `expr`; dropped
128
+ // so no consumer reads the const's name through them.
129
+ return { ...value, expr: stringifyParsedExpr(inlined), parsed: inlined, templateExpr: undefined, parts: undefined }
130
+ }
131
+
132
+ /** The initializer of a const read `name` stands for, or `null` when the read stays as it is. */
133
+ function inlinableInitializer(name: string, ctx: ComputedConstContext): ParsedExpr | null {
134
+ const constant = ctx.constants?.find(c => c.name === name)
135
+ const init = constant?.parsed
136
+ if (!constant || !init || !isPlainComputedConst(constant, init)) return null
137
+ if (ctx.isShadowed(name) || ctx.getters.has(name) || ctx.contextConsumers.has(name) || ctx.propsBindings.has(name)) return null
138
+ if (ctx.isAdapterBound(name)) return null
139
+ // An adapter already inlines a literal const in its own syntax.
140
+ if (lookupLiteralConst(name, ctx.constants, ctx.isShadowed) !== null) return null
141
+ // A free name the read site rebinds would be captured by the substitution.
142
+ const free = freeIdentifiers(init)
143
+ if (!free || [...free].some(n => ctx.isShadowed(n))) return null
144
+ return callsOnlyGetters(init, ctx.getters) ? init : null
145
+ }
146
+
147
+ /**
148
+ * A `const` holding a value computed by an expression, as opposed to a
149
+ * function, JSX, a static object or array the adapters resolve through their
150
+ * own lookups, or a runtime construct. A `let` no statement reassigns after
151
+ * its declaration holds one value too: its render-time reassignments were
152
+ * folded into the initializer (`fold-render-reassignments.ts`, #3501).
153
+ */
154
+ function isPlainComputedConst(constant: ConstantInfo, init: ParsedExpr): boolean {
155
+ if (constant.mutatedAfterDeclaration) return false
156
+ if (constant.isJsx || constant.isJsxFunction || constant.containsArrow || constant.isFunctionValue) return false
157
+ if (constant.systemConstructKind) return false
158
+ if (init.kind === 'call' && init.callee.kind === 'identifier' && init.callee.name === 'useContext') return false
159
+ return init.kind !== 'object-literal' && init.kind !== 'array-literal' && init.kind !== 'unsupported'
160
+ }
161
+
162
+ /**
163
+ * Whether every zero-arg identifier call in `init` is a signal or memo read.
164
+ * Any other one (`const label = makeLabel()`) is an opaque accessor: inlined,
165
+ * it would read as a getter of the helper's name, so the const keeps its own
166
+ * refusal path instead.
167
+ */
168
+ function callsOnlyGetters(init: ParsedExpr, getters: ReadonlySet<string>): boolean {
169
+ let ok = true
170
+ const visit = (node: unknown): void => {
171
+ if (!ok || node === null || typeof node !== 'object') return
172
+ if (Array.isArray(node)) {
173
+ node.forEach(visit)
174
+ return
175
+ }
176
+ const e = node as ParsedExpr
177
+ if (e.kind === 'call' && e.callee.kind === 'identifier' && e.args.length === 0 && !getters.has(e.callee.name)) {
178
+ ok = false
179
+ return
180
+ }
181
+ for (const value of Object.values(e)) visit(value)
182
+ }
183
+ visit(init)
184
+ return ok
185
+ }
@@ -243,3 +243,36 @@ export function dangerousInnerHtmlDiagnostic(
243
243
  },
244
244
  }
245
245
  }
246
+
247
+ /**
248
+ * The children `element`'s `dangerouslySetInnerHTML` renders in place of
249
+ * its own, or `null` when it has none. A refusal is pushed onto `errors`
250
+ * and renders as `''`. `rawSink` writes a dynamic value through the
251
+ * adapter's raw-output sink; the runtime evaluates the expression, so no
252
+ * template-metachar guard applies, and the element already carries its
253
+ * hydration slot marker (#2319). A static literal is spliced as trusted
254
+ * template text after the `adapterId` metachar guard.
255
+ */
256
+ export function renderDangerousInnerHtml(
257
+ element: IRElement,
258
+ errors: CompilerError[],
259
+ adapterId: string,
260
+ rawSink: (valueExpr: string, valueParsed: ParsedExpr, loc: SourceLocation) => string,
261
+ ): string | null {
262
+ const resolution = resolveDangerousInnerHtml(element)
263
+ if (!resolution) return null
264
+ if (resolution.kind === 'unlowerable') {
265
+ errors.push(dangerousInnerHtmlDiagnostic(resolution.expr, resolution.loc))
266
+ return ''
267
+ }
268
+ if (resolution.kind === 'dynamic') {
269
+ return rawSink(resolution.valueExpr, resolution.valueParsed, resolution.loc)
270
+ }
271
+ const violation = dangerousInnerHtmlMetacharViolation(resolution.html, adapterId)
272
+ if (violation) {
273
+ const attr = element.attrs.find(isDangerousInnerHtmlAttr)!
274
+ errors.push(dangerousInnerHtmlDiagnostic(`{ __html: ${JSON.stringify(resolution.html)} }`, attr.loc, violation))
275
+ return ''
276
+ }
277
+ return resolution.html
278
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * The HTML element every template adapter writes the same way (#3475): its
3
+ * attributes, its hydration markers, its children, and the void-element
4
+ * form. The adapter supplies how each value is spelled in its template
5
+ * language; the order and the conditions live here once.
6
+ */
7
+
8
+ import { BF_PORTAL_OWNER, BF_REGION } from '@barefootjs/shared'
9
+ import type { IRElement, IRFragment, IRNode } from '../types.ts'
10
+ import { emitAttrValue, type AttrValueEmitter } from './attr-value-emitter.ts'
11
+ import { isDangerousInnerHtmlAttr } from './dangerous-inner-html.ts'
12
+
13
+ const VOID_ELEMENTS = [
14
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
15
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
16
+ ]
17
+
18
+ /**
19
+ * The element's own attributes, each lowered through `emitter`, as a
20
+ * leading-space list (`''` when none renders).
21
+ */
22
+ export function renderElementAttributes(element: IRElement, emitter: AttrValueEmitter): string {
23
+ const parts: string[] = []
24
+
25
+ for (const attr of element.attrs) {
26
+ // `/* @client */` attribute bindings are deferred to hydrate: the
27
+ // client runtime sets/patches the attribute in a mount effect (the
28
+ // CSR template omits it; ir-to-client-js emits the setAttribute
29
+ // effect). Skip SSR emission so the server omits the attribute and
30
+ // the unsupported-expression lowering is never reached for a deferred
31
+ // predicate (no BF101 / BF102). #1966
32
+ if (attr.clientOnly) continue
33
+ // `dangerouslySetInnerHTML` never renders as an HTML attribute — it's
34
+ // handled by `renderDangerousInnerHtml` instead, which replaces the
35
+ // element's children. Skip it here so its `{ __html: ... }` object
36
+ // literal never reaches the generic object-literal BF101 refusal
37
+ // (which would double-report alongside the purpose-built one).
38
+ if (isDangerousInnerHtmlAttr(attr)) continue
39
+ // `key` never renders as a literal HTML attribute — #2753 resolves it
40
+ // onto `element.keyAttr` (name AND value) at IR-build time, emitted
41
+ // separately by `renderElementShell`. A stray `key` that jsx-to-ir.ts did
42
+ // NOT recognize as a loop row root (so `keyAttr` was never set) has no
43
+ // defined rendering outside a `.map()` anyway; drop it rather than
44
+ // leak an invalid `key="..."` HTML attribute.
45
+ if (attr.name === 'key') continue
46
+ // Rewrite JSX special-prop names to their HTML-attribute counterparts (#1475).
47
+ const attrName = attr.name === 'className' ? 'class' : attr.name
48
+ const lowered = emitAttrValue(attr.value, emitter, attrName)
49
+ if (lowered) parts.push(lowered)
50
+ }
51
+
52
+ return parts.length > 0 ? ' ' + parts.join(' ') : ''
53
+ }
54
+
55
+ /** How one adapter spells the parts of an element {@link renderElementShell} writes. */
56
+ export interface ElementShellSpelling {
57
+ /** Lowers each attribute value, the row key included. */
58
+ attrEmitter: AttrValueEmitter
59
+ /** The element's `dangerouslySetInnerHTML` content, or `null` when it has none. */
60
+ renderDangerousInnerHtml(element: IRElement): string | null
61
+ renderChildren(children: IRNode[]): string
62
+ renderScopeMarker(instanceIdExpr: string): string
63
+ renderSlotMarker(slotId: string): string
64
+ /**
65
+ * The raw print of the runtime's `data-key` attribute, for a render root
66
+ * that carries whatever key its own caller supplies (the `bf` instance's
67
+ * `data_key` field).
68
+ */
69
+ dataKeyRelay: string
70
+ /** The escaped print of this instance's scope id, the `bf-po` value. */
71
+ scopeIdValue: string
72
+ /** Sends an SSR-portal element to the `bf.portals()` outlet instead of placing it inline. */
73
+ wrapSsrPortalElement(rendered: string): string
74
+ }
75
+
76
+ /** The element, from its open tag to its close tag. */
77
+ export function renderElementShell(element: IRElement, spelling: ElementShellSpelling): string {
78
+ const tag = element.tag
79
+ const attrs = renderElementAttributes(element, spelling.attrEmitter)
80
+ const dangerousHtml = spelling.renderDangerousInnerHtml(element)
81
+ const children = dangerousHtml !== null ? dangerousHtml : spelling.renderChildren(element.children)
82
+
83
+ let hydrationAttrs = ''
84
+ if (element.needsScope) {
85
+ hydrationAttrs += ` ${spelling.renderScopeMarker('')}`
86
+ }
87
+ // #2753: `element.keyAttr` is the ONE IR-resolved decision for this
88
+ // element's row-key attribute — replacing both the `carriesDataKey`
89
+ // boolean and the adapters' own `rootScopeNodes`/`needsScope` check
90
+ // (mechanism 2: a render-root relay, including the #2732 fragment-root
91
+ // case) and the separate `currentLoopKeyDepth`-driven rewrite of a
92
+ // literal `key` attribute the adapters used to do in `renderAttributes`
93
+ // (mechanism 1: a `.map()` row root compiled inline here).
94
+ if (element.keyAttr) {
95
+ if (element.keyAttr.value !== undefined) {
96
+ const lowered = emitAttrValue(
97
+ { kind: 'expression', expr: element.keyAttr.value },
98
+ spelling.attrEmitter,
99
+ element.keyAttr.name,
100
+ )
101
+ if (lowered) hydrationAttrs += ` ${lowered}`
102
+ } else {
103
+ // Relay: this element is one of THIS component's own render roots,
104
+ // carrying whatever key its OWN caller supplies at runtime when this
105
+ // component is itself invoked as a caller's keyed loop row. Mirrors
106
+ // Hono stamping data-key on each loop item's root, including
107
+ // early-return (if-statement) roots (#1297), and #2732's fragment-root
108
+ // case.
109
+ hydrationAttrs += ` ${spelling.dataKeyRelay}`
110
+ }
111
+ }
112
+ if (element.slotId) {
113
+ hydrationAttrs += ` ${spelling.renderSlotMarker(element.slotId)}`
114
+ }
115
+ // Page-lifecycle boundary lowered from `<Region>` (spec/router.md). The id
116
+ // is a deterministic static string (`<file scope>:<index>`), so it emits as
117
+ // a plain literal attribute — no template tag.
118
+ if (element.regionId) {
119
+ hydrationAttrs += ` ${BF_REGION}="${element.regionId}"`
120
+ }
121
+ // #3119: the `ref`-callback SSR-portal pattern (`ssrPortalOwnerScope`,
122
+ // `isSsrPortalRefCallback` in `@barefootjs/jsx`) — the overlay/content
123
+ // pattern the dialog-style primitives use. Stamp `bf-po` directly on
124
+ // this element's own tag, matching exactly what the client
125
+ // `createPortal(el, document.body, { ownerScope })` stamps onto the
126
+ // SAME element at hydrate time (`packages/client/src/runtime/
127
+ // portal.ts`), mirroring the Hono reference adapter's identical
128
+ // `BF_PORTAL_OWNER` stamp. The element itself is then routed through
129
+ // `wrapSsrPortalElement` below instead of returned for inline
130
+ // placement, so it renders at the portal outlet the app's own layout
131
+ // places near `</body>`.
132
+ if (element.ssrPortalOwnerScope) {
133
+ hydrationAttrs += ` ${BF_PORTAL_OWNER}="${spelling.scopeIdValue}"`
134
+ }
135
+
136
+ const rendered = VOID_ELEMENTS.includes(tag.toLowerCase())
137
+ ? `<${tag}${attrs}${hydrationAttrs}>`
138
+ : `<${tag}${attrs}${hydrationAttrs}>${children}</${tag}>`
139
+
140
+ if (element.ssrPortalOwnerScope) {
141
+ return spelling.wrapSsrPortalElement(rendered)
142
+ }
143
+ return rendered
144
+ }
145
+
146
+ /**
147
+ * A fragment's children. A component-root fragment has no element of its
148
+ * own to carry the scope, so `wrapScopeComment` brackets the children with
149
+ * the comment-based scope marker pair; its end marker bounds the scope's
150
+ * sibling range, or queries from the fragment scope leak onto later
151
+ * siblings owned by the parent (#2289).
152
+ */
153
+ export function renderFragmentScope(
154
+ fragment: IRFragment,
155
+ renderChildren: (children: IRNode[]) => string,
156
+ wrapScopeComment: (rendered: string) => string,
157
+ ): string {
158
+ const children = renderChildren(fragment.children)
159
+ return fragment.needsScopeComment ? wrapScopeComment(children) : children
160
+ }
@@ -388,6 +388,14 @@ export abstract class BaseAdapter implements TemplateAdapter {
388
388
  return children.map((child) => this.renderNode(child)).join('')
389
389
  }
390
390
 
391
+ /** `null` for a `null` / `undefined` expression, which renders nothing; otherwise the node. */
392
+ protected renderNodeOrNull(node: IRNode): string | null {
393
+ if (node.type === 'expression' && (node.expr === 'null' || node.expr === 'undefined')) {
394
+ return null
395
+ }
396
+ return this.renderNode(node)
397
+ }
398
+
391
399
  /** Default: render fallback + children inline (no streaming). Override for streaming support. */
392
400
  renderAsync(node: IRAsync): string {
393
401
  return this.renderNode(node.fallback) + this.renderChildren(node.children)