prunelle 0.1.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +23 -19
- package/package.json +8 -2
- package/src/a11y/declaration.ts +335 -0
- package/src/a11y/index.ts +446 -0
- package/src/a11y/rgaa-map.ts +184 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +80 -36
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +8 -4
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +11 -9
- package/src/build/ecoindex.ts +229 -0
- package/src/build/index.ts +174 -108
- package/src/build/islands.ts +2 -2
- package/src/build/manifest.ts +66 -5
- package/src/build/output.ts +2 -2
- package/src/build/plugin-host.ts +91 -33
- package/src/build/precompress.ts +15 -2
- package/src/build/prerender.ts +128 -46
- package/src/build/report.ts +23 -2
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static.ts +137 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +52 -5
- package/src/cli/commands.ts +86 -4
- package/src/cli/docs.ts +402 -0
- package/src/cli/inspect.ts +31 -2
- package/src/cli/mcp-tools.ts +480 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +2 -2
- package/src/cli/render.ts +261 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/compiler/analyze.ts +20 -6
- package/src/compiler/cacheability.ts +592 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +120 -221
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +12 -11
- package/src/compiler/expr-context.ts +167 -57
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +56 -17
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +216 -84
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +84 -34
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/protocol.ts +1 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +42 -25
- package/src/dev/watchers.ts +47 -11
- package/src/dom/action.ts +4 -1
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +2 -2
- package/src/dom/island.ts +11 -10
- package/src/plugins/config.ts +4 -4
- package/src/plugins/index.ts +2 -2
- package/src/plugins/public.ts +5 -2
- package/src/plugins/services.ts +62 -0
- package/src/plugins/types.ts +32 -0
- package/src/server/action-protect.ts +198 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +82 -27
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +91 -9
- package/src/server/errors.ts +303 -65
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +128 -31
- package/src/server/index.ts +230 -260
- package/src/server/loader.ts +5 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +123 -88
- package/src/server/public.ts +3 -3
- package/src/server/rate-limit.ts +58 -35
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +423 -0
- package/src/server/route-table.ts +339 -8
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +196 -63
- package/src/server/security.ts +208 -32
- package/src/server/serve-handlers.ts +21 -7
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +61 -8
- package/src/server/stream.ts +41 -22
- package/src/ssr/context.ts +85 -3
- package/src/ssr/index.ts +120 -1
- package/src/ssr/region.ts +31 -19
- package/src/test/browser.ts +6 -0
- package/src/test/index.ts +17 -3
- package/src/ts-plugin/diagnostics.ts +378 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +5 -0
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/index.tsx +4 -0
- package/ts-plugin.cjs +4277 -0
|
@@ -1,15 +1,51 @@
|
|
|
1
1
|
// The page routes of a build, compiled once at startup: each route's modules, middlewares and document options, and the handler of a page nothing can intercept.
|
|
2
2
|
|
|
3
3
|
import type { BuildManifest, RouteManifestEntry } from '../build/index'
|
|
4
|
+
import type { Html, HydrateStrategy } from '../jsx-runtime'
|
|
5
|
+
import type { AppRuntimeContext } from '../plugins/index'
|
|
4
6
|
import type { DocumentOptions } from '../ssr/index'
|
|
5
|
-
import type {
|
|
7
|
+
import type { ActionRegistry } from './action-registry'
|
|
8
|
+
import type { ServedFile } from './assets'
|
|
9
|
+
import type { CompressionCache } from './compress'
|
|
10
|
+
import type { NormalizedConsentConfig } from './consent'
|
|
11
|
+
import type { CookieStore } from './cookies'
|
|
12
|
+
import type { DocumentHooks, HtmlHeaders } from './document'
|
|
13
|
+
import type { NotifyError } from './errors'
|
|
14
|
+
import type { DevTiming, RequestIdResolver } from './health'
|
|
15
|
+
import type { Middleware, RequestContext } from './http'
|
|
6
16
|
import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
|
|
17
|
+
import type { ParamMatcherMap } from './param-matchers'
|
|
7
18
|
import type { RequestKind } from './plugin-host'
|
|
19
|
+
import type { RouteCache, RouteCacheSingleflightResult, RouteCacheSpec } from './route-cache'
|
|
8
20
|
import type { FastHandler, FastStaticPageOptions } from './routing'
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
21
|
+
import type { TrustProxy } from './security'
|
|
22
|
+
import { runWithAppContext } from '../plugins/index'
|
|
23
|
+
import { createRenderContext, runWithRenderContext } from '../ssr/context'
|
|
24
|
+
import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
|
|
25
|
+
import { ACTION_ERROR_COOKIE, hydrateActionErrorFlash } from './action'
|
|
26
|
+
import { compressedHtmlResponse, compressedHtmlStream, markCompressionHandled } from './compress'
|
|
27
|
+
import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
|
|
28
|
+
import { endTimer, startTimer } from './health'
|
|
29
|
+
import { isNotFound, makeRequestContext, runChain } from './http'
|
|
30
|
+
import { allowedMethodsHeader, mergedHeadTags, pickPageIslandProps, stripHeadBody } from './page'
|
|
31
|
+
import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
|
|
32
|
+
import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
|
|
33
|
+
import { isCacheableRequest, routeCacheKey, serveCachedHit, withCacheControl } from './route-cache'
|
|
11
34
|
import { Router } from './router'
|
|
12
|
-
import { createFastStaticPageHandler } from './routing'
|
|
35
|
+
import { createFastStaticPageHandler, methodNotAllowed } from './routing'
|
|
36
|
+
import { styleHashesOf } from './security'
|
|
37
|
+
import { hasActionErrorCookie, isRead } from './serve-handlers'
|
|
38
|
+
import { STREAM_TAIL_MARK, streamDocument } from './stream'
|
|
39
|
+
|
|
40
|
+
export const HTTP_METHOD_EXPORTS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
|
|
41
|
+
|
|
42
|
+
/** Returns the exported HTTP method handler for `method` only when `method` is a standard HTTP method export. */
|
|
43
|
+
export function routeMethodHandler(mod: LoadedPageModule, method: string): ((c: RequestContext) => Response | Promise<Response>) | undefined {
|
|
44
|
+
if (!HTTP_METHOD_EXPORTS.has(method))
|
|
45
|
+
return undefined
|
|
46
|
+
const handler = mod[method]
|
|
47
|
+
return typeof handler === 'function' ? handler as (c: RequestContext) => Response | Promise<Response> : undefined
|
|
48
|
+
}
|
|
13
49
|
|
|
14
50
|
export interface CompiledRoute {
|
|
15
51
|
entry: RouteManifestEntry
|
|
@@ -44,6 +80,7 @@ type SharedFastOptions = Omit<FastStaticPageOptions, 'entry' | 'mod' | 'layouts'
|
|
|
44
80
|
export interface RouteTableOptions {
|
|
45
81
|
manifest: BuildManifest
|
|
46
82
|
modules: Record<string, unknown>
|
|
83
|
+
paramMatchers?: ParamMatcherMap | undefined
|
|
47
84
|
lang: string
|
|
48
85
|
alwaysLoadRuntime: boolean
|
|
49
86
|
navigation: DocumentOptions['navigation']
|
|
@@ -54,8 +91,8 @@ export interface RouteTableOptions {
|
|
|
54
91
|
}
|
|
55
92
|
|
|
56
93
|
export function compileRouteTable(options: RouteTableOptions): { router: Router<CompiledRoute>, fastStaticPages: Map<string, FastHandler> } {
|
|
57
|
-
const { manifest, modules, lang, alwaysLoadRuntime, navigation, middlewaresFor, pluginIntercepts, fast } = options
|
|
58
|
-
const router = new Router<CompiledRoute>()
|
|
94
|
+
const { manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation, middlewaresFor, pluginIntercepts, fast } = options
|
|
95
|
+
const router = new Router<CompiledRoute>(paramMatchers ?? BUILTIN_PARAM_MATCHERS)
|
|
59
96
|
const fastStaticPages = new Map<string, FastHandler>()
|
|
60
97
|
for (const entry of manifest.routes) {
|
|
61
98
|
const mod = modules[entry.file] as LoadedPageModule
|
|
@@ -65,10 +102,10 @@ export function compileRouteTable(options: RouteTableOptions): { router: Router<
|
|
|
65
102
|
const dynamic = entry.path.includes(':') || entry.path.includes('*')
|
|
66
103
|
const doc = routeDocument(manifest, entry, lang, alwaysLoadRuntime, navigation)
|
|
67
104
|
|
|
68
|
-
// Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, and no intercepting plugin hook
|
|
105
|
+
// Zero-overhead path for a static route with no middleware, no <Head>/<Suspense>, no route cache, and no intercepting plugin hook
|
|
69
106
|
const canFastPath = middlewaresFor(entry.path, hasLoad ? 'dynamic' : 'static').length === 0
|
|
70
107
|
&& !pluginIntercepts(entry.path) && !dynamic
|
|
71
|
-
&& dirMiddlewares.length === 0 && !entry.usesRenderContext
|
|
108
|
+
&& dirMiddlewares.length === 0 && !entry.usesRenderContext && entry.cache === undefined
|
|
72
109
|
&& typeof mod.default === 'function' && mod.GET === undefined
|
|
73
110
|
if (canFastPath)
|
|
74
111
|
fastStaticPages.set(entry.path, createFastStaticPageHandler({ ...fast, entry, mod, layouts, doc, reviveScript: manifest.reviveScript, hasIslands: entry.islandChunks.length > 0, hasLoad }))
|
|
@@ -77,3 +114,297 @@ export function compileRouteTable(options: RouteTableOptions): { router: Router<
|
|
|
77
114
|
}
|
|
78
115
|
return { router, fastStaticPages }
|
|
79
116
|
}
|
|
117
|
+
|
|
118
|
+
function lookupPrerendered<T>(map: ReadonlyMap<string, T>, staticPath: string | undefined): T | undefined {
|
|
119
|
+
if (staticPath === undefined)
|
|
120
|
+
return undefined
|
|
121
|
+
const normPath = staticPath.length > 1 && staticPath.endsWith('/') ? staticPath.slice(0, -1) : staticPath
|
|
122
|
+
return map.get(staticPath) ?? map.get(normPath)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function renderRouteBody(route: CompiledRoute, data: unknown, pageProps: Record<string, unknown>, ctx: RequestContext): Promise<string> {
|
|
126
|
+
const { entry, mod, layouts } = route
|
|
127
|
+
let inner: string
|
|
128
|
+
if (entry.isIsland && entry.islandChunk !== undefined) {
|
|
129
|
+
inner = ssrIsland(
|
|
130
|
+
entry.islandChunk,
|
|
131
|
+
() => ssrChild(mod.default!(pageProps) as Html),
|
|
132
|
+
pickPageIslandProps(data, entry, mod),
|
|
133
|
+
entry.islandHydrate as HydrateStrategy | undefined,
|
|
134
|
+
true,
|
|
135
|
+
mod.default!.name,
|
|
136
|
+
)
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
inner = ssrChild(await mod.default!(pageProps) as Html)
|
|
140
|
+
}
|
|
141
|
+
for (let i = layouts.length - 1; i >= 0; i--)
|
|
142
|
+
inner = ssrChild(await layouts[i]!.default({ children: raw(inner), url: ctx.url, params: ctx.params, locals: ctx.locals }) as Html)
|
|
143
|
+
return inner
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface CompiledRouteRendererDeps {
|
|
147
|
+
manifest: BuildManifest
|
|
148
|
+
prerenderedMap: ReadonlyMap<string, ServedFile>
|
|
149
|
+
serveFile: (request: Request, file: ServedFile) => Promise<Response>
|
|
150
|
+
buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
|
|
151
|
+
htmlHeaders: HtmlHeaders
|
|
152
|
+
resolveDocumentHead: DocumentHooks['resolveDocumentHead']
|
|
153
|
+
applyHtmlTransforms: DocumentHooks['applyHtmlTransforms']
|
|
154
|
+
hasHtmlTransformers: boolean
|
|
155
|
+
streamTimeout: number
|
|
156
|
+
compressCache: CompressionCache | undefined
|
|
157
|
+
routeCache: RouteCache | undefined
|
|
158
|
+
notifyError: NotifyError
|
|
159
|
+
actions: ActionRegistry
|
|
160
|
+
rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
|
|
161
|
+
trustProxy: TrustProxy
|
|
162
|
+
consent: NormalizedConsentConfig | undefined
|
|
163
|
+
resolveRequestId: RequestIdResolver
|
|
164
|
+
serverAppCtx: AppRuntimeContext
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
type RenderedPageOutput =
|
|
168
|
+
| { kind: 'stream', response: Response }
|
|
169
|
+
| { kind: 'html', html: string, headers: Record<string, string> }
|
|
170
|
+
|
|
171
|
+
async function renderPageDocument(
|
|
172
|
+
deps: CompiledRouteRendererDeps,
|
|
173
|
+
route: CompiledRoute,
|
|
174
|
+
data: unknown,
|
|
175
|
+
pageProps: Record<string, unknown>,
|
|
176
|
+
ctx: RequestContext,
|
|
177
|
+
hasFlash: boolean,
|
|
178
|
+
disableTimeout?: () => void,
|
|
179
|
+
timing?: DevTiming,
|
|
180
|
+
): Promise<RenderedPageOutput> {
|
|
181
|
+
const { entry, doc } = route
|
|
182
|
+
const renderStart = startTimer(timing)
|
|
183
|
+
const rctx = createRenderContext(undefined, undefined, ctx.consent, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId))
|
|
184
|
+
const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, ctx))
|
|
185
|
+
if (hasFlash)
|
|
186
|
+
ctx.cookies.delete(ACTION_ERROR_COOKIE)
|
|
187
|
+
const docHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
|
|
188
|
+
const renderedIslands = resolveRenderedIslands(rctx, body)
|
|
189
|
+
const isStreamed = rctx.pending.length > 0
|
|
190
|
+
const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
|
|
191
|
+
const preloadChunks = [...isStreamed ? entry.eagerIslandChunks ?? entry.islandChunks : renderedIslands.eagerChunks, ...revivePreload(rctx, deps.manifest.reviveScript)]
|
|
192
|
+
const hasRegions = rctx.regionNames.size > 0
|
|
193
|
+
const trustedStyleHashes = mergeStyleHashes(route.headStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles))
|
|
194
|
+
|
|
195
|
+
if (isStreamed) {
|
|
196
|
+
endTimer(timing, 'render', renderStart)
|
|
197
|
+
const streamStart = startTimer(timing)
|
|
198
|
+
if (ctx.request.method === 'HEAD') {
|
|
199
|
+
rctx.aborted = true
|
|
200
|
+
endTimer(timing, 'stream', streamStart)
|
|
201
|
+
return { kind: 'stream', response: markCompressionHandled(new Response(null, { status: 200, headers: withRegionVary(deps.htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions) })) }
|
|
202
|
+
}
|
|
203
|
+
disableTimeout?.()
|
|
204
|
+
const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
|
|
205
|
+
const shell = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docShell, ctx.url, ctx.request, ctx) : docShell
|
|
206
|
+
const streamStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docShell, shell))
|
|
207
|
+
rctx.headersFlushed = true
|
|
208
|
+
endTimer(timing, 'stream', streamStart)
|
|
209
|
+
const transformChunk = deps.hasHtmlTransformers ? (html: string) => deps.applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined
|
|
210
|
+
const response = await compressedHtmlStream(streamDocument(shell, rctx, deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId), transformChunk), 200, withRegionVary(deps.htmlHeaders(hasIslands, true, true, streamStyleHashes), hasRegions), ctx.request, deps.compressCache)
|
|
211
|
+
return { kind: 'stream', response }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const docHtml = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
|
|
215
|
+
const html = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docHtml, ctx.url, ctx.request, ctx) : docHtml
|
|
216
|
+
const finalStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docHtml, html))
|
|
217
|
+
endTimer(timing, 'render', renderStart)
|
|
218
|
+
return { kind: 'html', html, headers: withRegionVary(deps.htmlHeaders(hasIslands, false, true, finalStyleHashes), hasRegions) }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function revalidateCompiledRoute(
|
|
222
|
+
deps: CompiledRouteRendererDeps,
|
|
223
|
+
route: CompiledRoute,
|
|
224
|
+
url: URL,
|
|
225
|
+
params: Record<string, string>,
|
|
226
|
+
cacheKey: string,
|
|
227
|
+
cacheSpec: RouteCacheSpec,
|
|
228
|
+
middlewares: readonly Middleware[],
|
|
229
|
+
): Promise<void> {
|
|
230
|
+
const routeCache = deps.routeCache
|
|
231
|
+
if (routeCache === undefined)
|
|
232
|
+
return
|
|
233
|
+
await runWithAppContext(deps.serverAppCtx, async () => {
|
|
234
|
+
const bgReq = new Request(url.href, { method: 'GET' })
|
|
235
|
+
const bgReqId = deps.resolveRequestId(bgReq)
|
|
236
|
+
const { ctx, cookieStore } = makeRequestContext(bgReq, { ...params }, { trustProxy: deps.trustProxy, url, consent: deps.consent, requestId: bgReqId })
|
|
237
|
+
for (const rewrite of deps.rewrites)
|
|
238
|
+
rewrite(url.pathname, ctx)
|
|
239
|
+
await deps.actions.run(ctx, async () => {
|
|
240
|
+
let rendered: RenderedPageOutput | undefined
|
|
241
|
+
let nonCacheable = false
|
|
242
|
+
const res = await runChain(ctx, middlewares, async () => {
|
|
243
|
+
let data: unknown
|
|
244
|
+
if (route.entry.hasLoad && typeof route.mod.load === 'function') {
|
|
245
|
+
try {
|
|
246
|
+
data = await route.mod.load(ctx)
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
if (isNotFound(error)) {
|
|
250
|
+
nonCacheable = true
|
|
251
|
+
return new Response(null, { status: 404 })
|
|
252
|
+
}
|
|
253
|
+
throw error
|
|
254
|
+
}
|
|
255
|
+
if (isNotFound(data) || data instanceof Response) {
|
|
256
|
+
nonCacheable = true
|
|
257
|
+
return data instanceof Response ? data : new Response(null, { status: 404 })
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const pageProps: Record<string, unknown> = { params: ctx.params, locals: ctx.locals, url: ctx.url, ...(data !== undefined ? { data } : {}) }
|
|
261
|
+
rendered = await renderPageDocument(deps, route, data, pageProps, ctx, false)
|
|
262
|
+
return rendered.kind === 'html'
|
|
263
|
+
? new Response(null, { status: 200, headers: rendered.headers })
|
|
264
|
+
: rendered.response
|
|
265
|
+
})
|
|
266
|
+
if (!nonCacheable && rendered?.kind === 'html' && res.status === 200 && !cookieStore.hasChanges)
|
|
267
|
+
routeCache.set(cacheKey, rendered.html, withCacheControl(rendered.headers, cacheSpec.cacheControl), cacheSpec)
|
|
268
|
+
else
|
|
269
|
+
routeCache.delete(cacheKey)
|
|
270
|
+
})
|
|
271
|
+
})
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function runCompiledRouteLoad(
|
|
275
|
+
deps: CompiledRouteRendererDeps,
|
|
276
|
+
route: CompiledRoute,
|
|
277
|
+
ctx: RequestContext,
|
|
278
|
+
timing?: DevTiming,
|
|
279
|
+
): Promise<{ kind: 'response', response: Response } | { kind: 'data', data: unknown }> {
|
|
280
|
+
const { entry, mod } = route
|
|
281
|
+
let data: unknown
|
|
282
|
+
if (entry.hasLoad && typeof mod.load === 'function') {
|
|
283
|
+
const loadStart = startTimer(timing)
|
|
284
|
+
try {
|
|
285
|
+
data = await mod.load(ctx)
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
if (isNotFound(error))
|
|
289
|
+
return { kind: 'response', response: await deps.buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file) }
|
|
290
|
+
throw error
|
|
291
|
+
}
|
|
292
|
+
endTimer(timing, 'load', loadStart)
|
|
293
|
+
}
|
|
294
|
+
if (isNotFound(data))
|
|
295
|
+
return { kind: 'response', response: await deps.buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file) }
|
|
296
|
+
if (data instanceof Response)
|
|
297
|
+
return { kind: 'response', response: data }
|
|
298
|
+
return { kind: 'data', data }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function resolvePrerenderedOrApi(
|
|
302
|
+
deps: CompiledRouteRendererDeps,
|
|
303
|
+
route: CompiledRoute,
|
|
304
|
+
ctx: RequestContext,
|
|
305
|
+
isRegion: boolean,
|
|
306
|
+
staticPath?: string,
|
|
307
|
+
): Promise<Response | undefined> {
|
|
308
|
+
const { entry, mod } = route
|
|
309
|
+
if (isRead(ctx.request)) {
|
|
310
|
+
const pre = lookupPrerendered(deps.prerenderedMap, staticPath)
|
|
311
|
+
if (pre !== undefined && !isRegion && (ctx.request.method === 'HEAD' || !hasActionErrorCookie(ctx.request)))
|
|
312
|
+
return deps.serveFile(ctx.request, pre)
|
|
313
|
+
if (pre === undefined && entry.prerender === true && entry.prerendered !== undefined && route.dynamic)
|
|
314
|
+
return deps.buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file)
|
|
315
|
+
}
|
|
316
|
+
const method = ctx.request.method.toUpperCase()
|
|
317
|
+
const methodHandler = routeMethodHandler(mod, method)
|
|
318
|
+
if (methodHandler !== undefined)
|
|
319
|
+
return await methodHandler(ctx)
|
|
320
|
+
if (method === 'HEAD' && typeof mod.GET === 'function')
|
|
321
|
+
return stripHeadBody(await mod.GET(ctx))
|
|
322
|
+
return undefined
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
|
|
326
|
+
return async function renderCompiledRoute(
|
|
327
|
+
route: CompiledRoute,
|
|
328
|
+
ctx: RequestContext,
|
|
329
|
+
cookieStore: CookieStore,
|
|
330
|
+
disableTimeout?: () => void,
|
|
331
|
+
staticPath?: string,
|
|
332
|
+
timing?: DevTiming,
|
|
333
|
+
middlewares: readonly Middleware[] = route.middlewares,
|
|
334
|
+
): Promise<Response> {
|
|
335
|
+
const { entry, mod, doc } = route
|
|
336
|
+
const isRegion = hasRegionHeader(ctx.request)
|
|
337
|
+
|
|
338
|
+
const early = await resolvePrerenderedOrApi(deps, route, ctx, isRegion, staticPath)
|
|
339
|
+
if (early !== undefined)
|
|
340
|
+
return early
|
|
341
|
+
|
|
342
|
+
if (typeof mod.default !== 'function' || !isRead(ctx.request))
|
|
343
|
+
return methodNotAllowed(allowedMethodsHeader(mod))
|
|
344
|
+
if (isRegion && requestedRegion(ctx.request) === undefined)
|
|
345
|
+
return invalidRegionResponse(ctx.request)
|
|
346
|
+
|
|
347
|
+
const hasFlash = ctx.request.method === 'GET' && !isRegion && hasActionErrorCookie(ctx.request) && hydrateActionErrorFlash(ctx)
|
|
348
|
+
const cacheSpec = deps.routeCache !== undefined && !isRegion && !hasFlash && isCacheableRequest(ctx.request) ? entry.cache : undefined
|
|
349
|
+
const cacheKey = cacheSpec !== undefined ? routeCacheKey(ctx.url) : undefined
|
|
350
|
+
let inflight: PromiseWithResolvers<RouteCacheSingleflightResult | undefined> | undefined
|
|
351
|
+
if (cacheSpec !== undefined && cacheKey !== undefined && deps.routeCache !== undefined) {
|
|
352
|
+
const cached = serveCachedHit(
|
|
353
|
+
deps.routeCache,
|
|
354
|
+
cacheKey,
|
|
355
|
+
ctx.request,
|
|
356
|
+
ctx.requestId,
|
|
357
|
+
deps.compressCache,
|
|
358
|
+
() => revalidateCompiledRoute(deps, route, ctx.url, ctx.params, cacheKey, cacheSpec, middlewares),
|
|
359
|
+
error => deps.notifyError(error, ctx.request, 'route', ctx.requestId),
|
|
360
|
+
)
|
|
361
|
+
if (cached !== undefined)
|
|
362
|
+
return cached
|
|
363
|
+
const existing = deps.routeCache.getInflight(cacheKey)
|
|
364
|
+
if (existing !== undefined) {
|
|
365
|
+
const shared = await existing
|
|
366
|
+
if (shared !== undefined)
|
|
367
|
+
return deps.routeCache.respondMiss(shared.entry, shared.html, shared.headers, ctx.request, ctx.requestId, deps.compressCache)
|
|
368
|
+
}
|
|
369
|
+
else {
|
|
370
|
+
inflight = Promise.withResolvers<RouteCacheSingleflightResult | undefined>()
|
|
371
|
+
void inflight.promise.catch(() => undefined)
|
|
372
|
+
deps.routeCache.trackInflight(cacheKey, inflight.promise)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
try {
|
|
377
|
+
const loaded = await runCompiledRouteLoad(deps, route, ctx, timing)
|
|
378
|
+
if (loaded.kind === 'response')
|
|
379
|
+
return loaded.response
|
|
380
|
+
const pageProps: Record<string, unknown> = { params: ctx.params, locals: ctx.locals, url: ctx.url, ...(loaded.data !== undefined ? { data: loaded.data } : {}) }
|
|
381
|
+
|
|
382
|
+
if (isRegion) {
|
|
383
|
+
return respondRegion(
|
|
384
|
+
ctx.request, mod, pageProps, entry.path, deps.htmlHeaders,
|
|
385
|
+
rctx => deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx),
|
|
386
|
+
deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId),
|
|
387
|
+
deps.hasHtmlTransformers ? html => deps.applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined,
|
|
388
|
+
)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const rendered = await renderPageDocument(deps, route, loaded.data, pageProps, ctx, hasFlash, disableTimeout, timing)
|
|
392
|
+
if (rendered.kind === 'stream')
|
|
393
|
+
return rendered.response
|
|
394
|
+
if (cacheSpec !== undefined && cacheKey !== undefined && deps.routeCache !== undefined && !cookieStore.hasChanges) {
|
|
395
|
+
const cachedHeaders = withCacheControl(rendered.headers, cacheSpec.cacheControl)
|
|
396
|
+
const stored = deps.routeCache.set(cacheKey, rendered.html, cachedHeaders, cacheSpec)
|
|
397
|
+
inflight?.resolve({ entry: stored, html: rendered.html, headers: cachedHeaders })
|
|
398
|
+
return deps.routeCache.respondMiss(stored, rendered.html, cachedHeaders, ctx.request, ctx.requestId, deps.compressCache)
|
|
399
|
+
}
|
|
400
|
+
return compressedHtmlResponse(rendered.html, 200, rendered.headers, ctx.request, deps.compressCache)
|
|
401
|
+
}
|
|
402
|
+
catch (error) {
|
|
403
|
+
inflight?.reject(error)
|
|
404
|
+
throw error
|
|
405
|
+
}
|
|
406
|
+
finally {
|
|
407
|
+
inflight?.resolve(undefined)
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
package/src/server/router.ts
CHANGED
|
@@ -1,18 +1,23 @@
|
|
|
1
|
-
// File-based route matcher: static >
|
|
1
|
+
// File-based route matcher: static > matched param > param > optional > catch-all priority sorting + param extraction.
|
|
2
2
|
|
|
3
|
+
import type { ParamMatcher, ParamMatcherMap } from './param-matchers'
|
|
3
4
|
import type { RequestPath } from './request-path'
|
|
5
|
+
import { BUILTIN_PARAM_MATCHERS, parsePatternSegment } from './param-matchers'
|
|
4
6
|
import { decodeRequestPath } from './request-path'
|
|
5
7
|
|
|
6
8
|
const enum SegmentKind {
|
|
7
9
|
Static = 0,
|
|
8
10
|
Param = 1,
|
|
9
|
-
|
|
11
|
+
OptionalParam = 2,
|
|
12
|
+
CatchAll = 3,
|
|
10
13
|
}
|
|
11
14
|
|
|
12
15
|
interface CompiledSegment {
|
|
13
16
|
kind: SegmentKind
|
|
14
|
-
/** Exact literal for Static, parameter name for Param/CatchAll. */
|
|
17
|
+
/** Exact literal for Static, parameter name for Param/OptionalParam/CatchAll. */
|
|
15
18
|
value: string
|
|
19
|
+
matcherName?: string | undefined
|
|
20
|
+
matcher?: ParamMatcher | undefined
|
|
16
21
|
}
|
|
17
22
|
|
|
18
23
|
interface RoutePattern<T> {
|
|
@@ -20,31 +25,44 @@ interface RoutePattern<T> {
|
|
|
20
25
|
segments: CompiledSegment[]
|
|
21
26
|
isStatic: boolean
|
|
22
27
|
hasCatchAll: boolean
|
|
28
|
+
/** Number of optional segments omitted to produce this concrete match variant. */
|
|
29
|
+
omittedOptionals: number
|
|
30
|
+
/** The catch-all takes a segment holding an encoded separator, left encoded. */
|
|
31
|
+
encodedSlashes: boolean
|
|
23
32
|
data: T
|
|
24
33
|
}
|
|
25
34
|
|
|
35
|
+
export interface RouteOptions {
|
|
36
|
+
encodedSlashes?: boolean | undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
26
39
|
export interface RouteMatch<T> {
|
|
27
40
|
data: T
|
|
28
41
|
params: Record<string, string>
|
|
29
42
|
}
|
|
30
43
|
|
|
44
|
+
const MAX_OPTIONAL_SEGMENTS = 6
|
|
45
|
+
|
|
31
46
|
function normalizePath(path: string): string {
|
|
32
47
|
return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
33
48
|
}
|
|
34
49
|
|
|
35
50
|
/**
|
|
36
|
-
* Segment specificity rank:
|
|
37
|
-
*
|
|
38
|
-
*
|
|
51
|
+
* Segment specificity rank:
|
|
52
|
+
* Static (9) > SpecificMatchedParam (8) > SlugMatchedParam (7) > Param (6) > OptionalSpecificMatched (5) > OptionalSlugMatched (4) > OptionalParam (3) > End (2) > MatchedCatchAll (1) > CatchAll (0).
|
|
53
|
+
* Lexicographic comparison guarantees exact static > matched param > param > optional > catch-all for any shared prefix
|
|
54
|
+
* (e.g. `/docs/:slug` beats `/docs/:section/*rest`, `/docs/:a/:b` beats `/docs/*rest`, and `integer`/`uuid` beat `slug`).
|
|
39
55
|
*/
|
|
40
56
|
function segmentRank(seg: CompiledSegment | undefined): number {
|
|
41
57
|
if (seg === undefined)
|
|
42
|
-
return
|
|
58
|
+
return 2
|
|
43
59
|
if (seg.kind === SegmentKind.Static)
|
|
44
|
-
return
|
|
60
|
+
return 9
|
|
45
61
|
if (seg.kind === SegmentKind.Param)
|
|
46
|
-
return
|
|
47
|
-
|
|
62
|
+
return seg.matcherName === undefined ? 6 : (seg.matcherName === 'slug' ? 7 : 8)
|
|
63
|
+
if (seg.kind === SegmentKind.OptionalParam)
|
|
64
|
+
return seg.matcherName === undefined ? 3 : (seg.matcherName === 'slug' ? 4 : 5)
|
|
65
|
+
return seg.matcherName !== undefined ? 1 : 0
|
|
48
66
|
}
|
|
49
67
|
|
|
50
68
|
function compareRoutes<T>(a: RoutePattern<T>, b: RoutePattern<T>): number {
|
|
@@ -54,54 +72,112 @@ function compareRoutes<T>(a: RoutePattern<T>, b: RoutePattern<T>): number {
|
|
|
54
72
|
if (diff !== 0)
|
|
55
73
|
return diff
|
|
56
74
|
}
|
|
57
|
-
return
|
|
75
|
+
return a.omittedOptionals - b.omittedOptionals
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function toCompiledSegment(seg: string, matchers: ParamMatcherMap): CompiledSegment {
|
|
79
|
+
const parsed = parsePatternSegment(seg)
|
|
80
|
+
const matcher = parsed.matcherName !== undefined ? matchers[parsed.matcherName] : undefined
|
|
81
|
+
if (parsed.kind === 'catchall')
|
|
82
|
+
return { kind: SegmentKind.CatchAll, value: parsed.value, matcherName: parsed.matcherName, matcher }
|
|
83
|
+
if (parsed.kind === 'optional')
|
|
84
|
+
return { kind: SegmentKind.OptionalParam, value: parsed.value, matcherName: parsed.matcherName, matcher }
|
|
85
|
+
if (parsed.kind === 'param')
|
|
86
|
+
return { kind: SegmentKind.Param, value: parsed.value, matcherName: parsed.matcherName, matcher }
|
|
87
|
+
return { kind: SegmentKind.Static, value: parsed.value }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Expands optional segments into concrete flat variants (include-first, omit-second) so matching runs with zero recursion. */
|
|
91
|
+
function expandOptionalVariants(base: CompiledSegment[]): { segments: CompiledSegment[], omitted: number }[] {
|
|
92
|
+
const optIndexes: number[] = []
|
|
93
|
+
for (let i = 0; i < base.length; i++) {
|
|
94
|
+
if (base[i]!.kind === SegmentKind.OptionalParam)
|
|
95
|
+
optIndexes.push(i)
|
|
96
|
+
}
|
|
97
|
+
if (optIndexes.length === 0)
|
|
98
|
+
return [{ segments: base, omitted: 0 }]
|
|
99
|
+
if (optIndexes.length > MAX_OPTIONAL_SEGMENTS)
|
|
100
|
+
throw new Error(`prunelle: route pattern has ${optIndexes.length} optional segments (maximum supported is ${MAX_OPTIONAL_SEGMENTS}).`)
|
|
101
|
+
|
|
102
|
+
const variants: { segments: CompiledSegment[], omitted: number }[] = []
|
|
103
|
+
const build = (optPos: number, omittedSet: Set<number>): void => {
|
|
104
|
+
if (optPos === optIndexes.length) {
|
|
105
|
+
const segments = omittedSet.size === 0 ? base : base.filter((_, idx) => !omittedSet.has(idx))
|
|
106
|
+
variants.push({ segments, omitted: omittedSet.size })
|
|
107
|
+
return
|
|
108
|
+
}
|
|
109
|
+
build(optPos + 1, omittedSet)
|
|
110
|
+
omittedSet.add(optIndexes[optPos]!)
|
|
111
|
+
build(optPos + 1, omittedSet)
|
|
112
|
+
omittedSet.delete(optIndexes[optPos]!)
|
|
113
|
+
}
|
|
114
|
+
build(0, new Set())
|
|
115
|
+
return variants
|
|
58
116
|
}
|
|
59
117
|
|
|
60
|
-
function
|
|
118
|
+
function compileRoutePatterns<T>(path: string, data: T, matchers: ParamMatcherMap, options?: RouteOptions): RoutePattern<T>[] {
|
|
61
119
|
const norm = normalizePath(path)
|
|
62
120
|
const clean = norm === '/' ? '' : norm.replace(/^\/|\/$/g, '')
|
|
63
121
|
const rawSegments = clean === '' ? [] : clean.split('/')
|
|
64
|
-
const
|
|
122
|
+
const baseSegments: CompiledSegment[] = []
|
|
65
123
|
let isStatic = true
|
|
66
124
|
let hasCatchAll = false
|
|
67
125
|
|
|
68
126
|
for (let i = 0; i < rawSegments.length; i++) {
|
|
69
|
-
const
|
|
70
|
-
if (
|
|
127
|
+
const compiled = toCompiledSegment(rawSegments[i]!, matchers)
|
|
128
|
+
if (compiled.kind !== SegmentKind.Static)
|
|
71
129
|
isStatic = false
|
|
130
|
+
if (compiled.kind === SegmentKind.CatchAll)
|
|
72
131
|
hasCatchAll = true
|
|
73
|
-
|
|
74
|
-
}
|
|
75
|
-
else if (seg.startsWith(':')) {
|
|
76
|
-
isStatic = false
|
|
77
|
-
segments.push({ kind: SegmentKind.Param, value: seg.slice(1) })
|
|
78
|
-
}
|
|
79
|
-
else {
|
|
80
|
-
segments.push({ kind: SegmentKind.Static, value: seg })
|
|
81
|
-
}
|
|
132
|
+
baseSegments.push(compiled)
|
|
82
133
|
}
|
|
83
134
|
|
|
84
|
-
|
|
135
|
+
const encodedSlashes = options?.encodedSlashes === true
|
|
136
|
+
if (isStatic)
|
|
137
|
+
return [{ path: norm, segments: baseSegments, isStatic: true, hasCatchAll: false, omittedOptionals: 0, encodedSlashes, data }]
|
|
138
|
+
|
|
139
|
+
return expandOptionalVariants(baseSegments).map(({ segments, omitted }) => ({
|
|
140
|
+
path: norm,
|
|
141
|
+
segments,
|
|
142
|
+
isStatic: false,
|
|
143
|
+
hasCatchAll,
|
|
144
|
+
omittedOptionals: omitted,
|
|
145
|
+
encodedSlashes,
|
|
146
|
+
data,
|
|
147
|
+
}))
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function segmentMatchesParam(seg: CompiledSegment, value: string): boolean {
|
|
151
|
+
if (seg.matcherName !== undefined)
|
|
152
|
+
return seg.matcher !== undefined && seg.matcher(value)
|
|
153
|
+
return true
|
|
85
154
|
}
|
|
86
155
|
|
|
87
156
|
export class Router<T> {
|
|
88
157
|
readonly #staticRoutes = new Map<string, T>()
|
|
89
158
|
readonly #dynamicRoutes: RoutePattern<T>[] = []
|
|
159
|
+
readonly #matchers: ParamMatcherMap
|
|
90
160
|
#sorted = true
|
|
91
161
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
162
|
+
constructor(matchers: ParamMatcherMap = BUILTIN_PARAM_MATCHERS) {
|
|
163
|
+
this.#matchers = matchers
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Adds the route at `path`, or replaces the one already there. */
|
|
167
|
+
add(path: string, data: T, options?: RouteOptions): void {
|
|
168
|
+
const compiled = compileRoutePatterns(path, data, this.#matchers, options)
|
|
169
|
+
const first = compiled[0]!
|
|
170
|
+
if (first.isStatic) {
|
|
171
|
+
this.#staticRoutes.set(first.path, data)
|
|
172
|
+
return
|
|
96
173
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
this.#dynamicRoutes[existing] = compiled
|
|
101
|
-
else
|
|
102
|
-
this.#dynamicRoutes.push(compiled)
|
|
103
|
-
this.#sorted = false
|
|
174
|
+
for (let i = this.#dynamicRoutes.length - 1; i >= 0; i--) {
|
|
175
|
+
if (this.#dynamicRoutes[i]!.path === first.path)
|
|
176
|
+
this.#dynamicRoutes.splice(i, 1)
|
|
104
177
|
}
|
|
178
|
+
for (const pattern of compiled)
|
|
179
|
+
this.#dynamicRoutes.push(pattern)
|
|
180
|
+
this.#sorted = false
|
|
105
181
|
}
|
|
106
182
|
|
|
107
183
|
/** Matches a decoded request path; a string is a URL pathname, decoded first. */
|
|
@@ -127,7 +203,8 @@ export class Router<T> {
|
|
|
127
203
|
|
|
128
204
|
const parts = path.segments
|
|
129
205
|
// A param never receives a separator, a NUL or a dot segment, encoded or not: joined into a path, it would walk out of the folder it names.
|
|
130
|
-
const
|
|
206
|
+
const dotSegment = (k: number): boolean => parts[k] === '.' || parts[k] === '..'
|
|
207
|
+
const refused = (k: number): boolean => path.encoded?.has(k) === true || dotSegment(k)
|
|
131
208
|
|
|
132
209
|
for (let i = 0; i < dynLen; i++) {
|
|
133
210
|
const route = this.#dynamicRoutes[i]!
|
|
@@ -143,12 +220,20 @@ export class Router<T> {
|
|
|
143
220
|
const seg = segs[j]!
|
|
144
221
|
if (seg.kind === SegmentKind.CatchAll) {
|
|
145
222
|
for (let k = j; k < parts.length; k++) {
|
|
146
|
-
if (refused(k))
|
|
223
|
+
if ((route.encodedSlashes ? dotSegment(k) : refused(k)) || !segmentMatchesParam(seg, parts[k]!)) {
|
|
147
224
|
matched = false
|
|
225
|
+
break
|
|
226
|
+
}
|
|
148
227
|
}
|
|
149
228
|
break
|
|
150
229
|
}
|
|
151
|
-
if (seg.kind === SegmentKind.
|
|
230
|
+
if (seg.kind === SegmentKind.Static) {
|
|
231
|
+
if (seg.value !== parts[j] || path.encoded?.has(j) === true) {
|
|
232
|
+
matched = false
|
|
233
|
+
break
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else if (refused(j) || !segmentMatchesParam(seg, parts[j]!)) {
|
|
152
237
|
matched = false
|
|
153
238
|
break
|
|
154
239
|
}
|
|
@@ -165,7 +250,7 @@ export class Router<T> {
|
|
|
165
250
|
params[seg.value] = parts.slice(j).join('/')
|
|
166
251
|
break
|
|
167
252
|
}
|
|
168
|
-
if (seg.kind === SegmentKind.Param)
|
|
253
|
+
if (seg.kind === SegmentKind.Param || seg.kind === SegmentKind.OptionalParam)
|
|
169
254
|
params[seg.value] = parts[j]!
|
|
170
255
|
}
|
|
171
256
|
return { data: route.data, params }
|