prunelle 0.1.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/llms.txt +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +139 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +101 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +407 -352
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +64 -20
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +188 -152
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +356 -11
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
package/src/build/resolve.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Resolves an import the way prunelle build follows it: relative files, then packages through Bun's resolver; prunelle, node:, bun and
|
|
1
|
+
// Resolves an import the way prunelle build follows it: relative files, then packages and tsconfig aliases through Bun's resolver; prunelle, node:, bun and virtual prefixes stay unresolved.
|
|
2
2
|
|
|
3
3
|
import { statSync } from 'node:fs'
|
|
4
4
|
import { dirname, join, resolve } from 'node:path'
|
|
@@ -23,28 +23,30 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
|
|
|
23
23
|
|| specifier.startsWith('node:')
|
|
24
24
|
|| specifier === 'bun'
|
|
25
25
|
|| specifier.startsWith('bun:')
|
|
26
|
-
|| specifier.startsWith('~')
|
|
26
|
+
|| specifier.startsWith('~icons/')
|
|
27
|
+
|| specifier.startsWith('virtual:')
|
|
27
28
|
) {
|
|
28
29
|
return undefined
|
|
29
30
|
}
|
|
30
31
|
try {
|
|
31
32
|
const resolved = Bun.resolveSync(specifier, dirname(fromFile))
|
|
32
|
-
return resolved.endsWith('.tsx') || resolved.endsWith('.ts') ? resolved : undefined
|
|
33
|
+
return resolved.endsWith('.tsx') || resolved.endsWith('.ts') || resolved.endsWith('.css') ? resolved : undefined
|
|
33
34
|
}
|
|
34
35
|
catch {
|
|
35
36
|
return undefined
|
|
36
37
|
}
|
|
37
38
|
}
|
|
38
39
|
|
|
40
|
+
const PRUNELLE_PKG_ROOT = resolve(PRUNELLE_SRC_ROOT, '..')
|
|
41
|
+
|
|
39
42
|
const PRUNELLE_SPECIFIER_FILES = new Map<string, string>(
|
|
40
43
|
Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
|
|
41
44
|
subpath === '.' ? 'prunelle' : `prunelle/${subpath.slice(2)}`,
|
|
42
|
-
|
|
45
|
+
resolve(PRUNELLE_PKG_ROOT, target),
|
|
43
46
|
]),
|
|
44
47
|
)
|
|
45
48
|
|
|
46
49
|
/** Maps `prunelle` and its subpaths to their source file. */
|
|
47
50
|
export function resolvePrunelleSpecifier(specifier: string): string | undefined {
|
|
48
|
-
|
|
49
|
-
return file === undefined ? undefined : join(PRUNELLE_SRC_ROOT, file)
|
|
51
|
+
return PRUNELLE_SPECIFIER_FILES.get(specifier)
|
|
50
52
|
}
|
package/src/build/routes.ts
CHANGED
|
@@ -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([
|
|
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([
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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[] = []
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// What a `--static` export tells the host that serves it: a `_headers` file (Netlify, Cloudflare Pages) and `prunelle.caddy` / `prunelle.nginx.conf` snippets, each carrying the security headers and the `_redirects` rules.
|
|
2
|
+
|
|
3
|
+
import type { SecurityHeadersOptions } from '../server/security'
|
|
4
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { buildSecurityHeaderEntries, resolveHstsValue } from '../server/security'
|
|
7
|
+
|
|
8
|
+
export const CADDY_SNIPPET = 'prunelle.caddy'
|
|
9
|
+
export const NGINX_SNIPPET = 'prunelle.nginx.conf'
|
|
10
|
+
|
|
11
|
+
// A page carries its own script and style policy as a `<meta>` tag with the hashes of that page, so the headers keep only the directives a `<meta>` tag cannot set or a page never varies.
|
|
12
|
+
const HEADER_CSP_DIRECTIVES = new Set(['frame-ancestors', 'base-uri', 'form-action', 'object-src', 'report-uri', 'sandbox'])
|
|
13
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])
|
|
14
|
+
const WHITESPACE_RE = /\s+/
|
|
15
|
+
const DYNAMIC_PATH_RE = /[*:]/
|
|
16
|
+
const FORCE_MARK_RE = /!$/
|
|
17
|
+
const UNSAFE_REDIRECT_TOKEN_RE = /[\s;{}'"$\\]/
|
|
18
|
+
|
|
19
|
+
export interface StaticRedirect {
|
|
20
|
+
from: string
|
|
21
|
+
to: string
|
|
22
|
+
status: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function isSafeRedirect(rule: StaticRedirect): boolean {
|
|
26
|
+
return REDIRECT_STATUSES.has(rule.status)
|
|
27
|
+
&& rule.from !== ''
|
|
28
|
+
&& rule.to !== ''
|
|
29
|
+
&& !rule.from.startsWith('#')
|
|
30
|
+
&& !rule.to.startsWith('#')
|
|
31
|
+
&& !DYNAMIC_PATH_RE.test(rule.from)
|
|
32
|
+
&& !UNSAFE_REDIRECT_TOKEN_RE.test(rule.from)
|
|
33
|
+
&& !UNSAFE_REDIRECT_TOKEN_RE.test(rule.to)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The `from to [status]` lines of a `_redirects` file that a snippet can state: an exact 3xx redirect, no splat, placeholder, or config-breaking character. */
|
|
37
|
+
export function parseRedirects(text: string): StaticRedirect[] {
|
|
38
|
+
const rules: StaticRedirect[] = []
|
|
39
|
+
for (const line of text.split('\n')) {
|
|
40
|
+
const fields = line.trim().split(WHITESPACE_RE)
|
|
41
|
+
const [from, to, status = '301'] = fields
|
|
42
|
+
const code = Number(status.replace(FORCE_MARK_RE, ''))
|
|
43
|
+
if (from === undefined || to === undefined)
|
|
44
|
+
continue
|
|
45
|
+
const rule: StaticRedirect = { from, to, status: code }
|
|
46
|
+
if (isSafeRedirect(rule))
|
|
47
|
+
rules.push(rule)
|
|
48
|
+
}
|
|
49
|
+
return rules
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function headerEntries(security: SecurityHeadersOptions | false | undefined): [string, string][] {
|
|
53
|
+
const entries: [string, string][] = []
|
|
54
|
+
for (const [name, value] of buildSecurityHeaderEntries(security)) {
|
|
55
|
+
if (name !== 'content-security-policy') {
|
|
56
|
+
entries.push([name, value])
|
|
57
|
+
continue
|
|
58
|
+
}
|
|
59
|
+
const kept = value.split(';').map(part => part.trim()).filter(part => HEADER_CSP_DIRECTIVES.has(part.split(WHITESPACE_RE)[0]!.toLowerCase()))
|
|
60
|
+
if (kept.length > 0)
|
|
61
|
+
entries.push([name, kept.join('; ')])
|
|
62
|
+
}
|
|
63
|
+
const hsts = resolveHstsValue(security)
|
|
64
|
+
if (hsts !== undefined && security !== false)
|
|
65
|
+
entries.push(['strict-transport-security', hsts])
|
|
66
|
+
return entries
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function titleCase(name: string): string {
|
|
70
|
+
return name.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('-')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const quote = (value: string): string => `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`
|
|
74
|
+
|
|
75
|
+
export function netlifyHeaders(security: SecurityHeadersOptions | false | undefined): string {
|
|
76
|
+
const lines = headerEntries(security).map(([name, value]) => ` ${titleCase(name)}: ${value}`)
|
|
77
|
+
return lines.length === 0 ? '' : `/*\n${lines.join('\n')}\n`
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function caddySnippet(security: SecurityHeadersOptions | false | undefined, redirects: readonly StaticRedirect[]): string {
|
|
81
|
+
const lines = ['# Written by `prunelle build --static`. Inside a site block: `import /path/to/dist/prunelle.caddy`.']
|
|
82
|
+
const entries = headerEntries(security)
|
|
83
|
+
if (entries.length > 0)
|
|
84
|
+
lines.push('header {', ...entries.map(([name, value]) => `\t${titleCase(name)} ${quote(value)}`), '}')
|
|
85
|
+
for (const rule of redirects) {
|
|
86
|
+
if (isSafeRedirect(rule))
|
|
87
|
+
lines.push(`redir ${rule.from} ${rule.to} ${rule.status}`)
|
|
88
|
+
}
|
|
89
|
+
return `${lines.join('\n')}\n`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function nginxSnippet(security: SecurityHeadersOptions | false | undefined, redirects: readonly StaticRedirect[]): string {
|
|
93
|
+
const lines = ['# Written by `prunelle build --static`. Inside a server block: `include /path/to/dist/prunelle.nginx.conf;`.', '# A location block that sets its own add_header drops these: repeat the include there.']
|
|
94
|
+
for (const [name, value] of headerEntries(security))
|
|
95
|
+
lines.push(`add_header ${titleCase(name)} ${quote(value)} always;`)
|
|
96
|
+
for (const rule of redirects) {
|
|
97
|
+
if (isSafeRedirect(rule))
|
|
98
|
+
lines.push(`location = ${rule.from} { return ${rule.status} ${rule.to}; }`)
|
|
99
|
+
}
|
|
100
|
+
return `${lines.join('\n')}\n`
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Writes the header files into the stage; a `_headers` or snippet the app ships in `public/` is left as it is. */
|
|
104
|
+
export function writeStaticHostFiles(stageDir: string, security: SecurityHeadersOptions | false | undefined): void {
|
|
105
|
+
const redirectsFile = join(stageDir, '_redirects')
|
|
106
|
+
const redirects = existsSync(redirectsFile) ? parseRedirects(readFileSync(redirectsFile, 'utf8')) : []
|
|
107
|
+
const files: [string, string][] = [['_headers', netlifyHeaders(security)], [CADDY_SNIPPET, caddySnippet(security, redirects)], [NGINX_SNIPPET, nginxSnippet(security, redirects)]]
|
|
108
|
+
for (const [name, text] of files) {
|
|
109
|
+
if (text !== '' && !existsSync(join(stageDir, name)))
|
|
110
|
+
writeFileSync(join(stageDir, name), text)
|
|
111
|
+
}
|
|
112
|
+
}
|
package/src/build/static.ts
CHANGED
|
@@ -3,19 +3,23 @@
|
|
|
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 {
|
|
14
|
-
import {
|
|
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 {
|
|
20
|
+
import { precompressFiles } from './precompress'
|
|
18
21
|
import { pageFailure } from './prerender'
|
|
22
|
+
import { writeStaticHostFiles } from './static-headers'
|
|
19
23
|
|
|
20
24
|
const LEADING_SLASH_RE = /^\//
|
|
21
25
|
|
|
@@ -36,9 +40,11 @@ export interface StaticExportOptions {
|
|
|
36
40
|
pluginOverride?: PrunellePlugin[] | undefined
|
|
37
41
|
assets: string[]
|
|
38
42
|
publicFiles: { files: string[], register: (relPath: string) => string }
|
|
39
|
-
/** The server the pages were prerendered with,
|
|
43
|
+
/** The server the pages were prerendered with, holding plugin services, rewrites and middlewares. */
|
|
40
44
|
app: PrunelleApp | undefined
|
|
45
|
+
errorFor?: ((url: string) => unknown) | undefined
|
|
41
46
|
hasNotFoundFile: boolean
|
|
47
|
+
notFoundEmitted?: boolean | undefined
|
|
42
48
|
stageSuffix: string
|
|
43
49
|
}
|
|
44
50
|
|
|
@@ -48,47 +54,140 @@ function copyInto(dstRoot: string, rel: string, src: string): void {
|
|
|
48
54
|
copyFileSync(src, dst)
|
|
49
55
|
}
|
|
50
56
|
|
|
51
|
-
|
|
57
|
+
interface StaticNotFoundTarget {
|
|
58
|
+
outRel: string
|
|
59
|
+
urlPath: string
|
|
60
|
+
routeFile?: string | undefined
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function staticNotFoundTargets(manifest: BuildManifest, hasNotFoundFile: boolean): StaticNotFoundTarget[] {
|
|
64
|
+
const targets: StaticNotFoundTarget[] = []
|
|
65
|
+
const seen = new Set<string>()
|
|
66
|
+
const statusPages: StatusPageManifestEntry[] = manifest.statusPages ?? []
|
|
67
|
+
for (const entry of statusPages) {
|
|
68
|
+
if (entry.kind !== '404' || entry.inGroup === true)
|
|
69
|
+
continue
|
|
70
|
+
if (entry.dirPattern.includes(':') || entry.dirPattern.includes('*'))
|
|
71
|
+
continue
|
|
72
|
+
const cleanDir = entry.dirPattern === '/' ? '' : entry.dirPattern.replace(LEADING_SLASH_RE, '')
|
|
73
|
+
const outRel = cleanDir === '' ? '404.html' : `${cleanDir}/404.html`
|
|
74
|
+
if (seen.has(outRel))
|
|
75
|
+
continue
|
|
76
|
+
seen.add(outRel)
|
|
77
|
+
targets.push({
|
|
78
|
+
outRel,
|
|
79
|
+
urlPath: cleanDir === '' ? '/404' : `/${cleanDir}/404`,
|
|
80
|
+
routeFile: entry.file,
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
if (hasNotFoundFile && !seen.has('404.html'))
|
|
84
|
+
targets.push({ outRel: '404.html', urlPath: '/404' })
|
|
85
|
+
return targets
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface StaticNotFoundOptions {
|
|
89
|
+
stageDir: string
|
|
90
|
+
site?: string | undefined
|
|
91
|
+
isDev?: boolean | undefined
|
|
92
|
+
manifest: BuildManifest
|
|
93
|
+
entry: ServerEntry | undefined
|
|
94
|
+
pluginOverride?: PrunellePlugin[] | undefined
|
|
95
|
+
app: PrunelleApp | undefined
|
|
96
|
+
errorFor?: ((url: string) => unknown) | undefined
|
|
97
|
+
hasNotFoundFile: boolean
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function hasCatchAllRoute(manifest: BuildManifest): boolean {
|
|
101
|
+
return manifest.routes.some(r => r.path.includes('*'))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function writeStaticNotFound(stageDir: string, outRel: string, html: string, csp: string | null): void {
|
|
105
|
+
const outAbs = join(stageDir, outRel)
|
|
106
|
+
mkdirSync(dirname(outAbs), { recursive: true })
|
|
107
|
+
writeFileSync(outAbs, injectMetaCsp(html, csp))
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function emitStaticNotFoundPages(options: StaticNotFoundOptions): Promise<void> {
|
|
111
|
+
const targets = staticNotFoundTargets(options.manifest, options.hasNotFoundFile)
|
|
112
|
+
if (targets.length === 0 || (options.entry === undefined && options.app === undefined))
|
|
113
|
+
return
|
|
52
114
|
const origin = prerenderOrigin(options.site)
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
115
|
+
const catchAllPresent = hasCatchAllRoute(options.manifest)
|
|
116
|
+
const fallbackTargets: StaticNotFoundTarget[] = []
|
|
117
|
+
|
|
118
|
+
if (options.app !== undefined) {
|
|
119
|
+
for (const target of targets) {
|
|
120
|
+
// A root catch-all route returning notFound() would select the root _404 instead of a nested _404.
|
|
121
|
+
if (catchAllPresent && target.outRel !== '404.html') {
|
|
122
|
+
fallbackTargets.push(target)
|
|
123
|
+
continue
|
|
124
|
+
}
|
|
125
|
+
const probePath = target.urlPath.replace(/\/404$/, '/__pru_404__')
|
|
126
|
+
const req = new Request(`${origin}${probePath}`)
|
|
127
|
+
const res = await options.app.handle(req)
|
|
128
|
+
const renderError = options.errorFor?.(req.url)
|
|
129
|
+
if (renderError !== undefined || res.status >= 500)
|
|
130
|
+
throw pageFailure(`prunelle build: the _404 page "${target.outRel}" of the static export answered HTTP ${res.status}`, renderError)
|
|
131
|
+
if (res.status === 404) {
|
|
132
|
+
writeStaticNotFound(options.stageDir, target.outRel, await res.text(), res.headers.get('content-security-policy'))
|
|
133
|
+
continue
|
|
134
|
+
}
|
|
135
|
+
if (options.entry !== undefined)
|
|
136
|
+
fallbackTargets.push(target)
|
|
137
|
+
else
|
|
138
|
+
writeStaticNotFound(options.stageDir, target.outRel, await res.text(), res.headers.get('content-security-policy'))
|
|
60
139
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
140
|
+
if (fallbackTargets.length === 0)
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
fallbackTargets.push(...targets)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (options.entry === undefined)
|
|
148
|
+
return
|
|
149
|
+
|
|
150
|
+
const plugins = resolvePlugins(options.pluginOverride ?? options.entry.prunelleConfig.plugins)
|
|
151
|
+
const lang = options.entry.prunelleConfig.lang ?? 'en'
|
|
152
|
+
const trustProxy = options.entry.prunelleConfig.trustProxy ?? false
|
|
153
|
+
let renderError: unknown
|
|
154
|
+
const notifyError = (err: unknown): void => {
|
|
155
|
+
renderError ??= err
|
|
156
|
+
}
|
|
157
|
+
const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
|
|
158
|
+
const navigation = createNavigation(options.entry.prunelleConfig.navigation)
|
|
159
|
+
const htmlHeaders = createHtmlHeaders(options.entry.prunelleConfig.security, {}, navigation, plugins)
|
|
160
|
+
const routesPrefix = inferRoutesServerPrefix(options.manifest)
|
|
161
|
+
const paramMatchers = resolveParamMatchers(options.manifest.paramMatchers, options.entry.modules)
|
|
162
|
+
const { buildNotFoundResponse } = createFallbackPages({
|
|
163
|
+
manifest: options.manifest,
|
|
164
|
+
modules: options.entry.modules,
|
|
165
|
+
routesPrefix,
|
|
166
|
+
paramMatchers,
|
|
167
|
+
lang,
|
|
168
|
+
alwaysLoadRuntime: plugins.some(p => Boolean(p.clientEntry)),
|
|
169
|
+
navigation: navigation.html,
|
|
170
|
+
dev: options.isDev === true,
|
|
171
|
+
document,
|
|
172
|
+
htmlHeaders,
|
|
173
|
+
notifyError,
|
|
174
|
+
finish: res => res,
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
for (const target of fallbackTargets) {
|
|
178
|
+
renderError = undefined
|
|
179
|
+
const url = new URL(target.urlPath, origin)
|
|
180
|
+
const res = await buildNotFoundResponse(url, new Request(url), undefined, target.routeFile)
|
|
78
181
|
if (renderError !== undefined || res.status >= 500)
|
|
79
|
-
throw pageFailure(`prunelle build: the _404 page of the static export answered HTTP ${res.status}`, renderError)
|
|
80
|
-
|
|
182
|
+
throw pageFailure(`prunelle build: the _404 page "${target.outRel}" of the static export answered HTTP ${res.status}`, renderError)
|
|
183
|
+
writeStaticNotFound(options.stageDir, target.outRel, await res.text(), res.headers.get('content-security-policy'))
|
|
81
184
|
}
|
|
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
185
|
}
|
|
87
186
|
|
|
88
187
|
export async function exportStatic(options: StaticExportOptions): Promise<void> {
|
|
89
188
|
const { stageDir, finalOutDir, outDir, clientDir, publicFiles } = options
|
|
90
|
-
if (options.
|
|
91
|
-
|
|
189
|
+
if (options.notFoundEmitted !== true)
|
|
190
|
+
await emitStaticNotFoundPages(options)
|
|
92
191
|
|
|
93
192
|
// Client assets go to <stage>/_pru/..., public files to <stage>/...
|
|
94
193
|
const assetDir = join(stageDir, options.assetPrefix.replace(LEADING_SLASH_RE, ''))
|
|
@@ -100,6 +199,7 @@ export async function exportStatic(options: StaticExportOptions): Promise<void>
|
|
|
100
199
|
publicFiles.register(relative(outPublicDir, abs))
|
|
101
200
|
for (const rel of publicFiles.files)
|
|
102
201
|
copyInto(stageDir, rel, join(outPublicDir, rel))
|
|
202
|
+
writeStaticHostFiles(stageDir, options.entry?.prunelleConfig.security)
|
|
103
203
|
await precompressFiles(walkAllFiles(stageDir), 128, options.root)
|
|
104
204
|
if (!options.isDev)
|
|
105
205
|
carryPreviousAssets(finalOutDir, stageDir, relative(stageDir, assetDir), options.assets)
|