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
@@ -0,0 +1,64 @@
1
+ // `prunelle check` warnings about what weakens an app's defences: dotfiles under public/, and the security opt-outs in its config.
2
+
3
+ import type { SecurityHeadersOptions } from '../server/security'
4
+ import { relative } from 'node:path'
5
+ import { isHiddenPublicPath, walkAllFiles } from '../build/files'
6
+ import { formatDiagnostic } from '../compiler/shared'
7
+ import { resolveCspPolicy } from '../server/security'
8
+
9
+ /** One warning per dotfile in `public/` (other than `.well-known`): the build leaves it out, so it is either dead weight or a secret about to be committed. */
10
+ export function publicDotfileWarnings(publicDir: string, root: string): string[] {
11
+ return walkAllFiles(publicDir)
12
+ .map(abs => ({ abs, rel: relative(publicDir, abs) }))
13
+ .filter(file => isHiddenPublicPath(file.rel))
14
+ .sort((a, b) => a.rel.localeCompare(b.rel))
15
+ .map(file => formatDiagnostic(`${relative(root, file.abs)}:1:1`, `[security/public-dotfile] "${file.rel}" is in public/ but the build does not copy dotfiles, so it is never served: delete it, or move it out of public/ (only .well-known/ is kept).`, 'warning'))
16
+ }
17
+
18
+ // `.redirect("https://…"` or `.redirect("//…"`: a literal address on another site, up to the closing parenthesis of the call.
19
+ const EXTERNAL_REDIRECT_RE = /\.redirect\(\s*(['"`])(?:https?:)?\/\/[^)]*\)/g
20
+
21
+ /** One warning per `ctx.redirect("https://other.site/…")` that lacks `{ external: true }`: since 0.x it throws at runtime. */
22
+ export function externalRedirectWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
23
+ const warnings: string[] = []
24
+ for (const file of files) {
25
+ const code = read(file)
26
+ for (const match of code.matchAll(EXTERNAL_REDIRECT_RE)) {
27
+ if (!match[0].includes('external'))
28
+ warnings.push(formatDiagnostic(locate(file, match.index), '[security/external-redirect] ctx.redirect() to another site throws unless the app passes { external: true } as its third argument: add `{ external: true }` if the address is the app\'s own, and never pass one read from the request.', 'warning'))
29
+ }
30
+ }
31
+ return warnings
32
+ }
33
+
34
+ // Fetch directives whose `'unsafe-inline'` lets an injected script or stylesheet run; `style-src-attr` is left out, as the default policy allows `style=""` attributes.
35
+ const INLINE_CODE_DIRECTIVES = new Set(['default-src', 'script-src', 'script-src-elem', 'style-src', 'style-src-elem'])
36
+
37
+ /** One warning for each way `security` in `prunelle.config.ts` turns a default defence off: all headers, the CSP, or `'unsafe-inline'` in it. */
38
+ export function securityConfigWarnings(security: SecurityHeadersOptions | false | undefined): string[] {
39
+ const at = 'prunelle.config.ts:1:1'
40
+ if (security === false)
41
+ return [formatDiagnostic(at, '[security/headers-off] security: false sends no CSP, HSTS, nosniff, frame, referrer, permissions, opener or resource policy header: drop it, and relax only the one header an integration needs (`security: { frameOptions: false }`).', 'warning')]
42
+ if (security?.csp === false)
43
+ return [formatDiagnostic(at, '[security/csp-off] security.csp is false, so no page carries a Content-Security-Policy: drop it, or extend the default with `security: { csp: { \'img-src\': [\'https://cdn.example\'] } }`.', 'warning')]
44
+ const csp = resolveCspPolicy(security)
45
+ const loose = (csp ?? '').split(';')
46
+ .map(part => part.trim().split(/\s+/))
47
+ .filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.includes('\'unsafe-inline\''))
48
+ .map(([name]) => name!.toLowerCase())
49
+ return loose.length === 0
50
+ ? []
51
+ : [formatDiagnostic(at, `[security/unsafe-inline] the CSP allows 'unsafe-inline' in ${loose.join(', ')}, which lets an injected script or style run: remove it, since prunelle hashes its own inline scripts and styles, or add a hash of the inline one you need.`, 'warning')]
52
+ }
53
+
54
+ const CSRF_OFF_RE = /export\s+const\s+csrf\s*=\s*false\b/g
55
+
56
+ /** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. */
57
+ export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
58
+ const warnings: string[] = []
59
+ for (const file of files) {
60
+ for (const match of read(file).matchAll(CSRF_OFF_RE))
61
+ warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook or bearer-token API that verifies a signature or token itself, and drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
62
+ }
63
+ return warnings
64
+ }
package/src/cli/check.ts CHANGED
@@ -1,22 +1,30 @@
1
1
  // `prunelle check [dir]`: validates routes, Prunelle compiler & island rules (unified with `prunelle build`), config, and TypeScript types.
