@barefootjs/jsx 0.38.0 → 0.39.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.
Files changed (87) hide show
  1. package/dist/action-accessor.d.ts +159 -0
  2. package/dist/action-accessor.d.ts.map +1 -0
  3. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  4. package/dist/analyzer.d.ts +30 -1
  5. package/dist/analyzer.d.ts.map +1 -1
  6. package/dist/async-action-refusal.d.ts +45 -0
  7. package/dist/async-action-refusal.d.ts.map +1 -0
  8. package/dist/compiler.d.ts.map +1 -1
  9. package/dist/debug.d.ts +61 -5
  10. package/dist/debug.d.ts.map +1 -1
  11. package/dist/errors.d.ts +4 -0
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/format-date-refusal.d.ts +2 -6
  14. package/dist/format-date-refusal.d.ts.map +1 -1
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1056 -344
  18. package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  20. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/compute-scope.d.ts.map +1 -1
  22. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  23. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/declaration-sort.d.ts +2 -1
  26. package/dist/ir-to-client-js/declaration-sort.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/emit-module-level.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +7 -5
  30. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/types.d.ts +4 -0
  34. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/utils.d.ts +41 -2
  36. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  37. package/dist/jsx-to-ir.d.ts.map +1 -1
  38. package/dist/signal-initializer.d.ts +24 -0
  39. package/dist/signal-initializer.d.ts.map +1 -0
  40. package/dist/template-position-walk.d.ts +68 -0
  41. package/dist/template-position-walk.d.ts.map +1 -0
  42. package/dist/types.d.ts +51 -0
  43. package/dist/types.d.ts.map +1 -1
  44. package/package.json +2 -2
  45. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +191 -1
  46. package/src/__tests__/action-accessor.test.ts +166 -0
  47. package/src/__tests__/create-mutation.test.ts +220 -0
  48. package/src/__tests__/create-query.test.ts +644 -0
  49. package/src/__tests__/csr-fragment-root-scope-shape.test.ts +156 -0
  50. package/src/__tests__/debug.test.ts +222 -0
  51. package/src/__tests__/doc-examples.test.ts +66 -3
  52. package/src/__tests__/props-destructuring.test.ts +79 -4
  53. package/src/__tests__/reactive-factory-arity.test.ts +311 -0
  54. package/src/__tests__/ssr-portal-ref-callback.test.ts +5 -3
  55. package/src/action-accessor.ts +289 -0
  56. package/src/adapters/jsx-adapter.ts +17 -0
  57. package/src/analyzer.ts +558 -33
  58. package/src/async-action-refusal.ts +254 -0
  59. package/src/compiler.ts +3 -0
  60. package/src/debug.ts +318 -103
  61. package/src/errors.ts +39 -0
  62. package/src/format-date-refusal.ts +6 -125
  63. package/src/index.ts +2 -1
  64. package/src/ir-to-client-js/build-references.ts +6 -2
  65. package/src/ir-to-client-js/collect-elements.ts +1 -0
  66. package/src/ir-to-client-js/compute-inlinability.ts +2 -1
  67. package/src/ir-to-client-js/compute-scope.ts +3 -1
  68. package/src/ir-to-client-js/control-flow/plan/build-insert.ts +1 -0
  69. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  70. package/src/ir-to-client-js/control-flow/stringify/insert.ts +1 -1
  71. package/src/ir-to-client-js/csr-substitute.ts +11 -3
  72. package/src/ir-to-client-js/declaration-sort.ts +7 -3
  73. package/src/ir-to-client-js/emit-module-level.ts +7 -4
  74. package/src/ir-to-client-js/emit-registration.ts +5 -10
  75. package/src/ir-to-client-js/index.ts +7 -2
  76. package/src/ir-to-client-js/phases/ref-callbacks.ts +1 -1
  77. package/src/ir-to-client-js/plan/build-declaration-emit.ts +16 -15
  78. package/src/ir-to-client-js/plan/declaration-emit.ts +7 -5
  79. package/src/ir-to-client-js/prop-handling.ts +4 -0
  80. package/src/ir-to-client-js/reactivity.ts +1 -0
  81. package/src/ir-to-client-js/stringify/declaration-emit.ts +14 -7
  82. package/src/ir-to-client-js/types.ts +4 -0
  83. package/src/ir-to-client-js/utils.ts +55 -7
  84. package/src/jsx-to-ir.ts +36 -2
  85. package/src/signal-initializer.ts +36 -0
  86. package/src/template-position-walk.ts +203 -0
  87. package/src/types.ts +52 -0
