prunelle 0.1.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
package/src/ssr/index.ts CHANGED
@@ -1,11 +1,15 @@
1
1
  // Prunelle SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
2
2
 
3
3
  import type { Html, HydrateStrategy, PrunelleChild } from '../jsx-runtime'
4
+ import type { ServerAction } from '../server/action'
5
+ import type { FieldConstraint } from '../server/form-schema'
4
6
  import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
5
7
  import { renderOnServer } from '../reactivity/index'
8
+ import { renderProtectFields } from '../server/action-protect'
9
+ import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
6
10
  import { styleText } from '../style'
7
11
  import { assertRenderable } from '../unrenderable'
8
- import { currentRenderContext, PRUNELLE_STREAM_SCRIPT, renderIsland } from './context'
12
+ import { currentFormFields, currentRenderContext, lookupFormAction, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
9
13
  import { keepScrollTag } from './navigation'
10
14
  export { ssrStyleBlock } from './context'
11
15
 
@@ -96,6 +100,16 @@ export function escAttr(value: unknown): string {
96
100
  .replaceAll('>', '>')
97
101
  }
98
102
 
103
+ // What XML 1.0 forbids in a document: C0 controls but tab, LF and CR, U+FFFE, U+FFFF and lone surrogates.
104
+ const XML_FORBIDDEN_RE = /[\0-\x08\v\f\x0E-\x1F\uFFFE\uFFFF\uD800-\uDFFF]/gu
105
+ const XML_ESCAPES: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&apos;' }
106
+ const XML_SPECIAL_RE = /[&<>"']/g
107
+
108
+ /** Text for an XML document (a feed, a sitemap): escaped, and stripped of the characters that would make the whole file invalid. */
109
+ export function escXml(value: unknown): string {
110
+ return String(value).replace(XML_FORBIDDEN_RE, '').replace(XML_SPECIAL_RE, c => XML_ESCAPES[c]!)
111
+ }
112
+
99
113
  // `<`, then the two line separators, built from their code points so the source shows no invisible character.
100
114
  const SCRIPT_JSON_RE = new RegExp(`[<${String.fromCharCode(0x2028, 0x2029)}]`, 'g')
101
115
 
@@ -143,6 +157,8 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
143
157
  if (props == null || typeof props !== 'object')
144
158
  return ''
145
159
  let out = ''
160
+ let formPresent = 0
161
+ const trackForm = (tag === 'input' || tag === 'select' || tag === 'textarea') && currentFormFields() !== undefined
146
162
  for (const [rawKey, value] of Object.entries(props)) {
147
163
  if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
148
164
  continue
@@ -151,8 +167,121 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
151
167
  const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
152
168
  if (isBlockedAttr(name))
153
169
  continue
170
+ if (trackForm && value !== undefined) {
171
+ const bit = FORM_ATTR_BITS[name.toLowerCase()]
172
+ if (bit !== undefined)
173
+ formPresent |= bit
174
+ }
154
175
  out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value, tag)
155
176
  }
177
+ if (trackForm && typeof props.name === 'string')
178
+ out += ssrFormAttrs(tag, props.name, formPresent, props.type)
179
+ return out
180
+ }
181
+
182
+ const FORM_ATTR_BITS: Record<string, number> = {
183
+ type: 1,
184
+ required: 2,
185
+ minlength: 4,
186
+ maxlength: 8,
187
+ min: 16,
188
+ max: 32,
189
+ step: 64,
190
+ pattern: 128,
191
+ }
192
+ const TEXT_INPUT_TYPES = new Set(['text', 'search', 'url', 'tel', 'email', 'password'])
193
+ const NON_REQUIRED_INPUT_TYPES = new Set(['hidden', 'submit', 'button', 'reset', 'image'])
194
+
195
+ function resolveActionForForm(action: unknown): ServerAction<unknown, unknown> | undefined {
196
+ if (typeof action === 'function' && (action as { __pruAction?: boolean }).__pruAction === true)
197
+ return action as ServerAction<unknown, unknown>
198
+ if (typeof action === 'string') {
199
+ const found = lookupFormAction(action)
200
+ if (typeof found === 'function' && (found as { __pruAction?: boolean }).__pruAction === true)
201
+ return found as ServerAction<unknown, unknown>
202
+ }
203
+ return undefined
204
+ }
205
+
206
+ function formFieldsOf(act: ServerAction<unknown, unknown>): ReadonlyMap<string, FieldConstraint> | undefined {
207
+ if (act.schema === undefined)
208
+ return undefined
209
+ const extracted = extractFormSchema(act.schema)
210
+ return extracted.ok && extracted.fields.size > 0 ? extracted.fields : undefined
211
+ }
212
+
213
+ /** Wraps an action-bound `<form>` render during SSR: injects schema constraints for child fields and appends honeypot / signed timestamp inputs. */
214
+ export function ssrForm(action: unknown, render: (action: unknown) => string): string {
215
+ const act = resolveActionForForm(action)
216
+ if (act === undefined)
217
+ return `${render(action)}</form>`
218
+ const hidden = renderProtectFields(act.protect, act.url)
219
+ const fields = formFieldsOf(act)
220
+ const body = fields !== undefined ? runWithFormFields(fields, () => render(action)) : render(action)
221
+ return `${body}${hidden}</form>`
222
+ }
223
+
224
+ /** Async variant of `ssrForm` for action-bound `<form>` elements containing `await`. */
225
+ export async function ssrFormAsync(action: unknown, render: (action: unknown) => Promise<string>): Promise<string> {
226
+ const act = resolveActionForForm(action)
227
+ if (act === undefined)
228
+ return `${await render(action)}</form>`
229
+ const hidden = renderProtectFields(act.protect, act.url)
230
+ const fields = formFieldsOf(act)
231
+ const body = fields !== undefined ? await runWithFormFields(fields, () => render(action)) : await render(action)
232
+ return `${body}${hidden}</form>`
233
+ }
234
+
235
+ /** Emits schema-derived HTML5 constraint attributes on `<input>`, `<select>`, and `<textarea>` inside an action-bound `<form>`. */
236
+ export function ssrFormAttrs(tag: 'input' | 'select' | 'textarea', name: unknown, present: number, inputType?: unknown): string {
237
+ const fields = currentFormFields()
238
+ if (fields === undefined || typeof name !== 'string' || name === '')
239
+ return ''
240
+ const c = lookupFieldConstraint(fields, name)
241
+ if (c === undefined)
242
+ return ''
243
+
244
+ let out = ''
245
+ const explicitType = typeof inputType === 'string' ? inputType.toLowerCase() : undefined
246
+ let effectiveType: string | undefined
247
+ if (tag === 'input') {
248
+ if (explicitType === undefined && (present & 1) === 0 && c.type !== undefined) {
249
+ out += ` type="${c.type}"`
250
+ effectiveType = c.type
251
+ }
252
+ else {
253
+ effectiveType = explicitType ?? 'text'
254
+ }
255
+ }
256
+
257
+ const skipRequired = tag === 'input' && (
258
+ NON_REQUIRED_INPUT_TYPES.has(effectiveType!)
259
+ || (effectiveType === 'checkbox' && c.isArray === true)
260
+ )
261
+ if (c.required === true && (present & 2) === 0 && !skipRequired)
262
+ out += ' required'
263
+
264
+ const supportsLength = tag === 'textarea' || (tag === 'input' && TEXT_INPUT_TYPES.has(effectiveType!))
265
+ if (supportsLength) {
266
+ if (c.minLength !== undefined && (present & 4) === 0)
267
+ out += ` minlength="${c.minLength}"`
268
+ if (c.maxLength !== undefined && (present & 8) === 0)
269
+ out += ` maxlength="${c.maxLength}"`
270
+ }
271
+
272
+ if (tag === 'input') {
273
+ if (effectiveType === 'number' || effectiveType === 'range') {
274
+ if (c.min !== undefined && (present & 16) === 0)
275
+ out += ` min="${c.min}"`
276
+ if (c.max !== undefined && (present & 32) === 0)
277
+ out += ` max="${c.max}"`
278
+ if (c.step !== undefined && (present & 64) === 0)
279
+ out += ` step="${c.step}"`
280
+ }
281
+ if (TEXT_INPUT_TYPES.has(effectiveType!) && c.pattern !== undefined && (present & 128) === 0)
282
+ out += ` pattern="${escAttr(c.pattern)}"`
283
+ }
284
+
156
285
  return out
157
286
  }
