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
@@ -17,10 +17,10 @@ import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } fro
17
17
  import type { ParamMatcherMap } from './param-matchers'
18
18
  import type { RequestPath } from './request-path'
19
19
  import type { TrustProxy } from './security'
20
- import { createRenderContext, runWithRenderContext } from '../ssr/context'
20
+ import { createRenderContext, hasRenderedRegions, runWithRenderContext } from '../ssr/context'
21
21
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
22
22
  import { withKeepScroll } from '../ssr/navigation'
23
- import { compressedHtmlResponse, maybeCompressResponse } from './compress'
23
+ import { compressedHtmlResponse, maybeCompressResponse, withVaryAcceptEncoding } from './compress'
24
24
  import { headTagStyleHashes, mergeStyleHashes } from './document'
25
25
  import { createTiming, endTimer, finishRenderTiming, formatServerTiming, resolveFallbackRequestId, startTimer } from './health'
26
26
  import { acceptsHtml, getDeniedInfo, isNotFound, makeRequestContext } from './http'
@@ -247,6 +247,52 @@ function buildFastDocShell(doc: DocumentOptions, eagerChunks: string[], reviveSc
247
247
  return { docPrefix, revivingPrefix, docSuffix }
248
248
  }
249
249
 
250
+ interface FastHtmlResponderConfig {
251
+ docPrefix: string
252
+ revivingPrefix: string
253
+ docSuffix: string
254
+ headStyleHashes: readonly string[]
255
+ needsIslandStyle: boolean
256
+ baseVaryHeaders: Record<string, string>
257
+ varyPremerged: boolean
258
+ skipKeepScroll: boolean
259
+ hasLoad: boolean
260
+ htmlHeaders: HtmlHeaders
261
+ compressCache: CompressionCache | undefined
262
+ finish: FastStaticPageOptions['finish']
263
+ withHsts: FastStaticPageOptions['withHsts']
264
+ }
265
+
266
+ function createFastHtmlResponder(cfg: FastHtmlResponderConfig) {
267
+ const { docPrefix, revivingPrefix, docSuffix, headStyleHashes, needsIslandStyle, baseVaryHeaders, varyPremerged, skipKeepScroll, hasLoad, htmlHeaders, compressCache, finish, withHsts } = cfg
268
+ return (body: string, request: Request, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, timing?: PhaseTiming): Response => {
269
+ const prefix = rctx.revives ? revivingPrefix : docPrefix
270
+ const html = skipKeepScroll ? prefix + body + docSuffix : withKeepScroll(prefix, body, docSuffix)
271
+ const hasInlineStyles = rctx.inlineStyles !== undefined
272
+ const hasRegions = hasRenderedRegions(rctx)
273
+ const st = timing !== undefined ? finishRenderTiming(timing) : undefined
274
+ let res: Response
275
+ if (!hasInlineStyles && !hasRegions) {
276
+ res = compressedHtmlResponse(html, 200, baseVaryHeaders, request, compressCache, !hasLoad, {
277
+ varyPremerged,
278
+ skipMarkHandled: true,
279
+ requestId: reqId,
280
+ serverTiming: st,
281
+ })
282
+ }
283
+ else {
284
+ const styleHashes = hasInlineStyles ? mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles)) : headStyleHashes
285
+ const headers = hasRegions ? withRegionVary(htmlHeaders(needsIslandStyle, false, true, styleHashes), true) : htmlHeaders(needsIslandStyle, false, true, styleHashes)
286
+ res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad, {
287
+ skipMarkHandled: true,
288
+ requestId: reqId,
289
+ serverTiming: st,
290
+ })
291
+ }
292
+ return cookieStore?.hasChanges ? finish(res, request, cookieStore, reqId, st) : withHsts(res, request)
293
+ }
294
+ }
295
+
250
296
  /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
251
297
  export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
252
298
  const { entry, mod, layouts, doc, reviveScript, hasIslands, hasLoad, trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts } = options