2
2
 
3
+ import type { IslandValueUse } from '../build/island-promote'
3
4
  import type { IslandIssue } from '../build/islands'
4
5
  import type { ModuleAnalysis } from '../compiler/analyze'
5
6
  import type { ComplianceConfig } from '../compiler/compliance'
6
- import type { CheckPluginContext, PrunellePlugin } from '../plugins/index'
7
+ import type { CheckPluginContext, PrunelleConfig, PrunellePlugin } from '../plugins/index'
7
8
  import { existsSync, readFileSync } from 'node:fs'
8
9
  import { basename, join, relative, resolve } from 'node:path'
9
10
  import { isInNodeModules, isNotSourceDir, isTsFile, relPosix, walkFiles, walkRoutes } from '../build/files'
10
11
  import { ModuleGraph } from '../build/graph'
11
12
  import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from '../build/render-rules'
12
13
  import { analyzeIslands } from '../build/islands'
13
- import { fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblemLocation, routeFileProblem, SPECIAL_ROUTE_FILES } from '../build/routes'
14
+ import { ancestorFiles, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblemLocation, routeFileProblem, SPECIAL_ROUTE_FILES } from '../build/routes'
15
+ import { findUnknownStatusPages } from '../build/status-pages'
14
16
  import { analyzeModule } from '../compiler/analyze'
15
- import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
17
+ import { findCachedRoutePrivateReads } from '../compiler/cacheability'
18
+ import { collectProjectComplianceWarnings, isIgnoredAt, isRuleIgnored, parsePrunelleIgnores, pluginSetsLang, shouldEmitWarning } from '../compiler/compliance'
16
19
  import { collectMistakes, PrunelleMistake, serverOnlyTagError } from '../compiler/mistakes'
17
20
  import { DIAGNOSTIC_PREFIX_RE, formatDiagnostic, formatLoc } from '../compiler/shared'
18
21
  import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
19
22
  import { collectRequirements } from '../plugins/requires'
23
+ import { normalizeConsentConfig } from '../server/consent'
24
+ import { checkAppForms } from './check-forms'
25
+ import { unresolvedImport } from './check-imports'
26
+ import { checkAppLinks } from './check-links'
27
+ import { csrfOffWarnings, externalRedirectWarnings, publicDotfileWarnings, securityConfigWarnings } from './check-security'
20
28
 
21
29
  /** Whether `prunelle check` typechecked the app, with which tool, or why it did not. */
22
30
  export type TypecheckRun = { ran: true, tool: string } | { ran: false, reason: string }
@@ -137,6 +145,16 @@ function loadCheckedModule(
137
145
  return undefined
138
146
  }
139
147
 
