prunelle 0.1.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/llms.txt +23 -19
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +80 -36
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +91 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +654 -0
  27. package/src/cli/check-links.ts +619 -0
  28. package/src/cli/check.ts +52 -5
  29. package/src/cli/commands.ts +86 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +31 -2
  32. package/src/cli/mcp-tools.ts +480 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +261 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +20 -6
  39. package/src/compiler/cacheability.ts +592 -0
  40. package/src/compiler/compliance-rgaa.ts +502 -0
  41. package/src/compiler/compliance.ts +120 -221
  42. package/src/compiler/dev-source.ts +87 -0
  43. package/src/compiler/dom-attrs.ts +138 -65
  44. package/src/compiler/dom.ts +12 -11
  45. package/src/compiler/expr-context.ts +167 -57
  46. package/src/compiler/props.ts +87 -36
  47. package/src/compiler/scope.ts +56 -17
  48. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  49. package/src/compiler/ssr.ts +216 -84
  50. package/src/dev/error-log.ts +151 -0
  51. package/src/dev/index.ts +84 -34
  52. package/src/dev/open-editor.ts +204 -0
  53. package/src/dev/protocol.ts +1 -0
  54. package/src/dev/reload.ts +5 -3
  55. package/src/dev/supervisor.ts +42 -25
  56. package/src/dev/watchers.ts +47 -11
  57. package/src/dom/action.ts +4 -1
  58. package/src/dom/attrs.ts +15 -3
  59. package/src/dom/extras.ts +2 -2
  60. package/src/dom/island.ts +11 -10
  61. package/src/plugins/config.ts +4 -4
  62. package/src/plugins/index.ts +2 -2
  63. package/src/plugins/public.ts +5 -2
  64. package/src/plugins/services.ts +62 -0
  65. package/src/plugins/types.ts +32 -0
  66. package/src/server/action-protect.ts +198 -0
  67. package/src/server/action-registry.ts +1 -1
  68. package/src/server/action.ts +82 -27
  69. package/src/server/assets.ts +34 -2
  70. package/src/server/compress.ts +91 -9
  71. package/src/server/errors.ts +303 -65
  72. package/src/server/form-schema.ts +343 -0
  73. package/src/server/health.ts +244 -0
  74. package/src/server/http.ts +128 -31
  75. package/src/server/index.ts +230 -260
  76. package/src/server/loader.ts +5 -0
  77. package/src/server/param-matchers.ts +112 -0
  78. package/src/server/plugin-host.ts +123 -88
  79. package/src/server/public.ts +3 -3
  80. package/src/server/rate-limit.ts +58 -35
  81. package/src/server/request-body.ts +1 -1
  82. package/src/server/route-cache.ts +423 -0
  83. package/src/server/route-table.ts +339 -8
  84. package/src/server/router.ts +125 -40
  85. package/src/server/routing.ts +196 -63
  86. package/src/server/security.ts +208 -32
  87. package/src/server/serve-handlers.ts +21 -7
  88. package/src/server/start.ts +60 -16
  89. package/src/server/static-dir.ts +61 -8
  90. package/src/server/stream.ts +41 -22
  91. package/src/ssr/context.ts +85 -3
  92. package/src/ssr/index.ts +120 -1
  93. package/src/ssr/region.ts +31 -19
  94. package/src/test/browser.ts +6 -0
  95. package/src/test/index.ts +17 -3
  96. package/src/ts-plugin/diagnostics.ts +378 -0
  97. package/src/ts-plugin/fixes.ts +364 -0
  98. package/src/ts-plugin/index.ts +194 -0
  99. package/templates/_shared/AGENTS.md +2 -2
  100. package/templates/_shared/mcp.json +11 -0
  101. package/templates/_shared/src/routes/legal.tsx +5 -0
  102. package/templates/_shared/tsconfig.json +5 -0
  103. package/templates/blog/prunelle.config.ts +1 -1
  104. package/templates/blog/src/routes/index.tsx +4 -0
  105. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,654 @@
