prunelle 0.1.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/llms.txt +23 -19
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +80 -36
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +91 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +654 -0
  27. package/src/cli/check-links.ts +619 -0
  28. package/src/cli/check.ts +52 -5
  29. package/src/cli/commands.ts +86 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +31 -2
  32. package/src/cli/mcp-tools.ts +480 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +261 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +20 -6
  39. package/src/compiler/cacheability.ts +592 -0
  40. package/src/compiler/compliance-rgaa.ts +502 -0
  41. package/src/compiler/compliance.ts +120 -221
  42. package/src/compiler/dev-source.ts +87 -0
  43. package/src/compiler/dom-attrs.ts +138 -65
  44. package/src/compiler/dom.ts +12 -11
  45. package/src/compiler/expr-context.ts +167 -57
  46. package/src/compiler/props.ts +87 -36
  47. package/src/compiler/scope.ts +56 -17
  48. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  49. package/src/compiler/ssr.ts +216 -84
  50. package/src/dev/error-log.ts +151 -0
  51. package/src/dev/index.ts +84 -34
  52. package/src/dev/open-editor.ts +204 -0
  53. package/src/dev/protocol.ts +1 -0
  54. package/src/dev/reload.ts +5 -3
  55. package/src/dev/supervisor.ts +42 -25
  56. package/src/dev/watchers.ts +47 -11
  57. package/src/dom/action.ts +4 -1
  58. package/src/dom/attrs.ts +15 -3
  59. package/src/dom/extras.ts +2 -2
  60. package/src/dom/island.ts +11 -10
  61. package/src/plugins/config.ts +4 -4
  62. package/src/plugins/index.ts +2 -2
  63. package/src/plugins/public.ts +5 -2
  64. package/src/plugins/services.ts +62 -0
  65. package/src/plugins/types.ts +32 -0
  66. package/src/server/action-protect.ts +198 -0
  67. package/src/server/action-registry.ts +1 -1
  68. package/src/server/action.ts +82 -27
  69. package/src/server/assets.ts +34 -2
  70. package/src/server/compress.ts +91 -9
  71. package/src/server/errors.ts +303 -65
  72. package/src/server/form-schema.ts +343 -0
  73. package/src/server/health.ts +244 -0
  74. package/src/server/http.ts +128 -31
  75. package/src/server/index.ts +230 -260
  76. package/src/server/loader.ts +5 -0
  77. package/src/server/param-matchers.ts +112 -0
  78. package/src/server/plugin-host.ts +123 -88
  79. package/src/server/public.ts +3 -3
  80. package/src/server/rate-limit.ts +58 -35
  81. package/src/server/request-body.ts +1 -1
  82. package/src/server/route-cache.ts +423 -0
  83. package/src/server/route-table.ts +339 -8
  84. package/src/server/router.ts +125 -40
  85. package/src/server/routing.ts +196 -63
  86. package/src/server/security.ts +208 -32
  87. package/src/server/serve-handlers.ts +21 -7
  88. package/src/server/start.ts +60 -16
  89. package/src/server/static-dir.ts +61 -8
  90. package/src/server/stream.ts +41 -22
  91. package/src/ssr/context.ts +85 -3
  92. package/src/ssr/index.ts +120 -1
  93. package/src/ssr/region.ts +31 -19
  94. package/src/test/browser.ts +6 -0
  95. package/src/test/index.ts +17 -3
  96. package/src/ts-plugin/diagnostics.ts +378 -0
  97. package/src/ts-plugin/fixes.ts +364 -0
  98. package/src/ts-plugin/index.ts +194 -0
  99. package/templates/_shared/AGENTS.md +2 -2
  100. package/templates/_shared/mcp.json +11 -0
  101. package/templates/_shared/src/routes/legal.tsx +5 -0
  102. package/templates/_shared/tsconfig.json +5 -0
  103. package/templates/blog/prunelle.config.ts +1 -1
  104. package/templates/blog/src/routes/index.tsx +4 -0
  105. package/ts-plugin.cjs +4277 -0
@@ -1,26 +1,101 @@
1
- // Route files: their URL patterns, conflicts, and the `_layout`/`_middleware` chain that wraps them.
1
+ // Route files: their URL patterns, groups, param matchers, conflicts, and the `_layout`/`_middleware` chain that wraps them.
2
2
 
