prunelle 0.1.1 → 0.2.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 (48) hide show
  1. package/llms.txt +12 -12
  2. package/package.json +1 -1
  3. package/src/build/client-entries.ts +3 -2
  4. package/src/build/compile.ts +2 -1
  5. package/src/build/index.ts +68 -29
  6. package/src/build/manifest.ts +18 -1
  7. package/src/build/output.ts +2 -2
  8. package/src/build/precompress.ts +15 -2
  9. package/src/build/prerender.ts +2 -2
  10. package/src/build/routes.ts +171 -10
  11. package/src/build/static.ts +71 -17
  12. package/src/build/status-pages.ts +127 -0
  13. package/src/cli/check-forms.ts +654 -0
  14. package/src/cli/check-links.ts +619 -0
  15. package/src/cli/check.ts +37 -4
  16. package/src/cli/commands.ts +5 -3
  17. package/src/cli/inspect.ts +21 -2
  18. package/src/cli/upgrade-names.ts +73 -13
  19. package/src/cli/upgrade.ts +137 -16
  20. package/src/compiler/compliance-rgaa.ts +502 -0
  21. package/src/compiler/compliance.ts +119 -220
  22. package/src/compiler/ssr.ts +121 -24
  23. package/src/dom/action.ts +4 -1
  24. package/src/dom/island.ts +5 -5
  25. package/src/plugins/config.ts +1 -1
  26. package/src/plugins/types.ts +13 -0
  27. package/src/server/action-protect.ts +186 -0
  28. package/src/server/action.ts +33 -10
  29. package/src/server/errors.ts +291 -62
  30. package/src/server/form-schema.ts +343 -0
  31. package/src/server/health.ts +244 -0
  32. package/src/server/http.ts +84 -17
  33. package/src/server/index.ts +162 -91
  34. package/src/server/param-matchers.ts +112 -0
  35. package/src/server/plugin-host.ts +40 -14
  36. package/src/server/public.ts +3 -3
  37. package/src/server/route-table.ts +5 -2
  38. package/src/server/router.ts +125 -40
  39. package/src/server/routing.ts +95 -57
  40. package/src/server/security.ts +171 -22
  41. package/src/server/serve-handlers.ts +21 -7
  42. package/src/ssr/context.ts +49 -0
  43. package/src/ssr/index.ts +120 -1
  44. package/src/test/browser.ts +6 -0
  45. package/src/test/index.ts +17 -3
  46. package/templates/_shared/src/routes/legal.tsx +5 -0
  47. package/templates/blog/prunelle.config.ts +1 -1
  48. package/templates/blog/src/routes/index.tsx +4 -0
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { CatchProps, ConsentGateProps } from '../context'
5
5
  import type { Html, PrunelleChild } from '../jsx-runtime'
6
+ import type { FieldConstraint } from '../server/form-schema'
6
7
  import { AsyncLocalStorage } from 'node:async_hooks'
7
8
  import { registerServerContextBridge } from '../context'
8
9
  import { raw, ssrChild } from './index'
@@ -55,6 +56,8 @@ export interface RenderContext {
55
56
  consent: { has(category: string): boolean } | undefined
56
57
  /** Reports an error a `<Catch>` rendered its fallback for, to the app's error hook. */
57
58
  onCaught: ((error: unknown) => void) | undefined
59
+ /** Actions referenced via `useAction(fn).action` during this request, keyed by action URL. */
60
+ formActions: Map<string, unknown> | undefined
58
61
  }
59
62
 
60
63
  interface RenderScope {
@@ -63,12 +66,25 @@ interface RenderScope {
63
66
  outerContexts: ReadonlyMap<symbol, unknown> | undefined
64
67
  island: string | undefined
65
68
  inTarget: boolean
69
+ formFields: ReadonlyMap<string, FieldConstraint> | undefined
66
70
  }
67
71
 
68
72
  const STORAGE_KEY = Symbol.for('pru.render.storage')
69
73
  const SCOPE_STORAGE_KEY = Symbol.for('pru.render.scope.storage')
70
74
  const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
71
75
  const scopeStorage: AsyncLocalStorage<RenderScope> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderScope> | undefined>)[SCOPE_STORAGE_KEY] ??= new AsyncLocalStorage<RenderScope>())
