prunelle 0.0.0-stage → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/llms.txt +152 -0
  2. package/package.json +59 -4
  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/ambient.d.ts +6 -0
  7. package/src/attrs.ts +43 -0
  8. package/src/build/bundle.ts +657 -0
  9. package/src/build/carry.ts +57 -0
  10. package/src/build/client-entries.ts +107 -0
  11. package/src/build/client-plugin.ts +173 -0
  12. package/src/build/client-prune.ts +168 -0
  13. package/src/build/compile.ts +129 -0
  14. package/src/build/ecoindex.ts +229 -0
  15. package/src/build/files.ts +156 -0
  16. package/src/build/first-load.ts +164 -0
  17. package/src/build/graph.ts +247 -0
  18. package/src/build/index.ts +641 -0
  19. package/src/build/is-inside.ts +12 -0
  20. package/src/build/islands.ts +641 -0
  21. package/src/build/manifest.ts +325 -0
  22. package/src/build/output.ts +84 -0
  23. package/src/build/plugin-host.ts +278 -0
  24. package/src/build/precompress.ts +139 -0
  25. package/src/build/prerender.ts +232 -0
  26. package/src/build/render-rules.ts +205 -0
  27. package/src/build/report.ts +268 -0
  28. package/src/build/resolve.ts +52 -0
  29. package/src/build/routes.ts +342 -0
  30. package/src/build/server-entry.ts +38 -0
  31. package/src/build/static.ts +207 -0
  32. package/src/build/status-pages.ts +127 -0
  33. package/src/build/style-bundles.ts +526 -0
  34. package/src/cli/check-forms.ts +654 -0
  35. package/src/cli/check-links.ts +619 -0
  36. package/src/cli/check.ts +381 -0
  37. package/src/cli/commands.ts +345 -0
  38. package/src/cli/docs.ts +402 -0
  39. package/src/cli/index.ts +70 -0
  40. package/src/cli/inspect.ts +345 -0
  41. package/src/cli/mcp-tools.ts +480 -0
  42. package/src/cli/mcp.ts +205 -0
  43. package/src/cli/new.ts +41 -0
  44. package/src/cli/render.ts +261 -0
  45. package/src/cli/upgrade-names.ts +209 -0
  46. package/src/cli/upgrade.ts +354 -0
  47. package/src/compiler/analyze.ts +632 -0
  48. package/src/compiler/ast.ts +82 -0
  49. package/src/compiler/browser-globals.ts +127 -0
  50. package/src/compiler/cacheability.ts +592 -0
  51. package/src/compiler/compliance-rgaa.ts +502 -0
  52. package/src/compiler/compliance.ts +497 -0
  53. package/src/compiler/data-keys.ts +295 -0
  54. package/src/compiler/dev-source.ts +87 -0
  55. package/src/compiler/dom-attrs.ts +452 -0
  56. package/src/compiler/dom.ts +567 -0
  57. package/src/compiler/emit.ts +131 -0
  58. package/src/compiler/expr-context.ts +518 -0
  59. package/src/compiler/index.ts +8 -0
  60. package/src/compiler/interactivity.ts +366 -0
  61. package/src/compiler/mistakes.ts +499 -0
  62. package/src/compiler/node-env.ts +50 -0
  63. package/src/compiler/patch.ts +97 -0
  64. package/src/compiler/props.ts +511 -0
  65. package/src/compiler/scope.ts +607 -0
  66. package/src/compiler/server-only.ts +326 -0
  67. package/src/compiler/shared.ts +369 -0
  68. package/src/compiler/signal-reads.ts +242 -0
  69. package/src/compiler/slots.ts +227 -0
  70. package/src/compiler/ssr-helpers.ts +555 -0
  71. package/src/compiler/ssr-island.ts +90 -0
  72. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  73. package/src/compiler/ssr.ts +526 -0
  74. package/src/context.ts +165 -0
  75. package/src/dev/child.ts +30 -0
  76. package/src/dev/error-log.ts +151 -0
  77. package/src/dev/index.ts +258 -0
  78. package/src/dev/modules.ts +68 -0
  79. package/src/dev/open-editor.ts +204 -0
  80. package/src/dev/protocol.ts +22 -0
  81. package/src/dev/queue.ts +79 -0
  82. package/src/dev/reload.ts +159 -0
  83. package/src/dev/supervisor.ts +204 -0
  84. package/src/dev/watchers.ts +251 -0
  85. package/src/dom/action.ts +164 -0
  86. package/src/dom/attrs.ts +84 -0
  87. package/src/dom/claim.ts +120 -0
  88. package/src/dom/extras.ts +562 -0
  89. package/src/dom/index.ts +289 -0
  90. package/src/dom/island.ts +285 -0
  91. package/src/dom/loop.ts +450 -0
  92. package/src/dom/revive.ts +36 -0
  93. package/src/index.ts +22 -0
  94. package/src/jsx-runtime.ts +566 -0
  95. package/src/plugins/config.ts +86 -0
  96. package/src/plugins/context.ts +66 -0
  97. package/src/plugins/index.ts +14 -0
  98. package/src/plugins/load.ts +70 -0
  99. package/src/plugins/order.ts +111 -0
  100. package/src/plugins/public.ts +15 -0
  101. package/src/plugins/requires.ts +47 -0
  102. package/src/plugins/services.ts +97 -0
  103. package/src/plugins/types.ts +261 -0
  104. package/src/reactivity/graph.ts +249 -0
  105. package/src/reactivity/index.ts +533 -0
  106. package/src/reactivity/selector.ts +51 -0
  107. package/src/reactivity/store.ts +208 -0
  108. package/src/server/action-protect.ts +198 -0
  109. package/src/server/action-registry.ts +78 -0
  110. package/src/server/action.ts +530 -0
  111. package/src/server/app-entry.ts +23 -0
  112. package/src/server/assets.ts +168 -0
  113. package/src/server/compress.ts +642 -0
  114. package/src/server/consent.ts +253 -0
  115. package/src/server/cookies.ts +139 -0
  116. package/src/server/document.ts +271 -0
  117. package/src/server/env.ts +33 -0
  118. package/src/server/errors.ts +391 -0
  119. package/src/server/form-schema.ts +343 -0
  120. package/src/server/health.ts +244 -0
  121. package/src/server/http.ts +538 -0
  122. package/src/server/index.ts +586 -0
  123. package/src/server/lifecycle.ts +75 -0
  124. package/src/server/loader.ts +123 -0
  125. package/src/server/page.ts +107 -0
  126. package/src/server/param-matchers.ts +112 -0
  127. package/src/server/plugin-host.ts +265 -0
  128. package/src/server/prerendered.ts +71 -0
  129. package/src/server/public.ts +19 -0
  130. package/src/server/rate-limit.ts +156 -0
  131. package/src/server/region.ts +96 -0
  132. package/src/server/request-body.ts +27 -0
  133. package/src/server/request-path.ts +73 -0
  134. package/src/server/request-scope.ts +22 -0
  135. package/src/server/route-cache.ts +423 -0
  136. package/src/server/route-table.ts +410 -0
  137. package/src/server/router.ts +261 -0
  138. package/src/server/routing.ts +472 -0
  139. package/src/server/security.ts +499 -0
  140. package/src/server/serve-handlers.ts +83 -0
  141. package/src/server/served-file.ts +128 -0
  142. package/src/server/standard-schema.ts +87 -0
  143. package/src/server/start.ts +143 -0
  144. package/src/server/static-dir.ts +220 -0
  145. package/src/server/stream.ts +211 -0
  146. package/src/ssr/context.ts +383 -0
  147. package/src/ssr/index.ts +596 -0
  148. package/src/ssr/navigation.ts +96 -0
  149. package/src/ssr/region.ts +183 -0
  150. package/src/style.ts +33 -0
  151. package/src/test/browser.ts +192 -0
  152. package/src/test/index.ts +191 -0
  153. package/src/ts-plugin/diagnostics.ts +378 -0
  154. package/src/ts-plugin/fixes.ts +364 -0
  155. package/src/ts-plugin/index.ts +194 -0
  156. package/src/unrenderable.ts +35 -0
  157. package/templates/_shared/AGENTS.md +10 -0
  158. package/templates/_shared/CLAUDE.md +1 -0
  159. package/templates/_shared/gitignore +3 -0
  160. package/templates/_shared/mcp.json +11 -0
  161. package/templates/_shared/public/robots.txt +2 -0
  162. package/templates/_shared/src/routes/legal.tsx +13 -0
  163. package/templates/_shared/tsconfig.json +25 -0
  164. package/templates/app/.env.example +4 -0
  165. package/templates/app/package.json +21 -0
  166. package/templates/app/prunelle.config.ts +11 -0
  167. package/templates/app/src/auth.ts +14 -0
  168. package/templates/app/src/routes/_layout.tsx +32 -0
  169. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  171. package/templates/app/src/routes/index.tsx +15 -0
  172. package/templates/app/src/routes/login.tsx +34 -0
  173. package/templates/app/src/styles/app.css +7 -0
  174. package/templates/app/tests/app.test.ts +32 -0
  175. package/templates/blog/content/posts/welcome.md +9 -0
  176. package/templates/blog/package.json +22 -0
  177. package/templates/blog/prunelle.config.ts +23 -0
  178. package/templates/blog/src/posts.ts +26 -0
  179. package/templates/blog/src/routes/_layout.tsx +20 -0
  180. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  181. package/templates/blog/src/routes/index.tsx +33 -0
  182. package/templates/blog/src/styles/app.css +10 -0
  183. package/templates/fullstack/package.json +19 -0
  184. package/templates/fullstack/prunelle.config.ts +6 -0
  185. package/templates/fullstack/src/actions/greet.ts +19 -0
  186. package/templates/fullstack/src/components/Counter.tsx +10 -0
  187. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  188. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  189. package/templates/fullstack/src/routes/api/health.ts +5 -0
  190. package/templates/fullstack/src/routes/index.tsx +13 -0
  191. package/templates/fullstack/src/styles/app.css +29 -0
  192. package/templates/fullstack/tests/app.test.ts +37 -0
  193. package/templates/minimal/package.json +19 -0
  194. package/templates/minimal/prunelle.config.ts +6 -0
  195. package/templates/minimal/src/components/Counter.tsx +10 -0
  196. package/templates/minimal/src/routes/_layout.tsx +14 -0
  197. package/templates/minimal/src/routes/index.tsx +11 -0
  198. package/templates/minimal/src/styles/app.css +22 -0
  199. package/ts-plugin.cjs +4277 -0
  200. package/README.md +0 -3
