prunelle 0.0.0-stage → 0.7.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 (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,641 @@
1
+ // Prunelle Client DOM compiler: compiles TSX to hoisted template() clones, child-path walks,
2
+ // delegated events, compiler-safe destructured props, reactive spreads, and shared balanced hydration markers.
3
+
4
+ import type {
5
+ ArrowFunctionExpression,
6
+ BlockStatement,
7
+ Function as OxcFunction,
8
+ JSXChild,
9
+ JSXElement,
10
+ JSXFragment,
11
+ Node,
12
+ } from 'oxc-parser'
13
+ import type { ModuleAnalysis } from './analyze'
14
+ import type { WalkItem } from './emit'
15
+ import type { ExprContext, HydrationMarker, MapCallMatch } from './shared'
16
+
17
+ import { analyzeModule, getExprContext, loadDeclarations, parseTsx } from './analyze'
18
+ import { walk } from './ast'
19
+ import { createDevSourceAttr } from './dev-source'
20
+ import { collectStaticStyleNames, compileElementAttributes, compileRawTextChildren, formatSetTextOp, resolveComponentCallee } from './dom-attrs'
21
+ import { emitWalkStatements, moduleHeader, SVG_CHILD_TAGS } from './emit'
22
+ import { SourceEditor } from './patch'
23
+ import { compileParamList, createPropCompiler, isStaticPropExpr, withoutBindings } from './props'
24
+ import { extractBlockKeyExpr, extractKeyExpr, literalArrayConsts, rewriteFreeIdentifiers } from './scope'
25
+ import {
26
+ cleanJsxText,
27
+ containsJsx,
28
+ decodeHtmlEntities,
29
+ escapeStaticText,
30
+ filterMeaningfulChildren,
31
+ isComponentTag,
32
+ isJsxNode,
33
+ jsxTagName,
34
+ matchJsxMapCall,
35
+ planChildSlots,
36
+ RAW_TEXT_ELEMENTS,
37
+ resolvePrunelleTag,
38
+ VOID_ELEMENTS,
39
+ } from './shared'
40
+
41
+ export interface CompileDomOptions {
42
+ analysis?: ModuleAnalysis | undefined
43
+ /** Project root for dev-only `data-pru-src="file:line:col"` attributes; omit in production. */
44
+ devSourceRoot?: string | undefined
45
+ }
46
+
47
+ export interface CompileDomResult {
48
+ code: string
49
+ analysis: ModuleAnalysis
50
+ }
51
+
52
+ const SUB_VAR_RE = /__SUB_\d+/g
53
+
54
+ interface DomCompilerCtx {
55
+ code: string
56
+ analysis: ModuleAnalysis
57
+ jsxNodes: WeakSet<Node>
58
+ exprContext: ExprContext
59
+ staticArrays: ReadonlySet<string>
60
+ staticStyleNames: ReadonlySet<string>
61
+ devSrc: (el: JSXElement, tag: string) => string
62
+ templates: { name: string, html: string, isSvg?: boolean }[]
63
+ delegatedEvents: Set<string>
64
+ svgDepth: number
65
+ use: (name: string) => string
66
+ freshVar: (prefix?: string) => string
67
+ nextVarId: () => number
68
+ compileExpression: (node: Node, scopeRewrites: ReadonlyMap<string, string>) => string
69
+ compileLoopRow: ReturnType<typeof createPropCompiler>['compileLoopRow']
70
+ withPrelude: ReturnType<typeof createPropCompiler>['withPrelude']
71
+ }
72
+
73
+ interface ElementTreeState {
74
+ ops: string[]
75
+ walkPlan: WalkItem[]
76
+ childRefs: Map<string, string>
77
+ textSlotsByParent: Map<string, Set<number>>
78
+ rangeSlotsByParent: Map<string, Set<number>>
79
+ varAliases: Map<string, string>
80
+ }
81
+
82
+ function addSlot(map: Map<string, Set<number>>, parentVar: string, idx: number): void {
83
+ let s = map.get(parentVar)
84
+ if (s === undefined) {
85
+ s = new Set()
86
+ map.set(parentVar, s)
87
+ }
88
+ s.add(idx)
89
+ }
90
+
91
+ function remapSlotMap(map: Map<string, Set<number>>, aliases: ReadonlyMap<string, string>): void {
92
+ if (map.size === 0)
93
+ return
94
+ const moved: [string, string, Set<number>][] = []
95
+ for (const [k, v] of map) {
96
+ const target = aliases.get(k)
97
+ if (target !== undefined)
98
+ moved.push([k, target, v])
99
+ }
100
+ for (const [from, to, v] of moved) {
101
+ map.delete(from)
102
+ map.set(to, v)
103
+ }
104
+ }
105
+
106
+ function resolveElementAliases(tree: ElementTreeState): void {
107
+ const { varAliases, walkPlan, ops, textSlotsByParent, rangeSlotsByParent } = tree
108
+ if (varAliases.size === 0)
109
+ return
110
+ for (let i = 0; i < walkPlan.length; i++) {
111
+ const item = walkPlan[i]!
112
+ const mapped = varAliases.get(item.parentVar)
113
+ if (mapped !== undefined)
114
+ item.parentVar = mapped
115
+ }
116
+ remapSlotMap(textSlotsByParent, varAliases)
117
+ remapSlotMap(rangeSlotsByParent, varAliases)
118
+ const replaceFn = (match: string): string => varAliases.get(match) ?? match
119
+ for (let i = 0; i < ops.length; i++) {
120
+ const op = ops[i]!
121
+ if (op.includes('__SUB_'))
122
+ ops[i] = op.replace(SUB_VAR_RE, replaceFn)
123
+ }
124
+ }
125
+
126
+ function requestTreeChild(ctx: DomCompilerCtx, tree: ElementTreeState, parentVar: string, index: number): string {
127
+ const key = `${parentVar}:${index}`
128
+ const existing = tree.childRefs.get(key)
129
+ if (existing !== undefined)
130
+ return existing
131
+ const v = ctx.freshVar('_e')
132
+ tree.childRefs.set(key, v)
133
+ tree.walkPlan.push({ parentVar, index, varName: v })
134
+ return v
135
+ }
136
+
137
+ function compileComponentCall(ctx: DomCompilerCtx, node: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
138
+ const tag = jsxTagName(node.openingElement.name)
139
+ // `Catch` itself stays server-side, so the `prunelle` an island imports does not pull the DOM runtime into every client build.
140
+ const callee = resolvePrunelleTag(tag, ctx.analysis.imports) === 'Catch' ? ctx.use('catchBoundary') : resolveComponentCallee(tag, scopeRewrites)
141
+ const attrs = node.openingElement.attributes
142
+ const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
143
+ const segments: string[] = []
144
+ let currentObj: string[] = []
145
+
146
+ const flushObj = () => {
147
+ if (currentObj.length > 0) {
148
+ segments.push(`{ ${currentObj.join(', ')} }`)
149
+ currentObj = []
150
+ }
151
+ }
152
+
153
+ for (const attr of attrs) {
154
+ if (attr.type === 'JSXSpreadAttribute') {
155
+ flushObj()
156
+ segments.push(`(${ctx.compileExpression(attr.argument, scopeRewrites)})`)
157
+ continue
158
+ }
159
+ const name = jsxTagName(attr.name)
160
+ if (name === 'key' || name === '$hydrate')
161
+ continue
162
+
163
+ const propKey = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
164
+ if (attr.value === null) {
165
+ currentObj.push(`${propKey}: true`)
166
+ }
167
+ else if (attr.value.type === 'Literal') {
168
+ currentObj.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
169
+ }
170
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
171
+ const expr = attr.value.expression
172
+ const exprCode = ctx.compileExpression(expr, scopeRewrites)
173
+ // Reactive getter for dynamic expressions; plain property for identifiers, constant literals/collections, and inline functions.
174
+ if (isStaticPropExpr(expr, scopeRewrites))
175
+ currentObj.push(`${propKey}: ${exprCode}`)
176
+ else
177
+ currentObj.push(`get ${propKey}() { return ${exprCode} }`)
178
+ }
179
+ }
180
+
181
+ const meaningful = filterMeaningfulChildren(node.children)
182
+ if (meaningful.length === 1) {
183
+ const child = meaningful[0]!
184
+ if (child.type === 'JSXText')
185
+ currentObj.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))}`)
186
+ else if (isJsxNode(child))
187
+ currentObj.push(`get children() { return ${compileRootJsx(ctx, child, scopeRewrites)} }`)
188
+ else if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
189
+ currentObj.push(`get children() { return ${matchJsxMapCall(child.expression, ctx.jsxNodes) !== undefined ? compileFragmentChildren(ctx, node.children, scopeRewrites) : ctx.compileExpression(child.expression, scopeRewrites)} }`)
190
+ }
191
+ else if (meaningful.length > 1) {
192
+ currentObj.push(`get children() { return ${compileFragmentChildren(ctx, node.children, scopeRewrites)} }`)
193
+ }
194
+
195
+ flushObj()
196
+
197
+ if (!hasSpread)
198
+ return `${callee}(${segments[0] ?? '{}'})`
199
+ if (segments.length === 1)
200
+ return `${callee}(${segments[0]!})`
201
+ return `${callee}(${ctx.use('mergeProps')}(${segments.join(', ')}))`
202
+ }
203
+
204
+ /** Compiles a `.map()` JSX loop into either `__eachStatic` or keyed `__loop`, reusable for both element children and fragments. */
205
+ function compileLoopCall(
206
+ ctx: DomCompilerCtx,
207
+ match: MapCallMatch,
208
+ scopeRewrites: ReadonlyMap<string, string>,
209
+ skipArg = '',
210
+ ): { isStatic: boolean, call: (p: string, a: string) => string } {
211
+ const eachCode = ctx.compileExpression(match.target, scopeRewrites)
212
+ const params = match.params
213
+ const firstParam = params[0]
214
+ const secondParam = params[1]
215
+ const idxParam = secondParam?.type === 'Identifier'
216
+ ? secondParam.name
217
+ : secondParam?.type === 'AssignmentPattern' && secondParam.left.type === 'Identifier'
218
+ ? secondParam.left.name
219
+ : undefined
220
+
221
+ // Fast path: a const array literal (e.g. `NAV.map(...)`) renders once through `eachStatic`.
222
+ const isStaticArr = match.target.type === 'Identifier' && ctx.staticArrays.has(match.target.name) && !scopeRewrites.has(match.target.name)
223
+ if (isStaticArr) {
224
+ const rawParams = compileParamList(ctx.code, params, scopeRewrites, ctx.compileExpression)
225
+ const shadowed = withoutBindings(scopeRewrites, params)
226
+ const rowBody = match.isJsxBody ? compileRootJsx(ctx, match.body as JSXElement | JSXFragment, shadowed) : ctx.compileExpression(match.body, shadowed)
227
+ return {
228
+ isStatic: true,
229
+ call: (p, a) => `${ctx.use('eachStatic')}(${p}, ${a}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg})`,
230
+ }
231
+ }
232
+
233
+ const keyAst = match.isJsxBody ? extractKeyExpr(match.body) : extractBlockKeyExpr(match.body as BlockStatement)
234
+ const rowSig = ctx.freshVar('_r')
235
+ const idxSig = idxParam !== undefined ? ctx.freshVar('_i') : undefined
236
+ const keyRewrites = withoutBindings(scopeRewrites, params)
237
+ const { keyFn, rowRewrites, prelude } = ctx.compileLoopRow({ firstParam, idxParam, keyAst, rowSig, scopeRewrites, keyRewrites })
238
+ if (idxParam !== undefined && idxSig !== undefined)
239
+ rowRewrites.set(idxParam, `${idxSig}.value`)
240
+
241
+ const rawRowBody = match.isJsxBody ? compileRootJsx(ctx, match.body as JSXElement | JSXFragment, rowRewrites) : ctx.compileExpression(match.body, rowRewrites)
242
+ const rowBody = ctx.withPrelude(rawRowBody, match.body, prelude)
243
+ const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
244
+ return {
245
+ isStatic: false,
246
+ call: (p, a) => `${ctx.use('loop')}(${p}, ${a}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg})`,
247
+ }
248
+ }
249
+
250
+ function emitTextSlotOp(
251
+ ctx: DomCompilerCtx,
252
+ tree: ElementTreeState,
253
+ elVar: string,
254
+ domIndex: number,
255
+ marker: HydrationMarker,
256
+ open: string,
257
+ close: string,
258
+ exprCode: string,
259
+ expr: Node,
260
+ scopeRewrites: ReadonlyMap<string, string>,
261
+ ): { html: string, nextIndex: number } {
262
+ const txtVar = ctx.freshVar('_txt')
263
+ let html: string
264
+ let nextIndex: number
265
+ if (marker === 'none') {
266
+ html = ' '
267
+ nextIndex = domIndex + 1
268
+ tree.ops.push(`const ${txtVar} = ${ctx.use('firstText')}(${elVar});`)
269
+ }
270
+ else {
271
+ const markerVar = requestTreeChild(ctx, tree, elVar, domIndex)
272
+ if (marker === 'text') {
273
+ html = `${open} ${close}`
274
+ addSlot(tree.textSlotsByParent, elVar, domIndex + 1)
275
+ nextIndex = domIndex + 3
276
+ }
277
+ else {
278
+ html = `${open} `
279
+ nextIndex = domIndex + 2
280
+ }
281
+ tree.ops.push(`const ${txtVar} = ${ctx.use('textAfter')}(${markerVar});`)
282
+ }
283
+ tree.ops.push(formatSetTextOp(txtVar, exprCode, expr, scopeRewrites, ctx.use))
284
+ return { html, nextIndex }
285
+ }
286
+
287
+ function buildElementHtml(
288
+ ctx: DomCompilerCtx,
289
+ tree: ElementTreeState,
290
+ el: JSXElement,
291
+ elVar: string,
292
+ scopeRewrites: ReadonlyMap<string, string>,
293
+ ): string {
294
+ const tag = jsxTagName(el.openingElement.name)
295
+ const rawTextTag = RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined
296
+ const postChildOps: string[] = []
297
+ const attrHtml = compileElementAttributes({
298
+ el,
299
+ tag,
300
+ elVar,
301
+ scopeRewrites,
302
+ staticStyleNames: ctx.staticStyleNames,
303
+ ops: tree.ops,
304
+ postChildOps,
305
+ delegatedEvents: ctx.delegatedEvents,
306
+ use: ctx.use,
307
+ freshVar: ctx.freshVar,
308
+ compileExpression: ctx.compileExpression,
309
+ })
310
+
311
+ let html = `<${tag}${ctx.devSrc(el, tag)}${attrHtml}>`
312
+ if (VOID_ELEMENTS.has(tag))
313
+ return html
314
+
315
+ if (rawTextTag !== undefined) {
316
+ html += compileRawTextChildren(el, rawTextTag, elVar, scopeRewrites, tree.ops, ctx.use, ctx.compileExpression)
317
+ return `${html}</${tag}>`
318
+ }
319
+
320
+ const planned = planChildSlots(el.children, { jsxNodes: ctx.jsxNodes, exprContext: ctx.exprContext })
321
+ let domIndex = 0
322
+ let prevWasStaticText = false
323
+
324
+ const claimRangeAnchor = (marker: HydrationMarker, open: string, close: string): string => {
325
+ if (marker !== 'range')
326
+ return 'null'
327
+ const v = requestTreeChild(ctx, tree, elVar, domIndex)
328
+ html += open + close
329
+ addSlot(tree.rangeSlotsByParent, elVar, domIndex + 1)
330
+ domIndex += 2
331
+ return v
332
+ }
333
+
334
+ const emitInsert = (valueCode: string, marker: HydrationMarker, open: string, close: string): void => {
335
+ if (marker === 'none') {
336
+ tree.ops.push(`${ctx.use('insert')}(${elVar}, () => ${valueCode}, null, null);`)
337
+ }
338
+ else if (marker === 'range-open') {
339
+ const startVar = requestTreeChild(ctx, tree, elVar, domIndex)
340
+ html += open
341
+ domIndex++
342
+ tree.ops.push(`${ctx.use('insert')}(${elVar}, () => ${valueCode}, null, ${startVar});`)
343
+ }
344
+ else {
345
+ const startVar = requestTreeChild(ctx, tree, elVar, domIndex)
346
+ const endVar = requestTreeChild(ctx, tree, elVar, domIndex + 1)
347
+ html += open + close
348
+ addSlot(tree.rangeSlotsByParent, elVar, domIndex + 1)
349
+ domIndex += 2
350
+ tree.ops.push(`${ctx.use('insert')}(${elVar}, () => ${valueCode}, ${endVar}, ${startVar});`)
351
+ }
352
+ }
353
+
354
+ const prevSvgDepth = ctx.svgDepth
355
+ if (tag === 'svg')
356
+ ctx.svgDepth = 1
357
+ else if (tag === 'foreignObject' || tag === 'math')
358
+ ctx.svgDepth = 0
359
+
360
+ try {
361
+ for (const { slot, marker, open, close, nodeCapable } of planned) {
362
+ if (slot.kind === 'static-text') {
363
+ html += escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text))
364
+ if (!prevWasStaticText) {
365
+ domIndex++
366
+ prevWasStaticText = true
367
+ }
368
+ continue
369
+ }
370
+
371
+ prevWasStaticText = false
372
+
373
+ if (slot.kind === 'element') {
374
+ const subOpsBefore = tree.ops.length
375
+ const subWalkBefore = tree.walkPlan.length
376
+ const placeholderVar = `__SUB_${ctx.nextVarId()}`
377
+ const subHtml = buildElementHtml(ctx, tree, slot.node, placeholderVar, scopeRewrites)
378
+ if (tree.ops.length > subOpsBefore || tree.walkPlan.length > subWalkBefore)
379
+ tree.varAliases.set(placeholderVar, requestTreeChild(ctx, tree, elVar, domIndex))
380
+ html += subHtml
381
+ domIndex++
382
+ continue
383
+ }
384
+
385
+ if (slot.kind === 'component' || slot.kind === 'fragment') {
386
+ const renderedCode = slot.kind === 'component'
387
+ ? compileComponentCall(ctx, slot.node, scopeRewrites)
388
+ : compileRootJsx(ctx, slot.node, scopeRewrites)
389
+ emitInsert(renderedCode, marker, open, close)
390
+ continue
391
+ }
392
+
393
+ if (slot.kind === 'loop') {
394
+ const anchorVar = claimRangeAnchor(marker, open, close)
395
+ const skipArg = marker === 'none' && domIndex > 0 ? `, ${domIndex}` : ''
396
+ const compiled = compileLoopCall(ctx, slot.match, scopeRewrites, skipArg)
397
+ tree.ops.push(`${compiled.call(elVar, anchorVar)};`)
398
+ continue
399
+ }
400
+
401
+ if (slot.kind === 'and-show') {
402
+ const anchorVar = claimRangeAnchor(marker, open, close)
403
+ const whenCode = ctx.compileExpression(slot.expr.left, scopeRewrites)
404
+ const trueCode = compileRootJsx(ctx, slot.right, scopeRewrites)
405
+ tree.ops.push(`${ctx.use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode});`)
406
+ continue
407
+ }
408
+
409
+ if (slot.kind === 'ternary-show') {
410
+ const anchorVar = claimRangeAnchor(marker, open, close)
411
+ const whenCode = ctx.compileExpression(slot.expr.test, scopeRewrites)
412
+ const trueCode = isJsxNode(slot.cons) ? compileRootJsx(ctx, slot.cons, scopeRewrites) : ctx.compileExpression(slot.cons, scopeRewrites)
413
+ const falseCode = isJsxNode(slot.alt) ? compileRootJsx(ctx, slot.alt, scopeRewrites) : ctx.compileExpression(slot.alt, scopeRewrites)
414
+ tree.ops.push(`${ctx.use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode});`)
415
+ continue
416
+ }
417
+
418
+ const exprCode = ctx.compileExpression(slot.expr, scopeRewrites)
419
+ if (nodeCapable) {
420
+ emitInsert(exprCode, marker, open, close)
421
+ }
422
+ else {
423
+ const res = emitTextSlotOp(ctx, tree, elVar, domIndex, marker, open, close, exprCode, slot.expr, scopeRewrites)
424
+ html += res.html
425
+ domIndex = res.nextIndex
426
+ }
427
+ }
428
+ }
429
+ finally {
430
+ ctx.svgDepth = prevSvgDepth
431
+ }
432
+
433
+ for (const op of postChildOps)
434
+ tree.ops.push(op)
435
+
436
+ return `${html}</${tag}>`
437
+ }
438
+
439
+ function compileElementTree(ctx: DomCompilerCtx, rootEl: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
440
+ const rootVar = ctx.freshVar('_e')
441
+ const tree: ElementTreeState = {
442
+ ops: [],
443
+ walkPlan: [],
444
+ childRefs: new Map(),
445
+ textSlotsByParent: new Map(),
446
+ rangeSlotsByParent: new Map(),
447
+ varAliases: new Map(),
448
+ }
449
+
450
+ const html = buildElementHtml(ctx, tree, rootEl, rootVar, scopeRewrites)
451
+ resolveElementAliases(tree)
452
+
453
+ const rootTag = jsxTagName(rootEl.openingElement.name)
454
+ const tmplName = `_t${ctx.templates.length}`
455
+ const isSvg = ctx.svgDepth > 0 ? rootTag !== 'svg' : SVG_CHILD_TAGS.has(rootTag)
456
+ ctx.templates.push({ name: tmplName, html, isSvg })
457
+
458
+ const walkStmts = emitWalkStatements(rootVar, tree.walkPlan, tree.textSlotsByParent, tree.rangeSlotsByParent, ctx.use)
459
+ if (walkStmts.length === 0 && tree.ops.length === 0)
460
+ return `${tmplName}()`
461
+
462
+ return `(() => { const ${rootVar} = ${tmplName}(); ${walkStmts.join(' ')} ${tree.ops.join(' ')} return ${rootVar}; })()`
463
+ }
464
+
465
+ function compileFragmentChildren(ctx: DomCompilerCtx, children: readonly JSXChild[], scopeRewrites: ReadonlyMap<string, string>): string {
466
+ const planned = planChildSlots(children, { jsxNodes: ctx.jsxNodes, exprContext: ctx.exprContext, inFragment: true })
467
+ if (planned.length === 0)
468
+ return 'null'
469
+
470
+ const hasSiblings = planned.length > 1
471
+ // Coalesce consecutive static-text slots (e.g. `<>a{"b"}c</>`) so DOM matches the single merged SSR text node.
472
+ const items: string[] = []
473
+ let pendingStatic: string | undefined
474
+ const flushStatic = () => {
475
+ if (pendingStatic !== undefined) {
476
+ items.push(`${ctx.use('fragText')}(${JSON.stringify(pendingStatic)})`)
477
+ pendingStatic = undefined
478
+ }
479
+ }
480
+
481
+ const emitFragRangeOp = (hydrateCall: string, mountCall: string, needsRemoveChild: boolean): string => {
482
+ const removeProp = needsRemoveChild ? ', removeChild: (n) => n.parentNode && n.parentNode.removeChild(n)' : ''
483
+ return `(() => { const _s = ${ctx.use('claimRange')}(); if (_s !== null) { ${hydrateCall}; return null; } const _f = document.createDocumentFragment(); _f.appendChild(document.createComment("")); const _m = _f.appendChild(document.createComment("")); const _p = { insertBefore: (n, r) => (_m.parentNode || _f).insertBefore(n, r)${removeProp} }; ${mountCall}; return _f; })()`
484
+ }
485
+
486
+ for (const { slot, marker } of planned) {
487
+ if (slot.kind === 'static-text') {
488
+ const decoded = slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text)
489
+ pendingStatic = pendingStatic === undefined ? decoded : pendingStatic + decoded
490
+ continue
491
+ }
492
+ flushStatic()
493
+
494
+ if (slot.kind === 'element') {
495
+ items.push(compileRootJsx(ctx, slot.node, scopeRewrites))
496
+ }
497
+ else if (slot.kind === 'component' || slot.kind === 'fragment') {
498
+ const rendered = compileRootJsx(ctx, slot.node, scopeRewrites)
499
+ items.push(hasSiblings ? `${ctx.use('fragInsert')}(() => ${rendered})` : rendered)
500
+ }
501
+ else if (slot.kind === 'loop') {
502
+ const compiled = compileLoopCall(ctx, slot.match, scopeRewrites)
503
+ if (compiled.isStatic)
504
+ items.push(`(() => { const _s = ${ctx.use('claimRange')}(); if (_s !== null) { ${compiled.call('_s.parentNode', '_s')}; return null; } const _f = document.createDocumentFragment(); ${compiled.call('_f', 'null')}; return _f; })()`)
505
+ else
506
+ items.push(emitFragRangeOp(compiled.call('_s.parentNode', '_s'), compiled.call('_p', '_m'), true))
507
+ }
508
+ else if (slot.kind === 'and-show') {
509
+ const whenCode = ctx.compileExpression(slot.expr.left, scopeRewrites)
510
+ const trueCode = compileRootJsx(ctx, slot.right, scopeRewrites)
511
+ items.push(emitFragRangeOp(
512
+ `${ctx.use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode})`,
513
+ `${ctx.use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode})`,
514
+ false,
515
+ ))
516
+ }
517
+ else if (slot.kind === 'ternary-show') {
518
+ const whenCode = ctx.compileExpression(slot.expr.test, scopeRewrites)
519
+ const trueCode = isJsxNode(slot.cons) ? compileRootJsx(ctx, slot.cons, scopeRewrites) : ctx.compileExpression(slot.cons, scopeRewrites)
520
+ const falseCode = isJsxNode(slot.alt) ? compileRootJsx(ctx, slot.alt, scopeRewrites) : ctx.compileExpression(slot.alt, scopeRewrites)
521
+ items.push(emitFragRangeOp(
522
+ `${ctx.use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
523
+ `${ctx.use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
524
+ false,
525
+ ))
526
+ }
527
+ else {
528
+ const exprCode = ctx.compileExpression(slot.expr, scopeRewrites)
529
+ if (marker === 'range')
530
+ items.push(`${ctx.use('fragInsert')}(() => (${exprCode}))`)
531
+ else
532
+ items.push(`(() => { const _t = ${ctx.use('fragText')}("", true); ${formatSetTextOp('_t', `(${exprCode})`, slot.expr, scopeRewrites, ctx.use)} return _t; })()`)
533
+ }
534
+ }
535
+ flushStatic()
536
+
537
+ return items.length === 1 ? items[0]! : `${ctx.use('frag')}(${items.join(', ')})`
538
+ }
539
+
540
+ function compileRootJsx(ctx: DomCompilerCtx, node: JSXElement | JSXFragment, scopeRewrites: ReadonlyMap<string, string>): string {
541
+ if (node.type === 'JSXFragment')
542
+ return compileFragmentChildren(ctx, node.children, scopeRewrites)
543
+ return isComponentTag(jsxTagName(node.openingElement.name))
544
+ ? compileComponentCall(ctx, node, scopeRewrites)
545
+ : compileElementTree(ctx, node, scopeRewrites)
546
+ }
547
+
548
+ export function compileDom(filename: string, code: string, options: CompileDomOptions = {}): CompileDomResult {
549
+ const program = options.analysis?.program ?? parseTsx(filename, code)
550
+ const analysis = options.analysis ?? analyzeModule(filename, code, program)
551
+
552
+ if (!analysis.hasJsx && !analysis.hasLoadExport)
553
+ return { code, analysis }
554
+
555
+ const staticArrays = literalArrayConsts(program)
556
+ const loadNodes = new Set<Node>(loadDeclarations(program))
557
+ const jsxNodes = analysis.jsxNodes
558
+ const exprContext = getExprContext(analysis)
559
+ const staticStyleNames = collectStaticStyleNames(program, exprContext.primitiveVars)
560
+ const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
561
+
562
+ const editor = new SourceEditor(code)
563
+ const used = new Set<string>()
564
+ const templates: { name: string, html: string, isSvg?: boolean }[] = []
565
+ const delegatedEvents = new Set<string>()
566
+ let varCounter = 0
567
+
568
+ const use = (name: string): string => {
569
+ used.add(name)
570
+ return `__${name}`
571
+ }
572
+ const freshVar = (prefix = '_e'): string => `${prefix}${varCounter++}`
573
+
574
+ // Client builds keep the `load` binding, so every export form stays valid, and drop its server-only code.
575
+ for (const node of loadNodes) {
576
+ if (node.type === 'FunctionDeclaration' && node.id !== null)
577
+ editor.replace(node.start, node.end, `const ${node.id.name} = undefined`)
578
+ else
579
+ editor.replace(node.start, node.end, 'undefined')
580
+ }
581
+
582
+ const { compileLoopRow, withPrelude, extractDestructuredParam, buildCompiledFunction, processFunction } = createPropCompiler({
583
+ code,
584
+ editor,
585
+ jsxNodes,
586
+ use,
587
+ freshVar,
588
+ compileExpression: (node, rewrites) => compileExpression(node, rewrites),
589
+ })
590
+
591
+ function compileNestedComponent(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string | undefined {
592
+ if (!containsJsx(fn.body, jsxNodes))
593
+ return undefined
594
+ if (extractDestructuredParam(fn.params[0]) === undefined)
595
+ return undefined
596
+ return buildCompiledFunction(fn, outerRewrites)
597
+ }
598
+
599
+ function compileExpression(node: Node, scopeRewrites: ReadonlyMap<string, string>): string {
600
+ return rewriteFreeIdentifiers(code, node, scopeRewrites, jsxNodes, (n, r) => compileRootJsx(ctx, n, r), compileNestedComponent)
601
+ }
602
+
603
+ const ctx: DomCompilerCtx = {
604
+ code,
605
+ analysis,
606
+ jsxNodes,
607
+ exprContext,
608
+ staticArrays,
609
+ staticStyleNames,
610
+ devSrc,
611
+ templates,
612
+ delegatedEvents,
613
+ svgDepth: 0,
614
+ use,
615
+ freshVar,
616
+ nextVarId: () => varCounter++,
617
+ compileExpression,
618
+ compileLoopRow,
619
+ withPrelude,
620
+ }
621
+
622
+ walk(program, (node) => {
623
+ if (loadNodes.has(node))
624
+ return false
625
+ if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
626
+ processFunction(node)
627
+ return false
628
+ }
629
+ if (isJsxNode(node)) {
630
+ editor.replace(node.start, node.end, compileRootJsx(ctx, node, new Map()))
631
+ return false
632
+ }
633
+ return undefined
634
+ })
635
+
636
+ const header = moduleHeader(used, templates, delegatedEvents)
637
+ if (header !== '')
638
+ editor.prepend(header)
639
+
640
+ return { code: editor.toString(), analysis }
641
+ }