prunelle 0.1.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) 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 +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  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 +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -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 +636 -0
  36. package/src/cli/check-imports.ts +31 -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 +101 -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 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -17,6 +17,9 @@ const COMPRESSIBLE_EXACT = new Set([
17
17
  'application/atom+xml',
18
18
  'application/wasm',
19
19
  'image/svg+xml',
20
+ 'image/x-icon',
21
+ 'font/ttf',
22
+ 'font/otf',
20
23
  ])
21
24
 
22
25
  export function isCompressibleType(contentType: string | null | undefined): boolean {
@@ -380,7 +383,8 @@ export function compressedHtmlResponse(
380
383
  if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
381
384
  const enc = pickEncoding(request.headers.get('accept-encoding'))
382
385
  if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
383
- const staticKey = reuse ? `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}` : undefined
386
+ // SHA-256 of the page, so two pages never share a kept body: a 64-bit hash could be made to collide by a page that renders the query string.
387
+ const staticKey = reuse ? `s:${new Bun.CryptoHasher('sha256').update(html).digest('base64url')}` : undefined
384
388
  let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
385
389
  if (compressed === undefined)
386
390
  compressed = cache.compress(html, enc, staticKey)
@@ -438,34 +442,111 @@ function zstdFrames(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array
438
442
  }, { highWaterMark: 0 })
439
443
  }
440
444
 
445
+ function tryCloseController(controller: ReadableStreamDefaultController<Uint8Array>): boolean {
446
+ try {
447
+ controller.close()
448
+ return true
449
+ }
450
+ catch {
451
+ return false
452
+ }
453
+ }
454
+
455
+ function tryErrorController(controller: ReadableStreamDefaultController<Uint8Array>, error: unknown): boolean {
456
+ try {
457
+ controller.error(error)
458
+ return true
459
+ }
460
+ catch {
461
+ return false
462
+ }
463
+ }
464
+
441
465
  /** One gzip stream flushed after each chunk: concatenated gzip members would stop a browser after the first. */
