prunelle 0.9.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 (96) hide show
  1. package/llms.txt +18 -18
  2. package/package.json +2 -2
  3. package/src/a11y/declaration.ts +4 -7
  4. package/src/build/bundle.ts +6 -2
  5. package/src/build/index.ts +3 -1
  6. package/src/build/island-promote.ts +42 -2
  7. package/src/build/islands.ts +59 -8
  8. package/src/build/manifest.ts +98 -0
  9. package/src/build/plugin-host.ts +11 -1
  10. package/src/build/prerender.ts +6 -1
  11. package/src/build/reach.ts +4 -3
  12. package/src/build/resolve.ts +5 -1
  13. package/src/build/routes.ts +18 -0
  14. package/src/cli/check-forms.ts +8 -0
  15. package/src/cli/check-links.ts +14 -5
  16. package/src/cli/check.ts +12 -6
  17. package/src/cli/commands.ts +5 -3
  18. package/src/cli/form-opaque-children.ts +40 -0
  19. package/src/compiler/analyze.ts +20 -14
  20. package/src/compiler/cacheability-private.ts +13 -3
  21. package/src/compiler/compliance-contrast.ts +48 -10
  22. package/src/compiler/compliance-rules.ts +72 -0
  23. package/src/compiler/compliance.ts +6 -66
  24. package/src/compiler/dom-attrs.ts +178 -22
  25. package/src/compiler/dom.ts +31 -44
  26. package/src/compiler/emit.ts +17 -6
  27. package/src/compiler/expr-context.ts +260 -207
  28. package/src/compiler/props-body.ts +263 -21
  29. package/src/compiler/props.ts +155 -5
  30. package/src/compiler/signal-reads.ts +142 -29
  31. package/src/compiler/spread-handlers.ts +25 -13
  32. package/src/compiler/ssr-emit.ts +3 -3
  33. package/src/compiler/ssr-helpers.ts +0 -5
  34. package/src/compiler/ssr.ts +4 -2
  35. package/src/dev/host-check.ts +2 -1
  36. package/src/dev/reload.ts +4 -1
  37. package/src/dom/attrs.ts +93 -25
  38. package/src/dom/extras.ts +89 -49
  39. package/src/dom/field-marks.ts +9 -1
  40. package/src/dom/index.ts +19 -13
  41. package/src/dom/loop.ts +259 -188
  42. package/src/dom/prefetch.ts +4 -1
  43. package/src/dom/regions.ts +25 -8
  44. package/src/dom/swap.ts +11 -10
  45. package/src/dom/trusted.ts +4 -4
  46. package/src/eco/declaration.ts +5 -1
  47. package/src/eco/index.ts +3 -0
  48. package/src/index.ts +3 -2
  49. package/src/plugins/config.ts +1 -1
  50. package/src/plugins/public.ts +4 -0
  51. package/src/plugins/types.ts +8 -1
  52. package/src/reactivity/graph.ts +244 -41
  53. package/src/reactivity/hmr.ts +14 -3
  54. package/src/reactivity/index.ts +219 -235
  55. package/src/reactivity/resource.ts +17 -3
  56. package/src/reactivity/seed.ts +118 -16
  57. package/src/reactivity/selector.ts +85 -47
  58. package/src/reactivity/server-seed.ts +31 -23
  59. package/src/reactivity/store.ts +316 -136
  60. package/src/server/action-protect.ts +3 -0
  61. package/src/server/action-registry.ts +5 -1
  62. package/src/server/cache-invalidation.ts +4 -3
  63. package/src/server/compress.ts +52 -17
  64. package/src/server/consent.ts +5 -3
  65. package/src/server/cookies.ts +27 -8
  66. package/src/server/cors.ts +98 -0
  67. package/src/server/csp-report.ts +8 -4
  68. package/src/server/health.ts +9 -0
  69. package/src/server/http.ts +3 -1
  70. package/src/server/index.ts +25 -13
  71. package/src/server/loader.ts +1 -0
  72. package/src/server/plugin-host.ts +41 -9
  73. package/src/server/plugin-route-shadow.ts +24 -0
  74. package/src/server/rate-limit.ts +13 -3
  75. package/src/server/region.ts +19 -2
  76. package/src/server/request-handler.ts +58 -22
  77. package/src/server/request-log.ts +1 -1
  78. package/src/server/route-cache.ts +14 -2
  79. package/src/server/route-table.ts +21 -11
  80. package/src/server/router.ts +2 -1
  81. package/src/server/routing.ts +100 -42
  82. package/src/server/sanitize-html.ts +3 -1
  83. package/src/server/serve-handlers.ts +10 -4
  84. package/src/server/served-file.ts +19 -14
  85. package/src/server/shared-store.ts +10 -1
  86. package/src/server/static-dir.ts +21 -3
  87. package/src/server/webhook.ts +6 -4
  88. package/src/ssr/context.ts +149 -51
  89. package/src/ssr/index.ts +41 -46
  90. package/src/ssr/region.ts +9 -3
  91. package/src/style.ts +12 -5
  92. package/src/test/browser.ts +3 -1
  93. package/src/test/build-reuse.ts +22 -7
  94. package/src/test/index.ts +7 -3
  95. package/src/ts-plugin/diagnostics.ts +56 -18
  96. package/ts-plugin.cjs +465 -131