3
3
  import type { ModuleAnalysis } from '../compiler/index'
4
4
  import { existsSync } from 'node:fs'
5
5
  import { basename, dirname, join, relative } from 'node:path'
6
+ import { parseCacheExport } from '../compiler/cacheability'
7
+ import { BUILTIN_PARAM_MATCHER_NAMES, extractPatternMatchers, isBuiltinMatcher, parsePatternSegment } from '../server/param-matchers'
6
8
  import { relPosix } from './files'
7
9
 
8
- export const SPECIAL_ROUTE_FILES = new Set(['_layout.tsx', '_middleware.ts', '_middleware.tsx', '_error.tsx', '_404.tsx'])
10
+ export const SPECIAL_ROUTE_FILES = new Set([
11
+ '_layout.tsx',
12
+ '_middleware.ts',
13
+ '_middleware.tsx',
14
+ '_error.tsx',
15
+ '_404.tsx',
16
+ '_401.tsx',
17
+ '_403.tsx',
18
+ '_429.tsx',
19
+ '_503.tsx',
20
+ ])
9
21
  export const MIDDLEWARE_NAMES = ['_middleware.ts', '_middleware.tsx']
10
22
  const ROUTE_EXPORTS = new Set(['default', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])
11
23
  const TS_EXT_RE = /\.(?:tsx|ts)$/
24
+ const ROUTE_GROUP_RE = /^\(([^/()]+)\)$/
25
+ const OPTIONAL_PARAM_SEG_RE = /^\[\[([^\[\]]+)\]\]$/
26
+ const CATCH_ALL_SEG_RE = /^\[\.\.\.([^\[\]]+)\]$/
27
+ const PARAM_SEG_RE = /^\[([^\[\]]+)\]$/
12
28
  const CATCH_ALL_RE = /\[\.\.\.([^\]]+)\]/g
13
29
  const PARAM_RE = /\[([^\]]+)\]/g
14
30
  const PATH_SEPARATOR_RE = /[/\\]/
15
31
 
32
+ /** True when a route folder segment is a route group such as `(marketing)` or `(admin)`. */
33
+ export function isRouteGroupSegment(segment: string): boolean {
34
+ return ROUTE_GROUP_RE.test(segment)
35
+ }
36
+
37
+ /** True when a relative POSIX directory path contains any `(group)` segment. */
38
+ export function hasRouteGroupInRel(relDir: string): boolean {
39
+ if (relDir === '' || relDir === '.')
40
+ return false
41
+ return relDir.split('/').some(isRouteGroupSegment)
42
+ }
43
+
44
+ /** Returns the `(group)` folder names wrapping `file` under `routesDir`, outermost first. */
45
+ export function routeGroupsOf(routesDir: string, file: string): string[] {
46
+ const relDir = relPosix(routesDir, dirname(file))
47
+ if (relDir === '' || relDir === '.')
48
+ return []
49
+ const groups: string[] = []
50
+ for (const part of relDir.split('/')) {
51
+ const match = ROUTE_GROUP_RE.exec(part)
52
+ if (match !== null)
53
+ groups.push(match[1]!)
54
+ }
55
+ return groups
56
+ }
57
+
58
+ /** Converts one file-system route segment (`about`, `[id=integer]`, `[[lang]]`, `[...path=slug]`) into a router pattern segment. */
59
+ export function convertRouteSegment(segment: string): string {
60
+ const opt = OPTIONAL_PARAM_SEG_RE.exec(segment)
61
+ if (opt !== null)
62
+ return `:${opt[1]}?`
63
+ const catchAll = CATCH_ALL_SEG_RE.exec(segment)
64
+ if (catchAll !== null)
65
+ return `*${catchAll[1]}`
66
+ const param = PARAM_SEG_RE.exec(segment)
67
+ if (param !== null)
68
+ return `:${param[1]}`
69
+ return segment.replace(CATCH_ALL_RE, '*$1').replace(PARAM_RE, ':$1')
70
+ }
71
+
72
+ /** Converts a relative POSIX directory path under `routesDir` into a URL folder pattern, stripping `(group)` folders. */
73
+ export function dirToRoutePatternFromRel(relDir: string): string {
74
+ if (relDir === '' || relDir === '.')
75
+ return '/'
76
+ const parts = relDir.split('/').filter(p => p !== '' && !isRouteGroupSegment(p))
77
+ if (parts.length === 0)
78
+ return '/'
79
+ return `/${parts.map(convertRouteSegment).join('/')}`
80
+ }
81
+
16
82
  /** A file in routes/ is a route when it exports a default component or an HTTP method handler, directly or through `export { ... }`. */
