prunelle 0.8.0 → 0.10.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 (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  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 +94 -136
  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 +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
@@ -66,6 +66,15 @@ export function mistake(what: string, filename: string, fix: string): PrunelleMi
66
66
  return new PrunelleMistake(`prunelle compiler: ${what} in ${filename}: ${fix}.`)
67
67
  }
68
68
 
69
+ const GUIDES = 'https://prunelle.kaynooo.fr/docs/getting-started'
70
+ // The pages mapping another framework's concepts to prunelle's, linked from each error refusing a habit that framework taught.
71
+ export const ASTRO_GUIDE = `${GUIDES}/coming-from-astro`
72
+ export const NEXT_GUIDE = `${GUIDES}/coming-from-next`
73
+
74
+ export function withGuide(fix: string, guide: string): string {
75
+ return `${fix}; see ${guide}`
76
+ }
77
+
69
78
  /** `$hydrate` where nothing can hydrate: on an element (`component` false) or on a component that is not an island. The one wording the compiler, the build and `prunelle check` share. */
70
79
  export function hydrateMistake(tag: string, filename: string, component: boolean): PrunelleMistake {
71
80
  return mistake(`$hydrate on <${tag}>`, filename, component
@@ -121,7 +130,7 @@ export function serverOnlyTagError(filename: string, { tag, island, reason, offs
121
130
 
122
131
  /** The error for an Astro `---` block opening a file, at the first dash. */
123
132
  export function frontmatterMistake(filename: string, start: number): PrunelleMistake {
124
- const err = mistake('a --- frontmatter block', filename, 'prunelle files are plain TypeScript with no --- fence; write that code above the component, or inside it, and delete both --- lines')
133
+ const err = mistake('a --- frontmatter block', filename, withGuide('prunelle files are plain TypeScript with no --- fence; write that code above the component, or inside it, and delete both --- lines', ASTRO_GUIDE))
125
134
  err.start = start
126
135
  return err
127
136
  }
@@ -242,13 +251,13 @@ function checkNamespacedAttribute(namespace: string, name: string, filename: str
242
251
  if (namespace === 'on')
243
252
  throw mistake(what, filename, `write ${eventProp(name.toLowerCase())}={...}`)
244
253
  if (namespace === 'client')
245
- throw mistake(what, filename, `write $hydrate="${CLIENT_DIRECTIVES.get(name) ?? 'load'}"`)
254
+ throw mistake(what, filename, withGuide(`write $hydrate="${CLIENT_DIRECTIVES.get(name) ?? 'load'}"`, ASTRO_GUIDE))
246
255
  if (what === 'class:list')
247
- throw mistake(what, filename, 'pass one string to class, joining the names yourself')
256
+ throw mistake(what, filename, withGuide('pass one string to class, joining the names yourself', ASTRO_GUIDE))
248
257
  if (what === 'set:html')
249
- throw mistake(what, filename, 'write innerHTML={...}')
258
+ throw mistake(what, filename, withGuide('write innerHTML={...}', ASTRO_GUIDE))
250
259
  if (what === 'set:text')
251
- throw mistake(what, filename, 'write the text as children')
260
+ throw mistake(what, filename, withGuide('write the text as children', ASTRO_GUIDE))
252
261
  if (namespace === 'use')
253
262
  throw mistake(what, filename, `call ${name} in a ref`)
254
263
  if (namespace === 'prop' || namespace === 'attr' || namespace === 'bool')
@@ -389,7 +398,7 @@ export function checkMistakes(
389
398
  const isCustomElement = tag.includes('-')
390
399
  if (tag === 'slot') {
391
400
  const named = staticAttr(element.openingElement.attributes, 'name') !== undefined
392
- guarded(element.start, () => { throw mistake('<slot>', filename, named ? 'prunelle has no slots, pass the named part as its own prop, <Card footer={<p />} />, and write {footer} where it goes' : 'prunelle has no slots, take children as a prop, function Card({ children }) { return <div>{children}</div> }, and write {children} where the content goes') })
401
+ guarded(element.start, () => { throw mistake('<slot>', filename, withGuide(named ? 'prunelle has no slots, pass the named part as its own prop, <Card footer={<p />} />, and write {footer} where it goes' : 'prunelle has no slots, take children as a prop, function Card({ children }) { return <div>{children}</div> }, and write {children} where the content goes', ASTRO_GUIDE)) })
393
402
  }
394
403
  if (canonical === 'Suspense') {
395
404
  const children = filterMeaningfulChildren(element.children).length
@@ -452,7 +461,7 @@ function checkRegionNesting(
452
461
  })
453
462
  }
454
463
 
455
- // The markup `regions()` from `@prunellejs/spa` reads: <Region name>, and data-pru-target, data-pru-append and data-pru-live on the elements that can use them.
464
+ // The markup core `<Region>` reads: <Region name>, and data-pru-target, data-pru-append and data-pru-live on the elements that can use them.
456
465
  function checkRegionMarkup(
457
466
  tag: string,
458
467
  canonical: string | undefined,
@@ -500,8 +509,8 @@ function checkKeepScroll(element: JSXElement, attributes: readonly JSXAttributeI
500
509
  }
501
510
 
502
511
  const DIRECTIVE_FIXES: Record<string, string> = {
503
- 'use client': 'delete it, prunelle makes a component an island by itself when it uses state or handlers',
504
- 'use server': 'delete it, a server function is an action() exported from its own file',
512
+ 'use client': withGuide('delete it, prunelle makes a component an island by itself when it uses state or handlers', NEXT_GUIDE),
513
+ 'use server': withGuide('delete it, a server function is an action() exported from its own file', NEXT_GUIDE),
505
514
  }
506
515
 
507
516
  /** Throws on a React or Next habit plain code carries: a 'use client' or 'use server' directive, or an effect(async ...). */
@@ -1,8 +1,12 @@
1
- // Warns on `const { a } = props` in a component that runs in the browser: only a destructured parameter is rewritten to stay reactive, and a read of stable objects in the body can be meant.
1
+ // Warns on reactivity-breaking patterns in browser-reachable components: body props destructuring, mutated destructured props, store destructuring, and top-level `.value` snapshots rendered in JSX.
2
2
 
3
- import type { Function as FunctionNode, Node, Program } from 'oxc-parser'
3
+ import type { Function as FunctionNode, JSXElement, JSXFragment, Node, Program } from 'oxc-parser'
4
4
  import type { CompilerWarning } from './mistakes'
5
- import { containsJsx, unwrapTsExpr } from './shared'
5
+ import type { ReactiveImportCallees } from './signal-reads'
6
+ import { walk } from './ast'
7
+ import { collectMutatedNames, walkScoped } from './scope'
8
+ import { calleeName, collectPatternNames, containsJsx, EVENT_ATTR, jsxTagName, unwrapTsExpr } from './shared'
9
+ import { collectReactiveImportCallees } from './signal-reads'
6
10
 
7
11
  function isFunction(node: Node | null | undefined): node is FunctionNode {
8
12
  return node !== null && node !== undefined && (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression')
@@ -26,7 +30,255 @@ function declaredFunctions(stmt: Node): FunctionNode[] {
26
30
  return found
27
31
  }
28
32
 
29
- /** Warns on a top-level statement of a browser component's body that destructures its first parameter, with the parameter form as the fix. */
33
+ interface ReactiveScope {
34
+ signals: Set<string>
35
+ fieldObjs: Map<string, ReadonlySet<string>>
36
+ stores: Set<string>
37
+ }
38
+
39
+ function shadowNames(scope: ReactiveScope, names: Iterable<string>, snapshots?: Map<string, unknown>): void {
40
+ for (const name of names) {
41
+ scope.signals.delete(name)
42
+ scope.fieldObjs.delete(name)
43
+ scope.stores.delete(name)
44
+ snapshots?.delete(name)
45
+ }
46
+ }
47
+
48
+ function recordDeclaratorBinding(
49
+ d: Extract<Node, { type: 'VariableDeclarator' }>,
50
+ callees: ReactiveImportCallees,
51
+ scope: ReactiveScope,
52
+ snapshots?: Map<string, { source: string, start: number }>,
53
+ isConst = false,
54
+ ): void {
55
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
56
+ if (d.id.type === 'Identifier') {
57
+ const name = d.id.name
58
+ shadowNames(scope, [name], snapshots)
59
+ if (init === undefined)
60
+ return
61
+ if (init.type === 'CallExpression') {
62
+ const callee = calleeName(init.callee)
63
+ if (callees.storeCallees.has(callee)) {
64
+ scope.stores.add(name)
65
+ return
66
+ }
67
+ if (callees.signalCallees.has(callee))
68
+ scope.signals.add(name)
69
+ const fields = callees.signalFieldCallees.get(callee)
70
+ if (fields !== undefined)
71
+ scope.fieldObjs.set(name, fields)
72
+ return
73
+ }
74
+ if (isConst && snapshots !== undefined && init.type === 'MemberExpression' && !init.computed && init.property.type === 'Identifier' && init.property.name === 'value') {
75
+ const obj = unwrapTsExpr(init.object)
76
+ if (obj.type === 'Identifier' && scope.signals.has(obj.name))
77
+ snapshots.set(name, { source: `${obj.name}.value`, start: d.start })
78
+ else if (obj.type === 'MemberExpression' && !obj.computed && obj.object.type === 'Identifier' && obj.property.type === 'Identifier' && scope.fieldObjs.get(obj.object.name)?.has(obj.property.name))
79
+ snapshots.set(name, { source: `${obj.object.name}.${obj.property.name}.value`, start: d.start })
80
+ }
81
+ return
82
+ }
83
+ const bound = new Set<string>()
84
+ collectPatternNames(d.id, bound)
85
+ shadowNames(scope, bound, snapshots)
86
+ if (d.id.type === 'ObjectPattern' && init?.type === 'CallExpression') {
87
+ const fields = callees.signalFieldCallees.get(calleeName(init.callee))
88
+ if (fields === undefined)
89
+ return
90
+ for (const prop of d.id.properties) {
91
+ if (prop.type !== 'Property' || prop.computed)
92
+ continue
93
+ const key = prop.key.type === 'Identifier' ? prop.key.name : prop.key.type === 'Literal' ? String(prop.key.value) : undefined
94
+ const target = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value
95
+ if (key !== undefined && fields.has(key) && target.type === 'Identifier')
96
+ scope.signals.add(target.name)
97
+ }
98
+ }
99
+ }
100
+
101
+ function collectModuleReactiveScope(program: Program, callees: ReactiveImportCallees): ReactiveScope {
102
+ const scope: ReactiveScope = { signals: new Set(), fieldObjs: new Map(), stores: new Set() }
103
+ for (const stmt of program.body) {
104
+ const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt
105
+ if (decl?.type === 'VariableDeclaration') {
106
+ for (const d of decl.declarations)
107
+ recordDeclaratorBinding(d, callees, scope)
108
+ }
109
+ }
110
+ return scope
111
+ }
112
+
113
+ function collectPatternIdentifierStarts(pattern: Node, out: Map<string, number>): void {
114
+ walk(pattern, (node) => {
115
+ if (node.type === 'Identifier') {
116
+ if (!out.has(node.name))
117
+ out.set(node.name, node.start)
118
+ return false
119
+ }
120
+ if (node.type === 'AssignmentPattern') {
121
+ collectPatternIdentifierStarts(node.left, out)
122
+ return false
123
+ }
124
+ if (node.type === 'Property') {
125
+ collectPatternIdentifierStarts(node.value, out)
126
+ return false
127
+ }
128
+ return undefined
129
+ })
130
+ }
131
+
132
+ function scanJsxNodeReads(
133
+ jsxNode: JSXElement | JSXFragment,
134
+ outerShadowed: ReadonlySet<string>,
135
+ snapshots: ReadonlyMap<string, { source: string, start: number }>,
136
+ jsxNodes: WeakSet<Node>,
137
+ found: Set<string>,
138
+ ): void {
139
+ const scanExpr = (expr: Node): void => {
140
+ walkScoped(expr, {
141
+ onIdentifier(id, innerShadowed) {
142
+ const snap = snapshots.get(id.name)
143
+ if (snap !== undefined && id.start > snap.start && !outerShadowed.has(id.name) && !innerShadowed.has(id.name))
144
+ found.add(id.name)
145
+ },
146
+ onFunction(fn) {
147
+ // Skip event/callback functions without JSX so `onClick={() => log(snap)}` never warns.
148
+ return !containsJsx(fn.body, jsxNodes)
149
+ },
150
+ onJsx(nested, innerShadowed) {
151
+ const combined = innerShadowed.size === 0 ? outerShadowed : new Set([...outerShadowed, ...innerShadowed])
152
+ scanJsxNodeReads(nested, combined, snapshots, jsxNodes, found)
153
+ },
154
+ })
155
+ }
156
+ if (jsxNode.type === 'JSXElement') {
157
+ for (const attr of jsxNode.openingElement.attributes) {
158
+ if (attr.type === 'JSXSpreadAttribute') {
159
+ scanExpr(attr.argument)
160
+ continue
161
+ }
162
+ const attrName = jsxTagName(attr.name)
163
+ if (EVENT_ATTR.test(attrName) || attrName === 'ref')
164
+ continue
165
+ if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
166
+ scanExpr(attr.value.expression)
167
+ }
168
+ }
169
+ for (const child of jsxNode.children) {
170
+ if (child.type === 'JSXElement' || child.type === 'JSXFragment')
171
+ scanJsxNodeReads(child, outerShadowed, snapshots, jsxNodes, found)
172
+ else if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
173
+ scanExpr(child.expression)
174
+ }
175
+ }
176
+
177
+ function findDirectJsxSnapshotReads(
178
+ body: Extract<Node, { type: 'BlockStatement' }>,
179
+ snapshots: ReadonlyMap<string, { source: string, start: number }>,
180
+ jsxNodes: WeakSet<Node>,
181
+ ): Set<string> {
182
+ const found = new Set<string>()
183
+ for (const stmt of body.body) {
184
+ walkScoped(stmt, {
185
+ onFunction(fn) {
186
+ return !containsJsx(fn.body, jsxNodes)
187
+ },
188
+ onJsx(node, shadowed) {
189
+ scanJsxNodeReads(node, shadowed, snapshots, jsxNodes, found)
190
+ },
191
+ })
192
+ }
193
+ return found
194
+ }
195
+
196
+ function checkComponentBody(
197
+ fn: FunctionNode,
198
+ code: string,
199
+ callees: ReactiveImportCallees,
200
+ moduleScope: ReactiveScope,
201
+ jsxNodes: WeakSet<Node>,
202
+ filename: string,
203
+ warnings: CompilerWarning[],
204
+ isBrowser: boolean,
205
+ ): void {
206
+ if (fn.body === null || !containsJsx(fn.body, jsxNodes))
207
+ return
208
+ const rawParam = fn.params[0]
209
+ const param = rawParam?.type === 'AssignmentPattern' ? rawParam.left : rawParam
210
+
211
+ if (isBrowser && param?.type === 'ObjectPattern') {
212
+ const propNames = new Set<string>()
213
+ collectPatternNames(param, propNames)
214
+ const mutated = collectMutatedNames(fn.body, propNames)
215
+ if (mutated.size > 0) {
216
+ const starts = new Map<string, number>()
217
+ collectPatternIdentifierStarts(param, starts)
218
+ for (const name of mutated) {
219
+ warnings.push({
220
+ start: starts.get(name) ?? param.start,
221
+ message: `prunelle compiler: reassigning destructured prop \`${name}\` in ${filename} copies it once at mount and breaks reactivity: keep props read-only, or copy into a local \`signal(${name})\` or \`let\` variable.`,
222
+ })
223
+ }
224
+ }
225
+ }
226
+
227
+ if (fn.body.type !== 'BlockStatement')
228
+ return
229
+
230
+ const propsParamName = isBrowser && param?.type === 'Identifier' ? param.name : undefined
231
+ const scope: ReactiveScope = {
232
+ signals: new Set(moduleScope.signals),
233
+ fieldObjs: new Map(moduleScope.fieldObjs),
234
+ stores: new Set(moduleScope.stores),
235
+ }
236
+ const paramNames = new Set<string>()
237
+ for (const p of fn.params)
238
+ collectPatternNames(p, paramNames)
239
+ shadowNames(scope, paramNames)
240
+
241
+ const snapshots = new Map<string, { source: string, start: number }>()
242
+
243
+ for (const inner of fn.body.body) {
244
+ if ((inner.type === 'FunctionDeclaration' || inner.type === 'ClassDeclaration') && inner.id !== null) {
245
+ shadowNames(scope, [inner.id.name], snapshots)
246
+ continue
247
+ }
248
+ if (inner.type !== 'VariableDeclaration')
249
+ continue
250
+ for (const d of inner.declarations) {
251
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
252
+ if (propsParamName !== undefined && d.id.type === 'ObjectPattern' && init?.type === 'Identifier' && init.name === propsParamName) {
253
+ warnings.push({
254
+ start: d.start,
255
+ message: `prunelle compiler: \`${inner.kind} ${code.slice(d.start, d.end)}\` in ${filename} reads the props once, so a change to them never reaches this component: destructure in the parameter list, (${code.slice(d.id.start, d.id.end)}), which stays reactive, or read props.<name> where it is used.`,
256
+ })
257
+ }
258
+ else if ((d.id.type === 'ObjectPattern' || d.id.type === 'ArrayPattern') && init?.type === 'Identifier' && scope.stores.has(init.name)) {
259
+ warnings.push({
260
+ start: d.start,
261
+ message: `prunelle compiler: \`${inner.kind} ${code.slice(d.start, d.end)}\` in ${filename} reads store properties once at mount, so updates never reach it: read \`${init.name}.<prop>\` where it is used, or use \`snapshot(${init.name})\` if a one-time copy is intended.`,
262
+ })
263
+ }
264
+ recordDeclaratorBinding(d, callees, scope, snapshots, inner.kind === 'const')
265
+ }
266
+ }
267
+
268
+ if (snapshots.size > 0) {
269
+ const jsxUsed = findDirectJsxSnapshotReads(fn.body, snapshots, jsxNodes)
270
+ for (const [name, snap] of snapshots) {
271
+ if (jsxUsed.has(name)) {
272
+ warnings.push({
273
+ start: snap.start,
274
+ message: `prunelle compiler: \`const ${name} = ${snap.source}\` in ${filename} snapshots \`${snap.source}\` once at mount and never updates in JSX: read \`${snap.source}\` directly in JSX, or wrap it in \`computed(() => ...)\`.`,
275
+ })
276
+ }
277
+ }
278
+ }
279
+ }
280
+
281
+ /** Warns on reactivity-breaking patterns in browser-reachable components: body props destructuring, mutated destructured props, store destructuring, and top-level `.value` snapshots in JSX. */
30
282
  export function checkBodyPropsDestructure(
31
283
  program: Program,
32
284
  code: string,
@@ -35,26 +287,16 @@ export function checkBodyPropsDestructure(
35
287
  filename: string,
36
288
  warnings: CompilerWarning[],
37
289
  ): void {
38
- if (browserSpans.length === 0)
290
+ const callees = collectReactiveImportCallees(program)
291
+ const hasReactiveHooks = callees.signalCallees.size > 0 || callees.signalFieldCallees.size > 0 || callees.storeCallees.size > 0
292
+ if (browserSpans.length === 0 && !hasReactiveHooks)
39
293
  return
294
+ const moduleScope = collectModuleReactiveScope(program, callees)
40
295
  for (const stmt of program.body) {
41
296
  for (const fn of declaredFunctions(stmt)) {
42
- if (!browserSpans.some(([s, e]) => fn.start >= s && fn.end <= e))
43
- continue
44
- const rawParam = fn.params[0]
45
- const param = rawParam?.type === 'AssignmentPattern' ? rawParam.left : rawParam
46
- if (param?.type !== 'Identifier' || fn.body?.type !== 'BlockStatement' || !containsJsx(fn.body, jsxNodes))
47
- continue
48
- for (const inner of fn.body.body) {
49
- if (inner.type !== 'VariableDeclaration')
50
- continue
51
- for (const d of inner.declarations) {
52
- const init = d.init === null ? undefined : unwrapTsExpr(d.init)
53
- if (d.id.type !== 'ObjectPattern' || init?.type !== 'Identifier' || init.name !== param.name)
54
- continue
55
- warnings.push({ start: d.start, message: `prunelle compiler: \`${inner.kind} ${code.slice(d.start, d.end)}\` in ${filename} reads the props once, so a change to them never reaches this component: destructure in the parameter list, (${code.slice(d.id.start, d.id.end)}), which stays reactive, or read props.<name> where it is used.` })
56
- }
57
- }
297
+ const isBrowser = browserSpans.some(([s, e]) => fn.start >= s && fn.end <= e)
298
+ if (isBrowser || hasReactiveHooks)
299
+ checkComponentBody(fn, code, callees, moduleScope, jsxNodes, filename, warnings, isBrowser)
58
300
  }
59
301
  }
60
302
  }
@@ -0,0 +1,211 @@
1
+ // How each name a destructuring pattern binds is read from a source expression, so a destructured prop or loop row stays reactive.
2
+
3
+ import type { Node, ObjectPattern } from 'oxc-parser'
4
+ import { walk } from './ast'
5
+ import { SourceEditor } from './patch'
6
+ import { referencesAny } from './scope'
7
+ import { collectPatternNames, containsJsx } from './shared'
8
+
9
+ export interface PatternContext {
10
+ code: string
11
+ jsxNodes: WeakSet<Node>
12
+ use: (name: string) => string
13
+ freshVar: (prefix?: string) => string
14
+ compileExpression: (node: Node, rewrites: ReadonlyMap<string, string>) => string
15
+ }
16
+
17
+ function hoistInto(ctx: PatternContext, hoisted: string[], init: string): string {
18
+ const name = ctx.freshVar('__d')
19
+ hoisted.push(`const ${name} = ${init};`)
20
+ return name
21
+ }
22
+
23
+ function isReactiveDefault(node: Node, running: ReadonlyMap<string, string>): boolean {
24
+ if (running.size > 0 && referencesAny(node, new Set(running.keys())))
25
+ return true
26
+ let readsValue = false
27
+ walk(node, (child) => {
28
+ if (readsValue)
29
+ return false
30
+ if (child.type === 'ArrowFunctionExpression' || child.type === 'FunctionExpression' || child.type === 'FunctionDeclaration')
31
+ return false
32
+ if (child.type === 'MemberExpression' && !child.computed && child.property.type === 'Identifier' && child.property.name === 'value') {
33
+ readsValue = true
34
+ return false
35
+ }
36
+ return undefined
37
+ })
38
+ return readsValue
39
+ }
40
+
41
+ // Walks a pattern, recording in `reads` how each identifier is read from `src`. With `hoisted`, defaults and computed keys become statements for the start of the body.
42
+ function createBinder(
43
+ ctx: PatternContext,
44
+ reads: Map<string, string>,
45
+ running: Map<string, string>,
46
+ hoisted: string[] | undefined,
47
+ ): (pat: Node, src: string) => void {
48
+ const { jsxNodes, use, freshVar, compileExpression } = ctx
49
+
50
+ const hoist = (init: string): string => hoistInto(ctx, hoisted!, init)
51
+
52
+ function bindDefault(pat: Extract<Node, { type: 'AssignmentPattern' }>, src: string): void {
53
+ const defExpr = compileExpression(pat.right, running)
54
+ const simpleDef = pat.right.type === 'Literal' || pat.right.type === 'Identifier'
55
+ const reactiveDef = !simpleDef && !containsJsx(pat.right, jsxNodes) && isReactiveDefault(pat.right, running)
56
+ let fallback = simpleDef ? defExpr : `(${defExpr})`
57
+ if (!simpleDef && !reactiveDef && hoisted !== undefined)
58
+ fallback = `${hoist(`${use('propDefault')}(() => (${defExpr}), ${src} === undefined)`)}()`
59
+ let nextSrc: string
60
+ if (pat.left.type !== 'Identifier' && hoisted !== undefined) {
61
+ const v = freshVar('__v')
62
+ nextSrc = `${hoist(`() => { const ${v} = ${src}; return ${v} === undefined ? ${fallback} : ${v}; }`)}()`
63
+ }
64
+ else {
65
+ nextSrc = `(${src} === undefined ? ${fallback} : ${src})`
66
+ }
67
+ bind(pat.left, nextSrc)
68
+ }
69
+
70
+ function bindObject(pat: Extract<Node, { type: 'ObjectPattern' }>, src: string): void {
71
+ const excludedKeys: string[] = []
72
+ let canOmit = hoisted !== undefined
73
+ for (const prop of pat.properties) {
74
+ if (prop.type === 'RestElement') {
75
+ if (canOmit) {
76
+ const restRead = `${use('omit')}(${src}, [${excludedKeys.join(', ')}])`
77
+ bind(prop.argument, restRead)
78
+ }
79
+ continue
80
+ }
81
+ let propSrc: string | undefined
82
+ if (!prop.computed && prop.key.type === 'Identifier') {
83
+ excludedKeys.push(JSON.stringify(prop.key.name))
84
+ propSrc = `${src}.${prop.key.name}`
85
+ }
86
+ else if (!prop.computed && prop.key.type === 'Literal' && (typeof prop.key.value === 'string' || typeof prop.key.value === 'number')) {
87
+ excludedKeys.push(JSON.stringify(String(prop.key.value)))
88
+ propSrc = `${src}[${JSON.stringify(prop.key.value)}]`
89
+ }
90
+ else if (prop.computed && hoisted !== undefined) {
91
+ const keyVar = hoist(compileExpression(prop.key, running))
92
+ excludedKeys.push(`typeof ${keyVar} === 'symbol' ? ${keyVar} : String(${keyVar})`)
93
+ propSrc = `${src}[${keyVar}]`
94
+ }
95
+ else {
96
+ canOmit = false
97
+ }
98
+ if (propSrc !== undefined)
99
+ bind(prop.value, propSrc)
100
+ }
101
+ }
102
+
103
+ function bind(pat: Node, src: string): void {
104
+ if (pat.type === 'Identifier') {
105
+ reads.set(pat.name, src)
106
+ running.set(pat.name, src)
107
+ }
108
+ else if (pat.type === 'AssignmentPattern') {
109
+ bindDefault(pat, src)
110
+ }
111
+ else if (pat.type === 'ObjectPattern') {
112
+ bindObject(pat, src)
113
+ }
114
+ else if (pat.type === 'ArrayPattern') {
115
+ for (let i = 0; i < pat.elements.length; i++) {
116
+ const el = pat.elements[i]
117
+ if (el == null)
118
+ continue
119
+ if (el.type === 'RestElement')
120
+ bind(el.argument, `Array.from(${src}).slice(${i})`)
121
+ else
122
+ bind(el, `${src}[${i}]`)
123
+ }
124
+ }
125
+ }
126
+
127
+ return bind
128
+ }
129
+
130
+ // The source of a pattern node as a getter parameter: type annotations dropped, defaults and computed keys compiled.
131
+ function compilePatternSource(ctx: PatternContext, patNode: Node, outerRewrites: ReadonlyMap<string, string>): string {
132
+ const sub = new SourceEditor(ctx.code.slice(patNode.start, patNode.end))
133
+ const base = patNode.start
134
+ const patchPattern = (p: Node | null | undefined): void => {
135
+ if (p === null || p === undefined)
136
+ return
137
+ if ('typeAnnotation' in p && p.typeAnnotation != null) {
138
+ const ann = p.typeAnnotation as Node
139
+ sub.remove(ann.start - base, ann.end - base)
140
+ }
141
+ switch (p.type) {
142
+ case 'AssignmentPattern':
143
+ patchPattern(p.left)
144
+ sub.replace(p.right.start - base, p.right.end - base, ctx.compileExpression(p.right, outerRewrites))
145
+ return
146
+ case 'RestElement':
147
+ patchPattern(p.argument)
148
+ return
149
+ case 'ArrayPattern':
150
+ for (const el of p.elements)
151
+ patchPattern(el)
152
+ return
153
+ case 'ObjectPattern':
154
+ for (const prop of p.properties) {
155
+ if (prop.type === 'RestElement') {
156
+ patchPattern(prop.argument)
157
+ }
158
+ else {
159
+ if (prop.computed)
160
+ sub.replace(prop.key.start - base, prop.key.end - base, ctx.compileExpression(prop.key, outerRewrites))
161
+ patchPattern(prop.value)
162
+ }
163
+ }
164
+ }
165
+ }
166
+ patchPattern(patNode)
167
+ return sub.toString()
168
+ }
169
+
170
+ // The pattern a read runs: only the property binding `name`, so another property's default does not run on this read.
171
+ function patternFor(ctx: PatternContext, pattern: Node, name: string, outerRewrites: ReadonlyMap<string, string>): string {
172
+ if (pattern.type === 'ObjectPattern') {
173
+ for (const prop of (pattern as ObjectPattern).properties) {
174
+ const bound = new Set<string>()
175
+ collectPatternNames(prop.type === 'RestElement' ? prop.argument : prop.value, bound)
176
+ if (prop.type === 'Property' && bound.has(name)) {
177
+ const sub = new SourceEditor(ctx.code.slice(prop.start, prop.end))
178
+ const base = prop.start
179
+ if (prop.computed)
180
+ sub.replace(prop.key.start - base, prop.key.end - base, ctx.compileExpression(prop.key, outerRewrites))
181
+ sub.replace(prop.value.start - base, prop.value.end - base, compilePatternSource(ctx, prop.value, outerRewrites))
182
+ return `{ ${sub.toString()} }`
183
+ }
184
+ }
185
+ }
186
+ return compilePatternSource(ctx, pattern, outerRewrites)
187
+ }
188
+
189
+ // How each name a destructuring pattern binds is read from `source` on every access, so reads stay reactive.
190
+ // 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.
191
+ export function patternReads(
192
+ ctx: PatternContext,
193
+ pattern: Node,
194
+ source: string,
195
+ outerRewrites: ReadonlyMap<string, string>,
196
+ hoisted?: string[],
197
+ ): Map<string, string> {
198
+ const reads = new Map<string, string>()
199
+ const running = new Map(outerRewrites)
200
+ createBinder(ctx, reads, running, hoisted)(pattern, source)
201
+
202
+ const names = new Set<string>()
203
+ collectPatternNames(pattern, names)
204
+ for (const name of names) {
205
+ if (reads.has(name))
206
+ continue
207
+ const getter = `(${patternFor(ctx, pattern, name, outerRewrites)}) => ${name}`
208
+ reads.set(name, hoisted === undefined ? `(${getter})(${source})` : `${hoistInto(ctx, hoisted, getter)}(${source})`)
209
+ }
210
+ return reads
211
+ }