prunelle 0.1.1 → 0.5.1

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 (88) 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 +3 -2
  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 +11 -2
  11. package/src/build/compile.ts +2 -1
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +121 -44
  14. package/src/build/manifest.ts +66 -5
  15. package/src/build/output.ts +2 -2
  16. package/src/build/plugin-host.ts +91 -33
  17. package/src/build/precompress.ts +15 -2
  18. package/src/build/prerender.ts +2 -2
  19. package/src/build/report.ts +23 -2
  20. package/src/build/resolve.ts +4 -3
  21. package/src/build/routes.ts +175 -10
  22. package/src/build/static.ts +71 -17
  23. package/src/build/status-pages.ts +127 -0
  24. package/src/build/style-bundles.ts +338 -0
  25. package/src/cli/check-forms.ts +654 -0
  26. package/src/cli/check-links.ts +619 -0
  27. package/src/cli/check.ts +52 -5
  28. package/src/cli/commands.ts +86 -4
  29. package/src/cli/docs.ts +402 -0
  30. package/src/cli/inspect.ts +31 -2
  31. package/src/cli/mcp-tools.ts +480 -0
  32. package/src/cli/mcp.ts +205 -0
  33. package/src/cli/new.ts +2 -2
  34. package/src/cli/render.ts +261 -0
  35. package/src/cli/upgrade-names.ts +73 -13
  36. package/src/cli/upgrade.ts +137 -16
  37. package/src/compiler/analyze.ts +17 -3
  38. package/src/compiler/cacheability.ts +592 -0
  39. package/src/compiler/compliance-rgaa.ts +502 -0
  40. package/src/compiler/compliance.ts +120 -221
  41. package/src/compiler/dev-source.ts +87 -0
  42. package/src/compiler/dom.ts +7 -7
  43. package/src/compiler/ssr.ts +135 -37
  44. package/src/dev/error-log.ts +151 -0
  45. package/src/dev/index.ts +60 -29
  46. package/src/dev/open-editor.ts +204 -0
  47. package/src/dev/reload.ts +5 -3
  48. package/src/dev/supervisor.ts +3 -0
  49. package/src/dom/action.ts +4 -1
  50. package/src/dom/island.ts +11 -10
  51. package/src/plugins/config.ts +4 -4
  52. package/src/plugins/index.ts +2 -2
  53. package/src/plugins/public.ts +5 -2
  54. package/src/plugins/services.ts +62 -0
  55. package/src/plugins/types.ts +32 -0
  56. package/src/server/action-protect.ts +198 -0
  57. package/src/server/action-registry.ts +1 -1
  58. package/src/server/action.ts +82 -27
  59. package/src/server/errors.ts +291 -62
  60. package/src/server/form-schema.ts +343 -0
  61. package/src/server/health.ts +244 -0
  62. package/src/server/http.ts +86 -19
  63. package/src/server/index.ts +158 -219
  64. package/src/server/param-matchers.ts +112 -0
  65. package/src/server/plugin-host.ts +40 -14
  66. package/src/server/public.ts +3 -3
  67. package/src/server/rate-limit.ts +58 -35
  68. package/src/server/request-body.ts +1 -1
  69. package/src/server/route-cache.ts +365 -0
  70. package/src/server/route-table.ts +302 -6
  71. package/src/server/router.ts +125 -40
  72. package/src/server/routing.ts +187 -61
  73. package/src/server/security.ts +208 -32
  74. package/src/server/serve-handlers.ts +21 -7
  75. package/src/ssr/context.ts +49 -0
  76. package/src/ssr/index.ts +120 -1
  77. package/src/test/browser.ts +6 -0
  78. package/src/test/index.ts +17 -3
  79. package/src/ts-plugin/diagnostics.ts +378 -0
  80. package/src/ts-plugin/fixes.ts +364 -0
  81. package/src/ts-plugin/index.ts +194 -0
  82. package/templates/_shared/AGENTS.md +2 -2
  83. package/templates/_shared/mcp.json +11 -0
  84. package/templates/_shared/src/routes/legal.tsx +5 -0
  85. package/templates/_shared/tsconfig.json +5 -0
  86. package/templates/blog/prunelle.config.ts +1 -1
  87. package/templates/blog/src/routes/index.tsx +4 -0
  88. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,204 @@