76
+ let fallbackFormAction: { url: string, action: unknown } | undefined
77
+ let fallbackFormFields: ReadonlyMap<string, FieldConstraint> | undefined
78
+
79
+ ;(globalThis as { __pruAct?: (url: string, action: unknown) => void }).__pruAct = (url, action) => {
80
+ if (url === '')
81
+ return
82
+ const ctx = renderStorage.getStore()
83
+ if (ctx !== undefined)
84
+ (ctx.formActions ??= new Map()).set(url, action)
85
+ else
86
+ fallbackFormAction = { url, action }
87
+ }
72
88
 
73
89
  function activeScope(ctx: RenderContext): RenderScope {
74
90
  const scope = scopeStorage.getStore()
@@ -80,6 +96,38 @@ function activeScope(ctx: RenderContext): RenderScope {
80
96
  outerContexts: ctx.outerContexts,
81
97
  island: ctx.island,
82
98
  inTarget: ctx.inTarget,
99
+ formFields: undefined,
100
+ }
101
+ }
102
+
103
+ export function lookupFormAction(url: string): unknown {
104
+ const ctx = renderStorage.getStore()
105
+ if (ctx !== undefined)
106
+ return ctx.formActions?.get(url)
107
+ return fallbackFormAction?.url === url ? fallbackFormAction.action : undefined
108
+ }
109
+
110
+ export function currentFormFields(): ReadonlyMap<string, FieldConstraint> | undefined {
111
+ const ctx = renderStorage.getStore()
112
+ return ctx !== undefined ? activeScope(ctx).formFields : fallbackFormFields
113
+ }
114
+
115
+ export function runWithFormFields<T>(fields: ReadonlyMap<string, FieldConstraint>, fn: () => T): T {
116
+ const ctx = renderStorage.getStore()
117
+ if (ctx !== undefined)
118
+ return scopeStorage.run({ ...activeScope(ctx), formFields: fields }, fn)
119
+ const prev = fallbackFormFields
120
+ fallbackFormFields = fields
121
+ try {
122
+ const out = fn()
123
+ if (out instanceof Promise)
124
+ return out.finally(() => { fallbackFormFields = prev }) as T
125
+ fallbackFormFields = prev
126
+ return out
127
+ }
128
+ catch (err) {
129
+ fallbackFormFields = prev
130
+ throw err
83
131
  }
84
132
  }
85
133
 
@@ -165,6 +213,7 @@ export function createRenderContext(
165
213
  inlineStyles: undefined,
166
214
  consent,
167
215
  onCaught,
216
+ formActions: undefined,
168
217
  }
169
218
  }
170
219
 
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
 
@@ -143,6 +147,8 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
143
147
  if (props == null || typeof props !== 'object')
144
148
  return ''
145
149
  let out = ''
150
+ let formPresent = 0
151
+ const trackForm = (tag === 'input' || tag === 'select' || tag === 'textarea') && currentFormFields() !== undefined
146
152
  for (const [rawKey, value] of Object.entries(props)) {
147
153
  if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
148
154
  continue
@@ -151,8 +157,121 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
151
157
  const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
152
158
  if (isBlockedAttr(name))
153
159
  continue
160
+ if (trackForm && value !== undefined) {
161
+ const bit = FORM_ATTR_BITS[name.toLowerCase()]
162
+ if (bit !== undefined)
163
+ formPresent |= bit
164
+ }
154
165
  out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value, tag)
155
166
  }
