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
@@ -135,7 +135,11 @@ export function staticLiteralOrTemplate(node: Node): { ok: true, value: string |
135
135
  }
136
136
 
137
137
  export function formatStaticAttrValue(name: string, value: string | number | boolean | null, tag?: string): string {
138
- if (value === null || isBlockedAttr(name))
138
+ if (value === null || isBlockedAttr(name) || name === 'indeterminate')
139
+ return ''
140
+ if (name === 'checked' || name === 'selected' || name === 'muted')
141
+ return value ? ` ${name}` : ''
142
+ if (name === 'value' && typeof value === 'boolean')
139
143
  return ''
140
144
  if (typeof value === 'boolean') {
141
145
  if (isStringBoolAttr(name))
@@ -264,7 +268,7 @@ export function serializeComponentProps(
264
268
  export interface SelectValueBinding {
265
269
  staticValue?: string | undefined
266
270
  expr?: string | undefined
267
- multiple: boolean
271
+ multiple: boolean | string
268
272
  }
269
273
 
270
274
  export function isSimpleValueExpr(node: Node): boolean {
@@ -300,16 +304,17 @@ export function formatOptionSelectedExpr(
300
304
  return { staticSelected: selectVal.staticValue === optVal.staticValue }
301
305
  const sv = selectVal.staticValue !== undefined ? JSON.stringify(selectVal.staticValue) : selectVal.expr!
302
306
  const ov = optVal.staticValue !== undefined ? JSON.stringify(optVal.staticValue) : optVal.expr!
303
- if (selectVal.multiple) {
307
+ const scalarEq = optVal.staticValue !== undefined
308
+ ? `${sv} != null && typeof ${sv} !== "boolean" && String(${sv}) === ${ov}`
309
+ : `${sv} != null && typeof ${sv} !== "boolean" && ${ov} != null && String(${sv}) === String(${ov})`
310
+ if (selectVal.multiple !== false) {
311
+ const isMulti = selectVal.multiple === true ? `Array.isArray(${sv})` : `(${selectVal.multiple} && Array.isArray(${sv}))`
304
312
  const cond = optVal.staticValue !== undefined
305
- ? `Array.isArray(${sv}) ? ${sv}.some((_x) => String(_x) === ${ov}) : (${sv} != null && String(${sv}) === ${ov})`
306
- : `${ov} != null && (Array.isArray(${sv}) ? ${sv}.some((_x) => String(_x) === String(${ov})) : (${sv} != null && String(${sv}) === String(${ov})))`
313
+ ? `${isMulti} ? ${sv}.some((_x) => String(_x) === ${ov}) : (${scalarEq})`
314
+ : `${ov} != null && (${isMulti} ? ${sv}.some((_x) => String(_x) === String(${ov})) : (${scalarEq}))`
307
315
  return { expr: `((${cond}) ? " selected" : "")` }
308
316
  }
309
- const cond = optVal.staticValue !== undefined
310
- ? `${sv} != null && String(${sv}) === ${ov}`
311
- : `${sv} != null && ${ov} != null && String(${sv}) === String(${ov})`
312
- return { expr: `((${cond}) ? " selected" : "")` }
317
+ return { expr: `((${scalarEq}) ? " selected" : "")` }
313
318
  }
314
319
 
315
320
  export interface SsrElementAttrsContext {
@@ -388,6 +393,32 @@ function emitSsrExprAttr(
388
393
  return undefined
389
394
  }
390
395
 
396
+ function emitSsrSpreadAttrs(
397
+ ctx: SsrElementAttrsContext,
398
+ attrs: readonly JSXAttributeItem[],
399
+ spreadEntries: readonly string[],
400
+ selectIsMultiple: boolean,
401
+ ): Pick<SsrElementAttrsResult, 'textareaValue' | 'nextSelectValue'> {
402
+ const { tag, parts, flushParts, pushStmt, nextId, use, compileSubExpression } = ctx
403
+ if (spreadEntries.length === 0)
404
+ return { textareaValue: undefined, nextSelectValue: undefined }
405
+ const soleSpread = spreadEntries.length === 1 && attrs.length === 1
406
+ ? compileSubExpression((attrs[0] as Extract<JSXAttributeItem, { type: 'JSXSpreadAttribute' }>).argument)
407
+ : undefined
408
+ const propsExpr = soleSpread ?? `{ ${spreadEntries.join(', ')} }`
409
+ if (tag === 'textarea' || tag === 'select') {
410
+ const spVar = `_sp${nextId()}`
411
+ flushParts()
412
+ pushStmt(`const ${spVar} = ${propsExpr};`)
413
+ parts.pushExpr(`${use('ssrSpread')}(${spVar}, ${JSON.stringify(tag)})`)
414
+ if (tag === 'textarea')
415
+ return { textareaValue: { expr: `${spVar}?.value` }, nextSelectValue: undefined }
416
+ return { textareaValue: undefined, nextSelectValue: { expr: `${spVar}?.value`, multiple: selectIsMultiple || `${spVar}?.multiple` } }
417
+ }
418
+ parts.pushExpr(`${use('ssrSpread')}(${propsExpr}, ${JSON.stringify(tag)})`)
419
+ return { textareaValue: undefined, nextSelectValue: undefined }
420
+ }
421
+
391
422
  /** Emits an HTML/SVG element's SSR opening attributes, handling spreads, `<textarea value>`, and `<select value>`/`<option>`. */
392
423
  export function emitSsrElementAttrs(ctx: SsrElementAttrsContext): SsrElementAttrsResult {
393
424
  const { node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId, use, compileSubExpression } = ctx
@@ -430,7 +461,7 @@ export function emitSsrElementAttrs(ctx: SsrElementAttrsContext): SsrElementAttr
430
461
  if (isBlockedAttr(name))
431
462
  continue
432
463
 
433
- if (isTextarea && name === 'value') {
464
+ if (!hasSpread && isTextarea && name === 'value') {
434
465
  if (attr.value?.type === 'Literal') {
435
466
  textareaValue = { staticText: String(attr.value.value) }
436
467
  }
@@ -444,14 +475,14 @@ export function emitSsrElementAttrs(ctx: SsrElementAttrsContext): SsrElementAttr
444
475
  continue
445
476
  }
446
477
 
447
- if (isSelect && name === 'value') {
478
+ if (!hasSpread && isSelect && name === 'value') {
448
479
  if (attr.value?.type === 'Literal') {
449
480
  nextSelectValue = { staticValue: String(attr.value.value), multiple: selectIsMultiple }
450
481
  }
451
482
  else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
452
483
  const lit = staticLiteralOrTemplate(attr.value.expression)
453
484
  if (lit.ok) {
454
- if (lit.value !== null)
485
+ if (lit.value !== null && typeof lit.value !== 'boolean')
455
486
  nextSelectValue = { staticValue: String(lit.value), multiple: selectIsMultiple }
456
487
  }
457
488
  else {
@@ -514,15 +545,8 @@ export function emitSsrElementAttrs(ctx: SsrElementAttrsContext): SsrElementAttr
514
545
  }
515
546
  }
516
547
 
517
- if (hasSpread) {
518
- if (spreadEntries.length === 1 && attrs.length === 1) {
519
- const spreadAttr = attrs[0] as Extract<typeof attrs[number], { type: 'JSXSpreadAttribute' }>
520
- parts.pushExpr(`${use('ssrSpread')}(${compileSubExpression(spreadAttr.argument)}, ${JSON.stringify(tag)})`)
521
- }
522
- else if (spreadEntries.length > 0) {
523
- parts.pushExpr(`${use('ssrSpread')}({ ${spreadEntries.join(', ')} }, ${JSON.stringify(tag)})`)
524
- }
525
- }
548
+ if (hasSpread)
549
+ ({ textareaValue, nextSelectValue } = emitSsrSpreadAttrs(ctx, attrs, spreadEntries, selectIsMultiple))
526
550
 
527
551
  if (isOption && activeSelectValue !== undefined && !optionHasExplicitSelected) {
528
552
  if (optionValue === undefined) {
@@ -224,6 +224,22 @@ function compileSsrExprAsString(
224
224
  return `${use('esc')}(${compileSubExpression(expr)})`
225
225
  }
226
226
 
227
+ function pushLeadNlStatic(parts: StringParts, text: string): void {
228
+ parts.pushStatic(text.startsWith('\n') || text.startsWith('\r') ? `\n${text}` : text)
229
+ }
230
+
231
+ function createIdCounter(code: string): () => number {
232
+ const used = new Set<number>()
233
+ for (const m of code.matchAll(/\b_[A-Za-z_]+(\d+)\b/g))
234
+ used.add(Number(m[1]))
235
+ let n = 0
236
+ return () => {
237
+ while (used.has(n))
238
+ n++
239
+ return n++
240
+ }
241
+ }
242
+
227
243
  export function compileSsr(filename: string, code: string, options: CompileSsrOptions = {}): CompileResult {
228
244
  const program = options.analysis?.program ?? parseTsx(filename, code)
229
245
  const analysis = options.analysis ?? analyzeModule(filename, code, program)
@@ -235,7 +251,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
235
251
  // Generated code keeps each expression on its source line: Bun maps a stack trace by the code this compiler hands it, not by a source map of its own.
236
252
  const mark = lineMarker(code)
237
253
  const used = new Set<string>()
238
- let loopCounter = 0
254
+ const nextId = createIdCounter(code)
239
255
  let activeSelectValue: SelectValueBinding | undefined
240
256
 
241
257
  const use = (name: string): string => {
@@ -258,7 +274,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
258
274
  const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, compileComponentRaw, markersAt, directAwaitNodes, jsxNodes }
259
275
 
260
276
  function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = markersAt(children[0]?.start ?? 0), inFragment = false, rawTextTag?: 'style' | 'script'): string {
261
- const bufVar = `_o${loopCounter++}`
277
+ const bufVar = `_o${nextId()}`
262
278
  const stmts: string[] = []
263
279
  const parts = new StringParts()
264
280
  const flush = () => flushStringParts(bufVar, parts, stmts)
@@ -288,16 +304,16 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
288
304
  if (tag === 'form' && actionOverride === undefined) {
289
305
  const formAction = findDynamicFormAction(node)
290
306
  if (formAction !== undefined) {
291
- parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), () => loopCounter++, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
307
+ parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), nextId, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
292
308
  return
293
309
  }
294
310
  }
295
311
 
296
312
  parts.pushStatic(`<${tag}${devSrc(node, tag)}`)
297
313
  const isTextarea = tag === 'textarea'
298
- const isSelect = tag === 'select'
314
+ const needsLeadNl = isTextarea || tag === 'pre'
299
315
  const compileAttrExpr = actionOverride !== undefined ? (n: Node) => (n === actionOverride.node ? actionOverride.ident : compileSubExpression(n)) : compileSubExpression
300
- const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId: () => loopCounter++, use, compileSubExpression: compileAttrExpr })
316
+ const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId, use, compileSubExpression: compileAttrExpr })
301
317
  if (FORM_CONTROL_TAGS.has(tag))
302
318
  emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
303
319
  parts.pushStatic('>')
@@ -305,18 +321,18 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
305
321
  return
306
322
 
307
323
  const prevSelectValue = activeSelectValue
308
- if (isSelect)
324
+ if (tag === 'select')
309
325
  activeSelectValue = nextSelectValue
310
326
 
311
327
  try {
312
328
  if (innerHtmlExpr !== undefined)
313
- parts.pushExpr(innerHtmlExpr)
329
+ parts.pushExpr(needsLeadNl ? `${use('ssrLeadNl')}(${innerHtmlExpr})` : innerHtmlExpr)
314
330
  else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0)
315
- textareaValue.staticText !== undefined ? parts.pushStatic(escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('esc')}(${textareaValue.expr})`)
316
- else if (tag === 'style') {
317
- const styleExpr = compileChildrenListToStringExpr(node.children, false, false, 'style')
318
- if (styleExpr !== '""')
319
- parts.pushExpr(`${use('ssrStyleBlock')}(${styleExpr})`)
331
+ textareaValue.staticText !== undefined ? pushLeadNlStatic(parts, escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('ssrLeadNl')}(${use('esc')}(${textareaValue.expr}))`)
332
+ else if (tag === 'style' || needsLeadNl) {
333
+ const bodyExpr = tag === 'style' ? compileChildrenListToStringExpr(node.children, false, false, 'style') : compileChildrenListToStringExpr(node.children)
334
+ if (bodyExpr !== '""')
335
+ parts.pushExpr(`${use(tag === 'style' ? 'ssrStyleBlock' : 'ssrLeadNl')}(${bodyExpr})`)
320
336
  }
321
337
  else
322
338
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
@@ -382,7 +398,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
382
398
 
383
399
  if (match.isJsxBody && itemParam !== undefined && match.params.length <= 2 && (match.params.length < 2 || idxParam !== undefined)) {
384
400
  flushParts()
385
- const n = loopCounter++
401
+ const n = nextId()
386
402
  const arrVar = `_a${n}`
387
403
  const idxVar = idxParam ?? `_i${n}`
388
404
  const innerStmts: string[] = []
@@ -454,7 +470,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
454
470
 
455
471
  if (islandInfo !== undefined) {
456
472
  const target = onRaw !== undefined ? new StringParts() : parts
457
- emitIsland({ use, nextId: () => loopCounter++, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
473
+ emitIsland({ use, nextId, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
458
474
  if (onRaw !== undefined)
459
475
  onRaw(`${use('raw')}(${target.toExpr()})`)
460
476
  return
@@ -471,7 +487,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
471
487
 
472
488
  // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
473
489
  if (childrenHaveDynamic && !childrenHaveAwait) {
474
- const cVar = `_c${loopCounter++}`
490
+ const cVar = `_c${nextId()}`
475
491
  const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
476
492
  emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
477
493
  return
@@ -485,7 +501,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
485
501
  }
486
502
 
487
503
  function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
488
- const bufVar = `_o${loopCounter++}`
504
+ const bufVar = `_o${nextId()}`
489
505
  const stmts: string[] = []
490
506
  const parts = new StringParts()
491
507
 
package/src/context.ts CHANGED
@@ -37,6 +37,8 @@ export interface ConsentBannerProps extends ConsentTexts {
37
37
  children?: PrunelleChild
38
38
  /** The cookie or privacy policy page, linked under the text. */
39
39
  policyHref?: string | undefined
40
+ /** Label of the `policyHref` link (default: `'Cookie policy'`). */
41
+ policyLabel?: string | undefined
40
42
  /** Text of the disclosure holding the checkboxes (default: `'Choose'`). */
41
43
  choose?: string | undefined
42
44
  }
@@ -163,7 +163,7 @@ function safePathname(rawUrl: string): string {
163
163
  }
164
164
  }
165
165
 
166
- /** Builds an `errorSink` callback for `devServer` that records unhandled runtime errors into `.prunelle-dev/last-errors.json`. */
166
+ /** Builds an `errorSink` callback for `devServer` that records unhandled runtime errors into `.prunelle-dev/last-errors.jsonl`. */
167
167
  export function createDevRuntimeErrorSink(root: string): (info: ServerErrorInfo) => void {
168
168
  return (info) => {
169
169
  const message = info.error instanceof Error ? info.error.stack ?? info.error.message : String(info.error)
package/src/dev/index.ts CHANGED
@@ -98,7 +98,7 @@ async function handleAppFetch(
98
98
  if (state.lastError !== undefined)
99
99
  return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
100
100
 
101
- const res = await state.app!.handle(request, remoteIp)
101
+ const res = await state.app!.handle(request, remoteIp, seconds => srv.timeout(request, seconds))
102
102
  const ct = res.headers.get('content-type') ?? ''
103
103
  const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
104
104
  if (ct.includes('text/event-stream') || isStreamedHtml)
@@ -162,6 +162,8 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
162
162
  const child = await ready
163
163
  if (child === undefined)
164
164
  return buildErrorResponse(request, crashed ?? 'prunelle dev: the app process is not running.', reloadAssets.script)
165
+ // The app process keeps its own idle timeout, which a stream or a route's `export const idleTimeout` sets, so this hop waits on it alone.
166
+ srv.timeout(request, 0)
165
167
  const headers = new Headers(request.headers)
166
168
  headers.set(DEV_CLIENT_IP_HEADER, srv.requestIP(request)?.address ?? '')
167
169
  try {
@@ -173,8 +175,6 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
173
175
  redirect: 'manual',
174
176
  signal: request.signal,
175
177
  })
176
- if (!res.headers.has('content-length'))
177
- srv.timeout(request, 0)
178
178
  return res
179
179
  }
180
180
  catch (err) {
package/src/dom/attrs.ts CHANGED
@@ -64,13 +64,21 @@ export function setAttr(el: Element, name: string, value: unknown): void {
64
64
 
65
65
  export function setProp(el: Element, name: string, value: unknown): void {
66
66
  const next = name === 'value'
67
- ? (value == null ? '' : String(value))
67
+ ? (value == null || typeof value === 'boolean' ? '' : String(value))
68
68
  : Boolean(value)
69
69
  const rec = el as unknown as Record<string, unknown>
70
70
  if (rec[name] !== next)
71
71
  rec[name] = next
72
72
  }
73
73
 
74
+ /** The `value` of a `<select multiple>`: an array selects the options it lists, as SSR renders them; anything else is a plain value. */
75
+ export function setSelectValues(el: HTMLSelectElement, value: unknown): void {
76
+ if (!Array.isArray(value) || !el.multiple)
77
+ return setProp(el, 'value', value)
78
+ for (const option of el.options)
79
+ option.selected = value.some(v => String(v) === option.value)
80
+ }
81
+
74
82
  export function setStyle(el: HTMLElement, value: unknown): void {
75
83
  if (value == null || value === false) {
76
84
  el.removeAttribute('style')
package/src/dom/island.ts CHANGED
@@ -71,7 +71,7 @@ function collectVisibleTargets(root: Element, out: Element[]): void {
71
71
  function replayEvent(root: Element, ev: Event, target: EventTarget | null): void {
72
72
  if (target === null || typeof target.dispatchEvent !== 'function')
73
73
  return
74
- if (typeof (target as Node).nodeType === 'number' && !root.contains(target as Node))
74
+ if (typeof (target as Node).nodeType === 'number' && target !== document && !root.contains(target as Node))
75
75
  return
76
76
  const init: EventInit = { bubbles: ev.bubbles, cancelable: ev.cancelable, composed: ev.composed }
77
77
  let clone: Event
@@ -90,16 +90,31 @@ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void
90
90
  target.dispatchEvent(clone)
91
91
  }
92
92
 
93
+ const MODIFIERS = ['Alt', 'Control', 'Meta', 'Shift']
94
+
95
+ // True when the key is one an element inside names with `aria-keyshortcuts="Control+K Meta+K"`, with exactly its modifiers held.
96
+ function isKeyShortcut(root: Element, e: KeyboardEvent): boolean {
97
+ for (const el of root.querySelectorAll('[aria-keyshortcuts]')) {
98
+ for (const combo of el.getAttribute('aria-keyshortcuts')!.split(' ')) {
99
+ const parts = combo.split('+')
100
+ if (parts.pop()!.toLowerCase() === e.key?.toLowerCase() && MODIFIERS.every(m => e.getModifierState(m) === parts.includes(m)))
101
+ return true
102
+ }
103
+ }
104
+ return false
105
+ }
106
+
93
107
  // A failed load keeps the listeners and drops the queued events: the next interaction loads the chunk again and is replayed once it is in.
108
+ // A shortcut the island declares is heard on the whole page, kept from the browser, and replayed on the document, where the component listens for it.
94
109
  function watchInteraction(root: Element, onTrigger: (after: () => void) => Promise<boolean>): () => void {
95
110
  const evs = ['pointerdown', 'click', 'focusin', 'keydown']
96
111
  const queued: { ev: Event, target: EventTarget | null }[] = []
97
112
  let loading = false
98
- const go = (ev: Event) => {
113
+ const go = (ev: Event, target = ev.target) => {
99
114
  // Prevent native toggle/submit/navigation before hydration so replaying the click triggers it once with handlers attached.
100
115
  if (ev.type === 'click')
101
116
  ev.preventDefault()
102
- queued.push({ ev, target: ev.target })
117
+ queued.push({ ev, target })
103
118
  if (!loading) {
104
119
  loading = true
105
120
  void onTrigger(() => {
@@ -113,9 +128,18 @@ function watchInteraction(root: Element, onTrigger: (after: () => void) => Promi
113
128
  })
114
129
  }
115
130
  }
131
+ const onShortcut = (ev: Event) => {
132
+ if (!isKeyShortcut(root, ev as KeyboardEvent))
133
+ return
134
+ ev.preventDefault()
135
+ if (!root.contains(ev.target as Node))
136
+ go(ev, document)
137
+ }
116
138
  for (const e of evs) root.addEventListener(e, go, true)
139
+ addEventListener('keydown', onShortcut, true)
117
140
  return () => {
118
141
  for (const e of evs) root.removeEventListener(e, go, true)
142
+ removeEventListener('keydown', onShortcut, true)
119
143
  }
120
144
  }
121
145
 
@@ -300,7 +324,9 @@ export function defineIslandElement(): void {
300
324
  return true
301
325
  }
302
326
  this._d = dispose
303
- after?.()
327
+ // Queued behind the component's `onMount` callbacks, so a listener it binds there hears the replayed event.
328
+ if (after)
329
+ queueMicrotask(after)
304
330
  return true
305
331
  }
306
332
  catch (err) {
@@ -425,7 +425,7 @@ type VoidElementTagName =
425
425
  | 'link' | 'meta' | 'param' | 'source' | 'track' | 'wbr'
426
426
 
427
427
  type HtmlIntrinsicElements = {
428
- [K in keyof HTMLElementTagNameMap]:
428
+ [K in Exclude<keyof HTMLElementTagNameMap, 'slot'>]:
429
429
  (K extends keyof HtmlElementOverrides
430
430
  ? Omit<HTMLAttributes<HTMLElementTagNameMap[K]>, keyof HtmlElementOverrides[K] | (K extends VoidElementTagName ? 'children' : never)> & HtmlElementOverrides[K]
431
431
  : Omit<HTMLAttributes<HTMLElementTagNameMap[K]>, K extends VoidElementTagName ? 'children' : never>)
@@ -86,9 +86,26 @@ async function runImporting<T>(ctx: AppRuntimeContext, load: () => Promise<T>):
86
86
  }
87
87
  }
88
88
 
89
+ // A frame of module top-level code prints with no function name and no parentheses: `at /app/prunelle.config.ts:3:1`.
90
+ const MODULE_FRAME_RE = /^\s*at [^\s(]+:\d+:\d+$/m
91
+
92
+ // Bun drops `inImport` too in a module's top-level code, so a call made there, while an import is running, is told apart by the module frame on its stack; queuing it would wait on the import that awaits it.
93
+ function calledFromImportedModule(): boolean {
94
+ if (importState.current === undefined)
95
+ return false
96
+ const limit = Error.stackTraceLimit
97
+ Error.stackTraceLimit = 50
98
+ try {
99
+ return MODULE_FRAME_RE.test(new Error('stack').stack ?? '')
100
+ }
101
+ finally {
102
+ Error.stackTraceLimit = limit
103
+ }
104
+ }
105
+
89
106
  /** Imports with `ctx` as the app context, the imported modules' top-level code included. */
90
107
  export async function importWithAppContext<T>(ctx: AppRuntimeContext, load: () => Promise<T>): Promise<T> {
91
- if (importState.inImport.getStore() === true)
108
+ if (importState.inImport.getStore() === true || calledFromImportedModule())
92
109
  return runImporting(ctx, load)
93
110
  const prev = importState.tail
94
111
  let release!: () => void
@@ -85,6 +85,7 @@ export const CMS_INLINE_ENABLED_SERVICE = serviceKey<boolean>('prunelle.cms.inli
85
85
  export interface JobsQueueOptions {
86
86
  attempts?: number | undefined
87
87
  backoff?: 'exponential' | 'fixed' | number | undefined
88
+ timeout?: number | undefined
88
89
  }
89
90
 
90
91
  export interface JobsEnqueueOptions {
@@ -240,7 +240,7 @@ export interface ServerRuntimeConfig {
240
240
  assetPrefix?: string | undefined
241
241
  security?: SecurityHeadersOptions | false | undefined
242
242
  trustedOrigins?: string[] | undefined
243
- trustProxy?: TrustProxy | undefined
243
+ trustProxy?: boolean | number | undefined
244
244
  maxRequestBodySize?: number | undefined
245
245
  /** How plain page changes feel without client JS: view transitions between pages, Speculation Rules prefetch on hover, opt-in prerender. */
246
246
  navigation?: NavigationConfig | undefined
@@ -301,9 +301,17 @@ class EffectNode implements SubNode, Owner {
301
301
  if (this.f & F.DISPOSED)
302
302
  return
303
303
  this.f &= ~(F.DIRTY | F.CHECK)
304
- releaseOwned(this)
305
- if (this.f & F.DISPOSED)
304
+ let errors: unknown[] | undefined
305
+ try {
306
+ releaseOwned(this)
307
+ }
308
+ catch (err) {
309
+ errors = [err]
310
+ }
311
+ if (this.f & F.DISPOSED) {
312
+ throwErrors(errors)
306
313
  return
314
+ }
307
315
  const prevSub = currentSub
308
316
  const prevOwner = currentOwner
309
317
  this.f |= F.RUNNING
@@ -320,12 +328,16 @@ class EffectNode implements SubNode, Owner {
320
328
  ;(this.cl ??= []).unshift(ret)
321
329
  }
322
330
  }
331
+ catch (err) {
332
+ ;(errors ??= []).push(err)
333
+ }
323
334
  finally {
324
335
  unlinkRemaining(this)
325
336
  this.f &= ~F.RUNNING
326
337
  currentSub = prevSub
327
338
  currentOwner = prevOwner
328
339
  }
340
+ throwErrors(errors)
329
341
  }
330
342
  }
331
343
 
@@ -157,54 +157,58 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
157
157
  return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Blob)
158
158
  }
159
159
 
160
- function appendFormValue(target: Record<string, unknown>, key: string, value: FormDataEntryValue, forceArray: boolean): void {
160
+ /** A form field whose name both holds a value and nests dotted fields (`a` and `a.b`): the body has no shape that keeps both. */
161
+ class FormFieldConflict extends Error {
162
+ constructor(readonly field: string) {
163
+ super(`form field "${field}" conflicts with another field`)
164
+ }
165
+ }
166
+
167
+ function appendFormValue(target: Record<string, unknown>, key: string, value: FormDataEntryValue, forceArray: boolean, rawKey: string): void {
161
168
  if (!Object.hasOwn(target, key)) {
162
169
  setField(target, key, forceArray ? [value] : value)
163
170
  return
164
171
  }
165
172
  const prev = target[key]
173
+ if (isPlainRecord(prev))
174
+ throw new FormFieldConflict(rawKey)
166
175
  if (Array.isArray(prev))
167
176
  prev.push(value)
168
177
  else
169
178
  setField(target, key, [prev, value])
170
179
  }
171
180
 
172
- /** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely. */
181
+ /** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely; throws `FormFieldConflict` when a name both holds a value and nests others. */
173
182
  export function parseFormData(formData: FormData): Record<string, unknown> {
174
183
  const out: Record<string, unknown> = {}
175
184
  for (const [rawKey, val] of formData.entries()) {
176
185
  const forceArray = rawKey.length > 2 && rawKey.endsWith('[]')
177
186
  const key = forceArray ? rawKey.slice(0, -2) : rawKey
178
187
  if (!key.includes('.')) {
179
- appendFormValue(out, key, val, forceArray)
188
+ appendFormValue(out, key, val, forceArray, rawKey)
180
189
  continue
181
190
  }
182
191
  const parts = key.split('.')
183
192
  if (parts.some(p => UNSAFE_NESTED_KEYS.has(p)))
184
193
  continue
185
194
  if (parts.length > MAX_NESTED_DEPTH || parts.some(p => p.length === 0)) {
186
- appendFormValue(out, key, val, forceArray)
195
+ appendFormValue(out, key, val, forceArray, rawKey)
187
196
  continue
188
197
  }
189
198
  let cur = out
190
- let blocked = false
191
- for (let i = 0; i < parts.length - 1; i++) {
192
- const seg = parts[i]!
199
+ for (const seg of parts.slice(0, -1)) {
193
200
  if (!Object.hasOwn(cur, seg)) {
194
201
  const next: Record<string, unknown> = {}
195
202
  setField(cur, seg, next)
196
203
  cur = next
204
+ continue
197
205
  }
198
- else if (isPlainRecord(cur[seg])) {
199
- cur = cur[seg]
200
- }
201
- else {
202
- blocked = true
203
- break
204
- }
206
+ const held = cur[seg]
207
+ if (!isPlainRecord(held))
208
+ throw new FormFieldConflict(rawKey)
209
+ cur = held
205
210
  }
206
- if (!blocked)
207
- appendFormValue(cur, parts[parts.length - 1]!, val, forceArray)
211
+ appendFormValue(cur, parts[parts.length - 1]!, val, forceArray, rawKey)
208
212
  }
209
213
  return out
210
214
  }
@@ -448,8 +452,12 @@ export async function executeAction(
448
452
  try {
449
453
  rawBody = await parseActionBody(request)
450
454
  }
451
- catch {
452
- return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
455
+ catch (error) {
456
+ if (!(error instanceof FormFieldConflict))
457
+ return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
458
+ const fieldErrors = { [error.field]: 'This field conflicts with another field of the form' }
459
+ return flashAndRedirect('Invalid request body', fieldErrors, undefined)
460
+ ?? Response.json({ ok: false, status: 400, error: 'Invalid request body', fieldErrors }, { status: 400 })
453
461
  }
454
462
  }
455
463
 
@@ -20,9 +20,8 @@ export function appSecret(): { secret: string, ephemeral: boolean } {
20
20
  return { secret, ephemeral: true }
21
21
  }
22
22
 
23
- /** A 32-byte key for `purpose` (`"form-timestamp"`, `"action-flash"`), HKDF-SHA256 (RFC 5869) of the app secret with `"prunelle"` as salt and the purpose as `info`. */
24
- export function deriveKey(purpose: string): Buffer {
25
- const { secret } = appSecret()
23
+ /** A 32-byte key for `purpose` (`"form-timestamp"`, `"action-flash"`), HKDF-SHA256 (RFC 5869) of the app secret (or of `secret`, for a plugin with a secret of its own) with `"prunelle"` as salt and the purpose as `info`. */
24
+ export function deriveKey(purpose: string, secret: string = appSecret().secret): Buffer {
26
25
  const id = `${purpose}\0${secret}`
27
26
  let key = keyCache.get(id)
28
27
  if (key === undefined) {
@@ -48,16 +47,16 @@ export function safeEqual(a: string, b: string): boolean {
48
47
  return diff === 0
49
48
  }
50
49
 
51
- /** `<signature>.<payload>`: the payload as is, behind the HMAC-SHA256 (base64url) of it under the key for `purpose`. */
52
- export function signPayload(purpose: string, payload: string): string {
53
- return `${hmac(deriveKey(purpose), payload).toString('base64url')}.${payload}`
50
+ /** `<signature>.<payload>`: the payload as is, behind the HMAC-SHA256 (base64url) of it under the key for `purpose`, derived from the app secret or from `secret`. */
51
+ export function signPayload(purpose: string, payload: string, secret?: string): string {
52
+ return `${hmac(deriveKey(purpose, secret), payload).toString('base64url')}.${payload}`
54
53
  }
55
54
 
56
- /** The payload of a `signPayload` value, or undefined when it is not one or its signature does not match. */
57
- export function verifyPayload(purpose: string, signed: string): string | undefined {
55
+ /** The payload of a `signPayload` value made for `purpose` (and `secret`), or undefined when it is not one or its signature does not match. */
56
+ export function verifyPayload(purpose: string, signed: string, secret?: string): string | undefined {
58
57
  const dot = signed.indexOf('.')
59
58
  if (dot <= 0)
60
59
  return undefined
61
60
  const payload = signed.slice(dot + 1)
62
- return safeEqual(signed.slice(0, dot), hmac(deriveKey(purpose), payload).toString('base64url')) ? payload : undefined
61
+ return safeEqual(signed.slice(0, dot), hmac(deriveKey(purpose, secret), payload).toString('base64url')) ? payload : undefined
63
62
  }