148
+ // An imported island read as a value hydrates what holds it whole: a warning, as a table of islands may mean it.
149
+ function islandValueWarnings(uses: readonly IslandValueUse[], root: string, sources: Map<string, string>, compliance: ComplianceConfig | undefined): string[] {
150
+ const rule = 'rgesn/island-by-value'
151
+ if (isRuleIgnored(rule, compliance))
152
+ return []
153
+ return uses
154
+ .filter(use => !isIgnoredAt(parsePrunelleIgnores(sourceOf(use.file, sources)), rule, use.offset))
155
+ .map(use => formatDiagnostic(locOf(root, use.file, sources, use.offset), `[${rule}] ${use.name} is an island read as a value, not rendered as <${use.name} />, so what holds it hydrates as an island and ships its code too: render <${use.name} /> itself where it shows, or // prunelle-ignore ${rule} when the whole component should hydrate.`, 'warning'))
156
+ }
157
+
140
158
  function formatIslandIssue(issue: IslandIssue, root: string, sources: Map<string, string>): string {
141
159
  const rel = relPosix(root, issue.file)
142
160
  switch (issue.kind) {
@@ -162,10 +180,13 @@ function formatIslandIssue(issue: IslandIssue, root: string, sources: Map<string
162
180
  return formatDiagnostic(locOf(root, issue.file, sources, issue.offset), message)
163
181
  }
164
182
  case 'private-env': {
165
- const envName = issue.envKind === 'bun' ? 'Bun.env' : 'process.env'
183
+ const isImportMeta = issue.envKind === 'process' && sources.get(issue.file)?.slice(issue.offset, issue.offset + 15).startsWith('import.meta') === true
184
+ const envName = issue.envKind === 'bun' ? 'Bun.env' : isImportMeta ? 'import.meta.env' : 'process.env'
166
185
  const hint = issue.envKind === 'bun'
167
186
  ? 'Bun.env is server-only and is not inlined in browser bundles; use process.env.PUBLIC_* for build-time client values.'
168
- : 'Only process.env.PUBLIC_* reaches the browser.'
187
+ : isImportMeta
188
+ ? 'Only import.meta.env.PUBLIC_* and MODE/DEV/PROD reach the browser.'
189
+ : 'Only process.env.PUBLIC_* reaches the browser.'
169
190
  return formatDiagnostic(locOf(root, issue.file, sources, issue.offset), `prunelle check: reads ${envName} and is reachable from the island in ${relPosix(root, issue.island)}. ${hint}`)
170
191
  }
171
192
  case 'compiler-mistake':
@@ -174,16 +195,19 @@ function formatIslandIssue(issue: IslandIssue, root: string, sources: Map<string
174
195
  }
175
196
 
176
197
  // Each plugin's check(ctx) runs inside a real AppRuntimeContext; what it reports without a place lands on prunelle.config.ts.
177
- async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, outDir: string, assetPrefix: string, site: string | undefined }, errors: string[], warnings: string[]): Promise<void> {
178
- const { root, routesDir, outDir, assetPrefix, site } = paths
179
- const appCtx = createAppContext({ root, outDir, publicDir: join(outDir, 'public'), assetPrefix, dev: false })
198
+ async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, publicDir: string, outDir: string, assetPrefix: string, site: string | undefined, consentCategories: readonly string[] }, errors: string[], warnings: string[]): Promise<void> {
199
+ const { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories } = paths
200
+ const appCtx = createAppContext({ root, outDir, publicDir: join(outDir, 'public'), assetPrefix, site, dev: false })
180
201
  const placed = (message: string, severity: 'error' | 'warning'): string =>
181
202
  DIAGNOSTIC_PREFIX_RE.test(message) ? message : formatDiagnostic('prunelle.config.ts:1:1', message, severity)
182
203
  const pluginCtx: CheckPluginContext = {
183
204
  root,
184
205
  routesDir,
206
+ publicDir,
185
207
  error: message => errors.push(placed(message, 'error')),
186
208
  warn: message => warnings.push(placed(message, 'warning')),
209
+ provide: appCtx.provide,
210
+ inject: appCtx.inject,
187
211
  }
188
212
  for (const plugin of plugins) {
189
213
  if (plugin.check === undefined)
@@ -195,7 +219,7 @@ async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root
195
219
  errors.push(placed(`${plugin.name}: ${err instanceof Error ? err.message : String(err)}`, 'error'))
196
220
  }
197
221
  }
198
- const { unmet, failed } = await runWithAppContext(appCtx, () => collectRequirements(plugins, { root, site }))
222
+ const { unmet, failed } = await runWithAppContext(appCtx, () => collectRequirements(plugins, { root, site, consentCategories }))
199
223
  for (const line of unmet)
200
224
  warnings.push(placed(`${line} (a production start refuses until it is set)`, 'warning'))
201
225
  for (const line of failed)
@@ -203,6 +227,17 @@ async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root
203
227
  }
204
228
 
205
229
 
230
+ function discoverProjectFiles(srcDir: string, routesDir: string, configFile: string): string[] {
231
+ const fileSet = new Set<string>()
232
+ if (existsSync(srcDir))
233
+ walkTsFiles(srcDir).forEach(f => fileSet.add(f))
234
+ if (existsSync(routesDir))
235
+ walkTsFiles(routesDir).forEach(f => fileSet.add(f))
236
+ if (existsSync(configFile))
237
+ fileSet.add(configFile)
238
+ return [...fileSet].sort()
239
+ }
240
+
206
241
  export async function checkProject(rootDir: string, options: { skipTypecheck?: boolean } = {}): Promise<CheckResult> {
207
242
  const root = resolve(rootDir)
208
243
  const errors: string[] = []
@@ -210,19 +245,26 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
210
245
  // 1. Validate prunelle.config.ts
211
246
  let routesDir = resolve(root, 'src/routes')
212
247
  let outDir = resolve(root, 'dist')
248
+ let publicDir = resolve(root, 'public')
213
249
  let assetPrefix = '/_pru'
214
250
  let site: string | undefined
215
251
  let compliance: ComplianceConfig | undefined
252
+ let loadedConfig: PrunelleConfig = {}
216
253
  let plugins: Awaited<ReturnType<typeof loadConfig>>['plugins'] = []
254
+ let consentCategories: readonly string[] = []
217
255
  try {
218
256
  const cfg = await loadConfig(root)
257
+ loadedConfig = cfg
219
258
  plugins = resolvePlugins(cfg.plugins)
259
+ consentCategories = normalizeConsentConfig(cfg.consent)?.categories ?? []
220
260
  site = cfg.site
221
261
  compliance = cfg.compliance
222
262
  if (cfg.routesDir !== undefined)
223
263
  routesDir = resolve(root, cfg.routesDir)
224
264
  if (cfg.outDir !== undefined)
225
265
  outDir = resolve(root, cfg.outDir)
266
+ if (cfg.publicDir !== undefined)
267
+ publicDir = resolve(root, cfg.publicDir)
226
268
  if (cfg.assetPrefix !== undefined)
227
269
  assetPrefix = cfg.assetPrefix.replace(/\/$/, '')
228
270
  }
@@ -236,18 +278,10 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
236
278
  errors.push(formatDiagnostic(`${relRoutes.replace(/\\/g, '/')}:1:1`, `prunelle check: missing routes directory: ${relRoutes}`))
237
279
  }
