prunelle 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/llms.txt +148 -0
  2. package/package.json +53 -4
  3. package/src/ambient.d.ts +6 -0
  4. package/src/attrs.ts +35 -0
  5. package/src/build/bundle.ts +613 -0
  6. package/src/build/carry.ts +57 -0
  7. package/src/build/client-entries.ts +107 -0
  8. package/src/build/client-plugin.ts +169 -0
  9. package/src/build/client-prune.ts +118 -0
  10. package/src/build/compile.ts +128 -0
  11. package/src/build/files.ts +156 -0
  12. package/src/build/first-load.ts +164 -0
  13. package/src/build/graph.ts +247 -0
  14. package/src/build/index.ts +614 -0
  15. package/src/build/is-inside.ts +12 -0
  16. package/src/build/islands.ts +641 -0
  17. package/src/build/manifest.ts +281 -0
  18. package/src/build/output.ts +84 -0
  19. package/src/build/plugin-host.ts +220 -0
  20. package/src/build/precompress.ts +139 -0
  21. package/src/build/prerender.ts +150 -0
  22. package/src/build/render-rules.ts +205 -0
  23. package/src/build/report.ts +247 -0
  24. package/src/build/resolve.ts +50 -0
  25. package/src/build/routes.ts +338 -0
  26. package/src/build/server-entry.ts +38 -0
  27. package/src/build/static.ts +163 -0
  28. package/src/build/status-pages.ts +127 -0
  29. package/src/cli/check-forms.ts +654 -0
  30. package/src/cli/check-links.ts +619 -0
  31. package/src/cli/check.ts +367 -0
  32. package/src/cli/commands.ts +265 -0
  33. package/src/cli/index.ts +70 -0
  34. package/src/cli/inspect.ts +335 -0
  35. package/src/cli/new.ts +41 -0
  36. package/src/cli/upgrade-names.ts +209 -0
  37. package/src/cli/upgrade.ts +354 -0
  38. package/src/compiler/analyze.ts +618 -0
  39. package/src/compiler/ast.ts +82 -0
  40. package/src/compiler/browser-globals.ts +127 -0
  41. package/src/compiler/compliance-rgaa.ts +502 -0
  42. package/src/compiler/compliance.ts +497 -0
  43. package/src/compiler/data-keys.ts +295 -0
  44. package/src/compiler/dom-attrs.ts +379 -0
  45. package/src/compiler/dom.ts +566 -0
  46. package/src/compiler/emit.ts +131 -0
  47. package/src/compiler/expr-context.ts +408 -0
  48. package/src/compiler/index.ts +8 -0
  49. package/src/compiler/interactivity.ts +366 -0
  50. package/src/compiler/mistakes.ts +499 -0
  51. package/src/compiler/node-env.ts +50 -0
  52. package/src/compiler/patch.ts +97 -0
  53. package/src/compiler/props.ts +460 -0
  54. package/src/compiler/scope.ts +568 -0
  55. package/src/compiler/server-only.ts +326 -0
  56. package/src/compiler/shared.ts +369 -0
  57. package/src/compiler/signal-reads.ts +242 -0
  58. package/src/compiler/slots.ts +227 -0
  59. package/src/compiler/ssr-helpers.ts +555 -0
  60. package/src/compiler/ssr-island.ts +90 -0
  61. package/src/compiler/ssr-prunelle-tags.ts +56 -0
  62. package/src/compiler/ssr.ts +491 -0
  63. package/src/context.ts +165 -0
  64. package/src/dev/child.ts +30 -0
  65. package/src/dev/index.ts +208 -0
  66. package/src/dev/modules.ts +68 -0
  67. package/src/dev/protocol.ts +21 -0
  68. package/src/dev/queue.ts +79 -0
  69. package/src/dev/reload.ts +157 -0
  70. package/src/dev/supervisor.ts +187 -0
  71. package/src/dev/watchers.ts +215 -0
  72. package/src/dom/action.ts +164 -0
  73. package/src/dom/attrs.ts +72 -0
  74. package/src/dom/claim.ts +120 -0
  75. package/src/dom/extras.ts +562 -0
  76. package/src/dom/index.ts +289 -0
  77. package/src/dom/island.ts +284 -0
  78. package/src/dom/loop.ts +450 -0
  79. package/src/dom/revive.ts +36 -0
  80. package/src/index.ts +22 -0
  81. package/src/jsx-runtime.ts +566 -0
  82. package/src/plugins/config.ts +86 -0
  83. package/src/plugins/context.ts +66 -0
  84. package/src/plugins/index.ts +14 -0
  85. package/src/plugins/load.ts +70 -0
  86. package/src/plugins/order.ts +111 -0
  87. package/src/plugins/public.ts +12 -0
  88. package/src/plugins/requires.ts +47 -0
  89. package/src/plugins/services.ts +35 -0
  90. package/src/plugins/types.ts +242 -0
  91. package/src/reactivity/graph.ts +249 -0
  92. package/src/reactivity/index.ts +533 -0
  93. package/src/reactivity/selector.ts +51 -0
  94. package/src/reactivity/store.ts +208 -0
  95. package/src/server/action-protect.ts +186 -0
  96. package/src/server/action-registry.ts +78 -0
  97. package/src/server/action.ts +498 -0
  98. package/src/server/app-entry.ts +23 -0
  99. package/src/server/assets.ts +136 -0
  100. package/src/server/compress.ts +560 -0
  101. package/src/server/consent.ts +253 -0
  102. package/src/server/cookies.ts +139 -0
  103. package/src/server/document.ts +271 -0
  104. package/src/server/env.ts +33 -0
  105. package/src/server/errors.ts +382 -0
  106. package/src/server/form-schema.ts +343 -0
  107. package/src/server/health.ts +244 -0
  108. package/src/server/http.ts +508 -0
  109. package/src/server/index.ts +687 -0
  110. package/src/server/lifecycle.ts +75 -0
  111. package/src/server/loader.ts +118 -0
  112. package/src/server/page.ts +107 -0
  113. package/src/server/param-matchers.ts +112 -0
  114. package/src/server/plugin-host.ts +256 -0
  115. package/src/server/prerendered.ts +71 -0
  116. package/src/server/public.ts +19 -0
  117. package/src/server/rate-limit.ts +133 -0
  118. package/src/server/region.ts +96 -0
  119. package/src/server/request-body.ts +27 -0
  120. package/src/server/request-path.ts +73 -0
  121. package/src/server/request-scope.ts +22 -0
  122. package/src/server/route-table.ts +82 -0
  123. package/src/server/router.ts +261 -0
  124. package/src/server/routing.ts +377 -0
  125. package/src/server/security.ts +472 -0
  126. package/src/server/serve-handlers.ts +83 -0
  127. package/src/server/served-file.ts +128 -0
  128. package/src/server/standard-schema.ts +87 -0
  129. package/src/server/start.ts +99 -0
  130. package/src/server/static-dir.ts +167 -0
  131. package/src/server/stream.ts +192 -0
  132. package/src/ssr/context.ts +350 -0
  133. package/src/ssr/index.ts +596 -0
  134. package/src/ssr/navigation.ts +96 -0
  135. package/src/ssr/region.ts +171 -0
  136. package/src/style.ts +33 -0
  137. package/src/test/browser.ts +192 -0
  138. package/src/test/index.ts +191 -0
  139. package/src/unrenderable.ts +35 -0
  140. package/templates/_shared/AGENTS.md +10 -0
  141. package/templates/_shared/CLAUDE.md +1 -0
  142. package/templates/_shared/gitignore +3 -0
  143. package/templates/_shared/public/robots.txt +2 -0
  144. package/templates/_shared/src/routes/legal.tsx +13 -0
  145. package/templates/_shared/tsconfig.json +20 -0
  146. package/templates/app/.env.example +4 -0
  147. package/templates/app/package.json +21 -0
  148. package/templates/app/prunelle.config.ts +11 -0
  149. package/templates/app/src/auth.ts +14 -0
  150. package/templates/app/src/routes/_layout.tsx +32 -0
  151. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  152. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  153. package/templates/app/src/routes/index.tsx +15 -0
  154. package/templates/app/src/routes/login.tsx +34 -0
  155. package/templates/app/src/styles/app.css +7 -0
  156. package/templates/app/tests/app.test.ts +32 -0
  157. package/templates/blog/content/posts/welcome.md +9 -0
  158. package/templates/blog/package.json +22 -0
  159. package/templates/blog/prunelle.config.ts +23 -0
  160. package/templates/blog/src/posts.ts +26 -0
  161. package/templates/blog/src/routes/_layout.tsx +20 -0
  162. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  163. package/templates/blog/src/routes/index.tsx +33 -0
  164. package/templates/blog/src/styles/app.css +10 -0
  165. package/templates/fullstack/package.json +19 -0
  166. package/templates/fullstack/prunelle.config.ts +6 -0
  167. package/templates/fullstack/src/actions/greet.ts +19 -0
  168. package/templates/fullstack/src/components/Counter.tsx +10 -0
  169. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  170. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  171. package/templates/fullstack/src/routes/api/health.ts +5 -0
  172. package/templates/fullstack/src/routes/index.tsx +13 -0
  173. package/templates/fullstack/src/styles/app.css +29 -0
  174. package/templates/fullstack/tests/app.test.ts +37 -0
  175. package/templates/minimal/package.json +19 -0
  176. package/templates/minimal/prunelle.config.ts +6 -0
  177. package/templates/minimal/src/components/Counter.tsx +10 -0
  178. package/templates/minimal/src/routes/_layout.tsx +14 -0
  179. package/templates/minimal/src/routes/index.tsx +11 -0
  180. package/templates/minimal/src/styles/app.css +22 -0
  181. package/README.md +0 -3
