prunelle 0.1.1 → 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 +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +139 -39
- 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 +101 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- 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 +407 -352
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +64 -20
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +188 -152
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +356 -11
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- 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/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
package/src/server/loader.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
|
7
7
|
import { join, resolve } from 'node:path'
|
|
8
8
|
import { SERVER_ENTRY_FILE } from '../build/server-entry'
|
|
9
9
|
import { loadConfig, resolveServerConfig } from '../plugins/index'
|
|
10
|
+
import { devFromEnv } from './env'
|
|
10
11
|
import { createStaticDirServer } from './static-dir'
|
|
11
12
|
|
|
12
13
|
let serverLoadSeq = 0
|
|
@@ -70,10 +71,12 @@ export async function startBuiltApp(options: ServerOptions): Promise<{ app: Prun
|
|
|
70
71
|
root,
|
|
71
72
|
outDir,
|
|
72
73
|
publicDir: join(outDir, 'public'),
|
|
73
|
-
dev: options.dev ?? (
|
|
74
|
+
dev: options.dev ?? devFromEnv(),
|
|
75
|
+
devHost: options.devHost,
|
|
74
76
|
nodeEnv: options.nodeEnv,
|
|
75
77
|
errorSink: options.errorSink,
|
|
76
78
|
prerender: options.prerender,
|
|
79
|
+
static: options.static,
|
|
77
80
|
})
|
|
78
81
|
return { app, outDir, entry }
|
|
79
82
|
}
|
|
@@ -107,12 +110,22 @@ async function loadServerEntry(options: ServerOptions): Promise<BuiltOutput> {
|
|
|
107
110
|
|
|
108
111
|
async function serveStaticDir(options: ServerOptions, root: string, outDir: string): Promise<PrunelleApp> {
|
|
109
112
|
const config = await loadConfig(root, { dev: options.dev, nodeEnv: options.nodeEnv })
|
|
113
|
+
const site = (options.site ?? config.site)?.replace(/\/$/, '') || undefined
|
|
114
|
+
const isDev = options.dev ?? devFromEnv()
|
|
110
115
|
return createStaticDirServer(
|
|
111
116
|
outDir,
|
|
112
117
|
options.assetPrefix ?? config.assetPrefix ?? '/_pru',
|
|
113
118
|
options.security ?? config.security,
|
|
114
119
|
(options.compress ?? config.compress) !== false,
|
|
115
120
|
options.trustProxy ?? config.trustProxy ?? false,
|
|
116
|
-
|
|
121
|
+
isDev,
|
|
122
|
+
{
|
|
123
|
+
navigation: options.navigation ?? config.navigation,
|
|
124
|
+
plugins: options.plugins ?? config.plugins,
|
|
125
|
+
onError: options.onError ?? config.onError,
|
|
126
|
+
errorSink: options.errorSink,
|
|
127
|
+
httpsSite: !isDev && site?.startsWith('https://') === true,
|
|
128
|
+
nodeEnv: options.nodeEnv,
|
|
129
|
+
},
|
|
117
130
|
)
|
|
118
131
|
}
|
package/src/server/page.ts
CHANGED
|
@@ -4,6 +4,8 @@ import type { BuildManifest, RouteManifestEntry } from '../build/index'
|
|
|
4
4
|
import type { Html } from '../jsx-runtime'
|
|
5
5
|
import type { Middleware, RequestContext } from './http'
|
|
6
6
|
import type { PrunelleLocals } from './index'
|
|
7
|
+
import { existsSync } from 'node:fs'
|
|
8
|
+
import { join } from 'node:path'
|
|
7
9
|
|
|
8
10
|
export interface LoadedPageModule {
|
|
9
11
|
default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
|
|
@@ -36,6 +38,19 @@ export function mergedHeadTags(manifest: BuildManifest, entry: RouteManifestEntr
|
|
|
36
38
|
: manifest.headTags
|
|
37
39
|
}
|
|
38
40
|
|
|
41
|
+
/** Whether the app ships a `/favicon.ico` in `public/` (or via `emitPublic`), so SSR should not inject an empty `data:,` icon. */
|
|
42
|
+
export function hasPublicFavicon(
|
|
43
|
+
manifest: BuildManifest,
|
|
44
|
+
publicMap?: ReadonlyMap<string, unknown>,
|
|
45
|
+
publicDir?: string,
|
|
46
|
+
): boolean {
|
|
47
|
+
if (publicMap?.has('/favicon.ico'))
|
|
48
|
+
return true
|
|
49
|
+
if (manifest.publicFiles?.some(f => f === 'favicon.ico' || f === '/favicon.ico'))
|
|
50
|
+
return true
|
|
51
|
+
return publicDir !== undefined && existsSync(join(publicDir, 'favicon.ico'))
|
|
52
|
+
}
|
|
53
|
+
|
|
39
54
|
export function allowedMethodsHeader(mod: LoadedPageModule): string {
|
|
40
55
|
const allowed = new Set<string>()
|
|
41
56
|
if (typeof mod.default === 'function') {
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Route parameter matchers (built-in `integer`, `uuid`, `slug` and app-defined `src/params/<name>.ts`) and shared route-pattern segment parsing.
|
|
2
|
+
|
|
3
|
+
export type ParamMatcher = (value: string) => boolean
|
|
4
|
+
export type ParamMatcherMap = Readonly<Record<string, ParamMatcher>>
|
|
5
|
+
|
|
6
|
+
const INTEGER_RE = /^\d+$/
|
|
7
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
8
|
+
const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
9
|
+
|
|
10
|
+
export const BUILTIN_PARAM_MATCHERS: ParamMatcherMap = {
|
|
11
|
+
integer: value => INTEGER_RE.test(value),
|
|
12
|
+
uuid: value => UUID_RE.test(value),
|
|
13
|
+
slug: value => SLUG_RE.test(value),
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const BUILTIN_PARAM_MATCHER_NAMES = ['integer', 'uuid', 'slug'] as const
|
|
17
|
+
|
|
18
|
+
export function isBuiltinMatcher(name: string): boolean {
|
|
19
|
+
return Object.hasOwn(BUILTIN_PARAM_MATCHERS, name)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Extracts a matcher function from an app param matcher module (`export function match` or `export default`). */
|
|
23
|
+
export function extractMatcherFn(mod: unknown): ParamMatcher | undefined {
|
|
24
|
+
if (typeof mod === 'function')
|
|
25
|
+
return mod as ParamMatcher
|
|
26
|
+
if (mod !== null && typeof mod === 'object') {
|
|
27
|
+
const rec = mod as Record<string, unknown>
|
|
28
|
+
if (typeof rec.match === 'function')
|
|
29
|
+
return rec.match as ParamMatcher
|
|
30
|
+
if (typeof rec.default === 'function')
|
|
31
|
+
return rec.default as ParamMatcher
|
|
32
|
+
}
|
|
33
|
+
return undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Merges built-in matchers with app matchers listed in the build manifest. */
|
|
37
|
+
export function resolveParamMatchers(
|
|
38
|
+
manifestMatchers: Readonly<Record<string, string>> | undefined,
|
|
39
|
+
modules: Readonly<Record<string, unknown>>,
|
|
40
|
+
): ParamMatcherMap {
|
|
41
|
+
if (manifestMatchers === undefined)
|
|
42
|
+
return BUILTIN_PARAM_MATCHERS
|
|
43
|
+
const merged: Record<string, ParamMatcher> = { ...BUILTIN_PARAM_MATCHERS }
|
|
44
|
+
for (const [name, modKey] of Object.entries(manifestMatchers)) {
|
|
45
|
+
const fn = extractMatcherFn(modules[modKey])
|
|
46
|
+
if (fn !== undefined)
|
|
47
|
+
merged[name] = fn
|
|
48
|
+
}
|
|
49
|
+
return merged
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ParsedPatternSegment {
|
|
53
|
+
kind: 'static' | 'param' | 'optional' | 'catchall'
|
|
54
|
+
/** Exact literal for static, parameter name for param/optional/catchall. */
|
|
55
|
+
value: string
|
|
56
|
+
matcherName?: string | undefined
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function splitNameAndMatcher(spec: string, fallbackName?: string): { name: string, matcherName?: string | undefined } {
|
|
60
|
+
const eq = spec.indexOf('=')
|
|
61
|
+
if (eq === -1)
|
|
62
|
+
return { name: spec || fallbackName || '' }
|
|
63
|
+
const name = spec.slice(0, eq) || fallbackName || ''
|
|
64
|
+
const matcherName = spec.slice(eq + 1)
|
|
65
|
+
return matcherName.length > 0 ? { name, matcherName } : { name }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Parses one segment of a compiled route pattern (`about`, `:id`, `:id=integer`, `:lang?`, `:page=integer?`, `*rest`, `*path=slug`). */
|
|
69
|
+
export function parsePatternSegment(seg: string): ParsedPatternSegment {
|
|
70
|
+
if (seg.startsWith('*')) {
|
|
71
|
+
const { name, matcherName } = splitNameAndMatcher(seg.slice(1), 'rest')
|
|
72
|
+
return { kind: 'catchall', value: name, matcherName }
|
|
73
|
+
}
|
|
74
|
+
if (seg.startsWith(':')) {
|
|
75
|
+
const body = seg.slice(1)
|
|
76
|
+
const optional = body.endsWith('?')
|
|
77
|
+
const spec = optional ? body.slice(0, -1) : body
|
|
78
|
+
const { name, matcherName } = splitNameAndMatcher(spec)
|
|
79
|
+
return { kind: optional ? 'optional' : 'param', value: name, matcherName }
|
|
80
|
+
}
|
|
81
|
+
return { kind: 'static', value: seg }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Lists every param matcher reference in a compiled route pattern (e.g. `'/users/:id=integer'` -> `[{ param: 'id', matcher: 'integer' }]`). */
|
|
85
|
+
export function extractPatternMatchers(routePath: string): { param: string, matcher: string }[] {
|
|
86
|
+
const result: { param: string, matcher: string }[] = []
|
|
87
|
+
if (!routePath.includes('='))
|
|
88
|
+
return result
|
|
89
|
+
for (const seg of routePath.split('/')) {
|
|
90
|
+
if (seg === '')
|
|
91
|
+
continue
|
|
92
|
+
const parsed = parsePatternSegment(seg)
|
|
93
|
+
if (parsed.matcherName !== undefined)
|
|
94
|
+
result.push({ param: parsed.value, matcher: parsed.matcherName })
|
|
95
|
+
}
|
|
96
|
+
return result
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Lists optional parameter names in a compiled route pattern (e.g. `'/:lang?/about'` -> `['lang']`). */
|
|
100
|
+
export function extractOptionalParams(routePath: string): string[] {
|
|
101
|
+
const result: string[] = []
|
|
102
|
+
if (!routePath.includes('?'))
|
|
103
|
+
return result
|
|
104
|
+
for (const seg of routePath.split('/')) {
|
|
105
|
+
if (seg === '')
|
|
106
|
+
continue
|
|
107
|
+
const parsed = parsePatternSegment(seg)
|
|
108
|
+
if (parsed.kind === 'optional')
|
|
109
|
+
result.push(parsed.value)
|
|
110
|
+
}
|
|
111
|
+
return result
|
|
112
|
+
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import type { BuildManifest } from '../build/index'
|
|
4
4
|
import type { AppRuntimeContext } from '../plugins/context'
|
|
5
5
|
import type { PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerPluginAPI } from '../plugins/index'
|
|
6
|
+
import type { HealthCheckEntry } from './health'
|
|
6
7
|
import type { EmbeddedServerConfig, Middleware, RequestContext } from './http'
|
|
7
8
|
|
|
8
9
|
import type { TrustProxy } from './security'
|
|
@@ -10,6 +11,8 @@ import { runWithAppContext } from '../plugins/context'
|
|
|
10
11
|
import { enforceRequirements } from '../plugins/requires'
|
|
11
12
|
import { normalizeConsentConfig, registerConsentRoute } from './consent'
|
|
12
13
|
import { assertRateLimit, createRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
|
|
14
|
+
import type { RequestPath } from './request-path'
|
|
15
|
+
import type { RouteMatch } from './router'
|
|
13
16
|
import { Router } from './router'
|
|
14
17
|
|
|
15
18
|
export interface PluginRouteDef {
|
|
@@ -18,6 +21,8 @@ export interface PluginRouteDef {
|
|
|
18
21
|
csrf: boolean
|
|
19
22
|
trustedOrigins: Set<string> | undefined
|
|
20
23
|
trustProxy: TrustProxy
|
|
24
|
+
/** The catch-all takes an encoded separator for this method (`PluginRouteOptions.encodedSlashes`). */
|
|
25
|
+
encodedSlashes: boolean
|
|
21
26
|
}
|
|
22
27
|
|
|
23
28
|
interface ScopedMiddleware {
|
|
@@ -40,6 +45,7 @@ export interface ServerPluginHostOptions {
|
|
|
40
45
|
assetPrefix: string
|
|
41
46
|
site: string | undefined
|
|
42
47
|
dev: boolean
|
|
48
|
+
devExposed: boolean
|
|
43
49
|
trustProxy: TrustProxy
|
|
44
50
|
trustedOriginsList: readonly string[]
|
|
45
51
|
trustedOrigins: Set<string> | undefined
|
|
@@ -59,6 +65,14 @@ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string,
|
|
|
59
65
|
return normPath === normScope || normPath.startsWith(`${normScope}/`)
|
|
60
66
|
}
|
|
61
67
|
|
|
68
|
+
/** The methods of `match` that may answer `path`: for a path with an encoded separator, only those that set `encodedSlashes`; none left is no match. */
|
|
69
|
+
export function takesEncoded(match: RouteMatch<Map<string, PluginRouteDef>> | undefined, path: RequestPath): RouteMatch<Map<string, PluginRouteDef>> | undefined {
|
|
70
|
+
if (match === undefined || path.encoded === undefined || path.encoded.size === 0)
|
|
71
|
+
return match
|
|
72
|
+
const data = new Map([...match.data].filter(([, def]) => def.encodedSlashes))
|
|
73
|
+
return data.size === 0 ? undefined : { data, params: match.params }
|
|
74
|
+
}
|
|
75
|
+
|
|
62
76
|
export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
|
|
63
77
|
const allowed = new Set<string>()
|
|
64
78
|
for (const m of methods.keys()) {
|
|
@@ -71,11 +85,49 @@ export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRo
|
|
|
71
85
|
return [...allowed].join(', ')
|
|
72
86
|
}
|
|
73
87
|
|
|
88
|
+
function assertRouteFree(pluginName: string, upperMethod: string, normPath: string, byMethod: ReadonlyMap<string, PluginRouteDef>): void {
|
|
89
|
+
const directConflict = byMethod.get(upperMethod)
|
|
90
|
+
if (directConflict !== undefined)
|
|
91
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with "${directConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
92
|
+
if (upperMethod === 'ALL' && byMethod.size > 0) {
|
|
93
|
+
const [existingMethod, existingDef] = byMethod.entries().next().value!
|
|
94
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
|
|
95
|
+
}
|
|
96
|
+
const allConflict = byMethod.get('ALL')
|
|
97
|
+
if (allConflict !== undefined)
|
|
98
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function createMiddlewareLookup(scopedMiddlewares: readonly ScopedMiddleware[]) {
|
|
102
|
+
const allMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
|
|
103
|
+
const hasPathScopedMiddlewares = scopedMiddlewares.some(m => !isKindScope(m.scope))
|
|
104
|
+
// With no path-scoped middleware the list depends on the kind alone, so it is worked out once per kind.
|
|
105
|
+
const byKind: Record<RequestKind, readonly Middleware[]> = {
|
|
106
|
+
prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'prerendered')).map(m => m.mw),
|
|
107
|
+
static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'static')).map(m => m.mw),
|
|
108
|
+
dynamic: allMiddlewares,
|
|
109
|
+
}
|
|
110
|
+
const middlewaresFor = (path: string, kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
111
|
+
if (!hasPathScopedMiddlewares)
|
|
112
|
+
return byKind[kind]
|
|
113
|
+
return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, kind)).map(m => m.mw)
|
|
114
|
+
}
|
|
115
|
+
const middlewaresForPaths = (paths: readonly string[], kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
116
|
+
if (!hasPathScopedMiddlewares)
|
|
117
|
+
return byKind[kind]
|
|
118
|
+
return scopedMiddlewares
|
|
119
|
+
.filter(m => paths.some(path => middlewareAppliesToPath(m.scope, path, kind)))
|
|
120
|
+
.map(m => m.mw)
|
|
121
|
+
}
|
|
122
|
+
return { allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths }
|
|
123
|
+
}
|
|
124
|
+
|
|
74
125
|
export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
75
126
|
const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
|
|
76
127
|
// The counters of every limited route and action of this server, dropped with it.
|
|
77
128
|
const rateLimits = createRateLimitStore()
|
|
78
129
|
const scopedMiddlewares: ScopedMiddleware[] = []
|
|
130
|
+
const healthChecks: HealthCheckEntry[] = []
|
|
79
131
|
const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
|
|
80
132
|
const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
|
|
81
133
|
const router = new Router<Map<string, PluginRouteDef>>()
|
|
@@ -89,25 +141,20 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
89
141
|
): void => {
|
|
90
142
|
const upperMethod = method.toUpperCase()
|
|
91
143
|
const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
144
|
+
const encodedSlashes = routeOptions?.encodedSlashes === true
|
|
145
|
+
if (encodedSlashes && !normPath.split('/').some(seg => seg.startsWith('*')))
|
|
146
|
+
throw new Error(`prunelle: plugin "${pluginName}" set encodedSlashes on ${upperMethod} ${normPath}, which has no catch-all: only a \`*name\` segment takes an encoded /, so end the path with one, or drop the option.`)
|
|
92
147
|
let byMethod = routeEntries.get(normPath)
|
|
93
148
|
if (byMethod === undefined) {
|
|
94
149
|
byMethod = new Map()
|
|
95
150
|
routeEntries.set(normPath, byMethod)
|
|
96
|
-
router.add(normPath, byMethod)
|
|
151
|
+
router.add(normPath, byMethod, { encodedSlashes })
|
|
97
152
|
}
|
|
98
153
|
else {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
if (upperMethod === 'ALL' && byMethod.size > 0) {
|
|
104
|
-
const [existingMethod, existingDef] = byMethod.entries().next().value!
|
|
105
|
-
throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
|
|
106
|
-
}
|
|
107
|
-
const allConflict = byMethod.get('ALL')
|
|
108
|
-
if (allConflict !== undefined) {
|
|
109
|
-
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
110
|
-
}
|
|
154
|
+
assertRouteFree(pluginName, upperMethod, normPath, byMethod)
|
|
155
|
+
// The path matches encoded separators once any method takes them; takesEncoded still refuses them to the others.
|
|
156
|
+
if (encodedSlashes)
|
|
157
|
+
router.add(normPath, byMethod, { encodedSlashes })
|
|
111
158
|
}
|
|
112
159
|
let routeTrustedOrigins = trustedOrigins
|
|
113
160
|
if (routeOptions?.trustedOrigins !== undefined && routeOptions.trustedOrigins.length > 0) {
|
|
@@ -129,12 +176,25 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
129
176
|
csrf: routeOptions?.csrf ?? true,
|
|
130
177
|
trustedOrigins: routeTrustedOrigins,
|
|
131
178
|
trustProxy: routeOptions?.trustProxy ?? trustProxy,
|
|
179
|
+
encodedSlashes,
|
|
132
180
|
})
|
|
133
181
|
}
|
|
134
182
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
183
|
+
let disposed = false
|
|
184
|
+
async function dispose(): Promise<void> {
|
|
185
|
+
if (disposed)
|
|
186
|
+
return
|
|
187
|
+
disposed = true
|
|
188
|
+
rateLimits.close()
|
|
189
|
+
for (const { plugin, hook } of shutdownHooks) {
|
|
190
|
+
try {
|
|
191
|
+
await hook()
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
console.error(`prunelle: the onShutdown hook of ${plugin} threw; the other hooks still run.`, error)
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
138
198
|
|
|
139
199
|
const {
|
|
140
200
|
manifest: _m,
|
|
@@ -148,83 +208,60 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
|
148
208
|
} = config as EmbeddedServerConfig & Record<string, unknown>
|
|
149
209
|
const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
|
|
150
210
|
|
|
151
|
-
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
for (const plugin of plugins) {
|
|
156
|
-
if (plugin.server !== undefined) {
|
|
157
|
-
const pluginApi: ServerPluginAPI = {
|
|
158
|
-
root: options.root,
|
|
159
|
-
outDir: options.outDir,
|
|
160
|
-
assetPrefix: options.assetPrefix,
|
|
161
|
-
site: options.site,
|
|
162
|
-
dev: options.dev,
|
|
163
|
-
trustProxy,
|
|
164
|
-
trustedOrigins: options.trustedOriginsList,
|
|
165
|
-
config: readonlyRuntimeConfig,
|
|
166
|
-
use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
|
|
167
|
-
scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
|
|
168
|
-
},
|
|
169
|
-
route: registerRouteFor(plugin.name),
|
|
170
|
-
rateLimiter(limit) {
|
|
171
|
-
assertRateLimit(limit, `the rateLimiter of "${plugin.name}"`)
|
|
172
|
-
return rateLimits.limiter(limit)
|
|
173
|
-
},
|
|
174
|
-
rewrite(fn) {
|
|
175
|
-
rewrites.push(fn)
|
|
176
|
-
},
|
|
177
|
-
provide: appCtx.provide,
|
|
178
|
-
inject: appCtx.inject,
|
|
179
|
-
getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
|
|
180
|
-
return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
|
|
181
|
-
},
|
|
182
|
-
onShutdown(fn) {
|
|
183
|
-
shutdownHooks.push({ plugin: plugin.name, hook: fn })
|
|
184
|
-
},
|
|
185
|
-
}
|
|
186
|
-
await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
const allMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
|
|
191
|
-
const hasPathScopedMiddlewares = scopedMiddlewares.some(m => !isKindScope(m.scope))
|
|
192
|
-
// With no path-scoped middleware the list depends on the kind alone, so it is worked out once per kind.
|
|
193
|
-
const byKind: Record<RequestKind, readonly Middleware[]> = {
|
|
194
|
-
prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'prerendered')).map(m => m.mw),
|
|
195
|
-
static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'static')).map(m => m.mw),
|
|
196
|
-
dynamic: allMiddlewares,
|
|
197
|
-
}
|
|
198
|
-
const middlewaresFor = (path: string, kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
199
|
-
if (!hasPathScopedMiddlewares)
|
|
200
|
-
return byKind[kind]
|
|
201
|
-
return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, kind)).map(m => m.mw)
|
|
202
|
-
}
|
|
203
|
-
const middlewaresForPaths = (paths: readonly string[], kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
204
|
-
if (!hasPathScopedMiddlewares)
|
|
205
|
-
return byKind[kind]
|
|
206
|
-
return scopedMiddlewares
|
|
207
|
-
.filter(m => paths.some(path => middlewareAppliesToPath(m.scope, path, kind)))
|
|
208
|
-
.map(m => m.mw)
|
|
209
|
-
}
|
|
211
|
+
try {
|
|
212
|
+
const consentConfig = normalizeConsentConfig(config.consent)
|
|
213
|
+
if (consentConfig !== undefined)
|
|
214
|
+
registerConsentRoute(registerRouteFor('pru:consent'), consentConfig, trustedOrigins, trustProxy)
|
|
210
215
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
216
|
+
if (config.prerender !== true || config.static === true) {
|
|
217
|
+
const production = !options.dev && (appCtx.nodeEnv ?? process.env.NODE_ENV) === 'production'
|
|
218
|
+
await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site, consentCategories: consentConfig?.categories ?? [] }, production))
|
|
219
|
+
}
|
|
220
|
+
for (const plugin of plugins) {
|
|
221
|
+
if (plugin.server !== undefined) {
|
|
222
|
+
const pluginApi: ServerPluginAPI = {
|
|
223
|
+
root: options.root,
|
|
224
|
+
outDir: options.outDir,
|
|
225
|
+
assetPrefix: options.assetPrefix,
|
|
226
|
+
site: options.site,
|
|
227
|
+
dev: options.dev,
|
|
228
|
+
devExposed: options.devExposed,
|
|
229
|
+
trustProxy,
|
|
230
|
+
trustedOrigins: options.trustedOriginsList,
|
|
231
|
+
config: readonlyRuntimeConfig,
|
|
232
|
+
use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
|
|
233
|
+
scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
|
|
234
|
+
},
|
|
235
|
+
route: registerRouteFor(plugin.name),
|
|
236
|
+
rateLimiter(limit) {
|
|
237
|
+
assertRateLimit(limit, `the rateLimiter of "${plugin.name}"`)
|
|
238
|
+
return rateLimits.limiter(limit)
|
|
239
|
+
},
|
|
240
|
+
rewrite(fn) {
|
|
241
|
+
rewrites.push(fn)
|
|
242
|
+
},
|
|
243
|
+
provide: appCtx.provide,
|
|
244
|
+
inject: appCtx.inject,
|
|
245
|
+
getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
|
|
246
|
+
return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
|
|
247
|
+
},
|
|
248
|
+
healthCheck(name, fn) {
|
|
249
|
+
healthChecks.push({ name, fn })
|
|
250
|
+
},
|
|
251
|
+
onShutdown(fn) {
|
|
252
|
+
shutdownHooks.push({ plugin: plugin.name, hook: fn })
|
|
253
|
+
},
|
|
254
|
+
}
|
|
255
|
+
await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
|
|
223
256
|
}
|
|
224
257
|
}
|
|
225
258
|
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
await dispose()
|
|
261
|
+
throw error
|
|
262
|
+
}
|
|
226
263
|
|
|
227
|
-
return { router, rewrites,
|
|
264
|
+
return { router, rewrites, healthChecks, ...createMiddlewareLookup(scopedMiddlewares), rateLimits, dispose }
|
|
228
265
|
}
|
|
229
266
|
|
|
230
267
|
export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>
|
package/src/server/public.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// `prunelle/server`: what an app's routes, actions and middleware use, and `createServer` to run a built app inside another program. Anything not listed here stays internal.
|
|
2
2
|
|
|
3
3
|
export { action, getActionError } from './action'
|
|
4
|
-
export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
|
|
4
|
+
export type { ActionContext, ActionErrorFlash, ActionOptions, ActionProtectOptions, ActionResult, ServerAction } from './action'
|
|
5
|
+
export { safeEqual } from './app-secret'
|
|
5
6
|
export type { ConsentConfig, RequestConsent } from './consent'
|
|
6
7
|
export type { CookieOptions, Cookies } from './cookies'
|
|
7
8
|
export { defineEnv, nodeEnv } from './env'
|
|
@@ -9,11 +10,11 @@ export { notFound, wantsJson } from './http'
|
|
|
9
10
|
export type { ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
|
|
10
11
|
export type { PrunelleLocals } from './index'
|
|
11
12
|
export { createServer } from './loader'
|
|
12
|
-
export { createRateLimitStore } from './rate-limit'
|
|
13
|
+
export { createRateLimitStore, rateLimitAddress } from './rate-limit'
|
|
13
14
|
export type { RateLimit, RateLimiter, RateLimitStore, RateLimitStoreOptions } from './rate-limit'
|
|
14
15
|
export { readStringFields } from './request-body'
|
|
15
|
-
export { getClientIp, isHttpsRequest, isTrustedOrigin,
|
|
16
|
-
export type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
16
|
+
export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin, safeRedirect, verifyOrigin } from './security'
|
|
17
|
+
export type { CspDirectives, SecurityHeadersOptions, TrustProxy } from './security'
|
|
17
18
|
export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
|
|
18
19
|
export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
|
|
19
|
-
export { esc, escAttr, escJson, raw } from '../ssr/index'
|
|
20
|
+
export { esc, escAttr, escJson, escXml, raw } from '../ssr/index'
|