prunelle 0.0.0-stage → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/llms.txt +245 -0
- package/package.json +62 -4
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +43 -0
- package/src/build/bundle.ts +661 -0
- package/src/build/byte-size.ts +11 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +175 -0
- package/src/build/client-prune.ts +168 -0
- package/src/build/compile.ts +130 -0
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +171 -0
- package/src/build/first-load.ts +235 -0
- package/src/build/graph.ts +237 -0
- package/src/build/index.ts +678 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +452 -0
- package/src/build/manifest.ts +204 -0
- package/src/build/output.ts +81 -0
- package/src/build/plugin-host.ts +294 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +288 -0
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +290 -0
- package/src/build/resolve.ts +52 -0
- package/src/build/routes.ts +342 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +209 -0
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +409 -0
- package/src/cli/commands.ts +372 -0
- package/src/cli/docs.ts +403 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +406 -0
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +52 -0
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +367 -0
- package/src/compiler/analyze.ts +651 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +250 -0
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +653 -0
- package/src/compiler/data-keys.ts +302 -0
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +452 -0
- package/src/compiler/dom.ts +641 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +587 -0
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +520 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +511 -0
- package/src/compiler/scope.ts +635 -0
- package/src/compiler/server-only.ts +365 -0
- package/src/compiler/shared.ts +397 -0
- package/src/compiler/signal-reads.ts +246 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +69 -0
- package/src/compiler/ssr.ts +525 -0
- package/src/context.ts +199 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +268 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +24 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +159 -0
- package/src/dev/supervisor.ts +212 -0
- package/src/dev/watchers.ts +276 -0
- package/src/dom/action.ts +187 -0
- package/src/dom/attrs.ts +84 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +579 -0
- package/src/dom/index.ts +329 -0
- package/src/dom/island.ts +318 -0
- package/src/dom/loop.ts +484 -0
- package/src/dom/revive.ts +36 -0
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +92 -0
- package/src/plugins/context.ts +109 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +90 -0
- package/src/plugins/order.ts +148 -0
- package/src/plugins/public.ts +15 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +119 -0
- package/src/plugins/types.ts +278 -0
- package/src/reactivity/graph.ts +259 -0
- package/src/reactivity/index.ts +541 -0
- package/src/reactivity/selector.ts +78 -0
- package/src/reactivity/store.ts +252 -0
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +511 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +168 -0
- package/src/server/compress.ts +646 -0
- package/src/server/consent.ts +290 -0
- package/src/server/cookies.ts +153 -0
- package/src/server/document.ts +286 -0
- package/src/server/env.ts +47 -0
- package/src/server/errors.ts +396 -0
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +588 -0
- package/src/server/index.ts +615 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +131 -0
- package/src/server/page.ts +122 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +267 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +20 -0
- package/src/server/rate-limit.ts +199 -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-cache.ts +541 -0
- package/src/server/route-table.ts +424 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +388 -0
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +550 -0
- package/src/server/serve-handlers.ts +93 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +104 -0
- package/src/server/start.ts +143 -0
- package/src/server/static-dir.ts +246 -0
- package/src/server/stream.ts +233 -0
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +399 -0
- package/src/ssr/index.ts +624 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +192 -0
- package/src/style.ts +96 -0
- package/src/test/browser.ts +201 -0
- package/src/test/index.ts +262 -0
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +8 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +22 -0
- package/templates/_shared/tsconfig.json +25 -0
- package/templates/app/.env.example +8 -0
- package/templates/app/package.json +22 -0
- package/templates/app/prunelle.config.ts +13 -0
- package/templates/app/src/auth.ts +12 -0
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +40 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +47 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +53 -0
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +14 -0
- package/templates/app/tests/app.test.ts +73 -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 +25 -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 +15 -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 +28 -0
- package/templates/fullstack/src/routes/_layout.tsx +18 -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 +39 -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 +18 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +32 -0
- package/ts-plugin.cjs +4277 -0
- package/README.md +0 -3
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// The previous build's client files that a new build dropped, linked into its stage for one more deploy,
|
|
2
|
+
// so a page loaded before the deploy still finds the deferred island chunks it links (#3663).
|
|
3
|
+
|
|
4
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { linkOrCopyFile } from './bundle'
|
|
7
|
+
import { isInside } from './is-inside'
|
|
8
|
+
|
|
9
|
+
/** Written at the root of each output: which client files the build made itself, and which it carried from the one before. */
|
|
10
|
+
export const ASSET_RECORD = '.prunelle-assets.json'
|
|
11
|
+
|
|
12
|
+
interface AssetRecord {
|
|
13
|
+
/** The client folder, from the output root: `client`, or the asset prefix's folder in a static export. */
|
|
14
|
+
dir: string
|
|
15
|
+
assets: string[]
|
|
16
|
+
carried: string[]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function readRecord(path: string): AssetRecord | undefined {
|
|
20
|
+
if (!existsSync(path))
|
|
21
|
+
return undefined
|
|
22
|
+
try {
|
|
23
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<AssetRecord>
|
|
24
|
+
return typeof parsed.dir === 'string' && Array.isArray(parsed.assets) ? parsed as AssetRecord : undefined
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// A record prunelle cannot read carries nothing: the deploy still works, an old page reloads for its chunk as before.
|
|
28
|
+
return undefined
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Hard-links into `stageRoot/dir` each client file the build in `previousRoot` made and the stage lacks, with its `.br` and `.gz`, and writes this build's record.
|
|
34
|
+
* What the previous build carried itself is left behind, so a file outlives one deploy, never two.
|
|
35
|
+
*/
|
|
36
|
+
export function carryPreviousAssets(previousRoot: string, stageRoot: string, dir: string, assets: readonly string[]): string[] {
|
|
37
|
+
const previous = readRecord(join(previousRoot, ASSET_RECORD))
|
|
38
|
+
const carried: string[] = []
|
|
39
|
+
if (previous !== undefined) {
|
|
40
|
+
const fromDir = join(previousRoot, previous.dir)
|
|
41
|
+
const toDir = join(stageRoot, dir)
|
|
42
|
+
for (const rel of previous.assets) {
|
|
43
|
+
const from = join(fromDir, rel)
|
|
44
|
+
const to = join(toDir, rel)
|
|
45
|
+
if (!isInside(previousRoot, from) || !isInside(toDir, to) || !existsSync(from) || existsSync(to))
|
|
46
|
+
continue
|
|
47
|
+
for (const ext of ['', '.br', '.gz']) {
|
|
48
|
+
if (existsSync(`${from}${ext}`))
|
|
49
|
+
linkOrCopyFile(`${from}${ext}`, `${to}${ext}`)
|
|
50
|
+
}
|
|
51
|
+
carried.push(rel)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const record: AssetRecord = { dir, assets: [...assets], carried }
|
|
55
|
+
writeFileSync(join(stageRoot, ASSET_RECORD), JSON.stringify(record))
|
|
56
|
+
return carried
|
|
57
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// The generated entry files of the client build (the island runtime, the region bundle, one per island) and the hydrate strategies its loader keeps.
|
|
2
|
+
|
|
3
|
+
import type { BundleEnv } from './bundle'
|
|
4
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
const LEADING_DOT_SLASH_RE = /^\.\//
|
|
8
|
+
|
|
9
|
+
/** The lazy strategies some island of the app hydrates with, so the loader keeps only theirs. A mode computed at runtime (`*`) may be any of them. */
|
|
10
|
+
export function hydrateStrategies(analyses: Iterable<{ defaultHydrate?: string | undefined, hydrateModes: Set<string> }>): { strategies: Record<'visible' | 'idle' | 'interaction' | 'media', boolean>, hasClientOnlyHydrate: boolean } {
|
|
11
|
+
const strategies = { visible: false, idle: false, interaction: false, media: false }
|
|
12
|
+
let hasClientOnlyHydrate = false
|
|
13
|
+
for (const analysis of analyses) {
|
|
14
|
+
for (const mode of [analysis.defaultHydrate, ...analysis.hydrateModes]) {
|
|
15
|
+
const any = mode === '*'
|
|
16
|
+
hasClientOnlyHydrate ||= any || mode === 'client'
|
|
17
|
+
strategies.visible ||= any || mode === 'visible'
|
|
18
|
+
strategies.idle ||= any || mode === 'idle'
|
|
19
|
+
strategies.interaction ||= any || mode === 'interaction'
|
|
20
|
+
strategies.media ||= any || (mode?.startsWith('media(') ?? false)
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return { strategies, hasClientOnlyHydrate }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Another build of the same app (`prunelle build` beside `prunelle dev`) may be reading the file, hence the rename.
|
|
27
|
+
function writeEntry(path: string, contents: string): void {
|
|
28
|
+
if (existsSync(path) && readFileSync(path, 'utf8') === contents)
|
|
29
|
+
return
|
|
30
|
+
const tmpPath = `${path}.${process.pid}.tmp`
|
|
31
|
+
writeFileSync(tmpPath, contents)
|
|
32
|
+
renameSync(tmpPath, path)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ClientEntryFiles {
|
|
36
|
+
entryPoints: string[]
|
|
37
|
+
islandEntryToKey: Map<string, string>
|
|
38
|
+
runtimeEntryPath: string | undefined
|
|
39
|
+
/** The plugins' `regionClientEntry` modules, bundled apart so only the routes that render a `<Region>` load them. */
|
|
40
|
+
regionEntryPath: string | undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function writeClientEntries(env: BundleEnv, entriesDir: string, options: { pluginClientEntries: string[], regionClientEntries: string[], hasClientOnlyHydrate: boolean, standaloneCss: string[] }): ClientEntryFiles {
|
|
44
|
+
const { pluginClientEntries, regionClientEntries, hasClientOnlyHydrate } = options
|
|
45
|
+
const out: ClientEntryFiles = { entryPoints: [], islandEntryToKey: new Map(), runtimeEntryPath: undefined, regionEntryPath: undefined }
|
|
46
|
+
if (env.islands.targets.size > 0 || pluginClientEntries.length > 0) {
|
|
47
|
+
const runtimeLines: string[] = []
|
|
48
|
+
if (env.islands.targets.size > 0) {
|
|
49
|
+
runtimeLines.push(`import { defineIslandElement } from 'prunelle/internal/island';`)
|
|
50
|
+
runtimeLines.push(`defineIslandElement();`)
|
|
51
|
+
}
|
|
52
|
+
for (const pe of pluginClientEntries)
|
|
53
|
+
runtimeLines.push(`import ${JSON.stringify(pe)};`)
|
|
54
|
+
out.runtimeEntryPath = join(entriesDir, 'runtime.ts')
|
|
55
|
+
writeEntry(out.runtimeEntryPath, `${runtimeLines.join('\n')}\n`)
|
|
56
|
+
out.entryPoints.push(out.runtimeEntryPath)
|
|
57
|
+
}
|
|
58
|
+
if (regionClientEntries.length > 0) {
|
|
59
|
+
out.regionEntryPath = join(entriesDir, 'regions.ts')
|
|
60
|
+
writeEntry(out.regionEntryPath, `${regionClientEntries.map(pe => `import ${JSON.stringify(pe)};`).join('\n')}\n`)
|
|
61
|
+
out.entryPoints.push(out.regionEntryPath)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
out.entryPoints.push(...options.standaloneCss)
|
|
65
|
+
|
|
66
|
+
// Each island hands the loader the DOM runtime its chunk imports anyway, so a page whose islands all wait downloads the loader alone.
|
|
67
|
+
const domExports = `export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';\n`
|
|
68
|
+
for (const [key, target] of env.islands.targets) {
|
|
69
|
+
const entryPath = join(entriesDir, `${target.id}.ts`)
|
|
70
|
+
const exportStmt = target.exportName === 'default'
|
|
71
|
+
? `export { default } from ${JSON.stringify(target.file)};\n`
|
|
72
|
+
: `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
|
|
73
|
+
writeEntry(entryPath, exportStmt + domExports)
|
|
74
|
+
out.entryPoints.push(entryPath)
|
|
75
|
+
out.islandEntryToKey.set(entryPath, key)
|
|
76
|
+
}
|
|
77
|
+
return out
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** For each JS entry of the client build with static imports, every chunk it imports, transitively: the page preloads them beside the entry, so the browser fetches them at once rather than one level at a time. */
|
|
81
|
+
export function entryStaticImports(metafile: Bun.BuildOutput['metafile'], assetPrefix: string): Record<string, string[]> {
|
|
82
|
+
const deps = new Map<string, string[]>()
|
|
83
|
+
const entries: string[] = []
|
|
84
|
+
for (const [outKey, info] of Object.entries(metafile?.outputs ?? {})) {
|
|
85
|
+
const rel = outKey.replace(LEADING_DOT_SLASH_RE, '')
|
|
86
|
+
if (!rel.endsWith('.js'))
|
|
87
|
+
continue
|
|
88
|
+
deps.set(rel, (info.imports ?? []).filter(imp => imp.kind === 'import-statement').map(imp => imp.path.replace(LEADING_DOT_SLASH_RE, '')))
|
|
89
|
+
if (info.entryPoint !== undefined)
|
|
90
|
+
entries.push(rel)
|
|
91
|
+
}
|
|
92
|
+
const out: Record<string, string[]> = {}
|
|
93
|
+
for (const entry of entries) {
|
|
94
|
+
const seen = new Set<string>()
|
|
95
|
+
const stack = [...deps.get(entry)!]
|
|
96
|
+
while (stack.length > 0) {
|
|
97
|
+
const cur = stack.pop()!
|
|
98
|
+
if (seen.has(cur) || cur === entry)
|
|
99
|
+
continue
|
|
100
|
+
seen.add(cur)
|
|
101
|
+
stack.push(...deps.get(cur) ?? [])
|
|
102
|
+
}
|
|
103
|
+
if (seen.size > 0)
|
|
104
|
+
out[`${assetPrefix}/${entry}`] = [...seen].sort().map(rel => `${assetPrefix}/${rel}`)
|
|
105
|
+
}
|
|
106
|
+
return out
|
|
107
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// The Bun plugin of the client build: prunelle specifiers, action stubs, compiled islands, and imports of the `prunelle` barrel pointed at the module holding each name.
|
|
2
|
+
|
|
3
|
+
import type { BunPlugin } from 'bun'
|
|
4
|
+
import type { BuildCache, ModuleGraph } from './graph'
|
|
5
|
+
import type { ActionsByFile } from './islands'
|
|
6
|
+
import { parseSync } from 'oxc-parser'
|
|
7
|
+
import { compileDom } from '../compiler/index'
|
|
8
|
+
import { SERVER_ONLY_FILTER } from '../compiler/server-only'
|
|
9
|
+
import { pruneForClient } from './client-prune'
|
|
10
|
+
import { isInNodeModules, relPosix } from './files'
|
|
11
|
+
import { resolvePrunelleSpecifier } from './resolve'
|
|
12
|
+
|
|
13
|
+
export const PRUNELLE_SPECIFIER_FILTER = /^prunelle(?:\/.*)?$/
|
|
14
|
+
export const TS_FILTER = /\.(?:ts|tsx)$/
|
|
15
|
+
const TS_LANG_RE = /\.[cm]?ts$/i
|
|
16
|
+
const BARREL_IMPORT_RE = /['"]prunelle['"]/
|
|
17
|
+
|
|
18
|
+
export interface ClientTransforms {
|
|
19
|
+
active: boolean
|
|
20
|
+
key: string
|
|
21
|
+
/** The first hook that threw, named, rethrown once the build is done. */
|
|
22
|
+
failure: Error | undefined
|
|
23
|
+
apply: (code: string, id: string, target: 'server' | 'client') => string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ClientPluginEnv {
|
|
27
|
+
root: string
|
|
28
|
+
isDev: boolean
|
|
29
|
+
graph: ModuleGraph
|
|
30
|
+
cache: BuildCache | undefined
|
|
31
|
+
actionsByFile: ActionsByFile
|
|
32
|
+
transforms: ClientTransforms
|
|
33
|
+
/** Collects each server-only import a browser file makes, reported once the build ends. */
|
|
34
|
+
leaks: Set<string>
|
|
35
|
+
/** Per file, the `export { … }` statement naming the islands it does not export itself. */
|
|
36
|
+
localExports: ReadonlyMap<string, string>
|
|
37
|
+
/** Per file the browser loads only for its own islands, the top-level names its client copy keeps. */
|
|
38
|
+
clientKeep: ReadonlyMap<string, ReadonlySet<string>>
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The `export { … }` statement each file needs so the client entry can import the islands the file does not export. */
|
|
42
|
+
export function localIslandExports(targets: Iterable<{ file: string, exportName: string, local?: string | undefined }>): Map<string, string> {
|
|
43
|
+
const names = new Map<string, string[]>()
|
|
44
|
+
for (const t of targets) {
|
|
45
|
+
if (t.local === undefined)
|
|
46
|
+
continue
|
|
47
|
+
const list = names.get(t.file) ?? []
|
|
48
|
+
list.push(t.local === t.exportName ? t.local : `${t.local} as ${t.exportName}`)
|
|
49
|
+
names.set(t.file, list)
|
|
50
|
+
}
|
|
51
|
+
return new Map([...names].map(([file, list]) => [file, `\nexport { ${list.join(', ')} };\n`]))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Rewrites top-level `import { a, b } from 'prunelle'` statements to import each name from the module declaring it.
|
|
56
|
+
* Through the barrel every island reaches every module it re-exports, and Bun then places a module only some islands use (the action runtime) in the shared chunk in one build and in the island's own chunk in the next (#3598).
|
|
57
|
+
*/
|
|
58
|
+
export function directPrunelleImports(code: string, graph: ModuleGraph, filename = 'module.tsx'): string {
|
|
59
|
+
// Compiled DOM output imports `prunelle/internal/…` only, so it is parsed again only when the module itself imports the barrel.
|
|
60
|
+
if (!BARREL_IMPORT_RE.test(code))
|
|
61
|
+
return code
|
|
62
|
+
const barrel = resolvePrunelleSpecifier('prunelle')!
|
|
63
|
+
const lang = TS_LANG_RE.test(filename) ? 'ts' : 'tsx'
|
|
64
|
+
const parsed = parseSync(filename, code, { lang, sourceType: 'module' })
|
|
65
|
+
if (parsed.errors.length > 0)
|
|
66
|
+
return code
|
|
67
|
+
|
|
68
|
+
const edits: { start: number, end: number, text: string }[] = []
|
|
69
|
+
for (const stmt of parsed.program.body) {
|
|
70
|
+
if (stmt.type !== 'ImportDeclaration' || stmt.importKind === 'type' || stmt.source.value !== 'prunelle')
|
|
71
|
+
continue
|
|
72
|
+
if (stmt.specifiers.length === 0 || stmt.specifiers.some(s => s.type !== 'ImportSpecifier'))
|
|
73
|
+
continue
|
|
74
|
+
|
|
75
|
+
const byFile = new Map<string, string[]>()
|
|
76
|
+
const kept: string[] = []
|
|
77
|
+
for (const spec of stmt.specifiers) {
|
|
78
|
+
if (spec.type !== 'ImportSpecifier')
|
|
79
|
+
continue
|
|
80
|
+
const imported = spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value
|
|
81
|
+
const importedRaw = spec.imported.type === 'Identifier' ? imported : JSON.stringify(imported)
|
|
82
|
+
const local = spec.local.name
|
|
83
|
+
const rawSpec = imported === local && spec.imported.type === 'Identifier' ? local : `${importedRaw} as ${local}`
|
|
84
|
+
if (spec.importKind === 'type') {
|
|
85
|
+
kept.push(`type ${rawSpec}`)
|
|
86
|
+
continue
|
|
87
|
+
}
|
|
88
|
+
const target = graph.exportTarget(barrel, imported)
|
|
89
|
+
if (target.file === barrel) {
|
|
90
|
+
kept.push(rawSpec)
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
const names = byFile.get(target.file) ?? []
|
|
94
|
+
names.push(target.exportName === local ? local : `${target.exportName} as ${local}`)
|
|
95
|
+
byFile.set(target.file, names)
|
|
96
|
+
}
|
|
97
|
+
if (byFile.size === 0)
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
const lines = [...byFile].map(([file, names]) => `import { ${names.join(', ')} } from ${JSON.stringify(file)};`)
|
|
101
|
+
if (kept.length > 0)
|
|
102
|
+
lines.push(`import { ${kept.join(', ')} } from 'prunelle';`)
|
|
103
|
+
const stmtText = code.slice(stmt.start, stmt.end)
|
|
104
|
+
// Same line count, so later positions in the module stay where they were.
|
|
105
|
+
edits.push({ start: stmt.start, end: stmt.end, text: `${lines.join(' ')}${'\n'.repeat(stmtText.split('\n').length - 1)}` })
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (edits.length === 0)
|
|
109
|
+
return code
|
|
110
|
+
let out = ''
|
|
111
|
+
let cursor = 0
|
|
112
|
+
for (const edit of edits) {
|
|
113
|
+
out += code.slice(cursor, edit.start) + edit.text
|
|
114
|
+
cursor = edit.end
|
|
115
|
+
}
|
|
116
|
+
return out + code.slice(cursor)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function clientPlugin(env: ClientPluginEnv): BunPlugin {
|
|
120
|
+
const { root, isDev, graph, cache, actionsByFile, transforms, leaks, localExports, clientKeep } = env
|
|
121
|
+
return {
|
|
122
|
+
name: 'prunelle-client',
|
|
123
|
+
setup(b) {
|
|
124
|
+
// Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
|
|
125
|
+
b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
|
|
126
|
+
if (!isInNodeModules(args.importer))
|
|
127
|
+
leaks.add(`${relPosix(root, args.importer)} imports server-only module "${args.path}"`)
|
|
128
|
+
return undefined
|
|
129
|
+
})
|
|
130
|
+
b.onResolve({ filter: PRUNELLE_SPECIFIER_FILTER }, (args) => {
|
|
131
|
+
const resolved = resolvePrunelleSpecifier(args.path)
|
|
132
|
+
return resolved !== undefined ? { path: resolved } : undefined
|
|
133
|
+
})
|
|
134
|
+
b.onLoad({ filter: TS_FILTER }, (args) => {
|
|
135
|
+
const actions = actionsByFile.get(args.path)
|
|
136
|
+
if (actions !== undefined) {
|
|
137
|
+
if (graph.analyses.get(args.path)?.isInteractive) {
|
|
138
|
+
leaks.add(`${relPosix(root, args.path)} exports server actions and uses browser interactivity (move actions to a separate non-interactive file)`)
|
|
139
|
+
return undefined
|
|
140
|
+
}
|
|
141
|
+
const lines = [`import { actionStub } from 'prunelle/internal/action';`]
|
|
142
|
+
for (const a of actions)
|
|
143
|
+
lines.push(`export const ${a.exportName} = actionStub(${JSON.stringify(a.url)});`)
|
|
144
|
+
return { contents: `${lines.join('\n')}\n`, loader: 'ts' }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (!args.path.endsWith('.tsx')) {
|
|
148
|
+
const raw = graph.source(args.path)
|
|
149
|
+
const own = transforms.active && !isInNodeModules(args.path) ? transforms.apply(raw, args.path, 'client') : raw
|
|
150
|
+
const direct = directPrunelleImports(own, graph, args.path)
|
|
151
|
+
return direct !== raw ? { contents: direct, loader: 'ts' } : undefined
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const stamp = graph.stamp(args.path)
|
|
155
|
+
const extraExports = localExports.get(args.path) ?? ''
|
|
156
|
+
const keep = clientKeep.get(args.path)
|
|
157
|
+
const key = `${isDev ? 'd:' : ''}${transforms.key}${extraExports}${keep === undefined ? '' : `|keep=${[...keep].sort().join(',')}`}`
|
|
158
|
+
const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
|
|
159
|
+
if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === key)
|
|
160
|
+
return { contents: cachedDom.code, loader: 'tsx' }
|
|
161
|
+
const analysis = graph.analyses.get(args.path)
|
|
162
|
+
const source = graph.source(args.path)
|
|
163
|
+
const clientSource = keep === undefined || analysis === undefined ? source : pruneForClient(source, analysis.program, keep, { preserveLines: isDev })
|
|
164
|
+
const dom = compileDom(args.path, clientSource, {
|
|
165
|
+
...(clientSource === source ? { analysis } : {}),
|
|
166
|
+
devSourceRoot: isDev ? root : undefined,
|
|
167
|
+
})
|
|
168
|
+
const compiled = directPrunelleImports(transforms.apply(dom.code, args.path, 'client'), graph, args.path) + extraExports
|
|
169
|
+
if (cache !== undefined && stamp !== undefined)
|
|
170
|
+
cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code: compiled })
|
|
171
|
+
return { contents: compiled, loader: 'tsx' }
|
|
172
|
+
})
|
|
173
|
+
},
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The browser's copy of a module it loads only for the islands declared in it: the code those islands reach, without the server code around them.
|
|
2
|
+
|
|
3
|
+
import type { Declaration, ImportDeclaration, ModuleExportName, Node, Program } from 'oxc-parser'
|
|
4
|
+
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
5
|
+
import { parseTsx } from '../compiler/analyze'
|
|
6
|
+
import { clientReach } from '../compiler/interactivity'
|
|
7
|
+
import { SourceEditor } from '../compiler/patch'
|
|
8
|
+
import { referencesAny } from '../compiler/scope'
|
|
9
|
+
import { collectPatternNames } from '../compiler/shared'
|
|
10
|
+
|
|
11
|
+
/** The top-level names the browser needs to run the islands `localNames` of a module: the bindings they reach and the imports those name. */
|
|
12
|
+
export function clientNeeds(analysis: Pick<ModuleAnalysis, 'bindings'>, localNames: readonly string[]): Set<string> {
|
|
13
|
+
const keep = new Set<string>()
|
|
14
|
+
for (const b of clientReach(analysis.bindings, localNames)) {
|
|
15
|
+
keep.add(b.name)
|
|
16
|
+
for (const ref of b.refs.keys())
|
|
17
|
+
keep.add(ref)
|
|
18
|
+
}
|
|
19
|
+
return keep
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The analysis of the client copy `keep` gives, for the walk of what the browser loads: its imports, dynamic imports and program. */
|
|
23
|
+
export function clientView(analysis: ModuleAnalysis, code: string, keep: ReadonlySet<string>): ModuleAnalysis {
|
|
24
|
+
const pruned = pruneForClient(code, analysis.program, keep)
|
|
25
|
+
if (pruned === code)
|
|
26
|
+
return analysis
|
|
27
|
+
const spans = analysis.bindings.filter(b => b.name === '' || keep.has(b.name))
|
|
28
|
+
return {
|
|
29
|
+
...analysis,
|
|
30
|
+
program: parseTsx(analysis.filename, pruned),
|
|
31
|
+
imports: analysis.imports.flatMap((imp) => {
|
|
32
|
+
if (imp.specifiers.length === 0)
|
|
33
|
+
return [imp]
|
|
34
|
+
const specifiers = imp.specifiers.filter(s => keep.has(s.local))
|
|
35
|
+
return specifiers.length === 0 ? [] : [{ ...imp, specifiers }]
|
|
36
|
+
}),
|
|
37
|
+
reexports: [],
|
|
38
|
+
dynamicImports: analysis.dynamicImports.filter(d => spans.some(b => d.start >= b.start && d.start < b.end)),
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function padPreservingLines(original: string, replacement: string): string {
|
|
43
|
+
if (replacement === '')
|
|
44
|
+
return original.replace(/[^\r\n]/g, ' ')
|
|
45
|
+
const origNewlines = original.split('\n').length - 1
|
|
46
|
+
const nextNewlines = replacement.split('\n').length - 1
|
|
47
|
+
return origNewlines > nextNewlines ? `${replacement}${'\n'.repeat(origNewlines - nextNewlines)}` : replacement
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `code` with each top-level declaration, import, re-export, and pruned-binding statement outside `keep` removed. Everything else stays. */
|
|
51
|
+
export function pruneForClient(code: string, program: Program, keep: ReadonlySet<string>, options?: { preserveLines?: boolean | undefined }): string {
|
|
52
|
+
const editor = new SourceEditor(code)
|
|
53
|
+
const preserveLines = options?.preserveLines === true
|
|
54
|
+
const prunedNames = new Set<string>()
|
|
55
|
+
const planned: { stmt: Node, text: string | undefined }[] = []
|
|
56
|
+
for (const stmt of program.body) {
|
|
57
|
+
const text = keptText(stmt, code, keep)
|
|
58
|
+
planned.push({ stmt, text })
|
|
59
|
+
collectPrunedNames(stmt, text, keep, prunedNames)
|
|
60
|
+
}
|
|
61
|
+
for (const { stmt, text } of planned) {
|
|
62
|
+
let next = text
|
|
63
|
+
if (next === undefined && prunedNames.size > 0 && (stmt.type === 'ExpressionStatement' || stmt.type === 'IfStatement') && referencesAny(stmt, prunedNames))
|
|
64
|
+
next = ''
|
|
65
|
+
if (next !== undefined)
|
|
66
|
+
editor.replace(stmt.start, stmt.end, preserveLines ? padPreservingLines(code.slice(stmt.start, stmt.end), next) : next)
|
|
67
|
+
}
|
|
68
|
+
return editor.toString()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function collectPrunedNames(stmt: Node, text: string | undefined, keep: ReadonlySet<string>, out: Set<string>): void {
|
|
72
|
+
if (stmt.type === 'ImportDeclaration') {
|
|
73
|
+
if (text === undefined || stmt.importKind === 'type')
|
|
74
|
+
return
|
|
75
|
+
for (const s of stmt.specifiers) {
|
|
76
|
+
if (!keep.has(s.local.name) && !(s.type === 'ImportSpecifier' && s.importKind === 'type'))
|
|
77
|
+
out.add(s.local.name)
|
|
78
|
+
}
|
|
79
|
+
return
|
|
80
|
+
}
|
|
81
|
+
if (text !== '')
|
|
82
|
+
return
|
|
83
|
+
if (stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration' || stmt.type === 'VariableDeclaration') {
|
|
84
|
+
for (const n of declaredNames(stmt) ?? [])
|
|
85
|
+
out.add(n)
|
|
86
|
+
}
|
|
87
|
+
else if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration !== null && stmt.declaration !== undefined) {
|
|
88
|
+
for (const n of declaredNames(stmt.declaration) ?? [])
|
|
89
|
+
out.add(n)
|
|
90
|
+
}
|
|
91
|
+
else if (stmt.type === 'ExportDefaultDeclaration') {
|
|
92
|
+
const decl = stmt.declaration
|
|
93
|
+
if ((decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') && decl.id !== null)
|
|
94
|
+
out.add(decl.id.name)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const nameOf = (name: ModuleExportName): string => name.type === 'Identifier' ? name.name : String(name.value)
|
|
99
|
+
|
|
100
|
+
function declaredNames(decl: Declaration): string[] | undefined {
|
|
101
|
+
if (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration')
|
|
102
|
+
return decl.id === null ? undefined : [decl.id.name]
|
|
103
|
+
if (decl.type !== 'VariableDeclaration')
|
|
104
|
+
return undefined
|
|
105
|
+
const names = new Set<string>()
|
|
106
|
+
for (const d of decl.declarations)
|
|
107
|
+
collectPatternNames(d.id, names)
|
|
108
|
+
return [...names]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The text replacing a top-level statement: `''` to drop it, `undefined` to leave it as written. */
|
|
112
|
+
function keptText(stmt: Node, code: string, keep: ReadonlySet<string>): string | undefined {
|
|
113
|
+
switch (stmt.type) {
|
|
114
|
+
case 'ImportDeclaration':
|
|
115
|
+
return keptImport(stmt, code, keep)
|
|
116
|
+
case 'FunctionDeclaration':
|
|
117
|
+
case 'ClassDeclaration':
|
|
118
|
+
case 'VariableDeclaration': {
|
|
119
|
+
const names = declaredNames(stmt)
|
|
120
|
+
return names === undefined || names.some(n => keep.has(n)) ? undefined : ''
|
|
121
|
+
}
|
|
122
|
+
case 'ExportNamedDeclaration': {
|
|
123
|
+
if (stmt.exportKind === 'type')
|
|
124
|
+
return undefined
|
|
125
|
+
if (stmt.declaration !== null && stmt.declaration !== undefined) {
|
|
126
|
+
const names = declaredNames(stmt.declaration)
|
|
127
|
+
return names === undefined || names.some(n => keep.has(n)) ? undefined : ''
|
|
128
|
+
}
|
|
129
|
+
if (stmt.source !== null)
|
|
130
|
+
return ''
|
|
131
|
+
const specs = stmt.specifiers.filter(s => keep.has(nameOf(s.local)))
|
|
132
|
+
if (specs.length === stmt.specifiers.length)
|
|
133
|
+
return undefined
|
|
134
|
+
return specs.length === 0 ? '' : `export { ${specs.map(s => code.slice(s.start, s.end)).join(', ')} };`
|
|
135
|
+
}
|
|
136
|
+
case 'ExportDefaultDeclaration': {
|
|
137
|
+
const decl = stmt.declaration
|
|
138
|
+
const name = decl.type === 'Identifier' ? decl.name : (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') && decl.id !== null ? decl.id.name : 'default'
|
|
139
|
+
return keep.has(name) ? undefined : ''
|
|
140
|
+
}
|
|
141
|
+
case 'ExportAllDeclaration':
|
|
142
|
+
return stmt.exportKind === 'type' ? undefined : ''
|
|
143
|
+
default:
|
|
144
|
+
return undefined
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function keptImport(stmt: ImportDeclaration, code: string, keep: ReadonlySet<string>): string | undefined {
|
|
149
|
+
// A type import stays as written; a side-effect import keeps all of its zero specifiers.
|
|
150
|
+
if (stmt.importKind === 'type')
|
|
151
|
+
return undefined
|
|
152
|
+
// A type specifier is erased with the types, so it stays whatever uses it.
|
|
153
|
+
const specs = stmt.specifiers.filter(s => keep.has(s.local.name) || (s.type === 'ImportSpecifier' && s.importKind === 'type'))
|
|
154
|
+
if (specs.length === stmt.specifiers.length)
|
|
155
|
+
return undefined
|
|
156
|
+
if (specs.length === 0)
|
|
157
|
+
return ''
|
|
158
|
+
if ((stmt.attributes?.length ?? 0) > 0)
|
|
159
|
+
return undefined
|
|
160
|
+
const source = code.slice(stmt.source.start, stmt.source.end)
|
|
161
|
+
return specs.map((s) => {
|
|
162
|
+
if (s.type === 'ImportDefaultSpecifier')
|
|
163
|
+
return `import ${s.local.name} from ${source};`
|
|
164
|
+
if (s.type === 'ImportNamespaceSpecifier')
|
|
165
|
+
return `import * as ${s.local.name} from ${source};`
|
|
166
|
+
return `import { ${code.slice(s.start, s.end)} } from ${source};`
|
|
167
|
+
}).join(' ')
|
|
168
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Single-executable standalone compiler (`prunelle build --compile [outfile]`)
|
|
2
|
+
// Embeds routes, plugins, prerendered HTML, and native zero-copy assets via `with { type: "file" }`.
|
|
3
|
+
|
|
4
|
+
import type { BunPlugin } from 'bun'
|
|
5
|
+
import type { BuildManifest } from './index'
|
|
6
|
+
import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { formatBunBuildLogs } from './files'
|
|
9
|
+
import { SERVER_ENTRY_FILE } from './server-entry'
|
|
10
|
+
|
|
11
|
+
export interface CompileExecutableOptions {
|
|
12
|
+
root: string
|
|
13
|
+
outDir: string
|
|
14
|
+
clientDir: string
|
|
15
|
+
manifest: BuildManifest
|
|
16
|
+
assetPrefix: string
|
|
17
|
+
site?: string | undefined
|
|
18
|
+
defaultPort?: number | undefined
|
|
19
|
+
outfile: string
|
|
20
|
+
resolvePrunelleSpecifier: (specifier: string) => string | undefined
|
|
21
|
+
bunPlugins?: BunPlugin[] | undefined
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
|
|
25
|
+
const { root, outDir, clientDir, manifest, assetPrefix, site, defaultPort, outfile, resolvePrunelleSpecifier, bunPlugins = [] } = opts
|
|
26
|
+
const entryPath = join(outDir, '__compile_entry.ts')
|
|
27
|
+
const entryJs = join(outDir, 'server', SERVER_ENTRY_FILE)
|
|
28
|
+
const lifecycle = join(import.meta.dir, '../server/lifecycle.ts')
|
|
29
|
+
const imports: string[] = []
|
|
30
|
+
|
|
31
|
+
// Embed client assets, public files and prerendered pages natively via `with { type: "file" }` (0 base64, 0 startup decode!), each with the sidecars the build compressed it into.
|
|
32
|
+
let fileIdx = 0
|
|
33
|
+
const embed = (entries: string[], rel: string, abs: string): void => {
|
|
34
|
+
for (const ext of ['', '.br', '.gz']) {
|
|
35
|
+
if (ext === '' || existsSync(`${abs}${ext}`)) {
|
|
36
|
+
const v = `_f${fileIdx++}`
|
|
37
|
+
imports.push(`import ${v} from ${JSON.stringify(`${abs}${ext}`)} with { type: "file" };`)
|
|
38
|
+
entries.push(`${JSON.stringify(`${rel}${ext}`)}: ${v}`)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const embeddedAssets: string[] = []
|
|
43
|
+
for (const rel of [...manifest.assets, ...(manifest.carriedAssets ?? [])]) {
|
|
44
|
+
const abs = join(clientDir, rel)
|
|
45
|
+
if (existsSync(abs))
|
|
46
|
+
embed(embeddedAssets, rel, abs)
|
|
47
|
+
}
|
|
48
|
+
const embeddedPublic: string[] = []
|
|
49
|
+
const embeddedPublicEtags: string[] = []
|
|
50
|
+
for (const rel of manifest.publicFiles) {
|
|
51
|
+
const abs = join(outDir, 'public', rel)
|
|
52
|
+
if (!existsSync(abs))
|
|
53
|
+
continue
|
|
54
|
+
embed(embeddedPublic, rel, abs)
|
|
55
|
+
embeddedPublicEtags.push(`${JSON.stringify(rel)}: ${JSON.stringify(`W/"${Bun.hash(readFileSync(abs)).toString(36)}"`)}`)
|
|
56
|
+
}
|
|
57
|
+
const embeddedPrerenderedFiles: string[] = []
|
|
58
|
+
const embeddedPrerenderedEtags: string[] = []
|
|
59
|
+
for (const r of manifest.routes) {
|
|
60
|
+
if (r.prerendered) {
|
|
61
|
+
for (const [, relHtml] of Object.entries(r.prerendered)) {
|
|
62
|
+
const abs = join(outDir, relHtml)
|
|
63
|
+
if (!existsSync(abs))
|
|
64
|
+
continue
|
|
65
|
+
embed(embeddedPrerenderedFiles, relHtml, abs)
|
|
66
|
+
// An embedded file has no mtime to version it by.
|
|
67
|
+
embeddedPrerenderedEtags.push(`${JSON.stringify(relHtml)}: ${JSON.stringify(`W/"${Bun.hash(readFileSync(abs)).toString(36)}"`)}`)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const siteProp = site !== undefined ? ` site: ${JSON.stringify(site)},` : ''
|
|
73
|
+
const healthPath = `${assetPrefix.replace(/\/$/, '')}/health`
|
|
74
|
+
const code = [
|
|
75
|
+
...imports,
|
|
76
|
+
`const hostname = process.env.HOST || undefined;`,
|
|
77
|
+
`const formatHost = (h: string) => h.includes(':') && !h.startsWith('[') ? \`[\${h}]\` : h;`,
|
|
78
|
+
`if (Bun.argv.includes('--health')) { const healthPort = Number(process.env.PORT || ${JSON.stringify(defaultPort ?? 3000)}); const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${healthPort}\${${JSON.stringify(healthPath)}}\`).catch(() => null); process.exit(r && r.ok ? 0 : 1); }`,
|
|
79
|
+
`const _envKey = 'NODE_ENV';`,
|
|
80
|
+
`process.env[_envKey] ??= 'production';`,
|
|
81
|
+
`const { createApp, prunelleConfig } = await import(${JSON.stringify(entryJs)});`,
|
|
82
|
+
`const { handleSignals } = await import(${JSON.stringify(lifecycle)});`,
|
|
83
|
+
`const manifest = ${JSON.stringify(manifest)};`,
|
|
84
|
+
`const assets = { ${embeddedAssets.join(', ')} };`,
|
|
85
|
+
`const publicAssets = { ${embeddedPublic.join(', ')} };`,
|
|
86
|
+
`const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
|
|
87
|
+
`const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
|
|
88
|
+
`const prerenderedEtags = { ${embeddedPrerenderedEtags.join(', ')} };`,
|
|
89
|
+
`const port = Number(process.env.PORT || prunelleConfig.port || 3000);`,
|
|
90
|
+
`const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)},${siteProp} manifest, assets, publicAssets, publicEtags, prerenderedFiles, prerenderedEtags });`,
|
|
91
|
+
`const server = app.serve(port, hostname);`,
|
|
92
|
+
`handleSignals(app, server);`,
|
|
93
|
+
`console.log(\`prunelle server listening on http://\${formatHost(hostname ?? 'localhost')}:\${server.port}\`);`,
|
|
94
|
+
].join('\n')
|
|
95
|
+
|
|
96
|
+
writeFileSync(entryPath, code)
|
|
97
|
+
try {
|
|
98
|
+
const prunelleResolvePlugin: BunPlugin = {
|
|
99
|
+
name: 'prunelle-compile-resolve',
|
|
100
|
+
setup(b) {
|
|
101
|
+
b.onResolve({ filter: /^prunelle(?:\/.*)?$/ }, (args) => {
|
|
102
|
+
const resolved = resolvePrunelleSpecifier(args.path)
|
|
103
|
+
return resolved !== undefined ? { path: resolved } : undefined
|
|
104
|
+
})
|
|
105
|
+
},
|
|
106
|
+
}
|
|
107
|
+
let res: Awaited<ReturnType<typeof Bun.build>>
|
|
108
|
+
try {
|
|
109
|
+
res = await Bun.build({
|
|
110
|
+
entrypoints: [entryPath],
|
|
111
|
+
// The host passes the environment: a .env or bunfig.toml (with its preload) in whatever cwd the binary starts in is not the app's.
|
|
112
|
+
compile: { outfile, autoloadDotenv: false, autoloadBunfig: false },
|
|
113
|
+
minify: true,
|
|
114
|
+
plugins: [prunelleResolvePlugin, ...bunPlugins],
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
118
|
+
if (err instanceof AggregateError && err.errors.length > 0)
|
|
119
|
+
throw new Error(`prunelle build: --compile failed:\n${formatBunBuildLogs(err.errors, root)}`)
|
|
120
|
+
throw err
|
|
121
|
+
}
|
|
122
|
+
if (!res.success) {
|
|
123
|
+
const msgs = formatBunBuildLogs(res.logs, root)
|
|
124
|
+
throw new Error(`prunelle build: --compile failed:\n${msgs}`)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
rmSync(entryPath, { force: true })
|
|
129
|
+
}
|
|
130
|
+
}
|