prunelle 0.1.1 → 0.7.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -90,23 +90,77 @@ function memberPropKey(node: Node): string | undefined {
90
90
  return undefined
91
91
  }
92
92
 
93
- function extractTypeLiteralPrimitives(typeNode: Node | null | undefined): { prims: Set<string>, primSignals: Set<string> } | undefined {
93
+ function extractTypeLiteralPrimitives(typeNode: Node | null | undefined): { prims: Set<string>, primSignals: Set<string>, arrayElemPrims: Map<string, Set<string>>, nestedPrims: Map<string, Set<string>> } | undefined {
94
94
  if (typeNode === null || typeNode === undefined || typeNode.type !== 'TSTypeLiteral')
95
95
  return undefined
96
96
  const prims = new Set<string>()
97
97
  const primSignals = new Set<string>()
98
+ const arrayElemPrims = new Map<string, Set<string>>()
99
+ const nestedPrims = new Map<string, Set<string>>()
98
100
  for (const m of typeNode.members) {
99
101
  if (m.type !== 'TSPropertySignature' || m.computed || m.typeAnnotation === null || m.typeAnnotation === undefined)
100
102
  continue
101
103
  const key = memberPropKey(m.key)
102
104
  if (key === undefined)
103
105
  continue
104
- if (isPrimitiveTypeNode(m.typeAnnotation.typeAnnotation))
106
+ const ann = m.typeAnnotation.typeAnnotation
107
+ if (isPrimitiveTypeNode(ann))
105
108
  prims.add(key)
106
- else if (isPrimitiveSignalTypeNode(m.typeAnnotation.typeAnnotation))
109
+ else if (isPrimitiveSignalTypeNode(ann))
107
110
  primSignals.add(key)
111
+ else if (ann.type === 'TSTypeLiteral') {
112
+ const nested = extractTypeLiteralPrimitives(ann)
113
+ if (nested !== undefined && nested.prims.size > 0)
114
+ nestedPrims.set(key, nested.prims)
115
+ }
116
+ else {
117
+ const elem = extractArrayElementPrimitives(ann)
118
+ if (elem !== undefined && elem.size > 0)
119
+ arrayElemPrims.set(key, elem)
120
+ }
108
121
  }
109
- return { prims, primSignals }
122
+ return { prims, primSignals, arrayElemPrims, nestedPrims }
123
+ }
124
+
125
+ function extractArrayElementPrimitives(typeNode: Node | null | undefined): Set<string> | undefined {
126
+ if (typeNode === null || typeNode === undefined)
127
+ return undefined
128
+ if (typeNode.type === 'TSParenthesizedType' || typeNode.type === 'TSTypeOperator')
129
+ return extractArrayElementPrimitives(typeNode.typeAnnotation)
130
+ if (typeNode.type === 'TSArrayType')
131
+ return extractTypeLiteralPrimitives(typeNode.elementType)?.prims
132
+ if (typeNode.type === 'TSTypeReference' && typeNode.typeName.type === 'Identifier') {
133
+ const name = typeNode.typeName.name
134
+ const params = typeNode.typeArguments?.params
135
+ if ((name === 'Array' || name === 'ReadonlyArray') && params !== undefined && params.length === 1)
136
+ return extractTypeLiteralPrimitives(params[0])?.prims
137
+ }
138
+ return undefined
139
+ }
140
+
141
+ function mapTargetArrayName(target: Node): string | undefined {
142
+ const cur = unwrapTsExpr(target)
143
+ if (cur.type === 'Identifier')
144
+ return cur.name
145
+ if (cur.type === 'MemberExpression' && !cur.computed && cur.object.type === 'Identifier' && cur.property.type === 'Identifier' && cur.property.name === 'value')
146
+ return cur.object.name
147
+ return undefined
148
+ }
149
+
150
+ function registerTypedParamKeys(
151
+ name: string,
152
+ keys: Set<string>,
153
+ primitivePropKeys: Map<string, Set<string>>,
154
+ ambiguousPropObjects: Set<string>,
155
+ ): void {
156
+ if (ambiguousPropObjects.has(name))
157
+ return
158
+ if (primitivePropKeys.has(name)) {
159
+ primitivePropKeys.delete(name)
160
+ ambiguousPropObjects.add(name)
161
+ return
162
+ }
163
+ primitivePropKeys.set(name, keys)
110
164
  }
111
165
 
112
166
  function rootIdentifierName(node: Node): string | undefined {
@@ -139,6 +193,78 @@ function isSignalCall(node: Node): { kind: 'signal' | 'computed', call: CallExpr
139
193
  return undefined
140
194
  }
141
195
 
196
+ function resolveDeferredInits(
197
+ deferredInits: readonly { name: string, init: Node, isSignal: boolean, signalKind?: 'signal' | 'computed' }[],
198
+ primCandidates: Set<string>,
199
+ sigCandidates: Set<string>,
200
+ nonPrimNames: ReadonlySet<string>,
201
+ nonSigNames: ReadonlySet<string>,
202
+ ctx: ExprContext,
203
+ ): void {
204
+ for (let pass = 0; pass < 2; pass++) {
205
+ for (const item of deferredInits) {
206
+ if (item.isSignal) {
207
+ if (nonSigNames.has(item.name))
208
+ continue
209
+ const call = item.init as CallExpression
210
+ const arg = call.arguments[0]
211
+ if (item.signalKind === 'signal' && arg !== undefined && arg.type !== 'SpreadElement' && isDefinitelyPrimitive(arg, ctx)) {
212
+ sigCandidates.add(item.name)
213
+ }
214
+ else if (item.signalKind === 'computed' && arg !== undefined && (arg.type === 'ArrowFunctionExpression' || arg.type === 'FunctionExpression')) {
215
+ if (arg.body !== null && arg.body.type !== 'BlockStatement' && isDefinitelyPrimitive(arg.body, ctx))
216
+ sigCandidates.add(item.name)
217
+ }
218
+ }
219
+ else if (!nonPrimNames.has(item.name) && isDefinitelyPrimitive(item.init, ctx)) {
220
+ primCandidates.add(item.name)
221
+ }
222
+ }
223
+ }
224
+ }
225
+
226
+ interface ParamTypeState {
227
+ primCandidates: Set<string>
228
+ nonPrimNames: Set<string>
229
+ sigCandidates: Set<string>
230
+ nonSigNames: Set<string>
231
+ primitivePropKeys: Map<string, Set<string>>
232
+ ambiguousPropObjects: Set<string>
233
+ arrayElemPrimKeys: Map<string, Set<string>>
234
+ markNonPrim: (pat: Node | null | undefined) => void
235
+ }
236
+
237
+ function recordObjectPatternTypes(pat: ObjectPattern, typeNode: Node | null | undefined, state: ParamTypeState): void {
238
+ const info = extractTypeLiteralPrimitives(typeNode)
239
+ for (const prop of pat.properties) {
240
+ if (prop.type === 'RestElement') {
241
+ state.markNonPrim(prop.argument)
242
+ continue
243
+ }
244
+ const key = !prop.computed ? memberPropKey(prop.key) : undefined
245
+ const val = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value
246
+ if (val.type === 'Identifier' && key !== undefined && info !== undefined) {
247
+ if (info.prims.has(key)) {
248
+ state.primCandidates.add(val.name)
249
+ state.nonSigNames.add(val.name)
250
+ continue
251
+ }
252
+ if (info.primSignals.has(key)) {
253
+ state.sigCandidates.add(val.name)
254
+ state.nonPrimNames.add(val.name)
255
+ continue
256
+ }
257
+ const elemPrims = info.arrayElemPrims.get(key)
258
+ if (elemPrims !== undefined)
259
+ state.arrayElemPrimKeys.set(val.name, elemPrims)
260
+ const nested = info.nestedPrims.get(key)
261
+ if (nested !== undefined)
262
+ registerTypedParamKeys(val.name, nested, state.primitivePropKeys, state.ambiguousPropObjects)
263
+ }
264
+ state.markNonPrim(val)
265
+ }
266
+ }
267
+
142
268
  /**
143
269
  * File-level static primitive/JSX binding analysis shared identically by SSR and DOM compilers
144
270
  * so `planChildSlots` chooses matching `setText` vs `insert` slots and markers on both targets.
@@ -150,6 +276,8 @@ export function createExprContext(program: Program, jsxNodes: WeakSet<Node>): Ex
150
276
  const nonSigNames = new Set<string>()
151
277
  const propsParams = new Set<string>()
152
278
  const primitivePropKeys = new Map<string, Set<string>>()
279
+ const ambiguousPropObjects = new Set<string>()
280
+ const arrayElemPrimKeys = new Map<string, Set<string>>()
153
281
  const jsxVars = new Set<string>()
154
282
  const deferredInits: { name: string, init: Node, isSignal: boolean, signalKind?: 'signal' | 'computed' }[] = []
155
283
 
@@ -160,35 +288,21 @@ export function createExprContext(program: Program, jsxNodes: WeakSet<Node>): Ex
160
288
  collectPatternNames(pat, nonSigNames)
161
289
  }
162
290
 
163
- const recordObjectPatternTypes = (pat: ObjectPattern, typeNode: Node | null | undefined): void => {
164
- const info = extractTypeLiteralPrimitives(typeNode)
165
- for (const prop of pat.properties) {
166
- if (prop.type === 'RestElement') {
167
- markNonPrim(prop.argument)
168
- continue
169
- }
170
- const key = !prop.computed ? memberPropKey(prop.key) : undefined
171
- const val = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value
172
- if (val.type === 'Identifier' && key !== undefined && info !== undefined) {
173
- if (info.prims.has(key)) {
174
- primCandidates.add(val.name)
175
- nonSigNames.add(val.name)
176
- continue
177
- }
178
- if (info.primSignals.has(key)) {
179
- sigCandidates.add(val.name)
180
- nonPrimNames.add(val.name)
181
- continue
182
- }
183
- }
184
- markNonPrim(val)
185
- }
291
+ const paramState: ParamTypeState = {
292
+ primCandidates,
293
+ nonPrimNames,
294
+ sigCandidates,
295
+ nonSigNames,
296
+ primitivePropKeys,
297
+ ambiguousPropObjects,
298
+ arrayElemPrimKeys,
299
+ markNonPrim,
186
300
  }
187
301
 
188
302
  const recordParam = (param: ParamPattern, isComponentFirstParam: boolean, isMapIndexParam: boolean): void => {
189
303
  const inner = param.type === 'AssignmentPattern' ? param.left : param
190
304
  if (inner.type === 'ObjectPattern') {
191
- recordObjectPatternTypes(inner, inner.typeAnnotation?.typeAnnotation)
305
+ recordObjectPatternTypes(inner, inner.typeAnnotation?.typeAnnotation, paramState)
192
306
  return
193
307
  }
194
308
  if (inner.type === 'Identifier') {
@@ -203,21 +317,30 @@ export function createExprContext(program: Program, jsxNodes: WeakSet<Node>): Ex
203
317
  nonPrimNames.add(inner.name)
204
318
  return
205
319
  }
206
- if (isComponentFirstParam) {
320
+ if (isComponentFirstParam)
207
321
  propsParams.add(inner.name)
208
- const info = extractTypeLiteralPrimitives(ann)
209
- if (info !== undefined && !primitivePropKeys.has(inner.name))
210
- primitivePropKeys.set(inner.name, info.prims)
211
- }
322
+ const info = extractTypeLiteralPrimitives(ann)
323
+ if (info !== undefined)
324
+ registerTypedParamKeys(inner.name, info.prims, primitivePropKeys, ambiguousPropObjects)
325
+ const elemPrims = extractArrayElementPrimitives(ann)
326
+ if (elemPrims !== undefined)
327
+ arrayElemPrimKeys.set(inner.name, elemPrims)
212
328
  }
213
329
  markNonPrim(inner)
214
330
  }
215
331
 
216
332
  const mapCallbacks = new WeakSet<Node>()
333
+ const mapItemTargets: { targetName: string, paramName: string }[] = []
217
334
  walk(program, (node) => {
218
335
  const mapMatch = matchJsxMapCall(node, jsxNodes)
219
- if (mapMatch !== undefined)
336
+ if (mapMatch !== undefined) {
220
337
  mapCallbacks.add(mapMatch.cb)
338
+ const targetName = mapTargetArrayName(mapMatch.target)
339
+ const first = mapMatch.params[0]
340
+ const paramName = first?.type === 'Identifier' ? first.name : undefined
341
+ if (targetName !== undefined && paramName !== undefined)
342
+ mapItemTargets.push({ targetName, paramName })
343
+ }
221
344
  })
222
345
 
223
346
  walk(program, (node) => {
@@ -296,6 +419,12 @@ export function createExprContext(program: Program, jsxNodes: WeakSet<Node>): Ex
296
419
  }
297
420
  })
298
421
 
422
+ for (const { targetName, paramName } of mapItemTargets) {
423
+ const elemPrims = arrayElemPrimKeys.get(targetName)
424
+ if (elemPrims !== undefined)
425
+ registerTypedParamKeys(paramName, elemPrims, primitivePropKeys, ambiguousPropObjects)
426
+ }
427
+
299
428
  for (const n of nonPrimNames)
300
429
  primCandidates.delete(n)
301
430
  for (const n of nonSigNames)
@@ -309,26 +438,7 @@ export function createExprContext(program: Program, jsxNodes: WeakSet<Node>): Ex
309
438
  jsxVars,
310
439
  }
311
440
 
312
- for (let pass = 0; pass < 2; pass++) {
313
- for (const item of deferredInits) {
314
- if (item.isSignal) {
315
- if (nonSigNames.has(item.name))
316
- continue
317
- const call = item.init as CallExpression
318
- const arg = call.arguments[0]
319
- if (item.signalKind === 'signal' && arg !== undefined && arg.type !== 'SpreadElement' && isDefinitelyPrimitive(arg, ctx)) {
320
- sigCandidates.add(item.name)
321
- }
322
- else if (item.signalKind === 'computed' && arg !== undefined && (arg.type === 'ArrowFunctionExpression' || arg.type === 'FunctionExpression')) {
323
- if (arg.body !== null && arg.body.type !== 'BlockStatement' && isDefinitelyPrimitive(arg.body, ctx))
324
- sigCandidates.add(item.name)
325
- }
326
- }
327
- else if (!nonPrimNames.has(item.name) && isDefinitelyPrimitive(item.init, ctx)) {
328
- primCandidates.add(item.name)
329
- }
330
- }
331
- }
441
+ resolveDeferredInits(deferredInits, primCandidates, sigCandidates, nonPrimNames, nonSigNames, ctx)
332
442
 
333
443
  for (const n of nonPrimNames)
334
444
  primCandidates.delete(n)
@@ -378,9 +488,9 @@ export function isDefinitelyPrimitive(node: Node, ctx?: ExprContext): boolean {
378
488
  const root = rootIdentifierName(cur.object)
379
489
  if (root !== undefined && ctx?.jsxVars.has(root) === true)
380
490
  return false
381
- if (cur.object.type === 'Identifier' && ctx?.propsParams.has(cur.object.name) === true)
382
- return ctx.primitivePropKeys.get(cur.object.name)?.has(prop) === true
383
- return true
491
+ if (cur.object.type === 'Identifier' && ctx?.primitivePropKeys.get(cur.object.name)?.has(prop) === true)
492
+ return true
493
+ return false
384
494
  }
385
495
  return false
386
496
  }
@@ -0,0 +1,88 @@
1
+ // Refuses a reactive primitive imported from another framework, with the prunelle name to write instead.
2
+
3
+ import { mistake } from './mistakes'
4
+
5
+ const REACT: Record<string, string> = {
6
+ useState: 'signal() from \'prunelle\' (count.value reads and writes it)',
7
+ useReducer: 'signal() from \'prunelle\' and a plain function that sets .value',
8
+ useEffect: 'effect() or onMount() from \'prunelle\'',
9
+ useLayoutEffect: 'effect() or onMount() from \'prunelle\'',
10
+ useMemo: 'computed() from \'prunelle\'',
11
+ useCallback: 'a plain function: a component runs once, so nothing is recreated',
12
+ useRef: 'a ref={el => ...} callback on the element, or a plain variable',
13
+ memo: 'nothing: a component runs once, so there is no re-render to skip',
14
+ useId: 'useId from \'prunelle\'',
15
+ useContext: 'useContext from \'prunelle\'',
16
+ createContext: 'createContext from \'prunelle\'',
17
+ Suspense: 'Suspense from \'prunelle\'',
18
+ Fragment: '<>...</>, which needs no import',
19
+ createRoot: 'nothing: prunelle hydrates islands itself',
20
+ hydrateRoot: 'nothing: prunelle hydrates islands itself',
21
+ render: 'nothing: prunelle renders pages and hydrates islands itself',
22
+ }
23
+
24
+ const SOLID: Record<string, string> = {
25
+ createSignal: 'signal() from \'prunelle\'',
26
+ createMemo: 'computed() from \'prunelle\'',
27
+ createEffect: 'effect() from \'prunelle\'',
28
+ createRenderEffect: 'effect() from \'prunelle\'',
29
+ createComputed: 'computed() from \'prunelle\'',
30
+ createRoot: 'root() from \'prunelle\'',
31
+ createSelector: 'selector() from \'prunelle\'',
32
+ createStore: 'store() from \'prunelle\'',
33
+ createContext: 'createContext from \'prunelle\'',
34
+ useContext: 'useContext from \'prunelle\'',
35
+ createUniqueId: 'useId from \'prunelle\'',
36
+ batch: 'batch from \'prunelle\'',
37
+ untrack: 'untrack from \'prunelle\'',
38
+ onMount: 'onMount from \'prunelle\'',
39
+ onCleanup: 'onCleanup from \'prunelle\'',
40
+ Show: 'a ternary or && in the JSX',
41
+ For: 'items.map(item => ...) in the JSX',
42
+ Index: 'items.map(item => ...) in the JSX',
43
+ Suspense: 'Suspense from \'prunelle\'',
44
+ }
45
+
46
+ const VUE: Record<string, string> = {
47
+ ref: 'signal() from \'prunelle\'',
48
+ shallowRef: 'signal() from \'prunelle\'',
49
+ reactive: 'store() from \'prunelle\'',
50
+ computed: 'computed from \'prunelle\'',
51
+ watch: 'effect() from \'prunelle\'',
52
+ watchEffect: 'effect() from \'prunelle\'',
53
+ onMounted: 'onMount() from \'prunelle\'',
54
+ onUnmounted: 'onCleanup() from \'prunelle\'',
55
+ provide: 'provideContext from \'prunelle\'',
56
+ inject: 'useContext from \'prunelle\'',
57
+ }
58
+
59
+ const SVELTE: Record<string, string> = {
60
+ onMount: 'onMount from \'prunelle\'',
61
+ onDestroy: 'onCleanup from \'prunelle\'',
62
+ writable: 'signal() from \'prunelle\'',
63
+ readable: 'signal() from \'prunelle\'',
64
+ derived: 'computed() from \'prunelle\'',
65
+ setContext: 'provideContext from \'prunelle\'',
66
+ getContext: 'useContext from \'prunelle\'',
67
+ }
68
+
69
+ const FOREIGN = new Map<string, Record<string, string>>([
70
+ ['react', REACT],
71
+ ['preact', REACT],
72
+ ['preact/hooks', REACT],
73
+ ['preact/compat', REACT],
74
+ ['react-dom', REACT],
75
+ ['react-dom/client', REACT],
76
+ ['solid-js', SOLID],
77
+ ['solid-js/store', SOLID],
78
+ ['vue', VUE],
79
+ ['svelte', SVELTE],
80
+ ['svelte/store', SVELTE],
81
+ ])
82
+
83
+ /** Throws on a name a React, Solid, Vue or Svelte app imports for what prunelle spells differently, naming the prunelle form. */
84
+ export function assertNoForeignImport(source: string, imported: string, filename: string): void {
85
+ const table = FOREIGN.get(source)
86
+ if (table !== undefined && Object.hasOwn(table, imported))
87
+ throw mistake(`import { ${imported} } from '${source}'`, filename, `prunelle has no ${source}; write ${table[imported]}`)
88
+ }
@@ -66,6 +66,13 @@ 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
+ /** `$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
+ export function hydrateMistake(tag: string, filename: string, component: boolean): PrunelleMistake {
71
+ return mistake(`$hydrate on <${tag}>`, filename, component
72
+ ? `${tag} is not an island, so it never hydrates; drop $hydrate, or give ${tag} state or handlers`
73
+ : 'only components can be islands; drop $hydrate, or move it onto a component tag')
74
+ }
75
+
69
76
  let collected: PrunelleMistake[] | undefined
70
77
 
71
78
  /** Runs one check, a mistake it throws placed at `start`. The build stops at the first mistake; while `collectMistakes` runs, the mistake is recorded and the caller goes on. */
@@ -112,6 +119,13 @@ export function serverOnlyTagError(filename: string, { tag, island, reason, offs
112
119
  return err
113
120
  }
114
121
 
122
+ /** The error for an Astro `---` block opening a file, at the first dash. */
123
+ 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')
125
+ err.start = start
126
+ return err
127
+ }
128
+
115
129
  const KAY_SOURCE_RE = /^@kayjs\/(kay(?=\/|$))?/
116
130
 
117
131
  /** Refuses an import of kay, the name prunelle had before: the app would load both. */
@@ -289,7 +303,7 @@ function checkElementAttribute(attr: JSXAttribute, tag: string, isCustomElement:
289
303
  return
290
304
  const name = attr.name.name
291
305
  if (name === '$hydrate')
292
- throw mistake(`$hydrate on <${tag}>`, filename, 'only components can be islands; drop $hydrate, or move it onto a component tag')
306
+ throw hydrateMistake(tag, filename, false)
293
307
  if (name.toLowerCase() === 'srcdoc')
294
308
  throw mistake(`${name} on <${tag}>`, filename, 'prunelle blocks srcdoc for XSS safety; serve the document from a route and load it with src')
295
309
  if (name === 'dangerouslySetInnerHTML')
@@ -373,6 +387,10 @@ export function checkMistakes(
373
387
  const canonical = resolveTag(tag)
374
388
  const isElement = tag !== '' && !isComponentTag(tag)
375
389
  const isCustomElement = tag.includes('-')
390
+ if (tag === 'slot') {
391
+ 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') })
393
+ }
376
394
  if (canonical === 'Suspense') {
377
395
  const children = filterMeaningfulChildren(element.children).length
378
396
  if (children > 1)
@@ -382,8 +400,11 @@ export function checkMistakes(
382
400
  guarded(element.start, () => checkRegionMarkup(tag, canonical, isElement, attributes, filename, element, resolveTag))
383
401
  if (isElement)
384
402
  guarded(element.start, () => checkKeepScroll(element, attributes, filename))
385
- if (isElement && VOID_ELEMENTS.has(tag) && (filterMeaningfulChildren(element.children).length > 0 || staticAttr(attributes, 'children') !== undefined))
403
+ const childrenAttr = isElement ? staticAttr(attributes, 'children') : undefined
404
+ if (isElement && VOID_ELEMENTS.has(tag) && (filterMeaningfulChildren(element.children).length > 0 || childrenAttr !== undefined))
386
405
  guarded(element.start, () => { throw mistake(`<${tag}> with children`, filename, `a void element has no content; write <${tag} />`) })
406
+ else if (childrenAttr !== undefined)
407
+ guarded(childrenAttr.start, () => { throw mistake(`children attribute on <${tag}>`, filename, `pass children between tags, <${tag}>...</${tag}>`) })
387
408
  const className = isElement && staticAttr(attributes, 'class') !== undefined ? staticAttr(attributes, 'className') : undefined
388
409
  if (className !== undefined)
389
410
  guarded(className.start, () => { throw mistake('class and className', filename, 'keep one, they set the same attribute') })
@@ -0,0 +1,52 @@
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.
2
+
3
+ import type { Function as FunctionNode, Node, Program } from 'oxc-parser'
4
+ import type { BindingFacts } from './interactivity'
5
+ import type { CompilerWarning } from './mistakes'
6
+ import { unwrapTsExpr } from './shared'
7
+
8
+ function isFunction(node: Node | null | undefined): node is FunctionNode {
9
+ return node !== null && node !== undefined && (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression')
10
+ }
11
+
12
+ // The functions a top-level statement declares: `function C`, `export default function`, `const C = () => ...`.
13
+ function declaredFunctions(stmt: Node): FunctionNode[] {
14
+ const decl = stmt.type === 'ExportNamedDeclaration' || stmt.type === 'ExportDefaultDeclaration' ? stmt.declaration : stmt
15
+ if (decl === null || decl === undefined)
16
+ return []
17
+ if (isFunction(decl))
18
+ return [decl]
19
+ if (decl.type !== 'VariableDeclaration')
20
+ return []
21
+ const found: FunctionNode[] = []
22
+ for (const d of decl.declarations) {
23
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
24
+ if (isFunction(init))
25
+ found.push(init)
26
+ }
27
+ return found
28
+ }
29
+
30
+ /** Warns on a top-level statement of a browser component's body that destructures its first parameter, with the parameter form as the fix. */
31
+ export function checkBodyPropsDestructure(program: Program, code: string, bindings: readonly BindingFacts[], filename: string, warnings: CompilerWarning[]): void {
32
+ const inBrowser = bindings.filter(b => b.fact !== undefined)
33
+ for (const stmt of program.body) {
34
+ if (!inBrowser.some(b => b.start >= stmt.start && b.end <= stmt.end))
35
+ continue
36
+ for (const fn of declaredFunctions(stmt)) {
37
+ const param = fn.params[0]
38
+ if (param?.type !== 'Identifier' || fn.body?.type !== 'BlockStatement')
39
+ continue
40
+ for (const inner of fn.body.body) {
41
+ if (inner.type !== 'VariableDeclaration')
42
+ continue
43
+ for (const d of inner.declarations) {
44
+ const init = d.init === null ? undefined : unwrapTsExpr(d.init)
45
+ if (d.id.type !== 'ObjectPattern' || init?.type !== 'Identifier' || init.name !== param.name)
46
+ continue
47
+ 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.` })
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }
@@ -1,10 +1,92 @@
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
5
  import { SourceEditor } from './patch'
5
- import { collectMutatedNames, isSafeLazyJsxRef } from './scope'
6
+ import { collectMutatedNames, isSafeLazyJsxRef, referencesAny } from './scope'
6
7
  import { collectPatternNames, containsJsx, isJsxNode, unwrapParens, unwrapTsExpr } from './shared'
7
8
 
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
+ function patchParamDefaults(
28
+ param: Node | null | undefined,
29
+ rewrites: ReadonlyMap<string, string>,
30
+ targetEditor: SourceEditor,
31
+ offset: number,
32
+ compileExpression: (node: Node, rewrites: ReadonlyMap<string, string>) => string,
33
+ ): void {
34
+ if (param === null || param === undefined)
35
+ return
36
+ switch (param.type) {
37
+ case 'AssignmentPattern':
38
+ patchParamDefaults(param.left, rewrites, targetEditor, offset, compileExpression)
39
+ targetEditor.replace(param.right.start - offset, param.right.end - offset, compileExpression(param.right, rewrites))
40
+ return
41
+ case 'RestElement':
42
+ patchParamDefaults(param.argument, rewrites, targetEditor, offset, compileExpression)
43
+ return
44
+ case 'TSParameterProperty':
45
+ patchParamDefaults(param.parameter, rewrites, targetEditor, offset, compileExpression)
46
+ return
47
+ case 'ArrayPattern': {
48
+ let cur = rewrites
49
+ for (const el of param.elements) {
50
+ patchParamDefaults(el, cur, targetEditor, offset, compileExpression)
51
+ if (el !== null)
52
+ cur = withoutBindings(cur, [el])
53
+ }
54
+ return
55
+ }
56
+ case 'ObjectPattern': {
57
+ let cur = rewrites
58
+ for (const prop of param.properties) {
59
+ if (prop.type === 'RestElement') {
60
+ patchParamDefaults(prop.argument, cur, targetEditor, offset, compileExpression)
61
+ }
62
+ else {
63
+ if (prop.computed)
64
+ targetEditor.replace(prop.key.start - offset, prop.key.end - offset, compileExpression(prop.key, cur))
65
+ patchParamDefaults(prop.value, cur, targetEditor, offset, compileExpression)
66
+ }
67
+ cur = withoutBindings(cur, [prop])
68
+ }
69
+ }
70
+ }
71
+ }
72
+
73
+ export function compileParamList(
74
+ code: string,
75
+ params: readonly ParamPattern[],
76
+ scopeRewrites: ReadonlyMap<string, string>,
77
+ compileExpression: (node: Node, rewrites: ReadonlyMap<string, string>) => string,
78
+ ): string {
79
+ let cur = scopeRewrites
80
+ const out: string[] = []
81
+ for (const p of params) {
82
+ const sub = new SourceEditor(code.slice(p.start, p.end))
83
+ patchParamDefaults(p, cur, sub, p.start, compileExpression)
84
+ out.push(sub.toString())
85
+ cur = withoutBindings(cur, [p])
86
+ }
87
+ return out.join(', ')
88
+ }
89
+
8
90
  export function withoutBindings(rewrites: ReadonlyMap<string, string>, patterns: readonly Node[]): Map<string, string> {
9
91
  const names = new Set<string>()
10
92
  for (const pattern of patterns)
@@ -101,8 +183,9 @@ export function createPropCompiler(ctx: PropCompilerContext): PropCompiler {
101
183
  if (pat.type === 'AssignmentPattern') {
102
184
  const defExpr = compileExpression(pat.right, running)
103
185
  const simpleDef = pat.right.type === 'Literal' || pat.right.type === 'Identifier'
186
+ const reactiveDef = !simpleDef && !containsJsx(pat.right, jsxNodes) && isReactiveDefault(pat.right, running)
104
187
  let fallback = simpleDef ? defExpr : `(${defExpr})`
105
- if (!simpleDef && hoisted !== undefined)
188
+ if (!simpleDef && !reactiveDef && hoisted !== undefined)
106
189
  fallback = `${hoist(`${use('propDefault')}(() => (${defExpr}), ${src} === undefined)`)}()`
107
190
  let nextSrc: string
108
191
  if (pat.left.type !== 'Identifier' && hoisted !== undefined) {
@@ -252,38 +335,6 @@ export function createPropCompiler(ctx: PropCompilerContext): PropCompiler {
252
335
  return undefined
253
336
  }
254
337
 
255
- function patchParamDefaults(param: Node | null | undefined, rewrites: ReadonlyMap<string, string>, targetEditor: SourceEditor, offset: number): void {
256
- if (param === null || param === undefined)
257
- return
258
- switch (param.type) {
259
- case 'AssignmentPattern':
260
- patchParamDefaults(param.left, rewrites, targetEditor, offset)
261
- targetEditor.replace(param.right.start - offset, param.right.end - offset, compileExpression(param.right, rewrites))
262
- return
263
- case 'RestElement':
264
- patchParamDefaults(param.argument, rewrites, targetEditor, offset)
265
- return
266
- case 'TSParameterProperty':
267
- patchParamDefaults(param.parameter, rewrites, targetEditor, offset)
268
- return
269
- case 'ArrayPattern':
270
- for (const el of param.elements)
271
- patchParamDefaults(el, rewrites, targetEditor, offset)
272
- return
273
- case 'ObjectPattern':
274
- for (const prop of param.properties) {
275
- if (prop.type === 'RestElement') {
276
- patchParamDefaults(prop.argument, rewrites, targetEditor, offset)
277
- }
278
- else {
279
- if (prop.computed)
280
- targetEditor.replace(prop.key.start - offset, prop.key.end - offset, compileExpression(prop.key, rewrites))
281
- patchParamDefaults(prop.value, rewrites, targetEditor, offset)
282
- }
283
- }
284
- }
285
- }
286
-
287
338
  function computePropRewrites(
288
339
  destructured: { pattern: ObjectPattern, defaultExpr: Node | undefined },
289
340
  pVar: string,
@@ -335,7 +386,7 @@ export function createPropCompiler(ctx: PropCompilerContext): PropCompiler {
335
386
 
336
387
  for (let i = 1; i < fn.params.length; i++) {
337
388
  const extraParam = fn.params[i]!
338
- patchParamDefaults(extraParam, propRewrites, fnEditor, offset)
389
+ patchParamDefaults(extraParam, propRewrites, fnEditor, offset, compileExpression)
339
390
  propRewrites = withoutBindings(propRewrites, [extraParam])
340
391
  }
341
392
 
@@ -364,7 +415,7 @@ export function createPropCompiler(ctx: PropCompilerContext): PropCompiler {
364
415
 
365
416
  for (let i = 1; i < fn.params.length; i++) {
366
417
  const extraParam = fn.params[i]!
367
- patchParamDefaults(extraParam, propRewrites, editor, 0)
418
+ patchParamDefaults(extraParam, propRewrites, editor, 0, compileExpression)
368
419
  propRewrites = withoutBindings(propRewrites, [extraParam])
369
420
  }
370
421