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
@@ -2,118 +2,20 @@
2
2
  // static attribute literal folding, compile-time static island props, and shared balanced hydration markers.
3
3
 
4
4
  import type {
5
- JSXChild,
6
5
  JSXElement,
7
6
  JSXFragment,
8
7
  Node,
9
8
  } from 'oxc-parser'
10
9
  import type { ModuleAnalysis } from './analyze'
11
- import type { SelectValueBinding } from './ssr-helpers'
12
- import type { PrunelleTagEmitter } from './ssr-prunelle-tags'
10
+ import type { SsrEnv } from './ssr-emit'
13
11
  import { analyzeModule, getExprContext, parseTsx } from './analyze'
14
12
  import { walk } from './ast'
15
13
  import { createDevSourceAttr } from './dev-source'
16
- import { hydrateMistake } from './mistakes'
14
+ import { runtimeAlias } from './emit'
17
15
  import { alignLines, lineMarker, SourceEditor } from './patch'
18
- import {
19
- containsJsx,
20
- decodeHtmlEntities,
21
- escapeRawText,
22
- escapeStaticText,
23
- filterMeaningfulChildren,
24
- isComponentTag,
25
- isJsxNode,
26
- jsxTagName,
27
- matchJsxMapCall,
28
- planChildSlots,
29
- RAW_TEXT_ELEMENTS,
30
- resolvePrunelleTag,
31
- unwrapParens,
32
- VOID_ELEMENTS,
33
- } from './shared'
34
- import {
35
- emitSsrElementAttrs,
36
- precomputeSsrSubtreeFlags,
37
- serializeComponentProps,
38
- staticLiteralOrTemplate,
39
- StringParts,
40
- } from './ssr-helpers'
41
- import { emitIsland } from './ssr-island'
42
- import { emitCatch, emitSuspense } from './ssr-prunelle-tags'
43
-
44
- const FORM_CONTROL_TAGS = new Set(['input', 'select', 'textarea'])
45
- const FORM_ATTR_BITS: Record<string, number> = {
46
- type: 1,
47
- required: 2,
48
- minlength: 4,
49
- maxlength: 8,
50
- min: 16,
51
- max: 32,
52
- step: 64,
53
- pattern: 128,
54
- }
55
-
56
- function findDynamicFormAction(node: JSXElement): Node | undefined {
57
- for (const attr of node.openingElement.attributes) {
58
- if (attr.type !== 'JSXAttribute' || jsxTagName(attr.name) !== 'action')
59
- continue
60
- if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
61
- return undefined
62
- const expr = attr.value.expression
63
- if (staticLiteralOrTemplate(expr).ok)
64
- return undefined
65
- if (expr.type === 'ConditionalExpression' && staticLiteralOrTemplate(expr.consequent).ok && staticLiteralOrTemplate(expr.alternate).ok)
66
- return undefined
67
- return expr
68
- }
69
- return undefined
70
- }
71
-
72
- function emitFormControlAttrs(
73
- node: JSXElement,
74
- tag: 'input' | 'select' | 'textarea',
75
- parts: StringParts,
76
- use: (name: string) => string,
77
- compileSubExpression: (node: Node) => string,
78
- ): void {
79
- const attrs = node.openingElement.attributes
80
- if (attrs.some(a => a.type === 'JSXSpreadAttribute'))
81
- return
82
- let nameExpr: string | undefined
83
- let typeExpr: string | undefined
84
- let present = 0
85
- for (const attr of attrs) {
86
- if (attr.type !== 'JSXAttribute')
87
- continue
88
- const attrName = jsxTagName(attr.name).toLowerCase()
89
- const bit = FORM_ATTR_BITS[attrName]
90
- if (bit !== undefined)
91
- present |= bit
92
- if (attrName === 'name') {
93
- if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
94
- nameExpr = JSON.stringify(attr.value.value)
95
- }
96
- else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
97
- const lit = staticLiteralOrTemplate(attr.value.expression)
98
- nameExpr = lit.ok && typeof lit.value === 'string' ? JSON.stringify(lit.value) : compileSubExpression(attr.value.expression)
99
- }
100
- }
101
- else if (tag === 'input' && attrName === 'type') {
102
- if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
103
- typeExpr = JSON.stringify(attr.value.value.toLowerCase())
104
- }
105
- else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
106
- const lit = staticLiteralOrTemplate(attr.value.expression)
107
- if (lit.ok && typeof lit.value === 'string')
108
- typeExpr = JSON.stringify(lit.value.toLowerCase())
109
- }
110
- }
111
- }
112
- if (nameExpr === undefined)
113
- return
114
- const typeArg = typeExpr !== undefined ? `, ${typeExpr}` : ''
115
- parts.pushExpr(`${use('ssrFormAttrs')}(${JSON.stringify(tag)}, ${nameExpr}, ${present}${typeArg})`)
116
- }
16
+ import { containsJsx, isJsxNode } from './shared'
17
+ import { precomputeSsrSubtreeFlags } from './ssr-helpers'
18
+ import { compileRootJsx } from './ssr-emit'
117
19
 
