@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.
Files changed (81) hide show
  1. package/agent-skill.md +5 -5
  2. package/dist/_chunks/{actions-CUh3cClk.js → actions-BwkmAYXq.js} +8 -1
  3. package/dist/_chunks/actions-BwkmAYXq.js.map +1 -0
  4. package/dist/_chunks/cloudflare-Byxl8FWP.js.map +1 -1
  5. package/dist/_chunks/dev-server-B8zsT-ee.js.map +1 -1
  6. package/dist/_chunks/dist-DtrJyBbw.js.map +1 -1
  7. package/dist/_chunks/graph-cache-CYiUS2aS.js.map +1 -1
  8. package/dist/_chunks/use-query-states-I3JMng6J.js.map +1 -1
  9. package/dist/adapters/cloudflare.js +1 -2
  10. package/dist/adapters/nitro.js.map +1 -1
  11. package/dist/analyze/graph-command.js.map +1 -1
  12. package/dist/client/error-boundary.js +1 -2
  13. package/dist/client/form.d.ts +34 -37
  14. package/dist/client/form.d.ts.map +1 -1
  15. package/dist/client/index.d.ts +3 -3
  16. package/dist/client/index.d.ts.map +1 -1
  17. package/dist/client/index.js +40 -75
  18. package/dist/client/index.js.map +1 -1
  19. package/dist/client/{use-form-field.d.ts → use-field-state.d.ts} +10 -7
  20. package/dist/client/use-field-state.d.ts.map +1 -0
  21. package/dist/config-types.d.ts +15 -18
  22. package/dist/config-types.d.ts.map +1 -1
  23. package/dist/cookies/index.js.map +1 -1
  24. package/dist/index.js +29 -27
  25. package/dist/index.js.map +1 -1
  26. package/dist/plugins/build-manifest.d.ts.map +1 -1
  27. package/dist/plugins/shims.d.ts.map +1 -1
  28. package/dist/search-params/index.js.map +1 -1
  29. package/dist/server/action-client.d.ts +11 -172
  30. package/dist/server/action-client.d.ts.map +1 -1
  31. package/dist/server/action-handler.d.ts +0 -7
  32. package/dist/server/action-handler.d.ts.map +1 -1
  33. package/dist/server/action-schema.d.ts +126 -0
  34. package/dist/server/action-schema.d.ts.map +1 -0
  35. package/dist/server/action-types.d.ts +108 -0
  36. package/dist/server/action-types.d.ts.map +1 -0
  37. package/dist/server/form-data.d.ts +7 -0
  38. package/dist/server/form-data.d.ts.map +1 -1
  39. package/dist/server/index.d.ts +3 -2
  40. package/dist/server/index.d.ts.map +1 -1
  41. package/dist/server/index.js +511 -148
  42. package/dist/server/index.js.map +1 -1
  43. package/dist/server/internal.js +12 -3
  44. package/dist/server/internal.js.map +1 -1
  45. package/dist/server/pipeline-metadata.d.ts +9 -0
  46. package/dist/server/pipeline-metadata.d.ts.map +1 -1
  47. package/dist/server/pipeline-phases.d.ts.map +1 -1
  48. package/dist/server/rsc-entry/action-dispatcher.d.ts +0 -3
  49. package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
  50. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  51. package/dist/server/schema-introspection.d.ts +68 -0
  52. package/dist/server/schema-introspection.d.ts.map +1 -0
  53. package/dist/server/sensitive-fields.d.ts +40 -26
  54. package/dist/server/sensitive-fields.d.ts.map +1 -1
  55. package/dist/server/sitemap-handler.d.ts.map +1 -1
  56. package/docs/api/31-api-client.mdx +19 -18
  57. package/docs/api/34-api-config.mdx +1 -1
  58. package/docs/learn/08-forms-and-actions.mdx +57 -23
  59. package/package.json +8 -8
  60. package/src/client/browser-entry/index.ts +7 -1
  61. package/src/client/form.tsx +57 -108
  62. package/src/client/index.ts +3 -3
  63. package/src/client/{use-form-field.ts → use-field-state.ts} +20 -8
  64. package/src/config-types.ts +15 -18
  65. package/src/plugins/build-manifest.ts +12 -27
  66. package/src/plugins/shims.ts +0 -1
  67. package/src/server/action-client.ts +82 -307
  68. package/src/server/action-handler.ts +1 -42
  69. package/src/server/action-schema.ts +203 -0
  70. package/src/server/action-types.ts +145 -0
  71. package/src/server/form-data.ts +7 -0
  72. package/src/server/index.ts +5 -3
  73. package/src/server/pipeline-metadata.ts +11 -1
  74. package/src/server/pipeline-phases.ts +9 -2
  75. package/src/server/rsc-entry/action-dispatcher.ts +0 -4
  76. package/src/server/rsc-entry/index.ts +1 -2
  77. package/src/server/schema-introspection.ts +393 -0
  78. package/src/server/sensitive-fields.ts +115 -58
  79. package/src/server/sitemap-handler.ts +14 -21
  80. package/dist/_chunks/actions-CUh3cClk.js.map +0 -1
  81. package/dist/client/use-form-field.d.ts.map +0 -1