238
280
 
239
- // 3. Parse & run Prunelle static compiler analysis across src/ AND custom routesDir
281
+ // 3. Parse & run Prunelle static compiler analysis across src/, custom routesDir, and prunelle.config.ts
240
282
  const srcDir = resolve(root, 'src')
241
- const fileSet = new Set<string>()
242
- if (existsSync(srcDir)) {
243
- for (const f of walkTsFiles(srcDir))
244
- fileSet.add(f)
245
- }
246
- if (existsSync(routesDir)) {
247
- for (const f of walkTsFiles(routesDir))
248
- fileSet.add(f)
249
- }
250
- const files = [...fileSet].sort()
283
+ const configFile = resolve(root, 'prunelle.config.ts')
284
+ const files = discoverProjectFiles(srcDir, routesDir, configFile)
251
285
  const graph = new ModuleGraph(root)
252
286
  const { analyses } = graph
253
287
  const sources = new Map<string, string>()
@@ -265,9 +299,19 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
265
299
 
266
300
  // Exact route discovery matching `prunelle build` (`walkRoutes` skips `_components/` dirs, `.d.ts`, `.test.ts`)
267
301
  const routeFiles = existsSync(routesDir) ? walkRoutes(routesDir).sort() : []
302
+ for (const unknown of findUnknownStatusPages(root, routeFiles))
303
+ errors.push(formatDiagnostic(`${relPosix(root, unknown.file)}:1:1`, `prunelle check: ${unknown.message}`))
268
304
  const routeFileSet = new Set(routeFiles)
269
305
  const specialFiles = routeFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
270
306
  const pageFiles = routeFiles.filter(f => !basename(f).startsWith('_') && analyses.has(f) && hasRouteHandlerExport(analyses.get(f)!))
307
+ const matcherDiscovery = discoverRouteMatchers({
308
+ root,
309
+ routesDir,
310
+ routeFiles: [...specialFiles, ...pageFiles],
311
+ loadAnalysis: load,
312
+ })
313
+ for (const problem of matcherDiscovery.problems)
314
+ errors.push(formatDiagnostic(`${relPosix(root, problem.file)}:1:1`, `prunelle check: ${problem.message}`))
271
315
 
272
316
  // 3a. Unified island planning, state-read promotion, special-file checks & reachability checks (shared with `prunelle build`)
273
317
  const islands = analyzeIslands({
@@ -281,6 +325,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
281
325
  })
282
326
  for (const issue of islands.issues)
283
327
  errors.push(formatIslandIssue(issue, root, sources))
328
+ warnings.push(...islandValueWarnings(islands.valueUses, root, sources, compliance))
284
329
 
285
330
  // 3b. Static guardrails: non-serializable island props, route exports, route conflicts, missing paths()
286
331
  const seenRoutes = new Map<string, string>()
@@ -288,8 +333,20 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
288
333
  if (isInNodeModules(file))
289
334
  continue
290
335
  const rel = relPosix(root, file)
