prunelle 0.0.0-stage → 0.7.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/LICENSE +21 -0
- package/llms.txt +245 -0
- package/package.json +62 -4
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +43 -0
- package/src/build/bundle.ts +661 -0
- package/src/build/byte-size.ts +11 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +175 -0
- package/src/build/client-prune.ts +168 -0
- package/src/build/compile.ts +130 -0
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +171 -0
- package/src/build/first-load.ts +235 -0
- package/src/build/graph.ts +237 -0
- package/src/build/index.ts +678 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +452 -0
- package/src/build/manifest.ts +204 -0
- package/src/build/output.ts +81 -0
- package/src/build/plugin-host.ts +294 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +288 -0
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +290 -0
- package/src/build/resolve.ts +52 -0
- package/src/build/routes.ts +342 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +209 -0
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +409 -0
- package/src/cli/commands.ts +372 -0
- package/src/cli/docs.ts +403 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +406 -0
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +52 -0
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +367 -0
- package/src/compiler/analyze.ts +651 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +250 -0
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +653 -0
- package/src/compiler/data-keys.ts +302 -0
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +452 -0
- package/src/compiler/dom.ts +641 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +587 -0
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +520 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +511 -0
- package/src/compiler/scope.ts +635 -0
- package/src/compiler/server-only.ts +365 -0
- package/src/compiler/shared.ts +397 -0
- package/src/compiler/signal-reads.ts +246 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +69 -0
- package/src/compiler/ssr.ts +525 -0
- package/src/context.ts +199 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +268 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +24 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +159 -0
- package/src/dev/supervisor.ts +212 -0
- package/src/dev/watchers.ts +276 -0
- package/src/dom/action.ts +187 -0
- package/src/dom/attrs.ts +84 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +579 -0
- package/src/dom/index.ts +329 -0
- package/src/dom/island.ts +318 -0
- package/src/dom/loop.ts +484 -0
- package/src/dom/revive.ts +36 -0
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +92 -0
- package/src/plugins/context.ts +109 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +90 -0
- package/src/plugins/order.ts +148 -0
- package/src/plugins/public.ts +15 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +119 -0
- package/src/plugins/types.ts +278 -0
- package/src/reactivity/graph.ts +259 -0
- package/src/reactivity/index.ts +541 -0
- package/src/reactivity/selector.ts +78 -0
- package/src/reactivity/store.ts +252 -0
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +511 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +168 -0
- package/src/server/compress.ts +646 -0
- package/src/server/consent.ts +290 -0
- package/src/server/cookies.ts +153 -0
- package/src/server/document.ts +286 -0
- package/src/server/env.ts +47 -0
- package/src/server/errors.ts +396 -0
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +588 -0
- package/src/server/index.ts +615 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +131 -0
- package/src/server/page.ts +122 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +267 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +20 -0
- package/src/server/rate-limit.ts +199 -0
- package/src/server/region.ts +96 -0
- package/src/server/request-body.ts +27 -0
- package/src/server/request-path.ts +73 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +424 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +388 -0
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +550 -0
- package/src/server/serve-handlers.ts +93 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +104 -0
- package/src/server/start.ts +143 -0
- package/src/server/static-dir.ts +246 -0
- package/src/server/stream.ts +233 -0
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +399 -0
- package/src/ssr/index.ts +624 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +192 -0
- package/src/style.ts +96 -0
- package/src/test/browser.ts +201 -0
- package/src/test/index.ts +262 -0
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +8 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +22 -0
- package/templates/_shared/tsconfig.json +25 -0
- package/templates/app/.env.example +8 -0
- package/templates/app/package.json +22 -0
- package/templates/app/prunelle.config.ts +13 -0
- package/templates/app/src/auth.ts +12 -0
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +40 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +47 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +53 -0
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +14 -0
- package/templates/app/tests/app.test.ts +73 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/package.json +22 -0
- package/templates/blog/prunelle.config.ts +23 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +25 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +33 -0
- package/templates/blog/src/styles/app.css +15 -0
- package/templates/fullstack/package.json +19 -0
- package/templates/fullstack/prunelle.config.ts +6 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +28 -0
- package/templates/fullstack/src/routes/_layout.tsx +18 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +39 -0
- package/templates/fullstack/tests/app.test.ts +37 -0
- package/templates/minimal/package.json +19 -0
- package/templates/minimal/prunelle.config.ts +6 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +18 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +32 -0
- package/ts-plugin.cjs +4277 -0
- package/README.md +0 -3
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
// Request pathname decoding, manifest prefix/ancestor middleware lookup, 405 helper, and fast static page handler.
|
|
2
|
+
|
|
3
|
+
import type { ActionManifestEntry, BuildManifest, RouteManifestEntry } from '../build/index'
|
|
4
|
+
import type { Html, HydrateStrategy } from '../jsx-runtime'
|
|
5
|
+
import type { DocumentOptions } from '../ssr/index'
|
|
6
|
+
import type { RenderContext } from '../ssr/context'
|
|
7
|
+
import type { ActionRegistry } from './action-registry'
|
|
8
|
+
import type { CompressionCache } from './compress'
|
|
9
|
+
import type { NormalizedConsentConfig } from './consent'
|
|
10
|
+
import type { CookieStore } from './cookies'
|
|
11
|
+
import type { HtmlHeaders } from './document'
|
|
12
|
+
import type { NotifyError } from './errors'
|
|
13
|
+
import type { DevTiming, RequestIdResolver } from './health'
|
|
14
|
+
import type { DeniedInfo, Middleware, RequestContext } from './http'
|
|
15
|
+
import type { PrunelleLocals } from './index'
|
|
16
|
+
import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
|
|
17
|
+
import type { ParamMatcherMap } from './param-matchers'
|
|
18
|
+
import type { RequestPath } from './request-path'
|
|
19
|
+
import type { TrustProxy } from './security'
|
|
20
|
+
import { createRenderContext, runWithRenderContext } from '../ssr/context'
|
|
21
|
+
import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
|
|
22
|
+
import { keepScrollTag } from '../ssr/navigation'
|
|
23
|
+
import { compressedHtmlResponse, maybeCompressResponse } from './compress'
|
|
24
|
+
import { headTagStyleHashes, mergeStyleHashes } from './document'
|
|
25
|
+
import { createTiming, endTimer, finishRenderTiming, formatServerTiming, resolveFallbackRequestId, startTimer } from './health'
|
|
26
|
+
import { acceptsHtml, getDeniedInfo, isNotFound, makeRequestContext } from './http'
|
|
27
|
+
import { pickPageIslandProps } from './page'
|
|
28
|
+
import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
|
|
29
|
+
import { withRegionVary } from './region'
|
|
30
|
+
import { decodeRequestPath, pathPrefix } from './request-path'
|
|
31
|
+
import { Router } from './router'
|
|
32
|
+
import { styleHashesOf } from './security'
|
|
33
|
+
|
|
34
|
+
const MIDDLEWARE_BASENAME_RE = /(?:^|\/)_middleware\.js$/
|
|
35
|
+
const ROUTE_GROUP_RE = /^\([^/()]+\)$/
|
|
36
|
+
const OPTIONAL_PARAM_SEG_RE = /^\[\[([^\[\]]+)\]\]$/
|
|
37
|
+
const CATCH_ALL_SEG_RE = /^\[\.\.\.([^\[\]]+)\]$/
|
|
38
|
+
const PARAM_SEG_RE = /^\[([^\[\]]+)\]$/
|
|
39
|
+
const CATCH_ALL_BRACKET_RE = /\[\.\.\.([^\]]+)\]/g
|
|
40
|
+
const PARAM_BRACKET_RE = /\[([^\]]+)\]/g
|
|
41
|
+
|
|
42
|
+
export type FastHandler = (req: Request, remoteIp?: string, url?: URL, requestId?: string) => Response | Promise<Response>
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
export function methodNotAllowed(allow: string): Response {
|
|
46
|
+
return new Response('Method Not Allowed', allow ? { status: 405, headers: { allow } } : { status: 405 })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Encodes a static route/asset path for Bun.serve's `routes` table (which requires ASCII keys and treats `*` as a wildcard). */
|
|
50
|
+
export function toBunRouteKey(path: string): string | undefined {
|
|
51
|
+
if (path.includes('*'))
|
|
52
|
+
return undefined
|
|
53
|
+
return path.split('/').map((seg) => {
|
|
54
|
+
if (seg.includes('%')) {
|
|
55
|
+
const decoded = decodeRequestPath(`/${seg}`)
|
|
56
|
+
if (decoded?.staticPath !== undefined)
|
|
57
|
+
return encodeURIComponent(decoded.staticPath.slice(1))
|
|
58
|
+
}
|
|
59
|
+
return encodeURIComponent(seg)
|
|
60
|
+
}).join('/')
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function dirnamePrefix(file: string): string {
|
|
64
|
+
const slash = file.lastIndexOf('/')
|
|
65
|
+
return slash === -1 ? '' : file.slice(0, slash + 1)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function convertDirSegment(seg: string): string {
|
|
69
|
+
const opt = OPTIONAL_PARAM_SEG_RE.exec(seg)
|
|
70
|
+
if (opt !== null)
|
|
71
|
+
return `:${opt[1]}?`
|
|
72
|
+
const catchAll = CATCH_ALL_SEG_RE.exec(seg)
|
|
73
|
+
if (catchAll !== null)
|
|
74
|
+
return `*${catchAll[1]}`
|
|
75
|
+
const param = PARAM_SEG_RE.exec(seg)
|
|
76
|
+
if (param !== null)
|
|
77
|
+
return `:${param[1]}`
|
|
78
|
+
return seg.replace(CATCH_ALL_BRACKET_RE, '*$1').replace(PARAM_BRACKET_RE, ':$1')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function dirToRoutePattern(relDir: string): string {
|
|
82
|
+
if (relDir === '')
|
|
83
|
+
return '/'
|
|
84
|
+
const parts = relDir.split('/').filter(p => p !== '' && !ROUTE_GROUP_RE.test(p))
|
|
85
|
+
if (parts.length === 0)
|
|
86
|
+
return '/'
|
|
87
|
+
return `/${parts.map(convertDirSegment).join('/')}`
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Infers the compiled module prefix for files under `routesDir` (e.g. `'server/'` or `'server/src/routes/'`). */
|
|
91
|
+
export function inferRoutesServerPrefix(manifest: BuildManifest): string {
|
|
92
|
+
const rootSpecial = manifest.rootLayoutFile ?? manifest.errorFile ?? manifest.notFoundFile
|
|
93
|
+
if (rootSpecial !== undefined)
|
|
94
|
+
return dirnamePrefix(rootSpecial)
|
|
95
|
+
|
|
96
|
+
for (const route of manifest.routes) {
|
|
97
|
+
const fileParts = route.file.split('/')
|
|
98
|
+
const pathSegs = route.path === '/' ? [] : route.path.replace(/^\/|\/$/g, '').split('/')
|
|
99
|
+
const isIndex = fileParts[fileParts.length - 1] === 'index.js'
|
|
100
|
+
let remaining = pathSegs.length + (isIndex ? 1 : 0)
|
|
101
|
+
let idx = fileParts.length
|
|
102
|
+
while (idx > 0 && remaining > 0) {
|
|
103
|
+
idx--
|
|
104
|
+
if (!ROUTE_GROUP_RE.test(fileParts[idx]!))
|
|
105
|
+
remaining--
|
|
106
|
+
}
|
|
107
|
+
while (idx > 0 && ROUTE_GROUP_RE.test(fileParts[idx - 1]!))
|
|
108
|
+
idx--
|
|
109
|
+
if (remaining === 0) {
|
|
110
|
+
const prefixParts = fileParts.slice(0, idx)
|
|
111
|
+
return prefixParts.length === 0 ? '' : `${prefixParts.join('/')}/`
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
for (const entry of manifest.actions) {
|
|
116
|
+
if (entry.file.startsWith('server/src/routes/'))
|
|
117
|
+
return 'server/src/routes/'
|
|
118
|
+
}
|
|
119
|
+
return 'server/'
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Derives an action's route directory prefix (e.g. `'/admin'`) when declared under `routesDir`. */
|
|
123
|
+
export function actionRoutePrefix(
|
|
124
|
+
entry: ActionManifestEntry,
|
|
125
|
+
routesPrefix: string,
|
|
126
|
+
routePathByFile: ReadonlyMap<string, string>,
|
|
127
|
+
): string | undefined {
|
|
128
|
+
const exactRoutePath = routePathByFile.get(entry.file)
|
|
129
|
+
if (exactRoutePath !== undefined)
|
|
130
|
+
return exactRoutePath
|
|
131
|
+
if (!entry.file.startsWith(routesPrefix))
|
|
132
|
+
return undefined
|
|
133
|
+
const rel = entry.file.slice(routesPrefix.length)
|
|
134
|
+
const slash = rel.lastIndexOf('/')
|
|
135
|
+
const relDir = slash === -1 ? '' : rel.slice(0, slash)
|
|
136
|
+
return dirToRoutePattern(relDir)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface AncestorMiddlewareMatch {
|
|
140
|
+
middlewares: Middleware[]
|
|
141
|
+
params: Record<string, string>
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Builds a lookup returning the outermost-to-innermost `_middleware.ts` chain for any unmatched pathname. */
|
|
145
|
+
export function createAncestorMiddlewareLookup(
|
|
146
|
+
manifest: BuildManifest,
|
|
147
|
+
modules: Record<string, unknown>,
|
|
148
|
+
routesPrefix: string,
|
|
149
|
+
paramMatchers: ParamMatcherMap = BUILTIN_PARAM_MATCHERS,
|
|
150
|
+
): (path: RequestPath) => AncestorMiddlewareMatch | undefined {
|
|
151
|
+
const byPattern = new Map<string, Middleware[]>()
|
|
152
|
+
const seenModules = new Set<string>()
|
|
153
|
+
|
|
154
|
+
const addMiddlewareModule = (modKey: string): void => {
|
|
155
|
+
if (seenModules.has(modKey))
|
|
156
|
+
return
|
|
157
|
+
seenModules.add(modKey)
|
|
158
|
+
if (!modKey.startsWith(routesPrefix) || !MIDDLEWARE_BASENAME_RE.test(modKey))
|
|
159
|
+
return
|
|
160
|
+
const mod = modules[modKey] as LoadedMiddlewareModule | undefined
|
|
161
|
+
if (typeof mod?.default !== 'function')
|
|
162
|
+
return
|
|
163
|
+
const rel = modKey.slice(routesPrefix.length)
|
|
164
|
+
const relDir = rel.replace(MIDDLEWARE_BASENAME_RE, '')
|
|
165
|
+
// A `(group)` middleware only applies to routes/actions inside that group, never to unrelated unmatched URLs.
|
|
166
|
+
if (relDir !== '' && relDir.split('/').some(p => ROUTE_GROUP_RE.test(p)))
|
|
167
|
+
return
|
|
168
|
+
const pattern = dirToRoutePattern(relDir)
|
|
169
|
+
let list = byPattern.get(pattern)
|
|
170
|
+
if (list === undefined) {
|
|
171
|
+
list = []
|
|
172
|
+
byPattern.set(pattern, list)
|
|
173
|
+
}
|
|
174
|
+
list.push(mod.default)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
for (const route of manifest.routes) {
|
|
178
|
+
for (const mwKey of route.middlewares)
|
|
179
|
+
addMiddlewareModule(mwKey)
|
|
180
|
+
}
|
|
181
|
+
for (const act of manifest.actions) {
|
|
182
|
+
for (const mwKey of act.middlewares)
|
|
183
|
+
addMiddlewareModule(mwKey)
|
|
184
|
+
}
|
|
185
|
+
for (const modKey of Object.keys(modules)) {
|
|
186
|
+
if (modKey.startsWith(routesPrefix) && MIDDLEWARE_BASENAME_RE.test(modKey))
|
|
187
|
+
addMiddlewareModule(modKey)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (byPattern.size === 0)
|
|
191
|
+
return () => undefined
|
|
192
|
+
|
|
193
|
+
const dirRouter = new Router<Middleware[]>(paramMatchers)
|
|
194
|
+
for (const [pattern, list] of byPattern)
|
|
195
|
+
dirRouter.add(pattern, list)
|
|
196
|
+
|
|
197
|
+
return (path: RequestPath): AncestorMiddlewareMatch | undefined => {
|
|
198
|
+
const middlewares: Middleware[] = []
|
|
199
|
+
const params: Record<string, string> = {}
|
|
200
|
+
|
|
201
|
+
for (let i = 0; i <= path.segments.length; i++) {
|
|
202
|
+
const matched = dirRouter.match(pathPrefix(path, i))
|
|
203
|
+
if (matched !== undefined) {
|
|
204
|
+
for (const mw of matched.data)
|
|
205
|
+
middlewares.push(mw)
|
|
206
|
+
Object.assign(params, matched.params)
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return middlewares.length > 0 ? { middlewares, params } : undefined
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export interface FastStaticPageOptions {
|
|
215
|
+
entry: RouteManifestEntry
|
|
216
|
+
mod: LoadedPageModule
|
|
217
|
+
layouts: LoadedLayoutModule[]
|
|
218
|
+
doc: DocumentOptions
|
|
219
|
+
/** The prop revivers, preloaded by the responses whose island props need them. */
|
|
220
|
+
reviveScript: string | undefined
|
|
221
|
+
hasIslands: boolean
|
|
222
|
+
hasLoad: boolean
|
|
223
|
+
trustProxy: TrustProxy
|
|
224
|
+
consent?: NormalizedConsentConfig | undefined
|
|
225
|
+
htmlHeaders: HtmlHeaders
|
|
226
|
+
compressCache: CompressionCache | undefined
|
|
227
|
+
actions: ActionRegistry
|
|
228
|
+
buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
|
|
229
|
+
renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
|
|
230
|
+
renderDenied?: ((denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>) | undefined
|
|
231
|
+
notifyError: NotifyError
|
|
232
|
+
finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
|
|
233
|
+
withHsts: (res: Response, request: Request) => Response
|
|
234
|
+
dev?: boolean | undefined
|
|
235
|
+
resolveRequestId?: RequestIdResolver | undefined
|
|
236
|
+
httpsSite?: boolean | undefined
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function buildFastDocShell(doc: DocumentOptions, eagerChunks: string[], reviveScript: string | undefined, hasIslands: boolean): { docPrefix: string, revivingPrefix: string, docSuffix: string } {
|
|
240
|
+
const shellAround = (preloadChunks: string[]): [string, string] => {
|
|
241
|
+
const shell = renderDocument({ ...doc, body: '\0', preloadChunks, hasIslands })
|
|
242
|
+
const splitAt = shell.indexOf('\0')
|
|
243
|
+
return [shell.slice(0, splitAt), shell.slice(splitAt + 1)]
|
|
244
|
+
}
|
|
245
|
+
const [docPrefix, docSuffix] = shellAround(eagerChunks)
|
|
246
|
+
const revivingPrefix = reviveScript === undefined ? docPrefix : shellAround([...eagerChunks, reviveScript])[0]
|
|
247
|
+
return { docPrefix, revivingPrefix, docSuffix }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
|
|
251
|
+
export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
|
|
252
|
+
const { entry, mod, layouts, doc, reviveScript, hasIslands, hasLoad, trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts } = options
|
|
253
|
+
const isDev = options.dev === true
|
|
254
|
+
const getRequestId: RequestIdResolver = options.resolveRequestId ?? (req => resolveFallbackRequestId(req, trustProxy))
|
|
255
|
+
const { docPrefix, revivingPrefix, docSuffix } = buildFastDocShell(doc, entry.eagerIslandChunks ?? entry.islandChunks, reviveScript, hasIslands)
|
|
256
|
+
const headStyleHashes = headTagStyleHashes(doc.headTags)
|
|
257
|
+
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)
|
|
261
|
+
return renderError(error, cookieStore, url, request, ctx, entry.file)
|
|
262
|
+
}
|
|
263
|
+
const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response => {
|
|
264
|
+
const html = (rctx.revives ? revivingPrefix : docPrefix) + body + keepScrollTag(body) + docSuffix
|
|
265
|
+
const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
|
|
266
|
+
const headers = withRegionVary(htmlHeaders(hasIslands, false, true, styleHashes), rctx.regionNames.size > 0)
|
|
267
|
+
const st = timing !== undefined ? finishRenderTiming(timing) : undefined
|
|
268
|
+
const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
|
|
269
|
+
res.headers.set('x-request-id', ctx.requestId)
|
|
270
|
+
if (st !== undefined)
|
|
271
|
+
res.headers.set('server-timing', st)
|
|
272
|
+
return cookieStore.hasChanges ? finish(res, request, cookieStore, ctx.requestId, st) : withHsts(res, request)
|
|
273
|
+
}
|
|
274
|
+
const layoutProps = (inner: string, url: URL, locals: PrunelleLocals) => ({ children: raw(inner), url, params: {}, locals })
|
|
275
|
+
|
|
276
|
+
const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
|
|
277
|
+
try {
|
|
278
|
+
return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore, ctx, timing)
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
|
|
286
|
+
if (layouts.length === 0)
|
|
287
|
+
return respondHtml(inner, request, rctx, cookieStore, ctx, timing)
|
|
288
|
+
if (singleLayout !== undefined) {
|
|
289
|
+
const wrapped = singleLayout.default(layoutProps(inner, url, locals))
|
|
290
|
+
if (wrapped instanceof Promise)
|
|
291
|
+
return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx, timing)
|
|
292
|
+
return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore, ctx, timing)
|
|
293
|
+
}
|
|
294
|
+
return (async () => {
|
|
295
|
+
try {
|
|
296
|
+
let cur = inner
|
|
297
|
+
for (let i = layouts.length - 1; i >= 0; i--)
|
|
298
|
+
cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
|
|
299
|
+
return respondHtml(cur, request, rctx, cookieStore, ctx, timing)
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
303
|
+
}
|
|
304
|
+
})()
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
|
|
308
|
+
try {
|
|
309
|
+
return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
|
|
310
|
+
}
|
|
311
|
+
catch (error) {
|
|
312
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
|
|
317
|
+
if (timing !== undefined)
|
|
318
|
+
timing.render = performance.now()
|
|
319
|
+
const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
|
|
320
|
+
if (entry.isIsland && entry.islandChunk !== undefined) {
|
|
321
|
+
return wrapLayouts(ssrIsland(
|
|
322
|
+
entry.islandChunk,
|
|
323
|
+
() => ssrChild(mod.default!(pageProps) as Html),
|
|
324
|
+
pickPageIslandProps(data, entry, mod),
|
|
325
|
+
entry.islandHydrate as HydrateStrategy | undefined,
|
|
326
|
+
true,
|
|
327
|
+
mod.default!.name,
|
|
328
|
+
), request, url, locals, rctx, cookieStore, ctx, timing)
|
|
329
|
+
}
|
|
330
|
+
const rendered = mod.default!(pageProps)
|
|
331
|
+
if (rendered instanceof Promise)
|
|
332
|
+
return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx, timing)
|
|
333
|
+
return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return (request, remoteIp, url = new URL(request.url), requestId?: string) => {
|
|
337
|
+
const reqId = requestId ?? getRequestId(request)
|
|
338
|
+
const timing = createTiming(isDev)
|
|
339
|
+
const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite: options.httpsSite, remoteIp, url, consent, requestId: reqId })
|
|
340
|
+
if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
|
|
341
|
+
return actions.run(ctx, async () => {
|
|
342
|
+
try {
|
|
343
|
+
return finish(await mod.HEAD!(ctx), request, cookieStore, reqId, formatServerTiming(timing))
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
347
|
+
}
|
|
348
|
+
})
|
|
349
|
+
}
|
|
350
|
+
const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route', reqId))
|
|
351
|
+
try {
|
|
352
|
+
if (!hasLoad)
|
|
353
|
+
return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx, timing)))
|
|
354
|
+
|
|
355
|
+
return actions.run(ctx, async () => {
|
|
356
|
+
let loaded: unknown
|
|
357
|
+
const loadStart = startTimer(timing)
|
|
358
|
+
try {
|
|
359
|
+
loaded = await mod.load!(ctx)
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
if (isNotFound(error))
|
|
363
|
+
return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
|
|
364
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
365
|
+
}
|
|
366
|
+
endTimer(timing, 'load', loadStart)
|
|
367
|
+
if (isNotFound(loaded))
|
|
368
|
+
return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
|
|
369
|
+
if (loaded instanceof Response) {
|
|
370
|
+
const denied = getDeniedInfo(loaded)
|
|
371
|
+
const out = denied !== undefined && renderDenied !== undefined && acceptsHtml(request)
|
|
372
|
+
? await renderDenied(denied, url, request, ctx, entry.file)
|
|
373
|
+
: loaded
|
|
374
|
+
return finish(await maybeCompressResponse(out, request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
|
|
375
|
+
}
|
|
376
|
+
try {
|
|
377
|
+
return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx, timing))
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
381
|
+
}
|
|
382
|
+
})
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
return fail(error, request, url, cookieStore, ctx)
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// HTML allow-list sanitizer for rendered Markdown, shared by @prunellejs/content and the @prunellejs/cms preview: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
|
|
2
|
+
|
|
3
|
+
const DROP_CONTENT_TAGS = new Set([
|
|
4
|
+
'script',
|
|
5
|
+
'style',
|
|
6
|
+
'iframe',
|
|
7
|
+
'object',
|
|
8
|
+
'applet',
|
|
9
|
+
'noscript',
|
|
10
|
+
'template',
|
|
11
|
+
])
|
|
12
|
+
|
|
13
|
+
const ALLOWED_MD_TAGS = new Set([
|
|
14
|
+
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
|
15
|
+
'p', 'br', 'hr', 'div', 'span', 'section', 'article', 'aside', 'header', 'footer', 'nav', 'main',
|
|
16
|
+
'a', 'img', 'picture', 'source',
|
|
17
|
+
'pre', 'code', 'kbd', 'samp', 'var',
|
|
18
|
+
'ul', 'ol', 'li', 'dl', 'dt', 'dd',
|
|
19
|
+
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col',
|
|
20
|
+
'blockquote', 'q', 'cite', 'abbr', 'time', 'mark', 'small', 'ins', 'del', 's', 'u', 'b', 'i', 'strong', 'em', 'sup', 'sub', 'wbr',
|
|
21
|
+
'details', 'summary', 'figure', 'figcaption',
|
|
22
|
+
'input',
|
|
23
|
+
])
|
|
24
|
+
|
|
25
|
+
// Strict attribute allowlist: blocks event handlers (on*), data-pru-*, data-persist, DOM clobbering (id/name), style, etc.
|
|
26
|
+
const GLOBAL_ALLOWED_ATTRS = new Set([
|
|
27
|
+
'class',
|
|
28
|
+
'title',
|
|
29
|
+
'lang',
|
|
30
|
+
'dir',
|
|
31
|
+
'role',
|
|
32
|
+
'aria-label',
|
|
33
|
+
'aria-hidden',
|
|
34
|
+
'aria-current',
|
|
35
|
+
'aria-expanded',
|
|
36
|
+
'aria-level',
|
|
37
|
+
'aria-description',
|
|
38
|
+
'aria-roledescription',
|
|
39
|
+
])
|
|
40
|
+
|
|
41
|
+
const TAG_ALLOWED_ATTRS: Record<string, ReadonlySet<string>> = {
|
|
42
|
+
a: new Set(['href', 'rel', 'target', 'hreflang']),
|
|
43
|
+
img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding', 'fetchpriority']),
|
|
44
|
+
source: new Set(['src', 'srcset', 'sizes', 'type', 'media', 'width', 'height']),
|
|
45
|
+
blockquote: new Set(['cite']),
|
|
46
|
+
q: new Set(['cite']),
|
|
47
|
+
del: new Set(['cite', 'datetime']),
|
|
48
|
+
ins: new Set(['cite', 'datetime']),
|
|
49
|
+
time: new Set(['datetime']),
|
|
50
|
+
ol: new Set(['start', 'reversed', 'type']),
|
|
51
|
+
li: new Set(['value']),
|
|
52
|
+
th: new Set(['colspan', 'rowspan', 'scope', 'align', 'valign', 'abbr']),
|
|
53
|
+
td: new Set(['colspan', 'rowspan', 'align', 'valign', 'abbr']),
|
|
54
|
+
col: new Set(['span', 'align']),
|
|
55
|
+
colgroup: new Set(['span', 'align']),
|
|
56
|
+
details: new Set(['open']),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const URL_ATTRS = new Set(['href', 'src', 'cite'])
|
|
60
|
+
const SAFE_DATA_IMAGE_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
|
|
61
|
+
const SAFE_SCHEME_RE = /^(?:https?|mailto|tel):/i
|
|
62
|
+
const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
|
|
63
|
+
|
|
64
|
+
function decodeHtmlEntities(rawVal: string): string {
|
|
65
|
+
return rawVal
|
|
66
|
+
.replace(/&#x([0-9a-f]+);?/gi, (_, hex: string) => {
|
|
67
|
+
const cp = Number.parseInt(hex, 16)
|
|
68
|
+
return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
|
|
69
|
+
})
|
|
70
|
+
.replace(/&#([0-9]+);?/g, (_, dec: string) => {
|
|
71
|
+
const cp = Number.parseInt(dec, 10)
|
|
72
|
+
return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
|
|
73
|
+
})
|
|
74
|
+
.replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
|
|
75
|
+
const lower = name.toLowerCase()
|
|
76
|
+
if (lower === 'colon') return ':'
|
|
77
|
+
if (lower === 'tab') return '\t'
|
|
78
|
+
if (lower === 'newline') return '\n'
|
|
79
|
+
return '&'
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isSafeUrl(val: string): boolean {
|
|
84
|
+
const cleaned = decodeHtmlEntities(val).replace(/[\u0000-\u0020\u007F]+/g, '').trim()
|
|
85
|
+
if (cleaned === '')
|
|
86
|
+
return true
|
|
87
|
+
if (SAFE_SCHEME_RE.test(cleaned) || SAFE_DATA_IMAGE_RE.test(cleaned))
|
|
88
|
+
return true
|
|
89
|
+
if (HAS_SCHEME_RE.test(cleaned))
|
|
90
|
+
return false
|
|
91
|
+
return true
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function parseTagAttributes(attrSrc: string): Array<{ name: string, value: string | null }> {
|
|
95
|
+
const attrs: Array<{ name: string, value: string | null }> = []
|
|
96
|
+
let i = 0
|
|
97
|
+
const len = attrSrc.length
|
|
98
|
+
while (i < len) {
|
|
99
|
+
while (i < len && /[\s/]/.test(attrSrc[i]!)) i++
|
|
100
|
+
if (i >= len) break
|
|
101
|
+
const nameStart = i
|
|
102
|
+
while (i < len && !/[\s=/>"'<]/.test(attrSrc[i]!)) i++
|
|
103
|
+
const name = attrSrc.slice(nameStart, i).toLowerCase()
|
|
104
|
+
if (!name) {
|
|
105
|
+
i++
|
|
106
|
+
continue
|
|
107
|
+
}
|
|
108
|
+
while (i < len && /\s/.test(attrSrc[i]!)) i++
|
|
109
|
+
if (attrSrc[i] !== '=') {
|
|
110
|
+
attrs.push({ name, value: null })
|
|
111
|
+
continue
|
|
112
|
+
}
|
|
113
|
+
i++ // skip '='
|
|
114
|
+
while (i < len && /\s/.test(attrSrc[i]!)) i++
|
|
115
|
+
if (i >= len) {
|
|
116
|
+
attrs.push({ name, value: '' })
|
|
117
|
+
break
|
|
118
|
+
}
|
|
119
|
+
const quote = attrSrc[i]!
|
|
120
|
+
if (quote === '"' || quote === '\'') {
|
|
121
|
+
i++
|
|
122
|
+
const valStart = i
|
|
123
|
+
while (i < len && attrSrc[i] !== quote) i++
|
|
124
|
+
attrs.push({ name, value: attrSrc.slice(valStart, i) })
|
|
125
|
+
if (i < len) i++
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
const valStart = i
|
|
129
|
+
while (i < len && !/[\s>]/.test(attrSrc[i]!)) i++
|
|
130
|
+
attrs.push({ name, value: attrSrc.slice(valStart, i) })
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return attrs
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function sanitizeInputTag(rawAttrs: Array<{ name: string, value: string | null }>): string {
|
|
137
|
+
const typeAttr = rawAttrs.find(a => a.name === 'type')
|
|
138
|
+
if (typeAttr?.value?.toLowerCase() !== 'checkbox')
|
|
139
|
+
return ''
|
|
140
|
+
const safeParts = ['type="checkbox"']
|
|
141
|
+
for (const a of rawAttrs) {
|
|
142
|
+
if (a.name === 'class' && a.value !== null)
|
|
143
|
+
safeParts.push(`class="${a.value.replaceAll('"', '"')}"`)
|
|
144
|
+
else if (a.name === 'disabled')
|
|
145
|
+
safeParts.push('disabled')
|
|
146
|
+
else if (a.name === 'checked')
|
|
147
|
+
safeParts.push('checked')
|
|
148
|
+
}
|
|
149
|
+
return `<input ${safeParts.join(' ')}>`
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
type AllowedSlotPrefixes = string | ReadonlySet<string> | undefined
|
|
153
|
+
|
|
154
|
+
function matchesSlotPrefix(value: string | null, allowed: AllowedSlotPrefixes): boolean {
|
|
155
|
+
if (value === null || allowed === undefined)
|
|
156
|
+
return false
|
|
157
|
+
if (typeof allowed === 'string')
|
|
158
|
+
return value.startsWith(allowed)
|
|
159
|
+
for (const prefix of allowed) {
|
|
160
|
+
if (value.startsWith(prefix))
|
|
161
|
+
return true
|
|
162
|
+
}
|
|
163
|
+
return false
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function isAllowedAttr(tagName: string, name: string, value: string | null, slotPrefixes: AllowedSlotPrefixes): boolean {
|
|
167
|
+
if (tagName === 'div' && name === 'data-pru-md-slot')
|
|
168
|
+
return matchesSlotPrefix(value, slotPrefixes)
|
|
169
|
+
return GLOBAL_ALLOWED_ATTRS.has(name) || TAG_ALLOWED_ATTRS[tagName]?.has(name) === true
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function sanitizeAttributes(
|
|
173
|
+
tagName: string,
|
|
174
|
+
rawAttrs: Array<{ name: string, value: string | null }>,
|
|
175
|
+
slotPrefixes: AllowedSlotPrefixes,
|
|
176
|
+
): string[] {
|
|
177
|
+
const safeParts: string[] = []
|
|
178
|
+
for (const a of rawAttrs) {
|
|
179
|
+
if (!isAllowedAttr(tagName, a.name, a.value, slotPrefixes))
|
|
180
|
+
continue
|
|
181
|
+
if (URL_ATTRS.has(a.name)) {
|
|
182
|
+
if (a.value === null || !isSafeUrl(a.value))
|
|
183
|
+
continue
|
|
184
|
+
}
|
|
185
|
+
else if (a.name === 'srcset' && a.value !== null) {
|
|
186
|
+
const candidates = a.value.split(',').map(s => s.trim().split(/\s+/)[0] ?? '')
|
|
187
|
+
if (!candidates.every(isSafeUrl))
|
|
188
|
+
continue
|
|
189
|
+
}
|
|
190
|
+
if (a.value === null)
|
|
191
|
+
safeParts.push(a.name)
|
|
192
|
+
else
|
|
193
|
+
safeParts.push(`${a.name}="${a.value.replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>')}"`)
|
|
194
|
+
}
|
|
195
|
+
return safeParts
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function findTagEndOffset(html: string, start: number): number {
|
|
199
|
+
let tagEnd = start
|
|
200
|
+
const len = html.length
|
|
201
|
+
let inQuote: string | null = null
|
|
202
|
+
while (tagEnd < len) {
|
|
203
|
+
const c = html[tagEnd]!
|
|
204
|
+
if (inQuote !== null) {
|
|
205
|
+
if (c === inQuote)
|
|
206
|
+
inQuote = null
|
|
207
|
+
}
|
|
208
|
+
else if (c === '"' || c === '\'') {
|
|
209
|
+
inQuote = c
|
|
210
|
+
}
|
|
211
|
+
else if (c === '>') {
|
|
212
|
+
return tagEnd
|
|
213
|
+
}
|
|
214
|
+
tagEnd++
|
|
215
|
+
}
|
|
216
|
+
return -1
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
|
|
220
|
+
let out = ''
|
|
221
|
+
let i = 0
|
|
222
|
+
const len = html.length
|
|
223
|
+
|
|
224
|
+
while (i < len) {
|
|
225
|
+
const lt = html.indexOf('<', i)
|
|
226
|
+
if (lt === -1) {
|
|
227
|
+
out += html.slice(i)
|
|
228
|
+
break
|
|
229
|
+
}
|
|
230
|
+
out += html.slice(i, lt)
|
|
231
|
+
|
|
232
|
+
// Strip HTML comments (including HTML5 `--!>` closer)
|
|
233
|
+
if (html.startsWith('<!--', lt)) {
|
|
234
|
+
const endStd = html.indexOf('-->', lt + 4)
|
|
235
|
+
const endBang = html.indexOf('--!>', lt + 4)
|
|
236
|
+
if (endStd === -1 && endBang === -1)
|
|
237
|
+
i = len
|
|
238
|
+
else if (endBang !== -1 && (endStd === -1 || endBang < endStd))
|
|
239
|
+
i = endBang + 4
|
|
240
|
+
else
|
|
241
|
+
i = endStd + 3
|
|
242
|
+
continue
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
let pos = lt + 1
|
|
246
|
+
const isClosing = html[pos] === '/'
|
|
247
|
+
if (isClosing)
|
|
248
|
+
pos++
|
|
249
|
+
|
|
250
|
+
const nameStart = pos
|
|
251
|
+
while (pos < len && /[A-Za-z0-9:-]/.test(html[pos]!)) pos++
|
|
252
|
+
const tagName = html.slice(nameStart, pos).toLowerCase()
|
|
253
|
+
if (!tagName) {
|
|
254
|
+
out += '<'
|
|
255
|
+
i = lt + 1
|
|
256
|
+
continue
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const tagEnd = findTagEndOffset(html, pos)
|
|
260
|
+
if (tagEnd === -1)
|
|
261
|
+
break
|
|
262
|
+
|
|
263
|
+
const attrSrc = html.slice(pos, tagEnd)
|
|
264
|
+
const selfClosing = !isClosing && /\/\s*$/.test(attrSrc)
|
|
265
|
+
i = tagEnd + 1
|
|
266
|
+
|
|
267
|
+
if (!isClosing && DROP_CONTENT_TAGS.has(tagName)) {
|
|
268
|
+
if (!selfClosing) {
|
|
269
|
+
const closeRe = new RegExp(`</${tagName}\\b[^<>]*>`, 'gi')
|
|
270
|
+
closeRe.lastIndex = i
|
|
271
|
+
const m = closeRe.exec(html)
|
|
272
|
+
i = m ? m.index + m[0].length : len
|
|
273
|
+
}
|
|
274
|
+
continue
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (!ALLOWED_MD_TAGS.has(tagName))
|
|
278
|
+
continue
|
|
279
|
+
|
|
280
|
+
if (isClosing) {
|
|
281
|
+
if (tagName !== 'input' && tagName !== 'br' && tagName !== 'hr' && tagName !== 'img')
|
|
282
|
+
out += `</${tagName}>`
|
|
283
|
+
continue
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const rawAttrs = parseTagAttributes(attrSrc)
|
|
287
|
+
if (tagName === 'input') {
|
|
288
|
+
out += sanitizeInputTag(rawAttrs)
|
|
289
|
+
continue
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const safeParts = sanitizeAttributes(tagName, rawAttrs, slotPrefixes)
|
|
293
|
+
const attrOut = safeParts.length > 0 ? ` ${safeParts.join(' ')}` : ''
|
|
294
|
+
out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return out
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function sanitizeMarkdownHtml(html: string, slotPrefixes?: AllowedSlotPrefixes): string {
|
|
301
|
+
let current = html
|
|
302
|
+
for (let pass = 0; pass < 3; pass++) {
|
|
303
|
+
const next = sanitizePass(current, slotPrefixes)
|
|
304
|
+
if (next === current)
|
|
305
|
+
return next
|
|
306
|
+
current = next
|
|
307
|
+
}
|
|
308
|
+
return current
|
|
309
|
+
}
|