prunelle 0.7.3 → 0.8.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 (63) hide show
  1. package/llms.txt +20 -18
  2. package/package.json +1 -1
  3. package/src/a11y/index.ts +9 -2
  4. package/src/build/graph.ts +1 -1
  5. package/src/build/index.ts +30 -31
  6. package/src/build/island-promote.ts +1 -1
  7. package/src/build/output.ts +1 -1
  8. package/src/build/prerender.ts +29 -13
  9. package/src/build/routes.ts +19 -1
  10. package/src/build/static.ts +24 -2
  11. package/src/cli/check-forms.ts +16 -6
  12. package/src/cli/check-links.ts +13 -10
  13. package/src/cli/check-security.ts +94 -12
  14. package/src/cli/check.ts +3 -2
  15. package/src/cli/commands.ts +3 -3
  16. package/src/cli/upgrade.ts +36 -3
  17. package/src/compiler/analyze.ts +16 -2
  18. package/src/compiler/compliance.ts +4 -0
  19. package/src/compiler/dom-attrs.ts +4 -1
  20. package/src/compiler/dom.ts +41 -15
  21. package/src/compiler/emit.ts +1 -1
  22. package/src/compiler/shared.ts +9 -16
  23. package/src/compiler/ssr-helpers.ts +45 -21
  24. package/src/compiler/ssr.ts +32 -16
  25. package/src/context.ts +2 -0
  26. package/src/dev/error-log.ts +1 -1
  27. package/src/dev/index.ts +1 -1
  28. package/src/dev/supervisor.ts +2 -2
  29. package/src/dom/attrs.ts +9 -1
  30. package/src/dom/island.ts +30 -4
  31. package/src/jsx-runtime.ts +1 -1
  32. package/src/plugins/context.ts +18 -1
  33. package/src/plugins/services.ts +1 -0
  34. package/src/plugins/types.ts +1 -1
  35. package/src/reactivity/index.ts +14 -2
  36. package/src/server/action.ts +26 -18
  37. package/src/server/app-secret.ts +8 -9
  38. package/src/server/assets.ts +22 -4
  39. package/src/server/consent.ts +7 -2
  40. package/src/server/cookies.ts +8 -1
  41. package/src/server/document.ts +5 -2
  42. package/src/server/errors.ts +57 -26
  43. package/src/server/health.ts +2 -2
  44. package/src/server/http.ts +1 -1
  45. package/src/server/index.ts +20 -18
  46. package/src/server/page.ts +12 -15
  47. package/src/server/public.ts +1 -1
  48. package/src/server/rate-limit.ts +36 -12
  49. package/src/server/route-cache.ts +9 -10
  50. package/src/server/route-table.ts +38 -13
  51. package/src/server/router.ts +4 -4
  52. package/src/server/sanitize-html.ts +21 -7
  53. package/src/server/security.ts +56 -15
  54. package/src/server/serve-handlers.ts +3 -3
  55. package/src/server/start.ts +2 -2
  56. package/src/server/static-dir.ts +3 -10
  57. package/src/server/stream.ts +4 -4
  58. package/src/ssr/consent-banner.ts +3 -1
  59. package/src/ssr/context.ts +85 -2
  60. package/src/ssr/index.ts +16 -4
  61. package/src/ssr/navigation.ts +1 -1
  62. package/src/style.ts +9 -7
  63. package/src/unrenderable.ts +15 -5
@@ -8,7 +8,7 @@ import type { ParamMatcher, ParamMatcherMap, ParsedPatternSegment } from '../ser
8
8
  import { existsSync, readFileSync, statSync } from 'node:fs'
9
9
  import { basename, resolve } from 'node:path'
10
10
  import { pathToFileURL } from 'node:url'
11
- import { isInNodeModules, relPosix, walkAllFiles, walkFiles } from '../build/files'
11
+ import { isHiddenPublicPath, isInNodeModules, relPosix, walkAllFiles, walkFiles } from '../build/files'
12
12
  import { isInside } from '../build/is-inside'
13
13
  import { discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, SPECIAL_ROUTE_FILES } from '../build/routes'
14
14
  import { walk } from '../compiler/ast'
@@ -46,6 +46,12 @@ function normalizePathname(raw: string): string {
46
46
  return p.length > 1 && p.endsWith('/') ? (p.replace(/\/+$/, '') || '/') : p
47
47
  }
48
48
 
49
+ function decodePathname(raw: string): string {
50
+ const norm = normalizePathname(raw)
51
+ const decoded = decodeRequestPath(norm)?.staticPath
52
+ return decoded !== undefined ? normalizePathname(decoded) : norm
53
+ }
54
+
49
55
  const isInternalLink = (raw: string): boolean => raw.startsWith('/') && !raw.startsWith('//')