291
- for (const offset of serverNodeEnvReads(analysis, islands, file))
292
- warnings.push(formatDiagnostic(locOf(root, file, sources, offset), nodeEnvWarning(rel), 'warning'))
336
+ for (const imp of analysis.imports) {
337
+ const unresolved = unresolvedImport(file, rel, imp.source)
338
+ if (unresolved !== undefined)
339
+ errors.push(formatDiagnostic(locOf(root, file, sources, imp.start), unresolved))
340
+ if (imp.source === '@prunellejs/auth') {
341
+ const removed = imp.specifiers.find(s => s.imported === 'createRateLimiter' || s.imported === 'RateLimiter')
342
+ if (removed !== undefined)
343
+ warnings.push(formatDiagnostic(locOf(root, file, sources, imp.start), `prunelle check: ${removed.imported} was removed from @prunellejs/auth in 0.2.0: use \`rateLimit\` on \`api.route()\`/\`action()\`, \`api.rateLimiter()\` in a plugin, or \`createRateLimitStore()\` from \`prunelle/server\`.`, 'warning'))
344
+ }
345
+ }
346
+ if (file !== configFile) {
347
+ for (const offset of serverNodeEnvReads(analysis, islands, file))
348
+ warnings.push(formatDiagnostic(locOf(root, file, sources, offset), nodeEnvWarning(rel), 'warning'))
349
+ }
293
350
 
294
351
  if (file.endsWith('.tsx')) {
295
352
  for (const problem of renderProblems(analysis, islands, file, rel, 'prunelle check'))
@@ -322,11 +379,35 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
322
379
  }
323
380
  }
324
381
 