17
83
  export function hasRouteHandlerExport(analysis: ModuleAnalysis): boolean {
18
84
  return analysis.exportedNames.some(name => ROUTE_EXPORTS.has(name))
19
85
  }
20
86
 
21
- const SPECIAL_FILE_DEFAULTS = new Map([['_layout', 'layout component'], ['_middleware', 'middleware function'], ['_error', 'error page component'], ['_404', 'not-found page component']])
87
+ const SPECIAL_FILE_DEFAULTS = new Map([
88
+ ['_layout', 'layout component'],
89
+ ['_middleware', 'middleware function'],
90
+ ['_error', 'error page component'],
91
+ ['_404', 'not-found page component'],
92
+ ['_401', '401 status page component'],
93
+ ['_403', '403 status page component'],
94
+ ['_429', '429 status page component'],
95
+ ['_503', '503 status page component'],
96
+ ])
22
97
 
23
- /** For a route file or a `_layout`, `_middleware`, `_error` or `_404`, what prunelle would otherwise drop or fail on per request: neither a route nor an action, which its folder's middleware guards, or no default export. `routesRel` is the routes folder as the app writes it. */
98
+ /** For a route file or a special route file (`_layout`, `_middleware`, `_error`, `_404`, `_401`, `_403`, `_429`, `_503`), reports missing default export or non-route files. */
24
99
  export function routeFileProblem(analysis: ModuleAnalysis, file: string, routesRel: string): string | undefined {
25
100
  const name = basename(file)
26
101
  if (SPECIAL_ROUTE_FILES.has(name))
@@ -88,6 +163,9 @@ export function routeExportProblemLocation(analysis: ModuleAnalysis, file: strin
88
163
  return { message: `${init?.type === 'Literal' ? `prerender = ${init.raw ?? String(init.value)}` : 'prerender set at runtime'} in ${file}: write prerender = true or prerender = false.`, offset: d.start }
89
164
  }
90
165
  }
166
+ const cacheExport = parseCacheExport(analysis.program)
167
+ if (cacheExport.problem !== undefined)
168
+ return { message: `${cacheExport.problem.replace(':', ` in ${file}:`)}.`, offset: cacheExport.offset }
91
169
  return undefined
92
170
  }
93
171
 
@@ -131,21 +209,37 @@ export function assertPathUrls(urls: unknown, file: string): asserts urls is str
131
209
 
132
210
  export function fileToRoutePath(routesDir: string, file: string): string {
133
211
  const rel = relPosix(routesDir, file).replace(TS_EXT_RE, '')
134
- if (rel === 'index')
212
+ const rawParts = rel.split('/')
213
+ const filePart = rawParts.pop()!
214
+ const urlParts = rawParts.filter(part => !isRouteGroupSegment(part))
215
+ if (filePart !== 'index')
216
+ urlParts.push(filePart)
217
+ if (urlParts.length === 0)
135
218
  return '/'
136
- const clean = rel.endsWith('/index') ? rel.slice(0, -'/index'.length) : rel
137
- return `/${clean.replace(CATCH_ALL_RE, '*$1').replace(PARAM_RE, ':$1')}`
219
+ return `/${urlParts.map(convertRouteSegment).join('/')}`
138
220
  }
139
221
 
140
- /** The shape two route paths conflict on: parameter names do not matter. */
222
+ /** The shape two route paths conflict on: parameter names do not matter, but optionality and matcher names do. */
141
223
  export function normalizeRoutePattern(routePath: string): string {
142
224
  return routePath
143
225
  .split('/')
144
- .map(seg => (seg.startsWith(':') ? ':' : seg.startsWith('*') ? '*' : seg))
226
+ .map((seg) => {
227
+ if (seg === '')
228
+ return ''
229
+ const parsed = parsePatternSegment(seg)
230
+ const matcher = parsed.matcherName !== undefined ? `=${parsed.matcherName}` : ''
231
+ if (parsed.kind === 'catchall')
232
+ return `*${matcher}`
233
+ if (parsed.kind === 'optional')
234
+ return `:${matcher}?`
235
+ if (parsed.kind === 'param')
236
+ return `:${matcher}`
237
+ return parsed.value
238
+ })
145
239
  .join('/')
146
240
  }
