prunelle 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/llms.txt +12 -12
  2. package/package.json +1 -1
  3. package/src/build/client-entries.ts +3 -2
  4. package/src/build/compile.ts +2 -1
  5. package/src/build/index.ts +68 -29
  6. package/src/build/manifest.ts +18 -1
  7. package/src/build/output.ts +2 -2
  8. package/src/build/precompress.ts +15 -2
  9. package/src/build/prerender.ts +2 -2
  10. package/src/build/routes.ts +171 -10
  11. package/src/build/static.ts +71 -17
  12. package/src/build/status-pages.ts +127 -0
  13. package/src/cli/check-forms.ts +654 -0
  14. package/src/cli/check-links.ts +619 -0
  15. package/src/cli/check.ts +37 -4
  16. package/src/cli/commands.ts +5 -3
  17. package/src/cli/inspect.ts +21 -2
  18. package/src/cli/upgrade-names.ts +73 -13
  19. package/src/cli/upgrade.ts +137 -16
  20. package/src/compiler/compliance-rgaa.ts +502 -0
  21. package/src/compiler/compliance.ts +119 -220
  22. package/src/compiler/ssr.ts +121 -24
  23. package/src/dom/action.ts +4 -1
  24. package/src/dom/island.ts +5 -5
  25. package/src/plugins/config.ts +1 -1
  26. package/src/plugins/types.ts +13 -0
  27. package/src/server/action-protect.ts +186 -0
  28. package/src/server/action.ts +33 -10
  29. package/src/server/errors.ts +291 -62
  30. package/src/server/form-schema.ts +343 -0
  31. package/src/server/health.ts +244 -0
  32. package/src/server/http.ts +84 -17
  33. package/src/server/index.ts +162 -91
  34. package/src/server/param-matchers.ts +112 -0
  35. package/src/server/plugin-host.ts +40 -14
  36. package/src/server/public.ts +3 -3
  37. package/src/server/route-table.ts +5 -2
  38. package/src/server/router.ts +125 -40
  39. package/src/server/routing.ts +95 -57
  40. package/src/server/security.ts +171 -22
  41. package/src/server/serve-handlers.ts +21 -7
  42. package/src/ssr/context.ts +49 -0
  43. package/src/ssr/index.ts +120 -1
  44. package/src/test/browser.ts +6 -0
  45. package/src/test/index.ts +17 -3
  46. package/templates/_shared/src/routes/legal.tsx +5 -0
  47. package/templates/blog/prunelle.config.ts +1 -1
  48. package/templates/blog/src/routes/index.tsx +4 -0
@@ -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 {
@@ -59,6 +64,14 @@ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string,
59
64
  return normPath === normScope || normPath.startsWith(`${normScope}/`)
60
65
  }
61
66
 
67
+ /** 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. */
68
+ export function takesEncoded(match: RouteMatch<Map<string, PluginRouteDef>> | undefined, path: RequestPath): RouteMatch<Map<string, PluginRouteDef>> | undefined {
69
+ if (match === undefined || path.encoded === undefined || path.encoded.size === 0)
70
+ return match
71
+ const data = new Map([...match.data].filter(([, def]) => def.encodedSlashes))
72
+ return data.size === 0 ? undefined : { data, params: match.params }
73
+ }
74
+
62
75
  export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
63
76
  const allowed = new Set<string>()
64
77
  for (const m of methods.keys()) {
@@ -71,11 +84,25 @@ export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRo
71
84
  return [...allowed].join(', ')
72
85
  }
73
86
 
87
+ function assertRouteFree(pluginName: string, upperMethod: string, normPath: string, byMethod: ReadonlyMap<string, PluginRouteDef>): void {
88
+ const directConflict = byMethod.get(upperMethod)
89
+ if (directConflict !== undefined)
90
+ throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with "${directConflict.plugin}". Mount one of the plugins on a different path.`)
91
+ if (upperMethod === 'ALL' && byMethod.size > 0) {
92
+ const [existingMethod, existingDef] = byMethod.entries().next().value!
93
+ 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.`)
94
+ }
95
+ const allConflict = byMethod.get('ALL')
96
+ if (allConflict !== undefined)
97
+ 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.`)
98
+ }
99
+
74
100
  export async function createServerPluginHost(options: ServerPluginHostOptions) {
75
101
  const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
76
102
  // The counters of every limited route and action of this server, dropped with it.
77
103
  const rateLimits = createRateLimitStore()
78
104
  const scopedMiddlewares: ScopedMiddleware[] = []
105
+ const healthChecks: HealthCheckEntry[] = []
79
106
  const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
80
107
  const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
81
108
  const router = new Router<Map<string, PluginRouteDef>>()
@@ -89,25 +116,20 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
89
116
  ): void => {
90
117
  const upperMethod = method.toUpperCase()
91
118
  const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
119
+ const encodedSlashes = routeOptions?.encodedSlashes === true
120
+ if (encodedSlashes && !normPath.split('/').some(seg => seg.startsWith('*')))
121
+ 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
122
  let byMethod = routeEntries.get(normPath)
93
123
  if (byMethod === undefined) {
94
124
  byMethod = new Map()
95
125
  routeEntries.set(normPath, byMethod)
96
- router.add(normPath, byMethod)
126
+ router.add(normPath, byMethod, { encodedSlashes })
97
127
  }
98
128
  else {
99
- const directConflict = byMethod.get(upperMethod)
100
- if (directConflict !== undefined) {
101
- throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with "${directConflict.plugin}". Mount one of the plugins on a different path.`)
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
- }
129
+ assertRouteFree(pluginName, upperMethod, normPath, byMethod)
130
+ // The path matches encoded separators once any method takes them; takesEncoded still refuses them to the others.
131
+ if (encodedSlashes)
132
+ router.add(normPath, byMethod, { encodedSlashes })
111
133
  }