118
20
  export interface IslandBinding {
119
21
  id: string
@@ -136,57 +38,16 @@ export interface CompileResult {
136
38
  analysis: ModuleAnalysis
137
39
  }
138
40
 
139
- function emitActionFormExpr(
140
- formAction: Node,
141
- isAsyncForm: boolean,
142
- nextId: () => number,
143
- use: (name: string) => string,
144
- compileSubExpression: (node: Node) => string,
145
- emitBody: (bufVar: string, parts: StringParts, flush: () => void, pushStmt: (stmt: string) => void, override: { node: Node, ident: string }) => void,
146
- ): string {
147
- const faVar = `_fa${nextId()}`
148
- const innerBuf = `_o${nextId()}`
149
- const innerStmts: string[] = []
150
- const innerParts = new StringParts()
151
- const flushInner = () => {
152
- if (!innerParts.isEmpty()) {
153
- innerStmts.push(`${innerBuf} += ${innerParts.toExpr()};`)
154
- innerParts.clear()
155
- }
156
- }
157
- emitBody(innerBuf, innerParts, flushInner, s => innerStmts.push(s), { node: formAction, ident: faVar })
158
- if (innerStmts.length > 0)
159
- flushInner()
160
- const body = innerStmts.length === 0 ? innerParts.toExpr() : `{ let ${innerBuf} = ""; ${innerStmts.join(' ')} return ${innerBuf}; }`
161
- return isAsyncForm
162
- ? `await ${use('ssrFormAsync')}(${compileSubExpression(formAction)}, async (${faVar}) => ${body})`
163
- : `${use('ssrForm')}(${compileSubExpression(formAction)}, (${faVar}) => ${body})`
164
- }
165
-
166
41
  function markerTest(markers: NonNullable<CompileSsrOptions['emitMarkers']>): (offset: number) => boolean {
167
42
  return typeof markers === 'boolean' ? () => markers : offset => markers.some(([start, end]) => offset >= start && offset < end)
168
43
  }
169
44
 
170
- function flushStringParts(bufVar: string, parts: StringParts, stmts: string[]): void {
171
- if (!parts.isEmpty()) {
172
- stmts.push(`${bufVar} += ${parts.toExpr()};`)
173
- parts.clear()
174
- }
175
- }
176
-
177
- function isSingleLoopChild(meaningful: readonly JSXChild[], jsxNodes: WeakSet<Node>): boolean {
178
- return meaningful.length === 1
179
- && meaningful[0]!.type === 'JSXExpressionContainer'
180
- && meaningful[0]!.expression.type !== 'JSXEmptyExpression'
181
- && matchJsxMapCall(meaningful[0]!.expression, jsxNodes) !== undefined
182
- }
183
-
184
45
  function compileSsrSubExpression(
185
46
  code: string,
186
47
  node: Node,
187
48
  jsxNodes: WeakSet<Node>,
188
49
  mark: (offset: number) => string,
189
- compileRootJsx: (n: JSXElement | JSXFragment) => string,
50
+ compileRoot: (n: JSXElement | JSXFragment) => string,
190
51
  ): string {
191
52
  if (!containsJsx(node, jsxNodes))
192
53
  return mark(node.start) + code.slice(node.start, node.end)
@@ -194,7 +55,7 @@ function compileSsrSubExpression(
194
55
  const offset = node.start
195
56
  walk(node, (child) => {
196
57
  if (isJsxNode(child)) {
197
- sub.replace(child.start - offset, child.end - offset, compileRootJsx(child) + mark(child.end))
58
+ sub.replace(child.start - offset, child.end - offset, compileRoot(child) + mark(child.end))
198
59
  return false
199
60
  }
200
61
  return undefined
@@ -202,32 +63,6 @@ function compileSsrSubExpression(
202
63
  return mark(node.start) + sub.toString()
203
64
  }
204
65
 
205
- function compileSsrExprAsString(
206
- expr: Node,
207
- use: (name: string) => string,
208
- compileSubExpression: (node: Node) => string,
209
- compileJsxToStringExpr: (node: JSXElement | JSXFragment) => string,
210
- ): string {
211
- if (isJsxNode(expr))
212
- return compileJsxToStringExpr(expr)
213
- if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
214
- const right = unwrapParens(expr.right)
215
- if (isJsxNode(right))
216
- return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
217
- }
218
- if (expr.type === 'ConditionalExpression') {
219
- const consNode = unwrapParens(expr.consequent)
220
- const altNode = unwrapParens(expr.alternate)
221
- if (isJsxNode(consNode) || isJsxNode(altNode))
222
- return `((${compileSubExpression(expr.test)}) ? (${compileSsrExprAsString(consNode, use, compileSubExpression, compileJsxToStringExpr)}) : (${compileSsrExprAsString(altNode, use, compileSubExpression, compileJsxToStringExpr)}))`
223
- }
224
- return `${use('esc')}(${compileSubExpression(expr)})`
225
- }
226
-
227
- function pushLeadNlStatic(parts: StringParts, text: string): void {
228
- parts.pushStatic(text.startsWith('\n') || text.startsWith('\r') ? `\n${text}` : text)
229
- }
230
-
231
66
  function createIdCounter(code: string): () => number {
232
67
  const used = new Set<number>()
233
68
  for (const m of code.matchAll(/\b_[A-Za-z_]+(\d+)\b/g))
@@ -251,288 +86,40 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
251
86
  // Generated code keeps each expression on its source line: Bun maps a stack trace by the code this compiler hands it, not by a source map of its own.
252
87
  const mark = lineMarker(code)
253
88
  const used = new Set<string>()
254
- const nextId = createIdCounter(code)
255
- let activeSelectValue: SelectValueBinding | undefined
256
-
257
- const use = (name: string): string => {
258
- used.add(name)
259
- return `__${name}`
260
- }
261
-
262
- const islands = options.islands
263
- const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
264
- const markersAt = markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive)
89
+ const alias = runtimeAlias(code)
265
90
  const jsxNodes = analysis.jsxNodes
266
- const exprContext = getExprContext(analysis)
267
91
  const { directAwaitNodes, dynamicChildNodes } = precomputeSsrSubtreeFlags(program)
268
- const compileSubExpression = (node: Node): string => compileSsrSubExpression(code, node, jsxNodes, mark, compileRootJsx)
269
- const compileComponentRaw = (node: JSXElement, tag: string): string => {
270
- let out = ''
271
- emitComponent(node, tag, new StringParts(), (e) => { out = e })
272
- return out
273
- }
274
- const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, compileComponentRaw, markersAt, directAwaitNodes, jsxNodes }
275
-
276
- function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = markersAt(children[0]?.start ?? 0), inFragment = false, rawTextTag?: 'style' | 'script'): string {
277
- const bufVar = `_o${nextId()}`
278
- const stmts: string[] = []
279
- const parts = new StringParts()
280
- const flush = () => flushStringParts(bufVar, parts, stmts)
281
- emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), rawTextTag, slotMarkers, inFragment)
282
- if (stmts.length === 0)
283
- return parts.toExpr()
284
- flush()
285
- const hasAwait = children.some(c => directAwaitNodes.has(c))
286
- if (hasAwait)
287
- return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
288
- return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
289
- }
290
-
291
- // Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
292
- function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void, actionOverride?: { node: Node, ident: string }): void {
293
- if (node.type === 'JSXFragment') {
294
- emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, markersAt(node.start), true)
295
- return
296
- }
297
-
298
- const tag = jsxTagName(node.openingElement.name)
299
- if (isComponentTag(tag)) {
300
- emitComponent(node, tag, parts)
301
- return
302
- }
303
-
304
- if (tag === 'form' && actionOverride === undefined) {
305
- const formAction = findDynamicFormAction(node)
306
- if (formAction !== undefined) {
307
- parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), nextId, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
308
- return
309
- }
310
- }
311
-
312
- parts.pushStatic(`<${tag}${devSrc(node, tag)}`)
313
- const isTextarea = tag === 'textarea'
314
- const needsLeadNl = isTextarea || tag === 'pre'
315
- const compileAttrExpr = actionOverride !== undefined ? (n: Node) => (n === actionOverride.node ? actionOverride.ident : compileSubExpression(n)) : compileSubExpression
316
- const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId, use, compileSubExpression: compileAttrExpr })
317
- if (FORM_CONTROL_TAGS.has(tag))
318
- emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
319
- parts.pushStatic('>')
320
- if (VOID_ELEMENTS.has(tag))
321
- return
322
-
323
- const prevSelectValue = activeSelectValue
324
- if (tag === 'select')
325
- activeSelectValue = nextSelectValue
326
-
327
- try {
328
- if (innerHtmlExpr !== undefined)
329
- parts.pushExpr(needsLeadNl ? `${use('ssrLeadNl')}(${innerHtmlExpr})` : innerHtmlExpr)
330
- else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0)
331
- textareaValue.staticText !== undefined ? pushLeadNlStatic(parts, escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('ssrLeadNl')}(${use('esc')}(${textareaValue.expr}))`)
332
- else if (tag === 'style' || needsLeadNl) {
333
- const bodyExpr = tag === 'style' ? compileChildrenListToStringExpr(node.children, false, false, 'style') : compileChildrenListToStringExpr(node.children)
334
- if (bodyExpr !== '""')
335
- parts.pushExpr(`${use(tag === 'style' ? 'ssrStyleBlock' : 'ssrLeadNl')}(${bodyExpr})`)
336
- }
337
- else
338
- emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
339
- }
340
- finally {
341
- activeSelectValue = prevSelectValue
342
- }
343
- if (actionOverride === undefined)
344
- parts.pushStatic(`</${tag}>`)
345
- }
346
-
347
- function emitChildrenIntoBuffer(
348
- children: readonly JSXChild[],
349
- bufVar: string,
350
- parts: StringParts,
351
- flushParts: () => void,
352
- pushStmt: (stmt: string) => void,
353
- rawTextTag?: 'style' | 'script',
354
- slotMarkers = markersAt(children[0]?.start ?? 0),
355
- inFragment = false,
356
- ): void {
357
- const planned = planChildSlots(children, { jsxNodes, exprContext, emitMarkers: slotMarkers, inFragment })
358
-
359
- for (const { child, slot, open, close } of planned) {
360
- if (slot.kind === 'static-text') {
361
- if (rawTextTag !== undefined)
362
- parts.pushStatic(escapeRawText(slot.text, rawTextTag))
363
- else
364
- parts.pushStatic(escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text)))
365
- continue
366
- }
367
-
368
- if (rawTextTag !== undefined) {
369
- if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression') {
370
- const expr = child.expression
371
- if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0 && expr.quasis.length === 1) {
372
- const cooked = expr.quasis[0]?.value.cooked
373
- if (typeof cooked === 'string') {
374
- parts.pushStatic(escapeRawText(cooked, rawTextTag))
375
- continue
376
- }
377
- }
378
- parts.pushExpr(`${use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${compileSubExpression(expr)})`)
379
- continue
380
- }
381
- }
382
-
383
- if (slot.kind === 'element') {
384
- emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
385
- continue
386
- }
387
-
388
- if (open !== '')
389
- parts.pushStatic(open)
390
-
391
- if (slot.kind === 'component' || slot.kind === 'fragment') {
392
- emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
393
- }
394
- else if (slot.kind === 'loop') {
395
- const { match } = slot
396
- const itemParam = match.params[0]?.type === 'Identifier' ? match.params[0].name : undefined
397
- const idxParam = match.params[1]?.type === 'Identifier' ? match.params[1].name : undefined
398
-
399
- if (match.isJsxBody && itemParam !== undefined && match.params.length <= 2 && (match.params.length < 2 || idxParam !== undefined)) {
400
- flushParts()
401
- const n = nextId()
402
- const arrVar = `_a${n}`
403
- const idxVar = idxParam ?? `_i${n}`
404
- const innerStmts: string[] = []
405
- const innerParts = new StringParts()
406
- const flushInner = () => flushStringParts(bufVar, innerParts, innerStmts)
407
- emitIntoBuffer(match.body as JSXElement | JSXFragment, bufVar, innerParts, flushInner, s => innerStmts.push(s))
408
- flushInner()
409
-
410
- const target = compileSubExpression(match.target)
411
- pushStmt(
412
- `const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
413
- )
414
- }
415
- else if (match.isJsxBody) {
416
- const target = compileSubExpression(match.target)
417
- const params = match.params.map(p => compileSubExpression(p)).join(', ')
418
- parts.pushExpr(`${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(match.body as JSXElement | JSXFragment)})`)
419
- }
420
- else {
421
- parts.pushExpr(`${use('esc')}(${compileSubExpression(match.call)})`)
422
- }
423
- }
424
- else if (slot.kind === 'and-show') {
425
- const left = compileSubExpression(slot.expr.left)
426
- const right = compileJsxToStringExpr(slot.right)
427
- parts.pushExpr(`((${left}) ? (${right}) : "")`)
428
- }
429
- else if (slot.kind === 'ternary-show') {
430
- const test = compileSubExpression(slot.expr.test)
431
- const cons = compileExpressionAsString(slot.cons)
432
- const alt = compileExpressionAsString(slot.alt)
433
- parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
434
- }
435
- else {
436
- parts.pushExpr(`${use('esc')}(${compileSubExpression(slot.expr)})`)
437
- }
438
-
439
- if (close !== '')
440
- parts.pushStatic(close)
441
- }
442
- }
443
-
444
- const compileExpressionAsString = (expr: Node): string => compileSsrExprAsString(expr, use, compileSubExpression, compileJsxToStringExpr)
445
-
446
- function emitComponent(node: JSXElement, tag: string, parts: StringParts, onRaw?: (expr: string) => void): void {
447
- const { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate } = serializeComponentProps(node.openingElement.attributes, compileSubExpression)
448
- const childNodes = node.children
449
- const meaningfulChildren = filterMeaningfulChildren(childNodes)
450
- const hasChildren = meaningfulChildren.length > 0
451
- // The call sits on the line of its tag, so a component that throws names that line in the caller's frame.
452
- const call = `${mark(node.start)}${tag}`
453
-
454
- const prunelleTag = resolvePrunelleTag(tag, analysis.imports)
455
- if (prunelleTag === 'Suspense' || prunelleTag === 'Catch') {
456
- ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts, onRaw)
457
- return
458
- }
459
-
460
- const islandInfo = islands?.get(tag)
461
- if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
462
- throw hydrateMistake(tag, filename, true)
463
-
464
- const childrenHaveAwait = hasChildren && childNodes.some(c => directAwaitNodes.has(c))
465
- const childMarkers = islandInfo === undefined && markersAt(node.start)
466
- const onlyComp = onRaw !== undefined && islandInfo === undefined && meaningfulChildren.length === 1 && meaningfulChildren[0]!.type === 'JSXElement' && isComponentTag(jsxTagName(meaningfulChildren[0]!.openingElement.name)) ? meaningfulChildren[0]! : undefined
467
- const childExpr = onlyComp !== undefined
468
- ? compileComponentRaw(onlyComp, jsxTagName(onlyComp.openingElement.name))
469
- : hasChildren ? compileChildrenListToStringExpr(childNodes, childMarkers, childMarkers && (meaningfulChildren.length > 1 || isSingleLoopChild(meaningfulChildren, jsxNodes))) : '""'
470
-
471
- if (islandInfo !== undefined) {
472
- const target = onRaw !== undefined ? new StringParts() : parts
473
- emitIsland({ use, nextId, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
474
- if (onRaw !== undefined)
475
- onRaw(`${use('raw')}(${target.toExpr()})`)
476
- return
477
- }
478
-
479
- const emitOut = (expr: string): void => {
480
- if (onRaw !== undefined)
481
- onRaw(expr)
482
- else
483
- parts.pushExpr(`${use('ssrChild')}(${expr})`)
484
- }
485
- const wrappedChild = onlyComp !== undefined ? childExpr : `${use('raw')}(${childExpr})`
486
- const childrenHaveDynamic = hasChildren && childNodes.some(c => dynamicChildNodes.has(c))
487
-
488
- // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
489
- if (childrenHaveDynamic && !childrenHaveAwait) {
490
- const cVar = `_c${nextId()}`
491
- const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
492
- emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
493
- return
494
- }
495
-
496
- if (hasChildren)
497
- propEntries.push(`children: ${wrappedChild}`)
498
-
499
- const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
500
- emitOut(`${call}(${propsObj})`)
501
- }
502
-
503
- function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
504
- const bufVar = `_o${nextId()}`
505
- const stmts: string[] = []
506
- const parts = new StringParts()
507
-
508
- const flush = () => flushStringParts(bufVar, parts, stmts)
509
-
510
- emitIntoBuffer(node, bufVar, parts, flush, s => stmts.push(s))
511
-
512
- // If no inline `for` statements were emitted, stay a pure flat concatenation expression!
513
- if (stmts.length === 0)
514
- return parts.toExpr()
515
-
516
- flush()
517
- if (directAwaitNodes.has(node))
518
- return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
519
- return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
520
- }
521
92
 
