prunelle 0.7.7 → 0.9.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 (189) hide show
  1. package/llms.txt +63 -46
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +15 -7
  14. package/src/build/index.ts +20 -10
  15. package/src/build/island-promote.ts +1 -1
  16. package/src/build/islands.ts +4 -1
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +19 -1
  19. package/src/build/plugin-host.ts +2 -0
  20. package/src/build/prerender.ts +2 -2
  21. package/src/build/reach.ts +14 -1
  22. package/src/build/report.ts +1 -1
  23. package/src/build/route-types.ts +16 -0
  24. package/src/build/routes.ts +24 -15
  25. package/src/build/seed-ids.ts +65 -0
  26. package/src/build/seed-writes.ts +111 -0
  27. package/src/build/static-headers.ts +2 -2
  28. package/src/build/static.ts +1 -1
  29. package/src/cli/check-cache.ts +51 -0
  30. package/src/cli/check-consent.ts +95 -0
  31. package/src/cli/check-forms.ts +2 -2
  32. package/src/cli/check-links-patterns.ts +101 -0
  33. package/src/cli/check-links.ts +16 -100
  34. package/src/cli/check-regions.ts +185 -0
  35. package/src/cli/check-security.ts +57 -6
  36. package/src/cli/check.ts +40 -17
  37. package/src/cli/commands.ts +134 -14
  38. package/src/cli/docs.ts +21 -2
  39. package/src/cli/index.ts +1 -1
  40. package/src/cli/inspect.ts +2 -0
  41. package/src/cli/mcp-tools.ts +2 -2
  42. package/src/cli/new.ts +9 -5
  43. package/src/cli/upgrade-names.ts +14 -2
  44. package/src/cli/upgrade.ts +3 -0
  45. package/src/compiler/analyze.ts +18 -4
  46. package/src/compiler/cacheability.ts +24 -2
  47. package/src/compiler/compliance-contrast.ts +284 -0
  48. package/src/compiler/compliance-empty.ts +24 -0
  49. package/src/compiler/compliance-rgaa-content.ts +95 -0
  50. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  51. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  52. package/src/compiler/compliance-rgaa.ts +19 -0
  53. package/src/compiler/compliance-third-party.ts +59 -0
  54. package/src/compiler/compliance-urls.ts +52 -0
  55. package/src/compiler/compliance.ts +72 -42
  56. package/src/compiler/cookie-inventory.ts +119 -0
  57. package/src/compiler/dom-attrs.ts +4 -1
  58. package/src/compiler/emit.ts +1 -1
  59. package/src/compiler/foreign-imports.ts +5 -3
  60. package/src/compiler/mistakes.ts +18 -9
  61. package/src/compiler/props-pattern.ts +211 -0
  62. package/src/compiler/props.ts +177 -346
  63. package/src/compiler/shared.ts +9 -16
  64. package/src/compiler/ssr-emit.ts +510 -0
  65. package/src/compiler/ssr-helpers.ts +170 -121
  66. package/src/compiler/ssr.ts +25 -440
  67. package/src/context.ts +14 -1
  68. package/src/dev/child.ts +1 -1
  69. package/src/dev/hot-islands.ts +71 -0
  70. package/src/dev/index.ts +31 -18
  71. package/src/dev/protocol.ts +1 -1
  72. package/src/dev/queue.ts +3 -2
  73. package/src/dev/reload.ts +1 -1
  74. package/src/dev/supervisor.ts +3 -1
  75. package/src/dev/watchers.ts +6 -2
  76. package/src/dom/action.ts +97 -14
  77. package/src/dom/attrs.ts +8 -0
  78. package/src/dom/extras.ts +2 -1
  79. package/src/dom/field-marks.ts +24 -0
  80. package/src/dom/hot.ts +9 -0
  81. package/src/dom/index.ts +25 -5
  82. package/src/dom/island-hot.ts +29 -0
  83. package/src/dom/island.ts +13 -2
  84. package/src/dom/prefetch.ts +132 -0
  85. package/src/dom/regions.ts +498 -0
  86. package/src/dom/swap.ts +245 -0
  87. package/src/dom/trusted.ts +22 -0
  88. package/src/dom/upload.ts +44 -0
  89. package/src/eco/declaration.ts +39 -40
  90. package/src/eco/index.ts +5 -5
  91. package/src/href.ts +31 -0
  92. package/src/index.ts +9 -3
  93. package/src/plugins/config.ts +1 -1
  94. package/src/plugins/context.ts +7 -1
  95. package/src/plugins/daily.ts +27 -0
  96. package/src/plugins/index.ts +3 -3
  97. package/src/plugins/order.ts +1 -1
  98. package/src/plugins/public.ts +8 -5
  99. package/src/plugins/services.ts +88 -14
  100. package/src/plugins/types.ts +121 -10
  101. package/src/reactivity/hmr.ts +90 -0
  102. package/src/reactivity/index.ts +38 -18
  103. package/src/reactivity/resource.ts +115 -0
  104. package/src/reactivity/seed.ts +39 -0
  105. package/src/reactivity/server-seed.ts +194 -0
  106. package/src/reactivity/store.ts +55 -1
  107. package/src/rgpd/draft.ts +171 -0
  108. package/src/rgpd/forms.ts +85 -0
  109. package/src/rgpd/index.ts +57 -0
  110. package/src/server/action-flash.ts +1 -0
  111. package/src/server/action-registry.ts +6 -8
  112. package/src/server/action.ts +51 -19
  113. package/src/server/app-secret.ts +22 -17
  114. package/src/server/cache-invalidation.ts +96 -0
  115. package/src/server/compress.ts +3 -1
  116. package/src/server/consent.ts +16 -2
  117. package/src/server/cookie-inventory.ts +78 -0
  118. package/src/server/cookies.ts +50 -0
  119. package/src/server/csp-report.ts +86 -0
  120. package/src/server/discard.ts +13 -0
  121. package/src/server/document.ts +7 -4
  122. package/src/server/env.ts +1 -1
  123. package/src/server/errors.ts +9 -2
  124. package/src/server/field-errors.ts +91 -0
  125. package/src/server/form-schema.ts +16 -11
  126. package/src/server/health.ts +35 -14
  127. package/src/server/http.ts +25 -10
  128. package/src/server/index.ts +102 -299
  129. package/src/server/loader.ts +1 -0
  130. package/src/server/page.ts +11 -24
  131. package/src/server/plugin-host.ts +26 -8
  132. package/src/server/public.ts +14 -3
  133. package/src/server/rate-limit.ts +39 -10
  134. package/src/server/region.ts +3 -0
  135. package/src/server/request-handler.ts +370 -0
  136. package/src/server/request-log.ts +94 -0
  137. package/src/server/route-cache.ts +41 -6
  138. package/src/server/route-input.ts +54 -0
  139. package/src/server/route-table.ts +35 -19
  140. package/src/server/routing.ts +12 -11
  141. package/src/server/sanitize-html.ts +1 -1
  142. package/src/server/security.ts +81 -20
  143. package/src/server/serve-handlers.ts +9 -5
  144. package/src/server/shared-store.ts +314 -0
  145. package/src/server/start.ts +12 -5
  146. package/src/server/static-dir.ts +14 -10
  147. package/src/server/stream.ts +2 -1
  148. package/src/server/surface.ts +39 -0
  149. package/src/server/webhook.ts +48 -0
  150. package/src/server/workers.ts +168 -0
  151. package/src/ssr/consent-banner.ts +20 -16
  152. package/src/ssr/consent-texts.ts +40 -0
  153. package/src/ssr/context.ts +26 -3
  154. package/src/ssr/cookie-table.ts +75 -0
  155. package/src/ssr/index.ts +23 -13
  156. package/src/ssr/navigation.ts +161 -14
  157. package/src/test/browser.ts +50 -22
  158. package/src/test/build-reuse.ts +70 -0
  159. package/src/test/index.ts +45 -6
  160. package/src/test/mount.ts +53 -0
  161. package/src/test/outside.ts +94 -0
  162. package/templates/_shared/AGENTS.md +1 -1
  163. package/templates/_shared/Dockerfile +22 -0
  164. package/templates/_shared/dockerignore +9 -0
  165. package/templates/_shared/gitignore +2 -0
  166. package/templates/app/.env.example +3 -1
  167. package/templates/app/compose.yaml +32 -0
  168. package/templates/app/db/migrations/001_notes.sql +7 -0
  169. package/templates/app/db/schema.ts +11 -0
  170. package/templates/app/package.json +1 -0
  171. package/templates/app/prunelle.config.ts +6 -0
  172. package/templates/app/src/actions/notes.ts +26 -0
  173. package/templates/app/src/auth.ts +4 -2
  174. package/templates/app/src/db.ts +5 -0
  175. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  176. package/templates/app/src/routes/privacy.tsx +6 -2
  177. package/templates/app/tests/app.test.ts +14 -3
  178. package/templates/plugin/AGENTS.md +11 -0
  179. package/templates/plugin/CLAUDE.md +1 -0
  180. package/templates/plugin/README.md +27 -0
  181. package/templates/plugin/gitignore +2 -0
  182. package/templates/plugin/llms.txt +19 -0
  183. package/templates/plugin/package.json +33 -0
  184. package/templates/plugin/src/index.ts +40 -0
  185. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  186. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  187. package/templates/plugin/tests/plugin.test.ts +42 -0
  188. package/templates/plugin/tsconfig.json +19 -0
  189. package/ts-plugin.cjs +3674 -2196