325
- // 3c. French web law compliance checks (CSS third-party URLs, LCEN legal notice, RGAA accessibility statement)
326
- warnings.push(...collectProjectComplianceWarnings({ root, srcDir, routesDir, routeFiles, analyses, compliance, site }))
382
+ // 3c. Cached route private-read guardrails (#6)
383
+ for (const problem of findCachedRoutePrivateReads({
384
+ graph,
385
+ pageFiles,
386
+ layoutsFor: file => ancestorFiles(routesDir, file, ['_layout.tsx']),
387
+ toRel: file => relPosix(root, file),
388
+ tool: 'prunelle check',
389
+ })) {
390
+ errors.push(formatDiagnostic(locOf(root, problem.file, sources, problem.offset), problem.message))
391
+ }
392
+
393
+ // 3d. French web law compliance checks (CSS third-party URLs, LCEN legal notice, RGAA accessibility statement)
394
+ warnings.push(...collectProjectComplianceWarnings({ root, srcDir, routesDir, routeFiles, analyses, compliance, consentMaxAge: loadedConfig.consent?.maxAge, site, lang: loadedConfig.lang, langFromPlugin: pluginSetsLang(plugins) }))
395
+
396
+ // 3d. Form field / schema checks & public action protection warnings (#4, #5)
397
+ const formCheck = await checkAppForms({ root, routesDir, routeFiles, graph, sources, compliance })
398
+ errors.push(...formCheck.errors)
399
+ warnings.push(...formCheck.warnings)
400
+
401
+ warnings.push(...publicDotfileWarnings(publicDir, root))
402
+ warnings.push(...securityConfigWarnings(loadedConfig.security))
403
+ warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
404
+ warnings.push(...externalRedirectWarnings(files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
405
+
406
+ // 3e. Broken internal link checks (#3)
407
+ warnings.push(...await checkAppLinks({ root, routesDir, publicDir, assetPrefix, site, config: loadedConfig, plugins, routeFiles, analyses, sources }))
327
408
 
328
- // 3d. Plugin check(ctx) hooks
329
- await runPluginChecks(plugins, { root, routesDir, outDir, assetPrefix, site }, errors, warnings)
409
+ // 3f. Plugin check(ctx) hooks
410
+ await runPluginChecks(plugins, { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories }, errors, warnings)
330
411
 
331
412
  const typecheck = options.skipTypecheck === true ? { ran: false as const, reason: "skipped by --no-typecheck" } : runTypecheck(root, errors)
332
413
 
@@ -4,9 +4,10 @@ import type { Commands, ExitRow } from '@kaynooo/cli-kit'
4
4
  import type { ScaffoldTemplate } from './new'
5
5
  import { resolve } from 'node:path'
6
6
  import { badUsage, Exit, fail, parse } from '@kaynooo/cli-kit'
7
+ import { parseByteSize } from '../build/byte-size'
7
8
 
8
9
  const TEMPLATES = ['minimal', 'fullstack', 'blog', 'app'] as const
9
- const SIZE_RE = /^(\d+(?:\.\d+)?)\s*(kb)?$/i
10
+
10
11
 
11
12
  const ROOT = { type: 'string', description: 'the app folder, when it is not the current one or the [dir] argument' } as const
12
13
  const PORT = { type: 'string', description: 'the port to listen on (PORT, then prunelle.config.ts port, then 3000; 0 picks a free one)' } as const
@@ -17,10 +18,7 @@ const USAGE_EXIT: ExitRow = [2, 'a usage error']
17
18
 
18
19
  // `--max-js 40kb`, `--max-js 40KB` or `--max-js 40960` (bytes).
19
20
  function parseSize(raw: string): number {
20
- const match = SIZE_RE.exec(raw.trim())
21
- if (match === null)
22
- return badUsage(`invalid --max-js "${raw}": give the gzipped size of a route's eager JS in bytes or KB, e.g. --max-js 40kb`)
23
- return Math.round(Number(match[1]) * (match[2] === undefined ? 1 : 1024))
21
+ return parseByteSize(raw) ?? badUsage(`invalid --max-js "${raw}": give the gzipped size of a route's eager JS in bytes or KB, e.g. --max-js 40kb`)
24
22
  }
25
23
 
26
24
  function parsePort(raw: string | number | undefined, fallback: number): number {
@@ -64,6 +62,9 @@ function newCommand(cwd: string): Commands[string] {
64
62
  const { scaffoldProject } = await import('./new')
65
63
  const template = (values.template ?? 'minimal') as ScaffoldTemplate
66
64
  const res = await failing('new', async () => scaffoldProject(rootOf(cwd, values.root, dir), { template, force: values.force === true }))
65
+
66
+ for (const file of res.overwritten)
67
+ console.log(`prunelle new: overwrote ${file}`)
67
68
  console.log(`Created Prunelle (${template}) project in ${res.root} (${res.files.length} files)`)
68
69
  console.log(`\nNext steps:\n cd ${dir}\n bun install\n bun run dev`)
69
70
  return 0
@@ -119,17 +120,22 @@ function upgradeCommand(cwd: string): Commands[string] {
119
120
  'root': ROOT,
120
121
  }, { positionals: ['[dir]'], exits: [[0, 'every file was rewritten and nothing is left to do by hand'], [1, 'bun install failed, or steps are left to do by hand (printed)'], USAGE_EXIT] })
121
122
  const root = rootOf(cwd, values.root, dir)
122
- const { upgradeProject } = await import('./upgrade')
123
+ const { notAnApp, upgradeProject } = await import('./upgrade')
124
+ const refused = notAnApp(root)
125
+ if (refused !== undefined)
126
+ return fail(refused, 1, 'run prunelle upgrade in the app\'s folder, or pass that folder as [dir]')
123
127
  const res = upgradeProject(root)
124
128
  for (const file of res.changed)
125
129
  console.log(` ${file}`)
126
- console.log(`prunelle upgrade rewrote ${res.changed.length} files`)
127
- if (res.changed.some(file => file === 'package.json' || file.endsWith('/package.json')) && values['no-install'] !== true) {
130
+ console.log(`prunelle upgrade rewrote ${res.changed.length} file${res.changed.length === 1 ? '' : 's'}`)
131
+ // The dependencies moved: the first run for this app, which renames its cookies; a later run only fixes what an older prunelle left.
132
+ const moved = res.changed.some(file => file === 'package.json' || file.endsWith('/package.json'))
133
+ if (moved && values['no-install'] !== true) {
128
134
  const install = Bun.spawnSync(['bun', 'install'], { cwd: root, stdout: 'inherit', stderr: 'inherit' })
129
135
  if (install.exitCode !== 0)
130
136
  return 1
131
137
  }
132
- if (res.changed.length > 0)
138
+ if (moved)
133
139
  console.log('Signed-in users sign in again and visitors answer the cookie banner again: prunelle names its cookies pru_session and pru_consent.')
134
140
  for (const line of res.manual)
135
141
  console.error(line)
@@ -163,6 +169,7 @@ function buildCommand(cwd: string): Commands[string] {
163
169
  run: async (args) => {
164
170
  const { values, positionals: [dir] } = parse(args, 'prunelle build [options] [dir]: builds the app into dist/', {
165
171
  'static': { type: 'boolean', description: 'export plain HTML files instead of a server' },
172
+ 'auto-prerender': { type: 'boolean', description: 'prerender static pages that read nothing from the request or clock' },
166
173
  'compile': { type: 'string', optional: { bare: '' }, description: 'also produce one binary, at [out] when given' },
167
174
  'analyze': { type: 'boolean', description: 'list each island with why it is one' },
168
175
  'json': { type: 'boolean', description: 'with --analyze, print the bundle report as JSON' },
@@ -176,7 +183,8 @@ function buildCommand(cwd: string): Commands[string] {
176
183
  const analyzeJson = values.analyze === true && values.json === true
177
184
  const { build } = await import('../build/index')
178
185
  const t0 = performance.now()
179
- const manifest = await failing('build', async () => build({ root: rootOf(cwd, values.root, dir), static: values.static === true, compile, analyze: values.analyze === true, analyzeJson, maxJs }))
186
+ const autoPrerender = values['auto-prerender'] === true ? true : undefined
187
+ const manifest = await failing('build', async () => build({ root: rootOf(cwd, values.root, dir), static: values.static === true, autoPrerender, compile, analyze: values.analyze === true, analyzeJson, maxJs }))
180
188
  const ms = (performance.now() - t0).toFixed(1)
181
189
  if (!analyzeJson)
182
190
  console.log(`prunelle build done in ${ms} ms (${manifest.routes.length} routes, ${manifest.assets.length} client assets, ${manifest.actions.length} actions)`)
@@ -185,6 +193,25 @@ function buildCommand(cwd: string): Commands[string] {
185
193
  }
186
194
  }
187
195
 
196
+ function ecoCommand(cwd: string): Commands[string] {
197
+ return {
198
+ summary: 'judge the RGESN eco-design criteria prunelle can measure, and draft the declaration',
199
+ run: async (args) => {
200
+ const { values, positionals: [dir] } = parse(args, 'prunelle eco [options] [dir]: builds the app and judges the RGESN 2024 criteria prunelle can measure', {
201
+ declaration: { type: 'string', optional: { bare: '' }, description: 'write an editable RGESN 2024 eco-design declaration page (default: src/routes/ecoconception.tsx)' },
202
+ service: { type: 'string', description: 'the service\'s name, written into --declaration' },
203
+ org: { type: 'string', description: 'the entity running the evaluation, written into --declaration' },
204
+ contact: { type: 'string', description: 'the contact email, written into --declaration' },
205
+ root: ROOT,
206
+ }, { positionals: ['[dir]'], exits: [OK, [1, 'the build failed'], USAGE_EXIT] })
207
+ const { formatEcoResult, runEco } = await import('../eco/index')
208
+ const result = await failing('eco', () => runEco({ root: rootOf(cwd, values.root, dir), declaration: values.declaration, service: values.service, organization: values.org, contactEmail: values.contact }))
209
+ console.log(formatEcoResult(result))
210
+ return 0
211
+ },
212
+ }
213
+ }
214
+
188
215
  const SERVE_EXITS: ExitRow[] = [[0, 'the server started'], [1, 'the config or the server failed to load'], USAGE_EXIT]
189
216
 
190
217
  function startCommand(cwd: string): Commands[string] {
@@ -203,6 +230,10 @@ function startCommand(cwd: string): Commands[string] {
203
230
  const { app, server } = await failing('start', async () => startServer({ root, port, hostname }))
204
231
  handleSignals(app, server)
205
232
  console.log(`prunelle server listening on http://${hostname}:${server.port}`)
233
+ const { loopbackBindNotice } = await import('../server/security')
234
+ const notice = process.env.NODE_ENV === 'production' ? loopbackBindNotice(hostname, values.host !== undefined || Boolean(process.env.HOST)) : undefined
235
+ if (notice !== undefined)
236
+ console.warn(notice)
206
237
  return 0
207
238
  },
208
239
  }
@@ -219,7 +250,7 @@ function devCommand(cwd: string): Commands[string] {
219
250
  const port = parsePort(values.port ?? (process.env.PORT || config.port), 3000)
220
251
  const hostname = values.host ?? (process.env.HOST || '127.0.0.1')
221
252
  const { devSupervisor } = await import('../dev/supervisor')
222
- const dev = await failing('dev', async () => devSupervisor({ root, port, hostname, maxRequestBodySize: resolveServerConfig(config, {}).maxRequestBodySize }))
253
+ const dev = await failing('dev', async () => devSupervisor({ root, port, hostname, maxRequestBodySize: resolveServerConfig(config, {}).maxRequestBodySize, allowedOrigins: [config.site, ...config.trustedOrigins ?? []] }))
223
254
  for (const signal of ['SIGINT', 'SIGTERM'] as const)
224
255
  process.once(signal, () => void dev.stop().finally(() => process.exit(0)))
225
256
  return 0
@@ -227,13 +258,91 @@ function devCommand(cwd: string): Commands[string] {
227
258
  }
228
259
  }
229
260
 
261
+ function docsCommand(cwd: string): Commands[string] {
262
+ return {
263
+ summary: 'search llms.txt across prunelle and installed plugins',
264
+ run: async (args) => {
265
+ const { values, positionals } = parse(args, 'prunelle docs [options] <words...>: searches llms.txt of prunelle and every installed @prunellejs/* package', {
266
+ json: { type: 'boolean', description: 'print { query, words, packages, matches } as JSON' },
267
+ limit: { type: 'string', description: 'maximum matching sections to print (default: 20)' },
268
+ root: ROOT,
269
+ }, { positionals: ['<words...>'], exits: [OK, [1, 'no matching section found'], USAGE_EXIT] })
270
+ const limit = values.limit === undefined ? undefined : Number(values.limit)
271
+ if (limit !== undefined && (!Number.isInteger(limit) || limit <= 0))
272
+ return badUsage(`invalid --limit "${values.limit}": give a positive integer`)
273
+ const query = positionals.join(' ').trim()
274
+ if (query === '')
275
+ return badUsage('give at least one search word, e.g. prunelle docs action')
276
+ const { formatDocsSearchResult, searchLlmsDocs } = await import('./docs')
277
+ const result = searchLlmsDocs(rootOf(cwd, values.root, undefined), query, { limit })
278
+ if (values.json === true) {
279
+ console.log(JSON.stringify(result, null, 2))
280
+ return result.matches.length > 0 ? 0 : 1
281
+ }
282
+ console.log(formatDocsSearchResult(result))
283
+ return result.matches.length > 0 ? 0 : 1
284
+ },
285
+ }
286
+ }
287
+
288
+ function renderCommand(cwd: string): Commands[string] {
289
+ return {
290
+ summary: 'render a URL in-process without binding a port',
291
+ run: async (args) => {
292
+ const { values, positionals: [url] } = parse(args, 'prunelle render [options] <url>: builds or reuses a test build and prints the response with no port bound', {
293
+ method: { type: 'string', short: 'X', description: 'HTTP method (default: GET, or POST when --body is passed)' },
294
+ body: { type: 'string', short: 'd', description: 'request body string' },
295
+ header: { type: 'string', short: 'H', multiple: true, description: 'request header as "Name: Value" (repeatable)' },
296
+ cookie: { type: 'string', short: 'b', multiple: true, description: 'request cookie as "name=value" (repeatable)' },
297
+ include: { type: 'boolean', short: 'i', description: 'include HTTP status line and response headers before the body' },
298
+ fresh: { type: 'boolean', description: 'force a fresh build instead of reusing the cached render build' },
299
+ root: ROOT,
300
+ }, { positionals: ['<url>'], exits: [[0, 'response status is 2xx or 3xx'], [1, 'response status is 4xx/5xx or the render failed'], USAGE_EXIT] })
301
+ const { renderUrl, writeRenderResult } = await import('./render')
302
+ const result = await failing('render', () => renderUrl({
303
+ root: rootOf(cwd, values.root, undefined),
304
+ url: url!,
305
+ method: values.method,
306
+ body: values.body,
307
+ headers: values.header,
308
+ cookies: values.cookie,
309
+ includeHeaders: values.include === true,
310
+ fresh: values.fresh === true,
311
+ }))
312
+ writeRenderResult(result, values.include === true)
313
+ return result.ok ? 0 : 1
314
+ },
315
+ }
316
+ }
317
+
318
+ function mcpCommand(cwd: string): Commands[string] {
319
+ return {
320
+ summary: 'run the Prunelle stdio MCP server for coding agents',
321
+ run: async (args) => {
322
+ const { values, positionals: [dir] } = parse(args, 'prunelle mcp [options] [dir]: runs a stdio MCP server exposing check, inspect, build analysis, render, docs, dev errors, and llms.txt resources', {
323
+ 'allow-write': { type: 'boolean', description: 'allow MCP tools that write build output to disk' },
324
+ 'root': ROOT,
325
+ }, { positionals: ['[dir]'], exits: [OK, [1, 'the MCP server exited with an error'], USAGE_EXIT] })
326
+ const { runPrunelleMcpStdio } = await import('./mcp')
327
+ return await failing('mcp', () => runPrunelleMcpStdio({
328
+ root: rootOf(cwd, values.root, dir),
329
+ allowWrite: values['allow-write'] === true,
330
+ }))
331
+ },
332
+ }
333
+ }
334
+
230
335
  export function builtinCommands(cwd: string): Commands {
231
336
  return {
232
337
  new: newCommand(cwd),
233
338
  check: checkCommand(cwd),
234
339
  inspect: inspectCommand(cwd),
340
+ docs: docsCommand(cwd),
341
+ render: renderCommand(cwd),
342
+ mcp: mcpCommand(cwd),
235
343
  dev: devCommand(cwd),
236
344
  build: buildCommand(cwd),
345
+ eco: ecoCommand(cwd),
237
346
  start: startCommand(cwd),
238
347
  upgrade: upgradeCommand(cwd),
239
348
  }