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,233 @@
1
+ // A page with pending `<Suspense>` boundaries: its document flushes first, then each boundary as a script once it resolves or times out.
2
+
3
+ import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
4
+ import { getAppContext, runWithAppContext } from '../plugins/index'
5
+ import { streamChunkScript } from '../ssr/context'
6
+ import { currentRequest, runInRequest } from './request-scope'
7
+
8
+ const textEncoder = new TextEncoder()
9
+ // Where a streamed page's document splits: everything before it flushes first, resolved boundaries go in between.
10
+ export const STREAM_TAIL_MARK = '<!--pru:stream-tail-->'
11
+
12
+ function captureAsyncScope(): <T>(fn: () => T) => T {
13
+ const appCtx = getAppContext()
14
+ const reqScope = currentRequest()
15
+ return <T>(fn: () => T): T => {
16
+ const inner = reqScope !== undefined ? () => runInRequest(reqScope, fn) : fn
17
+ return appCtx !== undefined ? runWithAppContext(appCtx, inner) : inner()
18
+ }
19
+ }
20
+
21
+ /** `streamTimeout` is only named in the error: the page's boundaries share one `deadlineMs`. */
22
+ async function settleWithin(
23
+ chunk: PendingChunk,
24
+ deadlineMs: number,
25
+ streamTimeout: number,
26
+ signal: AbortSignal,
27
+ runInScope: <T>(fn: () => T) => T,
28
+ ): Promise<SettledChunk | undefined> {
29
+ if (signal.aborted)
30
+ return undefined
31
+ const remaining = Math.max(0, deadlineMs - Date.now())
32
+ let timer: ReturnType<typeof setTimeout> | undefined
33
+ let onAbort: (() => void) | undefined
34
+ const abortedOrTimedOut = new Promise<SettledChunk | undefined>((resolve) => {
35
+ onAbort = () => resolve(undefined)
36
+ signal.addEventListener('abort', onAbort, { once: true })
37
+ timer = setTimeout(() => {
38
+ if (onAbort !== undefined)
39
+ signal.removeEventListener('abort', onAbort)
40
+ chunk.discard?.()
41
+ const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
42
+ resolve({ html: runInScope(() => chunk.renderError(error)), error })
43
+ }, remaining)
44
+ })
45
+ try {
46
+ return await Promise.race([chunk.settled, abortedOrTimedOut])
47
+ }
48
+ finally {
49
+ clearTimeout(timer)
50
+ if (onAbort !== undefined)
51
+ signal.removeEventListener('abort', onAbort)
52
+ }
53
+ }
54
+
55
+ /** Streams `shell` (a document holding `STREAM_TAIL_MARK`), with every boundary of `rctx` flushed before its tail. */
56
+ export function streamDocument(
57
+ shell: string,
58
+ rctx: RenderContext,
59
+ streamTimeout: number,
60
+ onBoundaryError: (error: unknown) => void,
61
+ transformChunk?: (html: string) => string | Promise<string>,
62
+ tracker?: Pick<StreamTracker, 'trackPage'>,
63
+ ): ReadableStream<Uint8Array> {
64
+ let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
65
+ let tailOffset = STREAM_TAIL_MARK.length
66
+ if (splitAt === -1) {
67
+ splitAt = shell.lastIndexOf('</body>')
68
+ tailOffset = 0
69
+ }
70
+ const openingHtml = splitAt === -1 ? shell : shell.slice(0, splitAt)
71
+ const tailHtml = splitAt === -1 ? '' : shell.slice(splitAt + tailOffset)
72
+
73
+ const runInScope = captureAsyncScope()
74
+ const abortCtrl = new AbortController()
75
+ let closed = false
76
+ const deadline = Date.now() + streamTimeout
77
+ // Shutdown stops waiting for the pending boundaries; the document still gets its tail.
78
+ let endedEarly = false
79
+
80
+ const safeEnqueue = (controller: ReadableStreamDefaultController<Uint8Array>, data: Uint8Array): void => {
81
+ if (closed || (abortCtrl.signal.aborted && !endedEarly))
82
+ return
83
+ try {
84
+ controller.enqueue(data)
85
+ }
86
+ catch {
87
+ closed = true
88
+ rctx.aborted = true
89
+ abortCtrl.abort()
90
+ }
91
+ }
92
+
93
+ return new ReadableStream<Uint8Array>({
94
+ async start(controller) {
95
+ const untrack = tracker?.trackPage(() => {
96
+ endedEarly = true
97
+ abortCtrl.abort()
98
+ })
99
+ try {
100
+ safeEnqueue(controller, textEncoder.encode(openingHtml))
101
+ // A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
102
+ let flushed = 0
103
+ const flushPending = async (): Promise<void> => {
104
+ if (closed || abortCtrl.signal.aborted)
105
+ return
106
+ const chunks = rctx.pending.slice(flushed)
107
+ flushed = rctx.pending.length
108
+ await Promise.all(chunks.map(async (chunk) => {
109
+ const settled = await settleWithin(chunk, deadline, streamTimeout, abortCtrl.signal, runInScope)
110
+ if (settled === undefined || closed || abortCtrl.signal.aborted)
111
+ return
112
+ if ('error' in settled)
113
+ runInScope(() => onBoundaryError(settled.error))
114
+ let chunkHtml = settled.html
115
+ if (transformChunk !== undefined && chunkHtml !== '')
116
+ chunkHtml = await runInScope(() => transformChunk(chunkHtml))
117
+ if (closed || abortCtrl.signal.aborted)
118
+ return
119
+ safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, chunkHtml)))
120
+ await flushPending()
121
+ }))
122
+ }
123
+ await flushPending()
124
+ if (!closed && (endedEarly || !abortCtrl.signal.aborted)) {
125
+ safeEnqueue(controller, textEncoder.encode(tailHtml))
126
+ closed = true
127
+ safeClose(controller)
128
+ }
129
+ }
130
+ finally {
131
+ untrack?.()
132
+ rctx.aborted = true
133
+ }
134
+ },
135
+ cancel() {
136
+ closed = true
137
+ rctx.aborted = true
138
+ abortCtrl.abort()
139
+ },
140
+ })
141
+ }
142
+
143
+ function safeClose(controller: ReadableStreamDefaultController<Uint8Array>): boolean {
144
+ try {
145
+ controller.close()
146
+ return true
147
+ }
148
+ catch {
149
+ return false
150
+ }
151
+ }
152
+
153
+ function trackEventStream(res: Response, active: Set<() => void>, disableTimeout?: () => void): Response {
154
+ disableTimeout?.()
155
+ if (res.body === null)
156
+ return res
157
+ const reader = res.body.getReader()
158
+ let closed = false
159
+ let closeStream: (() => void) | undefined
160
+ const body = new ReadableStream<Uint8Array>({
161
+ start(controller) {
162
+ closeStream = () => {
163
+ if (closed)
164
+ return
165
+ closed = true
166
+ active.delete(closeStream!)
167
+ safeClose(controller)
168
+ void reader.cancel().catch(() => undefined)
169
+ }
170
+ active.add(closeStream)
171
+ },
172
+ async pull(controller) {
173
+ if (closed)
174
+ return
175
+ try {
176
+ const { done, value } = await reader.read()
177
+ if (closed)
178
+ return
179
+ if (done) {
180
+ closed = true
181
+ if (closeStream !== undefined)
182
+ active.delete(closeStream)
183
+ controller.close()
184
+ }
185
+ else {
186
+ controller.enqueue(value)
187
+ }
188
+ }
189
+ catch (err) {
190
+ if (!closed) {
191
+ closed = true
192
+ if (closeStream !== undefined)
193
+ active.delete(closeStream)
194
+ controller.error(err)
195
+ }
196
+ }
197
+ },
198
+ cancel(reason) {
199
+ closed = true
200
+ if (closeStream !== undefined)
201
+ active.delete(closeStream)
202
+ return reader.cancel(reason)
203
+ },
204
+ })
205
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers })
206
+ }
207
+
208
+ export interface StreamTracker {
209
+ track: (res: Response, disableTimeout?: () => void) => Response
210
+ /** Registers a streamed page's way to end early; the returned function drops it once the page is done. */
211
+ trackPage: (end: () => void) => () => void
212
+ closeAll: () => Promise<void>
213
+ }
214
+
215
+ /** Tracks active SSE streams and streamed pages so graceful shutdown can end them before `server.stop()` drains in-flight requests. */
216
+ export function createStreamTracker(): StreamTracker {
217
+ const active = new Set<() => void>()
218
+ const pages = new Set<() => void>()
219
+ return {
220
+ track: (res, disableTimeout) => trackEventStream(res, active, disableTimeout),
221
+ trackPage: (end) => {
222
+ pages.add(end)
223
+ return () => { pages.delete(end) }
224
+ },
225
+ closeAll: () => {
226
+ for (const close of [...active])
227
+ close()
228
+ for (const end of [...pages])
229
+ end()
230
+ return Promise.resolve()
231
+ },
232
+ }
233
+ }
@@ -0,0 +1,58 @@
1
+ // The markup of <ConsentBanner> and <ConsentPreferences>: one form posting to the consent endpoint, with no script.
2
+
3
+ import type { ConsentBannerProps, ConsentTexts } from '../context'
4
+ import type { RequestConsent } from '../server/consent'
5
+ import { esc, escAttr, ssrChild } from './index'
6
+
7
+ function requireCategories(consent: RequestConsent, tag: string): void {
8
+ if (consent.categories.length === 0)
9
+ throw new Error(`prunelle: <${tag}> has no consent category to ask about: declare them in prunelle.config.ts, such as consent: { categories: { analytics: 'Audience measurement' } }.`)
10
+ }
11
+
12
+ function checkboxes(consent: RequestConsent, legend: string | undefined): string {
13
+ const boxes = consent.categories.map((category) => {
14
+ const checked = consent.has(category) ? ' checked' : ''
15
+ return `<label data-part="choice"><input type="checkbox" name="categories" value="${escAttr(category)}"${checked}> ${esc(consent.labels[category] ?? category)}</label>`
16
+ })
17
+ return `<fieldset data-part="choices"><legend>${esc(legend ?? 'Cookies by purpose')}</legend>${boxes.join('')}</fieldset>`
18
+ }
19
+
20
+ // Refuse comes first and looks the same as Accept: the CNIL asks for a refusal as easy as a consent.
21
+ function decisionButtons(texts: ConsentTexts): string {
22
+ return `<button type="submit" name="action" value="reject-all" data-ui="button">${esc(texts.refuse ?? 'Refuse all')}</button>`
23
+ + `<button type="submit" name="action" value="accept-all" data-ui="button">${esc(texts.accept ?? 'Accept all')}</button>`
24
+ }
25
+
26
+ function saveButton(texts: ConsentTexts): string {
27
+ return `<button type="submit" name="action" value="save" data-ui="button">${esc(texts.save ?? 'Save my choices')}</button>`
28
+ }
29
+
30
+ export function renderConsentBanner(consent: RequestConsent | undefined, props: ConsentBannerProps): string {
31
+ if (consent === undefined)
32
+ return ''
33
+ requireCategories(consent, 'ConsentBanner')
34
+ if (consent.decided)
35
+ return ''
36
+ const labels = consent.categories.map(category => consent.labels[category] ?? category).join(', ')
37
+ const body = props.children !== undefined
38
+ ? ssrChild(props.children)
39
+ : `<p>This site would like to set cookies for: ${esc(labels)}. You can accept or refuse them, and change your mind at any time.</p>`
40
+ const policy = props.policyHref !== undefined ? `<p><a href="${escAttr(props.policyHref)}">Cookie policy</a></p>` : ''
41
+ return `<section data-ui="consent" aria-labelledby="pru-consent-title">`
42
+ + `<h2 id="pru-consent-title" data-part="title">${esc(props.title ?? 'Cookies')}</h2>`
43
+ + `<div data-part="body">${body}${policy}</div>`
44
+ + `<form method="post" action="${escAttr(consent.endpoint)}" data-part="form">`
45
+ + `<div data-part="actions">${decisionButtons(props)}</div>`
46
+ + `<details data-part="details"><summary>${esc(props.choose ?? 'Choose')}</summary>${checkboxes(consent, props.legend)}${saveButton(props)}</details>`
47
+ + `</form></section>`
48
+ }
49
+
50
+ export function renderConsentPreferences(consent: RequestConsent | undefined, texts: ConsentTexts): string {
51
+ if (consent === undefined)
52
+ return ''
53
+ requireCategories(consent, 'ConsentPreferences')
54
+ return `<form method="post" action="${escAttr(consent.endpoint)}" data-ui="consent" data-part="preferences">`
55
+ + `${checkboxes(consent, texts.legend)}`
56
+ + `<div data-part="actions">${saveButton(texts)}${decisionButtons(texts)}</div>`
57
+ + `</form>`
58
+ }
@@ -0,0 +1,399 @@
1
+ // Per-request SSR context for <Head> metadata, streaming <Suspense>, rendered island tracking,
2
+ // universal createContext/useContext, and deterministic hydration-safe useId().
3
+
4
+ import type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts } from '../context'
5
+ import type { Html, PrunelleChild } from '../jsx-runtime'
6
+ import type { RequestConsent } from '../server/consent'
7
+ import type { FieldConstraint } from '../server/form-schema'
8
+ import { AsyncLocalStorage } from 'node:async_hooks'
9
+ import { registerServerContextBridge } from '../context'
10
+ import { renderConsentBanner, renderConsentPreferences } from './consent-banner'
11
+ import { raw, ssrChild } from './index'
12
+ import { Region } from './region'
13
+
14
+ export interface SettledChunk {
15
+ html: string
16
+ error?: unknown
17
+ }
18
+
19
+ export interface PendingChunk {
20
+ id: number
21
+ // Settles to the boundary's HTML, or to its error template and the error: it never rejects.
22
+ settled: Promise<SettledChunk>
23
+ renderError: (error: unknown) => string
24
+ /** Marks this chunk as timed out / aborted so late resolution skips rendering into the RenderContext. */
25
+ discard?: () => void
26
+ }
27
+
28
+ export interface RenderContext {
29
+ headParts: string[]
30
+ title: string | undefined
31
+ pending: PendingChunk[]
32
+ nextId: number
33
+ islandDepth: number
34
+ islandSeq: number
35
+ idPrefix: string
36
+ idSeq: number
37
+ contexts: Map<symbol, unknown>
38
+ /** While an island renders, the contexts provided outside it, which the browser never sees. */
39
+ outerContexts: Map<symbol, unknown> | undefined
40
+ /** The island rendering, as its tag. */
41
+ island: string | undefined
42
+ /** Maps island chunk URL -> eager (true if hydrate is undefined/'load'). */
43
+ renderedIslands: Map<string, boolean>
44
+ hasIslands: boolean
45
+ /** True once an island's props hold a tagged value (a Date, Map, Set…), whose page preloads the revivers. */
46
+ revives: boolean
47
+ htmlAttrs: Record<string, string>
48
+ /** The region a request asked for alone (`x-pru-region`). */
49
+ region: string | undefined
50
+ /** The requested region's HTML, once the page rendered it. */
51
+ regionHtml: string | undefined
52
+ regionNames: Set<string>
53
+ /** The regions around the requested one: rendered through, their own HTML dropped. */
54
+ regionAncestors: ReadonlySet<string>
55
+ /** True while the requested region's children render: regions inside it render in full. */
56
+ inTarget: boolean
57
+ /** Compiler-emitted inline `<style>` contents rendered during this request, for CSP hashing. */
58
+ inlineStyles: string[] | undefined
59
+ /** True once HTTP headers (and CSP) have been flushed for a streamed response. */
60
+ headersFlushed: boolean
61
+ /** True once the post-flush inline `<style>` warning has been emitted for this request. */
62
+ warnedStreamStyle: boolean
63
+ /** True once the stream/region finished, timed out, was aborted, or was discarded (e.g. HEAD). */
64
+ aborted: boolean
65
+ /** Request consent state used by `<ConsentGate>`, `<ConsentBanner>` and `<ConsentPreferences>`. */
66
+ consent: RequestConsent | undefined
67
+ /** Reports an error a `<Catch>` rendered its fallback for, to the app's error hook. */
68
+ onCaught: ((error: unknown) => void) | undefined
69
+ /** Actions referenced via `useAction(fn).action` during this request, keyed by action URL. */
70
+ formActions: Map<string, unknown> | undefined
71
+ }
72
+
73
+ interface RenderScope {
74
+ owner: RenderContext
75
+ contexts: ReadonlyMap<symbol, unknown>
76
+ outerContexts: ReadonlyMap<symbol, unknown> | undefined
77
+ island: string | undefined
78
+ inTarget: boolean
79
+ formFields: ReadonlyMap<string, FieldConstraint> | undefined
80
+ }
81
+
82
+ const STORAGE_KEY = Symbol.for('pru.render.storage')
83
+ const SCOPE_STORAGE_KEY = Symbol.for('pru.render.scope.storage')
84
+ const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
85
+ const scopeStorage: AsyncLocalStorage<RenderScope> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderScope> | undefined>)[SCOPE_STORAGE_KEY] ??= new AsyncLocalStorage<RenderScope>())
86
+ let fallbackFormAction: { url: string, action: unknown } | undefined
87
+ let fallbackFormFields: ReadonlyMap<string, FieldConstraint> | undefined
88
+
89
+ ;(globalThis as { __pruAct?: (url: string, action: unknown) => void }).__pruAct = (url, action) => {
90
+ if (url === '')
91
+ return
92
+ const ctx = renderStorage.getStore()
93
+ if (ctx !== undefined)
94
+ (ctx.formActions ??= new Map()).set(url, action)
95
+ else
96
+ fallbackFormAction = { url, action }
97
+ }
98
+
99
+ function activeScope(ctx: RenderContext): RenderScope {
100
+ const scope = scopeStorage.getStore()
101
+ if (scope !== undefined && scope.owner === ctx)
102
+ return scope
103
+ return {
104
+ owner: ctx,
105
+ contexts: ctx.contexts,
106
+ outerContexts: ctx.outerContexts,
107
+ island: ctx.island,
108
+ inTarget: ctx.inTarget,
109
+ formFields: undefined,
110
+ }
111
+ }
112
+
113
+ export function lookupFormAction(url: string): unknown {
114
+ const ctx = renderStorage.getStore()
115
+ if (ctx !== undefined)
116
+ return ctx.formActions?.get(url)
117
+ return fallbackFormAction?.url === url ? fallbackFormAction.action : undefined
118
+ }
119
+
120
+ export function currentFormFields(): ReadonlyMap<string, FieldConstraint> | undefined {
121
+ const ctx = renderStorage.getStore()
122
+ return ctx !== undefined ? activeScope(ctx).formFields : fallbackFormFields
123
+ }
124
+
125
+ export function runWithFormFields<T>(fields: ReadonlyMap<string, FieldConstraint>, fn: () => T): T {
126
+ const ctx = renderStorage.getStore()
127
+ if (ctx !== undefined)
128
+ return scopeStorage.run({ ...activeScope(ctx), formFields: fields }, fn)
129
+ const prev = fallbackFormFields
130
+ fallbackFormFields = fields
131
+ try {
132
+ const out = fn()
133
+ if (out instanceof Promise)
134
+ return out.finally(() => { fallbackFormFields = prev }) as T
135
+ fallbackFormFields = prev
136
+ return out
137
+ }
138
+ catch (err) {
139
+ fallbackFormFields = prev
140
+ throw err
141
+ }
142
+ }
143
+
144
+ export function isInTarget(ctx: RenderContext): boolean {
145
+ return activeScope(ctx).inTarget
146
+ }
147
+
148
+ export function runInTarget<T>(ctx: RenderContext, fn: () => T): T {
149
+ return scopeStorage.run({ ...activeScope(ctx), inTarget: true }, fn)
150
+ }
151
+
152
+ registerServerContextBridge({
153
+ getContext(key: symbol) {
154
+ const ctx = renderStorage.getStore()
155
+ if (ctx === undefined)
156
+ return undefined
157
+ const scope = activeScope(ctx)
158
+ if (scope.contexts.has(key))
159
+ return { found: true, value: scope.contexts.get(key) }
160
+ if (scope.outerContexts?.has(key) === true)
161
+ throw new Error(`prunelle: <${scope.island}> reads a context provided outside the island, which the browser never sees; pass its value as a prop.`)
162
+ return undefined
163
+ },
164
+ runWithContext<T>(key: symbol, value: unknown, fn: () => T): T {
165
+ const ctx = renderStorage.getStore()
166
+ if (ctx === undefined)
167
+ return fn()
168
+ const cur = activeScope(ctx)
169
+ const next = new Map(cur.contexts)
170
+ next.set(key, value)
171
+ return scopeStorage.run({ ...cur, contexts: next }, fn)
172
+ },
173
+ nextId() {
174
+ const ctx = renderStorage.getStore()
175
+ if (ctx === undefined)
176
+ return undefined
177
+ return `${ctx.idPrefix}${ctx.idSeq++}`
178
+ },
179
+ region(props) {
180
+ return Region(props)
181
+ },
182
+ consentGate(props) {
183
+ return ConsentGate(props)
184
+ },
185
+ consentBanner(props) {
186
+ return ConsentBanner(props)
187
+ },
188
+ consentPreferences(props) {
189
+ return ConsentPreferences(props)
190
+ },
191
+ head(props) {
192
+ return Head(props)
193
+ },
194
+ suspense(props) {
195
+ return Suspense(props)
196
+ },
197
+ catch(props) {
198
+ return Catch(props)
199
+ },
200
+ })
201
+
202
+ export function createRenderContext(
203
+ region?: string,
204
+ ancestors: ReadonlySet<string> = new Set(),
205
+ consent?: RequestConsent,
206
+ onCaught?: (error: unknown) => void,
207
+ ): RenderContext {
208
+ return {
209
+ headParts: [],
210
+ title: undefined,
211
+ pending: [],
212
+ nextId: 0,
213
+ islandDepth: 0,
214
+ islandSeq: 0,
215
+ idPrefix: '',
216
+ idSeq: 0,
217
+ contexts: new Map(),
218
+ outerContexts: undefined,
219
+ island: undefined,
220
+ renderedIslands: new Map(),
221
+ hasIslands: false,
222
+ revives: false,
223
+ htmlAttrs: {},
224
+ region,
225
+ regionHtml: undefined,
226
+ regionNames: new Set(),
227
+ regionAncestors: ancestors,
228
+ inTarget: false,
229
+ inlineStyles: undefined,
230
+ headersFlushed: false,
231
+ warnedStreamStyle: false,
232
+ aborted: false,
233
+ consent,
234
+ onCaught,
235
+ formActions: undefined,
236
+ }
237
+ }
238
+
239
+ /** Records a compiler-emitted inline `<style>` block's CSS in the active RenderContext for CSP hashing. */
240
+ export function recordInlineStyle(css: string): void {
241
+ const ctx = renderStorage.getStore()
242
+ if (ctx === undefined || css === '')
243
+ return
244
+ const isNew = ctx.inlineStyles === undefined || !ctx.inlineStyles.includes(css)
245
+ if (ctx.headersFlushed && isNew && !ctx.warnedStreamStyle) {
246
+ ctx.warnedStreamStyle = true
247
+ console.warn('prunelle: an inline <style> was rendered inside a streamed <Suspense> boundary after CSP headers were sent; move the style into a CSS file or outside <Suspense> so strict CSP does not block it.')
248
+ }
249
+ if (ctx.inlineStyles === undefined)
250
+ ctx.inlineStyles = [css]
251
+ else if (isNew)
252
+ ctx.inlineStyles.push(css)
253
+ }
254
+
255
+ /** Emits compiler-authored `<style>` text unchanged while registering it for CSP hashing. */
256
+ export function ssrStyleBlock(css: string): string {
257
+ recordInlineStyle(css)
258
+ return css
259
+ }
260
+
261
+ // An island sees only the contexts provided inside it, as in the browser.
262
+ export function renderIsland(ctx: RenderContext, name: string, render: () => string): string {
263
+ const cur = activeScope(ctx)
264
+ return scopeStorage.run({ ...cur, contexts: new Map(), outerContexts: cur.contexts, island: name }, render)
265
+ }
266
+
267
+
268
+ export function runWithRenderContext<T>(ctx: RenderContext, fn: () => T): T {
269
+ return renderStorage.run(ctx, fn)
270
+ }
271
+
272
+ export function currentRenderContext(): RenderContext | undefined {
273
+ return renderStorage.getStore()
274
+ }
275
+
276
+ const TITLE_RE = /<title\b[^>]*>([\s\S]*?)<\/title>/gi
277
+
278
+ /** Renders `children`, or `fallback` when they throw or reject; the compiler hands it `children` as a getter, so they render inside the try. */
279
+ export function Catch(props: CatchProps): Html | Promise<Html> {
280
+ const ctx = renderStorage.getStore()
281
+ const fail = (error: unknown): Html => {
282
+ if (ctx?.onCaught !== undefined)
283
+ ctx.onCaught(error)
284
+ else
285
+ console.error(error)
286
+ const fallback = props.fallback
287
+ return raw(ssrChild(typeof fallback === 'function' ? fallback(error, () => {}) : fallback))
288
+ }
289
+ try {
290
+ const children = props.children as PrunelleChild | Promise<PrunelleChild>
291
+ if (children instanceof Promise)
292
+ return children.then(resolved => raw(ssrChild(resolved)), fail)
293
+ return raw(ssrChild(children))
294
+ }
295
+ catch (error) {
296
+ return fail(error)
297
+ }
298
+ }
299
+
300
+ /** Renders `children` only when consent for `category` is granted; otherwise renders `fallback`. */
301
+ export function ConsentGate(props: ConsentGateProps): Html {
302
+ const ctx = renderStorage.getStore()
303
+ const granted = props.category === 'essential' || ctx?.consent?.has(props.category) === true
304
+ return raw(ssrChild(granted ? props.children : props.fallback))
305
+ }
306
+
307
+ export function ConsentBanner(props: ConsentBannerProps): Html {
308
+ return raw(renderConsentBanner(renderStorage.getStore()?.consent, props))
309
+ }
310
+
311
+ export function ConsentPreferences(props: ConsentTexts): Html {
312
+ return raw(renderConsentPreferences(renderStorage.getStore()?.consent, props))
313
+ }
314
+
315
+ /** Collects document <head> tags during SSR; innermost <title> wins. */
316
+ export function Head(props: { children?: PrunelleChild }): Html {
317
+ const ctx = renderStorage.getStore()
318
+ if (ctx === undefined)
319
+ return raw('')
320
+
321
+ let html = ssrChild(props.children)
322
+ TITLE_RE.lastIndex = 0
323
+ const titleMatch = TITLE_RE.exec(html)
324
+ if (titleMatch !== null) {
325
+ // Inner page renders before outer layouts, so the first (innermost) <title> wins.
326
+ ctx.title ??= titleMatch[0]
327
+ TITLE_RE.lastIndex = 0
328
+ html = html.replace(TITLE_RE, '')
329
+ }
330
+ if (html !== '')
331
+ ctx.headParts.push(html)
332
+
333
+ return raw('')
334
+ }
335
+
336
+ /**
337
+ * Streaming SSR boundary: flushes `fallback` immediately and streams resolved async children
338
+ * with a zero-dependency inline swap script. Islands inside streamed chunks hydrate automatically!
339
+ */
340
+ export function Suspense(props: { fallback?: PrunelleChild, error?: PrunelleChild | ((error: unknown) => PrunelleChild), children?: PrunelleChild | Promise<PrunelleChild> }): Html {
341
+ const ctx = renderStorage.getStore()
342
+ const child = props.children
343
+
344
+ if (!(child instanceof Promise))
345
+ return raw(ssrChild(child))
346
+
347
+ if (ctx === undefined)
348
+ return raw(ssrChild(props.fallback))
349
+
350
+ const id = ctx.nextId++
351
+ const scope = activeScope(ctx)
352
+ // Capture RenderContext and RenderScope so timeout / error fallback renders still see outer Context.Provider and <Region> state.
353
+ const renderError = (error: unknown): string => {
354
+ try {
355
+ return runWithRenderContext(ctx, () => scopeStorage.run(scope, () => ssrChild(typeof props.error === 'function' ? props.error(error) : props.error)))
356
+ }
357
+ catch {
358
+ return ''
359
+ }
360
+ }
361
+ let discarded = false
362
+ const isAborted = (): boolean => ctx.aborted || discarded
363
+ ctx.pending.push({
364
+ id,
365
+ settled: settle(ctx, scope, child, renderError, isAborted),
366
+ renderError,
367
+ discard: () => { discarded = true },
368
+ })
369
+
370
+ const fallbackHtml = ssrChild(props.fallback)
371
+ return raw(`<pru-s id="k-s-${id}">${fallbackHtml}</pru-s>`)
372
+ }
373
+
374
+ async function settle(
375
+ ctx: RenderContext,
376
+ scope: RenderScope,
377
+ child: Promise<PrunelleChild>,
378
+ renderError: (error: unknown) => string,
379
+ isAborted: () => boolean,
380
+ ): Promise<SettledChunk> {
381
+ try {
382
+ const resolved = await child
383
+ if (isAborted())
384
+ return { html: '' }
385
+ return { html: runWithRenderContext(ctx, () => scopeStorage.run(scope, () => ssrChild(resolved))) }
386
+ }
387
+ catch (error) {
388
+ if (isAborted())
389
+ return { html: '' }
390
+ return { html: renderError(error), error }
391
+ }
392
+ }
393
+
394
+ /** Fixed streaming swap bootstrap (constant content -> deterministic SHA-256 CSP hash, zero per-chunk inline scripts). */
395
+ export const PRUNELLE_STREAM_SCRIPT = `(()=>{const q=new Map(),w=n=>{if(n.isConnected&&n.nodeType===1&&n.tagName==='TEMPLATE'&&n.dataset.ks){const id=n.dataset.ks,s=document.getElementById('k-s-'+id);if(s){q.delete(id);s.replaceWith(n.content);n.remove();for(const t of q.values())w(t)}else q.set(id,n)}};const o=new MutationObserver(ms=>{for(const m of ms)for(const n of m.addedNodes)w(n)});o.observe(document.documentElement,{childList:true,subtree:true});document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('template[data-ks]').forEach(w);o.disconnect();q.clear()},{once:true})})()`
396
+
397
+ export function streamChunkScript(id: number, resolvedHtml: string): string {
398
+ return `<template data-ks="${id}">${resolvedHtml}</template>`
399
+ }