1
+ // Opens a project source file at `line:col` in `$PRUNELLE_EDITOR` or `$VISUAL` on Alt-click in `prunelle dev`.
2
+
3
+ import { existsSync, realpathSync } from 'node:fs'
4
+ import { relative, resolve } from 'node:path'
5
+ import { isInside } from '../build/is-inside'
6
+
7
+ export const OPEN_EDITOR_SUBPATH = 'open-editor'
8
+
9
+ export interface ParsedSourceLoc {
10
+ file: string
11
+ relFile: string
12
+ line: number
13
+ col: number
14
+ }
15
+
16
+ const POSITIVE_INT_RE = /^\d+$/
17
+ const BIN_EXT_RE = /\.(?:exe|cmd|bat)$/i
18
+ const MISSING_EDITOR_ERROR = 'Set PRUNELLE_EDITOR or VISUAL to open files on Alt-click.'
19
+
20
+ const VSCODE_EDITORS = new Set(['code', 'code-insiders', 'codium', 'vscodium', 'cursor', 'windsurf'])
21
+ const ZED_EDITORS = new Set(['zed', 'zeditor'])
22
+ const JETBRAINS_EDITORS = new Set(['idea', 'webstorm', 'phpstorm', 'pycharm', 'goland', 'rubymine', 'rider', 'clion', 'datagrip', 'fleet', 'studio'])
23
+ const SUBLIME_HELIX_EDITORS = new Set(['subl', 'sublime_text', 'hx'])
24
+ const TERMINAL_EDITORS = new Set(['vim', 'nvim', 'vi', 'nano', 'emacs', 'emacsclient'])
25
+
26
+ /** Splits an editor command string into argv tokens, honoring single/double quotes without invoking a shell. */
27
+ function splitEditorSpec(spec: string): string[] {
28
+ const tokens: string[] = []
29
+ let current = ''
30
+ let quote: '\'' | '"' | undefined
31
+ let hasToken = false
32
+
33
+ for (let i = 0; i < spec.length; i++) {
34
+ const ch = spec[i]!
35
+ if (quote !== undefined) {
36
+ if (ch === '\\' && quote === '"' && i + 1 < spec.length && (spec[i + 1] === '"' || spec[i + 1] === '\\')) {
37
+ current += spec[++i]!
38
+ }
39
+ else if (ch === quote) {
40
+ quote = undefined
41
+ }
42
+ else {
43
+ current += ch
44
+ }
45
+ continue
46
+ }
47
+
48
+ if (ch === '\'' || ch === '"') {
49
+ quote = ch
50
+ hasToken = true
51
+ continue
52
+ }
53
+ if (ch === '\\' && i + 1 < spec.length && /\s/.test(spec[i + 1]!)) {
54
+ current += spec[++i]!
55
+ hasToken = true
56
+ continue
57
+ }
58
+ if (/\s/.test(ch)) {
59
+ if (hasToken) {
60
+ tokens.push(current)
61
+ current = ''
62
+ hasToken = false
63
+ }
64
+ continue
65
+ }
66
+ current += ch
67
+ hasToken = true
68
+ }
69
+
70
+ if (hasToken)
71
+ tokens.push(current)
72
+ return tokens
73
+ }
74
+
75
+ /** Parses and validates a `relPath:line:col` location, confining it strictly inside `root`. */
76
+ export function parseSourceLoc(raw: string, root: string): ParsedSourceLoc | { error: string, status: 400 | 403 | 404 } {
77
+ const trimmed = raw.trim()
78
+ const lastColon = trimmed.lastIndexOf(':')
79
+ const prevColon = lastColon > 0 ? trimmed.lastIndexOf(':', lastColon - 1) : -1
80
+ if (lastColon <= 0 || prevColon <= 0)
81
+ return { error: 'Invalid source location; expected file:line:col.', status: 400 }
82
+
83
+ const relPart = trimmed.slice(0, prevColon)
84
+ const lineStr = trimmed.slice(prevColon + 1, lastColon)
85
+ const colStr = trimmed.slice(lastColon + 1)
86
+ if (relPart === '' || relPart.includes('\0') || !POSITIVE_INT_RE.test(lineStr) || !POSITIVE_INT_RE.test(colStr))
87
+ return { error: 'Invalid source location; expected file:line:col.', status: 400 }
88
+
89
+ const line = Number.parseInt(lineStr, 10)
90
+ const col = Number.parseInt(colStr, 10)
91
+ if (!Number.isSafeInteger(line) || line < 1 || !Number.isSafeInteger(col) || col < 1)
92
+ return { error: 'Line and column must be positive integers.', status: 400 }
93
+
94
+ const resolvedRoot = resolve(root)
95
+ const file = resolve(resolvedRoot, relPart)
96
+ if (!isInside(resolvedRoot, file))
97
+ return { error: 'Source file is outside the project root.', status: 403 }
98
+ if (!existsSync(file))
99
+ return { error: 'Source file does not exist.', status: 404 }
100
+
101
+ const realRoot = realpathSync(resolvedRoot)
102
+ const realFile = realpathSync(file)
103
+ if (!isInside(realRoot, realFile))
104
+ return { error: 'Source file is outside the project root.', status: 403 }
105
+
106
+ return { file, relFile: relative(resolvedRoot, file).replaceAll('\\', '/'), line, col }
107
+ }
108
+
109
+ /** Builds the argv array to open `loc` in `editorSpec` (supporting `{file}`/`{line}`/`{col}` templates and common editors). */
110
+ export function buildEditorCommand(editorSpec: string, loc: { file: string, line: number, col: number }): string[] {
111
+ const parts = splitEditorSpec(editorSpec.trim())
112
+ if (parts.length === 0)
113
+ return []
114
+
115
+ const lineStr = String(loc.line)
116
+ const colStr = String(loc.col)
117
+ if (parts.some(p => p.includes('{file}') || p.includes('{line}') || p.includes('{col}')))
118
+ return parts.map(p => p.replaceAll('{file}', loc.file).replaceAll('{line}', lineStr).replaceAll('{col}', colStr))
119
+
120
+ const rawBin = parts[0]!.split(/[\\/]/).pop() ?? ''
121
+ const bin = rawBin.toLowerCase().replace(BIN_EXT_RE, '')
122
+ const fileLineCol = `${loc.file}:${lineStr}:${colStr}`
123
+
124
+ if (VSCODE_EDITORS.has(bin))
125
+ return [...parts, '--goto', fileLineCol]
126
+ if (ZED_EDITORS.has(bin) || SUBLIME_HELIX_EDITORS.has(bin))
127
+ return [...parts, fileLineCol]
128
+ if (JETBRAINS_EDITORS.has(bin))
129
+ return [...parts, '--line', lineStr, '--column', colStr, loc.file]
130
+ if (TERMINAL_EDITORS.has(bin))
131
+ return [...parts, `+${lineStr}`, loc.file]
132
+ return [...parts, fileLineCol]
133
+ }
134
+
135
+ export interface OpenEditorOptions {
136
+ env?: Record<string, string | undefined> | undefined
137
+ spawn?: ((cmd: string[]) => void) | undefined
138
+ }
139
+
140
+ export function openInEditor(
141
+ rawSrc: string,
142
+ root: string,
143
+ options?: OpenEditorOptions,
144
+ ): { ok: true, command: string[] } | { ok: false, status: number, error: string } {
145
+ const env = options?.env ?? process.env
146
+ const editor = env.PRUNELLE_EDITOR?.trim() || env.VISUAL?.trim()
147
+ if (!editor)
148
+ return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
149
+
150
+ const parsed = parseSourceLoc(rawSrc, root)
151
+ if ('error' in parsed)
152
+ return { ok: false, status: parsed.status, error: parsed.error }
153
+
154
+ const command = buildEditorCommand(editor, parsed)
155
+ if (command.length === 0)
156
+ return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
157
+
158
+ try {
159
+ if (options?.spawn !== undefined) {
160
+ options.spawn(command)
161
+ }
162
+ else {
163
+ const proc = Bun.spawn(command, { cwd: root, stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' })
164
+ proc.unref()
165
+ }
166
+ }
167
+ catch (err) {
168
+ return {
169
+ ok: false,
170
+ status: 500,
171
+ error: `Failed to launch editor "${command[0]}": ${err instanceof Error ? err.message : String(err)}`,
172
+ }
173
+ }
174
+
175
+ return { ok: true, command }
176
+ }
177
+
178
+ /** Handles `POST /_pru/open-editor` from the dev server's Alt-click listener. */
179
+ export async function handleOpenEditorRequest(
180
+ request: Request,
181
+ root: string,
182
+ options?: OpenEditorOptions,
183
+ ): Promise<Response> {
184
+ if (request.method !== 'POST')
185
+ return Response.json({ ok: false, error: 'Method Not Allowed' }, { status: 405, headers: { allow: 'POST' } })
186
+
187
+ let rawSrc = new URL(request.url).searchParams.get('src') ?? ''
188
+ if (rawSrc === '') {
189
+ try {
190
+ const body = await request.json() as unknown
191
+ if (body !== null && typeof body === 'object' && typeof (body as { src?: unknown }).src === 'string')
192
+ rawSrc = (body as { src: string }).src
193
+ }
194
+ catch {
195
+ return Response.json({ ok: false, error: 'Invalid JSON body; expected { "src": "file:line:col" }.' }, { status: 400 })
196
+ }
197
+ }
198
+
199
+ if (rawSrc.trim() === '')
200
+ return Response.json({ ok: false, error: 'Missing "src" location.' }, { status: 400 })
201
+
202
+ const result = openInEditor(rawSrc, root, options)
203
+ return Response.json(result, { status: result.ok ? 200 : result.status })
204
+ }
package/src/dev/reload.ts CHANGED
@@ -4,13 +4,15 @@ import { wantsJson } from '../server/http'
4
4
  import { withCspHashes } from '../server/security'
5
5
  import { REGION_HEADER } from '../server/region'
6
6
  import { cspSha256 } from '../ssr/navigation'
7
+ import { OPEN_EDITOR_SUBPATH } from './open-editor'
7
8
 
8
- export function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string } {
9
+ export function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string, openEditorPath: string } {
9
10
  const prefix = assetPrefix.replace(/\/$/, '')
10
11
  const eventsPath = `${prefix}/dev-events`
11
- const js = `(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource(${JSON.stringify(eventsPath)});s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map(urls.map(u=>[stem(u),u]));const old=[...document.querySelectorAll('link[rel="stylesheet"][href^=${JSON.stringify(`${prefix}/`)}]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};})();`
12
+ const openEditorPath = `${prefix}/${OPEN_EDITOR_SUBPATH}`
13
+ const js = `(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource(${JSON.stringify(eventsPath)});s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map(urls.map(u=>[stem(u),u]));const old=[...document.querySelectorAll('link[rel="stylesheet"][href^=${JSON.stringify(`${prefix}/`)}]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};document.addEventListener('click',e=>{if(!e.altKey||e.ctrlKey||e.metaKey||e.button!==0)return;const t=e.target instanceof Element?e.target.closest('[data-pru-src]'):null;if(!t)return;e.preventDefault();e.stopImmediatePropagation();fetch(${JSON.stringify(openEditorPath)},{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({src:t.getAttribute('data-pru-src')})}).catch(()=>{});},true);})();`
12
14
  const hash = cspSha256(js)
13
- return { script: `<script>${js}</script>`, hash, eventsPath }
15
+ return { script: `<script>${js}</script>`, hash, eventsPath, openEditorPath }
14
16
  }
15
17
 
16
18
  export function renderErrorOverlay(errText: string, reloadScript: string): string {
@@ -7,6 +7,7 @@ import { existsSync, mkdtempSync, rmSync, watch } from 'node:fs'
7
7
  import { tmpdir } from 'node:os'
8
8
  import { join, resolve } from 'node:path'
9
9
  import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
10
+ import { recordDevCrashError } from './error-log'
10
11
  import { DEV_CHILD_ENV, DEV_CLIENT_IP_HEADER } from './protocol'
11
12
  import { buildErrorResponse, createReloadHub, makeDevReloadAssets } from './reload'
12
13
 
@@ -64,6 +65,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
64
65
  else if (message.t === 'ready') {
65
66
  reloadAssets = makeDevReloadAssets(message.assetPrefix)
66
67
  crashed = undefined
68
+ recordDevCrashError(root, undefined)
67
69
  onReady(child)
68
70
  }
69
71
  else if (child === live && !child.stopping && !stopped) {
@@ -87,6 +89,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
87
89
  return
88
90
  const how = proc.signalCode !== null ? `was killed by ${proc.signalCode}` : `exited with code ${code}`
89
91
  crashed = [`prunelle dev: the app process ${how}.`, stderrTail.trim(), 'Save a file to start it again.'].filter(Boolean).join('\n\n')
92
+ recordDevCrashError(root, crashed)
90
93
  if (live === child)
91
94
  live = undefined
92
95
  onReady(undefined)
package/src/dom/action.ts CHANGED
@@ -88,7 +88,10 @@ export function useAction<Input, Output>(
88
88
  fieldErrors,
89
89
  data,
90
90
  get action() {
91
- return action.url || String(action)
91
+ const u = action.url || String(action)
92
+ if ('__pruAction' in action)
93
+ (globalThis as { __pruAct?: (url: string, act: unknown) => void }).__pruAct?.(u, action)
94
+ return u
92
95
  },
93
96
  onSubmit(event) {
94
97
  event.preventDefault()
package/src/dom/island.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  // Native <pru-island> Custom Element: the build defines which strategies an app uses, so the loader drops the code of the others.
2
2
 
3
- import { hydrate, mount } from './index'
4
-
3
+ import type { hydrate, mount } from './index'
5
4
 
6
5
  declare const PRUNELLE_VISIBLE: boolean | undefined
7
6
  declare const PRUNELLE_IDLE: boolean | undefined
@@ -14,7 +13,8 @@ declare const PRUNELLE_REVIVE: string | undefined
14
13
  // Only props holding a Date, Map, Set or another tagged value load the revivers: plain JSON parses with no extra file.
15
14
  const reviver = (): Promise<typeof import('./revive')> => typeof PRUNELLE_REVIVE === 'undefined' ? import('./revive') : import(PRUNELLE_REVIVE)
16
15
 
17
- type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null }
16
+ // An island chunk also re-exports the DOM runtime it imports (`writeClientEntries`), `mount` only in an app with a client-only island.
17
+ type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null, hydrate: typeof hydrate, mount?: typeof mount }
18
18
 
19
19
  /** Finds this island's own `<script type="application/json" data-pru-props>` direct child. */
20
20
  function findOwnPropsScript(root: Element): Element | null {
@@ -91,18 +91,19 @@ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void
91
91
  }
92
92
 
93
93
  function isAllowedChunkUrl(chunk: string): boolean {
94
- // A browser reads `//host` and `/\host` as another site.
95
- if (chunk[0] === '/')
96
- return chunk[1] !== '/' && chunk[1] !== '\\'
94
+ if (/[\u0000-\u0020\u007F]/.test(chunk))
95
+ return false
97
96
  if (typeof location !== 'undefined' && location.origin && location.origin !== 'null') {
98
97
  try {
99
- const parsed = new URL(chunk, location.href)
100
- return parsed.origin === location.origin
98
+ return new URL(chunk, location.href).origin === location.origin
101
99
  }
102
100
  catch {
103
101
  return false
104
102
  }
105
103
  }
104
+ // A browser reads `//host` and `/\host` as another site.
105
+ if (chunk[0] === '/')
106
+ return chunk[1] !== '/' && chunk[1] !== '\\'
106
107
  return !/^(?:javascript|data|vbscript):/i.test(chunk)
107
108
  }
108
109
 
@@ -262,8 +263,8 @@ export function defineIslandElement(): void {
262
263
  const idPrefix = this.getAttribute('i') ?? `c${clientIslandIdSeq++}-`
263
264
  const render = () => loaded.default(props)
264
265
  dispose = (typeof PRUNELLE_CLIENT_ONLY === 'undefined' || PRUNELLE_CLIENT_ONLY) && clientOnly
265
- ? mount(this, render, idPrefix)
266
- : hydrate(this, render, idPrefix)
266
+ ? loaded.mount!(this, render, idPrefix)
267
+ : loaded.hydrate(this, render, idPrefix)
267
268
  if (!this.isConnected || token !== this._t) {
268
269
  dispose()
269
270
  return
@@ -6,17 +6,17 @@ export function defineConfig(config: PrunelleConfig): PrunelleConfig {
6
6
  return config
7
7
  }
8
8
 
9
- /** Forwards every runtime key from `prunelle.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`, `compliance`). */
9
+ /** Forwards every runtime key from `prunelle.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`, `compliance`, `autoPrerender`). */
10
10
  export function pickRuntimeConfig(config: PrunelleConfig | undefined): ServerRuntimeConfig {
11
11
  if (config === undefined)
12
12
  return {}
13
- const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, compliance: _c, ...runtime } = config
13
+ const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, compliance: _c, autoPrerender: _ap, ...runtime } = config
14
14
  return runtime
15
15
  }
16
16
 
17
17
  // Typed as records so that a key added to the config types without being listed here fails the typecheck.
18
- const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, onError: true, plugins: true }
19
- const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true }
18
+ const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, routeCache: true, healthCheck: true, onError: true, plugins: true }
19
+ const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true, autoPrerender: true }
20
20
  const RUNTIME_CONFIG_KEYS = Object.keys(RUNTIME_KEYS) as (keyof ServerRuntimeConfig)[]
