prunelle 0.1.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,177 @@
1
+ // Persists the last dev build error, child crash, and recent runtime errors in an append-only journal, `.prunelle-dev/last-errors.jsonl`,
2
+ // so `prunelle mcp` (`dev_errors` tool) can inspect live dev failures without touching `dist/` or tracked files.
3
+
4
+ import type { ServerErrorInfo } from '../plugins/index'
5
+ import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
6
+ import { dirname, join, resolve } from 'node:path'
7
+
8
+ export interface DevErrorEntry {
9
+ kind: 'build' | 'runtime' | 'crash'
10
+ timestamp: string
11
+ message: string
12
+ source?: string | undefined
13
+ method?: string | undefined
14
+ path?: string | undefined
15
+ }
16
+
17
+ export interface DevErrorLog {
18
+ updatedAt: string
19
+ buildError?: string | undefined
20
+ crashError?: string | undefined
21
+ runtimeErrors: DevErrorEntry[]
22
+ }
23
+
24
+ const MAX_RUNTIME_ERRORS = 20
25
+ /** Past this size the journal is folded back to its current state. */
26
+ const COMPACT_BYTES = 256 * 1024
27
+
28
+ /** One line of the journal: a build or crash message (none clears it), or a runtime error. */
29
+ type JournalRecord =
30
+ | { op: 'build' | 'crash', at: string, message?: string | undefined }
31
+ | { op: 'runtime', at: string, entry: DevErrorEntry }
32
+
33
+ function errorLogPath(root: string): string {
34
+ return join(resolve(root), '.prunelle-dev', 'last-errors.jsonl')
35
+ }
36
+
37
+ function isDevErrorEntry(value: unknown): value is DevErrorEntry {
38
+ if (typeof value !== 'object' || value === null)
39
+ return false
40
+ const rec = value as Record<string, unknown>
41
+ return (rec.kind === 'build' || rec.kind === 'runtime' || rec.kind === 'crash')
42
+ && typeof rec.timestamp === 'string'
43
+ && typeof rec.message === 'string'
44
+ }
45
+
46
+ function parseRecord(line: string): JournalRecord | undefined {
47
+ try {
48
+ const rec = JSON.parse(line) as Record<string, unknown>
49
+ if (typeof rec.at !== 'string')
50
+ return undefined
51
+ if ((rec.op === 'build' || rec.op === 'crash') && (rec.message === undefined || typeof rec.message === 'string'))
52
+ return { op: rec.op, at: rec.at, message: rec.message }
53
+ if (rec.op === 'runtime' && isDevErrorEntry(rec.entry))
54
+ return { op: 'runtime', at: rec.at, entry: rec.entry }
55
+ }
56
+ catch {
57
+ // A line cut by a crash is skipped; the rest of the journal still reads.
58
+ return undefined
59
+ }
60
+ return undefined
61
+ }
62
+
63
+ /** Folds the journal lines, in order, into the state they leave. */
64
+ function foldJournal(text: string): DevErrorLog | undefined {
65
+ let log: DevErrorLog | undefined
66
+ for (const line of text.split('\n')) {
67
+ const rec = line === '' ? undefined : parseRecord(line)
68
+ if (rec === undefined)
69
+ continue
70
+ log ??= { updatedAt: rec.at, runtimeErrors: [] }
71
+ log.updatedAt = rec.at
72
+ if (rec.op === 'runtime') {
73
+ log.runtimeErrors.push(rec.entry)
74
+ if (log.runtimeErrors.length > MAX_RUNTIME_ERRORS)
75
+ log.runtimeErrors.shift()
76
+ continue
77
+ }
78
+ const key = rec.op === 'build' ? 'buildError' : 'crashError'
79
+ if (rec.message !== undefined && rec.message.length > 0)
80
+ log[key] = rec.message
81
+ else
82
+ delete log[key]
83
+ }
84
+ return log
85
+ }
86
+
87
+ /** Reads `.prunelle-dev/last-errors.jsonl` safely, returning `undefined` when missing or unreadable. */
88
+ export function readDevErrorLog(root: string): DevErrorLog | undefined {
89
+ try {
90
+ return foldJournal(readFileSync(errorLogPath(root), 'utf8'))
91
+ }
92
+ catch {
93
+ return undefined
94
+ }
95
+ }
96
+
97
+ /** The records that rebuild `log`, for a compacted journal. */
98
+ function recordsOf(log: DevErrorLog): JournalRecord[] {
99
+ return [
100
+ ...(log.buildError !== undefined ? [{ op: 'build', at: log.updatedAt, message: log.buildError } as const] : []),
101
+ ...(log.crashError !== undefined ? [{ op: 'crash', at: log.updatedAt, message: log.crashError } as const] : []),
102
+ ...log.runtimeErrors.map(entry => ({ op: 'runtime', at: entry.timestamp, entry }) as const),
103
+ ]
104
+ }
105
+
106
+ /**
107
+ * Appends one record. A short `O_APPEND` write lands whole, so two processes (the supervisor and its child) never overwrite each other.
108
+ * Only a journal past `COMPACT_BYTES` is rewritten, through a temp file.
109
+ */
110
+ function appendRecord(root: string, rec: JournalRecord): void {
111
+ const file = errorLogPath(root)
112
+ try {
113
+ mkdirSync(dirname(file), { recursive: true })
114
+ appendFileSync(file, `${JSON.stringify(rec)}\n`, 'utf8')
115
+ if (statSync(file).size <= COMPACT_BYTES)
116
+ return
117
+ const log = foldJournal(readFileSync(file, 'utf8'))
118
+ if (log === undefined)
119
+ return
120
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
121
+ writeFileSync(tmp, recordsOf(log).map(r => `${JSON.stringify(r)}\n`).join(''), 'utf8')
122
+ renameSync(tmp, file)
123
+ }
124
+ catch {
125
+ // The log is a convenience for `prunelle mcp`; a read-only folder must not take the dev server down.
126
+ return
127
+ }
128
+ }
129
+
130
+ /** Records or clears the active dev build error (passing `undefined` clears it after a successful build). */
131
+ export function recordDevBuildError(root: string, message: string | undefined): void {
132
+ appendRecord(root, { op: 'build', at: new Date().toISOString(), message })
133
+ }
134
+
135
+ /** Records or clears the active dev child crash message (passing `undefined` clears it once the child is ready). */
136
+ export function recordDevCrashError(root: string, message: string | undefined): void {
137
+ appendRecord(root, { op: 'crash', at: new Date().toISOString(), message })
138
+ }
139
+
140
+ /** Appends a runtime error to `.prunelle-dev/last-errors.jsonl`; reading keeps the last 20. */
141
+ export function recordDevRuntimeError(root: string, entry: Omit<DevErrorEntry, 'kind' | 'timestamp'>): void {
142
+ const at = new Date().toISOString()
143
+ appendRecord(root, {
144
+ op: 'runtime',
145
+ at,
146
+ entry: {
147
+ kind: 'runtime',
148
+ timestamp: at,
149
+ message: entry.message,
150
+ ...(entry.source !== undefined ? { source: entry.source } : {}),
151
+ ...(entry.method !== undefined ? { method: entry.method } : {}),
152
+ ...(entry.path !== undefined ? { path: entry.path } : {}),
153
+ },
154
+ })
155
+ }
156
+
157
+ function safePathname(rawUrl: string): string {
158
+ try {
159
+ return new URL(rawUrl).pathname
160
+ }
161
+ catch {
162
+ return rawUrl
163
+ }
164
+ }
165
+
166
+ /** Builds an `errorSink` callback for `devServer` that records unhandled runtime errors into `.prunelle-dev/last-errors.json`. */
167
+ export function createDevRuntimeErrorSink(root: string): (info: ServerErrorInfo) => void {
168
+ return (info) => {
169
+ const message = info.error instanceof Error ? info.error.stack ?? info.error.message : String(info.error)
170
+ recordDevRuntimeError(root, {
171
+ message,
172
+ source: info.source,
173
+ method: info.request.method,
174
+ path: safePathname(info.request.url),
175
+ })
176
+ }
177
+ }
@@ -0,0 +1,32 @@
1
+ // A DNS-rebinding page reaches a dev server under the page's own domain name, so the dev server answers only the names it can be opened under.
2
+
3
+ const LOOPBACK_NAMES = new Set(['localhost', '127.0.0.1', '[::1]'])
4
+ const IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/
5
+ const BAD_HOST_CHARS_RE = /[@/?#\\\s\u0000-\u001F\u007F]/
6
+
7
+ function hostnameOf(host: string): string | undefined {
8
+ if (host.length === 0 || BAD_HOST_CHARS_RE.test(host) || !URL.canParse(`http://${host}`))
9
+ return undefined
10
+ const parsed = new URL(`http://${host}`)
11
+ if (parsed.username !== '' || parsed.password !== '' || parsed.pathname !== '/' || parsed.search !== '' || parsed.hash !== '')
12
+ return undefined
13
+ return parsed.hostname
14
+ }
15
+
16
+ /** Refuses with `421` a request whose `Host` is not loopback, `*.localhost`, an IP address, the bound `hostname` or the host of one of `origins`. */
17
+ export function createDevHostCheck(hostname: string | undefined, origins: readonly (string | undefined)[]): (request: Request) => Response | undefined {
18
+ const names = new Set<string>()
19
+ if (hostname !== undefined)
20
+ names.add(hostnameOf(hostname) ?? hostname)
21
+ for (const origin of origins) {
22
+ if (origin !== undefined && URL.canParse(origin))
23
+ names.add(new URL(origin).hostname)
24
+ }
25
+ return (request) => {
26
+ const host = request.headers.get('host') ?? ''
27
+ const name = hostnameOf(host)
28
+ if (name !== undefined && (LOOPBACK_NAMES.has(name) || name.endsWith('.localhost') || name.startsWith('[') || IPV4_RE.test(name) || names.has(name)))
29
+ return undefined
30
+ return new Response(`prunelle dev: refused Host "${name ?? host}": a dev server answers only localhost, an IP address, its --host and the hosts of site and trustedOrigins in prunelle.config.ts, so that a page on another domain cannot reach it by DNS rebinding. Add the origin you open it under to trustedOrigins.\n`, { status: 421, headers: { 'content-type': 'text/plain; charset=utf-8' } })
31
+ }
32
+ }
package/src/dev/index.ts CHANGED
@@ -4,16 +4,20 @@
4
4
  import type { Server } from 'bun'
5
5
  import type { BuildCacheStats } from '../build/graph'
6
6
  import type { PrunelleApp } from '../server/index'
7
+ import type { TrustProxy } from '../server/security'
7
8
  import type { RecycleReason } from './protocol'
8
9
  import type { PendingBuild } from './queue'
9
- import { rmSync } from 'node:fs'
10
+ import { existsSync, readdirSync, rmSync } from 'node:fs'
10
11
  import { join, resolve } from 'node:path'
11
12
  import { clearBuildCache } from '../build/graph'
12
13
  import { build, createBuildCache } from '../build/index'
13
14
  import { loadConfig, resolveServerConfig } from '../plugins/index'
14
15
  import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
15
16
  import { createServer } from '../server/index'
17
+ import { createDevRuntimeErrorSink, recordDevBuildError } from './error-log'
16
18
  import { createModuleStore } from './modules'
19
+ import { createDevHostCheck } from './host-check'
20
+ import { handleOpenEditorRequest } from './open-editor'
17
21
  import { DEV_CLIENT_IP_HEADER } from './protocol'
18
22
  import { createRebuildQueue } from './queue'
19
23
  import { buildErrorResponse, createReloadHub, makeDevReloadAssets, withReloadScript } from './reload'
@@ -37,6 +41,71 @@ export interface DevServerOptions {
37
41
 
38
42
  const errorText = (err: unknown): string => err instanceof Error ? err.stack ?? err.message : String(err)
39
43
 
44
+ /** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.jsonl` intact across child recycles. */
45
+ function cleanDevArtifacts(devRoot: string): void {
46
+ if (!existsSync(devRoot))
47
+ return
48
+ for (const entry of readdirSync(devRoot)) {
49
+ if (entry !== 'last-errors.jsonl')
50
+ rmSync(join(devRoot, entry), { recursive: true, force: true })
51
+ }
52
+ }
53
+
54
+ function startDevHttpServer(
55
+ options: DevServerOptions,
56
+ maxRequestBodySize: number,
57
+ configPort: number | undefined,
58
+ onFetch: (request: Request, srv: Server<undefined>) => Promise<Response>,
59
+ ): { server: Server<undefined>, url: string } {
60
+ const hostname = options.hostname ?? '127.0.0.1'
61
+ const serveOptions = { maxRequestBodySize, fetch: onFetch }
62
+ const server = options.unix !== undefined
63
+ ? Bun.serve({ ...serveOptions, unix: options.unix })
64
+ : Bun.serve({ ...serveOptions, port: options.port ?? configPort ?? 3000, hostname, idleTimeout: 30 })
65
+ // `0.0.0.0` is printed as the loopback address a browser on this machine opens.
66
+ const url = options.unix !== undefined ? `unix:${options.unix}` : `http://${hostname === '0.0.0.0' ? '127.0.0.1' : hostname}:${server.port}`
67
+ if (options.unix === undefined)
68
+ console.log(`[prunelle dev] listening on ${url}`)
69
+ return { server, url }
70
+ }
71
+
72
+ async function handleAppFetch(
73
+ request: Request,
74
+ srv: Server<undefined>,
75
+ state: {
76
+ root: string
77
+ unix: string | undefined
78
+ checkHost: ((request: Request) => Response | undefined) | undefined
79
+ hub: ReturnType<typeof createReloadHub> | undefined
80
+ reloadAssets: ReturnType<typeof makeDevReloadAssets>
81
+ lastError: string | undefined
82
+ app: PrunelleApp | undefined
83
+ trustedOrigins: readonly string[] | undefined
84
+ trustProxy: TrustProxy | undefined
85
+ },
86
+ ): Promise<Response> {
87
+ const refused = state.checkHost?.(request)
88
+ if (refused !== undefined)
89
+ return refused
90
+ const { pathname } = new URL(request.url)
91
+ if (state.hub !== undefined && pathname === state.reloadAssets.eventsPath) {
92
+ srv.timeout(request, 0)
93
+ return state.hub.events(request)
94
+ }
95
+ const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
96
+ if (pathname === state.reloadAssets.openEditorPath)
97
+ return handleOpenEditorRequest(request, state.root, { trustedOrigins: state.trustedOrigins, trustProxy: state.trustProxy, remoteIp: remoteIp ?? '' })
98
+ if (state.lastError !== undefined)
99
+ return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
100
+
101
+ const res = await state.app!.handle(request, remoteIp)
102
+ const ct = res.headers.get('content-type') ?? ''
103
+ const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
104
+ if (ct.includes('text/event-stream') || isStreamedHtml)
105
+ srv.timeout(request, 0)
106
+ return withReloadScript(request, res, state.reloadAssets)
107
+ }
108
+
40
109
  export async function devServer(options: DevServerOptions): Promise<{
41
110
  url: string
42
111
  assetPrefix: string
@@ -47,8 +116,8 @@ export async function devServer(options: DevServerOptions): Promise<{
47
116
  const root = resolve(options.root)
48
117
  const devRoot = join(root, '.prunelle-dev')
49
118
  const initialCfg = await loadConfig(root, { dev: true })
50
- // Clean stale `.prunelle-dev/` left behind by a previously killed dev process.
51
- rmSync(devRoot, { recursive: true, force: true })
119
+ // Clean stale build folders left behind by a previously killed or recycled dev process, preserving last-errors.jsonl.
120
+ cleanDevArtifacts(devRoot)
52
121
  let activeCfg = initialCfg
53
122
  let activeAssetPrefix = (initialCfg.assetPrefix ?? '/_pru').replace(/\/$/, '')
54
123
  let reloadAssets = makeDevReloadAssets(activeAssetPrefix)
@@ -56,7 +125,13 @@ export async function devServer(options: DevServerOptions): Promise<{
56
125
  const modules = createModuleStore(join(devRoot, 'server'))
57
126
  const hub = options.broadcast === undefined ? createReloadHub() : undefined
58
127
  const broadcast = options.broadcast ?? hub!.broadcast
59
- const recycle = options.recycle
128
+ let recycled = false
129
+ const recycle = options.recycle === undefined
130
+ ? undefined
131
+ : (reason: RecycleReason) => {
132
+ recycled = true
133
+ options.recycle!(reason)
134
+ }
60
135
  const queue = createRebuildQueue(runSingleBuild)
61
136
  const watchers = createDevWatchers({
62
137
  root,
@@ -65,7 +140,7 @@ export async function devServer(options: DevServerOptions): Promise<{
65
140
  routesDir: options.routesDir,
66
141
  schedule: kind => kind === 'config' && recycle !== undefined ? recycle('config') : queue.schedule(kind),
67
142
  })
68
- const serverOptions = { root, dev: true, compress: false, ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
143
+ const serverOptions = { root, dev: true, devHost: options.hostname ?? '127.0.0.1', compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
69
144
 
70
145
  let buildNum = 0
71
146
  let current: { app: PrunelleApp, outDir: string } | undefined
@@ -119,6 +194,7 @@ export async function devServer(options: DevServerOptions): Promise<{
119
194
  return
120
195
  }
121
196
  lastError = undefined
197
+ recordDevBuildError(root, undefined)
122
198
  watchers.syncBuild(buildCache.watchedFiles, manifest.publicFiles)
123
199
  if (n > 2)
124
200
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
@@ -131,6 +207,7 @@ export async function devServer(options: DevServerOptions): Promise<{
131
207
  if (stopped)
132
208
  return
133
209
  lastError = errorText(err)
210
+ recordDevBuildError(root, lastError)
134
211
  console.error(`[prunelle dev] build error:\n${lastError}`)
135
212
  // Push reload over SSE so open browser tabs immediately display the error overlay
136
213
  broadcast('reload')
@@ -150,34 +227,14 @@ export async function devServer(options: DevServerOptions): Promise<{
150
227
  }
151
228
 
152
229
  const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
153
- const hostname = options.hostname ?? '127.0.0.1'
154
- const serveOptions = {
155
- maxRequestBodySize: runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
156
- async fetch(request: Request, srv: Server<undefined>): Promise<Response> {
157
- if (hub !== undefined && new URL(request.url).pathname === reloadAssets.eventsPath) {
158
- srv.timeout(request, 0)
159
- return hub.events(request)
160
- }
161
- if (lastError !== undefined)
162
- return buildErrorResponse(request, lastError, reloadAssets.script)
163
-
164
- const remoteIp = options.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
165
- const res = await current!.app.handle(request, remoteIp)
166
- const ct = res.headers.get('content-type') ?? ''
167
- const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
168
- if (ct.includes('text/event-stream') || isStreamedHtml)
169
- srv.timeout(request, 0)
170
- return withReloadScript(request, res, reloadAssets)
171
- },
172
- }
173
- const server = options.unix !== undefined
174
- ? Bun.serve({ ...serveOptions, unix: options.unix })
175
- : Bun.serve({ ...serveOptions, port: options.port ?? initialCfg.port ?? 3000, hostname, idleTimeout: 30 })
176
-
177
- // `0.0.0.0` is printed as the loopback address a browser on this machine opens.
178
- const url = options.unix !== undefined ? `unix:${options.unix}` : `http://${hostname === '0.0.0.0' ? '127.0.0.1' : hostname}:${server.port}`
179
- if (options.unix === undefined)
180
- console.log(`[prunelle dev] listening on ${url}`)
230
+ // Behind the supervisor's socket, the supervisor has checked the Host already.
231
+ const checkHost = options.unix === undefined ? createDevHostCheck(options.hostname, [initialCfg.site, ...initialCfg.trustedOrigins ?? []]) : undefined
232
+ const { server, url } = startDevHttpServer(
233
+ options,
234
+ runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
235
+ initialCfg.port,
236
+ (request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, checkHost, hub, reloadAssets, lastError, app: current?.app, trustedOrigins: activeCfg.trustedOrigins, trustProxy: activeCfg.trustProxy }),
237
+ )
181
238
  let stopPromise: Promise<void> | undefined
182
239
 
183
240
  return {
@@ -200,7 +257,10 @@ export async function devServer(options: DevServerOptions): Promise<{
200
257
  catch (err) {
201
258
  console.warn(`[prunelle dev] the app failed to dispose: ${errorText(err)}`)
202
259
  }
203
- rmSync(devRoot, { recursive: true, force: true })
260
+ if (recycled)
261
+ cleanDevArtifacts(devRoot)
262
+ else
263
+ rmSync(devRoot, { recursive: true, force: true })
204
264
  })()
205
265
  return stopPromise
206
266
  },
@@ -0,0 +1,228 @@
1
+ // Opens a project source file at `line:col` in `$PRUNELLE_EDITOR` or `$VISUAL` on Alt-click in `prunelle dev`.
2
+
3
+ import type { TrustProxy } from '../server/security'
4
+ import { existsSync, realpathSync } from 'node:fs'
5
+ import { relative, resolve } from 'node:path'
6
+ import { isInside } from '../build/is-inside'
7
+ import { verifyOrigin } from '../server/security'
8
+
9
+ export const OPEN_EDITOR_SUBPATH = 'open-editor'
10
+
11
+ export interface ParsedSourceLoc {
12
+ file: string
13
+ relFile: string
14
+ line: number
15
+ col: number
16
+ }
17
+
18
+ const POSITIVE_INT_RE = /^\d+$/
19
+ const BIN_EXT_RE = /\.(?:exe|cmd|bat)$/i
20
+ const MISSING_EDITOR_ERROR = 'Set PRUNELLE_EDITOR or VISUAL to open files on Alt-click.'
21
+
22
+ const VSCODE_EDITORS = new Set(['code', 'code-insiders', 'codium', 'vscodium', 'cursor', 'windsurf'])
23
+ const ZED_EDITORS = new Set(['zed', 'zeditor'])
24
+ const JETBRAINS_EDITORS = new Set(['idea', 'webstorm', 'phpstorm', 'pycharm', 'goland', 'rubymine', 'rider', 'clion', 'datagrip', 'fleet', 'studio'])
25
+ const SUBLIME_HELIX_EDITORS = new Set(['subl', 'sublime_text', 'hx'])
26
+ const TERMINAL_EDITORS = new Set(['vim', 'nvim', 'vi', 'nano', 'emacs', 'emacsclient'])
27
+
28
+ /** Splits an editor command string into argv tokens, honoring single/double quotes without invoking a shell. */
29
+ function splitEditorSpec(spec: string): string[] {
30
+ const tokens: string[] = []
31
+ let current = ''
32
+ let quote: '\'' | '"' | undefined
33
+ let hasToken = false
34
+
35
+ for (let i = 0; i < spec.length; i++) {
36
+ const ch = spec[i]!
37
+ if (quote !== undefined) {
38
+ if (ch === '\\' && quote === '"' && i + 1 < spec.length && (spec[i + 1] === '"' || spec[i + 1] === '\\')) {
39
+ current += spec[++i]!
40
+ }
41
+ else if (ch === quote) {
42
+ quote = undefined
43
+ }
44
+ else {
45
+ current += ch
46
+ }
47
+ continue
48
+ }
49
+
50
+ if (ch === '\'' || ch === '"') {
51
+ quote = ch
52
+ hasToken = true
53
+ continue
54
+ }
55
+ if (ch === '\\' && i + 1 < spec.length && /\s/.test(spec[i + 1]!)) {
56
+ current += spec[++i]!
57
+ hasToken = true
58
+ continue
59
+ }
60
+ if (/\s/.test(ch)) {
61
+ if (hasToken) {
62
+ tokens.push(current)
63
+ current = ''
64
+ hasToken = false
65
+ }
66
+ continue
67
+ }
68
+ current += ch
69
+ hasToken = true
70
+ }
71
+
72
+ if (hasToken)
73
+ tokens.push(current)
74
+ return tokens
75
+ }
76
+
77
+ /** Parses and validates a `relPath:line:col` location, confining it strictly inside `root`. */
78
+ export function parseSourceLoc(raw: string, root: string): ParsedSourceLoc | { error: string, status: 400 | 403 | 404 } {
79
+ const trimmed = raw.trim()
80
+ const lastColon = trimmed.lastIndexOf(':')
81
+ const prevColon = lastColon > 0 ? trimmed.lastIndexOf(':', lastColon - 1) : -1
82
+ if (lastColon <= 0 || prevColon <= 0)
83
+ return { error: 'Invalid source location; expected file:line:col.', status: 400 }
84
+
85
+ const relPart = trimmed.slice(0, prevColon)
86
+ const lineStr = trimmed.slice(prevColon + 1, lastColon)
87
+ const colStr = trimmed.slice(lastColon + 1)
88
+ if (relPart === '' || relPart.includes('\0') || !POSITIVE_INT_RE.test(lineStr) || !POSITIVE_INT_RE.test(colStr))
89
+ return { error: 'Invalid source location; expected file:line:col.', status: 400 }
90
+
91
+ const line = Number.parseInt(lineStr, 10)
92
+ const col = Number.parseInt(colStr, 10)
93
+ if (!Number.isSafeInteger(line) || line < 1 || !Number.isSafeInteger(col) || col < 1)
94
+ return { error: 'Line and column must be positive integers.', status: 400 }
95
+
96
+ const resolvedRoot = resolve(root)
97
+ const file = resolve(resolvedRoot, relPart)
98
+ if (!isInside(resolvedRoot, file))
99
+ return { error: 'Source file is outside the project root.', status: 403 }
100
+ if (!existsSync(file))
101
+ return { error: 'Source file does not exist.', status: 404 }
102
+
103
+ const realRoot = realpathSync(resolvedRoot)
104
+ const realFile = realpathSync(file)
105
+ if (!isInside(realRoot, realFile))
106
+ return { error: 'Source file is outside the project root.', status: 403 }
107
+
108
+ return { file, relFile: relative(resolvedRoot, file).replaceAll('\\', '/'), line, col }
109
+ }
110
+
111
+ /** Builds the argv array to open `loc` in `editorSpec` (supporting `{file}`/`{line}`/`{col}` templates and common editors). */
112
+ export function buildEditorCommand(editorSpec: string, loc: { file: string, line: number, col: number }): string[] {
113
+ const parts = splitEditorSpec(editorSpec.trim())
114
+ if (parts.length === 0)
115
+ return []
116
+
117
+ const lineStr = String(loc.line)
118
+ const colStr = String(loc.col)
119
+ if (parts.some(p => p.includes('{file}') || p.includes('{line}') || p.includes('{col}')))
120
+ return parts.map(p => p.replaceAll('{file}', loc.file).replaceAll('{line}', lineStr).replaceAll('{col}', colStr))
121
+
122
+ const rawBin = parts[0]!.split(/[\\/]/).pop() ?? ''
123
+ const bin = rawBin.toLowerCase().replace(BIN_EXT_RE, '')
124
+ const fileLineCol = `${loc.file}:${lineStr}:${colStr}`
125
+
126
+ if (VSCODE_EDITORS.has(bin))
127
+ return [...parts, '--goto', fileLineCol]
128
+ if (ZED_EDITORS.has(bin) || SUBLIME_HELIX_EDITORS.has(bin))
129
+ return [...parts, fileLineCol]
130
+ if (JETBRAINS_EDITORS.has(bin))
131
+ return [...parts, '--line', lineStr, '--column', colStr, loc.file]
132
+ if (TERMINAL_EDITORS.has(bin))
133
+ return [...parts, `+${lineStr}`, loc.file]
134
+ return [...parts, fileLineCol]
135
+ }
136
+
137
+ export interface OpenEditorOptions {
138
+ env?: Record<string, string | undefined> | undefined
139
+ spawn?: ((cmd: string[]) => void) | undefined
140
+ trustedOrigins?: ReadonlySet<string> | readonly string[] | undefined
141
+ trustProxy?: TrustProxy | undefined
142
+ remoteIp?: string | undefined
143
+ }
144
+
145
+ const IPV4_LOOPBACK_RE = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
146
+
147
+ function isLoopbackIp(ip: string): boolean {
148
+ const bare = ip.trim().toLowerCase().replace(/^\[|\]$/g, '')
149
+ const unmapped = bare.startsWith('::ffff:') ? bare.slice(7) : bare
150
+ return unmapped === '::1' || unmapped === '0:0:0:0:0:0:0:1' || IPV4_LOOPBACK_RE.test(unmapped)
151
+ }
152
+
153
+ export function openInEditor(
154
+ rawSrc: string,
155
+ root: string,
156
+ options?: OpenEditorOptions,
157
+ ): { ok: true, command: string[] } | { ok: false, status: number, error: string } {
158
+ const env = options?.env ?? process.env
159
+ const editor = env.PRUNELLE_EDITOR?.trim() || env.VISUAL?.trim()
160
+ if (!editor)
161
+ return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
162
+
163
+ const parsed = parseSourceLoc(rawSrc, root)
164
+ if ('error' in parsed)
165
+ return { ok: false, status: parsed.status, error: parsed.error }
166
+
167
+ const command = buildEditorCommand(editor, parsed)
168
+ if (command.length === 0)
169
+ return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
170
+
171
+ try {
172
+ if (options?.spawn !== undefined) {
173
+ options.spawn(command)
174
+ }
175
+ else {
176
+ const proc = Bun.spawn(command, { cwd: root, stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' })
177
+ proc.unref()
178
+ }
179
+ }
180
+ catch (err) {
181
+ return {
182
+ ok: false,
183
+ status: 500,
184
+ error: `Failed to launch editor "${command[0]}": ${err instanceof Error ? err.message : String(err)}`,
185
+ }
186
+ }
187
+
188
+ return { ok: true, command }
189
+ }
190
+
191
+ /** Handles `POST /_pru/open-editor` from the dev server's Alt-click listener: a same-origin JSON body only, so another site cannot open the editor with a form or a no-cors fetch. */
192
+ export async function handleOpenEditorRequest(
193
+ request: Request,
194
+ root: string,
195
+ options?: OpenEditorOptions,
196
+ ): Promise<Response> {
197
+ if (request.method !== 'POST')
198
+ return Response.json({ ok: false, error: 'Method Not Allowed' }, { status: 405, headers: { allow: 'POST' } })
199
+ if (options?.remoteIp !== undefined && !isLoopbackIp(options.remoteIp))
200
+ return Response.json({ ok: false, error: 'Open-editor is only available from loopback addresses.' }, { status: 403 })
201
+ const trusted = options?.trustedOrigins === undefined
202
+ ? undefined
203
+ : options.trustedOrigins instanceof Set
204
+ ? options.trustedOrigins
205
+ : new Set(options.trustedOrigins)
206
+ const originCheck = verifyOrigin(request, trusted, options?.trustProxy ?? false)
207
+ if (!originCheck.ok)
208
+ return Response.json({ ok: false, error: originCheck.reason }, { status: 403 })
209
+ const mediaType = (request.headers.get('content-type') ?? '').split(';', 1)[0]!.trim().toLowerCase()
210
+ if (mediaType !== 'application/json')
211
+ return Response.json({ ok: false, error: 'Expected content-type: application/json.' }, { status: 415 })
212
+
213
+ let rawSrc = ''
214
+ try {
215
+ const body = await request.json() as unknown
216
+ if (body !== null && typeof body === 'object' && typeof (body as { src?: unknown }).src === 'string')
217
+ rawSrc = (body as { src: string }).src
218
+ }
219
+ catch {
220
+ return Response.json({ ok: false, error: 'Invalid JSON body; expected { "src": "file:line:col" }.' }, { status: 400 })
221
+ }
222
+
223
+ if (rawSrc.trim() === '')
224
+ return Response.json({ ok: false, error: 'Missing "src" location.' }, { status: 400 })
225
+
226
+ const result = openInEditor(rawSrc, root, options)
227
+ return Response.json(result, { status: result.ok ? 200 : result.status })
228
+ }
@@ -12,6 +12,9 @@ export interface DevChildOptions {
12
12
  root: string
13
13
  routesDir?: string | undefined
14
14
  unix: string
15
+ /** The address the parent binds, which the app's plugins see as `api.devExposed`. */
16
+ hostname?: string | undefined
17
+ maxRequestBodySize?: number | undefined
15
18
  maxRssMb?: number | undefined
16
19
  }
17
20
 
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();for(const u of urls){const k=stem(u);byStem.set(k,byStem.has(k)?null: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===null){location.reload();return;}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 {