prunelle 0.0.0-stage → 0.5.2

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 (200) hide show
  1. package/llms.txt +152 -0
  2. package/package.json +59 -4
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/ambient.d.ts +6 -0
  7. package/src/attrs.ts +43 -0
  8. package/src/build/bundle.ts +657 -0
  9. package/src/build/carry.ts +57 -0
  10. package/src/build/client-entries.ts +107 -0
  11. package/src/build/client-plugin.ts +173 -0
  12. package/src/build/client-prune.ts +168 -0
  13. package/src/build/compile.ts +129 -0
  14. package/src/build/ecoindex.ts +229 -0
  15. package/src/build/files.ts +156 -0
  16. package/src/build/first-load.ts +164 -0
  17. package/src/build/graph.ts +247 -0
  18. package/src/build/index.ts +641 -0
  19. package/src/build/is-inside.ts +12 -0
  20. package/src/build/islands.ts +641 -0
  21. package/src/build/manifest.ts +325 -0
  22. package/src/build/output.ts +84 -0
  23. package/src/build/plugin-host.ts +278 -0
  24. package/src/build/precompress.ts +139 -0
  25. package/src/build/prerender.ts +232 -0
  26. package/src/build/render-rules.ts +205 -0
  27. package/src/build/report.ts +268 -0
  28. package/src/build/resolve.ts +52 -0
  29. package/src/build/routes.ts +342 -0
  30. package/src/build/server-entry.ts +38 -0
  31. package/src/build/static.ts +207 -0
  32. package/src/build/status-pages.ts +127 -0
  33. package/src/build/style-bundles.ts +526 -0
  34. package/src/cli/check-forms.ts +654 -0
  35. package/src/cli/check-links.ts +619 -0
  36. package/src/cli/check.ts +381 -0
  37. package/src/cli/commands.ts +345 -0
  38. package/src/cli/docs.ts +402 -0
  39. package/src/cli/index.ts +70 -0
  40. package/src/cli/inspect.ts +345 -0
  41. package/src/cli/mcp-tools.ts +480 -0
  42. package/src/cli/mcp.ts +205 -0
  43. package/src/cli/new.ts +41 -0
  44. package/src/cli/render.ts +261 -0
  45. package/src/cli/upgrade-names.ts +209 -0
  46. package/src/cli/upgrade.ts +354 -0
  47. package/src/compiler/analyze.ts +632 -0
  48. package/src/compiler/ast.ts +82 -0
  49. package/src/compiler/browser-globals.ts +127 -0
  50. package/src/compiler/cacheability.ts +592 -0
  51. package/src/compiler/compliance-rgaa.ts +502 -0
  52. package/src/compiler/compliance.ts +497 -0
  53. package/src/compiler/data-keys.ts +295 -0
  54. package/src/compiler/dev-source.ts +87 -0
  55. package/src/compiler/dom-attrs.ts +452 -0
  56. package/src/compiler/dom.ts +567 -0
  57. package/src/compiler/emit.ts +131 -0
  58. package/src/compiler/expr-context.ts +518 -0
  59. package/src/compiler/index.ts +8 -0
  60. package/src/compiler/interactivity.ts +366 -0
  61. package/src/compiler/mistakes.ts +499 -0
  62. package/src/compiler/node-env.ts +50 -0
  63. package/src/compiler/patch.ts +97 -0
  64. package/src/compiler/props.ts +511 -0
  65. package/src/compiler/scope.ts +607 -0
  66. package/src/compiler/server-only.ts +326 -0
  67. package/src/compiler/shared.ts +369 -0
  68. package/src/compiler/signal-reads.ts +242 -0
  69. package/src/compiler/slots.ts +227 -0
  70. package/src/compiler/ssr-helpers.ts +555 -0
  71. package/src/compiler/ssr-island.ts +90 -0
  72. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  73. package/src/compiler/ssr.ts +526 -0
  74. package/src/context.ts +165 -0
  75. package/src/dev/child.ts +30 -0
  76. package/src/dev/error-log.ts +151 -0
  77. package/src/dev/index.ts +258 -0
  78. package/src/dev/modules.ts +68 -0
  79. package/src/dev/open-editor.ts +204 -0
  80. package/src/dev/protocol.ts +22 -0
  81. package/src/dev/queue.ts +79 -0
  82. package/src/dev/reload.ts +159 -0
  83. package/src/dev/supervisor.ts +204 -0
  84. package/src/dev/watchers.ts +251 -0
  85. package/src/dom/action.ts +164 -0
  86. package/src/dom/attrs.ts +84 -0
  87. package/src/dom/claim.ts +120 -0
  88. package/src/dom/extras.ts +562 -0
  89. package/src/dom/index.ts +289 -0
  90. package/src/dom/island.ts +285 -0
  91. package/src/dom/loop.ts +450 -0
  92. package/src/dom/revive.ts +36 -0
  93. package/src/index.ts +22 -0
  94. package/src/jsx-runtime.ts +566 -0
  95. package/src/plugins/config.ts +86 -0
  96. package/src/plugins/context.ts +66 -0
  97. package/src/plugins/index.ts +14 -0
  98. package/src/plugins/load.ts +70 -0
  99. package/src/plugins/order.ts +111 -0
  100. package/src/plugins/public.ts +15 -0
  101. package/src/plugins/requires.ts +47 -0
  102. package/src/plugins/services.ts +97 -0
  103. package/src/plugins/types.ts +261 -0
  104. package/src/reactivity/graph.ts +249 -0
  105. package/src/reactivity/index.ts +533 -0
  106. package/src/reactivity/selector.ts +51 -0
  107. package/src/reactivity/store.ts +208 -0
  108. package/src/server/action-protect.ts +198 -0
  109. package/src/server/action-registry.ts +78 -0
  110. package/src/server/action.ts +530 -0
  111. package/src/server/app-entry.ts +23 -0
  112. package/src/server/assets.ts +168 -0
  113. package/src/server/compress.ts +642 -0
  114. package/src/server/consent.ts +253 -0
  115. package/src/server/cookies.ts +139 -0
  116. package/src/server/document.ts +271 -0
  117. package/src/server/env.ts +33 -0
  118. package/src/server/errors.ts +391 -0
  119. package/src/server/form-schema.ts +343 -0
  120. package/src/server/health.ts +244 -0
  121. package/src/server/http.ts +538 -0
  122. package/src/server/index.ts +586 -0
  123. package/src/server/lifecycle.ts +75 -0
  124. package/src/server/loader.ts +123 -0
  125. package/src/server/page.ts +107 -0
  126. package/src/server/param-matchers.ts +112 -0
  127. package/src/server/plugin-host.ts +265 -0
  128. package/src/server/prerendered.ts +71 -0
  129. package/src/server/public.ts +19 -0
  130. package/src/server/rate-limit.ts +156 -0
  131. package/src/server/region.ts +96 -0
  132. package/src/server/request-body.ts +27 -0
  133. package/src/server/request-path.ts +73 -0
  134. package/src/server/request-scope.ts +22 -0
  135. package/src/server/route-cache.ts +423 -0
  136. package/src/server/route-table.ts +410 -0
  137. package/src/server/router.ts +261 -0
  138. package/src/server/routing.ts +472 -0
  139. package/src/server/security.ts +499 -0
  140. package/src/server/serve-handlers.ts +83 -0
  141. package/src/server/served-file.ts +128 -0
  142. package/src/server/standard-schema.ts +87 -0
  143. package/src/server/start.ts +143 -0
  144. package/src/server/static-dir.ts +220 -0
  145. package/src/server/stream.ts +211 -0
  146. package/src/ssr/context.ts +383 -0
  147. package/src/ssr/index.ts +596 -0
  148. package/src/ssr/navigation.ts +96 -0
  149. package/src/ssr/region.ts +183 -0
  150. package/src/style.ts +33 -0
  151. package/src/test/browser.ts +192 -0
  152. package/src/test/index.ts +191 -0
  153. package/src/ts-plugin/diagnostics.ts +378 -0
  154. package/src/ts-plugin/fixes.ts +364 -0
  155. package/src/ts-plugin/index.ts +194 -0
  156. package/src/unrenderable.ts +35 -0
  157. package/templates/_shared/AGENTS.md +10 -0
  158. package/templates/_shared/CLAUDE.md +1 -0
  159. package/templates/_shared/gitignore +3 -0
  160. package/templates/_shared/mcp.json +11 -0
  161. package/templates/_shared/public/robots.txt +2 -0
  162. package/templates/_shared/src/routes/legal.tsx +13 -0
  163. package/templates/_shared/tsconfig.json +25 -0
  164. package/templates/app/.env.example +4 -0
  165. package/templates/app/package.json +21 -0
  166. package/templates/app/prunelle.config.ts +11 -0
  167. package/templates/app/src/auth.ts +14 -0
  168. package/templates/app/src/routes/_layout.tsx +32 -0
  169. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  171. package/templates/app/src/routes/index.tsx +15 -0
  172. package/templates/app/src/routes/login.tsx +34 -0
  173. package/templates/app/src/styles/app.css +7 -0
  174. package/templates/app/tests/app.test.ts +32 -0
  175. package/templates/blog/content/posts/welcome.md +9 -0
  176. package/templates/blog/package.json +22 -0
  177. package/templates/blog/prunelle.config.ts +23 -0
  178. package/templates/blog/src/posts.ts +26 -0
  179. package/templates/blog/src/routes/_layout.tsx +20 -0
  180. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  181. package/templates/blog/src/routes/index.tsx +33 -0
  182. package/templates/blog/src/styles/app.css +10 -0
  183. package/templates/fullstack/package.json +19 -0
  184. package/templates/fullstack/prunelle.config.ts +6 -0
  185. package/templates/fullstack/src/actions/greet.ts +19 -0
  186. package/templates/fullstack/src/components/Counter.tsx +10 -0
  187. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  188. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  189. package/templates/fullstack/src/routes/api/health.ts +5 -0
  190. package/templates/fullstack/src/routes/index.tsx +13 -0
  191. package/templates/fullstack/src/styles/app.css +29 -0
  192. package/templates/fullstack/tests/app.test.ts +37 -0
  193. package/templates/minimal/package.json +19 -0
  194. package/templates/minimal/prunelle.config.ts +6 -0
  195. package/templates/minimal/src/components/Counter.tsx +10 -0
  196. package/templates/minimal/src/routes/_layout.tsx +14 -0
  197. package/templates/minimal/src/routes/index.tsx +11 -0
  198. package/templates/minimal/src/styles/app.css +22 -0
  199. package/ts-plugin.cjs +4277 -0
  200. package/README.md +0 -3
