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.
- package/llms.txt +18 -18
- package/package.json +2 -2
- package/src/a11y/declaration.ts +4 -7
- package/src/build/bundle.ts +6 -2
- package/src/build/index.ts +3 -1
- package/src/build/island-promote.ts +42 -2
- package/src/build/islands.ts +59 -8
- package/src/build/manifest.ts +98 -0
- package/src/build/plugin-host.ts +11 -1
- package/src/build/prerender.ts +6 -1
- package/src/build/reach.ts +4 -3
- package/src/build/resolve.ts +5 -1
- package/src/build/routes.ts +18 -0
- package/src/cli/check-forms.ts +8 -0
- package/src/cli/check-links.ts +14 -5
- package/src/cli/check.ts +12 -6
- package/src/cli/commands.ts +5 -3
- package/src/cli/form-opaque-children.ts +40 -0
- package/src/compiler/analyze.ts +20 -14
- package/src/compiler/cacheability-private.ts +13 -3
- package/src/compiler/compliance-contrast.ts +48 -10
- package/src/compiler/compliance-rules.ts +72 -0
- package/src/compiler/compliance.ts +6 -66
- package/src/compiler/dom-attrs.ts +178 -22
- package/src/compiler/dom.ts +31 -44
- package/src/compiler/emit.ts +17 -6
- package/src/compiler/expr-context.ts +260 -207
- package/src/compiler/props-body.ts +263 -21
- package/src/compiler/props.ts +155 -5
- package/src/compiler/signal-reads.ts +142 -29
- package/src/compiler/spread-handlers.ts +25 -13
- package/src/compiler/ssr-emit.ts +3 -3
- package/src/compiler/ssr-helpers.ts +0 -5
- package/src/compiler/ssr.ts +4 -2
- package/src/dev/host-check.ts +2 -1
- package/src/dev/reload.ts +4 -1
- package/src/dom/attrs.ts +93 -25
- package/src/dom/extras.ts +89 -49
- package/src/dom/field-marks.ts +9 -1
- package/src/dom/index.ts +19 -13
- package/src/dom/loop.ts +259 -188
- package/src/dom/prefetch.ts +4 -1
- package/src/dom/regions.ts +25 -8
- package/src/dom/swap.ts +11 -10
- package/src/dom/trusted.ts +4 -4
- package/src/eco/declaration.ts +5 -1
- package/src/eco/index.ts +3 -0
- package/src/index.ts +3 -2
- package/src/plugins/config.ts +1 -1
- package/src/plugins/public.ts +4 -0
- package/src/plugins/types.ts +8 -1
- package/src/reactivity/graph.ts +244 -41
- package/src/reactivity/hmr.ts +14 -3
- package/src/reactivity/index.ts +219 -235
- package/src/reactivity/resource.ts +17 -3
- package/src/reactivity/seed.ts +118 -16
- package/src/reactivity/selector.ts +85 -47
- package/src/reactivity/server-seed.ts +31 -23
- package/src/reactivity/store.ts +316 -136
- package/src/server/action-protect.ts +3 -0
- package/src/server/action-registry.ts +5 -1
- package/src/server/cache-invalidation.ts +4 -3
- package/src/server/compress.ts +52 -17
- package/src/server/consent.ts +5 -3
- package/src/server/cookies.ts +27 -8
- package/src/server/cors.ts +98 -0
- package/src/server/csp-report.ts +8 -4
- package/src/server/health.ts +9 -0
- package/src/server/http.ts +3 -1
- package/src/server/index.ts +25 -13
- package/src/server/loader.ts +1 -0
- package/src/server/plugin-host.ts +41 -9
- package/src/server/plugin-route-shadow.ts +24 -0
- package/src/server/rate-limit.ts +13 -3
- package/src/server/region.ts +19 -2
- package/src/server/request-handler.ts +58 -22
- package/src/server/request-log.ts +1 -1
- package/src/server/route-cache.ts +14 -2
- package/src/server/route-table.ts +21 -11
- package/src/server/router.ts +2 -1
- package/src/server/routing.ts +100 -42
- package/src/server/sanitize-html.ts +3 -1
- package/src/server/serve-handlers.ts +10 -4
- package/src/server/served-file.ts +19 -14
- package/src/server/shared-store.ts +10 -1
- package/src/server/static-dir.ts +21 -3
- package/src/server/webhook.ts +6 -4
- package/src/ssr/context.ts +149 -51
- package/src/ssr/index.ts +41 -46
- package/src/ssr/region.ts +9 -3
- package/src/style.ts +12 -5
- package/src/test/browser.ts +3 -1
- package/src/test/build-reuse.ts +22 -7
- package/src/test/index.ts +7 -3
- package/src/ts-plugin/diagnostics.ts +56 -18
- package/ts-plugin.cjs +465 -131
package/src/server/routing.ts
CHANGED
|
@@ -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
|
|
260
|
-
|
|
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 = (
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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'
|
|
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
|
|
64
|
-
|
|
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?.(
|
|
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 ??=
|
|
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
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
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
|
|
138
|
+
callListener(channel, onMessage, payload)
|
|
130
139
|
}
|
|
131
140
|
|
|
132
141
|
async function readNew(): Promise<void> {
|
package/src/server/static-dir.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
|
package/src/server/webhook.ts
CHANGED
|
@@ -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
|
-
|
|
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,
|
|
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}
|
|
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}
|
|
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
|
}
|