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,624 @@
1
+ // Prunelle SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
2
+
3
+ import type { Html, HydrateStrategy, PrunelleChild } from '../jsx-runtime'
4
+ import type { ServerAction } from '../server/action'
5
+ import type { FieldConstraint } from '../server/form-schema'
6
+ import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
7
+ import { renderOnServer } from '../reactivity/index'
8
+ import { renderProtectFields } from '../server/action-protect'
9
+ import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
10
+ import { styleText } from '../style'
11
+ import { assertRenderable } from '../unrenderable'
12
+ import { currentFormFields, currentRenderContext, lookupFormAction, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
13
+ import { keepScrollTag } from './navigation'
14
+ export { ssrStyleBlock } from './context'
15
+
16
+ export const PRUNELLE_ISLAND_STYLE = 'pru-island,pru-slot{display:contents}'
17
+ export const PRUNELLE_SUSPENSE_STYLE = 'pru-s{display:contents}'
18
+
19
+ export const RAW_HTML = Symbol.for('pru.html')
20
+
21
+ function isRawHtml(value: unknown): value is Html {
22
+ return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[RAW_HTML] === true && '__html' in value
23
+ }
24
+
25
+ const ESC_TEXT = /[&<>]/
26
+ const ESC_ATTR = /[&"<>]/
27
+ const bunEscape = typeof Bun !== 'undefined' && typeof Bun.escapeHTML === 'function' ? Bun.escapeHTML : undefined
28
+
29
+ function escText(str: string): string {
30
+ if (bunEscape !== undefined)
31
+ return bunEscape(str)
32
+ if (!ESC_TEXT.test(str))
33
+ return str
34
+ return str.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
35
+ }
36
+
37
+ export function esc(value: unknown): string {
38
+ if (typeof value === 'string')
39
+ return escText(value)
40
+ if (typeof value === 'number')
41
+ return String(value)
42
+ if (value == null || typeof value === 'boolean')
43
+ return ''
44
+ if (isRawHtml(value))
45
+ return value.__html
46
+ if (Array.isArray(value)) {
47
+ let out = ''
48
+ for (let i = 0; i < value.length; i++)
49
+ out += esc(value[i])
50
+ return out
51
+ }
52
+ assertRenderable(value, 'text')
53
+ return escText(String(value))
54
+ }
55
+
56
+ export function ssrRaw(value: unknown): string {
57
+ if (value == null || value === false)
58
+ return ''
59
+ if (isRawHtml(value))
60
+ return String(value.__html)
61
+ if (typeof value === 'object' && '__html' in value)
62
+ throw new TypeError(UNBRANDED_INNER_HTML)
63
+ return String(value)
64
+ }
65
+
66
+ /** React's `{ __html }` shape reaching innerHTML unbranded: prunelle would print `[object Object]`. */
67
+ const UNBRANDED_INNER_HTML = 'prunelle: innerHTML takes the HTML string, got a { __html } object; pass the string, or raw(html) for a value typed Html.'
68
+
69
+ const CLOSE_STYLE_RE = /<\/(style)/gi
70
+ const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
71
+
72
+ /** Emits raw text inside `<style>` or `<script>` without HTML entity escaping, neutralizing dangerous script/style sequences. */
73
+ export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
74
+ if (value == null || typeof value === 'boolean')
75
+ return ''
76
+ if (Array.isArray(value)) {
77
+ let out = ''
78
+ for (let i = 0; i < value.length; i++)
79
+ out += ssrRawText(tag, value[i])
80
+ return out
81
+ }
82
+ const str = isRawHtml(value) ? String(value.__html) : String(value)
83
+ if (tag === 'script') {
84
+ return str.replace(SCRIPT_UNSAFE_RE, (_, body: string) =>
85
+ body.charCodeAt(0) === 47 ? `<\\${body}` : `\\u003c${body}`)
86
+ }
87
+ return str.replace(CLOSE_STYLE_RE, '<\\/$1')
88
+ }
89
+
90
+ export function escAttr(value: unknown): string {
91
+ const str = String(value)
92
+ if (bunEscape !== undefined)
93
+ return bunEscape(str)
94
+ if (!ESC_ATTR.test(str))
95
+ return str
96
+ return str
97
+ .replaceAll('&', '&amp;')
98
+ .replaceAll('"', '&quot;')
99
+ .replaceAll('<', '&lt;')
100
+ .replaceAll('>', '&gt;')
101
+ }
102
+
103
+ // What XML 1.0 forbids in a document: C0 controls but tab, LF and CR, U+FFFE, U+FFFF and lone surrogates.
104
+ const XML_FORBIDDEN_RE = /[\0-\x08\v\f\x0E-\x1F\uFFFE\uFFFF\uD800-\uDFFF]/gu
105
+ const XML_ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&apos;' }
106
+ const XML_SPECIAL_RE = /[&<>"']/g
107
+
108
+ /** Text for an XML document (a feed, a sitemap): escaped, and stripped of the characters that would make the whole file invalid. */
109
+ export function escXml(value: unknown): string {
110
+ return String(value).replace(XML_FORBIDDEN_RE, '').replace(XML_SPECIAL_RE, c => XML_ESCAPES[c]!)
111
+ }
112
+
113
+ // `<`, then the two line separators, built from their code points so the source shows no invisible character.
114
+ const SCRIPT_JSON_RE = new RegExp(`[<${String.fromCharCode(0x2028, 0x2029)}]`, 'g')
115
+
116
+ /** JSON text made safe inside a `<script>` element: `<` can no longer close it or open a comment, and U+2028 and U+2029 cannot end a line of script. */
117
+ export function escJson(json: string): string {
118
+ return json.replace(SCRIPT_JSON_RE, c => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`)
119
+ }
120
+
121
+ export function raw(html: string): Html {
122
+ return { __html: html, [RAW_HTML]: true } as unknown as Html
123
+ }
124
+
125
+ export function ssrAttr(name: string, value: unknown, tag?: string): string {
126
+ if (value == null || isBlockedAttr(name))
127
+ return ''
128
+ if (typeof value === 'boolean') {
129
+ if (isStringBoolAttr(name))
130
+ return ` ${name}="${value ? 'true' : 'false'}"`
131
+ return value ? ` ${name}` : ''
132
+ }
133
+ if (isUnsafeUrlAttr(name, value, tag)) {
134
+ if (process.env.NODE_ENV !== 'production')
135
+ console.warn(`prunelle: dropped unsafe URL on <${tag ?? 'element'} ${name}>.`)
136
+ return ''
137
+ }
138
+ assertRenderable(value, name)
139
+ return ` ${name}="${escAttr(value)}"`
140
+ }
141
+
142
+ export function ssrStyle(value: unknown): string {
143
+ if (value == null || value === false)
144
+ return ''
145
+ if (typeof value === 'string')
146
+ return ` style="${escAttr(value)}"`
147
+ if (typeof value === 'object') {
148
+ const out = styleText(value as Record<string, unknown>)
149
+ return out === '' ? '' : ` style="${escAttr(out)}"`
150
+ }
151
+ return ''
152
+ }
153
+
154
+ const SPREAD_DANGEROUS_HTML = 'prunelle: dangerouslySetInnerHTML in a spread: write innerHTML={html} on the element.'
155
+
156
+ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag?: string): string {
157
+ if (props == null || typeof props !== 'object')
158
+ return ''
159
+ let out = ''
160
+ let formPresent = 0
161
+ const trackForm = (tag === 'input' || tag === 'select' || tag === 'textarea') && currentFormFields() !== undefined
162
+ for (const [rawKey, value] of Object.entries(props)) {
163
+ if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
164
+ continue
165
+ if (rawKey === 'dangerouslySetInnerHTML')
166
+ throw new TypeError(SPREAD_DANGEROUS_HTML)
167
+ const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
168
+ if (isBlockedAttr(name))
169
+ continue
170
+ if (trackForm && value !== undefined) {
171
+ const bit = FORM_ATTR_BITS[name.toLowerCase()]
172
+ if (bit !== undefined)
173
+ formPresent |= bit
174
+ }
175
+ out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value, tag)
176
+ }
177
+ if (trackForm && typeof props.name === 'string')
178
+ out += ssrFormAttrs(tag, props.name, formPresent, props.type)
179
+ return out
180
+ }
181
+
182
+ const FORM_ATTR_BITS: Record<string, number> = {
183
+ type: 1,
184
+ required: 2,
185
+ minlength: 4,
186
+ maxlength: 8,
187
+ min: 16,
188
+ max: 32,
189
+ step: 64,
190
+ pattern: 128,
191
+ }
192
+ const TEXT_INPUT_TYPES = new Set(['text', 'search', 'url', 'tel', 'email', 'password'])
193
+ const NON_REQUIRED_INPUT_TYPES = new Set(['hidden', 'submit', 'button', 'reset', 'image'])
194
+
195
+ function resolveActionForForm(action: unknown): ServerAction<unknown, unknown> | undefined {
196
+ if (typeof action === 'function' && (action as { __pruAction?: boolean }).__pruAction === true)
197
+ return action as ServerAction<unknown, unknown>
198
+ if (typeof action === 'string') {
199
+ const found = lookupFormAction(action)
200
+ if (typeof found === 'function' && (found as { __pruAction?: boolean }).__pruAction === true)
201
+ return found as ServerAction<unknown, unknown>
202
+ }
203
+ return undefined
204
+ }
205
+
206
+ function formFieldsOf(act: ServerAction<unknown, unknown>): ReadonlyMap<string, FieldConstraint> | undefined {
207
+ if (act.schema === undefined)
208
+ return undefined
209
+ const extracted = extractFormSchema(act.schema)
210
+ return extracted.ok && extracted.fields.size > 0 ? extracted.fields : undefined
211
+ }
212
+
213
+ /** Wraps an action-bound `<form>` render during SSR: injects schema constraints for child fields and appends honeypot / signed timestamp inputs. */
214
+ export function ssrForm(action: unknown, render: (action: unknown) => string): string {
215
+ const act = resolveActionForForm(action)
216
+ if (act === undefined)
217
+ return `${render(action)}</form>`
218
+ const hidden = renderProtectFields(act.protect, act.url)
219
+ const fields = formFieldsOf(act)
220
+ const body = fields !== undefined ? runWithFormFields(fields, () => render(action)) : render(action)
221
+ return `${body}${hidden}</form>`
222
+ }
223
+
224
+ /** Async variant of `ssrForm` for action-bound `<form>` elements containing `await`. */
225
+ export async function ssrFormAsync(action: unknown, render: (action: unknown) => Promise<string>): Promise<string> {
226
+ const act = resolveActionForForm(action)
227
+ if (act === undefined)
228
+ return `${await render(action)}</form>`
229
+ const hidden = renderProtectFields(act.protect, act.url)
230
+ const fields = formFieldsOf(act)
231
+ const body = fields !== undefined ? await runWithFormFields(fields, () => render(action)) : await render(action)
232
+ return `${body}${hidden}</form>`
233
+ }
234
+
235
+ /** Emits schema-derived HTML5 constraint attributes on `<input>`, `<select>`, and `<textarea>` inside an action-bound `<form>`. */
236
+ export function ssrFormAttrs(tag: 'input' | 'select' | 'textarea', name: unknown, present: number, inputType?: unknown): string {
237
+ const fields = currentFormFields()
238
+ if (fields === undefined || typeof name !== 'string' || name === '')
239
+ return ''
240
+ const c = lookupFieldConstraint(fields, name)
241
+ if (c === undefined)
242
+ return ''
243
+
244
+ let out = ''
245
+ const explicitType = typeof inputType === 'string' ? inputType.toLowerCase() : undefined
246
+ let effectiveType: string | undefined
247
+ if (tag === 'input') {
248
+ if (explicitType === undefined && (present & 1) === 0 && c.type !== undefined) {
249
+ out += ` type="${c.type}"`
250
+ effectiveType = c.type
251
+ }
252
+ else {
253
+ effectiveType = explicitType ?? 'text'
254
+ }
255
+ }
256
+
257
+ const skipRequired = tag === 'input' && (
258
+ NON_REQUIRED_INPUT_TYPES.has(effectiveType!)
259
+ || (effectiveType === 'checkbox' && c.isArray === true)
260
+ )
261
+ if (c.required === true && (present & 2) === 0 && !skipRequired)
262
+ out += ' required'
263
+
264
+ const supportsLength = tag === 'textarea' || (tag === 'input' && TEXT_INPUT_TYPES.has(effectiveType!))
265
+ if (supportsLength) {
266
+ if (c.minLength !== undefined && (present & 4) === 0)
267
+ out += ` minlength="${c.minLength}"`
268
+ if (c.maxLength !== undefined && (present & 8) === 0)
269
+ out += ` maxlength="${c.maxLength}"`
270
+ }
271
+
272
+ if (tag === 'input') {
273
+ if (effectiveType === 'number' || effectiveType === 'range') {
274
+ if (c.min !== undefined && (present & 16) === 0)
275
+ out += ` min="${c.min}"`
276
+ if (c.max !== undefined && (present & 32) === 0)
277
+ out += ` max="${c.max}"`
278
+ if (c.step !== undefined && (present & 64) === 0)
279
+ out += ` step="${c.step}"`
280
+ }
281
+ if (TEXT_INPUT_TYPES.has(effectiveType!) && c.pattern !== undefined && (present & 128) === 0)
282
+ out += ` pattern="${escAttr(c.pattern)}"`
283
+ }
284
+
285
+ return out
286
+ }
287
+
288
+ export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render: (item: T, index: number, array: readonly T[]) => string): string {
289
+ if (!items)
290
+ return ''
291
+ const list: readonly T[] = Array.isArray(items) ? items : [...items]
292
+ let out = ''
293
+ for (let i = 0; i < list.length; i++)
294
+ out += render(list[i] as T, i, list)
295
+ return out
296
+ }
297
+
298
+ export function ssrChild(value: PrunelleChild): string {
299
+ if (typeof value === 'string')
300
+ return esc(value)
301
+ if (typeof value === 'number')
302
+ return String(value)
303
+ if (value == null || typeof value === 'boolean')
304
+ return ''
305
+ if (isRawHtml(value))
306
+ return value.__html
307
+ if (Array.isArray(value)) {
308
+ let out = ''
309
+ for (let i = 0; i < value.length; i++)
310
+ out += ssrChild(value[i])
311
+ return out
312
+ }
313
+ assertRenderable(value, 'text')
314
+ return esc(String(value))
315
+ }
316
+
317
+ function serializeIslandProps(props: Record<string, unknown>): string {
318
+ return JSON.stringify(props, function (this: Record<string, unknown>, key: string, value: unknown) {
319
+ const orig = key !== '' && this != null && typeof this === 'object' ? this[key] : value
320
+ if (orig === undefined)
321
+ return Array.isArray(this) ? { __k: 'u', v: 0 } : value
322
+ if (typeof orig === 'number') {
323
+ if (!Number.isFinite(orig))
324
+ return { __k: 'N', v: String(orig) }
325
+ if (Object.is(orig, -0))
326
+ return { __k: 'N', v: '-0' }
327
+ return value
328
+ }
329
+ if (orig instanceof Date)
330
+ return { __k: 'D', v: Number.isNaN(orig.getTime()) ? 'NaN' : orig.toISOString() }
331
+ if (orig instanceof Set)
332
+ return { __k: 'S', v: [...orig] }
333
+ if (orig instanceof Map)
334
+ return { __k: 'M', v: [...orig.entries()] }
335
+ if (orig instanceof URL)
336
+ return { __k: 'U', v: orig.href }
337
+ if (orig instanceof RegExp)
338
+ return { __k: 'R', v: [orig.source, orig.flags] }
339
+ if (typeof orig === 'bigint')
340
+ return { __k: 'B', v: orig.toString() }
341
+ if (isRawHtml(orig))
342
+ throw new TypeError(`prunelle: island prop "${key}" is server-rendered JSX, which cannot reach the browser; pass it as children, or build it inside the island.`)
343
+ if (typeof orig === 'function')
344
+ throw new TypeError(`prunelle: island prop "${key}" is a function, which cannot reach the browser; define it inside the island, or import it there.`)
345
+ if (typeof orig === 'object' && orig !== null && 'peek' in orig && 'value' in orig)
346
+ throw new TypeError(`prunelle: island prop "${key}" is a signal; pass ${key}.value, or import the signal in the island from a shared module.`)
347
+ if (typeof orig === 'object' && orig !== null && !Array.isArray(orig)) {
348
+ const proto = Object.getPrototypeOf(orig) as { constructor?: { name?: string } } | null
349
+ if (proto !== Object.prototype && proto !== null) {
350
+ const typeName = proto?.constructor?.name || 'Object'
351
+ const propName = key ? `"${key}"` : '(root)'
352
+ throw new TypeError(`prunelle: island prop ${propName} (${typeName}) cannot be serialized to the browser; pass a plain object, array, primitive, Date, Map, Set, URL, RegExp, or BigInt.`)
353
+ }
354
+ if (Object.hasOwn(orig, '__k'))
355
+ return { __k: 'O', v: Object.entries(orig).filter(([, x]) => x !== undefined) }
356
+ }
357
+ return value
358
+ })
359
+ }
360
+
361
+ let fallbackIslandDepth = 0
362
+
363
+ function getIslandDepth(): number {
364
+ const ctx = currentRenderContext()
365
+ return ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth
366
+ }
367
+
368
+ export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy): void {
369
+ const ctx = currentRenderContext()
370
+ if (ctx === undefined)
371
+ return
372
+ ctx.hasIslands = true
373
+ const eager = hydrate === undefined || hydrate === 'load'
374
+ if (eager)
375
+ ctx.renderedIslands.set(chunk, true)
376
+ else if (!ctx.renderedIslands.has(chunk))
377
+ ctx.renderedIslands.set(chunk, false)
378
+ }
379
+
380
+ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy, name = 'island'): string {
381
+ const ctx = currentRenderContext()
382
+ if (ctx !== undefined) {
383
+ if (chunk !== undefined && ctx.islandDepth === 0)
384
+ recordRenderedIsland(chunk, hydrate)
385
+ ctx.islandDepth++
386
+ try {
387
+ return renderOnServer(ctx.islandDepth === 1 ? () => renderIsland(ctx, name, render) : render)
388
+ }
389
+ finally {
390
+ ctx.islandDepth--
391
+ }
392
+ }
393
+ fallbackIslandDepth++
394
+ try {
395
+ return renderOnServer(render)
396
+ }
397
+ finally {
398
+ fallbackIslandDepth--
399
+ }
400
+ }
401
+
402
+
403
+ /** Lazily evaluates non-async component children on first read inside the component's dynamic context, memoizing the result. */
404
+ export function ssrChildProp<P extends Record<string, unknown>>(props: P, fn: () => Html): P {
405
+ let cached: Html | undefined
406
+ let evaluated = false
407
+ return Object.defineProperty(props, 'children', {
408
+ enumerable: true,
409
+ configurable: true,
410
+ get() {
411
+ if (!evaluated) {
412
+ evaluated = true
413
+ cached = fn()
414
+ }
415
+ return cached
416
+ },
417
+ })
418
+ }
419
+
420
+ export interface TrackedSlot {
421
+ prop: Html
422
+ html: string
423
+ used: boolean
424
+ }
425
+
426
+ /** Wraps server-rendered island children in `<pru-slot>` and tracks whether the island emitted them during SSR. */
427
+ export function ssrSlot(html: string): TrackedSlot {
428
+ const slot: TrackedSlot = {
429
+ html,
430
+ used: false,
431
+ prop: null as unknown as Html,
432
+ }
433
+ slot.prop = Object.defineProperty(
434
+ { [RAW_HTML]: true },
435
+ '__html',
436
+ {
437
+ enumerable: true,
438
+ get() {
439
+ slot.used = true
440
+ return `<pru-slot>${html}</pru-slot>`
441
+ },
442
+ },
443
+ ) as unknown as Html
444
+ return slot
445
+ }
446
+
447
+ function renderIslandBody(
448
+ ctx: ReturnType<typeof currentRenderContext>,
449
+ render: (() => string) | undefined,
450
+ hydrate: HydrateStrategy | undefined,
451
+ name: string | undefined,
452
+ slot: TrackedSlot | undefined,
453
+ ): { idAttr: string, inner: string, hiddenSlot: string } {
454
+ let idAttr = ''
455
+ let inner = ''
456
+ if (render !== undefined && hydrate !== 'client') {
457
+ if (ctx !== undefined) {
458
+ const prevPrefix = ctx.idPrefix
459
+ const prevSeq = ctx.idSeq
460
+ const islandPrefix = `i${ctx.islandSeq++}-`
461
+ ctx.idPrefix = islandPrefix
462
+ ctx.idSeq = 0
463
+ try {
464
+ inner = ssrInIsland(render, undefined, undefined, name)
465
+ if (ctx.idSeq > 0)
466
+ idAttr = ` i="${islandPrefix}"`
467
+ }
468
+ finally {
469
+ ctx.idPrefix = prevPrefix
470
+ ctx.idSeq = prevSeq
471
+ }
472
+ }
473
+ else {
474
+ inner = ssrInIsland(render, undefined, undefined, name)
475
+ }
476
+ }
477
+
478
+ const hiddenSlot = slot !== undefined && !slot.used && slot.html !== ''
479
+ ? `<template data-pru-slot>${slot.html}</template>`
480
+ : ''
481
+ return { idAttr, inner, hiddenSlot }
482
+ }
483
+
484
+ export function ssrIslandStatic(
485
+ chunk: string,
486
+ openTag: string,
487
+ render: (() => string) | undefined,
488
+ hydrate?: HydrateStrategy,
489
+ name?: string,
490
+ slot?: TrackedSlot,
491
+ ): string {
492
+ if (getIslandDepth() > 0)
493
+ return render !== undefined ? render() : ''
494
+
495
+ const ctx = currentRenderContext()
496
+ if (ctx !== undefined)
497
+ recordRenderedIsland(chunk, hydrate)
498
+
499
+ const { idAttr, inner, hiddenSlot } = renderIslandBody(ctx, render, hydrate, name, slot)
500
+ const tag = idAttr === '' ? openTag : `${openTag.slice(0, -1)}${idAttr}>`
501
+ return `${tag}${inner}${hiddenSlot}</pru-island>`
502
+ }
503
+
504
+
505
+ export function ssrIsland(
506
+ chunk: string,
507
+ render: () => string,
508
+ props: Record<string, unknown>,
509
+ hydrate?: HydrateStrategy,
510
+ scriptProps = false,
511
+ name?: string,
512
+ slot?: TrackedSlot,
513
+ ): string {
514
+ if (getIslandDepth() > 0)
515
+ return render()
516
+
517
+ const ctx = currentRenderContext()
518
+ if (ctx !== undefined)
519
+ recordRenderedIsland(chunk, hydrate)
520
+
521
+ let propsAttr = ''
522
+ let propsScript = ''
523
+ if (Object.keys(props).length > 0) {
524
+ const json = serializeIslandProps(props)
525
+ if (ctx !== undefined && json.includes('"__k":'))
526
+ ctx.revives = true
527
+ if (scriptProps)
528
+ propsScript = `<script type="application/json" data-pru-props>${escJson(json)}</script>`
529
+ else
530
+ propsAttr = ` p="${escAttr(json)}"`
531
+ }
532
+ const hydrateAttr = hydrate !== undefined && hydrate !== 'load'
533
+ ? ` h="${escAttr(hydrate)}"`
534
+ : ''
535
+
536
+ const { idAttr, inner, hiddenSlot } = renderIslandBody(ctx, render, hydrate, name, slot)
537
+ return `<pru-island c="${escAttr(chunk)}"${propsAttr}${hydrateAttr}${idAttr}>${inner}${hiddenSlot}${propsScript}</pru-island>`
538
+ }
539
+
540
+ export interface DocumentOptions {
541
+ body: string
542
+ head?: string | undefined
543
+ headTags?: Iterable<string> | undefined
544
+ lang?: string | undefined
545
+ htmlAttrs?: Record<string, string> | undefined
546
+ runtimeScript?: string | undefined
547
+ alwaysLoadRuntime?: boolean | undefined
548
+ /** Set on a route that renders a `<Region>`: the plugins' `regionClientEntry` bundle. */
549
+ regionScript?: string | undefined
550
+ preloadChunks?: Iterable<string> | undefined
551
+ /** Script URL to the chunks it imports statically, preloaded with it: the browser then fetches them all at once. */
552
+ chunkImports?: Readonly<Record<string, readonly string[]>> | undefined
553
+ styles?: Iterable<string> | undefined
554
+ hasIslands?: boolean | undefined
555
+ hasSuspense?: boolean | undefined
556
+ /** True when the app ships `/favicon.ico` in `public/`, so no empty `data:,` fallback icon is injected. */
557
+ hasFavicon?: boolean | undefined
558
+ // The head markup every page shares for the `navigation` settings: see `createNavigation`.
559
+ navigation?: string | undefined
560
+ }
561
+
562
+ // A tab icon link (`icon`, `shortcut icon`); an `apple-touch-icon` alone still leaves the browser asking for /favicon.ico.
563
+ const TAB_ICON_RE = /<link\b[^>]*\brel=["']?(?:[^"'>]*\s)?icon(?=[\s"'>])/i
564
+ // Named in a page with no icon of its own: the browser takes it as the icon and never requests /favicon.ico, which most apps answer with a 404.
565
+ const EMPTY_ICON = '<link rel="icon" href="data:,">'
566
+
567
+ export function renderDocument(options: DocumentOptions): string {
568
+ const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, hasFavicon, navigation } = options
569
+ let headExtra = head
570
+
571
+ if (headTags !== undefined) {
572
+ for (const tag of headTags)
573
+ headExtra += tag
574
+ }
575
+
576
+ if (!hasFavicon && !TAB_ICON_RE.test(headExtra))
577
+ headExtra += EMPTY_ICON
578
+
579
+ if (styles !== undefined) {
580
+ for (const href of styles)
581
+ headExtra += `<link rel="stylesheet" href="${escAttr(href)}">`
582
+ }
583
+
584
+ if (navigation !== undefined)
585
+ headExtra += navigation
586
+
587
+ const loadsRuntime = runtimeScript !== undefined && (hasIslands || alwaysLoadRuntime)
588
+ const preloads = new Set<string>()
589
+ const preload = (script: string, self: boolean): void => {
590
+ if (self)
591
+ preloads.add(script)
592
+ for (const dep of chunkImports?.[script] ?? [])
593
+ preloads.add(dep)
594
+ }
595
+ if (hasIslands) {
596
+ headExtra += `<style>${PRUNELLE_ISLAND_STYLE}</style>`
597
+ for (const chunk of preloadChunks ?? [])
598
+ preload(chunk, true)
599
+ }
600
+ if (loadsRuntime)
601
+ preload(runtimeScript, false)
602
+ for (const href of preloads)
603
+ headExtra += `<link rel="modulepreload" href="${escAttr(href)}">`
604
+
605
+ if (hasSuspense)
606
+ headExtra += `<style>${PRUNELLE_SUSPENSE_STYLE}</style><script>${PRUNELLE_STREAM_SCRIPT}</script>`
607
+
608
+ if (loadsRuntime)
609
+ headExtra += `<script type="module" src="${escAttr(runtimeScript)}"></script>`
610
+ if (regionScript !== undefined)
611
+ headExtra += `<script type="module" src="${escAttr(regionScript)}"></script>`
612
+
613
+ let attrStr = ''
614
+ const effectiveLang = htmlAttrs?.lang ?? lang
615
+ attrStr += ` lang="${escAttr(effectiveLang)}"`
616
+ if (htmlAttrs !== undefined) {
617
+ for (const [k, v] of Object.entries(htmlAttrs)) {
618
+ if (k !== 'lang' && !isBlockedAttr(k))
619
+ attrStr += ` ${k}="${escAttr(v)}"`
620
+ }
621
+ }
622
+
623
+ return `<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>${body}${keepScrollTag(body)}</body></html>`
624
+ }