prunelle 0.1.1 → 0.7.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.
Files changed (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -1,13 +1,18 @@
1
1
  // The build manifest: its shape, and the per-route entries (islands, styles, layouts, middlewares) computed from the module graph.
2
2
 
3
+ import type { RouteCacheSpec } from '../server/route-cache'
3
4
  import type { ModuleGraph } from './graph'
4
5
  import type { IslandPlan } from './islands'
6
+ import type { StatusPageManifestEntry } from './status-pages'
5
7
  import { join } from 'node:path'
8
+ import { isRouteCacheable } from '../compiler/cacheability'
6
9
  import { isInside } from './is-inside'
7
- import { islandKey } from './islands'
10
+ import { createReachWalker } from './reach'
8
11
  import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
12
+ import { buildStatusPageEntries } from './status-pages'
13
+
14
+ export type { StatusPageKind, StatusPageManifestEntry } from './status-pages'
9
15
 
10
- const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
11
16
 
12
17
  export interface ActionManifestEntry {
13
18
  url: string
@@ -38,6 +43,12 @@ export interface RouteManifestEntry {
38
43
  /** The route, a layout or a component it renders imports `<Region>`. */
39
44
  usesRegion?: boolean | undefined
40
45
  prerender?: boolean | undefined
46
+ /** Prerendered only because `autoPrerender` found it static, so the build may render it at request time instead. */
47
+ autoPrerender?: boolean | undefined
48
+ /** Route response cache policy from `export const cache = ...`. */
49
+ cache?: RouteCacheSpec | undefined
50
+ /** True when static analysis proves the page reads nothing from the request or clock. */
51
+ cacheable?: boolean | undefined
41
52
  prerendered?: Record<string, string> | undefined
42
53
  /** CSP hashes of the app's `<style>` blocks per prerendered URL, for the pages that have any. */
43
54
  prerenderedStyleHashes?: Record<string, string[]> | undefined
@@ -63,6 +74,10 @@ export interface BuildManifest {
63
74
  rootLayoutFile?: string | undefined
64
75
  errorFile?: string | undefined
65
76
  notFoundFile?: string | undefined
77
+ /** Discovered status/error pages (`_401`, `_403`, `_404`, `_429`, `_503`, `_error`), root and nested. */
78
+ statusPages?: StatusPageManifestEntry[] | undefined
79
+ /** Custom app param matchers (`src/params/<name>.ts`), mapping matcher name to compiled module key. */
80
+ paramMatchers?: Record<string, string> | undefined
66
81
  actions: ActionManifestEntry[]
67
82
  islands: Record<string, string>
68
83
  assets: string[]
@@ -73,122 +88,17 @@ export interface BuildManifest {
73
88
  pluginData?: Record<string, Record<string, unknown>> | undefined
74
89
  }
75
90
 
76
- interface FileReach {
77
- /** Island chunks reachable from the file, and the subset loaded eagerly. */
78
- chunks: Set<string>
79
- eager: Set<string>
80
- styles: Set<string>
81
- usesRenderContext: boolean
82
- usesRegion: boolean
83
- }
84
-
85
- /** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it. */
86
- function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
87
- const { analyses } = graph
88
-
89
- function walkIslands(file: string, seen: Set<string>, reach: FileReach): void {
90
- if (seen.has(file))
91
- return
92
- seen.add(file)
93
- const analysis = analyses.get(file)
94
- if (analysis === undefined)
95
- return
96
- if (analysis.isInteractive) {
97
- const chunk = islandChunks.get(`${file}#default`)
98
- if (chunk !== undefined) {
99
- reach.chunks.add(chunk)
100
- if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
101
- reach.eager.add(chunk)
102
- }
103
- // Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
104
- if (analysis.staticJsxTags.size === 0)
105
- return
106
- }
107
- for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
108
- const chunk = islandChunks.get(islandKey(target))
109
- if (chunk === undefined)
110
- continue
111
- reach.chunks.add(chunk)
112
- const isDeferred = analysis.deferredIslandTags.has(localName)
113
- || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
114
- if (!isDeferred)
115
- reach.eager.add(chunk)
116
- }
117
- for (const dep of graph.localDeps(file))
118
- walkIslands(dep, seen, reach)
119
- }
120
-
121
- function walkStyles(file: string, seen: Set<string>, out: Set<string>): void {
122
- if (seen.has(file))
123
- return
124
- seen.add(file)
125
- const analysis = analyses.get(file)
126
- if (analysis === undefined)
127
- return
128
- if (analysis.isInteractive) {
129
- const islCss = islandCssUrl.get(`${file}#default`)
130
- if (islCss !== undefined)
131
- out.add(islCss)
132
- }
133
- for (const target of islands.pageBindings.get(file)?.values() ?? []) {
134
- const islCss = islandCssUrl.get(islandKey(target))
135
- if (islCss !== undefined)
136
- out.add(islCss)
137
- walkStyles(target.file, seen, out)
138
- }
139
- for (const imp of analysis.imports) {
140
- const cssUrl = srcCssToUrl.get(graph.resolve(file, imp.source) ?? '')
141
- if (cssUrl !== undefined)
142
- out.add(cssUrl)
143
- }
144
- for (const dep of graph.localDeps(file))
145
- walkStyles(dep, seen, out)
146
- }
147
-
148
- function walkRenderContext(file: string, seen: Set<string>): boolean {
149
- if (seen.has(file))
150
- return false
151
- seen.add(file)
152
- const analysis = analyses.get(file)
153
- if (analysis === undefined)
154
- return false
155
- return analysis.usesRenderContext || graph.localDeps(file).some(dep => walkRenderContext(dep, seen))
156
- }
157
-
158
- // A namespace import of prunelle may render `NS.Region`, so it counts.
159
- function walkRegion(file: string, seen: Set<string>): boolean {
160
- if (seen.has(file))
161
- return false
162
- seen.add(file)
163
- const analysis = analyses.get(file)
164
- if (analysis === undefined)
165
- return false
166
- return analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*'))
167
- || graph.localDeps(file).some(dep => walkRegion(dep, seen))
168
- }
169
-
170
- // Layouts are shared by many routes, so each file is walked once.
171
- const memo = new Map<string, FileReach>()
172
- return (file: string): FileReach => {
173
- let reach = memo.get(file)
174
- if (reach === undefined) {
175
- reach = { chunks: new Set(), eager: new Set(), styles: new Set(), usesRenderContext: false, usesRegion: false }
176
- walkIslands(file, new Set(), reach)
177
- walkStyles(file, new Set(), reach.styles)
178
- reach.usesRenderContext = walkRenderContext(file, new Set())
179
- reach.usesRegion = walkRegion(file, new Set())
180
- memo.set(file, reach)
181
- }
182
- return reach
183
- }
184
- }
185
-
186
91
  export interface RouteEntries {
187
92
  routes: RouteManifestEntry[]
93
+ statusPages: StatusPageManifestEntry[]
188
94
  /** Stylesheets of every page: the plugins' CSS, then the root layout's. */
189
95
  globalStyles: string[]
190
96
  /** The plugins' CSS alone. */
191
97
  globalPluginStyles: string[]
98
+ /** Reachable source files for each route path (layouts + page + islands + local deps). */
99
+ routeSourceFiles: Map<string, string[]>
100
+ /** Reachable source files of the root layout and status/error pages. */
101
+ globalSourceFiles: string[]
192
102
  }
193
103
 
194
104
  export function buildRouteEntries(options: {
@@ -199,8 +109,11 @@ export function buildRouteEntries(options: {
199
109
  islandCssUrl: Map<string, string>
200
110
  routesDir: string
201
111
  pageFiles: string[]
112
+ specialFiles?: readonly string[] | undefined
202
113
  pluginCssFiles: string[]
203
114
  isStatic: boolean
115
+ /** Automatically prerender static cacheable pages (no middleware, not `prerender = false`, no `cache` export). */
116
+ autoPrerender?: boolean | undefined
204
117
  /** Maps a source file to its compiled module, relative to the out dir. */
205
118
  toOutRel: (srcFile: string) => string
206
119
  }): RouteEntries {
@@ -210,6 +123,8 @@ export function buildRouteEntries(options: {
210
123
  const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
211
124
  const rootLayout = join(routesDir, '_layout.tsx')
212
125
  const globalStyles = [...new Set([...globalPluginStyles, ...(graph.analyses.has(rootLayout) ? reachOf(rootLayout).styles : [])])]
126
+ const routeSourceFiles = new Map<string, string[]>()
127
+ const globalSourceSet = new Set<string>(graph.analyses.has(rootLayout) ? reachOf(rootLayout).files : [])
213
128
 
214
129
  const routes = options.pageFiles.map((file): RouteManifestEntry => {
215
130
  const analysis = graph.analyses.get(file)
@@ -218,6 +133,7 @@ export function buildRouteEntries(options: {
218
133
  const chunks = new Set<string>()
219
134
  const eagerChunks = new Set<string>()
220
135
  const styles = new Set<string>(globalPluginStyles)
136
+ const reachableFiles = new Set<string>()
221
137
  let usesRenderContext = false
222
138
  let usesRegion = false
223
139
  for (const src of [...layoutSrcs, file]) {
@@ -228,14 +144,22 @@ export function buildRouteEntries(options: {
228
144
  eagerChunks.add(chunk)
229
145
  for (const style of reach.styles)
230
146
  styles.add(style)
147
+ for (const f of reach.files)
148
+ reachableFiles.add(f)
231
149
  usesRenderContext ||= reach.usesRenderContext
232
150
  usesRegion ||= reach.usesRegion
233
151
  }
152
+ const routePath = fileToRoutePath(routesDir, file)
153
+ routeSourceFiles.set(routePath, [...reachableFiles])
154
+ const middlewareSrcs = ancestorFiles(routesDir, file, MIDDLEWARE_NAMES)
155
+ const cacheable = isRouteCacheable({ graph, islands, file, layoutSrcs, middlewareCount: middlewareSrcs.length, routePath })
156
+ const cache = analysis?.cache
157
+ const autoPre = options.autoPrerender === true && cacheable && cache === undefined
234
158
  return {
235
- path: fileToRoutePath(routesDir, file),
159
+ path: routePath,
236
160
  file: toOutRel(file),
237
161
  layouts: layoutSrcs.map(toOutRel),
238
- middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
162
+ middlewares: middlewareSrcs.map(toOutRel),
239
163
  hasLoad: analysis?.hasLoadExport,
240
164
  isIsland: page?.interactive,
241
165
  islandChunk: islandChunks.get(`${file}#default`),
@@ -246,10 +170,26 @@ export function buildRouteEntries(options: {
246
170
  styles: [...styles],
247
171
  usesRenderContext,
248
172
  usesRegion,
249
- prerender: analysis?.hasPrerender || options.isStatic,
173
+ prerender: analysis?.hasPrerender || options.isStatic || autoPre,
174
+ ...(autoPre && analysis?.hasPrerender !== true && !options.isStatic ? { autoPrerender: true } : {}),
175
+ ...(cache !== undefined ? { cache } : {}),
176
+ ...(cacheable ? { cacheable: true } : {}),
250
177
  }
251
178
  })
252
- return { routes, globalStyles, globalPluginStyles }
179
+ for (const special of options.specialFiles ?? []) {
180
+ if (graph.analyses.has(special)) {
181
+ for (const f of reachOf(special).files)
182
+ globalSourceSet.add(f)
183
+ }
184
+ }
185
+ const statusPages = buildStatusPageEntries({
186
+ routesDir,
187
+ specialFiles: options.specialFiles ?? [],
188
+ globalPluginStyles,
189
+ reachOf,
190
+ toOutRel,
191
+ })
192
+ return { routes, statusPages, globalStyles, globalPluginStyles, routeSourceFiles, globalSourceFiles: [...globalSourceSet] }
253
193
  }
254
194
 
255
195
  export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
@@ -16,9 +16,9 @@ export function assertOwnOutDir(root: string, outDir: string, assetPrefix: strin
16
16
  const names = new Set(readdirSync(outDir))
17
17
  if (names.size === 0 || names.has(OUTPUT_MARKER))
18
18
  return
19
- // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder.
19
+ // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder (including a kay v2 export's `_kay/`).
20
20
  const assetDir = assetPrefix.replace(LEADING_SLASH_RE, '').split('/')[0] ?? ''
21
- if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)))
21
+ if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)) || names.has('_kay'))
22
22
  return
23
23
  throw new Error(`prunelle build: refusing to replace "${relPosix(root, outDir)}": it holds files prunelle did not build. Delete it, or set \`outDir\` in prunelle.config.ts to a folder of its own.`)
24
24
  }
@@ -2,9 +2,10 @@
2
2
 
3
3
  import type { AppRuntimeContext } from '../plugins/context'
4
4
  import type { BuildPluginContext, FinalizeBuildContext, PrunellePlugin } from '../plugins/index'
5
- import type { RouteManifestEntry } from './manifest'
5
+ import type { RouteManifestEntry, StatusPageManifestEntry } from './manifest'
6
6
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
7
- import { dirname, join } from 'node:path'
7
+ import { dirname, join, resolve } from 'node:path'
8
+ import { isInside } from './is-inside'
8
9
  import { precompressFiles } from './precompress'
9
10
 
10
11
  const LEADING_SLASHES_RE = /^\/+/
@@ -14,6 +15,14 @@ function cleanRel(relPath: string): string {
14
15
  return relPath.replace(LEADING_SLASHES_RE, '').replace(BACKSLASH_RE, '/')
15
16
  }
16
17
 
18
+ /** The clean relative path of a file a plugin writes under `base`, or a throw naming the plugin when it climbs out of `base`. */
19
+ function confinedRel(plugin: string, what: string, base: string, relPath: string): string {
20
+ const clean = cleanRel(relPath)
21
+ if (!isInside(base, resolve(base, clean)))
22
+ throw new Error(`prunelle build: plugin "${plugin}" ${what}("${relPath}") leaves the output folder: use a relative path without "..".`)
23
+ return clean
24
+ }
25
+
17
26
  export interface PublicFiles {
18
27
  /** Public files known so far, as relative paths in registration order. */
19
28
  files: string[]
@@ -66,6 +75,9 @@ export interface PluginHostOptions {
66
75
  isStatic: boolean
67
76
  isDev: boolean
68
77
  routes: RouteManifestEntry[]
78
+ statusPages?: StatusPageManifestEntry[] | undefined
79
+ routeSourceFiles?: ReadonlyMap<string, readonly string[]> | undefined
80
+ globalSourceFiles?: readonly string[] | undefined
69
81
  publicFiles: PublicFiles
70
82
  /** Client files already emitted, relative to the client dir. */
71
83
  assets: string[]
@@ -73,17 +85,91 @@ export interface PluginHostOptions {
73
85
  globalStyles: string[]
74
86
  }
75
87
 
76
- export function createPluginHost(options: PluginHostOptions) {
77
- const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, assets, styleUrls, globalStyles } = options
78
- const assetSet = new Set(assets)
88
+ function createStyleMutators(
89
+ styleUrls: string[],
90
+ globalStyles: string[],
91
+ routes: RouteManifestEntry[],
92
+ statusPages: StatusPageManifestEntry[],
93
+ ) {
79
94
  const styleSet = new Set(styleUrls)
80
95
  const globalStyleSet = new Set(globalStyles)
96
+ let prependedGlobalCount = 0
97
+
98
+ const addStyleUrl = (href: string): void => {
99
+ if (!styleSet.has(href)) {
100
+ styleSet.add(href)
101
+ styleUrls.push(href)
102
+ }
103
+ }
104
+
105
+ return {
106
+ addStyle(href: string) {
107
+ addStyleUrl(href)
108
+ if (!globalStyleSet.has(href)) {
109
+ globalStyleSet.add(href)
110
+ globalStyles.push(href)
111
+ }
112
+ for (const r of routes) {
113
+ if (r.styles !== undefined && !r.styles.includes(href))
114
+ r.styles.push(href)
115
+ }
116
+ for (const sp of statusPages) {
117
+ if (!sp.styles.includes(href))
118
+ sp.styles.push(href)
119
+ }
120
+ },
121
+ prependStyle(href: string) {
122
+ addStyleUrl(href)
123
+ const insertAt = prependedGlobalCount
124
+ if (!globalStyleSet.has(href)) {
125
+ globalStyleSet.add(href)
126
+ globalStyles.splice(insertAt, 0, href)
127
+ prependedGlobalCount++
128
+ }
129
+ for (const r of routes) {
130
+ if (r.styles !== undefined && !r.styles.includes(href))
131
+ r.styles.splice(Math.min(insertAt, r.styles.length), 0, href)
132
+ }
133
+ for (const sp of statusPages) {
134
+ if (!sp.styles.includes(href))
135
+ sp.styles.splice(Math.min(insertAt, sp.styles.length), 0, href)
136
+ }
137
+ },
138
+ addRouteStyle(routePath: string, href: string) {
139
+ addStyleUrl(href)
140
+ const route = routes.find(r => r.path === routePath)
141
+ if (route !== undefined) {
142
+ route.styles ??= [...globalStyles]
143
+ if (!route.styles.includes(href))
144
+ route.styles.push(href)
145
+ }
146
+ },
147
+ prependRouteStyle(routePath: string, href: string) {
148
+ addStyleUrl(href)
149
+ const route = routes.find(r => r.path === routePath)
150
+ if (route !== undefined) {
151
+ route.styles ??= [...globalStyles]
152
+ if (!route.styles.includes(href)) {
153
+ let idx = 0
154
+ while (idx < route.styles.length && globalStyleSet.has(route.styles[idx]!))
155
+ idx++
156
+ route.styles.splice(idx, 0, href)
157
+ }
158
+ }
159
+ },
160
+ }
161
+ }
162
+
163
+ export function createPluginHost(options: PluginHostOptions) {
164
+ const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, statusPages = [], assets, styleUrls, globalStyles } = options
165
+ const assetSet = new Set(assets)
81
166
  const headTags: string[] = []
82
167
  const pluginData: Record<string, Record<string, unknown>> = {}
83
168
  const precompressed = new Set<string>()
169
+ const styles = createStyleMutators(styleUrls, globalStyles, routes, statusPages)
84
170
 
85
- function emitAsset(relPath: string, content: string | Uint8Array): string {
86
- const clean = cleanRel(relPath)
171
+ function emitAsset(plugin: string, relPath: string, content: string | Uint8Array): string {
172
+ const clean = confinedRel(plugin, 'emitAsset', clientDir, relPath)
87
173
  const dst = join(clientDir, clean)
88
174
  mkdirSync(dirname(dst), { recursive: true })
89
175
  writeFileSync(dst, content)
@@ -94,21 +180,14 @@ export function createPluginHost(options: PluginHostOptions) {
94
180
  return `${assetPrefix}/${clean}`
95
181
  }
96
182
 
97
- function emitPublic(relPath: string, content: string | Uint8Array): string {
98
- const clean = options.publicFiles.register(relPath)
183
+ function emitPublic(plugin: string, relPath: string, content: string | Uint8Array): string {
184
+ const clean = options.publicFiles.register(confinedRel(plugin, 'emitPublic', outPublicDir, relPath))
99
185
  const dst = join(outPublicDir, clean)
100
186
  mkdirSync(dirname(dst), { recursive: true })
101
187
  writeFileSync(dst, content)
102
188
  return `/${clean}`
103
189
  }
104
190
 
105
- function addStyleUrl(href: string): void {
106
- if (!styleSet.has(href)) {
107
- styleSet.add(href)
108
- styleUrls.push(href)
109
- }
110
- }
111
-
112
191
  // resolvePlugins() refuses two plugins sharing a name, so each name has one owner.
113
192
  const setDataFor = (plugin: PrunellePlugin) => (data: Record<string, unknown>): void => {
114
193
  pluginData[plugin.name] = { ...pluginData[plugin.name], ...data }
@@ -123,34 +202,20 @@ export function createPluginHost(options: PluginHostOptions) {
123
202
  isStatic: options.isStatic,
124
203
  dev: options.isDev,
125
204
  routes,
126
- emitAsset,
127
- emitPublic,
128
205
  provide: appCtx.provide,
129
206
  inject: appCtx.inject,
130
207
  }
131
208
 
209
+ const emittersFor = (plugin: PrunellePlugin) => ({
210
+ emitAsset: (relPath: string, content: string | Uint8Array) => emitAsset(plugin.name, relPath, content),
211
+ emitPublic: (relPath: string, content: string | Uint8Array) => emitPublic(plugin.name, relPath, content),
212
+ })
213
+
132
214
  const buildCtx = {
133
215
  ...shared,
134
- addStyle(href: string) {
135
- addStyleUrl(href)
136
- if (!globalStyleSet.has(href)) {
137
- globalStyleSet.add(href)
138
- globalStyles.push(href)
139
- }
140
- for (const r of routes) {
141
- if (r.styles !== undefined && !r.styles.includes(href))
142
- r.styles.push(href)
143
- }
144
- },
145
- addRouteStyle(routePath: string, href: string) {
146
- addStyleUrl(href)
147
- const route = routes.find(r => r.path === routePath)
148
- if (route !== undefined) {
149
- route.styles ??= [...globalStyles]
150
- if (!route.styles.includes(href))
151
- route.styles.push(href)
152
- }
153
- },
216
+ ...(options.routeSourceFiles !== undefined ? { routeSourceFiles: options.routeSourceFiles } : {}),
217
+ ...(options.globalSourceFiles !== undefined ? { globalSourceFiles: options.globalSourceFiles } : {}),
218
+ ...styles,
154
219
  addHead(html: string) {
155
220
  if (html !== '')
156
221
  headTags.push(html)
@@ -169,19 +234,26 @@ export function createPluginHost(options: PluginHostOptions) {
169
234
  async runBuild(): Promise<void> {
170
235
  for (const plugin of plugins) {
171
236
  if (plugin.build !== undefined) {
172
- const ctx: BuildPluginContext = { ...buildCtx, setData: setDataFor(plugin) }
237
+ const ctx: BuildPluginContext = { ...buildCtx, ...emittersFor(plugin), setData: setDataFor(plugin) }
173
238
  await runPluginHook(plugin, 'build', () => plugin.build!(ctx))
174
239
  }
175
240
  }
176
241
  },
177
242
 
178
243
  /** Runs every plugin's `afterPrerender(ctx)`, once `route.prerendered` and prerender-emitted public files are known. */
179
- async runAfterPrerender(): Promise<boolean> {
244
+ async runAfterPrerender(prerenderDir?: string): Promise<boolean> {
180
245
  let ran = false
181
246
  for (const plugin of plugins) {
182
247
  if (plugin.afterPrerender !== undefined) {
183
248
  ran = true
184
- const ctx: FinalizeBuildContext = { ...shared, publicFiles: options.publicFiles.files, setData: setDataFor(plugin) }
249
+ const ctx: FinalizeBuildContext = {
250
+ ...shared,
251
+ ...emittersFor(plugin),
252
+ ...(prerenderDir !== undefined ? { prerenderDir } : {}),
253
+ publicFiles: options.publicFiles.files,
254
+ assets,
255
+ setData: setDataFor(plugin),
256
+ }
185
257
  await runPluginHook(plugin, 'afterPrerender', () => plugin.afterPrerender!(ctx))
186
258
  }
187
259
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
4
4
  import { availableParallelism } from 'node:os'
5
- import { dirname, extname, join } from 'node:path'
5
+ import { basename, dirname, extname, join } from 'node:path'
6
6
  import { promisify } from 'node:util'
7
7
  import { brotliCompress, brotliCompressSync, constants as zlibConstants } from 'node:zlib'
8
8
  import { getAppContext } from '../plugins/context'
@@ -10,7 +10,7 @@ import { getAppContext } from '../plugins/context'
10
10
  /** Brotli quality of the sidecars: written once per build, downloaded by every visitor, so the smallest the encoder makes. */
11
11
  export const BROTLI_QUALITY = 11
12
12
 
13
- const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm'])
13
+ const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm', '.ttf', '.otf', '.ico'])
14
14
  const STALE_MS = 7 * 86_400_000
15
15
 
16
16
  const compress = promisify(brotliCompress)
@@ -46,9 +46,22 @@ function readEntry(file: string): Buffer | undefined {
46
46
  }
47
47
  }
48
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
+
49
58
  // Renamed into place, so a build running beside this one never reads half an entry.
50
59
  function writeEntry(file: string, packed: Uint8Array): void {
51
- mkdirSync(dirname(file), { recursive: true })
60
+ const dir = dirname(file)
61
+ mkdirSync(dir, { recursive: true })
62
+ const parent = dirname(dir)
63
+ if (basename(parent) === '.prunelle-cache')
64
+ ensureCacheGitignore(parent)
52
65
  const tmp = `${file}.${process.pid}-${tmpCount++}.tmp`
53
66
  writeFileSync(tmp, packed)
54
67
  renameSync(tmp, file)