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.
Files changed (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -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 }
@@ -10,9 +10,11 @@ import type { NormalizedConsentConfig } from './consent'
10
10
  import type { CookieStore } from './cookies'
11
11
  import type { HtmlHeaders } from './document'
12
12
  import type { NotifyError } from './errors'
13
- import type { Middleware, RequestContext } from './http'
13
+ import type { DevTiming, RequestIdResolver } from './health'
14
+ import type { DeniedInfo, Middleware, RequestContext } from './http'
14
15
  import type { PrunelleLocals } from './index'
15
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
+ import type { ParamMatcherMap } from './param-matchers'
16
18
  import type { RequestPath } from './request-path'
17
19
  import type { TrustProxy } from './security'
18
20
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
@@ -20,18 +22,24 @@ import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
20
22
  import { keepScrollTag } from '../ssr/navigation'
21
23
  import { compressedHtmlResponse, maybeCompressResponse } from './compress'
22
24
  import { headTagStyleHashes, mergeStyleHashes } from './document'
23
- import { isNotFound, makeRequestContext } from './http'
25
+ import { createTiming, endTimer, finishRenderTiming, formatServerTiming, resolveFallbackRequestId, startTimer } from './health'
26
+ import { acceptsHtml, getDeniedInfo, isNotFound, makeRequestContext } from './http'
24
27
  import { pickPageIslandProps } from './page'
28
+ import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
25
29
  import { withRegionVary } from './region'
26
- import { pathPrefix } from './request-path'
30
+ import { decodeRequestPath, pathPrefix } from './request-path'
27
31
  import { Router } from './router'
28
32
  import { styleHashesOf } from './security'
29
33
 
30
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 = /^\[([^\[\]]+)\]$/
31
39
  const CATCH_ALL_BRACKET_RE = /\[\.\.\.([^\]]+)\]/g
32
40
  const PARAM_BRACKET_RE = /\[([^\]]+)\]/g
33
41
 
34
- export type FastHandler = (req: Request, remoteIp?: string, url?: URL) => Response | Promise<Response>
42
+ export type FastHandler = (req: Request, remoteIp?: string, url?: URL, requestId?: string) => Response | Promise<Response>
35
43
 
36
44
 