@@ -255,69 +301,71 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
255
301
  const { docPrefix, revivingPrefix, docSuffix } = buildFastDocShell(doc, entry.eagerIslandChunks ?? entry.islandChunks, reviveScript, hasIslands)
256
302
  const headStyleHashes = headTagStyleHashes(doc.headTags)
257
303
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
258
-
259
- const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
260
- notifyError(error, request, 'route', ctx?.requestId)
304
+ const needsIslandStyle = hasIslands || (doc.regionScript !== undefined && doc.runtimeScript !== undefined)
305
+ const baseHeaders = htmlHeaders(needsIslandStyle, false, true, headStyleHashes)
306
+ const baseVaryHeaders = compressCache !== undefined ? withVaryAcceptEncoding(baseHeaders) : baseHeaders
307
+ const skipRequestScope = !hasLoad && consent === undefined && entry.usesRequestScope === false
308
+ const hasHeadHandler = typeof mod.HEAD === 'function'
309
+
310
+ const fail = (error: unknown, request: Request, url: URL, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, remoteIp?: string): Promise<Response> => {
311
+ notifyError(error, request, 'route', reqId)
312
+ if (ctx === undefined) {
313
+ const built = makeRequestContext(request, {}, { trustProxy, httpsSite: options.httpsSite, remoteIp, url, consent, requestId: reqId })
314
+ return renderError(error, built.cookieStore, url, request, built.ctx, entry.file)
315
+ }
261
316
  return renderError(error, cookieStore, url, request, ctx, entry.file)
262
317
  }
263
- const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Response => {
264
- const html = withKeepScroll(rctx.revives ? revivingPrefix : docPrefix, body, docSuffix)
265
- const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
266
- const needsIslandStyle = hasIslands || (doc.regionScript !== undefined && doc.runtimeScript !== undefined)
267
- const headers = withRegionVary(htmlHeaders(needsIslandStyle, false, true, styleHashes), rctx.regionNames.size > 0)
268
- const st = timing !== undefined ? finishRenderTiming(timing) : undefined
269
- const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
270
- res.headers.set('x-request-id', ctx.requestId)
271
- if (st !== undefined)
272
- res.headers.set('server-timing', st)
273
- return cookieStore.hasChanges ? finish(res, request, cookieStore, ctx.requestId, st) : withHsts(res, request)
274
- }
318
+ const respondHtml = createFastHtmlResponder({
319
+ docPrefix, revivingPrefix, docSuffix, headStyleHashes, needsIslandStyle, baseVaryHeaders,
320
+ varyPremerged: compressCache !== undefined, skipKeepScroll: entry.usesKeepScroll === false,
321
+ hasLoad, htmlHeaders, compressCache, finish, withHsts,
322
+ })
275
323
  const layoutProps = (inner: string, url: URL, locals: PrunelleLocals) => ({ children: raw(inner), url, params: {}, locals })
276
324
 
277
- const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Promise<Response> => {
325
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, timing?: PhaseTiming): Promise<Response> => {
278
326
  try {
279
- return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore, ctx, timing)
327
+ return respondHtml(ssrChild(await wrapped as Html), request, rctx, reqId, cookieStore, timing)
280
328
  }
281
329
  catch (error) {
282
- return fail(error, request, url, cookieStore, ctx)
330
+ return fail(error, request, url, reqId, cookieStore, ctx)
283
331
  }
284
332
  }
285
333
 
286
- const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Response | Promise<Response> => {
334
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, timing?: PhaseTiming): Response | Promise<Response> => {
287
335
  if (layouts.length === 0)
288
- return respondHtml(inner, request, rctx, cookieStore, ctx, timing)
336
+ return respondHtml(inner, request, rctx, reqId, cookieStore, timing)
289
337
  if (singleLayout !== undefined) {
290
338
  const wrapped = singleLayout.default(layoutProps(inner, url, locals))
291
339
  if (wrapped instanceof Promise)
292
- return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx, timing)
293
- return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore, ctx, timing)
340
+ return finishSingleLayout(wrapped, request, url, rctx, reqId, cookieStore, ctx, timing)
341
+ return respondHtml(ssrChild(wrapped as Html), request, rctx, reqId, cookieStore, timing)
294
342
  }