522
- function compileRootJsx(node: JSXElement | JSXFragment): string {
523
- return `${use('raw')}(${compileJsxToStringExpr(node)})`
93
+ const env: SsrEnv = {
94
+ filename,
95
+ analysis,
96
+ islands: options.islands,
97
+ devSrc: createDevSourceAttr(filename, code, options.devSourceRoot),
98
+ markersAt: markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive),
99
+ jsxNodes,
100
+ exprContext: getExprContext(analysis),
101
+ directAwaitNodes,
102
+ dynamicChildNodes,
103
+ use: (name) => {
104
+ used.add(name)
105
+ return alias(name)
106
+ },
107
+ nextId: createIdCounter(code),
108
+ mark,
109
+ compileSubExpression: node => compileSsrSubExpression(code, node, jsxNodes, mark, n => compileRootJsx(env, n)),
110
+ activeSelectValue: undefined,
524
111
  }
525
112
 
526
113
  walk(program, (node) => {
527
114
  if (isJsxNode(node)) {
528
- editor.replace(node.start, node.end, compileRootJsx(node) + mark(node.end))
115
+ editor.replace(node.start, node.end, compileRootJsx(env, node) + mark(node.end))
529
116
  return false
530
117
  }
531
118
  return undefined
532
119
  })
