@timber-js/app 0.2.0-alpha.217 → 0.2.0-alpha.219
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/agent-skill.md +5 -5
- package/dist/_chunks/{actions-CUh3cClk.js → actions-BwkmAYXq.js} +8 -1
- package/dist/_chunks/actions-BwkmAYXq.js.map +1 -0
- package/dist/_chunks/cloudflare-Byxl8FWP.js.map +1 -1
- package/dist/_chunks/dev-server-B8zsT-ee.js.map +1 -1
- package/dist/_chunks/dist-DtrJyBbw.js.map +1 -1
- package/dist/_chunks/graph-cache-CYiUS2aS.js.map +1 -1
- package/dist/_chunks/use-query-states-I3JMng6J.js.map +1 -1
- package/dist/adapters/cloudflare.js +1 -2
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/analyze/graph-command.js.map +1 -1
- package/dist/client/error-boundary.js +1 -2
- package/dist/client/form.d.ts +34 -37
- package/dist/client/form.d.ts.map +1 -1
- package/dist/client/index.d.ts +3 -3
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +40 -75
- package/dist/client/index.js.map +1 -1
- package/dist/client/{use-form-field.d.ts → use-field-state.d.ts} +10 -7
- package/dist/client/use-field-state.d.ts.map +1 -0
- package/dist/config-types.d.ts +15 -18
- package/dist/config-types.d.ts.map +1 -1
- package/dist/cookies/index.js.map +1 -1
- package/dist/index.js +29 -27
- package/dist/index.js.map +1 -1
- package/dist/plugins/build-manifest.d.ts.map +1 -1
- package/dist/plugins/shims.d.ts.map +1 -1
- package/dist/search-params/index.js.map +1 -1
- package/dist/server/action-client.d.ts +11 -172
- package/dist/server/action-client.d.ts.map +1 -1
- package/dist/server/action-handler.d.ts +0 -7
- package/dist/server/action-handler.d.ts.map +1 -1
- package/dist/server/action-schema.d.ts +126 -0
- package/dist/server/action-schema.d.ts.map +1 -0
- package/dist/server/action-types.d.ts +108 -0
- package/dist/server/action-types.d.ts.map +1 -0
- package/dist/server/form-data.d.ts +7 -0
- package/dist/server/form-data.d.ts.map +1 -1
- package/dist/server/index.d.ts +3 -2
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +511 -148
- package/dist/server/index.js.map +1 -1
- package/dist/server/internal.js +12 -3
- package/dist/server/internal.js.map +1 -1
- package/dist/server/pipeline-metadata.d.ts +9 -0
- package/dist/server/pipeline-metadata.d.ts.map +1 -1
- package/dist/server/pipeline-phases.d.ts.map +1 -1
- package/dist/server/rsc-entry/action-dispatcher.d.ts +0 -3
- package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/schema-introspection.d.ts +68 -0
- package/dist/server/schema-introspection.d.ts.map +1 -0
- package/dist/server/sensitive-fields.d.ts +40 -26
- package/dist/server/sensitive-fields.d.ts.map +1 -1
- package/dist/server/sitemap-handler.d.ts.map +1 -1
- package/docs/api/31-api-client.mdx +19 -18
- package/docs/api/34-api-config.mdx +1 -1
- package/docs/learn/08-forms-and-actions.mdx +57 -23
- package/package.json +8 -8
- package/src/client/browser-entry/index.ts +7 -1
- package/src/client/form.tsx +57 -108
- package/src/client/index.ts +3 -3
- package/src/client/{use-form-field.ts → use-field-state.ts} +20 -8
- package/src/config-types.ts +15 -18
- package/src/plugins/build-manifest.ts +12 -27
- package/src/plugins/shims.ts +0 -1
- package/src/server/action-client.ts +82 -307
- package/src/server/action-handler.ts +1 -42
- package/src/server/action-schema.ts +203 -0
- package/src/server/action-types.ts +145 -0
- package/src/server/form-data.ts +7 -0
- package/src/server/index.ts +5 -3
- package/src/server/pipeline-metadata.ts +11 -1
- package/src/server/pipeline-phases.ts +9 -2
- package/src/server/rsc-entry/action-dispatcher.ts +0 -4
- package/src/server/rsc-entry/index.ts +1 -2
- package/src/server/schema-introspection.ts +393 -0
- package/src/server/sensitive-fields.ts +115 -58
- package/src/server/sitemap-handler.ts +14 -21
- package/dist/_chunks/actions-CUh3cClk.js.map +0 -1
- package/dist/client/use-form-field.d.ts.map +0 -1
|
@@ -8,9 +8,40 @@
|
|
|
8
8
|
* 1. Direct call: action(input) → Promise<ActionResult>
|
|
9
9
|
* 2. React useActionState: (prevState, formData) => Promise<ActionResult>
|
|
10
10
|
*
|
|
11
|
+
* Types live in `action-types.ts`, schema handling in `action-schema.ts`, and
|
|
12
|
+
* the schema's declared shape (list fields, sensitive fields) in
|
|
13
|
+
* `schema-introspection.ts`.
|
|
14
|
+
*
|
|
11
15
|
* See design/08-forms-and-actions.md §"Middleware and Server Actions"
|
|
12
16
|
*/
|
|
13
17
|
|
|
18
|
+
import { parseFormData } from './form-data.ts';
|
|
19
|
+
import { formatSize } from '../utils/format.ts';
|
|
20
|
+
import { isDebug, isDevMode } from './debug.ts';
|
|
21
|
+
import { isDenySignal, isRedirectSignal } from './signal-identity.ts';
|
|
22
|
+
import {
|
|
23
|
+
stripSensitiveFields,
|
|
24
|
+
resolveSensitivePredicate,
|
|
25
|
+
getGlobalSensitiveFieldsConfig,
|
|
26
|
+
type SensitiveFieldsOption,
|
|
27
|
+
} from './sensitive-fields.ts';
|
|
28
|
+
import {
|
|
29
|
+
validateWithSchema,
|
|
30
|
+
type ActionSchema,
|
|
31
|
+
type SchemaInput,
|
|
32
|
+
type SchemaOutput,
|
|
33
|
+
} from './action-schema.ts';
|
|
34
|
+
import { introspectSchema, normalizeListFields, type FieldShape } from './schema-introspection.ts';
|
|
35
|
+
import type {
|
|
36
|
+
ActionBuilder,
|
|
37
|
+
ActionContext,
|
|
38
|
+
ActionFn,
|
|
39
|
+
ActionMiddleware,
|
|
40
|
+
ActionResult,
|
|
41
|
+
ActionServerError,
|
|
42
|
+
ValidationErrors,
|
|
43
|
+
} from './action-types.ts';
|
|
44
|
+
|
|
14
45
|
// ─── ActionError ─────────────────────────────────────────────────────────
|
|
15
46
|
|
|
16
47
|
/**
|
|
@@ -33,178 +64,22 @@ export class ActionError<TCode extends string = string> extends Error {
|
|
|
33
64
|
}
|
|
34
65
|
}
|
|
35
66
|
|
|
36
|
-
// ───
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Standard Schema v1 interface (subset).
|
|
40
|
-
* Zod ≥3.24, Valibot ≥1.0, and ArkType all implement this.
|
|
41
|
-
* See https://github.com/standard-schema/standard-schema
|
|
42
|
-
*
|
|
43
|
-
* We use permissive types here to accept all compliant libraries without
|
|
44
|
-
* requiring exact structural matches on issues/path shapes.
|
|
45
|
-
*/
|
|
46
|
-
interface StandardSchemaV1<Output = unknown> {
|
|
47
|
-
readonly '~standard': {
|
|
48
|
-
readonly validate: (
|
|
49
|
-
value: unknown
|
|
50
|
-
) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
type StandardSchemaResult<Output> =
|
|
55
|
-
| { value: Output; issues?: undefined }
|
|
56
|
-
| { value?: undefined; issues: ReadonlyArray<StandardSchemaIssue> };
|
|
57
|
-
|
|
58
|
-
interface StandardSchemaIssue {
|
|
59
|
-
message: string;
|
|
60
|
-
path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** Check if a schema implements the Standard Schema protocol. */
|
|
64
|
-
function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {
|
|
65
|
-
return (
|
|
66
|
-
typeof schema === 'object' &&
|
|
67
|
-
schema !== null &&
|
|
68
|
-
'~standard' in schema &&
|
|
69
|
-
typeof (schema as StandardSchemaV1)['~standard'].validate === 'function'
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// ─── Types ───────────────────────────────────────────────────────────────
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Minimal schema interface — compatible with Zod, Valibot, ArkType, etc.
|
|
77
|
-
*
|
|
78
|
-
* Accepts either:
|
|
79
|
-
* - Standard Schema (preferred): any object with `~standard.validate()`
|
|
80
|
-
* - Legacy parse interface: objects with `.parse()` / `.safeParse()`
|
|
81
|
-
*
|
|
82
|
-
* At runtime, Standard Schema is detected via `~standard` property and
|
|
83
|
-
* takes priority over the legacy interface.
|
|
84
|
-
*/
|
|
85
|
-
export type ActionSchema<T = unknown> = StandardSchemaV1<T> | LegacyActionSchema<T>;
|
|
86
|
-
|
|
87
|
-
/** Legacy schema interface with .parse() / .safeParse(). */
|
|
88
|
-
interface LegacyActionSchema<T = unknown> {
|
|
89
|
-
'parse'(data: unknown): T;
|
|
90
|
-
'safeParse'?(data: unknown): { success: true; data: T } | { success: false; error: SchemaError };
|
|
91
|
-
// Exclude Standard Schema objects from matching this interface
|
|
92
|
-
'~standard'?: never;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** Schema validation error shape (for legacy .safeParse()/.parse() interface). */
|
|
96
|
-
export interface SchemaError {
|
|
97
|
-
issues?: Array<{ path?: Array<string | number>; message: string }>;
|
|
98
|
-
flatten?(): { fieldErrors: Record<string, string[]> };
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Flattened validation errors keyed by field name. */
|
|
102
|
-
export type ValidationErrors = Record<string, string[]>;
|
|
103
|
-
|
|
104
|
-
/** Middleware function: returns context to merge into the action body's ctx. */
|
|
105
|
-
export type ActionMiddleware<TCtx = Record<string, unknown>> = () => Promise<TCtx> | TCtx;
|
|
106
|
-
|
|
107
|
-
/** The result type returned to the client. */
|
|
108
|
-
export type ActionResult<TData = unknown> =
|
|
109
|
-
| { data: TData; validationErrors?: never; serverError?: never; submittedValues?: never }
|
|
110
|
-
| {
|
|
111
|
-
data?: never;
|
|
112
|
-
validationErrors: ValidationErrors;
|
|
113
|
-
serverError?: never;
|
|
114
|
-
/** Raw input values on validation failure — for repopulating form fields. */
|
|
115
|
-
submittedValues?: Record<string, unknown>;
|
|
116
|
-
}
|
|
117
|
-
| {
|
|
118
|
-
data?: never;
|
|
119
|
-
validationErrors?: never;
|
|
120
|
-
serverError: { code: string; data?: Record<string, unknown> };
|
|
121
|
-
/**
|
|
122
|
-
* The submitted form, when the input was FormData — for repopulating
|
|
123
|
-
* form fields, which React resets after the action (TIM-1573).
|
|
124
|
-
*/
|
|
125
|
-
submittedValues?: Record<string, unknown>;
|
|
126
|
-
};
|
|
127
|
-
|
|
128
|
-
/** Context passed to the action body. */
|
|
129
|
-
export interface ActionContext<TCtx, TInput> {
|
|
130
|
-
ctx: TCtx;
|
|
131
|
-
input: TInput;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// ─── Builder ─────────────────────────────────────────────────────────────
|
|
67
|
+
// ─── Config ──────────────────────────────────────────────────────────────
|
|
135
68
|
|
|
136
69
|
interface ActionClientConfig<TCtx> {
|
|
137
70
|
middleware?: ActionMiddleware<TCtx> | ActionMiddleware<Record<string, unknown>>[];
|
|
138
71
|
/** Max file size in bytes. Files exceeding this are rejected with validation errors. */
|
|
139
72
|
fileSizeLimit?: number;
|
|
140
73
|
/**
|
|
141
|
-
* Override the sensitive-field deny-list for this action client.
|
|
142
|
-
* See `SensitiveFieldsOption` in `./sensitive-fields.ts`. Per-
|
|
74
|
+
* Override the sensitive-field name deny-list for this action client.
|
|
75
|
+
* See `SensitiveFieldsOption` in `./sensitive-fields.ts`. Per-client config
|
|
143
76
|
* takes precedence over the global `forms.stripSensitiveFields` option in
|
|
144
|
-
* `timber.config.ts`.
|
|
77
|
+
* `timber.config.ts`. Fields the schema marks `.meta({ sensitive: true })`
|
|
78
|
+
* are stripped whatever this says. See design/08-forms-and-actions.md.
|
|
145
79
|
*/
|
|
146
80
|
stripSensitiveFields?: SensitiveFieldsOption;
|
|
147
81
|
}
|
|
148
82
|
|
|
149
|
-
/** Intermediate builder returned by createActionClient(). */
|
|
150
|
-
export interface ActionBuilder<TCtx> {
|
|
151
|
-
/** Declare the input schema. Validation errors are returned typed. */
|
|
152
|
-
schema<TInput>(schema: ActionSchema<TInput>): ActionBuilderWithSchema<TCtx, TInput>;
|
|
153
|
-
/** Define the action body without input validation. */
|
|
154
|
-
action<TData>(
|
|
155
|
-
fn: (ctx: ActionContext<TCtx, undefined>) => Promise<TData>
|
|
156
|
-
): ActionFn<TData, undefined>;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/** Builder after .schema() has been called. */
|
|
160
|
-
export interface ActionBuilderWithSchema<TCtx, TInput> {
|
|
161
|
-
/** Define the action body with validated input. */
|
|
162
|
-
action<TData>(fn: (ctx: ActionContext<TCtx, TInput>) => Promise<TData>): ActionFn<TData, TInput>;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/**
|
|
166
|
-
* The final action function. Callable three ways:
|
|
167
|
-
* - Direct: action(input) → Promise<ActionResult<TData>>
|
|
168
|
-
* - React useActionState: action(prevState, payload) → Promise<ActionResult<TData>>,
|
|
169
|
-
* where payload is the submitted FormData or the value dispatch was called with
|
|
170
|
-
* - React <form action={fn}>: action(formData) → void (return value ignored by React)
|
|
171
|
-
*
|
|
172
|
-
* The third overload exists purely for type compatibility with React's
|
|
173
|
-
* `<form action>` prop, which expects `(formData: FormData) => void`.
|
|
174
|
-
* At runtime the function still returns Promise<ActionResult>, but React
|
|
175
|
-
* discards it. This lets validated actions be passed directly to forms
|
|
176
|
-
* without casts.
|
|
177
|
-
*/
|
|
178
|
-
/**
|
|
179
|
-
* Map schema output keys to `string | undefined` for form-facing APIs.
|
|
180
|
-
* HTML form values are always strings, and fields can be absent.
|
|
181
|
-
* Gives autocomplete for field names without lying about value types.
|
|
182
|
-
*/
|
|
183
|
-
export type InputHint<T> =
|
|
184
|
-
T extends Record<string, unknown> ? { [K in keyof T]: string | undefined } : T;
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* ActionFn — the callable returned by `createActionClient().action()`.
|
|
188
|
-
*
|
|
189
|
-
* Generic order: `<TData, TInput>` — TData first for backward compatibility.
|
|
190
|
-
* Previously ActionFn had a single `<TData>` generic, so existing code like
|
|
191
|
-
* `ActionFn<MyResult>` must still work with TData in the first position.
|
|
192
|
-
* See TIM-797.
|
|
193
|
-
*/
|
|
194
|
-
export type ActionFn<TData = unknown, TInput = unknown> = {
|
|
195
|
-
/** <form action={fn}> compatibility — React discards the return value. */
|
|
196
|
-
(formData: FormData): void;
|
|
197
|
-
/** Direct call: action(input) — optional when TInput is undefined/unknown (no-schema actions). */
|
|
198
|
-
(
|
|
199
|
-
...args: undefined extends TInput ? [input?: TInput] : [input: TInput]
|
|
200
|
-
): Promise<ActionResult<TData>>;
|
|
201
|
-
/**
|
|
202
|
-
* React useActionState: action(prevState, payload). The payload is the
|
|
203
|
-
* submitted FormData, or whatever the hook's dispatch was called with.
|
|
204
|
-
*/
|
|
205
|
-
(prevState: ActionResult<TData> | null, payload: TInput | FormData): Promise<ActionResult<TData>>;
|
|
206
|
-
};
|
|
207
|
-
|
|
208
83
|
// ─── Implementation ──────────────────────────────────────────────────────
|
|
209
84
|
|
|
210
85
|
/**
|
|
@@ -229,62 +104,6 @@ async function runActionMiddleware<TCtx>(
|
|
|
229
104
|
return await middleware();
|
|
230
105
|
}
|
|
231
106
|
|
|
232
|
-
// Re-export parseFormData for use throughout the framework
|
|
233
|
-
import { parseFormData } from './form-data.ts';
|
|
234
|
-
import { formatSize } from '../utils/format.ts';
|
|
235
|
-
import { isDebug, isDevMode } from './debug.ts';
|
|
236
|
-
import { isDenySignal, isRedirectSignal } from './signal-identity.ts';
|
|
237
|
-
import {
|
|
238
|
-
stripSensitiveFields,
|
|
239
|
-
resolveSensitivePredicate,
|
|
240
|
-
getGlobalSensitiveFieldsConfig,
|
|
241
|
-
type SensitiveFieldsOption,
|
|
242
|
-
} from './sensitive-fields.ts';
|
|
243
|
-
|
|
244
|
-
/**
|
|
245
|
-
* Extract validation errors from a schema error.
|
|
246
|
-
* Supports Zod's flatten() and generic issues array.
|
|
247
|
-
*/
|
|
248
|
-
function extractValidationErrors(error: SchemaError): ValidationErrors {
|
|
249
|
-
// Zod-style flatten
|
|
250
|
-
if (typeof error.flatten === 'function') {
|
|
251
|
-
return error.flatten().fieldErrors;
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
// Generic issues array
|
|
255
|
-
if (error.issues) {
|
|
256
|
-
const errors: ValidationErrors = {};
|
|
257
|
-
for (const issue of error.issues) {
|
|
258
|
-
const path = issue.path?.join('.') ?? '_root';
|
|
259
|
-
if (!errors[path]) errors[path] = [];
|
|
260
|
-
errors[path].push(issue.message);
|
|
261
|
-
}
|
|
262
|
-
return errors;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
return { _root: ['Validation failed'] };
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* Extract validation errors from Standard Schema issues.
|
|
270
|
-
*/
|
|
271
|
-
function extractStandardSchemaErrors(issues: ReadonlyArray<StandardSchemaIssue>): ValidationErrors {
|
|
272
|
-
const errors: ValidationErrors = {};
|
|
273
|
-
for (const issue of issues) {
|
|
274
|
-
const path =
|
|
275
|
-
issue.path
|
|
276
|
-
?.map((p) => {
|
|
277
|
-
// Standard Schema path items can be { key: ... } objects or bare PropertyKey values
|
|
278
|
-
if (typeof p === 'object' && p !== null && 'key' in p) return String(p.key);
|
|
279
|
-
return String(p);
|
|
280
|
-
})
|
|
281
|
-
.join('.') ?? '_root';
|
|
282
|
-
if (!errors[path]) errors[path] = [];
|
|
283
|
-
errors[path].push(issue.message);
|
|
284
|
-
}
|
|
285
|
-
return Object.keys(errors).length > 0 ? errors : { _root: ['Validation failed'] };
|
|
286
|
-
}
|
|
287
|
-
|
|
288
107
|
/**
|
|
289
108
|
* Wrap unexpected errors into a safe server error result.
|
|
290
109
|
* ActionError → typed result. Other errors → INTERNAL_ERROR (no leak).
|
|
@@ -292,9 +111,7 @@ function extractStandardSchemaErrors(issues: ReadonlyArray<StandardSchemaIssue>)
|
|
|
292
111
|
* `createActionClient` actions only. A raw `'use server'` function that
|
|
293
112
|
* throws is rejected on the client instead (action-handler.ts).
|
|
294
113
|
*/
|
|
295
|
-
export function handleActionError(error: unknown): {
|
|
296
|
-
serverError: { code: string; data?: Record<string, unknown> };
|
|
297
|
-
} {
|
|
114
|
+
export function handleActionError(error: unknown): { serverError: ActionServerError } {
|
|
298
115
|
if (error instanceof ActionError) {
|
|
299
116
|
return {
|
|
300
117
|
serverError: {
|
|
@@ -340,10 +157,22 @@ export function handleActionError(error: unknown): {
|
|
|
340
157
|
export function createActionClient<TCtx = Record<string, never>>(
|
|
341
158
|
config: ActionClientConfig<TCtx> = {}
|
|
342
159
|
): ActionBuilder<TCtx> {
|
|
343
|
-
function buildAction<TInput, TData>(
|
|
344
|
-
schema: ActionSchema
|
|
345
|
-
fn: (ctx: ActionContext<TCtx,
|
|
160
|
+
function buildAction<TInput, TOutput, TData>(
|
|
161
|
+
schema: ActionSchema | undefined,
|
|
162
|
+
fn: (ctx: ActionContext<TCtx, TOutput>) => Promise<TData>
|
|
346
163
|
): ActionFn<TData, TInput> {
|
|
164
|
+
// The schema's declared shape, read once per action on its first call:
|
|
165
|
+
// which fields are lists, and which are marked sensitive.
|
|
166
|
+
let shape: FieldShape | undefined;
|
|
167
|
+
let introspected = false;
|
|
168
|
+
const getShape = (): FieldShape | undefined => {
|
|
169
|
+
if (!introspected) {
|
|
170
|
+
shape = introspectSchema(schema);
|
|
171
|
+
introspected = true;
|
|
172
|
+
}
|
|
173
|
+
return shape;
|
|
174
|
+
};
|
|
175
|
+
|
|
347
176
|
async function actionHandler(...args: unknown[]): Promise<ActionResult<TData>> {
|
|
348
177
|
// The input is the last argument in every call shape: `(input)`,
|
|
349
178
|
// `(formData)`, `(prevState, payload)` from useActionState's
|
|
@@ -353,12 +182,13 @@ export function createActionClient<TCtx = Record<string, never>>(
|
|
|
353
182
|
// action with bound arguments. Nothing before it is input:
|
|
354
183
|
// `prevState` comes from the client, so it is never read.
|
|
355
184
|
const last = args.at(-1);
|
|
356
|
-
|
|
185
|
+
// A form's list fields take the shape the schema declares whatever
|
|
186
|
+
// their count, both for validation and for `submittedValues`.
|
|
187
|
+
const form =
|
|
188
|
+
last instanceof FormData ? normalizeListFields(parseFormData(last), getShape()) : undefined;
|
|
357
189
|
|
|
358
|
-
//
|
|
359
|
-
// Precedence: per-action (config.stripSensitiveFields) > global
|
|
190
|
+
// Precedence: per-client (config.stripSensitiveFields) > global
|
|
360
191
|
// (forms.stripSensitiveFields from timber.config.ts) > built-in deny-list.
|
|
361
|
-
// See TIM-816.
|
|
362
192
|
const sensitivePredicate = resolveSensitivePredicate(
|
|
363
193
|
config.stripSensitiveFields,
|
|
364
194
|
getGlobalSensitiveFieldsConfig()
|
|
@@ -366,12 +196,12 @@ export function createActionClient<TCtx = Record<string, never>>(
|
|
|
366
196
|
|
|
367
197
|
// A "safe-to-echo" copy of the input. Files are stripped (can't
|
|
368
198
|
// serialize, shouldn't echo back) and sensitive fields (passwords,
|
|
369
|
-
// tokens, CVV,
|
|
370
|
-
// payload → client form `defaultValue` → DOM.
|
|
199
|
+
// tokens, CVV, schema-marked fields) are removed before they would
|
|
200
|
+
// land in the RSC payload → client form `defaultValue` → DOM.
|
|
371
201
|
const echo = (value: unknown): Record<string, unknown> | undefined => {
|
|
372
202
|
const withoutFiles = stripFiles(value);
|
|
373
203
|
if (withoutFiles === undefined) return undefined;
|
|
374
|
-
return stripSensitiveFields(withoutFiles, sensitivePredicate);
|
|
204
|
+
return stripSensitiveFields(withoutFiles, sensitivePredicate, getShape());
|
|
375
205
|
};
|
|
376
206
|
|
|
377
207
|
try {
|
|
@@ -382,7 +212,6 @@ export function createActionClient<TCtx = Record<string, never>>(
|
|
|
382
212
|
// and echoes read the parsed form: a FormData has no own entries.
|
|
383
213
|
const rawInput: unknown = schema && form ? form : last;
|
|
384
214
|
const submitted: unknown = form ?? rawInput;
|
|
385
|
-
const buildSubmittedValues = () => echo(submitted);
|
|
386
215
|
|
|
387
216
|
// Validate file sizes before schema validation.
|
|
388
217
|
if (config.fileSizeLimit !== undefined && submitted && typeof submitted === 'object') {
|
|
@@ -391,53 +220,26 @@ export function createActionClient<TCtx = Record<string, never>>(
|
|
|
391
220
|
config.fileSizeLimit
|
|
392
221
|
);
|
|
393
222
|
if (fileSizeErrors) {
|
|
394
|
-
return { validationErrors: fileSizeErrors, submittedValues:
|
|
223
|
+
return { validationErrors: fileSizeErrors, submittedValues: echo(submitted) };
|
|
395
224
|
}
|
|
396
225
|
}
|
|
397
226
|
|
|
398
|
-
|
|
399
|
-
const submittedValues = schema ? buildSubmittedValues() : undefined;
|
|
400
|
-
|
|
401
|
-
// Validate with schema if provided
|
|
402
|
-
let input: TInput;
|
|
227
|
+
let input: unknown = rawInput;
|
|
403
228
|
if (schema) {
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
}
|
|
412
|
-
if (result.issues) {
|
|
413
|
-
const validationErrors = extractStandardSchemaErrors(result.issues);
|
|
414
|
-
logValidationFailure(validationErrors);
|
|
415
|
-
return { validationErrors, submittedValues };
|
|
416
|
-
}
|
|
417
|
-
input = result.value;
|
|
418
|
-
} else if (typeof schema.safeParse === 'function') {
|
|
419
|
-
const result = schema.safeParse(rawInput);
|
|
420
|
-
if (!result.success) {
|
|
421
|
-
const validationErrors = extractValidationErrors(result.error);
|
|
422
|
-
logValidationFailure(validationErrors);
|
|
423
|
-
return { validationErrors, submittedValues };
|
|
424
|
-
}
|
|
425
|
-
input = result.data;
|
|
426
|
-
} else {
|
|
427
|
-
try {
|
|
428
|
-
input = schema.parse(rawInput);
|
|
429
|
-
} catch (parseError) {
|
|
430
|
-
const validationErrors = extractValidationErrors(parseError as SchemaError);
|
|
431
|
-
logValidationFailure(validationErrors);
|
|
432
|
-
return { validationErrors, submittedValues };
|
|
433
|
-
}
|
|
229
|
+
const validation = validateWithSchema(schema, rawInput);
|
|
230
|
+
if (!validation.ok) {
|
|
231
|
+
logValidationFailure(validation.validationErrors);
|
|
232
|
+
return {
|
|
233
|
+
validationErrors: validation.validationErrors,
|
|
234
|
+
submittedValues: echo(submitted),
|
|
235
|
+
};
|
|
434
236
|
}
|
|
435
|
-
|
|
436
|
-
input = rawInput as TInput;
|
|
237
|
+
input = validation.value;
|
|
437
238
|
}
|
|
438
239
|
|
|
439
|
-
// Execute the action body
|
|
440
|
-
|
|
240
|
+
// Execute the action body. `input` is the schema's output, or the
|
|
241
|
+
// raw input when there is no schema (TOutput is `undefined` then).
|
|
242
|
+
const data = await fn({ ctx, input: input as TOutput });
|
|
441
243
|
return { data };
|
|
442
244
|
} catch (error) {
|
|
443
245
|
// Re-throw redirect/deny signals — these are control flow, not errors.
|
|
@@ -456,15 +258,17 @@ export function createActionClient<TCtx = Record<string, never>>(
|
|
|
456
258
|
}
|
|
457
259
|
}
|
|
458
260
|
|
|
261
|
+
// One implementation serves every overload of `ActionFn`, which
|
|
262
|
+
// TypeScript cannot check a single function against.
|
|
459
263
|
return actionHandler as ActionFn<TData, TInput>;
|
|
460
264
|
}
|
|
461
265
|
|
|
462
266
|
return {
|
|
463
|
-
schema<
|
|
267
|
+
schema<S extends ActionSchema>(schema: S) {
|
|
464
268
|
return {
|
|
465
269
|
action<TData>(
|
|
466
|
-
fn: (ctx: ActionContext<TCtx,
|
|
467
|
-
): ActionFn<TData,
|
|
270
|
+
fn: (ctx: ActionContext<TCtx, SchemaOutput<S>>) => Promise<TData>
|
|
271
|
+
): ActionFn<TData, SchemaInput<S>> {
|
|
468
272
|
return buildAction(schema, fn);
|
|
469
273
|
},
|
|
470
274
|
};
|
|
@@ -472,40 +276,11 @@ export function createActionClient<TCtx = Record<string, never>>(
|
|
|
472
276
|
action<TData>(
|
|
473
277
|
fn: (ctx: ActionContext<TCtx, undefined>) => Promise<TData>
|
|
474
278
|
): ActionFn<TData, undefined> {
|
|
475
|
-
return buildAction(undefined, fn
|
|
279
|
+
return buildAction(undefined, fn);
|
|
476
280
|
},
|
|
477
281
|
};
|
|
478
282
|
}
|
|
479
283
|
|
|
480
|
-
// ─── validated() ────────────────────────────────────────────────────────
|
|
481
|
-
|
|
482
|
-
/**
|
|
483
|
-
* Convenience wrapper for the common case: validate input, run handler.
|
|
484
|
-
* No middleware needed.
|
|
485
|
-
*
|
|
486
|
-
* @example
|
|
487
|
-
* ```ts
|
|
488
|
-
* 'use server'
|
|
489
|
-
* import { validated } from '@timber-js/app/server'
|
|
490
|
-
* import { z } from 'zod'
|
|
491
|
-
*
|
|
492
|
-
* export const createTodo = validated(
|
|
493
|
-
* z.object({ title: z.string().min(1) }),
|
|
494
|
-
* async (input) => {
|
|
495
|
-
* await db.todos.create(input)
|
|
496
|
-
* }
|
|
497
|
-
* )
|
|
498
|
-
* ```
|
|
499
|
-
*/
|
|
500
|
-
export function validated<TInput, TData>(
|
|
501
|
-
schema: ActionSchema<TInput>,
|
|
502
|
-
handler: (input: TInput) => Promise<TData>
|
|
503
|
-
): ActionFn<TData, TInput> {
|
|
504
|
-
return createActionClient()
|
|
505
|
-
.schema(schema)
|
|
506
|
-
.action(async ({ input }) => handler(input));
|
|
507
|
-
}
|
|
508
|
-
|
|
509
284
|
// ─── Helpers ────────────────────────────────────────────────────────────
|
|
510
285
|
|
|
511
286
|
/**
|
|
@@ -517,7 +292,7 @@ function logValidationFailure(errors: ValidationErrors): void {
|
|
|
517
292
|
if (!isDev) return;
|
|
518
293
|
|
|
519
294
|
const fields = Object.entries(errors)
|
|
520
|
-
.map(([field, messages]) => ` ${field}: ${messages.join(', ')}`)
|
|
295
|
+
.map(([field, messages]) => ` ${field}: ${(messages ?? []).join(', ')}`)
|
|
521
296
|
.join('\n');
|
|
522
297
|
console.warn(`[timber] action schema validation failed:\n${fields}`);
|
|
523
298
|
}
|
|
@@ -526,14 +301,14 @@ function logValidationFailure(errors: ValidationErrors): void {
|
|
|
526
301
|
* Validate that all File objects in the input are within the size limit.
|
|
527
302
|
* Returns validation errors keyed by field name, or null if all files are ok.
|
|
528
303
|
* Keys are dot paths (`rows.0.file`), the form a field name and a Standard
|
|
529
|
-
* Schema error use, so `
|
|
304
|
+
* Schema error use, so `errors.field()` finds a file in a list.
|
|
530
305
|
*/
|
|
531
306
|
function validateFileSizes(input: Record<string, unknown>, limit: number): ValidationErrors | null {
|
|
532
307
|
const limitKb = Math.round(limit / 1024);
|
|
533
308
|
const limitLabel =
|
|
534
309
|
limit >= 1024 * 1024 ? `${Math.round(limit / (1024 * 1024))}MB` : `${limitKb}KB`;
|
|
535
310
|
|
|
536
|
-
const errors:
|
|
311
|
+
const errors: Record<string, string[]> = {};
|
|
537
312
|
|
|
538
313
|
function walk(obj: Record<string, unknown>, prefix: string): void {
|
|
539
314
|
for (const [key, value] of Object.entries(obj)) {
|
|
@@ -30,13 +30,6 @@ import { runOutsideReactCacheScope, runWithReactCacheScope } from './react-cache
|
|
|
30
30
|
import { getSetCookieHeaders, getCookiesForSsr } from './cookie-context.ts';
|
|
31
31
|
import { ActionError } from './action-client.ts';
|
|
32
32
|
import { enforceBodyLimits, enforceFieldLimit, type BodyLimitsConfig } from './body-limits.ts';
|
|
33
|
-
import {
|
|
34
|
-
stripSensitiveFields,
|
|
35
|
-
resolveSensitivePredicate,
|
|
36
|
-
getGlobalSensitiveFieldsConfig,
|
|
37
|
-
type ResolvedSensitivePredicate,
|
|
38
|
-
type SensitiveFieldsOption,
|
|
39
|
-
} from './sensitive-fields.ts';
|
|
40
33
|
import { randomUUID } from 'node:crypto';
|
|
41
34
|
import type { ReactFormState } from 'react-dom/client';
|
|
42
35
|
import { encodeErrorDigest } from '../shared/error-digest.ts';
|
|
@@ -58,12 +51,6 @@ export interface ActionDispatchConfig {
|
|
|
58
51
|
revalidateRenderer?: RevalidateRenderer;
|
|
59
52
|
/** Body size limits (from timber.config.ts). */
|
|
60
53
|
bodyLimits?: BodyLimitsConfig;
|
|
61
|
-
/**
|
|
62
|
-
* Override the sensitive-field deny-list for the no-JS form POST path.
|
|
63
|
-
* Defaults to the global `forms.stripSensitiveFields` from `timber.config.ts`.
|
|
64
|
-
* See `SensitiveFieldsOption` in `./sensitive-fields.ts` and TIM-816.
|
|
65
|
-
*/
|
|
66
|
-
sensitiveFields?: SensitiveFieldsOption;
|
|
67
54
|
}
|
|
68
55
|
|
|
69
56
|
// ─── Detection ────────────────────────────────────────────────────────────
|
|
@@ -670,40 +657,12 @@ async function handleFormAction(
|
|
|
670
657
|
});
|
|
671
658
|
}
|
|
672
659
|
|
|
673
|
-
// Defense-in-depth: strip sensitive fields from `submittedValues` before
|
|
674
|
-
// the result is rendered into the page. `createActionClient` strips
|
|
675
|
-
// internally, but a raw `'use server'` function that returns
|
|
676
|
-
// `{ submittedValues }` itself is not covered by that. See TIM-816.
|
|
677
|
-
const actionResult = stripResultSubmittedValues(
|
|
678
|
-
result.actionResult,
|
|
679
|
-
resolveSensitivePredicate(config.sensitiveFields, getGlobalSensitiveFieldsConfig())
|
|
680
|
-
);
|
|
681
|
-
|
|
682
660
|
// React keys the result to the hook that submitted: `$ACTION_KEY` names
|
|
683
661
|
// the useActionState instance, and Fizz hands the result to it as its
|
|
684
662
|
// initial state only when that key and the action match. A form with no
|
|
685
663
|
// useActionState has no key, so this is undefined and the page renders
|
|
686
664
|
// with no result, as the JS path discards the return value of a plain
|
|
687
665
|
// `<form action>`. Such forms should `redirect()` (post-redirect-get).
|
|
688
|
-
const formState = (await decodeFormState(actionResult, formData)) ?? undefined;
|
|
666
|
+
const formState = (await decodeFormState(result.actionResult, formData)) ?? undefined;
|
|
689
667
|
return { kind: 'rerender', formState };
|
|
690
668
|
}
|
|
691
|
-
|
|
692
|
-
/**
|
|
693
|
-
* `result` with sensitive fields removed from its `submittedValues`, when it
|
|
694
|
-
* has any. A copy: the action's own object is not written to.
|
|
695
|
-
*/
|
|
696
|
-
function stripResultSubmittedValues(
|
|
697
|
-
result: unknown,
|
|
698
|
-
isSensitive: ResolvedSensitivePredicate
|
|
699
|
-
): unknown {
|
|
700
|
-
if (typeof result !== 'object' || result === null || !('submittedValues' in result)) {
|
|
701
|
-
return result;
|
|
702
|
-
}
|
|
703
|
-
const { submittedValues } = result;
|
|
704
|
-
if (typeof submittedValues !== 'object' || submittedValues === null) return result;
|
|
705
|
-
return {
|
|
706
|
-
...result,
|
|
707
|
-
submittedValues: stripSensitiveFields(submittedValues, isSensitive),
|
|
708
|
-
};
|
|
709
|
-
}
|