21
21
  const CONFIG_KEYS = [...RUNTIME_CONFIG_KEYS, ...Object.keys(BUILD_KEYS)]
22
22
 
@@ -7,8 +7,8 @@ export { createAppContext, getAppContext, runWithAppContext } from './context'
7
7
  export type { AppRuntimeContext, CreateAppContextOptions } from './context'
8
8
  export { loadConfig } from './load'
9
9
  export { resolvePlugins } from './order'
10
- export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, serviceKey } from './services'
11
- export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult, ServiceKey } from './services'
10
+ export { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, JOBS_SERVICE, serviceKey } from './services'
11
+ export type { AccessedContentEntry, ActiveI18nConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, JobsEnqueueOptions, JobsQueueOptions, JobsService, ServiceKey } from './services'
12
12
  export type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
13
13
  export type { ConsentConfig } from '../server/consent'
14
14
  export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -1,12 +1,15 @@
1
1
  // `prunelle/config`: what `prunelle.config.ts` and plugin packages use.
2
2
 
3
+ export { a11y, auditAccessibility, draftAccessibilityStatement, formatA11yReport, rgaaCriteriaForAxeRule } from '../a11y/index'
4
+ export type { A11yAuditOptions, A11yAuditReport, A11yImpact, A11yPluginOptions, A11yRouteReport, A11yViolation, A11yViolationNode, AccessibilityDeclarationOptions, AccessibilityDeclarationResult, ComplianceStatus, RgaaCriterion } from '../a11y/index'
3
5
  export { isInside } from '../build/is-inside'
