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.
Files changed (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,661 @@
1
+ // The two Bun.build passes: the client (runtime + island chunks + standalone CSS) and the server (routes compiled for SSR).
2
+
3
+ import type { BunPlugin, PluginBuilder } from 'bun'
4
+ import type { IslandBinding } from '../compiler/index'
5
+ import type { BuildPluginTarget, PrunellePlugin } from '../plugins/index'
6
+ import type { ClientTransforms } from './client-plugin'
7
+ import type { BuildCache, ModuleGraph } from './graph'
8
+ import type { ActionsByFile, IslandPlan } from './islands'
9
+ import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, realpathSync, writeFileSync } from 'node:fs'
10
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
11
+ import { compileSsr } from '../compiler/index'
12
+ import { readsPrivateEnv } from '../compiler/server-only'
13
+ import { clientPlugin, PRUNELLE_SPECIFIER_FILTER, localIslandExports, TS_FILTER } from './client-plugin'
14
+ import { formatBunBuildLogs, isInNodeModules, isTsFile, relPosix } from './files'
15
+ import { isInside } from './is-inside'
16
+ import { stampFiles, stampsMatch } from './graph'
17
+ import { entryStaticImports, hydrateStrategies, writeClientEntries } from './client-entries'
18
+ import { clientLeakError, islandKey } from './islands'
19
+ import { pluginHookError } from './plugin-host'
20
+ import { ensureCacheGitignore } from './precompress'
21
+ import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
22
+
23
+ export interface BundleEnv {
24
+ root: string
25
+ outDir: string
26
+ clientDir: string
27
+ serverDir: string
28
+ assetPrefix: string
29
+ /** `lang` from the config, handed to plugin `bunPlugins` factories. */
30
+ lang?: string | undefined
31
+ minify: boolean
32
+ isDev: boolean
33
+ nodeEnv?: string | undefined
34
+ analyze?: boolean | undefined
35
+ graph: ModuleGraph
36
+ cache: BuildCache | undefined
37
+ plugins: PrunellePlugin[]
38
+ actionsByFile: ActionsByFile
39
+ islands: IslandPlan
40
+ }
41
+
42
+ export function linkOrCopyFile(src: string, dst: string): void {
43
+ mkdirSync(dirname(dst), { recursive: true })
44
+ try {
45
+ linkSync(src, dst)
46
+ }
47
+ catch {
48
+ copyFileSync(src, dst)
49
+ }
50
+ }
51
+
52
+ const prunedClientCss = new WeakMap<BuildCache, Map<string, Uint8Array>>()
53
+
54
+ /** Keeps intermediate CSS bytes pruned by stylesheet consolidation so the next `buildClient` cache hit can restore them before consolidating again. */
55
+ export function setPrunedClientCss(cache: BuildCache | undefined, files: Map<string, Uint8Array>): void {
56
+ if (cache === undefined)
57
+ return
58
+ if (files.size > 0)
59
+ prunedClientCss.set(cache, files)
60
+ else
61
+ prunedClientCss.delete(cache)
62
+ }
63
+
64
+ function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly string[], fallbackFiles?: ReadonlyMap<string, Uint8Array>): boolean {
65
+ if (!existsSync(srcDir))
66
+ return false
67
+ if (relFiles !== undefined) {
68
+ for (const rel of relFiles) {
69
+ const from = join(srcDir, rel)
70
+ const to = join(dstDir, rel)
71
+ if (existsSync(from)) {
72
+ linkOrCopyFile(from, to)
73
+ continue
74
+ }
75
+ const bytes = fallbackFiles?.get(rel)
76
+ if (bytes === undefined)
77
+ return false
78
+ mkdirSync(dirname(to), { recursive: true })
79
+ writeFileSync(to, bytes)
80
+ }
81
+ return true
82
+ }
83
+ let count = 0
84
+ for (const ent of readdirSync(srcDir, { recursive: true, withFileTypes: true })) {
85
+ if (!ent.isFile())
86
+ continue
87
+ const from = join(ent.parentPath, ent.name)
88
+ const rel = relative(srcDir, from)
89
+ linkOrCopyFile(from, join(dstDir, rel))
90
+ count++
91
+ }
92
+ return count > 0
93
+ }
94
+
95
+ const PRUNELLE_SCOPE_RE = /^@prunellejs\//
96
+ const LEADING_DOT_SLASH_RE = /^\.\//
97
+ const EXTERNAL_PRUNELLE_SPECIFIERS = new Set(['prunelle/build', 'prunelle/test'])
98
+
99
+ export function pluginBunPlugins(env: Pick<BundleEnv, 'plugins' | 'root' | 'assetPrefix' | 'minify' | 'lang'>, target: BuildPluginTarget): BunPlugin[] {
100
+ const { root, assetPrefix, minify, lang } = env
101
+ return env.plugins.flatMap((p) => {
102
+ const bp = p.bunPlugins
103
+ return typeof bp === 'function' ? bp({ root, assetPrefix, minify, target, lang }) : bp ?? []
104
+ })
105
+ }
106
+
107
+ /** Plugin `transform` hooks, applied in order to every module the bundles load. The first throw is kept in `failure`, since Bun turns it into a log line. */
108
+ function pluginTransforms(plugins: PrunellePlugin[]): ClientTransforms {
109
+ const list = plugins.filter(p => typeof p.transform === 'function')
110
+ const transforms: ClientTransforms = {
111
+ active: list.length > 0,
112
+ key: list.map(p => p.name).join(','),
113
+ failure: undefined,
114
+ apply(code, id, target) {
115
+ let cur = code
116
+ for (const plugin of list) {
117
+ let next: string | void
118
+ try {
119
+ next = plugin.transform!(cur, id, target)
120
+ }
121
+ catch (error) {
122
+ transforms.failure ??= pluginHookError(plugin, 'transform', error)
123
+ throw transforms.failure
124
+ }
125
+ if (typeof next === 'string')
126
+ cur = next
127
+ }
128
+ return cur
129
+ },
130
+ }
131
+ return transforms
132
+ }
133
+
134
+ /** Runs Bun.build, failing first with what `ownFailure` throws (a leak, a plugin hook), then with Bun's own logs. */
135
+ async function runBunBuild(side: 'client' | 'server', root: string, ownFailure: () => void, config: Parameters<typeof Bun.build>[0]): Promise<Awaited<ReturnType<typeof Bun.build>>> {
136
+ let result: Awaited<ReturnType<typeof Bun.build>>
137
+ try {
138
+ result = await Bun.build(config)
139
+ }
140
+ catch (err) {
141
+ ownFailure()
142
+ if (err instanceof AggregateError && err.errors.length > 0)
143
+ throw new Error(`prunelle build (${side}) failed:\n${formatBunBuildLogs(err.errors, root)}`)
144
+ throw err
145
+ }
146
+ ownFailure()
147
+ if (!result.success)
148
+ throw new Error(`prunelle build (${side}) failed:\n${formatBunBuildLogs(result.logs, root)}`)
149
+ return result
150
+ }
151
+
152
+ /** CSS files imported outside islands (plus the plugins' own), built as standalone stylesheets. */
153
+ export function standaloneCssFiles(graph: ModuleGraph, pluginCss: string[], islandCss: Set<string>): string[] {
154
+ const out = new Set(pluginCss)
155
+ for (const [file, analysis] of graph.analyses) {
156
+ for (const { source } of [...analysis.imports, ...analysis.reexports]) {
157
+ const target = graph.resolve(file, source)
158
+ if (target !== undefined && target.endsWith('.css') && !islandCss.has(target))
159
+ out.add(target)
160
+ }
161
+ }
162
+ return [...out]
163
+ }
164
+
165
+ export interface ClientBuild {
166
+ /** Island key to the URL of its chunk. */
167
+ islandChunks: Map<string, string>
168
+ srcCssToUrl: Map<string, string>
169
+ /** Island key to the URL of the CSS bundled with it. */
170
+ islandCssUrl: Map<string, string>
171
+ /** Emitted files, relative to the client dir. */
172
+ assetFiles: string[]
173
+ styleUrls: string[]
174
+ runtimeScript: string | undefined
175
+ regionScript: string | undefined
176
+ /** The prop revivers, which the loader imports for an island whose props hold a Date, Map, Set or another tagged value. */
177
+ reviveScript: string | undefined
178
+ /** Entry URL to the chunks it imports statically, transitively, for the page's preloads. */
179
+ chunkImports: Record<string, string[]>
180
+ metafile: Bun.BuildOutput['metafile']
181
+ }
182
+
183
+ /** Builds the prop revivers on their own, so the loader names the file through `PRUNELLE_REVIVE` and imports it only for the props that need it. */
184
+ async function buildReviver(env: BundleEnv): Promise<{ url: string, file: string }> {
185
+ const built = await runBunBuild('client', env.root, () => {}, {
186
+ entrypoints: [join(PRUNELLE_SRC_ROOT, 'dom/revive.ts')],
187
+ outdir: env.clientDir,
188
+ target: 'browser',
189
+ format: 'esm',
190
+ minify: env.minify,
191
+ naming: '[name]-[hash].[ext]',
192
+ })
193
+ const file = relPosix(env.clientDir, built.outputs[0]!.path)
194
+ return { url: `${env.assetPrefix}/${file}`, file }
195
+ }
196
+
197
+ function publicEnvDefines(): Record<string, string> {
198
+ const defines: Record<string, string> = {}
199
+ for (const [key, value] of Object.entries(process.env)) {
200
+ if (key.startsWith('PUBLIC_') && value !== undefined)
201
+ defines[`process.env.${key}`] = JSON.stringify(value)
202
+ }
203
+ return defines
204
+ }
205
+
206
+
207
+ function buildClientSignature(
208
+ env: BundleEnv,
209
+ standaloneCss: readonly string[],
210
+ pluginClientEntries: readonly string[],
211
+ regionClientEntries: readonly string[],
212
+ transformsKey: string,
213
+ strategies: ReturnType<typeof hydrateStrategies>['strategies'],
214
+ hasClientOnlyHydrate: boolean,
215
+ envDefines: Readonly<Record<string, string>>,
216
+ ): string {
217
+ if (env.cache === undefined)
218
+ return ''
219
+ return JSON.stringify({
220
+ minify: env.minify,
221
+ assetPrefix: env.assetPrefix, lang: env.lang,
222
+ isDev: env.isDev,
223
+ nodeEnv: env.nodeEnv ?? (env.isDev ? 'development' : 'production'),
224
+ transforms: transformsKey,
225
+ strategies,
226
+ hasClientOnlyHydrate,
227
+ pluginClientEntries,
228
+ regionClientEntries,
229
+ standaloneCss: [...standaloneCss].sort(),
230
+ islands: [...env.islands.targets.entries()]
231
+ .sort(([a], [b]) => a.localeCompare(b))
232
+ .map(([k, t]) => [k, t.id, t.file, t.exportName, t.defaultHydrate ?? '']),
233
+ actions: [...env.actionsByFile.entries()]
234
+ .sort(([a], [b]) => a.localeCompare(b))
235
+ .map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
236
+ envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
237
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
238
+ })
239
+ }
240
+
241
+ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Promise<ClientBuild> {
242
+ const { root, clientDir, assetPrefix, graph, cache, actionsByFile, islands } = env
243
+ const result: ClientBuild = {
244
+ islandChunks: new Map(),
245
+ srcCssToUrl: new Map(),
246
+ islandCssUrl: new Map(),
247
+ assetFiles: [],
248
+ styleUrls: [],
249
+ runtimeScript: undefined,
250
+ regionScript: undefined,
251
+ reviveScript: undefined,
252
+ chunkImports: {},
253
+ metafile: undefined,
254
+ }
255
+ const pluginClientEntries = env.plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
256
+ const regionClientEntries = env.plugins.map(p => p.regionClientEntry).filter((e): e is string => Boolean(e))
257
+ if (islands.targets.size === 0 && pluginClientEntries.length === 0 && regionClientEntries.length === 0 && standaloneCss.length === 0) {
258
+ if (cache !== undefined) {
259
+ cache.lastClient = undefined
260
+ prunedClientCss.delete(cache)
261
+ }
262
+ return result
263
+ }
264
+
265
+ const transforms = pluginTransforms(env.plugins)
266
+ const { strategies, hasClientOnlyHydrate } = hydrateStrategies(graph.analyses.values())
267
+
268
+ const envDefines = publicEnvDefines()
269
+ const clientSignature = buildClientSignature(env, standaloneCss, pluginClientEntries, regionClientEntries, transforms.key, strategies, hasClientOnlyHydrate, envDefines)
270
+
271
+ if (
272
+ cache !== undefined
273
+ && !env.analyze
274
+ && cache.lastClient !== undefined
275
+ && cache.lastClient.signature === clientSignature
276
+ && stampsMatch(cache.lastClient.inputStamps)
277
+ && reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles, prunedClientCss.get(cache))
278
+ ) {
279
+ cache.stats.clientSkips++
280
+ cache.lastClient.clientDir = clientDir
281
+ return {
282
+ islandChunks: new Map(cache.lastClient.islandChunks),
283
+ srcCssToUrl: new Map(cache.lastClient.srcCssToUrl),
284
+ islandCssUrl: new Map(cache.lastClient.islandCssUrl),
285
+ assetFiles: [...cache.lastClient.assetFiles],
286
+ styleUrls: [...cache.lastClient.styleUrls],
287
+ runtimeScript: cache.lastClient.runtimeScript,
288
+ regionScript: cache.lastClient.regionScript,
289
+ reviveScript: cache.lastClient.reviveScript,
290
+ chunkImports: cache.lastClient.chunkImports,
291
+ metafile: undefined,
292
+ }
293
+ }
294
+
295
+ // Bun hashes an entry's path into its chunk name, so the entries sit at one path per app: a dev rebuild or a static stage then keeps every unchanged chunk name.
296
+ const entriesDir = join(root, '.prunelle-cache/entries')
297
+ mkdirSync(entriesDir, { recursive: true })
298
+ ensureCacheGitignore(dirname(entriesDir))
299
+ const { entryPoints, islandEntryToKey, runtimeEntryPath, regionEntryPath } = writeClientEntries(env, entriesDir, { pluginClientEntries, regionClientEntries, hasClientOnlyHydrate, standaloneCss })
300
+
301
+ const clientLeaks = new Set<string>()
302
+ const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
303
+ const plugin = clientPlugin({ root, isDev: env.isDev, graph, cache, actionsByFile, transforms, leaks: clientLeaks, localExports: localIslandExports(islands.targets.values()), clientKeep: islands.clientKeep })
304
+ const reviver = islands.targets.size > 0 ? await buildReviver(env) : undefined
305
+
306
+ const clientResult = await runBunBuild('client', env.root, () => {
307
+ if (clientLeaks.size > 0)
308
+ throw clientLeakError(clientLeaks)
309
+ if (transforms.failure !== undefined)
310
+ throw transforms.failure
311
+ }, {
312
+ entrypoints: entryPoints,
313
+ outdir: clientDir,
314
+ target: 'browser',
315
+ format: 'esm',
316
+ splitting: true,
317
+ minify: env.minify,
318
+ metafile: true,
319
+ naming: '[name]-[hash].[ext]',
320
+ external: reviver === undefined ? [] : [reviver.url],
321
+ define: {
322
+ ...(reviver === undefined ? {} : { PRUNELLE_REVIVE: JSON.stringify(reviver.url) }),
323
+ PRUNELLE_VISIBLE: String(strategies.visible),
324
+ PRUNELLE_IDLE: String(strategies.idle),
325
+ PRUNELLE_INTERACTION: String(strategies.interaction),
326
+ PRUNELLE_MEDIA: String(strategies.media),
327
+ PRUNELLE_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
328
+ PRUNELLE_BROWSER: 'true',
329
+ 'process.env.NODE_ENV': JSON.stringify(env.nodeEnv ?? (env.isDev ? 'development' : 'production')),
330
+ ...envDefines,
331
+ },
332
+ plugins: [plugin, ...pluginBunPlugins(env, 'client')],
333
+ })
334
+
335
+ const { metafile } = clientResult
336
+ result.metafile = metafile
337
+ const metaPaths = new Map<string, string>()
338
+ const resolveMetaPath = (p: string): string => {
339
+ let abs = metaPaths.get(p)
340
+ if (abs === undefined) {
341
+ const fromCwd = resolve(process.cwd(), p)
342
+ abs = existsSync(fromCwd) || islandEntryToKey.has(fromCwd) || fromCwd === runtimeEntryPath || fromCwd === regionEntryPath ? fromCwd : resolve(clientDir, p)
343
+ metaPaths.set(p, abs)
344
+ }
345
+ return abs
346
+ }
347
+
348
+ // A process.env or Bun.env left in a chunk is a key the build did not inline: name the app module that put it there.
349
+ for (const output of clientResult.outputs) {
350
+ if (!output.path.endsWith('.js'))
351
+ continue
352
+ const js = await output.text()
353
+ if (!js.includes('process.env') && !js.includes('Bun.env'))
354
+ continue
355
+ const relFile = relPosix(clientDir, output.path)
356
+ const info = metafile?.outputs[relFile] ?? metafile?.outputs[`./${relFile}`]
357
+ for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
358
+ if (input.bytesInOutput <= 0)
359
+ continue
360
+ const abs = resolveMetaPath(inKey)
361
+ let program = graph.analyses.get(abs)?.program
362
+ if (program === undefined && existsSync(abs) && isTsFile(abs) && !isInNodeModules(abs))
363
+ program = graph.load(abs).program
364
+ if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
365
+ clientLeaks.add(`${relPosix(root, abs)} reads process.env or Bun.env (only a process.env.PUBLIC_* set at build time is inlined)`)
366
+ }
367
+ }
368
+ if (clientLeaks.size > 0)
369
+ throw clientLeakError(clientLeaks)
370
+
371
+ for (const [outKey, info] of Object.entries(metafile?.outputs ?? {})) {
372
+ const relOut = outKey.replace(LEADING_DOT_SLASH_RE, '')
373
+ const url = `${assetPrefix}/${relOut}`
374
+ const entry = info.entryPoint === undefined ? undefined : resolveMetaPath(info.entryPoint)
375
+ if (entry !== undefined && entry === runtimeEntryPath && relOut.endsWith('.js'))
376
+ result.runtimeScript = url
377
+ if (entry !== undefined && entry === regionEntryPath && relOut.endsWith('.js'))
378
+ result.regionScript = url
379
+ const entryKey = entry === undefined ? undefined : islandEntryToKey.get(entry)
380
+ if (entryKey !== undefined && relOut.endsWith('.js'))
381
+ result.islandChunks.set(entryKey, url)
382
+ if (relOut.endsWith('.css')) {
383
+ if (entry?.endsWith('.css'))
384
+ result.srcCssToUrl.set(entry, url)
385
+ for (const inKey of Object.keys(info.inputs ?? {})) {
386
+ if (inKey.endsWith('.css'))
387
+ result.srcCssToUrl.set(resolveMetaPath(inKey), url)
388
+ }
389
+ }
390
+ const cssBundle = (info as { cssBundle?: string }).cssBundle
391
+ if (cssBundle !== undefined && entryKey !== undefined)
392
+ result.islandCssUrl.set(entryKey, `${assetPrefix}/${cssBundle.replace(LEADING_DOT_SLASH_RE, '')}`)
393
+ }
394
+
395
+ recordClientFiles(result, clientResult.outputs, env, reviver)
396
+
397
+ if (cache !== undefined)
398
+ rememberClientBuild(cache, result, { signature: clientSignature, clientDir, inputFiles: [...standaloneCss, ...pluginClientEntries, ...regionClientEntries], entriesDir, actionsByFile, graph, resolveMetaPath })
399
+ return result
400
+ }
401
+
402
+ /** The emitted files, the stylesheets, each entry's static imports and the revivers, into the client build's result. */
403
+ function recordClientFiles(result: ClientBuild, outputs: readonly Bun.BuildArtifact[], env: BundleEnv, reviver: { url: string, file: string } | undefined): void {
404
+ for (const output of outputs) {
405
+ const relFile = relPosix(env.clientDir, output.path)
406
+ result.assetFiles.push(relFile)
407
+ if (relFile.endsWith('.css'))
408
+ result.styleUrls.push(`${env.assetPrefix}/${relFile}`)
409
+ }
410
+ result.chunkImports = entryStaticImports(result.metafile, env.assetPrefix)
411
+ if (reviver !== undefined) {
412
+ result.reviveScript = reviver.url
413
+ result.assetFiles.push(reviver.file)
414
+ }
415
+ }
416
+
417
+ /** Keeps what a client build produced, so the next build with the same signature and unchanged inputs reuses its files. */
418
+ function rememberClientBuild(
419
+ cache: BuildCache,
420
+ result: ClientBuild,
421
+ options: { signature: string, clientDir: string, inputFiles: string[], entriesDir: string, actionsByFile: ActionsByFile, graph: ModuleGraph, resolveMetaPath: (p: string) => string },
422
+ ): void {
423
+ const { signature, clientDir, entriesDir, actionsByFile, graph, resolveMetaPath } = options
424
+ cache.stats.clientBuilds++
425
+ prunedClientCss.delete(cache)
426
+ const inputFiles = new Set<string>(options.inputFiles)
427
+ for (const inKey of Object.keys(result.metafile?.inputs ?? {})) {
428
+ const abs = resolveMetaPath(inKey)
429
+ // Skip generated entry shims and stubbed action files (whose signature tracks exported action names/URLs, not server body).
430
+ if (abs.startsWith(entriesDir))
431
+ continue
432
+ if (actionsByFile.has(abs) && !graph.analyses.get(abs)?.isInteractive)
433
+ continue
434
+ inputFiles.add(abs)
435
+ }
436
+ cache.lastClient = {
437
+ signature,
438
+ clientDir,
439
+ inputStamps: stampFiles(inputFiles),
440
+ islandChunks: new Map(result.islandChunks),
441
+ srcCssToUrl: new Map(result.srcCssToUrl),
442
+ islandCssUrl: new Map(result.islandCssUrl),
443
+ assetFiles: [...result.assetFiles],
444
+ styleUrls: [...result.styleUrls],
445
+ runtimeScript: result.runtimeScript,
446
+ regionScript: result.regionScript,
447
+ reviveScript: result.reviveScript,
448
+ chunkImports: result.chunkImports,
449
+ }
450
+ }
451
+
452
+ // Where the server build takes each import from: `prunelle` from its source, packages that render components bundled for the SSR compiler, the rest external.
453
+ // In dev prunelle's own source stays external too: Bun never unloads a module, so a bundled copy of prunelle's runtime was evaluated again and kept on every save.
454
+ function resolveServerImports(b: PluginBuilder, isDev: boolean, root: string, reachesTsx: (file: string) => boolean, externalOutDir: boolean): void {
455
+ b.onResolve({ filter: PRUNELLE_SPECIFIER_FILTER }, (args) => {
456
+ const resolved = resolvePrunelleSpecifier(args.path)
457
+ if (resolved === undefined)
458
+ return undefined
459
+ return EXTERNAL_PRUNELLE_SPECIFIERS.has(args.path) || isDev ? { path: resolved, external: true } : { path: resolved }
460
+ })
461
+ if (isDev)
462
+ b.onResolve({ filter: new RegExp(`^${RegExp.escape(`${PRUNELLE_SRC_ROOT}/`)}`) }, args => ({ path: args.path, external: true }))
463
+ b.onResolve({ filter: PRUNELLE_SCOPE_RE }, (args) => {
464
+ try {
465
+ return { path: Bun.resolveSync(args.path, args.resolveDir || root) }
466
+ }
467
+ catch {
468
+ return undefined
469
+ }
470
+ })
471
+ b.onLoad({ filter: /.*/, namespace: 'prunelle-server-css' }, () => ({ contents: '', loader: 'js' }))
472
+ b.onResolve({ filter: /^[^./]/ }, (args) => {
473
+ if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~icons/') || args.path.startsWith('virtual:') || isAbsolute(args.path))
474
+ return undefined
475
+ let resolved: string | undefined
476
+ try {
477
+ resolved = Bun.resolveSync(args.path, args.resolveDir || root)
478
+ }
479
+ catch {
480
+ try {
481
+ resolved = Bun.resolveSync(args.path, root)
482
+ }
483
+ catch {
484
+ return undefined
485
+ }
486
+ }
487
+ if (resolved.endsWith('.css'))
488
+ return resolved.endsWith('.module.css') ? { path: resolved } : { path: resolved, namespace: 'prunelle-server-css' }
489
+ if (resolved.endsWith('.tsx') || reachesTsx(resolved))
490
+ return { path: resolved }
491
+ if (isTsFile(resolved)) {
492
+ if (!isInNodeModules(resolved))
493
+ return { path: resolved }
494
+ if (isDev) {
495
+ try {
496
+ const real = realpathSync(resolved)
497
+ if (!isInNodeModules(real))
498
+ return { path: resolved }
499
+ }
500
+ catch {}
501
+ }
502
+ }
503
+ if (externalOutDir)
504
+ return { path: resolved, external: true }
505
+ return undefined
506
+ })
507
+ }
508
+
509
+ /** `entry` is the generated `_entry.js`, an in-memory file bundled beside `entries` so it shares their chunks. */
510
+ export async function buildServer(env: BundleEnv, entries: string[], serverRoot: string, islandChunks: Map<string, string>, entry: { file: string, source: string }): Promise<void> {
511
+ const { root, outDir, serverDir, graph, cache, islands } = env
512
+ const transforms = pluginTransforms(env.plugins)
513
+ const externalOutDir = !isInside(root, outDir, { orSame: true })
514
+
515
+ const serverSignature = cache !== undefined
516
+ ? JSON.stringify({
517
+ serverRoot,
518
+ assetPrefix: env.assetPrefix, lang: env.lang,
519
+ isDev: env.isDev,
520
+ transforms: transforms.key,
521
+ entries: [...entries].sort(),
522
+ islandChunks: [...islandChunks.entries()].sort(([a], [b]) => a.localeCompare(b)),
523
+ reach: [...islands.reach].sort(),
524
+ bindings: [...islands.pageBindings.entries()]
525
+ .sort(([a], [b]) => a.localeCompare(b))
526
+ .map(([f, map]) => [f, [...map.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([l, t]) => [l, t.id, t.defaultHydrate ?? ''])]),
527
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
528
+ })
529
+ : ''
530
+
531
+ if (
532
+ cache !== undefined
533
+ && cache.lastServer !== undefined
534
+ && cache.lastServer.signature === serverSignature
535
+ && stampsMatch(cache.lastServer.inputStamps)
536
+ && reuseDirFiles(cache.lastServer.serverDir, serverDir)
537
+ ) {
538
+ cache.stats.serverSkips++
539
+ cache.lastServer.serverDir = serverDir
540
+ return
541
+ }
542
+
543
+ // Whether a file renders components, directly or through what it imports: such packages are bundled so Prunelle's SSR compiler transforms them.
544
+ const tsxReach = new Map<string, boolean>()
545
+ const reachesTsx = (start: string): boolean => {
546
+ const known = tsxReach.get(start)
547
+ if (known !== undefined)
548
+ return known
549
+ if (start.endsWith('.tsx')) {
550
+ tsxReach.set(start, true)
551
+ return true
552
+ }
553
+ const seen = new Set<string>([start])
554
+ const stack = [start]
555
+ while (stack.length > 0) {
556
+ for (const dep of graph.localDeps(stack.pop()!)) {
557
+ if (dep.endsWith('.tsx') || tsxReach.get(dep) === true) {
558
+ tsxReach.set(start, true)
559
+ return true
560
+ }
561
+ if (tsxReach.get(dep) === false || seen.has(dep))
562
+ continue
563
+ seen.add(dep)
564
+ stack.push(dep)
565
+ }
566
+ }
567
+ for (const node of seen)
568
+ tsxReach.set(node, false)
569
+ return false
570
+ }
571
+
572
+ const serverPlugin: BunPlugin = {
573
+ name: 'prunelle-server',
574
+ setup(b) {
575
+ resolveServerImports(b, env.isDev, root, reachesTsx, externalOutDir)
576
+ b.onLoad({ filter: TS_FILTER }, (args) => {
577
+ if (!args.path.endsWith('.tsx')) {
578
+ if (!transforms.active || isInNodeModules(args.path))
579
+ return undefined
580
+ const raw = graph.source(args.path)
581
+ const transformed = transforms.apply(raw, args.path, 'server')
582
+ return transformed !== raw ? { contents: transformed, loader: 'ts' } : undefined
583
+ }
584
+ const analysis = graph.analyses.get(args.path)
585
+ const rawBindings = islands.pageBindings.get(args.path)
586
+ const isInteractive = analysis?.isInteractive === true
587
+ // Island code of another module may render any component of a module it imports; in its own module, only the code an island reaches.
588
+ const emitMarkers = islands.reach.has(args.path) || (isInteractive && analysis.browserSpans)
589
+ let islandMap: Map<string, IslandBinding> | undefined
590
+ let key = `${env.isDev ? 'd:' : ''}${isInteractive ? '1' : '0'}:${emitMarkers === true ? '1' : emitMarkers === false ? '0' : 's'}|t=${transforms.key}`
591
+ if (rawBindings !== undefined) {
592
+ islandMap = new Map()
593
+ for (const [localName, target] of rawBindings) {
594
+ const chunk = islandChunks.get(islandKey(target))
595
+ if (chunk !== undefined) {
596
+ islandMap.set(localName, { id: target.id, chunk, defaultHydrate: target.defaultHydrate })
597
+ key += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
598
+ }
599
+ }
600
+ }
601
+ const stamp = graph.stamp(args.path)
602
+ const cachedSsr = stamp !== undefined ? cache?.ssrCompiled.get(args.path) : undefined
603
+ if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === key)
604
+ return { contents: cachedSsr.code, loader: 'tsx' }
605
+ const compiled = compileSsr(args.path, graph.source(args.path), {
606
+ analysis,
607
+ islands: islandMap,
608
+ isIsland: isInteractive,
609
+ emitMarkers,
610
+ devSourceRoot: env.isDev ? root : undefined,
611
+ } as Parameters<typeof compileSsr>[2])
612
+ const code = transforms.apply(compiled.code, args.path, 'server')
613
+ if (cache !== undefined && stamp !== undefined)
614
+ cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code })
615
+ return { contents: code, loader: 'tsx' }
616
+ })
617
+ },
618
+ }
619
+
620
+ const serverResult = await runBunBuild('server', env.root, () => {
621
+ if (transforms.failure !== undefined)
622
+ throw transforms.failure
623
+ }, {
624
+ entrypoints: [...entries, entry.file],
625
+ files: { [entry.file]: entry.source },
626
+ outdir: serverDir,
627
+ root: serverRoot,
628
+ target: 'bun',
629
+ format: 'esm',
630
+ splitting: true,
631
+ packages: 'external',
632
+ minify: false,
633
+ // A stack trace names the source file and line: Bun reads the map beside each chunk.
634
+ sourcemap: 'linked',
635
+ metafile: cache !== undefined,
636
+ define: {
637
+ 'process.env.NODE_ENV': 'process.env.NODE_ENV',
638
+ },
639
+ plugins: [serverPlugin, ...pluginBunPlugins(env, 'server')],
640
+ })
641
+
642
+ if (cache !== undefined) {
643
+ cache.stats.serverBuilds++
644
+ const inputFiles = new Set<string>(entries)
645
+ for (const inKey of Object.keys(serverResult.metafile?.inputs ?? {})) {
646
+ const fromCwd = resolve(process.cwd(), inKey)
647
+ const abs = existsSync(fromCwd) ? fromCwd : resolve(serverDir, inKey)
648
+ if (!existsSync(abs))
649
+ continue
650
+ // Plain `.css` stylesheets are bundled exclusively by `buildClient`; CSS edits must not trigger a server rebuild.
651
+ if (abs.endsWith('.css') && !abs.endsWith('.module.css'))
652
+ continue
653
+ inputFiles.add(abs)
654
+ }
655
+ cache.lastServer = {
656
+ signature: serverSignature,
657
+ serverDir,
658
+ inputStamps: stampFiles(inputFiles),
659
+ }
660
+ }
661
+ }
@@ -0,0 +1,11 @@
1
+ // Sizes as `prunelle.config.ts` and `--max-js` take them, kept free of imports so the CLI reads them before it loads the build.
2
+
3
+ const SIZE_RE = /^(\d+(?:\.\d+)?)\s*(kb)?$/i
4
+
5
+ /** `40kb`, `40KB` or `40960` as bytes (a KB is 1024 bytes), or `undefined` when it is not a size. */
6
+ export function parseByteSize(raw: number | string): number | undefined {
7
+ if (typeof raw === 'number')
8
+ return Number.isFinite(raw) && raw >= 0 ? raw : undefined
9
+ const match = SIZE_RE.exec(raw.trim())
10
+ return match === null ? undefined : Math.round(Number(match[1]) * (match[2] === undefined ? 1 : 1024))
11
+ }