@@ -3,137 +3,86 @@
3
3
  *
4
4
  * Forms use React's own `useActionState`: an action built with
5
5
  * `createActionClient` already has the `(prevState, payload)` signature it
6
- * calls, and the result is typed from it. `parseFormErrors` reads the errors
7
- * out of that result.
6
+ * calls, and the result is typed from it. An imperative call (a delete
7
+ * button) uses the same hook: `startTransition(() => dispatch(input))`.
8
+ * `readFormErrors` reads the errors out of that result.
8
9
  *
9
- * See design/08-forms-and-actions.md §"Client-Side Form Mechanics"
10
+ * See design/08-forms-and-actions.md §"Form Errors via readFormErrors"
10
11
  */
11
12
 
12
- import { useTransition } from 'react';
13
- import type {
14
- ActionFn,
15
- ActionResult,
16
- InputHint,
17
- ValidationErrors,
18
- } from '../server/action-client.ts';
19
-
20
- // ─── useFormAction ───────────────────────────────────────────────────────
21
-
22
- /**
23
- * Hook for calling a server action imperatively (not via a form).
24
- * Returns [execute, isPending] where execute accepts the input directly.
25
- *
26
- * @example
27
- * ```tsx
28
- * const [deleteTodo, isPending] = useFormAction(deleteTodoAction)
29
- * <button onClick={() => deleteTodo({ id: todo.id })} disabled={isPending}>
30
- * Delete
31
- * </button>
32
- * ```
33
- */
34
- export function useFormAction<TData = unknown, TInput = unknown>(
35
- action: ActionFn<TData, TInput> | ((input: TInput) => Promise<ActionResult<TData>>)
36
- ): [
37
- (
38
- ...args: undefined extends TInput ? [input?: InputHint<TInput>] : [input: InputHint<TInput>]
39
- ) => Promise<ActionResult<TData>>,
40
- boolean,
41
- ] {
42
- const [isPending, startTransition] = useTransition();
43
-
44
- const execute = (input?: InputHint<TInput>): Promise<ActionResult<TData>> => {
45
- return new Promise((resolve, reject) => {
46
- startTransition(async () => {
47
- // A raw server function that throws rejects (TIM-1570). The caller
48
- // awaiting `execute` gets that rejection; without the catch the
49
- // promise would never settle.
50
- try {
51
- resolve(
52
- await (action as (input: InputHint<TInput>) => Promise<ActionResult<TData>>)(
53
- input as InputHint<TInput>
54
- )
55
- );
56
- } catch (error) {
57
- reject(error);
58
- }
59
- });
60
- });
61
- };
62
-
63
- return [execute, isPending];
64
- }
13
+ import type { ActionServerError } from '../server/action-types.ts';
65
14
 
