prunelle 0.1.1 → 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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  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/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -1,10 +1,13 @@
1
1
  // Per-request SSR context for <Head> metadata, streaming <Suspense>, rendered island tracking,
2
2
  // universal createContext/useContext, and deterministic hydration-safe useId().
3
3
 
4
- import type { CatchProps, ConsentGateProps } from '../context'
4
+ import type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts } from '../context'
5
5
  import type { Html, PrunelleChild } from '../jsx-runtime'
6
+ import type { RequestConsent } from '../server/consent'
7
+ import type { FieldConstraint } from '../server/form-schema'
6
8
  import { AsyncLocalStorage } from 'node:async_hooks'
7
9
  import { registerServerContextBridge } from '../context'
10
+ import { renderConsentBanner, renderConsentPreferences } from './consent-banner'
8
11
  import { raw, ssrChild } from './index'
9
12
  import { Region } from './region'
10
13
 
@@ -18,6 +21,8 @@ export interface PendingChunk {
18
21
  // Settles to the boundary's HTML, or to its error template and the error: it never rejects.
19
22
  settled: Promise<SettledChunk>
20
23
  renderError: (error: unknown) => string
24
+ /** Marks this chunk as timed out / aborted so late resolution skips rendering into the RenderContext. */
25
+ discard?: () => void
21
26
  }
22
27
 