158
287
 
@@ -215,8 +344,16 @@ function serializeIslandProps(props: Record<string, unknown>): string {
215
344
  throw new TypeError(`prunelle: island prop "${key}" is a function, which cannot reach the browser; define it inside the island, or import it there.`)
216
345
  if (typeof orig === 'object' && orig !== null && 'peek' in orig && 'value' in orig)
217
346
  throw new TypeError(`prunelle: island prop "${key}" is a signal; pass ${key}.value, or import the signal in the island from a shared module.`)
218
- if (typeof orig === 'object' && orig !== null && !Array.isArray(orig) && Object.hasOwn(orig, '__k'))
219
- return { __k: 'O', v: Object.entries(orig).filter(([, x]) => x !== undefined) }
347
+ if (typeof orig === 'object' && orig !== null && !Array.isArray(orig)) {
348
+ const proto = Object.getPrototypeOf(orig) as { constructor?: { name?: string } } | null
349
+ if (proto !== Object.prototype && proto !== null) {
350
+ const typeName = proto?.constructor?.name || 'Object'
351
+ const propName = key ? `"${key}"` : '(root)'
352
+ throw new TypeError(`prunelle: island prop ${propName} (${typeName}) cannot be serialized to the browser; pass a plain object, array, primitive, Date, Map, Set, URL, RegExp, or BigInt.`)
353
+ }
354
+ if (Object.hasOwn(orig, '__k'))
355
+ return { __k: 'O', v: Object.entries(orig).filter(([, x]) => x !== undefined) }
356
+ }
220
357
  return value
221
358
  })