@@ -1,29 +1,12 @@
1
1
  // Compiles a component's destructured props: reads stay reactive through `__p`, and the function is rewritten around it.
2
2
 
3
3
  import type { ArrowFunctionExpression, Function as OxcFunction, Node, ObjectPattern, ParamPattern } from 'oxc-parser'
4
- import { walk } from './ast'
4
+ import type { PatternContext } from './props-pattern'
5
5
  import { SourceEditor } from './patch'
6
- import { collectMutatedNames, isSafeLazyJsxRef, referencesAny } from './scope'
6
+ import { patternReads } from './props-pattern'
7
+ import { collectMutatedNames, isSafeLazyJsxRef } from './scope'
7
8
  import { collectPatternNames, containsJsx, isJsxNode, unwrapParens, unwrapTsExpr } from './shared'
8
9
 
9
- function isReactiveDefault(node: Node, running: ReadonlyMap<string, string>): boolean {
10
- if (running.size > 0 && referencesAny(node, new Set(running.keys())))
11
- return true
12
- let readsValue = false
13
- walk(node, (child) => {
14
- if (readsValue)
15
- return false
16
- if (child.type === 'ArrowFunctionExpression' || child.type === 'FunctionExpression' || child.type === 'FunctionDeclaration')
17
- return false
18
- if (child.type === 'MemberExpression' && !child.computed && child.property.type === 'Identifier' && child.property.name === 'value') {
19
- readsValue = true
20
- return false
21
- }
22
- return undefined
23
- })
24
- return readsValue
25
- }
26
-
27
10
  function patchParamDefaults(
28
11
  param: Node | null | undefined,
29
12
  rewrites: ReadonlyMap<string, string>,
@@ -135,13 +118,8 @@ export interface DestructuredParam {
135
118
  typeAnn: string
136
119
  }
137
120
 
138
- export interface PropCompilerContext {
139
- code: string
121
+ export interface PropCompilerContext extends PatternContext {
140
122
  editor: SourceEditor
141
- jsxNodes: WeakSet<Node>
142
- use: (name: string) => string
143
- freshVar: (prefix?: string) => string
144
- compileExpression: (node: Node, rewrites: ReadonlyMap<string, string>) => string
145
123
  }
146
124
 
147
125
  export interface PropCompiler {
@@ -160,352 +138,205 @@ export interface PropCompiler {
160
138
  processFunction: (fn: ArrowFunctionExpression | OxcFunction) => void
161
139
  }
162
140
 
163
- export function createPropCompiler(ctx: PropCompilerContext): PropCompiler {
164
- const { code, editor, jsxNodes, use, freshVar, compileExpression } = ctx
141
+ function extractDestructuredParam(code: string, firstParam: ParamPattern | undefined): DestructuredParam | undefined {
142
+ if (firstParam === undefined)
143
+ return undefined
144
+ if (firstParam.type === 'ObjectPattern') {
145
+ const typeAnn = firstParam.typeAnnotation ? code.slice(firstParam.typeAnnotation.start, firstParam.typeAnnotation.end) : ''
146
+ return { pattern: firstParam, defaultExpr: undefined, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
147
+ }
148
+ if (firstParam.type === 'AssignmentPattern' && firstParam.left.type === 'ObjectPattern') {
149
+ const pat = firstParam.left
150
+ const typeAnn = pat.typeAnnotation ? code.slice(pat.typeAnnotation.start, pat.typeAnnotation.end) : ''
151
+ return { pattern: pat, defaultExpr: firstParam.right, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
152
+ }
153
+ return undefined
154
+ }
165
155
 
166
- // How each name a destructuring pattern binds is read from `source` on every access, so reads stay reactive.
167
- // With `hoisted`, a default (at any nesting depth) and a nested pattern's getter become statements for the start of the body (evaluated once per call/row) instead of running on every read.
168
- function patternReads(pattern: Node, source: string, outerRewrites: ReadonlyMap<string, string>, hoisted?: string[]): Map<string, string> {
169
- const reads = new Map<string, string>()
170
- const running = new Map(outerRewrites)
171
- const hoist = (init: string): string => {
172
- const name = freshVar('__d')
173
- hoisted!.push(`const ${name} = ${init};`)
174
- return name
156
+ function computePropRewrites(
157
+ ctx: PropCompilerContext,
158
+ destructured: { pattern: ObjectPattern, defaultExpr: Node | undefined },
159
+ pVar: string,
160
+ outerRewrites: ReadonlyMap<string, string>,
161
+ body: Node | null,
162
+ ): { rewrites: Map<string, string>, prelude: string } {
163
+ const rewrites = new Map(outerRewrites)
164
+ const hoisted: string[] = []
165
+ const propReads = patternReads(ctx, destructured.pattern, pVar, outerRewrites, hoisted)
166
+ const mutated = collectMutatedNames(body, new Set(propReads.keys()))
167
+ for (const [name, read] of propReads) {
168
+ if (mutated.has(name)) {
169
+ // A mutated destructured prop becomes a local `let` binding initialized once, avoiding invalid assignment targets like `(a === undefined ? b : a) = c`.
170
+ hoisted.push(`let ${name} = ${read};`)
171
+ rewrites.delete(name)
175
172
  }
176
-
177
- function bindPattern(pat: Node, src: string): void {
178
- if (pat.type === 'Identifier') {
179
- reads.set(pat.name, src)
180
- running.set(pat.name, src)
181
- return
182
- }
183
- if (pat.type === 'AssignmentPattern') {
184
- const defExpr = compileExpression(pat.right, running)
185
- const simpleDef = pat.right.type === 'Literal' || pat.right.type === 'Identifier'
186
- const reactiveDef = !simpleDef && !containsJsx(pat.right, jsxNodes) && isReactiveDefault(pat.right, running)
187
- let fallback = simpleDef ? defExpr : `(${defExpr})`
188
- if (!simpleDef && !reactiveDef && hoisted !== undefined)
189
- fallback = `${hoist(`${use('propDefault')}(() => (${defExpr}), ${src} === undefined)`)}()`
190
- let nextSrc: string
191
- if (pat.left.type !== 'Identifier' && hoisted !== undefined) {
192
- const v = freshVar('__v')
193
- nextSrc = `${hoist(`() => { const ${v} = ${src}; return ${v} === undefined ? ${fallback} : ${v}; }`)}()`
194
- }
195
- else {
196
- nextSrc = `(${src} === undefined ? ${fallback} : ${src})`
197
- }
198
- bindPattern(pat.left, nextSrc)
199
- return
200
- }
201
- if (pat.type === 'ObjectPattern') {
202
- const excludedKeys: string[] = []
203
- let canOmit = hoisted !== undefined
204
- for (const prop of pat.properties) {
205
- if (prop.type === 'RestElement') {
206
- if (canOmit) {
207
- const restRead = `${use('omit')}(${src}, [${excludedKeys.join(', ')}])`
208
- bindPattern(prop.argument, restRead)
209
- }
210
- continue
211
- }
212
- let propSrc: string | undefined
213
- if (!prop.computed && prop.key.type === 'Identifier') {
214
- excludedKeys.push(JSON.stringify(prop.key.name))
215
- propSrc = `${src}.${prop.key.name}`
216
- }
217
- else if (!prop.computed && prop.key.type === 'Literal' && (typeof prop.key.value === 'string' || typeof prop.key.value === 'number')) {
218
- excludedKeys.push(JSON.stringify(String(prop.key.value)))
219
- propSrc = `${src}[${JSON.stringify(prop.key.value)}]`
220
- }
221
- else if (prop.computed && hoisted !== undefined) {
222
- const keyVar = hoist(compileExpression(prop.key, running))
223
- excludedKeys.push(`typeof ${keyVar} === 'symbol' ? ${keyVar} : String(${keyVar})`)
224
- propSrc = `${src}[${keyVar}]`
225
- }
226
- else {
227
- canOmit = false
228
- }
229
- if (propSrc !== undefined)
230
- bindPattern(prop.value, propSrc)
231
- }
232
- return
233
- }
234
- if (pat.type === 'ArrayPattern') {
235
- for (let i = 0; i < pat.elements.length; i++) {
236
- const el = pat.elements[i]
237
- if (el == null)
238
- continue
239
- if (el.type === 'RestElement')
240
- bindPattern(el.argument, `Array.from(${src}).slice(${i})`)
241
- else
242
- bindPattern(el, `${src}[${i}]`)
243
- }
244
- }
173
+ else {
174
+ rewrites.set(name, read)
245
175
  }
176
+ }
177
+ return { rewrites, prelude: hoisted.join(' ') }
178
+ }
246
179
 
247
- bindPattern(pattern, source)
180
+ // Puts the hoisted default statements at the start of a body, giving an expression body a block to hold them.
181
+ function withPrelude(compiledBody: string, body: Node, prelude: string): string {
182
+ if (prelude === '')
183
+ return compiledBody
184
+ return body.type === 'BlockStatement' ? `{ ${prelude}${compiledBody.slice(1)}` : `{ ${prelude} return (${compiledBody}); }`
185
+ }
248
186
 
249
- const compilePatternSource = (patNode: Node): string => {
250
- const sub = new SourceEditor(code.slice(patNode.start, patNode.end))
251
- const base = patNode.start
252
- const patchPattern = (p: Node | null | undefined): void => {
253
- if (p === null || p === undefined)
254
- return
255
- if ('typeAnnotation' in p && p.typeAnnotation != null) {
256
- const ann = p.typeAnnotation as Node
257
- sub.remove(ann.start - base, ann.end - base)
258
- }
259
- switch (p.type) {
260
- case 'AssignmentPattern':
261
- patchPattern(p.left)
262
- sub.replace(p.right.start - base, p.right.end - base, compileExpression(p.right, outerRewrites))
263
- return
264
- case 'RestElement':
265
- patchPattern(p.argument)
266
- return
267
- case 'ArrayPattern':
268
- for (const el of p.elements)
269
- patchPattern(el)
270
- return
271
- case 'ObjectPattern':
272
- for (const prop of p.properties) {
273
- if (prop.type === 'RestElement') {
274
- patchPattern(prop.argument)
275
- }
276
- else {
277
- if (prop.computed)
278
- sub.replace(prop.key.start - base, prop.key.end - base, compileExpression(prop.key, outerRewrites))
279
- patchPattern(prop.value)
280
- }
281
- }
282
- }
283
- }
284
- patchPattern(patNode)
285
- return sub.toString()
286
- }
187
+ function buildCompiledFunction(ctx: PropCompilerContext, fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string {
188
+ const { code, freshVar, compileExpression } = ctx
189
+ const fnEditor = new SourceEditor(code.slice(fn.start, fn.end))
190
+ const offset = fn.start
191
+ const destructured = extractDestructuredParam(code, fn.params[0])
192
+ const pVar = freshVar('__p')
193
+ const baseRewrites = new Map(outerRewrites)
194
+ if (fn.type !== 'ArrowFunctionExpression' && fn.id !== null)
195
+ baseRewrites.delete(fn.id.name)
196
+ let propRewrites = baseRewrites
197
+ let prelude = ''
287
198
 
288
- const names = new Set<string>()
289
- collectPatternNames(pattern, names)
290
- // The pattern a read runs: only the property binding `name`, so another property's default does not run on this read.
291
- const patternFor = (name: string): string => {
292
- if (pattern.type === 'ObjectPattern') {
293
- for (const prop of (pattern as ObjectPattern).properties) {
294
- const bound = new Set<string>()
295
- collectPatternNames(prop.type === 'RestElement' ? prop.argument : prop.value, bound)
296
- if (prop.type === 'Property' && bound.has(name)) {
297
- const sub = new SourceEditor(code.slice(prop.start, prop.end))
298
- const base = prop.start
299
- if (prop.computed)
300
- sub.replace(prop.key.start - base, prop.key.end - base, compileExpression(prop.key, outerRewrites))
301
- sub.replace(prop.value.start - base, prop.value.end - base, compilePatternSource(prop.value))
302
- return `{ ${sub.toString()} }`
303
- }
304
- }
305
- }
306
- return compilePatternSource(pattern)
307
- }
308
- for (const name of names) {
309
- if (reads.has(name))
310
- continue
311
- const getter = `(${patternFor(name)}) => ${name}`
312
- reads.set(name, hoisted === undefined ? `(${getter})(${source})` : `${hoist(getter)}(${source})`)
313
- }
314
- return reads
199
+ if (destructured !== undefined) {
200
+ const defSuffix = destructured.defaultExpr !== undefined
201
+ ? ` = ${compileExpression(destructured.defaultExpr, baseRewrites)}`
202
+ : ''
203
+ fnEditor.replace(destructured.replaceStart - offset, destructured.replaceEnd - offset, `${pVar}${destructured.typeAnn}${defSuffix}`)
204
+ ;({ rewrites: propRewrites, prelude } = computePropRewrites(ctx, destructured, pVar, baseRewrites, fn.body))
315
205
  }
316
206
 
317
- function extractDestructuredParam(firstParam: ParamPattern | undefined): {
318
- pattern: ObjectPattern
319
- defaultExpr: Node | undefined
320
- replaceStart: number
321
- replaceEnd: number
322
- typeAnn: string
323
- } | undefined {
324
- if (firstParam === undefined)
325
- return undefined
326
- if (firstParam.type === 'ObjectPattern') {
327
- const typeAnn = firstParam.typeAnnotation ? code.slice(firstParam.typeAnnotation.start, firstParam.typeAnnotation.end) : ''
328
- return { pattern: firstParam, defaultExpr: undefined, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
329
- }
330
- if (firstParam.type === 'AssignmentPattern' && firstParam.left.type === 'ObjectPattern') {
331
- const pat = firstParam.left
332
- const typeAnn = pat.typeAnnotation ? code.slice(pat.typeAnnotation.start, pat.typeAnnotation.end) : ''
333
- return { pattern: pat, defaultExpr: firstParam.right, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
334
- }
335
- return undefined
207
+ for (let i = 1; i < fn.params.length; i++) {
208
+ const extraParam = fn.params[i]!
209
+ patchParamDefaults(extraParam, propRewrites, fnEditor, offset, compileExpression)
210
+ propRewrites = withoutBindings(propRewrites, [extraParam])
336
211
  }
337
212
 
338
- function computePropRewrites(
339
- destructured: { pattern: ObjectPattern, defaultExpr: Node | undefined },
340
- pVar: string,
341
- outerRewrites: ReadonlyMap<string, string>,
342
- body: Node | null,
343
- ): { rewrites: Map<string, string>, prelude: string } {
344
- const rewrites = new Map(outerRewrites)
345
- const hoisted: string[] = []
346
- const propReads = patternReads(destructured.pattern, pVar, outerRewrites, hoisted)
347
- const mutated = collectMutatedNames(body, new Set(propReads.keys()))
348
- for (const [name, read] of propReads) {
349
- if (mutated.has(name)) {
350
- // A mutated destructured prop becomes a local `let` binding initialized once, avoiding invalid assignment targets like `(a === undefined ? b : a) = c`.
351
- hoisted.push(`let ${name} = ${read};`)
352
- rewrites.delete(name)
353
- }
354
- else {
355
- rewrites.set(name, read)
356
- }
357
- }
358
- return { rewrites, prelude: hoisted.join(' ') }
359
- }
213
+ if (fn.body !== null)
214
+ fnEditor.replace(fn.body.start - offset, fn.body.end - offset, withPrelude(compileExpression(fn.body, propRewrites), fn.body, prelude))
215
+ return fnEditor.toString()
216
+ }
360
217
 
361
- // Puts the hoisted default statements at the start of a body, giving an expression body a block to hold them.
362
- function withPrelude(compiledBody: string, body: Node, prelude: string): string {
363
- if (prelude === '')
364
- return compiledBody
365
- return body.type === 'BlockStatement' ? `{ ${prelude}${compiledBody.slice(1)}` : `{ ${prelude} return (${compiledBody}); }`
218
+ // Compiles each statement of a component body with the prop reads active, deferring a JSX-valued `const` that only JSX slots read.
219
+ function compileBodyStatements(ctx: PropCompilerContext, body: Extract<Node, { type: 'BlockStatement' }>, propRewrites: Map<string, string>): void {
220
+ const { editor, jsxNodes, compileExpression } = ctx
221
+ const shadowed = new Set<string>()
222
+ for (const stmt of body.body) {
223
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
224
+ shadowed.add(stmt.id.name)
225
+ else if (stmt.type === 'ClassDeclaration' && stmt.id !== null)
226
+ shadowed.add(stmt.id.name)
366
227
  }
367
-
368
- function buildCompiledFunction(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string {
369
- const fnEditor = new SourceEditor(code.slice(fn.start, fn.end))
370
- const offset = fn.start
371
- const destructured = extractDestructuredParam(fn.params[0])
372
- const pVar = freshVar('__p')
373
- const baseRewrites = new Map(outerRewrites)
374
- if (fn.type !== 'ArrowFunctionExpression' && fn.id !== null)
375
- baseRewrites.delete(fn.id.name)
376
- let propRewrites = baseRewrites
377
- let prelude = ''
378
-
379
- if (destructured !== undefined) {
380
- const defSuffix = destructured.defaultExpr !== undefined
381
- ? ` = ${compileExpression(destructured.defaultExpr, baseRewrites)}`
382
- : ''
383
- fnEditor.replace(destructured.replaceStart - offset, destructured.replaceEnd - offset, `${pVar}${destructured.typeAnn}${defSuffix}`)
384
- ;({ rewrites: propRewrites, prelude } = computePropRewrites(destructured, pVar, baseRewrites, fn.body))
228
+ const stmts = body.body
229
+ for (let i = 0; i < stmts.length; i++) {
230
+ const stmt = stmts[i]!
231
+ const active = new Map<string, string>()
232
+ for (const [k, v] of propRewrites) {
233
+ if (!shadowed.has(k))
234
+ active.set(k, v)
385
235
  }
386
-
387
- for (let i = 1; i < fn.params.length; i++) {
388
- const extraParam = fn.params[i]!
389
- patchParamDefaults(extraParam, propRewrites, fnEditor, offset, compileExpression)
390
- propRewrites = withoutBindings(propRewrites, [extraParam])
236
+ // Defer `const badge = <span />` to `const badge = () => _t0()` when only used in JSX slots so SSR hydration claims the outer element before the slot's nodes.
237
+ if (
238
+ stmt.type === 'VariableDeclaration' && stmt.kind === 'const' && stmt.declarations.length === 1
239
+ && stmt.declarations[0]!.id.type === 'Identifier' && stmt.declarations[0]!.init !== null
240
+ ) {
241
+ const decl = stmt.declarations[0]!
242
+ const jsxInit = unwrapParens(decl.init!)
243
+ const varName = (decl.id as Extract<Node, { type: 'Identifier' }>).name
244
+ if (isJsxNode(jsxInit) && isSafeLazyJsxRef(varName, stmts.slice(i + 1))) {
245
+ editor.replace(stmt.start, stmt.end, `const ${varName} = () => ${compileExpression(jsxInit, active)};`)
246
+ propRewrites.set(varName, `${varName}()`)
247
+ shadowed.delete(varName)
248
+ continue
249
+ }
250
+ }
251
+ if (active.size > 0 || containsJsx(stmt, jsxNodes))
252
+ editor.replace(stmt.start, stmt.end, compileExpression(stmt, active))
253
+ if (stmt.type === 'VariableDeclaration') {
254
+ for (const d of stmt.declarations)
255
+ collectPatternNames(d.id, shadowed)
391
256
  }
392
-
393
- if (fn.body !== null)
394
- fnEditor.replace(fn.body.start - offset, fn.body.end - offset, withPrelude(compileExpression(fn.body, propRewrites), fn.body, prelude))
395
- return fnEditor.toString()
396
257
  }
258
+ }
397
259
 
398
- // Handle top-level component functions with destructured props + JSX compilation
399
- function processFunction(fn: ArrowFunctionExpression | OxcFunction): void {
400
- if (fn.body === null || !containsJsx(fn.body, jsxNodes))
401
- return
260
+ // Handle top-level component functions with destructured props + JSX compilation
261
+ function processFunction(ctx: PropCompilerContext, fn: ArrowFunctionExpression | OxcFunction): void {
262
+ const { code, editor, jsxNodes, compileExpression } = ctx
263
+ if (fn.body === null || !containsJsx(fn.body, jsxNodes))
264
+ return
402
265
 
403
- const destructured = extractDestructuredParam(fn.params[0])
404
- let propRewrites = new Map<string, string>()
405
- let prelude = ''
266
+ const destructured = extractDestructuredParam(code, fn.params[0])
267
+ let propRewrites = new Map<string, string>()
268
+ let prelude = ''
406
269
 
407
- if (destructured !== undefined) {
408
- const pVar = '__p'
409
- const defSuffix = destructured.defaultExpr !== undefined
410
- ? ` = ${compileExpression(destructured.defaultExpr, new Map())}`
411
- : ''
412
- editor.replace(destructured.replaceStart, destructured.replaceEnd, `${pVar}${destructured.typeAnn}${defSuffix}`)
413
- ;({ rewrites: propRewrites, prelude } = computePropRewrites(destructured, pVar, new Map(), fn.body))
414
- }
270
+ if (destructured !== undefined) {
271
+ const pVar = '__p'
272
+ const defSuffix = destructured.defaultExpr !== undefined
273
+ ? ` = ${compileExpression(destructured.defaultExpr, new Map())}`
274
+ : ''
275
+ editor.replace(destructured.replaceStart, destructured.replaceEnd, `${pVar}${destructured.typeAnn}${defSuffix}`)
276
+ ;({ rewrites: propRewrites, prelude } = computePropRewrites(ctx, destructured, pVar, new Map(), fn.body))
277
+ }
415
278
 
416
- for (let i = 1; i < fn.params.length; i++) {
417
- const extraParam = fn.params[i]!
418
- patchParamDefaults(extraParam, propRewrites, editor, 0, compileExpression)
419
- propRewrites = withoutBindings(propRewrites, [extraParam])
420
- }
279
+ for (let i = 1; i < fn.params.length; i++) {
280
+ const extraParam = fn.params[i]!
281
+ patchParamDefaults(extraParam, propRewrites, editor, 0, compileExpression)
282
+ propRewrites = withoutBindings(propRewrites, [extraParam])
283
+ }
421
284
 
422
- const hasLazyJsxDecl = fn.body.type === 'BlockStatement' && fn.body.body.some(s =>
423
- s.type === 'VariableDeclaration' && s.kind === 'const' && s.declarations.length === 1
424
- && s.declarations[0]!.id.type === 'Identifier' && s.declarations[0]!.init !== null
425
- && isJsxNode(unwrapParens(s.declarations[0]!.init)),
426
- )
285
+ const hasLazyJsxDecl = fn.body.type === 'BlockStatement' && fn.body.body.some(s =>
286
+ s.type === 'VariableDeclaration' && s.kind === 'const' && s.declarations.length === 1
287
+ && s.declarations[0]!.id.type === 'Identifier' && s.declarations[0]!.init !== null
288
+ && isJsxNode(unwrapParens(s.declarations[0]!.init)),
289
+ )
427
290
 
428
- if ((propRewrites.size > 0 || hasLazyJsxDecl) && fn.body.type === 'BlockStatement') {
429
- if (prelude !== '')
430
- editor.replace(fn.body.start + 1, fn.body.start + 1, ` ${prelude}`)
431
- const shadowed = new Set<string>()
432
- for (const stmt of fn.body.body) {
433
- if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
434
- shadowed.add(stmt.id.name)
435
- else if (stmt.type === 'ClassDeclaration' && stmt.id !== null)
436
- shadowed.add(stmt.id.name)
437
- }
438
- const stmts = fn.body.body
439
- for (let i = 0; i < stmts.length; i++) {
440
- const stmt = stmts[i]!
441
- const active = new Map<string, string>()
442
- for (const [k, v] of propRewrites) {
443
- if (!shadowed.has(k))
444
- active.set(k, v)
445
- }
446
- // Defer `const badge = <span />` to `const badge = () => _t0()` when only used in JSX slots so SSR hydration claims the outer element before the slot's nodes.
447
- if (
448
- stmt.type === 'VariableDeclaration' && stmt.kind === 'const' && stmt.declarations.length === 1
449
- && stmt.declarations[0]!.id.type === 'Identifier' && stmt.declarations[0]!.init !== null
450
- ) {
451
- const decl = stmt.declarations[0]!
452
- const jsxInit = unwrapParens(decl.init!)
453
- const varName = (decl.id as Extract<Node, { type: 'Identifier' }>).name
454
- if (isJsxNode(jsxInit) && isSafeLazyJsxRef(varName, stmts.slice(i + 1))) {
455
- editor.replace(stmt.start, stmt.end, `const ${varName} = () => ${compileExpression(jsxInit, active)};`)
456
- propRewrites.set(varName, `${varName}()`)
457
- shadowed.delete(varName)
458
- continue
459
- }
460
- }
461
- if (active.size > 0 || containsJsx(stmt, jsxNodes))
462
- editor.replace(stmt.start, stmt.end, compileExpression(stmt, active))
463
- if (stmt.type === 'VariableDeclaration') {
464
- for (const d of stmt.declarations)
465
- collectPatternNames(d.id, shadowed)
466
- }
467
- }
468
- }
469
- else {
470
- editor.replace(fn.body.start, fn.body.end, withPrelude(compileExpression(fn.body, propRewrites), fn.body, prelude))
471
- }
291
+ if ((propRewrites.size > 0 || hasLazyJsxDecl) && fn.body.type === 'BlockStatement') {
292
+ if (prelude !== '')
293
+ editor.replace(fn.body.start + 1, fn.body.start + 1, ` ${prelude}`)
294
+ compileBodyStatements(ctx, fn.body, propRewrites)
472
295
  }
296
+ else {
297
+ editor.replace(fn.body.start, fn.body.end, withPrelude(compileExpression(fn.body, propRewrites), fn.body, prelude))
298
+ }
299
+ }
473
300
 
474
- function compileLoopRow(opts: {
475
- firstParam: ParamPattern | undefined
476
- idxParam: string | undefined
477
- keyAst: Node | undefined
478
- rowSig: string
479
- scopeRewrites: ReadonlyMap<string, string>
480
- keyRewrites: ReadonlyMap<string, string>
481
- }): { keyFn: string, rowRewrites: Map<string, string>, prelude: string } {
482
- const { firstParam, idxParam, keyAst, rowSig, scopeRewrites, keyRewrites } = opts
483
- const rowRewrites = new Map(scopeRewrites)
484
- const hoisted: string[] = []
485
- let keyFn: string
486
- if (firstParam !== undefined && firstParam.type !== 'Identifier') {
487
- if (keyAst !== undefined) {
488
- const keyItem = freshVar('_item')
489
- const keyScope = new Map(keyRewrites)
490
- for (const [name, read] of patternReads(firstParam, keyItem, scopeRewrites))
491
- keyScope.set(name, read)
492
- keyFn = `(${keyItem}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyScope)}`
493
- }
494
- else {
495
- keyFn = `(_item) => _item`
496
- }
497
- for (const [name, read] of patternReads(firstParam, `${rowSig}.value`, scopeRewrites, hoisted))
498
- rowRewrites.set(name, read)
301
+ type LoopRowOptions = Parameters<PropCompiler['compileLoopRow']>[0]
302
+
303
+ function compileLoopRow(ctx: PropCompilerContext, opts: LoopRowOptions): { keyFn: string, rowRewrites: Map<string, string>, prelude: string } {
304
+ const { freshVar, compileExpression } = ctx
305
+ const { firstParam, idxParam, keyAst, rowSig, scopeRewrites, keyRewrites } = opts
306
+ const rowRewrites = new Map(scopeRewrites)
307
+ const hoisted: string[] = []
308
+ let keyFn: string
309
+ if (firstParam !== undefined && firstParam.type !== 'Identifier') {
310
+ if (keyAst !== undefined) {
311
+ const keyItem = freshVar('_item')
312
+ const keyScope = new Map(keyRewrites)
313
+ for (const [name, read] of patternReads(ctx, firstParam, keyItem, scopeRewrites))
314
+ keyScope.set(name, read)
315
+ keyFn = `(${keyItem}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyScope)}`
499
316
  }
500
317
  else {
501
- const itemParam = firstParam?.type === 'Identifier' ? firstParam.name : '_item'
502
- keyFn = keyAst !== undefined
503
- ? `(${itemParam}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
504
- : `(${itemParam}) => ${itemParam}`
505
- rowRewrites.set(itemParam, `${rowSig}.value`)
318
+ keyFn = `(_item) => _item`
506
319
  }
507
- return { keyFn, rowRewrites, prelude: hoisted.join(' ') }
320
+ for (const [name, read] of patternReads(ctx, firstParam, `${rowSig}.value`, scopeRewrites, hoisted))
321
+ rowRewrites.set(name, read)
322
+ }
323
+ else {
324
+ const itemParam = firstParam?.type === 'Identifier' ? firstParam.name : '_item'
325
+ keyFn = keyAst !== undefined
326
+ ? `(${itemParam}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
327
+ : `(${itemParam}) => ${itemParam}`
328
+ rowRewrites.set(itemParam, `${rowSig}.value`)
508
329
  }
330
+ return { keyFn, rowRewrites, prelude: hoisted.join(' ') }
331
+ }
509
332
 
510
- return { patternReads, compileLoopRow, withPrelude, extractDestructuredParam, buildCompiledFunction, processFunction }
333
+ export function createPropCompiler(ctx: PropCompilerContext): PropCompiler {
334
+ return {
335
+ patternReads: (pattern, source, outerRewrites, hoisted) => patternReads(ctx, pattern, source, outerRewrites, hoisted),
336
+ compileLoopRow: opts => compileLoopRow(ctx, opts),
337
+ withPrelude,
338
+ extractDestructuredParam: firstParam => extractDestructuredParam(ctx.code, firstParam),
339
+ buildCompiledFunction: (fn, outerRewrites) => buildCompiledFunction(ctx, fn, outerRewrites),
340
+ processFunction: fn => processFunction(ctx, fn),
341
+ }
511
342
  }
@@ -367,28 +367,21 @@ type PrunelleTag = 'Head' | 'Region' | 'Suspense' | 'ConsentGate' | 'ConsentBann
367
367
 
368
368
  const PRUNELLE_TAGS = new Set<string>(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'Catch'])
369
369
 
370
- /** Resolves a JSX tag (direct, aliased, or namespaced via `prunelle`) to its canonical Prunelle tag. */
370
+ /** Resolves a JSX tag (direct, aliased, or namespaced via `prunelle`) to its canonical Prunelle tag; a tag not imported from `prunelle`, such as a component the file declares, is never one. */
371
371
  export function resolvePrunelleTag(tag: string, imports: readonly PrunelleTagBinding[]): PrunelleTag | undefined {
372
- let boundElsewhere = false
373
372
  for (const imp of imports) {
374
- const isPrunelle = imp.source === 'prunelle'
373
+ if (imp.source !== 'prunelle')
374
+ continue
375
375
  for (const spec of imp.specifiers) {
376
- if (isPrunelle) {
377
- if (spec.local === tag && PRUNELLE_TAGS.has(spec.imported))
378
- return spec.imported as PrunelleTag
379
- if (spec.imported === '*' && tag.startsWith(`${spec.local}.`)) {
380
- const member = tag.slice(spec.local.length + 1)
381
- if (PRUNELLE_TAGS.has(member))
382
- return member as PrunelleTag
383
- }
384
- }
385
- else if (spec.local === tag) {
386
- boundElsewhere = true
376
+ if (spec.local === tag && PRUNELLE_TAGS.has(spec.imported))
377
+ return spec.imported as PrunelleTag
378
+ if (spec.imported === '*' && tag.startsWith(`${spec.local}.`)) {
379
+ const member = tag.slice(spec.local.length + 1)
380
+ if (PRUNELLE_TAGS.has(member))
381
+ return member as PrunelleTag
387
382
  }
388
383
  }
389
384
  }
390
- if (!boundElsewhere && PRUNELLE_TAGS.has(tag))
391
- return tag as PrunelleTag
392
385
  return undefined
393
386
  }
394
387