prunelle 0.0.0-stage → 0.1.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/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 +106 -0
- package/src/build/client-plugin.ts +169 -0
- package/src/build/client-prune.ts +118 -0
- package/src/build/compile.ts +127 -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 +575 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +264 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +220 -0
- package/src/build/precompress.ts +126 -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 +177 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +109 -0
- package/src/cli/check.ts +334 -0
- package/src/cli/commands.ts +265 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +316 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/upgrade-names.ts +149 -0
- package/src/cli/upgrade.ts +258 -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.ts +598 -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 +394 -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 +161 -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 +234 -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-registry.ts +78 -0
- package/src/server/action.ts +475 -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 +153 -0
- package/src/server/http.ts +441 -0
- package/src/server/index.ts +616 -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/plugin-host.ts +251 -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 +79 -0
- package/src/server/router.ts +184 -0
- package/src/server/routing.ts +339 -0
- package/src/server/security.ts +323 -0
- package/src/server/serve-handlers.ts +69 -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 +301 -0
- package/src/ssr/index.ts +477 -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 +186 -0
- package/src/test/index.ts +177 -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 +8 -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 +29 -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,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 } 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, 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
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// The `--analyze` report and the `--max-js` budget: eager JS and CSS weight per route, from the manifest and the client metafile (or the chunks' own imports), and the islands behind it.
|
|
2
|
+
|
|
3
|
+
import type { ModuleGraph } from './graph'
|
|
4
|
+
import type { IslandPlan } from './islands'
|
|
5
|
+
import type { BuildManifest } from './manifest'
|
|
6
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
7
|
+
import { join, posix } from 'node:path'
|
|
8
|
+
import { relPosix } from './files'
|
|
9
|
+
import { distLocator, firstLoadUrls, measureFirstLoad, STATIC_CHUNK_IMPORT_RE } from './first-load'
|
|
10
|
+
|
|
11
|
+
export interface IslandOrigin {
|
|
12
|
+
/** The component's export name, `default` for a page or a default export. */
|
|
13
|
+
name: string
|
|
14
|
+
/** Root-relative source file. */
|
|
15
|
+
file: string
|
|
16
|
+
/** Why prunelle runs it in the browser, e.g. `uses onClick`. */
|
|
17
|
+
reason: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface RouteIsland extends IslandOrigin {
|
|
21
|
+
/** Loaded with the page, so counted in the route's eager JS. */
|
|
22
|
+
eager: boolean
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface RouteBundleMetrics {
|
|
26
|
+
path: string
|
|
27
|
+
jsRaw: number
|
|
28
|
+
jsGzip: number
|
|
29
|
+
cssRaw: number
|
|
30
|
+
cssGzip: number
|
|
31
|
+
jsFiles: number
|
|
32
|
+
cssFiles: number
|
|
33
|
+
/** Fonts the page preloads or its stylesheets declare, brotli. */
|
|
34
|
+
fonts: number
|
|
35
|
+
/** Everything a first visit fetches except the HTML (CSS, eager JS and its imports, fonts, images, icons), brotli. */
|
|
36
|
+
firstLoad: number
|
|
37
|
+
islands: RouteIsland[]
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface BundleReport {
|
|
41
|
+
routes: RouteBundleMetrics[]
|
|
42
|
+
totalJsGzip: number
|
|
43
|
+
totalCssGzip: number
|
|
44
|
+
topModules: { path: string, bytes: number }[]
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Each island chunk URL, mapped to the component it hydrates and why that component became an island. */
|
|
48
|
+
export function islandOrigins(islands: IslandPlan, islandChunks: Map<string, string>, graph: ModuleGraph, root: string): Map<string, IslandOrigin> {
|
|
49
|
+
const origins = new Map<string, IslandOrigin>()
|
|
50
|
+
for (const [key, target] of islands.targets) {
|
|
51
|
+
const url = islandChunks.get(key)
|
|
52
|
+
if (url === undefined)
|
|
53
|
+
continue
|
|
54
|
+
const analysis = graph.load(target.file)
|
|
55
|
+
const reason = target.local === undefined ? analysis.exports.get(target.exportName)?.reason : analysis.localIslands.get(target.local)?.reason
|
|
56
|
+
origins.set(url, { name: target.local ?? target.exportName, file: relPosix(root, target.file), reason: reason ?? 'is interactive' })
|
|
57
|
+
}
|
|
58
|
+
return origins
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function analyzeBundleWeights(
|
|
62
|
+
manifest: BuildManifest,
|
|
63
|
+
clientDir: string,
|
|
64
|
+
assetPrefix = '/_pru',
|
|
65
|
+
metafile?: Bun.BuildOutput['metafile'],
|
|
66
|
+
origins = new Map<string, IslandOrigin>(),
|
|
67
|
+
publicDirs: readonly string[] = [],
|
|
68
|
+
): BundleReport {
|
|
69
|
+
const locate = distLocator({ clientDir, assetPrefix, publicDirs })
|
|
70
|
+
const prefix = `${assetPrefix.replace(/\/$/, '')}/`
|
|
71
|
+
const sizeCache = new Map<string, { raw: number, gzip: number }>()
|
|
72
|
+
|
|
73
|
+
const getSize = (url: string): { raw: number, gzip: number } => {
|
|
74
|
+
const cached = sizeCache.get(url)
|
|
75
|
+
if (cached !== undefined)
|
|
76
|
+
return cached
|
|
77
|
+
if (!url.startsWith(prefix))
|
|
78
|
+
return { raw: 0, gzip: 0 }
|
|
79
|
+
const abs = join(clientDir, url.slice(prefix.length))
|
|
80
|
+
if (!existsSync(abs))
|
|
81
|
+
return { raw: 0, gzip: 0 }
|
|
82
|
+
const buf = readFileSync(abs)
|
|
83
|
+
const entry = { raw: buf.byteLength, gzip: Bun.gzipSync(buf, { level: 9 }).byteLength }
|
|
84
|
+
sizeCache.set(url, entry)
|
|
85
|
+
return entry
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Collect transitive JS chunk imports from metafile so eager JS includes shared runtime chunks!
|
|
89
|
+
const jsDeps = new Map<string, string[]>()
|
|
90
|
+
const moduleBytes = new Map<string, number>()
|
|
91
|
+
if (metafile !== undefined) {
|
|
92
|
+
for (const [outKey, info] of Object.entries(metafile.outputs)) {
|
|
93
|
+
const rel = outKey.replace(/^\.\//, '')
|
|
94
|
+
const url = `${prefix}${rel}`
|
|
95
|
+
if (rel.endsWith('.js')) {
|
|
96
|
+
const deps: string[] = []
|
|
97
|
+
for (const imp of info.imports ?? []) {
|
|
98
|
+
if (imp.kind === 'import-statement')
|
|
99
|
+
deps.push(`${prefix}${imp.path.replace(/^\.\//, '')}`)
|
|
100
|
+
}
|
|
101
|
+
jsDeps.set(url, deps)
|
|
102
|
+
}
|
|
103
|
+
for (const [inPath, inInfo] of Object.entries(info.inputs ?? {}))
|
|
104
|
+
moduleBytes.set(inPath, (moduleBytes.get(inPath) ?? 0) + inInfo.bytesInOutput)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Without the metafile, a chunk's static imports are read from the emitted file itself.
|
|
109
|
+
const depsOf = (url: string): readonly string[] => {
|
|
110
|
+
const known = jsDeps.get(url)
|
|
111
|
+
if (known !== undefined || metafile !== undefined || !url.startsWith(prefix))
|
|
112
|
+
return known ?? []
|
|
113
|
+
const abs = join(clientDir, url.slice(prefix.length))
|
|
114
|
+
const deps = existsSync(abs) ? [...readFileSync(abs, 'utf8').matchAll(STATIC_CHUNK_IMPORT_RE)].map(m => posix.join(posix.dirname(url), m[1]!)) : []
|
|
115
|
+
jsDeps.set(url, deps)
|
|
116
|
+
return deps
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
|
|
120
|
+
const seen = new Set<string>()
|
|
121
|
+
const stack = [...urls]
|
|
122
|
+
while (stack.length > 0) {
|
|
123
|
+
const cur = stack.pop()!
|
|
124
|
+
if (seen.has(cur))
|
|
125
|
+
continue
|
|
126
|
+
seen.add(cur)
|
|
127
|
+
for (const dep of depsOf(cur))
|
|
128
|
+
stack.push(dep)
|
|
129
|
+
}
|
|
130
|
+
return seen
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const routes: RouteBundleMetrics[] = manifest.routes.map((r) => {
|
|
134
|
+
const eagerJsRoots: string[] = []
|
|
135
|
+
if ((r.islandChunks.length > 0 || manifest.runtimeOnEveryPage === true) && manifest.runtimeScript !== undefined)
|
|
136
|
+
eagerJsRoots.push(manifest.runtimeScript)
|
|
137
|
+
if (r.usesRegion === true && manifest.regionScript !== undefined)
|
|
138
|
+
eagerJsRoots.push(manifest.regionScript)
|
|
139
|
+
const eager = r.eagerIslandChunks ?? r.islandChunks
|
|
140
|
+
for (const c of eager)
|
|
141
|
+
eagerJsRoots.push(c)
|
|
142
|
+
const islands: RouteIsland[] = []
|
|
143
|
+
for (const chunk of r.islandChunks) {
|
|
144
|
+
const origin = origins.get(chunk)
|
|
145
|
+
if (origin !== undefined)
|
|
146
|
+
islands.push({ ...origin, eager: eager.includes(chunk) })
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const jsSet = collectTransitiveJs(eagerJsRoots)
|
|
150
|
+
let jsRaw = 0
|
|
151
|
+
let jsGzip = 0
|
|
152
|
+
for (const u of jsSet) {
|
|
153
|
+
const s = getSize(u)
|
|
154
|
+
jsRaw += s.raw
|
|
155
|
+
jsGzip += s.gzip
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const cssList = r.styles ?? manifest.styles
|
|
159
|
+
let cssRaw = 0
|
|
160
|
+
let cssGzip = 0
|
|
161
|
+
for (const u of cssList) {
|
|
162
|
+
const s = getSize(u)
|
|
163
|
+
cssRaw += s.raw
|
|
164
|
+
cssGzip += s.gzip
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const headUrls = firstLoadUrls([...manifest.headTags ?? [], ...r.headTags ?? []].join(''))
|
|
168
|
+
const load = measureFirstLoad([...cssList, ...eagerJsRoots, ...headUrls], locate)
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
path: r.path,
|
|
172
|
+
fonts: load.fonts,
|
|
173
|
+
firstLoad: load.total,
|
|
174
|
+
jsRaw,
|
|
175
|
+
jsGzip,
|
|
176
|
+
cssRaw,
|
|
177
|
+
cssGzip,
|
|
178
|
+
jsFiles: jsSet.size,
|
|
179
|
+
cssFiles: cssList.length,
|
|
180
|
+
islands,
|
|
181
|
+
}
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
let totalJsGzip = 0
|
|
185
|
+
let totalCssGzip = 0
|
|
186
|
+
for (const rel of manifest.assets) {
|
|
187
|
+
const s = getSize(`${prefix}${rel}`)
|
|
188
|
+
if (rel.endsWith('.js'))
|
|
189
|
+
totalJsGzip += s.gzip
|
|
190
|
+
else if (rel.endsWith('.css'))
|
|
191
|
+
totalCssGzip += s.gzip
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const topModules = [...moduleBytes.entries()]
|
|
195
|
+
.map(([path, bytes]) => ({ path, bytes }))
|
|
196
|
+
.sort((a, b) => b.bytes - a.bytes)
|
|
197
|
+
.slice(0, 10)
|
|
198
|
+
|
|
199
|
+
return { routes, totalJsGzip, totalCssGzip, topModules }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const kb = (b: number): string => `${(b / 1024).toFixed(2)} KB`
|
|
203
|
+
const islandLine = (island: RouteIsland): string => `${island.name} (${island.file}) ${island.reason}`
|
|
204
|
+
|
|
205
|
+
export function formatBundleReport(report: BundleReport): string {
|
|
206
|
+
const lines = [
|
|
207
|
+
'\n=== PRUNELLE BUNDLE WEIGHT REPORT ===',
|
|
208
|
+
`Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
|
|
209
|
+
'',
|
|
210
|
+
'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Fonts (br)'.padStart(14) + 'First load (br)'.padStart(18) + 'Files'.padStart(10),
|
|
211
|
+
]
|
|
212
|
+
for (const r of report.routes) {
|
|
213
|
+
lines.push(
|
|
214
|
+
r.path.padEnd(28)
|
|
215
|
+
+ kb(r.jsGzip).padStart(16)
|
|
216
|
+
+ kb(r.cssGzip).padStart(14)
|
|
217
|
+
+ kb(r.fonts).padStart(14)
|
|
218
|
+
+ kb(r.firstLoad).padStart(18)
|
|
219
|
+
+ `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
|
|
220
|
+
)
|
|
221
|
+
for (const island of r.islands)
|
|
222
|
+
lines.push(` ${island.eager ? 'island' : 'island, deferred'}: ${islandLine(island)}`)
|
|
223
|
+
}
|
|
224
|
+
lines.push('', 'First load is what a first visit downloads besides the page\'s HTML: CSS, eager JS and its imports, fonts, images and icons, brotli.')
|
|
225
|
+
if (report.topModules.length > 0) {
|
|
226
|
+
lines.push('', 'Top modules (minified output bytes):')
|
|
227
|
+
for (const m of report.topModules.slice(0, 8))
|
|
228
|
+
lines.push(` ${kb(m.bytes).padStart(9)} ${m.path}`)
|
|
229
|
+
}
|
|
230
|
+
return lines.join('\n')
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function formatBundleReportJson(report: BundleReport): string {
|
|
234
|
+
return JSON.stringify(report, null, 2)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Throws naming each route whose eager JS, gzipped, is over `maxBytes`, with the islands it loads with the page. */
|
|
238
|
+
export function checkJsBudget(report: BundleReport, maxBytes: number): void {
|
|
239
|
+
const over = report.routes.filter(r => r.jsGzip > maxBytes)
|
|
240
|
+
if (over.length === 0)
|
|
241
|
+
return
|
|
242
|
+
const lines = over.map((r) => {
|
|
243
|
+
const eager = r.islands.filter(island => island.eager).map(islandLine)
|
|
244
|
+
return ` ${r.path} ships ${kb(r.jsGzip)} of eager JS: ${eager.length > 0 ? eager.join('; ') : 'the prunelle runtime alone'}`
|
|
245
|
+
})
|
|
246
|
+
throw new Error(`prunelle build: eager JS over --max-js ${kb(maxBytes)} (gzip) on ${over.length === 1 ? 'one route' : `${over.length} routes`}:\n${lines.join('\n')}\nDefer an island with export const hydrate = 'visible', move its state into fewer components, or raise --max-js.`)
|
|
247
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Resolves an import the way prunelle build follows it: relative files, then packages through Bun's resolver; prunelle, node:, bun and ~ aliases stay unresolved.
|
|
2
|
+
|
|
3
|
+
import { statSync } from 'node:fs'
|
|
4
|
+
import { dirname, join, resolve } from 'node:path'
|
|
5
|
+
import pkg from '../../package.json' with { type: 'json' }
|
|
6
|
+
|
|
7
|
+
export const PRUNELLE_SRC_ROOT = resolve(import.meta.dir, '..')
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
export function resolveImportPath(fromFile: string, specifier: string): string | undefined {
|
|
11
|
+
if (specifier.startsWith('.')) {
|
|
12
|
+
const base = resolve(dirname(fromFile), specifier)
|
|
13
|
+
const candidates = [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]
|
|
14
|
+
for (const c of candidates) {
|
|
15
|
+
if (statSync(c, { throwIfNoEntry: false })?.isFile())
|
|
16
|
+
return c
|
|
17
|
+
}
|
|
18
|
+
return undefined
|
|
19
|
+
}
|
|
20
|
+
if (
|
|
21
|
+
specifier === 'prunelle'
|
|
22
|
+
|| specifier.startsWith('prunelle/')
|
|
23
|
+
|| specifier.startsWith('node:')
|
|
24
|
+
|| specifier === 'bun'
|
|
25
|
+
|| specifier.startsWith('bun:')
|
|
26
|
+
|| specifier.startsWith('~')
|
|
27
|
+
) {
|
|
28
|
+
return undefined
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
const resolved = Bun.resolveSync(specifier, dirname(fromFile))
|
|
32
|
+
return resolved.endsWith('.tsx') || resolved.endsWith('.ts') ? resolved : undefined
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const PRUNELLE_SPECIFIER_FILES = new Map<string, string>(
|
|
40
|
+
Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
|
|
41
|
+
subpath === '.' ? 'prunelle' : `prunelle/${subpath.slice(2)}`,
|
|
42
|
+
target.replace(/^\.\/src\//, ''),
|
|
43
|
+
]),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
/** Maps `prunelle` and its subpaths to their source file. */
|
|
47
|
+
export function resolvePrunelleSpecifier(specifier: string): string | undefined {
|
|
48
|
+
const file = PRUNELLE_SPECIFIER_FILES.get(specifier)
|
|
49
|
+
return file === undefined ? undefined : join(PRUNELLE_SRC_ROOT, file)
|
|
50
|
+
}
|