@@ -0,0 +1,208 @@
1
+ // Deep reactive proxy store (tree-shakable: 0 B if unused).
2
+
3
+ import type { Signal } from './index'
4
+ import { batch, isTracking, signal, untrack } from './index'
5
+
6
+ const RAW = Symbol('prunelle.store.raw')
7
+ const OWN_KEYS = Symbol('prunelle.store.keys')
8
+
9
+ // An array method that moves several entries writes each one in turn; batched, its readers see only the finished array, and untracked, an effect calling it does not subscribe to what it writes.
10
+ const batchedMutators = new Map<PropertyKey, (this: unknown[], ...args: unknown[]) => unknown>(
11
+ (['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'] as const).map((name) => {
12
+ const method = Array.prototype[name] as (...args: unknown[]) => unknown
13
+ return [name, function (this: unknown[], ...args: unknown[]) {
14
+ return batch(() => untrack(() => method.apply(this, args)))
15
+ }]
16
+ }),
17
+ )
18
+
19
+ const proxyCache = new WeakMap<object, object>()
20
+ const depsCache = new WeakMap<object, Map<PropertyKey, Signal<number>>>()
21
+
22
+ function isPlain(value: unknown): value is Record<PropertyKey, unknown> {
23
+ if (typeof value !== 'object' || value === null)
24
+ return false
25
+ if (Array.isArray(value))
26
+ return true
27
+ const proto = Object.getPrototypeOf(value)
28
+ return proto === Object.prototype || proto === null
29
+ }
30
+
31
+ // The target behind a store proxy, or the value itself.
32
+ function unwrap<T>(value: T): T {
33
+ return typeof value === 'object' && value !== null && RAW in value ? (value as Record<symbol, T>)[RAW]! : value
34
+ }
35
+
36
+ function getDep(target: object, key: PropertyKey): Signal<number> {
37
+ let map = depsCache.get(target)
38
+ if (map === undefined) {
39
+ map = new Map()
40
+ depsCache.set(target, map)
41
+ }
42
+ let dep = map.get(key)
43
+ if (dep === undefined) {
44
+ dep = signal(0)
45
+ map.set(key, dep)
46
+ }
47
+ return dep
48
+ }
49
+
50
+ function notifyKey(target: object, key: PropertyKey): void {
51
+ const dep = depsCache.get(target)?.get(key)
52
+ if (dep !== undefined)
53
+ dep.value = dep.peek() + 1
54
+ }
55
+
56
+ function deleteDep(target: object, key: PropertyKey): void {
57
+ const map = depsCache.get(target)
58
+ const dep = map?.get(key)
59
+ if (dep !== undefined) {
60
+ dep.value = dep.peek() + 1
61
+ map!.delete(key)
62
+ if (map!.size === 0)
63
+ depsCache.delete(target)
64
+ }
65
+ }
66
+
67
+ function evictTruncated(target: object, nextLen: number, prevLen: number): void {
68
+ const map = depsCache.get(target)
69
+ if (map === undefined)
70
+ return
71
+ for (const [k, dep] of map) {
72
+ if (typeof k === 'string') {
73
+ const idx = Number(k)
74
+ if ((idx >>> 0) === idx && idx >= nextLen && idx < prevLen && String(idx) === k) {
75
+ dep.value = dep.peek() + 1
76
+ map.delete(k)
77
+ }
78
+ }
79
+ }
80
+ if (map.size === 0)
81
+ depsCache.delete(target)
82
+ }
83
+
84
+ function wrap<T extends object>(target: T): T {
85
+ const existing = proxyCache.get(target)
86
+ if (existing !== undefined)
87
+ return existing as T
88
+
89
+ const proxy = new Proxy(target, {
90
+ get(obj, key, receiver) {
91
+ if (key === RAW)
92
+ return obj
93
+ const mutator = Array.isArray(obj) ? batchedMutators.get(key) : undefined
94
+ if (mutator !== undefined)
95
+ return mutator
96
+ if (isTracking()) {
97
+ getDep(obj, key).value
98
+ // A reader of an array's length is walking it (a list loop reads entries untracked), so any entry write reaches it.
99
+ if (key === 'length' && Array.isArray(obj))
100
+ getDep(obj, OWN_KEYS).value
101
+ }
102
+ const value = Reflect.get(obj, key, receiver)
103
+ return isPlain(value) ? wrap(value) : value
104
+ },
105
+ set(obj, key, value, receiver) {
106
+ const rawValue = unwrap(value)
107
+ const had = Object.prototype.hasOwnProperty.call(obj, key)
108
+ const prev = Reflect.get(obj, key, obj)
109
+ const isArr = Array.isArray(obj)
110
+ const prevLength = isArr ? obj.length : 0
111
+ const ok = Reflect.set(obj, key, rawValue, receiver)
112
+ if (!ok)
113
+ return false
114
+ const changed = !had || !Object.is(prev, rawValue)
115
+ const lenChanged = isArr && obj.length !== prevLength
116
+ if (changed || lenChanged) {
117
+ batch(() => {
118
+ if (changed) {
119
+ notifyKey(obj, key)
120
+ if (!had || isArr)
121
+ notifyKey(obj, OWN_KEYS)
122
+ }
123
+ // Writing past the end grows the array without a later `length` write that differs; truncating drops trailing elements.
124
+ if (lenChanged) {
125
+ if (key !== 'length')
126
+ notifyKey(obj, 'length')
127
+ else if (obj.length < prevLength)
128
+ evictTruncated(obj, obj.length, prevLength)
129
+ }
130
+ })
131
+ }
132
+ return true
133
+ },
134
+ deleteProperty(obj, key) {
135
+ const had = Object.prototype.hasOwnProperty.call(obj, key)
136
+ const ok = Reflect.deleteProperty(obj, key)
137
+ if (had && ok) {
138
+ batch(() => {
139
+ deleteDep(obj, key)
140
+ notifyKey(obj, OWN_KEYS)
141
+ })
142
+ }
143
+ return ok
144
+ },
145
+ has(obj, key) {
146
+ if (key === RAW)
147
+ return true
148
+ if (isTracking())
149
+ getDep(obj, key).value
150
+ return Reflect.has(obj, key)
151
+ },
152
+ ownKeys(obj) {
153
+ if (isTracking())
154
+ getDep(obj, OWN_KEYS).value
155
+ return Reflect.ownKeys(obj)
156
+ },
157
+ })
158
+
159
+ proxyCache.set(target, proxy)
160
+ return proxy
161
+ }
162
+
163
+ export function store<T extends object>(initial: T): T {
164
+ if (!isPlain(initial))
165
+ return initial
166
+ return wrap(initial)
167
+ }
168
+
169
+ export function snapshot<T>(value: T): T {
170
+ return untrack(() => cloneRaw(value, new Map()))
171
+ }
172
+
173
+ /** @internal Test helper: number of tracked dependency keys currently cached for `target`. */
174
+ export function _storeDepsSize(target: object): number {
175
+ return depsCache.get(unwrap(target))?.size ?? 0
176
+ }
177
+
178
+ function cloneRaw<T>(value: T, seen: Map<object, unknown>): T {
179
+ const raw = unwrap(value)
180
+ if (typeof raw !== 'object' || raw === null)
181
+ return raw
182
+ const cached = seen.get(raw)
183
+ if (cached !== undefined)
184
+ return cached as T
185
+ if (Array.isArray(raw)) {
186
+ const copy: unknown[] = []
187
+ copy.length = raw.length
188
+ seen.set(raw, copy)
189
+ for (let i = 0; i < raw.length; i++) {
190
+ if (i in raw)
191
+ copy[i] = cloneRaw(raw[i], seen)
192
+ }
193
+ return copy as unknown as T
194
+ }
195
+ if (isPlain(raw)) {
196
+ const copy: Record<string, unknown> = {}
197
+ seen.set(raw, copy)
198
+ for (const [k, v] of Object.entries(raw)) {
199
+ // Assigning `__proto__` would set the copy's prototype; JSON.parse makes it an own key, so it stays one.
200
+ if (k === '__proto__')
201
+ Object.defineProperty(copy, k, { value: cloneRaw(v, seen), writable: true, enumerable: true, configurable: true })
202
+ else
203
+ copy[k] = cloneRaw(v, seen)
204
+ }
205
+ return copy as T
206
+ }
207
+ return raw as T
208
+ }
@@ -0,0 +1,186 @@
1
+ // Built-in spam & abuse protection for public server actions: honeypot field + HMAC-signed render timestamp.
2
+
3
+ import type { ActionContext } from './action'
4
+ import type { RateLimit } from './rate-limit'
5
+ import { assertRateLimit } from './rate-limit'
6
+
7
+ function constantTimeEqual(a: string, b: string): boolean {
8
+ const x = new Bun.CryptoHasher('sha256').update(a).digest()
9
+ const y = new Bun.CryptoHasher('sha256').update(b).digest()
10
+ let diff = 0
11
+ for (let i = 0; i < x.length; i++)
12
+ diff |= x[i]! ^ y[i]!
13
+ return diff === 0
14
+ }
15
+
16
+ export const DEFAULT_HONEYPOT_FIELD = '_pru_hp'
17
+ export const FORM_TIMESTAMP_FIELD = '_pru_ts'
18
+ export const MAX_FORM_AGE_MS = 24 * 60 * 60 * 1000
19
+
20
+ export interface ActionProtectOptions {
21
+ /** Sliding-window rate limit for submissions to this action. */
22
+ rateLimit?: RateLimit<ActionContext> | undefined
23
+ /** Hidden trap input name (`true` uses `_pru_hp`, or pass a custom field name). Non-empty values are rejected. */
24
+ honeypot?: boolean | string | undefined
25
+ /** Minimum elapsed milliseconds between SSR render and submit; enforced with an HMAC-signed `_pru_ts` token. */
26
+ minTime?: number | undefined
27
+ }
28
+
29
+ const EPHEMERAL_SECRET_KEY = Symbol.for('pru.form.secret')
30
+ const DIGITS_RE = /^\d+$/
31
+
32
+ function formSecret(): string {
33
+ const configured = process.env.PRUNELLE_FORM_SECRET || process.env.AUTH_SECRET
34
+ if (configured)
35
+ return configured
36
+ const g = globalThis as Record<symbol, string | undefined>
37
+ let secret = g[EPHEMERAL_SECRET_KEY]
38
+ if (secret === undefined) {
39
+ const bytes = new Uint8Array(32)
40
+ crypto.getRandomValues(bytes)
41
+ secret = Buffer.from(bytes).toString('hex')
42
+ g[EPHEMERAL_SECRET_KEY] = secret
43
+ }
44
+ return secret
45
+ }
46
+
47
+ function escapeAttrValue(value: string): string {
48
+ return value.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
49
+ }
50
+
51
+ /** Returns the configured honeypot field name, or `undefined` when honeypot is disabled. */
52
+ export function honeypotFieldName(protect: ActionProtectOptions | undefined): string | undefined {
53
+ if (protect?.honeypot === true)
54
+ return DEFAULT_HONEYPOT_FIELD
55
+ if (typeof protect?.honeypot === 'string') {
56
+ const trimmed = protect.honeypot.trim()
57
+ return trimmed !== '' ? trimmed : undefined
58
+ }
59
+ return undefined
60
+ }
61
+
62
+ /** Whether `protect` requires reading the request body (honeypot or minTime). */
63
+ export function needsProtectBody(protect: ActionProtectOptions | undefined): boolean {
64
+ return honeypotFieldName(protect) !== undefined || protect?.minTime !== undefined
65
+ }
66
+
67
+ /** Validates `ActionProtectOptions` eagerly when `action()` is defined. */
68
+ export function assertActionProtect(protect: ActionProtectOptions): void {
69
+ if (protect.rateLimit !== undefined)
70
+ assertRateLimit(protect.rateLimit, 'an action')
71
+ if (protect.minTime !== undefined && (!Number.isFinite(protect.minTime) || protect.minTime < 0))
72
+ throw new Error(`prunelle: protect.minTime of an action is ${String(protect.minTime)}; give a non-negative number of milliseconds.`)
73
+ if (typeof protect.honeypot === 'string' && protect.honeypot.trim() === '')
74
+ throw new Error('prunelle: protect.honeypot of an action must be a non-empty field name.')
75
+ }
76
+
77
+ /** Creates an HMAC-SHA256 signed timestamp token (`<timestampMs>.<signatureHex>`). */
78
+ export function signFormTimestamp(timestampMs = Date.now()): string {
79
+ const ts = String(Math.trunc(timestampMs))
80
+ const sig = new Bun.CryptoHasher('sha256', formSecret()).update(ts).digest('hex')
81
+ return `${ts}.${sig}`
82
+ }
83
+
84
+ /** Verifies an HMAC-signed `_pru_ts` token against `minTimeMs` and the 24-hour expiry window. */
85
+ export function verifyFormTimestamp(
86
+ token: unknown,
87
+ minTimeMs: number,
88
+ now = Date.now(),
89
+ ): { ok: true } | { ok: false, reason: string } {
90
+ if (typeof token !== 'string')
91
+ return { ok: false, reason: 'Missing form timestamp' }
92
+ const dot = token.indexOf('.')
93
+ if (dot <= 0 || dot === token.length - 1)
94
+ return { ok: false, reason: 'Invalid form timestamp' }
95
+ const tsStr = token.slice(0, dot)
96
+ const sig = token.slice(dot + 1)
97
+ if (!DIGITS_RE.test(tsStr))
98
+ return { ok: false, reason: 'Invalid form timestamp' }
99
+ const expected = new Bun.CryptoHasher('sha256', formSecret()).update(tsStr).digest('hex')
100
+ if (!constantTimeEqual(sig, expected))
101
+ return { ok: false, reason: 'Invalid form timestamp' }
102
+ const ts = Number(tsStr)
103
+ if (!Number.isFinite(ts))
104
+ return { ok: false, reason: 'Invalid form timestamp' }
105
+ const elapsed = now - ts
106
+ if (elapsed < minTimeMs)
107
+ return { ok: false, reason: 'Form submitted too quickly' }
108
+ if (elapsed > MAX_FORM_AGE_MS)
109
+ return { ok: false, reason: 'Form submission expired' }
110
+ return { ok: true }
111
+ }
112
+
113
+ function isNonEmptyFieldValue(value: unknown): boolean {
114
+ if (Array.isArray(value))
115
+ return value.some(v => v !== '' && v != null)
116
+ return value !== '' && value != null
117
+ }
118
+
119
+ /** Returns a shallow copy of `rawBody` with internal Prunelle protection fields removed. */
120
+ export function stripProtectFields(protect: ActionProtectOptions | undefined, rawBody: unknown): unknown {
121
+ if (protect === undefined || rawBody === null || typeof rawBody !== 'object' || Array.isArray(rawBody))
122
+ return rawBody
123
+ const hpField = honeypotFieldName(protect)
124
+ const hasMinTime = protect.minTime !== undefined
125
+ if (hpField === undefined && !hasMinTime)
126
+ return rawBody
127
+ const obj = rawBody as Record<string, unknown>
128
+ const dropHp = hpField !== undefined && Object.hasOwn(obj, hpField)
129
+ const dropTs = hasMinTime && Object.hasOwn(obj, FORM_TIMESTAMP_FIELD)
130
+ if (!dropHp && !dropTs)
131
+ return rawBody
132
+ const entries: [string, unknown][] = []
133
+ for (const [k, v] of Object.entries(obj)) {
134
+ if ((dropHp && k === hpField) || (dropTs && k === FORM_TIMESTAMP_FIELD))
135
+ continue
136
+ entries.push([k, v])
137
+ }
138
+ return Object.fromEntries(entries)
139
+ }
140
+
141
+ /** Verifies honeypot and signed timestamp protections and returns the body with internal fields stripped. */
142
+ export function verifyActionProtection(
143
+ protect: ActionProtectOptions | undefined,
144
+ rawBody: unknown,
145
+ now = Date.now(),
146
+ ): { ok: true, cleanedBody: unknown } | { ok: false, error: string, cleanedBody: unknown } {
147
+ if (protect === undefined)
148
+ return { ok: true, cleanedBody: rawBody }
149
+ const hpField = honeypotFieldName(protect)
150
+ const minTime = protect.minTime
151
+ if (hpField === undefined && minTime === undefined)
152
+ return { ok: true, cleanedBody: rawBody }
153
+
154
+ const cleanedBody = stripProtectFields(protect, rawBody)
155
+ const obj = rawBody !== null && typeof rawBody === 'object' && !Array.isArray(rawBody)
156
+ ? rawBody as Record<string, unknown>
157
+ : undefined
158
+
159
+ if (hpField !== undefined && obj !== undefined && Object.hasOwn(obj, hpField)) {
160
+ if (isNonEmptyFieldValue(obj[hpField]))
161
+ return { ok: false, error: 'Submission rejected', cleanedBody }
162
+ }
163
+
164
+ if (minTime !== undefined) {
165
+ const rawTs = obj !== undefined && Object.hasOwn(obj, FORM_TIMESTAMP_FIELD) ? obj[FORM_TIMESTAMP_FIELD] : undefined
166
+ const token = Array.isArray(rawTs) ? rawTs[0] : rawTs
167
+ const tsResult = verifyFormTimestamp(token, minTime, now)
168
+ if (!tsResult.ok)
169
+ return { ok: false, error: tsResult.reason, cleanedBody }
170
+ }
171
+
172
+ return { ok: true, cleanedBody }
173
+ }
174
+
175
+ /** Renders the SSR hidden protection inputs (visually hidden honeypot + signed timestamp) for `<form action={fn}>`. */
176
+ export function renderProtectFields(protect: ActionProtectOptions | undefined): string {
177
+ if (protect === undefined)
178
+ return ''
179
+ let html = ''
180
+ const hp = honeypotFieldName(protect)
181
+ if (hp !== undefined)
182
+ html += `<input type="text" name="${escapeAttrValue(hp)}" value="" tabindex="-1" autocomplete="off" aria-hidden="true" style="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden">`
183
+ if (protect.minTime !== undefined)
184
+ html += `<input type="hidden" name="${FORM_TIMESTAMP_FIELD}" value="${signFormTimestamp()}">`
185
+ return html
186
+ }
@@ -0,0 +1,78 @@
1
+ // The app's server actions: their live URLs, the middleware each one runs behind, and invocation with its folder's `_middleware.ts` chain.
2
+
3
+ import type { ActionResult, ServerAction } from './action'
4
+ import type { Middleware, RequestContext } from './http'
5
+ import { invokeActionCore } from './action'
6
+ import { runChain } from './http'
7
+ import { runInRequest } from './request-scope'
8
+
9
+ export interface RegisteredAction {
10
+ act: ServerAction<unknown, unknown>
11
+ /** Plugin middlewares, then the `_middleware.ts` chain of the action's folder. */
12
+ middlewares: Middleware[]
13
+ }
14
+
15
+ export interface ActionRegistry {
16
+ /** Gives `act` its name and live URL and records the middlewares a request to it runs behind. */
17
+ register: (act: ServerAction<unknown, unknown>, name: string, url: string, dirMiddlewares: Middleware[], pluginMiddlewares: readonly Middleware[]) => void
18
+ byUrl: (url: string) => RegisteredAction | undefined
19
+ /** Runs an action with schema validation behind its folder's `_middleware.ts` chain, as an island call would. */
20
+ invoke: <I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext) => Promise<ActionResult<O>>
21
+ /** Runs `fn` as part of the request `ctx`, so the actions it calls run in that request. */
22
+ run: <T>(ctx: RequestContext, fn: () => T) => T
23
+ }
24
+
25
+ export function createActionRegistry(): ActionRegistry {
26
+ const handlers = new Map<string, RegisteredAction>()
27
+ const dirMiddlewaresByRef = new WeakMap<ServerAction<unknown, unknown>, Middleware[]>()
28
+
29
+ async function invoke<I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>> {
30
+ const dirMiddlewares = dirMiddlewaresByRef.get(act as unknown as ServerAction<unknown, unknown>) ?? []
31
+ if (dirMiddlewares.length === 0)
32
+ return invokeActionCore(act, input, ctx)
33
+
34
+ let actionResult: ActionResult<O> | undefined
35
+ const res = await runChain(ctx, dirMiddlewares, async () => {
36
+ actionResult = await invokeActionCore(act, input, ctx)
37
+ return new Response(null, { status: actionResult.ok ? 200 : actionResult.status })
38
+ })
39
+ if (actionResult !== undefined)
40
+ return actionResult
41
+ // A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
42
+ const ct = res.headers.get('content-type') ?? ''
43
+ if (ct.includes('application/json')) {
44
+ try {
45
+ const body = await res.clone().json() as Record<string, unknown>
46
+ return {
47
+ ok: false,
48
+ status: res.status,
49
+ error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
50
+ }
51
+ }
52
+ catch {}
53
+ }
54
+ let text = ''
55
+ try {
56
+ text = await res.clone().text()
57
+ }
58
+ catch {}
59
+ return {
60
+ ok: false,
61
+ status: res.status,
62
+ error: text || res.statusText || 'Forbidden',
63
+ }
64
+ }
65
+
66
+ const registry: ActionRegistry = {
67
+ register(act, name, url, dirMiddlewares, pluginMiddlewares) {
68
+ ;(act as { url: string }).url = url
69
+ Object.defineProperty(act, 'name', { value: name, configurable: true })
70
+ dirMiddlewaresByRef.set(act, dirMiddlewares)
71
+ handlers.set(url, { act, middlewares: [...pluginMiddlewares, ...dirMiddlewares] })
72
+ },
73
+ byUrl: url => handlers.get(url),
74
+ invoke,
75
+ run: (ctx, fn) => runInRequest({ ctx, actions: registry }, fn),
76
+ }
77
+ return registry
78
+ }