@barefootjs/jsx 0.35.8 → 0.37.0

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.
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Regression tests for #3000: a module-top-level helper declared as
3
+ * `function name(params) { ... }` that calls ANOTHER module-top-level
4
+ * `function` helper (not itself, not any component-scope name) is safe to
5
+ * reference from a component's CSR template lambda by bare name. This is
6
+ * the function-declaration analog of #2988 (arrow-valued module consts).
7
+ *
8
+ * Pre-fix, `compute-inlinability.ts`'s `functionReferencesDeclaredName`
9
+ * flagged a module-scope function unsafe if it referenced ANY name in
10
+ * `graph.declaredNames` — every local const/function/signal/prop — not
11
+ * just names that are themselves unsafe. `fmt` calling `inner` (itself a
12
+ * safe module-scope helper) tripped that check even though both would
13
+ * correctly land at true module scope per `compute-scope.ts`'s own
14
+ * forward-reachability fixpoint — so the CSR-emitted template lambda
15
+ * substituted `${''}` for the `fmt(label)` slot instead of referencing
16
+ * `fmt` by name.
17
+ *
18
+ * The fix has `computeInlinability`'s function loop read `functionScope`
19
+ * from the same `computeDeclarationScopes(ctx, graph)` call #2998 already
20
+ * added for constants, instead of re-deriving an independent (and more
21
+ * conservative) verdict — closing out the "one producer, three
22
+ * consumers" restructuring #2988's issue body proposed for constants and
23
+ * functions alike.
24
+ *
25
+ * These tests exercise `compileJSX` — the same entry point
26
+ * `@barefootjs/vite`'s plugin and `packages/adapter-tests/src/csr-render.ts`
27
+ * call — and evaluate the extracted CSR template body as a real
28
+ * template-literal function, mirroring what `hydrate()` does at runtime
29
+ * (minus the DOM). This is the closest unit-level stand-in for the real
30
+ * pipeline: `compileJSX` performs the exact analysis → compute-scope →
31
+ * compute-inlinability → html-template sequence `generateClientJsWithSourceMap`
32
+ * runs in production (`packages/jsx/src/ir-to-client-js/generate-init.ts`
33
+ * L66-73), with nothing mocked.
34
+ */
35
+ import { describe, test, expect } from 'bun:test'
36
+ import { compileJSX } from '../compiler'
37
+ import { HonoAdapter } from '../../../adapter-hono/src/adapter/hono-adapter'
38
+ import { extractTemplateBody } from './staged-ir/helpers'
39
+ import { RUNTIME_IMPORT_CANDIDATES } from '../ir-to-client-js/imports'
40
+
41
+ const onlyErrors = (errors: { severity?: string }[]) =>
42
+ errors.filter((e) => e.severity === 'error')
43
+
44
+ function compileTemplateBody(source: string, fileName: string): { templateBody: string; clientJs: string } {
45
+ const result = compileJSX(source, fileName, { adapter: new HonoAdapter() })
46
+ expect(onlyErrors(result.errors)).toHaveLength(0)
47
+ const clientJs = result.files.find((f) => f.type === 'clientJs')!.content
48
+ return { templateBody: extractTemplateBody(clientJs), clientJs }
49
+ }
50
+
51
+ /** Module-level declarations sit between the import line and
52
+ * `export function init<Name>` in the compiled bundle. The template
53
+ * lambda runs at real module scope in production, closing over these
54
+ * by normal JS scoping — reproduce that here instead of leaving them
55
+ * undeclared in the sandbox. */
56
+ function extractModulePreamble(clientJs: string): string {
57
+ const m = clientJs.match(/\n\n([\s\S]*?)\nexport function init\w+/)
58
+ return m ? m[1] : ''
59
+ }
60
+
61
+ /** Evaluate an extracted CSR template body as a real template-literal
62
+ * function, with every runtime helper the compiler might reference
63
+ * stubbed to identity/no-op, and the compiled bundle's module-level
64
+ * declarations (if any) in scope. Mirrors `hydrate()` minus the DOM. */
65
+ function evalTemplate(templateBody: string, props: Record<string, unknown>, modulePreamble = ''): string {
66
+ const helperNames = [...RUNTIME_IMPORT_CANDIDATES]
67
+ const stubs = helperNames.map((name) => {
68
+ if (name === 'escapeAttr' || name === 'escapeText' || name === 'escapeTextOrMarkup' || name === 'styleToCss') {
69
+ return (v: unknown) => String(v)
70
+ }
71
+ return (..._args: unknown[]) => ''
72
+ })
73
+ // eslint-disable-next-line no-new-func
74
+ const fn = new Function('_p', ...helperNames, `${modulePreamble}\nreturn \`${templateBody}\``)
75
+ return fn(props, ...stubs)
76
+ }
77
+
78
+ describe('CSR template: module-scope function calling another module-scope function (#3000)', () => {
79
+ test('a module function helper that calls another module function helper renders its real value, not an empty seed', () => {
80
+ const source = `
81
+ 'use client'
82
+ import { createSignal } from '@barefootjs/client'
83
+
84
+ function inner(s: string) { return s.toUpperCase() }
85
+ function fmt(s: string) { return inner(s) }
86
+
87
+ export function Widget({ label }: { label: string }) {
88
+ const [count, setCount] = createSignal(0)
89
+ return (
90
+ <div>
91
+ <span>{fmt(label)}</span>
92
+ <button onClick={() => setCount(count() + 1)}>{count()}</button>
93
+ </div>
94
+ )
95
+ }
96
+ `
97
+ const { templateBody, clientJs } = compileTemplateBody(source, 'Widget.tsx')
98
+
99
+ // Both helpers are referenced by bare name in the template (wrapped
100
+ // in relocate/CSR-substitution parens, so match on the word boundary
101
+ // rather than the literal call-site text), not substituted away as
102
+ // an unsafe/empty fallback.
103
+ expect(/\bfmt\b/.test(templateBody)).toBe(true)
104
+ expect(templateBody).not.toBe('')
105
+
106
+ const html = evalTemplate(templateBody, { label: 'hi' }, extractModulePreamble(clientJs))
107
+ expect(html).toContain('HI')
108
+ expect(html).not.toContain('undefined')
109
+ })
110
+
111
+ test('the arrow-const form of the same two-hop helper chain renders identically (parity check with #2988)', () => {
112
+ const functionSource = `
113
+ 'use client'
114
+ import { createSignal } from '@barefootjs/client'
115
+ function inner(s: string) { return s.toUpperCase() }
116
+ function fmt(s: string) { return inner(s) }
117
+ export function Widget({ label }: { label: string }) {
118
+ const [count] = createSignal(0)
119
+ return <div>{fmt(label)}{count()}</div>
120
+ }
121
+ `
122
+ const arrowSource = `
123
+ 'use client'
124
+ import { createSignal } from '@barefootjs/client'
125
+ const inner = (s: string) => s.toUpperCase()
126
+ const fmt = (s: string) => inner(s)
127
+ export function Widget({ label }: { label: string }) {
128
+ const [count] = createSignal(0)
129
+ return <div>{fmt(label)}{count()}</div>
130
+ }
131
+ `
132
+ const fn = compileTemplateBody(functionSource, 'FunctionChainWidget.tsx')
133
+ const arrow = compileTemplateBody(arrowSource, 'ArrowChainWidget.tsx')
134
+
135
+ const fnHtml = evalTemplate(fn.templateBody, { label: 'hi' }, extractModulePreamble(fn.clientJs))
136
+ const arrowHtml = evalTemplate(arrow.templateBody, { label: 'hi' }, extractModulePreamble(arrow.clientJs))
137
+
138
+ expect(fnHtml).toBe(arrowHtml)
139
+ expect(fnHtml).toContain('HI')
140
+ })
141
+
142
+ test('a module function that calls a helper reading a signal stays template-unsafe (no over-widening)', () => {
143
+ // `fmt` here transitively references the module-scope-invisible
144
+ // signal getter `count` (via `inner`), so both must stay classified
145
+ // unsafe — the fixpoint must demote them to 'init' scope exactly
146
+ // like a single module-scope function that touches component
147
+ // internals directly already is.
148
+ const source = `
149
+ 'use client'
150
+ import { createSignal } from '@barefootjs/client'
151
+
152
+ function inner(s: string) { return \`\${s}-\${count()}\` }
153
+ function fmt(s: string) { return inner(s) }
154
+
155
+ export function Widget({ label }: { label: string }) {
156
+ const [count, setCount] = createSignal(0)
157
+ return <div>{fmt(label)}</div>
158
+ }
159
+ `
160
+ const { templateBody } = compileTemplateBody(source, 'UnsafeChainWidget.tsx')
161
+ // Falls back to the empty-slot sentinel, same as the pre-existing
162
+ // behavior for any function that genuinely can't be hoisted to
163
+ // module scope — NOT a bare `fmt(...)` reference (which would
164
+ // ReferenceError: `fmt` never gets a module-level declaration for
165
+ // this shape).
166
+ expect(templateBody).not.toContain('fmt(')
167
+ })
168
+
169
+ test('a three-hop module function chain resolves the same fixpoint transitively', () => {
170
+ // `outer` -> `mid` -> `inner`, none touching component internals.
171
+ // Exercises resolve-by-name for a chain longer than one hop, not just
172
+ // the direct two-function case above. Since none of the three
173
+ // transitively reference an init-required name, all three land on
174
+ // `'module'` via the fixpoint's trailing "survivors are module"
175
+ // assignment on the very first pass (`changed` never flips `true`) —
176
+ // this is coverage for the 3-hop resolve-by-name behavior, not for
177
+ // multi-round fixpoint iteration specifically (that would need at
178
+ // least one hop to genuinely demote before a later pass re-checks a
179
+ // caller of it).
180
+ const source = `
181
+ 'use client'
182
+ import { createSignal } from '@barefootjs/client'
183
+
184
+ function inner(s: string) { return s.toUpperCase() }
185
+ function mid(s: string) { return inner(s) }
186
+ function outer(s: string) { return mid(s) }
187
+
188
+ export function Widget({ label }: { label: string }) {
189
+ const [count] = createSignal(0)
190
+ return <div>{outer(label)}{count()}</div>
191
+ }
192
+ `
193
+ const { templateBody, clientJs } = compileTemplateBody(source, 'ThreeHopWidget.tsx')
194
+ expect(/\bouter\b/.test(templateBody)).toBe(true)
195
+
196
+ const html = evalTemplate(templateBody, { label: 'hi' }, extractModulePreamble(clientJs))
197
+ expect(html).toContain('HI')
198
+ expect(html).not.toContain('undefined')
199
+ })
200
+ })
@@ -59,7 +59,14 @@ export function Search() {
59
59
  // Pre-fix this line was duplicated: once (broken) at the top of init
60
60
  // and once inside `score`'s own body. It must appear exactly once.
61
61
  expect(countOccurrences(clientJs, 'const t = title.toLowerCase()')).toBe(1)
62
- expect(clientJs).toContain('const score = (title, term) => {')
62
+ // `score` closes over nothing but its own params, so #2988's
63
+ // compute-scope fixpoint now promotes it to true module scope
64
+ // (`var score = score ?? (...)`, parenthesised — an arrow is not a
65
+ // valid bare `??` operand) instead of leaving it a per-instance
66
+ // `const` inside `initSearch`. This is the shape #2988 exists to
67
+ // produce; pre-#2988 this assertion read
68
+ // `expect(clientJs).toContain('const score = (title, term) => {')`.
69
+ expect(clientJs).toContain('var score = score ?? ((title, term) => {')
63
70
  // The Hono reference adapter's marked template is TSX source rendered
64
71
  // through the JSX runtime, so it legitimately contains the helper
65
72
  // once, correctly scoped — pre-fix it was duplicated here too.
@@ -83,7 +90,10 @@ export default Widget
83
90
  `)
84
91
  expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
85
92
  expect(countOccurrences(clientJs, "await fetch('/data.json')")).toBe(1)
86
- expect(clientJs).toContain('const loadData = async () => {')
93
+ // Same #2988 promotion as the sync case above: `loadData` closes
94
+ // over nothing but its own (empty) params, so it is now hoisted to
95
+ // real module scope instead of staying a per-instance `const`.
96
+ expect(clientJs).toContain('var loadData = loadData ?? (async () => {')
87
97
  // Same reasoning as the sync case: the reference adapter's marked
88
98
  // template is TSX source, so `loadData` legitimately appears once,
89
99
  // correctly scoped — pre-fix its inner `await` was duplicated here.
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Regression tests for #2988: a module-top-level helper declared as
3
+ * `const name = (params) => expr` (arrow form) that closes over nothing
4
+ * but its own parameters is safe to reference from a component's CSR
5
+ * template lambda by bare name — same as the equivalent
6
+ * `function name(params) { ... }` declaration form. Pre-fix,
7
+ * `compute-inlinability.ts`'s `classifyConstantInitial` returned
8
+ * `arrow-literal` (template-unsafe) for EVERY arrow-valued constant
9
+ * unconditionally, ignoring `isModule` entirely — so the CSR-emitted
10
+ * template lambda substituted `${''}` for the slot instead of the real
11
+ * value, even though `compute-scope.ts` had no equivalent
12
+ * forward-reachability fixpoint for constants either (it fell straight
13
+ * to `'init'` scope, disagreeing with `relocate.ts`'s independent
14
+ * `'module-local'` classification, which reads only the raw `isModule`
15
+ * flag).
16
+ *
17
+ * The fix folds arrow-valued module constants into the SAME
18
+ * forward-reachability fixpoint `compute-scope.ts` already runs for
19
+ * module-level functions, and has `compute-inlinability.ts` read that
20
+ * one answer (via a fresh, pure call to `computeDeclarationScopes`)
21
+ * instead of re-deriving an independent verdict.
22
+ *
23
+ * These tests exercise `compileJSX` — the same entry point
24
+ * `@barefootjs/vite`'s plugin and `packages/adapter-tests/src/csr-render.ts`
25
+ * call — and evaluate the extracted CSR template body as a real
26
+ * template-literal function, mirroring what `hydrate()` does at runtime
27
+ * (minus the DOM). This is the closest unit-level stand-in for the real
28
+ * pipeline: `compileJSX` performs the exact analysis → compute-scope →
29
+ * compute-inlinability → html-template sequence `generateClientJsWithSourceMap`
30
+ * runs in production (`packages/jsx/src/ir-to-client-js/generate-init.ts`
31
+ * L66-73), with nothing mocked.
32
+ */
33
+ import { describe, test, expect } from 'bun:test'
34
+ import { compileJSX } from '../compiler'
35
+ import { HonoAdapter } from '../../../adapter-hono/src/adapter/hono-adapter'
36
+ import { extractTemplateBody } from './staged-ir/helpers'
37
+ import { RUNTIME_IMPORT_CANDIDATES } from '../ir-to-client-js/imports'
38
+
39
+ const onlyErrors = (errors: { severity?: string }[]) =>
40
+ errors.filter((e) => e.severity === 'error')
41
+
42
+ function compileTemplateBody(source: string, fileName: string): { templateBody: string; clientJs: string } {
43
+ const result = compileJSX(source, fileName, { adapter: new HonoAdapter() })
44
+ expect(onlyErrors(result.errors)).toHaveLength(0)
45
+ const clientJs = result.files.find((f) => f.type === 'clientJs')!.content
46
+ return { templateBody: extractTemplateBody(clientJs), clientJs }
47
+ }
48
+
49
+ /** Module-level declarations (`var fmt = fmt ?? (...)`, etc.) sit
50
+ * between the import line and `export function init<Name>` in the
51
+ * compiled bundle. The template lambda runs at real module scope in
52
+ * production, closing over these by normal JS scoping — reproduce
53
+ * that here instead of leaving them undeclared in the sandbox. */
54
+ function extractModulePreamble(clientJs: string): string {
55
+ const m = clientJs.match(/\n\n([\s\S]*?)\nexport function init\w+/)
56
+ return m ? m[1] : ''
57
+ }
58
+
59
+ /** Evaluate an extracted CSR template body as a real template-literal
60
+ * function, with every runtime helper the compiler might reference
61
+ * stubbed to identity/no-op, and the compiled bundle's module-level
62
+ * declarations (if any) in scope. Mirrors `hydrate()` minus the DOM. */
63
+ function evalTemplate(templateBody: string, props: Record<string, unknown>, modulePreamble = ''): string {
64
+ const helperNames = [...RUNTIME_IMPORT_CANDIDATES]
65
+ const stubs = helperNames.map((name) => {
66
+ if (name === 'escapeAttr' || name === 'escapeText' || name === 'escapeTextOrMarkup' || name === 'styleToCss') {
67
+ return (v: unknown) => String(v)
68
+ }
69
+ return (..._args: unknown[]) => ''
70
+ })
71
+ // eslint-disable-next-line no-new-func
72
+ const fn = new Function('_p', ...helperNames, `${modulePreamble}\nreturn \`${templateBody}\``)
73
+ return fn(props, ...stubs)
74
+ }
75
+
76
+ describe('CSR template: module-scope arrow-valued const helper (#2988)', () => {
77
+ test('an arrow-valued module const applied to a prop renders its real value, not an empty seed', () => {
78
+ const source = `
79
+ 'use client'
80
+ import { createSignal } from '@barefootjs/client'
81
+
82
+ const fmt = (s: string) => s.toUpperCase()
83
+
84
+ export function Widget({ label }: { label: string }) {
85
+ const [count, setCount] = createSignal(0)
86
+ return (
87
+ <div>
88
+ <span>{fmt(label)}</span>
89
+ <button onClick={() => setCount(count() + 1)}>{count()}</button>
90
+ </div>
91
+ )
92
+ }
93
+ `
94
+ const { templateBody, clientJs } = compileTemplateBody(source, 'Widget.tsx')
95
+
96
+ // The module-level declaration is emitted once, parenthesised on
97
+ // the right of `??` (an arrow function is NOT a valid `??` operand
98
+ // unwrapped — `x ?? (s) => …` is a SyntaxError).
99
+ expect(clientJs).toContain('var fmt = fmt ?? ((s) => s.toUpperCase())')
100
+
101
+ // `fmt` is referenced by bare name in the template (wrapped in
102
+ // relocate/CSR-substitution parens, so match on the word boundary
103
+ // rather than the literal call-site text), not substituted away as
104
+ // an unsafe/empty fallback.
105
+ expect(/\bfmt\b/.test(templateBody)).toBe(true)
106
+ expect(templateBody).not.toBe('')
107
+
108
+ const html = evalTemplate(templateBody, { label: 'hi' }, extractModulePreamble(clientJs))
109
+ expect(html).toContain('HI')
110
+ expect(html).not.toContain('undefined')
111
+ })
112
+
113
+ test('the function-declaration form of the same helper renders identically (parity check)', () => {
114
+ const arrowSource = `
115
+ 'use client'
116
+ import { createSignal } from '@barefootjs/client'
117
+ const fmt = (s: string) => s.toUpperCase()
118
+ export function Widget({ label }: { label: string }) {
119
+ const [count] = createSignal(0)
120
+ return <div>{fmt(label)}{count()}</div>
121
+ }
122
+ `
123
+ const functionSource = `
124
+ 'use client'
125
+ import { createSignal } from '@barefootjs/client'
126
+ function fmt(s: string) { return s.toUpperCase() }
127
+ export function Widget({ label }: { label: string }) {
128
+ const [count] = createSignal(0)
129
+ return <div>{fmt(label)}{count()}</div>
130
+ }
131
+ `
132
+ const arrow = compileTemplateBody(arrowSource, 'ArrowWidget.tsx')
133
+ const fn = compileTemplateBody(functionSource, 'FunctionWidget.tsx')
134
+
135
+ const arrowHtml = evalTemplate(arrow.templateBody, { label: 'hi' }, extractModulePreamble(arrow.clientJs))
136
+ const fnHtml = evalTemplate(fn.templateBody, { label: 'hi' }, extractModulePreamble(fn.clientJs))
137
+
138
+ expect(arrowHtml).toBe(fnHtml)
139
+ expect(arrowHtml).toContain('HI')
140
+ })
141
+
142
+ test('an arrow-valued module const that reads a signal stays template-unsafe (no over-widening)', () => {
143
+ // `fmt` here closes over the module-scope-invisible signal getter
144
+ // `count`, so it must stay classified unsafe — #2988's fixpoint
145
+ // must demote it to 'init' scope exactly like a module-scope
146
+ // FUNCTION that touches component internals already is.
147
+ const source = `
148
+ 'use client'
149
+ import { createSignal } from '@barefootjs/client'
150
+
151
+ const fmt = (s: string) => \`\${s}-\${count()}\`
152
+
153
+ export function Widget({ label }: { label: string }) {
154
+ const [count, setCount] = createSignal(0)
155
+ return <div>{fmt(label)}</div>
156
+ }
157
+ `
158
+ const { templateBody } = compileTemplateBody(source, 'UnsafeWidget.tsx')
159
+ // Falls back to the empty-slot sentinel, same as pre-#2988 behavior
160
+ // for any const that genuinely can't be hoisted to module scope —
161
+ // NOT a bare `fmt(...)` reference (which would ReferenceError: `fmt`
162
+ // never gets a module-level declaration for this shape).
163
+ expect(templateBody).not.toContain('fmt(')
164
+ })
165
+
166
+ test('a component-scope (non-module) arrow const of the same shape stays template-unsafe', () => {
167
+ const source = `
168
+ 'use client'
169
+ import { createSignal } from '@barefootjs/client'
170
+
171
+ export function Widget({ label }: { label: string }) {
172
+ const [count, setCount] = createSignal(0)
173
+ const fmt = (s: string) => s.toUpperCase()
174
+ return <div>{fmt(label)}{count()}</div>
175
+ }
176
+ `
177
+ const { templateBody } = compileTemplateBody(source, 'LocalArrowWidget.tsx')
178
+ expect(templateBody).not.toContain('fmt(')
179
+ })
180
+ })
@@ -170,6 +170,11 @@ const TEMPLATE_METACHAR_PATTERNS: Readonly<Record<string, RegExp>> = {
170
170
  jinja: /\{\{|\{%|\{#/,
171
171
  minijinja: /\{\{|\{%|\{#/,
172
172
  mojolicious: /<%|^\s*%/m,
173
+ // Pebble's confirmed grammar (pebble-adapter.ts's file header syntax
174
+ // table): `{{ }}` print, `{% %}` tag, and a `{# #}` comment form — the
175
+ // identical three-delimiter family Jinja/Twig/minijinja share (Pebble is
176
+ // explicitly Twig-inspired), so the same guard pattern applies verbatim.
177
+ pebble: /\{\{|\{%|\{#/,
173
178
  twig: /\{\{|\{%|\{#/,
174
179
  xslate: /<:|^\s*:/m,
175
180
  }
package/src/analyzer.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  */
8
8
 
9
9
  import ts from 'typescript'
10
+ import { CLIENT_DIRECTIVE_INTERIOR_RE, USE_CLIENT_DIRECTIVE, isUseClientDirectiveText } from './directives.ts'
10
11
  import type { ImportSpecifier, TypeInfo, ParamInfo, ReactiveFactoryInfo, DeclinedReactiveFactory, RequiredFactoryImport, FactoryRenameSite, SourceLocation } from './types.ts'
11
12
  import { parseExpression, parseBlockBodyTolerant, foldBlockToExpr, tsNodeToParsedExpr } from './expression-parser.ts'
12
13
  import type { CallbackBodyAcceptor } from './adapters/interface.ts'
@@ -416,10 +417,7 @@ function visit(
416
417
  ): void {
417
418
  // Check for 'use client' directive at module level
418
419
  if (ts.isExpressionStatement(node) && ts.isStringLiteral(node.expression)) {
419
- if (
420
- node.expression.text === 'use client' ||
421
- node.expression.text === "'use client'"
422
- ) {
420
+ if (isUseClientDirectiveText(node.expression.text)) {
423
421
  ctx.hasUseClientDirective = true
424
422
  }
425
423
  }
@@ -3091,7 +3089,6 @@ function declarationIsReactiveFactoryCall(
3091
3089
  // Module-level `/* @client */` directive detection + collection
3092
3090
  // =============================================================================
3093
3091
 
3094
- const CLIENT_DIRECTIVE_INTERIOR_RE = /^\s*@client\s*$/
3095
3092
  const BLOCK_COMMENT_RE = /\/\*([\s\S]*?)\*\//g
3096
3093
 
3097
3094
  /**
@@ -4288,7 +4285,7 @@ function fileHasUseClientDirective(filePath: string): boolean {
4288
4285
  function visit(node: ts.Node): void {
4289
4286
  if (found) return
4290
4287
  if (ts.isExpressionStatement(node) && ts.isStringLiteral(node.expression)) {
4291
- if (node.expression.text === 'use client') {
4288
+ if (node.expression.text === USE_CLIENT_DIRECTIVE) {
4292
4289
  found = true
4293
4290
  return
4294
4291
  }
@@ -4472,7 +4469,7 @@ function listComponentFunctionsFromSourceFile(sourceFile: ts.SourceFile): string
4472
4469
  const hasUseClient = sourceFile.statements.some(stmt =>
4473
4470
  ts.isExpressionStatement(stmt) &&
4474
4471
  ts.isStringLiteral(stmt.expression) &&
4475
- (stmt.expression.text === 'use client' || stmt.expression.text === "'use client'")
4472
+ isUseClientDirectiveText(stmt.expression.text)
4476
4473
  )
4477
4474
  const namedExports = collectNamedExports(sourceFile)
4478
4475
 
@@ -5905,7 +5902,7 @@ function factoryImportInsertionOffset(sf: ts.SourceFile): number {
5905
5902
  for (const stmt of sf.statements) {
5906
5903
  if (ts.isImportDeclaration(stmt)) { lastImportEnd = stmt.getEnd(); continue }
5907
5904
  if (directiveEnd === -1 && ts.isExpressionStatement(stmt) &&
5908
- ts.isStringLiteral(stmt.expression) && stmt.expression.text === 'use client') {
5905
+ ts.isStringLiteral(stmt.expression) && stmt.expression.text === USE_CLIENT_DIRECTIVE) {
5909
5906
  directiveEnd = stmt.getEnd()
5910
5907
  }
5911
5908
  }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The source-level directives the compiler recognizes. This module is the
3
+ * single definition of their spelling: every detection site in the
4
+ * analyzer, the IR builder, and the preprocessors reads the constants
5
+ * below rather than repeating the literal, and the API reference
6
+ * (`docs/core/advanced/api-reference.md`, generated by
7
+ * `scripts/generate-api-reference.ts`) reads their JSDoc tags.
8
+ *
9
+ * The docstrings below write the client directive with a zero-width space
10
+ * (U+200B) before the `/` that would close this comment, and before the `c`
11
+ * of a space-preceded at-sign that TypeScript's JSDoc scanner would
12
+ * otherwise read as a new tag. The generator strips every U+200B, so the
13
+ * published reference shows — and a reader can copy — the real syntax.
14
+ */
15
+
16
+ /**
17
+ * Module-level `"use client"` directive. A component file that opens with
18
+ * it ships client JS and hydrates; without it the file's components render
19
+ * to static HTML only, and importing a browser-only API from it is a
20
+ * compile error.
21
+ *
22
+ * @example
23
+ * ```tsx
24
+ * "use client"
25
+ * import { createSignal } from '@barefootjs/client'
26
+ *
27
+ * export function Counter() {
28
+ * const [count, setCount] = createSignal(0)
29
+ * return <button onClick={() => setCount(count() + 1)}>{count()}</button>
30
+ * }
31
+ * ```
32
+ *
33
+ * @since 0.1.0
34
+ * @stability beta
35
+ */
36
+ export const USE_CLIENT_DIRECTIVE = 'use client'
37
+
38
+ /**
39
+ * Expression-level `/* @​client *​/` directive, placed as a block comment
40
+ * directly before a JSX expression, an attribute initializer or a component
41
+ * prop initializer. It tells the compiler to skip server evaluation of that
42
+ * expression and evaluate it on the client only — the escape for expressions
43
+ * no template adapter can lower.
44
+ *
45
+ * @example
46
+ * ```tsx
47
+ * // No template adapter can lower `toLocaleString()`, so evaluate it on the
48
+ * // client only. The server renders nothing there; hydration fills it in.
49
+ * <span>{/* @​client *​/ total().toLocaleString()}</span>
50
+ * ```
51
+ *
52
+ * @since 0.1.0
53
+ * @stability beta
54
+ */
55
+ export const CLIENT_EXPRESSION_DIRECTIVE = '@client'
56
+
57
+ /**
58
+ * True when a string-literal expression statement's text is the
59
+ * `"use client"` directive. Accepts the doubly-quoted spelling
60
+ * (`"'use client'"`) some detection sites have always tolerated.
61
+ *
62
+ * @internal
63
+ */
64
+ export function isUseClientDirectiveText(text: string): boolean {
65
+ return text === USE_CLIENT_DIRECTIVE || text === `'${USE_CLIENT_DIRECTIVE}'`
66
+ }
67
+
68
+ /**
69
+ * Matches the interior of a block comment that is exactly the client
70
+ * expression directive (whitespace-padded), so the directive word as a
71
+ * substring of some other comment never matches.
72
+ *
73
+ * @internal
74
+ */
75
+ export const CLIENT_DIRECTIVE_INTERIOR_RE = new RegExp(`^\\s*${CLIENT_EXPRESSION_DIRECTIVE}\\s*$`)
package/src/index.ts CHANGED
@@ -345,6 +345,9 @@ export type {
345
345
  // HTML constants
346
346
  export { BOOLEAN_ATTRS, isBooleanAttr } from './html-constants.ts'
347
347
 
348
+ // The compiler's source-level directives (single definition of their spelling)
349
+ export { USE_CLIENT_DIRECTIVE, CLIENT_EXPRESSION_DIRECTIVE } from './directives.ts'
350
+
348
351
  // Shared props-object-pattern helpers for the Go / Mojo template adapters
349
352
  export { augmentInheritedPropAccesses, parseRecordIndexAccess, evalStringArrayJoin, collectModuleStringConsts, lookupStaticRecordLiteral, collectContextConsumers } from './augment-inherited-props.ts'
350
353
  export type { RecordIndexAccess, RecordIndexEntry, ContextConsumer } from './augment-inherited-props.ts'