1
+ // Static form validation for `prunelle check` and `prunelle build`:
2
+ // - Checks `<form action={fn}>` fields against the action's Standard Schema JSON Schema (unknown fields, missing required fields, `<select>` enum options)
3
+ // - Warns once per schema vendor lacking JSON Schema output
4
+ // - Warns on unguarded public form actions without `protect` / `rateLimit` / `_middleware.ts`
5
+
6
+ import type { JSXAttribute, JSXElement, Node, Program } from 'oxc-parser'
7
+ import type { ModuleGraph } from '../build/graph'
8
+ import type { ModuleAnalysis } from '../compiler/analyze'
9
+ import type { ServerAction } from '../server/action'
10
+ import { readFileSync } from 'node:fs'
11
+ import { basename, dirname } from 'node:path'
12
+ import { isInNodeModules, isTsFile, relPosix } from '../build/files'
13
+ import { isInside } from '../build/is-inside'
14
+ import { resolvePrunelleSpecifier } from '../build/resolve'
15
+ import { walk } from '../compiler/ast'
16
+ import { calleeName, formatDiagnostic, formatLoc, isComponentTag, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
17
+ import { staticLiteralOrTemplate, staticOptionText } from '../compiler/ssr-helpers'
18
+ import { closestName } from '../plugins/config'
19
+ import { isServerAction } from '../server/action'
20
+ import { FORM_TIMESTAMP_FIELD, honeypotFieldName } from '../server/action-protect'
21
+ import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
22
+
23
+ export interface FormCheckInput {
24
+ root: string
25
+ routesDir: string
26
+ routeFiles: readonly string[]
27
+ graph: ModuleGraph
28
+ /** Optional pre-read source map (falls back to `graph.source(file)`). */
29
+ sources?: ReadonlyMap<string, string> | undefined
30
+ }
31
+
32
+ export interface FormCheckResult {
33
+ errors: string[]
34
+ warnings: string[]
35
+ }
36
+
37
+ interface ActionRef {
38
+ file: string
39
+ exportName: string
40
+ }
41
+
42
+ interface SelectOptionInfo {
43
+ value: string
44
+ offset: number
45
+ }
46
+
47
+ interface CollectedField {
48
+ name: string
49
+ tag: string
50
+ offset: number
51
+ options?: SelectOptionInfo[] | undefined
52
+ }
53
+
54
+ interface CollectedForm {
55
+ action: ActionRef
56
+ offset: number
57
+ fields: CollectedField[]
58
+ hasOpaqueFields: boolean
59
+ }
60
+
61
+ const PRUNELLE_SPECIFIER_RE = /^prunelle(?:\/|$)/
62
+
63
+ async function tryDirectImport(file: string, hash: string): Promise<Record<string, unknown> | undefined> {
64
+ try {
65
+ return await import(`${file}?pru-form=${hash}`) as Record<string, unknown>
66
+ }
67
+ catch {
68
+ return undefined
69
+ }
70
+ }
71
+
72
+ async function loadActionModule(file: string, cache: Map<string, Record<string, unknown> | null>): Promise<Record<string, unknown> | undefined> {
73
+ if (cache.has(file))
74
+ return cache.get(file) ?? undefined
75
+
76
+ let hash = '0'
77
+ try {
78
+ hash = Bun.hash(readFileSync(file)).toString(36)
79
+ }
80
+ catch {
81
+ cache.set(file, null)
82
+ return undefined
83
+ }
84
+
85
+ const direct = await tryDirectImport(file, hash)
86
+ if (direct !== undefined) {
87
+ cache.set(file, direct)
88
+ return direct
89
+ }
90
+
91
+ try {
92
+ const built = await Bun.build({
93
+ entrypoints: [file],
94
+ target: 'bun',
95
+ plugins: [{
96
+ name: 'prunelle-form-check-resolve',
97
+ setup(b) {
98
+ b.onResolve({ filter: PRUNELLE_SPECIFIER_RE }, (args) => {
99
+ const resolved = resolvePrunelleSpecifier(args.path)
100
+ return resolved !== undefined ? { path: resolved, external: true } : undefined
101
+ })
102
+ },
103
+ }],
104
+ })
105
+ const output = built.outputs[0]
106
+ if (!built.success || output === undefined) {
107
+ cache.set(file, null)
108
+ return undefined
109
+ }
110
+ const js = await output.text()
111
+ const mod = await import(`data:text/javascript;base64,${Buffer.from(js, 'utf8').toString('base64')}`) as Record<string, unknown>
112
+ cache.set(file, mod)
113
+ return mod
114
+ }
115
+ catch {
116
+ cache.set(file, null)
117
+ return undefined
118
+ }
119
+ }
120
+
121
+ function isExportedAction(graph: ModuleGraph, target: ActionRef): boolean {
122
+ const analysis = graph.analyses.get(target.file)
123
+ return analysis !== undefined && analysis.exportedActions.includes(target.exportName)
124
+ }
125
+
126
+ interface ModuleActionResolver {
127
+ resolveExpr(node: Node): ActionRef | undefined
128
+ }
129
+
130
+ function safeExportTarget(graph: ModuleGraph, file: string, exportName: string, depth = 0): ActionRef {
131
+ const analysis = depth > 16 ? undefined : graph.analyses.get(file)
132
+ if (analysis === undefined)
133
+ return { file, exportName }
134
+ const direct = analysis.reexports.find(r => r.exported === exportName)
135
+ if (direct !== undefined) {
136
+ const next = graph.resolve(file, direct.source)
137
+ if (next !== undefined && isTsFile(next))
138
+ return safeExportTarget(graph, next, direct.local, depth + 1)
139
+ }
140
+ if (analysis.exportedNames.includes(exportName) || exportName === 'default')
141
+ return { file, exportName }
142
+ for (const re of analysis.reexports) {
143
+ if (re.exported !== '*')
144
+ continue
145
+ const next = graph.resolve(file, re.source)
146
+ if (next !== undefined && isTsFile(next) && graph.analyses.has(next)) {
147
+ const resolved = safeExportTarget(graph, next, exportName, depth + 1)
148
+ if (graph.analyses.get(resolved.file)?.exportedNames.includes(resolved.exportName))
149
+ return resolved
150
+ }
151
+ }
152
+ return { file, exportName }
153
+ }
154
+
155
+ function createActionResolver(file: string, analysis: ModuleAnalysis, graph: ModuleGraph): ModuleActionResolver {
156
+ const directActions = new Map<string, ActionRef>()
157
+ const namespaceImports = new Map<string, string>()
158
+ const useActionVars = new Map<string, ActionRef>()
159
+ const useActionCallees = new Set<string>()
160
+ const prunelleNamespaces = new Set<string>()
161
+
162
+ for (const name of analysis.exportedActions)
163
+ directActions.set(name, { file, exportName: name })
164
+
165
+ for (const imp of analysis.imports) {
166
+ if (imp.source === 'prunelle') {
167
+ for (const spec of imp.specifiers) {
168
+ if (spec.imported === 'useAction')
169
+ useActionCallees.add(spec.local)
170
+ else if (spec.imported === '*')
171
+ prunelleNamespaces.add(spec.local)
172
+ }
173
+ continue
174
+ }
175
+ const target = graph.resolve(file, imp.source)
176
+ if (target === undefined || !isTsFile(target) || !graph.analyses.has(target))
177
+ continue
178
+ for (const spec of imp.specifiers) {
179
+ if (spec.imported === '*') {
180
+ namespaceImports.set(spec.local, target)
181
+ continue
182
+ }
183
+ const resolved = safeExportTarget(graph, target, spec.imported)
184
+ if (isExportedAction(graph, resolved))
185
+ directActions.set(spec.local, resolved)
186
+ }
187
+ }
188
+
189
+ const resolveBase = (node: Node): ActionRef | undefined => {
190
+ const inner = unwrapTsExpr(node)
191
+ if (inner.type === 'Identifier')
192
+ return directActions.get(inner.name)
193
+ if (inner.type === 'MemberExpression' && !inner.computed && inner.object.type === 'Identifier' && inner.property.type === 'Identifier') {
194
+ if (inner.property.name === 'action' && useActionVars.has(inner.object.name))
195
+ return useActionVars.get(inner.object.name)
196
+ const nsFile = namespaceImports.get(inner.object.name)
197
+ if (nsFile !== undefined) {
198
+ const resolved = safeExportTarget(graph, nsFile, inner.property.name)
199
+ if (isExportedAction(graph, resolved))
200
+ return resolved
201
+ }
202
+ }
203
+ return undefined
204
+ }
205
+
206
+ const isUseActionCall = (node: Node): boolean => {
207
+ if (node.type !== 'CallExpression')
208
+ return false
209
+ const name = calleeName(node.callee)
210
+ return useActionCallees.has(name) || (name.endsWith('.useAction') && prunelleNamespaces.has(name.slice(0, -'.useAction'.length)))
211
+ }
212
+
213
+ walk(analysis.program, (node) => {
214
+ if (node.type !== 'VariableDeclarator' || node.init === null)
215
+ return
216
+ const init = unwrapTsExpr(node.init)
217
+ if (isUseActionCall(init) && init.type === 'CallExpression' && init.arguments.length >= 1) {
218
+ const arg = init.arguments[0]
219
+ if (arg === undefined || arg.type === 'SpreadElement')
220
+ return
221
+ const target = resolveBase(arg)
222
+ if (target === undefined)
223
+ return
224
+ if (node.id.type === 'Identifier') {
225
+ useActionVars.set(node.id.name, target)
226
+ }
227
+ else if (node.id.type === 'ObjectPattern') {
228
+ for (const prop of node.id.properties) {
229
+ if (prop.type === 'Property' && !prop.computed && prop.key.type === 'Identifier' && prop.key.name === 'action' && prop.value.type === 'Identifier')
230
+ directActions.set(prop.value.name, target)
231
+ }
232
+ }
233
+ return
234
+ }
235
+ if (node.id.type === 'Identifier') {
236
+ const ref = resolveBase(init)
237
+ if (ref !== undefined)
238
+ directActions.set(node.id.name, ref)
239
+ }
240
+ })
241
+
242
+ return { resolveExpr: resolveBase }
243
+ }
244
+
245
+ function findAttr(attrs: readonly JSXElement['openingElement']['attributes'][number][], name: string): JSXAttribute | undefined {
246
+ for (const attr of attrs) {
247
+ if (attr.type === 'JSXAttribute' && jsxTagName(attr.name).toLowerCase() === name)
248
+ return attr
249
+ }
250
+ return undefined
251
+ }
252
+
253
+ function resolveStaticStringAttr(attr: JSXAttribute | undefined, propBindings: ReadonlyMap<string, string>): { known: true, value: string } | { known: false } {
254
+ if (attr === undefined || attr.value === null)
255
+ return { known: false }
256
+ if (attr.value.type === 'Literal' && typeof attr.value.value === 'string')
257
+ return { known: true, value: attr.value.value }
258
+ if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
259
+ const expr = unwrapTsExpr(attr.value.expression)
260
+ const lit = staticLiteralOrTemplate(expr)
261
+ if (lit.ok && typeof lit.value === 'string')
262
+ return { known: true, value: lit.value }
263
+ if (expr.type === 'Identifier' && propBindings.has(expr.name))
264
+ return { known: true, value: propBindings.get(expr.name)! }
265
+ if (expr.type === 'MemberExpression' && !expr.computed && expr.object.type === 'Identifier' && expr.property.type === 'Identifier' && propBindings.has(expr.property.name))
266
+ return { known: true, value: propBindings.get(expr.property.name)! }
267
+ }
268
+ return { known: false }
269
+ }
270
+
271
+ function findLocalComponentNode(program: Program, localName: string): Node | undefined {
272
+ for (const stmt of program.body) {
273
+ if (stmt.type === 'FunctionDeclaration' && stmt.id?.name === localName)
274
+ return stmt
275
+ if (stmt.type === 'VariableDeclaration') {
276
+ for (const d of stmt.declarations) {
277
+ if (d.id.type === 'Identifier' && d.id.name === localName && d.init !== null)
278
+ return unwrapTsExpr(d.init)
279
+ }
280
+ }
281
+ if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration !== null) {
282
+ const decl = stmt.declaration
283
+ if (decl.type === 'FunctionDeclaration' && decl.id?.name === localName)
284
+ return decl
285
+ if (decl.type === 'VariableDeclaration') {
286
+ for (const d of decl.declarations) {
287
+ if (d.id.type === 'Identifier' && d.id.name === localName && d.init !== null)
288
+ return unwrapTsExpr(d.init)
289
+ }
290
+ }
291
+ }
292
+ if (stmt.type === 'ExportDefaultDeclaration' && localName === 'default')
293
+ return unwrapTsExpr(stmt.declaration)
294
+ }
295
+ return undefined
296
+ }
297
+
298
+ function resolveComponentTarget(
299
+ tag: string,
300
+ file: string,
301
+ analysis: ModuleAnalysis,
302
+ graph: ModuleGraph,
303
+ ): { file: string, node: Node, key: string } | undefined {
304
+ const local = findLocalComponentNode(analysis.program, tag)
305
+ if (local !== undefined)
306
+ return { file, node: local, key: `${file}\0${tag}` }
307
+
308
+ const dotIdx = tag.indexOf('.')
309
+ for (const imp of analysis.imports) {
310
+ const targetFile = graph.resolve(file, imp.source)
311
+ if (targetFile === undefined || !isTsFile(targetFile) || !graph.analyses.has(targetFile))
312
+ continue
313
+ for (const spec of imp.specifiers) {
314
+ let exported: string | undefined
315
+ if (dotIdx === -1 && spec.local === tag && spec.imported !== '*')
316
+ exported = spec.imported
317
+ else if (dotIdx !== -1 && spec.imported === '*' && spec.local === tag.slice(0, dotIdx))
318
+ exported = tag.slice(dotIdx + 1)
319
+ if (exported === undefined)
320
+ continue
321
+ const resolved = graph.exportTarget(targetFile, exported)
322
+ const targetAnalysis = graph.analyses.get(resolved.file)
323
+ if (targetAnalysis === undefined)
324
+ continue
325
+ const localName = targetAnalysis.exportLocals.get(resolved.exportName) ?? resolved.exportName
326
+ const fnNode = findLocalComponentNode(targetAnalysis.program, localName)
327
+ if (fnNode !== undefined)
328
+ return { file: resolved.file, node: fnNode, key: `${resolved.file}\0${localName}` }
329
+ }
330
+ }
331
+ return undefined
332
+ }
333
+
334
+ function collectSelectOptions(selectEl: JSXElement): SelectOptionInfo[] {
335
+ const options: SelectOptionInfo[] = []
336
+ walk(selectEl.children, (node) => {
337
+ if (node.type !== 'JSXElement')
338
+ return undefined
339
+ const tag = jsxTagName(node.openingElement.name)
340
+ if (tag === 'select')
341
+ return false
342
+ if (tag !== 'option')
343
+ return undefined
344
+ const valueAttr = findAttr(node.openingElement.attributes, 'value')
345
+ if (valueAttr !== undefined) {
346
+ if (valueAttr.value?.type === 'Literal' && typeof valueAttr.value.value === 'string')
347
+ options.push({ value: valueAttr.value.value, offset: valueAttr.start })
348
+ else if (valueAttr.value?.type === 'JSXExpressionContainer' && valueAttr.value.expression.type !== 'JSXEmptyExpression') {
349
+ const lit = staticLiteralOrTemplate(valueAttr.value.expression)
350
+ if (lit.ok && (typeof lit.value === 'string' || typeof lit.value === 'number'))
351
+ options.push({ value: String(lit.value), offset: valueAttr.start })
352
+ }
353
+ return false
354
+ }
355
+ const text = staticOptionText(node.children)
356
+ if (text !== undefined)
357
+ options.push({ value: text, offset: node.start })
358
+ return false
359
+ })
360
+ return options
361
+ }
362
+
363
+ function collectFormFields(formNode: JSXElement, rootFile: string, graph: ModuleGraph): { fields: CollectedField[], hasOpaqueFields: boolean } {
364
+ const fields: CollectedField[] = []
365
+ let hasOpaqueFields = false
366
+
367
+ const visitTree = (
368
+ target: Node | readonly Node[],
369
+ file: string,
370
+ propBindings: ReadonlyMap<string, string>,
371
+ visited: ReadonlySet<string>,
372
+ ): void => {
373
+ const analysis = graph.analyses.get(file)
374
+ if (analysis === undefined)
375
+ return
376
+
377
+ walk(target, (node) => {
378
+ if (node.type !== 'JSXElement')
379
+ return undefined
380
+ const tag = jsxTagName(node.openingElement.name)
381
+ if (tag === 'form')
382
+ return false
383
+
384
+ if (tag === 'input' || tag === 'select' || tag === 'textarea' || tag === 'button') {
385
+ const attrs = node.openingElement.attributes
386
+ const nameAttr = findAttr(attrs, 'name')
387
+ const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
388
+ if (tag === 'button') {
389
+ if (nameAttr === undefined)
390
+ return undefined
391
+ const typeVal = resolveStaticStringAttr(findAttr(attrs, 'type'), propBindings)
392
+ if (typeVal.known && (typeVal.value.toLowerCase() === 'button' || typeVal.value.toLowerCase() === 'reset'))
393
+ return undefined
394
+ }
395
+ if (nameAttr === undefined) {
396
+ if (hasSpread && tag !== 'button')
397
+ hasOpaqueFields = true
398
+ return undefined
399
+ }
400
+ const resolvedName = resolveStaticStringAttr(nameAttr, propBindings)
401
+ if (!resolvedName.known) {
402
+ hasOpaqueFields = true
403
+ return undefined
404
+ }
405
+ if (resolvedName.value !== '') {
406
+ fields.push({
407
+ name: resolvedName.value,
408
+ tag,
409
+ offset: nameAttr.start,
410
+ ...(tag === 'select' ? { options: collectSelectOptions(node) } : {}),
411
+ })
412
+ }
413
+ return tag === 'select' ? false : undefined
414
+ }
415
+
416
+ if (isComponentTag(tag)) {
417
+ if (node.children.length > 0)
418
+ visitTree(node.children, file, propBindings, visited)
419
+ if (resolvePrunelleTag(tag, analysis.imports) !== undefined)
420
+ return false
421
+ const resolved = resolveComponentTarget(tag, file, analysis, graph)
422
+ if (resolved === undefined) {
423
+ hasOpaqueFields = true
424
+ return false
425
+ }
426
+ if (visited.has(resolved.key))
427
+ return false
428
+ const nextBindings = new Map<string, string>()
429
+ for (const attr of node.openingElement.attributes) {
430
+ if (attr.type !== 'JSXAttribute')
431
+ continue
432
+ const val = resolveStaticStringAttr(attr, propBindings)
433
+ if (val.known)
434
+ nextBindings.set(jsxTagName(attr.name), val.value)
435
+ }
436
+ const nextVisited = new Set(visited)
437
+ nextVisited.add(resolved.key)
438
+ visitTree(resolved.node, resolved.file, nextBindings, nextVisited)
439
+ return false
440
+ }
441
+
442
+ return undefined
443
+ })
444
+ }
445
+
446
+ visitTree(formNode.children, rootFile, new Map(), new Set())
447
+ return { fields, hasOpaqueFields }
448
+ }
449
+
450
+ function collectModuleForms(file: string, analysis: ModuleAnalysis, graph: ModuleGraph): CollectedForm[] {
451
+ const resolver = createActionResolver(file, analysis, graph)
452
+ const forms: CollectedForm[] = []
453
+
454
+ walk(analysis.program, (node) => {
455
+ if (node.type !== 'JSXElement' || jsxTagName(node.openingElement.name) !== 'form')
456
+ return undefined
457
+ const actionAttr = findAttr(node.openingElement.attributes, 'action')
458
+ if (actionAttr?.value?.type !== 'JSXExpressionContainer' || actionAttr.value.expression.type === 'JSXEmptyExpression')
459
+ return undefined
460
+ const actionRef = resolver.resolveExpr(actionAttr.value.expression)
461
+ if (actionRef === undefined)
462
+ return undefined
463
+ const { fields, hasOpaqueFields } = collectFormFields(node, file, graph)
464
+ forms.push({ action: actionRef, offset: node.start, fields, hasOpaqueFields })
465
+ return undefined
466
+ })
467
+
468
+ return forms
469
+ }
470
+
471
+ function buildMiddlewareLookup(routesDir: string, routeFiles: readonly string[], graph: ModuleGraph) {
472
+ const middlewareDirs = new Set<string>()
473
+ const pageRouteSet = new Set<string>()
474
+ for (const file of routeFiles) {
475
+ if (basename(file) === '_middleware.ts') {
476
+ middlewareDirs.add(dirname(file))
477
+ }
478
+ else if (!basename(file).startsWith('_') && graph.analyses.get(file)?.exportedNames.includes('default')) {
479
+ pageRouteSet.add(file)
480
+ }
481
+ }
482
+
483
+ const hasAncestorMiddleware = (file: string): boolean => {
484
+ if (!isInside(routesDir, file))
485
+ return false
486
+ let dir = dirname(file)
487
+ while (true) {
488
+ if (middlewareDirs.has(dir))
489
+ return true
490
+ if (dir === routesDir)
491
+ return false
492
+ const parent = dirname(dir)
493
+ if (parent === dir || !isInside(routesDir, parent, { orSame: true }))
494
+ return false
495
+ dir = parent
496
+ }
497
+ }
498
+
499
+ const importers = new Map<string, Set<string>>()
500
+ for (const file of graph.analyses.keys()) {
501
+ for (const dep of graph.localDeps(file)) {
502
+ let set = importers.get(dep)
503
+ if (set === undefined) {
504
+ set = new Set()
505
+ importers.set(dep, set)
506
+ }
507
+ set.add(file)
508
+ }
509
+ }
510
+
511
+ const isOnPublicPage = (file: string): boolean => {
512
+ const seen = new Set<string>([file])
513
+ const queue = [file]
514
+ for (let i = 0; i < queue.length; i++) {
515
+ const cur = queue[i]!
516
+ if (pageRouteSet.has(cur) && !hasAncestorMiddleware(cur))
517
+ return true
518
+ for (const parent of importers.get(cur) ?? []) {
519
+ if (!seen.has(parent)) {
520
+ seen.add(parent)
521
+ queue.push(parent)
522
+ }
523
+ }
524
+ }
525
+ return false
526
+ }
527
+
528
+ return { hasAncestorMiddleware, isOnPublicPage }
529
+ }
530
+
531
+ function checkFormAgainstAction(
532
+ form: CollectedForm,
533
+ act: ServerAction<unknown, unknown>,
534
+ locAt: (offset: number) => string,
535
+ warnedVendors: Set<string>,
536
+ errors: string[],
537
+ warnings: string[],
538
+ ): void {
539
+ const { exportName } = form.action
540
+ if (act.schema === undefined)
541
+ return
542
+
543
+ const extracted = extractFormSchema(act.schema)
544
+ if (!extracted.ok) {
545
+ if (!warnedVendors.has(extracted.vendor)) {
546
+ warnedVendors.add(extracted.vendor)
547
+ warnings.push(formatDiagnostic(
548
+ locAt(form.offset),
549
+ `[form/schema-unsupported] Action "${exportName}" uses a "${extracted.vendor}" schema that has no JSON Schema output; form field checks skipped.`,
550
+ 'warning',
551
+ ))
552
+ }
553
+ return
554
+ }
555
+
556
+ const hpField = honeypotFieldName(act.protect)
557
+ const knownFields = [...extracted.fields.keys()]
558
+ const checkUnknown = extracted.fields.size > 0 || extracted.jsonSchema.additionalProperties === false
559
+ const sentFields = new Set<string>()
560
+
561
+ for (const field of form.fields) {
562
+ if (field.name === FORM_TIMESTAMP_FIELD || (hpField !== undefined && field.name === hpField))
563
+ continue
564
+ const normalized = field.name.endsWith('[]') ? field.name.slice(0, -2) : field.name
565
+ sentFields.add(field.name)
566
+ sentFields.add(normalized)
567
+
568
+ const constraint = lookupFieldConstraint(extracted.fields, field.name)
569
+ if (constraint === undefined && checkUnknown) {
570
+ const near = closestName(normalized, knownFields)
571
+ const hint = near !== undefined
572
+ ? `did you mean "${near}"?`
573
+ : knownFields.length > 0 ? `known fields: ${knownFields.join(', ')}.` : 'the schema accepts no fields.'
574
+ errors.push(formatDiagnostic(
575
+ locAt(field.offset),
576
+ `[form/unknown-field] Form field "${field.name}" does not exist on action "${exportName}"'s schema: ${hint}`,
577
+ 'error',
578
+ ))
579
+ continue
580
+ }
581
+
582
+ if (field.options !== undefined && constraint?.enumValues !== undefined && constraint.enumValues.length > 0) {
583
+ const allowed = new Set(constraint.enumValues)
584
+ for (const opt of field.options) {
585
+ if (opt.value === '' || allowed.has(opt.value))
586
+ continue
587
+ warnings.push(formatDiagnostic(
588
+ locAt(opt.offset),
589
+ `[form/invalid-option] <option value="${opt.value}"> on <select name="${field.name}"> is not allowed by action "${exportName}"'s schema (allowed: ${constraint.enumValues.join(', ')}).`,
590
+ 'warning',
591
+ ))
592
+ }
593
+ }
594
+ }
595
+
596
+ if (!form.hasOpaqueFields) {
597
+ const sentList = [...sentFields]
598
+ for (const reqField of extracted.required) {
599
+ if (sentFields.has(reqField))
600
+ continue
601
+ const near = closestName(reqField, sentList)
602
+ const hint = near !== undefined ? ` (found "${near}")` : ''
603
+ errors.push(formatDiagnostic(
604
+ locAt(form.offset),
605
+ `[form/missing-field] Form bound to action "${exportName}" never sends required schema field "${reqField}"${hint}.`,
606
+ 'error',
607
+ ))
608
+ }
609
+ }
610
+ }
611
+
612
+ /** Checks every `<form action={fn}>` across the app against its action's schema and public protection config. */
613
+ export async function checkAppForms(input: FormCheckInput): Promise<FormCheckResult> {
614
+ const { root, routesDir, routeFiles, graph, sources } = input
615
+ const errors: string[] = []
616
+ const warnings: string[] = []
617
+ const moduleCache = new Map<string, Record<string, unknown> | null>()
618
+ const warnedVendors = new Set<string>()
619
+ const { hasAncestorMiddleware, isOnPublicPage } = buildMiddlewareLookup(routesDir, routeFiles, graph)
620
+
621
+ const sourceOf = (file: string): string => sources?.get(file) ?? graph.source(file)
622
+
623
+ for (const [file, analysis] of graph.analyses) {
624
+ if (isInNodeModules(file) || !file.endsWith('.tsx') || !analysis.hasJsx)
625
+ continue
626
+ const forms = collectModuleForms(file, analysis, graph)
627
+ if (forms.length === 0)
628
+ continue
629
+
630
+ const rel = relPosix(root, file)
631
+ const code = sourceOf(file)
632
+ const locAt = (offset: number): string => formatLoc(rel, code, offset)
633
+ const publicPage = isOnPublicPage(file)
634
+
635
+ for (const form of forms) {
636
+ const mod = await loadActionModule(form.action.file, moduleCache)
637
+ const act = mod?.[form.action.exportName]
638
+ if (!isServerAction(act))
639
+ continue
640
+
641
+ checkFormAgainstAction(form, act, locAt, warnedVendors, errors, warnings)
642
+
643
+ if (publicPage && !hasAncestorMiddleware(form.action.file) && act.protect === undefined && act.rateLimit === undefined) {
644
+ warnings.push(formatDiagnostic(
645
+ locAt(form.offset),
646
+ `[action/unguarded-public-form] Public form action "${form.action.exportName}" has no protection: add { protect: { rateLimit, honeypot, minTime } } to action() or guard it with _middleware.ts.`,
647
+ 'warning',
648
+ ))
649
+ }
650
+ }
651
+ }
652
+
653
+ return { errors, warnings }
654
+ }