@vulcantech/forms 0.2.0 → 0.3.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.
package/README.md CHANGED
@@ -62,7 +62,7 @@ For `booking`, the CMS resolves the booking date in three steps: `bookingConfig.
62
62
 
63
63
  Your `apiRoute` is expected to be a **server-side proxy in your own app** that adds the credentials and forwards to the CMS `POST /api/contact`. The renderer never sends `projectId`, `apiKey`, or `url` — the proxy adds those. Forward the browser's body through **whole**; hand-picking fields into a new object is what silently destroys leads once the CMS re-validates the definition's required fields.
64
64
 
65
- Other `DynamicForm` props: `onSuccess(data?)` (receives the parsed response body — this is how you read `referenceNumber`), `onError(error)`, `extraData`, `className`, `onFormView` / `onFormSubmit` (analytics; they fall back to `window.__vtTrack` so a site running `@vulcantech/analytics` tracks conversions with no wiring), `transportKeyEndpoint`, and the `preview*` props used only by the CMS builder.
65
+ Other `DynamicForm` props: `onSuccess(data?)` (receives the parsed response body — this is how you read `referenceNumber`), `onError(error)`, `extraData`, `className`, `onFileUpload` / `fileUploadRoute` (required for `file` fields — see [Field types needing extra wiring](#field-types-needing-extra-wiring)), `onFormView` / `onFormSubmit` (analytics; they fall back to `window.__vtTrack` so a site running `@vulcantech/analytics` tracks conversions with no wiring), `transportKeyEndpoint`, and the `preview*` props used only by the CMS builder.
66
66
 
67
67
  ### Two CMS rejections that will bite you
68
68
 
@@ -84,7 +84,36 @@ Other CMS statuses reach `onError` with the server's `error` string as the messa
84
84
  ### Field types needing extra wiring
85
85
 
86
86
  - **`sensitive`** — encrypted in the browser (RSA-OAEP + AES-GCM) before submission. The renderer fetches the wrapping key from `transportKeyEndpoint`, defaulting to **`/api/forms/transport-key` on the same origin**. That route exists in the CMS, not in consumer apps, so a site with a sensitive field must either proxy it or pass an absolute CMS URL. Values arrive at the CMS as envelopes, get re-encrypted with KMS into an isolated `sensitive_data` collection, and the submission keeps only `{ sensitiveDataId, last4 }`. An envelope on a field the definition doesn't declare sensitive is rejected with `400 {"error":"Failed to process sensitive fields"}` — the usual cause is a wrong or missing `formId`.
87
- - **`file`** — the value submitted is a URL string (or an array of them when `multiple`), never file bytes; the CMS stores it as an ordinary string. **`FileField`'s `onUpload` prop is not currently threaded through `DynamicForm`**, so file fields rendered by `DynamicForm` fall back to `URL.createObjectURL` and submit a `blob:` URL that is meaningless outside the submitting tab. Render `FileField` directly with an `onUpload` handler if you need real uploads.
87
+ - **`file`** — the value submitted is a URL string (or an array of them when `multiple`), never file bytes; the CMS stores it as an ordinary string. **Uploads are not automatic**: this package ships no default uploader, because a public form submitter holds no CMS credentials. Give `DynamicForm` an upload path, exactly as you give it an `apiRoute`:
88
+
89
+ ```tsx
90
+ <DynamicForm definition={def} apiRoute="/api/contact" fileUploadRoute="/api/form-upload" />
91
+ ```
92
+
93
+ `fileUploadRoute` is a route **in your own app**. It receives `POST` `multipart/form-data` with `file` (the File) and `formId`, and must answer `200 {"url": "https://…"}` (optionally `name`, `size`); on failure, answer non-2xx with `{"error": "…"}` and that message renders under the field. The returned `url` must be durable — a `blob:`/`data:` URL is rejected. For full control (a client-side SDK upload, a signed URL, progress of your own), pass `onFileUpload(file, config)` instead; it wins over `fileUploadRoute`.
94
+
95
+ **The standard implementation of that route is a thin proxy to the CMS** — copy it rather than inventing storage of your own. The CMS exposes `POST /api/forms/upload`, the credentialed counterpart to `/api/contact`: same apiKey + `url`-binding trust model, per-IP and per-project rate limits, a 10 MB hard cap, and a content-type allowlist verified against the file's magic bytes (no SVG, no HTML — both execute script when opened from the storage origin). Files land under `forms/{projectId}/uploads/…`, never the media library, so lead attachments stay out of the staff media picker, and deleting a submission deletes its attachments with it. The response is `{ url, name, size }` where `url` is a non-expiring Firebase download-token URL — chosen over a signed URL because the value is persisted verbatim on the lead and staff may open it months later.
96
+
97
+ Your route's only job is to add the credentials the browser must never hold:
98
+
99
+ ```ts
100
+ // app/api/form-upload/route.ts
101
+ const outgoing = new FormData();
102
+ outgoing.append("file", file, file.name);
103
+ outgoing.append("formId", formId);
104
+ outgoing.append("projectId", process.env.VULCANTECH_PROJECT_ID!);
105
+ outgoing.append("apiKey", process.env.VULCANTECH_API_KEY!);
106
+ outgoing.append("url", SITE_URL); // must equal the project's stored `url`
107
+ const res = await fetch(`${CMS_URL}/api/forms/upload`, { method: "POST", body: outgoing });
108
+ ```
109
+
110
+ Relay the CMS's `error` string verbatim on a non-2xx — it renders under the field, and a message like "That file's contents don't match its type" is worth the user seeing. `apps/castlerents/src/app/api/form-upload/route.ts` is the reference copy. The API key needs the `contact:write` scope (an attachment is part of a submission, so there is no new scope to provision), and — exactly as with `/api/contact` — the `url` must match the project's stored `url`, which is why localhost dev uploads always 400.
111
+
112
+ With **neither** prop set, the picker renders disabled and says so, and nothing is submitted. That is deliberate: the field previously fell back to `URL.createObjectURL` and submitted a `blob:` URL, which looked like a successful upload and arrived as an unopenable attachment on the lead. `DynamicForm` also aborts any submission still carrying a `blob:`/`data:` value rather than storing a dead link. The CMS form builder's live preview is the one exception — it keeps the local stand-in, since its submissions never leave the browser.
113
+
114
+ `FileField` is also exported for use outside `DynamicForm`, taking the same handler as an `onUpload` prop.
115
+
116
+ `fileConfig.resizeImages` (default **true**) downscales images in the browser before they reach your handler, to `fileConfig.maxImageWidth` (default **1600**). It only touches JPEG/PNG/WebP wider than the limit, keeps the original format, and hands the file over untouched if anything about the round-trip fails — GIF is skipped so an animation isn't flattened to its first frame, and HEIC/HEIF because only Safari decodes it. `maxSizeBytes` is checked against the **resized** file, so a photo that only fits once downscaled is accepted. Set `resizeImages: false` if your handler wants the original bytes.
88
117
 
89
118
  ## Integration
90
119
 
@@ -131,10 +160,12 @@ export function ContactForm({ definition }: { definition?: FormDefinition }) {
131
160
  }
132
161
  ```