4
6
  export { distLocator, firstLoadUrls, measureFirstLoad } from '../build/first-load'
5
7
  export type { FirstLoad, Locate } from '../build/first-load'
6
8
  export { brotliSize } from '../build/precompress'
9
+ export { minifyCss } from '../build/style-bundles'
7
10
  export { defineConfig, definePlugin } from './config'
8
- export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, serviceKey } from './services'
9
- export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult, ServiceKey } from './services'
11
+ export { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, JOBS_SERVICE, serviceKey } from './services'
12
+ export type { AccessedContentEntry, ActiveI18nConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, JobsEnqueueOptions, JobsQueueOptions, JobsService, ServiceKey } from './services'
10
13
  export type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
11
14
  export type { ConsentConfig } from '../server/consent'
12
15
  export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -1,5 +1,8 @@
1
1
  // Service keys: `serviceKey` for any plugin, and the keys shared between two plugins, kept in core as contracts so neither depends on the other.
2
2
 
3
+ import type { RequestContext } from '../server/http'
4
+ import type { StandardSchemaV1 } from '../server/standard-schema'
5
+
3
6
  declare const SERVICE_TYPE: unique symbol
4
7
 
5
8
  /** Names a service and the type of its value; `provide` and `inject` take one instead of a string. */
@@ -33,3 +36,62 @@ export interface ContentImageResult {
33
36
  export type ContentImageResolver = (src: string, file: string | undefined) => ContentImageResult | string | undefined
34
37
 
35
38
  export const CONTENT_IMAGE_RESOLVER_SERVICE = serviceKey<ContentImageResolver>('prunelle.content.imageResolver')
39
+
40
+ export interface ContentCollectionEntrySummary {
41
+ readonly slug: string
42
+ readonly locale?: string | undefined
43
+ readonly file?: string | undefined
44
+ readonly data: Record<string, unknown>
45
+ readonly body: string
46
+ }
47
+
48
+ export interface ContentCollectionDescriptor {
49
+ /** Collection identifier (directory basename or explicit name). */
50
+ readonly name: string
51
+ /** Optional URL prefix registered via feeds or collection config (e.g. '/blog'). */
52
+ readonly linkPrefix?: string | undefined
53
+ /** Absolute directory path for file-backed collections; undefined for loader-backed collections. */
54
+ readonly dir?: string | undefined
55
+ readonly localized: boolean
56
+ readonly defaultLocale: string
57
+ readonly locales?: readonly string[] | undefined
58
+ readonly schema?: StandardSchemaV1 | undefined
59
+ all(locale?: string): readonly ContentCollectionEntrySummary[] | Promise<readonly ContentCollectionEntrySummary[]>
60
+ get(slug: string, locale?: string): ContentCollectionEntrySummary | undefined | Promise<ContentCollectionEntrySummary | undefined>
61
+ clearCache(): void
62
+ }
63
+
64
+ export interface AccessedContentEntry {
65
+ readonly collection: string
66
+ readonly slug: string
67
+ readonly locale?: string | undefined
68
+ }
69
+
70
+ export interface ContentCollectionsService {
71
+ list(root?: string): readonly ContentCollectionDescriptor[] | Promise<readonly ContentCollectionDescriptor[]>
72
+ discover?(root: string): Promise<readonly ContentCollectionDescriptor[]>
73
+ /** Returns file-backed content entries accessed during the given dev request (primary `get()` entries first). */
74
+ accessedEntries?(ctx: RequestContext): readonly AccessedContentEntry[]
75
+ }
76
+
77
+ export const CONTENT_COLLECTIONS_SERVICE = serviceKey<ContentCollectionsService>('prunelle.content.collections')
78
+
79
+ /** Provided by `@prunellejs/cms` in dev mode when in-page editing is enabled so `@prunellejs/content` emits body anchor comments. */
80
+ export const CMS_INLINE_ENABLED_SERVICE = serviceKey<boolean>('prunelle.cms.inline')
81
+
82
+ export interface JobsQueueOptions {
83
+ attempts?: number | undefined
84
+ backoff?: 'exponential' | 'fixed' | number | undefined
85
+ }
86
+
87
+ export interface JobsEnqueueOptions {
88
+ delay?: number | undefined
89
+ key?: string | undefined
90
+ }
91
+
92
+ export interface JobsService {
93
+ queue<T = unknown>(name: string, handler: (data: T) => void | Promise<void>, options?: JobsQueueOptions): void
94
+ enqueue<T = unknown>(name: string, data: T, options?: JobsEnqueueOptions): Promise<void> | void
95
+ }
96
+
97
+ export const JOBS_SERVICE = serviceKey<JobsService>('prunelle.jobs.service')
@@ -4,12 +4,16 @@ import type { BunPlugin } from 'bun'
4
4
  import type { RouteManifestEntry } from '../build/index'
5
5
  import type { ComplianceConfig } from '../compiler/compliance'
6
6
  import type { ConsentConfig } from '../server/consent'
7
+ import type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from '../server/health'
7
8
  import type { Middleware, RequestContext } from '../server/index'
8
9
  import type { RateLimit, RateLimiter } from '../server/rate-limit'
10
+ import type { RouteCacheOptions } from '../server/route-cache'
9
11
  import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
10
12
  import type { NavigationConfig } from '../ssr/navigation'
11
13
  import type { ServiceKey } from './services'
12
14
 
15
+ export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult }
16
+
13
17
  export type BuildPluginTarget = 'client' | 'server' | 'compile'