147
241
 
148
- /** Throws on two route files that serve one pattern (about.tsx vs about/index.tsx, [id].tsx vs [slug].tsx). */
242
+ /** Throws on two route files that serve one pattern (about.tsx vs about/index.tsx, (a)/about.tsx vs (b)/about.tsx, [id].tsx vs [slug].tsx). */
149
243
  export function assertNoRouteConflicts(root: string, routesDir: string, pageFiles: string[]): void {
150
244
  const seen = new Map<string, { file: string, path: string }>()
151
245
  for (const file of pageFiles) {
@@ -158,6 +252,77 @@ export function assertNoRouteConflicts(root: string, routesDir: string, pageFile
158
252
  }
159
253
  }
160
254
 
255
+ /** Resolves an app-defined param matcher file (`src/params/<name>.ts` or `.tsx`, or `<routesDir>/../params/<name>.ts`). */
256
+ export function findCustomMatcherFile(root: string, routesDir: string, matcherName: string): string | undefined {
257
+ const candidates = [
258
+ join(root, 'src/params', `${matcherName}.ts`),
259
+ join(root, 'src/params', `${matcherName}.tsx`),
260
+ join(dirname(routesDir), 'params', `${matcherName}.ts`),
261
+ join(dirname(routesDir), 'params', `${matcherName}.tsx`),
262
+ ]
263
+ for (const candidate of candidates) {
264
+ if (existsSync(candidate))
265
+ return candidate
266
+ }
267
+ return undefined
268
+ }
269
+
270
+ export interface MatcherDiscoveryResult {
271
+ /** Custom (non-built-in) matcher name -> absolute source file path. */
272
+ customFiles: Map<string, string>
273
+ /** Missing or invalid matcher diagnostics. */
274
+ problems: { file: string, message: string }[]
275
+ }
276
+
277
+ /** Discovers and validates every param matcher referenced by route patterns (and directory patterns of middleware/status pages). */
278
+ export function discoverRouteMatchers(options: {
279
+ root: string
280
+ routesDir: string
281
+ routeFiles: readonly string[]
282
+ loadAnalysis: (file: string) => ModuleAnalysis | undefined
283
+ }): MatcherDiscoveryResult {
284
+ const { root, routesDir, routeFiles, loadAnalysis } = options
285
+ const customFiles = new Map<string, string>()
286
+ const problems: { file: string, message: string }[] = []
287
+ const validatedCustom = new Set<string>()
288
+ const builtinList = BUILTIN_PARAM_MATCHER_NAMES.join(', ')
289
+
290
+ for (const file of routeFiles) {
291
+ const pattern = basename(file).startsWith('_')
292
+ ? dirToRoutePatternFromRel(relPosix(routesDir, dirname(file)))
293
+ : fileToRoutePath(routesDir, file)
294
+ const refs = extractPatternMatchers(pattern)
295
+ if (refs.length === 0)
296
+ continue
297
+ const rel = relPosix(root, file)
298
+ for (const { matcher } of refs) {
299
+ if (isBuiltinMatcher(matcher))
300
+ continue
301
+ const found = findCustomMatcherFile(root, routesDir, matcher)
302
+ if (found === undefined) {
303
+ problems.push({
304
+ file,
305
+ message: `unknown param matcher "${matcher}" in ${rel}: use a built-in matcher (${builtinList}) or create src/params/${matcher}.ts exporting match(value: string): boolean (or a default function).`,
306
+ })
307
+ continue
308
+ }
309
+ customFiles.set(matcher, found)
310
+ if (!validatedCustom.has(found)) {
311
+ validatedCustom.add(found)
312
+ const analysis = loadAnalysis(found)
313
+ if (analysis !== undefined && !analysis.exportedNames.includes('match') && !analysis.exportedNames.includes('default')) {
314
+ problems.push({
315
+ file: found,
316
+ message: `${relPosix(root, found)} exports no param matcher: export function match(value: string): boolean (or export default).`,
317
+ })
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ return { customFiles, problems }
324
+ }
325
+
161
326
  /** Finds all ancestor files named one of `names` from routesDir down to dirname(routeFile), outermost first. */
162
327
  export function ancestorFiles(routesDir: string, routeFile: string, names: string[]): string[] {
163
328
  const result: string[] = []
@@ -3,18 +3,21 @@
3
3
  import type { PrunellePlugin } from '../plugins/index'
4
4
  import type { ServerEntry } from '../server/app-entry'
5
5
  import type { PrunelleApp } from '../server/index'
6
- import type { BuildManifest } from './manifest'
6
+ import type { BuildManifest, StatusPageManifestEntry } from './manifest'
7
7
  import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs'
8
8
  import { dirname, join, relative } from 'node:path'
9
9
  import { resolvePlugins } from '../plugins/index'
10
10
  import { createDocumentHooks, createHtmlHeaders } from '../server/document'
11
- import { createNavigation } from '../ssr/navigation'
12
11
  import { createFallbackPages } from '../server/errors'
13
- import { walkAllFiles } from './files'
14
- import { precompressFiles } from './precompress'
12
+ import { resolveParamMatchers } from '../server/param-matchers'
13
+ import { prerenderOrigin } from '../server/prerendered'
14
+ import { inferRoutesServerPrefix } from '../server/routing'
15
+ import { injectMetaCsp } from '../server/security'
16
+ import { createNavigation } from '../ssr/navigation'
15
17
  import { carryPreviousAssets } from './carry'
18
+ import { walkAllFiles } from './files'
16
19
  import { swapStage } from './output'
17
- import { prerenderOrigin } from '../server/prerendered'
20
+ import { precompressFiles } from './precompress'
18
21
  import { pageFailure } from './prerender'
19
22
 
20
23
  const LEADING_SLASH_RE = /^\//
@@ -36,9 +39,11 @@ export interface StaticExportOptions {
36
39
  pluginOverride?: PrunellePlugin[] | undefined
37
40
  assets: string[]
38
41
  publicFiles: { files: string[], register: (relPath: string) => string }
39
- /** The server the pages were prerendered with, fallback if `entry` is absent. */
42
+ /** The server the pages were prerendered with, holding plugin services, rewrites and middlewares. */
40
43
  app: PrunelleApp | undefined
44
+ errorFor?: ((url: string) => unknown) | undefined
41
45
  hasNotFoundFile: boolean
46
+ notFoundEmitted?: boolean | undefined
42
47
  stageSuffix: string
43
48
  }
44
49
 
@@ -48,47 +53,140 @@ function copyInto(dstRoot: string, rel: string, src: string): void {
48
53
  copyFileSync(src, dst)
49
54
  }
50
55
 
51
- async function renderStaticNotFound(options: StaticExportOptions): Promise<string> {
56
+ interface StaticNotFoundTarget {
57
+ outRel: string
58
+ urlPath: string
59
+ routeFile?: string | undefined
60
+ }
61
+
62
+ function staticNotFoundTargets(manifest: BuildManifest, hasNotFoundFile: boolean): StaticNotFoundTarget[] {
63
+ const targets: StaticNotFoundTarget[] = []
64
+ const seen = new Set<string>()
65
+ const statusPages: StatusPageManifestEntry[] = manifest.statusPages ?? []
66
+ for (const entry of statusPages) {
67
+ if (entry.kind !== '404' || entry.inGroup === true)
68
+ continue
69
+ if (entry.dirPattern.includes(':') || entry.dirPattern.includes('*'))
70
+ continue
71
+ const cleanDir = entry.dirPattern === '/' ? '' : entry.dirPattern.replace(LEADING_SLASH_RE, '')
72
+ const outRel = cleanDir === '' ? '404.html' : `${cleanDir}/404.html`
73
+ if (seen.has(outRel))
74
+ continue
75
+ seen.add(outRel)
76
+ targets.push({
77
+ outRel,
78
+ urlPath: cleanDir === '' ? '/404' : `/${cleanDir}/404`,
79
+ routeFile: entry.file,
80
+ })
81
+ }
82
+ if (hasNotFoundFile && !seen.has('404.html'))
83
+ targets.push({ outRel: '404.html', urlPath: '/404' })
84
+ return targets
85
+ }
86
+
87
+ export interface StaticNotFoundOptions {
88
+ stageDir: string
89
+ site?: string | undefined
90
+ isDev?: boolean | undefined
91
+ manifest: BuildManifest
92
+ entry: ServerEntry | undefined
93
+ pluginOverride?: PrunellePlugin[] | undefined
94
+ app: PrunelleApp | undefined
95
+ errorFor?: ((url: string) => unknown) | undefined
96
+ hasNotFoundFile: boolean
97
+ }
98
+
99
+ function hasCatchAllRoute(manifest: BuildManifest): boolean {
100
+ return manifest.routes.some(r => r.path.includes('*'))
101
+ }
102
+
103
+ function writeStaticNotFound(stageDir: string, outRel: string, html: string, csp: string | null): void {
104
+ const outAbs = join(stageDir, outRel)
105
+ mkdirSync(dirname(outAbs), { recursive: true })
106
+ writeFileSync(outAbs, injectMetaCsp(html, csp))
107
+ }
108
+
109
+ export async function emitStaticNotFoundPages(options: StaticNotFoundOptions): Promise<void> {
110
+ const targets = staticNotFoundTargets(options.manifest, options.hasNotFoundFile)
111
+ if (targets.length === 0 || (options.entry === undefined && options.app === undefined))
112
+ return
52
113
  const origin = prerenderOrigin(options.site)
53
- if (options.entry !== undefined) {
54
- const plugins = resolvePlugins(options.pluginOverride ?? options.entry.prunelleConfig.plugins)
55
- const lang = options.entry.prunelleConfig.lang ?? 'en'
56
- const trustProxy = options.entry.prunelleConfig.trustProxy ?? false
57
- let renderError: unknown
58
- const notifyError = (err: unknown): void => {
59
- renderError ??= err
114
+ const catchAllPresent = hasCatchAllRoute(options.manifest)
115
+ const fallbackTargets: StaticNotFoundTarget[] = []
116
+
117
+ if (options.app !== undefined) {
118
+ for (const target of targets) {
119
+ // A root catch-all route returning notFound() would select the root _404 instead of a nested _404.
120
+ if (catchAllPresent && target.outRel !== '404.html') {
121
+ fallbackTargets.push(target)
122
+ continue
123
+ }
124
+ const probePath = target.urlPath.replace(/\/404$/, '/__pru_404__')
125
+ const req = new Request(`${origin}${probePath}`)
126
+ const res = await options.app.handle(req)
127
+ const renderError = options.errorFor?.(req.url)
128
+ if (renderError !== undefined || res.status >= 500)
129
+ throw pageFailure(`prunelle build: the _404 page "${target.outRel}" of the static export answered HTTP ${res.status}`, renderError)
130
+ if (res.status === 404) {
131
+ writeStaticNotFound(options.stageDir, target.outRel, await res.text(), res.headers.get('content-security-policy'))
132
+ continue
133
+ }
134
+ if (options.entry !== undefined)
135
+ fallbackTargets.push(target)
136
+ else
137
+ writeStaticNotFound(options.stageDir, target.outRel, await res.text(), res.headers.get('content-security-policy'))
60
138
  }
61
- const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
62
- const navigation = createNavigation(options.entry.prunelleConfig.navigation)
63
- const htmlHeaders = createHtmlHeaders(options.entry.prunelleConfig.security, {}, navigation, plugins)
64
- const { buildNotFoundResponse } = createFallbackPages({
65
- manifest: options.manifest,
66
- modules: options.entry.modules,
67
- lang,
68
- alwaysLoadRuntime: plugins.some(p => Boolean(p.clientEntry)),
69
- navigation: navigation.html,
70
- dev: options.isDev === true,
71
- document,
72
- htmlHeaders,
73
- notifyError,
74
- finish: res => res,
75
- })
76
- const url = new URL('/404', origin)
77
- const res = await buildNotFoundResponse(url, new Request(url))
139
+ if (fallbackTargets.length === 0)
140
+ return
141
+ }
142
+ else {
143
+ fallbackTargets.push(...targets)
144
+ }
145
+
146
+ if (options.entry === undefined)
147
+ return
148
+
149
+ const plugins = resolvePlugins(options.pluginOverride ?? options.entry.prunelleConfig.plugins)
150
+ const lang = options.entry.prunelleConfig.lang ?? 'en'
151
+ const trustProxy = options.entry.prunelleConfig.trustProxy ?? false
152
+ let renderError: unknown
153
+ const notifyError = (err: unknown): void => {
154
+ renderError ??= err
155
+ }
156
+ const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
157
+ const navigation = createNavigation(options.entry.prunelleConfig.navigation)
158
+ const htmlHeaders = createHtmlHeaders(options.entry.prunelleConfig.security, {}, navigation, plugins)
159
+ const routesPrefix = inferRoutesServerPrefix(options.manifest)
160
+ const paramMatchers = resolveParamMatchers(options.manifest.paramMatchers, options.entry.modules)
161
+ const { buildNotFoundResponse } = createFallbackPages({
162
+ manifest: options.manifest,
163
+ modules: options.entry.modules,
164
+ routesPrefix,
165
+ paramMatchers,
166
+ lang,
167
+ alwaysLoadRuntime: plugins.some(p => Boolean(p.clientEntry)),
168
+ navigation: navigation.html,
169
+ dev: options.isDev === true,
170
+ document,
171
+ htmlHeaders,
172
+ notifyError,
173
+ finish: res => res,
174
+ })
175
+
176
+ for (const target of fallbackTargets) {
177
+ renderError = undefined
178
+ const url = new URL(target.urlPath, origin)
179
+ const res = await buildNotFoundResponse(url, new Request(url), undefined, target.routeFile)
78
180
  if (renderError !== undefined || res.status >= 500)
79
- throw pageFailure(`prunelle build: the _404 page of the static export answered HTTP ${res.status}`, renderError)
80
- return await res.text()
181
+ throw pageFailure(`prunelle build: the _404 page "${target.outRel}" of the static export answered HTTP ${res.status}`, renderError)
182
+ writeStaticNotFound(options.stageDir, target.outRel, await res.text(), res.headers.get('content-security-policy'))
81
183
  }
82
- const res = await options.app!.handle(new Request(`${origin}/__pru_404__`))
83
- if (res.status >= 500)
84
- throw pageFailure(`prunelle build: the _404 page of the static export answered HTTP ${res.status}`, undefined)
85
- return await res.text()
86
184
  }
87
185
 
88
186
  export async function exportStatic(options: StaticExportOptions): Promise<void> {
89
187
  const { stageDir, finalOutDir, outDir, clientDir, publicFiles } = options
90
- if (options.hasNotFoundFile && (options.entry !== undefined || options.app !== undefined))
91
- writeFileSync(join(stageDir, '404.html'), await renderStaticNotFound(options))
188
+ if (options.notFoundEmitted !== true)
189
+ await emitStaticNotFoundPages(options)
92
190
 
93
191
  // Client assets go to <stage>/_pru/..., public files to <stage>/...
94
192
  const assetDir = join(stageDir, options.assetPrefix.replace(LEADING_SLASH_RE, ''))
@@ -0,0 +1,127 @@
1
+ // Status and error page discovery, validation, and manifest entry construction (`_401`, `_403`, `_404`, `_429`, `_503`, `_error`).
2
+
3
+ import { basename, dirname, relative } from 'node:path'
4
+ import { relPosix } from './files'
5
+ import { ancestorFiles, dirToRoutePatternFromRel, hasRouteGroupInRel } from './routes'
6
+
7
+ export type StatusPageKind = '401' | '403' | '404' | '429' | '503' | 'error'
8
+
9
+ export const SUPPORTED_STATUS_CODES = new Set(['401', '403', '404', '429', '503'])
10
+
11
+ export const STATUS_PAGE_FILES = new Set([
12
+ '_401.tsx',
13
+ '_403.tsx',
14
+ '_404.tsx',
15
+ '_429.tsx',
16
+ '_503.tsx',
17
+ '_error.tsx',
18
+ ])
19
+
20
+ const NUMERIC_STATUS_FILE_RE = /^_(\d{3})\.tsx$/
21
+
22
+ /** Maps a supported status/error page filename to its kind, or undefined for other files. */
23
+ export function statusPageKindOf(file: string): StatusPageKind | undefined {
24
+ const name = basename(file)
25
+ if (name === '_error.tsx')
26
+ return 'error'
27
+ const match = NUMERIC_STATUS_FILE_RE.exec(name)
28
+ if (match !== null && SUPPORTED_STATUS_CODES.has(match[1]!))
29
+ return match[1] as StatusPageKind
30
+ return undefined
31
+ }
32
+
33
+ /** Reports an unsupported `_NNN.tsx` file (e.g. `_418.tsx`, `_500.tsx`) in `routesDir`. */
34
+ export function unknownStatusPageProblem(fileRel: string): string | undefined {
35
+ const match = NUMERIC_STATUS_FILE_RE.exec(basename(fileRel))
36
+ if (match === null || SUPPORTED_STATUS_CODES.has(match[1]!))
37
+ return undefined
38
+ return `unsupported status page ${fileRel}: supported status pages are _401.tsx, _403.tsx, _404.tsx, _429.tsx, _503.tsx, and _error.tsx.`
39
+ }
40
+
41
+ export interface StatusPageManifestEntry {
42
+ kind: StatusPageKind
43
+ /** Route pattern of the folder holding this status page (`'/'`, `'/admin'`, `'/blog/:slug'`). */
44
+ dirPattern: string
45
+ /** Compiled server directory prefix holding this status page (`'server/'`, `'server/admin/'`, `'server/(admin)/'`). */
46
+ dirPrefix: string
47
+ /** True when the status page lives inside a `(group)/` folder. */
48
+ inGroup?: boolean | undefined
49
+ file: string
50
+ layouts: string[]
51
+ styles: string[]
52
+ islandChunks: string[]
53
+ eagerIslandChunks?: string[] | undefined
54
+ }
55
+
56
+ export interface FileReachLike {
57
+ chunks: ReadonlySet<string>
58
+ eager: ReadonlySet<string>
59
+ styles: ReadonlySet<string>
60
+ }
61
+
62
+ function compiledDirPrefix(outRel: string): string {
63
+ const slash = outRel.lastIndexOf('/')
64
+ return slash === -1 ? '' : outRel.slice(0, slash + 1)
65
+ }
66
+
67
+ /** Builds manifest entries for every status/error page (`_404`, `_error`, `_401`, `_403`, `_429`, `_503`) across `routesDir`. */
68
+ export function buildStatusPageEntries(options: {
69
+ routesDir: string
70
+ specialFiles: readonly string[]
71
+ globalPluginStyles: readonly string[]
72
+ reachOf: (file: string) => FileReachLike
73
+ toOutRel: (srcFile: string) => string
74
+ }): StatusPageManifestEntry[] {
75
+ const { routesDir, specialFiles, globalPluginStyles, reachOf, toOutRel } = options
76
+ const entries: StatusPageManifestEntry[] = []
77
+
78
+ for (const file of specialFiles) {
79
+ const kind = statusPageKindOf(file)
80
+ if (kind === undefined)
81
+ continue
82
+ const relDir = relative(routesDir, dirname(file)).replace(/\\/g, '/')
83
+ const dirPattern = dirToRoutePatternFromRel(relDir)
84
+ const inGroup = hasRouteGroupInRel(relDir)
85
+ const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
86
+ const chunks = new Set<string>()
87
+ const eagerChunks = new Set<string>()
88
+ const styles = new Set<string>(globalPluginStyles)
89
+
90
+ for (const src of [...layoutSrcs, file]) {
91
+ const reach = reachOf(src)
92
+ for (const chunk of reach.chunks)
93
+ chunks.add(chunk)
94
+ for (const chunk of reach.eager)
95
+ eagerChunks.add(chunk)
96
+ for (const style of reach.styles)
97
+ styles.add(style)
98
+ }
99
+
100
+ const outRel = toOutRel(file)
101
+ entries.push({
102
+ kind,
103
+ dirPattern,
104
+ dirPrefix: compiledDirPrefix(outRel),
105
+ ...(inGroup ? { inGroup: true } : {}),
106
+ file: outRel,
107
+ layouts: layoutSrcs.map(toOutRel),
108
+ styles: [...styles],
109
+ islandChunks: [...chunks],
110
+ eagerIslandChunks: [...eagerChunks],
111
+ })
112
+ }
113
+
114
+ return entries
115
+ }
116
+
117
+ /** Finds every unsupported `_NNN.tsx` file under `routesDir` and returns its error messages. */
118
+ export function findUnknownStatusPages(root: string, routeFiles: readonly string[]): { file: string, message: string }[] {
119
+ const problems: { file: string, message: string }[] = []
120
+ for (const file of routeFiles) {
121
+ const rel = relPosix(root, file)
122
+ const message = unknownStatusPageProblem(rel)
123
+ if (message !== undefined)
124
+ problems.push({ file, message })
125
+ }
126
+ return problems
127
+ }