442
466
  async function gzipFlushed(body: ReadableStream<Uint8Array>): Promise<ReadableStream<Uint8Array>> {
443
467
  const { constants, createGzip } = await (zlib ??= import('node:zlib'))
444
468
  const compressor = createGzip({ level: GZIP_PER_RESPONSE, flush: constants.Z_SYNC_FLUSH })
445
469
  const reader = body.getReader()
470
+ let closed = false
446
471
  let ended: Promise<void> | undefined
472
+ let resolveEnded: (() => void) | undefined
473
+ const markEnded = (): void => {
474
+ resolveEnded?.()
475
+ resolveEnded = undefined
476
+ }
447
477
  return new ReadableStream<Uint8Array>({
448
478
  start(controller) {
449
- compressor.on('data', (chunk: Uint8Array) => controller.enqueue(chunk))
450
- compressor.once('end', () => controller.close())
451
- compressor.once('error', error => controller.error(error))
479
+ compressor.on('data', (chunk: Uint8Array) => {
480
+ if (closed)
481
+ return
482
+ try {
483
+ controller.enqueue(chunk)
484
+ }
485
+ catch {
486
+ closed = true
487
+ markEnded()
488
+ compressor.destroy()
489
+ }
490
+ })
491
+ compressor.once('end', () => {
492
+ if (!closed) {
493
+ closed = true
494
+ tryCloseController(controller)
495
+ }
496
+ markEnded()
497
+ })
498
+ compressor.on('error', (error: unknown) => {
499
+ if (!closed) {
500
+ closed = true
501
+ tryErrorController(controller, error)
502
+ }
503
+ markEnded()
504
+ })
505
+ compressor.once('close', () => {
506
+ closed = true
507
+ markEnded()
508
+ })
452
509
  },
453
510
  async pull() {
511
+ if (closed)
512
+ return
454
513
  if (ended !== undefined)
455
514
  return ended
456
- const next = await reader.read().catch((error: unknown) => {
515
+ let next: Awaited<ReturnType<typeof reader.read>>
516
+ try {
517
+ next = await reader.read()
518
+ }
519
+ catch (error: unknown) {
520
+ closed = true
521
+ markEnded()
457
522
  compressor.destroy()
458
523
  throw error
459
- })
524
+ }
525
+ if (closed)
526
+ return
460
527
  if (next.done) {
461
- ended = new Promise(resolve => compressor.once('end', resolve))
528
+ if (compressor.readableEnded || compressor.destroyed) {
529
+ closed = true
530
+ return
531
+ }
532
+ ended = new Promise<void>((resolve) => {
533
+ resolveEnded = resolve
534
+ })
462
535
  compressor.end()
463
536
  return ended
464
537
  }
465
538
  // The compressor emits the flushed bytes before it calls back, so each chunk leaves before the next one is read.
466
- await new Promise<void>((resolve, reject) => compressor.write(next.value, error => error ? reject(error) : resolve()))
539
+ await new Promise<void>((resolve, reject) => {
540
+ if (closed || compressor.destroyed) {
541
+ resolve()
542
+ return
543
+ }
544
+ compressor.write(next.value, error => (error && !closed ? reject(error) : resolve()))
545
+ })
467
546
  },
468
547
  cancel(reason) {
548
+ closed = true
549
+ markEnded()
469
550
  compressor.destroy()
470
551
  return reader.cancel(reason)
471
552
  },
@@ -512,11 +593,13 @@ export async function maybeCompressResponse(
512
593
  return res
513
594
 
514
595
  const cl = res.headers.get('content-length')
596
+ const clBytes = cl !== null && cl.trim() !== '' ? Number(cl) : Number.NaN
597
+ const hasValidCl = Number.isFinite(clBytes) && clBytes >= 0
515
598
  const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
516
599
  if (enc === undefined)
517
600
  return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
518
601
 
519
- if (cl !== null && Number(cl) < MIN_COMPRESS_BYTES)
602
+ if (hasValidCl && clBytes < MIN_COMPRESS_BYTES)
520
603
  return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
521
604
 
522
605
  if (res.body === null)
@@ -538,8 +621,11 @@ export async function maybeCompressResponse(
538
621
  return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
539
622
  }
540
623
 
624
+ if (hasValidCl && clBytes > MAX_BUFFERED_PROBE_BYTES)
625
+ return isHtml(res) ? compressedStream(res, res.body, enc) : markCompressionHandled(tryAppendVaryAcceptEncoding(res))
626
+
541
627
  let raw: Uint8Array<ArrayBuffer>
542
- if (cl !== null) {
628
+ if (hasValidCl) {
543
629
  raw = new Uint8Array(await res.arrayBuffer())
544
630
  }
545
631
  else {
@@ -10,7 +10,10 @@ export const DEFAULT_CONSENT_COOKIE = 'pru_consent'
10
10
  /** 180 days in seconds (CNIL 6-month guideline for consent retention). */
11
11
  export const DEFAULT_CONSENT_MAX_AGE = 15_552_000
12
12
  export const DEFAULT_CONSENT_ENDPOINT = '/_pru/consent'
13
- const COOKIE_VERSION_PREFIX = 'v1:'
13
+ // v1 held the granted categories alone; v2 adds when the visitor chose and the policy version they chose under.
14
+ const LEGACY_COOKIE_PREFIX = 'v1:'
15
+ const COOKIE_PREFIX = 'v2:'
16
+ const POLICY_VERSION_RE = /^[\w.-]{1,32}$/
14
17
 
15
18
  export interface ConsentConfig {
16
19
  /** Non-essential consent categories (e.g. `['analytics', 'media']` or `{ analytics: 'Audience measurement' }`). */
@@ -21,11 +24,19 @@ export interface ConsentConfig {
21
24
  maxAge?: number | undefined
22
25
  /** POST endpoint path handling consent form submissions (default: `'/_pru/consent'`). */
23
26
  endpoint?: string | undefined
27
+ /** Version of the cookie policy (letters, digits, `.`, `-`, `_`): changing it asks every visitor again. */
28
+ version?: string | undefined
24
29
  }
25
30
 
26
31
  export interface RequestConsent {
27
32
  readonly decided: boolean
33
+ /** When the visitor made the choice in force, kept in the consent cookie as proof. */
34
+ readonly decidedAt: Date | undefined
28
35
  readonly categories: readonly string[]
36
+ /** Each category's label, from `consent.categories`, the name itself when given as a list. */
37
+ readonly labels: Readonly<Record<string, string>>
38
+ /** Path the consent form posts to. */
39
+ readonly endpoint: string
29
40
  has(category: string): boolean
30
41
  all(): Record<string, boolean>
31
42
  }
@@ -33,14 +44,19 @@ export interface RequestConsent {
33
44
  export interface NormalizedConsentConfig {
34
45
  readonly categories: readonly string[]
35
46
  readonly categorySet: ReadonlySet<string>
47
+ readonly labels: Readonly<Record<string, string>>
36
48
  readonly cookieName: string
37
49
  readonly maxAge: number
38
50
  readonly endpoint: string
51
+ readonly version: string
39
52
  }
40
53
 
41
54
  const EMPTY_CONSENT: RequestConsent = {
42
55
  decided: false,
56
+ decidedAt: undefined,
43
57
  categories: [],
58
+ labels: {},
59
+ endpoint: DEFAULT_CONSENT_ENDPOINT,
44
60
  has: category => category === 'essential',
45
61
  all: () => ({}),
46
62
  }
@@ -49,8 +65,10 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
49
65
  if (config === undefined)
50
66
  return undefined
51
67
  const rawList = Array.isArray(config.categories) ? config.categories : Object.keys(config.categories)
68
+ const given: Readonly<Record<string, string>> = Array.isArray(config.categories) ? {} : config.categories as Readonly<Record<string, string>>
52
69
  const categories: string[] = []
53
70
  const categorySet = new Set<string>()
71
+ const labels: Record<string, string> = {}
54
72
  for (const item of rawList) {
55
73
  const name = item.trim()
56
74
  if (name === '' || name === 'essential' || categorySet.has(name))
@@ -59,49 +77,67 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
59
77
  throw new Error(`prunelle: consent category "${name}" cannot contain "," or ":"`)
60
78
  categorySet.add(name)
61
79
  categories.push(name)
80
+ labels[name] = given[item]?.trim() || name
62
81
  }
82
+ const version = config.version?.trim() ?? ''
83
+ if (version !== '' && !POLICY_VERSION_RE.test(version))
84
+ throw new Error(`prunelle: consent version "${config.version}" must be 1 to 32 letters, digits, ".", "-" or "_", such as '2026-11' or '3'`)
63
85
  const rawEndpoint = (config.endpoint ?? DEFAULT_CONSENT_ENDPOINT).trim()
64
86
  const endpoint = rawEndpoint.startsWith('/') ? rawEndpoint : `/${rawEndpoint}`
65
87
  return {
66
88
  categories,
67
89
  categorySet,
90
+ labels,
68
91
  cookieName: config.cookieName ?? DEFAULT_CONSENT_COOKIE,
69
92
  maxAge: config.maxAge ?? DEFAULT_CONSENT_MAX_AGE,
70
93
  endpoint,
94
+ version,
71
95
  }
72
96
  }
73
97
 
74
- export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>): { decided: boolean, granted: Set<string> } {
98
+ interface ParsedConsent { decided: boolean, decidedAt: Date | undefined, granted: Set<string> }
99
+
100
+ function grantedOf(list: string, declared: ReadonlySet<string>): Set<string> {
75
101
  const granted = new Set<string>()
76
- if (raw === undefined || !raw.startsWith(COOKIE_VERSION_PREFIX))
77
- return { decided: false, granted }
78
- const payload = raw.slice(COOKIE_VERSION_PREFIX.length)
79
- if (payload !== '') {
80
- for (const part of payload.split(',')) {
81
- const cat = part.trim()
82
- if (declared.has(cat))
83
- granted.add(cat)
84
- }
102
+ for (const part of list.split(',')) {
103
+ const cat = part.trim()
104
+ if (declared.has(cat))
105
+ granted.add(cat)
85
106
  }
86
- return { decided: true, granted }
107
+ return granted
87
108
  }
88
109
 
89
- export function serializeConsentCookie(granted: ReadonlySet<string>, declared: readonly string[]): string {
90
- const ordered: string[] = []
91
- for (const cat of declared) {
92
- if (granted.has(cat))
93
- ordered.push(cat)
94
- }
95
- return `${COOKIE_VERSION_PREFIX}${ordered.join(',')}`
110
+ /** Reads `v2:<seconds>:<policy version>:<categories>`; a choice made under another policy version counts as no choice. */
111
+ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySet<string>, version = ''): ParsedConsent {
112
+ const none: ParsedConsent = { decided: false, decidedAt: undefined, granted: new Set() }
113
+ if (raw === undefined)
114
+ return none
115
+ if (raw.startsWith(LEGACY_COOKIE_PREFIX))
116
+ return version === '' ? { decided: true, decidedAt: undefined, granted: grantedOf(raw.slice(LEGACY_COOKIE_PREFIX.length), declared) } : none
117
+ if (!raw.startsWith(COOKIE_PREFIX))
118
+ return none
119
+ const [seconds, storedVersion, list] = raw.slice(COOKIE_PREFIX.length).split(':')
120
+ const at = Number(seconds)
121
+ if (list === undefined || storedVersion !== version || !Number.isSafeInteger(at) || at <= 0)
122
+ return none
123
+ return { decided: true, decidedAt: new Date(at * 1000), granted: grantedOf(list, declared) }
124
+ }
125
+
126
+ export function serializeConsentCookie(granted: ReadonlySet<string>, declared: readonly string[], version = '', decidedAt = new Date()): string {
127
+ const ordered = declared.filter(cat => granted.has(cat))
128
+ return `${COOKIE_PREFIX}${Math.floor(decidedAt.getTime() / 1000)}:${version}:${ordered.join(',')}`
96
129
  }
97
130
 
98
131
  export function createRequestConsent(rawCookie: string | undefined, config: NormalizedConsentConfig | undefined): RequestConsent {
99
132
  if (config === undefined)
100
133
  return EMPTY_CONSENT
101
- const { decided, granted } = parseConsentCookie(rawCookie, config.categorySet)
134
+ const { decided, decidedAt, granted } = parseConsentCookie(rawCookie, config.categorySet, config.version)
102
135
  return {
103
136
  decided,
137
+ decidedAt,
104
138
  categories: config.categories,
139
+ labels: config.labels,
140
+ endpoint: config.endpoint,
105
141
  has(category: string): boolean {
106
142
  return category === 'essential' || granted.has(category)
107
143
  },
@@ -232,7 +268,7 @@ export function registerConsentRoute(
232
268
  if (!parsed.ok)
233
269
  return ctx.deny(400, parsed.error)
234
270
 
235
- const cookieVal = serializeConsentCookie(parsed.granted, config.categories)
271
+ const cookieVal = serializeConsentCookie(parsed.granted, config.categories, config.version)
236
272
  ctx.cookies.set(config.cookieName, cookieVal, {
237
273
  httpOnly: true,
238
274
  sameSite: 'lax',
@@ -248,6 +284,7 @@ export function registerConsentRoute(
248
284
  return ctx.json({ ok: true, decided: true, consent })
249
285
  }
250
286
  const target = resolveConsentRedirect(ctx.request, ctx.url, parsed.redirect, trustedOrigins, trustProxy)
251
- return ctx.redirect(target, 303)
287
+ // resolveConsentRedirect only returns this site or a trusted origin.
288
+ return ctx.redirect(target, 303, { external: true })
252
289
  }, { csrf: true })
253
290
  }
@@ -1,5 +1,7 @@
1
1
  // Typed cookie jar for RequestContext (lazy Cookie header parsing, validated & deduplicated Set-Cookie serialization).
2
2
 
3
+ import { getAppContext } from '../plugins/context'
4
+
3
5
  export interface CookieOptions {
4
6
  path?: string | undefined
5
7
  domain?: string | undefined
@@ -8,10 +10,20 @@ export interface CookieOptions {
8
10
  httpOnly?: boolean | undefined
9
11
  secure?: boolean | undefined
10
12
  sameSite?: 'strict' | 'lax' | 'none' | undefined
11
- /** Consent category required before setting this cookie (omit or `'essential'` for strictly necessary cookies). */
13
+ /** Consent category required before setting this cookie, or `'essential'` for a cookie the site cannot work without; omitted, it counts as essential and `prunelle dev` warns. */
12
14
  category?: string | undefined
13
15
  }
14
16
 
17
+ const warnedUncategorized = new Set<string>()
18
+
19
+ // Once per cookie name and process, in dev only: production has no one to read it.
20
+ function warnUncategorized(name: string): void {
21
+ if (warnedUncategorized.has(name) || getAppContext()?.dev !== true)
22
+ return
23
+ warnedUncategorized.add(name)
24
+ console.warn(`prunelle: cookie "${name}" was set without a category, so it counts as essential and is set without consent: pass { category: 'essential' } when the site cannot work without it, or its consent category (such as 'analytics') so it waits for the visitor's consent.`)
25
+ }
26
+
15
27
  export interface Cookies {
16
28
  get(name: string): string | undefined
17
29
  set(name: string, value: string, options?: CookieOptions): void
@@ -110,7 +122,9 @@ export class CookieStore implements Cookies {
110
122
  }
111
123
 
112
124
  set(name: string, value: string, options?: CookieOptions): void {
113
- if (options?.category !== undefined && options.category !== 'essential') {
125
+ if (options?.category === undefined)
126
+ warnUncategorized(name)
127
+ else if (options.category !== 'essential') {
114
128
  if (this.#isConsentGranted === undefined || !this.#isConsentGranted(options.category))
115
129
  return
116
130
  }
@@ -11,6 +11,18 @@ import { extractRenderedIslands, makeRequestContext } from './http'
11
11
  import { inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, resolveCspPolicy, withCspHashes } from './security'
12
12
 
13
13
  const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
14
+ const UNESCAPED_TITLE_CHAR_RE = /[<>]|&(?!(?:#\d+|#x[\da-f]+|[a-z][a-z0-9]+);)/gi
15
+
16
+ // Escapes raw `<`, `>` and unescaped `&` in plugin-supplied `head.title` values without double-escaping existing HTML entities (such as `&amp;` from compiled `<Head><title>` or `@prunellejs/seo`).
17
+ function escapeTitleHtml(title: string): string {
18
+ return title.replace(UNESCAPED_TITLE_CHAR_RE, (ch) => {
19
+ if (ch === '<')
20
+ return '&lt;'
21
+ if (ch === '>')
22
+ return '&gt;'
23
+ return '&amp;'
24
+ })
25
+ }
14
26
 
15
27
  /** `styleHashes` are the page's own `<style>` blocks (`inlineStyleHashes`), added to its CSP. */
16
28
  export type HtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean, styleHashes?: readonly string[]) => Record<string, string>
@@ -181,7 +193,7 @@ export function createDocumentHooks(options: DocumentHooksOptions) {
181
193
  if (!hasHeadHooks) {
182
194
  return {
183
195
  head: (rctx.title ?? '') + collectedParts,
184
- lang,
196
+ lang: rctx.htmlAttrs.lang ?? lang,
185
197
  htmlAttrs: rctx.htmlAttrs,
186
198
  styleHashes: [],
187
199
  }
@@ -194,16 +206,21 @@ export function createDocumentHooks(options: DocumentHooksOptions) {
194
206
  let currentTitle = initialTitleInner
195
207
  let titleDirty = false
196
208
  let currentLang = htmlAttrs.lang ?? lang
197
- let headBuf = (initialTitleTag ?? '') + collectedParts
209
+ let headRest = collectedParts
198
210
  if (baseHeadTags !== undefined) {
199
211
  for (let i = 0; i < baseHeadTags.length; i++)
200
- headBuf += baseHeadTags[i]
212
+ headRest += baseHeadTags[i]
201
213
  }
202
214
  const added: string[] = []
215
+ const renderTitleTag = (): string => (
216
+ titleDirty
217
+ ? (currentTitle !== undefined ? `<title>${escapeTitleHtml(currentTitle)}</title>` : '')
218
+ : (initialTitleTag ?? '')
219
+ )
203
220
 
204
221
  const docHead: DocumentHeadContext = {
205
222
  get lang() {
206
- return currentLang
223
+ return htmlAttrs.lang ?? currentLang
207
224
  },
208
225
  set lang(v: string) {
209
226
  currentLang = v
@@ -218,12 +235,12 @@ export function createDocumentHooks(options: DocumentHooksOptions) {
218
235
  titleDirty = true
219
236
  },
220
237
  get headHtml() {
221
- return headBuf
238
+ return renderTitleTag() + headRest
222
239
  },
223
240
  add(html: string) {
224
241
  if (html !== '') {
225
242
  added.push(html)
226
- headBuf += html
243
+ headRest += html
227
244
  }
228
245
  },
229
246
  }
@@ -237,13 +254,11 @@ export function createDocumentHooks(options: DocumentHooksOptions) {
237
254
  }
238
255
  }
239
256
 
240
- const titleHtml = titleDirty
241
- ? (currentTitle !== undefined ? `<title>${currentTitle}</title>` : '')
242
- : (initialTitleTag ?? '')
257
+ const titleHtml = renderTitleTag()
243
258
  const addedHtml = added.length > 0 ? added.join('') : ''
244
259
  return {
245
260
  head: titleHtml + collectedParts + addedHtml,
246
- lang: currentLang,
261
+ lang: htmlAttrs.lang ?? currentLang,
247
262
  htmlAttrs,
248
263
  styleHashes: addedHtml !== '' ? inlineStyleHashes(addedHtml) : [],
249
264
  }
package/src/server/env.ts CHANGED
@@ -11,6 +11,20 @@ export function nodeEnv(): string | undefined {
11
11
  return getAppContext()?.nodeEnv ?? process.env[NODE_ENV_KEY]
12
12
  }
13
13
 
14
+ const DEV_KEY = 'PRUNELLE_DEV'
15
+ // A compiled binary runs its entry from Bun's embedded filesystem.
16
+ const BINARY_MAIN_RE = /^\/\$bunfs\//
17
+
18
+ /** Whether `PRUNELLE_DEV=1` asks for dev mode where the caller did not say; it throws under NODE_ENV=production and inside a compiled binary, where the dev-only routes would reach visitors. */
19
+ export function devFromEnv(): boolean {
20
+ if (process.env[DEV_KEY] !== '1')
21
+ return false
22
+ const where = BINARY_MAIN_RE.test(Bun.main) ? 'inside a compiled binary' : nodeEnv() === 'production' ? 'with NODE_ENV=production' : undefined
23
+ if (where !== undefined)
24
+ throw new Error(`prunelle: PRUNELLE_DEV=1 is set ${where}, where dev mode would open the CMS write routes, the mail outbox and the other dev-only routes to visitors: unset PRUNELLE_DEV, or use prunelle dev.`)
25
+ return true
26
+ }
27
+
14
28
  export function defineEnv<S extends StandardSchemaV1>(
15
29
  schema: S,
16
30
  source: Record<string, string | undefined> = process.env,