23
28
  export interface RenderContext {
@@ -51,10 +56,18 @@ export interface RenderContext {
51
56
  inTarget: boolean
52
57
  /** Compiler-emitted inline `<style>` contents rendered during this request, for CSP hashing. */
53
58
  inlineStyles: string[] | undefined
54
- /** Request consent state used by `<ConsentGate>`. */
55
- consent: { has(category: string): boolean } | 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
56
67
  /** Reports an error a `<Catch>` rendered its fallback for, to the app's error hook. */
57
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
58
71
  }
59
72
 
60
73
  interface RenderScope {
@@ -63,12 +76,25 @@ interface RenderScope {
63
76
  outerContexts: ReadonlyMap<symbol, unknown> | undefined
64
77
  island: string | undefined
65
78
  inTarget: boolean
79
+ formFields: ReadonlyMap<string, FieldConstraint> | undefined
66
80
  }
67
81
 
68
82
  const STORAGE_KEY = Symbol.for('pru.render.storage')
69
83
  const SCOPE_STORAGE_KEY = Symbol.for('pru.render.scope.storage')
70
84
  const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
71
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
+ }
72
98
 
73
99
  function activeScope(ctx: RenderContext): RenderScope {
74
100
  const scope = scopeStorage.getStore()
@@ -80,6 +106,38 @@ function activeScope(ctx: RenderContext): RenderScope {
80
106
  outerContexts: ctx.outerContexts,
81
107
  island: ctx.island,
82
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
83
141
  }
84
142
  }
85
143
 
@@ -124,6 +182,12 @@ registerServerContextBridge({
124
182
  consentGate(props) {
125
183
  return ConsentGate(props)
126
184
  },
185
+ consentBanner(props) {
186
+ return ConsentBanner(props)
187
+ },
188
+ consentPreferences(props) {
189
+ return ConsentPreferences(props)
190
+ },
127
191
  head(props) {
128
192
  return Head(props)
129
193
  },
@@ -138,7 +202,7 @@ registerServerContextBridge({
138
202
  export function createRenderContext(
139
203
  region?: string,
140
204
  ancestors: ReadonlySet<string> = new Set(),
141
- consent?: { has(category: string): boolean },
205
+ consent?: RequestConsent,
142
206
  onCaught?: (error: unknown) => void,
143
207
  ): RenderContext {
144
208
  return {
@@ -163,8 +227,12 @@ export function createRenderContext(
163
227
  regionAncestors: ancestors,
164
228
  inTarget: false,
165
229
  inlineStyles: undefined,
230
+ headersFlushed: false,
231
+ warnedStreamStyle: false,
232
+ aborted: false,
166
233
  consent,
167
234
  onCaught,
235
+ formActions: undefined,
168
236
  }
169
237
  }
170
238
 
@@ -173,9 +241,14 @@ export function recordInlineStyle(css: string): void {
173
241
  const ctx = renderStorage.getStore()
174
242
  if (ctx === undefined || css === '')
175
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
+ }
176
249
  if (ctx.inlineStyles === undefined)
177
250
  ctx.inlineStyles = [css]
178
- else if (!ctx.inlineStyles.includes(css))
251
+ else if (isNew)
179
252
  ctx.inlineStyles.push(css)
180
253
  }
181
254
 
@@ -231,6 +304,14 @@ export function ConsentGate(props: ConsentGateProps): Html {
231
304
  return raw(ssrChild(granted ? props.children : props.fallback))
232
305
  }
233
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
+
234
315
  /** Collects document <head> tags during SSR; innermost <title> wins. */
235
316
  export function Head(props: { children?: PrunelleChild }): Html {
236
317
  const ctx = renderStorage.getStore()
@@ -277,24 +358,41 @@ export function Suspense(props: { fallback?: PrunelleChild, error?: PrunelleChil
277
358
  return ''
278
359
  }
279
360
  }
280
- ctx.pending.push({ id, settled: settle(ctx, scope, child, renderError), renderError })
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
+ })
281
369
 
282
370
  const fallbackHtml = ssrChild(props.fallback)
283
371
  return raw(`<pru-s id="k-s-${id}">${fallbackHtml}</pru-s>`)
284
372
  }
285
373
 
286
- async function settle(ctx: RenderContext, scope: RenderScope, child: Promise<PrunelleChild>, renderError: (error: unknown) => string): Promise<SettledChunk> {
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> {
287
381
  try {
288
382
  const resolved = await child
383
+ if (isAborted())
384
+ return { html: '' }
289
385
  return { html: runWithRenderContext(ctx, () => scopeStorage.run(scope, () => ssrChild(resolved))) }
290
386
  }
291
387
  catch (error) {
388
+ if (isAborted())
389
+ return { html: '' }
292
390
  return { html: renderError(error), error }
293
391
  }
294
392
  }
295
393
 
296
394
  /** Fixed streaming swap bootstrap (constant content -> deterministic SHA-256 CSP hash, zero per-chunk inline scripts). */
297
- export const PRUNELLE_STREAM_SCRIPT = `(()=>{const w=n=>{if(n.nodeType===1&&n.tagName==='TEMPLATE'&&n.dataset.ks){const s=document.getElementById('k-s-'+n.dataset.ks);if(s){s.replaceWith(n.content);n.remove()}}};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()},{once:true})})()`
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})})()`
298
396
 
299
397
  export function streamChunkScript(id: number, resolvedHtml: string): string {
300
398
  return `<template data-ks="${id}">${resolvedHtml}</template>`
package/src/ssr/index.ts CHANGED
@@ -1,11 +1,15 @@
1
1
  // Prunelle SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
2
2
 
3
3
  import type { Html, HydrateStrategy, PrunelleChild } from '../jsx-runtime'
4
+ import type { ServerAction } from '../server/action'
5
+ import type { FieldConstraint } from '../server/form-schema'
4
6
  import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
5
7
  import { renderOnServer } from '../reactivity/index'
8
+ import { renderProtectFields } from '../server/action-protect'
9
+ import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
6
10
  import { styleText } from '../style'
7
11
  import { assertRenderable } from '../unrenderable'
8
- import { currentRenderContext, PRUNELLE_STREAM_SCRIPT, renderIsland } from './context'
12
+ import { currentFormFields, currentRenderContext, lookupFormAction, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
9
13
  import { keepScrollTag } from './navigation'
10
14
  export { ssrStyleBlock } from './context'
11
15
 
@@ -96,6 +100,16 @@ export function escAttr(value: unknown): string {
96
100
  .replaceAll('>', '&gt;')
97
101
  }
98
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
+
99
113
  // `<`, then the two line separators, built from their code points so the source shows no invisible character.
100
114
  const SCRIPT_JSON_RE = new RegExp(`[<${String.fromCharCode(0x2028, 0x2029)}]`, 'g')
101
115
 
@@ -143,6 +157,8 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
143
157
  if (props == null || typeof props !== 'object')
144
158
  return ''
145
159
  let out = ''
160
+ let formPresent = 0
161
+ const trackForm = (tag === 'input' || tag === 'select' || tag === 'textarea') && currentFormFields() !== undefined
146
162
  for (const [rawKey, value] of Object.entries(props)) {
147
163
  if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
148
164
  continue
@@ -151,8 +167,121 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
151
167
  const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
152
168
  if (isBlockedAttr(name))
153
169
  continue
170
+ if (trackForm && value !== undefined) {
171
+ const bit = FORM_ATTR_BITS[name.toLowerCase()]
172
+ if (bit !== undefined)
173
+ formPresent |= bit
174
+ }
154
175
  out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value, tag)
155
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
+
156
285
  return out
157
286
  }
158
287
 
@@ -215,8 +344,16 @@ function serializeIslandProps(props: Record<string, unknown>): string {
215
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.`)
216
345
  if (typeof orig === 'object' && orig !== null && 'peek' in orig && 'value' in orig)
