prunelle 0.0.0-stage → 0.2.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 (181) hide show
  1. package/llms.txt +148 -0
  2. package/package.json +53 -4
  3. package/src/ambient.d.ts +6 -0
  4. package/src/attrs.ts +35 -0
  5. package/src/build/bundle.ts +613 -0
  6. package/src/build/carry.ts +57 -0
  7. package/src/build/client-entries.ts +107 -0
  8. package/src/build/client-plugin.ts +169 -0
  9. package/src/build/client-prune.ts +118 -0
  10. package/src/build/compile.ts +128 -0
  11. package/src/build/files.ts +156 -0
  12. package/src/build/first-load.ts +164 -0
  13. package/src/build/graph.ts +247 -0
  14. package/src/build/index.ts +614 -0
  15. package/src/build/is-inside.ts +12 -0
  16. package/src/build/islands.ts +641 -0
  17. package/src/build/manifest.ts +281 -0
  18. package/src/build/output.ts +84 -0
  19. package/src/build/plugin-host.ts +220 -0
  20. package/src/build/precompress.ts +139 -0
  21. package/src/build/prerender.ts +150 -0
  22. package/src/build/render-rules.ts +205 -0
  23. package/src/build/report.ts +247 -0
  24. package/src/build/resolve.ts +50 -0
  25. package/src/build/routes.ts +338 -0
  26. package/src/build/server-entry.ts +38 -0
  27. package/src/build/static.ts +163 -0
  28. package/src/build/status-pages.ts +127 -0
  29. package/src/cli/check-forms.ts +654 -0
  30. package/src/cli/check-links.ts +619 -0
  31. package/src/cli/check.ts +367 -0
  32. package/src/cli/commands.ts +265 -0
  33. package/src/cli/index.ts +70 -0
  34. package/src/cli/inspect.ts +335 -0
  35. package/src/cli/new.ts +41 -0
  36. package/src/cli/upgrade-names.ts +209 -0
  37. package/src/cli/upgrade.ts +354 -0
  38. package/src/compiler/analyze.ts +618 -0
  39. package/src/compiler/ast.ts +82 -0
  40. package/src/compiler/browser-globals.ts +127 -0
  41. package/src/compiler/compliance-rgaa.ts +502 -0
  42. package/src/compiler/compliance.ts +497 -0
  43. package/src/compiler/data-keys.ts +295 -0
  44. package/src/compiler/dom-attrs.ts +379 -0
  45. package/src/compiler/dom.ts +566 -0
  46. package/src/compiler/emit.ts +131 -0
  47. package/src/compiler/expr-context.ts +408 -0
  48. package/src/compiler/index.ts +8 -0
  49. package/src/compiler/interactivity.ts +366 -0
  50. package/src/compiler/mistakes.ts +499 -0
  51. package/src/compiler/node-env.ts +50 -0
  52. package/src/compiler/patch.ts +97 -0
  53. package/src/compiler/props.ts +460 -0
  54. package/src/compiler/scope.ts +568 -0
  55. package/src/compiler/server-only.ts +326 -0
  56. package/src/compiler/shared.ts +369 -0
  57. package/src/compiler/signal-reads.ts +242 -0
  58. package/src/compiler/slots.ts +227 -0
  59. package/src/compiler/ssr-helpers.ts +555 -0
  60. package/src/compiler/ssr-island.ts +90 -0
  61. package/src/compiler/ssr-prunelle-tags.ts +56 -0
  62. package/src/compiler/ssr.ts +491 -0
  63. package/src/context.ts +165 -0
  64. package/src/dev/child.ts +30 -0
  65. package/src/dev/index.ts +208 -0
  66. package/src/dev/modules.ts +68 -0
  67. package/src/dev/protocol.ts +21 -0
  68. package/src/dev/queue.ts +79 -0
  69. package/src/dev/reload.ts +157 -0
  70. package/src/dev/supervisor.ts +187 -0
  71. package/src/dev/watchers.ts +215 -0
  72. package/src/dom/action.ts +164 -0
  73. package/src/dom/attrs.ts +72 -0
  74. package/src/dom/claim.ts +120 -0
  75. package/src/dom/extras.ts +562 -0
  76. package/src/dom/index.ts +289 -0
  77. package/src/dom/island.ts +284 -0
  78. package/src/dom/loop.ts +450 -0
  79. package/src/dom/revive.ts +36 -0
  80. package/src/index.ts +22 -0
  81. package/src/jsx-runtime.ts +566 -0
  82. package/src/plugins/config.ts +86 -0
  83. package/src/plugins/context.ts +66 -0
  84. package/src/plugins/index.ts +14 -0
  85. package/src/plugins/load.ts +70 -0
  86. package/src/plugins/order.ts +111 -0
  87. package/src/plugins/public.ts +12 -0
  88. package/src/plugins/requires.ts +47 -0
  89. package/src/plugins/services.ts +35 -0
  90. package/src/plugins/types.ts +242 -0
  91. package/src/reactivity/graph.ts +249 -0
  92. package/src/reactivity/index.ts +533 -0
  93. package/src/reactivity/selector.ts +51 -0
  94. package/src/reactivity/store.ts +208 -0
  95. package/src/server/action-protect.ts +186 -0
  96. package/src/server/action-registry.ts +78 -0
  97. package/src/server/action.ts +498 -0
  98. package/src/server/app-entry.ts +23 -0
  99. package/src/server/assets.ts +136 -0
  100. package/src/server/compress.ts +560 -0
  101. package/src/server/consent.ts +253 -0
  102. package/src/server/cookies.ts +139 -0
  103. package/src/server/document.ts +271 -0
  104. package/src/server/env.ts +33 -0
  105. package/src/server/errors.ts +382 -0
  106. package/src/server/form-schema.ts +343 -0
  107. package/src/server/health.ts +244 -0
  108. package/src/server/http.ts +508 -0
  109. package/src/server/index.ts +687 -0
  110. package/src/server/lifecycle.ts +75 -0
  111. package/src/server/loader.ts +118 -0
  112. package/src/server/page.ts +107 -0
  113. package/src/server/param-matchers.ts +112 -0
  114. package/src/server/plugin-host.ts +256 -0
  115. package/src/server/prerendered.ts +71 -0
  116. package/src/server/public.ts +19 -0
  117. package/src/server/rate-limit.ts +133 -0
  118. package/src/server/region.ts +96 -0
  119. package/src/server/request-body.ts +27 -0
  120. package/src/server/request-path.ts +73 -0
  121. package/src/server/request-scope.ts +22 -0
  122. package/src/server/route-table.ts +82 -0
  123. package/src/server/router.ts +261 -0
  124. package/src/server/routing.ts +377 -0
  125. package/src/server/security.ts +472 -0
  126. package/src/server/serve-handlers.ts +83 -0
  127. package/src/server/served-file.ts +128 -0
  128. package/src/server/standard-schema.ts +87 -0
  129. package/src/server/start.ts +99 -0
  130. package/src/server/static-dir.ts +167 -0
  131. package/src/server/stream.ts +192 -0
  132. package/src/ssr/context.ts +350 -0
  133. package/src/ssr/index.ts +596 -0
  134. package/src/ssr/navigation.ts +96 -0
  135. package/src/ssr/region.ts +171 -0
  136. package/src/style.ts +33 -0
  137. package/src/test/browser.ts +192 -0
  138. package/src/test/index.ts +191 -0
  139. package/src/unrenderable.ts +35 -0
  140. package/templates/_shared/AGENTS.md +10 -0
  141. package/templates/_shared/CLAUDE.md +1 -0
  142. package/templates/_shared/gitignore +3 -0
  143. package/templates/_shared/public/robots.txt +2 -0
  144. package/templates/_shared/src/routes/legal.tsx +13 -0
  145. package/templates/_shared/tsconfig.json +20 -0
  146. package/templates/app/.env.example +4 -0
  147. package/templates/app/package.json +21 -0
  148. package/templates/app/prunelle.config.ts +11 -0
  149. package/templates/app/src/auth.ts +14 -0
  150. package/templates/app/src/routes/_layout.tsx +32 -0
  151. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  152. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  153. package/templates/app/src/routes/index.tsx +15 -0
  154. package/templates/app/src/routes/login.tsx +34 -0
  155. package/templates/app/src/styles/app.css +7 -0
  156. package/templates/app/tests/app.test.ts +32 -0
  157. package/templates/blog/content/posts/welcome.md +9 -0
  158. package/templates/blog/package.json +22 -0
  159. package/templates/blog/prunelle.config.ts +23 -0
  160. package/templates/blog/src/posts.ts +26 -0
  161. package/templates/blog/src/routes/_layout.tsx +20 -0
  162. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  163. package/templates/blog/src/routes/index.tsx +33 -0
  164. package/templates/blog/src/styles/app.css +10 -0
  165. package/templates/fullstack/package.json +19 -0
  166. package/templates/fullstack/prunelle.config.ts +6 -0
  167. package/templates/fullstack/src/actions/greet.ts +19 -0
  168. package/templates/fullstack/src/components/Counter.tsx +10 -0
  169. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  170. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  171. package/templates/fullstack/src/routes/api/health.ts +5 -0
  172. package/templates/fullstack/src/routes/index.tsx +13 -0
  173. package/templates/fullstack/src/styles/app.css +29 -0
  174. package/templates/fullstack/tests/app.test.ts +37 -0
  175. package/templates/minimal/package.json +19 -0
  176. package/templates/minimal/prunelle.config.ts +6 -0
  177. package/templates/minimal/src/components/Counter.tsx +10 -0
  178. package/templates/minimal/src/routes/_layout.tsx +14 -0
  179. package/templates/minimal/src/routes/index.tsx +11 -0
  180. package/templates/minimal/src/styles/app.css +22 -0
  181. package/README.md +0 -3