50
56
  const matchesLinkIgnore = (raw?: string): boolean => { const t = (raw ?? '').trim(); return t === '' || t.split(/[\s,]+/).some(tok => LINK_IGNORE_TOKENS.has(tok)) }
51
57
  const spaces = (n: number): string => ' '.repeat(Math.max(0, n))
@@ -236,7 +242,7 @@ function collectPublicPaths(publicDir: string, emittedPublic: readonly string[])
236
242
  out.add(clean === 'index.html' ? '/' : `/${clean.slice(0, -5)}`)
237
243
  if (clean.endsWith('/index.html')) out.add(`/${clean.slice(0, -'/index.html'.length)}`)
238
244
  }
239
- if (existsSync(publicDir)) walkAllFiles(publicDir).forEach(abs => add(relPosix(publicDir, abs)))
245
+ if (existsSync(publicDir)) walkAllFiles(publicDir).forEach((abs) => { const rel = relPosix(publicDir, abs); if (!isHiddenPublicPath(rel)) add(rel) })
240
246
  emittedPublic.forEach(add)
241
247
  return out
242
248
  }
@@ -343,16 +349,13 @@ function createLinkResolver(opts: {
343
349
  const { router, publicPaths, dynamicPatterns, staticPaths, suggestionPool, prefixSuggestionPool, locales } = opts
344
350
  const assetPrefix = opts.assetPrefix.replace(/\/+$/, '')
345
351
  const isAsset = (p: string): boolean => assetPrefix !== '' && (p === assetPrefix || p.startsWith(`${assetPrefix}/`))
346
- const hasPublic = (p: string): boolean => {
347
- if (publicPaths.has(p)) return true
348
- const decoded = decodeRequestPath(p)?.staticPath
349
- return decoded !== undefined && publicPaths.has(normalizePathname(decoded))
350
- }
352
+ const hasPublic = (p: string): boolean => publicPaths.has(p) || publicPaths.has(decodePathname(p))
351
353
  const matchExact = (p: string): { ok: true } | { ok: false, miss?: RouteEntry } => {
352
354
  if (hasPublic(p)) return { ok: true }
353
355
  const hit = router.match(p)
354
356
  if (hit === undefined) return { ok: false }
355
- return hit.data.knownPaths !== undefined && !hit.data.knownPaths.has(p) ? { ok: false, miss: hit.data } : { ok: true }
357
+ if (hit.data.knownPaths === undefined) return { ok: true }
358
+ return hit.data.knownPaths.has(p) || hit.data.knownPaths.has(decodePathname(p)) ? { ok: true } : { ok: false, miss: hit.data }
356
359
  }
357
360
  const checkExact = (raw: string): string | undefined => {
358
361
  const trimmed = raw.trim()
@@ -491,7 +494,7 @@ function discoverCollectionDirs(root: string, plugins: readonly PrunellePlugin[]
491
494
  for (const plugin of plugins) {
492
495
  if (plugin.name !== '@prunellejs/content' || plugin.watchPaths === undefined) continue
493
496
  try { (typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : plugin.watchPaths).forEach(addDir) }
494
- catch (err) { void err }
497
+ catch {}
495
498
  }
496
499
  for (const [file, analysis] of analyses) {
497
500
  if (isInNodeModules(file) || !isInside(root, file)) continue
@@ -599,7 +602,7 @@ export async function checkAppLinks(input: LinkCheckInput): Promise<string[]> {
599
602
  const pattern = fileToRoutePath(routesDir, file)
600
603
  const isDynamic = pattern.includes(':') || pattern.includes('*')
601
604
  const knownPathList = isDynamic && analysis.hasPaths ? await evaluateRoutePaths(file, analysis, appCtx) : undefined
602
- register(pattern, { pattern, fileRel: relPosix(root, file), isDynamic, knownPaths: knownPathList !== undefined ? new Set(knownPathList) : undefined, knownPathList })
605
+ register(pattern, { pattern, fileRel: relPosix(root, file), isDynamic, knownPaths: knownPathList !== undefined ? new Set(knownPathList.map(decodePathname)) : undefined, knownPathList })
603
606
  }
604
607
  probe.pluginRoutes.forEach(p => register(p, { pattern: p, isDynamic: p.includes(':') || p.includes('*') }))
605
608
  if (config.consent !== undefined) {
@@ -1,9 +1,14 @@
1
1
  // `prunelle check` warnings about what weakens an app's defences: dotfiles under public/, and the security opt-outs in its config.
2
2
 
3
+ import type { Node } from 'oxc-parser'
4
+ import type { ComplianceConfig } from '../compiler/compliance'
3
5
  import type { SecurityHeadersOptions } from '../server/security'
4
6
  import { relative } from 'node:path'
7
+ import { parseSync } from 'oxc-parser'
5
8
  import { isHiddenPublicPath, walkAllFiles } from '../build/files'
6
- import { formatDiagnostic } from '../compiler/shared'
9
+ import { walk } from '../compiler/ast'
10
+ import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
11
+ import { formatDiagnostic, unwrapTsExpr } from '../compiler/shared'
7
12
  import { resolveCspPolicy } from '../server/security'
8
13
 
9
14
  /** 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. */
@@ -15,18 +20,82 @@ export function publicDotfileWarnings(publicDir: string, root: string): string[]
15
20
  .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
21
  }
17
22
 
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
23
+ const EXTERNAL_URL_PREFIX_RE = /^(?:https?:)?\/\//i
24
+
25
+ function isResponseObject(node: Node): boolean {
26
+ const expr = unwrapTsExpr(node)
27
+ if (expr.type === 'Identifier')
28
+ return expr.name === 'Response'
29
+ return expr.type === 'MemberExpression'
30
+ && !expr.computed
31
+ && expr.object.type === 'Identifier'
32
+ && expr.object.name === 'globalThis'
33
+ && expr.property.type === 'Identifier'
34
+ && expr.property.name === 'Response'
35
+ }
36
+
37
+ function leadingStringLiteral(node: Node): string | undefined {
38
+ const expr = unwrapTsExpr(node)
39
+ if (expr.type === 'Literal' && typeof expr.value === 'string')
40
+ return expr.value
41
+ if (expr.type === 'TemplateLiteral')
42
+ return expr.quasis[0]?.value.cooked ?? expr.quasis[0]?.value.raw ?? ''
43
+ return undefined
44
+ }
45
+
46
+ function allowsExternalRedirect(arg: Node | undefined): boolean {
47
+ if (arg === undefined || arg.type === 'SpreadElement')
48
+ return false
49
+ const expr = unwrapTsExpr(arg)
50
+ if (expr.type !== 'ObjectExpression')
51
+ return true
52
+ let external: boolean | undefined
53
+ for (const prop of expr.properties) {
54
+ if (prop.type === 'SpreadElement') {
55
+ external = true
56
+ continue
57
+ }
58
+ const key = !prop.computed && prop.key.type === 'Identifier'
59
+ ? prop.key.name
60
+ : prop.key.type === 'Literal' && typeof prop.key.value === 'string'
61
+ ? prop.key.value
62
+ : undefined
63
+ if (key !== 'external')
64
+ continue
65
+ const val = unwrapTsExpr(prop.value)
66
+ const definitelyNotTrue = (val.type === 'Literal' && val.value !== true)
67
+ || (val.type === 'Identifier' && val.name === 'undefined')
68
+ external = !definitelyNotTrue
69
+ }
70
+ return external === true
71
+ }
20
72
 
21
73
  /** One warning per `ctx.redirect("https://other.site/…")` that lacks `{ external: true }`: since 0.x it throws at runtime. */
22
74
  export function externalRedirectWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
23
75
  const warnings: string[] = []
24
76
  for (const file of files) {
25
77
  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
- }
78
+ if (!code.includes('.redirect('))
79
+ continue
80
+ const lang = file.endsWith('.tsx') || file.endsWith('.jsx') ? 'tsx' : 'ts'
81
+ const parsed = parseSync(file, code, { lang, sourceType: 'module' })
82
+ walk(parsed.program, (node) => {
83
+ if (node.type !== 'CallExpression')
84
+ return
85
+ const callee = unwrapTsExpr(node.callee)
86
+ if (callee.type !== 'MemberExpression' || callee.computed || callee.property.type !== 'Identifier' || callee.property.name !== 'redirect')
87
+ return
88
+ if (isResponseObject(callee.object))
89
+ return
90
+ const first = node.arguments[0]
91
+ if (first === undefined || first.type === 'SpreadElement')
92
+ return
93
+ const prefix = leadingStringLiteral(first)
94
+ if (prefix === undefined || !EXTERNAL_URL_PREFIX_RE.test(prefix))
95
+ return
96
+ if (!allowsExternalRedirect(node.arguments[2]))
97
+ warnings.push(formatDiagnostic(locate(file, callee.object.end), '[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'))
98
+ })
30
99
  }
31
100
  return warnings
32
101
  }
@@ -44,7 +113,7 @@ export function securityConfigWarnings(security: SecurityHeadersOptions | false
44
113
  const csp = resolveCspPolicy(security)
45
114
  const loose = (csp ?? '').split(';')
46
115
  .map(part => part.trim().split(/\s+/))
47
- .filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.includes('\'unsafe-inline\''))
116
+ .filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.some(token => token.toLowerCase() === '\'unsafe-inline\''))
48
117
  .map(([name]) => name!.toLowerCase())
49
118
  return loose.length === 0
50
119
  ? []
@@ -53,12 +122,25 @@ export function securityConfigWarnings(security: SecurityHeadersOptions | false
53
122
 
54
123
  const CSRF_OFF_RE = /export\s+const\s+csrf\s*=\s*false\b/g
55
124
 
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[] {
125
+ /** 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. A route that does says so with `// prunelle-ignore security/csrf-off` above the export. */
126
+ export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, compliance?: ComplianceConfig | undefined): string[] {
127
+ if (isRuleIgnored('security/csrf-off', compliance))
128
+ return []
58
129
  const warnings: string[] = []
59
130
  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'))
131
+ const code = read(file)
132
+ const ignores = parsePrunelleIgnores(code)
133
+ for (const match of code.matchAll(CSRF_OFF_RE)) {
134
+ if (!isIgnoredAt(ignores, 'security/csrf-off', match.index))
135
+ 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 say so with `// prunelle-ignore security/csrf-off` above the export; drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
136
+ }
62
137
  }
63
138
  return warnings
64
139
  }
140
+
141
+ /** A warning when `trustProxy` is on and `site` is not: any `X-Forwarded-Host` then counts as the app's host, though a proxy that sets `Host` alone passes the client's one through. */
142
+ export function proxyWithoutSiteWarnings(trustProxy: boolean | number | undefined, site: string | undefined, compliance?: ComplianceConfig | undefined): string[] {
143
+ if (trustProxy === undefined || trustProxy === false || trustProxy === 0 || site !== undefined || isRuleIgnored('security/proxy-no-site', compliance))
144
+ return []
145
+ return [formatDiagnostic('prunelle.config.ts:1:1', '[security/proxy-no-site] trustProxy is on but site is not set, so the origin check and ctx.redirect take any X-Forwarded-Host as this app\'s host, even one a client sent past a proxy that does not overwrite it: set site: \'https://your.domain\' in prunelle.config.ts, and list any other domain the app answers on in trustedOrigins.', 'warning')]
146
+ }
package/src/cli/check.ts CHANGED
@@ -24,7 +24,7 @@ import { normalizeConsentConfig } from '../server/consent'
24
24
  import { checkAppForms } from './check-forms'
25
25
  import { unresolvedImport } from './check-imports'
26
26
  import { checkAppLinks } from './check-links'
27
- import { csrfOffWarnings, externalRedirectWarnings, publicDotfileWarnings, securityConfigWarnings } from './check-security'
27
+ import { csrfOffWarnings, externalRedirectWarnings, proxyWithoutSiteWarnings, publicDotfileWarnings, securityConfigWarnings } from './check-security'
28
28
 
29
29
  /** Whether `prunelle check` typechecked the app, with which tool, or why it did not. */
30
30
  export type TypecheckRun = { ran: true, tool: string } | { ran: false, reason: string }
@@ -394,7 +394,8 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
394
394
 
395
395
  warnings.push(...publicDotfileWarnings(publicDir, root))
396
396
  warnings.push(...securityConfigWarnings(loadedConfig.security))
397
- warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
397
+ warnings.push(...proxyWithoutSiteWarnings(loadedConfig.trustProxy, site, compliance))
398
+ warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset), compliance))
398
399
  warnings.push(...externalRedirectWarnings(files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
399
400
 
400
401
  // 3e. Broken internal link checks (#3)
@@ -130,16 +130,16 @@ function upgradeCommand(cwd: string): Commands[string] {
130
130
  console.log(`prunelle upgrade rewrote ${res.changed.length} file${res.changed.length === 1 ? '' : 's'}`)
131
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
132
  const moved = res.changed.some(file => file === 'package.json' || file.endsWith('/package.json'))
133
+ let installFailed = false
133
134
  if (moved && values['no-install'] !== true) {
134
135
  const install = Bun.spawnSync(['bun', 'install'], { cwd: root, stdout: 'inherit', stderr: 'inherit' })
135
- if (install.exitCode !== 0)
136
- return 1
136
+ installFailed = install.exitCode !== 0
137
137
  }
138
138
  if (moved)
139
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.')
140
140
  for (const line of res.manual)
141
141
  console.error(line)
142
- if (res.manual.length > 0)
142
+ if (installFailed || res.manual.length > 0)
143
143
  return 1
144
144
  console.log('Next: prunelle check')
145
145
  return 0
@@ -56,9 +56,18 @@ const PRUNELLE_SOURCE_RE = /^prunelle(\/.*)?$/
56
56
  const NPM_KAY_ALIAS_RE = /^npm:(@kayjs\/[\w-]+)(?:@.*)?$/
57
57
  const ESCAPE_RE = /[.*+?^${}()|[\]\\]/g
58
58
  const GITIGNORE_CACHE_RE = /(?:^|\/)\.prunelle-cache(?:\/|$|\s)/m
59
+ const PARSE_LOC_RE = /:(\d+):\d+:\s*error:\s*(?:prunelle compiler:\s*)?([^\n]+)/
59
60
 
60
61
  const apply = (text: string, rules: readonly [RegExp, string][]): string => rules.reduce((out, [re, to]) => out.replace(re, to), text)
61
62
 
63
+ function formatParseManual(file: string, err: unknown, action: string): string {
64
+ const msg = err instanceof Error ? err.message : String(err)
65
+ const match = PARSE_LOC_RE.exec(msg)
66
+ const line = match?.[1] ?? '1'
67
+ const reason = match?.[2]?.trim() ?? msg.split('\n', 1)[0]!.trim()
68
+ return `${file}:${line}: ${reason} — ${action}.`
69
+ }
70
+
62
71
  /** Why `root` is no app to upgrade: neither on kay nor prunelle, nor a workspace holding one; undefined when it is one. */
63
72
  export function notAnApp(root: string): string | undefined {
64
73
  if (hasKayOrPrunelle(root) || existsSync(join(root, 'kay.config.ts')) || existsSync(join(root, 'prunelle.config.ts')) || workspaceMembers(root).some(m => hasKayOrPrunelle(join(root, m))))
@@ -112,7 +121,16 @@ function upgradeDir(root: string, inheritedAliases?: ReadonlyMap<string, string>
112
121
  const publicDir = configuredPublicDir(root)
113
122
  for (const file of sourceFiles(root, publicDir)) {
114
123
  const text = readFileSync(join(root, file), 'utf8')
115
- const renamed = SOURCE_FILE_RE.test(file) ? renameKayNames(file, text, aliases) : text
124
+ let renamed = text
125
+ if (SOURCE_FILE_RE.test(file)) {
126
+ try {
127
+ renamed = renameKayNames(file, text, aliases)
128
+ }
129
+ catch (err) {
130
+ manual.push(formatParseManual(file, err, 'fix the syntax error and re-run prunelle upgrade'))
131
+ continue
132
+ }
133
+ }
116
134
  const next = apply(apply(renamed, PATH_RULES), WIRE_RULES)
117
135
  write(file, text, next)
118
136
  if (SOURCE_FILE_RE.test(file) && next !== text)
@@ -197,7 +215,14 @@ function configuredPublicDir(root: string): string {
197
215
  : existsSync(join(root, 'kay.config.ts')) ? 'kay.config.ts' : undefined
198
216
  if (file === undefined)
199
217
  return resolve(root, 'public')
200
- const program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
218
+ let program: ReturnType<typeof parseTsx>
219
+ try {
220
+ program = parseTsx(file, readFileSync(join(root, file), 'utf8'))
221
+ }
222
+ catch (err) {
223
+ void err
224
+ return resolve(root, 'public')
225
+ }
201
226
  let value: string | undefined
202
227
  walk(program.body, (node) => {
203
228
  if (value !== undefined)
@@ -349,7 +374,15 @@ function exportsOf(file: string): Set<string> {
349
374
 
350
375
  // A name kay exported that prunelle no longer does is reported on the line importing it.
351
376
  function checkImports(file: string, code: string, manual: string[]): void {
352
- for (const stmt of parseTsx(file, code).body) {
377
+ let body: ReturnType<typeof parseTsx>['body']
378
+ try {
379
+ body = parseTsx(file, code).body
380
+ }
381
+ catch (err) {
382
+ manual.push(formatParseManual(file, err, 'fix the syntax error and check its prunelle imports'))
383
+ return
384
+ }
385
+ for (const stmt of body) {
353
386
  if (stmt.type !== 'ImportDeclaration' || !PRUNELLE_SOURCE_RE.test(stmt.source.value))
354
387
  continue
355
388
  const line = code.slice(0, stmt.start).split('\n').length
@@ -308,6 +308,16 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
308
308
  scan.localInits.set(d.id.name, d.init)
309
309
  }
310
310
  }
311
+ // `import X from './x'; export default X` (or `export { X }`) re-exports './x', so islands and state behind it are followed like `export { default } from './x'`.
312
+ const reexportImported = (exported: string, local: string, start: number): void => {
313
+ for (const imp of imports.imports) {
314
+ const spec = imp.specifiers.find(s => s.local === local && s.imported !== '*')
315
+ if (spec !== undefined) {
316
+ scan.reexports.push({ exported, local: spec.imported, source: imp.source, start })
317
+ return
318
+ }
319
+ }
320
+ }
311
321
  const addExport = (exported: string, local: string | undefined): void => {
312
322
  scan.exportedNames.push(exported)
313
323
  if (local !== undefined)
@@ -335,8 +345,10 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
335
345
  addExport('default', decl.type === 'Identifier' ? decl.name : named ?? 'default')
336
346
  if (isAsyncFunction(decl))
337
347
  scan.hasAsyncDefault = true
338
- else if (decl.type === 'Identifier')
348
+ else if (decl.type === 'Identifier') {
339
349
  scan.defaultLocal = decl.name
350
+ reexportImported('default', decl.name, stmt.start)
351
+ }
340
352
  else
341
353
  scan.localInits.set('default', decl)
342
354
  }
@@ -349,7 +361,9 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
349
361
  addExport(exported, stmt.source === null ? local : undefined)
350
362
  if (stmt.source !== null)
351
363
  scan.reexports.push({ exported, local, source: stmt.source.value, start: stmt.start })
352
- else if (exported === 'default')
364
+ else
365
+ reexportImported(exported, local, stmt.start)
366
+ if (stmt.source === null && exported === 'default')
353
367
  scan.defaultLocal = local
354
368
  }
355
369
  if (stmt.declaration !== null)
@@ -41,6 +41,8 @@ export type ComplianceRule =
41
41
  | 'lcen/legal-notice'
42
42
  | 'rgaa/document-lang'
43
43
  | 'rgaa/accessibility-statement'
44
+ | 'security/csrf-off'
45
+ | 'security/proxy-no-site'
44
46
  | FormWarningRule
45
47
 
46
48
  /** The warnings of the form-vs-action check (`cli/check-forms.ts`), silenced like the compliance rules. */
@@ -69,6 +71,8 @@ const COMPLIANCE_RULES = new Set<ComplianceRule>([
69
71
  'lcen/legal-notice',
70
72
  'rgaa/document-lang',
71
73
  'rgaa/accessibility-statement',
74
+ 'security/csrf-off',
75
+ 'security/proxy-no-site',
72
76
  'action/unguarded-public-form',
73
77
  'form/invalid-option',
74
78
  'form/schema-unsupported',
@@ -156,7 +156,10 @@ function emitDomExprAttr(
156
156
  }
157
157
  else if (DOM_PROPS.has(name)) {
158
158
  const targetOps = isSelect && name === 'value' ? postChildOps : ops
159
- targetOps.push(wrapDomOp(`${use('setProp')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`, isStatic, use))
159
+ // Only a <select multiple> pulls in setSelectValues, so other pages ship none of it.
160
+ const multiple = isSelect && name === 'value' && ctx.el.openingElement.attributes.some(a => a.type === 'JSXAttribute' && jsxTagName(a.name) === 'multiple')
161
+ const call = multiple ? `${use('setSelectValues')}(${elVar}, ${exprCode})` : `${use('setProp')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`
162
+ targetOps.push(wrapDomOp(call, isStatic, use))
160
163
  }
161
164
  else {
162
165
  ops.push(wrapDomOp(`${use('setAttr')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`, isStatic, use))
@@ -451,7 +451,7 @@ function compileElementTree(ctx: DomCompilerCtx, rootEl: JSXElement, scopeRewrit
451
451
  resolveElementAliases(tree)
452
452
 
453
453
  const rootTag = jsxTagName(rootEl.openingElement.name)
454
- const tmplName = `_t${ctx.templates.length}`
454
+ const tmplName = ctx.freshVar('_t')
455
455
  const isSvg = ctx.svgDepth > 0 ? rootTag !== 'svg' : SVG_CHILD_TAGS.has(rootTag)
456
456
  ctx.templates.push({ name: tmplName, html, isSvg })
457
457
 
@@ -478,9 +478,17 @@ function compileFragmentChildren(ctx: DomCompilerCtx, children: readonly JSXChil
478
478
  }
479
479
  }
480
480
 
481
- const emitFragRangeOp = (hydrateCall: string, mountCall: string, needsRemoveChild: boolean): string => {
481
+ const emitFragRangeOp = (
482
+ hydrate: (sVar: string) => string,
483
+ mount: (pVar: string, mVar: string) => string,
484
+ needsRemoveChild: boolean,
485
+ ): string => {
486
+ const sVar = ctx.freshVar('_s')
487
+ const fVar = ctx.freshVar('_f')
488
+ const mVar = ctx.freshVar('_m')
489
+ const pVar = ctx.freshVar('_p')
482
490
  const removeProp = needsRemoveChild ? ', removeChild: (n) => n.parentNode && n.parentNode.removeChild(n)' : ''
483
- return `(() => { const _s = ${ctx.use('claimRange')}(); if (_s !== null) { ${hydrateCall}; return null; } const _f = document.createDocumentFragment(); _f.appendChild(document.createComment("")); const _m = _f.appendChild(document.createComment("")); const _p = { insertBefore: (n, r) => (_m.parentNode || _f).insertBefore(n, r)${removeProp} }; ${mountCall}; return _f; })()`
491
+ return `(() => { const ${sVar} = ${ctx.use('claimRange')}(); if (${sVar} !== null) { ${hydrate(sVar)}; return null; } const ${fVar} = document.createDocumentFragment(); ${fVar}.appendChild(document.createComment("")); const ${mVar} = ${fVar}.appendChild(document.createComment("")); const ${pVar} = { insertBefore: (n, r) => (${mVar}.parentNode || ${fVar}).insertBefore(n, r)${removeProp} }; ${mount(pVar, mVar)}; return ${fVar}; })()`
484
492
  }
485
493
 
486
494
  for (const { slot, marker } of planned) {
@@ -500,17 +508,21 @@ function compileFragmentChildren(ctx: DomCompilerCtx, children: readonly JSXChil
500
508
  }
501
509
  else if (slot.kind === 'loop') {
502
510
  const compiled = compileLoopCall(ctx, slot.match, scopeRewrites)
503
- if (compiled.isStatic)
504
- items.push(`(() => { const _s = ${ctx.use('claimRange')}(); if (_s !== null) { ${compiled.call('_s.parentNode', '_s')}; return null; } const _f = document.createDocumentFragment(); ${compiled.call('_f', 'null')}; return _f; })()`)
505
- else
506
- items.push(emitFragRangeOp(compiled.call('_s.parentNode', '_s'), compiled.call('_p', '_m'), true))
511
+ if (compiled.isStatic) {
512
+ const sVar = ctx.freshVar('_s')
513
+ const fVar = ctx.freshVar('_f')
514
+ items.push(`(() => { const ${sVar} = ${ctx.use('claimRange')}(); if (${sVar} !== null) { ${compiled.call(`${sVar}.parentNode`, sVar)}; return null; } const ${fVar} = document.createDocumentFragment(); ${compiled.call(fVar, 'null')}; return ${fVar}; })()`)
515
+ }
516
+ else {
517
+ items.push(emitFragRangeOp(s => compiled.call(`${s}.parentNode`, s), (p, m) => compiled.call(p, m), true))
518
+ }
507
519
  }
508
520
  else if (slot.kind === 'and-show') {
509
521
  const whenCode = ctx.compileExpression(slot.expr.left, scopeRewrites)
510
522
  const trueCode = compileRootJsx(ctx, slot.right, scopeRewrites)
511
523
  items.push(emitFragRangeOp(
512
- `${ctx.use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode})`,
513
- `${ctx.use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode})`,
524
+ s => `${ctx.use('show')}(${s}.parentNode, ${s}, () => ${whenCode}, () => ${trueCode})`,
525
+ (p, m) => `${ctx.use('show')}(${p}, ${m}, () => ${whenCode}, () => ${trueCode})`,
514
526
  false,
515
527
  ))
516
528
  }
@@ -519,17 +531,20 @@ function compileFragmentChildren(ctx: DomCompilerCtx, children: readonly JSXChil
519
531
  const trueCode = isJsxNode(slot.cons) ? compileRootJsx(ctx, slot.cons, scopeRewrites) : ctx.compileExpression(slot.cons, scopeRewrites)
520
532
  const falseCode = isJsxNode(slot.alt) ? compileRootJsx(ctx, slot.alt, scopeRewrites) : ctx.compileExpression(slot.alt, scopeRewrites)
521
533
  items.push(emitFragRangeOp(
522
- `${ctx.use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
523
- `${ctx.use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
534
+ s => `${ctx.use('show')}(${s}.parentNode, ${s}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
535
+ (p, m) => `${ctx.use('show')}(${p}, ${m}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
524
536
  false,
525
537
  ))
526
538
  }
527
539
  else {
528
540
  const exprCode = ctx.compileExpression(slot.expr, scopeRewrites)
529
- if (marker === 'range')
541
+ if (marker === 'range') {
530
542
  items.push(`${ctx.use('fragInsert')}(() => (${exprCode}))`)
531
- else
532
- items.push(`(() => { const _t = ${ctx.use('fragText')}("", true); ${formatSetTextOp('_t', `(${exprCode})`, slot.expr, scopeRewrites, ctx.use)} return _t; })()`)
543
+ }
544
+ else {
545
+ const tVar = ctx.freshVar('_t')
546
+ items.push(`(() => { const ${tVar} = ${ctx.use('fragText')}("", true); ${formatSetTextOp(tVar, `(${exprCode})`, slot.expr, scopeRewrites, ctx.use)} return ${tVar}; })()`)
547
+ }
533
548
  }
534
549
  }
535
550
  flushStatic()
@@ -563,13 +578,24 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
563
578
  const used = new Set<string>()
564
579
  const templates: { name: string, html: string, isSvg?: boolean }[] = []
565
580
  const delegatedEvents = new Set<string>()
581
+ const taken = new Set(code.match(/\b_[\w$]*/g))
582
+ const counters = new Map<string, number>()
566
583
  let varCounter = 0
567
584
 
568
585
  const use = (name: string): string => {
569
586
  used.add(name)
570
587
  return `__${name}`
571
588
  }
572
- const freshVar = (prefix = '_e'): string => `${prefix}${varCounter++}`
589
+ const freshVar = (prefix = '_e'): string => {
590
+ let n = counters.get(prefix) ?? 0
591
+ let name: string
592
+ do {
593
+ name = `${prefix}${n++}`
594
+ } while (taken.has(name))
595
+ counters.set(prefix, n)
596
+ taken.add(name)
597
+ return name
598
+ }
573
599
 
574
600
  // Client builds keep the `load` binding, so every export form stays valid, and drop its server-only code.
575
601
  for (const node of loadNodes) {
@@ -20,7 +20,7 @@ export const DELEGATED_EVENTS = new Set([
20
20
  ])
21
21
 
22
22
  // Helpers kept out of the dom core, which every island loads: a page pays for them only when one of its islands binds them.
23
- const ATTR_HELPERS = ['setAttr', 'setClass', 'setProp', 'setStyle']
23
+ const ATTR_HELPERS = ['setAttr', 'setClass', 'setProp', 'setSelectValues', 'setStyle']
24
24
  const CLAIM_HELPERS = ['eachStatic']
25
25
  const EXTRA_HELPERS = ['catchBoundary', 'fragInsert', 'insert', 'mergeProps', 'omit', 'propDefault', 'setInnerHtml', 'show', 'spread']
26
26
 
@@ -367,28 +367,21 @@ type PrunelleTag = 'Head' | 'Region' | 'Suspense' | 'ConsentGate' | 'ConsentBann
367
367
 
368
368
  const PRUNELLE_TAGS = new Set<string>(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'Catch'])
369
369
 
370
- /** Resolves a JSX tag (direct, aliased, or namespaced via `prunelle`) to its canonical Prunelle tag. */
370
+ /** Resolves a JSX tag (direct, aliased, or namespaced via `prunelle`) to its canonical Prunelle tag; a tag not imported from `prunelle`, such as a component the file declares, is never one. */
371
371
  export function resolvePrunelleTag(tag: string, imports: readonly PrunelleTagBinding[]): PrunelleTag | undefined {
372
- let boundElsewhere = false
373
372
  for (const imp of imports) {
374
- const isPrunelle = imp.source === 'prunelle'
373
+ if (imp.source !== 'prunelle')
374
+ continue
375
375
  for (const spec of imp.specifiers) {
376
- if (isPrunelle) {
377
- if (spec.local === tag && PRUNELLE_TAGS.has(spec.imported))
378
- return spec.imported as PrunelleTag
379
- if (spec.imported === '*' && tag.startsWith(`${spec.local}.`)) {
380
- const member = tag.slice(spec.local.length + 1)
381
- if (PRUNELLE_TAGS.has(member))
382
- return member as PrunelleTag
383
- }
384
- }
385
- else if (spec.local === tag) {
386
- boundElsewhere = true
376
+ if (spec.local === tag && PRUNELLE_TAGS.has(spec.imported))
377
+ return spec.imported as PrunelleTag
378
+ if (spec.imported === '*' && tag.startsWith(`${spec.local}.`)) {
379
+ const member = tag.slice(spec.local.length + 1)
380
+ if (PRUNELLE_TAGS.has(member))
381
+ return member as PrunelleTag
387
382
  }
388
383
  }
389
384
  }
390
- if (!boundElsewhere && PRUNELLE_TAGS.has(tag))
391
- return tag as PrunelleTag
392
385
  return undefined
393
386
  }
394
387