@@ -0,0 +1,69 @@
1
+ // The SSR compiler's emission of `<Suspense>` and `<Catch>`, whose children must reach the component unrendered.
2
+
3
+ import type { JSXChild, JSXElement, JSXFragment, Node } from 'oxc-parser'
4
+ import type { StringParts } from './ssr-helpers'
5
+ import { cleanJsxText, decodeHtmlEntities, filterMeaningfulChildren, isComponentTag, isJsxNode, jsxTagName, matchJsxMapCall } from './shared'
6
+
7
+ /** What the two emitters borrow from the running `compileSsr()`. */
8
+ export interface PrunelleTagEmitter {
9
+ use: (name: string) => string
10
+ compileSubExpression: (node: Node) => string
11
+ compileChildren: (children: readonly JSXChild[], slotMarkers?: boolean, inFragment?: boolean) => string
12
+ compileJsx: (node: JSXElement | JSXFragment) => string
13
+ compileComponentRaw: (node: JSXElement, tag: string) => string
14
+ markersAt: (offset: number) => boolean
15
+ directAwaitNodes: WeakSet<Node>
16
+ jsxNodes: WeakSet<Node>
17
+ }
18
+
19
+ // `<Suspense fallback={...}><AsyncComp .../></Suspense>` passes the raw component call or Promise.
20
+ export function emitSuspense(em: PrunelleTagEmitter, node: JSXElement, tag: string, propEntries: string[], parts: StringParts, onRaw?: (expr: string) => void): void {
21
+ const meaningful = filterMeaningfulChildren(node.children)
22
+ const only = meaningful.length === 1 ? meaningful[0]! : undefined
23
+ if (only?.type === 'JSXElement' && isComponentTag(jsxTagName(only.openingElement.name))) {
24
+ propEntries.push(`children: ${em.compileComponentRaw(only, jsxTagName(only.openingElement.name))}`)
25
+ }
26
+ else if (only?.type === 'JSXExpressionContainer' && only.expression.type !== 'JSXEmptyExpression') {
27
+ propEntries.push(`children: ${em.compileSubExpression(only.expression)}`)
28
+ }
29
+ else if (only?.type === 'JSXText') {
30
+ propEntries.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(only.value)))}`)
31
+ }
32
+ else if (only !== undefined && isJsxNode(only)) {
33
+ propEntries.push(`children: ${em.use('raw')}(${em.compileJsx(only)})`)
34
+ }
35
+ const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
36
+ const callExpr = `${tag}(${propsObj})`
37
+ if (onRaw !== undefined)
38
+ onRaw(callExpr)
39
+ else
40
+ parts.pushExpr(`${em.use('ssrChild')}(${callExpr})`)
41
+ }
42
+
43
+ // `<Catch>` reads its children inside a try, so they reach it as a getter even when static; in an island it renders in a range of its own, which the browser swaps.
44
+ export function emitCatch(em: PrunelleTagEmitter, node: JSXElement, tag: string, propEntries: string[], parts: StringParts, onRaw?: (expr: string) => void): void {
45
+ const meaningful = filterMeaningfulChildren(node.children)
46
+ const awaits = node.children.some(c => em.directAwaitNodes.has(c))
47
+ const markers = onRaw === undefined && em.markersAt(node.start)
48
+ if (meaningful.length > 0) {
49
+ const only = meaningful.length === 1 ? meaningful[0]! : undefined
50
+ let childExpr: string
51
+ if (onRaw !== undefined && only?.type === 'JSXElement' && isComponentTag(jsxTagName(only.openingElement.name))) {
52
+ childExpr = em.compileComponentRaw(only, jsxTagName(only.openingElement.name))
53
+ }
54
+ else {
55
+ const singleLoop = only?.type === 'JSXExpressionContainer' && only.expression.type !== 'JSXEmptyExpression' && matchJsxMapCall(only.expression, em.jsxNodes) !== undefined
56
+ childExpr = `${em.use('raw')}(${em.compileChildren(node.children, markers, markers && (meaningful.length > 1 || singleLoop))})`
57
+ }
58
+ propEntries.push(`get children() { return (${awaits ? `(async () => ${childExpr})()` : childExpr}) }`)
59
+ }
60
+ if (markers)
61
+ parts.pushStatic('<!--k[-->')
62
+ const callExpr = `${awaits ? 'await ' : ''}${tag}({ ${propEntries.join(', ')} })`
63
+ if (onRaw !== undefined)
64
+ onRaw(callExpr)
65
+ else
66
+ parts.pushExpr(`${em.use('ssrChild')}(${callExpr})`)
67
+ if (markers)
68
+ parts.pushStatic('<!--k]-->')
69
+ }
@@ -0,0 +1,526 @@
1
+ // Prunelle SSR compiler: compiles TSX directly to flat string concatenation, inline for-loops,
2
+ // static attribute literal folding, compile-time static island props, and shared balanced hydration markers.
3
+
4
+ import type {
5
+ JSXChild,
6
+ JSXElement,
7
+ JSXFragment,
8
+ Node,
9
+ } from 'oxc-parser'
10
+ import type { ModuleAnalysis } from './analyze'
11
+ import type { SelectValueBinding } from './ssr-helpers'
12
+ import type { PrunelleTagEmitter } from './ssr-prunelle-tags'
13
+ import { analyzeModule, parseTsx } from './analyze'
14
+ import { walk } from './ast'
15
+ import { createDevSourceAttr } from './dev-source'
16
+ import { mistake } from './mistakes'
17
+ import { alignLines, lineMarker, SourceEditor } from './patch'
18
+ import {
19
+ containsJsx,
20
+ createExprContext,
21
+ decodeHtmlEntities,
22
+ escapeRawText,
23
+ escapeStaticText,
24
+ filterMeaningfulChildren,
25
+ isComponentTag,
26
+ isJsxNode,
27
+ jsxTagName,
28
+ matchJsxMapCall,
29
+ planChildSlots,
30
+ RAW_TEXT_ELEMENTS,
31
+ resolvePrunelleTag,
32
+ unwrapParens,
33
+ VOID_ELEMENTS,
34
+ } from './shared'
35
+ import {
36
+ emitSsrElementAttrs,
37
+ precomputeSsrSubtreeFlags,
38
+ serializeComponentProps,
39
+ staticLiteralOrTemplate,
40
+ StringParts,
41
+ } from './ssr-helpers'
42
+ import { emitIsland } from './ssr-island'
43
+ import { emitCatch, emitSuspense } from './ssr-prunelle-tags'
44
+
45
+ const FORM_CONTROL_TAGS = new Set(['input', 'select', 'textarea'])
46
+ const FORM_ATTR_BITS: Record<string, number> = {
47
+ type: 1,
48
+ required: 2,
49
+ minlength: 4,
50
+ maxlength: 8,
51
+ min: 16,
52
+ max: 32,
53
+ step: 64,
54
+ pattern: 128,
55
+ }
56
+
57
+ function findDynamicFormAction(node: JSXElement): Node | undefined {
58
+ for (const attr of node.openingElement.attributes) {
59
+ if (attr.type !== 'JSXAttribute' || jsxTagName(attr.name) !== 'action')
60
+ continue
61
+ if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
62
+ return undefined
63
+ const expr = attr.value.expression
64
+ if (staticLiteralOrTemplate(expr).ok)
65
+ return undefined
66
+ if (expr.type === 'ConditionalExpression' && staticLiteralOrTemplate(expr.consequent).ok && staticLiteralOrTemplate(expr.alternate).ok)
67
+ return undefined
68
+ return expr
69
+ }
70
+ return undefined
71
+ }
72
+
73
+ function emitFormControlAttrs(
74
+ node: JSXElement,
75
+ tag: 'input' | 'select' | 'textarea',
76
+ parts: StringParts,
77
+ use: (name: string) => string,
78
+ compileSubExpression: (node: Node) => string,
79
+ ): void {
80
+ const attrs = node.openingElement.attributes
81
+ if (attrs.some(a => a.type === 'JSXSpreadAttribute'))
82
+ return
83
+ let nameExpr: string | undefined
84
+ let typeExpr: string | undefined
85
+ let present = 0
86
+ for (const attr of attrs) {
87
+ if (attr.type !== 'JSXAttribute')
88
+ continue
89
+ const attrName = jsxTagName(attr.name).toLowerCase()
90
+ const bit = FORM_ATTR_BITS[attrName]
91
+ if (bit !== undefined)
92
+ present |= bit
93
+ if (attrName === 'name') {
94
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
95
+ nameExpr = JSON.stringify(attr.value.value)
96
+ }
97
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
98
+ const lit = staticLiteralOrTemplate(attr.value.expression)
99
+ nameExpr = lit.ok && typeof lit.value === 'string' ? JSON.stringify(lit.value) : compileSubExpression(attr.value.expression)
100
+ }
101
+ }
102
+ else if (tag === 'input' && attrName === 'type') {
103
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
104
+ typeExpr = JSON.stringify(attr.value.value.toLowerCase())
105
+ }
106
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
107
+ const lit = staticLiteralOrTemplate(attr.value.expression)
108
+ if (lit.ok && typeof lit.value === 'string')
109
+ typeExpr = JSON.stringify(lit.value.toLowerCase())
110
+ }
111
+ }
112
+ }
113
+ if (nameExpr === undefined)
114
+ return
115
+ const typeArg = typeExpr !== undefined ? `, ${typeExpr}` : ''
116
+ parts.pushExpr(`${use('ssrFormAttrs')}(${JSON.stringify(tag)}, ${nameExpr}, ${present}${typeArg})`)
117
+ }
118
+
119
+ export interface IslandBinding {
120
+ id: string
121
+ chunk: string
122
+ defaultHydrate?: string | undefined
123
+ }
124
+
125
+ export interface CompileSsrOptions {
126
+ islands?: ReadonlyMap<string, IslandBinding> | undefined
127
+ isIsland?: boolean | undefined
128
+ /** Hydration markers everywhere, nowhere, or only inside these source spans. */
129
+ emitMarkers?: boolean | readonly (readonly [number, number])[] | undefined
130
+ analysis?: ModuleAnalysis | undefined
131
+ /** Project root for dev-only `data-pru-src="file:line:col"` attributes; omit in production. */
132
+ devSourceRoot?: string | undefined
133
+ }
134
+
135
+ export interface CompileResult {
136
+ code: string
137
+ analysis: ModuleAnalysis
138
+ }
139
+
140
+ function emitActionFormExpr(
141
+ formAction: Node,
142
+ isAsyncForm: boolean,
143
+ nextId: () => number,
144
+ use: (name: string) => string,
145
+ compileSubExpression: (node: Node) => string,
146
+ emitBody: (bufVar: string, parts: StringParts, flush: () => void, pushStmt: (stmt: string) => void, override: { node: Node, ident: string }) => void,
147
+ ): string {
148
+ const faVar = `_fa${nextId()}`
149
+ const innerBuf = `_o${nextId()}`
150
+ const innerStmts: string[] = []
151
+ const innerParts = new StringParts()
152
+ const flushInner = () => {
153
+ if (!innerParts.isEmpty()) {
154
+ innerStmts.push(`${innerBuf} += ${innerParts.toExpr()};`)
155
+ innerParts.clear()
156
+ }
157
+ }
158
+ emitBody(innerBuf, innerParts, flushInner, s => innerStmts.push(s), { node: formAction, ident: faVar })
159
+ if (innerStmts.length > 0)
160
+ flushInner()
161
+ const body = innerStmts.length === 0 ? innerParts.toExpr() : `{ let ${innerBuf} = ""; ${innerStmts.join(' ')} return ${innerBuf}; }`
162
+ return isAsyncForm
163
+ ? `await ${use('ssrFormAsync')}(${compileSubExpression(formAction)}, async (${faVar}) => ${body})`
164
+ : `${use('ssrForm')}(${compileSubExpression(formAction)}, (${faVar}) => ${body})`
165
+ }
166
+
167
+ function markerTest(markers: NonNullable<CompileSsrOptions['emitMarkers']>): (offset: number) => boolean {
168
+ return typeof markers === 'boolean' ? () => markers : offset => markers.some(([start, end]) => offset >= start && offset < end)
169
+ }
170
+
171
+ function flushStringParts(bufVar: string, parts: StringParts, stmts: string[]): void {
172
+ if (!parts.isEmpty()) {
173
+ stmts.push(`${bufVar} += ${parts.toExpr()};`)
174
+ parts.clear()
175
+ }
176
+ }
177
+
178
+ function isSingleLoopChild(meaningful: readonly JSXChild[], jsxNodes: WeakSet<Node>): boolean {
179
+ return meaningful.length === 1
180
+ && meaningful[0]!.type === 'JSXExpressionContainer'
181
+ && meaningful[0]!.expression.type !== 'JSXEmptyExpression'
182
+ && matchJsxMapCall(meaningful[0]!.expression, jsxNodes) !== undefined
183
+ }
184
+
185
+ function compileSsrSubExpression(
186
+ code: string,
187
+ node: Node,
188
+ jsxNodes: WeakSet<Node>,
189
+ mark: (offset: number) => string,
190
+ compileRootJsx: (n: JSXElement | JSXFragment) => string,
191
+ ): string {
192
+ if (!containsJsx(node, jsxNodes))
193
+ return mark(node.start) + code.slice(node.start, node.end)
194
+ const sub = new SourceEditor(code.slice(node.start, node.end))
195
+ const offset = node.start
196
+ walk(node, (child) => {
197
+ if (isJsxNode(child)) {
198
+ sub.replace(child.start - offset, child.end - offset, compileRootJsx(child) + mark(child.end))
199
+ return false
200
+ }
201
+ return undefined
202
+ })
203
+ return mark(node.start) + sub.toString()
204
+ }
205
+
206
+ function compileSsrExprAsString(
207
+ expr: Node,
208
+ use: (name: string) => string,
209
+ compileSubExpression: (node: Node) => string,
210
+ compileJsxToStringExpr: (node: JSXElement | JSXFragment) => string,
211
+ ): string {
212
+ if (isJsxNode(expr))
213
+ return compileJsxToStringExpr(expr)
214
+ if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
215
+ const right = unwrapParens(expr.right)
216
+ if (isJsxNode(right))
217
+ return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
218
+ }
219
+ if (expr.type === 'ConditionalExpression') {
220
+ const consNode = unwrapParens(expr.consequent)
221
+ const altNode = unwrapParens(expr.alternate)
222
+ if (isJsxNode(consNode) || isJsxNode(altNode))
223
+ return `((${compileSubExpression(expr.test)}) ? (${compileSsrExprAsString(consNode, use, compileSubExpression, compileJsxToStringExpr)}) : (${compileSsrExprAsString(altNode, use, compileSubExpression, compileJsxToStringExpr)}))`
224
+ }
225
+ return `${use('esc')}(${compileSubExpression(expr)})`
226
+ }
227
+
228
+ export function compileSsr(filename: string, code: string, options: CompileSsrOptions = {}): CompileResult {
229
+ const program = options.analysis?.program ?? parseTsx(filename, code)
230
+ const analysis = options.analysis ?? analyzeModule(filename, code, program)
231
+
232
+ if (!analysis.hasJsx)
233
+ return { code, analysis }
234
+
235
+ const editor = new SourceEditor(code)
236
+ // 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.
237
+ const mark = lineMarker(code)
238
+ const used = new Set<string>()
239
+ let loopCounter = 0
240
+ let activeSelectValue: SelectValueBinding | undefined
241
+
242
+ const use = (name: string): string => {
243
+ used.add(name)
244
+ return `__${name}`
245
+ }
246
+
247
+ const islands = options.islands
248
+ const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
249
+ const markersAt = markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive)
250
+ const jsxNodes = analysis.jsxNodes
251
+ const exprContext = createExprContext(program, jsxNodes)
252
+ const { directAwaitNodes, dynamicChildNodes } = precomputeSsrSubtreeFlags(program)
253
+ const compileSubExpression = (node: Node): string => compileSsrSubExpression(code, node, jsxNodes, mark, compileRootJsx)
254
+ const compileComponentRaw = (node: JSXElement, tag: string): string => {
255
+ let out = ''
256
+ emitComponent(node, tag, new StringParts(), (e) => { out = e })
257
+ return out
258
+ }
259
+ const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, compileComponentRaw, markersAt, directAwaitNodes, jsxNodes }
260
+
261
+ function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = markersAt(children[0]?.start ?? 0), inFragment = false, rawTextTag?: 'style' | 'script'): string {
262
+ const bufVar = `_o${loopCounter++}`
263
+ const stmts: string[] = []
264
+ const parts = new StringParts()
265
+ const flush = () => flushStringParts(bufVar, parts, stmts)
266
+ emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), rawTextTag, slotMarkers, inFragment)
267
+ if (stmts.length === 0)
268
+ return parts.toExpr()
269
+ flush()
270
+ const hasAwait = children.some(c => directAwaitNodes.has(c))
271
+ if (hasAwait)
272
+ return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
273
+ return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
274
+ }
275
+
276
+ // Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
277
+ function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void, actionOverride?: { node: Node, ident: string }): void {
278
+ if (node.type === 'JSXFragment') {
279
+ emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, markersAt(node.start), true)
280
+ return
281
+ }
282
+
283
+ const tag = jsxTagName(node.openingElement.name)
284
+ if (isComponentTag(tag)) {
285
+ emitComponent(node, tag, parts)
286
+ return
287
+ }
288
+
289
+ if (tag === 'form' && actionOverride === undefined) {
290
+ const formAction = findDynamicFormAction(node)
291
+ if (formAction !== undefined) {
292
+ parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), () => loopCounter++, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
293
+ return
294
+ }
295
+ }
296
+
297
+ parts.pushStatic(`<${tag}${devSrc(node, tag)}`)
298
+ const isTextarea = tag === 'textarea'
299
+ const isSelect = tag === 'select'
300
+ const compileAttrExpr = actionOverride !== undefined ? (n: Node) => (n === actionOverride.node ? actionOverride.ident : compileSubExpression(n)) : compileSubExpression
301
+ const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId: () => loopCounter++, use, compileSubExpression: compileAttrExpr })
302
+ if (FORM_CONTROL_TAGS.has(tag))
303
+ emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
304
+ parts.pushStatic('>')
305
+ if (VOID_ELEMENTS.has(tag))
306
+ return
307
+
308
+ const prevSelectValue = activeSelectValue
309
+ if (isSelect)
310
+ activeSelectValue = nextSelectValue
311
+
312
+ try {
313
+ if (innerHtmlExpr !== undefined)
314
+ parts.pushExpr(innerHtmlExpr)
315
+ else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0)
316
+ textareaValue.staticText !== undefined ? parts.pushStatic(escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('esc')}(${textareaValue.expr})`)
317
+ else if (tag === 'style') {
318
+ const styleExpr = compileChildrenListToStringExpr(node.children, false, false, 'style')
319
+ if (styleExpr !== '""')
320
+ parts.pushExpr(`${use('ssrStyleBlock')}(${styleExpr})`)
321
+ }
322
+ else
323
+ emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
324
+ }
325
+ finally {
326
+ activeSelectValue = prevSelectValue
327
+ }
328
+ if (actionOverride === undefined)
329
+ parts.pushStatic(`</${tag}>`)
330
+ }
331
+
332
+ function emitChildrenIntoBuffer(
333
+ children: readonly JSXChild[],
334
+ bufVar: string,
335
+ parts: StringParts,
336
+ flushParts: () => void,
337
+ pushStmt: (stmt: string) => void,
338
+ rawTextTag?: 'style' | 'script',
339
+ slotMarkers = markersAt(children[0]?.start ?? 0),
340
+ inFragment = false,
341
+ ): void {
342
+ const planned = planChildSlots(children, { jsxNodes, exprContext, emitMarkers: slotMarkers, inFragment })
343
+
344
+ for (const { child, slot, open, close } of planned) {
345
+ if (slot.kind === 'static-text') {
346
+ if (rawTextTag !== undefined)
347
+ parts.pushStatic(escapeRawText(slot.text, rawTextTag))
348
+ else
349
+ parts.pushStatic(escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text)))
350
+ continue
351
+ }
352
+
353
+ if (rawTextTag !== undefined) {
354
+ if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression') {
355
+ const expr = child.expression
356
+ if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0 && expr.quasis.length === 1) {
357
+ const cooked = expr.quasis[0]?.value.cooked
358
+ if (typeof cooked === 'string') {
359
+ parts.pushStatic(escapeRawText(cooked, rawTextTag))
360
+ continue
361
+ }
362
+ }
363
+ parts.pushExpr(`${use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${compileSubExpression(expr)})`)
364
+ continue
365
+ }
366
+ }
367
+
368
+ if (slot.kind === 'element') {
369
+ emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
370
+ continue
371
+ }
372
+
373
+ if (open !== '')
374
+ parts.pushStatic(open)
375
+
376
+ if (slot.kind === 'component' || slot.kind === 'fragment') {
377
+ emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
378
+ }
379
+ else if (slot.kind === 'loop') {
380
+ const { match } = slot
381
+ const itemParam = match.params[0]?.type === 'Identifier' ? match.params[0].name : undefined
382
+ const idxParam = match.params[1]?.type === 'Identifier' ? match.params[1].name : undefined
383
+
384
+ if (match.isJsxBody && itemParam !== undefined && match.params.length <= 2 && (match.params.length < 2 || idxParam !== undefined)) {
385
+ flushParts()
386
+ const n = loopCounter++
387
+ const arrVar = `_a${n}`
388
+ const idxVar = idxParam ?? `_i${n}`
389
+ const innerStmts: string[] = []
390
+ const innerParts = new StringParts()
391
+ const flushInner = () => flushStringParts(bufVar, innerParts, innerStmts)
392
+ emitIntoBuffer(match.body as JSXElement | JSXFragment, bufVar, innerParts, flushInner, s => innerStmts.push(s))
393
+ flushInner()
394
+
395
+ const target = compileSubExpression(match.target)
396
+ pushStmt(
397
+ `const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
398
+ )
399
+ }
400
+ else if (match.isJsxBody) {
401
+ const target = compileSubExpression(match.target)
402
+ const params = match.params.map(p => compileSubExpression(p)).join(', ')
403
+ parts.pushExpr(`${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(match.body as JSXElement | JSXFragment)})`)
404
+ }
405
+ else {
406
+ parts.pushExpr(`${use('esc')}(${compileSubExpression(match.call)})`)
407
+ }
408
+ }
409
+ else if (slot.kind === 'and-show') {
410
+ const left = compileSubExpression(slot.expr.left)
411
+ const right = compileJsxToStringExpr(slot.right)
412
+ parts.pushExpr(`((${left}) ? (${right}) : "")`)
413
+ }
414
+ else if (slot.kind === 'ternary-show') {
415
+ const test = compileSubExpression(slot.expr.test)
416
+ const cons = compileExpressionAsString(slot.cons)
417
+ const alt = compileExpressionAsString(slot.alt)
418
+ parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
419
+ }
420
+ else {
421
+ parts.pushExpr(`${use('esc')}(${compileSubExpression(slot.expr)})`)
422
+ }
423
+
424
+ if (close !== '')
425
+ parts.pushStatic(close)
426
+ }
427
+ }
428
+
429
+ const compileExpressionAsString = (expr: Node): string => compileSsrExprAsString(expr, use, compileSubExpression, compileJsxToStringExpr)
430
+
431
+ function emitComponent(node: JSXElement, tag: string, parts: StringParts, onRaw?: (expr: string) => void): void {
432
+ const { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate } = serializeComponentProps(node.openingElement.attributes, compileSubExpression)
433
+ const childNodes = node.children
434
+ const meaningfulChildren = filterMeaningfulChildren(childNodes)
435
+ const hasChildren = meaningfulChildren.length > 0
436
+ // The call sits on the line of its tag, so a component that throws names that line in the caller's frame.
437
+ const call = `${mark(node.start)}${tag}`
438
+
439
+ const prunelleTag = resolvePrunelleTag(tag, analysis.imports)
440
+ if (prunelleTag === 'Suspense' || prunelleTag === 'Catch') {
441
+ ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts, onRaw)
442
+ return
443
+ }
444
+
445
+ const islandInfo = islands?.get(tag)
446
+ if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
447
+ throw mistake(`$hydrate on <${tag}>`, filename, `${tag} is not an island, so it never hydrates; drop $hydrate, or give ${tag} state or handlers`)
448
+
449
+ const childrenHaveAwait = hasChildren && childNodes.some(c => directAwaitNodes.has(c))
450
+ const childMarkers = islandInfo === undefined && markersAt(node.start)
451
+ const onlyComp = onRaw !== undefined && islandInfo === undefined && meaningfulChildren.length === 1 && meaningfulChildren[0]!.type === 'JSXElement' && isComponentTag(jsxTagName(meaningfulChildren[0]!.openingElement.name)) ? meaningfulChildren[0]! : undefined
452
+ const childExpr = onlyComp !== undefined
453
+ ? compileComponentRaw(onlyComp, jsxTagName(onlyComp.openingElement.name))
454
+ : hasChildren ? compileChildrenListToStringExpr(childNodes, childMarkers, childMarkers && (meaningfulChildren.length > 1 || isSingleLoopChild(meaningfulChildren, jsxNodes))) : '""'
455
+
456
+ if (islandInfo !== undefined) {
457
+ const target = onRaw !== undefined ? new StringParts() : parts
458
+ emitIsland({ use, nextId: () => loopCounter++, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
459
+ if (onRaw !== undefined)
460
+ onRaw(`${use('raw')}(${target.toExpr()})`)
461
+ return
462
+ }
463
+
464
+ const emitOut = (expr: string): void => {
465
+ if (onRaw !== undefined)
466
+ onRaw(expr)
467
+ else
468
+ parts.pushExpr(`${use('ssrChild')}(${expr})`)
469
+ }
470
+ const wrappedChild = onlyComp !== undefined ? childExpr : `${use('raw')}(${childExpr})`
471
+ const childrenHaveDynamic = hasChildren && childNodes.some(c => dynamicChildNodes.has(c))
472
+
473
+ // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
474
+ if (childrenHaveDynamic && !childrenHaveAwait) {
475
+ const cVar = `_c${loopCounter++}`
476
+ const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
477
+ emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
478
+ return
479
+ }
480
+
481
+ if (hasChildren)
482
+ propEntries.push(`children: ${wrappedChild}`)
483
+
484
+ const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
485
+ emitOut(`${call}(${propsObj})`)
486
+ }
487
+
488
+ function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
489
+ const bufVar = `_o${loopCounter++}`
490
+ const stmts: string[] = []
491
+ const parts = new StringParts()
492
+
493
+ const flush = () => flushStringParts(bufVar, parts, stmts)
494
+
495
+ emitIntoBuffer(node, bufVar, parts, flush, s => stmts.push(s))
496
+
497
+ // If no inline `for` statements were emitted, stay a pure flat concatenation expression!
498
+ if (stmts.length === 0)
499
+ return parts.toExpr()
500
+
501
+ flush()
502
+ if (directAwaitNodes.has(node))
503
+ return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
504
+ return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
505
+ }
506
+
507
+ function compileRootJsx(node: JSXElement | JSXFragment): string {
508
+ return `${use('raw')}(${compileJsxToStringExpr(node)})`
509
+ }
510
+
511
+ walk(program, (node) => {
512
+ if (isJsxNode(node)) {
513
+ editor.replace(node.start, node.end, compileRootJsx(node) + mark(node.end))
514
+ return false
515
+ }
516
+ return undefined
517
+ })
518
+
519
+ if (used.size > 0) {
520
+ const specifiers = [...used].sort().map(name => `${name} as __${name}`).join(', ')
521
+ // Last, where it moves no line: an import is hoisted wherever it is written.
522
+ editor.append(`\nimport { ${specifiers} } from 'prunelle/internal/ssr';\n`)
523
+ }
524
+
525
+ return { code: alignLines(editor.toString()), analysis }
526
+ }