14
18
 
15
19
  export interface BuildPluginContext {
@@ -21,14 +25,22 @@ export interface BuildPluginContext {
21
25
  readonly isStatic: boolean
22
26
  readonly dev: boolean
23
27
  readonly routes: readonly RouteManifestEntry[]
28
+ /** Reachable source files (layouts, page, islands, local imports) for each route path. */
29
+ readonly routeSourceFiles?: ReadonlyMap<string, readonly string[]> | undefined
30
+ /** Reachable source files of the root layout and status/error pages (shared across the site). */
31
+ readonly globalSourceFiles?: readonly string[] | undefined
24
32
  /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_pru/<relPath>`). */
25
33
  emitAsset(relPath: string, content: string | Uint8Array): string
26
34
  /** Emit a static file into dist/public/<relPath> served at `/<relPath>`. */
27
35
  emitPublic(relPath: string, content: string | Uint8Array): string
28
36
  /** Add a stylesheet URL to <head> on every page. */
29
37
  addStyle(href: string): void
38
+ /** Prepend a global stylesheet URL before app stylesheets (preserving plugin-before-app cascade order). */
39
+ prependStyle?(href: string): void
30
40
  /** Add a stylesheet URL to <head> on a specific route path only. */
31
41
  addRouteStyle(routePath: string, href: string): void
42
+ /** Prepend a route-specific stylesheet URL before that route's app stylesheets. */
43
+ prependRouteStyle?(routePath: string, href: string): void
32
44
  /** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
33
45
  addHead(html: string): void
34
46
  /** Add raw HTML to <head> on a specific route path only. */
@@ -44,6 +56,8 @@ export interface BuildPluginContext {
44
56
  export interface FinalizeBuildContext {
45
57
  readonly root: string
46
58
  readonly outDir: string
59
+ /** Base directory that `route.prerendered` relative paths resolve against (equals `stageDir` in `--static`, `outDir` otherwise). */
60
+ readonly prerenderDir?: string | undefined
47
61
  readonly assetPrefix: string
48
62
  readonly site?: string | undefined
49
63
  readonly minify: boolean
@@ -72,6 +86,10 @@ export interface CheckPluginContext {
72
86
  error(message: string): void
73
87
  /** Report what may be intended but usually is not; `prunelle check --strict` fails on it. */
74
88
  warn(message: string): void
89
+ /** Register a check-scoped service for downstream plugins. */
90
+ provide?<T>(key: ServiceKey<T>, value: T): void
91
+ /** Look up a check-scoped service registered by an earlier plugin. */
92
+ inject?<T>(key: ServiceKey<T>): T | undefined
75
93
  }
76
94
 
77
95
  export interface RequiresPluginContext {
@@ -89,6 +107,11 @@ export interface PluginRouteOptions {
89
107
  trustProxy?: TrustProxy | undefined
90
108
  /** How often one client may call the route: past `max` per `windowMs`, it answers 429 with `Retry-After` before the handler runs. */
91
109
  rateLimit?: RateLimit<RequestContext> | undefined
110
+ /**
111
+ * Let the route's catch-all take a segment with an encoded `/`, `\` or NUL (`%2F`, `%5C`, `%00`), which every route refuses by default.
112
+ * Such a segment reaches the param still encoded, never as a separator: for a route that reads it as text (a QR code of a URL), never one that joins it into a file path.
113
+ */
114
+ encodedSlashes?: boolean | undefined
92
115
  }
93
116
 
94
117
  export interface MiddlewareOptions {
@@ -126,6 +149,8 @@ export interface ServerPluginAPI {
126
149
  inject<T>(key: ServiceKey<T>): T | undefined
127
150
  /** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
128
151
  getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
152
+ /** Register a named health check evaluated on `GET ${assetPrefix}/health`. */
153
+ healthCheck(name: string, fn: HealthCheckFn): void
129
154
  /** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
130
155
  onShutdown(fn: () => void | Promise<void>): void
131
156
  }
@@ -134,6 +159,7 @@ export interface ServerErrorInfo {
134
159
  error: unknown
135
160
  request: Request
136
161
  source: 'route' | 'action' | 'plugin'
162
+ requestId?: string | undefined
137
163
  }
138
164
 
139
165
  export interface DocumentHeadContext {
@@ -215,6 +241,10 @@ export interface ServerRuntimeConfig {
215
241
  /** CNIL/RGPD consent categories, cookie name, retention, and POST endpoint. */
216
242
  consent?: ConsentConfig | undefined
217
243
  compress?: boolean | undefined
244
+ /** Bounded in-memory cache for routes exporting `export const cache = ...` (default: 500 entries / 32 MiB; set `false` to disable). */
245
+ routeCache?: RouteCacheOptions | false | undefined
246
+ /** Health check function or named check map evaluated on `GET ${assetPrefix}/health`. */
247
+ healthCheck?: HealthCheckConfig | undefined
218
248
  onError?: ((info: ServerErrorInfo) => void) | undefined
219
249
  plugins?: PrunellePlugin[] | undefined
220
250
  }
@@ -226,4 +256,6 @@ export interface PrunelleConfig extends ServerRuntimeConfig {
226
256
  publicDir?: string | undefined
227
257
  /** French web law compliance checks (RGAA, RGPD, LCEN) configuration and rule silencing. */
228
258
  compliance?: ComplianceConfig | undefined
259
+ /** Automatically prerender static pages that read nothing from the request or clock (and have no middleware or `cache` export). */
260
+ autoPrerender?: boolean | undefined
229
261
  }