66
15
  // ─── Form error extraction ────────────────────────────────────────────────
67
16
 
68
- /** What `parseFormErrors` reads out of an action result. */
69
- export interface FormErrorsResult {
70
- /** Per-field validation errors keyed by field name. */
71
- fieldErrors: Record<string, string[]>;
72
- /** Form-level errors (from `_root` key). */
73
- formErrors: string[];
74
- /** Server error if the action threw an ActionError. */
75
- serverError: { code: string; data?: Record<string, unknown> } | null;
17
+ /** What `readFormErrors` reads out of an action result. */
18
+ export interface FormErrors<TPath extends string = string> {
19
+ /** The first validation error for a field, or null. Paths are dot paths: `sets.0.name`. */
20
+ field(name: TPath): string | null;
21
+ /** Form-level validation errors (the `_root` key). */
22
+ form: readonly string[];
23
+ /** The server error, if the action threw (an `ActionError`, or `INTERNAL_ERROR`). */
24
+ server: ActionServerError | null;
76
25
  /** Whether any errors are present. */
77
26
  hasErrors: boolean;
78
- /** Get the first error message for a field, or null. */
79
- getFieldError: (field: string) => string | null;
27
+ }
28
+
29
+ /** The shape `readFormErrors` reads: any `ActionResult`. */
30
+ interface ResultWithErrors {
31
+ validationErrors?: { [path: string]: string[] | undefined };
32
+ serverError?: ActionServerError;
80
33
  }
81
34
 
35
+ /**
36
+ * The field paths of a result's validation errors, from its schema's input.
37
+ * Distributes over the result union: only the validation-failure member has
38
+ * a non-`never` `validationErrors`.
39
+ */
40
+ type ErrorPaths<R> = R extends { validationErrors?: infer V }
41
+ ? [NonNullable<V>] extends [never]
42
+ ? never
43
+ : Exclude<keyof NonNullable<V>, '_root'> & string
44
+ : never;
45
+
46
+ // Shared by every result without errors, so frozen: a caller cannot mutate
47
+ // it into a value later empty results would report.
48
+ const EMPTY: FormErrors<never> = Object.freeze({
49
+ field: () => null,
50
+ form: Object.freeze([]),
51
+ server: null,
52
+ hasErrors: false,
53
+ });
54
+
82
55
  /**
83
56
  * Read the errors out of an action result — the state `useActionState`
84
57
  * returns. `_root` validation errors are form-level; every other key is a
85
- * field.
58
+ * field. Field names are typed from the action's schema input, so a
59
+ * misspelled path is a type error.
86
60
  *
87
61
  * @example
88
62
  * ```tsx
89
63
  * const [result, action, isPending] = useActionState(createTodo, null)
90
- * const errors = parseFormErrors(result)
91
- * errors.getFieldError('title') // first message for the field, or null
64
+ * const errors = readFormErrors(result)
65
+ * errors.field('title') // first message for the field, or null
92
66
  * ```
93
67
  */
94
- export function parseFormErrors<TData>(
95
- result: ActionResult<TData> | null | undefined
96
- ): FormErrorsResult {
97
- const empty: FormErrorsResult = {
98
- fieldErrors: {},
99
- formErrors: [],
100
- serverError: null,
101
- hasErrors: false,
102
- getFieldError: () => null,
103
- };
104
-
105
- if (!result) return empty;
106
-
107
- const validationErrors: ValidationErrors | undefined = result.validationErrors;
108
- const serverError = result.serverError;
109
-
110
- if (!validationErrors && !serverError) return empty;
111
-
112
- // Separate _root (form-level) errors from field errors
113
- const fieldErrors: Record<string, string[]> = {};
114
- const formErrors: string[] = [];
115
-
116
- if (validationErrors) {
117
- for (const [key, messages] of Object.entries(validationErrors)) {
118
- if (key === '_root') {
119
- formErrors.push(...messages);
120
- } else {
121
- fieldErrors[key] = messages;
122
- }
123
- }
124
- }
68
+ export function readFormErrors<R extends ResultWithErrors>(
69
+ result: R | null | undefined
70
+ ): FormErrors<ErrorPaths<R>> {
71
+ if (!result) return EMPTY;
125
72
 
73
+ const validationErrors = result.validationErrors ?? {};
74
+ const server = result.serverError ?? null;
75
+ const form = validationErrors._root ?? [];
126
76
  const hasErrors =
127
- Object.keys(fieldErrors).length > 0 || formErrors.length > 0 || serverError != null;
77
+ server !== null || Object.values(validationErrors).some((messages) => messages?.length);
128
78
 
79
+ if (!hasErrors) return EMPTY;
129
80
  return {
130
- fieldErrors,
131
- formErrors,
132
- serverError: serverError ?? null,
133
- hasErrors,
134
- getFieldError(field: string): string | null {
135
- const errs = fieldErrors[field];
136
- return errs && errs.length > 0 ? errs[0] : null;
81
+ field(name) {
82
+ return validationErrors[name]?.[0] ?? null;
137
83
  },
84
+ form,
85
+ server,
86
+ hasErrors,
138
87
  };
139
88
  }
@@ -75,9 +75,9 @@ export {
75
75
  } from './use-selected-layout-segment.ts';
76
76
 
77
77
  // Forms
78
- export { parseFormErrors, useFormAction } from './form.tsx';
79
- export { useFormField } from './use-form-field.ts';
80
- export type { FormErrorsResult } from './form.tsx';
78
+ export { readFormErrors } from './form.tsx';
79
+ export { useFieldState } from './use-field-state.ts';
80
+ export type { FormErrors } from './form.tsx';
81
81
 
82
82
  // Params. Called with no argument this returns the untyped accumulated params;
83
83
  // pass the route's SEGMENT_PATH (from its generated `./$segment` module) to get
@@ -1,5 +1,5 @@
1
1
  /**
2
- * useFormField — state for a form field that needs JavaScript (a combobox, a
2
+ * useFieldState — state for a form field that needs JavaScript (a combobox, a
3
3
  * chip list, a row list), made to behave like a native uncontrolled input.
4
4
  *
5
5
  * React resets a form after its action settles, so a native field with a
@@ -27,8 +27,11 @@ import {
27
27
  * State for a field that follows its form's reset.
28
28
  *
29
29
  * Returns `[value, setValue, ref]`. Attach `ref` to any element inside the
30
- * `<form>`, and render the value into the form data yourself (usually a
31
- * hidden input). `value` is `defaultValue` until `setValue` is called, and is
30
+ * `<form>`, or to the `<form>` itself (the hook subscribes to
31
+ * `closest('form')`, which includes the element), and render the value into
32
+ * the form data yourself (usually hidden inputs). With the ref on the form,
33
+ * the hook can live above it and hold the whole draft as one object, for a
34
+ * live preview beside the form. `value` is `defaultValue` until `setValue` is called, and is
32
35
  * `defaultValue` again after the form resets, unless the form cancels its
33
36
  * `reset` event. An edit dispatches a bubbling `change` event from the `ref`
34
37
  * element after it commits, so a native `change` listener on the form sees it
@@ -39,14 +42,14 @@ import {
39
42
  * @example
40
43
  * ```tsx
41
44
  * // draft: the form's defaults, read from result?.submittedValues ?? pageData
42
- * const [tags, setTags, ref] = useFormField(draft.tags);
45
+ * const [tags, setTags, ref] = useFieldState(draft.tags);
43
46
  * <div ref={ref}>
44
- * <input type="hidden" name="tags" value={tags.join(',')} />
47
+ * {tags.map((tag) => <input key={tag} type="hidden" name="tags" value={tag} />)}
45
48
  * <TagPicker value={tags} onChange={setTags} />
46
49
  * </div>
47
50
  * ```
48
51
  */
49
- export function useFormField<T>(
52
+ export function useFieldState<T>(
50
53
  defaultValue: T
51
54
  ): [value: T, setValue: Dispatch<SetStateAction<T>>, ref: RefCallback<HTMLElement>] {
52
55
  // `null` means "not edited": the field shows its default. A box, so an edit
@@ -107,9 +110,18 @@ export function useFormField<T>(
107
110
  if (!form) return;
108
111
  const onReset = (event: Event) => {
109
112
  pendingResets.current.push(event);
110
- // Dispatch is over by the time a microtask runs.
111
- queueMicrotask(() => {
113
+ const apply = () => {
112
114
  if (takeResets()) setEdit(null);
115
+ };
116
+ // A reset dispatched from script (`form.reset()`, React's post-action
117
+ // reset) is over by the time a microtask runs. A native one (a
118
+ // `type="reset"` button) is not: the browser drains microtasks
119
+ // between listeners, before React's delegated `onReset` has run. Then
120
+ // apply it in the next task, once dispatch has certainly ended. One
121
+ // task, not a loop: dispatch is synchronous within this one.
122
+ queueMicrotask(() => {
123
+ if (event.eventPhase === Event.NONE) apply();
124
+ else setTimeout(apply, 0);
113
125
  });
114
126
  };
115
127
  form.addEventListener('reset', onReset);
@@ -56,34 +56,31 @@ export interface TimberUserConfig {
56
56
  forms?: {
57
57
  /**
58
58
  * Strip sensitive fields (passwords, tokens, CVV, SSN, etc.) from the
59
- * `submittedValues` echoed back when an action fails (a validation
60
- * failure, or a `serverError` from a form submission).
59
+ * `submittedValues` a `createActionClient` action echoes back when it
60
+ * fails (a validation failure, or a `serverError` from a form submission).
61
+ * A raw `'use server'` action's return value is never changed.
61
62
  *
62
- * Applied to both the with-JS (`createActionClient`) and no-JS (form POST
63
- * re-render) paths. Safe-by-default: the built-in deny-list is active
64
- * unless you explicitly opt out.
63
+ * Hygiene, not a security boundary: the echo only returns to the user who
64
+ * typed it. Stripping keeps credentials out of the re-rendered form (and,
65
+ * without JS, out of the page's HTML), so they come back empty.
65
66
  *
66
67
  * - `true` / omitted — use the built-in deny-list (default, recommended).
67
- * - `false` — do not strip anything. Dev convenience only; never do this
68
- * in production — plaintext passwords end up in `defaultValue` attributes,
69
- * browser history, proxy logs, and the back-forward cache.
68
+ * - `false` — strip no field by name. Fields the action's schema marks
69
+ * `.meta({ sensitive: true })` are still stripped.
70
70
  * - `string[]` — additional field names to strip, merged with the built-in list.
71
71
  *
72
- * The built-in list matches (case-insensitive, substring match on
73
- * normalized names) the following patterns: password / passwd / pwd,
74
- * secret, apiKey, accessToken, refreshToken, cvv, cvc, cardNumber,
75
- * cardCvc, ssn, socialSecurityNumber, otp, totp, mfaCode, twoFactorCode,
76
- * privateKey — plus exact match on `token` (exact-only to avoid
77
- * false positives on `csrfToken`).
72
+ * The built-in list (passwords, tokens, card numbers, SSNs, one-time
73
+ * codes, keys) is in `server/sensitive-fields.ts` and documented in
74
+ * design/08-forms-and-actions.md §"Sensitive field stripping".
78
75
  *
79
76
  * **Function predicates are not supported at the global level** because
80
77
  * `timber.config.ts` is JSON-serialized into the runtime config and
81
78
  * functions cannot cross that boundary. For custom predicates, use
82
- * the per-action override: `createActionClient({ stripSensitiveFields:
83
- * (name) => ... })` (functions are supported at the per-action level
84
- * since `createActionClient` runs in the same module graph as user code).
79
+ * the per-client override: `createActionClient({ stripSensitiveFields:
80
+ * (name) => ... })` (functions are supported there since
81
+ * `createActionClient` runs in the same module graph as user code).
85
82
  *
86
- * See TIM-816.
83
+ * See TIM-816, TIM-1584.
87
84
  */
88
85
  stripSensitiveFields?: boolean | readonly string[];
89
86
  };
@@ -22,7 +22,6 @@ import type { Plugin, ResolvedConfig } from 'vite';
22
22
  import type { PluginContext } from '../plugin-context.ts';
23
23
  import { EMPTY_BUILD_MANIFEST, type BuildManifest } from '../server/build-manifest.ts';
24
24
  import type { SegmentNode, RouteFile } from '../routing/types.ts';
25
- import { isDynamicMetadataExtension } from '../server/metadata-routes.ts';
26
25
 
27
26
  // Rollup types used by generateBundle hook — imported from vite which re-exports them.
28
27
  // We define minimal interfaces here to avoid a direct 'rollup' dependency.
@@ -217,36 +216,22 @@ function collectTransitiveBundleDeps(
217
216
  }
218
217
 
219
218
  /**
220
- * Walk the route tree and compute short content hashes for metadata route files
221
- * (opengraph-image, icon, apple-icon) used for cache-busting
222
- * the auto-linked URLs in <head>.
219
+ * Walk the route tree and compute short content hashes for metadata route
220
+ * files, used to cache-bust the auto-linked opengraph-image URL in <head>.
221
+ * A dynamic handler (.ts/.tsx) is hashed by its source: its output can depend
222
+ * on runtime data too, but the source is the best build-time signal there is.
223
+ * An unreadable file gets no hash, and the link falls back to the per-startup
224
+ * nonce.
223
225
  */
224
226
  function computeMetadataRouteHashes(node: SegmentNode<RouteFile>): Record<string, string> {
225
227
  const hashes: Record<string, string> = {};
226
228
 
227
- if (node.metadataRoutes) {
228
- for (const [baseName, file] of Object.entries(node.metadataRoutes)) {
229
- if (!isDynamicMetadataExtension(baseName, file.extension)) {
230
- // For static files, hash the file content
231
- try {
232
- const content = readFileSync(file.filePath);
233
- const hash = createHash('sha256').update(content).digest('hex').slice(0, 8);
234
- hashes[file.filePath] = hash;
235
- } catch {
236
- // File unreadable — skip hash, DEV_NONCE fallback applies
237
- }
238
- } else {
239
- // For dynamic files (.ts/.tsx), hash the source file as a reasonable
240
- // approximation — the output depends on runtime data too, but the
241
- // source change is the best build-time signal we have.
242
- try {
243
- const content = readFileSync(file.filePath);
244
- const hash = createHash('sha256').update(content).digest('hex').slice(0, 8);
245
- hashes[file.filePath] = hash;
246
- } catch {
247
- // File unreadable — skip
248
- }
249
- }
229
+ for (const file of Object.values(node.metadataRoutes ?? {})) {
230
+ try {
231
+ const content = readFileSync(file.filePath);
232
+ hashes[file.filePath] = createHash('sha256').update(content).digest('hex').slice(0, 8);
233
+ } catch {
234
+ // File unreadable — skip hash, dev nonce fallback applies
250
235
  }
251
236
  }
252
237
 
@@ -99,7 +99,6 @@ export const SERVER_STUB_EXPORTS: readonly string[] = [
99
99
  // action-client
100
100
  'createActionClient',
101
101
  'ActionError',
102
- 'validated',
103
102
  // form-data
104
103
  'coerce',
105
104
  'parseFormData',