217
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.`)
218
- if (typeof orig === 'object' && orig !== null && !Array.isArray(orig) && Object.hasOwn(orig, '__k'))
219
- return { __k: 'O', v: Object.entries(orig).filter(([, x]) => x !== undefined) }
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
+ }
220
357
  return value
221
358
  })
222
359
  }
@@ -416,12 +553,19 @@ export interface DocumentOptions {
416
553
  styles?: Iterable<string> | undefined
417
554
  hasIslands?: boolean | undefined
418
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
419
558
  // The head markup every page shares for the `navigation` settings: see `createNavigation`.
420
559
  navigation?: string | undefined
421
560
  }
422
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
+
423
567
  export function renderDocument(options: DocumentOptions): string {
424
- const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, navigation } = options
568
+ const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, hasFavicon, navigation } = options
425
569
  let headExtra = head
426
570
 
427
571
  if (headTags !== undefined) {
@@ -429,6 +573,9 @@ export function renderDocument(options: DocumentOptions): string {
429
573
  headExtra += tag
430
574
  }
431
575
 
576
+ if (!hasFavicon && !TAB_ICON_RE.test(headExtra))
577
+ headExtra += EMPTY_ICON
578
+
432
579
  if (styles !== undefined) {
433
580
  for (const href of styles)
434
581
  headExtra += `<link rel="stylesheet" href="${escAttr(href)}">`
@@ -10,7 +10,7 @@ export type Eagerness = 'conservative' | 'moderate' | 'eager'
10
10
  export interface NavigationConfig {
11
11
  /** Fades one page into the next with a cross-document view transition (`@view-transition { navigation: auto }`), off under `prefers-reduced-motion`. On by default, `false` leaves the browser's plain repaint. */
12
12
  viewTransitions?: boolean | undefined
13
- /** When the browser fetches the page a same-origin link points at, through Speculation Rules: `'moderate'` (the default) on hover, `'conservative'` on press, `'eager'` as soon as it can, `false` never. A link, or an ancestor of it, with `data-pru-no-prefetch` is never fetched; neither is a `download` or `rel="nofollow"` link, a prunelle route (actions among them) or another origin's page. */
13
+ /** When the browser fetches the page a same-origin link points at, through Speculation Rules: `'conservative'` (the default) on press, `'moderate'` on hover (and, on phones, as a link scrolls into view), `'eager'` as soon as it can, `false` never. A link, or an ancestor of it, with `data-pru-no-prefetch` is never fetched; neither is a `download` or `rel="nofollow"` link, a prunelle route (actions among them) or another origin's page. */
14
14
  prefetch?: Eagerness | false | undefined
15
15
  /** Renders the page a link points at before it is followed, which runs its `load()`: off by default, `true` is `'moderate'`. */
16
16
  prerender?: Eagerness | boolean | undefined
@@ -64,7 +64,7 @@ export function createNavigation(config: NavigationConfig | undefined): Navigati
64
64
  html += `<style>${VIEW_TRANSITION_STYLE}</style>`
65
65
  styleHashes.push(cspSha256(VIEW_TRANSITION_STYLE))
66
66
  }
67
- const prefetch = config?.prefetch === undefined ? 'moderate' : config.prefetch
67
+ const prefetch = config?.prefetch === undefined ? 'conservative' : config.prefetch
68
68
  const prerender = config?.prerender === true ? 'moderate' : config?.prerender || undefined
69
69
  if (prefetch !== false || prerender !== undefined) {
70
70
  const where = rulesWhere()
package/src/ssr/region.ts CHANGED
@@ -83,6 +83,7 @@ async function settleChunkWithin(
83
83
  let timer: ReturnType<typeof setTimeout> | undefined
84
84
  const timedOut = new Promise<SettledChunk>((resolve) => {
85
85
  timer = setTimeout(() => {
86
+ chunk.discard?.()
86
87
  const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
87
88
  resolve({ html: runInScope(() => chunk.renderError(error)), error })
88
89
  }, remaining)
@@ -98,8 +99,7 @@ async function settleChunkWithin(
98
99
  async function awaitRegionDiscovery(
99
100
  ctx: RenderContext,
100
101
  deadline: number,
101
- onError: ((error: unknown) => void) | undefined,
102
- runInScope: <T>(fn: () => T) => T,
102
+ reportError: (id: number, error: unknown) => void,
103
103
  ): Promise<void> {
104
104
  const watched = new Set<number>()
105
105
  let pendingCount = 0
@@ -125,8 +125,8 @@ async function awaitRegionDiscovery(
125
125
  pendingCount--
126
126
  if (done)
127
127
  return
128
- if ('error' in settled && onError !== undefined)
129
- runInScope(() => onError(settled.error))
128
+ if ('error' in settled)
129
+ reportError(chunk.id, settled.error)
130
130
  if (ctx.regionHtml !== undefined) {
131
131
  finish()
132
132
  return
@@ -150,22 +150,43 @@ export async function finishRegion(ctx: RenderContext, options?: FinishRegionOpt
150
150
  const onError = options?.onError
151
151
  const runInScope = options?.runInScope ?? (<T>(fn: () => T) => fn())
152
152
  const deadline = Date.now() + streamTimeout
153
+ const reported = new Set<number>()
154
+ const reportError = (id: number, error: unknown): void => {
155
+ if (onError === undefined || reported.has(id))
156
+ return
157
+ reported.add(id)
158
+ runInScope(() => onError(error))
159
+ }
153
160
 
154
- if (ctx.regionHtml === undefined && ctx.pending.length > 0)
155
- await awaitRegionDiscovery(ctx, deadline, onError, runInScope)
161
+ try {
162
+ if (ctx.regionHtml === undefined && ctx.pending.length > 0)
163
+ await awaitRegionDiscovery(ctx, deadline, reportError)
156
164
 
157
- let html = ctx.regionHtml
158
- if (html === undefined)
159
- return undefined
160
- for (let i = 0; i < ctx.pending.length; i++) {
161
- const chunk = ctx.pending[i]!
162
- const range = findPlaceholderRange(html, chunk.id)
163
- if (range === undefined)
164
- continue
165
- const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
166
- if ('error' in settled && onError !== undefined)
167
- runInScope(() => onError(settled.error))
168
- html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
165
+ let html = ctx.regionHtml
166
+ if (html === undefined)
167
+ return undefined
168
+ const resolved = new Set<number>()
169
+ let progressed = true
170
+ while (progressed) {
171
+ progressed = false
172
+ for (let i = 0; i < ctx.pending.length; i++) {
173
+ const chunk = ctx.pending[i]!
174
+ if (resolved.has(chunk.id))
175
+ continue
176
+ const range = findPlaceholderRange(html, chunk.id)
177
+ if (range === undefined)
178
+ continue
179
+ resolved.add(chunk.id)
180
+ const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
181
+ if ('error' in settled)
182
+ reportError(chunk.id, settled.error)
183
+ html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
184
+ progressed = true
185
+ }
186
+ }
187
+ return html
188
+ }
189
+ finally {
190
+ ctx.aborted = true
169
191
  }
170
- return html
171
192
  }
package/src/style.ts CHANGED
@@ -20,10 +20,73 @@ function cssName(key: string): string {
20
20
  return MS_PREFIX.test(key) ? `-${name}` : name
21
21
  }
22
22
 
23
+ const PROPERTY_NAME = /^-{0,2}[a-z][\w-]*$/i
24
+
25
+ const NL = /[\n\r\f]/
26
+ const URL_FN = /(?:^|[^\w-])url$/i
27
+ // After `url(`, either a quoted string opener (group 1) or a valid unquoted `<url-token>` through `)` (disjoint branches: linear time).
28
+ const UNQUOTED_URL = /[ \t]*(?:(["'])|(?:\\[^\n\r\f]|[^"'(){}\u0000-\u0020\u007F\\])*[ \t]*\))/y
29
+
30
+ // Whether `value` stays one declaration value: a `;`, `{` or `}` outside quotes and parentheses, a comment, a raw newline, a trailing/newline escape, an unquoted bad-url, or a quote or parenthesis left open would end it and let the rest add declarations.
31
+ function isOneValue(value: string): boolean {
32
+ let depth = 0
33
+ let quote = ''
34
+ let esc = false
35
+ for (let i = 0; i < value.length; i++) {
36
+ const c = value[i]!
37
+ if (c === '\\') {
38
+ if (++i >= value.length || NL.test(value[i]!))
39
+ return false
40
+ esc = true
41
+ }
42
+ else if (NL.test(c)) {
43
+ return false
44
+ }
45
+ else if (quote !== '') {
46
+ quote = c === quote ? '' : quote
47
+ }
48
+ else if (c === '"' || c === '\'') {
49
+ quote = c
50
+ esc = false
51
+ }
52
+ else if (c === '/' && value[i + 1] === '*') {
53
+ return false
54
+ }
55
+ else if (c === '(') {
56
+ const checkUrl = esc || URL_FN.test(value.slice(0, i))
57
+ esc = false
58
+ if (checkUrl) {
59
+ UNQUOTED_URL.lastIndex = i + 1
60
+ const m = UNQUOTED_URL.exec(value)
61
+ if (m === null || (m[1] === undefined && m[0].includes('/*')))
62
+ return false
63
+ if (m[1] === undefined) {
64
+ i = UNQUOTED_URL.lastIndex - 1
65
+ continue
66
+ }
67
+ }
68
+ depth++
69
+ }
70
+ else if (c === ')' && --depth < 0) {
71
+ return false
72
+ }
73
+ else if (depth === 0 && (c === ';' || c === '{' || c === '}')) {
74
+ return false
75
+ }
76
+ else if (',);{}'.includes(c)) {
77
+ esc = false
78
+ }
79
+ }
80
+ return quote === '' && depth === 0
81
+ }
82
+
83
+ /** The CSS text of a style object. A declaration that could not stay one is dropped, as a browser drops an invalid one: a key that is not a property name, a non-finite number, a string value `isOneValue` refuses. */
23
84
  export function styleText(style: Record<string, unknown>): string {
24
85
  let out = ''
25
86
  for (const [key, value] of Object.entries(style)) {
26
- if (value == null || value === '' || value === false)
87
+ if (value == null || value === '' || value === false || !PROPERTY_NAME.test(key))
88
+ continue
89
+ if (typeof value === 'number' ? !Number.isFinite(value) : !isOneValue(String(value)))
27
90
  continue
28
91
  const name = cssName(key)
29
92
  const px = typeof value === 'number' && !name.startsWith('--') && !UNITLESS.has(name)