295
343
  return (async () => {
296
344
  try {
297
345
  let cur = inner
298
346
  for (let i = layouts.length - 1; i >= 0; i--)
299
347
  cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
300
- return respondHtml(cur, request, rctx, cookieStore, ctx, timing)
348
+ return respondHtml(cur, request, rctx, reqId, cookieStore, timing)
301
349
  }
302
350
  catch (error) {
303
- return fail(error, request, url, cookieStore, ctx)
351
+ return fail(error, request, url, reqId, cookieStore, ctx)
304
352
  }
305
353
  })()
306
354
  }
307
355
 
308
- const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Promise<Response> => {
356
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, timing?: PhaseTiming): Promise<Response> => {
309
357
  try {
310
- return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
358
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, reqId, cookieStore, ctx, timing)
311
359
  }
312
360
  catch (error) {
313
- return fail(error, request, url, cookieStore, ctx)
361
+ return fail(error, request, url, reqId, cookieStore, ctx)
314
362
  }
315
363
  }
316
364
 
317
- const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Response | Promise<Response> => {
365
+ const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, reqId: string, cookieStore?: CookieStore, ctx?: RequestContext, timing?: PhaseTiming): Response | Promise<Response> => {
318
366
  if (timing !== undefined)
319
367
  timing.render = performance.now()
320
- const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
368
+ const pageProps: Record<string, unknown> = data !== undefined ? { params: {}, locals, url, data } : { params: {}, locals, url }
321
369
  if (entry.isIsland && entry.islandChunk !== undefined) {
322
370
  return wrapLayouts(ssrIsland(
323
371
  entry.islandChunk,
@@ -326,32 +374,42 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
326
374
  entry.islandHydrate as HydrateStrategy | undefined,
327
375
  true,
328
376
  mod.default!.name,
329
- ), request, url, locals, rctx, cookieStore, ctx, timing)
377
+ ), request, url, locals, rctx, reqId, cookieStore, ctx, timing)
330
378
  }
331
379
  const rendered = mod.default!(pageProps)
332
380
  if (rendered instanceof Promise)
333
- return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx, timing)
334
- return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
381
+ return finishAsyncPage(rendered, request, url, locals, rctx, reqId, cookieStore, ctx, timing)
382
+ return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, reqId, cookieStore, ctx, timing)
335
383
  }
336
384
 
337
385
  return (request, remoteIp, url = new URL(request.url), requestId?: string) => {
338
386
  const reqId = requestId ?? getRequestId(request)
339
387
  const timing = createTiming(isDev, request)
388
+ if (skipRequestScope && !(hasHeadHandler && request.method === 'HEAD')) {
389
+ const locals: PrunelleLocals = {}
390
+ const rctx = createRenderContext(undefined, undefined, undefined, error => notifyError(error, request, 'route', reqId), true)
391
+ try {
392
+ return runWithRenderContext(rctx, () => renderPage(undefined, request, url, locals, rctx, reqId, undefined, undefined, timing))
393
+ }
394
+ catch (error) {
395
+ return fail(error, request, url, reqId, undefined, undefined, remoteIp)
396
+ }
397
+ }
340
398
  const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite: options.httpsSite, remoteIp, url, consent, requestId: reqId })
341
- if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
399
+ if (hasHeadHandler && request.method === 'HEAD') {
342
400
  return actions.run(ctx, async () => {
343
401
  try {
344
402
  return finish(await mod.HEAD!(ctx), request, cookieStore, reqId, formatServerTiming(timing))
345
403
  }
346
404
  catch (error) {
347
- return fail(error, request, url, cookieStore, ctx)
405
+ return fail(error, request, url, reqId, cookieStore, ctx)
348
406
  }
349
407
  })
350
408
  }