222
359
  }
@@ -420,6 +557,11 @@ export interface DocumentOptions {
420
557
  navigation?: string | undefined
421
558
  }
422
559
 
560
+ // A tab icon link (`icon`, `shortcut icon`); an `apple-touch-icon` alone still leaves the browser asking for /favicon.ico.
561
+ const TAB_ICON_RE = /<link\b[^>]*\brel=["']?(?:[^"'>]*\s)?icon(?=[\s"'>])/i
562
+ // Named in a page with no icon of its own: the browser takes it as the icon and never requests /favicon.ico, which most apps answer with a 404.
563
+ const EMPTY_ICON = '<link rel="icon" href="data:,">'
564
+
423
565
  export function renderDocument(options: DocumentOptions): string {
424
566
  const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, navigation } = options
425
567
  let headExtra = head
@@ -429,6 +571,9 @@ export function renderDocument(options: DocumentOptions): string {
429
571
  headExtra += tag
430
572
  }
431
573
 
574
+ if (!TAB_ICON_RE.test(headExtra))
575
+ headExtra += EMPTY_ICON
576
+
432
577
  if (styles !== undefined) {
433
578
  for (const href of styles)
434
579
  headExtra += `<link rel="stylesheet" href="${escAttr(href)}">`
@@ -10,7 +10,7 @@ export type Eagerness = 'conservative' | 'moderate' | 'eager'
10
10
  export interface NavigationConfig {
11
11
  /** Fades one page into the next with a cross-document view transition (`@view-transition { navigation: auto }`), off under `prefers-reduced-motion`. On by default, `false` leaves the browser's plain repaint. */
12
12
  viewTransitions?: boolean | undefined
13
- /** When the browser fetches the page a same-origin link points at, through Speculation Rules: `'moderate'` (the default) on hover, `'conservative'` on press, `'eager'` as soon as it can, `false` never. A link, or an ancestor of it, with `data-pru-no-prefetch` is never fetched; neither is a `download` or `rel="nofollow"` link, a prunelle route (actions among them) or another origin's page. */
13
+ /** When the browser fetches the page a same-origin link points at, through Speculation Rules: `'conservative'` (the default) on press, `'moderate'` on hover (and, on phones, as a link scrolls into view), `'eager'` as soon as it can, `false` never. A link, or an ancestor of it, with `data-pru-no-prefetch` is never fetched; neither is a `download` or `rel="nofollow"` link, a prunelle route (actions among them) or another origin's page. */
14
14
  prefetch?: Eagerness | false | undefined
15
15
  /** Renders the page a link points at before it is followed, which runs its `load()`: off by default, `true` is `'moderate'`. */
16
16
  prerender?: Eagerness | boolean | undefined
@@ -64,7 +64,7 @@ export function createNavigation(config: NavigationConfig | undefined): Navigati
64
64
  html += `<style>${VIEW_TRANSITION_STYLE}</style>`
65
65
  styleHashes.push(cspSha256(VIEW_TRANSITION_STYLE))
66
66
  }
67
- const prefetch = config?.prefetch === undefined ? 'moderate' : config.prefetch
67
+ const prefetch = config?.prefetch === undefined ? 'conservative' : config.prefetch
68
68
  const prerender = config?.prerender === true ? 'moderate' : config?.prerender || undefined
69
69
  if (prefetch !== false || prerender !== undefined) {
70
70
  const where = rulesWhere()
package/src/ssr/region.ts CHANGED
@@ -83,6 +83,7 @@ async function settleChunkWithin(
83
83
  let timer: ReturnType<typeof setTimeout> | undefined
84
84
  const timedOut = new Promise<SettledChunk>((resolve) => {
85
85
  timer = setTimeout(() => {
86
+ chunk.discard?.()
86
87
  const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
87
88
  resolve({ html: runInScope(() => chunk.renderError(error)), error })
88
89
  }, remaining)
@@ -98,8 +99,7 @@ async function settleChunkWithin(
98
99
  async function awaitRegionDiscovery(
99
100
  ctx: RenderContext,
100
101
  deadline: number,
101
- onError: ((error: unknown) => void) | undefined,
102
- runInScope: <T>(fn: () => T) => T,
102
+ reportError: (id: number, error: unknown) => void,
103
103
  ): Promise<void> {
104
104
  const watched = new Set<number>()
105
105
  let pendingCount = 0
@@ -125,8 +125,8 @@ async function awaitRegionDiscovery(
125
125
  pendingCount--
126
126
  if (done)
127
127
  return
128
- if ('error' in settled && onError !== undefined)
129
- runInScope(() => onError(settled.error))
128
+ if ('error' in settled)
129
+ reportError(chunk.id, settled.error)
130
130
  if (ctx.regionHtml !== undefined) {
131
131
  finish()
132
132
  return
@@ -150,22 +150,34 @@ export async function finishRegion(ctx: RenderContext, options?: FinishRegionOpt
150
150
  const onError = options?.onError
151
151
  const runInScope = options?.runInScope ?? (<T>(fn: () => T) => fn())
152
152
  const deadline = Date.now() + streamTimeout
153
+ const reported = new Set<number>()
154
+ const reportError = (id: number, error: unknown): void => {
155
+ if (onError === undefined || reported.has(id))
156
+ return
157
+ reported.add(id)
158
+ runInScope(() => onError(error))
159
+ }
153
160
 
154
- if (ctx.regionHtml === undefined && ctx.pending.length > 0)
155
- await awaitRegionDiscovery(ctx, deadline, onError, runInScope)
161
+ try {
162
+ if (ctx.regionHtml === undefined && ctx.pending.length > 0)
163
+ await awaitRegionDiscovery(ctx, deadline, reportError)
156
164
 
157
- let html = ctx.regionHtml
158
- if (html === undefined)
159
- return undefined
160
- for (let i = 0; i < ctx.pending.length; i++) {
161
- const chunk = ctx.pending[i]!
162
- const range = findPlaceholderRange(html, chunk.id)
163
- if (range === undefined)
164
- continue
165
- const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
166
- if ('error' in settled && onError !== undefined)
167
- runInScope(() => onError(settled.error))
168
- html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
165
+ let html = ctx.regionHtml
166
+ if (html === undefined)
167
+ return undefined
168
+ for (let i = 0; i < ctx.pending.length; i++) {
169
+ const chunk = ctx.pending[i]!
170
+ const range = findPlaceholderRange(html, chunk.id)
171
+ if (range === undefined)
172
+ continue
173
+ const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
174
+ if ('error' in settled)
175
+ reportError(chunk.id, settled.error)
176
+ html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
177
+ }
178
+ return html
179
+ }
180
+ finally {
181
+ ctx.aborted = true
169
182
  }
170
- return html
171
183
  }
package/src/style.ts CHANGED
@@ -20,10 +20,41 @@ function cssName(key: string): string {
20
20
  return MS_PREFIX.test(key) ? `-${name}` : name
21
21
  }
22
22
 
23
+ const PROPERTY_NAME = /^-{0,2}[a-z][\w-]*$/i
24
+
25
+ // Whether `value` stays one declaration value: a `;`, `{` or `}` outside quotes and parentheses, a comment, a raw newline, or a quote or parenthesis left open would end it and let the rest add declarations.
26
+ function isOneValue(value: string): boolean {
27
+ let depth = 0
28
+ let quote = ''
29
+ for (let i = 0; i < value.length; i++) {
30
+ const c = value[i]!
31
+ if (c === '\\')
32
+ i++
33
+ else if (c === '\n' || c === '\r' || c === '\f')
34
+ return false
35
+ else if (quote !== '')
36
+ quote = c === quote ? '' : quote
37
+ else if (c === '"' || c === '\'')
38
+ quote = c
39
+ else if (c === '/' && value[i + 1] === '*')
40
+ return false
41
+ else if (c === '(')
42
+ depth++
43
+ else if (c === ')' && --depth < 0)
44
+ return false
45
+ else if (depth === 0 && (c === ';' || c === '{' || c === '}'))
46
+ return false
47
+ }
48
+ return quote === '' && depth === 0
49
+ }
50
+
51
+ /** The CSS text of a style object. A declaration that could not stay one is dropped, as a browser drops an invalid one: a key that is not a property name, a non-finite number, a string value `isOneValue` refuses. */
23
52
  export function styleText(style: Record<string, unknown>): string {
24
53
  let out = ''
25
54
  for (const [key, value] of Object.entries(style)) {
26
- if (value == null || value === '' || value === false)
55
+ if (value == null || value === '' || value === false || !PROPERTY_NAME.test(key))
56
+ continue
57
+ if (typeof value === 'number' ? !Number.isFinite(value) : !isOneValue(String(value)))
27
58
  continue
28
59
  const name = cssName(key)
29
60
  const px = typeof value === 'number' && !name.startsWith('--') && !UNITLESS.has(name)
@@ -23,6 +23,8 @@ export interface BrowserPage {
23
23
  /** Moves the pointer over the first element matching `selector`, as a visitor hovering a link does. */
24
24
  hover(selector: string): Promise<void>
25
25
  fill(selector: string, value: string): Promise<void>
26
+ /** Presses a key (`'Escape'`, `'ArrowRight'`, `'Tab'`) through the browser's keyboard input pipeline. */
27
+ press(key: string): Promise<void>
26
28
  /** The text content of the first element matching `selector`. */
27
29
  text(selector: string): Promise<string>
28
30
  close(): Promise<void>
@@ -43,6 +45,7 @@ const DEFAULT_TIMEOUT_MS = 10_000
43
45
 
44
46
  // The few playwright-core types used here, so an app's typecheck never needs playwright-core installed.
45
47
  interface Page {
48
+ url(): string
46
49
  on(event: 'pageerror', listener: (error: Error) => void): void
47
50
  on(event: 'response', listener: (response: { status: () => number, url: () => string }) => void): void
48
51
  on(event: 'console', listener: (message: { type: () => string, text: () => string }) => void): void
@@ -53,6 +56,7 @@ interface Page {
53
56
  click(selector: string, options: { timeout: number }): Promise<void>
54
57
  hover(selector: string, options: { timeout: number }): Promise<void>
55
58
  fill(selector: string, value: string, options: { timeout: number }): Promise<void>
59
+ keyboard: { press(key: string): Promise<void> }
56
60
  locator(selector: string): { first: () => { innerText: (options: { timeout: number }) => Promise<string> } }
57
61
  }
58
62
  interface BrowserContext {
@@ -64,8 +68,8 @@ interface Browser {
64
68
  close(): Promise<void>
65
69
  }
66
70
 
67
- // True once every island that hydrates on load has hydrated; the ones waiting to be seen, idle or touched are left to the test.
68
- const ISLANDS_HYDRATED = `[...document.querySelectorAll('pru-island')].every(e => ['visible', 'idle', 'interaction'].includes(e.getAttribute('h')) || e._d !== undefined)`
71
+ // True once every island that hydrates on load has hydrated; the ones waiting to be seen, idle, touched or matching a media query are left to the test.
72
+ const ISLANDS_HYDRATED = `[...document.querySelectorAll('pru-island')].every(e => { const h = e.getAttribute('h'); return h === 'visible' || h === 'idle' || h === 'interaction' || (h !== null && h.startsWith('media(')) || e._d !== undefined })`
69
73
 
70
74
  interface PlaywrightCore {
71
75
  chromium: { launch: (options: { headless: boolean, executablePath: string }) => Promise<Browser>, executablePath: () => string }
@@ -93,7 +97,7 @@ function findBrowser(playwright: PlaywrightCore, given: string | undefined): str
93
97
  return found
94
98
  }
95
99
 
96
- function wrapPage(page: Page, context: BrowserContext, timeout: number, url: string): BrowserPage {
100
+ function wrapPage(page: Page, context: BrowserContext, timeout: number): BrowserPage {
97
101
  const errors: string[] = []
98
102
  page.on('pageerror', error => errors.push(error.message))
99
103
  // A failed load logs a console error without its URL, so the response names it instead; the favicon browsers ask for unprompted is no mistake of the app.
@@ -106,7 +110,9 @@ function wrapPage(page: Page, context: BrowserContext, timeout: number, url: str
106
110
  errors.push(message.text())
107
111
  })
108
112
  return {
109
- url,
113
+ get url() {
114
+ return page.url()
115
+ },
110
116
  errors,
111
117
  async evaluate(fn) {
112
118
  return await page.evaluate(fn as () => never)
@@ -126,6 +132,9 @@ function wrapPage(page: Page, context: BrowserContext, timeout: number, url: str
126
132
  async fill(selector, value) {
127
133
  await page.fill(selector, value, { timeout })
128
134
  },
135
+ async press(key) {
136
+ await page.keyboard.press(key)
137
+ },
129
138
  async text(selector) {
130
139
  return await page.locator(selector).first().innerText({ timeout })
131
140
  },
@@ -160,19 +169,25 @@ export async function testBrowser(options: BrowserTestOptions): Promise<BrowserT
160
169
  origin,
161
170
  async open(path, openOptions) {
162
171
  const context = await browser.newContext(openOptions?.reducedMotion === true ? { reducedMotion: 'reduce' } : undefined)
163
- const page = await context.newPage()
164
- const url = new URL(path, origin).href
165
- const wrapped = wrapPage(page, context, timeout, url)
166
- // Not `networkidle`: a page that polls or streams never goes idle.
167
- await page.goto(url, { waitUntil: 'load', timeout })
168
172
  try {
169
- await page.waitForFunction(ISLANDS_HYDRATED, undefined, { timeout })
173
+ const page = await context.newPage()
174
+ const url = new URL(path, origin).href
175
+ const wrapped = wrapPage(page, context, timeout)
176
+ // Not `networkidle`: a page that polls or streams never goes idle.
177
+ await page.goto(url, { waitUntil: 'load', timeout })
178
+ try {
179
+ await page.waitForFunction(ISLANDS_HYDRATED, undefined, { timeout })
180
+ }
181
+ catch (error) {
182
+ const seen = wrapped.errors.length > 0 ? `; the page reported: ${wrapped.errors.join('; ')}` : ''
183
+ throw new Error(`prunelle: the islands of ${url} did not hydrate within ${timeout} ms${seen}.`, { cause: error })
184
+ }
185
+ return wrapped
170
186
  }
171
187
  catch (error) {
172
- const seen = wrapped.errors.length > 0 ? `; the page reported: ${wrapped.errors.join('; ')}` : ''
173
- throw new Error(`prunelle: the islands of ${url} did not hydrate within ${timeout} ms${seen}.`, { cause: error })
188
+ await context.close().catch(() => undefined)
189
+ throw error
174
190
  }
175
- return wrapped
176
191
  },
177
192
  async close() {
178
193
  try {
package/src/test/index.ts CHANGED
@@ -2,16 +2,65 @@
2
2
 
3
3
  import type { BuildManifest, BuildOptions } from '../build/index'
4
4
  import type { PrunelleApp, ServerAction, ServerRuntimeConfig } from '../server/index'
5
- import { readdirSync, rmSync } from 'node:fs'
5
+ import { existsSync, readdirSync, rmSync } from 'node:fs'
6
6
  import { dirname, join, resolve } from 'node:path'
7
7
  import { build } from '../build/index'
8
8
  import { relPosix } from '../build/files'
9
9
  import { processSuffix, removeDeadProcessDirs } from '../build/output'
10
+ import { ensureCacheGitignore } from '../build/precompress'
10
11
  import { resolveServerConfig } from '../server/index'
12
+ import { FORM_TIMESTAMP_FIELD, honeypotFieldName, signFormTimestamp } from '../server/action-protect'
11
13
  import { startBuiltApp } from '../server/loader'
12
14
 
13
15
  const TEST_DIR_PREFIX = 'test-'
14
- const ABSOLUTE_URL_RE = /^https?:\/\//
16
+ const ABSOLUTE_URL_RE = /^https?:\/\//i
17
+ const INTEGER_RE = /^-?\d+$/
18
+
19
+ function safeDecodeCookieValue(val: string): string {
20
+ try {
21
+ return decodeURIComponent(val)
22
+ }
23
+ catch {
24
+ return val
25
+ }
26
+ }
27
+
28
+ function isExpiredSetCookie(raw: string): boolean {
29
+ const parts = raw.split(';')
30
+ let hasMaxAge = false
31
+ let maxAgeExpired = false
32
+ let expiresExpired = false
33
+ for (let i = 1; i < parts.length; i++) {
34
+ const seg = parts[i]!.trim()
35
+ const eq = seg.indexOf('=')
36
+ if (eq <= 0)
37
+ continue
38
+ const attrName = seg.slice(0, eq).trim().toLowerCase()
39
+ const attrVal = seg.slice(eq + 1).trim()
40
+ if (attrName === 'max-age' && INTEGER_RE.test(attrVal)) {
41
+ hasMaxAge = true
42
+ maxAgeExpired = Number(attrVal) <= 0
43
+ }
44
+ else if (attrName === 'expires') {
45
+ const ts = Date.parse(attrVal)
46
+ if (Number.isFinite(ts))
47
+ expiresExpired = ts <= Date.now()
48
+ }
49
+ }
50
+ return hasMaxAge ? maxAgeExpired : expiresExpired
51
+ }
52
+
53
+ function defaultOriginFor(target: string): string {
54
+ if (ABSOLUTE_URL_RE.test(target)) {
55
+ try {
56
+ return new URL(target).origin
57
+ }
58
+ catch {
59
+ return 'http://localhost'
60
+ }
61
+ }
62
+ return 'http://localhost'
63
+ }
15
64
 
16
65
  export interface TestAppOptions extends Omit<BuildOptions, 'compile' | 'static'>, Partial<ServerRuntimeConfig> {
17
66
  prebuilt?: boolean | undefined
@@ -31,6 +80,9 @@ export interface TestApp {
31
80
  /** Posts `fields` as a form to an action, given as one from `import()` or as its URL. */
32
81
  submit(action: ServerAction<never, unknown> | string, fields: Record<string, string>, headers?: HeadersInit): Promise<Response>
33
82
  clearCookies(): void
83
+ /** Runs plugin shutdown hooks and cleans up app resources (idempotent). */
84
+ dispose(): Promise<void>
85
+ [Symbol.asyncDispose](): Promise<void>
34
86
  }
35
87
 
36
88
  /** The folder of the latest testApp() build of each app root in this process, which `prebuilt: true` reuses. */
@@ -41,12 +93,17 @@ const ownOutDirs: string[] = []
41
93
  function ownOutDir(root: string): string {
42
94
  const cacheDir = join(root, '.prunelle-cache')
43
95
  removeDeadProcessDirs(cacheDir, TEST_DIR_PREFIX)
96
+ ensureCacheGitignore(cacheDir)
44
97
  if (ownOutDirs.length === 0) {
45
98
  process.once('exit', () => {
46
99
  for (const dir of ownOutDirs) {
47
100
  rmSync(dir, { recursive: true, force: true })
48
- if (readdirSync(dirname(dir)).length === 0)
49
- rmSync(dirname(dir), { recursive: true, force: true })
101
+ const parent = dirname(dir)
102
+ if (!existsSync(parent))
103
+ continue
104
+ const remaining = readdirSync(parent)
105
+ if (remaining.length === 0 || (remaining.length === 1 && remaining[0] === '.gitignore'))
106
+ rmSync(parent, { recursive: true, force: true })
50
107
  }
51
108
  })
52
109
  }
@@ -63,10 +120,19 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
63
120
  root: options.root,
64
121
  routesDir: options.routesDir,
65
122
  outDir,
123
+ publicDir: options.publicDir,
66
124
  minify: options.minify ?? false,
67
125
  assetPrefix: options.assetPrefix,
68
126
  site: options.site,
69
127
  plugins: options.plugins,
128
+ cache: options.cache,
129
+ analyze: options.analyze,
130
+ analyzeJson: options.analyzeJson,
131
+ onAnalyze: options.onAnalyze,
132
+ maxJs: options.maxJs,
133
+ prerender: options.prerender,
134
+ autoPrerender: options.autoPrerender,
135
+ copyPublic: options.copyPublic,
70
136
  dev: options.dev,
71
137
  nodeEnv: options.nodeEnv,
72
138
  })
@@ -100,29 +166,39 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
100
166
  continue
101
167
  const name = first.slice(0, eq).trim()
102
168
  const val = first.slice(eq + 1).trim()
103
- if (/max-age=0/i.test(raw) || val === '')
169
+ if (isExpiredSetCookie(raw) || val === '')
104
170
  cookies.delete(name)
105
171
  else
106
- cookies.set(name, decodeURIComponent(val))
172
+ cookies.set(name, safeDecodeCookieValue(val))
107
173
  }
108
174
  }
109
175
 
110
176
  async function doFetch(pathOrReq: string | Request, init?: RequestInit): Promise<Response> {
111
177
  const req = typeof pathOrReq === 'string'
112
178
  ? new Request(ABSOLUTE_URL_RE.test(pathOrReq) ? pathOrReq : `http://localhost${pathOrReq}`, init)
113
- : pathOrReq
179
+ : (init !== undefined ? new Request(pathOrReq, init) : pathOrReq)
114
180
 
115
- const headers = new Headers(req.headers)
116
181
  const existing = cookieHeader()
117
- if (existing !== undefined && !headers.has('cookie'))
182
+ let withCookies = req
183
+ if (existing !== undefined && !req.headers.has('cookie')) {
184
+ const headers = new Headers(req.headers)
118
185
  headers.set('cookie', existing)
186
+ withCookies = new Request(req, { headers })
187
+ }
119
188
 
120
- const withCookies = new Request(req, { headers })
121
189
  const res = await app.handle(withCookies)
122
190
  storeSetCookies(res)
123
191
  return res
124
192
  }
125
193
 
194
+ let disposed = false
195
+ async function dispose(): Promise<void> {
196
+ if (disposed)
197
+ return
198
+ disposed = true
199
+ await app.dispose?.()
200
+ }
201
+
126
202
  return {
127
203
  app,
128
204
  manifest,
@@ -135,7 +211,7 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
135
211
  post(path, body, headers) {
136
212
  const h = new Headers(headers)
137
213
  if (!h.has('origin'))
138
- h.set('origin', 'http://localhost')
214
+ h.set('origin', defaultOriginFor(path))
139
215
  if (body instanceof FormData)
140
216
  return doFetch(path, { method: 'POST', body, headers: h })
141
217
  if (!h.has('content-type'))
@@ -162,14 +238,23 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
162
238
  const fd = new FormData()
163
239
  for (const [k, v] of Object.entries(fields))
164
240
  fd.append(k, v)
241
+ if (typeof action !== 'string' && action.protect !== undefined) {
242
+ const hp = honeypotFieldName(action.protect)
243
+ if (hp !== undefined && !Object.hasOwn(fields, hp))
244
+ fd.append(hp, '')
245
+ if (action.protect.minTime !== undefined && !Object.hasOwn(fields, FORM_TIMESTAMP_FIELD))
246
+ fd.append(FORM_TIMESTAMP_FIELD, signFormTimestamp(Date.now() - Math.max(0, action.protect.minTime) - 1000, actionUrl))
247
+ }
165
248
  const h = new Headers(headers)
166
249
  if (!h.has('origin'))
167
- h.set('origin', 'http://localhost')
250
+ h.set('origin', defaultOriginFor(actionUrl))
168
251
  return doFetch(actionUrl, { method: 'POST', body: fd, headers: h })
169
252
  },
170
253
  clearCookies() {
171
254
  cookies.clear()
172
255
  },
256
+ dispose,
257
+ [Symbol.asyncDispose]: dispose,
173
258
  }
174
259
  }
175
260