167
+ if (trackForm && typeof props.name === 'string')
168
+ out += ssrFormAttrs(tag, props.name, formPresent, props.type)
169
+ return out
170
+ }
171
+
172
+ const FORM_ATTR_BITS: Record<string, number> = {
173
+ type: 1,
174
+ required: 2,
175
+ minlength: 4,
176
+ maxlength: 8,
177
+ min: 16,
178
+ max: 32,
179
+ step: 64,
180
+ pattern: 128,
181
+ }
182
+ const TEXT_INPUT_TYPES = new Set(['text', 'search', 'url', 'tel', 'email', 'password'])
183
+ const NON_REQUIRED_INPUT_TYPES = new Set(['hidden', 'submit', 'button', 'reset', 'image'])
184
+
185
+ function resolveActionForForm(action: unknown): ServerAction<unknown, unknown> | undefined {
186
+ if (typeof action === 'function' && (action as { __pruAction?: boolean }).__pruAction === true)
187
+ return action as ServerAction<unknown, unknown>
188
+ if (typeof action === 'string') {
189
+ const found = lookupFormAction(action)
190
+ if (typeof found === 'function' && (found as { __pruAction?: boolean }).__pruAction === true)
191
+ return found as ServerAction<unknown, unknown>
192
+ }
193
+ return undefined
194
+ }
195
+
196
+ function formFieldsOf(act: ServerAction<unknown, unknown>): ReadonlyMap<string, FieldConstraint> | undefined {
197
+ if (act.schema === undefined)
198
+ return undefined
199
+ const extracted = extractFormSchema(act.schema)
200
+ return extracted.ok && extracted.fields.size > 0 ? extracted.fields : undefined
201
+ }
202
+
203
+ /** Wraps an action-bound `<form>` render during SSR: injects schema constraints for child fields and appends honeypot / signed timestamp inputs. */
204
+ export function ssrForm(action: unknown, render: (action: unknown) => string): string {
205
+ const act = resolveActionForForm(action)
206
+ if (act === undefined)
207
+ return `${render(action)}</form>`
208
+ const hidden = renderProtectFields(act.protect)
209
+ const fields = formFieldsOf(act)
210
+ const body = fields !== undefined ? runWithFormFields(fields, () => render(action)) : render(action)
211
+ return `${body}${hidden}</form>`
212
+ }
213
+
214
+ /** Async variant of `ssrForm` for action-bound `<form>` elements containing `await`. */
215
+ export async function ssrFormAsync(action: unknown, render: (action: unknown) => Promise<string>): Promise<string> {
216
+ const act = resolveActionForForm(action)
217
+ if (act === undefined)
218
+ return `${await render(action)}</form>`
219
+ const hidden = renderProtectFields(act.protect)
220
+ const fields = formFieldsOf(act)
221
+ const body = fields !== undefined ? await runWithFormFields(fields, () => render(action)) : await render(action)
222
+ return `${body}${hidden}</form>`
223
+ }
224
+
225
+ /** Emits schema-derived HTML5 constraint attributes on `<input>`, `<select>`, and `<textarea>` inside an action-bound `<form>`. */
226
+ export function ssrFormAttrs(tag: 'input' | 'select' | 'textarea', name: unknown, present: number, inputType?: unknown): string {
227
+ const fields = currentFormFields()
228
+ if (fields === undefined || typeof name !== 'string' || name === '')
229
+ return ''
230
+ const c = lookupFieldConstraint(fields, name)
231
+ if (c === undefined)
232
+ return ''
233
+
234
+ let out = ''
235
+ const explicitType = typeof inputType === 'string' ? inputType.toLowerCase() : undefined
236
+ let effectiveType: string | undefined
237
+ if (tag === 'input') {
238
+ if (explicitType === undefined && (present & 1) === 0 && c.type !== undefined) {
239
+ out += ` type="${c.type}"`
240
+ effectiveType = c.type
241
+ }
242
+ else {
243
+ effectiveType = explicitType ?? 'text'
244
+ }
245
+ }
246
+
247
+ const skipRequired = tag === 'input' && (
248
+ NON_REQUIRED_INPUT_TYPES.has(effectiveType!)
249
+ || (effectiveType === 'checkbox' && c.isArray === true)
250
+ )
251
+ if (c.required === true && (present & 2) === 0 && !skipRequired)
252
+ out += ' required'
253
+
254
+ const supportsLength = tag === 'textarea' || (tag === 'input' && TEXT_INPUT_TYPES.has(effectiveType!))
255
+ if (supportsLength) {
256
+ if (c.minLength !== undefined && (present & 4) === 0)
257
+ out += ` minlength="${c.minLength}"`
258
+ if (c.maxLength !== undefined && (present & 8) === 0)
259
+ out += ` maxlength="${c.maxLength}"`
260
+ }
261
+
262
+ if (tag === 'input') {
263
+ if (effectiveType === 'number' || effectiveType === 'range') {
264
+ if (c.min !== undefined && (present & 16) === 0)
265
+ out += ` min="${c.min}"`
266
+ if (c.max !== undefined && (present & 32) === 0)
267
+ out += ` max="${c.max}"`
268
+ if (c.step !== undefined && (present & 64) === 0)
269
+ out += ` step="${c.step}"`
270
+ }
271
+ if (TEXT_INPUT_TYPES.has(effectiveType!) && c.pattern !== undefined && (present & 128) === 0)
272
+ out += ` pattern="${escAttr(c.pattern)}"`
273
+ }
274
+
156
275
  return out
157
276
  }
158
277
 