@@ -0,0 +1,644 @@
1
+ /**
2
+ * `createQuery` recognition (#3165): the value is collected as a signal
3
+ * seeded from `options.initial`, and the request function is emitted into
4
+ * the client JS only. Since #3166 (#3158-B), a DIRECT read of the action's
5
+ * `isPending()` / `error()` accessors — as the WHOLE expression of a
6
+ * condition, or (`isPending()` only) of an ARIA boolean-state attribute — is
7
+ * an ordinary seeded value (`false` / `undefined`, spec/async.md §7.3), not a
8
+ * refusal; a direct read anywhere else (where the seed would not render like
9
+ * Hono), calling the action itself, and any compound/transitive read
10
+ * (through a memo, constant or function) still refuse with BF117. Cross-adapter output lives in the `create-query-*`
11
+ * conformance fixtures; this file pins the compiler-internal decisions.
12
+ */
13
+
14
+ import { describe, test, expect } from 'bun:test'
15
+ import ts from 'typescript'
16
+ import path from 'path'
17
+ import { compileJSX } from '../compiler'
18
+ import { TestAdapter } from '../adapters/test-adapter'
19
+ import { HonoAdapter } from '../../../adapter-hono/src/adapter/hono-adapter'
20
+ import { GoTemplateAdapter } from '../../../adapter-go-template/src/index'
21
+ import { extractInitBody, extractTemplateBody } from './staged-ir/helpers'
22
+
23
+ function compile(source: string, options: { hono?: boolean; program?: ts.Program; fileName?: string } = {}) {
24
+ const fileName = options.fileName ?? 'Component.tsx'
25
+ const result = compileJSX(source, fileName, {
26
+ adapter: options.hono ? new HonoAdapter() : new TestAdapter(),
27
+ ...(options.program ? { program: options.program } : {}),
28
+ })
29
+ const clientJs = result.files.find((f) => f.type === 'clientJs')?.content ?? ''
30
+ const ssr = result.files.find((f) => f.type === 'markedTemplate')?.content ?? ''
31
+ return {
32
+ codes: result.errors.map((e) => e.code),
33
+ errors: result.errors,
34
+ clientJs,
35
+ initBody: extractInitBody(clientJs),
36
+ templateBody: extractTemplateBody(clientJs),
37
+ ssr,
38
+ }
39
+ }
40
+
41
+ /**
42
+ * A program whose `@barefootjs/client` resolves to the real sources, so the
43
+ * TypeChecker sees `createQuery`'s real signature (aliases, `Reactive` brands).
44
+ */
45
+ function programFor(source: string, componentPath: string): ts.Program {
46
+ const repo = path.resolve(__dirname, '../../../..')
47
+ const compilerOptions: ts.CompilerOptions = {
48
+ target: ts.ScriptTarget.Latest,
49
+ module: ts.ModuleKind.ESNext,
50
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
51
+ jsx: ts.JsxEmit.ReactJSX,
52
+ strict: true,
53
+ skipLibCheck: true,
54
+ noEmit: true,
55
+ allowImportingTsExtensions: true,
56
+ paths: {
57
+ '@barefootjs/client': [path.join(repo, 'packages/client/src/index.ts')],
58
+ '@barefootjs/client/async': [path.join(repo, 'packages/client/src/async.ts')],
59
+ '@barefootjs/client/reactive': [path.join(repo, 'packages/client/src/reactive.ts')],
60
+ },
61
+ }
62
+ const defaultHost = ts.createCompilerHost(compilerOptions)
63
+ const host: ts.CompilerHost = {
64
+ ...defaultHost,
65
+ getSourceFile(fileName, languageVersion) {
66
+ if (path.resolve(fileName) === componentPath) {
67
+ return ts.createSourceFile(fileName, source, languageVersion, true, ts.ScriptKind.TSX)
68
+ }
69
+ return defaultHost.getSourceFile(fileName, languageVersion)
70
+ },
71
+ fileExists(fileName) {
72
+ return path.resolve(fileName) === componentPath || defaultHost.fileExists(fileName)
73
+ },
74
+ readFile(fileName) {
75
+ return path.resolve(fileName) === componentPath ? source : defaultHost.readFile(fileName)
76
+ },
77
+ }
78
+ return ts.createProgram([componentPath], compilerOptions, host)
79
+ }
80
+
81
+ const MODE_A = `
82
+ 'use client'
83
+ import { createQuery, http } from '@barefootjs/client'
84
+ type Post = { id: number; title: string }
85
+ export function PostList(props: { posts: Post[]; userId: number }) {
86
+ const [posts, fetchPosts] = createQuery(() => http.get<Post[]>('/api/posts?user=' + props.userId), { initial: props.posts })
87
+ return (
88
+ <div>
89
+ <ul>{posts().map((post) => <li key={post.id}>{post.title}</li>)}</ul>
90
+ <button onClick={() => fetchPosts()}>reload</button>
91
+ </div>
92
+ )
93
+ }
94
+ `
95
+
96
+ describe('createQuery value and client JS (#3165)', () => {
97
+ test('emits the factory call with props read live, and no createSignal or prop sync for it', () => {
98
+ const { codes, initBody } = compile(MODE_A)
99
+ expect(codes).toEqual([])
100
+ expect(initBody).toContain(
101
+ "const [posts, fetchPosts] = createQuery(() => http.get('/api/posts?user=' + _p.userId), { initial: _p.posts })",
102
+ )
103
+ expect(initBody).not.toContain('createSignal(')
104
+ // `initial` is taken once: no controlled-prop sync effect writes the prop back.
105
+ expect(initBody).not.toContain('fetchPosts(__val)')
106
+ })
107
+
108
+ test('the CSR template reads `initial`, never the request function', () => {
109
+ const { templateBody } = compile(MODE_A)
110
+ expect(templateBody).toContain('(_p.posts).map(')
111
+ expect(templateBody).not.toContain('http.get')
112
+ })
113
+
114
+ test('Hono SSR seeds the value from `initial` and never emits the request function', () => {
115
+ const { codes, ssr } = compile(MODE_A, { hono: true })
116
+ expect(codes).toEqual([])
117
+ expect(ssr).toContain('const posts = () => props.posts')
118
+ expect(ssr).not.toContain('http.get')
119
+ // A prop read only by the request function still reaches the client.
120
+ expect(ssr).toContain("__hydrateProps['userId'] = props.userId")
121
+ })
122
+
123
+ test('an aliased import re-emits the call through the alias', () => {
124
+ // Aliases resolve through the TypeChecker, as for every reactive primitive.
125
+ const source = `
126
+ 'use client'
127
+ import { createQuery as query, http } from '@barefootjs/client'
128
+ export function C(props: { items: string[] }) {
129
+ const [items] = query(() => http.get<string[]>('/api/items'), { initial: props.items })
130
+ return <ul>{items().map((i) => <li key={i}>{i}</li>)}</ul>
131
+ }
132
+ `
133
+ const componentPath = path.join(__dirname, '_create-query-alias.tsx')
134
+ const { codes, initBody } = compile(source, { program: programFor(source, componentPath), fileName: componentPath })
135
+ expect(codes).toEqual([])
136
+ expect(initBody).toContain("const [items] = query(() => http.get('/api/items'), { initial: _p.items })")
137
+ })
138
+
139
+ test('the value-elided form keeps just the action', () => {
140
+ const { codes, initBody } = compile(`
141
+ 'use client'
142
+ import { createQuery, http } from '@barefootjs/client'
143
+ export function C() {
144
+ const [, fetchItems] = createQuery(() => http.get<string[]>('/api/items'))
145
+ return <button onClick={() => fetchItems()}>load</button>
146
+ }
147
+ `)
148
+ expect(codes).toEqual([])
149
+ expect(initBody).toContain("const [, fetchItems] = createQuery(() => http.get('/api/items'))")
150
+ })
151
+
152
+ test('`initial` absent seeds undefined; a shorthand `initial` is read structurally', () => {
153
+ const absent = compile(`
154
+ 'use client'
155
+ import { createQuery, http } from '@barefootjs/client'
156
+ export function C() {
157
+ const [items] = createQuery(() => http.get<string[]>('/api/items'))
158
+ return <p>{items() ? 'loaded' : 'loading'}</p>
159
+ }
160
+ `, { hono: true })
161
+ expect(absent.codes).toEqual([])
162
+ expect(absent.ssr).toContain('const items = () => undefined')
163
+
164
+ const shorthand = compile(`
165
+ 'use client'
166
+ import { createQuery, http } from '@barefootjs/client'
167
+ export function C({ initial }: { initial?: string[] }) {
168
+ const [items] = createQuery(() => http.get<string[]>('/api/items'), { initial })
169
+ return <p>{items() ? 'loaded' : 'loading'}</p>
170
+ }
171
+ `, { hono: true })
172
+ expect(shorthand.codes).toEqual([])
173
+ expect(shorthand.ssr).toContain('const items = () => initial')
174
+ })
175
+
176
+ test('options that cannot be read structurally seed from a member read of the options', () => {
177
+ const { codes, ssr } = compile(`
178
+ 'use client'
179
+ import { createQuery, http } from '@barefootjs/client'
180
+ export function C(props: { base: { initial?: string[] } }) {
181
+ const [items] = createQuery(() => http.get<string[]>('/api/items'), { ...props.base, ttl: 1000 })
182
+ return <p>{items() ? 'loaded' : 'loading'}</p>
183
+ }
184
+ `, { hono: true })
185
+ expect(codes).toEqual([])
186
+ expect(ssr).toContain('const items = () => ({ ...props.base, ttl: 1000 }).initial')
187
+ })
188
+
189
+ test('a forwarded action gets an SSR no-op', () => {
190
+ const { codes, ssr } = compile(`
191
+ 'use client'
192
+ import { createQuery, http } from '@barefootjs/client'
193
+ function Retry(props: { onRetry: () => void }) {
194
+ return <button onClick={() => props.onRetry()}>retry</button>
195
+ }
196
+ export function C(props: { items: string[] }) {
197
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
198
+ return <div><p>{items().length}</p><Retry onRetry={fetchItems} /></div>
199
+ }
200
+ `, { hono: true, fileName: 'C.tsx' })
201
+ expect(codes).toEqual([])
202
+ // #3166: the SSR no-op now carries working `isPending`/`error` methods
203
+ // too (spec/async.md §7.3's seed), not just a callable stub — a forwarded
204
+ // reference that reaches a template position through a child could call
205
+ // them (out of scope for THIS fixture, which only forwards the action as
206
+ // a value, but the stub must not assume the caller never will).
207
+ expect(ssr).toContain('const fetchItems: any = Object.assign(() => {}, { isPending: () => false, error: () => undefined })')
208
+ })
209
+ })
210
+
211
+ describe('createQuery arity (BF115 / BF116)', () => {
212
+ test('a two-argument call and a two-element destructure are accepted', () => {
213
+ expect(compile(MODE_A).codes).toEqual([])
214
+ })
215
+
216
+ test('a three-element destructure is BF115', () => {
217
+ const { codes } = compile(`
218
+ 'use client'
219
+ import { createQuery, http } from '@barefootjs/client'
220
+ export function C() {
221
+ const [a, b, c] = createQuery(() => http.get('/api/items'))
222
+ return <p>{a()}</p>
223
+ }
224
+ `)
225
+ expect(codes).toContain('BF115')
226
+ })
227
+
228
+ test('a third argument is BF116', () => {
229
+ const { codes } = compile(`
230
+ 'use client'
231
+ import { createQuery, http } from '@barefootjs/client'
232
+ export function C() {
233
+ const [a] = createQuery(() => http.get('/api/items'), {}, 'extra')
234
+ return <p>{a()}</p>
235
+ }
236
+ `)
237
+ expect(codes).toContain('BF116')
238
+ })
239
+ })
240
+
241
+ describe('createQuery action accessors seed as ordinary IR-visible values (#3166, #3158-B)', () => {
242
+ const SEEDED = `
243
+ 'use client'
244
+ import { createQuery, http } from '@barefootjs/client'
245
+ type Post = { id: number; title: string }
246
+ export function PostList(props: { posts: Post[] }) {
247
+ const [posts, fetchPosts] = createQuery(() => http.get<Post[]>('/api/posts'), { initial: props.posts })
248
+ return (
249
+ <div aria-busy={fetchPosts.isPending()}>
250
+ {fetchPosts.error() ? <p>Failed to load</p> : null}
251
+ <ul>{posts().map((post) => <li key={post.id}>{post.title}</li>)}</ul>
252
+ </div>
253
+ )
254
+ }
255
+ `
256
+
257
+ test('compiles clean on Hono, whose SSR stub carries working isPending/error methods', () => {
258
+ const { codes, ssr } = compile(SEEDED, { hono: true })
259
+ expect(codes).toEqual([])
260
+ // Hono's execution model runs the real JS text (unlike a DSL adapter's
261
+ // `parsedCondition`-based seed substitution below) — the read stays
262
+ // `fetchPosts.isPending()` verbatim, and the SSR no-op stub is what
263
+ // actually answers it (`false` / `undefined`, spec/async.md §7.3).
264
+ expect(ssr).toContain('fetchPosts.isPending()')
265
+ expect(ssr).toContain('fetchPosts.error()')
266
+ expect(ssr).toContain('const fetchPosts: any = Object.assign(() => {}, { isPending: () => false, error: () => undefined })')
267
+ })
268
+
269
+ test('the CSR path keeps the real accessor call — reactivity survives hydration', () => {
270
+ // A real `ts.Program` (as the real pipeline always supplies —
271
+ // `@barefootjs/vite`'s plugin, `packages/vite/src/plugin.ts`, calls
272
+ // `compileJSX` with `program: corpusProgram.programFor(...)` on every
273
+ // component, never without one): `isPending()` carries a `Reactive<T>`
274
+ // brand the TypeChecker resolves, which is what marks the attribute
275
+ // reactive enough to get a live DOM patch — without a checker, neither
276
+ // this accessor's brand nor a bare signal/props regex fallback fires, so
277
+ // this fixture's `aria-busy` would (mis-)compile as a static, one-shot
278
+ // value under the no-checker `compile()` default. See
279
+ // `shouldAutoDeferReactiveBrand`'s own checker-required gate for the
280
+ // same reason.
281
+ const componentPath = path.join(__dirname, '_create-query-seeded.tsx')
282
+ const { codes, initBody } = compile(SEEDED, { program: programFor(SEEDED, componentPath), fileName: componentPath })
283
+ expect(codes).toEqual([])
284
+ // The client must still call the REAL query accessor to patch the DOM
285
+ // when a request actually goes pending/fails — never a baked literal.
286
+ expect(initBody).toContain('fetchPosts.isPending()')
287
+ expect(initBody).toContain('fetchPosts.error()')
288
+ })
289
+
290
+ test('a direct read is structurally recognised via action-accessor.ts, not a name heuristic', () => {
291
+ // Same accessor name, same position role (`aria-busy`), same component:
292
+ // only the binding a real `createQuery` produced is seeded. `upload` is a
293
+ // different local whose value also has an `isPending()` method — a
294
+ // name-based match would seed it too (`{{false}}`); the structural one
295
+ // leaves it to the adapter's ordinary lowering.
296
+ const result = compileJSX(`
297
+ 'use client'
298
+ import { createQuery, http } from '@barefootjs/client'
299
+ type Tracker = { isPending: () => boolean }
300
+ export function C(props: { tracker: Tracker }) {
301
+ const [posts, fetchPosts] = createQuery(() => http.get<string[]>('/x'), { initial: [] as string[] })
302
+ const upload = props.tracker
303
+ return (
304
+ <div aria-busy={fetchPosts.isPending()}>
305
+ <span aria-busy={upload.isPending()}>{posts().length}</span>
306
+ </div>
307
+ )
308
+ }
309
+ `, 'C.tsx', { adapter: new GoTemplateAdapter() })
310
+ expect(result.errors.map((e) => e.code)).toEqual([])
311
+ const template = result.files.find((f) => f.type === 'markedTemplate')?.content ?? ''
312
+ expect(template).toContain('<div aria-busy="{{false}}"')
313
+ expect(template).toContain('<span aria-busy="{{.Tracker.IsPending}}"')
314
+ expect(template.match(/\{\{false\}\}/g)).toHaveLength(1)
315
+ expect(template).not.toContain('FetchPosts')
316
+ })
317
+ })
318
+
319
+ /**
320
+ * The seed is `false` (`isPending()`) / `undefined` (`error()`), rendered by
321
+ * DSL adapters as the literal `false`. It is admitted only where that renders
322
+ * exactly like Hono's real stub value (`action-accessor.ts`'s
323
+ * `seedableActionAccessorRead`); everywhere else the read still refuses with
324
+ * BF117, exactly as before #3166.
325
+ */
326
+ describe('createQuery action accessors seed only where the seed renders like Hono (#3166)', () => {
327
+ const withBody = (body: string) => `
328
+ 'use client'
329
+ import { createQuery, http } from '@barefootjs/client'
330
+ type Post = { id: number; title: string }
331
+ export function PostList(props: { posts: Post[] }) {
332
+ const [posts, fetchPosts] = createQuery(() => http.get<Post[]>('/api/posts'), { initial: props.posts })
333
+ return (
334
+ <div>
335
+ ${body}
336
+ <ul>{posts().map((post) => <li key={post.id}>{post.title}</li>)}</ul>
337
+ </div>
338
+ )
339
+ }
340
+ `
341
+
342
+ // Hono renders `{undefined}` / `{false}` as nothing, omits `title={undefined}`,
343
+ // and a DSL adapter renders the `false` literal as `false` (Mojolicious /
344
+ // Xslate: `0`) — so none of these has a sound seed.
345
+ const REFUSED: Array<[string, string]> = [
346
+ ['error() as a text child', '<span>{fetchPosts.error()}</span>'],
347
+ ['isPending() as a text child', '<b>{fetchPosts.isPending()}</b>'],
348
+ ['error() in a plain attribute', '<p title={fetchPosts.error()}>x</p>'],
349
+ ['error() in an aria-* attribute', '<p aria-label={fetchPosts.error()}>x</p>'],
350
+ ['error() in an ARIA boolean-state attribute', '<p aria-busy={fetchPosts.error()}>x</p>'],
351
+ ['isPending() in a plain attribute', '<p title={fetchPosts.isPending()}>x</p>'],
352
+ ['isPending() in a non-boolean aria-* attribute', '<p aria-label={fetchPosts.isPending()}>x</p>'],
353
+ ['isPending() in a data-* attribute', '<p data-pending={fetchPosts.isPending()}>x</p>'],
354
+ // A truthiness test, but the condition is raw template-part text every
355
+ // adapter lowers itself — nothing to substitute, so it is not lifted.
356
+ ['isPending() as a structured template-attribute ternary', "<p class={fetchPosts.isPending() ? 'busy' : 'idle'}>x</p>"],
357
+ ]
358
+
359
+ for (const [label, body] of REFUSED) {
360
+ test(`BF117 still refuses ${label}`, () => {
361
+ for (const hono of [false, true]) {
362
+ const { errors } = compile(withBody(body), { hono })
363
+ const bf117 = errors.filter((e) => e.code === 'BF117')
364
+ expect(bf117).toHaveLength(1)
365
+ expect(bf117[0].message).toContain("reads an async action's accessor")
366
+ }
367
+ })
368
+ }
369
+
370
+ const LIFTED: Array<[string, string, string]> = [
371
+ ['isPending() in aria-busy', '<p aria-busy={fetchPosts.isPending()}>x</p>', '<p aria-busy="{{false}}"'],
372
+ ['isPending() in another ARIA boolean-state attribute', '<p aria-hidden={fetchPosts.isPending()}>x</p>', '<p aria-hidden="{{false}}"'],
373
+ ['error() as a conditional test', '{fetchPosts.error() ? <p>failed</p> : null}', '{{if false}}<p'],
374
+ ['isPending() as a conditional test', '{fetchPosts.isPending() ? <p>loading</p> : null}', '{{if false}}<p'],
375
+ ]
376
+
377
+ for (const [label, body, seeded] of LIFTED) {
378
+ test(`lifts and seeds ${label}`, () => {
379
+ expect(compile(withBody(body)).codes).toEqual([])
380
+ expect(compile(withBody(body), { hono: true }).codes).toEqual([])
381
+ const result = compileJSX(withBody(body), 'PostList.tsx', { adapter: new GoTemplateAdapter() })
382
+ expect(result.errors).toEqual([])
383
+ const template = result.files.find((f) => f.type === 'markedTemplate')?.content ?? ''
384
+ expect(template).toContain(seeded)
385
+ expect(template).not.toContain('FetchPosts')
386
+ })
387
+ }
388
+
389
+ test('lifts and seeds an early-return if-statement condition', () => {
390
+ const source = `
391
+ 'use client'
392
+ import { createQuery, http } from '@barefootjs/client'
393
+ export function C() {
394
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/x'), { initial: [] as string[] })
395
+ if (fetchItems.error()) return <p>failed</p>
396
+ return <ul>{items().map((item) => <li key={item}>{item}</li>)}</ul>
397
+ }
398
+ `
399
+ expect(compile(source).codes).toEqual([])
400
+ const result = compileJSX(source, 'C.tsx', { adapter: new GoTemplateAdapter() })
401
+ expect(result.errors).toEqual([])
402
+ const template = result.files.find((f) => f.type === 'markedTemplate')?.content ?? ''
403
+ expect(template).toContain('{{if false}}<p')
404
+ expect(template).not.toContain('FetchItems')
405
+ // The CSR module-scope fallback template gets the JS seed text instead:
406
+ // `undefined` for `error()`, never the out-of-scope accessor call.
407
+ const { templateBody } = compile(source)
408
+ expect(templateBody).toContain('undefined ?')
409
+ expect(templateBody).not.toContain('fetchItems.error()')
410
+ })
411
+
412
+ test('a /* @client */ position is neither refused nor seeded', () => {
413
+ const result = compileJSX(withBody('{/* @client */ fetchPosts.error() ? <p>failed</p> : null}'), 'PostList.tsx', {
414
+ adapter: new GoTemplateAdapter(),
415
+ })
416
+ expect(result.errors).toEqual([])
417
+ const template = result.files.find((f) => f.type === 'markedTemplate')?.content ?? ''
418
+ expect(template).not.toContain('{{if false}}')
419
+ })
420
+ })
421
+
422
+ const ACTION_READS = `
423
+ 'use client'
424
+ import { createMemo, createQuery, http } from '@barefootjs/client'
425
+ type Post = { id: number; title: string }
426
+ export function PostList(props: { posts: Post[] }) {
427
+ const [posts, fetchPosts] = createQuery(() => http.get<Post[]>('/api/posts'), { initial: props.posts })
428
+ const busy = createMemo(() => fetchPosts.isPending())
429
+ return (
430
+ <div aria-busy={fetchPosts.isPending()}>
431
+ {fetchPosts.error() ? <p>failed</p> : null}
432
+ <span>{busy() ? 'loading' : 'ready'}</span>
433
+ <ul>{posts().map((post) => <li key={post.id}>{post.title}</li>)}</ul>
434
+ </div>
435
+ )
436
+ }
437
+ `
438
+
439
+ describe('BF117: query action reads in template positions', () => {
440
+ test('no longer refuses a direct accessor read in an attribute or a condition (#3166); still refuses a memo that reads the action', () => {
441
+ const { errors } = compile(ACTION_READS)
442
+ const bf117 = errors.filter((e) => e.code === 'BF117')
443
+ // Lines 9 (`aria-busy={fetchPosts.isPending()}`) and 10
444
+ // (`{fetchPosts.error() ? … : null}`) are direct, whole-expression reads
445
+ // — seeded (`false`/`undefined`, spec/async.md §7.3) rather than refused.
446
+ // Line 11 (`{busy() ? … : …}`) reads the action only THROUGH a memo, which
447
+ // this pass doesn't seed structurally (`action-accessor.ts`'s docstring),
448
+ // so it still refuses.
449
+ expect(bf117.map((e) => e.loc.start.line)).toEqual([11])
450
+ expect(bf117[0].message).toContain("memo 'busy' reads the async action 'fetchPosts'")
451
+ expect(bf117[0].suggestion?.escape).toEqual([{ kind: 'client-directive' }])
452
+ })
453
+
454
+ test('fires on Hono too, only for the memo-transitive read', () => {
455
+ expect(compile(ACTION_READS, { hono: true }).codes.filter((c) => c === 'BF117')).toHaveLength(1)
456
+ })
457
+
458
+ test('refuses calling the action in a template position', () => {
459
+ const { codes } = compile(`
460
+ 'use client'
461
+ import { createQuery, http } from '@barefootjs/client'
462
+ export function C() {
463
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'))
464
+ return <p>{String(fetchItems())}</p>
465
+ }
466
+ `)
467
+ expect(codes).toContain('BF117')
468
+ })
469
+
470
+ test('refuses reads through a local constant or a called local function', () => {
471
+ const viaConstant = compile(`
472
+ 'use client'
473
+ import { createQuery, http } from '@barefootjs/client'
474
+ export function C(props: { items: string[] }) {
475
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
476
+ const busy = fetchItems.isPending()
477
+ return <div aria-busy={busy}>{items().length}</div>
478
+ }
479
+ `, { hono: true })
480
+ expect(viaConstant.codes).toContain('BF117')
481
+ expect(viaConstant.errors.find((e) => e.code === 'BF117')!.message).toContain("constant 'busy' reads the async action 'fetchItems'")
482
+
483
+ const viaFunction = compile(`
484
+ 'use client'
485
+ import { createQuery, http } from '@barefootjs/client'
486
+ export function C(props: { items: string[] }) {
487
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
488
+ const status = () => (fetchItems.error() ? 'failed' : 'ok')
489
+ return <p>{status()} {items().length}</p>
490
+ }
491
+ `, { hono: true })
492
+ expect(viaFunction.codes).toContain('BF117')
493
+
494
+ const viaDeclaration = compile(`
495
+ 'use client'
496
+ import { createQuery, http } from '@barefootjs/client'
497
+ export function C(props: { items: string[] }) {
498
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
499
+ function status() {
500
+ return fetchItems.error() ? 'failed' : 'ok'
501
+ }
502
+ return <p>{status()} {items().length}</p>
503
+ }
504
+ `, { hono: true })
505
+ expect(viaDeclaration.codes).toContain('BF117')
506
+ })
507
+
508
+ test('follows reads transitively through memos, constants and functions', () => {
509
+ const { errors } = compile(`
510
+ 'use client'
511
+ import { createMemo, createQuery, http } from '@barefootjs/client'
512
+ export function C(props: { items: string[] }) {
513
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
514
+ const failed = () => fetchItems.error() !== undefined
515
+ const busy = createMemo(() => fetchItems.isPending() || failed())
516
+ const label = busy() ? 'loading' : 'ready'
517
+ return <p data-state={label}>{items().length}</p>
518
+ }
519
+ `)
520
+ const bf117 = errors.filter((e) => e.code === 'BF117')
521
+ expect(bf117).toHaveLength(1)
522
+ expect(bf117[0].message).toContain("constant 'label' reads the async action 'fetchItems'")
523
+ })
524
+
525
+ test('allows passing a function that reads the action as a value', () => {
526
+ const { codes } = compile(`
527
+ 'use client'
528
+ import { createQuery, http } from '@barefootjs/client'
529
+ function Retry(props: { run: () => void }) {
530
+ return <button onClick={() => props.run()}>retry</button>
531
+ }
532
+ export function C(props: { items: string[] }) {
533
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
534
+ const reload = () => fetchItems()
535
+ return (
536
+ <div>
537
+ <button onClick={reload}>{items().length}</button>
538
+ <Retry run={reload} />
539
+ </div>
540
+ )
541
+ }
542
+ `, { fileName: 'C.tsx' })
543
+ expect(codes).not.toContain('BF117')
544
+ })
545
+
546
+ test('treats a constant that aliases the action or a reader like its target', () => {
547
+ const accepted = compile(`
548
+ 'use client'
549
+ import { createQuery, http } from '@barefootjs/client'
550
+ function Retry(props: { run: () => void }) {
551
+ return <button onClick={() => props.run()}>retry</button>
552
+ }
553
+ export function C(props: { items: string[] }) {
554
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
555
+ const run = fetchItems
556
+ const reload = () => fetchItems()
557
+ const again = reload
558
+ return (
559
+ <div>
560
+ <Retry run={run} />
561
+ <Retry run={again} />
562
+ <p>{items().length}</p>
563
+ </div>
564
+ )
565
+ }
566
+ `, { fileName: 'C.tsx' })
567
+ expect(accepted.codes).not.toContain('BF117')
568
+
569
+ const refused = compile(`
570
+ 'use client'
571
+ import { createQuery, http } from '@barefootjs/client'
572
+ export function C(props: { items: string[] }) {
573
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
574
+ const run = fetchItems
575
+ const reload = () => run.error()
576
+ const again = reload
577
+ return (
578
+ <div aria-busy={run.isPending()}>
579
+ <p>{again() ? 'failed' : items().length}</p>
580
+ </div>
581
+ )
582
+ }
583
+ `, { fileName: 'C.tsx' })
584
+ expect(refused.codes.filter(c => c === 'BF117')).toHaveLength(2)
585
+ })
586
+
587
+ test('refuses an inline arrow reading the action outside an on* prop', () => {
588
+ const { codes } = compile(`
589
+ 'use client'
590
+ import { createQuery, http } from '@barefootjs/client'
591
+ function Retry(props: { run: () => void }) {
592
+ return <button onClick={() => props.run()}>retry</button>
593
+ }
594
+ export function C(props: { items: string[] }) {
595
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
596
+ return <div><Retry run={() => fetchItems()} />{items().length}</div>
597
+ }
598
+ `, { fileName: 'C.tsx' })
599
+ expect(codes).toContain('BF117')
600
+ })
601
+
602
+ test('allows /* @client */ reads, event handlers, and forwarding the action as a value', () => {
603
+ const { codes } = compile(`
604
+ 'use client'
605
+ import { createQuery, http } from '@barefootjs/client'
606
+ function Retry(props: { onRetry: () => void; run: () => void }) {
607
+ return <button onClick={() => props.onRetry()}>retry</button>
608
+ }
609
+ export function C(props: { items: string[] }) {
610
+ const [items, fetchItems] = createQuery(() => http.get<string[]>('/api/items'), { initial: props.items })
611
+ return (
612
+ <div aria-busy={/* @client */ fetchItems.isPending()}>
613
+ <button onClick={() => fetchItems()}>{items().length}</button>
614
+ <Retry onRetry={() => fetchItems()} run={fetchItems} />
615
+ </div>
616
+ )
617
+ }
618
+ `, { fileName: 'C.tsx' })
619
+ expect(codes).not.toContain('BF117')
620
+ })
621
+
622
+ test('with a TypeChecker, accessor reads are refused rather than auto-deferred to the client', () => {
623
+ const componentPath = path.join(__dirname, '_create-query-component.tsx')
624
+ const program = programFor(ACTION_READS, componentPath)
625
+ // Sanity: the checker sees the accessor as a reactive brand, which is
626
+ // what would auto-defer it without the async-action exclusion.
627
+ const checker = program.getTypeChecker()
628
+ const sourceFile = program.getSourceFile(componentPath)!
629
+ let accessorType = ''
630
+ const visit = (node: ts.Node): void => {
631
+ if (ts.isPropertyAccessExpression(node) && node.getText(sourceFile) === 'fetchPosts.isPending' && !accessorType) {
632
+ accessorType = checker.typeToString(checker.getTypeAtLocation(node))
633
+ }
634
+ ts.forEachChild(node, visit)
635
+ }
636
+ visit(sourceFile)
637
+ expect(accessorType).toStartWith('Reactive<')
638
+
639
+ const { codes } = compile(ACTION_READS, { program, fileName: componentPath })
640
+ // Only the memo-transitive read (line 11) still refuses — see the
641
+ // top-level describe's first test for why lines 9/10 no longer do.
642
+ expect(codes.filter((c) => c === 'BF117')).toHaveLength(1)
643
+ })
644
+ })