133
162
 
134
- **7. ISR invalidation** — ensure `src/app/api/revalidate/route.ts` exists; the CMS purges `form:{projectId}:{formId}` (single) and `forms:{projectId}` (list) on edit.
163
+ **7. ISR invalidation** — ensure `src/app/api/revalidate/route.ts` exists, set `VULCANTECH_REVALIDATE_SECRET`, and register the site under **Settings → Form Consumers (ISR Revalidation)** in the CMS. The CMS purges `form:{projectId}:{formId}` (single) and `forms:{projectId}` (list) on edit. This is the same route and consumer entry the blog, banners, and SEO-files dispatchers use — one per site. Route contract and reference copy: the `@vulcantech/cms` README, [ISR revalidation](../cms/README.md#isr-revalidation).
164
+
165
+ **8. File-upload proxy (only if any form has a `file` field)** — add `src/app/api/form-upload/route.ts` and pass `fileUploadRoute="/api/form-upload"` alongside `apiRoute`. The route re-posts the multipart body to the CMS `/api/forms/upload` with `projectId` / `apiKey` / `url` attached server-side, and relays the CMS's `error` string on failure. See [Field types needing extra wiring](#field-types-needing-extra-wiring) for the full contract and `apps/castlerents/src/app/api/form-upload/route.ts` for the reference copy. Without it a `file` field renders a disabled picker saying uploads aren't configured.
135
166
 
136
167
  ### Required env
137
- `VULCANTECH_PROJECT_ID`, `VULCANTECH_API_KEY` (required) · `VULCANTECH_CMS_URL` (optional) · `VULCANTECH_FORMS_NO_CACHE` (optional, `1`/`true` to bypass ISR).
168
+ `VULCANTECH_PROJECT_ID`, `VULCANTECH_API_KEY` (required) · `VULCANTECH_REVALIDATE_SECRET` (required for instant ISR purges; see step 7) · `VULCANTECH_CMS_URL` (optional) · `VULCANTECH_FORMS_NO_CACHE` (optional, `1`/`true` to bypass ISR).
138
169
 
139
170
  ### Per-app values
140
171
  - **Form definition ID(s)** — Firestore doc id from the CMS admin (one per form), pinned in `load<Name>Form.ts` (e.g. `CONTACT_FORM_ID`, `SERVICE_REQUEST_FORM_ID`).
package/dist/index.d.mts CHANGED
@@ -74,17 +74,17 @@ interface SensitiveFieldConfig {
74
74
  }
75
75
  declare const DEFAULT_SENSITIVE_FIELD_CONFIG: SensitiveFieldConfig;
76
76
  /**
77
- * Configuration for the `file` field type. Files are uploaded to
78
- * Firebase Storage client-side; the form submission receives the
79
- * download URL(s) rather than raw file data — a string, or an array of
80
- * strings when `multiple`. The CMS stores whatever string arrives and does
81
- * nothing file-specific with it.
77
+ * Configuration for the `file` field type. Files are uploaded by the
78
+ * consuming app before submit; the form submission receives the resulting
79
+ * URL(s) rather than raw file data — a string, or an array of strings when
80
+ * `multiple`. The CMS stores whatever string arrives and does nothing
81
+ * file-specific with it.
82
82
  *
83
- * KNOWN LIMITATION: `FileField`'s `onUpload` prop is not threaded through
84
- * `DynamicFormField`, so a file field rendered via `DynamicForm` falls back
85
- * to `URL.createObjectURL` and submits a `blob:` URL that is meaningless
86
- * outside the submitting tab. Render `FileField` directly with an `onUpload`
87
- * handler when real uploads are needed.
83
+ * Uploads are NOT automatic: a form containing a `file` field must be given
84
+ * an upload path via `DynamicForm`'s `onFileUpload` or `fileUploadRoute`
85
+ * prop (see {@link FormFileUploadHandler}). Without one the picker renders
86
+ * disabled with an explanatory message rather than silently submitting a
87
+ * throwaway `blob:` URL.
88
88
  */
89
89
  interface FileFieldConfig {
90
90
  /** Accepted MIME types. Default: "image/*" */
@@ -96,14 +96,48 @@ interface FileFieldConfig {
96
96
  /** Max number of files when multiple=true. Default: 5. */
97
97
  maxFiles?: number;
98
98
  /**
99
- * Resize images before upload. Default: true.
100
- * When true, images are scaled to maxImageWidth and compressed.
99
+ * Downscale images in the browser before handing them to the upload
100
+ * handler. Default: true.
101
+ *
102
+ * Applies only to JPEG, PNG and WebP, and only when the image is wider
103
+ * than {@link FileFieldConfig.maxImageWidth}; the format is preserved and
104
+ * anything that can't be re-encoded (GIF — a canvas round-trip would drop
105
+ * the animation, HEIC/HEIF, SVG, a file this browser can't decode) is
106
+ * uploaded untouched. `maxSizeBytes` is checked against the resized file,
107
+ * so a large photo that fits once downscaled is accepted.
101
108
  */
102
109
  resizeImages?: boolean;
103
- /** Max image width for resize. Default: 1600. */
110
+ /** Max image width in pixels when `resizeImages`. Default: 1600. */
104
111
  maxImageWidth?: number;
105
112
  }
106
113
  declare const DEFAULT_FILE_FIELD_CONFIG: FileFieldConfig;
114
+ /**
115
+ * A file that has finished uploading. `url` is the value the form submits
116
+ * for the field (or one entry of the array, when `multiple`), so it must be
117
+ * durable and reachable outside the submitting browser tab — never a
118
+ * `blob:` or `data:` URL.
119
+ */
120
+ interface UploadedFormFile {
121
+ /** Stored, publicly reachable URL. */
122
+ url: string;
123
+ /** Display name, shown in the field's file list. */
124
+ name: string;
125
+ /** Size in bytes, shown in the field's file list. */
126
+ size: number;
127
+ }
128
+ /**
129
+ * Uploads one picked file and resolves with its stored location.
130
+ *
131
+ * Supplied by the consuming app — this package deliberately ships no
132
+ * default implementation, because a public form submitter holds no CMS
133
+ * credentials. The usual shape mirrors `DynamicForm`'s `apiRoute`: POST the
134
+ * file to a server-side route in your own app, which holds the credentials
135
+ * and writes to storage, then return the stored URL.
136
+ *
137
+ * Called once per file, sequentially. Throw to fail the file — the message
138
+ * is shown inline under the picker and no value is recorded.
139
+ */
140
+ type FormFileUploadHandler = (file: File, config: FileFieldConfig) => Promise<UploadedFormFile>;
107
141
  interface FormFieldDefinition {
108
142
  id: string;
109
143
  type: FieldType;
@@ -497,6 +531,8 @@ interface FormFieldDefinitionJSON {
497
531
  datetimeConfig?: DatetimeConfig;
498
532
  showWhen?: FieldVisibilityCondition;
499
533
  sensitiveConfig?: SensitiveFieldConfigJSON;
534
+ /** No narrowed unions, so the strict type is reused. */
535
+ fileConfig?: FileFieldConfig;
500
536
  }
501
537
  interface FormSectionJSON {
502
538
  id: string;
@@ -723,6 +759,42 @@ declare function renderNotificationEmail(template: NotificationEmailTemplate, va
723
759
  html: string;
724
760
  };
725
761
 
762
+ /**
763
+ * Client-side image downscaling for `file` fields.
764
+ *
765
+ * A phone camera hands the picker a 4000px, several-megabyte photo for what
766
+ * is almost always displayed as a thumbnail on a lead. Downscaling in the
767
+ * browser — before the bytes leave it — is the only place that saves the
768
+ * submitter's upload time as well as our storage.
769
+ *
770
+ * The rule this module follows everywhere: **never lose a file to an
771
+ * optimisation.** Every failure path (an undecodable file, a browser without
772
+ * the APIs, an encoder that returns nothing, a re-encode that came out
773
+ * bigger) returns the original `File` unchanged, so the worst case is the
774
+ * behaviour we had before resizing existed.
775
+ */
776
+ /**
777
+ * Scale an image file down so it is at most `maxWidth` pixels wide,
778
+ * re-encoding it in its original format.
779
+ *
780
+ * Only images narrower-or-equal to the limit, unsupported formats, and files
781
+ * this environment cannot decode are left alone — everything else comes back
782
+ * as a new `File` carrying the same name, type and `lastModified`, so the
783
+ * upload handler and the CMS's magic-byte check see an ordinary picked file.
784
+ *
785
+ * EXIF orientation is baked into the pixels (`imageOrientation: "from-image"`),
786
+ * which is what a browser would have rendered anyway; the resized copy carries
787
+ * no EXIF of its own, so a rotated photo stays upright without the metadata
788
+ * that made it so.
789
+ *
790
+ * @param file - The picked file.
791
+ * @param maxWidth - Maximum width in pixels. Non-positive or non-finite
792
+ * values disable resizing.
793
+ * @returns The downscaled file, or the original when resizing was skipped or
794
+ * failed. Never rejects.
795
+ */
796
+ declare function resizeImageFile(file: File, maxWidth: number): Promise<File>;
797
+
726
798
  /**
727
799
  * Client-side encryption utilities for sensitive form fields.
728
800
  *
@@ -824,6 +896,35 @@ interface DynamicFormProps {
824
896
  onError?: (error: Error) => void;
825
897
  /** Extra top-level keys merged into the payload alongside the field values. */
826
898
  extraData?: Record<string, unknown>;
899
+ /**
900
+ * Upload path for `file` fields. Called once per picked file; resolve with
901
+ * the stored URL, which becomes the field's submitted value.
902
+ *
903
+ * There is no default — a public form submitter holds no CMS credentials,
904
+ * so the upload has to go through a route in the consuming app, exactly
905
+ * like {@link DynamicFormProps.apiRoute}. Use {@link DynamicFormProps.fileUploadRoute}
906
+ * for the standard multipart wiring, or this prop for full control.
907
+ *
908
+ * A definition containing a `file` field with neither prop set renders the
909
+ * picker disabled with an explanatory message — it will NOT fall back to a
910
+ * throwaway `blob:` URL, which used to look like a successful upload and
911
+ * arrive as an unopenable attachment on the lead.
912
+ */
913
+ onFileUpload?: FormFileUploadHandler;
914
+ /**
915
+ * Convenience alternative to {@link DynamicFormProps.onFileUpload}: an
916
+ * endpoint in the consuming app that accepts one file and returns its
917
+ * stored location.
918
+ *
919
+ * Request: `POST <fileUploadRoute>` with `multipart/form-data` carrying
920
+ * `file` (the File) and `formId` (the definition id).
921
+ * Response: `200` with JSON `{ url: string, name?: string, size?: number }`.
922
+ * `url` must be durable — a `blob:`/`data:` URL is rejected. On failure,
923
+ * answer non-2xx with `{ error }` and the message is shown under the field.
924
+ *
925
+ * Ignored when `onFileUpload` is set.
926
+ */
927
+ fileUploadRoute?: string;
827
928
  className?: string;
828
929
  /**
829
930
  * Endpoint that returns the RSA-OAEP transport public key used to wrap the
@@ -887,7 +988,7 @@ interface DynamicFormProps {
887
988
  * and a server-side spam catch both answer `200` and are indistinguishable
888
989
  * from a stored lead by design.
889
990
  */
890
- declare const DynamicForm: ({ definition, apiRoute, onSuccess, onError, extraData, className, onFormView, onFormSubmit: onFormSubmitCallback, transportKeyEndpoint, previewState, previewTouchAllSignal, previewUntouchAllSignal, previewBg, previewTextColor, }: DynamicFormProps) => react.JSX.Element;
991
+ declare const DynamicForm: ({ definition, apiRoute, onSuccess, onError, extraData, onFileUpload, fileUploadRoute, className, onFormView, onFormSubmit: onFormSubmitCallback, transportKeyEndpoint, previewState, previewTouchAllSignal, previewUntouchAllSignal, previewBg, previewTextColor, }: DynamicFormProps) => react.JSX.Element;
891
992
 
892
993
  /**
893
994
  * Single source of truth for the CSS custom properties the renderer publishes
@@ -959,6 +1060,47 @@ declare const FORM_VAR: {
959
1060
  */
960
1061
  declare function buildFormCssVars(style: FormStyle, previewBg?: string): CSSProperties;
961
1062
 
1063
+ /**
1064
+ * The upload path `DynamicForm` publishes to the `file` fields beneath it.
1065
+ *
1066
+ * Threaded by context rather than by prop because `FileField` sits two
1067
+ * levels down (section → field) and no intermediate component has any other
1068
+ * reason to know about uploads.
1069
+ */
1070
+ interface FormFileUploadContextValue {
1071
+ /**
1072
+ * Uploads a picked file and returns its stored URL. Undefined means the
1073
+ * consuming app wired no upload path — file fields then render disabled
1074
+ * instead of submitting an unusable value.
1075
+ */
1076
+ upload?: FormFileUploadHandler;
1077
+ /**
1078
+ * Builder-preview escape hatch: allows `FileField` to stand in a local
1079
+ * `URL.createObjectURL` value when no `upload` is set. Only ever true in
1080
+ * the CMS form builder, where submissions are short-circuited and the
1081
+ * throwaway URL can't reach a lead.
1082
+ */
1083
+ allowObjectUrlFallback?: boolean;
1084
+ }
1085
+ declare const useFormFileUpload: () => FormFileUploadContextValue;
1086
+ declare const FormFileUploadProvider: react.Provider<FormFileUploadContextValue>;
1087
+
1088
+ interface Props$2 {
1089
+ field: FormFieldDefinition;
1090
+ /** Project ID for storage path. Passed from the form renderer. */
1091
+ projectId?: string;
1092
+ /**
1093
+ * Upload handler. Normally supplied through `DynamicForm`'s
1094
+ * `onFileUpload` / `fileUploadRoute` prop (delivered by context); pass it
1095
+ * here when rendering `FileField` outside a `DynamicForm`. This prop wins
1096
+ * over the context value.
1097
+ */
1098
+ onUpload?: FormFileUploadHandler;
1099
+ /** When true (mirrored/locked), the picker is read-only. */
1100
+ disabled?: boolean;
1101
+ }
1102
+ declare const FileField: ({ field: fieldDef, onUpload, disabled }: Props$2) => react.JSX.Element;
1103
+
962
1104
  interface Props$1 {
963
1105
  section: FormSection;
964
1106
  isLast?: boolean;
@@ -1107,4 +1249,4 @@ interface UseDragReorderResult extends DragReorderState {
1107
1249
  */
1108
1250
  declare function useDragReorder<T>({ items, getId, onReorder, dragType, }: UseDragReorderOptions<T>): UseDragReorderResult;
1109
1251
 
1110
- export { APPLICATION_STATUS_KEYS, type ApplicationStatusEmailTemplates, type ApplicationStatusKey, CORE_EMAIL_TEMPLATE_VARIABLES, DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES, DEFAULT_FILE_FIELD_CONFIG, DEFAULT_FORM_STYLE, DEFAULT_NOTIFICATION_EMAIL_HTML, DEFAULT_NOTIFICATION_EMAIL_SUBJECT, DEFAULT_NOTIFICATION_EMAIL_TEMPLATE, DEFAULT_SENSITIVE_FIELD_CONFIG, DEFAULT_SPAM_PROTECTION, type DatetimeConfig, type DragReorderItemHandlers, type DragReorderState, type DropPosition, DynamicForm, DynamicFormField, DynamicFormSection, type EmailTemplateVariableDescriptor, type EmailTemplateVariables, type EncryptedSensitiveValue, FORM_CSS_VAR, FORM_DEFAULT_COLOR, FORM_VAR, type FieldOption, type FieldTransform, type FieldType, type FieldVisibilityCondition, type FieldWidth, type FileFieldConfig, type FormBookingConfig, type FormDefinition, type FormDefinitionJSON, type FormFieldDefinition, type FormFieldDefinitionJSON, type FormIdentifier, type FormIntegrationConfig, type FormIntegrationConfigJSON, type FormIntegrations, type FormIntegrationsJSON, type FormSection, type FormSectionJSON, type FormSpamProtectionConfig, type FormStatus, type FormStyle, type FormStyleJSON, type FormStylePreset, type FormSubmissionType, type FormSubmitConfig, type FormSubmitConfigJSON, type FormSuccessBehavior, HONEYPOT_FIELD_NAME, type InputVariant, type IntegrationFieldMappingEntry, type IntegrationFieldMappingEntryJSON, NEWSLETTER_ALLOWED_FIELD_TYPES, type NotificationEmailTemplate, SAME_AS_TOGGLE_PREFIX, SAMPLE_EMAIL_TEMPLATE_VARIABLES, type SectionSameAsConfig, type SensitiveFieldConfig, type SensitiveFieldConfigJSON, type SetStateUpdater, type TextTransform, type TransportPublicKey, type UseDragReorderOptions, type UseDragReorderResult, type UseFormDefinitionOptions, type UseUndoRedoControls, type UseUndoRedoOptions, type UseUndoRedoReturn, type ValidationRule, type ValidationRuleJSON, type VisibilityOperator, applyTextTransform, applyTransform, base64ToBuffer, bufferToBase64, buildEmailTemplateVariables, buildFormCssVars, buildInitialValues, buildYupSchema, deriveLast4, encryptSensitiveValue, formatSsn, formatUsPhone, getFormDefinition, getSafeRedirectUrl, isVisibilityConditionMet, parseFormDefinition, renderEmailTemplate, renderNotificationEmail, sameAsToggleKey, useDragReorder, useFormDefinition, useUndoRedo, useUndoRedoShortcuts };
1252
+ export { APPLICATION_STATUS_KEYS, type ApplicationStatusEmailTemplates, type ApplicationStatusKey, CORE_EMAIL_TEMPLATE_VARIABLES, DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES, DEFAULT_FILE_FIELD_CONFIG, DEFAULT_FORM_STYLE, DEFAULT_NOTIFICATION_EMAIL_HTML, DEFAULT_NOTIFICATION_EMAIL_SUBJECT, DEFAULT_NOTIFICATION_EMAIL_TEMPLATE, DEFAULT_SENSITIVE_FIELD_CONFIG, DEFAULT_SPAM_PROTECTION, type DatetimeConfig, type DragReorderItemHandlers, type DragReorderState, type DropPosition, DynamicForm, DynamicFormField, DynamicFormSection, type EmailTemplateVariableDescriptor, type EmailTemplateVariables, type EncryptedSensitiveValue, FORM_CSS_VAR, FORM_DEFAULT_COLOR, FORM_VAR, type FieldOption, type FieldTransform, type FieldType, type FieldVisibilityCondition, type FieldWidth, FileField, type FileFieldConfig, type FormBookingConfig, type FormDefinition, type FormDefinitionJSON, type FormFieldDefinition, type FormFieldDefinitionJSON, type FormFileUploadContextValue, type FormFileUploadHandler, FormFileUploadProvider, type FormIdentifier, type FormIntegrationConfig, type FormIntegrationConfigJSON, type FormIntegrations, type FormIntegrationsJSON, type FormSection, type FormSectionJSON, type FormSpamProtectionConfig, type FormStatus, type FormStyle, type FormStyleJSON, type FormStylePreset, type FormSubmissionType, type FormSubmitConfig, type FormSubmitConfigJSON, type FormSuccessBehavior, HONEYPOT_FIELD_NAME, type InputVariant, type IntegrationFieldMappingEntry, type IntegrationFieldMappingEntryJSON, NEWSLETTER_ALLOWED_FIELD_TYPES, type NotificationEmailTemplate, SAME_AS_TOGGLE_PREFIX, SAMPLE_EMAIL_TEMPLATE_VARIABLES, type SectionSameAsConfig, type SensitiveFieldConfig, type SensitiveFieldConfigJSON, type SetStateUpdater, type TextTransform, type TransportPublicKey, type UploadedFormFile, type UseDragReorderOptions, type UseDragReorderResult, type UseFormDefinitionOptions, type UseUndoRedoControls, type UseUndoRedoOptions, type UseUndoRedoReturn, type ValidationRule, type ValidationRuleJSON, type VisibilityOperator, applyTextTransform, applyTransform, base64ToBuffer, bufferToBase64, buildEmailTemplateVariables, buildFormCssVars, buildInitialValues, buildYupSchema, deriveLast4, encryptSensitiveValue, formatSsn, formatUsPhone, getFormDefinition, getSafeRedirectUrl, isVisibilityConditionMet, parseFormDefinition, renderEmailTemplate, renderNotificationEmail, resizeImageFile, sameAsToggleKey, useDragReorder, useFormDefinition, useFormFileUpload, useUndoRedo, useUndoRedoShortcuts };
package/dist/index.d.ts CHANGED
@@ -74,17 +74,17 @@ interface SensitiveFieldConfig {
74
74
  }
75
75
  declare const DEFAULT_SENSITIVE_FIELD_CONFIG: SensitiveFieldConfig;
76
76
  /**
77
- * Configuration for the `file` field type. Files are uploaded to
78
- * Firebase Storage client-side; the form submission receives the
79
- * download URL(s) rather than raw file data — a string, or an array of
80
- * strings when `multiple`. The CMS stores whatever string arrives and does
81
- * nothing file-specific with it.
77
+ * Configuration for the `file` field type. Files are uploaded by the
78
+ * consuming app before submit; the form submission receives the resulting
79
+ * URL(s) rather than raw file data — a string, or an array of strings when
80
+ * `multiple`. The CMS stores whatever string arrives and does nothing
81
+ * file-specific with it.
82
82
  *
83
- * KNOWN LIMITATION: `FileField`'s `onUpload` prop is not threaded through
84
- * `DynamicFormField`, so a file field rendered via `DynamicForm` falls back
85
- * to `URL.createObjectURL` and submits a `blob:` URL that is meaningless
86
- * outside the submitting tab. Render `FileField` directly with an `onUpload`
87
- * handler when real uploads are needed.
83
+ * Uploads are NOT automatic: a form containing a `file` field must be given
84
+ * an upload path via `DynamicForm`'s `onFileUpload` or `fileUploadRoute`
85
+ * prop (see {@link FormFileUploadHandler}). Without one the picker renders
86
+ * disabled with an explanatory message rather than silently submitting a
87
+ * throwaway `blob:` URL.
88
88
  */
89
89
  interface FileFieldConfig {
90
90
  /** Accepted MIME types. Default: "image/*" */
@@ -96,14 +96,48 @@ interface FileFieldConfig {
96
96
  /** Max number of files when multiple=true. Default: 5. */
97
97
  maxFiles?: number;
98
98
  /**
99
- * Resize images before upload. Default: true.
100
- * When true, images are scaled to maxImageWidth and compressed.
99
+ * Downscale images in the browser before handing them to the upload
100
+ * handler. Default: true.
101
+ *
102
+ * Applies only to JPEG, PNG and WebP, and only when the image is wider
103
+ * than {@link FileFieldConfig.maxImageWidth}; the format is preserved and
104
+ * anything that can't be re-encoded (GIF — a canvas round-trip would drop
105
+ * the animation, HEIC/HEIF, SVG, a file this browser can't decode) is
106
+ * uploaded untouched. `maxSizeBytes` is checked against the resized file,
107
+ * so a large photo that fits once downscaled is accepted.
101
108
  */
102
109
  resizeImages?: boolean;
103
- /** Max image width for resize. Default: 1600. */
110
+ /** Max image width in pixels when `resizeImages`. Default: 1600. */
104
111
  maxImageWidth?: number;
105
112
  }
106
113
  declare const DEFAULT_FILE_FIELD_CONFIG: FileFieldConfig;
114
+ /**
115
+ * A file that has finished uploading. `url` is the value the form submits
116
+ * for the field (or one entry of the array, when `multiple`), so it must be
117
+ * durable and reachable outside the submitting browser tab — never a
118
+ * `blob:` or `data:` URL.
119
+ */
120
+ interface UploadedFormFile {
121
+ /** Stored, publicly reachable URL. */
122
+ url: string;
123
+ /** Display name, shown in the field's file list. */
124
+ name: string;
125
+ /** Size in bytes, shown in the field's file list. */
126
+ size: number;
127
+ }
128
+ /**
129
+ * Uploads one picked file and resolves with its stored location.
130
+ *
131
+ * Supplied by the consuming app — this package deliberately ships no
132
+ * default implementation, because a public form submitter holds no CMS
133
+ * credentials. The usual shape mirrors `DynamicForm`'s `apiRoute`: POST the
134
+ * file to a server-side route in your own app, which holds the credentials
135
+ * and writes to storage, then return the stored URL.
136
+ *
137
+ * Called once per file, sequentially. Throw to fail the file — the message
138
+ * is shown inline under the picker and no value is recorded.
139
+ */
140
+ type FormFileUploadHandler = (file: File, config: FileFieldConfig) => Promise<UploadedFormFile>;
107
141
  interface FormFieldDefinition {
108
142
  id: string;
109
143
  type: FieldType;
@@ -497,6 +531,8 @@ interface FormFieldDefinitionJSON {
497
531
  datetimeConfig?: DatetimeConfig;
498
532
  showWhen?: FieldVisibilityCondition;
499
533
  sensitiveConfig?: SensitiveFieldConfigJSON;
534
+ /** No narrowed unions, so the strict type is reused. */
535
+ fileConfig?: FileFieldConfig;
500
536
  }
501
537
  interface FormSectionJSON {
502
538
  id: string;
@@ -723,6 +759,42 @@ declare function renderNotificationEmail(template: NotificationEmailTemplate, va
723
759
  html: string;
724
760
  };
725
761
 
762
+ /**
763
+ * Client-side image downscaling for `file` fields.
764
+ *
765
+ * A phone camera hands the picker a 4000px, several-megabyte photo for what
766
+ * is almost always displayed as a thumbnail on a lead. Downscaling in the
767
+ * browser — before the bytes leave it — is the only place that saves the
768
+ * submitter's upload time as well as our storage.
769
+ *
770
+ * The rule this module follows everywhere: **never lose a file to an
771
+ * optimisation.** Every failure path (an undecodable file, a browser without
772
+ * the APIs, an encoder that returns nothing, a re-encode that came out
773
+ * bigger) returns the original `File` unchanged, so the worst case is the
774
+ * behaviour we had before resizing existed.
775
+ */
776
+ /**
777
+ * Scale an image file down so it is at most `maxWidth` pixels wide,
778
+ * re-encoding it in its original format.
779
+ *
780
+ * Only images narrower-or-equal to the limit, unsupported formats, and files
781
+ * this environment cannot decode are left alone — everything else comes back
782
+ * as a new `File` carrying the same name, type and `lastModified`, so the
783
+ * upload handler and the CMS's magic-byte check see an ordinary picked file.
784
+ *
785
+ * EXIF orientation is baked into the pixels (`imageOrientation: "from-image"`),
786
+ * which is what a browser would have rendered anyway; the resized copy carries
787
+ * no EXIF of its own, so a rotated photo stays upright without the metadata
788
+ * that made it so.
789
+ *
790
+ * @param file - The picked file.
791
+ * @param maxWidth - Maximum width in pixels. Non-positive or non-finite
792
+ * values disable resizing.
793
+ * @returns The downscaled file, or the original when resizing was skipped or
794
+ * failed. Never rejects.
795
+ */
796
+ declare function resizeImageFile(file: File, maxWidth: number): Promise<File>;
797
+
726
798
  /**
727
799
  * Client-side encryption utilities for sensitive form fields.
728
800
  *
@@ -824,6 +896,35 @@ interface DynamicFormProps {
824
896
  onError?: (error: Error) => void;
825
897
  /** Extra top-level keys merged into the payload alongside the field values. */
826
898
  extraData?: Record<string, unknown>;
899
+ /**
900
+ * Upload path for `file` fields. Called once per picked file; resolve with
901
+ * the stored URL, which becomes the field's submitted value.
902
+ *
903
+ * There is no default — a public form submitter holds no CMS credentials,
904
+ * so the upload has to go through a route in the consuming app, exactly
905
+ * like {@link DynamicFormProps.apiRoute}. Use {@link DynamicFormProps.fileUploadRoute}
906
+ * for the standard multipart wiring, or this prop for full control.
907
+ *
908
+ * A definition containing a `file` field with neither prop set renders the
909
+ * picker disabled with an explanatory message — it will NOT fall back to a
910
+ * throwaway `blob:` URL, which used to look like a successful upload and
911
+ * arrive as an unopenable attachment on the lead.
912
+ */
913
+ onFileUpload?: FormFileUploadHandler;
914
+ /**
915
+ * Convenience alternative to {@link DynamicFormProps.onFileUpload}: an
916
+ * endpoint in the consuming app that accepts one file and returns its
917
+ * stored location.
918
+ *
919
+ * Request: `POST <fileUploadRoute>` with `multipart/form-data` carrying
920
+ * `file` (the File) and `formId` (the definition id).
921
+ * Response: `200` with JSON `{ url: string, name?: string, size?: number }`.
922
+ * `url` must be durable — a `blob:`/`data:` URL is rejected. On failure,
923
+ * answer non-2xx with `{ error }` and the message is shown under the field.
924
+ *
925
+ * Ignored when `onFileUpload` is set.
926
+ */
927
+ fileUploadRoute?: string;
827
928
  className?: string;
828
929
  /**
829
930
  * Endpoint that returns the RSA-OAEP transport public key used to wrap the
@@ -887,7 +988,7 @@ interface DynamicFormProps {
887
988
  * and a server-side spam catch both answer `200` and are indistinguishable
888
989
  * from a stored lead by design.
889
990
  */
890
- declare const DynamicForm: ({ definition, apiRoute, onSuccess, onError, extraData, className, onFormView, onFormSubmit: onFormSubmitCallback, transportKeyEndpoint, previewState, previewTouchAllSignal, previewUntouchAllSignal, previewBg, previewTextColor, }: DynamicFormProps) => react.JSX.Element;
991
+ declare const DynamicForm: ({ definition, apiRoute, onSuccess, onError, extraData, onFileUpload, fileUploadRoute, className, onFormView, onFormSubmit: onFormSubmitCallback, transportKeyEndpoint, previewState, previewTouchAllSignal, previewUntouchAllSignal, previewBg, previewTextColor, }: DynamicFormProps) => react.JSX.Element;
891
992
 
892
993
  /**
893
994
  * Single source of truth for the CSS custom properties the renderer publishes
@@ -959,6 +1060,47 @@ declare const FORM_VAR: {
959
1060
  */
960
1061
  declare function buildFormCssVars(style: FormStyle, previewBg?: string): CSSProperties;
961
1062
 
1063
+ /**
1064
+ * The upload path `DynamicForm` publishes to the `file` fields beneath it.
1065
+ *
1066
+ * Threaded by context rather than by prop because `FileField` sits two
1067
+ * levels down (section → field) and no intermediate component has any other
1068
+ * reason to know about uploads.
1069
+ */
1070
+ interface FormFileUploadContextValue {
1071
+ /**
1072
+ * Uploads a picked file and returns its stored URL. Undefined means the
1073
+ * consuming app wired no upload path — file fields then render disabled
1074
+ * instead of submitting an unusable value.
1075
+ */
1076
+ upload?: FormFileUploadHandler;
1077
+ /**
1078
+ * Builder-preview escape hatch: allows `FileField` to stand in a local
1079
+ * `URL.createObjectURL` value when no `upload` is set. Only ever true in
1080
+ * the CMS form builder, where submissions are short-circuited and the
1081
+ * throwaway URL can't reach a lead.
1082
+ */
1083
+ allowObjectUrlFallback?: boolean;
1084
+ }
1085
+ declare const useFormFileUpload: () => FormFileUploadContextValue;
1086
+ declare const FormFileUploadProvider: react.Provider<FormFileUploadContextValue>;
1087
+
1088
+ interface Props$2 {
1089
+ field: FormFieldDefinition;
1090
+ /** Project ID for storage path. Passed from the form renderer. */
1091
+ projectId?: string;
1092
+ /**
1093
+ * Upload handler. Normally supplied through `DynamicForm`'s
1094
+ * `onFileUpload` / `fileUploadRoute` prop (delivered by context); pass it
1095
+ * here when rendering `FileField` outside a `DynamicForm`. This prop wins
1096
+ * over the context value.
1097
+ */
1098
+ onUpload?: FormFileUploadHandler;
1099
+ /** When true (mirrored/locked), the picker is read-only. */
1100
+ disabled?: boolean;
1101
+ }
1102
+ declare const FileField: ({ field: fieldDef, onUpload, disabled }: Props$2) => react.JSX.Element;
1103
+
962
1104
  interface Props$1 {
963
1105
  section: FormSection;
964
1106
  isLast?: boolean;
@@ -1107,4 +1249,4 @@ interface UseDragReorderResult extends DragReorderState {
1107
1249
  */
1108
1250
  declare function useDragReorder<T>({ items, getId, onReorder, dragType, }: UseDragReorderOptions<T>): UseDragReorderResult;
1109
1251
 
1110
- export { APPLICATION_STATUS_KEYS, type ApplicationStatusEmailTemplates, type ApplicationStatusKey, CORE_EMAIL_TEMPLATE_VARIABLES, DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES, DEFAULT_FILE_FIELD_CONFIG, DEFAULT_FORM_STYLE, DEFAULT_NOTIFICATION_EMAIL_HTML, DEFAULT_NOTIFICATION_EMAIL_SUBJECT, DEFAULT_NOTIFICATION_EMAIL_TEMPLATE, DEFAULT_SENSITIVE_FIELD_CONFIG, DEFAULT_SPAM_PROTECTION, type DatetimeConfig, type DragReorderItemHandlers, type DragReorderState, type DropPosition, DynamicForm, DynamicFormField, DynamicFormSection, type EmailTemplateVariableDescriptor, type EmailTemplateVariables, type EncryptedSensitiveValue, FORM_CSS_VAR, FORM_DEFAULT_COLOR, FORM_VAR, type FieldOption, type FieldTransform, type FieldType, type FieldVisibilityCondition, type FieldWidth, type FileFieldConfig, type FormBookingConfig, type FormDefinition, type FormDefinitionJSON, type FormFieldDefinition, type FormFieldDefinitionJSON, type FormIdentifier, type FormIntegrationConfig, type FormIntegrationConfigJSON, type FormIntegrations, type FormIntegrationsJSON, type FormSection, type FormSectionJSON, type FormSpamProtectionConfig, type FormStatus, type FormStyle, type FormStyleJSON, type FormStylePreset, type FormSubmissionType, type FormSubmitConfig, type FormSubmitConfigJSON, type FormSuccessBehavior, HONEYPOT_FIELD_NAME, type InputVariant, type IntegrationFieldMappingEntry, type IntegrationFieldMappingEntryJSON, NEWSLETTER_ALLOWED_FIELD_TYPES, type NotificationEmailTemplate, SAME_AS_TOGGLE_PREFIX, SAMPLE_EMAIL_TEMPLATE_VARIABLES, type SectionSameAsConfig, type SensitiveFieldConfig, type SensitiveFieldConfigJSON, type SetStateUpdater, type TextTransform, type TransportPublicKey, type UseDragReorderOptions, type UseDragReorderResult, type UseFormDefinitionOptions, type UseUndoRedoControls, type UseUndoRedoOptions, type UseUndoRedoReturn, type ValidationRule, type ValidationRuleJSON, type VisibilityOperator, applyTextTransform, applyTransform, base64ToBuffer, bufferToBase64, buildEmailTemplateVariables, buildFormCssVars, buildInitialValues, buildYupSchema, deriveLast4, encryptSensitiveValue, formatSsn, formatUsPhone, getFormDefinition, getSafeRedirectUrl, isVisibilityConditionMet, parseFormDefinition, renderEmailTemplate, renderNotificationEmail, sameAsToggleKey, useDragReorder, useFormDefinition, useUndoRedo, useUndoRedoShortcuts };
1252
+ export { APPLICATION_STATUS_KEYS, type ApplicationStatusEmailTemplates, type ApplicationStatusKey, CORE_EMAIL_TEMPLATE_VARIABLES, DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES, DEFAULT_FILE_FIELD_CONFIG, DEFAULT_FORM_STYLE, DEFAULT_NOTIFICATION_EMAIL_HTML, DEFAULT_NOTIFICATION_EMAIL_SUBJECT, DEFAULT_NOTIFICATION_EMAIL_TEMPLATE, DEFAULT_SENSITIVE_FIELD_CONFIG, DEFAULT_SPAM_PROTECTION, type DatetimeConfig, type DragReorderItemHandlers, type DragReorderState, type DropPosition, DynamicForm, DynamicFormField, DynamicFormSection, type EmailTemplateVariableDescriptor, type EmailTemplateVariables, type EncryptedSensitiveValue, FORM_CSS_VAR, FORM_DEFAULT_COLOR, FORM_VAR, type FieldOption, type FieldTransform, type FieldType, type FieldVisibilityCondition, type FieldWidth, FileField, type FileFieldConfig, type FormBookingConfig, type FormDefinition, type FormDefinitionJSON, type FormFieldDefinition, type FormFieldDefinitionJSON, type FormFileUploadContextValue, type FormFileUploadHandler, FormFileUploadProvider, type FormIdentifier, type FormIntegrationConfig, type FormIntegrationConfigJSON, type FormIntegrations, type FormIntegrationsJSON, type FormSection, type FormSectionJSON, type FormSpamProtectionConfig, type FormStatus, type FormStyle, type FormStyleJSON, type FormStylePreset, type FormSubmissionType, type FormSubmitConfig, type FormSubmitConfigJSON, type FormSuccessBehavior, HONEYPOT_FIELD_NAME, type InputVariant, type IntegrationFieldMappingEntry, type IntegrationFieldMappingEntryJSON, NEWSLETTER_ALLOWED_FIELD_TYPES, type NotificationEmailTemplate, SAME_AS_TOGGLE_PREFIX, SAMPLE_EMAIL_TEMPLATE_VARIABLES, type SectionSameAsConfig, type SensitiveFieldConfig, type SensitiveFieldConfigJSON, type SetStateUpdater, type TextTransform, type TransportPublicKey, type UploadedFormFile, type UseDragReorderOptions, type UseDragReorderResult, type UseFormDefinitionOptions, type UseUndoRedoControls, type UseUndoRedoOptions, type UseUndoRedoReturn, type ValidationRule, type ValidationRuleJSON, type VisibilityOperator, applyTextTransform, applyTransform, base64ToBuffer, bufferToBase64, buildEmailTemplateVariables, buildFormCssVars, buildInitialValues, buildYupSchema, deriveLast4, encryptSensitiveValue, formatSsn, formatUsPhone, getFormDefinition, getSafeRedirectUrl, isVisibilityConditionMet, parseFormDefinition, renderEmailTemplate, renderNotificationEmail, resizeImageFile, sameAsToggleKey, useDragReorder, useFormDefinition, useFormFileUpload, useUndoRedo, useUndoRedoShortcuts };