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,139 @@
|
|
|
1
|
+
// The `.br` and `.gz` sidecars of a build, and the brotli they hold, cached by content under `.prunelle-cache/` so a build pays only for the files that changed.
|
|
2
|
+
|
|
3
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
|
|
4
|
+
import { availableParallelism } from 'node:os'
|
|
5
|
+
import { basename, dirname, extname, join } from 'node:path'
|
|
6
|
+
import { promisify } from 'node:util'
|
|
7
|
+
import { brotliCompress, brotliCompressSync, constants as zlibConstants } from 'node:zlib'
|
|
8
|
+
import { getAppContext } from '../plugins/context'
|
|
9
|
+
|
|
10
|
+
/** Brotli quality of the sidecars: written once per build, downloaded by every visitor, so the smallest the encoder makes. */
|
|
11
|
+
export const BROTLI_QUALITY = 11
|
|
12
|
+
|
|
13
|
+
const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm'])
|
|
14
|
+
const STALE_MS = 7 * 86_400_000
|
|
15
|
+
|
|
16
|
+
const compress = promisify(brotliCompress)
|
|
17
|
+
const optionsFor = (data: Uint8Array) => ({ params: { [zlibConstants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY, [zlibConstants.BROTLI_PARAM_SIZE_HINT]: data.byteLength } })
|
|
18
|
+
let tmpCount = 0
|
|
19
|
+
|
|
20
|
+
/** Where the app under `root` keeps the brotli of each content a build compressed. */
|
|
21
|
+
export function brotliCacheDir(root: string): string {
|
|
22
|
+
return join(root, '.prunelle-cache', `brotli-${BROTLI_QUALITY}`)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The cache of the app being built, if any. */
|
|
26
|
+
export function appBrotliCacheDir(): string | undefined {
|
|
27
|
+
const root = getAppContext()?.root
|
|
28
|
+
return root === undefined ? undefined : brotliCacheDir(root)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function entryFile(data: Uint8Array, cacheDir: string | undefined): string | undefined {
|
|
32
|
+
return cacheDir === undefined ? undefined : join(cacheDir, new Bun.CryptoHasher('sha256').update(data).digest('hex'))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function readEntry(file: string): Buffer | undefined {
|
|
36
|
+
try {
|
|
37
|
+
const packed = readFileSync(file)
|
|
38
|
+
const now = new Date()
|
|
39
|
+
utimesSync(file, now, now)
|
|
40
|
+
return packed
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
|
|
44
|
+
return undefined
|
|
45
|
+
throw error
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Writes a self-ignoring `.gitignore` inside `.prunelle-cache/` so git never lists cached files as untracked (#39). */
|
|
50
|
+
export function ensureCacheGitignore(cacheRoot: string): void {
|
|
51
|
+
const file = join(cacheRoot, '.gitignore')
|
|
52
|
+
if (existsSync(file))
|
|
53
|
+
return
|
|
54
|
+
mkdirSync(cacheRoot, { recursive: true })
|
|
55
|
+
writeFileSync(file, '*\n')
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Renamed into place, so a build running beside this one never reads half an entry.
|
|
59
|
+
function writeEntry(file: string, packed: Uint8Array): void {
|
|
60
|
+
const dir = dirname(file)
|
|
61
|
+
mkdirSync(dir, { recursive: true })
|
|
62
|
+
const parent = dirname(dir)
|
|
63
|
+
if (basename(parent) === '.prunelle-cache')
|
|
64
|
+
ensureCacheGitignore(parent)
|
|
65
|
+
const tmp = `${file}.${process.pid}-${tmpCount++}.tmp`
|
|
66
|
+
writeFileSync(tmp, packed)
|
|
67
|
+
renameSync(tmp, file)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Brotli of `data` at `BROTLI_QUALITY`, off the main thread; with `cacheDir`, read from there when this content was compressed before. */
|
|
71
|
+
export async function brotli(data: Uint8Array, cacheDir?: string): Promise<Uint8Array> {
|
|
72
|
+
const file = entryFile(data, cacheDir)
|
|
73
|
+
const cached = file === undefined ? undefined : readEntry(file)
|
|
74
|
+
if (cached !== undefined)
|
|
75
|
+
return cached
|
|
76
|
+
const packed = await compress(data, optionsFor(data))
|
|
77
|
+
if (file !== undefined)
|
|
78
|
+
writeEntry(file, packed)
|
|
79
|
+
return packed
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** `brotli` on the main thread, for a caller that cannot wait. */
|
|
83
|
+
export function brotliSync(data: Uint8Array, cacheDir?: string): Uint8Array {
|
|
84
|
+
const file = entryFile(data, cacheDir)
|
|
85
|
+
const cached = file === undefined ? undefined : readEntry(file)
|
|
86
|
+
if (cached !== undefined)
|
|
87
|
+
return cached
|
|
88
|
+
const packed = brotliCompressSync(data, optionsFor(data))
|
|
89
|
+
if (file !== undefined)
|
|
90
|
+
writeEntry(file, packed)
|
|
91
|
+
return packed
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Bytes of `content` in brotli at the quality the sidecars are written at, from the app's cache when a build compressed it before. */
|
|
95
|
+
export async function brotliSize(content: string | Uint8Array): Promise<number> {
|
|
96
|
+
return (await brotli(typeof content === 'string' ? Buffer.from(content) : content, appBrotliCacheDir())).byteLength
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Removes the entries no build read for 7 days, and the temporary files of a build that died; returns how many went. */
|
|
100
|
+
export function pruneBrotliCache(cacheDir: string, now = Date.now()): number {
|
|
101
|
+
if (!existsSync(cacheDir))
|
|
102
|
+
return 0
|
|
103
|
+
let removed = 0
|
|
104
|
+
for (const name of readdirSync(cacheDir)) {
|
|
105
|
+
const file = join(cacheDir, name)
|
|
106
|
+
const stat = statSync(file, { throwIfNoEntry: false })
|
|
107
|
+
if (stat !== undefined && now - stat.mtimeMs > STALE_MS) {
|
|
108
|
+
rmSync(file, { force: true })
|
|
109
|
+
removed++
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return removed
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function precompressFile(abs: string, minBytes: number, cacheDir: string): Promise<void> {
|
|
116
|
+
if (!COMPRESSIBLE_EXTS.has(extname(abs).toLowerCase()))
|
|
117
|
+
return
|
|
118
|
+
const raw = readFileSync(abs)
|
|
119
|
+
if (raw.byteLength < minBytes)
|
|
120
|
+
return
|
|
121
|
+
const br = await brotli(raw, cacheDir)
|
|
122
|
+
if (br.byteLength < raw.byteLength)
|
|
123
|
+
writeFileSync(`${abs}.br`, br)
|
|
124
|
+
const gz = Bun.gzipSync(raw, { level: 9 })
|
|
125
|
+
if (gz.byteLength < raw.byteLength)
|
|
126
|
+
writeFileSync(`${abs}.gz`, gz)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Writes `.br` and `.gz` sidecars next to each compressible file of at least `minBytes`, when they come out smaller, one file per core at a time off the main thread, the brotli cached for the app under `root`. */
|
|
130
|
+
export async function precompressFiles(files: Iterable<string>, minBytes: number, root: string): Promise<void> {
|
|
131
|
+
const cacheDir = brotliCacheDir(root)
|
|
132
|
+
pruneBrotliCache(cacheDir)
|
|
133
|
+
const queue = [...files]
|
|
134
|
+
const next = async (): Promise<void> => {
|
|
135
|
+
for (let abs = queue.pop(); abs !== undefined; abs = queue.pop())
|
|
136
|
+
await precompressFile(abs, minBytes, cacheDir)
|
|
137
|
+
}
|
|
138
|
+
await Promise.all(Array.from({ length: Math.min(availableParallelism(), queue.length) }, next))
|
|
139
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Build-time rendering: routes exporting `prerender = true` (and every route in a static export) are rendered through the real server and written as HTML.
|
|
2
|
+
|
|
3
|
+
import type { PrunellePlugin } from '../plugins/index'
|
|
4
|
+
import type { RouteManifestEntry } from './manifest'
|
|
5
|
+
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { dirname, extname, resolve } from 'node:path'
|
|
7
|
+
import { prerenderOrigin } from '../server/prerendered'
|
|
8
|
+
import { inlineStyleHashes, injectMetaCsp } from '../server/security'
|
|
9
|
+
import { relPosix } from './files'
|
|
10
|
+
import { runPluginHook } from './plugin-host'
|
|
11
|
+
import { assertPathUrls } from './routes'
|
|
12
|
+
|
|
13
|
+
const CONCURRENCY = 8
|
|
14
|
+
const SLASH_EDGES_RE = /^\/|\/$/g
|
|
15
|
+
const TRAILING_SLASHES_RE = /\/+$/
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
function normalizePrerenderUrl(urlStr: string): string {
|
|
19
|
+
const pathname = new URL(urlStr, 'http://localhost').pathname
|
|
20
|
+
return pathname.length > 1 && pathname.endsWith('/') ? (pathname.replace(TRAILING_SLASHES_RE, '') || '/') : pathname
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function resolvePrerenderPath(prerenderDir: string, urlStr: string, isStatic: boolean, contentType: string | null): string {
|
|
24
|
+
const pathname = new URL(urlStr, 'http://localhost').pathname
|
|
25
|
+
const trimmed = pathname.replace(SLASH_EDGES_RE, '')
|
|
26
|
+
const lastSeg = trimmed.slice(trimmed.lastIndexOf('/') + 1)
|
|
27
|
+
const ext = extname(lastSeg).toLowerCase()
|
|
28
|
+
const isHtml = (contentType ?? '').toLowerCase().includes('text/html')
|
|
29
|
+
const preserveFile = ext !== '' && (ext === '.html' || ext === '.htm' || !isHtml)
|
|
30
|
+
const rel = pathname === '/'
|
|
31
|
+
? 'index.html'
|
|
32
|
+
: (isStatic && pathname === '/404')
|
|
33
|
+
? '404.html'
|
|
34
|
+
: preserveFile
|
|
35
|
+
? trimmed
|
|
36
|
+
: `${trimmed}/index.html`
|
|
37
|
+
const absRoot = resolve(prerenderDir)
|
|
38
|
+
const abs = resolve(absRoot, rel)
|
|
39
|
+
if (!abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
|
|
40
|
+
throw new Error(`prunelle build: prerender path "${urlStr}" escapes output directory.`)
|
|
41
|
+
return abs
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface PrerenderOptions {
|
|
45
|
+
root: string
|
|
46
|
+
outDir: string
|
|
47
|
+
assetPrefix: string
|
|
48
|
+
site?: string | undefined
|
|
49
|
+
plugins: PrunellePlugin[]
|
|
50
|
+
/** Plugins passed to `build()` itself, which the app runs with in place of its bundled config's. */
|
|
51
|
+
pluginOverride?: PrunellePlugin[] | undefined
|
|
52
|
+
isDev: boolean
|
|
53
|
+
nodeEnv?: string | undefined
|
|
54
|
+
isStatic: boolean
|
|
55
|
+
/** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
|
|
56
|
+
prerenderDir: string
|
|
57
|
+
routes: RouteManifestEntry[]
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// The build fails through the CLI, which prints only the message: the page's own error and its stack go in it.
|
|
61
|
+
export function pageFailure(head: string, error: unknown): Error {
|
|
62
|
+
if (error === undefined)
|
|
63
|
+
return new Error(`${head}.`)
|
|
64
|
+
if (!(error instanceof Error))
|
|
65
|
+
return new Error(`${head}: ${String(error)}`, { cause: error })
|
|
66
|
+
const title = `${error.name}: ${error.message}`
|
|
67
|
+
const stack = error.stack ?? ''
|
|
68
|
+
const frames = stack.startsWith(title) ? stack.slice(title.length) : `\n${stack}`
|
|
69
|
+
return new Error(`${head}: ${error.message}${frames}`, { cause: error })
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Renders every route to HTML, records `route.prerendered`, and returns the server and entry the pages were rendered with. */
|
|
73
|
+
export async function prerender(options: PrerenderOptions) {
|
|
74
|
+
const { root, outDir, prerenderDir, isStatic } = options
|
|
75
|
+
// Pages render with the runtime's own plugin instances, from the bundled config; `options.plugins` are the build's native ones.
|
|
76
|
+
const { startBuiltApp } = await import('../server/loader')
|
|
77
|
+
const pageErrors = new Map<string, unknown>()
|
|
78
|
+
const errorSink = ({ error, request }: { error: unknown, request: Request }): void => {
|
|
79
|
+
if (!pageErrors.has(request.url))
|
|
80
|
+
pageErrors.set(request.url, error)
|
|
81
|
+
}
|
|
82
|
+
const { app, entry } = await startBuiltApp({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.pluginOverride, dev: options.isDev, nodeEnv: options.nodeEnv, errorSink, prerender: true })
|
|
83
|
+
const origin = prerenderOrigin(options.site)
|
|
84
|
+
mkdirSync(prerenderDir, { recursive: true })
|
|
85
|
+
|
|
86
|
+
for (const route of options.routes) {
|
|
87
|
+
let urls: string[] = []
|
|
88
|
+
let hasPathsFn = false
|
|
89
|
+
if (!route.path.includes(':') && !route.path.includes('*')) {
|
|
90
|
+
urls = [route.path]
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
const mod = entry?.modules[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
|
|
94
|
+
if (typeof mod.paths === 'function') {
|
|
95
|
+
hasPathsFn = true
|
|
96
|
+
const returned: unknown = await mod.paths()
|
|
97
|
+
assertPathUrls(returned, route.file)
|
|
98
|
+
urls = returned
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
console.warn(`prunelle build${isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
for (const plugin of options.plugins) {
|
|
106
|
+
if (plugin.prerenderPaths !== undefined && (urls.length > 0 || hasPathsFn))
|
|
107
|
+
urls = await runPluginHook(plugin, 'prerenderPaths', () => plugin.prerenderPaths!(urls, route))
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
urls = [...new Set(urls.map(normalizePrerenderUrl))]
|
|
111
|
+
|
|
112
|
+
if (urls.length === 0) {
|
|
113
|
+
if (hasPathsFn)
|
|
114
|
+
route.prerendered = {}
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const map: Record<string, string> = {}
|
|
119
|
+
const styleHashes: Record<string, string[]> = {}
|
|
120
|
+
for (let i = 0; i < urls.length; i += CONCURRENCY) {
|
|
121
|
+
await Promise.all(urls.slice(i, i + CONCURRENCY).map(async (u) => {
|
|
122
|
+
const request = new Request(`${origin}${u}`)
|
|
123
|
+
const res = await app.handle(request)
|
|
124
|
+
const isExplicit404 = u === '/404' && res.status === 404
|
|
125
|
+
if (res.status !== 200 && !isExplicit404) {
|
|
126
|
+
if (isStatic || res.status >= 500)
|
|
127
|
+
throw pageFailure(`prunelle build: prerender route "${u}" answered HTTP ${res.status}`, pageErrors.get(request.url))
|
|
128
|
+
return
|
|
129
|
+
}
|
|
130
|
+
const ct = res.headers.get('content-type')
|
|
131
|
+
const absOut = resolvePrerenderPath(prerenderDir, u, isStatic, ct)
|
|
132
|
+
mkdirSync(dirname(absOut), { recursive: true })
|
|
133
|
+
if ((ct ?? '').toLowerCase().includes('text/html')) {
|
|
134
|
+
const html = await res.text()
|
|
135
|
+
writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
|
|
136
|
+
const hashes = inlineStyleHashes(html)
|
|
137
|
+
if (hashes.length > 0)
|
|
138
|
+
styleHashes[u] = hashes
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
writeFileSync(absOut, new Uint8Array(await res.arrayBuffer()))
|
|
142
|
+
}
|
|
143
|
+
map[u] = relPosix(isStatic ? prerenderDir : outDir, absOut)
|
|
144
|
+
}))
|
|
145
|
+
}
|
|
146
|
+
route.prerendered = map
|
|
147
|
+
route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
|
|
148
|
+
}
|
|
149
|
+
return { app, entry }
|
|
150
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// What server code may not render: props an island cannot receive, a handler or `$hydrate` on a component that is not an island, an async component outside <Suspense>. `prunelle build` and `prunelle check` both run these rules.
|
|
2
|
+
|
|
3
|
+
import type { Node } from 'oxc-parser'
|
|
4
|
+
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
5
|
+
import type { IslandPlan, StaticTag } from './islands'
|
|
6
|
+
import { isInNodeModules } from './files'
|
|
7
|
+
import { visitorKeys } from 'oxc-parser'
|
|
8
|
+
import { walk } from '../compiler/ast'
|
|
9
|
+
import { mistake } from '../compiler/mistakes'
|
|
10
|
+
import { collectPatternNames, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
|
|
11
|
+
|
|
12
|
+
const SERIALIZABLE_NEW_CTORS = new Set(['Date', 'Map', 'Set', 'URL', 'RegExp'])
|
|
13
|
+
|
|
14
|
+
type FnScope = Map<string, boolean>
|
|
15
|
+
|
|
16
|
+
function bindFnStatements(scope: FnScope, statements: readonly Node[]): void {
|
|
17
|
+
for (const stmt of statements) {
|
|
18
|
+
const decl = (stmt.type === 'ExportNamedDeclaration' || stmt.type === 'ExportDefaultDeclaration') ? stmt.declaration : stmt
|
|
19
|
+
if (decl?.type === 'VariableDeclaration') {
|
|
20
|
+
for (const d of decl.declarations) {
|
|
21
|
+
if (d.id.type === 'Identifier') {
|
|
22
|
+
const init = d.init === null ? undefined : unwrapTsExpr(d.init)
|
|
23
|
+
scope.set(d.id.name, init?.type === 'ArrowFunctionExpression' || init?.type === 'FunctionExpression')
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
const names = new Set<string>()
|
|
27
|
+
collectPatternNames(d.id, names)
|
|
28
|
+
for (const n of names)
|
|
29
|
+
scope.set(n, false)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
else if (decl?.type === 'FunctionDeclaration' && decl.id !== null) {
|
|
34
|
+
scope.set(decl.id.name, true)
|
|
35
|
+
}
|
|
36
|
+
else if (decl?.type === 'ClassDeclaration' && decl.id !== null) {
|
|
37
|
+
scope.set(decl.id.name, false)
|
|
38
|
+
}
|
|
39
|
+
else if (decl?.type === 'ImportDeclaration') {
|
|
40
|
+
for (const spec of decl.specifiers)
|
|
41
|
+
scope.set(spec.local.name, false)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function fnScopeOf(node: Node): FnScope | undefined {
|
|
47
|
+
const scope: FnScope = new Map()
|
|
48
|
+
switch (node.type) {
|
|
49
|
+
case 'Program':
|
|
50
|
+
case 'BlockStatement':
|
|
51
|
+
case 'StaticBlock':
|
|
52
|
+
bindFnStatements(scope, node.body)
|
|
53
|
+
return scope
|
|
54
|
+
case 'FunctionDeclaration':
|
|
55
|
+
case 'FunctionExpression':
|
|
56
|
+
case 'ArrowFunctionExpression': {
|
|
57
|
+
if (node.type === 'FunctionExpression' && node.id !== null)
|
|
58
|
+
scope.set(node.id.name, true)
|
|
59
|
+
const names = new Set<string>()
|
|
60
|
+
for (const param of node.params)
|
|
61
|
+
collectPatternNames(param, names)
|
|
62
|
+
for (const n of names)
|
|
63
|
+
scope.set(n, false)
|
|
64
|
+
return scope
|
|
65
|
+
}
|
|
66
|
+
case 'ForStatement':
|
|
67
|
+
case 'ForInStatement':
|
|
68
|
+
case 'ForOfStatement': {
|
|
69
|
+
const head = node.type === 'ForStatement' ? node.init : node.left
|
|
70
|
+
if (head?.type === 'VariableDeclaration')
|
|
71
|
+
bindFnStatements(scope, [head])
|
|
72
|
+
return scope
|
|
73
|
+
}
|
|
74
|
+
case 'CatchClause': {
|
|
75
|
+
const names = new Set<string>()
|
|
76
|
+
collectPatternNames(node.param, names)
|
|
77
|
+
for (const n of names)
|
|
78
|
+
scope.set(n, false)
|
|
79
|
+
return scope
|
|
80
|
+
}
|
|
81
|
+
case 'SwitchStatement':
|
|
82
|
+
for (const c of node.cases)
|
|
83
|
+
bindFnStatements(scope, c.consequent)
|
|
84
|
+
return scope
|
|
85
|
+
default:
|
|
86
|
+
return undefined
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
type Attribute = Extract<Node, { type: 'JSXOpeningElement' }>['attributes'][number]
|
|
91
|
+
|
|
92
|
+
const EVENT_PROP_RE = /^on[A-Z]/
|
|
93
|
+
|
|
94
|
+
function isFunctionValue(attr: Attribute, isLocalFn: (name: string) => boolean): boolean {
|
|
95
|
+
if (attr.type !== 'JSXAttribute' || attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
|
|
96
|
+
return false
|
|
97
|
+
const expr = unwrapTsExpr(attr.value.expression)
|
|
98
|
+
return expr.type === 'ArrowFunctionExpression' || expr.type === 'FunctionExpression' || (expr.type === 'Identifier' && isLocalFn(expr.name))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// What server code may not pass into an island: a function, JSX, or a `new` instance that does not serialize.
|
|
102
|
+
function islandPropProblems(attributes: readonly Attribute[], tag: string, command: string, isLocalFn: (name: string) => boolean): RenderProblem[] {
|
|
103
|
+
const problems: RenderProblem[] = []
|
|
104
|
+
for (const attr of attributes) {
|
|
105
|
+
if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier' || attr.name.name === 'key' || attr.name.name === '$hydrate')
|
|
106
|
+
continue
|
|
107
|
+
if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
|
|
108
|
+
continue
|
|
109
|
+
const attrName = attr.name.name
|
|
110
|
+
const expr = unwrapTsExpr(attr.value.expression)
|
|
111
|
+
if (isFunctionValue(attr, isLocalFn))
|
|
112
|
+
problems.push({ offset: attr.start, message: `${command}: cannot pass function prop "${attrName}" from a server component into island <${tag}>. Define the handler inside the island or pass serializable data.` })
|
|
113
|
+
else if (isJsxNode(expr))
|
|
114
|
+
problems.push({ offset: attr.start, message: `${command}: cannot pass JSX in prop "${attrName}" from a server component into island <${tag}>; pass it as children, which render on the server, or build it inside the island.` })
|
|
115
|
+
else if (expr.type === 'NewExpression' && expr.callee.type === 'Identifier' && !SERIALIZABLE_NEW_CTORS.has(expr.callee.name))
|
|
116
|
+
problems.push({ offset: expr.start, message: `${command}: cannot pass non-serializable \`new ${expr.callee.name}()\` prop "${attrName}" into island <${tag}>.` })
|
|
117
|
+
}
|
|
118
|
+
return problems
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// What server code may not do with a component that is not an island: hydrate it, hand it a handler it can never run, or render it async outside <Suspense>.
|
|
122
|
+
function staticTagProblems(element: Extract<Node, { type: 'JSXOpeningElement' }>, tag: string, found: StaticTag | undefined, suspended: boolean, rel: string, command: string, isLocalFn: (name: string) => boolean): RenderProblem[] {
|
|
123
|
+
const problems: RenderProblem[] = []
|
|
124
|
+
for (const attr of element.attributes) {
|
|
125
|
+
if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier')
|
|
126
|
+
continue
|
|
127
|
+
const attrName = attr.name.name
|
|
128
|
+
if (attrName === '$hydrate')
|
|
129
|
+
problems.push({ offset: attr.start, message: mistake(`$hydrate on <${tag}>`, rel, `${tag} is not an island, so it never hydrates; drop $hydrate, or give ${tag} state or handlers`).message })
|
|
130
|
+
else if (found !== undefined && EVENT_PROP_RE.test(attrName) && isFunctionValue(attr, isLocalFn))
|
|
131
|
+
problems.push({ offset: attr.start, message: `${command}: cannot pass event handler "${attrName}" to <${tag}>, which is not an island: the server renders it as HTML, so the handler never runs. Write the handler inside <${tag}>, or render <${tag}> from an island.` })
|
|
132
|
+
}
|
|
133
|
+
if (found?.async === true && !suspended)
|
|
134
|
+
problems.push({ offset: element.start, message: `${command}: async component <${tag}> must be the only child of <Suspense>, or the page fails at its first request: render it as <Suspense fallback={...}><${tag} /></Suspense>.` })
|
|
135
|
+
return problems
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** A refused render: where it is in the file, and the message after the command prefix. */
|
|
139
|
+
export interface RenderProblem { offset: number, message: string }
|
|
140
|
+
|
|
141
|
+
/** What `file`'s server code renders wrong: props an island cannot receive, `$hydrate` or a handler on a component that is not an island, and an async component outside `<Suspense>`. `command` is `prunelle build` or `prunelle check`, which prefixes the messages. */
|
|
142
|
+
export function renderProblems(analysis: ModuleAnalysis, islands: Pick<IslandPlan, 'pageBindings' | 'staticTags'>, file: string, rel: string, command: string): RenderProblem[] {
|
|
143
|
+
const islandTags = islands.pageBindings.get(file)
|
|
144
|
+
const importedStatics = islands.staticTags.get(file)
|
|
145
|
+
const problems: RenderProblem[] = []
|
|
146
|
+
// JSX inside the module's own islands runs in the browser, where any prop is fine.
|
|
147
|
+
const inIsland = (offset: number): boolean => analysis.islandSpans.some(([start, end]) => offset >= start && offset < end)
|
|
148
|
+
const scopes: FnScope[] = []
|
|
149
|
+
const isLocalFn = (name: string): boolean => {
|
|
150
|
+
for (let i = scopes.length - 1; i >= 0; i--) {
|
|
151
|
+
const found = scopes[i]!.get(name)
|
|
152
|
+
if (found !== undefined)
|
|
153
|
+
return found
|
|
154
|
+
}
|
|
155
|
+
return false
|
|
156
|
+
}
|
|
157
|
+
// A component of this file, declared at the top level outside its islands.
|
|
158
|
+
const localStatic = (tag: string): StaticTag | undefined => {
|
|
159
|
+
const binding = analysis.bindings.find(b => b.name === tag)
|
|
160
|
+
return binding !== undefined && isLocalFn(tag) && !inIsland(binding.start) ? { async: analysis.asyncLocals.has(tag) } : undefined
|
|
161
|
+
}
|
|
162
|
+
// Opening elements that are the only element child of a <Suspense>, where an async component may render.
|
|
163
|
+
const suspended = new Set<number>()
|
|
164
|
+
const visit = (node: Node): boolean | void => {
|
|
165
|
+
if (node.type === 'JSXElement' && resolvePrunelleTag(jsxTagName(node.openingElement.name), analysis.imports) === 'Suspense') {
|
|
166
|
+
const children = node.children.filter(child => child.type !== 'JSXText' || child.value.trim() !== '')
|
|
167
|
+
if (children.length === 1 && children[0]!.type === 'JSXElement')
|
|
168
|
+
suspended.add(children[0]!.openingElement.start)
|
|
169
|
+
}
|
|
170
|
+
if (node.type === 'JSXOpeningElement' && !inIsland(node.start)) {
|
|
171
|
+
const tag = jsxTagName(node.name)
|
|
172
|
+
if (islandTags?.has(tag) === true)
|
|
173
|
+
problems.push(...islandPropProblems(node.attributes, tag, command, isLocalFn))
|
|
174
|
+
else if (isComponentTag(tag))
|
|
175
|
+
problems.push(...staticTagProblems(node, tag, importedStatics?.get(tag) ?? localStatic(tag), suspended.has(node.start), rel, command, isLocalFn))
|
|
176
|
+
}
|
|
177
|
+
const scope = fnScopeOf(node)
|
|
178
|
+
if (scope === undefined)
|
|
179
|
+
return
|
|
180
|
+
scopes.push(scope)
|
|
181
|
+
for (const key of visitorKeys[node.type] ?? [])
|
|
182
|
+
walk((node as unknown as Record<string, unknown>)[key], visit)
|
|
183
|
+
scopes.pop()
|
|
184
|
+
return false
|
|
185
|
+
}
|
|
186
|
+
walk(analysis.program, visit)
|
|
187
|
+
return problems
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Offsets of the `process.env.NODE_ENV` reads of `file` the server runs: island code is left out, since its bundle inlines the value (#3681). */
|
|
191
|
+
export function serverNodeEnvReads(analysis: ModuleAnalysis, islands: Pick<IslandPlan, 'clientFiles' | 'clientKeep'>, file: string): number[] {
|
|
192
|
+
if (analysis.nodeEnvReads.length === 0 || isInNodeModules(file))
|
|
193
|
+
return []
|
|
194
|
+
if (!islands.clientFiles.has(file))
|
|
195
|
+
return analysis.nodeEnvReads
|
|
196
|
+
const keep = islands.clientKeep.get(file)
|
|
197
|
+
if (keep === undefined)
|
|
198
|
+
return []
|
|
199
|
+
const kept = analysis.bindings.filter(b => b.name === '' || keep.has(b.name))
|
|
200
|
+
return analysis.nodeEnvReads.filter(offset => !kept.some(b => offset >= b.start && offset < b.end))
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function nodeEnvWarning(rel: string): string {
|
|
204
|
+
return `prunelle compiler: process.env.NODE_ENV read in ${rel}: prunelle build does not set it, so a page it prerenders renders it unset; call nodeEnv() from prunelle/server, which returns the mode of the build or the server.`
|
|
205
|
+
}
|