prunelle 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +94 -136
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
package/src/ssr/index.ts CHANGED
@@ -9,8 +9,9 @@ import { renderProtectFields } from '../server/action-protect'
9
9
  import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
10
10
  import { styleText } from '../style'
11
11
  import { assertRenderable } from '../unrenderable'
12
- import { currentFormFields, currentRenderContext, lookupFormAction, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
13
- import { KEEP_SCROLL_TAG, keepScrollTag } from './navigation'
12
+ import type { RenderContext } from './context'
13
+ import { currentFormFields, currentRenderContext, ensureRenderedIslands, lookupFormAction, needsIslandScope, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
14
+ import { withKeepScroll } from './navigation'
14
15
  export { ssrStyleBlock } from './context'
15
16
 
16
17
  export const PRUNELLE_ISLAND_STYLE = 'pru-island,pru-slot{display:contents}'
@@ -24,15 +25,13 @@ function isRawHtml(value: unknown): value is Html {
24
25
 
25
26
  const ESC_TEXT = /[&<>]/
26
27
  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
- }
28
+ const hasBunEscape = typeof Bun !== 'undefined' && typeof Bun.escapeHTML === 'function'
29
+ const escText: (str: string) => string = hasBunEscape
30
+ ? Bun.escapeHTML
31
+ : (str: string): string => (ESC_TEXT.test(str) ? str.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;') : str)
32
+ const escAttrStr: (str: string) => string = hasBunEscape
33
+ ? Bun.escapeHTML
34
+ : (str: string): string => (ESC_ATTR.test(str) ? str.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;') : str)
36
35
 
37
36
  export function esc(value: unknown): string {
38
37
  if (typeof value === 'string')
@@ -88,16 +87,7 @@ export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
88
87
  }
89
88
 
90
89
  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;')
90
+ return escAttrStr(typeof value === 'string' ? value : String(value))
101
91
  }
102
92
 
103
93
  // What XML 1.0 forbids in a document: C0 controls but tab, LF and CR, U+FFFE, U+FFFF and lone surrogates.
@@ -300,15 +290,16 @@ export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render
300
290
  if (!items)
301
291
  return ''
302
292
  const list: readonly T[] = Array.isArray(items) ? items : [...items]
303
- let out = ''
293
+ // Joined once, like the loops the compiler writes inline: `+=` would leave a rope node per row for the garbage collector.
294
+ const out: string[] = []
304
295
  for (let i = 0; i < list.length; i++)
305
- out += render(list[i] as T, i, list)
306
- return out
296
+ out.push(render(list[i] as T, i, list))
297
+ return out.join('')
307
298
  }
308
299
 
309
300
  export function ssrChild(value: PrunelleChild): string {
310
301
  if (typeof value === 'string')
311
- return esc(value)
302
+ return escText(value)
312
303
  if (typeof value === 'number')
313
304
  return String(value)
314
305
  if (value == null || typeof value === 'boolean')
@@ -322,7 +313,7 @@ export function ssrChild(value: PrunelleChild): string {
322
313
  return out
323
314
  }
324
315
  assertRenderable(value, 'text')
325
- return esc(String(value))
316
+ return escText(String(value))
326
317
  }
327
318
 
328
319
  function serializeIslandProps(props: Record<string, unknown>): string {
@@ -371,31 +362,32 @@ function serializeIslandProps(props: Record<string, unknown>): string {
371
362
 
372
363
  let fallbackIslandDepth = 0
373
364
 
374
- function getIslandDepth(): number {
375
- const ctx = currentRenderContext()
376
- return ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth
377
- }
378
-
379
- export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy): void {
380
- const ctx = currentRenderContext()
381
- if (ctx === undefined)
382
- return
365
+ function recordIslandOn(ctx: RenderContext, chunk: string, hydrate?: HydrateStrategy): void {
383
366
  ctx.hasIslands = true
367
+ if (ctx.skipIslandMap)
368
+ return
369
+ const map = ensureRenderedIslands(ctx)
384
370
  const eager = hydrate === undefined || hydrate === 'load'
385
371
  if (eager)
386
- ctx.renderedIslands.set(chunk, true)
387
- else if (!ctx.renderedIslands.has(chunk))
388
- ctx.renderedIslands.set(chunk, false)
372
+ map.set(chunk, true)
373
+ else if (!map.has(chunk))
374
+ map.set(chunk, false)
389
375
  }
390
376
 
391
- export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy, name = 'island'): string {
377
+ export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy): void {
392
378
  const ctx = currentRenderContext()
379
+ if (ctx !== undefined)
380
+ recordIslandOn(ctx, chunk, hydrate)
381
+ }
382
+
383
+ function runInIsland(ctx: RenderContext | undefined, render: () => string, chunk?: string, hydrate?: HydrateStrategy, name = 'island'): string {
393
384
  if (ctx !== undefined) {
394
385
  if (chunk !== undefined && ctx.islandDepth === 0)
395
- recordRenderedIsland(chunk, hydrate)
386
+ recordIslandOn(ctx, chunk, hydrate)
396
387
  ctx.islandDepth++
397
388
  try {
398
- return renderOnServer(ctx.islandDepth === 1 ? () => renderIsland(ctx, name, render) : render)
389
+ const fn = ctx.islandDepth === 1 && needsIslandScope(ctx) ? () => renderIsland(ctx, name, render) : render
390
+ return renderOnServer(fn, ctx.seeds, ctx)
399
391
  }
400
392
  finally {
401
393
  ctx.islandDepth--
@@ -410,6 +402,10 @@ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: Hydr
410
402
  }
411
403
  }
412
404
 
405
+ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy, name = 'island'): string {
406
+ return runInIsland(currentRenderContext(), render, chunk, hydrate, name)
407
+ }
408
+
413
409
 
414
410
  /** Lazily evaluates non-async component children on first read inside the component's dynamic context, memoizing the result. */
415
411
  export function ssrChildProp<P extends Record<string, unknown>>(props: P, fn: () => Html): P {
@@ -468,13 +464,16 @@ function renderIslandBody(
468
464
  if (ctx !== undefined) {
469
465
  const prevPrefix = ctx.idPrefix
470
466
  const prevSeq = ctx.idSeq
471
- const islandPrefix = `i${ctx.islandSeq++}-`
467
+ const islandPrefix = `i${ctx.idScope}${ctx.islandSeq++}-`
472
468
  ctx.idPrefix = islandPrefix
473
469
  ctx.idSeq = 0
474
470
  try {
475
- inner = ssrInIsland(render, undefined, undefined, name)
471
+ inner = runInIsland(ctx, render, undefined, undefined, name)
476
472
  if (ctx.idSeq > 0)
477
473
  idAttr = ` i="${islandPrefix}"`
474
+ // The module state this island wrote, for the browser to start from as the server rendered it.
475
+ if (ctx.seeds?.out !== undefined)
476
+ idAttr += ` s="${escAttr(JSON.stringify(ctx.seeds.out))}"`
478
477
  }
479
478
  finally {
480
479
  ctx.idPrefix = prevPrefix
@@ -482,7 +481,7 @@ function renderIslandBody(
482
481
  }
483
482
  }
484
483
  else {
485
- inner = ssrInIsland(render, undefined, undefined, name)
484
+ inner = runInIsland(undefined, render, undefined, undefined, name)
486
485
  }
487
486
  }
488
487
 
@@ -500,12 +499,12 @@ export function ssrIslandStatic(
500
499
  name?: string,
501
500
  slot?: TrackedSlot,
502
501
  ): string {
503
- if (getIslandDepth() > 0)
502
+ const ctx = currentRenderContext()
503
+ if ((ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth) > 0)
504
504
  return render !== undefined ? render() : ''
505
505
 
506
- const ctx = currentRenderContext()
507
506
  if (ctx !== undefined)
508
- recordRenderedIsland(chunk, hydrate)
507
+ recordIslandOn(ctx, chunk, hydrate)
509
508
 
510
509
  const { idAttr, inner, hiddenSlot } = renderIslandBody(ctx, render, hydrate, name, slot)
511
510
  const tag = idAttr === '' ? openTag : `${openTag.slice(0, -1)}${idAttr}>`
@@ -522,12 +521,12 @@ export function ssrIsland(
522
521
  name?: string,
523
522
  slot?: TrackedSlot,
524
523
  ): string {
525
- if (getIslandDepth() > 0)
524
+ const ctx = currentRenderContext()
525
+ if ((ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth) > 0)
526
526
  return render()
527
527
 
528
- const ctx = currentRenderContext()
529
528
  if (ctx !== undefined)
530
- recordRenderedIsland(chunk, hydrate)
529
+ recordIslandOn(ctx, chunk, hydrate)
531
530
 
532
531
  let propsAttr = ''
533
532
  let propsScript = ''
@@ -556,8 +555,10 @@ export interface DocumentOptions {
556
555
  htmlAttrs?: Record<string, string> | undefined
557
556
  runtimeScript?: string | undefined
558
557
  alwaysLoadRuntime?: boolean | undefined
559
- /** Set on a route that renders a `<Region>`: the plugins' `regionClientEntry` bundle. */
558
+ /** Set on a route that renders a `<Region>`: the core region client bundle. */
560
559
  regionScript?: string | undefined
560
+ /** The manifest's `buildId`, stamped on the region script so a swap can tell an answer from another build. */
561
+ buildId?: string | undefined
561
562
  preloadChunks?: Iterable<string> | undefined
562
563
  /** Script URL to the chunks it imports statically, preloaded with it: the browser then fetches them all at once. */
563
564
  chunkImports?: Readonly<Record<string, readonly string[]>> | undefined
@@ -576,7 +577,7 @@ const TAB_ICON_RE = /<link\b[^>]*\brel=["']?(?:[^"'>]*\s)?icon(?=[\s"'>])/i
576
577
  const EMPTY_ICON = '<link rel="icon" href="data:,">'
577
578
 
578
579
  export function renderDocument(options: DocumentOptions): string {
579
- const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, hasFavicon, navigation } = options
580
+ const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, buildId, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, hasFavicon, navigation } = options
580
581
  let headExtra = head
581
582
 
582
583
  if (headTags !== undefined) {
@@ -603,8 +604,10 @@ export function renderDocument(options: DocumentOptions): string {
603
604
  for (const dep of chunkImports?.[script] ?? [])
604
605
  preloads.add(dep)
605
606
  }
606
- if (hasIslands) {
607
+ const hasCombinedIslandStyle = headExtra.includes('pru-island,pru-slot,pru-s{display:contents}')
608
+ if (!hasCombinedIslandStyle && (hasIslands || (regionScript !== undefined && runtimeScript !== undefined)))
607
609
  headExtra += `<style>${PRUNELLE_ISLAND_STYLE}</style>`
610
+ if (hasIslands) {
608
611
  for (const chunk of preloadChunks ?? [])
609
612
  preload(chunk, true)
610
613
  }
@@ -614,12 +617,15 @@ export function renderDocument(options: DocumentOptions): string {
614
617
  headExtra += `<link rel="modulepreload" href="${escAttr(href)}">`
615
618
 
616
619
  if (hasSuspense)
617
- headExtra += `<style>${PRUNELLE_SUSPENSE_STYLE}</style><script>${PRUNELLE_STREAM_SCRIPT}</script>`
620
+ headExtra += `${hasCombinedIslandStyle ? '' : `<style>${PRUNELLE_SUSPENSE_STYLE}</style>`}<script>${PRUNELLE_STREAM_SCRIPT}</script>`
618
621
 
619
622
  if (loadsRuntime)
620
623
  headExtra += `<script type="module" src="${escAttr(runtimeScript)}"></script>`
621
- if (regionScript !== undefined)
622
- headExtra += `<script type="module" src="${escAttr(regionScript)}"></script>`
624
+ if (regionScript !== undefined) {
625
+ const buildAttr = buildId === undefined ? '' : ` data-pru-build="${escAttr(buildId)}"`
626
+ const runtimeAttr = !loadsRuntime && runtimeScript !== undefined ? ` data-pru-runtime="${escAttr(runtimeScript)}"` : ''
627
+ headExtra += `<script type="module" src="${escAttr(regionScript)}"${buildAttr}${runtimeAttr}></script>`
628
+ }
623
629
 
624
630
  let attrStr = ''
625
631
  const effectiveLang = htmlAttrs?.lang ?? lang
@@ -631,6 +637,5 @@ export function renderDocument(options: DocumentOptions): string {
631
637
  }
632
638
  }
633
639
 
634
- const scrollTag = keepScrollTag(body) || (hasSuspense ? KEEP_SCROLL_TAG : '')
635
- return `<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>${body}${scrollTag}</body></html>`
640
+ return withKeepScroll(`<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>`, body, '</body></html>', hasSuspense)
636
641
  }
@@ -50,12 +50,14 @@ export function checkNavigationConfig(config: NavigationConfig | undefined): voi
50
50
  }
51
51
 
52
52
  // Never a link that opts out (or sits in a container that does), a download, a nofollow link (a sign-out link often is), prunelle's own routes (an action's URL among them); `href_matches: '/*'` only reaches this origin.
53
- function rulesWhere(): object {
54
- return { and: [{ href_matches: '/*' }, { not: { href_matches: '/_pru/*' } }, { not: { selector_matches: `[${NO_PREFETCH_ATTR}], [${NO_PREFETCH_ATTR}] a, [download], [rel~=nofollow]` } }] }
53
+ function rulesWhere(assetPrefix = '/_pru'): object {
54
+ const trimmed = assetPrefix.replace(/\/+$/, '')
55
+ const internalPattern = trimmed.startsWith('/') && trimmed.length > 1 ? `${trimmed}/*` : '/_pru/*'
56
+ return { and: [{ href_matches: '/*' }, { not: { href_matches: internalPattern } }, { not: { selector_matches: `[${NO_PREFETCH_ATTR}], [${NO_PREFETCH_ATTR}] a, [download], [rel~=nofollow]` } }] }
55
57
  }
56
58
 
57
59
  /** What a page's head holds for the `navigation` settings, made once at start: the rules for each setting left on, as one style and one script the policy hashes. */
58
- export function createNavigation(config: NavigationConfig | undefined): Navigation {
60
+ export function createNavigation(config: NavigationConfig | undefined, assetPrefix?: string): Navigation {
59
61
  checkNavigationConfig(config)
60
62
  const styleHashes: string[] = []
61
63
  const scriptHashes = [cspSha256(KEEP_SCROLL_SCRIPT)]
@@ -67,7 +69,7 @@ export function createNavigation(config: NavigationConfig | undefined): Navigati
67
69
  const prefetch = config?.prefetch === undefined ? 'conservative' : config.prefetch
68
70
  const prerender = config?.prerender === true ? 'moderate' : config?.prerender || undefined
69
71
  if (prefetch !== false || prerender !== undefined) {
70
- const where = rulesWhere()
72
+ const where = rulesWhere(assetPrefix)
71
73
  const rules: Record<string, unknown[]> = {}
72
74
  if (prefetch !== false)
73
75
  rules.prefetch = [{ source: 'document', where, eagerness: prefetch }]
@@ -80,17 +82,162 @@ export function createNavigation(config: NavigationConfig | undefined): Navigati
80
82
  return { html, styleHashes, scriptHashes }
81
83
  }
82
84
 
83
- const DUPLICATE_RE = new RegExp(` ${KEEP_SCROLL_ATTR}="([^"]*)"`, 'g')
85
+ const KEEP_SCROLL_MARK = ` ${KEEP_SCROLL_ATTR}`
86
+ const TAG_NAME_RE = /^([a-z][a-z0-9:-]*)/i
87
+ const ATTR_NAME_RE = /^[a-z0-9_:-]+/i
88
+ const RAW_TEXT_TAGS = new Set(['script', 'style', 'textarea', 'title'])
84
89
 
85
- /** The script a document needs for the panels it marks, or nothing: a page leaving `data-pru-keep-scroll` out costs one `includes`. Two panels of one key throw, as the browser could keep only one offset for them. */
86
- export function keepScrollTag(body: string): string {
87
- if (!body.includes(` ${KEEP_SCROLL_ATTR}`))
88
- return ''
90
+ function findTagEnd(html: string, start: number): number {
91
+ for (let i = start; i < html.length; i++) {
92
+ const ch = html.charCodeAt(i)
93
+ if (ch === 34 || ch === 39) {
94
+ const close = html.indexOf(ch === 34 ? '"' : '\'', i + 1)
95
+ if (close === -1)
96
+ return -1
97
+ i = close
98
+ }
99
+ else if (ch === 62) {
100
+ return i
101
+ }
102
+ }
103
+ return -1
104
+ }
105
+
106
+ function scanTagKeepScroll(html: string, start: number, end: number, seen: Set<string>): boolean {
107
+ let found = false
108
+ let i = start
109
+ while (i < end) {
110
+ while (i < end && (html.charCodeAt(i) <= 32 || html.charCodeAt(i) === 47))
111
+ i++
112
+ if (i >= end)
113
+ break
114
+ const nameMatch = ATTR_NAME_RE.exec(html.slice(i, end))
115
+ if (nameMatch === null) {
116
+ i++
117
+ continue
118
+ }
119
+ const name = nameMatch[0].toLowerCase()
120
+ i += name.length
121
+ while (i < end && html.charCodeAt(i) <= 32)
122
+ i++
123
+ let value = ''
124
+ if (i < end && html.charCodeAt(i) === 61) {
125
+ i++
126
+ while (i < end && html.charCodeAt(i) <= 32)
127
+ i++
128
+ if (i < end) {
129
+ const q = html.charCodeAt(i)
130
+ if (q === 34 || q === 39) {
131
+ const close = html.indexOf(q === 34 ? '"' : '\'', i + 1)
132
+ const valEnd = close === -1 || close > end ? end : close
133
+ value = html.slice(i + 1, valEnd)
134
+ i = valEnd + 1
135
+ }
136
+ else {
137
+ let valEnd = i
138
+ while (valEnd < end && html.charCodeAt(valEnd) > 32)
139
+ valEnd++
140
+ value = html.slice(i, valEnd)
141
+ i = valEnd
142
+ }
143
+ }
144
+ }
145
+ if (name === KEEP_SCROLL_ATTR) {
146
+ found = true
147
+ if (seen.has(value))
148
+ throw new Error(`prunelle: ${KEEP_SCROLL_ATTR}="${value}" is on two elements of one page: give each panel its own key.`)
149
+ seen.add(value)
150
+ }
151
+ }
152
+ return found
153
+ }
154
+
155
+ // Scans only real element open tags outside comments, raw-text elements, and `<code>`/`<pre>` bodies so literal docs/code text never triggers false-positive duplicate errors.
156
+ function scanKeepScrollBody(body: string): boolean {
89
157
  const seen = new Set<string>()
90
- for (const [, key] of body.matchAll(DUPLICATE_RE)) {
91
- if (seen.has(key!))
92
- throw new Error(`prunelle: ${KEEP_SCROLL_ATTR}="${key}" is on two elements of one page: give each panel its own key.`)
93
- seen.add(key!)
158
+ let found = false
159
+ let codeDepth = 0
160
+ let preDepth = 0
161
+ let i = 0
162
+ while (i < body.length) {
163
+ const lt = body.indexOf('<', i)
164
+ if (lt === -1)
165
+ break
166
+ if (body.startsWith('<!--', lt)) {
167
+ const end = body.indexOf('-->', lt + 4)
168
+ if (end === -1)
169
+ break
170
+ i = end + 3
171
+ continue
172
+ }
173
+ const next = body.charCodeAt(lt + 1)
174
+ if (next === 47) {
175
+ const tagMatch = TAG_NAME_RE.exec(body.slice(lt + 2, lt + 32))
176
+ const gt = body.indexOf('>', lt + 2)
177
+ if (tagMatch !== null) {
178
+ const tag = tagMatch[1]!.toLowerCase()
179
+ if (tag === 'code' && codeDepth > 0)
180
+ codeDepth--
181
+ else if (tag === 'pre' && preDepth > 0)
182
+ preDepth--
183
+ }
184
+ if (gt === -1)
185
+ break
186
+ i = gt + 1
187
+ continue
188
+ }
189
+ if (next === 33 || next === 63) {
190
+ const gt = body.indexOf('>', lt + 2)
191
+ if (gt === -1)
192
+ break
193
+ i = gt + 1
194
+ continue
195
+ }
196
+ const tagMatch = TAG_NAME_RE.exec(body.slice(lt + 1, lt + 32))
197
+ if (tagMatch === null) {
198
+ i = lt + 1
199
+ continue
200
+ }
201
+ const tag = tagMatch[1]!.toLowerCase()
202
+ const attrsStart = lt + 1 + tag.length
203
+ const gt = findTagEnd(body, attrsStart)
204
+ if (gt === -1)
205
+ break
206
+ const selfClosing = body.charCodeAt(gt - 1) === 47
207
+ if (codeDepth === 0 && preDepth === 0) {
208
+ const markAt = body.indexOf(KEEP_SCROLL_ATTR, attrsStart)
209
+ if (markAt !== -1 && markAt < gt && scanTagKeepScroll(body, attrsStart, selfClosing ? gt - 1 : gt, seen))
210
+ found = true
211
+ }
212
+ if (!selfClosing && RAW_TEXT_TAGS.has(tag)) {
213
+ const closeRe = new RegExp(`</${tag}\\s*>`, 'gi')
214
+ closeRe.lastIndex = gt + 1
215
+ const closeMatch = closeRe.exec(body)
216
+ if (closeMatch === null)
217
+ break
218
+ i = closeMatch.index + closeMatch[0].length
219
+ continue
220
+ }
221
+ if (!selfClosing) {
222
+ if (tag === 'code')
223
+ codeDepth++
224
+ else if (tag === 'pre')
225
+ preDepth++
226
+ }
227
+ i = gt + 1
94
228
  }
95
- return KEEP_SCROLL_TAG
229
+ return found
230
+ }
231
+
232
+ /** `before + body + after`, with the script keeping the scroll offset of the panels `body` marks ahead of `after`, or always when `always`: a page marking none costs one `indexOf`. Two panels of one key throw, as the browser could keep only one offset for them. */
233
+ export function withKeepScroll(before: string, body: string, after: string, always = false): string {
234
+ // The joined page is searched, not `body`: searching a string built with `+` copies it into one buffer, the joined page would then be copied again, and the Response needs it in one buffer anyway.
235
+ const html = before + body + (always ? KEEP_SCROLL_TAG : '') + after
236
+ const end = before.length + body.length
237
+ const first = html.indexOf(KEEP_SCROLL_MARK, before.length)
238
+ if (first === -1 || first >= end)
239
+ return html
240
+ if (!scanKeepScrollBody(body))
241
+ return html
242
+ return always ? html : before + body + KEEP_SCROLL_TAG + after
96
243
  }
package/src/ssr/region.ts CHANGED
@@ -27,21 +27,27 @@ export function Region(props: RegionProps): Html {
27
27
  throw new Error(`prunelle: two <Region name="${name}"> on one page: give each region its own name.`)
28
28
  ctx.regionNames.add(name)
29
29
  if (ctx.region !== undefined && !isInTarget(ctx)) {
30
- if (ctx.region === name)
30
+ if (ctx.region === name) {
31
+ ctx.regionAttrs = ssrSpread(attributesOf(props))
31
32
  ctx.regionHtml = renderTarget(ctx, () => props.children)
33
+ }
32
34
  else if (ctx.regionAncestors.has(name))
33
35
  ssrChild(props.children)
34
36
  return raw('')
35
37
  }
36
38
  }
37
39
  const inner = ssrChild(props.children)
38
- // Copied key by key: spreading `props` would read `children`, a lazy getter the other regions must never trigger.
40
+ return raw(`<${as} data-pru-region="${escAttr(name)}"${ssrSpread(attributesOf(props))}>${inner}</${as}>`)
41
+ }
42
+
43
+ // Copied key by key: spreading `props` would read `children`, a lazy getter the other regions must never trigger.
44
+ function attributesOf(props: RegionProps): Record<string, unknown> {
39
45
  const attributes: Record<string, unknown> = {}
40
46
  for (const key of Object.keys(props)) {
41
47
  if (key !== 'name' && key !== 'as' && key !== 'children')
42
48
  attributes[key] = props[key]
43
49
  }
44
- return raw(`<${as} data-pru-region="${escAttr(name)}"${ssrSpread(attributes)}>${inner}</${as}>`)
50
+ return attributes
45
51
  }
46
52
 
47
53
  function findPlaceholderRange(html: string, id: number): [number, number] | undefined {
package/src/style.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // The CSS text of a style object, shared by the server and the browser so both render the same declarations.
2
2
 
3
3
  // Properties that take a bare number; any other number gets `px`.
4
- const UNITLESS = new Set([
4
+ const UNITLESS = /* @__PURE__ */ new Set([
5
5
  'animation-iteration-count', 'aspect-ratio', 'border-image-outset', 'border-image-slice', 'border-image-width',
6
6
  'box-flex', 'box-flex-group', 'box-ordinal-group', 'column-count', 'columns', 'fill-opacity', 'flex',
7
7
  'flex-grow', 'flex-negative', 'flex-order', 'flex-positive', 'flex-shrink', 'flood-opacity', 'font-weight',
@@ -82,9 +82,8 @@ function isOneValue(value: string): boolean {
82
82
  return quote === '' && depth === 0
83
83
  }
84
84
 
85
- /** 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. */
86
- export function styleText(style: Record<string, unknown>): string {
87
- let out = ''
85
+ /** Iterates valid CSS property-value pairs of a style object, dropping any declaration that could not stay one. */
86
+ export function eachStyleProp(style: Record<string, unknown>, fn: (name: string, value: string) => void): void {
88
87
  for (const [key, value] of Object.entries(style)) {
89
88
  if (value == null || value === '' || value === false || !PROPERTY_NAME.test(key))
90
89
  continue
@@ -92,7 +91,15 @@ export function styleText(style: Record<string, unknown>): string {
92
91
  continue
93
92
  const name = cssName(key)
94
93
  const px = typeof value === 'number' && !name.startsWith('--') && !UNITLESS.has(name.replace(VENDOR, ''))
95
- out += `${name}:${value}${px ? 'px' : ''};`
94
+ fn(name, `${value}${px ? 'px' : ''}`)
96
95
  }
96
+ }
97
+
98
+ /** 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. */
99
+ export function styleText(style: Record<string, unknown>): string {
100
+ let out = ''
101
+ eachStyleProp(style, (name, value) => {
102
+ out += `${name}:${value};`
103
+ })
97
104
  return out
98
105
  }
@@ -1,8 +1,10 @@
1
1
  // prunelle/test browser tests: the built app served on a loopback port of its own, its pages opened in Chromium with islands hydrated.
2
2
 
3
3
  import type { TestApp, TestAppOptions } from './index'
4
+ import type { MountedApp } from './mount'
4
5
  import { existsSync } from 'node:fs'
5
6
  import { testApp } from './index'
7
+ import { serveMount } from './mount'
6
8
 
7
9
  export interface BrowserTestOptions extends TestAppOptions {
8
10
  /** Chrome or Chromium executable; defaults to `BUN_CHROME_PATH`, Playwright's own, then the system's. */
@@ -36,12 +38,18 @@ export interface BrowserTest {
36
38
  /** `http://127.0.0.1:<port>`, a port the test owns. */
37
39
  readonly origin: string
38
40
  /** Opens `path` and resolves once the page has loaded and the islands that hydrate on load have hydrated; `reducedMotion` opens it for a visitor asking for less motion. */
39
- open(path: string, options?: { reducedMotion?: boolean | undefined }): Promise<BrowserPage>
41
+ open(path: string, options?: OpenOptions): Promise<BrowserPage>
42
+ /** Opens the component `file` exports (its default export, or `export`) alone on an empty page with `props` (JSON values), built and hydrated as the app's pages are; the app is built once per component. */
43
+ mount(file: string, props?: Record<string, unknown>, options?: OpenOptions & { export?: string | undefined }): Promise<BrowserPage>
40
44
  /** Closes the browser and the server. */
41
45
  close(): Promise<void>
42
46
  }
43
47
 
48
+ interface OpenOptions { reducedMotion?: boolean | undefined }
49
+
44
50
  const DEFAULT_TIMEOUT_MS = 10_000
51
+ // A specifier tsc does not resolve, so an app that never calls testBrowser() typechecks without playwright-core (#445).
52
+ const PLAYWRIGHT_SPECIFIER = 'playwright-core'
45
53
 
46
54
  // The few playwright-core types used here, so an app's typecheck never needs playwright-core installed.
47
55
  interface Page {
@@ -69,7 +77,13 @@ interface Browser {
69
77
  }
70
78
 
71
79
  // True once every island that hydrates on load has hydrated; the ones waiting to be seen, idle, touched or matching a media query are left to the test.
72
- const ISLANDS_HYDRATED = `[...document.querySelectorAll('pru-island')].every(e => { const h = e.getAttribute('h'); return h === 'visible' || h === 'idle' || h === 'interaction' || (h !== null && h.startsWith('media(')) || e._d !== undefined })`
80
+ // Passed as a function (not a string) so Playwright evaluates it via CDP rather than `eval()`, which strict CSP + Trusted Types blocks.
81
+ function islandsHydrated(): boolean {
82
+ return [...document.querySelectorAll('pru-island')].every((el) => {
83
+ const h = el.getAttribute('h')
84
+ return h === 'visible' || h === 'idle' || h === 'interaction' || (h !== null && h.startsWith('media(')) || (el as Element & { _d?: unknown })._d !== undefined
85
+ })
86
+ }
73
87
 
74
88
  interface PlaywrightCore {
75
89
  chromium: { launch: (options: { headless: boolean, executablePath: string }) => Promise<Browser>, executablePath: () => string }
@@ -77,7 +91,7 @@ interface PlaywrightCore {
77
91
 
78
92
  async function loadPlaywright(): Promise<PlaywrightCore> {
79
93
  try {
80
- return await import('playwright-core') as unknown as PlaywrightCore
94
+ return await import(PLAYWRIGHT_SPECIFIER) as PlaywrightCore
81
95
  }
82
96
  catch {
83
97
  throw new Error('prunelle: browser tests need playwright-core, and it is not installed: run `bun add -d playwright-core`.')
@@ -164,36 +178,52 @@ export async function testBrowser(options: BrowserTestOptions): Promise<BrowserT
164
178
  await stop()
165
179
  throw error
166
180
  }
167
- return {
168
- app,
169
- origin,
170
- async open(path, openOptions) {
171
- const context = await browser.newContext(openOptions?.reducedMotion === true ? { reducedMotion: 'reduce' } : undefined)
181
+ const mounts = new Map<string, Promise<MountedApp>>()
182
+ const openAt = async (at: string, path: string, openOptions: OpenOptions | undefined): Promise<BrowserPage> => {
183
+ const context = await browser.newContext(openOptions?.reducedMotion === true ? { reducedMotion: 'reduce' } : undefined)
184
+ try {
185
+ const page = await context.newPage()
186
+ const url = new URL(path, at).href
187
+ const wrapped = wrapPage(page, context, timeout)
188
+ // Not `networkidle`: a page that polls or streams never goes idle.
189
+ await page.goto(url, { waitUntil: 'load', timeout })
172
190
  try {
173
- const page = await context.newPage()
174
- const url = new URL(path, origin).href
175
- const wrapped = wrapPage(page, context, timeout)
176
- // Not `networkidle`: a page that polls or streams never goes idle.
177
- await page.goto(url, { waitUntil: 'load', timeout })
178
- try {
179
- await page.waitForFunction(ISLANDS_HYDRATED, undefined, { timeout })
180
- }
181
- catch (error) {
182
- const seen = wrapped.errors.length > 0 ? `; the page reported: ${wrapped.errors.join('; ')}` : ''
183
- throw new Error(`prunelle: the islands of ${url} did not hydrate within ${timeout} ms${seen}.`, { cause: error })
184
- }
185
- return wrapped
191
+ await page.waitForFunction(islandsHydrated, undefined, { timeout })
186
192
  }
187
193
  catch (error) {
188
- await context.close().catch(() => undefined)
189
- throw error
194
+ const seen = wrapped.errors.length > 0 ? `; the page reported: ${wrapped.errors.join('; ')}` : ''
195
+ throw new Error(`prunelle: the islands of ${url} did not hydrate within ${timeout} ms${seen}.`, { cause: error })
196
+ }
197
+ return wrapped
198
+ }
199
+ catch (error) {
200
+ await context.close().catch(() => undefined)
201
+ throw error
202
+ }
203
+ }
204
+ return {
205
+ app,
206
+ origin,
207
+ open: async (path, openOptions) => openAt(origin, path, openOptions),
208
+ async mount(file, props = {}, mountOptions) {
209
+ const exportName = mountOptions?.export ?? 'default'
210
+ const key = `${file}#${exportName}`
211
+ let mounted = mounts.get(key)
212
+ if (mounted === undefined) {
213
+ mounted = serveMount(options, file, exportName)
214
+ mounts.set(key, mounted)
215
+ // A mount that failed to build is tried again by the next call rather than failing it too.
216
+ mounted.catch(() => mounts.delete(key))
190
217
  }
218
+ return openAt((await mounted).origin, `/?props=${encodeURIComponent(JSON.stringify(props))}`, mountOptions)
191
219
  },
192
220
  async close() {
193
221
  try {
194
222
  await browser.close()
195
223
  }
196
224
  finally {
225
+ const built = await Promise.allSettled(mounts.values())
226
+ await Promise.all(built.map(async result => result.status === 'fulfilled' ? result.value.close() : undefined))
197
227
  await stop()
198
228
  }
199
229
  },