@@ -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>
@@ -53,6 +55,7 @@ interface Page {
53
55
  click(selector: string, options: { timeout: number }): Promise<void>
54
56
  hover(selector: string, options: { timeout: number }): Promise<void>
55
57
  fill(selector: string, value: string, options: { timeout: number }): Promise<void>
58
+ keyboard: { press(key: string): Promise<void> }
56
59
  locator(selector: string): { first: () => { innerText: (options: { timeout: number }) => Promise<string> } }
57
60
  }
58
61
  interface BrowserContext {
@@ -126,6 +129,9 @@ function wrapPage(page: Page, context: BrowserContext, timeout: number, url: str
126
129
  async fill(selector, value) {
127
130
  await page.fill(selector, value, { timeout })
128
131
  },
132
+ async press(key) {
133
+ await page.keyboard.press(key)
134
+ },
129
135
  async text(selector) {
130
136
  return await page.locator(selector).first().innerText({ timeout })
131
137
  },
package/src/test/index.ts CHANGED
@@ -2,12 +2,14 @@
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-'
@@ -41,12 +43,17 @@ const ownOutDirs: string[] = []
41
43
  function ownOutDir(root: string): string {
42
44
  const cacheDir = join(root, '.prunelle-cache')
43
45
  removeDeadProcessDirs(cacheDir, TEST_DIR_PREFIX)
46
+ ensureCacheGitignore(cacheDir)
44
47
  if (ownOutDirs.length === 0) {
45
48
  process.once('exit', () => {
46
49
  for (const dir of ownOutDirs) {
47
50
  rmSync(dir, { recursive: true, force: true })
48
- if (readdirSync(dirname(dir)).length === 0)
49
- rmSync(dirname(dir), { recursive: true, force: true })
51
+ const parent = dirname(dir)
52
+ if (!existsSync(parent))
53
+ continue
54
+ const remaining = readdirSync(parent)
55
+ if (remaining.length === 0 || (remaining.length === 1 && remaining[0] === '.gitignore'))
56
+ rmSync(parent, { recursive: true, force: true })
50
57
  }
51
58
  })
52
59
  }
@@ -162,6 +169,13 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
162
169
  const fd = new FormData()
163
170
  for (const [k, v] of Object.entries(fields))
164
171
  fd.append(k, v)
172
+ if (typeof action !== 'string' && action.protect !== undefined) {
173
+ const hp = honeypotFieldName(action.protect)
174
+ if (hp !== undefined && !Object.hasOwn(fields, hp))
175
+ fd.append(hp, '')
176
+ if (action.protect.minTime !== undefined && !Object.hasOwn(fields, FORM_TIMESTAMP_FIELD))
177
+ fd.append(FORM_TIMESTAMP_FIELD, signFormTimestamp(Date.now() - Math.max(0, action.protect.minTime) - 1000))
178
+ }
165
179
  const h = new Headers(headers)
166
180
  if (!h.has('origin'))
167
181
  h.set('origin', 'http://localhost')
@@ -1,6 +1,11 @@
1
+ import { Head } from 'prunelle'
2
+
1
3
  export default function LegalNotice() {
2
4
  return (
3
5
  <section>
6
+ <Head>
7
+ <title>Legal Notice</title>
8
+ </Head>
4
9
  <h1>Legal Notice</h1>
5
10
  <p>Publisher: __APP_NAME__</p>
6
11
  </section>
@@ -8,7 +8,7 @@ export default defineConfig({
8
8
  lang: 'en',
9
9
  plugins: [
10
10
  ui({ grammar: 'editorial' }),
11
- seo({ site: 'https://example.com', titleTemplate: '%s — __APP_NAME__' }),
11
+ seo({ site: 'https://example.com', titleTemplate: '%s — __APP_NAME__', description: 'Articles & notes from __APP_NAME__', image: '/og.png' }),
12
12
  content({
13
13
  feeds: [{
14
14
  path: '/rss.xml',
@@ -1,4 +1,5 @@
1
1
  import { Badge, Card, CardBody, CardFooter, CardHeader, Cluster, Stack } from '@prunellejs/ui'
2
+ import { Head } from 'prunelle'
2
3
  import { posts } from '../posts'
3
4
 
4
5
  export const prerender = true
@@ -7,6 +8,9 @@ export default async function BlogIndex() {
7
8
  const list = posts.all()
8
9
  return (
9
10
  <Stack gap="lg">
11
+ <Head>
12
+ <title>Articles</title>
13
+ </Head>
10
14
  <h1 class="page-title">Articles</h1>
11
15
  {list.map(post => (
12
16
  <Card key={post.slug}>