37
45
  export function methodNotAllowed(allow: string): Response {
@@ -42,7 +50,14 @@ export function methodNotAllowed(allow: string): Response {
42
50
  export function toBunRouteKey(path: string): string | undefined {
43
51
  if (path.includes('*'))
44
52
  return undefined
45
- return path.split('/').map(encodeURIComponent).join('/')
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('/')
46
61
  }
47
62
 
48
63
  function dirnamePrefix(file: string): string {
@@ -50,10 +65,26 @@ function dirnamePrefix(file: string): string {
50
65
  return slash === -1 ? '' : file.slice(0, slash + 1)
51
66
  }
52
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
+
53
81
  function dirToRoutePattern(relDir: string): string {
54
82
  if (relDir === '')
55
83
  return '/'
56
- return `/${relDir.replace(CATCH_ALL_BRACKET_RE, '*$1').replace(PARAM_BRACKET_RE, ':$1')}`
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('/')}`
57
88
  }
58
89
 
59
90
  /** Infers the compiled module prefix for files under `routesDir` (e.g. `'server/'` or `'server/src/routes/'`). */
@@ -66,9 +97,17 @@ export function inferRoutesServerPrefix(manifest: BuildManifest): string {
66
97
  const fileParts = route.file.split('/')
67
98
  const pathSegs = route.path === '/' ? [] : route.path.replace(/^\/|\/$/g, '').split('/')
68
99
  const isIndex = fileParts[fileParts.length - 1] === 'index.js'
69
- const routePartCount = pathSegs.length + (isIndex ? 1 : 0)
70
- if (routePartCount <= fileParts.length) {
71
- const prefixParts = fileParts.slice(0, fileParts.length - routePartCount)
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)
72
111
  return prefixParts.length === 0 ? '' : `${prefixParts.join('/')}/`
73
112
  }
74
113
  }
@@ -107,6 +146,7 @@ export function createAncestorMiddlewareLookup(
107
146
  manifest: BuildManifest,
108
147
  modules: Record<string, unknown>,
109
148
  routesPrefix: string,
149
+ paramMatchers: ParamMatcherMap = BUILTIN_PARAM_MATCHERS,
110
150
  ): (path: RequestPath) => AncestorMiddlewareMatch | undefined {
111
151
  const byPattern = new Map<string, Middleware[]>()
112
152
  const seenModules = new Set<string>()
@@ -122,6 +162,9 @@ export function createAncestorMiddlewareLookup(
122
162
  return
123
163
  const rel = modKey.slice(routesPrefix.length)
124
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
125
168
  const pattern = dirToRoutePattern(relDir)
126
169
  let list = byPattern.get(pattern)
127
170
  if (list === undefined) {
@@ -147,7 +190,7 @@ export function createAncestorMiddlewareLookup(
147
190
  if (byPattern.size === 0)
148
191
  return () => undefined
149
192
 
150
- const dirRouter = new Router<Middleware[]>()
193
+ const dirRouter = new Router<Middleware[]>(paramMatchers)
151
194
  for (const [pattern, list] of byPattern)
152
195
  dirRouter.add(pattern, list)
153
196
 
@@ -182,36 +225,18 @@ export interface FastStaticPageOptions {
182
225
  htmlHeaders: HtmlHeaders
183
226
  compressCache: CompressionCache | undefined
184
227
  actions: ActionRegistry
185
- buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext) => Promise<Response>
186
- renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
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
187
231
  notifyError: NotifyError
188
- finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
232
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
189
233
  withHsts: (res: Response, request: Request) => Response
234
+ dev?: boolean | undefined
235
+ resolveRequestId?: RequestIdResolver | undefined
236
+ httpsSite?: boolean | undefined
190
237
  }
191
238
 
192
- /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
193
- export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
194
- const {
195
- entry,
196
- mod,
197
- layouts,
198
- doc,
199
- reviveScript,
200
- hasIslands,
201
- hasLoad,
202
- trustProxy,
203
- consent,
204
- htmlHeaders,
205
- compressCache,
206
- actions,
207
- buildNotFoundResponse,
208
- renderError,
209
- notifyError,
210
- finish,
211
- withHsts,
212
- } = options
213
-
214
- const eagerChunks = entry.eagerIslandChunks ?? entry.islandChunks
239
+ function buildFastDocShell(doc: DocumentOptions, eagerChunks: string[], reviveScript: string | undefined, hasIslands: boolean): { docPrefix: string, revivingPrefix: string, docSuffix: string } {
215
240
  const shellAround = (preloadChunks: string[]): [string, string] => {
216
241
  const shell = renderDocument({ ...doc, body: '\0', preloadChunks, hasIslands })
217
242
  const splitAt = shell.indexOf('\0')
@@ -219,46 +244,59 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
219
244
  }
220
245
  const [docPrefix, docSuffix] = shellAround(eagerChunks)
221
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)
222
256
  const headStyleHashes = headTagStyleHashes(doc.headTags)
223
257
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
224
258
 
225
259
  const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
226
- notifyError(error, request, 'route')
227
- return renderError(error, cookieStore, url, request, ctx)
260
+ notifyError(error, request, 'route', ctx?.requestId)
261
+ return renderError(error, cookieStore, url, request, ctx, entry.file)
228
262
  }
229
- const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore?: CookieStore): Response => {
263
+ const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response => {
230
264
  const html = (rctx.revives ? revivingPrefix : docPrefix) + body + keepScrollTag(body) + docSuffix
231
265
  const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
232
266
  const headers = withRegionVary(htmlHeaders(hasIslands, false, true, styleHashes), rctx.regionNames.size > 0)
267
+ const st = timing !== undefined ? finishRenderTiming(timing) : undefined
233
268
  const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
234
- return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
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)
235
273
  }
236
274
  const layoutProps = (inner: string, url: URL, locals: PrunelleLocals) => ({ children: raw(inner), url, params: {}, locals })
237
275
 
238
- const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
276
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
239
277
  try {
240
- return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore)
278
+ return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore, ctx, timing)
241
279
  }
242
280
  catch (error) {
243
281
  return fail(error, request, url, cookieStore, ctx)
244
282
  }
245
283
  }
246
284
 
247
- const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
285
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
248
286
  if (layouts.length === 0)
249
- return respondHtml(inner, request, rctx, cookieStore)
287
+ return respondHtml(inner, request, rctx, cookieStore, ctx, timing)
250
288
  if (singleLayout !== undefined) {
251
289
  const wrapped = singleLayout.default(layoutProps(inner, url, locals))
252
290
  if (wrapped instanceof Promise)
253
- return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx)
254
- return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore)
291
+ return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx, timing)
292
+ return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore, ctx, timing)
255
293
  }
256
294
  return (async () => {
257
295
  try {
258
296
  let cur = inner
259
297
  for (let i = layouts.length - 1; i >= 0; i--)
260
298
  cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
261
- return respondHtml(cur, request, rctx, cookieStore)
299
+ return respondHtml(cur, request, rctx, cookieStore, ctx, timing)
262
300
  }
263
301
  catch (error) {
264
302
  return fail(error, request, url, cookieStore, ctx)
@@ -266,16 +304,18 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
266
304
  })()
267
305
  }
268
306
 
269
- const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
307
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
270
308
  try {
271
- return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx)
309
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
272
310
  }
273
311
  catch (error) {
274
312
  return fail(error, request, url, cookieStore, ctx)
275
313
  }
276
314
  }
277
315
 
278
- const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
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()
279
319
  const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
280
320
  if (entry.isIsland && entry.islandChunk !== undefined) {
281
321
  return wrapLayouts(ssrIsland(
@@ -285,47 +325,56 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
285
325
  entry.islandHydrate as HydrateStrategy | undefined,
286
326
  true,
287
327
  mod.default!.name,
288
- ), request, url, locals, rctx, cookieStore, ctx)
328
+ ), request, url, locals, rctx, cookieStore, ctx, timing)
289
329
  }
290
330
  const rendered = mod.default!(pageProps)
291
331
  if (rendered instanceof Promise)
292
- return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx)
293
- return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx)
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)
294
334
  }
295
335
 
296
- return (request, remoteIp, url = new URL(request.url)) => {
297
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent })
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 })
298
340
  if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
299
341
  return actions.run(ctx, async () => {
300
342
  try {
301
- return finish(await mod.HEAD!(ctx), request, cookieStore)
343
+ return finish(await mod.HEAD!(ctx), request, cookieStore, reqId, formatServerTiming(timing))
302
344
  }
303
345
  catch (error) {
304
346
  return fail(error, request, url, cookieStore, ctx)
305
347
  }
306
348
  })
307
349
  }
308
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route'))
350
+ const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route', reqId))
309
351
  try {
310
352
  if (!hasLoad)
311
- return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx)))
353
+ return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx, timing)))
312
354
 
313
355
  return actions.run(ctx, async () => {
314
356
  let loaded: unknown
357
+ const loadStart = startTimer(timing)
315
358
  try {
316
359
  loaded = await mod.load!(ctx)
317
360
  }
318
361
  catch (error) {
319
362
  if (isNotFound(error))
320
- return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx), request, compressCache), request, cookieStore)
363
+ return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
321
364
  return fail(error, request, url, cookieStore, ctx)
322
365
  }
366
+ endTimer(timing, 'load', loadStart)
323
367
  if (isNotFound(loaded))
324
- return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx), request, compressCache), request, cookieStore)
325
- if (loaded instanceof Response)
326
- return finish(await maybeCompressResponse(loaded, request, compressCache), request, cookieStore)
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
+ }
327
376
  try {
328
- return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx))
377
+ return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx, timing))
329
378
  }
330
379
  catch (error) {
331
380
  return fail(error, request, url, cookieStore, ctx)