351
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route', reqId))
409
+ const rctx = createRenderContext(undefined, undefined, consent !== undefined ? ctx.consent : undefined, error => notifyError(error, request, 'route', reqId), true)
352
410
  try {
353
411
  if (!hasLoad)
354
- return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx, timing)))
412
+ return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, reqId, cookieStore, ctx, timing)))
355
413
 
356
414
  return actions.run(ctx, async () => {
357
415
  let loaded: unknown
@@ -362,7 +420,7 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
362
420
  catch (error) {
363
421
  if (isNotFound(error))
364
422
  return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
365
- return fail(error, request, url, cookieStore, ctx)
423
+ return fail(error, request, url, reqId, cookieStore, ctx)
366
424
  }
367
425
  endTimer(timing, 'load', loadStart)
368
426
  if (isNotFound(loaded))
@@ -375,15 +433,15 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
375
433
  return finish(await maybeCompressResponse(out, request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
376
434
  }
377
435
  try {
378
- return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx, timing))
436
+ return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, reqId, cookieStore, ctx, timing))
379
437
  }
380
438
  catch (error) {
381
- return fail(error, request, url, cookieStore, ctx)
439
+ return fail(error, request, url, reqId, cookieStore, ctx)
382
440
  }
383
441
  })
384
442
  }
385
443
  catch (error) {
386
- return fail(error, request, url, cookieStore, ctx)
444
+ return fail(error, request, url, reqId, cookieStore, ctx)
387
445
  }
388
446
  }
389
447
  }
@@ -290,8 +290,8 @@ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
290
290
  const openIdx = openStack.lastIndexOf(tagName)
291
291
  if (openIdx === -1)
292
292
  continue
293
+ for (let k = openStack.length - 1; k >= openIdx; k--) out += `</${openStack[k]}>`
293
294
  openStack.length = openIdx
294
- out += `</${tagName}>`
295
295
  continue
296
296
  }
297
297
 
@@ -308,6 +308,8 @@ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
308
308
  out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
309
309
  }
310
310
 
311
+ // Close what the input left open, or an untrusted `<div class="hidden">` swallows the page around it.
312
+ for (let k = openStack.length - 1; k >= 0; k--) out += `</${openStack[k]}>`
311
313
  return out
312
314
  }
313
315
 
@@ -1,6 +1,7 @@
1
1
  // The handlers `Bun.serve()` runs for an app: its native route table of files and fast pages, its fetch fallback and its error answer. `serve()` starts a server with them, `reloadInto()` swaps them into one already listening.
2
2
 
3
3
  import type { createAssets, ServedFile } from './assets'
4
+ import type { CorsWrap } from './cors'
4
5
  import type { NotifyError } from './errors'
5
6
  import type { RequestIdResolver } from './health'
6
7
  import type { PrunelleServer } from './http'
@@ -29,6 +30,8 @@ export interface ServeHandlerSources {
29
30
  fileGone: () => Response
30
31
  /** Wraps every handler but the health probe's, when the access log or an `onRequestEnd` hook listens. */
31
32
  observe?: ObserveHandler | undefined
33
+ /** Answers the preflight and adds the CORS headers on every handler, the health probe's included. */
34
+ cors?: CorsWrap | undefined
32
35
  }
33
36
 
34
37
  export const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
@@ -39,7 +42,7 @@ export const hasActionErrorCookie = (request: Request): boolean => (request.head
39
42
  export const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request) && !hasRegionHeader(request)
40
43
 
41
44
  export function serveHandlers(server: () => PrunelleServer | undefined, sources: ServeHandlerSources) {
42
- const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone, observe } = sources
45
+ const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone, observe, cors } = sources
43
46
  const ipOf = (req: Request) => server()?.requestIP(req)?.address
44
47
  const fetchReq = (req: Request) => runRequest(req, ipOf(req), seconds => server()?.timeout(req, seconds))
