prunelle 0.1.1 → 0.7.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.
- package/LICENSE +21 -0
- package/llms.txt +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +139 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +101 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +407 -352
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +64 -20
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +188 -152
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +356 -11
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
// Extracts per-field HTML5 constraints and known field names from Standard Schema JSON Schema output.
|
|
2
|
+
|
|
3
|
+
import type { StandardSchemaV1 } from './standard-schema'
|
|
4
|
+
|
|
5
|
+
export interface FieldConstraint {
|
|
6
|
+
required?: boolean | undefined
|
|
7
|
+
type?: 'email' | 'url' | 'number' | undefined
|
|
8
|
+
minLength?: number | undefined
|
|
9
|
+
maxLength?: number | undefined
|
|
10
|
+
min?: number | undefined
|
|
11
|
+
max?: number | undefined
|
|
12
|
+
step?: number | 'any' | undefined
|
|
13
|
+
pattern?: string | undefined
|
|
14
|
+
enumValues?: readonly string[] | undefined
|
|
15
|
+
isArray?: boolean | undefined
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type ExtractedFormSchema =
|
|
19
|
+
| {
|
|
20
|
+
ok: true
|
|
21
|
+
fields: ReadonlyMap<string, FieldConstraint>
|
|
22
|
+
required: ReadonlySet<string>
|
|
23
|
+
jsonSchema: Record<string, unknown>
|
|
24
|
+
}
|
|
25
|
+
| {
|
|
26
|
+
ok: false
|
|
27
|
+
vendor: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface LegacyJsonSchemaCapable {
|
|
31
|
+
toJSONSchema?: (() => Record<string, unknown>) | undefined
|
|
32
|
+
jsonSchema?: Record<string, unknown> | undefined
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const SAFE_INT_MIN = Number.MIN_SAFE_INTEGER
|
|
36
|
+
const SAFE_INT_MAX = Number.MAX_SAFE_INTEGER
|
|
37
|
+
const schemaCache = new WeakMap<StandardSchemaV1, ExtractedFormSchema>()
|
|
38
|
+
|
|
39
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
40
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function readRawJsonSchema(schema: StandardSchemaV1): Record<string, unknown> | undefined {
|
|
44
|
+
const stdJson = schema['~standard']?.jsonSchema
|
|
45
|
+
if (stdJson !== undefined && typeof stdJson.input === 'function') {
|
|
46
|
+
for (const target of ['draft-2020-12', 'draft-07'] as const) {
|
|
47
|
+
try {
|
|
48
|
+
const out = stdJson.input({ target })
|
|
49
|
+
if (isRecord(out))
|
|
50
|
+
return out
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
continue
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const candidate = schema as unknown as LegacyJsonSchemaCapable
|
|
58
|
+
if (typeof candidate.toJSONSchema === 'function') {
|
|
59
|
+
try {
|
|
60
|
+
const out = candidate.toJSONSchema()
|
|
61
|
+
if (isRecord(out))
|
|
62
|
+
return out
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return undefined
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (isRecord(candidate.jsonSchema))
|
|
69
|
+
return candidate.jsonSchema
|
|
70
|
+
return undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function resolveRef(node: Record<string, unknown>, root: Record<string, unknown>, seen: Set<string>): Record<string, unknown> {
|
|
74
|
+
const ref = node.$ref
|
|
75
|
+
if (typeof ref !== 'string' || !ref.startsWith('#/') || seen.has(ref))
|
|
76
|
+
return node
|
|
77
|
+
seen.add(ref)
|
|
78
|
+
const segments = ref.slice(2).split('/').map(s => s.replaceAll('~1', '/').replaceAll('~0', '~'))
|
|
79
|
+
let cur: unknown = root
|
|
80
|
+
for (const seg of segments) {
|
|
81
|
+
if (!isRecord(cur) || !Object.hasOwn(cur, seg))
|
|
82
|
+
return node
|
|
83
|
+
cur = cur[seg]
|
|
84
|
+
}
|
|
85
|
+
return isRecord(cur) ? resolveRef(cur, root, seen) : node
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function isNullSchema(node: Record<string, unknown>): boolean {
|
|
89
|
+
return node.type === 'null' || (Array.isArray(node.enum) && node.enum.length === 1 && node.enum[0] === null)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function collectEnumValues(node: Record<string, unknown>): string[] | undefined {
|
|
93
|
+
if (Array.isArray(node.enum)) {
|
|
94
|
+
const vals = node.enum.filter((v): v is string | number => typeof v === 'string' || typeof v === 'number').map(String)
|
|
95
|
+
return vals.length > 0 ? vals : undefined
|
|
96
|
+
}
|
|
97
|
+
if (typeof node.const === 'string' || typeof node.const === 'number')
|
|
98
|
+
return [String(node.const)]
|
|
99
|
+
return undefined
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function branchSpecificity(branch: Record<string, unknown>): number {
|
|
103
|
+
if (branch.type === 'number' || branch.type === 'integer')
|
|
104
|
+
return 4
|
|
105
|
+
if (branch.format === 'email' || branch.format === 'idn-email' || branch.format === 'uri' || branch.format === 'url')
|
|
106
|
+
return 3
|
|
107
|
+
if (branch.enum !== undefined || branch.const !== undefined)
|
|
108
|
+
return 2
|
|
109
|
+
if (branch.type === 'string' && (branch.minLength !== undefined || branch.maxLength !== undefined || branch.pattern !== undefined))
|
|
110
|
+
return 2
|
|
111
|
+
if (branch.type === 'array' || branch.type === 'object')
|
|
112
|
+
return 2
|
|
113
|
+
return 1
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function unwrapUnion(node: Record<string, unknown>, root: Record<string, unknown>): { primary: Record<string, unknown>, unionEnums?: string[] | undefined } {
|
|
117
|
+
const rawList = Array.isArray(node.anyOf) ? node.anyOf : Array.isArray(node.oneOf) ? node.oneOf : undefined
|
|
118
|
+
if (rawList === undefined || rawList.length === 0)
|
|
119
|
+
return { primary: node }
|
|
120
|
+
|
|
121
|
+
const branches = rawList
|
|
122
|
+
.filter(isRecord)
|
|
123
|
+
.map(b => resolveRef(b, root, new Set()))
|
|
124
|
+
.filter(b => !isNullSchema(b))
|
|
125
|
+
|
|
126
|
+
if (branches.length === 0)
|
|
127
|
+
return { primary: node }
|
|
128
|
+
|
|
129
|
+
// Literal unions like `anyOf: [{ const: 'a' }, { const: 'b' }]`
|
|
130
|
+
const literalVals: string[] = []
|
|
131
|
+
let allLiterals = true
|
|
132
|
+
for (const b of branches) {
|
|
133
|
+
const vals = collectEnumValues(b)
|
|
134
|
+
if (vals === undefined) {
|
|
135
|
+
allLiterals = false
|
|
136
|
+
break
|
|
137
|
+
}
|
|
138
|
+
literalVals.push(...vals)
|
|
139
|
+
}
|
|
140
|
+
if (allLiterals && literalVals.length > 0)
|
|
141
|
+
return { primary: node, unionEnums: literalVals }
|
|
142
|
+
|
|
143
|
+
let best = branches[0]!
|
|
144
|
+
let bestScore = branchSpecificity(best)
|
|
145
|
+
for (let i = 1; i < branches.length; i++) {
|
|
146
|
+
const score = branchSpecificity(branches[i]!)
|
|
147
|
+
if (score > bestScore) {
|
|
148
|
+
best = branches[i]!
|
|
149
|
+
bestScore = score
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { primary: best }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function mergeAllOf(node: Record<string, unknown>, root: Record<string, unknown>): Record<string, unknown> {
|
|
156
|
+
const resolved = resolveRef(node, root, new Set())
|
|
157
|
+
if (!Array.isArray(resolved.allOf))
|
|
158
|
+
return resolved
|
|
159
|
+
const merged: Record<string, unknown> = { ...resolved }
|
|
160
|
+
delete merged.allOf
|
|
161
|
+
const props: Record<string, unknown> = isRecord(merged.properties) ? { ...merged.properties } : {}
|
|
162
|
+
const req = new Set<string>(Array.isArray(merged.required) ? merged.required.filter((r): r is string => typeof r === 'string') : [])
|
|
163
|
+
for (const entry of resolved.allOf) {
|
|
164
|
+
if (!isRecord(entry))
|
|
165
|
+
continue
|
|
166
|
+
const sub = mergeAllOf(entry, root)
|
|
167
|
+
if (isRecord(sub.properties)) {
|
|
168
|
+
for (const [k, v] of Object.entries(sub.properties))
|
|
169
|
+
props[k] = v
|
|
170
|
+
}
|
|
171
|
+
if (Array.isArray(sub.required)) {
|
|
172
|
+
for (const r of sub.required) {
|
|
173
|
+
if (typeof r === 'string')
|
|
174
|
+
req.add(r)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
for (const [k, v] of Object.entries(sub)) {
|
|
178
|
+
if (k !== 'properties' && k !== 'required' && merged[k] === undefined)
|
|
179
|
+
merged[k] = v
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (Object.keys(props).length > 0)
|
|
183
|
+
merged.properties = props
|
|
184
|
+
if (req.size > 0)
|
|
185
|
+
merged.required = [...req]
|
|
186
|
+
return merged
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function applyNumericConstraints(node: Record<string, unknown>, isInteger: boolean, out: FieldConstraint): void {
|
|
190
|
+
out.type = 'number'
|
|
191
|
+
if (typeof node.multipleOf === 'number' && Number.isFinite(node.multipleOf) && node.multipleOf > 0)
|
|
192
|
+
out.step = node.multipleOf
|
|
193
|
+
else
|
|
194
|
+
out.step = isInteger ? 1 : 'any'
|
|
195
|
+
if (typeof node.minimum === 'number' && Number.isFinite(node.minimum) && node.minimum > SAFE_INT_MIN)
|
|
196
|
+
out.min = node.minimum
|
|
197
|
+
else if (typeof node.exclusiveMinimum === 'number' && Number.isFinite(node.exclusiveMinimum))
|
|
198
|
+
out.min = isInteger ? node.exclusiveMinimum + 1 : node.exclusiveMinimum
|
|
199
|
+
if (typeof node.maximum === 'number' && Number.isFinite(node.maximum) && node.maximum < SAFE_INT_MAX)
|
|
200
|
+
out.max = node.maximum
|
|
201
|
+
else if (typeof node.exclusiveMaximum === 'number' && Number.isFinite(node.exclusiveMaximum))
|
|
202
|
+
out.max = isInteger ? node.exclusiveMaximum - 1 : node.exclusiveMaximum
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function extractLeafConstraint(rawNode: Record<string, unknown>, root: Record<string, unknown>, required: boolean): FieldConstraint {
|
|
206
|
+
const merged = mergeAllOf(rawNode, root)
|
|
207
|
+
const { primary, unionEnums } = unwrapUnion(merged, root)
|
|
208
|
+
const out: FieldConstraint = required ? { required: true } : {}
|
|
209
|
+
|
|
210
|
+
const type = Array.isArray(primary.type)
|
|
211
|
+
? primary.type.find(t => t !== 'null')
|
|
212
|
+
: primary.type
|
|
213
|
+
|
|
214
|
+
if (type === 'array') {
|
|
215
|
+
out.isArray = true
|
|
216
|
+
if (isRecord(primary.items)) {
|
|
217
|
+
const itemConstraint = extractLeafConstraint(primary.items, root, false)
|
|
218
|
+
if (itemConstraint.type !== undefined)
|
|
219
|
+
out.type = itemConstraint.type
|
|
220
|
+
if (itemConstraint.minLength !== undefined)
|
|
221
|
+
out.minLength = itemConstraint.minLength
|
|
222
|
+
if (itemConstraint.maxLength !== undefined)
|
|
223
|
+
out.maxLength = itemConstraint.maxLength
|
|
224
|
+
if (itemConstraint.min !== undefined)
|
|
225
|
+
out.min = itemConstraint.min
|
|
226
|
+
if (itemConstraint.max !== undefined)
|
|
227
|
+
out.max = itemConstraint.max
|
|
228
|
+
if (itemConstraint.step !== undefined)
|
|
229
|
+
out.step = itemConstraint.step
|
|
230
|
+
if (itemConstraint.pattern !== undefined)
|
|
231
|
+
out.pattern = itemConstraint.pattern
|
|
232
|
+
if (itemConstraint.enumValues !== undefined)
|
|
233
|
+
out.enumValues = itemConstraint.enumValues
|
|
234
|
+
}
|
|
235
|
+
return out
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const format = typeof primary.format === 'string' ? primary.format.toLowerCase() : undefined
|
|
239
|
+
if (format === 'email' || format === 'idn-email')
|
|
240
|
+
out.type = 'email'
|
|
241
|
+
else if (format === 'uri' || format === 'url' || format === 'iri')
|
|
242
|
+
out.type = 'url'
|
|
243
|
+
else if (type === 'integer' || type === 'number')
|
|
244
|
+
applyNumericConstraints(primary, type === 'integer', out)
|
|
245
|
+
|
|
246
|
+
if (typeof primary.minLength === 'number' && Number.isFinite(primary.minLength) && primary.minLength > 0)
|
|
247
|
+
out.minLength = Math.trunc(primary.minLength)
|
|
248
|
+
if (typeof primary.maxLength === 'number' && Number.isFinite(primary.maxLength) && primary.maxLength >= 0 && primary.maxLength < SAFE_INT_MAX)
|
|
249
|
+
out.maxLength = Math.trunc(primary.maxLength)
|
|
250
|
+
if (typeof primary.pattern === 'string' && primary.pattern.length > 0)
|
|
251
|
+
out.pattern = primary.pattern
|
|
252
|
+
|
|
253
|
+
const enums = unionEnums ?? collectEnumValues(primary)
|
|
254
|
+
if (enums !== undefined)
|
|
255
|
+
out.enumValues = enums
|
|
256
|
+
|
|
257
|
+
return out
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function walkObjectSchema(
|
|
261
|
+
node: Record<string, unknown>,
|
|
262
|
+
root: Record<string, unknown>,
|
|
263
|
+
prefix: string,
|
|
264
|
+
parentRequired: boolean,
|
|
265
|
+
fields: Map<string, FieldConstraint>,
|
|
266
|
+
requiredSet: Set<string>,
|
|
267
|
+
depth = 0,
|
|
268
|
+
): void {
|
|
269
|
+
if (depth > 8)
|
|
270
|
+
return
|
|
271
|
+
const merged = mergeAllOf(node, root)
|
|
272
|
+
const { primary } = unwrapUnion(merged, root)
|
|
273
|
+
if (!isRecord(primary.properties))
|
|
274
|
+
return
|
|
275
|
+
|
|
276
|
+
const ownRequired = new Set<string>(
|
|
277
|
+
Array.isArray(primary.required) ? primary.required.filter((r): r is string => typeof r === 'string') : [],
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
for (const [key, propSchema] of Object.entries(primary.properties)) {
|
|
281
|
+
const path = prefix !== '' ? `${prefix}.${key}` : key
|
|
282
|
+
const isReq = parentRequired && ownRequired.has(key)
|
|
283
|
+
if (!isRecord(propSchema)) {
|
|
284
|
+
fields.set(path, isReq ? { required: true } : {})
|
|
285
|
+
if (isReq)
|
|
286
|
+
requiredSet.add(path)
|
|
287
|
+
continue
|
|
288
|
+
}
|
|
289
|
+
const resolved = mergeAllOf(propSchema, root)
|
|
290
|
+
const { primary: propPrimary } = unwrapUnion(resolved, root)
|
|
291
|
+
if (isRecord(propPrimary.properties) && Object.keys(propPrimary.properties).length > 0) {
|
|
292
|
+
walkObjectSchema(propPrimary, root, path, isReq, fields, requiredSet, depth + 1)
|
|
293
|
+
continue
|
|
294
|
+
}
|
|
295
|
+
const constraint = extractLeafConstraint(propSchema, root, isReq)
|
|
296
|
+
fields.set(path, constraint)
|
|
297
|
+
if (isReq)
|
|
298
|
+
requiredSet.add(path)
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Looks up a form field constraint by HTML `name`, normalizing `name[]` array notation. */
|
|
303
|
+
export function lookupFieldConstraint(
|
|
304
|
+
fields: ReadonlyMap<string, FieldConstraint>,
|
|
305
|
+
name: string,
|
|
306
|
+
): FieldConstraint | undefined {
|
|
307
|
+
const direct = fields.get(name)
|
|
308
|
+
if (direct !== undefined)
|
|
309
|
+
return direct
|
|
310
|
+
if (name.length > 2 && name.endsWith('[]'))
|
|
311
|
+
return fields.get(name.slice(0, -2))
|
|
312
|
+
return undefined
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Extracts HTML5 form constraints and required field names from a Standard Schema (cached per schema instance). */
|
|
316
|
+
export function extractFormSchema(schema: StandardSchemaV1): ExtractedFormSchema {
|
|
317
|
+
const cached = schemaCache.get(schema)
|
|
318
|
+
if (cached !== undefined)
|
|
319
|
+
return cached
|
|
320
|
+
|
|
321
|
+
const raw = readRawJsonSchema(schema)
|
|
322
|
+
if (raw === undefined) {
|
|
323
|
+
const rawVendor: unknown = schema['~standard']?.vendor
|
|
324
|
+
const vendor = typeof rawVendor === 'string' && rawVendor.trim() !== '' ? rawVendor : 'unknown'
|
|
325
|
+
const result: ExtractedFormSchema = { ok: false, vendor }
|
|
326
|
+
schemaCache.set(schema, result)
|
|
327
|
+
return result
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const fields = new Map<string, FieldConstraint>()
|
|
331
|
+
const required = new Set<string>()
|
|
332
|
+
walkObjectSchema(raw, raw, '', true, fields, required)
|
|
333
|
+
|
|
334
|
+
const result: ExtractedFormSchema = { ok: true, fields, required, jsonSchema: raw }
|
|
335
|
+
schemaCache.set(schema, result)
|
|
336
|
+
return result
|
|
337
|
+
}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// Server observability helpers: `/_pru/health` probes, fast request IDs (`x-request-id`), and dev-only `Server-Timing`.
|
|
2
|
+
|
|
3
|
+
import type { Middleware, RequestContext } from './http'
|
|
4
|
+
import type { TrustProxy } from './security'
|
|
5
|
+
|
|
6
|
+
export type HealthCheckResult = boolean | void | { ok: boolean, message?: string | undefined }
|
|
7
|
+
export type HealthCheckFn = () => HealthCheckResult | Promise<HealthCheckResult>
|
|
8
|
+
export type HealthCheckConfig = HealthCheckFn | Record<string, HealthCheckFn>
|
|
9
|
+
|
|
10
|
+
export interface HealthCheckEntry {
|
|
11
|
+
name: string
|
|
12
|
+
fn: HealthCheckFn
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface HealthCheckOutcome {
|
|
16
|
+
ok: boolean
|
|
17
|
+
message?: string | undefined
|
|
18
|
+
error?: string | undefined
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface DevTiming {
|
|
22
|
+
middleware?: number | undefined
|
|
23
|
+
load?: number | undefined
|
|
24
|
+
render?: number | undefined
|
|
25
|
+
stream?: number | undefined
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type RequestIdResolver = (request: Request) => string
|
|
29
|
+
|
|
30
|
+
const MAX_REQUEST_ID_LEN = 128
|
|
31
|
+
|
|
32
|
+
function randomBootPrefix(): string {
|
|
33
|
+
const bytes = new Uint8Array(4)
|
|
34
|
+
crypto.getRandomValues(bytes)
|
|
35
|
+
let hex = ''
|
|
36
|
+
for (let i = 0; i < 4; i++)
|
|
37
|
+
hex += bytes[i]!.toString(16).padStart(2, '0')
|
|
38
|
+
return hex
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Validates an incoming proxy `x-request-id`: non-empty, <= 128 chars, restricted to `[A-Za-z0-9._:/-]`. */
|
|
42
|
+
export function isSafeRequestId(id: string): boolean {
|
|
43
|
+
const len = id.length
|
|
44
|
+
if (len === 0 || len > MAX_REQUEST_ID_LEN)
|
|
45
|
+
return false
|
|
46
|
+
for (let i = 0; i < len; i++) {
|
|
47
|
+
const c = id.charCodeAt(i)
|
|
48
|
+
const ok = (c >= 48 && c <= 57)
|
|
49
|
+
|| (c >= 65 && c <= 90)
|
|
50
|
+
|| (c >= 97 && c <= 122)
|
|
51
|
+
|| c === 45 || c === 46 || c === 47 || c === 58 || c === 95
|
|
52
|
+
if (!ok)
|
|
53
|
+
return false
|
|
54
|
+
}
|
|
55
|
+
return true
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const trustsProxyHeader = (trustProxy: TrustProxy): boolean =>
|
|
59
|
+
trustProxy === true || (typeof trustProxy === 'number' && trustProxy > 0)
|
|
60
|
+
|
|
61
|
+
/** Fast per-server request ID resolver: 8-char random boot prefix + base36 counter (zero `randomUUID` / regex per request). */
|
|
62
|
+
export function createRequestIdResolver(trustProxy: TrustProxy): RequestIdResolver {
|
|
63
|
+
const bootId = randomBootPrefix()
|
|
64
|
+
let seq = 0
|
|
65
|
+
if (!trustsProxyHeader(trustProxy))
|
|
66
|
+
return () => `${bootId}-${(++seq).toString(36)}`
|
|
67
|
+
return (request: Request): string => {
|
|
68
|
+
const incoming = request.headers.get('x-request-id')
|
|
69
|
+
if (incoming !== null && isSafeRequestId(incoming))
|
|
70
|
+
return incoming
|
|
71
|
+
return `${bootId}-${(++seq).toString(36)}`
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const fallbackBootId = randomBootPrefix()
|
|
76
|
+
let fallbackSeq = 0
|
|
77
|
+
|
|
78
|
+
/** Fallback request ID for direct `makeRequestContext()` calls outside a running server. */
|
|
79
|
+
export function resolveFallbackRequestId(request: Request, trustProxy: TrustProxy): string {
|
|
80
|
+
if (trustsProxyHeader(trustProxy)) {
|
|
81
|
+
const incoming = request.headers.get('x-request-id')
|
|
82
|
+
if (incoming !== null && isSafeRequestId(incoming))
|
|
83
|
+
return incoming
|
|
84
|
+
}
|
|
85
|
+
return `${fallbackBootId}-${(++fallbackSeq).toString(36)}`
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Attaches `x-request-id` in place when mutable, rebuilding only for immutable responses. */
|
|
89
|
+
export function withRequestId(res: Response, requestId: string): Response {
|
|
90
|
+
if (res.headers.has('x-request-id'))
|
|
91
|
+
return res
|
|
92
|
+
try {
|
|
93
|
+
res.headers.set('x-request-id', requestId)
|
|
94
|
+
return res
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
const headers = new Headers(res.headers)
|
|
98
|
+
headers.set('x-request-id', requestId)
|
|
99
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export const createTiming = (isDev: boolean): DevTiming | undefined => (isDev ? {} : undefined)
|
|
104
|
+
|
|
105
|
+
export const startTimer = (timing: DevTiming | undefined): number => (timing !== undefined ? performance.now() : 0)
|
|
106
|
+
|
|
107
|
+
export function endTimer(timing: DevTiming | undefined, phase: keyof DevTiming, start: number): void {
|
|
108
|
+
if (timing !== undefined)
|
|
109
|
+
timing[phase] = performance.now() - start
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Completes an in-progress `timing.render` start timestamp and formats the `Server-Timing` header value. */
|
|
113
|
+
export function finishRenderTiming(timing: DevTiming): string | undefined {
|
|
114
|
+
if (timing.render !== undefined)
|
|
115
|
+
timing.render = performance.now() - timing.render
|
|
116
|
+
return formatServerTiming(timing)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Formats dev-only `Server-Timing` phases (returns `undefined` in production or when no phases ran). */
|
|
120
|
+
export function formatServerTiming(timing: DevTiming | undefined): string | undefined {
|
|
121
|
+
if (timing === undefined)
|
|
122
|
+
return undefined
|
|
123
|
+
const parts: string[] = []
|
|
124
|
+
if (timing.middleware !== undefined)
|
|
125
|
+
parts.push(`middleware;dur=${timing.middleware.toFixed(2)}`)
|
|
126
|
+
if (timing.load !== undefined)
|
|
127
|
+
parts.push(`load;dur=${timing.load.toFixed(2)}`)
|
|
128
|
+
if (timing.render !== undefined)
|
|
129
|
+
parts.push(`render;dur=${timing.render.toFixed(2)}`)
|
|
130
|
+
if (timing.stream !== undefined)
|
|
131
|
+
parts.push(`stream;dur=${timing.stream.toFixed(2)}`)
|
|
132
|
+
return parts.length > 0 ? parts.join(', ') : undefined
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Runs a middleware chain, measuring only middleware time (excluding `last()`) when dev timing is active. */
|
|
136
|
+
export async function runTimedChain(
|
|
137
|
+
ctx: RequestContext,
|
|
138
|
+
middlewares: readonly Middleware[],
|
|
139
|
+
last: () => Response | Promise<Response>,
|
|
140
|
+
timing: DevTiming | undefined,
|
|
141
|
+
runChain: (ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>) => Promise<Response>,
|
|
142
|
+
): Promise<Response> {
|
|
143
|
+
if (timing === undefined || middlewares.length === 0)
|
|
144
|
+
return runChain(ctx, middlewares, last)
|
|
145
|
+
let innerMs = 0
|
|
146
|
+
const chainStart = performance.now()
|
|
147
|
+
const res = await runChain(ctx, middlewares, async () => {
|
|
148
|
+
const innerStart = performance.now()
|
|
149
|
+
try {
|
|
150
|
+
return await last()
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
innerMs += performance.now() - innerStart
|
|
154
|
+
}
|
|
155
|
+
})
|
|
156
|
+
timing.middleware = Math.max(0, performance.now() - chainStart - innerMs)
|
|
157
|
+
return res
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Merges app-configured and plugin-registered health checks into a flat ordered list. */
|
|
161
|
+
export function collectHealthChecks(
|
|
162
|
+
appCheck: HealthCheckConfig | undefined,
|
|
163
|
+
pluginChecks: readonly HealthCheckEntry[],
|
|
164
|
+
): HealthCheckEntry[] {
|
|
165
|
+
const entries: HealthCheckEntry[] = []
|
|
166
|
+
if (typeof appCheck === 'function') {
|
|
167
|
+
entries.push({ name: 'app', fn: appCheck })
|
|
168
|
+
}
|
|
169
|
+
else if (typeof appCheck === 'object' && appCheck !== null) {
|
|
170
|
+
for (const [name, fn] of Object.entries(appCheck)) {
|
|
171
|
+
if (typeof fn === 'function')
|
|
172
|
+
entries.push({ name, fn })
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
for (const entry of pluginChecks)
|
|
176
|
+
entries.push(entry)
|
|
177
|
+
return entries
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function runSingleHealthCheck(entry: HealthCheckEntry, timeoutMs: number, exposeErrors: boolean): Promise<[string, HealthCheckOutcome]> {
|
|
181
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
182
|
+
try {
|
|
183
|
+
const result = await Promise.race([
|
|
184
|
+
entry.fn(),
|
|
185
|
+
new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs} ms`)), timeoutMs) }),
|
|
186
|
+
])
|
|
187
|
+
if (result === true || result === undefined)
|
|
188
|
+
return [entry.name, { ok: true }]
|
|
189
|
+
if (result === false)
|
|
190
|
+
return [entry.name, { ok: false }]
|
|
191
|
+
if (result.ok)
|
|
192
|
+
return [entry.name, result.message !== undefined ? { ok: true, message: result.message } : { ok: true }]
|
|
193
|
+
return [entry.name, result.message !== undefined ? { ok: false, error: result.message } : { ok: false }]
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
// What a check threw can name a host, a table or a credential: the log keeps it, the answer says only that the check failed (outside dev).
|
|
197
|
+
console.error(`prunelle: health check "${entry.name}" failed: ${err instanceof Error ? err.message : String(err)}`)
|
|
198
|
+
return [entry.name, { ok: false, error: exposeErrors ? (err instanceof Error ? err.message : String(err)) : 'check failed' }]
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
clearTimeout(timer)
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
interface HealthSnapshot {
|
|
206
|
+
at: number
|
|
207
|
+
status: number
|
|
208
|
+
payload: string
|
|
209
|
+
length: string
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export interface HealthHandlerOptions {
|
|
213
|
+
checks: readonly HealthCheckEntry[]
|
|
214
|
+
securityRecord: Record<string, string>
|
|
215
|
+
withHsts: (res: Response, request: Request) => Response
|
|
216
|
+
resolveRequestId: RequestIdResolver
|
|
217
|
+
/** Send what a check threw back to the caller (`prunelle dev`); by default the answer only says `check failed`. */
|
|
218
|
+
exposeErrors?: boolean | undefined
|
|
219
|
+
/** How long one answer is reused (default 5000 ms), so a probe loop or a flood runs the checks once per window. */
|
|
220
|
+
cacheMs?: number | undefined
|
|
221
|
+
/** How long one check may take (default 5000 ms) before it counts as failed. */
|
|
222
|
+
timeoutMs?: number | undefined
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Handles `GET`/`HEAD` requests to `${assetPrefix}/health`, returning 200 when healthy and 503 if any check fails. */
|
|
226
|
+
export function createHealthHandler(options: HealthHandlerOptions): (request: Request, requestId?: string) => Response | Promise<Response> {
|
|
227
|
+
const { checks, securityRecord, withHsts, resolveRequestId, exposeErrors = false, cacheMs = 5000, timeoutMs = 5000 } = options
|
|
228
|
+
const baseHeaders: Record<string, string> = {
|
|
229
|
+
'content-type': 'application/json; charset=utf-8',
|
|
230
|
+
'cache-control': 'no-store',
|
|
231
|
+
...securityRecord,
|
|
232
|
+
}
|
|
233
|
+
const okPayload = '{"ok":true}'
|
|
234
|
+
const okLength = String(okPayload.length)
|
|
235
|
+
|
|
236
|
+
const jsonReply = (request: Request, status: number, payload: string, length: string, reqId: string): Response => {
|
|
237
|
+
const body = request.method === 'HEAD' ? null : payload
|
|
238
|
+
const res = new Response(body, { status, headers: { ...baseHeaders, 'content-length': length, 'x-request-id': reqId } })
|
|
239
|
+
return withHsts(res, request)
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
let cached: HealthSnapshot | undefined
|
|
243
|
+
let inflight: Promise<HealthSnapshot> | undefined
|
|
244
|
+
const evaluate = async (): Promise<HealthSnapshot> => {
|
|
245
|
+
const results = await Promise.all(checks.map(entry => runSingleHealthCheck(entry, timeoutMs, exposeErrors)))
|
|
246
|
+
const checkMap: Record<string, HealthCheckOutcome> = {}
|
|
247
|
+
let allOk = true
|
|
248
|
+
for (const [name, outcome] of results) {
|
|
249
|
+
checkMap[name] = outcome
|
|
250
|
+
if (!outcome.ok)
|
|
251
|
+
allOk = false
|
|
252
|
+
}
|
|
253
|
+
const payload = JSON.stringify({ ok: allOk, checks: checkMap })
|
|
254
|
+
cached = { at: Date.now(), status: allOk ? 200 : 503, payload, length: String(Buffer.byteLength(payload, 'utf8')) }
|
|
255
|
+
return cached
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
return (request: Request, requestId?: string): Response | Promise<Response> => {
|
|
259
|
+
const reqId = requestId ?? resolveRequestId(request)
|
|
260
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
261
|
+
const res = new Response('Method Not Allowed', {
|
|
262
|
+
status: 405,
|
|
263
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'allow': 'GET, HEAD', ...securityRecord, 'x-request-id': reqId },
|
|
264
|
+
})
|
|
265
|
+
return withHsts(res, request)
|
|
266
|
+
}
|
|
267
|
+
if (checks.length === 0)
|
|
268
|
+
return jsonReply(request, 200, okPayload, okLength, reqId)
|
|
269
|
+
|
|
270
|
+
if (cached !== undefined && Date.now() - cached.at < cacheMs)
|
|
271
|
+
return jsonReply(request, cached.status, cached.payload, cached.length, reqId)
|
|
272
|
+
inflight ??= evaluate().finally(() => { inflight = undefined })
|
|
273
|
+
return inflight.then(snap => jsonReply(request, snap.status, snap.payload, snap.length, reqId))
|
|
274
|
+
}
|
|
275
|
+
}
|