package/src/context.ts ADDED
@@ -0,0 +1,165 @@
1
+ // Universal component context (createContext / useContext) and hydration-safe useId().
2
+ // Browser-pure: zero Node imports. SSR wires its per-request AsyncLocalStorage bridge via registerServerContextBridge().
3
+
4
+ import type { PrunelleChild } from './jsx-runtime'
5
+ import type { IdScope, Owner } from './reactivity/index'
6
+ import { createOwner, getOwner, runWithOwner } from './reactivity/index'
7
+
8
+ export interface RegionProps {
9
+ name: string
10
+ /** The element tag, `div` by default. */
11
+ as?: string
12
+ children?: PrunelleChild
13
+ [attribute: string]: unknown
14
+ }
15
+
16
+ export interface ConsentGateProps {
17
+ /** Consent category required to render `children` (e.g. `'analytics'`, `'media'`). */
18
+ category: string
19
+ /** Rendered when consent for `category` has not been granted. */
20
+ fallback?: PrunelleChild
21
+ children?: PrunelleChild
22
+ }
23
+
24
+ export interface CatchProps {
25
+ /** Rendered in place of `children` when they throw; a function gets the error and a `retry` that renders the children again (a no-op on the server). */
26
+ fallback?: PrunelleChild | ((error: unknown, retry: () => void) => PrunelleChild)
27
+ children?: PrunelleChild
28
+ }
29
+
30
+ export interface ServerContextBridge {
31
+ region(props: RegionProps): PrunelleChild
32
+ consentGate(props: ConsentGateProps): PrunelleChild
33
+ getContext(key: symbol): { found: true, value: unknown } | undefined
34
+ runWithContext<T>(key: symbol, value: unknown, fn: () => T): T
35
+ nextId(): string | undefined
36
+ head(props: { children?: PrunelleChild }): PrunelleChild
37
+ suspense(props: { fallback?: PrunelleChild, error?: PrunelleChild | ((error: unknown) => PrunelleChild), children?: PrunelleChild | Promise<PrunelleChild> }): PrunelleChild
38
+ catch(props: CatchProps): PrunelleChild | Promise<PrunelleChild>
39
+ }
40
+
41
+ const BRIDGE_KEY = Symbol.for('pru.server.context.bridge')
42
+
43
+ function getServerBridge(): ServerContextBridge | undefined {
44
+ return (globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY]
45
+ }
46
+
47
+ /** Internal: registered by prunelle's SSR runtime on the server so `Head`, `Suspense`, `useContext`, and `useId` stay request-scoped without pulling `node:async_hooks` into client bundles. */
48
+ export function registerServerContextBridge(bridge: ServerContextBridge): void {
49
+ ;(globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY] = bridge
50
+ }
51
+
52
+ /** Collects document `<head>` tags during SSR; no-op in the browser. */
53
+ export function Head(props: { children?: PrunelleChild }): PrunelleChild {
54
+ const bridge = getServerBridge()
55
+ return bridge !== undefined ? bridge.head(props) : null
56
+ }
57
+
58
+ /** Streaming SSR boundary: flushes `fallback` immediately and streams resolved async children. */
59
+ export function Suspense(props: { fallback?: PrunelleChild, error?: PrunelleChild | ((error: unknown) => PrunelleChild), children?: PrunelleChild | Promise<PrunelleChild> }): PrunelleChild {
60
+ const bridge = getServerBridge()
61
+ if (bridge !== undefined)
62
+ return bridge.suspense(props)
63
+ return props.children instanceof Promise ? (props.fallback ?? null) : (props.children ?? null)
64
+ }
65
+
66
+ /** Renders `fallback` in place of `children` when they throw, on the server and in an island; the app's `onError` hook still gets the error. */
67
+ export function Catch(props: CatchProps): PrunelleChild | Promise<PrunelleChild> {
68
+ const bridge = getOwner() === undefined ? getServerBridge() : undefined
69
+ if (bridge !== undefined)
70
+ return bridge.catch(props)
71
+ throw new Error('prunelle: Catch was called as a function in the browser: write it as <Catch fallback={...}>...</Catch>, which the compiler turns into the browser boundary.')
72
+ }
73
+
74
+ /** A part of the page that a link or form with `data-pru-target` swaps alone: a request for it renders only its children. Server-only, like `Head`. */
75
+ export function Region(props: RegionProps): PrunelleChild {
76
+ const bridge = getServerBridge()
77
+ return bridge !== undefined ? bridge.region(props) : null
78
+ }
79
+
80
+ /** Renders `children` on the server only when consent for `category` has been granted; otherwise renders `fallback`. Server-only, 0 KB browser JS. */
81
+ export function ConsentGate(props: ConsentGateProps): PrunelleChild {
82
+ const bridge = getServerBridge()
83
+ return bridge !== undefined ? bridge.consentGate(props) : (props.fallback ?? null)
84
+ }
85
+
86
+ export interface Context<T> {
87
+ readonly id: symbol
88
+ readonly defaultValue: T
89
+ Provider: (props: { value: T, children?: PrunelleChild | (() => PrunelleChild) }) => PrunelleChild
90
+ }
91
+
92
+ function findOwnerContext(owner: Owner | undefined, key: symbol): { found: true, value: unknown } | undefined {
93
+ for (let o = owner; o !== undefined; o = o.o) {
94
+ if (o.cx !== undefined && o.cx.has(key))
95
+ return { found: true, value: o.cx.get(key) }
96
+ }
97
+ return undefined
98
+ }
99
+
100
+ function findOwnerIdScope(owner: Owner | undefined): IdScope | undefined {
101
+ for (let o = owner; o !== undefined; o = o.o) {
102
+ if (o.id !== undefined)
103
+ return o.id
104
+ }
105
+ return undefined
106
+ }
107
+
108
+ /** Run `fn` with `ctx` bound to `value` on both server (SSR) and browser (reactive owner tree). */
109
+ export function provideContext<T, R>(ctx: Context<T>, value: T, fn: () => R): R {
110
+ const owner = getOwner()
111
+ if (owner !== undefined) {
112
+ const scope = createOwner(owner)
113
+ ;(scope.cx ??= new Map()).set(ctx.id, value)
114
+ return runWithOwner(scope, fn)
115
+ }
116
+ const bridge = getServerBridge()
117
+ if (bridge !== undefined)
118
+ return bridge.runWithContext(ctx.id, value, fn)
119
+ return fn()
120
+ }
121
+
122
+ export function createContext<T>(defaultValue: T): Context<T> {
123
+ const id = Symbol('prunelle.context')
124
+ const ctx: Context<T> = {
125
+ id,
126
+ defaultValue,
127
+ Provider(props) {
128
+ return provideContext(ctx, props.value, () => {
129
+ const c = props.children
130
+ return typeof c === 'function' ? (c as () => PrunelleChild)() : c
131
+ })
132
+ },
133
+ }
134
+ return ctx
135
+ }
136
+
137
+ export function useContext<T>(ctx: Context<T>): T {
138
+ const owner = getOwner()
139
+ if (owner !== undefined) {
140
+ const hit = findOwnerContext(owner, ctx.id)
141
+ if (hit !== undefined)
142
+ return hit.value as T
143
+ }
144
+ const bridge = getServerBridge()
145
+ if (bridge !== undefined) {
146
+ const hit = bridge.getContext(ctx.id)
147
+ if (hit !== undefined)
148
+ return hit.value as T
149
+ }
150
+ return ctx.defaultValue
151
+ }
152
+
153
+ let fallbackIdSeq = 0
154
+
155
+ /** Generates a deterministic, hydration-safe unique ID scoped to the current island or SSR request. */
156
+ export function useId(prefix = 'k'): string {
157
+ const scope = findOwnerIdScope(getOwner())
158
+ if (scope !== undefined)
159
+ return `${prefix}-${scope.p}${scope.n++}`
160
+ const bridge = getServerBridge()
161
+ const serverId = bridge?.nextId()
162
+ if (serverId !== undefined)
163
+ return `${prefix}-${serverId}`
164
+ return `${prefix}-g${fallbackIdSeq++}`
165
+ }
@@ -0,0 +1,30 @@
1
+ // prunelle dev's app process: the build, the watchers and the app, on a Unix socket behind the `prunelle dev` process that keeps the port.
2
+
3
+ import type { DevChildMessage, DevChildOptions } from './protocol'
4
+ import { devServer } from './index'
5
+ import { DEV_CHILD_ENV } from './protocol'
6
+
7
+ if (import.meta.main) {
8
+ const options = JSON.parse(process.env[DEV_CHILD_ENV] ?? '{}') as DevChildOptions
9
+ const send = (message: DevChildMessage): void => {
10
+ process.send?.(message)
11
+ }
12
+ const srv = await devServer({
13
+ ...options,
14
+ broadcast: payload => send({ t: 'event', payload }),
15
+ recycle: reason => send({ t: 'recycle', reason }),
16
+ })
17
+ let stopping: Promise<void> | undefined
18
+ const stop = (): void => {
19
+ stopping ??= srv.stop().finally(() => process.exit(0))
20
+ }
21
+ process.on('message', (message: { t?: string }) => {
22
+ if (message.t === 'stop')
23
+ stop()
24
+ })
25
+ // The parent died without asking, or Ctrl-C reached the whole process group.
26
+ process.on('disconnect', stop)
27
+ process.on('SIGINT', stop)
28
+ process.on('SIGTERM', stop)
29
+ send({ t: 'ready', assetPrefix: srv.assetPrefix })
30
+ }
@@ -0,0 +1,151 @@
1
+ // Persists the last dev build error, child crash, and recent runtime errors under `.prunelle-dev/last-errors.json`
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 { existsSync, mkdirSync, readFileSync, renameSync, 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
+
26
+ function errorLogPath(root: string): string {
27
+ return join(resolve(root), '.prunelle-dev', 'last-errors.json')
28
+ }
29
+
30
+ function isDevErrorEntry(value: unknown): value is DevErrorEntry {
31
+ if (typeof value !== 'object' || value === null)
32
+ return false
33
+ const rec = value as Record<string, unknown>
34
+ return (rec.kind === 'build' || rec.kind === 'runtime' || rec.kind === 'crash')
35
+ && typeof rec.timestamp === 'string'
36
+ && typeof rec.message === 'string'
37
+ }
38
+
39
+ /** Reads `.prunelle-dev/last-errors.json` safely, returning `undefined` when missing or unreadable. */
40
+ export function readDevErrorLog(root: string): DevErrorLog | undefined {
41
+ const file = errorLogPath(root)
42
+ if (!existsSync(file))
43
+ return undefined
44
+ try {
45
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown
46
+ if (typeof parsed !== 'object' || parsed === null)
47
+ return undefined
48
+ const rec = parsed as Record<string, unknown>
49
+ const updatedAt = typeof rec.updatedAt === 'string' ? rec.updatedAt : new Date(0).toISOString()
50
+ const buildError = typeof rec.buildError === 'string' && rec.buildError.length > 0 ? rec.buildError : undefined
51
+ const crashError = typeof rec.crashError === 'string' && rec.crashError.length > 0 ? rec.crashError : undefined
52
+ const runtimeErrors = Array.isArray(rec.runtimeErrors) ? rec.runtimeErrors.filter(isDevErrorEntry) : []
53
+ return {
54
+ updatedAt,
55
+ ...(buildError !== undefined ? { buildError } : {}),
56
+ ...(crashError !== undefined ? { crashError } : {}),
57
+ runtimeErrors,
58
+ }
59
+ }
60
+ catch {
61
+ return undefined
62
+ }
63
+ }
64
+
65
+ function writeDevErrorLog(root: string, log: DevErrorLog): void {
66
+ const file = errorLogPath(root)
67
+ const payload = JSON.stringify(log, null, 2)
68
+ try {
69
+ mkdirSync(dirname(file), { recursive: true })
70
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
71
+ writeFileSync(tmp, payload, 'utf8')
72
+ renameSync(tmp, file)
73
+ }
74
+ catch {
75
+ try {
76
+ mkdirSync(dirname(file), { recursive: true })
77
+ writeFileSync(file, payload, 'utf8')
78
+ }
79
+ catch {
80
+ return
81
+ }
82
+ }
83
+ }
84
+
85
+ function loadOrCreateLog(root: string, now: string): DevErrorLog {
86
+ const existing = readDevErrorLog(root)
87
+ if (existing !== undefined)
88
+ return { ...existing, updatedAt: now, runtimeErrors: [...existing.runtimeErrors] }
89
+ return { updatedAt: now, runtimeErrors: [] }
90
+ }
91
+
92
+ /** Records or clears the active dev build error (passing `undefined` clears it after a successful build). */
93
+ export function recordDevBuildError(root: string, message: string | undefined): void {
94
+ const now = new Date().toISOString()
95
+ const log = loadOrCreateLog(root, now)
96
+ if (message !== undefined && message.length > 0)
97
+ log.buildError = message
98
+ else
99
+ delete log.buildError
100
+ writeDevErrorLog(root, log)
101
+ }
102
+
103
+ /** Records or clears the active dev child crash message (passing `undefined` clears it once the child is ready). */
104
+ export function recordDevCrashError(root: string, message: string | undefined): void {
105
+ const now = new Date().toISOString()
106
+ const log = loadOrCreateLog(root, now)
107
+ if (message !== undefined && message.length > 0)
108
+ log.crashError = message
109
+ else
110
+ delete log.crashError
111
+ writeDevErrorLog(root, log)
112
+ }
113
+
114
+ /** Appends a runtime error to `.prunelle-dev/last-errors.json`, keeping the last 20 entries. */
115
+ export function recordDevRuntimeError(root: string, entry: Omit<DevErrorEntry, 'kind' | 'timestamp'>): void {
116
+ const now = new Date().toISOString()
117
+ const log = loadOrCreateLog(root, now)
118
+ log.runtimeErrors.push({
119
+ kind: 'runtime',
120
+ timestamp: now,
121
+ message: entry.message,
122
+ ...(entry.source !== undefined ? { source: entry.source } : {}),
123
+ ...(entry.method !== undefined ? { method: entry.method } : {}),
124
+ ...(entry.path !== undefined ? { path: entry.path } : {}),
125
+ })
126
+ if (log.runtimeErrors.length > MAX_RUNTIME_ERRORS)
127
+ log.runtimeErrors = log.runtimeErrors.slice(-MAX_RUNTIME_ERRORS)
128
+ writeDevErrorLog(root, log)
129
+ }
130
+
131
+ function safePathname(rawUrl: string): string {
132
+ try {
133
+ return new URL(rawUrl).pathname
134
+ }
135
+ catch {
136
+ return rawUrl
137
+ }
138
+ }
139
+
140
+ /** Builds an `errorSink` callback for `devServer` that records unhandled runtime errors into `.prunelle-dev/last-errors.json`. */
141
+ export function createDevRuntimeErrorSink(root: string): (info: ServerErrorInfo) => void {
142
+ return (info) => {
143
+ const message = info.error instanceof Error ? info.error.stack ?? info.error.message : String(info.error)
144
+ recordDevRuntimeError(root, {
145
+ message,
146
+ source: info.source,
147
+ method: info.request.method,
148
+ path: safePathname(info.request.url),
149
+ })
150
+ }
151
+ }
@@ -0,0 +1,258 @@
1
+ // prunelle dev: incremental cached rebuilds, serialized rebuild queue, CSS hot-swap, streaming reload injection,
2
+ // SSE error push, and live config reload.
3
+
4
+ import type { Server } from 'bun'
5
+ import type { BuildCacheStats } from '../build/graph'
6
+ import type { PrunelleApp } from '../server/index'
7
+ import type { RecycleReason } from './protocol'
8
+ import type { PendingBuild } from './queue'
9
+ import { existsSync, readdirSync, rmSync } from 'node:fs'
10
+ import { join, resolve } from 'node:path'
11
+ import { clearBuildCache } from '../build/graph'
12
+ import { build, createBuildCache } from '../build/index'
13
+ import { loadConfig, resolveServerConfig } from '../plugins/index'
14
+ import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
15
+ import { createServer } from '../server/index'
16
+ import { createDevRuntimeErrorSink, recordDevBuildError } from './error-log'
17
+ import { createModuleStore } from './modules'
18
+ import { handleOpenEditorRequest } from './open-editor'
19
+ import { DEV_CLIENT_IP_HEADER } from './protocol'
20
+ import { createRebuildQueue } from './queue'
21
+ import { buildErrorResponse, createReloadHub, makeDevReloadAssets, withReloadScript } from './reload'
22
+ import { createDevWatchers } from './watchers'
23
+
24
+
25
+ export interface DevServerOptions {
26
+ root: string
27
+ port?: number | undefined
28
+ hostname?: string | undefined
29
+ routesDir?: string | undefined
30
+ maxRequestBodySize?: number | undefined
31
+ /** Listens on this Unix socket instead of a port, behind a parent that keeps the port and sets {@link DEV_CLIENT_IP_HEADER}. */
32
+ unix?: string | undefined
33
+ /** Receives each reload event instead of a stream this server serves. */
34
+ broadcast?: ((payload: string) => void) | undefined
35
+ /** Called instead of reloading `prunelle.config.ts` in place, on an edit to it or to a file it imports, and once the RSS passes `maxRssMb` after a build. */
36
+ recycle?: ((reason: RecycleReason) => void) | undefined
37
+ maxRssMb?: number | undefined
38
+ }
39
+
40
+ const errorText = (err: unknown): string => err instanceof Error ? err.stack ?? err.message : String(err)
41
+
42
+ /** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.json` intact across child recycles. */
43
+ function cleanDevArtifacts(devRoot: string): void {
44
+ if (!existsSync(devRoot))
45
+ return
46
+ for (const entry of readdirSync(devRoot)) {
47
+ if (entry !== 'last-errors.json')
48
+ rmSync(join(devRoot, entry), { recursive: true, force: true })
49
+ }
50
+ }
51
+
52
+ function startDevHttpServer(
53
+ options: DevServerOptions,
54
+ maxRequestBodySize: number,
55
+ configPort: number | undefined,
56
+ onFetch: (request: Request, srv: Server<undefined>) => Promise<Response>,
57
+ ): { server: Server<undefined>, url: string } {
58
+ const hostname = options.hostname ?? '127.0.0.1'
59
+ const serveOptions = { maxRequestBodySize, fetch: onFetch }
60
+ const server = options.unix !== undefined
61
+ ? Bun.serve({ ...serveOptions, unix: options.unix })
62
+ : Bun.serve({ ...serveOptions, port: options.port ?? configPort ?? 3000, hostname, idleTimeout: 30 })
63
+ // `0.0.0.0` is printed as the loopback address a browser on this machine opens.
64
+ const url = options.unix !== undefined ? `unix:${options.unix}` : `http://${hostname === '0.0.0.0' ? '127.0.0.1' : hostname}:${server.port}`
65
+ if (options.unix === undefined)
66
+ console.log(`[prunelle dev] listening on ${url}`)
67
+ return { server, url }
68
+ }
69
+
70
+ async function handleAppFetch(
71
+ request: Request,
72
+ srv: Server<undefined>,
73
+ state: {
74
+ root: string
75
+ unix: string | undefined
76
+ hub: ReturnType<typeof createReloadHub> | undefined
77
+ reloadAssets: ReturnType<typeof makeDevReloadAssets>
78
+ lastError: string | undefined
79
+ app: PrunelleApp | undefined
80
+ },
81
+ ): Promise<Response> {
82
+ const { pathname } = new URL(request.url)
83
+ if (state.hub !== undefined && pathname === state.reloadAssets.eventsPath) {
84
+ srv.timeout(request, 0)
85
+ return state.hub.events(request)
86
+ }
87
+ if (pathname === state.reloadAssets.openEditorPath)
88
+ return handleOpenEditorRequest(request, state.root)
89
+ if (state.lastError !== undefined)
90
+ return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
91
+
92
+ const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
93
+ const res = await state.app!.handle(request, remoteIp)
94
+ const ct = res.headers.get('content-type') ?? ''
95
+ const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
96
+ if (ct.includes('text/event-stream') || isStreamedHtml)
97
+ srv.timeout(request, 0)
98
+ return withReloadScript(request, res, state.reloadAssets)
99
+ }
100
+
101
+ export async function devServer(options: DevServerOptions): Promise<{
102
+ url: string
103
+ assetPrefix: string
104
+ stop: () => Promise<void>
105
+ rebuild: () => Promise<void>
106
+ stats: () => BuildCacheStats
107
+ }> {
108
+ const root = resolve(options.root)
109
+ const devRoot = join(root, '.prunelle-dev')
110
+ const initialCfg = await loadConfig(root, { dev: true })
111
+ // Clean stale build folders left behind by a previously killed or recycled dev process, preserving last-errors.json.
112
+ cleanDevArtifacts(devRoot)
113
+ let activeCfg = initialCfg
114
+ let activeAssetPrefix = (initialCfg.assetPrefix ?? '/_pru').replace(/\/$/, '')
115
+ let reloadAssets = makeDevReloadAssets(activeAssetPrefix)
116
+ const buildCache = createBuildCache()
117
+ const modules = createModuleStore(join(devRoot, 'server'))
118
+ const hub = options.broadcast === undefined ? createReloadHub() : undefined
119
+ const broadcast = options.broadcast ?? hub!.broadcast
120
+ let recycled = false
121
+ const recycle = options.recycle === undefined
122
+ ? undefined
123
+ : (reason: RecycleReason) => {
124
+ recycled = true
125
+ options.recycle!(reason)
126
+ }
127
+ const queue = createRebuildQueue(runSingleBuild)
128
+ const watchers = createDevWatchers({
129
+ root,
130
+ devRoot,
131
+ srcDir: resolve(root, 'src'),
132
+ routesDir: options.routesDir,
133
+ schedule: kind => kind === 'config' && recycle !== undefined ? recycle('config') : queue.schedule(kind),
134
+ })
135
+ const serverOptions = { root, dev: true, compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
136
+
137
+ let buildNum = 0
138
+ let current: { app: PrunelleApp, outDir: string } | undefined
139
+ let lastError: string | undefined
140
+ let stopped = false
141
+
142
+ async function swapApp(outDir: string): Promise<void> {
143
+ const nextApp = await createServer({ ...serverOptions, outDir, importModule: modules.importFrom(join(root, outDir, 'server')) })
144
+ if (stopped) {
145
+ await nextApp.dispose?.()
146
+ return
147
+ }
148
+ const prev = current?.app
149
+ current = { app: nextApp, outDir }
150
+ await prev?.dispose?.()
151
+ }
152
+
153
+ async function runSingleBuild({ cssOnly, publicOnly, resetCache, reloadAll }: PendingBuild): Promise<void> {
154
+ if (stopped)
155
+ return
156
+ const hadError = lastError !== undefined
157
+ const hadApp = current !== undefined
158
+ const n = buildNum + 1
159
+ const outDir = `.prunelle-dev/b${n}`
160
+ const t0 = performance.now()
161
+ try {
162
+ // An edited `public/` file only needs the app's file table, and its ETag, built again.
163
+ if (publicOnly && current !== undefined && !hadError) {
164
+ await swapApp(current.outDir)
165
+ broadcast('reload')
166
+ return
167
+ }
168
+ buildNum = n
169
+ if (resetCache) {
170
+ clearBuildCache(buildCache)
171
+ activeCfg = await loadConfig(root, { fresh: true, dev: true })
172
+ activeAssetPrefix = (activeCfg.assetPrefix ?? '/_pru').replace(/\/$/, '')
173
+ reloadAssets = makeDevReloadAssets(activeAssetPrefix)
174
+ watchers.syncStatic(activeCfg)
175
+ watchers.refreshPlugins(activeCfg, activeAssetPrefix)
176
+ }
177
+ if (reloadAll)
178
+ modules.reloadAll()
179
+ const manifest = await build({ root, routesDir: options.routesDir, outDir, minify: false, prerender: false, copyPublic: false, dev: true, cache: buildCache })
180
+ if (!stopped) {
181
+ modules.sync(join(root, outDir, 'server'))
182
+ await swapApp(outDir)
183
+ }
184
+ if (stopped) {
185
+ rmSync(join(root, outDir), { recursive: true, force: true })
186
+ return
187
+ }
188
+ lastError = undefined
189
+ recordDevBuildError(root, undefined)
190
+ watchers.syncBuild(buildCache.watchedFiles, manifest.publicFiles)
191
+ if (n > 2)
192
+ rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
193
+ console.log(`[prunelle dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
194
+ broadcast(cssOnly && hadApp && !hadError && manifest.styles.length > 0 ? `css:${JSON.stringify(manifest.styles)}` : 'reload')
195
+ if (n > 1 && recycle !== undefined && options.maxRssMb !== undefined && process.memoryUsage().rss > options.maxRssMb * 1024 * 1024)
196
+ recycle('memory')
197
+ }
198
+ catch (err) {
199
+ if (stopped)
200
+ return
201
+ lastError = errorText(err)
202
+ recordDevBuildError(root, lastError)
203
+ console.error(`[prunelle dev] build error:\n${lastError}`)
204
+ // Push reload over SSE so open browser tabs immediately display the error overlay
205
+ broadcast('reload')
206
+ }
207
+ }
208
+
209
+ await queue.now()
210
+
211
+ watchers.syncStatic(initialCfg)
212
+ watchers.watchRoot(() => activeCfg, recycle !== undefined)
213
+ // Plugin-declared extra paths (e.g. content/ or messages/ directories); refreshed on prunelle.config.ts edits.
214
+ try {
215
+ watchers.refreshPlugins(initialCfg, activeAssetPrefix)
216
+ }
217
+ catch (err) {
218
+ console.warn(`[prunelle dev] could not attach plugin watchers: ${err instanceof Error ? err.message : String(err)}`)
219
+ }
220
+
221
+ const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
222
+ const { server, url } = startDevHttpServer(
223
+ options,
224
+ runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
225
+ initialCfg.port,
226
+ (request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, hub, reloadAssets, lastError, app: current?.app }),
227
+ )
228
+ let stopPromise: Promise<void> | undefined
229
+
230
+ return {
231
+ url,
232
+ assetPrefix: activeAssetPrefix,
233
+ rebuild: () => queue.now(),
234
+ stats: () => ({ ...buildCache.stats }),
235
+ stop() {
236
+ if (stopPromise !== undefined)
237
+ return stopPromise
238
+ stopped = true
239
+ hub?.close()
240
+ watchers.close()
241
+ server.stop(true)
242
+ stopPromise = (async () => {
243
+ await queue.stop()
244
+ try {
245
+ await current?.app.dispose?.()
246
+ }
247
+ catch (err) {
248
+ console.warn(`[prunelle dev] the app failed to dispose: ${errorText(err)}`)
249
+ }
250
+ if (recycled)
251
+ cleanDevArtifacts(devRoot)
252
+ else
253
+ rmSync(devRoot, { recursive: true, force: true })
254
+ })()
255
+ return stopPromise
256
+ },
257
+ }
258
+ }
@@ -0,0 +1,68 @@
1
+ // prunelle dev's module store: each build's server files, copied so an unchanged chunk keeps its loaded instance.
2
+
3
+ import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
4
+ import { dirname, join, relative } from 'node:path'
5
+
6
+ // Bun never unloads a module, so each build's server files are copied into a generation store.
7
+ // Only `_entry.js` is imported, with its hash: the code lives in content-named chunks, so an unchanged chunk keeps its loaded instance across saves.
8
+ // A failed import starts a new generation, since Bun keeps a module that failed to evaluate.
9
+ export function createModuleStore(storeRoot: string) {
10
+ const hashes = new Map<string, string>()
11
+ let generation = 0
12
+ let stale = false
13
+ const generationDir = (g: number): string => join(storeRoot, `g${g}`)
14
+ return {
15
+ reloadAll(): void {
16
+ stale = true
17
+ },
18
+ sync(serverDir: string): void {
19
+ const nextFiles = new Map<string, { bytes: Buffer, hash: string }>()
20
+ for (const entry of readdirSync(serverDir, { recursive: true, withFileTypes: true })) {
21
+ if (!entry.isFile())
22
+ continue
23
+ const from = join(entry.parentPath, entry.name)
24
+ const rel = relative(serverDir, from).replaceAll('\\', '/')
25
+ const bytes = readFileSync(from)
26
+ const hash = Bun.hash(bytes).toString(36)
27
+ nextFiles.set(rel, { bytes, hash })
28
+ }
29
+
30
+ if (stale) {
31
+ stale = false
32
+ hashes.clear()
33
+ generation++
34
+ // The previous generation stays for requests the old app is still serving.
35
+ rmSync(generationDir(generation - 2), { recursive: true, force: true })
36
+ }
37
+ const storeDir = generationDir(generation)
38
+ for (const [rel, { bytes, hash }] of nextFiles) {
39
+ if (hashes.get(rel) === hash)
40
+ continue
41
+ const to = join(storeDir, rel)
42
+ mkdirSync(dirname(to), { recursive: true })
43
+ writeFileSync(to, bytes)
44
+ hashes.set(rel, hash)
45
+ }
46
+ // Prune removed chunk files from current generation to avoid unbounded disk/map growth.
47
+ for (const rel of [...hashes.keys()]) {
48
+ if (!nextFiles.has(rel)) {
49
+ hashes.delete(rel)
50
+ rmSync(join(storeDir, rel), { force: true })
51
+ }
52
+ }
53
+ },
54
+ importFrom(serverDir: string) {
55
+ const storeDir = generationDir(generation)
56
+ return async (path: string): Promise<Record<string, unknown>> => {
57
+ const rel = relative(serverDir, path).replaceAll('\\', '/')
58
+ try {
59
+ return await import(`${join(storeDir, rel)}?v=${hashes.get(rel)}`)
60
+ }
61
+ catch (err) {
62
+ stale = true
63
+ throw err
64
+ }
65
+ }
66
+ },
67
+ }
68
+ }