45
48
  // A file that fails to open answers here, where the request is known: gone since the build is a 404, anything else is reported with it.
@@ -60,9 +63,12 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
60
63
  const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
61
64
  const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>, observed = true): void => {
62
65
  const key = toBunRouteKey(path)
63
- if (key !== undefined && !(key in routes))
64
- routes[key] = observed && observe !== undefined ? observe(handler) : handler
66
+ if (key === undefined || key in routes)
67
+ return
68
+ const answered = cors?.(handler) ?? handler
69
+ routes[key] = observed && observe !== undefined ? observe(answered) : answered
65
70
  }
71
+ const fetchAnswered = cors?.(fetchReq) ?? fetchReq
66
72
 
67
73
  // A container probes its health every few seconds: logging each probe would bury the requests.
68
74
  if (healthPath !== undefined && healthHandler !== undefined)
@@ -84,7 +90,7 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
84
90
 
85
91
  return {
86
92
  routes,
87
- fetch: observe?.(fetchReq) ?? fetchReq,
93
+ fetch: observe?.(fetchAnswered) ?? fetchAnswered,
88
94
  error(err: Error) {
89
95
  const fallbackReq = new Request('http://localhost/')
90
96
  const reqId = resolveRequestId?.(fallbackReq)
@@ -15,6 +15,8 @@ interface Variant {
15
15
  headers: Record<string, string>
16
16
  /** The file's path and size, for a variant on disk the compression cache may keep in memory. */
17
17
  disk: { path: string, size: () => number } | undefined
18
+ /** The variant's byte length, for the `content-length` of a `HEAD`. */
19
+ size: () => number
18
20
  }
19
21
 
20
22
  export interface ServedFile {
@@ -54,6 +56,10 @@ async function bytesOf(source: FileSource): Promise<Uint8Array<ArrayBuffer>> {
54
56
  return 'path' in source ? new Uint8Array(await Bun.file(source.path).arrayBuffer()) : 'bytes' in source ? source.bytes : textEncoder.encode(source.text)
55
57
  }
56
58
 
59
+ function sizeOf(source: FileSource): number {
60
+ return 'path' in source ? Bun.file(source.path).size : 'bytes' in source ? source.bytes.byteLength : textEncoder.encode(source.text).byteLength
61
+ }
62
+
57
63
  /** `W/"<size>-<mtime>"` for a file on disk, a hash of the bytes otherwise. */
58
64
  export function sourceEtag(source: FileSource): string {
59
65
  if ('path' in source) {
@@ -73,7 +79,7 @@ export function servedFile(init: ServedFileInit): ServedFile {
73
79
  return { path, size: () => bytes ??= Bun.file(path).size }
74
80
  }
75
81
  const encoded = (source: FileSource | undefined, encoding: string): Variant | undefined =>
76
- source === undefined ? undefined : { body: bodyOf(source), headers: { ...headers, 'content-encoding': encoding, 'etag': toWeakEtag(etag) }, disk: 'path' in source ? onDisk(source.path) : undefined }
82
+ source === undefined ? undefined : { body: bodyOf(source), headers: { ...headers, 'content-encoding': encoding, 'etag': toWeakEtag(etag) }, disk: 'path' in source ? onDisk(source.path) : undefined, size: () => sizeOf(source) }
77
83
  let size: number | undefined
78
84
  return {
79
85
  key: `${init.key}:${etag}`,
@@ -85,7 +91,7 @@ export function servedFile(init: ServedFileInit): ServedFile {
85
91
  gz: encoded(init.gz, 'gzip'),
86
92
  body: bodyOf(init.source),
87
93
  read: () => bytesOf(init.source),
88
- size: () => size ??= 'path' in init.source ? Bun.file(init.source.path).size : 'bytes' in init.source ? init.source.bytes.byteLength : textEncoder.encode(init.source.text).byteLength,
94
+ size: () => size ??= sizeOf(init.source),
89
95
  }
90
96
  }
91
97
 
@@ -101,19 +107,18 @@ export function createFileServer(options: {
101
107
  return async function serveFile(request: Request, file: ServedFile, status = 200): Promise<Response> {
102
108
  if (status === 200 && file.etag !== undefined && etagMatches(request.headers.get('if-none-match'), file.etag))
103
109
  return done(new Response(null, { status: 304, headers: file.notModifiedHeaders }), request)
104
- if (request.method === 'HEAD')
105
- return done(new Response(null, { status, headers: { ...file.headers, 'content-length': String(file.size()) } }), request)
106
110
  const accept = request.headers.get('accept-encoding')
107
- if (compressEnabled && (file.br !== undefined || file.gz !== undefined)) {
108
- const pre = pickPrecompressedEncoding(accept, { br: file.br !== undefined, gz: file.gz !== undefined })
109
- if (pre !== undefined) {
110
- const variant = pre === 'br' ? file.br! : file.gz!
111
- const { disk } = variant
112
- const kept = disk !== undefined && compressCache?.keeps(disk.size()) === true
113
- ? await compressCache.sidecar(`${file.key}:${pre}`, async () => new Uint8Array(await Bun.file(disk.path).arrayBuffer()))
114
- : undefined
115
- return done(new Response(kept ?? variant.body, { status, headers: variant.headers }), request)
116
- }
111
+ const pre = compressEnabled && (file.br !== undefined || file.gz !== undefined) ? pickPrecompressedEncoding(accept, { br: file.br !== undefined, gz: file.gz !== undefined }) : undefined
112
+ const variant = pre === undefined ? undefined : pre === 'br' ? file.br! : file.gz!
113
+ // A HEAD carries the headers of the GET it stands for, the sidecar's encoding and length included.
114
+ if (request.method === 'HEAD')
115
+ return done(new Response(null, { status, headers: { ...variant?.headers ?? file.headers, 'content-length': String(variant?.size() ?? file.size()) } }), request)
116
+ if (variant !== undefined) {
117
+ const { disk } = variant
118
+ const kept = disk !== undefined && compressCache?.keeps(disk.size()) === true
119
+ ? await compressCache.sidecar(`${file.key}:${pre}`, async () => new Uint8Array(await Bun.file(disk.path).arrayBuffer()))
120
+ : undefined
121
+ return done(new Response(kept ?? variant.body, { status, headers: variant.headers }), request)
117
122
  }
118
123
  if (file.compressedHeaders !== undefined && compressCache !== undefined) {
119
124
  const enc = pickEncoding(accept)
@@ -76,6 +76,15 @@ function backgroundTask(what: string): (task: () => Promise<unknown>) => void {
76
76
  }
77
77
  }
78
78
 
79
+ function callListener(channel: string, onMessage: (payload: string) => void, payload: string): void {
80
+ try {
81
+ onMessage(payload)
82
+ }
83
+ catch (error) {
84
+ console.error(`prunelle: a listener of the shared store channel "${channel}" threw; the other listeners still got the message.`, error)
85
+ }
86
+ }
87
+
79
88
  interface MessageRow { id: number | string, channel: string, payload: string, origin: string, at: number | string }
80
89
 
81
90
  function rateCounter(sql: SQL, kind: Kind, prepare: () => Promise<void>): Pick<SharedStore, 'hit' | 'peek'> {
@@ -126,7 +135,7 @@ function messageChannel(sql: SQL, kind: Kind, prepare: () => Promise<void>): Pic
126
135
 
127
136
  function deliver(channel: string, payload: string): void {
128
137
  for (const onMessage of [...listeners.get(channel) ?? []])
129
- onMessage(payload)
138
+ callListener(channel, onMessage, payload)
130
139
  }
131
140
 
132
141
  async function readNew(): Promise<void> {
@@ -3,6 +3,7 @@
3
3
  import type { FSWatcher } from 'node:fs'
4
4
  import type { LogConfig, PrunellePlugin, ServerErrorInfo } from '../plugins/index'
5
5
  import type { NavigationConfig } from '../ssr/navigation'
6
+ import type { CorsConfig } from './cors'
6
7
  import type { PrunelleApp, PrunelleServer, ServeOptions } from './http'
7
8
  import type { SecurityHeadersOptions, TrustProxy } from './security'
8
9
  import type { FileSource, ServedFile } from './served-file'
@@ -13,6 +14,7 @@ import { resolvePlugins } from '../plugins/index'
13
14
  import { createNavigation, cspSha256 } from '../ssr/navigation'
14
15
  import { staticMime } from './assets'
15
16
  import { CompressionCache, isCompressibleType } from './compress'
17
+ import { withCorsSetting } from './cors'
16
18
  import { createErrorNotifier } from './errors'
17
19
  import { applyHstsHeader } from './http'
18
20
  import { createRequestObserver } from './request-log'
@@ -20,6 +22,17 @@ import { decodeRequestPath } from './request-path'
20
22
  import { buildSecurityHeaderEntries, inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes, withoutCspReports } from './security'
21
23
  import { createFileServer, servedFile } from './served-file'
22
24
 
25
+ // The extensions `prunelle build --static` gives an extension-less API route by its content type (`CONTENT_TYPE_EXT` in `build/prerender.ts`).
26
+ const PRERENDERED_API_EXTS = new Set(['.json', '.xml', '.rss', '.atom', '.txt', '.ics', '.csv'])
27
+
28
+ // An extension-less API route the export wrote as `x.json`, `x.xml` or `x.txt` is also served at `x`.
29
+ function aliasApiRoute(table: Map<string, ServedFile>, rel: string, entry: ServedFile): void {
30
+ const ext = extname(rel)
31
+ const bare = rel.slice(0, -ext.length)
32
+ if (PRERENDERED_API_EXTS.has(ext) && extname(bare) === '' && !table.has(bare))
33
+ table.set(bare, entry)
34
+ }
35
+
23
36
  const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
24
37
 
25
38
  export interface StaticDirExtraOptions {
@@ -31,6 +44,7 @@ export interface StaticDirExtraOptions {
31
44
  httpsSite?: boolean | undefined
32
45
  nodeEnv?: string | undefined
33
46
  log?: LogConfig | undefined
47
+ cors?: CorsConfig | undefined
34
48
  }
35
49
 
36
50
  function findNotFound(rel: string | undefined, byDir: ReadonlyMap<string, ServedFile>): ServedFile | undefined {
@@ -159,7 +173,7 @@ export function createStaticDirServer(
159
173
  })
160
174
  }
161
175
 
162
- // Each file at its own path, then `x.html` at `x` and `x/index.html` at `x`, a real file always winning.
176
+ // Each file at its own path, then `x.html` at `x`, `x/index.html` at `x` and an exported `x.json` at `x`, a real file always winning.
163
177
  function buildTable(): { table: Map<string, ServedFile>, notFoundByDir: Map<string, ServedFile> } {
164
178
  const files = listFiles(absRoot, realRoot)
165
179
  const table = new Map<string, ServedFile>()
@@ -183,6 +197,9 @@ export function createStaticDirServer(
183
197
  table.set(dir, entry)
184
198
  }
185
199
  }
200
+ // Last, so a page (`x.html`, `x/index.html`) keeps `x` over a data file beside it.
201
+ for (const [rel, entry] of [...table])
202
+ aliasApiRoute(table, rel, entry)
186
203
  return { table, notFoundByDir }
187
204
  }
188
205
 
@@ -201,7 +218,8 @@ export function createStaticDirServer(
201
218
  console.warn(`prunelle start: files changed in ${absRoot} will be served only after a restart: ${err instanceof Error ? err.message : String(err)}`)
202
219
  }
203
220
 
204
- const answer = async (req: Request): Promise<Response> => {
221
+ // Behind `cors`, a preflight carries the headers the other answers do.
222
+ const answer = withCorsSetting(extra?.cors, (res, req) => withHsts(new Response(null, { status: res.status, headers: { ...securityRecord, ...Object.fromEntries(res.headers) } }), req), async (req: Request): Promise<Response> => {
205
223
  if (!isRead(req))
206
224
  return withHsts(new Response('Method Not Allowed', { status: 405, headers: { ...securityRecord, allow: 'GET, HEAD' } }), req)
207
225
  const rel = requestedRel(new URL(req.url).pathname)
@@ -212,7 +230,7 @@ export function createStaticDirServer(
212
230
  if (notFound !== undefined)
213
231
  return serveFile(req, notFound, 404)
214
232
  return withHsts(new Response('Not Found', { status: 404, headers: securityRecord }), req)
215
- }
233
+ })
216
234
  const observe = createRequestObserver(extra?.log, [], isDev)
217
235
  const handle = observe?.(answer) ?? answer
218
236
 
@@ -17,19 +17,21 @@ const STANDARD_PREFIX = 'whsec_'
17
17
  export async function verifyWebhook(request: Request, scheme: WebhookScheme, secret: string | undefined, options: VerifyWebhookOptions = {}): Promise<string | undefined> {
18
18
  if (!secret)
19
19
  throw new Error(`prunelle: verifyWebhook('${scheme}') got no secret: pass the signing secret the sender shows, read from an environment variable`)
20
- const body = await request.text()
20
+ // The signature covers the bytes the sender wrote: decoding them first would turn a non-UTF-8 byte into U+FFFD and fail a valid body.
21
+ const bytes = Buffer.from(await request.arrayBuffer())
22
+ const body = new TextDecoder().decode(bytes)
21
23
  const headers = request.headers
22
24
  const tolerance = options.toleranceSeconds ?? TOLERANCE_SECONDS
23
25
  if (scheme === 'github') {
24
26
  const signature = headers.get('x-hub-signature-256') ?? ''
25
- return safeEqual(signature, `sha256=${hmac(secret, body).toString('hex')}`) ? body : undefined
27
+ return safeEqual(signature, `sha256=${hmac(secret, bytes).toString('hex')}`) ? body : undefined
26
28
  }
27
29
  if (scheme === 'stripe') {
28
30
  const fields = (headers.get('stripe-signature') ?? '').split(',').map(field => field.split('='))
29
31
  const timestamp = fields.find(([key]) => key === 't')?.[1]
30
32
  if (timestamp === undefined || !fresh(timestamp, tolerance))
31
33
  return undefined
32
- const expected = hmac(secret, `${timestamp}.${body}`).toString('hex')
34
+ const expected = hmac(secret, Buffer.concat([Buffer.from(`${timestamp}.`), bytes])).toString('hex')
33
35
  return fields.some(([key, value]) => key === 'v1' && value !== undefined && safeEqual(value, expected)) ? body : undefined
34
36
  }
35
37
  const id = headers.get('webhook-id')
@@ -37,7 +39,7 @@ export async function verifyWebhook(request: Request, scheme: WebhookScheme, sec
37
39
  if (id === null || timestamp === null || !fresh(timestamp, tolerance))
38
40
  return undefined
39
41
  const key = Buffer.from(secret.startsWith(STANDARD_PREFIX) ? secret.slice(STANDARD_PREFIX.length) : secret, 'base64')
40
- const expected = hmac(key, `${id}.${timestamp}.${body}`).toString('base64')
42
+ const expected = hmac(key, Buffer.concat([Buffer.from(`${id}.${timestamp}.`), bytes])).toString('base64')
41
43
  const signatures = (headers.get('webhook-signature') ?? '').split(' ')
42
44
  return signatures.some(entry => entry.startsWith('v1,') && safeEqual(entry.slice(3), expected)) ? body : undefined
43
45
  }