@@ -32,13 +32,15 @@ export interface PendingChunk {
32
32
 
33
33
  export interface RenderContext {
34
34
  headParts: string[]
35
- headKeys: Set<string>
35
+ headKeys: Set<string> | undefined
36
36
  title: string | undefined
37
37
  pending: PendingChunk[]
38
38
  nextId: number
39
39
  islandDepth: number
40
40
  islandSeq: number
41
41
  idPrefix: string
42
+ /** Starts every `useId` and island prefix of a region answer, so its ids differ from the page's and from the other answers' already in the document. */
43
+ idScope: string
42
44
  idSeq: number
43
45
  contexts: Map<symbol, unknown>
44
46
  /** While an island renders, the contexts provided outside it, which the browser never sees. */
@@ -49,6 +51,8 @@ export interface RenderContext {
49
51
  seeds: RequestSeeds | undefined
50
52
  /** Maps island chunk URL -> eager (true if hydrate is undefined/'load'). */
51
53
  renderedIslands: Map<string, boolean>
54
+ /** True on fast-static routes whose island preload chunks were already precomputed into the document shell. */
55
+ skipIslandMap: boolean
52
56
  hasIslands: boolean
53
57
  /** True once an island's props hold a tagged value (a Date, Map, Set…), whose page preloads the revivers. */
54
58
  revives: boolean
@@ -57,6 +61,8 @@ export interface RenderContext {
57
61
  region: string | undefined
58
62
  /** The requested region's HTML, once the page rendered it. */
59
63
  regionHtml: string | undefined
64
+ /** The requested region's own attributes as its tag renders them (` class="a"`), sent so a swap keeps the element as the new page has it. */
65
+ regionAttrs: string
60
66
  regionNames: Set<string>
61
67
  /** The regions around the requested one: rendered through, their own HTML dropped. */
62
68
  regionAncestors: ReadonlySet<string>
@@ -123,6 +129,93 @@ function activeScope(ctx: RenderContext): RenderScope {
123
129
  }
124
130
  }
125
131
 
132
+ const EMPTY_SET: ReadonlySet<string> = new Set()
133
+ const EMPTY_STRINGS: string[] = Object.freeze([]) as unknown as string[]
134
+ const EMPTY_PENDING: PendingChunk[] = Object.freeze([]) as unknown as PendingChunk[]
135
+ const EMPTY_CONTEXTS: Map<symbol, unknown> = new Map()
136
+ const EMPTY_ISLANDS: Map<string, boolean> = new Map()
137
+ const EMPTY_HTML_ATTRS: Record<string, string> = Object.freeze({})
138
+
139
+ class RenderContextImpl implements RenderContext {
140
+ headParts: string[] = EMPTY_STRINGS
141
+ headKeys: Set<string> | undefined = undefined
142
+ title: string | undefined = undefined
143
+ pending: PendingChunk[] = EMPTY_PENDING
144
+ nextId = 0
145
+ islandDepth = 0
146
+ islandSeq = 0
147
+ idPrefix: string
148
+ idScope: string
149
+ idSeq = 0
150
+ contexts: Map<symbol, unknown> = EMPTY_CONTEXTS
151
+ outerContexts: Map<symbol, unknown> | undefined = undefined
152
+ island: string | undefined = undefined
153
+ seeds: RequestSeeds | undefined = undefined
154
+ renderedIslands: Map<string, boolean> = EMPTY_ISLANDS
155
+ skipIslandMap: boolean
156
+ hasIslands = false
157
+ revives = false
158
+ htmlAttrs: Record<string, string> = EMPTY_HTML_ATTRS
159
+ region: string | undefined
160
+ regionHtml: string | undefined = undefined
161
+ regionAttrs = ''
162
+ #regionNames: Set<string> | undefined = undefined
163
+ regionAncestors: ReadonlySet<string>
164
+ inTarget = false
165
+ inlineStyles: string[] | undefined = undefined
166
+ headersFlushed = false
167
+ headFlushed = false
168
+ warnedStreamStyle = false
169
+ warnedStreamHead = false
170
+ aborted = false
171
+ consent: RequestConsent | undefined
172
+ onCaught: ((error: unknown) => void) | undefined
173
+ formActions: Map<string, unknown> | undefined = undefined
174
+
175
+ constructor(
176
+ region: string | undefined,
177
+ ancestors: ReadonlySet<string>,
178
+ consent: RequestConsent | undefined,
179
+ onCaught: ((error: unknown) => void) | undefined,
180
+ skipIslandMap: boolean,
181
+ ) {
182
+ // A region answer is swapped or appended into a document that already holds ids from its own render, so it gets a scope of its own.
183
+ const idScope = region === undefined ? '' : `r${Math.random().toString(36).slice(2, 8)}-`
184
+ this.idPrefix = idScope
185
+ this.idScope = idScope
186
+ this.region = region
187
+ this.regionAncestors = ancestors
188
+ this.consent = consent
189
+ this.onCaught = onCaught
190
+ this.skipIslandMap = skipIslandMap
191
+ }
192
+
193
+ get regionNames(): Set<string> {
194
+ return this.#regionNames ??= new Set()
195
+ }
196
+
197
+ set regionNames(value: Set<string>) {
198
+ this.#regionNames = value
199
+ }
200
+
201
+ hasRenderedRegions(): boolean {
202
+ return this.#regionNames !== undefined && this.#regionNames.size > 0
203
+ }
204
+ }
205
+
206
+ /** True when `<Region>` actually rendered during this request, without materializing an empty `Set`. */
207
+ export function hasRenderedRegions(ctx: RenderContext): boolean {
208
+ const probe = ctx as RenderContext & { hasRenderedRegions?: () => boolean }
209
+ return typeof probe.hasRenderedRegions === 'function' ? probe.hasRenderedRegions() : ctx.regionNames.size > 0
210
+ }
211
+
212
+ /** Returns a mutable per-request island map, replacing the shared empty sentinel on first write. */
213
+ export function ensureRenderedIslands(ctx: RenderContext): Map<string, boolean> {
214
+ if (ctx.renderedIslands.size === 0)
215
+ ctx.renderedIslands = new Map()
216
+ return ctx.renderedIslands
217
+ }
218
+
126
219
  export function lookupFormAction(url: string): unknown {
127
220
  const ctx = renderStorage.getStore()
128
221
  if (ctx !== undefined)
@@ -132,7 +225,10 @@ export function lookupFormAction(url: string): unknown {
132
225
 
133
226
  export function currentFormFields(): ReadonlyMap<string, FieldConstraint> | undefined {
134
227
  const ctx = renderStorage.getStore()
135
- return ctx !== undefined ? activeScope(ctx).formFields : fallbackFormFields
228
+ if (ctx === undefined)
229
+ return fallbackFormFields
230
+ const scope = scopeStorage.getStore()
231
+ return scope !== undefined && scope.owner === ctx ? scope.formFields : undefined
136
232
  }
137
233
 
138
234
  export function runWithFormFields<T>(fields: ReadonlyMap<string, FieldConstraint>, fn: () => T): T {
@@ -155,7 +251,8 @@ export function runWithFormFields<T>(fields: ReadonlyMap<string, FieldConstraint
155
251
  }
156
252
 
157
253
  export function isInTarget(ctx: RenderContext): boolean {
158
- return activeScope(ctx).inTarget
254
+ const scope = scopeStorage.getStore()
255
+ return scope !== undefined && scope.owner === ctx ? scope.inTarget : ctx.inTarget
159
256
  }
160
257
 
161
258
  export function runInTarget<T>(ctx: RenderContext, fn: () => T): T {
@@ -167,11 +264,14 @@ registerServerContextBridge({
167
264
  const ctx = renderStorage.getStore()
168
265
  if (ctx === undefined)
169
266
  return undefined
170
- const scope = activeScope(ctx)
171
- if (scope.contexts.has(key))
172
- return { found: true, value: scope.contexts.get(key) }
173
- if (scope.outerContexts?.has(key) === true)
174
- throw new Error(`prunelle: <${scope.island}> reads a context provided outside the island, which the browser never sees; pass its value as a prop.`)
267
+ const scope = scopeStorage.getStore()
268
+ const own = scope !== undefined && scope.owner === ctx
269
+ const contexts = own ? scope.contexts : ctx.contexts
270
+ if (contexts.has(key))
271
+ return { found: true, value: contexts.get(key) }
272
+ const outer = own ? scope.outerContexts : ctx.outerContexts
273
+ if (outer?.has(key) === true)
274
+ throw new Error(`prunelle: <${own ? scope.island : ctx.island}> reads a context provided outside the island, which the browser never sees; pass its value as a prop.`)
175
275
  return undefined
176
276
  },
177
277
  runWithContext<T>(key: symbol, value: unknown, fn: () => T): T {
@@ -220,43 +320,12 @@ registerServerContextBridge({
220
320
 
221
321
  export function createRenderContext(
222
322
  region?: string,
223
- ancestors: ReadonlySet<string> = new Set(),
323
+ ancestors: ReadonlySet<string> = EMPTY_SET,
224
324
  consent?: RequestConsent,
225
325
  onCaught?: (error: unknown) => void,
326
+ skipIslandMap = false,
226
327
  ): RenderContext {
227
- return {
228
- headParts: [],
229
- headKeys: new Set(),
230
- title: undefined,
231
- pending: [],
232
- nextId: 0,
233
- islandDepth: 0,
234
- islandSeq: 0,
235
- idPrefix: '',
236
- idSeq: 0,
237
- contexts: new Map(),
238
- outerContexts: undefined,
239
- island: undefined,
240
- seeds: undefined,
241
- renderedIslands: new Map(),
242
- hasIslands: false,
243
- revives: false,
244
- htmlAttrs: {},
245
- region,
246
- regionHtml: undefined,
247
- regionNames: new Set(),
248
- regionAncestors: ancestors,
249
- inTarget: false,
250
- inlineStyles: undefined,
251
- headersFlushed: false,
252
- headFlushed: false,
253
- warnedStreamStyle: false,
254
- warnedStreamHead: false,
255
- aborted: false,
256
- consent,
257
- onCaught,
258
- formActions: undefined,
259
- }
328
+ return new RenderContextImpl(region, ancestors, consent, onCaught, skipIslandMap)
260
329
  }
261
330
 
262
331
  /** Records a compiler-emitted inline `<style>` block's CSS in the active RenderContext for CSP hashing. */
@@ -281,10 +350,30 @@ export function ssrStyleBlock(css: string): string {
281
350
  return css
282
351
  }
283
352
 
353
+ /** True when an island needs a fresh `scopeStorage` entry to isolate outer `Context.Provider` values. */
354
+ export function needsIslandScope(ctx: RenderContext): boolean {
355
+ const scope = scopeStorage.getStore()
356
+ const cur = scope !== undefined && scope.owner === ctx ? scope : undefined
357
+ const contexts = cur !== undefined ? cur.contexts : ctx.contexts
358
+ return contexts.size > 0 || (cur !== undefined ? cur.outerContexts : ctx.outerContexts) !== undefined
359
+ }
360
+
284
361
  // An island sees only the contexts provided inside it, as in the browser.
285
362
  export function renderIsland(ctx: RenderContext, name: string, render: () => string): string {
286
- const cur = activeScope(ctx)
287
- return scopeStorage.run({ ...cur, contexts: new Map(), outerContexts: cur.contexts, island: name }, render)
363
+ const scope = scopeStorage.getStore()
364
+ const cur = scope !== undefined && scope.owner === ctx ? scope : undefined
365
+ const contexts = cur !== undefined ? cur.contexts : ctx.contexts
366
+ if (contexts.size === 0 && (cur !== undefined ? cur.outerContexts : ctx.outerContexts) === undefined)
367
+ return render()
368
+ const base = cur ?? {
369
+ owner: ctx,
370
+ contexts,
371
+ outerContexts: ctx.outerContexts,
372
+ island: ctx.island,
373
+ inTarget: ctx.inTarget,
374
+ formFields: undefined,
375
+ }
376
+ return scopeStorage.run({ ...base, contexts: EMPTY_CONTEXTS, outerContexts: contexts, island: name }, render)
288
377
  }
289
378
 
290
379
 
@@ -359,7 +448,7 @@ export function Catch(props: CatchProps): Html | Promise<Html> {
359
448
  try {
360
449
  const children = props.children as PrunelleChild | Promise<PrunelleChild>
361
450
  if (children instanceof Promise)
362
- return children.then(resolved => raw(ssrChild(resolved)), fail)
451
+ return children.then(resolved => raw(ssrChild(resolved))).catch(fail)
363
452
  return raw(ssrChild(children))
364
453
  }
365
454
  catch (error) {
@@ -412,7 +501,8 @@ export function Head(props: { children?: PrunelleChild }): Html {
412
501
  if (ctx === undefined)
413
502
  return raw('')
414
503
 
415
- if (ctx.headersFlushed || ctx.headFlushed || activeScope(ctx).inSuspense === true) {
504
+ const scope = scopeStorage.getStore()
505
+ if (ctx.headersFlushed || ctx.headFlushed || (scope !== undefined && scope.owner === ctx && scope.inSuspense === true)) {
416
506
  if (!ctx.warnedStreamHead) {
417
507
  ctx.warnedStreamHead = true
418
508
  const component = callerComponentName()
@@ -432,9 +522,13 @@ export function Head(props: { children?: PrunelleChild }): Html {
432
522
  html = html.replace(TITLE_RE, '')
433
523
  }
434
524
  if (html !== '')
435
- html = dedupeHeadTags(html, ctx.headKeys)
436
- if (html !== '')
437
- ctx.headParts.push(html)
525
+ html = dedupeHeadTags(html, ctx.headKeys ??= new Set())
526
+ if (html !== '') {
527
+ if (ctx.headParts.length === 0)
528
+ ctx.headParts = [html]
529
+ else
530
+ ctx.headParts.push(html)
531
+ }
438
532
 
439
533
  return raw('')
440
534
  }
@@ -466,12 +560,16 @@ export function Suspense(props: { fallback?: PrunelleChild, error?: PrunelleChil
466
560
  }
467
561
  let discarded = false
468
562
  const isAborted = (): boolean => ctx.aborted || discarded
469
- ctx.pending.push({
563
+ const entry: PendingChunk = {
470
564
  id,
471
565
  settled: settle(ctx, scope, child, renderError, isAborted),
472
566
  renderError,
473
567
  discard: () => { discarded = true },
474
- })
568
+ }
569
+ if (ctx.pending.length === 0)
570
+ ctx.pending = [entry]
571
+ else
572
+ ctx.pending.push(entry)
475
573
 
476
574
  const fallbackHtml = ssrChild(props.fallback)
477
575
  return raw(`<pru-s id="k-s-${id}">${fallbackHtml}</pru-s>`)
package/src/ssr/index.ts CHANGED
@@ -9,7 +9,8 @@ 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'
12
+ import type { RenderContext } from './context'
13
+ import { currentFormFields, currentRenderContext, ensureRenderedIslands, lookupFormAction, needsIslandScope, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
13
14
  import { withKeepScroll } from './navigation'
14
15
  export { ssrStyleBlock } from './context'
15
16
 
@@ -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.
@@ -309,7 +299,7 @@ export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render
309
299
 
310
300
  export function ssrChild(value: PrunelleChild): string {
311
301
  if (typeof value === 'string')
312
- return esc(value)
302
+ return escText(value)
313
303
  if (typeof value === 'number')
314
304
  return String(value)
315
305
  if (value == null || typeof value === 'boolean')
@@ -323,7 +313,7 @@ export function ssrChild(value: PrunelleChild): string {
323
313
  return out
324
314
  }
325
315
  assertRenderable(value, 'text')
326
- return esc(String(value))
316
+ return escText(String(value))
327
317
  }
328
318
 
329
319
  function serializeIslandProps(props: Record<string, unknown>): string {
@@ -372,31 +362,32 @@ function serializeIslandProps(props: Record<string, unknown>): string {
372
362
 
373
363
  let fallbackIslandDepth = 0
374
364
 
375
- function getIslandDepth(): number {
376
- const ctx = currentRenderContext()
377
- return ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth
378
- }
379
-
380
- export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy): void {
381
- const ctx = currentRenderContext()
382
- if (ctx === undefined)
383
- return
365
+ function recordIslandOn(ctx: RenderContext, chunk: string, hydrate?: HydrateStrategy): void {
384
366
  ctx.hasIslands = true
367
+ if (ctx.skipIslandMap)
368
+ return
369
+ const map = ensureRenderedIslands(ctx)
385
370
  const eager = hydrate === undefined || hydrate === 'load'
386
371
  if (eager)
387
- ctx.renderedIslands.set(chunk, true)
388
- else if (!ctx.renderedIslands.has(chunk))
389
- ctx.renderedIslands.set(chunk, false)
372
+ map.set(chunk, true)
373
+ else if (!map.has(chunk))
374
+ map.set(chunk, false)
390
375
  }
391
376
 
392
- export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy, name = 'island'): string {
377
+ export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy): void {
393
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 {
394
384
  if (ctx !== undefined) {
395
385
  if (chunk !== undefined && ctx.islandDepth === 0)
396
- recordRenderedIsland(chunk, hydrate)
386
+ recordIslandOn(ctx, chunk, hydrate)
397
387
  ctx.islandDepth++
398
388
  try {
399
- return renderOnServer(ctx.islandDepth === 1 ? () => renderIsland(ctx, name, render) : render, ctx.seeds ??= { ops: [], out: undefined })
389
+ const fn = ctx.islandDepth === 1 && needsIslandScope(ctx) ? () => renderIsland(ctx, name, render) : render
390
+ return renderOnServer(fn, ctx.seeds, ctx)
400
391
  }
401
392
  finally {
402
393
  ctx.islandDepth--
@@ -411,6 +402,10 @@ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: Hydr
411
402
  }
412
403
  }
413
404
 
405
+ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy, name = 'island'): string {
406
+ return runInIsland(currentRenderContext(), render, chunk, hydrate, name)
407
+ }
408
+
414
409
 
415
410
  /** Lazily evaluates non-async component children on first read inside the component's dynamic context, memoizing the result. */
416
411
  export function ssrChildProp<P extends Record<string, unknown>>(props: P, fn: () => Html): P {
@@ -469,11 +464,11 @@ function renderIslandBody(
469
464
  if (ctx !== undefined) {
470
465
  const prevPrefix = ctx.idPrefix
471
466
  const prevSeq = ctx.idSeq
472
- const islandPrefix = `i${ctx.islandSeq++}-`
467
+ const islandPrefix = `i${ctx.idScope}${ctx.islandSeq++}-`
473
468
  ctx.idPrefix = islandPrefix
474
469
  ctx.idSeq = 0
475
470
  try {
476
- inner = ssrInIsland(render, undefined, undefined, name)
471
+ inner = runInIsland(ctx, render, undefined, undefined, name)
477
472
  if (ctx.idSeq > 0)
478
473
  idAttr = ` i="${islandPrefix}"`
479
474
  // The module state this island wrote, for the browser to start from as the server rendered it.
@@ -486,7 +481,7 @@ function renderIslandBody(
486
481
  }
487
482
  }
488
483
  else {
489
- inner = ssrInIsland(render, undefined, undefined, name)
484
+ inner = runInIsland(undefined, render, undefined, undefined, name)
490
485
  }
491
486
  }
492
487
 
@@ -504,12 +499,12 @@ export function ssrIslandStatic(
504
499
  name?: string,
505
500
  slot?: TrackedSlot,
506
501
  ): string {
507
- if (getIslandDepth() > 0)
502
+ const ctx = currentRenderContext()
503
+ if ((ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth) > 0)
508
504
  return render !== undefined ? render() : ''
509
505
 
510
- const ctx = currentRenderContext()
511
506
  if (ctx !== undefined)
512
- recordRenderedIsland(chunk, hydrate)
507
+ recordIslandOn(ctx, chunk, hydrate)
513
508
 
514
509
  const { idAttr, inner, hiddenSlot } = renderIslandBody(ctx, render, hydrate, name, slot)
515
510
  const tag = idAttr === '' ? openTag : `${openTag.slice(0, -1)}${idAttr}>`
@@ -526,12 +521,12 @@ export function ssrIsland(
526
521
  name?: string,
527
522
  slot?: TrackedSlot,
528
523
  ): string {
529
- if (getIslandDepth() > 0)
524
+ const ctx = currentRenderContext()
525
+ if ((ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth) > 0)
530
526
  return render()
531
527
 
532
- const ctx = currentRenderContext()
533
528
  if (ctx !== undefined)
534
- recordRenderedIsland(chunk, hydrate)
529
+ recordIslandOn(ctx, chunk, hydrate)
535
530
 
536
531
  let propsAttr = ''
537
532
  let propsScript = ''
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
  }
@@ -48,6 +48,8 @@ export interface BrowserTest {
48
48
  interface OpenOptions { reducedMotion?: boolean | undefined }
49
49
 
50
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'
51
53
 
52
54
  // The few playwright-core types used here, so an app's typecheck never needs playwright-core installed.
53
55
  interface Page {
@@ -89,7 +91,7 @@ interface PlaywrightCore {
89
91
 
90
92
  async function loadPlaywright(): Promise<PlaywrightCore> {
91
93
  try {
92
- return await import('playwright-core') as unknown as PlaywrightCore
94
+ return await import(PLAYWRIGHT_SPECIFIER) as PlaywrightCore
93
95
  }
94
96
  catch {
95
97
  throw new Error('prunelle: browser tests need playwright-core, and it is not installed: run `bun add -d playwright-core`.')
@@ -1,8 +1,10 @@
1
1
  // testApp() builds an app once per test run: `bun test` runs every file in one process, so a later call with the same build options, environment and files reuses the build the first one made.
2
2
 
3
- import type { BuildManifest } from '../build/index'
3
+ import type { BuildCache, BuildManifest } from '../build/index'
4
+ import type { FileStamp } from '../build/graph'
4
5
  import { readdirSync, readFileSync, statSync } from 'node:fs'
5
- import { join } from 'node:path'
6
+ import { isAbsolute, join, relative, sep } from 'node:path'
7
+ import { stampsMatch } from '../build/graph'
6
8
 
7
9
  /** The build options that change what a build writes; a call passing `plugins` or an analysis callback always builds. */
8
10
  export interface ReusableBuildOptions {
@@ -30,17 +32,30 @@ export interface TestBuild {
30
32
  manifest: BuildManifest
31
33
  }
32
34
 
33
- const lastBuilds = new Map<string, { key: string, build: TestBuild }>()
35
+ const lastBuilds = new Map<string, { key: string, build: TestBuild, outside: ReadonlyMap<string, FileStamp> }>()
34
36
 
35
37
  /** This process's last build of `root` when nothing it depends on has changed since. */
36
38
  export function reusableBuild(root: string, options: ReusableBuildOptions): TestBuild | undefined {
37
39
  const last = lastBuilds.get(root)
38
- return last !== undefined && last.key === buildKey(root, options) ? last.build : undefined
40
+ return last !== undefined && last.key === buildKey(root, options) && stampsMatch(last.outside) ? last.build : undefined
39
41
  }
40
42
 
41
- /** Remembers a build of `root`, keyed on the files as the build left them: it writes route types into `src/`. */
42
- export function rememberBuild(root: string, options: ReusableBuildOptions, build: TestBuild): void {
43
- lastBuilds.set(root, { key: buildKey(root, options), build })
43
+ /** Remembers a build of `root`, keyed on the files as the build left them (it writes route types into `src/`) and on the files it read outside the root, which `cache` recorded. */
44
+ export function rememberBuild(root: string, options: ReusableBuildOptions, build: TestBuild, cache: BuildCache): void {
45
+ const outside = new Map<string, FileStamp>()
46
+ for (const stamps of [cache.lastClient?.inputStamps, cache.lastServer?.inputStamps]) {
47
+ for (const [file, stamp] of stamps ?? []) {
48
+ if (!fingerprinted(root, file))
49
+ outside.set(file, stamp)
50
+ }
51
+ }
52
+ lastBuilds.set(root, { key: buildKey(root, options), build, outside })
53
+ }
54
+
55
+ /** Whether `fingerprint()` already reads `file`: under the root and out of the folders it skips. */
56
+ function fingerprinted(root: string, file: string): boolean {
57
+ const rel = relative(root, file)
58
+ return !rel.startsWith('..') && !isAbsolute(rel) && !rel.split(sep).slice(0, -1).some(dir => SKIPPED_DIRS.has(dir))
44
59
  }
45
60
 
46
61
  function buildKey(root: string, options: ReusableBuildOptions): string {
package/src/test/index.ts CHANGED
@@ -4,7 +4,7 @@ import type { BuildManifest, BuildOptions } from '../build/index'
4
4
  import type { PrunelleApp, ServerAction, ServerRuntimeConfig } from '../server/index'
5
5
  import { existsSync, readdirSync, rmSync } from 'node:fs'
6
6
  import { dirname, join, resolve } from 'node:path'
7
- import { build } from '../build/index'
7
+ import { build, createBuildCache } from '../build/index'
8
8
  import { relPosix } from '../build/files'
9
9
  import { processSuffix, removeDeadProcessDirs } from '../build/output'
10
10
  import { ensureCacheGitignore } from '../build/precompress'
@@ -130,6 +130,8 @@ async function buildForTest(root: string, options: TestAppOptions): Promise<Test
130
130
  return reused
131
131
  }
132
132
  const outDir = options.outDir ?? ownOutDir(root)
133
+ // The build cache records every file the bundles read, which a reused build is checked against.
134
+ const cache = options.cache ?? createBuildCache()
133
135
  const manifest = await build({
134
136
  root: options.root,
135
137
  routesDir: options.routesDir,
@@ -139,7 +141,7 @@ async function buildForTest(root: string, options: TestAppOptions): Promise<Test
139
141
  assetPrefix: options.assetPrefix,
140
142
  site: options.site,
141
143
  plugins: options.plugins,
142
- cache: options.cache,
144
+ cache,
143
145
  analyze: options.analyze,
144
146
  analyzeJson: options.analyzeJson,
145
147
  onAnalyze: options.onAnalyze,
@@ -148,10 +150,11 @@ async function buildForTest(root: string, options: TestAppOptions): Promise<Test
148
150
  autoPrerender: options.autoPrerender,
149
151
  copyPublic: options.copyPublic,
150
152
  dev: options.dev,
153
+ splitServer: false,
151
154
  nodeEnv: options.nodeEnv,
152
155
  })
153
156
  if (reusable)
154
- rememberBuild(root, inputs, { outDir, manifest })
157
+ rememberBuild(root, inputs, { outDir, manifest }, cache)
155
158
  return { outDir, manifest }
156
159
  }
157
160
 
@@ -173,6 +176,7 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
173
176
  },
174
177
  }).catch((error: unknown) => {
175
178
  outside.release()
179
+ time.restore()
176
180
  throw error
177
181
  })
178
182