112
134
  let routeTrustedOrigins = trustedOrigins
113
135
  if (routeOptions?.trustedOrigins !== undefined && routeOptions.trustedOrigins.length > 0) {
@@ -129,6 +151,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
129
151
  csrf: routeOptions?.csrf ?? true,
130
152
  trustedOrigins: routeTrustedOrigins,
131
153
  trustProxy: routeOptions?.trustProxy ?? trustProxy,
154
+ encodedSlashes,
132
155
  })
133
156
  }
134
157
 
@@ -179,6 +202,9 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
179
202
  getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
180
203
  return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
181
204
  },
205
+ healthCheck(name, fn) {
206
+ healthChecks.push({ name, fn })
207
+ },
182
208
  onShutdown(fn) {
183
209
  shutdownHooks.push({ plugin: plugin.name, hook: fn })
184
210
  },
@@ -224,7 +250,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
224
250
  }
225
251
  }
226
252
 
227
- return { router, rewrites, allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths, rateLimits, dispose }
253
+ return { router, rewrites, healthChecks, allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths, rateLimits, dispose }
228
254
  }
229
255
 
230
256
  export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>
@@ -1,7 +1,7 @@
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
5
  export type { ConsentConfig, RequestConsent } from './consent'
6
6
  export type { CookieOptions, Cookies } from './cookies'
7
7
  export { defineEnv, nodeEnv } from './env'
@@ -12,8 +12,8 @@ export { createServer } from './loader'
12
12
  export { createRateLimitStore } from './rate-limit'
13
13
  export type { RateLimit, RateLimiter, RateLimitStore, RateLimitStoreOptions } from './rate-limit'
14
14
  export { readStringFields } from './request-body'
15
- export { getClientIp, isHttpsRequest, isTrustedOrigin, safeEqual, safeRedirect, verifyOrigin } from './security'
16
- export type { SecurityHeadersOptions, TrustProxy } from './security'
15
+ export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin, safeEqual, safeRedirect, verifyOrigin } from './security'
16
+ export type { CspDirectives, SecurityHeadersOptions, TrustProxy } from './security'
17
17
  export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
18
18
  export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
19
19
  export { esc, escAttr, escJson, raw } from '../ssr/index'
@@ -4,10 +4,12 @@ import type { BuildManifest, RouteManifestEntry } from '../build/index'
4
4
  import type { DocumentOptions } from '../ssr/index'
5
5
  import type { Middleware } from './http'
6
6
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
7
+ import type { ParamMatcherMap } from './param-matchers'
7
8
  import type { RequestKind } from './plugin-host'
8
9
  import type { FastHandler, FastStaticPageOptions } from './routing'
9
10
  import { headTagStyleHashes } from './document'
10
11
  import { mergedHeadTags } from './page'
12
+ import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
11
13
  import { Router } from './router'
12
14
  import { createFastStaticPageHandler } from './routing'
13
15
 
@@ -44,6 +46,7 @@ type SharedFastOptions = Omit<FastStaticPageOptions, 'entry' | 'mod' | 'layouts'
44
46
  export interface RouteTableOptions {
45
47
  manifest: BuildManifest
46
48
  modules: Record<string, unknown>
49
+ paramMatchers?: ParamMatcherMap | undefined
47
50
  lang: string
48
51
  alwaysLoadRuntime: boolean
49
52
  navigation: DocumentOptions['navigation']
@@ -54,8 +57,8 @@ export interface RouteTableOptions {
54
57
  }
55
58
 
56
59
  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>()
60
+ const { manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation, middlewaresFor, pluginIntercepts, fast } = options
61
+ const router = new Router<CompiledRoute>(paramMatchers ?? BUILTIN_PARAM_MATCHERS)
59
62
  const fastStaticPages = new Map<string, FastHandler>()
60
63
  for (const entry of manifest.routes) {
61
64
  const mod = modules[entry.file] as LoadedPageModule
@@ -1,18 +1,23 @@
1
- // File-based route matcher: static > [param] > [...catchall] priority sorting + param extraction.
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
- CatchAll = 2,
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: Static (3) > Param (2) > End of exact route (1) > CatchAll (0).
37
- * Lexicographic comparison guarantees exact static > exact parametric > catch-all for any shared prefix
38
- * (e.g. `/docs/:slug` beats `/docs/:section/*rest`, and `/docs/:a/:b` beats `/docs/*rest`).
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 1
58
+ return 2
43
59
  if (seg.kind === SegmentKind.Static)
44
- return 3
60
+ return 9
45
61
  if (seg.kind === SegmentKind.Param)
46
- return 2
47
- return 0
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 0
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 compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
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 segments: CompiledSegment[] = []
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 seg = rawSegments[i]!
70
- if (seg.startsWith('*')) {
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
- segments.push({ kind: SegmentKind.CatchAll, value: seg.slice(1) || 'rest' })
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
- return { path: norm, segments, isStatic, hasCatchAll, data }
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
- add(path: string, data: T): void {
93
- const compiled = compileRoutePattern(path, data)
94
- if (compiled.isStatic) {
95
- this.#staticRoutes.set(compiled.path, data)
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
- else {
98
- const existing = this.#dynamicRoutes.findIndex(r => r.path === compiled.path)
99
- if (existing !== -1)
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 refused = (k: number): boolean => path.encoded?.has(k) === true || parts[k] === '.' || parts[k] === '..'
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.Param ? refused(j) : seg.value !== parts[j] || path.encoded?.has(j) === true) {
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 }