533
120
 
534
121
  if (used.size > 0) {
535
- const specifiers = [...used].sort().map(name => `${name} as __${name}`).join(', ')
122
+ const specifiers = [...used].sort().map(name => `${name} as ${alias(name)}`).join(', ')
536
123
  // Last, where it moves no line: an import is hoisted wherever it is written.
537
124
  editor.append(`\nimport { ${specifiers} } from 'prunelle/internal/ssr';\n`)
538
125
  }
package/src/context.ts CHANGED
@@ -21,7 +21,7 @@ export interface ConsentGateProps {
21
21
  children?: PrunelleChild
22
22
  }
23
23
 
24
- /** The button and legend texts of `<ConsentBanner>` and `<ConsentPreferences>`, English by default. */
24
+ /** The button and legend texts of `<ConsentBanner>` and `<ConsentPreferences>`, French when `lang` is `fr` and English otherwise. */
25
25
  export interface ConsentTexts {
26
26
  accept?: string | undefined
27
27
  refuse?: string | undefined
@@ -43,6 +43,11 @@ export interface ConsentBannerProps extends ConsentTexts {
43
43
  choose?: string | undefined
44
44
  }
45
45
 
46
+ export interface CookieTableProps {
47
+ /** Caption of the table (default: `'Cookies this site sets'`, or its French when `lang` is `fr`). */
48
+ caption?: string | undefined
49
+ }
50
+
46
51
  export interface CatchProps {
47
52
  /** Rendered in place of `children` when they throw; a function gets the error and a `retry` that renders the children again (a no-op on the server). */
48
53
  fallback?: PrunelleChild | ((error: unknown, retry: () => void) => PrunelleChild)
@@ -54,9 +59,11 @@ export interface ServerContextBridge {
54
59
  consentGate(props: ConsentGateProps): PrunelleChild
55
60
  consentBanner(props: ConsentBannerProps): PrunelleChild
56
61
  consentPreferences(props: ConsentTexts): PrunelleChild
62
+ cookieTable(props: CookieTableProps): PrunelleChild
57
63
  getContext(key: symbol): { found: true, value: unknown } | undefined
58
64
  runWithContext<T>(key: symbol, value: unknown, fn: () => T): T
59
65
  nextId(): string | undefined
66
+ requestLocale?(): string | undefined
60
67
  head(props: { children?: PrunelleChild }): PrunelleChild
61
68
  suspense(props: { fallback?: PrunelleChild, error?: PrunelleChild | ((error: unknown) => PrunelleChild), children?: PrunelleChild | Promise<PrunelleChild> }): PrunelleChild
62
69
  catch(props: CatchProps): PrunelleChild | Promise<PrunelleChild>
@@ -119,6 +126,12 @@ export function ConsentPreferences(props: ConsentTexts): PrunelleChild {
119
126
  return bridge !== undefined ? bridge.consentPreferences(props) : null
120
127
  }
121
128
 
129
+ /** Every cookie the site sets, with its purpose, its consent category and how long it lives: prunelle's, each plugin's, and the app's, read from its `cookies.set` calls at build time. Server-only, 0 KB browser JS. */
130
+ export function CookieTable(props: CookieTableProps): PrunelleChild {
131
+ const bridge = getServerBridge()
132
+ return bridge !== undefined ? bridge.cookieTable(props) : null
133
+ }
134
+
122
135
  export interface Context<T> {
123
136
  readonly id: symbol
124
137
  readonly defaultValue: T
package/src/dev/child.ts CHANGED
@@ -26,5 +26,5 @@ if (import.meta.main) {
26
26
  process.on('disconnect', stop)
27
27
  process.on('SIGINT', stop)
28
28
  process.on('SIGTERM', stop)
29
- send({ t: 'ready', assetPrefix: srv.assetPrefix })
29
+ send({ t: 'ready', assetPrefix: srv.assetPrefix, allowedOrigins: srv.allowedOrigins })
30
30
  }
@@ -24,7 +24,8 @@ export function createDevHostCheck(hostname: string | undefined, origins: readon
24
24
  }
25
25
  return (request) => {
26
26
  const host = request.headers.get('host') ?? ''
27
- const name = hostnameOf(host)
27
+ // `localhost.` names the same host as `localhost`.
28
+ const name = hostnameOf(host)?.replace(/\.$/, '')
28
29
  if (name !== undefined && (LOOPBACK_NAMES.has(name) || name.endsWith('.localhost') || name.startsWith('[') || IPV4_RE.test(name) || names.has(name)))
29
30
  return undefined
30
31
  return new Response(`prunelle dev: refused Host "${name ?? host}": a dev server answers only localhost, an IP address, its --host and the hosts of site and trustedOrigins in prunelle.config.ts, so that a page on another domain cannot reach it by DNS rebinding. Add the origin you open it under to trustedOrigins.\n`, { status: 421, headers: { 'content-type': 'text/plain; charset=utf-8' } })
@@ -0,0 +1,71 @@
1
+ // prunelle dev's hot swap: after a rebuild, which islands of the open page get new code in place and which edits still reload it.
2
+
3
+ import type { BuildCache } from '../build/graph'
4
+ import type { BuildManifest } from '../build/manifest'
5
+
6
+ /** What each analysed source file read as, to tell which ones a rebuild changed. */
7
+ function sourceSnapshot(cache: BuildCache): Map<string, string> {
8
+ return new Map([...cache.analyses].map(([file, entry]) => [file, entry.code]))
9
+ }
10
+
11
+ function sameList(a: readonly string[] | undefined, b: readonly string[] | undefined): boolean {
12
+ return (a ?? []).join('\n') === (b ?? []).join('\n')
13
+ }
14
+
15
+ /**
16
+ * The island chunk URLs to swap, old to new, or `undefined` when the page must reload.
17
+ * Only the code of islands may have changed: the files this rebuild changed are island files with no `load()`, the scripts and styles every page loads are the same, and the same islands exist.
18
+ */
19
+ function hotIslandSwaps(prev: BuildManifest, next: BuildManifest, before: ReadonlyMap<string, string>, cache: BuildCache): Record<string, string> | undefined {
20
+ const keys = Object.keys(next.islands)
21
+ if (keys.length !== Object.keys(prev.islands).length || keys.some(key => prev.islands[key] === undefined))
22
+ return undefined
23
+ if (prev.runtimeScript !== next.runtimeScript || prev.regionScript !== next.regionScript || prev.reviveScript !== next.reviveScript)
24
+ return undefined
25
+ if (!sameList(prev.styles, next.styles) || !sameList(prev.globalStyles, next.globalStyles) || !sameList(prev.headTags, next.headTags))
26
+ return undefined
27
+ const swaps: Record<string, string> = {}
28
+ for (const key of keys) {
29
+ if (prev.islands[key] !== next.islands[key])
30
+ swaps[prev.islands[key]!] = next.islands[key]!
31
+ }
32
+ if (Object.keys(swaps).length === 0)
33
+ return undefined
34
+ const islandExports = new Map<string, Set<string>>()
35
+ for (const key of keys) {
36
+ const cut = key.lastIndexOf('#')
37
+ const file = key.slice(0, cut)
38
+ islandExports.set(file, (islandExports.get(file) ?? new Set()).add(key.slice(cut + 1)))
39
+ }
40
+ const files = new Set([...before.keys(), ...cache.analyses.keys()])
41
+ let changed = 0
42
+ for (const file of files) {
43
+ if (before.get(file) === cache.analyses.get(file)?.code)
44
+ continue
45
+ // A file that is no island, one that exports more than its islands (static markup of the page), or whose server side (`load()`) shows in the open page, cannot be told apart from a change to the static page.
46
+ const exported = islandExports.get(file)
47
+ const analysis = cache.analyses.get(file)?.analysis
48
+ if (exported === undefined || analysis?.hasLoadExport !== false || analysis.exportedNames.some(name => !exported.has(name)))
49
+ return undefined
50
+ changed++
51
+ }
52
+ return changed === 0 ? undefined : swaps
53
+ }
54
+
55
+ /** Remembers the last build's manifest and what each analysed file read as, so each rebuild can say which islands to swap. */
56
+ export function createHotSwaps(cache: BuildCache) {
57
+ let last: BuildManifest | undefined
58
+ let before = new Map<string, string>()
59
+ return {
60
+ /** Called before a rebuild reads the sources. */
61
+ start(): void {
62
+ before = sourceSnapshot(cache)
63
+ },
64
+ /** Called once the rebuild landed; `allowed` is false when the page must reload anyway. */
65
+ land(manifest: BuildManifest, allowed: boolean): Record<string, string> | undefined {
66
+ const swaps = allowed && last !== undefined ? hotIslandSwaps(last, manifest, before, cache) : undefined
67
+ last = manifest
68
+ return swaps
69
+ },
70
+ }
71
+ }