@@ -0,0 +1,555 @@
1
+ // Helper utilities for the SSR compiler: string buffer builder, static attribute folding, component prop serialization, and `<select>`/`<option>` helpers.
2
+
3
+ import type { JSXAttributeItem, JSXChild, JSXElement, Node, Program } from 'oxc-parser'
4
+ import { visitorKeys } from 'oxc-parser'
5
+ import { URL_ATTRS } from '../attrs'
6
+ import { styleText } from '../style'
7
+ import {
8
+ cleanJsxText,
9
+ decodeHtmlEntities,
10
+ escapeStaticAttr,
11
+ EVENT_ATTR,
12
+ filterMeaningfulChildren,
13
+ isBlockedAttr,
14
+ isComponentTag,
15
+ isStringBoolAttr,
16
+ isUnsafeUrlAttr,
17
+ jsxTagName,
18
+ staticLiteral,
19
+ unwrapTsExpr,
20
+ } from './shared'
21
+
22
+ export interface SsrSubtreeFlags {
23
+ directAwaitNodes: WeakSet<Node>
24
+ dynamicChildNodes: WeakSet<Node>
25
+ }
26
+
27
+ const AWAIT_BIT = 1
28
+ const DYNAMIC_BIT = 2
29
+
30
+ function isFunctionNode(type: string): boolean {
31
+ return type === 'FunctionDeclaration' || type === 'FunctionExpression' || type === 'ArrowFunctionExpression'
32
+ }
33
+
34
+ /** Precomputes direct-await and dynamic-JSX-child subtree membership in a single O(N) bottom-up pass. */
35
+ export function precomputeSsrSubtreeFlags(program: Program): SsrSubtreeFlags {
36
+ const directAwaitNodes = new WeakSet<Node>()
37
+ const dynamicChildNodes = new WeakSet<Node>()
38
+
39
+ const visit = (node: unknown): number => {
40
+ if (node === null || typeof node !== 'object')
41
+ return 0
42
+ if (Array.isArray(node)) {
43
+ let mask = 0
44
+ for (let i = 0; i < node.length; i++)
45
+ mask |= visit(node[i])
46
+ return mask
47
+ }
48
+ const ast = node as Node
49
+ const type = ast.type
50
+ if (typeof type !== 'string')
51
+ return 0
52
+
53
+ let mask = 0
54
+ if (type === 'AwaitExpression') {
55
+ mask |= AWAIT_BIT
56
+ }
57
+ else if (
58
+ (type === 'JSXExpressionContainer' && ast.expression.type !== 'JSXEmptyExpression')
59
+ || (type === 'JSXElement' && isComponentTag(jsxTagName(ast.openingElement.name)))
60
+ ) {
61
+ mask |= DYNAMIC_BIT
62
+ }
63
+
64
+ const keys = visitorKeys[type]
65
+ const rec = ast as unknown as Record<string, unknown>
66
+ if (keys !== undefined) {
67
+ for (let i = 0; i < keys.length; i++)
68
+ mask |= visit(rec[keys[i]!])
69
+ }
70
+ else {
71
+ for (const [k, v] of Object.entries(rec)) {
72
+ if (k !== 'start' && k !== 'end' && k !== 'type')
73
+ mask |= visit(v)
74
+ }
75
+ }
76
+
77
+ if ((mask & AWAIT_BIT) !== 0)
78
+ directAwaitNodes.add(ast)
79
+ if ((mask & DYNAMIC_BIT) !== 0)
80
+ dynamicChildNodes.add(ast)
81
+ return isFunctionNode(type) ? (mask & ~AWAIT_BIT) : mask
82
+ }
83
+
84
+ visit(program)
85
+ return { directAwaitNodes, dynamicChildNodes }
86
+ }
87
+
88
+ export class StringParts {
89
+ #parts: { static: boolean, value: string }[] = []
90
+
91
+ pushStatic(str: string): void {
92
+ if (str === '')
93
+ return
94
+ const last = this.#parts[this.#parts.length - 1]
95
+ if (last !== undefined && last.static)
96
+ last.value += str
97
+ else
98
+ this.#parts.push({ static: true, value: str })
99
+ }
100
+
101
+ pushExpr(code: string): void {
102
+ this.#parts.push({ static: false, value: code })
103
+ }
104
+
105
+ isEmpty(): boolean {
106
+ return this.#parts.length === 0
107
+ }
108
+
109
+ clear(): void {
110
+ this.#parts.length = 0
111
+ }
112
+
113
+ toExpr(): string {
114
+ if (this.#parts.length === 0)
115
+ return '""'
116
+ return this.#parts
117
+ .map(p => (p.static ? JSON.stringify(p.value) : `(${p.value})`))
118
+ .join(' + ')
119
+ }
120
+ }
121
+
122
+ function isStaticNullish(node: Node): boolean {
123
+ return (node.type === 'Identifier' && node.name === 'undefined')
124
+ || (node.type === 'Literal' && node.value === null)
125
+ }
126
+
127
+ export function staticLiteralOrTemplate(node: Node): { ok: true, value: string | number | boolean | null } | { ok: false } {
128
+ const n = unwrapTsExpr(node)
129
+ if (n.type === 'TemplateLiteral' && n.expressions.length === 0 && n.quasis.length === 1) {
130
+ const cooked = n.quasis[0]?.value.cooked
131
+ if (typeof cooked === 'string')
132
+ return { ok: true, value: cooked }
133
+ }
134
+ return staticLiteral(n)
135
+ }
136
+
137
+ export function formatStaticAttrValue(name: string, value: string | number | boolean | null, tag?: string): string {
138
+ if (value === null || isBlockedAttr(name))
139
+ return ''
140
+ if (typeof value === 'boolean') {
141
+ if (isStringBoolAttr(name))
142
+ return ` ${name}="${value ? 'true' : 'false'}"`
143
+ return value ? ` ${name}` : ''
144
+ }
145
+ if (isUnsafeUrlAttr(name, value, tag)) {
146
+ if (process.env.NODE_ENV !== 'production')
147
+ console.warn(`prunelle: dropped unsafe URL on <${tag ?? 'element'} ${name}>.`)
148
+ return ''
149
+ }
150
+ return ` ${name}="${escapeStaticAttr(String(value))}"`
151
+ }
152
+
153
+ export function staticStyleObject(node: Node): Record<string, string | number | boolean | null> | undefined {
154
+ const n = unwrapTsExpr(node)
155
+ if (n.type !== 'ObjectExpression')
156
+ return undefined
157
+ const obj: Record<string, string | number | boolean | null> = {}
158
+ for (const prop of n.properties) {
159
+ if (prop.type !== 'Property' || prop.kind !== 'init' || prop.computed)
160
+ return undefined
161
+ let key: string
162
+ if (prop.key.type === 'Identifier')
163
+ key = prop.key.name
164
+ else if (prop.key.type === 'Literal' && (typeof prop.key.value === 'string' || typeof prop.key.value === 'number'))
165
+ key = String(prop.key.value)
166
+ else
167
+ return undefined
168
+ if (key === '__proto__')
169
+ return undefined
170
+ const lit = staticLiteralOrTemplate(prop.value)
171
+ if (!lit.ok)
172
+ return undefined
173
+ obj[key] = lit.value
174
+ }
175
+ return obj
176
+ }
177
+
178
+ export function formatStaticStyleExpr(expr: Node): string | undefined {
179
+ const unwrapped = unwrapTsExpr(expr)
180
+ const lit = staticLiteralOrTemplate(unwrapped)
181
+ if (lit.ok)
182
+ return typeof lit.value === 'string' ? ` style="${escapeStaticAttr(lit.value)}"` : ''
183
+ if (isStaticNullish(unwrapped))
184
+ return ''
185
+ const obj = staticStyleObject(unwrapped)
186
+ if (obj !== undefined) {
187
+ const css = styleText(obj)
188
+ return css === '' ? '' : ` style="${escapeStaticAttr(css)}"`
189
+ }
190
+ return undefined
191
+ }
192
+
193
+ export function formatStaticAttrBranch(attrName: string, node: Node, tag?: string): string | undefined {
194
+ if (isBlockedAttr(attrName))
195
+ return '""'
196
+ const unwrapped = unwrapTsExpr(node)
197
+ if (isStaticNullish(unwrapped))
198
+ return '""'
199
+ const lit = staticLiteralOrTemplate(unwrapped)
200
+ if (lit.ok)
201
+ return JSON.stringify(formatStaticAttrValue(attrName, lit.value, tag))
202
+ return undefined
203
+ }
204
+
205
+ export function serializeComponentProps(
206
+ attrs: readonly JSXAttributeItem[],
207
+ compileSubExpression: (node: Node) => string,
208
+ ): {
209
+ propEntries: string[]
210
+ allStaticProps: boolean
211
+ staticPropsObj: Record<string, unknown>
212
+ hydrateExpr: string | undefined
213
+ staticHydrate: string | undefined
214
+ } {
215
+ const propEntries: string[] = []
216
+ let allStaticProps = true
217
+ const staticPropsObj: Record<string, unknown> = {}
218
+ let hydrateExpr: string | undefined
219
+ let staticHydrate: string | undefined
220
+
221
+ for (const attr of attrs) {
222
+ if (attr.type === 'JSXSpreadAttribute') {
223
+ allStaticProps = false
224
+ propEntries.push(`...(${compileSubExpression(attr.argument)})`)
225
+ continue
226
+ }
227
+ const name = jsxTagName(attr.name)
228
+ if (name === 'key')
229
+ continue
230
+ if (name === '$hydrate') {
231
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
232
+ staticHydrate = attr.value.value
233
+ hydrateExpr = JSON.stringify(attr.value.value)
234
+ }
235
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
236
+ hydrateExpr = compileSubExpression(attr.value.expression)
237
+ }
238
+ continue
239
+ }
240
+
241
+ const propKey = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
242
+ if (attr.value === null) {
243
+ propEntries.push(`${propKey}: true`)
244
+ staticPropsObj[name] = true
245
+ }
246
+ else if (attr.value.type === 'Literal') {
247
+ propEntries.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
248
+ staticPropsObj[name] = attr.value.value
249
+ }
250
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
251
+ const expr = attr.value.expression
252
+ const lit = staticLiteral(expr)
253
+ if (lit.ok)
254
+ staticPropsObj[name] = lit.value
255
+ else
256
+ allStaticProps = false
257
+ propEntries.push(`${propKey}: ${compileSubExpression(expr)}`)
258
+ }
259
+ }
260
+
261
+ return { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate }
262
+ }
263
+
264
+ export interface SelectValueBinding {
265
+ staticValue?: string | undefined
266
+ expr?: string | undefined
267
+ multiple: boolean
268
+ }
269
+
270
+ export function isSimpleValueExpr(node: Node): boolean {
271
+ if (node.type === 'Identifier' || node.type === 'Literal')
272
+ return true
273
+ if (node.type === 'MemberExpression' && !node.computed && node.property.type === 'Identifier')
274
+ return isSimpleValueExpr(node.object)
275
+ return false
276
+ }
277
+
278
+ /** Extracts the static text value of an `<option>` when it has no explicit `value` attribute. */
279
+ export function staticOptionText(children: readonly JSXChild[]): string | undefined {
280
+ const meaningful = filterMeaningfulChildren(children)
281
+ if (meaningful.length === 0)
282
+ return ''
283
+ let out = ''
284
+ for (const c of meaningful) {
285
+ if (c.type === 'JSXText')
286
+ out += decodeHtmlEntities(cleanJsxText(c.value))
287
+ else if (c.type === 'JSXExpressionContainer' && c.expression.type === 'Literal' && (typeof c.expression.value === 'string' || typeof c.expression.value === 'number'))
288
+ out += String(c.expression.value)
289
+ else
290
+ return undefined
291
+ }
292
+ return out
293
+ }
294
+
295
+ export function formatOptionSelectedExpr(
296
+ selectVal: SelectValueBinding,
297
+ optVal: { staticValue?: string | undefined, expr?: string | undefined },
298
+ ): { staticSelected?: boolean | undefined, expr?: string | undefined } {
299
+ if (selectVal.staticValue !== undefined && optVal.staticValue !== undefined)
300
+ return { staticSelected: selectVal.staticValue === optVal.staticValue }
301
+ const sv = selectVal.staticValue !== undefined ? JSON.stringify(selectVal.staticValue) : selectVal.expr!
302
+ const ov = optVal.staticValue !== undefined ? JSON.stringify(optVal.staticValue) : optVal.expr!
303
+ if (selectVal.multiple) {
304
+ const cond = optVal.staticValue !== undefined
305
+ ? `Array.isArray(${sv}) ? ${sv}.some((_x) => String(_x) === ${ov}) : (${sv} != null && String(${sv}) === ${ov})`
306
+ : `${ov} != null && (Array.isArray(${sv}) ? ${sv}.some((_x) => String(_x) === String(${ov})) : (${sv} != null && String(${sv}) === String(${ov})))`
307
+ return { expr: `((${cond}) ? " selected" : "")` }
308
+ }
309
+ const cond = optVal.staticValue !== undefined
310
+ ? `${sv} != null && String(${sv}) === ${ov}`
311
+ : `${sv} != null && ${ov} != null && String(${sv}) === String(${ov})`
312
+ return { expr: `((${cond}) ? " selected" : "")` }
313
+ }
314
+
315
+ export interface SsrElementAttrsContext {
316
+ node: JSXElement
317
+ tag: string
318
+ parts: StringParts
319
+ activeSelectValue: SelectValueBinding | undefined
320
+ flushParts: () => void
321
+ pushStmt: (stmt: string) => void
322
+ nextId: () => number
323
+ use: (name: string) => string
324
+ compileSubExpression: (node: Node) => string
325
+ }
326
+
327
+ export interface SsrElementAttrsResult {
328
+ innerHtmlExpr: string | undefined
329
+ textareaValue: { staticText?: string | undefined, expr?: string | undefined } | undefined
330
+ nextSelectValue: SelectValueBinding | undefined
331
+ }
332
+
333
+ function emitSsrExprAttr(
334
+ ctx: SsrElementAttrsContext,
335
+ name: string,
336
+ expr: Node,
337
+ isOption: boolean,
338
+ ): { staticValue?: string | undefined, expr?: string | undefined } | undefined {
339
+ const { tag, parts, activeSelectValue, flushParts, pushStmt, nextId, use, compileSubExpression } = ctx
340
+
341
+ if (name === 'style') {
342
+ const staticStyle = formatStaticStyleExpr(expr)
343
+ if (staticStyle !== undefined)
344
+ parts.pushStatic(staticStyle)
345
+ else
346
+ parts.pushExpr(`${use('ssrStyle')}(${compileSubExpression(expr)})`)
347
+ return undefined
348
+ }
349
+
350
+ const unwrapped = unwrapTsExpr(expr)
351
+ const lit = staticLiteralOrTemplate(unwrapped)
352
+ if (lit.ok) {
353
+ parts.pushStatic(formatStaticAttrValue(name, lit.value, tag))
354
+ if (isOption && name === 'value' && (typeof lit.value === 'string' || typeof lit.value === 'number'))
355
+ return { staticValue: String(lit.value) }
356
+ return undefined
357
+ }
358
+ if (isStaticNullish(unwrapped))
359
+ return undefined
360
+
361
+ if (isOption && name === 'value' && activeSelectValue !== undefined) {
362
+ const exprCode = compileSubExpression(expr)
363
+ if (isSimpleValueExpr(expr)) {
364
+ parts.pushExpr(`${use('ssrAttr')}("value", ${exprCode})`)
365
+ return { expr: exprCode }
366
+ }
367
+ const ovVar = `_ov${nextId()}`
368
+ flushParts()
369
+ pushStmt(`const ${ovVar} = ${exprCode};`)
370
+ parts.pushExpr(`${use('ssrAttr')}("value", ${ovVar})`)
371
+ return { expr: ovVar }
372
+ }
373
+
374
+ if (expr.type === 'ConditionalExpression') {
375
+ const cons = formatStaticAttrBranch(name, expr.consequent, tag)
376
+ const alt = formatStaticAttrBranch(name, expr.alternate, tag)
377
+ if (cons !== undefined && alt !== undefined) {
378
+ parts.pushExpr(`${compileSubExpression(expr.test)} ? ${cons} : ${alt}`)
379
+ return undefined
380
+ }
381
+ }
382
+
383
+ const exprCode = compileSubExpression(expr)
384
+ if (URL_ATTRS.has(name.toLowerCase()))
385
+ parts.pushExpr(`${use('ssrAttr')}(${JSON.stringify(name)}, ${exprCode}, ${JSON.stringify(tag)})`)
386
+ else
387
+ parts.pushExpr(`${use('ssrAttr')}(${JSON.stringify(name)}, ${exprCode})`)
388
+ return undefined
389
+ }
390
+
391
+ /** Emits an HTML/SVG element's SSR opening attributes, handling spreads, `<textarea value>`, and `<select value>`/`<option>`. */
392
+ export function emitSsrElementAttrs(ctx: SsrElementAttrsContext): SsrElementAttrsResult {
393
+ const { node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId, use, compileSubExpression } = ctx
394
+ const attrs = node.openingElement.attributes
395
+ const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
396
+ const isTextarea = tag === 'textarea'
397
+ const isSelect = tag === 'select'
398
+ const isOption = tag === 'option'
399
+ let innerHtmlExpr: string | undefined
400
+ let textareaValue: { staticText?: string | undefined, expr?: string | undefined } | undefined
401
+ let nextSelectValue: SelectValueBinding | undefined
402
+ let optionValue: { staticValue?: string | undefined, expr?: string | undefined } | undefined
403
+ let optionHasExplicitSelected = false
404
+ const selectIsMultiple = isSelect && attrs.some(a => a.type === 'JSXAttribute' && jsxTagName(a.name) === 'multiple')
405
+ const spreadEntries: string[] = []
406
+
407
+ for (const attr of attrs) {
408
+ if (attr.type === 'JSXSpreadAttribute') {
409
+ spreadEntries.push(`...(${compileSubExpression(attr.argument)})`)
410
+ continue
411
+ }
412
+ const rawName = jsxTagName(attr.name)
413
+ if (rawName === 'key' || rawName === 'ref' || rawName === '$hydrate' || EVENT_ATTR.test(rawName))
414
+ continue
415
+ if (rawName === 'innerHTML') {
416
+ if (attr.value?.type === 'Literal') {
417
+ innerHtmlExpr = JSON.stringify(String(attr.value.value))
418
+ }
419
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
420
+ const lit = staticLiteralOrTemplate(attr.value.expression)
421
+ if (lit.ok)
422
+ innerHtmlExpr = lit.value === null || lit.value === false ? '""' : JSON.stringify(String(lit.value))
423
+ else
424
+ innerHtmlExpr = `${use('ssrRaw')}(${compileSubExpression(attr.value.expression)})`
425
+ }
426
+ continue
427
+ }
428
+
429
+ const name = rawName === 'className' ? 'class' : rawName === 'htmlFor' ? 'for' : rawName
430
+ if (isBlockedAttr(name))
431
+ continue
432
+
433
+ if (isTextarea && name === 'value') {
434
+ if (attr.value?.type === 'Literal') {
435
+ textareaValue = { staticText: String(attr.value.value) }
436
+ }
437
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
438
+ const lit = staticLiteralOrTemplate(attr.value.expression)
439
+ if (lit.ok)
440
+ textareaValue = { staticText: lit.value === null || typeof lit.value === 'boolean' ? '' : String(lit.value) }
441
+ else
442
+ textareaValue = { expr: compileSubExpression(attr.value.expression) }
443
+ }
444
+ continue
445
+ }
446
+
447
+ if (isSelect && name === 'value') {
448
+ if (attr.value?.type === 'Literal') {
449
+ nextSelectValue = { staticValue: String(attr.value.value), multiple: selectIsMultiple }
450
+ }
451
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
452
+ const lit = staticLiteralOrTemplate(attr.value.expression)
453
+ if (lit.ok) {
454
+ if (lit.value !== null)
455
+ nextSelectValue = { staticValue: String(lit.value), multiple: selectIsMultiple }
456
+ }
457
+ else {
458
+ const svVar = `_sv${nextId()}`
459
+ flushParts()
460
+ pushStmt(`const ${svVar} = ${compileSubExpression(attr.value.expression)};`)
461
+ nextSelectValue = { expr: svVar, multiple: selectIsMultiple }
462
+ }
463
+ }
464
+ continue
465
+ }
466
+
467
+ if (isOption && name === 'selected')
468
+ optionHasExplicitSelected = true
469
+
470
+ if (hasSpread) {
471
+ const propKey = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
472
+ if (attr.value === null) {
473
+ spreadEntries.push(`${propKey}: true`)
474
+ }
475
+ else if (attr.value.type === 'Literal') {
476
+ if (isOption && name === 'value')
477
+ optionValue = { staticValue: String(attr.value.value) }
478
+ spreadEntries.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
479
+ }
480
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
481
+ const exprCode = compileSubExpression(attr.value.expression)
482
+ if (isOption && name === 'value' && activeSelectValue !== undefined) {
483
+ if (isSimpleValueExpr(attr.value.expression)) {
484
+ optionValue = { expr: exprCode }
485
+ spreadEntries.push(`${propKey}: ${exprCode}`)
486
+ }
487
+ else {
488
+ const ovVar = `_ov${nextId()}`
489
+ flushParts()
490
+ pushStmt(`const ${ovVar} = ${exprCode};`)
491
+ optionValue = { expr: ovVar }
492
+ spreadEntries.push(`${propKey}: ${ovVar}`)
493
+ }
494
+ }
495
+ else {
496
+ spreadEntries.push(`${propKey}: ${exprCode}`)
497
+ }
498
+ }
499
+ continue
500
+ }
501
+
502
+ if (attr.value === null) {
503
+ parts.pushStatic(isStringBoolAttr(name) ? ` ${name}="true"` : ` ${name}`)
504
+ }
505
+ else if (attr.value.type === 'Literal') {
506
+ if (isOption && name === 'value')
507
+ optionValue = { staticValue: String(attr.value.value) }
508
+ parts.pushStatic(formatStaticAttrValue(name, String(attr.value.value), tag))
509
+ }
510
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
511
+ const opt = emitSsrExprAttr(ctx, name, attr.value.expression, isOption)
512
+ if (opt !== undefined)
513
+ optionValue = opt
514
+ }
515
+ }
516
+
517
+ if (hasSpread) {
518
+ if (spreadEntries.length === 1 && attrs.length === 1) {
519
+ const spreadAttr = attrs[0] as Extract<typeof attrs[number], { type: 'JSXSpreadAttribute' }>
520
+ parts.pushExpr(`${use('ssrSpread')}(${compileSubExpression(spreadAttr.argument)}, ${JSON.stringify(tag)})`)
521
+ }
522
+ else if (spreadEntries.length > 0) {
523
+ parts.pushExpr(`${use('ssrSpread')}({ ${spreadEntries.join(', ')} }, ${JSON.stringify(tag)})`)
524
+ }
525
+ }
526
+
527
+ if (isOption && activeSelectValue !== undefined && !optionHasExplicitSelected) {
528
+ if (optionValue === undefined) {
529
+ const textVal = staticOptionText(node.children)
530
+ if (textVal !== undefined) {
531
+ optionValue = { staticValue: textVal }
532
+ }
533
+ else {
534
+ const meaningful = filterMeaningfulChildren(node.children)
535
+ if (
536
+ meaningful.length === 1
537
+ && meaningful[0]!.type === 'JSXExpressionContainer'
538
+ && meaningful[0]!.expression.type !== 'JSXEmptyExpression'
539
+ && isSimpleValueExpr(meaningful[0]!.expression)
540
+ ) {
541
+ optionValue = { expr: compileSubExpression(meaningful[0]!.expression) }
542
+ }
543
+ }
544
+ }
545
+ if (optionValue !== undefined) {
546
+ const sel = formatOptionSelectedExpr(activeSelectValue, optionValue)
547
+ if (sel.staticSelected === true)
548
+ parts.pushStatic(' selected')
549
+ else if (sel.expr !== undefined)
550
+ parts.pushExpr(sel.expr)
551
+ }
552
+ }
553
+
554
+ return { innerHtmlExpr, textareaValue, nextSelectValue }
555
+ }
@@ -0,0 +1,90 @@
1
+ // The SSR compiler's emission of an island: its server render inside the `<pru-island>` that hands its props and hydration mode to the browser.
2
+
3
+ import type { IslandBinding } from './ssr'
4
+ import type { StringParts } from './ssr-helpers'
5
+ import { escapeStaticAttr } from './shared'
6
+
7
+ /** What the island emitter borrows from the running `compileSsr()`. */
8
+ export interface IslandEmitter {
9
+ use: (name: string) => string
10
+ nextId: () => number
11
+ markersAt: (offset: number) => boolean
12
+ }
13
+
14
+ /** One island element, its props serialized and its server children compiled. */
15
+ export interface IslandCall {
16
+ island: IslandBinding
17
+ tag: string
18
+ /** The component as called, marked with its source line. */
19
+ call: string
20
+ start: number
21
+ propEntries: string[]
22
+ allStaticProps: boolean
23
+ staticPropsObj: Record<string, unknown>
24
+ hydrateExpr: string | undefined
25
+ staticHydrate: string | undefined
26
+ hasChildren: boolean
27
+ childExpr: string
28
+ childrenHaveAwait: boolean
29
+ }
30
+
31
+ export function emitIsland(em: IslandEmitter, c: IslandCall, parts: StringParts): void {
32
+ const { island, tag, call, start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait } = c
33
+ const propsCode = `{ ${propEntries.join(', ')} }`
34
+ // The server children an island is handed render before it, outside its contexts and ids, as the browser never re-renders them.
35
+ const slotVar = hasChildren ? `_c${em.nextId()}` : undefined
36
+ const slotProp = slotVar === undefined ? '' : `children: ${slotVar}.prop`
37
+ const callPropsCode = slotVar === undefined ? propsCode : `{ ${[...propEntries, slotProp].join(', ')} }`
38
+ const withSlot = (expr: string): string => slotVar === undefined ? expr : `((${slotVar}) => ${expr})(${em.use('ssrSlot')}(${childExpr}))`
39
+ const slotArg = slotVar === undefined ? '' : `, ${slotVar}`
40
+ const resolvedHydrate = staticHydrate ?? (hydrateExpr === undefined ? island.defaultHydrate : undefined)
41
+ const safeStaticProps = allStaticProps
42
+ && !Object.hasOwn(staticPropsObj, '__k')
43
+ && !Object.values(staticPropsObj).some(v => Object.is(v, -0))
44
+
45
+ // Compile-time static island props fast path (only when not inside an island-reachable component and children don't contain direct `await`):
46
+ // 0 JSON.stringify / Object.keys / escAttr at runtime, while still recording rendered islands & island ID scope!
47
+ if (!em.markersAt(start) && !childrenHaveAwait && safeStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
48
+ const pAttr = Object.keys(staticPropsObj).length > 0
49
+ ? ` p="${escapeStaticAttr(JSON.stringify(staticPropsObj))}"`
50
+ : ''
51
+ const hAttr = resolvedHydrate !== undefined && resolvedHydrate !== 'load'
52
+ ? ` h="${escapeStaticAttr(resolvedHydrate)}"`
53
+ : ''
54
+ const openTag = `<pru-island c="${escapeStaticAttr(island.chunk)}"${pAttr}${hAttr}>`
55
+ const hydrateArg = resolvedHydrate !== undefined ? JSON.stringify(resolvedHydrate) : 'undefined'
56
+ const renderArg = resolvedHydrate === 'client'
57
+ ? 'undefined'
58
+ : `() => ${em.use('ssrChild')}(${call}(${callPropsCode}))`
59
+ const expr = `${em.use('ssrIslandStatic')}(${JSON.stringify(island.chunk)}, ${JSON.stringify(openTag)}, ${renderArg}, ${hydrateArg}, ${JSON.stringify(tag)}${slotArg})`
60
+ parts.pushExpr(withSlot(expr))
61
+ return
62
+ }
63
+
64
+ const hydrateArg = hydrateExpr ?? (island.defaultHydrate !== undefined ? JSON.stringify(island.defaultHydrate) : 'undefined')
65
+ if (!childrenHaveAwait && safeStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
66
+ parts.pushExpr(withSlot(`${em.use('ssrIsland')}(${JSON.stringify(island.chunk)}, () => ${em.use('ssrChild')}(${call}(${callPropsCode})), ${propsCode}, ${hydrateArg}, false, ${JSON.stringify(tag)}${slotArg})`))
67
+ return
68
+ }
69
+
70
+ // Hoist dynamic island props / awaited children into a single binding so expressions evaluate once!
71
+ const pVar = `_p${em.nextId()}`
72
+ const argNames = [pVar]
73
+ const argExprs = [propsCode]
74
+ let callArg = pVar
75
+ if (slotVar !== undefined) {
76
+ argNames.push(slotVar)
77
+ argExprs.push(`${em.use('ssrSlot')}(${childExpr})`)
78
+ callArg = `{ ...${pVar}, ${slotProp} }`
79
+ }
80
+ let hArg = hydrateArg
81
+ if (hydrateExpr !== undefined && staticHydrate === undefined) {
82
+ const hVar = `_h${em.nextId()}`
83
+ argNames.push(hVar)
84
+ argExprs.push(hydrateExpr)
85
+ hArg = hVar
86
+ }
87
+ parts.pushExpr(
88
+ `((${argNames.join(', ')}) => ${em.use('ssrIsland')}(${JSON.stringify(island.chunk)}, () => ${em.use('ssrChild')}(${call}(${callArg})), ${pVar}, ${hArg}, false, ${JSON.stringify(tag)}${slotArg}))(${argExprs.join(', ')})`,
89
+ )
90
+ }