prunelle 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +148 -0
- package/package.json +53 -4
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +613 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +169 -0
- package/src/build/client-prune.ts +118 -0
- package/src/build/compile.ts +128 -0
- package/src/build/files.ts +156 -0
- package/src/build/first-load.ts +164 -0
- package/src/build/graph.ts +247 -0
- package/src/build/index.ts +614 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +281 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +220 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +150 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +247 -0
- package/src/build/resolve.ts +50 -0
- package/src/build/routes.ts +338 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +163 -0
- package/src/build/status-pages.ts +127 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +367 -0
- package/src/cli/commands.ts +265 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +335 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +354 -0
- package/src/compiler/analyze.ts +618 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +127 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +497 -0
- package/src/compiler/data-keys.ts +295 -0
- package/src/compiler/dom-attrs.ts +379 -0
- package/src/compiler/dom.ts +566 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +408 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +499 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props.ts +460 -0
- package/src/compiler/scope.ts +568 -0
- package/src/compiler/server-only.ts +326 -0
- package/src/compiler/shared.ts +369 -0
- package/src/compiler/signal-reads.ts +242 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +56 -0
- package/src/compiler/ssr.ts +491 -0
- package/src/context.ts +165 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/index.ts +208 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/protocol.ts +21 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +157 -0
- package/src/dev/supervisor.ts +187 -0
- package/src/dev/watchers.ts +215 -0
- package/src/dom/action.ts +164 -0
- package/src/dom/attrs.ts +72 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +562 -0
- package/src/dom/index.ts +289 -0
- package/src/dom/island.ts +284 -0
- package/src/dom/loop.ts +450 -0
- package/src/dom/revive.ts +36 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +86 -0
- package/src/plugins/context.ts +66 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +70 -0
- package/src/plugins/order.ts +111 -0
- package/src/plugins/public.ts +12 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +35 -0
- package/src/plugins/types.ts +242 -0
- package/src/reactivity/graph.ts +249 -0
- package/src/reactivity/index.ts +533 -0
- package/src/reactivity/selector.ts +51 -0
- package/src/reactivity/store.ts +208 -0
- package/src/server/action-protect.ts +186 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +498 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +136 -0
- package/src/server/compress.ts +560 -0
- package/src/server/consent.ts +253 -0
- package/src/server/cookies.ts +139 -0
- package/src/server/document.ts +271 -0
- package/src/server/env.ts +33 -0
- package/src/server/errors.ts +382 -0
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +508 -0
- package/src/server/index.ts +687 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +118 -0
- package/src/server/page.ts +107 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +256 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +19 -0
- package/src/server/rate-limit.ts +133 -0
- package/src/server/region.ts +96 -0
- package/src/server/request-body.ts +27 -0
- package/src/server/request-path.ts +73 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/route-table.ts +82 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +377 -0
- package/src/server/security.ts +472 -0
- package/src/server/serve-handlers.ts +83 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +87 -0
- package/src/server/start.ts +99 -0
- package/src/server/static-dir.ts +167 -0
- package/src/server/stream.ts +192 -0
- package/src/ssr/context.ts +350 -0
- package/src/ssr/index.ts +596 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +171 -0
- package/src/style.ts +33 -0
- package/src/test/browser.ts +192 -0
- package/src/test/index.ts +191 -0
- package/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +3 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +13 -0
- package/templates/_shared/tsconfig.json +20 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +21 -0
- package/templates/app/prunelle.config.ts +11 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/app/tests/app.test.ts +32 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/package.json +22 -0
- package/templates/blog/prunelle.config.ts +23 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +33 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/package.json +19 -0
- package/templates/fullstack/prunelle.config.ts +6 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +27 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/fullstack/tests/app.test.ts +37 -0
- package/templates/minimal/package.json +19 -0
- package/templates/minimal/prunelle.config.ts +6 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
- package/README.md +0 -3
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// What prunelle dev adds to the app's answers: the reload script and its event stream, the build-error overlay, and the script's injection into streamed HTML.
|
|
2
|
+
|
|
3
|
+
import { wantsJson } from '../server/http'
|
|
4
|
+
import { withCspHashes } from '../server/security'
|
|
5
|
+
import { REGION_HEADER } from '../server/region'
|
|
6
|
+
import { cspSha256 } from '../ssr/navigation'
|
|
7
|
+
|
|
8
|
+
export function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string } {
|
|
9
|
+
const prefix = assetPrefix.replace(/\/$/, '')
|
|
10
|
+
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 hash = cspSha256(js)
|
|
13
|
+
return { script: `<script>${js}</script>`, hash, eventsPath }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function renderErrorOverlay(errText: string, reloadScript: string): string {
|
|
17
|
+
const escaped = errText
|
|
18
|
+
.replaceAll('&', '&')
|
|
19
|
+
.replaceAll('<', '<')
|
|
20
|
+
.replaceAll('>', '>')
|
|
21
|
+
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Prunelle Dev Error</title><style>body{margin:0;min-height:100vh;background:#0d1117;color:#e6edf3;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;display:grid;place-items:center;padding:2rem}main{max-width:56rem;width:100%;background:#161b22;border:1px solid #f85149;border-radius:10px;padding:1.5rem 2rem;box-shadow:0 16px 48px rgba(0,0,0,.45)}h1{margin:0 0 1rem;color:#ff7b72;font-size:1.15rem}pre{margin:0;white-space:pre-wrap;word-break:break-word;line-height:1.5;font-size:.9rem;color:#ffa198}p{margin:1rem 0 0;font-size:.8rem;color:#8b949e}</style></head><body><main><h1>Prunelle Dev Build Error</h1><pre>${escaped}</pre><p>Save a fix to auto-reload.</p></main>${reloadScript}</body></html>`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function shouldInjectReload(request: Request, res: Response, ct: string): boolean {
|
|
25
|
+
return ct.includes('text/html')
|
|
26
|
+
&& request.method !== 'HEAD'
|
|
27
|
+
&& res.body !== null
|
|
28
|
+
&& !res.headers.has('content-encoding')
|
|
29
|
+
&& !request.headers.has(REGION_HEADER)
|
|
30
|
+
&& !res.headers.has(REGION_HEADER)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Injects the dev reload script into an HTML response while preserving streaming (<Suspense>).
|
|
34
|
+
export function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScript: string): ReadableStream<Uint8Array> {
|
|
35
|
+
const decoder = new TextDecoder()
|
|
36
|
+
const encoder = new TextEncoder()
|
|
37
|
+
let injected = false
|
|
38
|
+
let tail = ''
|
|
39
|
+
const KEEP = 16 // enough to span a split `</body>` tag across chunk boundaries
|
|
40
|
+
|
|
41
|
+
return body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
|
|
42
|
+
transform(chunk, controller) {
|
|
43
|
+
if (injected) {
|
|
44
|
+
controller.enqueue(chunk)
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
const text = tail + decoder.decode(chunk, { stream: true })
|
|
48
|
+
const idx = text.indexOf('</body>')
|
|
49
|
+
if (idx !== -1) {
|
|
50
|
+
injected = true
|
|
51
|
+
tail = ''
|
|
52
|
+
controller.enqueue(encoder.encode(`${text.slice(0, idx)}${reloadScript}${text.slice(idx)}`))
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
if (text.length > KEEP) {
|
|
56
|
+
const split = text.length - KEEP
|
|
57
|
+
controller.enqueue(encoder.encode(text.slice(0, split)))
|
|
58
|
+
tail = text.slice(split)
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
tail = text
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
flush(controller) {
|
|
65
|
+
const rest = tail + decoder.decode()
|
|
66
|
+
if (injected) {
|
|
67
|
+
if (rest.length > 0)
|
|
68
|
+
controller.enqueue(encoder.encode(rest))
|
|
69
|
+
return
|
|
70
|
+
}
|
|
71
|
+
const idx = rest.indexOf('</body>')
|
|
72
|
+
if (idx !== -1)
|
|
73
|
+
controller.enqueue(encoder.encode(`${rest.slice(0, idx)}${reloadScript}${rest.slice(idx)}`))
|
|
74
|
+
else
|
|
75
|
+
controller.enqueue(encoder.encode(rest + reloadScript))
|
|
76
|
+
},
|
|
77
|
+
}))
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The reload script's event stream: `controller` joins `clients` until the browser goes away. */
|
|
81
|
+
function reloadEvents(request: Request, clients: Set<ReadableStreamDefaultController<Uint8Array>>): Response {
|
|
82
|
+
let ctrl: ReadableStreamDefaultController<Uint8Array> | undefined
|
|
83
|
+
let open = true
|
|
84
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
85
|
+
start(controller) {
|
|
86
|
+
ctrl = controller
|
|
87
|
+
clients.add(controller)
|
|
88
|
+
controller.enqueue(new TextEncoder().encode(': connected\n\n'))
|
|
89
|
+
request.signal.addEventListener('abort', () => {
|
|
90
|
+
clients.delete(controller)
|
|
91
|
+
if (open) {
|
|
92
|
+
open = false
|
|
93
|
+
controller.close()
|
|
94
|
+
}
|
|
95
|
+
}, { once: true })
|
|
96
|
+
},
|
|
97
|
+
cancel() {
|
|
98
|
+
open = false
|
|
99
|
+
if (ctrl !== undefined)
|
|
100
|
+
clients.delete(ctrl)
|
|
101
|
+
},
|
|
102
|
+
})
|
|
103
|
+
return new Response(stream, {
|
|
104
|
+
headers: {
|
|
105
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
106
|
+
'cache-control': 'no-cache, no-transform',
|
|
107
|
+
'x-accel-buffering': 'no',
|
|
108
|
+
},
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The answer to every request while the build is broken: JSON or text when the client asks for it, else the overlay. */
|
|
113
|
+
export function buildErrorResponse(request: Request, error: string, reloadScript: string): Response {
|
|
114
|
+
if (wantsJson(request))
|
|
115
|
+
return Response.json({ ok: false, status: 500, error }, { status: 500 })
|
|
116
|
+
if ((request.headers.get('accept') ?? '').startsWith('text/plain'))
|
|
117
|
+
return new Response(error, { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
118
|
+
return new Response(renderErrorOverlay(error, reloadScript), {
|
|
119
|
+
status: 500,
|
|
120
|
+
headers: { 'content-type': 'text/html; charset=utf-8' },
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** An HTML answer with the reload script before `</body>` and its hash in the CSP; any other answer as it is. */
|
|
125
|
+
export function withReloadScript(request: Request, res: Response, assets: { script: string, hash: string }): Response {
|
|
126
|
+
if (!shouldInjectReload(request, res, res.headers.get('content-type') ?? ''))
|
|
127
|
+
return res
|
|
128
|
+
const headers = new Headers(res.headers)
|
|
129
|
+
headers.delete('content-length')
|
|
130
|
+
const existingCsp = headers.get('content-security-policy')
|
|
131
|
+
if (existingCsp !== null)
|
|
132
|
+
headers.set('content-security-policy', withCspHashes(existingCsp, { scriptHashes: [assets.hash] }))
|
|
133
|
+
return new Response(injectReloadStream(res.body!, assets.script), { status: res.status, headers })
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The browsers' reload streams: `broadcast` reaches each, and a ping every 15 s keeps idle ones open. */
|
|
137
|
+
export function createReloadHub() {
|
|
138
|
+
const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
|
|
139
|
+
const encoder = new TextEncoder()
|
|
140
|
+
const push = (chunk: Uint8Array): void => {
|
|
141
|
+
for (const c of clients) {
|
|
142
|
+
try {
|
|
143
|
+
c.enqueue(chunk)
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
clients.delete(c)
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const ping = encoder.encode(': ping\n\n')
|
|
151
|
+
const pinger = setInterval(() => push(ping), 15_000)
|
|
152
|
+
return {
|
|
153
|
+
events: (request: Request): Response => reloadEvents(request, clients),
|
|
154
|
+
broadcast: (payload: string): void => push(encoder.encode(`data: ${payload}\n\n`)),
|
|
155
|
+
close: (): void => clearInterval(pinger),
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// `prunelle dev`: keeps the port and the browsers' reload stream, and runs the app in a child process it replaces when prunelle.config.ts or what it imports changes, or past a memory limit.
|
|
2
|
+
|
|
3
|
+
import type { FSWatcher } from 'node:fs'
|
|
4
|
+
import type { Subprocess } from 'bun'
|
|
5
|
+
import type { DevChildMessage, DevChildOptions } from './protocol'
|
|
6
|
+
import { existsSync, mkdtempSync, rmSync, watch } from 'node:fs'
|
|
7
|
+
import { tmpdir } from 'node:os'
|
|
8
|
+
import { join, resolve } from 'node:path'
|
|
9
|
+
import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
|
|
10
|
+
import { DEV_CHILD_ENV, DEV_CLIENT_IP_HEADER } from './protocol'
|
|
11
|
+
import { buildErrorResponse, createReloadHub, makeDevReloadAssets } from './reload'
|
|
12
|
+
|
|
13
|
+
export interface DevSupervisorOptions {
|
|
14
|
+
root: string
|
|
15
|
+
port?: number | undefined
|
|
16
|
+
hostname?: string | undefined
|
|
17
|
+
routesDir?: string | undefined
|
|
18
|
+
maxRequestBodySize?: number | undefined
|
|
19
|
+
/** The app process is replaced once its RSS passes this after a rebuild. */
|
|
20
|
+
maxRssMb?: number | undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Child {
|
|
24
|
+
proc: Subprocess<'ignore', 'inherit', 'pipe'>
|
|
25
|
+
socket: string
|
|
26
|
+
stopping: boolean
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const CHILD_ENTRY = join(import.meta.dir, 'child.ts')
|
|
30
|
+
const STOP_GRACE_MS = 5000
|
|
31
|
+
const KEPT_STDERR = 8192
|
|
32
|
+
const DEFAULT_MAX_RSS_MB = 2048
|
|
33
|
+
|
|
34
|
+
export async function devSupervisor(options: DevSupervisorOptions): Promise<{ url: string, stop: () => Promise<void> }> {
|
|
35
|
+
const root = resolve(options.root)
|
|
36
|
+
const socketDir = mkdtempSync(join(tmpdir(), 'prunelle-dev-sockets-'))
|
|
37
|
+
const hub = createReloadHub()
|
|
38
|
+
let reloadAssets = makeDevReloadAssets('/_pru')
|
|
39
|
+
let spawned = 0
|
|
40
|
+
let live: Child | undefined
|
|
41
|
+
let crashed: string | undefined
|
|
42
|
+
let stopped = false
|
|
43
|
+
let saveWatchers: FSWatcher[] = []
|
|
44
|
+
// Requests wait on this while a child starts.
|
|
45
|
+
let ready: Promise<Child | undefined>
|
|
46
|
+
|
|
47
|
+
function spawnChild(): Promise<Child | undefined> {
|
|
48
|
+
if (stopped)
|
|
49
|
+
return Promise.resolve(undefined)
|
|
50
|
+
const socket = join(socketDir, `${++spawned}.sock`)
|
|
51
|
+
const childOptions: DevChildOptions = { root, routesDir: options.routesDir, unix: socket, maxRssMb: options.maxRssMb ?? DEFAULT_MAX_RSS_MB }
|
|
52
|
+
let stderrTail = ''
|
|
53
|
+
let onReady: (child: Child | undefined) => void = () => {}
|
|
54
|
+
const started = new Promise<Child | undefined>((res) => { onReady = res })
|
|
55
|
+
const proc = Bun.spawn({
|
|
56
|
+
cmd: [process.execPath, CHILD_ENTRY],
|
|
57
|
+
cwd: root,
|
|
58
|
+
env: { ...process.env, [DEV_CHILD_ENV]: JSON.stringify(childOptions) },
|
|
59
|
+
stdio: ['ignore', 'inherit', 'pipe'],
|
|
60
|
+
serialization: 'json',
|
|
61
|
+
ipc(message: DevChildMessage) {
|
|
62
|
+
if (message.t === 'event')
|
|
63
|
+
hub.broadcast(message.payload)
|
|
64
|
+
else if (message.t === 'ready') {
|
|
65
|
+
reloadAssets = makeDevReloadAssets(message.assetPrefix)
|
|
66
|
+
crashed = undefined
|
|
67
|
+
onReady(child)
|
|
68
|
+
}
|
|
69
|
+
else if (child === live && !child.stopping && !stopped) {
|
|
70
|
+
console.log(`[prunelle dev] ${message.reason === 'config' ? 'prunelle.config.ts or a file it imports changed' : `the app passed ${childOptions.maxRssMb} MB`}: starting a new app process`)
|
|
71
|
+
ready = stopChild(child).then(spawnChild)
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
})
|
|
75
|
+
const child: Child = { proc, socket, stopping: false }
|
|
76
|
+
live = child
|
|
77
|
+
void (async () => {
|
|
78
|
+
const decoder = new TextDecoder()
|
|
79
|
+
for await (const chunk of proc.stderr) {
|
|
80
|
+
process.stderr.write(chunk)
|
|
81
|
+
stderrTail = (stderrTail + decoder.decode(chunk, { stream: true })).slice(-KEPT_STDERR)
|
|
82
|
+
}
|
|
83
|
+
})()
|
|
84
|
+
void proc.exited.then((code) => {
|
|
85
|
+
rmSync(socket, { force: true })
|
|
86
|
+
if (child.stopping || stopped)
|
|
87
|
+
return
|
|
88
|
+
const how = proc.signalCode !== null ? `was killed by ${proc.signalCode}` : `exited with code ${code}`
|
|
89
|
+
crashed = [`prunelle dev: the app process ${how}.`, stderrTail.trim(), 'Save a file to start it again.'].filter(Boolean).join('\n\n')
|
|
90
|
+
if (live === child)
|
|
91
|
+
live = undefined
|
|
92
|
+
onReady(undefined)
|
|
93
|
+
hub.broadcast('reload')
|
|
94
|
+
restartOnSave()
|
|
95
|
+
})
|
|
96
|
+
return started
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function stopChild(child: Child): Promise<void> {
|
|
100
|
+
child.stopping = true
|
|
101
|
+
if (child.proc.exitCode === null && child.proc.signalCode === null)
|
|
102
|
+
child.proc.send({ t: 'stop' })
|
|
103
|
+
const kill = setTimeout(() => child.proc.kill('SIGKILL'), STOP_GRACE_MS)
|
|
104
|
+
await child.proc.exited
|
|
105
|
+
clearTimeout(kill)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// A crashed app restarts on the next edit under the root (not recursively) or its source folders.
|
|
109
|
+
function restartOnSave(): void {
|
|
110
|
+
const dirs = [[root, false], [join(root, 'src'), true], ...(options.routesDir !== undefined ? [[resolve(root, options.routesDir), true] as const] : [])] as const
|
|
111
|
+
for (const [dir, recursive] of dirs) {
|
|
112
|
+
if (!existsSync(dir))
|
|
113
|
+
continue
|
|
114
|
+
saveWatchers.push(watch(dir, { recursive }, () => {
|
|
115
|
+
for (const w of saveWatchers)
|
|
116
|
+
w.close()
|
|
117
|
+
saveWatchers = []
|
|
118
|
+
if (!stopped)
|
|
119
|
+
ready = spawnChild()
|
|
120
|
+
}))
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
ready = spawnChild()
|
|
125
|
+
await ready
|
|
126
|
+
|
|
127
|
+
const server = Bun.serve({
|
|
128
|
+
port: options.port ?? 3000,
|
|
129
|
+
hostname: options.hostname ?? '127.0.0.1',
|
|
130
|
+
idleTimeout: 30,
|
|
131
|
+
maxRequestBodySize: options.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
|
|
132
|
+
async fetch(request, srv) {
|
|
133
|
+
const url = new URL(request.url)
|
|
134
|
+
if (url.pathname === reloadAssets.eventsPath) {
|
|
135
|
+
srv.timeout(request, 0)
|
|
136
|
+
return hub.events(request)
|
|
137
|
+
}
|
|
138
|
+
const child = await ready
|
|
139
|
+
if (child === undefined)
|
|
140
|
+
return buildErrorResponse(request, crashed ?? 'prunelle dev: the app process is not running.', reloadAssets.script)
|
|
141
|
+
const headers = new Headers(request.headers)
|
|
142
|
+
headers.set(DEV_CLIENT_IP_HEADER, srv.requestIP(request)?.address ?? '')
|
|
143
|
+
try {
|
|
144
|
+
const res = await fetch(`http://localhost${url.pathname}${url.search}`, {
|
|
145
|
+
unix: child.socket,
|
|
146
|
+
method: request.method,
|
|
147
|
+
headers,
|
|
148
|
+
body: request.body,
|
|
149
|
+
redirect: 'manual',
|
|
150
|
+
signal: request.signal,
|
|
151
|
+
})
|
|
152
|
+
if (!res.headers.has('content-length'))
|
|
153
|
+
srv.timeout(request, 0)
|
|
154
|
+
return res
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
if (request.signal.aborted)
|
|
158
|
+
return new Response(null, { status: 499 })
|
|
159
|
+
// A refused connection is most often the child dying: its exit, and its stderr, come right after.
|
|
160
|
+
await Promise.race([child.proc.exited, Bun.sleep(1000)])
|
|
161
|
+
return buildErrorResponse(request, crashed ?? `prunelle dev: the app process did not answer: ${err instanceof Error ? err.message : String(err)}`, reloadAssets.script)
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
const host = options.hostname === undefined || options.hostname === '0.0.0.0' ? '127.0.0.1' : options.hostname
|
|
167
|
+
const url = `http://${host}:${server.port}`
|
|
168
|
+
console.log(`[prunelle dev] listening on ${url}`)
|
|
169
|
+
let stopPromise: Promise<void> | undefined
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
url,
|
|
173
|
+
stop() {
|
|
174
|
+
stopPromise ??= (async () => {
|
|
175
|
+
stopped = true
|
|
176
|
+
for (const w of saveWatchers)
|
|
177
|
+
w.close()
|
|
178
|
+
server.stop(true)
|
|
179
|
+
hub.close()
|
|
180
|
+
if (live !== undefined)
|
|
181
|
+
await stopChild(live)
|
|
182
|
+
rmSync(socketDir, { recursive: true, force: true })
|
|
183
|
+
})()
|
|
184
|
+
return stopPromise
|
|
185
|
+
},
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// prunelle dev's file watchers: src/, the routes and public folders, the root's prunelle.config.ts, plugin watchPaths, and the folders of the files the last build read.
|
|
2
|
+
|
|
3
|
+
import type { FSWatcher } from 'node:fs'
|
|
4
|
+
import type { loadConfig } from '../plugins/index'
|
|
5
|
+
import { existsSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
|
|
6
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path'
|
|
7
|
+
import { isInNodeModules } from '../build/files'
|
|
8
|
+
import { isInside } from '../build/is-inside'
|
|
9
|
+
import { createAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
10
|
+
|
|
11
|
+
export type ChangeKind = 'css' | 'code' | 'public' | 'full' | 'config'
|
|
12
|
+
|
|
13
|
+
type PrunelleConfig = Awaited<ReturnType<typeof loadConfig>>
|
|
14
|
+
|
|
15
|
+
// A source edit changes the bundled bytes; any other file (content, data, public/) may be read when a module loads.
|
|
16
|
+
const CODE_FILE_RE = /\.(?:[cm]?[jt]sx?|css)$/
|
|
17
|
+
|
|
18
|
+
export function srcChangeKind(name: string): ChangeKind {
|
|
19
|
+
if (name.endsWith('.css') && !name.endsWith('.module.css'))
|
|
20
|
+
return 'css'
|
|
21
|
+
return CODE_FILE_RE.test(name) ? 'code' : 'full'
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// The files outside node_modules that `entry` imports, transitively, `entry` left out.
|
|
25
|
+
export function localImports(entry: string): string[] {
|
|
26
|
+
const transpiler = new Bun.Transpiler({ loader: 'tsx' })
|
|
27
|
+
const seen = new Set<string>([entry])
|
|
28
|
+
const queue = [entry]
|
|
29
|
+
for (let file = queue.pop(); file !== undefined; file = queue.pop()) {
|
|
30
|
+
let source: string
|
|
31
|
+
try {
|
|
32
|
+
source = readFileSync(file, 'utf8')
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
continue // deleted since it was resolved
|
|
36
|
+
}
|
|
37
|
+
for (const { path } of transpiler.scanImports(source)) {
|
|
38
|
+
let resolved: string
|
|
39
|
+
try {
|
|
40
|
+
resolved = Bun.resolveSync(path, dirname(file))
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
continue // a specifier that does not resolve from here, which the config load reports itself
|
|
44
|
+
}
|
|
45
|
+
if (!isAbsolute(resolved) || isInNodeModules(resolved) || seen.has(resolved))
|
|
46
|
+
continue
|
|
47
|
+
seen.add(resolved)
|
|
48
|
+
queue.push(resolved)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
seen.delete(entry)
|
|
52
|
+
return [...seen]
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const isInsideDir = (parent: string, target: string): boolean => isInside(parent, target, { orSame: true })
|
|
56
|
+
|
|
57
|
+
export interface DevWatcherOptions {
|
|
58
|
+
root: string
|
|
59
|
+
devRoot: string
|
|
60
|
+
srcDir: string
|
|
61
|
+
routesDir: string | undefined
|
|
62
|
+
schedule: (kind: ChangeKind) => void
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function createDevWatchers({ root, devRoot, srcDir, routesDir, schedule }: DevWatcherOptions) {
|
|
66
|
+
const rootWatchers: FSWatcher[] = []
|
|
67
|
+
const dirWatchers = new Map<string, FSWatcher>()
|
|
68
|
+
const pluginWatchers: FSWatcher[] = []
|
|
69
|
+
const graphWatchers = new Map<string, FSWatcher>()
|
|
70
|
+
let activeRoutesDir = resolve(root, routesDir ?? 'src/routes')
|
|
71
|
+
let activePublicDir = resolve(root, 'public')
|
|
72
|
+
let builtPublic = new Set<string>()
|
|
73
|
+
// An edit to a file the last build listed changes no bundle; one added or removed changes the list.
|
|
74
|
+
const publicChangeKind = (name: string): ChangeKind =>
|
|
75
|
+
builtPublic.has(name) && existsSync(join(activePublicDir, name)) ? 'public' : 'full'
|
|
76
|
+
|
|
77
|
+
function isCoveredByStaticWatchers(dir: string): boolean {
|
|
78
|
+
if (dir === root)
|
|
79
|
+
return false
|
|
80
|
+
for (const base of dirWatchers.keys()) {
|
|
81
|
+
if (isInsideDir(base, dir))
|
|
82
|
+
return true
|
|
83
|
+
}
|
|
84
|
+
return false
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function syncStatic(cfg: PrunelleConfig): void {
|
|
88
|
+
activeRoutesDir = resolve(root, routesDir ?? cfg.routesDir ?? 'src/routes')
|
|
89
|
+
activePublicDir = resolve(root, cfg.publicDir ?? 'public')
|
|
90
|
+
const desired = new Map<string, (filename: string) => void>()
|
|
91
|
+
if (existsSync(srcDir))
|
|
92
|
+
desired.set(srcDir, name => schedule(srcChangeKind(name)))
|
|
93
|
+
if (!isInsideDir(srcDir, activeRoutesDir) && existsSync(activeRoutesDir))
|
|
94
|
+
desired.set(activeRoutesDir, name => schedule(srcChangeKind(name)))
|
|
95
|
+
if (existsSync(activePublicDir))
|
|
96
|
+
desired.set(activePublicDir, name => schedule(publicChangeKind(name)))
|
|
97
|
+
for (const [dir, w] of dirWatchers) {
|
|
98
|
+
if (!desired.has(dir)) {
|
|
99
|
+
w.close()
|
|
100
|
+
dirWatchers.delete(dir)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
for (const [dir, handler] of desired) {
|
|
104
|
+
if (dirWatchers.has(dir))
|
|
105
|
+
continue
|
|
106
|
+
dirWatchers.set(dir, watch(dir, { recursive: true }, (_ev, filename) => {
|
|
107
|
+
handler(typeof filename === 'string' ? filename : '')
|
|
108
|
+
}))
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
get publicDir(): string {
|
|
114
|
+
return activePublicDir
|
|
115
|
+
},
|
|
116
|
+
syncStatic,
|
|
117
|
+
|
|
118
|
+
refreshPlugins(cfg: PrunelleConfig, assetPrefix: string): void {
|
|
119
|
+
for (const w of pluginWatchers)
|
|
120
|
+
w.close()
|
|
121
|
+
pluginWatchers.length = 0
|
|
122
|
+
const seen = new Set<string>(dirWatchers.keys())
|
|
123
|
+
const watchCtx = createAppContext({ root, outDir: devRoot, publicDir: activePublicDir, assetPrefix, site: cfg.site, dev: true })
|
|
124
|
+
for (const plugin of resolvePlugins(cfg.plugins)) {
|
|
125
|
+
const paths = runWithAppContext(watchCtx, () =>
|
|
126
|
+
typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? []))
|
|
127
|
+
for (const p of paths) {
|
|
128
|
+
const abs = resolve(root, p)
|
|
129
|
+
if (seen.has(abs) || !existsSync(abs))
|
|
130
|
+
continue
|
|
131
|
+
seen.add(abs)
|
|
132
|
+
const isDir = statSync(abs).isDirectory()
|
|
133
|
+
pluginWatchers.push(watch(abs, isDir ? { recursive: true } : {}, () => schedule('full')))
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
|
|
138
|
+
syncBuild(watchedFiles: ReadonlySet<string>, publicFiles: readonly string[]): void {
|
|
139
|
+
builtPublic = new Set(publicFiles)
|
|
140
|
+
const nextDirs = new Set<string>()
|
|
141
|
+
let realRoot: string
|
|
142
|
+
try {
|
|
143
|
+
realRoot = realpathSync(root)
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
realRoot = root
|
|
147
|
+
}
|
|
148
|
+
for (const file of watchedFiles) {
|
|
149
|
+
if (isInNodeModules(file))
|
|
150
|
+
continue
|
|
151
|
+
if (isInsideDir(devRoot, file) || isInsideDir(join(root, '.prunelle-cache'), file))
|
|
152
|
+
continue
|
|
153
|
+
const dir = dirname(file)
|
|
154
|
+
// Root is already watched non-recursively for `prunelle.config.ts`; skip if it's only prunelle.config.ts itself.
|
|
155
|
+
if (dir === root || dir === realRoot) {
|
|
156
|
+
if (file === join(root, 'prunelle.config.ts') || file === join(realRoot, 'prunelle.config.ts'))
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
159
|
+
if (isCoveredByStaticWatchers(dir))
|
|
160
|
+
continue
|
|
161
|
+
nextDirs.add(dir)
|
|
162
|
+
}
|
|
163
|
+
for (const [dir, watcher] of graphWatchers) {
|
|
164
|
+
if (!nextDirs.has(dir)) {
|
|
165
|
+
watcher.close()
|
|
166
|
+
graphWatchers.delete(dir)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
for (const dir of nextDirs) {
|
|
170
|
+
if (graphWatchers.has(dir) || !existsSync(dir))
|
|
171
|
+
continue
|
|
172
|
+
try {
|
|
173
|
+
graphWatchers.set(dir, watch(dir, (_ev, filename) => {
|
|
174
|
+
const name = typeof filename === 'string' ? filename : ''
|
|
175
|
+
schedule(srcChangeKind(name))
|
|
176
|
+
}))
|
|
177
|
+
}
|
|
178
|
+
catch (err) {
|
|
179
|
+
console.warn(`[prunelle dev] could not watch ${dir}: ${err instanceof Error ? err.message : String(err)}`)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
|
|
184
|
+
// The root, non-recursively: prunelle.config.ts, and a public, routes or src folder created after startup; with `configImports`, the local files prunelle.config.ts imports too.
|
|
185
|
+
watchRoot(currentConfig: () => PrunelleConfig, configImports: boolean): void {
|
|
186
|
+
if (configImports) {
|
|
187
|
+
for (const file of localImports(join(root, 'prunelle.config.ts')))
|
|
188
|
+
rootWatchers.push(watch(file, () => schedule('config')))
|
|
189
|
+
}
|
|
190
|
+
rootWatchers.push(watch(root, (_ev, filename) => {
|
|
191
|
+
if (filename === 'prunelle.config.ts') {
|
|
192
|
+
schedule('config')
|
|
193
|
+
return
|
|
194
|
+
}
|
|
195
|
+
const changed = typeof filename === 'string' && filename !== '' ? resolve(root, filename) : undefined
|
|
196
|
+
for (const dir of [activePublicDir, activeRoutesDir, srcDir]) {
|
|
197
|
+
if (!dirWatchers.has(dir) && existsSync(dir) && (changed === undefined || isInsideDir(changed, dir))) {
|
|
198
|
+
syncStatic(currentConfig())
|
|
199
|
+
schedule(dir === activePublicDir ? 'full' : 'code')
|
|
200
|
+
break
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}))
|
|
204
|
+
},
|
|
205
|
+
|
|
206
|
+
close(): void {
|
|
207
|
+
for (const w of [...rootWatchers, ...dirWatchers.values(), ...pluginWatchers, ...graphWatchers.values()])
|
|
208
|
+
w.close()
|
|
209
|
+
rootWatchers.length = 0
|
|
210
|
+
pluginWatchers.length = 0
|
|
211
|
+
dirWatchers.clear()
|
|
212
|
+
graphWatchers.clear()
|
|
213
|
+
},
|
|
214
|
+
}
|
|
215
|
+
}
|