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
@@ -0,0 +1,610 @@
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 { ComplianceConfig, FormWarningRule } from '../compiler/compliance'
10
+ import type { ServerAction } from '../server/action'
11
+ import { readFileSync } from 'node:fs'
12
+ import { basename, dirname } from 'node:path'
13
+ import { isInNodeModules, isTsFile, relPosix } from '../build/files'
14
+ import { resolveExportTarget } from '../build/island-promote'
15
+ import { isInside } from '../build/is-inside'
16
+ import { resolvePrunelleSpecifier } from '../build/resolve'
17
+ import { walk } from '../compiler/ast'
18
+ import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
19
+ import { calleeName, formatDiagnostic, formatLoc, isComponentTag, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
20
+ import { staticLiteralOrTemplate, staticOptionText } from '../compiler/ssr-helpers'
21
+ import { closestName } from '../plugins/config'
22
+ import { isServerAction } from '../server/action'
23
+ import { FORM_TIMESTAMP_FIELD, honeypotFieldName } from '../server/action-protect'
24
+ import { extractFormSchema, isRecord, lookupFieldConstraint } from '../server/form-schema'
25
+
26
+ export interface FormCheckInput {
27
+ root: string
28
+ routesDir: string
29
+ routeFiles: readonly string[]
30
+ graph: ModuleGraph
31
+ /** Optional pre-read source map (falls back to `graph.source(file)`). */
32
+ sources?: ReadonlyMap<string, string> | undefined
33
+ /** `compliance.ignore` silences a form warning across the app. */
34
+ compliance?: ComplianceConfig | undefined
35
+ }
36
+
37
+ /** Emits a form warning unless `compliance.ignore` or a `prunelle-ignore` comment at that place silences it; says whether it did. */
38
+ type WarnAt = (rule: FormWarningRule, file: string, offset: number, message: string) => boolean
39
+
40
+ export interface FormCheckResult {
41
+ errors: string[]
42
+ warnings: string[]
43
+ }
44
+
45
+ interface ActionRef { file: string, exportName: string }
46
+ interface SelectOptionInfo { value: string, file: string, offset: number }
47
+ interface CollectedField { name: string, tag: string, file: string, offset: number, options?: SelectOptionInfo[] | undefined }
48
+ interface CollectedForm { action: ActionRef, file: string, offset: number, fields: CollectedField[], hasOpaqueFields: boolean }
49
+ interface PropsScope { bindings: ReadonlyMap<string, string>, propsParam?: string | undefined, destructured: ReadonlyMap<string, string> }
50
+ interface ModuleActionResolver { resolveExpr(node: Node): ActionRef | undefined }
51
+
52
+ const PRUNELLE_SPECIFIER_RE = /^prunelle(?:\/|$)/
53
+ const EMPTY_MAP: ReadonlyMap<string, string> = new Map()
54
+ const EMPTY_PROPS_SCOPE: PropsScope = { bindings: EMPTY_MAP, destructured: EMPTY_MAP }
55
+ const UI_FORM_CONTROL_TAGS = new Set(['Checkbox', 'RadioGroup', 'Switch', 'Select'])
56
+ const NON_INPUT_UI_TAGS = new Set([
57
+ 'Button', 'Icon', 'Stack', 'Cluster', 'Notice', 'Badge', 'Card', 'CardHeader', 'CardBody', 'CardFooter',
58
+ 'Divider', 'Spinner', 'Field', 'Grid', 'Sidebar', 'Split', 'Accordion', 'AccordionItem', 'Popover', 'Progress',
59
+ 'Tabs', 'Dialog', 'ControlledDialog', 'Drawer', 'ControlledDrawer', 'Menu', 'DataTable', 'CommandPalette',
60
+ 'Toaster', 'Alert', 'Tooltip', 'Separator', 'Spacer', 'Box', 'Flex', 'Container', 'Heading', 'Text', 'Avatar',
61
+ 'Skeleton', 'Image', 'Picture', 'Link',
62
+ ])
63
+
64
+ async function tryDirectImport(file: string, hash: string): Promise<Record<string, unknown> | undefined> {
65
+ try { return await import(`${file}?pru-form=${hash}`) as Record<string, unknown> }
66
+ catch { return undefined }
67
+ }
68
+
69
+ // An action module's exports, or why it would not import.
70
+ type LoadedModule = { mod: Record<string, unknown> } | { failure: string }
71
+
72
+ const messageOf = (error: unknown): string => error instanceof AggregateError && error.errors.length > 0
73
+ ? error.errors.map(messageOf).join('; ')
74
+ : error instanceof Error ? error.message : String(error)
75
+
76
+ async function loadActionModule(file: string, cache: Map<string, LoadedModule>): Promise<LoadedModule> {
77
+ const cached = cache.get(file)
78
+ if (cached !== undefined) return cached
79
+ const loaded = await importActionModule(file)
80
+ cache.set(file, loaded)
81
+ return loaded
82
+ }
83
+
84
+ async function importActionModule(file: string): Promise<LoadedModule> {
85
+ let hash = '0'
86
+ try { hash = Bun.hash(readFileSync(file)).toString(36) }
87
+ catch (error) { return { failure: messageOf(error) } }
88
+
89
+ const direct = await tryDirectImport(file, hash)
90
+ if (direct !== undefined) return { mod: direct }
91
+
92
+ try {
93
+ const built = await Bun.build({
94
+ entrypoints: [file],
95
+ target: 'bun',
96
+ plugins: [{
97
+ name: 'prunelle-form-check-resolve',
98
+ setup(b) {
99
+ b.onResolve({ filter: PRUNELLE_SPECIFIER_RE }, (args) => {
100
+ const resolved = resolvePrunelleSpecifier(args.path)
101
+ return resolved !== undefined ? { path: resolved, external: true } : undefined
102
+ })
103
+ },
104
+ }],
105
+ })
106
+ const output = built.outputs[0]
107
+ if (!built.success || output === undefined) return { failure: built.logs.map(log => log.message).join('; ') || 'it does not bundle' }
108
+ const js = await output.text()
109
+ return { mod: await import(`data:text/javascript;base64,${Buffer.from(js, 'utf8').toString('base64')}`) as Record<string, unknown> }
110
+ }
111
+ catch (error) { return { failure: messageOf(error) } }
112
+ }
113
+
114
+ function isExportedAction(graph: ModuleGraph, target: ActionRef): boolean {
115
+ const analysis = graph.analyses.get(target.file)
116
+ return analysis !== undefined && analysis.exportedActions.includes(target.exportName)
117
+ }
118
+
119
+ /** The declaring module of an export among the files the graph already analyzed. */
120
+ function safeExportTarget(graph: ModuleGraph, file: string, exportName: string): ActionRef {
121
+ return resolveExportTarget(graph, f => graph.analyses.get(f), file, exportName) ?? { file, exportName }
122
+ }
123
+
124
+ function createActionResolver(file: string, analysis: ModuleAnalysis, graph: ModuleGraph): ModuleActionResolver {
125
+ const directActions = new Map<string, ActionRef>()
126
+ const namespaceImports = new Map<string, string>()
127
+ const useActionVars = new Map<string, ActionRef>()
128
+ const useActionCallees = new Set<string>()
129
+ const prunelleNamespaces = new Set<string>()
130
+
131
+ for (const name of analysis.exportedActions)
132
+ directActions.set(name, { file, exportName: name })
133
+
134
+ for (const imp of analysis.imports) {
135
+ if (imp.source === 'prunelle') {
136
+ for (const spec of imp.specifiers) {
137
+ if (spec.imported === 'useAction') useActionCallees.add(spec.local)
138
+ else if (spec.imported === '*') prunelleNamespaces.add(spec.local)
139
+ }
140
+ continue
141
+ }
142
+ const target = graph.resolve(file, imp.source)
143
+ if (target === undefined || !isTsFile(target) || !graph.analyses.has(target)) continue
144
+ for (const spec of imp.specifiers) {
145
+ if (spec.imported === '*') { namespaceImports.set(spec.local, target); continue }
146
+ const resolved = safeExportTarget(graph, target, spec.imported)
147
+ if (isExportedAction(graph, resolved)) directActions.set(spec.local, resolved)
148
+ }
149
+ }
150
+
151
+ const resolveBase = (node: Node): ActionRef | undefined => {
152
+ const inner = unwrapTsExpr(node)
153
+ if (inner.type === 'Identifier') return directActions.get(inner.name)
154
+ if (inner.type === 'MemberExpression' && !inner.computed && inner.object.type === 'Identifier' && inner.property.type === 'Identifier') {
155
+ if (inner.property.name === 'action' && useActionVars.has(inner.object.name))
156
+ return useActionVars.get(inner.object.name)
157
+ const nsFile = namespaceImports.get(inner.object.name)
158
+ if (nsFile !== undefined) {
159
+ const resolved = safeExportTarget(graph, nsFile, inner.property.name)
160
+ if (isExportedAction(graph, resolved)) return resolved
161
+ }
162
+ }
163
+ return undefined
164
+ }
165
+
166
+ const isUseActionCall = (node: Node): boolean => {
167
+ if (node.type !== 'CallExpression') return false
168
+ const name = calleeName(node.callee)
169
+ return useActionCallees.has(name) || (name.endsWith('.useAction') && prunelleNamespaces.has(name.slice(0, -'.useAction'.length)))
170
+ }
171
+
172
+ walk(analysis.program, (node) => {
173
+ if (node.type !== 'VariableDeclarator' || node.init === null) return
174
+ const init = unwrapTsExpr(node.init)
175
+ if (isUseActionCall(init) && init.type === 'CallExpression' && init.arguments.length >= 1) {
176
+ const arg = init.arguments[0]
177
+ const target = arg !== undefined && arg.type !== 'SpreadElement' ? resolveBase(arg) : undefined
178
+ if (target === undefined) return
179
+ if (node.id.type === 'Identifier') { useActionVars.set(node.id.name, target); return }
180
+ if (node.id.type === 'ObjectPattern') {
181
+ for (const prop of node.id.properties) {
182
+ if (prop.type === 'Property' && !prop.computed && prop.key.type === 'Identifier' && prop.key.name === 'action' && prop.value.type === 'Identifier')
183
+ directActions.set(prop.value.name, target)
184
+ }
185
+ }
186
+ return
187
+ }
188
+ if (node.id.type === 'Identifier') {
189
+ const ref = resolveBase(init)
190
+ if (ref !== undefined) directActions.set(node.id.name, ref)
191
+ }
192
+ })
193
+
194
+ return { resolveExpr: resolveBase }
195
+ }
196
+
197
+ function findAttr(attrs: readonly JSXElement['openingElement']['attributes'][number][], name: string): JSXAttribute | undefined {
198
+ for (const attr of attrs)
199
+ if (attr.type === 'JSXAttribute' && jsxTagName(attr.name).toLowerCase() === name) return attr
200
+ return undefined
201
+ }
202
+
203
+ function extractPropsScope(fnNode: Node, bindings: ReadonlyMap<string, string>): PropsScope {
204
+ if (bindings.size === 0) return EMPTY_PROPS_SCOPE
205
+ const inner = unwrapTsExpr(fnNode)
206
+ if (inner.type !== 'FunctionDeclaration' && inner.type !== 'FunctionExpression' && inner.type !== 'ArrowFunctionExpression')
207
+ return EMPTY_PROPS_SCOPE
208
+ const rawFirst = inner.params[0]
209
+ if (rawFirst === undefined) return EMPTY_PROPS_SCOPE
210
+ const first = rawFirst.type === 'AssignmentPattern' ? rawFirst.left : rawFirst
211
+ if (first.type === 'Identifier') return { bindings, propsParam: first.name, destructured: EMPTY_MAP }
212
+ if (first.type !== 'ObjectPattern') return EMPTY_PROPS_SCOPE
213
+ const destructured = new Map<string, string>()
214
+ for (const prop of first.properties) {
215
+ if (prop.type !== 'Property' || prop.computed) continue
216
+ const key = prop.key.type === 'Identifier' ? prop.key.name : prop.key.type === 'Literal' && typeof prop.key.value === 'string' ? prop.key.value : undefined
217
+ const val = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value
218
+ if (key !== undefined && val.type === 'Identifier') destructured.set(val.name, key)
219
+ }
220
+ return { bindings, destructured }
221
+ }
222
+
223
+ function resolveStaticStringAttr(attr: JSXAttribute | undefined, props: PropsScope): { known: true, value: string } | { known: false } {
224
+ if (attr === undefined || attr.value === null) return { known: false }
225
+ if (attr.value.type === 'Literal' && typeof attr.value.value === 'string') return { known: true, value: attr.value.value }
226
+ if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
227
+ const expr = unwrapTsExpr(attr.value.expression)
228
+ const lit = staticLiteralOrTemplate(expr)
229
+ if (lit.ok && typeof lit.value === 'string') return { known: true, value: lit.value }
230
+ if (expr.type === 'Identifier') {
231
+ const propKey = props.destructured.get(expr.name)
232
+ if (propKey !== undefined && props.bindings.has(propKey)) return { known: true, value: props.bindings.get(propKey)! }
233
+ }
234
+ if (expr.type === 'MemberExpression' && !expr.computed && expr.object.type === 'Identifier' && props.propsParam !== undefined && expr.object.name === props.propsParam && expr.property.type === 'Identifier' && props.bindings.has(expr.property.name))
235
+ return { known: true, value: props.bindings.get(expr.property.name)! }
236
+ }
237
+ return { known: false }
238
+ }
239
+
240
+ function isKnownNonInputExternal(tag: string, attrs: readonly JSXElement['openingElement']['attributes'][number][], analysis: ModuleAnalysis): boolean {
241
+ const hasNameAttr = findAttr(attrs, 'name') !== undefined
242
+ const dotIdx = tag.indexOf('.')
243
+ for (const imp of analysis.imports) {
244
+ if (imp.source.startsWith('.') || imp.source.startsWith('/')) continue
245
+ for (const spec of imp.specifiers) {
246
+ let importedName: string | undefined
247
+ if (dotIdx === -1 && spec.local === tag && spec.imported !== '*')
248
+ importedName = spec.imported === 'default' ? tag : spec.imported
249
+ else if (dotIdx !== -1 && spec.imported === '*' && spec.local === tag.slice(0, dotIdx))
250
+ importedName = tag.slice(dotIdx + 1)
251
+ if (importedName === undefined) continue
252
+ if (imp.source === '@prunellejs/icons' || imp.source.startsWith('@prunellejs/icons/') || imp.source === '@prunellejs/images' || imp.source.startsWith('@prunellejs/images/'))
253
+ return true
254
+ if (imp.source === '@prunellejs/ui' || imp.source.startsWith('@prunellejs/ui/'))
255
+ return !UI_FORM_CONTROL_TAGS.has(importedName) && (importedName !== 'Button' || !hasNameAttr)
256
+ return (NON_INPUT_UI_TAGS.has(importedName) || NON_INPUT_UI_TAGS.has(tag)) && (importedName !== 'Button' || !hasNameAttr)
257
+ }
258
+ }
259
+ return false
260
+ }
261
+
262
+ function findLocalComponentNode(program: Program, localName: string): Node | undefined {
263
+ for (const stmt of program.body) {
264
+ if (stmt.type === 'ExportDefaultDeclaration' && localName === 'default')
265
+ return unwrapTsExpr(stmt.declaration)
266
+ const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt
267
+ if (decl?.type === 'FunctionDeclaration' && decl.id?.name === localName) return decl
268
+ if (decl?.type === 'VariableDeclaration') {
269
+ for (const d of decl.declarations)
270
+ if (d.id.type === 'Identifier' && d.id.name === localName && d.init !== null) return unwrapTsExpr(d.init)
271
+ }
272
+ }
273
+ return undefined
274
+ }
275
+
276
+ function resolveComponentTarget(
277
+ tag: string,
278
+ file: string,
279
+ analysis: ModuleAnalysis,
280
+ graph: ModuleGraph,
281
+ ): { file: string, node: Node, key: string } | undefined {
282
+ const local = findLocalComponentNode(analysis.program, tag)
283
+ if (local !== undefined) return { file, node: local, key: `${file}\0${tag}` }
284
+
285
+ const dotIdx = tag.indexOf('.')
286
+ for (const imp of analysis.imports) {
287
+ const targetFile = graph.resolve(file, imp.source)
288
+ if (targetFile === undefined || !isTsFile(targetFile) || !graph.analyses.has(targetFile)) continue
289
+ for (const spec of imp.specifiers) {
290
+ const exported = dotIdx === -1 && spec.local === tag && spec.imported !== '*'
291
+ ? spec.imported
292
+ : dotIdx !== -1 && spec.imported === '*' && spec.local === tag.slice(0, dotIdx)
293
+ ? tag.slice(dotIdx + 1)
294
+ : undefined
295
+ if (exported === undefined) continue
296
+ const resolved = graph.exportTarget(targetFile, exported)
297
+ const targetAnalysis = graph.analyses.get(resolved.file)
298
+ if (targetAnalysis === undefined) continue
299
+ const localName = targetAnalysis.exportLocals.get(resolved.exportName) ?? resolved.exportName
300
+ const fnNode = findLocalComponentNode(targetAnalysis.program, localName)
301
+ if (fnNode !== undefined) return { file: resolved.file, node: fnNode, key: `${resolved.file}\0${localName}` }
302
+ }
303
+ }
304
+ return undefined
305
+ }
306
+
307
+ function collectSelectOptions(selectEl: JSXElement, file: string): SelectOptionInfo[] {
308
+ const options: SelectOptionInfo[] = []
309
+ walk(selectEl.children, (node) => {
310
+ if (node.type !== 'JSXElement') return undefined
311
+ const tag = jsxTagName(node.openingElement.name)
312
+ if (tag === 'select') return false
313
+ if (tag !== 'option') return undefined
314
+ const valueAttr = findAttr(node.openingElement.attributes, 'value')
315
+ if (valueAttr !== undefined) {
316
+ if (valueAttr.value?.type === 'Literal' && typeof valueAttr.value.value === 'string') {
317
+ options.push({ value: valueAttr.value.value, file, offset: valueAttr.start })
318
+ }
319
+ else if (valueAttr.value?.type === 'JSXExpressionContainer' && valueAttr.value.expression.type !== 'JSXEmptyExpression') {
320
+ const lit = staticLiteralOrTemplate(valueAttr.value.expression)
321
+ if (lit.ok && (typeof lit.value === 'string' || typeof lit.value === 'number'))
322
+ options.push({ value: String(lit.value), file, offset: valueAttr.start })
323
+ }
324
+ return false
325
+ }
326
+ const text = staticOptionText(node.children)
327
+ if (text !== undefined) options.push({ value: text, file, offset: node.start })
328
+ return false
329
+ })
330
+ return options
331
+ }
332
+
333
+ function collectFormFields(formNode: JSXElement, rootFile: string, graph: ModuleGraph): { fields: CollectedField[], hasOpaqueFields: boolean } {
334
+ const fields: CollectedField[] = []
335
+ let hasOpaqueFields = false
336
+
337
+ const visitTree = (target: Node | readonly Node[], file: string, propsScope: PropsScope, visited: ReadonlySet<string>): void => {
338
+ const analysis = graph.analyses.get(file)
339
+ if (analysis === undefined) return
340
+
341
+ walk(target, (node) => {
342
+ if (node.type !== 'JSXElement') return undefined
343
+ const tag = jsxTagName(node.openingElement.name)
344
+ if (tag === 'form') return false
345
+
346
+ if (tag === 'input' || tag === 'select' || tag === 'textarea' || tag === 'button') {
347
+ const attrs = node.openingElement.attributes
348
+ const nameAttr = findAttr(attrs, 'name')
349
+ const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
350
+ if (tag === 'button') {
351
+ if (nameAttr === undefined) return undefined
352
+ const typeVal = resolveStaticStringAttr(findAttr(attrs, 'type'), propsScope)
353
+ if (typeVal.known && (typeVal.value.toLowerCase() === 'button' || typeVal.value.toLowerCase() === 'reset')) return undefined
354
+ }
355
+ if (nameAttr === undefined) {
356
+ if (hasSpread && tag !== 'button') hasOpaqueFields = true
357
+ return undefined
358
+ }
359
+ const resolvedName = resolveStaticStringAttr(nameAttr, propsScope)
360
+ if (!resolvedName.known) { hasOpaqueFields = true; return undefined }
361
+ if (resolvedName.value !== '') {
362
+ fields.push({
363
+ name: resolvedName.value,
364
+ tag,
365
+ file,
366
+ offset: nameAttr.start,
367
+ ...(tag === 'select' ? { options: collectSelectOptions(node, file) } : {}),
368
+ })
369
+ }
370
+ return tag === 'select' ? false : undefined
371
+ }
372
+
373
+ if (isComponentTag(tag)) {
374
+ if (node.children.length > 0) visitTree(node.children, file, propsScope, visited)
375
+ if (resolvePrunelleTag(tag, analysis.imports) !== undefined) return false
376
+ const resolved = resolveComponentTarget(tag, file, analysis, graph)
377
+ if (resolved === undefined) {
378
+ if (!isKnownNonInputExternal(tag, node.openingElement.attributes, analysis)) hasOpaqueFields = true
379
+ return false
380
+ }
381
+ if (visited.has(resolved.key)) return false
382
+ const nextBindings = new Map<string, string>()
383
+ for (const attr of node.openingElement.attributes) {
384
+ if (attr.type !== 'JSXAttribute') continue
385
+ const val = resolveStaticStringAttr(attr, propsScope)
386
+ if (val.known) nextBindings.set(jsxTagName(attr.name), val.value)
387
+ }
388
+ const nextVisited = new Set(visited)
389
+ nextVisited.add(resolved.key)
390
+ visitTree(resolved.node, resolved.file, extractPropsScope(resolved.node, nextBindings), nextVisited)
391
+ return false
392
+ }
393
+
394
+ return undefined
395
+ })
396
+ }
397
+
398
+ visitTree(formNode.children, rootFile, EMPTY_PROPS_SCOPE, new Set())
399
+ return { fields, hasOpaqueFields }
400
+ }
401
+
402
+ function collectModuleForms(file: string, analysis: ModuleAnalysis, graph: ModuleGraph): CollectedForm[] {
403
+ const resolver = createActionResolver(file, analysis, graph)
404
+ const forms: CollectedForm[] = []
405
+
406
+ walk(analysis.program, (node) => {
407
+ if (node.type !== 'JSXElement' || jsxTagName(node.openingElement.name) !== 'form') return undefined
408
+ const actionAttr = findAttr(node.openingElement.attributes, 'action')
409
+ if (actionAttr?.value?.type !== 'JSXExpressionContainer' || actionAttr.value.expression.type === 'JSXEmptyExpression') return undefined
410
+ const actionRef = resolver.resolveExpr(actionAttr.value.expression)
411
+ if (actionRef === undefined) return undefined
412
+ const { fields, hasOpaqueFields } = collectFormFields(node, file, graph)
413
+ forms.push({ action: actionRef, file, offset: node.start, fields, hasOpaqueFields })
414
+ return undefined
415
+ })
416
+
417
+ return forms
418
+ }
419
+
420
+ function buildMiddlewareLookup(routesDir: string, routeFiles: readonly string[], graph: ModuleGraph) {
421
+ const middlewareDirs = new Set<string>()
422
+ const layoutByDir = new Map<string, string>()
423
+ const pageRouteSet = new Set<string>()
424
+ for (const file of routeFiles) {
425
+ const base = basename(file)
426
+ if (base === '_middleware.ts' || base === '_middleware.tsx') middlewareDirs.add(dirname(file))
427
+ else if (base === '_layout.tsx') layoutByDir.set(dirname(file), file)
428
+ else if (!base.startsWith('_') && graph.analyses.get(file)?.exportedNames.includes('default')) pageRouteSet.add(file)
429
+ }
430
+
431
+ const walkAncestorDirs = (file: string, onDir: (dir: string) => boolean | void): boolean => {
432
+ if (!isInside(routesDir, file)) return false
433
+ let dir = dirname(file)
434
+ while (true) {
435
+ if (onDir(dir) === true) return true
436
+ if (dir === routesDir) return false
437
+ const parent = dirname(dir)
438
+ if (parent === dir || !isInside(routesDir, parent, { orSame: true })) return false
439
+ dir = parent
440
+ }
441
+ }
442
+
443
+ const hasAncestorMiddleware = (file: string): boolean => walkAncestorDirs(file, dir => middlewareDirs.has(dir))
444
+
445
+ const importers = new Map<string, Set<string>>()
446
+ const addImporter = (dep: string, owner: string): void => {
447
+ let set = importers.get(dep)
448
+ if (set === undefined) { set = new Set(); importers.set(dep, set) }
449
+ set.add(owner)
450
+ }
451
+ for (const file of graph.analyses.keys())
452
+ for (const dep of graph.localDeps(file)) addImporter(dep, file)
453
+ for (const page of pageRouteSet) {
454
+ walkAncestorDirs(page, (dir) => {
455
+ const layout = layoutByDir.get(dir)
456
+ if (layout !== undefined) addImporter(layout, page)
457
+ })
458
+ }
459
+
460
+ // Every page that renders `file`, through imports and through the layouts above it.
461
+ const pagesRendering = (file: string): string[] => {
462
+ const seen = new Set<string>([file])
463
+ const queue = [file]
464
+ for (let i = 0; i < queue.length; i++) {
465
+ for (const parent of importers.get(queue[i]!) ?? [])
466
+ if (!seen.has(parent)) { seen.add(parent); queue.push(parent) }
467
+ }
468
+ return queue.filter(cur => pageRouteSet.has(cur))
469
+ }
470
+
471
+ return { hasAncestorMiddleware, pagesRendering }
472
+ }
473
+
474
+ /** The `patternProperties` keys of a schema as regexes: a field name one matches is a key the schema accepts. */
475
+ function fieldPatterns(patternProperties: unknown): RegExp[] {
476
+ if (!isRecord(patternProperties))
477
+ return []
478
+ return Object.keys(patternProperties).flatMap((source) => {
479
+ try {
480
+ return [new RegExp(source, 'u')]
481
+ }
482
+ catch {
483
+ return []
484
+ }
485
+ })
486
+ }
487
+
488
+ function checkFormAgainstAction(
489
+ form: CollectedForm,
490
+ act: ServerAction<unknown, unknown>,
491
+ locAt: (file: string, offset: number) => string,
492
+ warnedVendors: Set<string>,
493
+ errors: string[],
494
+ warn: WarnAt,
495
+ ): void {
496
+ const { exportName } = form.action
497
+ if (act.schema === undefined) return
498
+
499
+ const extracted = extractFormSchema(act.schema)
500
+ if (!extracted.ok) {
501
+ if (!warnedVendors.has(extracted.vendor) && warn('form/schema-unsupported', form.file, form.offset, `Action "${exportName}" uses a "${extracted.vendor}" schema that has no JSON Schema output; form field checks skipped, and an error puts no field back in the form unless the action lists them in flashFields.`))
502
+ warnedVendors.add(extracted.vendor)
503
+ return
504
+ }
505
+
506
+ const hpField = honeypotFieldName(act.protect)
507
+ const knownFields = [...extracted.fields.keys()]
508
+ const extra = extracted.jsonSchema.additionalProperties
509
+ const checkUnknown = extra !== true && !isRecord(extra) && (extracted.fields.size > 0 || extra === false)
510
+ const patterns = fieldPatterns(extracted.jsonSchema.patternProperties)
511
+ const sentFields = new Set<string>()
512
+
513
+ for (const field of form.fields) {
514
+ if (field.name === FORM_TIMESTAMP_FIELD || (hpField !== undefined && field.name === hpField)) continue
515
+ const normalized = field.name.endsWith('[]') ? field.name.slice(0, -2) : field.name
516
+ sentFields.add(field.name)
517
+ sentFields.add(normalized)
518
+
519
+ const constraint = lookupFieldConstraint(extracted.fields, field.name)
520
+ if (constraint === undefined && checkUnknown && !patterns.some(re => re.test(normalized))) {
521
+ const near = closestName(normalized, knownFields)
522
+ const hint = near !== undefined ? `did you mean "${near}"?` : knownFields.length > 0 ? `known fields: ${knownFields.join(', ')}.` : 'the schema accepts no fields.'
523
+ errors.push(formatDiagnostic(locAt(field.file, field.offset), `[form/unknown-field] Form field "${field.name}" does not exist on action "${exportName}"'s schema: ${hint}`, 'error'))
524
+ continue
525
+ }
526
+
527
+ if (field.options !== undefined && constraint?.enumValues !== undefined && constraint.enumValues.length > 0) {
528
+ const allowed = new Set(constraint.enumValues)
529
+ for (const opt of field.options) {
530
+ if (opt.value === '' || allowed.has(opt.value)) continue
531
+ warn('form/invalid-option', opt.file, opt.offset, `<option value="${opt.value}"> on <select name="${field.name}"> is not allowed by action "${exportName}"'s schema (allowed: ${constraint.enumValues.join(', ')}).`)
532
+ }
533
+ }
534
+ }
535
+
536
+ if (!form.hasOpaqueFields) {
537
+ const sentList = [...sentFields]
538
+ for (const reqField of extracted.required) {
539
+ if (sentFields.has(reqField)) continue
540
+ const near = closestName(reqField, sentList)
541
+ const hint = near !== undefined ? ` (found "${near}")` : ''
542
+ errors.push(formatDiagnostic(locAt(form.file, form.offset), `[form/missing-field] Form bound to action "${exportName}" never sends required schema field "${reqField}"${hint}.`, 'error'))
543
+ }
544
+ }
545
+ }
546
+
547
+ /** A `protect.minTime` form on a prerendered or cached page: its signed `_pru_ts` is rendered once and handed to every visitor. */
548
+ function frozenTimestampErrors(form: CollectedForm, pages: readonly string[], graph: ModuleGraph, loc: string, relOf: (file: string) => string): string[] {
549
+ const errors: string[] = []
550
+ for (const page of pages) {
551
+ const analysis = graph.analyses.get(page)
552
+ const frozenBy = analysis?.hasPrerender === true ? 'prerender = true' : analysis?.cache !== undefined ? 'cache' : undefined
553
+ if (frozenBy === undefined) continue
554
+ errors.push(formatDiagnostic(loc, `[action/min-time-frozen] Form bound to action "${form.action.exportName}" uses protect.minTime on ${relOf(page)}, which exports ${frozenBy}: its signed timestamp is rendered once for every visitor, so bots pass minTime at once and every submit is refused 24 h after the render. Remove ${frozenBy === 'cache' ? 'the cache export' : 'prerender = true'} from ${relOf(page)}, or drop minTime and keep honeypot and rateLimit.`, 'error'))
555
+ }
556
+ return errors
557
+ }
558
+
559
+ /** Checks every `<form action={fn}>` across the app against its action's schema and public protection config. */
560
+ export async function checkAppForms(input: FormCheckInput): Promise<FormCheckResult> {
561
+ const { root, routesDir, routeFiles, graph, sources } = input
562
+ const errors: string[] = []
563
+ const warnings: string[] = []
564
+ const moduleCache = new Map<string, LoadedModule>()
565
+ const unimportable = new Set<string>()
566
+ const warnedVendors = new Set<string>()
567
+ const { hasAncestorMiddleware, pagesRendering } = buildMiddlewareLookup(routesDir, routeFiles, graph)
568
+
569
+ const sourceOf = (file: string): string => sources?.get(file) ?? graph.source(file)
570
+ const locAt = (targetFile: string, offset: number): string => formatLoc(relPosix(root, targetFile), sourceOf(targetFile), offset)
571
+ const ignoresByFile = new Map<string, ReturnType<typeof parsePrunelleIgnores>>()
572
+ const warn: WarnAt = (rule, file, offset, message) => {
573
+ if (isRuleIgnored(rule, input.compliance)) return false
574
+ let ignores = ignoresByFile.get(file)
575
+ if (ignores === undefined) { ignores = parsePrunelleIgnores(sourceOf(file)); ignoresByFile.set(file, ignores) }
576
+ if (isIgnoredAt(ignores, rule, offset)) return false
577
+ warnings.push(formatDiagnostic(locAt(file, offset), `[${rule}] ${message}`, 'warning'))
578
+ return true
579
+ }
580
+
581
+ for (const [file, analysis] of graph.analyses) {
582
+ if (isInNodeModules(file) || !file.endsWith('.tsx') || !analysis.hasJsx) continue
583
+ const forms = collectModuleForms(file, analysis, graph)
584
+ if (forms.length === 0) continue
585
+
586
+ const pages = pagesRendering(file)
587
+ const publicPage = pages.some(page => !hasAncestorMiddleware(page))
588
+ for (const form of forms) {
589
+ const loaded = await loadActionModule(form.action.file, moduleCache)
590
+ if ('failure' in loaded) {
591
+ if (!unimportable.has(form.action.file)) {
592
+ unimportable.add(form.action.file)
593
+ warn('form/unchecked', form.file, form.offset, `${relPosix(root, form.action.file)} fails to import (${loaded.failure}), so prunelle check cannot read its actions: the forms posting to them go unchecked for their fields and protection. Move what fails into the action's handler, or make it import without the running app.`)
594
+ }
595
+ continue
596
+ }
597
+ const act = loaded.mod[form.action.exportName]
598
+ if (!isServerAction(act)) continue
599
+
600
+ checkFormAgainstAction(form, act, locAt, warnedVendors, errors, warn)
601
+ if (act.protect?.minTime !== undefined)
602
+ errors.push(...frozenTimestampErrors(form, pages, graph, locAt(form.file, form.offset), page => relPosix(root, page)))
603
+
604
+ if (publicPage && !hasAncestorMiddleware(form.action.file) && act.protect === undefined && act.rateLimit === undefined)
605
+ warn('action/unguarded-public-form', form.file, form.offset, `Public form action "${form.action.exportName}" has no protection: add { protect: { rateLimit, honeypot, minTime } } to action(), guard it with _middleware.ts, or write // prunelle-ignore action/unguarded-public-form above the form when it needs none.`)
606
+ }
607
+ }
608
+
609
+ return { errors, warnings }
610
+ }
@@ -0,0 +1,25 @@
1
+ // Finds an import no file or package answers, so check names it before build stops on it.
2
+
3
+ import { dirname } from 'node:path'
4
+
5
+ const SKIPPED = /^(?:prunelle(?:\/|$)|~icons\/|virtual:)/
6
+
7
+ /** The problem with an import specifier Bun's resolver finds nothing for, or undefined when it resolves or prunelle resolves it itself. */
8
+ export function unresolvedImport(file: string, rel: string, source: string): string | undefined {
9
+ if (SKIPPED.test(source))
10
+ return undefined
11
+ try {
12
+ Bun.resolveSync(source, dirname(file))
13
+ return undefined
14
+ }
15
+ catch {
16
+ return source.startsWith('.')
17
+ ? `prunelle check: import '${source}' in ${rel} does not resolve to a file: create it, or fix the path.`
18
+ : `prunelle check: import '${source}' in ${rel} does not resolve to a package: run bun add ${packageName(source)}, or fix the name.`
19
+ }
20
+ }
21
+
22
+ function packageName(source: string): string {
23
+ const parts = source.split('/')
24
+ return source.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]!
25
+ }