@formhaus/core 0.11.0 → 0.11.1

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/dist/cloud.js CHANGED
@@ -1,2 +1,2 @@
1
- export{d as CloudError,i as createSubmitter,h as fetchDefinition,g as fetchForm,k as sessionDraftStore}from'./chunk-EPXEKDCK.js';//# sourceMappingURL=cloud.js.map
1
+ export{d as CloudError,i as createSubmitter,h as fetchDefinition,g as fetchForm,k as sessionDraftStore}from'./chunk-IVSO5ANU.js';//# sourceMappingURL=cloud.js.map
2
2
  //# sourceMappingURL=cloud.js.map
@@ -27,6 +27,7 @@ declare function fetchDefinition(options: CloudClientOptions, signal?: AbortSign
27
27
  interface CloudSubmitterOptions extends CloudClientOptions {
28
28
  version?: number;
29
29
  renderToken?: string;
30
+ firstRenderToken?: string;
30
31
  extraBody?: () => Record<string, unknown>;
31
32
  }
32
33
  declare function createSubmitter(options: CloudSubmitterOptions): (values: Record<string, unknown>, skippedSteps?: string[]) => Promise<CloudSubmission>;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { F as FormField, a as FormStep, S as ShowCondition } from './definition-Bufih_Bx.js';
2
2
  export { D as DefaultFieldType, b as FieldOption, c as FieldType, d as FieldValidation, e as FormAction, f as FormDefinition, g as StepRoute } from './definition-Bufih_Bx.js';
3
- export { A as AfterStepChangeFn, B as BeforeStepChangeFn, a as BeforeSubmitFn, F as FormEngine, b as FormEngineOptions, S as StepChangeContext, c as StepValidateFn, d as SubmitFn } from './runtime-DOIq-Zce.js';
3
+ export { A as AfterStepChangeFn, B as BeforeStepChangeFn, a as BeforeSubmitFn, F as FormEngine, b as FormEngineOptions, S as StepChangeContext, c as StepValidateFn, d as SubmitFn } from './runtime-LNJU0Dra.js';
4
4
  import { V as ValidatorFn } from './validate-field-glVVoN3E.js';
5
5
  export { D as DefinitionIssue, a as DefinitionIssueCode, F as FormDefinitionError, v as validateFieldValue } from './validate-field-glVVoN3E.js';
6
6
  export { C as CheckDefinitionOptions, c as checkDefinition, p as parseDefinition } from './check-definition-BTMV3Ziq.js';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export{a as FormDefinitionError,e as FormEngine,b as checkDefinition,c as parseDefinition,d as validateDefinition}from'./chunk-OMINRKEL.js';export{f as FormLifecycleError,b as evaluateCondition,g as getDefaultMessage,h as isVisible,k as validateFieldValue,m as validateFields,l as validateStep}from'./chunk-BXI5P7PF.js';//# sourceMappingURL=index.js.map
1
+ export{a as FormDefinitionError,e as FormEngine,b as checkDefinition,c as parseDefinition,d as validateDefinition}from'./chunk-47C7QX7J.js';export{d as FormLifecycleError,g as evaluateCondition,e as getDefaultMessage,h as isVisible,m as validateFieldValue,o as validateFields,n as validateStep}from'./chunk-YXQFFAXK.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
- export { j as CloudCallbacks, k as CloudControllerOptions, l as CloudState, m as cloudStateFor, n as createCloudController, o as initialCloudState } from './controller-x_emKgtv.js';
2
- import { F as FormEngine } from './runtime-DOIq-Zce.js';
1
+ export { j as CloudCallbacks, k as CloudControllerOptions, l as CloudState, m as cloudStateFor, n as createCloudController, o as initialCloudState } from './controller-CUZ5bMpv.js';
2
+ import { F as FormEngine } from './runtime-LNJU0Dra.js';
3
3
  import './definition-Bufih_Bx.js';
4
4
  import './validate-field-glVVoN3E.js';
5
5
 
package/dist/internal.js CHANGED
@@ -1,2 +1,2 @@
1
- import {f,i,j,g,d,e,a,c,b}from'./chunk-EPXEKDCK.js';import {z as z$1}from'./chunk-BXI5P7PF.js';var q={multiselect:"list",checkbox:"flag",switch:"flag",number:"number",file:"file"};function p(e){return [...e.fields??[],...(e.steps??[]).flatMap(n=>n.fields)]}function k(e){return q[e.type]??"text"}function G(e,n){if(!Array.isArray(e.options))return true;let r=new Set(e.options.map(i=>String(i.value)));return (Array.isArray(n)?n:[n]).every(i=>r.has(String(i)))}function L(e,n,r){if(e&&k(e)!==k(n))return false;switch(k(n)){case "list":return Array.isArray(r);case "flag":return typeof r=="boolean";case "number":return typeof r=="number";case "text":return typeof r=="string";default:return e!==void 0}}function D(e,n,r){let i=new Map(r?p(r).map(o=>[o.key,o]):[]),u={};for(let o of p(n)){let s=e[o.key];s!=null&&L(i.get(o.key),o,s)&&G(o,s)&&(u[o.key]=s);}return u}function O(e,n){let r=new Set(p(e).map(o=>o.key)),i={},u=new Set;for(let[o,s]of Object.entries(n))r.has(o)?i[o]=s:u.add(s);return {fields:i,other:[...u]}}function P(e,n,r,i){let u={};for(let o of p(e)){let s=n[o.key]!==void 0&&n[o.key]!==null&&n[o.key]!=="";s&&!(o.key in r)?u[o.key]=b:i[o.key]&&(!s||o.key in r)&&(u[o.key]=i[o.key]);}return u}var y={definition:null,version:null,settings:{},loadError:null,errors:{},notice:null,initialValues:null,revision:0,attempt:0,done:false};function N(e){return e?{...y,definition:e.definition,version:e.version??null,settings:f(e.settings)}:y}function V(e,n=[]){return {tone:"error",message:e.message,action:e.action,details:n}}function $(e$1,n){let r=new AbortController,i$1=t=>i({...e$1,version:t.version,renderToken:t.renderToken}),u=i(e$1),o=e$1.initialForm,s=()=>!r.signal.aborted,l=y,f$1=t=>{l={...l,...t},n.onChange(l);},g$1=t=>f$1({...t,attempt:l.attempt+1});function h(t){u=i$1(t);let c=e$1.draftStore?.load(e$1.id,t.version)??null;f$1({...N(t),revision:l.revision,attempt:l.attempt,initialValues:c});}async function T(t,c$1){let a$1=l.definition;try{let d$1=await g(e$1,r.signal,t.version);if(!s())return;if(d$1.version===void 0||d$1.version<(t.version??0))throw new d(409,"form_updated");let m=a$1?D(c$1,d$1.definition,a$1):{};u=i$1(d$1),g$1({definition:d$1.definition,version:d$1.version,settings:f(d$1.settings),initialValues:m,revision:l.revision+1,errors:P(d$1.definition,c$1,m,t.errors??{}),notice:{tone:"info",message:a,action:null,details:[]}});}catch{s()&&g$1({notice:{tone:"error",...c(409,"form_updated"),details:[]}});}}async function j$1(t,c){let a=t instanceof d?t:e(t);if(a.code==="form_updated"&&a.version!==void 0)return T(a,c);if(a.status!==422)return g$1({notice:V(a)});let d$1=a.errors??{},m=l.definition?O(l.definition,d$1):{fields:d$1,other:[]};g$1({errors:m.fields,notice:m.other.length>0?V(a,m.other):null});}return {start(){if(l.loadError&&f$1({loadError:null}),o){h(o),o=void 0;return}g(e$1,r.signal).then(t=>{s()&&h(t);},t=>{s()&&(f$1({loadError:t}),n.onError?.(t));});},dispose(){r.abort();},saveDraft(t){l.definition&&!l.done&&e$1.draftStore?.save(e$1.id,l.version??void 0,j(l.definition,t));},again(){f$1({done:false,errors:{},notice:null,initialValues:null,revision:l.revision+1});},async submit(t,c){l.notice&&f$1({notice:null});try{let a=await u(t,c);if(!s())return;e$1.draftStore?.clear(e$1.id),f$1({done:!0}),n.onSuccess?.(a);}catch(a){throw s()&&(await j$1(a,t),n.onError?.(a)),a}}}}var _='input:not([type="hidden"]):not(:disabled), select:not(:disabled), textarea:not(:disabled), button:not(:disabled)';function I(e,n){n.scrollIntoView?.({block:"center"}),e.focus({preventScroll:true});}function z(e,n){if(n)return I(n,n);let r=e?.querySelector('[aria-invalid="true"]');r&&I(r.matches(_)?r:r.querySelector(_)??r,r);}function B(e,n){let r=Object.keys(n);return r.length===Object.keys(e).length&&r.every(i=>e[i]===n[i])}function H(e,n){return Object.entries(n).every(([r,i])=>e.errors[r]===i||e.topLevelErrors.includes(i))}function U(e,n,r){return !n||!B(n,r)||!H(e,r)}function ie(e){return z$1(e,"next","autoAdvance")}var M=e=>e.replace(/[^A-Za-z0-9_-]/g,"-");function se(e,n){return `${e?M(e):"fh"}-${M(n)}`}export{ie as autoAdvance,N as cloudStateFor,$ as createCloudController,se as fieldDomId,z as focusProblem,y as initialCloudState,U as shouldApplyExternalErrors};//# sourceMappingURL=internal.js.map
1
+ import {f,i,j,g,d,e,a,c,b as b$1}from'./chunk-IVSO5ANU.js';import {B as B$1}from'./chunk-YXQFFAXK.js';var G={multiselect:"list",checkbox:"flag",switch:"flag",number:"number",file:"file"};function y(e){return [...e.fields??[],...(e.steps??[]).flatMap(n=>n.fields)]}function h(e){return G[e.type]??"text"}function L(e,n){if(!Array.isArray(e.options))return true;let r=new Set(e.options.map(i=>String(i.value)));return (Array.isArray(n)?n:[n]).every(i=>r.has(String(i)))}function $(e,n,r){if(e&&h(e)!==h(n))return false;switch(h(n)){case "list":return Array.isArray(r);case "flag":return typeof r=="boolean";case "number":return typeof r=="number";case "text":return typeof r=="string";default:return e!==void 0}}function O(e,n,r){let i=new Map(r?y(r).map(o=>[o.key,o]):[]),a={};for(let o of y(n)){let u=e[o.key];u!=null&&$(i.get(o.key),o,u)&&L(o,u)&&(a[o.key]=u);}return a}function P(e,n){let r=new Set(y(e).map(o=>o.key)),i={},a=new Set;for(let[o,u]of Object.entries(n))r.has(o)?i[o]=u:a.add(u);return {fields:i,other:[...a]}}function V(e,n,r,i){let a={};for(let o of y(e)){let u=n[o.key]!==void 0&&n[o.key]!==null&&n[o.key]!=="";u&&!(o.key in r)?a[o.key]=b$1:i[o.key]&&(!u||o.key in r)&&(a[o.key]=i[o.key]);}return a}var b={definition:null,version:null,settings:{},loadError:null,errors:{},notice:null,initialValues:null,revision:0,attempt:0,done:false};function N(e){return e?{...b,definition:e.definition,version:e.version??null,settings:f(e.settings)}:b}function T(e,n=[]){return {tone:"error",message:e.message,action:e.action,details:n}}function z(e$1,n){let r=new AbortController,i$1,a$1=t=>{i$1??(i$1=t.renderToken);let c=i$1===t.renderToken?void 0:i$1;return i({...e$1,version:t.version,renderToken:t.renderToken,firstRenderToken:c})},o=i(e$1),u=e$1.initialForm,m=()=>!r.signal.aborted,s=b,f$1=t=>{s={...s,...t},n.onChange(s);},p=t=>f$1({...t,attempt:s.attempt+1});function w(t){o=a$1(t);let c=e$1.draftStore?.load(e$1.id,t.version)??null;f$1({...N(t),revision:s.revision,attempt:s.attempt,initialValues:c});}async function j$1(t,c$1){let l=s.definition;try{let d$1=await g(e$1,r.signal,t.version);if(!m())return;if(d$1.version===void 0||d$1.version<(t.version??0))throw new d(409,"form_updated");let g$1=l?O(c$1,d$1.definition,l):{};o=a$1(d$1),p({definition:d$1.definition,version:d$1.version,settings:f(d$1.settings),initialValues:g$1,revision:s.revision+1,errors:V(d$1.definition,c$1,g$1,t.errors??{}),notice:{tone:"info",message:a,action:null,details:[]}});}catch{m()&&p({notice:{tone:"error",...c(409,"form_updated"),details:[]}});}}async function q(t,c){let l=t instanceof d?t:e(t);if(l.code==="form_updated"&&l.version!==void 0)return j$1(l,c);if(l.status!==422)return p({notice:T(l)});let d$1=l.errors??{},g=s.definition?P(s.definition,d$1):{fields:d$1,other:[]};p({errors:g.fields,notice:g.other.length>0?T(l,g.other):null});}return {start(){if(s.loadError&&f$1({loadError:null}),u){w(u),u=void 0;return}g(e$1,r.signal).then(t=>{m()&&w(t);},t=>{m()&&(f$1({loadError:t}),n.onError?.(t));});},dispose(){r.abort();},saveDraft(t){s.definition&&!s.done&&e$1.draftStore?.save(e$1.id,s.version??void 0,j(s.definition,t));},again(){f$1({done:false,errors:{},notice:null,initialValues:null,revision:s.revision+1});},async submit(t,c){s.notice&&f$1({notice:null});try{let l=await o(t,c);if(!m())return;e$1.draftStore?.clear(e$1.id),f$1({done:!0}),n.onSuccess?.(l);}catch(l){throw m()&&(await q(l,t),n.onError?.(l)),l}}}}var _='input:not([type="hidden"]):not(:disabled), select:not(:disabled), textarea:not(:disabled), button:not(:disabled)';function I(e,n){n.scrollIntoView?.({block:"center"}),e.focus({preventScroll:true});}function B(e,n){if(n)return I(n,n);let r=e?.querySelector('[aria-invalid="true"]');r&&I(r.matches(_)?r:r.querySelector(_)??r,r);}function H(e,n){let r=Object.keys(n);return r.length===Object.keys(e).length&&r.every(i=>e[i]===n[i])}function U(e,n){return Object.entries(n).every(([r,i])=>e.errors[r]===i||e.topLevelErrors.includes(i))}function W(e,n,r){return !n||!H(n,r)||!U(e,r)}function se(e){return B$1(e,"next","autoAdvance")}var M=e=>e.replace(/[^A-Za-z0-9_-]/g,"-");function le(e,n){return `${e?M(e):"fh"}-${M(n)}`}export{se as autoAdvance,N as cloudStateFor,z as createCloudController,le as fieldDomId,B as focusProblem,b as initialCloudState,W as shouldApplyExternalErrors};//# sourceMappingURL=internal.js.map
2
2
  //# sourceMappingURL=internal.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cloud/carry.ts","../src/cloud/controller.ts","../src/cloud/focus.ts","../src/engine/external-errors.ts","../src/internal/index.ts"],"names":["SHAPES","fieldsOf","definition","step","shapeOf","field","allowed","value","options","option","item","fits","previous","next","carryValues","values","before","kept","splitErrors","errors","known","fields","other","key","message","updatedErrors","sent","rejected","answered","ANSWER_AGAIN","initialCloudState","cloudStateFor","form","parseSettings","errorNotice","error","details","createCloudController","callbacks","controller","submitterFor","createSubmitter","submitter","initial","alive","state","update","patch","report","show","draft","refresh","fetchForm","CloudError","FORM_UPDATED_MESSAGE","failureFor","fail","cloud","networkError","split","draftValues","skippedSteps","submission","CONTROLS","reveal","target","scrollTo","focusProblem","root","notice","invalid","sameErrors","keys","holdsErrors","engine","shouldApplyExternalErrors","autoAdvance","changeStep","clean","fieldDomId","formId"],"mappings":"+FAGA,IAAMA,CAAAA,CAAiC,CACrC,WAAA,CAAa,MAAA,CACb,QAAA,CAAU,MAAA,CACV,MAAA,CAAQ,MAAA,CACR,MAAA,CAAQ,QAAA,CACR,IAAA,CAAM,MACR,CAAA,CAEA,SAASC,CAAAA,CAASC,CAAAA,CAAyC,CACzD,OAAO,CAAC,GAAIA,CAAAA,CAAW,MAAA,EAAU,EAAC,CAAI,GAAA,CAAIA,CAAAA,CAAW,KAAA,EAAS,EAAC,EAAG,OAAA,CAASC,CAAAA,EAASA,CAAAA,CAAK,MAAM,CAAC,CAClG,CAEA,SAASC,CAAAA,CAAQC,CAAAA,CAA0B,CACzC,OAAOL,CAAAA,CAAOK,CAAAA,CAAM,IAAI,CAAA,EAAK,MAC/B,CAEA,SAASC,CAAAA,CA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,EAAO,MAAA,CAAOnD,CAAG,CAAA,GAAMC,CAAAA,EAAWkD,CAAAA,CAAO,cAAA,CAAe,QAAA,CAASlD,CAAO,CACzE,CACH,CAEO,SAASmD,CAAAA,CACdD,CAAAA,CACA9D,CAAAA,CACAC,CAAAA,CACS,CACT,OAAO,CAACD,CAAAA,EAAY,CAAC2D,CAAAA,CAAW3D,CAAAA,CAAUC,CAAI,CAAA,EAAK,CAAC4D,CAAAA,CAAYC,CAAAA,CAAQ7D,CAAI,CAC9E,CCZO,SAAS+D,GAAYF,CAAAA,CAAsC,CAChE,OAAOG,GAAAA,CAAWH,CAAAA,CAAsC,MAAA,CAAQ,aAAa,CAC/E,CAEA,IAAMI,CAAAA,CAASvE,CAAAA,EAAkBA,CAAAA,CAAM,OAAA,CAAQ,iBAAA,CAAmB,GAAG,CAAA,CAE9D,SAASwE,EAAAA,CAAWC,CAAAA,CAA4BzD,CAAAA,CAAqB,CAC1E,OAAO,CAAA,EAAGyD,CAAAA,CAASF,CAAAA,CAAME,CAAM,CAAA,CAAI,IAAI,CAAA,CAAA,EAAIF,CAAAA,CAAMvD,CAAG,CAAC,CAAA,CACvD","file":"internal.js","sourcesContent":["import type { FormDefinition, FormField } from '../types';\nimport { ANSWER_AGAIN } from './failures';\n\nconst SHAPES: Record<string, string> = {\n multiselect: 'list',\n checkbox: 'flag',\n switch: 'flag',\n number: 'number',\n file: 'file',\n};\n\nfunction fieldsOf(definition: FormDefinition): FormField[] {\n return [...(definition.fields ?? []), ...(definition.steps ?? []).flatMap((step) => step.fields)];\n}\n\nfunction shapeOf(field: FormField): string {\n return SHAPES[field.type] ?? 'text';\n}\n\nfunction allowed(field: FormField, value: unknown): boolean {\n if (!Array.isArray(field.options)) return true;\n const options = new Set(field.options.map((option) => String(option.value)));\n return (Array.isArray(value) ? value : [value]).every((item) => options.has(String(item)));\n}\n\nfunction fits(previous: FormField | undefined, next: FormField, value: unknown): boolean {\n if (previous && shapeOf(previous) !== shapeOf(next)) return false;\n switch (shapeOf(next)) {\n case 'list': return Array.isArray(value);\n case 'flag': return typeof value === 'boolean';\n case 'number': return typeof value === 'number';\n case 'text': return typeof value === 'string';\n default: return previous !== undefined;\n }\n}\n\nexport function carryValues(\n values: Record<string, unknown>,\n next: FormDefinition,\n previous?: FormDefinition,\n): Record<string, unknown> {\n const before = new Map(previous ? fieldsOf(previous).map((field) => [field.key, field]) : []);\n const kept: Record<string, unknown> = {};\n for (const field of fieldsOf(next)) {\n const value = values[field.key];\n if (value === undefined || value === null) continue;\n if (fits(before.get(field.key), field, value) && allowed(field, value)) kept[field.key] = value;\n }\n return kept;\n}\n\nexport function splitErrors(definition: FormDefinition, errors: Record<string, string>) {\n const known = new Set(fieldsOf(definition).map((field) => field.key));\n const fields: Record<string, string> = {};\n const other = new Set<string>();\n for (const [key, message] of Object.entries(errors)) {\n if (known.has(key)) fields[key] = message;\n else other.add(message);\n }\n return { fields, other: [...other] };\n}\n\nexport function updatedErrors(\n next: FormDefinition,\n sent: Record<string, unknown>,\n kept: Record<string, unknown>,\n rejected: Record<string, string>,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n for (const field of fieldsOf(next)) {\n const answered = sent[field.key] !== undefined && sent[field.key] !== null && sent[field.key] !== '';\n if (answered && !(field.key in kept)) errors[field.key] = ANSWER_AGAIN;\n else if (rejected[field.key] && (!answered || field.key in kept)) errors[field.key] = rejected[field.key];\n }\n return errors;\n}\n","import type { FormDefinition } from '../types';\nimport { carryValues, splitErrors, updatedErrors } from './carry';\nimport { createSubmitter, fetchForm, type CloudClientOptions, type CloudSubmission } from './client';\nimport { draftValues, type DraftStore } from './draft';\nimport { parseSettings, type CloudSettings, type PublishedForm } from './envelope';\nimport { CloudError, networkError } from './error';\nimport { FORM_UPDATED_MESSAGE, failureFor, type CloudAction } from './failures';\n\nexport interface CloudNotice {\n tone: 'error' | 'info';\n message: string;\n action: CloudAction;\n details: string[];\n}\n\nexport interface CloudState {\n definition: FormDefinition | null;\n version: number | null;\n settings: CloudSettings;\n loadError: Error | null;\n errors: Record<string, string>;\n notice: CloudNotice | null;\n initialValues: Record<string, unknown> | null;\n revision: number;\n attempt: number;\n done: boolean;\n}\n\nexport interface CloudCallbacks {\n onChange(state: CloudState): void;\n onSuccess?(submission: CloudSubmission): void;\n onError?(error: unknown): void;\n}\n\nexport interface CloudControllerOptions extends CloudClientOptions {\n initialForm?: PublishedForm;\n extraBody?: () => Record<string, unknown>;\n draftStore?: DraftStore;\n}\n\nexport const initialCloudState: CloudState = {\n definition: null, version: null, settings: {}, loadError: null, errors: {}, notice: null,\n initialValues: null, revision: 0, attempt: 0, done: false,\n};\n\nexport function cloudStateFor(form?: PublishedForm): CloudState {\n if (!form) return initialCloudState;\n return { ...initialCloudState, definition: form.definition, version: form.version ?? null, settings: parseSettings(form.settings) };\n}\n\nfunction errorNotice(error: CloudError, details: string[] = []): CloudNotice {\n return { tone: 'error', message: error.message, action: error.action, details };\n}\n\nexport function createCloudController(options: CloudControllerOptions, callbacks: CloudCallbacks) {\n const controller = new AbortController();\n const submitterFor = (form: PublishedForm) => createSubmitter({ ...options, version: form.version, renderToken: form.renderToken });\n let submitter = createSubmitter(options);\n let initial = options.initialForm;\n const alive = () => !controller.signal.aborted;\n let state = initialCloudState;\n const update = (patch: Partial<CloudState>) => {\n state = { ...state, ...patch };\n callbacks.onChange(state);\n };\n const report = (patch: Partial<CloudState>) => update({ ...patch, attempt: state.attempt + 1 });\n\n function show(form: PublishedForm) {\n submitter = submitterFor(form);\n const draft = options.draftStore?.load(options.id, form.version) ?? null;\n update({ ...cloudStateFor(form), revision: state.revision, attempt: state.attempt, initialValues: draft });\n }\n\n async function refresh(error: CloudError, sent: Record<string, unknown>) {\n const before = state.definition;\n try {\n const next = await fetchForm(options, controller.signal, error.version);\n if (!alive()) return;\n if (next.version === undefined || next.version < (error.version ?? 0)) throw new CloudError(409, 'form_updated');\n const kept = before ? carryValues(sent, next.definition, before) : {};\n submitter = submitterFor(next);\n report({\n definition: next.definition,\n version: next.version,\n settings: parseSettings(next.settings),\n initialValues: kept,\n revision: state.revision + 1,\n errors: updatedErrors(next.definition, sent, kept, error.errors ?? {}),\n notice: { tone: 'info', message: FORM_UPDATED_MESSAGE, action: null, details: [] },\n });\n } catch {\n if (alive()) report({ notice: { tone: 'error', ...failureFor(409, 'form_updated'), details: [] } });\n }\n }\n\n async function fail(error: unknown, values: Record<string, unknown>) {\n const cloud = error instanceof CloudError ? error : networkError(error);\n if (cloud.code === 'form_updated' && cloud.version !== undefined) return refresh(cloud, values);\n if (cloud.status !== 422) return report({ notice: errorNotice(cloud) });\n const errors = cloud.errors ?? {};\n const split = state.definition ? splitErrors(state.definition, errors) : { fields: errors, other: [] };\n report({ errors: split.fields, notice: split.other.length > 0 ? errorNotice(cloud, split.other) : null });\n }\n\n return {\n start() {\n if (state.loadError) update({ loadError: null });\n if (initial) {\n show(initial);\n initial = undefined;\n return;\n }\n fetchForm(options, controller.signal).then(\n (form) => { if (alive()) show(form); },\n (error: Error) => {\n if (!alive()) return;\n update({ loadError: error });\n callbacks.onError?.(error);\n },\n );\n },\n dispose() {\n controller.abort();\n },\n saveDraft(values: Record<string, unknown>) {\n if (state.definition && !state.done) options.draftStore?.save(options.id, state.version ?? undefined, draftValues(state.definition, values));\n },\n again() {\n update({ done: false, errors: {}, notice: null, initialValues: null, revision: state.revision + 1 });\n },\n async submit(values: Record<string, unknown>, skippedSteps?: string[]) {\n if (state.notice) update({ notice: null });\n try {\n const submission = await submitter(values, skippedSteps);\n if (!alive()) return;\n options.draftStore?.clear(options.id);\n update({ done: true });\n callbacks.onSuccess?.(submission);\n } catch (error) {\n if (!alive()) throw error;\n await fail(error, values);\n callbacks.onError?.(error);\n throw error;\n }\n },\n };\n}\n","interface Searchable {\n querySelector(selector: string): unknown;\n}\n\ninterface Focusable extends Searchable {\n focus(options?: { preventScroll?: boolean }): void;\n scrollIntoView?(options?: { block?: 'center' | 'nearest' }): void;\n matches(selector: string): boolean;\n}\n\nconst CONTROLS = 'input:not([type=\"hidden\"]):not(:disabled), select:not(:disabled), textarea:not(:disabled), button:not(:disabled)';\n\nfunction reveal(target: Focusable, scrollTo: Focusable): void {\n scrollTo.scrollIntoView?.({ block: 'center' });\n target.focus({ preventScroll: true });\n}\n\nexport function focusProblem(root: Searchable | null, notice?: Focusable | null): void {\n if (notice) return reveal(notice, notice);\n const invalid = root?.querySelector('[aria-invalid=\"true\"]') as Focusable | null | undefined;\n if (invalid) reveal(invalid.matches(CONTROLS) ? invalid : (invalid.querySelector(CONTROLS) as Focusable | null) ?? invalid, invalid);\n}\n","import type { FormEngine } from './runtime';\n\nfunction sameErrors(previous: Record<string, string>, next: Record<string, string>): boolean {\n const keys = Object.keys(next);\n return keys.length === Object.keys(previous).length && keys.every((key) => previous[key] === next[key]);\n}\n\nfunction holdsErrors(engine: FormEngine, errors: Record<string, string>): boolean {\n return Object.entries(errors).every(([key, message]) => (\n engine.errors[key] === message || engine.topLevelErrors.includes(message)\n ));\n}\n\nexport function shouldApplyExternalErrors(\n engine: FormEngine,\n previous: Record<string, string> | undefined,\n next: Record<string, string>,\n): boolean {\n return !previous || !sameErrors(previous, next) || !holdsErrors(engine, next);\n}\n","export { cloudStateFor, createCloudController, initialCloudState, type CloudCallbacks, type CloudControllerOptions, type CloudState } from '../cloud/controller';\nexport { focusProblem } from '../cloud/focus';\nexport { shouldApplyExternalErrors } from '../engine/external-errors';\nimport type { FormEngine } from '../engine';\nimport { changeStep } from '../engine/navigation';\nimport type { EngineInternals } from '../engine/runtime-internals';\n\nexport function autoAdvance(engine: FormEngine): Promise<boolean> {\n return changeStep(engine as unknown as EngineInternals, 'next', 'autoAdvance');\n}\n\nconst clean = (value: string) => value.replace(/[^A-Za-z0-9_-]/g, '-');\n\nexport function fieldDomId(formId: string | undefined, key: string): string {\n return `${formId ? clean(formId) : 'fh'}-${clean(key)}`;\n}\n"]}
1
+ {"version":3,"sources":["../src/cloud/carry.ts","../src/cloud/controller.ts","../src/cloud/focus.ts","../src/engine/external-errors.ts","../src/internal/index.ts"],"names":["SHAPES","fieldsOf","definition","step","shapeOf","field","allowed","value","options","option","item","fits","previous","next","carryValues","values","before","kept","splitErrors","errors","known","fields","other","key","message","updatedErrors","sent","rejected","answered","ANSWER_AGAIN","initialCloudState","cloudStateFor","form","parseSettings","errorNotice","error","details","createCloudController","callbacks","controller","firstRenderToken","submitterFor","first","createSubmitter","submitter","initial","alive","state","update","patch","report","show","draft","refresh","fetchForm","CloudError","FORM_UPDATED_MESSAGE","failureFor","fail","cloud","networkError","split","draftValues","skippedSteps","submission","CONTROLS","reveal","target","scrollTo","focusProblem","root","notice","invalid","sameErrors","keys","holdsErrors","engine","shouldApplyExternalErrors","autoAdvance","changeStep","clean","fieldDomId","formId"],"mappings":"sGAGA,IAAMA,CAAAA,CAAiC,CACrC,WAAA,CAAa,MAAA,CACb,QAAA,CAAU,MAAA,CACV,MAAA,CAAQ,MAAA,CACR,MAAA,CAAQ,QAAA,CACR,IAAA,CAAM,MACR,CAAA,CAEA,SAASC,CAAAA,CAASC,CAAAA,CAAyC,CACzD,OAAO,CAAC,GAAIA,CAAAA,CAAW,MAAA,EAAU,EAAC,CAAI,GAAA,CAAIA,CAAAA,CAAW,KAAA,EAAS,IAAI,OAAA,CAASC,CAAAA,EAASA,CAAAA,CAAK,MAAM,CAAC,CAClG,CAEA,SAASC,CAAAA,CAAQC,CAAAA,CAA0B,CACzC,OAAOL,CAAAA,CAAOK,CAAAA,CAAM,IAAI,CAAA,EAAK,MAC/B,CAEA,SAASC,CAAAA,CAAQD,CAAAA,CAAkBE,CAAAA,CAAyB,CAC1D,GAAI,CAAC,KAAA,CAAM,OAAA,CAAQF,CAAAA,CAAM,OAAO,CAAA,CAAG,OAAO,KAAA,CAC1C,IAAMG,CAAAA,CAAU,IAAI,GAAA,CAAIH,CAAAA,CAAM,OAAA,CAAQ,GAAA,CAAKI,CAAAA,EAAW,MAAA,CAAOA,CAAAA,CAAO,KAAK,CAAC,CAAC,CAAA,CAC3E,OAAA,C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hE,CAAAA,CACAC,CAAAA,CACS,CACT,OAAO,CAACD,CAAAA,EAAY,CAAC6D,CAAAA,CAAW7D,CAAAA,CAAUC,CAAI,CAAA,EAAK,CAAC8D,CAAAA,CAAYC,CAAAA,CAAQ/D,CAAI,CAC9E,CCZO,SAASiE,EAAAA,CAAYF,CAAAA,CAAsC,CAChE,OAAOG,GAAAA,CAAWH,CAAAA,CAAsC,MAAA,CAAQ,aAAa,CAC/E,CAEA,IAAMI,CAAAA,CAASzE,CAAAA,EAAkBA,CAAAA,CAAM,OAAA,CAAQ,iBAAA,CAAmB,GAAG,CAAA,CAE9D,SAAS0E,EAAAA,CAAWC,CAAAA,CAA4B3D,CAAAA,CAAqB,CAC1E,OAAO,CAAA,EAAG2D,CAAAA,CAASF,CAAAA,CAAME,CAAM,CAAA,CAAI,IAAI,CAAA,CAAA,EAAIF,CAAAA,CAAMzD,CAAG,CAAC,CAAA,CACvD","file":"internal.js","sourcesContent":["import type { FormDefinition, FormField } from '../types';\nimport { ANSWER_AGAIN } from './failures';\n\nconst SHAPES: Record<string, string> = {\n multiselect: 'list',\n checkbox: 'flag',\n switch: 'flag',\n number: 'number',\n file: 'file',\n};\n\nfunction fieldsOf(definition: FormDefinition): FormField[] {\n return [...(definition.fields ?? []), ...(definition.steps ?? []).flatMap((step) => step.fields)];\n}\n\nfunction shapeOf(field: FormField): string {\n return SHAPES[field.type] ?? 'text';\n}\n\nfunction allowed(field: FormField, value: unknown): boolean {\n if (!Array.isArray(field.options)) return true;\n const options = new Set(field.options.map((option) => String(option.value)));\n return (Array.isArray(value) ? value : [value]).every((item) => options.has(String(item)));\n}\n\nfunction fits(previous: FormField | undefined, next: FormField, value: unknown): boolean {\n if (previous && shapeOf(previous) !== shapeOf(next)) return false;\n switch (shapeOf(next)) {\n case 'list': return Array.isArray(value);\n case 'flag': return typeof value === 'boolean';\n case 'number': return typeof value === 'number';\n case 'text': return typeof value === 'string';\n default: return previous !== undefined;\n }\n}\n\nexport function carryValues(\n values: Record<string, unknown>,\n next: FormDefinition,\n previous?: FormDefinition,\n): Record<string, unknown> {\n const before = new Map(previous ? fieldsOf(previous).map((field) => [field.key, field]) : []);\n const kept: Record<string, unknown> = {};\n for (const field of fieldsOf(next)) {\n const value = values[field.key];\n if (value === undefined || value === null) continue;\n if (fits(before.get(field.key), field, value) && allowed(field, value)) kept[field.key] = value;\n }\n return kept;\n}\n\nexport function splitErrors(definition: FormDefinition, errors: Record<string, string>) {\n const known = new Set(fieldsOf(definition).map((field) => field.key));\n const fields: Record<string, string> = {};\n const other = new Set<string>();\n for (const [key, message] of Object.entries(errors)) {\n if (known.has(key)) fields[key] = message;\n else other.add(message);\n }\n return { fields, other: [...other] };\n}\n\nexport function updatedErrors(\n next: FormDefinition,\n sent: Record<string, unknown>,\n kept: Record<string, unknown>,\n rejected: Record<string, string>,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n for (const field of fieldsOf(next)) {\n const answered = sent[field.key] !== undefined && sent[field.key] !== null && sent[field.key] !== '';\n if (answered && !(field.key in kept)) errors[field.key] = ANSWER_AGAIN;\n else if (rejected[field.key] && (!answered || field.key in kept)) errors[field.key] = rejected[field.key];\n }\n return errors;\n}\n","import type { FormDefinition } from '../types';\nimport { carryValues, splitErrors, updatedErrors } from './carry';\nimport { createSubmitter, fetchForm, type CloudClientOptions, type CloudSubmission } from './client';\nimport { draftValues, type DraftStore } from './draft';\nimport { parseSettings, type CloudSettings, type PublishedForm } from './envelope';\nimport { CloudError, networkError } from './error';\nimport { FORM_UPDATED_MESSAGE, failureFor, type CloudAction } from './failures';\n\nexport interface CloudNotice {\n tone: 'error' | 'info';\n message: string;\n action: CloudAction;\n details: string[];\n}\n\nexport interface CloudState {\n definition: FormDefinition | null;\n version: number | null;\n settings: CloudSettings;\n loadError: Error | null;\n errors: Record<string, string>;\n notice: CloudNotice | null;\n initialValues: Record<string, unknown> | null;\n revision: number;\n attempt: number;\n done: boolean;\n}\n\nexport interface CloudCallbacks {\n onChange(state: CloudState): void;\n onSuccess?(submission: CloudSubmission): void;\n onError?(error: unknown): void;\n}\n\nexport interface CloudControllerOptions extends CloudClientOptions {\n initialForm?: PublishedForm;\n extraBody?: () => Record<string, unknown>;\n draftStore?: DraftStore;\n}\n\nexport const initialCloudState: CloudState = {\n definition: null, version: null, settings: {}, loadError: null, errors: {}, notice: null,\n initialValues: null, revision: 0, attempt: 0, done: false,\n};\n\nexport function cloudStateFor(form?: PublishedForm): CloudState {\n if (!form) return initialCloudState;\n return { ...initialCloudState, definition: form.definition, version: form.version ?? null, settings: parseSettings(form.settings) };\n}\n\nfunction errorNotice(error: CloudError, details: string[] = []): CloudNotice {\n return { tone: 'error', message: error.message, action: error.action, details };\n}\n\nexport function createCloudController(options: CloudControllerOptions, callbacks: CloudCallbacks) {\n const controller = new AbortController();\n let firstRenderToken: string | undefined;\n const submitterFor = (form: PublishedForm) => {\n firstRenderToken ??= form.renderToken;\n const first = firstRenderToken === form.renderToken ? undefined : firstRenderToken;\n return createSubmitter({ ...options, version: form.version, renderToken: form.renderToken, firstRenderToken: first });\n };\n let submitter = createSubmitter(options);\n let initial = options.initialForm;\n const alive = () => !controller.signal.aborted;\n let state = initialCloudState;\n const update = (patch: Partial<CloudState>) => {\n state = { ...state, ...patch };\n callbacks.onChange(state);\n };\n const report = (patch: Partial<CloudState>) => update({ ...patch, attempt: state.attempt + 1 });\n\n function show(form: PublishedForm) {\n submitter = submitterFor(form);\n const draft = options.draftStore?.load(options.id, form.version) ?? null;\n update({ ...cloudStateFor(form), revision: state.revision, attempt: state.attempt, initialValues: draft });\n }\n\n async function refresh(error: CloudError, sent: Record<string, unknown>) {\n const before = state.definition;\n try {\n const next = await fetchForm(options, controller.signal, error.version);\n if (!alive()) return;\n if (next.version === undefined || next.version < (error.version ?? 0)) throw new CloudError(409, 'form_updated');\n const kept = before ? carryValues(sent, next.definition, before) : {};\n submitter = submitterFor(next);\n report({\n definition: next.definition,\n version: next.version,\n settings: parseSettings(next.settings),\n initialValues: kept,\n revision: state.revision + 1,\n errors: updatedErrors(next.definition, sent, kept, error.errors ?? {}),\n notice: { tone: 'info', message: FORM_UPDATED_MESSAGE, action: null, details: [] },\n });\n } catch {\n if (alive()) report({ notice: { tone: 'error', ...failureFor(409, 'form_updated'), details: [] } });\n }\n }\n\n async function fail(error: unknown, values: Record<string, unknown>) {\n const cloud = error instanceof CloudError ? error : networkError(error);\n if (cloud.code === 'form_updated' && cloud.version !== undefined) return refresh(cloud, values);\n if (cloud.status !== 422) return report({ notice: errorNotice(cloud) });\n const errors = cloud.errors ?? {};\n const split = state.definition ? splitErrors(state.definition, errors) : { fields: errors, other: [] };\n report({ errors: split.fields, notice: split.other.length > 0 ? errorNotice(cloud, split.other) : null });\n }\n\n return {\n start() {\n if (state.loadError) update({ loadError: null });\n if (initial) {\n show(initial);\n initial = undefined;\n return;\n }\n fetchForm(options, controller.signal).then(\n (form) => { if (alive()) show(form); },\n (error: Error) => {\n if (!alive()) return;\n update({ loadError: error });\n callbacks.onError?.(error);\n },\n );\n },\n dispose() {\n controller.abort();\n },\n saveDraft(values: Record<string, unknown>) {\n if (state.definition && !state.done) options.draftStore?.save(options.id, state.version ?? undefined, draftValues(state.definition, values));\n },\n again() {\n update({ done: false, errors: {}, notice: null, initialValues: null, revision: state.revision + 1 });\n },\n async submit(values: Record<string, unknown>, skippedSteps?: string[]) {\n if (state.notice) update({ notice: null });\n try {\n const submission = await submitter(values, skippedSteps);\n if (!alive()) return;\n options.draftStore?.clear(options.id);\n update({ done: true });\n callbacks.onSuccess?.(submission);\n } catch (error) {\n if (!alive()) throw error;\n await fail(error, values);\n callbacks.onError?.(error);\n throw error;\n }\n },\n };\n}\n","interface Searchable {\n querySelector(selector: string): unknown;\n}\n\ninterface Focusable extends Searchable {\n focus(options?: { preventScroll?: boolean }): void;\n scrollIntoView?(options?: { block?: 'center' | 'nearest' }): void;\n matches(selector: string): boolean;\n}\n\nconst CONTROLS = 'input:not([type=\"hidden\"]):not(:disabled), select:not(:disabled), textarea:not(:disabled), button:not(:disabled)';\n\nfunction reveal(target: Focusable, scrollTo: Focusable): void {\n scrollTo.scrollIntoView?.({ block: 'center' });\n target.focus({ preventScroll: true });\n}\n\nexport function focusProblem(root: Searchable | null, notice?: Focusable | null): void {\n if (notice) return reveal(notice, notice);\n const invalid = root?.querySelector('[aria-invalid=\"true\"]') as Focusable | null | undefined;\n if (invalid) reveal(invalid.matches(CONTROLS) ? invalid : (invalid.querySelector(CONTROLS) as Focusable | null) ?? invalid, invalid);\n}\n","import type { FormEngine } from './runtime';\n\nfunction sameErrors(previous: Record<string, string>, next: Record<string, string>): boolean {\n const keys = Object.keys(next);\n return keys.length === Object.keys(previous).length && keys.every((key) => previous[key] === next[key]);\n}\n\nfunction holdsErrors(engine: FormEngine, errors: Record<string, string>): boolean {\n return Object.entries(errors).every(([key, message]) => (\n engine.errors[key] === message || engine.topLevelErrors.includes(message)\n ));\n}\n\nexport function shouldApplyExternalErrors(\n engine: FormEngine,\n previous: Record<string, string> | undefined,\n next: Record<string, string>,\n): boolean {\n return !previous || !sameErrors(previous, next) || !holdsErrors(engine, next);\n}\n","export { cloudStateFor, createCloudController, initialCloudState, type CloudCallbacks, type CloudControllerOptions, type CloudState } from '../cloud/controller';\nexport { focusProblem } from '../cloud/focus';\nexport { shouldApplyExternalErrors } from '../engine/external-errors';\nimport type { FormEngine } from '../engine';\nimport { changeStep } from '../engine/navigation';\nimport type { EngineInternals } from '../engine/runtime-internals';\n\nexport function autoAdvance(engine: FormEngine): Promise<boolean> {\n return changeStep(engine as unknown as EngineInternals, 'next', 'autoAdvance');\n}\n\nconst clean = (value: string) => value.replace(/[^A-Za-z0-9_-]/g, '-');\n\nexport function fieldDomId(formId: string | undefined, key: string): string {\n return `${formId ? clean(formId) : 'fh'}-${clean(key)}`;\n}\n"]}
@@ -72,6 +72,7 @@ declare class FormEngine<TValues extends object = Record<string, unknown>> {
72
72
  getSubmitValues(): Partial<TValues>;
73
73
  goToStepWithField(key: string): void;
74
74
  reset(values?: Record<string, unknown>): void;
75
+ private get view();
75
76
  private get internals();
76
77
  private notify;
77
78
  }
@@ -1,6 +1,6 @@
1
1
  var Formhaus=(function(exports){'use strict';typeof console==="undefined"&&(globalThis.console={log:function(){},warn:function(){},error:function(){}});
2
- var ae=Object.defineProperty,ue=Object.defineProperties;var le=Object.getOwnPropertyDescriptors;var xt=Object.getOwnPropertySymbols;var de=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable;var Et=(t,e,n)=>e in t?ae(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n,f=(t,e)=>{for(var n in e||(e={}))de.call(e,n)&&Et(t,n,e[n]);if(xt)for(var n of xt(e))ce.call(e,n)&&Et(t,n,e[n]);return t},M=(t,e)=>ue(t,le(e));var It=["eq","neq","in","notIn","notEmpty","gt","gte","lt","lte"];function L(t){return t==null||t===""||Array.isArray(t)&&!t.length}function fe(t){let e=typeof t=="string"&&t.trim()!==""?Number(t):t;return typeof e=="number"&&Number.isFinite(e)?e:void 0}function q(t,e,n){let i=fe(t);return i!==void 0&&n(i,e)}function dt(t,e){let n=e[t.field];return t.eq!==void 0?n===t.eq:t.neq!==void 0?n!==t.neq:t.in!==void 0?t.in.includes(n):t.notIn!==void 0?!t.notIn.includes(n):t.notEmpty!==void 0?!t.notEmpty||!L(n):t.gt!==void 0?q(n,t.gt,(i,r)=>i>r):t.gte!==void 0?q(n,t.gte,(i,r)=>i>=r):t.lt!==void 0?q(n,t.lt,(i,r)=>i<r):t.lte!==void 0?q(n,t.lte,(i,r)=>i<=r):false}var k=class extends Error{constructor(e){super(`Invalid form definition:
2
+ var xe=Object.defineProperty,Ee=Object.defineProperties;var Ie=Object.getOwnPropertyDescriptors;var Lt=Object.getOwnPropertySymbols;var Ce=Object.prototype.hasOwnProperty,$e=Object.prototype.propertyIsEnumerable;var Tt=(t,e,n)=>e in t?xe(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n,m=(t,e)=>{for(var n in e||(e={}))Ce.call(e,n)&&Tt(t,n,e[n]);if(Lt)for(var n of Lt(e))$e.call(e,n)&&Tt(t,n,e[n]);return t},G=(t,e)=>Ee(t,Ie(e));var jt=["eq","neq","in","notIn","notEmpty","gt","gte","lt","lte"];function U(t){return t==null||t===""||Array.isArray(t)&&!t.length}function De(t){let e=typeof t=="string"&&t.trim()!==""?Number(t):t;return typeof e=="number"&&Number.isFinite(e)?e:void 0}function tt(t,e,n){let r=De(t);return r!==void 0&&n(r,e)}function Ft(t,e){let n=e[t.field];return t.eq!==void 0?n===t.eq:t.neq!==void 0?n!==t.neq:t.in!==void 0?t.in.includes(n):t.notIn!==void 0?!t.notIn.includes(n):t.notEmpty!==void 0?!t.notEmpty||!U(n):t.gt!==void 0?tt(n,t.gt,(r,i)=>r>i):t.gte!==void 0?tt(n,t.gte,(r,i)=>r>=i):t.lt!==void 0?tt(n,t.lt,(r,i)=>r<i):t.lte!==void 0?tt(n,t.lte,(r,i)=>r<=i):false}var $=class extends Error{constructor(e){super(`Invalid form definition:
3
3
  ${e.map(n=>n.message).join(`
4
- `)}`),this.name="FormDefinitionError",this.issues=e;}};function $t(t){return (e,n,i,r)=>f({code:e,severity:t,path:n,message:`${n||"/"}: ${i}.${r?` ${r}.`:""}`},r&&{hint:`${r}.`})}var p=$t("error"),h=$t("warning");function B(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function D(t){return t.severity==="error"}function E(t){if(t.length===1)return `Use ${JSON.stringify(t[0])}`;let e=t.slice(0,10).map(n=>JSON.stringify(n)).join(", ");return t.length>10?`Use one of: ${e}, ...`:`Use one of: ${e}`}function pe(t,e){let n=Array.from({length:e.length+1},(i,r)=>r);for(let i=1;i<=t.length;i++){let r=[i];for(let s=1;s<=e.length;s++)r[s]=Math.min(n[s]+1,r[s-1]+1,n[s-1]+(t[i-1]===e[s-1]?0:1));n=r;}return n[e.length]}function ct(t,e){let n=t.toLowerCase();return e.find(i=>i!==t&&pe(n,i.toLowerCase())<=(i.length>4?2:1))}function R(t,e){let n=ct(t,e);return n!==void 0?`Use ${JSON.stringify(n)}`:e.length?E(e):void 0}var U=It,me=new Set(["in","notIn"]),he=new Set(["neq","notIn"]),ye=new Set(["gt","gte","lt","lte"]),ge=new Set(["text","email","phone","password","textarea","date","datetime","select","radio","autocomplete"]),Ct=new Set(["checkbox","switch"]);function be(t){return t.type==="number"?"number":Ct.has(t.type)?"boolean":ge.has(t.type)?"string":void 0}function Se(t,e,n){if(!(t.type!=="multiselect"&&!Ct.has(t.type)))return h("condition-value-mismatch",n,`"${t.key}" is a ${t.type} field, so "${e}" never matches it`,"Compare a number, text, radio or select field")}function Fe(t,e,n,i){var l;if(e==="notEmpty")return;if(ye.has(e))return Se(t,e,i);if(t.type==="multiselect"){let d=he.has(e)?"always":"never";return h("condition-value-mismatch",i,`"${t.key}" holds a list of values, so "${e}" ${d} matches it`,"Use notEmpty, or a select or radio field")}let r=me.has(e)&&Array.isArray(n)?n:[n],s=be(t),o=s&&r.find(d=>typeof d!==s);if(s&&o!==void 0)return h("condition-value-mismatch",i,`${JSON.stringify(o)} is a ${typeof o}, but "${t.key}" holds a ${s}`,`Use a ${s} value`);let u=s==="string"&&!t.optionsFrom&&((l=t.options)!=null&&l.length)?t.options.map(d=>d.value):null,a=u&&r.find(d=>!u.includes(d));if(u&&a!==void 0)return h("condition-value-mismatch",i,`${JSON.stringify(a)} is not an option of "${t.key}"`,E(u))}function ve(t,e){let n=Object.keys(t).filter(o=>o!=="field"),i=n.filter(o=>!U.includes(o)),r=i.map(o=>p("unknown-operator",`${e}/${B(o)}`,`"${o}" is not a condition operator`,R(o,[...U]))),s=n.length-i.length;if(s!==1&&!(s===0&&i.length)){let o=s?`the condition has ${s} operators`:"the condition has no operator";r.push(p("condition-operator-count",e,o,`Use exactly one of: ${U.join(", ")}`));}return r}function ke(t,{condition:e,path:n,owner:i,step:r,key:s}){let o=t.keys.get(e.field);if(!o){let l=t.keyList.filter(d=>d!==s);return p("unknown-field",`${n}/field`,`"${e.field}" is not a field key`,R(e.field,l))}if(r<0||i==="action")return;let u=i==="step"?"this or a later step":"a later step";if(o.step<r||i!=="step"&&o.step===r)return;let a=i==="step"?"earlier steps":"this or an earlier step";return p("forward-reference",`${n}/field`,`"${e.field}" belongs to ${u}`,`${i==="route"?"Route":i==="step"?"Step":"Field"} conditions can use fields of ${a}`)}function Dt(t){let e=[];for(let n of t.conditions){let{condition:i,path:r}=n;if(typeof i.field!="string"){e.push(p("missing-property",`${r}/field`,'the condition has no "field"',"Add the key of the field to test"));continue}let s=ve(i,r);e.push(...s);let o=ke(t,n);o&&e.push(o);let u=t.keys.get(i.field),a=U.find(l=>l in i);if(!o&&!s.length&&u&&a){let l=Fe(u.field,a,i[a],`${r}/${a}`);l&&e.push(l);}}return e}function ft(t,e,n,i,r,s){var o;for(let u of ["show","showAny"])((o=e[u])!=null?o:[]).forEach((a,l)=>t.push({condition:a,path:`${n}/${u}/${l}`,owner:i,step:r,key:s}));}function pt(t,e,n,i){var r;(e?(r=e.disabled)!=null?r:[]:[]).forEach((s,o)=>t.push({condition:s,path:`${n}/disabled/${o}`,owner:"action",step:i}));}function Rt(t,e){var o,u;let n=(o=t.steps)!=null?o:[],i=n.length?n.flatMap((a,l)=>a.fields.map((d,c)=>({field:d,path:`/steps/${l}/fields/${c}`,step:l}))):((u=t.fields)!=null?u:[]).map((a,l)=>({field:a,path:`/fields/${l}`,step:-1})),r=new Map;for(let a of i)r.has(a.field.key)||r.set(a.field.key,a);let s=[];for(let a of i)ft(s,a.field,a.path,"field",a.step,a.field.key);return n.forEach((a,l)=>{var d;ft(s,a,`/steps/${l}`,"step",l),((d=a.routes)!=null?d:[]).forEach((c,m)=>ft(s,c,`/steps/${l}/routes/${m}`,"route",l));for(let c of ["next","back","skip"])pt(s,a[c],`/steps/${l}/${c}`,l);}),pt(s,t.submit,"/submit",-1),pt(s,t.cancel,"/cancel",-1),{definition:t,entries:i,keys:r,keyList:[...r.keys()],conditions:s,validators:e}}var mt=["text","email","phone","number","password","select","autocomplete","multiselect","checkbox","radio","switch","file","date","datetime","textarea"],we=new Set(["select","radio","multiselect"]),xe=new Set(["number","checkbox","switch"]);function Ee({field:t,path:e}){let n=mt.includes(t.type)?void 0:ct(t.type,mt);return n===void 0?[]:[h("unknown-field-type",`${e}/type`,`"${t.type}" is not a built-in field type`,`Use "${n}", or register a component for "${t.type}"`)]}function Ie({field:t,path:e}){if(!we.has(t.type))return [];if(!Array.isArray(t.options))return t.optionsFrom?[]:[h("missing-options",`${e}/options`,`the ${t.type} field "${t.key}" has no options`,'Add "options" or "optionsFrom"')];let n=t.options.map(s=>s.value),i=t.type==="multiselect"&&Array.isArray(t.defaultValue)?t.defaultValue:[t.defaultValue],r=t.defaultValue===void 0||!n.length||t.optionsFrom?void 0:i.find(s=>!n.includes(s));return r===void 0?[]:[h("default-not-in-options",`${e}/defaultValue`,`${JSON.stringify(r)} is not an option of "${t.key}"`,E(n))]}function Vt(t,e,n,i){let r=t[n],s=t[i];return r===void 0||s===void 0||r<=s?[]:[p("invalid-range",`${e}/validation/${n}`,`${n} (${r}) is greater than ${i} (${s})`,`Lower ${n} or raise ${i}`)]}function $e({field:t,path:e},n){if(!mt.includes(t.type))return [];let i=t.type==="number",r=i?[]:["min","max"].filter(o=>n[o]!==void 0),s=xe.has(t.type)?["minLength","maxLength"].filter(o=>n[o]!==void 0):[];return [...r.map(o=>h("rule-not-applicable",`${e}/validation/${o}`,`"${o}" applies to number fields only`,`Use ${o}Length to limit text length`)),...s.map(o=>h("rule-not-applicable",`${e}/validation/${o}`,`"${o}" does not apply to ${t.type} fields`,i?"Use min and max for numbers":`Remove ${o}`))]}function Ce(t,e){if(t===void 0)return [];try{return new RegExp(t),[]}catch(n){return [p("invalid-pattern",`${e}/validation/pattern`,`${JSON.stringify(t)} is not a valid regular expression`,"Fix the pattern or escape special characters with a backslash")]}}function De(t,e){let n=e.field.validation;if(!n)return [];let{path:i}=e,r=[...Vt(n,i,"minLength","maxLength"),...Vt(n,i,"min","max"),...$e(e,n),...Ce(n.pattern,i)];n.matchField!==void 0&&!t.keys.has(n.matchField)&&r.push(p("unknown-field",`${i}/validation/matchField`,`"${n.matchField}" is not a field key`,R(n.matchField,t.keyList)));let s=t.validators;return n.validator!==void 0&&s&&!Object.prototype.hasOwnProperty.call(s,n.validator)&&r.push(h("unknown-validator",`${i}/validation/validator`,`the validator "${n.validator}" is not registered`,'Pass it in the "validators" option')),r}function Re(t,{field:e,path:n}){var i;return ((i=e.optionsDependsOn)!=null?i:[]).flatMap((r,s)=>t.keys.has(r)?[]:[h("unknown-field",`${n}/optionsDependsOn/${s}`,`"${r}" is not a field key`,R(r,t.keyList))])}function Ot(t){return t.entries.flatMap(e=>[...Ee(e),...Ie(e),...De(t,e),...Re(t,e)])}function Ve({definition:t,entries:e,keys:n}){var o;let i=new Map,r=(u,a)=>{var d;let l=a.filter(c=>n.has(c));if(l.length)for(let c of u)i.set(c,[...(d=i.get(c))!=null?d:[],...l]);},s=u=>{var a,l;return [...(a=u.show)!=null?a:[],...(l=u.showAny)!=null?l:[]].map(d=>d.field)};for(let{field:u}of e)r([u.key],s(u));for(let u of (o=t.steps)!=null?o:[])r(u.fields.map(a=>a.key),s(u));return i}function Oe(t){var i;let e=new Map,n=[];for(let r of t.keys()){if(e.has(r))continue;e.set(r,true);let s=[[r,0]];for(;s.length>0;){let o=s[s.length-1],u=(i=t.get(o[0]))==null?void 0:i[o[1]++];if(u===void 0)e.set(o[0],false),s.pop();else if(e.get(u)){let a=s.map(([l])=>l);n.push([...a.slice(a.indexOf(u)),u]);}else e.has(u)||(e.set(u,true),s.push([u,0]));}}return n}function Ae(t){return Oe(Ve(t)).map(e=>p("condition-cycle",t.keys.get(e[0]).path,`show conditions form a cycle: ${e.join(" -> ")}`,"Remove one of the conditions in the cycle"))}function Me({definition:t}){var i;let e=(i=t.steps)!=null?i:[],n=[];return e.forEach((r,s)=>{var u,a,l;let o=new Set(((u=r.routes)!=null?u:[]).map(d=>d.to).filter(d=>d!==null));for(let d of o){let c=e.findIndex(F=>F.id===d),m=e[c+1],S=(l=(a=e[c])==null?void 0:a.routes)==null?void 0:l.some(F=>{var G,v;return !((G=F.show)!=null&&G.length)&&!((v=F.showAny)!=null&&v.length)});!m||!o.has(m.id)||S||n.push(h("route-fallthrough",`/steps/${c}`,`branch "${d}" from "${r.id}" continues into the sibling branch "${m.id}"`,`Add an unconditional route on "${d}" to the step where the branches meet`));}r.skip&&(r.next===false||!e[1])&&n.push(h("skip-unreachable",`/steps/${s}/skip`,`step "${r.id}" has "skip" but no Continue button or later step`,'Remove "skip", or remove "next": false'));}),n}function At(t){return [...Ae(t),...Me(t)]}var T=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Le={string:[t=>typeof t=="string","a string"],number:[t=>typeof t=="number"&&Number.isFinite(t),"a number"],boolean:[t=>typeof t=="boolean","true or false"],scalar:[t=>["string","number","boolean"].includes(typeof t),"a string, number or boolean"],list:[t=>Array.isArray(t)&&t.every(e=>["string","number"].includes(typeof e)),"an array of strings or numbers"]};function Mt(t,e,n){return Object.entries(e).flatMap(([i,r])=>{let[s,o]=Le[r];return t[i]===void 0||s(t[i])?[]:[p("invalid-type",`${n}/${B(i)}`,`"${i}" must be ${o}`)]})}function w(t,e,n,i,r=false){return t==null&&!r?[]:Array.isArray(t)?t.flatMap((s,o)=>T(s)?i(s,`${e}/${o}`):[p("invalid-type",`${e}/${o}`,`must be ${n}`)]):[p("invalid-type",e,"must be an array",r?"Use [] when there is nothing to list":void 0)]}function N(t,e,n){return typeof t[e]=="string"?[]:[p("missing-property",`${n}/${e}`,`"${e}" must be a string`)]}var ht=(t,e)=>Mt(t,{field:"string",eq:"scalar",neq:"scalar",in:"list",notIn:"list",notEmpty:"boolean",gt:"number",gte:"number",lt:"number",lte:"number"},e);function gt(t,e){return [...w(t.show,`${e}/show`,"a condition object",ht),...w(t.showAny,`${e}/showAny`,"a condition object",ht)]}function yt(t,e){return T(t)?w(t.disabled,`${e}/disabled`,"a condition object",ht):[]}var Ne=(t,e)=>N(t,"value",e),Te={minLength:"number",maxLength:"number",min:"number",max:"number",pattern:"string",matchField:"string",validator:"string"};function je(t,e){return t===void 0?[]:T(t)?Mt(t,Te,e):[p("invalid-type",e,"must be an object of validation rules")]}function Pe(t,e){return t===void 0||Array.isArray(t)&&t.every(i=>typeof i=="string")?[]:[p("invalid-type",e,"must be an array of field keys")]}var Lt=(t,e)=>[...N(t,"key",e),...N(t,"type",e),...gt(t,e),...w(t.options,`${e}/options`,"an option object",Ne),...je(t.validation,`${e}/validation`),...Pe(t.optionsDependsOn,`${e}/optionsDependsOn`)],_e=(t,e)=>[...t.to===null||typeof t.to=="string"?[]:[p("missing-property",`${e}/to`,'"to" must be a step id or null')],...gt(t,e)],Ke=(t,e)=>[...N(t,"id",e),...w(t.fields,`${e}/fields`,"a field object",Lt,true),...gt(t,e),...w(t.routes,`${e}/routes`,"a route object",_e),...["next","back","skip"].flatMap(n=>yt(t[n],`${e}/${n}`))];function Nt(t){return T(t)?[...w(t.fields,"/fields","a field object",Lt),...w(t.steps,"/steps","a step object",Ke),...yt(t.submit,"/submit"),...yt(t.cancel,"/cancel")]:[p("invalid-type","","the form definition must be an object")]}function Tt(t){return [...N(t,"id",""),...typeof t.title=="string"?[]:[h("missing-property","/title",'"title" must be a string',"Add a title for host UI and editors")],...T(t.submit)?[]:[p("missing-property","/submit","the submit action is missing",'Add "submit": { "label": "Submit" }')]]}var H=t=>{var e,n;return !!((e=t.show)!=null&&e.length||(n=t.showAny)!=null&&n.length)};function jt(t,e,n){var r;let i=[];for(let s of (r=t[n].routes)!=null?r:[]){let o=s.to===null?null:e.get(s.to);if(o===null&&!H(s))return i;if(!(o==null||o<=n)&&(i.push(o),!H(s)&&!H(t[o])))return i}return n+1<t.length?[...i,n+1]:i}function Pt(t){let e=new Map(t.map((n,i)=>[n.id,i]));return t.map((n,i)=>{let r=new Set,s=jt(t,e,i);for(;s.length;){let o=s.pop();r.has(o)||(r.add(o),s.push(...jt(t,e,o)),H(t[o])&&o+1<t.length&&s.push(o+1));}return r})}var Ge=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]);function qe({definition:t}){var r;let e=[],n=(r=t.steps)!=null?r:[],i=new Map;return n.forEach((s,o)=>{let u=i.get(s.id);u===void 0?i.set(s.id,o):e.push(p("duplicate-step-id",`/steps/${o}/id`,`step id "${s.id}" is already used by /steps/${u}`,"Give each step a unique id"));}),n.forEach((s,o)=>{var u;return ((u=s.routes)!=null?u:[]).forEach((a,l)=>{if(a.to===null)return;let d=i.get(a.to);if(d!==void 0&&d>o)return;let c=n.slice(o+1).map(F=>F.id),m=d===void 0?`"${a.to}" is not a step id`:`"${a.to}" is not a later step`,S=c.length?`${E(c)}, or null to end the form here`:"Use null to end the form here";e.push(p("route-target",`/steps/${o}/routes/${l}/to`,m,S));})}),e}function Be({definition:t,entries:e}){var s;let n=[],i=Pt((s=t.steps)!=null?s:[]),r=(o,u)=>{var a;return o.step!==u.step&&!((a=i[o.step])!=null&&a.has(u.step))};return e.forEach((o,u)=>{let{field:a,path:l}=o,d=e.slice(0,u).find(c=>c.field.key===a.key&&!r(c,o));Ge.has(a.key)?n.push(p("reserved-key",`${l}/key`,`"${a.key}" is a built-in object property name`,"Rename the field key")):d&&n.push(p("duplicate-key",`${l}/key`,`key "${a.key}" is already used by ${d.path} on the same path`,"Rename one of the fields, or move them to route branches that never meet"));}),n}function _t(t){var i,r;let{definition:e}=t;return [...!!((i=e.fields)!=null&&i.length)&&!!((r=e.steps)!=null&&r.length)?[p("fields-and-steps","",'the definition has both "fields" and "steps"','Move the top-level fields into a step, or remove "steps"')]:[],...qe(t),...Be(t)]}function Ue(t){return [...t.filter(D),...t.filter(e=>!D(e))]}function j(t,e={}){let n=Nt(t);if(n.length)return n;let i=Rt(t,e.validators);return Ue([...Tt(t),..._t(i),...Dt(i),...Ot(i),...At(i)])}function Y(t,e){let n=j(t,e).filter(D);if(n.length)throw new k(n);return t}function J(t){var e,n;return [...(e=t.show)!=null?e:[],...(n=t.showAny)!=null?n:[]].map(i=>i.field)}function z(t){var e,n;return (e=t.steps)!=null&&e.length?t.steps.flatMap(i=>i.fields):(n=t.fields)!=null?n:[]}function V(t,e){let n={};for(let i of t)i.defaultValue!==void 0&&(n[i.key]=i.defaultValue);return Object.assign(n,e)}function I(t,e){let n=new Set([...Object.keys(t),...Object.keys(e)]);return new Set([...n].filter(i=>!Object.is(t[i],e[i])))}var bt=class extends Error{constructor(n,i){super(`The action completed, but ${n} failed: ${i instanceof Error?i.message:String(i)}`);this.phase=n;this.committed=true;this.name="FormLifecycleError",this.cause=i;}};async function W(t,e){try{await e();}catch(n){throw new bt(t,n)}}function Kt(t){return t.visibleSteps.map(e=>e.id).join(`
5
- `)}function P(t,e){let n=Kt(t);return ()=>Kt(t)!==n||Object.keys(e).some(i=>e[i]!==void 0&&!Object.is(t.values[i],e[i]))}var y={email:"Enter a valid email",number:"Enter a number",boolean:"Must be true or false",option:"Select one of the available options",options:"Must be a list of available options",string:"Must be text",date:"Enter a valid date",datetime:"Enter a valid date and time",file:"Must be a file reference",value:"Invalid value"};function x(t,e){var n,i;switch(t){case "required":return "This field is required";case "minLength":return `Must be at least ${e==null?void 0:e.min} ${(n=e==null?void 0:e.unit)!=null?n:"characters"}`;case "maxLength":return `Must be at most ${e==null?void 0:e.max} ${(i=e==null?void 0:e.unit)!=null?i:"characters"}`;case "min":return `Must be at least ${e==null?void 0:e.min}`;case "max":return `Must be at most ${e==null?void 0:e.max}`;case "pattern":return "Invalid format";case "matchField":return "Fields must match";default:return "Invalid value"}}function g(t,e){var i,r;let n=s=>dt(s,e);return ((i=t.show)!=null?i:[]).every(n)&&(!((r=t.showAny)!=null&&r.length)||t.showAny.some(n))}var St=new Set(["checkbox","switch"]),He=new Set(["text","email","phone","number","password","select","autocomplete","multiselect","checkbox","radio","switch","date","datetime","textarea"]),_=1e4,Ye=254,Je=1e3,ze=/^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/,We=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/,Gt="\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])",Xe=new RegExp(`^${Gt}$`),Qe=new RegExp(`^${Gt}T(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d{1,3})?)?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)?$`),Ze=new Set(["text","phone","password","textarea","autocomplete"]),tn=new Map([["email",[ze,y.email,Ye]],["date",[Xe,y.date,_]],["datetime",[Qe,y.datetime,_]]]);function qt(t,e){if(t.type!=="number"||typeof e!="string"||!We.test(e))return e;let n=Number(e);return Number.isFinite(n)?n:e}function Bt(t,e){return !t.options||t.options.some(n=>n.value===e)}function Ut(t,e){var i,r,s,o;let n=Math.min(_,(r=(i=t.validation)==null?void 0:i.maxLength)!=null?r:_);return e.length<=n?null:(o=(s=t.validation)==null?void 0:s.maxLengthMessage)!=null?o:x("maxLength",{max:n})}function en(t,e){var i,r;return Array.isArray(e)?e.length>((r=(i=t.options)==null?void 0:i.length)!=null?r:Je)?y.option:e.every(s=>typeof s=="string"&&s.length<=_&&Bt(t,s))?null:y.option:y.options}function X(t,e,n){return typeof e=="string"?Ut(t,e):n}function nn(t,e,[n,i,r]){var s;return typeof e!="string"?i:(s=Ut(t,e))!=null?s:e.length<=r&&n.test(e)?null:i}function rn(t,e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)?null:X(t,e,y.value)}function sn(t,e){return e==null||e===""||t.type==="multiselect"&&Array.isArray(e)&&!e.length}function Ft(t,e){var i;if(sn(t,e))return null;if(St.has(t.type))return typeof e=="boolean"?null:y.boolean;if(t.type==="number")return typeof e=="number"&&Number.isFinite(e)?null:y.number;if(t.type==="multiselect")return en(t,e);if(t.type==="file")return X(t,e,y.file);let n=tn.get(t.type);return n?nn(t,e,n):t.type==="select"||t.type==="radio"?(i=X(t,e,y.option))!=null?i:Bt(t,e)?null:y.option:Ze.has(t.type)?X(t,e,y.string):rn(t,e)}function Ht(t,e){return He.has(t.type)?Ft(t.optionsFrom?M(f({},t),{options:void 0}):t,e):null}function on(t,e){return L(t)||t===false&&St.has(e.type)}function Yt(t,e,n,i){var o,u;let r=n[`min${e}`],s=n[`max${e}`];if(r!==void 0&&t<r)return (o=n[`min${e}Message`])!=null?o:x(`min${e}`,{min:r,unit:i});if(s!==void 0&&t>s)return (u=n[`max${e}Message`])!=null?u:x(`max${e}`,{max:s,unit:i})}function an(t,e){var n;if(e.pattern!==void 0)try{return new RegExp(e.pattern).test(String(t))?void 0:(n=e.patternMessage)!=null?n:x("pattern")}catch(i){return}}function O(t,e,n,i){var l,d,c,m,S;let r=(l=t.validation)!=null?l:{},s=(d=r.matchFieldMessage)!=null?d:x("matchField");if(on(e,t))return r.required?typeof r.required=="string"?r.required:x("required"):r.matchField!==void 0&&!L(n[r.matchField])?s:null;let o=Ht(t,e);if(o)return o;let u=typeof e=="string"||Array.isArray(e)?Yt(e.length,"Length",r,Array.isArray(e)?"items":void 0):typeof e=="number"?Yt(e,"",r):void 0,a=r.matchField!==void 0&&e!==n[r.matchField]?s:void 0;return ((S=(c=u!=null?u:an(e,r))!=null?c:a)!=null?S:r.validator?(m=i==null?void 0:i[r.validator])==null?void 0:m.call(i,e,n):void 0)||null}function $(t,e,n){return Q(t.fields,e,n)}function Q(t,e,n){let i={};for(let r of t){if(!g(r,e))continue;let s=O(r,e[r.key],e,n);s&&(i[r.key]=s);}return i}function Z(t,e,n=false){let i=t.errors;t.state.errors={},t.state.topLevelErrors=[];for(let[s,o]of Object.entries(e))t.visibility.isFieldVisible(s,t.values)?t.errors[s]=o:t.topLevelErrors.push(o);let r=n&&Jt(t,e);t.notify({fieldKeys:I(i,t.errors),structureChanged:r});}function Jt(t,e){let n=Object.keys(e).find(r=>t.errors[r]!==void 0),i=n&&t.isMultiStep?t.visibility.findStepIndex(n,t.values,t.currentStepIndex):null;return i===null||i===t.currentStepIndex?false:(t.state.currentStepIndex=i,true)}function zt(t,e){var i;let n=[];for(let r of t.visibility.allFields)((i=r.validation)==null?void 0:i.matchField)!==e||t.errors[r.key]===void 0||O(r,t.values[r.key],C(t),t.validators)||(delete t.errors[r.key],n.push(r.key));return n}function tt(t){let e=new Set(t.visibleSteps.flatMap(i=>i.fields.map(r=>r.key))),n=Object.keys(t.errors).filter(i=>!e.has(i));for(let i of n)delete t.errors[i];return n}function C(t){return A(t)}function un(t,e){for(let n of [...t.skipped.values()].flat())delete e[n];return e}function K(t,e=false){var s;let n=t.errors,i={};if(t.isMultiStep)for(let o of t.visibleSteps)t.skipped.has(o.id)||Object.assign(i,$(o,C(t),t.validators));else Object.assign(i,Q((s=t.definition.fields)!=null?s:[],C(t),t.validators));t.state.errors=i;let r=e&&Jt(t,i);return t.notify({fieldKeys:I(n,i),structureChanged:r}),i}function Wt(t,e){let n=t.visibility.activeField(e,t.values);if(!n)return null;let i=t.errors[e],r=O(n,t.values[e],C(t),t.validators);r?t.errors[e]=r:delete t.errors[e];let s=Object.is(i,t.errors[e])?[]:[e];return t.notify({fieldKeys:s}),r}function A(t){return un(t,f({},t.visibility.conditionValues(t.values)))}function Xt(t,e){let n=t.values,i=t.errors,r=Object.keys(t.fieldLoading);t.validationEpoch++,t.operationEpoch++,t.state.submitting=false,t.state.values=V(t.visibility.allFields,e),t.state.errors={},t.state.topLevelErrors=[],t.state.fieldLoading={},t.state.stepValidating=false,t.state.currentStepIndex=0,t.skipped.clear(),t.visibility.reconcileHidden(t.values,t.errors);let s=I(n,t.values),o=new Set([...s,...I(i,t.errors),...r]);t.notify({fieldKeys:o,structureChanged:true,valuesChanged:s.size>0});}function vt(t,e){var o,u;let n=(o=t.steps)!=null?o:[],i=new Map(n.map((a,l)=>[a.id,l])),r=[],s={};for(let a=0;a<n.length;){let l=n[a];if(!g(l,s)){a++;continue}r.push(l),Object.assign(s,Zt(l,e,s));let d=(u=l.routes)==null?void 0:u.find(c=>{var m;return g(c,s)&&(c.to===null||((m=i.get(c.to))!=null?m:-1)>a&&g(n[i.get(c.to)],s))});if((d==null?void 0:d.to)===null)break;a=d?i.get(d.to):a+1;}return r}function Qt(t,e,n){var o;let i=(o=t[n])!=null?o:t[t.length-1],r=e.findIndex(u=>u.id===(i==null?void 0:i.id));if(r!==-1)return r;let s=new Map(e.map((u,a)=>[u.id,a]));for(let u=Math.min(n-1,t.length-1);u>=0;u--){let a=s.get(t[u].id);if(a!==void 0)return a}return 0}function Zt(t,e,n){let i=f({},n);for(let s of t.fields)i[s.key]=e[s.key];let r={};for(let s of t.fields)g(s,i)&&e[s.key]!==void 0&&(r[s.key]=e[s.key]);return r}var et=class{constructor(e){this.definition=e;this.source=null;this.activeStepList=[];this.activeValueMap={};}invalidate(){this.source=null;}steps(e){return this.refresh(e),this.activeStepList}values(e){return this.refresh(e),this.activeValueMap}refresh(e){var r,s;if(this.source===e)return;this.source=e,this.activeStepList=vt(this.definition,e);let n={},i=(r=this.definition.steps)!=null&&r.length?this.activeStepList:[{fields:(s=this.definition.fields)!=null?s:[]}];for(let o of i)Object.assign(n,Zt(o,e,n));this.activeValueMap=n;}};function te(t){var i,r;let e=(r=(i=t.currentStep)==null?void 0:i.fields)!=null?r:[],n=f({},t.values);for(let{key:s}of e)delete n[s];return Object.assign(n,V(e))}function kt(t){return vt(t.definition,te(t))[t.currentStepIndex+1]}function nt(t){let e=t.currentStep,n=e.fields.map(({key:r})=>r);t.state.values=te(t);for(let r of n)delete t.errors[r];t.skipped.set(e.id,n),t.visibility.reconcileHidden(t.values,t.errors),t.visibility.markChanged(true,true);let i=tt(t);return t.notify({fieldKeys:[...n,...i],structureChanged:true,valuesChanged:true}),n}function it(t){let e=t.currentStep;e&&t.skipped.delete(e.id);}function ee(t,e){return t.state.currentStepIndex=e,t.notify({structureChanged:true}),nt(t)}async function rt(t,e,n=false){if(t.submitting||t.stepValidating)return false;n||it(t);let i=f({},t.lifecycle),r=false,s=t.validationEpoch,o=++t.operationEpoch,u=A(t),a=P(t,u),l=()=>s!==t.validationEpoch||o!==t.operationEpoch||a();t.state.submitting=true,t.notify();try{if(l()||Object.keys(K(t,!0)).length>0||l())return !1;if(i.onBeforeSubmit){let c=await i.onBeforeSubmit(u);if(l()||c===!1)return !1}if(l())return !1;if(i.onBeforeSubmit){if(Object.keys(K(t,!0)).length>0||l())return !1;u=A(t);}r=!0;let d=[...t.skipped.keys()];return await e(u,[...d]),o!==t.operationEpoch||await W("afterSubmit",()=>{var c;return (c=i.onAfterSubmit)==null?void 0:c.call(i,u,d)}),!0}catch(d){if(!r&&l())return false;throw d}finally{o===t.operationEpoch&&(t.state.submitting=false,t.notify());}}function ne(t){let e=t.currentStep;if(!e)return true;let n=$(e,C(t),t.validators);if(Object.keys(n).length===0)return false;let i=f({},t.errors);return Object.assign(t.errors,n),t.notify({fieldKeys:I(i,t.errors)}),true}function ie(t,e){t.validationEpoch++,t.state.currentStepIndex=e,t.notify({structureChanged:true});}async function re(t,e){var l;if(!t.isMultiStep||t.stepValidating||t.submitting||!((l=t.currentStep)!=null&&l.skip))return false;if(kt(t))return st(t,"next","skip");let n=t.currentStep;if(!e||!n)return false;let i=t.values,r=f({},t.errors),s=false,o=nt(t),u=t.values,a=P(t,f({},u));try{return await rt(t,async(d,c)=>{await e(d,c),s=!0;},!0)}finally{!s&&t.values===u&&!a()&&(t.state.values=i,t.state.errors=f(f({},r),t.errors),t.skipped.delete(n.id),t.notify({fieldKeys:o,structureChanged:true,valuesChanged:true}));}}async function st(t,e,n=e){let i=n==="skip";if(!t.isMultiStep||t.stepValidating||t.submitting||!i&&(e==="next"?t.isLastStep:t.isFirstStep))return false;let r=t.currentStep,s=e==="next"&&!i;if(s&&it(t),s&&ne(t))return false;let o=f({},t.lifecycle),u=t.onStepValidate,a=false,d=t.currentStepIndex+(e==="next"?1:-1),c=i?kt(t):t.visibleSteps[d];if(!c)return false;let m={fromStepId:r.id,toStepId:c.id,reason:n,values:f({},C(t))},S=t.validationEpoch,F=++t.operationEpoch,G=P(t,m.values),v=()=>{var b;return S!==t.validationEpoch||F!==t.operationEpoch||((b=t.currentStep)==null?void 0:b.id)!==r.id||G()};t.state.stepValidating=true,t.notify();try{if(v())return !1;if(s&&u){let b=await u(r.id,m.values);if(v())return !1;if(b&&Object.keys(b).length>0)return Z(t,b),!1}if(o.onBeforeStepChange){let b=await o.onBeforeStepChange(m);if(v()||b===!1)return !1}return v()||s&&ne(t)?!1:(a=!0,i&&nt(t),ie(t,d),await W("afterStepChange",()=>{var b;return (b=o.onAfterStepChange)==null?void 0:b.call(o,m)}),!0)}catch(b){if(!a&&v())return false;throw b}finally{F===t.operationEpoch&&(t.state.stepValidating=false,t.notify());}}function se(t,e){if(!t.isMultiStep)return;let n=t.visibility.findStepIndex(e,t.values,t.currentStepIndex);n===t.currentStepIndex?t.notify():n!==null&&ie(t,n);}var ot=class{constructor(){this.version=0;this.listeners=new Set;this.fieldVersions=new Map;this.fieldListeners=new Map;this.structureVersion=0;this.structureListeners=new Set;}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getSnapshot(){return this.version}subscribeField(e,n){var r;let i=(r=this.fieldListeners.get(e))!=null?r:new Set;return i.add(n),this.fieldListeners.set(e,i),()=>{i.delete(n),i.size===0&&this.fieldListeners.delete(e);}}getFieldSnapshot(e){var n;return (n=this.fieldVersions.get(e))!=null?n:0}subscribeStructure(e){return this.structureListeners.add(e),()=>this.structureListeners.delete(e)}getStructureSnapshot(){return this.structureVersion}notify({fieldKeys:e=[],structureChanged:n=false}={}){for(let i of new Set(e))this.notifyField(i);n&&this.notifyStructure(),this.version++;for(let i of this.listeners)i();}notifyField(e){var n,i;this.fieldVersions.set(e,((n=this.fieldVersions.get(e))!=null?n:0)+1);for(let r of (i=this.fieldListeners.get(e))!=null?i:[])r();}notifyStructure(){this.structureVersion++;for(let e of this.structureListeners)e();}};function ln(){try{return process.env.NODE_ENV==="production"}catch(t){return false}}function oe(t){ln()||console.warn(`[formhaus] ${t.message}`);}function wt(t,e){var n;for(let i of J(t)){let r=(n=e.get(i))!=null?n:new Set;r.add(t),e.set(i,r);}}var at=class{constructor(e){this.definition=e;this.fieldsByKey=new Map;this.routeFields=new Set;this.fieldDependents=new Map;this.stepDependents=new Map;this.stepOfField=new Map;this.visibilityDirty=true;this.canGoNextDirty=true;this.cache={visibleSteps:[],currentStep:null,visibleFields:[],canGoNext:false};var n,i;this.allFields=z(e);for(let r of this.allFields)this.fieldsByKey.set(r.key,[...(n=this.fieldsByKey.get(r.key))!=null?n:[],r]);this.path=new et(e);for(let r of (i=e.steps)!=null?i:[])for(let s of r.fields)this.stepOfField.set(s,r);this.buildIndexes();}markChanged(e,n){(e||n)&&this.path.invalidate(),e?(this.visibilityDirty=true,this.canGoNextDirty=true):n&&(this.canGoNextDirty=true);}state(e,n){return this.recomputeVisibility(e,n),this.cache}getCanGoNext(e,n,i){if(this.recomputeVisibility(e,n),!this.canGoNextDirty)return this.cache.canGoNext;this.canGoNextDirty=false;let r=this.cache.currentStep,s=r?$(r,this.conditionValues(e),i):{};return this.cache.canGoNext=this.isMultiStep&&Object.keys(s).length===0,this.cache.canGoNext}findStepIndex(e,n,i){let s=this.state(n,i).visibleSteps.findIndex(o=>o.fields.some(u=>u.key===e));return s===-1?null:s}affectsStructure(e,n){return this.routeFields.has(e)||this.fieldDependents.has(e)||this.stepDependents.has(e)||n.size>0}cascadeHiddenFields(e,n){return this.reconcileHidden(e,n)}reconcileHidden(e,n){this.path.invalidate();let i=new Set([...this.fieldDependents.keys(),...this.stepDependents.keys()]);return this.drainQueue(i,e,n)}drainQueue(e,n,i){let r=[...e],s=new Set(r),o=new Set,u=a=>{delete n[a],delete i[a],this.path.invalidate(),o.add(a),!s.has(a)&&(s.add(a),r.push(a));};for(let a=0;a<r.length;a++){let l=r[a];s.delete(l),this.clearHiddenFields(this.fieldDependents.get(l),n,i,u),this.clearHiddenSteps(this.stepDependents.get(l),n,i,u);}return o}activeField(e,n){var i;return (i=this.fieldsByKey.get(e))==null?void 0:i.find(r=>this.onPath(r,n)&&g(r,this.conditionValues(n)))}isFieldVisible(e,n){return this.activeField(e,n)!==void 0}conditionValues(e){return this.path.values(e)}onPath(e,n){let i=this.stepOfField.get(e);return !i||this.path.steps(n).includes(i)}get isMultiStep(){var e;return ((e=this.definition.steps)!=null?e:[]).length>0}buildIndexes(){var e,n;for(let i of this.allFields)wt(i,this.fieldDependents);for(let i of (e=this.definition.steps)!=null?e:[]){wt(i,this.stepDependents);for(let r of (n=i.routes)!=null?n:[])for(let s of J(r))this.routeFields.add(s);}}recomputeVisibility(e,n){var s,o,u;if(!this.visibilityDirty)return;if(this.visibilityDirty=false,!this.isMultiStep){this.cache.visibleSteps=[],this.cache.currentStep=null,this.cache.visibleFields=((s=this.definition.fields)!=null?s:[]).filter(a=>g(a,this.conditionValues(e)));return}this.cache.visibleSteps=this.path.steps(e);let i=this.cache.visibleSteps;this.cache.currentStep=(u=(o=i[n])!=null?o:i[i.length-1])!=null?u:null;let r=this.cache.currentStep;this.cache.visibleFields=r?r.fields.filter(a=>g(a,this.conditionValues(e))):[];}clearHiddenFields(e,n,i,r){for(let s of e!=null?e:[])this.onPath(s,n)&&(g(s,this.conditionValues(n))||n[s.key]===void 0&&i[s.key]===void 0||r(s.key));}clearHiddenSteps(e,n,i,r){for(let s of e!=null?e:[])if(!g(s,this.conditionValues(n)))for(let o of s.fields)n[o.key]===void 0&&i[o.key]===void 0||r(o.key);}};var ut=class{constructor(e,n,i){this.definition=e;this.skipped=new Map;this.validationEpoch=0;this.operationEpoch=0;this.subscriptions=new ot;var a,l;this.lifecycle=i!=null?i:{},this.validators=(a=i==null?void 0:i.validators)!=null?a:{};let r=j(e,{validators:this.validators}),s=r.filter(D);if(s.length)throw new k(s);let o=(l=this.lifecycle.onWarning)!=null?l:oe;for(let d of r)o(d);this.visibility=new at(e);let u=V(this.visibility.allFields,n);this.state={values:u,errors:{},topLevelErrors:[],currentStepIndex:0,fieldLoading:{},stepValidating:false,submitting:false},this.visibility.reconcileHidden(u,this.state.errors);}get onStepValidate(){return this.lifecycle.onStepValidate}get values(){return this.state.values}get errors(){return this.state.errors}get topLevelErrors(){return this.state.topLevelErrors}get currentStepIndex(){return this.state.currentStepIndex}get fieldLoading(){return this.state.fieldLoading}get stepValidating(){return this.state.stepValidating}get submitting(){return this.state.submitting}get isMultiStep(){var e;return ((e=this.definition.steps)!=null?e:[]).length>0}get visibleSteps(){return this.visibility.state(this.state.values,this.currentStepIndex).visibleSteps}get currentStep(){return this.visibility.state(this.state.values,this.currentStepIndex).currentStep}get visibleFields(){return this.visibility.state(this.state.values,this.currentStepIndex).visibleFields}get isFirstStep(){return this.currentStepIndex===0}get isLastStep(){return this.currentStepIndex>=this.visibleSteps.length-1}get canGoNext(){return this.visibility.getCanGoNext(this.state.values,this.currentStepIndex,this.validators)}get progress(){let e=this.visibleSteps.length;return {current:Math.min(this.currentStepIndex+1,e),total:e}}subscribe(e){return this.subscriptions.subscribe(e)}getSnapshot(){return this.subscriptions.getSnapshot()}subscribeField(e,n){return this.subscriptions.subscribeField(e,n)}getFieldSnapshot(e){return this.subscriptions.getFieldSnapshot(e)}subscribeStructure(e){return this.subscriptions.subscribeStructure(e)}getStructureSnapshot(){return this.subscriptions.getStructureSnapshot()}setValue(e,n){let{values:i,errors:r}=this.state,s=this.isMultiStep?this.visibleSteps:null,o=!Object.is(i[e],n),u=r[e]!==void 0;i[e]=n,delete r[e];for(let[S,F]of this.skipped)o&&F.includes(e)&&this.skipped.delete(S);let a=this.visibility.cascadeHiddenFields(i,r),l=zt(this.internals,e),d=new Set([...a,...l]);(o||u)&&d.add(e);let c=o||a.size>0,m=c&&this.visibility.affectsStructure(e,a);if(s&&m){this.visibility.markChanged(true,true),this.state.currentStepIndex=Qt(s,this.visibleSteps,this.currentStepIndex);for(let S of tt(this.internals))d.add(S);}this.notify({fieldKeys:d,structureChanged:m,valuesChanged:c});}setErrors(e){Z(this.internals,e,true);}setFieldLoading(e,n){let i=this.state.fieldLoading[e]===true;n?this.state.fieldLoading[e]=true:delete this.state.fieldLoading[e],this.notify({fieldKeys:i===n?[]:[e]});}cancelPendingActions(){this.validationEpoch++,this.operationEpoch++,this.state.stepValidating=false,this.state.submitting=false,this.notify();}next(){return st(this.internals,"next")}back(){return st(this.internals,"back")}skip(e){return re(this.internals,e)}submit(e){return rt(this.internals,e)}isStepSkipped(e){return this.skipped.has(e)}validate(){return K(this.internals)}validateField(e){return Wt(this.internals,e)}getSubmitValues(){return A(this.internals)}goToStepWithField(e){se(this.internals,e);}reset(e){Xt(this.internals,e);}get internals(){return this}notify(e={}){this.visibility.markChanged(!!e.structureChanged,!!e.valuesChanged),this.subscriptions.notify(e);}};var dn='Pass the values object as the second argument, not the request body with "values" and "skippedSteps".',cn=()=>null,lt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function fn(t,e){let n=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},i={};for(let r of t)lt(n,r.key)&&(i[r.key]=qt(r,n[r.key]));return i}function pn(t,e){let n=new Map;for(let i of t){let r=lt(e,i.key)?Ft(i,e[i.key]):null;r&&n.set(i.key,r);}return n}function mn(t,e){var r;let n=s=>s.map(o=>e.has(o.key)?M(f({},o),{validation:void 0}):o),i=(r=t.steps)==null?void 0:r.map(s=>M(f({},s),{fields:n(s.fields)}));return f(f(f({},t),t.fields&&{fields:n(t.fields)}),i&&{steps:i})}function hn(t,e={}){let n={};for(let{validation:i}of t)i!=null&&i.validator&&(n[i.validator]=cn);return f(f({},n),e)}function yn(t,e){return e===null||typeof e!="object"||!lt(e,"values")?false:!t.some(n=>n.key==="values"||n.key==="skippedSteps")}function gn(t,e){if(!Array.isArray(e))return;let n=new Set(e);for(let i=0;i<t.visibleSteps.length;i++){let r=t.visibleSteps[i];r.skip&&n.has(r.id)&&ee(t,i);}}function bn(t,e,n={}){Y(t);let i=z(t),r=fn(i,e),s=pn(i,r),o={validators:hn(i,n.validators),onWarning:()=>{}},u=new ut(mn(t,s),r,o);gn(u,n.skippedSteps);let a=u.validate(),l=u.getSubmitValues();for(let[d,c]of s)lt(l,d)&&(a[d]=c);return yn(i,e)&&(a.values=dn),{values:l,errors:a}}exports.FormDefinitionError=k;exports.checkDefinition=j;exports.parseDefinition=Y;exports.validateSubmission=bn;return exports;})({});//# sourceMappingURL=server.iife.js.map
4
+ `)}`),this.name="FormDefinitionError",this.issues=e;}};function Nt(t){return (e,n,r,i)=>m({code:e,severity:t,path:n,message:`${n||"/"}: ${r}.${i?` ${i}.`:""}`},i&&{hint:`${i}.`})}var h=Nt("error"),E=Nt("warning");function et(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Pt(t){return t.severity==="error"}function N(t){if(t.length===1)return `Use ${JSON.stringify(t[0])}`;let e=t.slice(0,10).map(n=>JSON.stringify(n)).join(", ");return t.length>10?`Use one of: ${e}, ...`:`Use one of: ${e}`}function Re(t,e){let n=Array.from({length:e.length+1},(r,i)=>i);for(let r=1;r<=t.length;r++){let i=[r];for(let o=1;o<=e.length;o++)i[o]=Math.min(n[o]+1,i[o-1]+1,n[o-1]+(t[r-1]===e[o-1]?0:1));n=i;}return n[e.length]}function kt(t,e){let n=t.toLowerCase();return e.find(r=>r!==t&&Re(n,r.toLowerCase())<=(r.length>4?2:1))}function W(t,e){let n=kt(t,e);return n!==void 0?`Use ${JSON.stringify(n)}`:e.length?N(e):void 0}var Y=jt;function Ve({suggest:t},e,n){let r=Object.keys(e).filter(a=>a!=="field"),i=r.filter(a=>!Y.includes(a)),o=i.map(a=>h("unknown-operator",`${n}/${et(a)}`,`"${a}" is not a condition operator`,t(a,[...Y]))),s=r.length-i.length;if(s!==1&&!(s===0&&i.length)){let a=s?`the condition has ${s} operators`:"the condition has no operator";o.push(h("condition-operator-count",n,a,`Use exactly one of: ${Y.join(", ")}`));}return o}function Oe(t,{condition:e,path:n,owner:r,step:i,key:o}){let s=t.keys.get(e.field);if(!s){let d=t.keyList.filter(l=>l!==o);return [h("unknown-field",`${n}/field`,`"${e.field}" is not a field key`,t.suggest(e.field,d))]}if(i<0||r==="action")return [];let a=r==="step"?"this or a later step":"a later step";if(s.step<i||r!=="step"&&s.step===i)return [];let u=r==="step"?"earlier steps":"this or an earlier step";return [h("forward-reference",`${n}/field`,`"${e.field}" belongs to ${a}`,`${r==="route"?"Route":r==="step"?"Step":"Field"} conditions can use fields of ${u}`)]}function St(t,e){let{condition:n,path:r}=e;return typeof n.field!="string"?[h("missing-property",`${r}/field`,'the condition has no "field"',"Add the key of the field to test")]:[...Ve(t,n,r),...Oe(t,e)]}function _t(t){return t.conditions.flatMap(e=>St(t,e))}function wt(t,e,n,r,i,o){var s;for(let a of ["show","showAny"])((s=e[a])!=null?s:[]).forEach((u,d)=>t.push({condition:u,path:`${n}/${a}/${d}`,owner:r,step:i,key:o}));}function vt(t,e,n,r){var i;(e?(i=e.disabled)!=null?i:[]:[]).forEach((o,s)=>t.push({condition:o,path:`${n}/disabled/${s}`,owner:"action",step:r}));}function qt(t,e,n=()=>{}){var a,u;let r=(a=t.steps)!=null?a:[],i=r.length?r.flatMap((d,l)=>d.fields.map((c,f)=>({field:c,path:`/steps/${l}/fields/${f}`,step:l}))):((u=t.fields)!=null?u:[]).map((d,l)=>({field:d,path:`/fields/${l}`,step:-1})),o=new Map;for(let d of i)o.has(d.field.key)||o.set(d.field.key,d);let s=[];for(let d of i)wt(s,d.field,d.path,"field",d.step,d.field.key);return r.forEach((d,l)=>{var c;wt(s,d,`/steps/${l}`,"step",l),((c=d.routes)!=null?c:[]).forEach((f,b)=>wt(s,f,`/steps/${l}/routes/${b}`,"route",l));for(let f of ["next","back","skip"])vt(s,d[f],`/steps/${l}/${f}`,l);}),vt(s,t.submit,"/submit",-1),vt(s,t.cancel,"/cancel",-1),{definition:t,entries:i,keys:o,keyList:[...o.keys()],conditions:s,validators:e,suggest:n}}function Kt(t,e,n,r){let i=t[n],o=t[r];return i===void 0||o===void 0||i<=o?[]:[h("invalid-range",`${e}/validation/${n}`,`${n} (${i}) is greater than ${r} (${o})`,`Lower ${n} or raise ${r}`)]}function Ae(t,e){if(t===void 0)return [];try{return new RegExp(t),[]}catch(n){return [h("invalid-pattern",`${e}/validation/pattern`,`${JSON.stringify(t)} is not a valid regular expression`,"Fix the pattern or escape special characters with a backslash")]}}function Me(t,{field:e,path:n}){let r=e.validation;if(!r)return [];let i=r.matchField;return [...Kt(r,n,"minLength","maxLength"),...Kt(r,n,"min","max"),...Ae(r.pattern,n),...i===void 0||t.keys.has(i)?[]:[h("unknown-field",`${n}/validation/matchField`,`"${i}" is not a field key`,t.suggest(i,t.keyList))]]}function Bt(t){return t.entries.flatMap(e=>Me(t,e))}function Le({definition:t,entries:e,keys:n}){var s;let r=new Map,i=(a,u)=>{var l;let d=u.filter(c=>n.has(c));if(d.length)for(let c of a)r.set(c,[...(l=r.get(c))!=null?l:[],...d]);},o=a=>{var u,d;return [...(u=a.show)!=null?u:[],...(d=a.showAny)!=null?d:[]].map(l=>l.field)};for(let{field:a}of e)i([a.key],o(a));for(let a of (s=t.steps)!=null?s:[])i(a.fields.map(u=>u.key),o(a));return r}function Te(t){var r;let e=new Map,n=[];for(let i of t.keys()){if(e.has(i))continue;e.set(i,true);let o=[[i,0]];for(;o.length>0;){let s=o[o.length-1],a=(r=t.get(s[0]))==null?void 0:r[s[1]++];if(a===void 0)e.set(s[0],false),o.pop();else if(e.get(a)){let u=o.map(([d])=>d);n.push([...u.slice(u.indexOf(a)),a]);}else e.has(a)||(e.set(a,true),o.push([a,0]));}}return n}function je(t){return Te(Le(t)).map(e=>h("condition-cycle",t.keys.get(e[0]).path,`show conditions form a cycle: ${e.join(" -> ")}`,"Remove one of the conditions in the cycle"))}function Gt(t){return je(t)}var J=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Ne={string:[t=>typeof t=="string","a string"],number:[t=>typeof t=="number"&&Number.isFinite(t),"a number"],boolean:[t=>typeof t=="boolean","true or false"],scalar:[t=>["string","number","boolean"].includes(typeof t),"a string, number or boolean"],list:[t=>Array.isArray(t)&&t.every(e=>["string","number"].includes(typeof e)),"an array of strings or numbers"]};function Ut(t,e,n){return Object.entries(e).flatMap(([r,i])=>{let[o,s]=Ne[i];return t[r]===void 0||o(t[r])?[]:[h("invalid-type",`${n}/${et(r)}`,`"${r}" must be ${s}`)]})}function D(t,e,n,r,i=false){return t==null&&!i?[]:Array.isArray(t)?t.flatMap((o,s)=>J(o)?r(o,`${e}/${s}`):[h("invalid-type",`${e}/${s}`,`must be ${n}`)]):[h("invalid-type",e,"must be an array",i?"Use [] when there is nothing to list":void 0)]}function H(t,e,n){return typeof t[e]=="string"?[]:[h("missing-property",`${n}/${e}`,`"${e}" must be a string`)]}var xt=(t,e)=>Ut(t,{field:"string",eq:"scalar",neq:"scalar",in:"list",notIn:"list",notEmpty:"boolean",gt:"number",gte:"number",lt:"number",lte:"number"},e);function It(t,e){return [...D(t.show,`${e}/show`,"a condition object",xt),...D(t.showAny,`${e}/showAny`,"a condition object",xt)]}function Et(t,e){return J(t)?D(t.disabled,`${e}/disabled`,"a condition object",xt):[]}var Pe=(t,e)=>H(t,"value",e),_e={minLength:"number",maxLength:"number",min:"number",max:"number",pattern:"string",matchField:"string",validator:"string"};function qe(t,e){return t===void 0?[]:J(t)?Ut(t,_e,e):[h("invalid-type",e,"must be an object of validation rules")]}function Ke(t,e){return t===void 0||Array.isArray(t)&&t.every(r=>typeof r=="string")?[]:[h("invalid-type",e,"must be an array of field keys")]}var Wt=(t,e)=>[...H(t,"key",e),...H(t,"type",e),...It(t,e),...D(t.options,`${e}/options`,"an option object",Pe),...qe(t.validation,`${e}/validation`),...Ke(t.optionsDependsOn,`${e}/optionsDependsOn`)],Be=(t,e)=>[...t.to===null||typeof t.to=="string"?[]:[h("missing-property",`${e}/to`,'"to" must be a step id or null')],...It(t,e)],Ge=(t,e)=>[...H(t,"id",e),...D(t.fields,`${e}/fields`,"a field object",Wt,true),...It(t,e),...D(t.routes,`${e}/routes`,"a route object",Be),...["next","back","skip"].flatMap(n=>Et(t[n],`${e}/${n}`))];function Yt(t){return J(t)?[...D(t.fields,"/fields","a field object",Wt),...D(t.steps,"/steps","a step object",Ge),...Et(t.submit,"/submit"),...Et(t.cancel,"/cancel")]:[h("invalid-type","","the form definition must be an object")]}function Ht(t){return [...H(t,"id",""),...J(t.submit)?[]:[h("missing-property","/submit","the submit action is missing",'Add "submit": { "label": "Submit" }')]]}var nt=t=>{var e,n;return !!((e=t.show)!=null&&e.length||(n=t.showAny)!=null&&n.length)};function Jt(t,e,n){var i;let r=[];for(let o of (i=t[n].routes)!=null?i:[]){let s=o.to===null?null:e.get(o.to);if(s===null&&!nt(o))return r;if(!(s==null||s<=n)&&(r.push(s),!nt(o)&&!nt(t[s])))return r}return n+1<t.length?[...r,n+1]:r}function zt(t){let e=new Map(t.map((n,r)=>[n.id,r]));return t.map((n,r)=>{let i=new Set,o=Jt(t,e,r);for(;o.length;){let s=o.pop();i.has(s)||(i.add(s),o.push(...Jt(t,e,s)),nt(t[s])&&s+1<t.length&&o.push(s+1));}return i})}var Ue=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]);function We({definition:t}){var i;let e=[],n=(i=t.steps)!=null?i:[],r=new Map;return n.forEach((o,s)=>{let a=r.get(o.id);a===void 0?r.set(o.id,s):e.push(h("duplicate-step-id",`/steps/${s}/id`,`step id "${o.id}" is already used by /steps/${a}`,"Give each step a unique id"));}),n.forEach((o,s)=>{var a;return ((a=o.routes)!=null?a:[]).forEach((u,d)=>{if(u.to===null)return;let l=r.get(u.to);if(l!==void 0&&l>s)return;let c=n.slice(s+1).map(F=>F.id),f=l===void 0?`"${u.to}" is not a step id`:`"${u.to}" is not a later step`,b=c.length?`${N(c)}, or null to end the form here`:"Use null to end the form here";e.push(h("route-target",`/steps/${s}/routes/${d}/to`,f,b));})}),e}function Ye({definition:t,entries:e}){var o;let n=[],r=zt((o=t.steps)!=null?o:[]),i=(s,a)=>{var u;return s.step!==a.step&&!((u=r[s.step])!=null&&u.has(a.step))};return e.forEach((s,a)=>{let{field:u,path:d}=s,l=e.slice(0,a).find(c=>c.field.key===u.key&&!i(c,s));Ue.has(u.key)?n.push(h("reserved-key",`${d}/key`,`"${u.key}" is a built-in object property name`,"Rename the field key")):l&&n.push(h("duplicate-key",`${d}/key`,`key "${u.key}" is already used by ${l.path} on the same path`,"Rename one of the fields, or move them to route branches that never meet"));}),n}function Xt(t){var r,i;let{definition:e}=t;return [...!!((r=e.fields)!=null&&r.length)&&!!((i=e.steps)!=null&&i.length)?[h("fields-and-steps","",'the definition has both "fields" and "steps"','Move the top-level fields into a step, or remove "steps"')]:[],...We(t),...Ye(t)]}var w={email:"Enter a valid email",number:"Enter a number",boolean:"Must be true or false",option:"Select one of the available options",options:"Must be a list of available options",string:"Must be text",date:"Enter a valid date",datetime:"Enter a valid date and time",file:"Must be a file reference",value:"Invalid value"};function R(t,e){var n,r;switch(t){case "required":return "This field is required";case "minLength":return `Must be at least ${e==null?void 0:e.min} ${(n=e==null?void 0:e.unit)!=null?n:"characters"}`;case "maxLength":return `Must be at most ${e==null?void 0:e.max} ${(r=e==null?void 0:e.unit)!=null?r:"characters"}`;case "min":return `Must be at least ${e==null?void 0:e.min}`;case "max":return `Must be at most ${e==null?void 0:e.max}`;case "pattern":return "Invalid format";case "matchField":return "Fields must match";default:return "Invalid value"}}var P=["checkbox","switch"],X=["text","email","phone","number","password","select","autocomplete","multiselect","checkbox","radio","switch","file","date","datetime","textarea"],z=1e4,He=254,Je=1e3,ze=/^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/,Xe=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/,Zt="\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])",Ze=new RegExp(`^${Zt}$`),Qe=new RegExp(`^${Zt}T(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d{1,3})?)?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)?$`),tn=new Set(["text","phone","password","textarea","autocomplete"]),en=new Map([["email",[ze,w.email,He]],["date",[Ze,w.date,z]],["datetime",[Qe,w.datetime,z]]]);function Qt(t,e){if(t.type!=="number"||typeof e!="string"||!Xe.test(e))return e;let n=Number(e);return Number.isFinite(n)?n:e}function te(t,e){return !t.options||t.options.some(n=>n.value===e)}function ee(t,e){var r,i,o,s;let n=Math.min(z,(i=(r=t.validation)==null?void 0:r.maxLength)!=null?i:z);return e.length<=n?null:(s=(o=t.validation)==null?void 0:o.maxLengthMessage)!=null?s:R("maxLength",{max:n})}function nn(t,e){var r,i;return Array.isArray(e)?e.length>((i=(r=t.options)==null?void 0:r.length)!=null?i:Je)?w.option:e.every(o=>typeof o=="string"&&o.length<=z&&te(t,o))?null:w.option:w.options}function rt(t,e,n){return typeof e=="string"?ee(t,e):n}function rn(t,e,[n,r,i]){var o;return typeof e!="string"?r:(o=ee(t,e))!=null?o:e.length<=i&&n.test(e)?null:r}function on(t,e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)?null:rt(t,e,w.value)}function sn(t,e){return e==null||e===""||t.type==="multiselect"&&Array.isArray(e)&&!e.length}function Ct(t,e){var r;if(sn(t,e))return null;if(P.includes(t.type))return typeof e=="boolean"?null:w.boolean;if(t.type==="number")return typeof e=="number"&&Number.isFinite(e)?null:w.number;if(t.type==="multiselect")return nn(t,e);if(t.type==="file")return rt(t,e,w.file);let n=en.get(t.type);return n?rn(t,e,n):t.type==="select"||t.type==="radio"?(r=rt(t,e,w.option))!=null?r:te(t,e)?null:w.option:tn.has(t.type)?rt(t,e,w.string):on(t,e)}function ne(t,e){return t.type==="file"||!X.includes(t.type)?null:Ct(t.optionsFrom?G(m({},t),{options:void 0}):t,e)}var an=["in","notIn"],un=["gt","gte","lt","lte"],ln=["text","email","phone","password","textarea","date","datetime","select","radio","autocomplete"];function dn(t){return t.type==="number"?"number":P.includes(t.type)?"boolean":ln.includes(t.type)?"string":void 0}function cn(t,e,n,r){var l;let i=(c,f)=>[E("condition-value-mismatch",r,c,f)];if(e==="notEmpty")return [];if(un.includes(e))return t.type!=="multiselect"&&!P.includes(t.type)?[]:i(`"${t.key}" is a ${t.type} field, so "${e}" never matches it`,"Compare a number, text, radio or select field");if(t.type==="multiselect"){let c=e==="neq"||e==="notIn"?"always":"never";return i(`"${t.key}" holds a list of values, so "${e}" ${c} matches it`,"Use notEmpty, or a select or radio field")}let o=an.includes(e)&&Array.isArray(n)?n:[n],s=dn(t),a=s&&o.find(c=>typeof c!==s);if(s&&a!==void 0)return i(`${JSON.stringify(a)} is a ${typeof a}, but "${t.key}" holds a ${s}`,`Use a ${s} value`);let u=s==="string"&&!t.optionsFrom&&((l=t.options)!=null&&l.length)?t.options.map(c=>c.value):null,d=u&&o.find(c=>!u.includes(c));return u&&d!==void 0?i(`${JSON.stringify(d)} is not an option of "${t.key}"`,N(u)):[]}function fn(t,e){let{condition:n,path:r}=e;if(St(t,e).length)return [];let i=Y.find(o=>o in n);return cn(t.keys.get(n.field).field,i,n[i],`${r}/${i}`)}function pn({field:t,path:e}){if(!["select","radio","multiselect"].includes(t.type))return [];if(!Array.isArray(t.options))return t.optionsFrom?[]:[E("missing-options",`${e}/options`,`the ${t.type} field "${t.key}" has no options`,'Add "options" or "optionsFrom"')];let n=t.options.map(o=>o.value),r=t.type==="multiselect"&&Array.isArray(t.defaultValue)?t.defaultValue:[t.defaultValue],i=t.defaultValue===void 0||!n.length||t.optionsFrom?void 0:r.find(o=>!n.includes(o));return i===void 0?[]:[E("default-not-in-options",`${e}/defaultValue`,`${JSON.stringify(i)} is not an option of "${t.key}"`,N(n))]}function mn(t,{field:e,path:n}){var c;let r=(c=e.validation)!=null?c:{},i=(f,b,F)=>E("rule-not-applicable",`${n}/validation/${f}`,b,F),o=X.includes(e.type),s=e.type==="number",a=o&&!s?["min","max"].filter(f=>r[f]!==void 0):[],u=o&&["number","checkbox","switch"].includes(e.type)?["minLength","maxLength"].filter(f=>r[f]!==void 0):[],d=[...a.map(f=>i(f,`"${f}" applies to number fields only`,`Use ${f}Length to limit text length`)),...u.map(f=>i(f,`"${f}" does not apply to ${e.type} fields`,s?"Use min and max for numbers":`Remove ${f}`))],{validators:l}=t;return r.validator!==void 0&&l&&!Object.prototype.hasOwnProperty.call(l,r.validator)&&d.push(E("unknown-validator",`${n}/validation/validator`,`the validator "${r.validator}" is not registered`,'Pass it in the "validators" option')),d}function hn(t,e){var o;let{field:n,path:r}=e,i=X.includes(n.type)?void 0:kt(n.type,X);return [...i===void 0?[]:[E("unknown-field-type",`${r}/type`,`"${n.type}" is not a built-in field type`,`Use "${i}", or register a component for "${n.type}"`)],...pn(e),...mn(t,e),...((o=n.optionsDependsOn)!=null?o:[]).flatMap((s,a)=>t.keys.has(s)?[]:[E("unknown-field",`${r}/optionsDependsOn/${a}`,`"${s}" is not a field key`,W(s,t.keyList))])]}function gn({definition:t}){var n;let e=(n=t.steps)!=null?n:[];return e.flatMap((r,i)=>{var a,u,d;let o=[],s=new Set(((a=r.routes)!=null?a:[]).map(l=>l.to).filter(l=>l!==null));for(let l of s){let c=e.findIndex(F=>F.id===l),f=e[c+1],b=(d=(u=e[c])==null?void 0:u.routes)==null?void 0:d.some(F=>{var V,x;return !((V=F.show)!=null&&V.length)&&!((x=F.showAny)!=null&&x.length)});!f||!s.has(f.id)||b||o.push(E("route-fallthrough",`/steps/${c}`,`branch "${l}" from "${r.id}" continues into the sibling branch "${f.id}"`,`Add an unconditional route on "${l}" to the step where the branches meet`));}return r.skip&&(r.next===false||!e[1])&&o.push(E("skip-unreachable",`/steps/${i}/skip`,`step "${r.id}" has "skip" but no Continue button or later step`,'Remove "skip", or remove "next": false')),o})}function re(t){return [...typeof t.definition.title=="string"?[]:[E("missing-property","/title",'"title" must be a string',"Add a title for host UI and editors")],...t.conditions.flatMap(e=>fn(t,e)),...t.entries.flatMap(e=>hn(t,e)),...gn(t)]}function $t(t,{validators:e,suggest:n,warnings:r}={}){let i=Yt(t);if(i.length)return i;let o=qt(t,e,n);return [...Ht(t),...Xt(o),..._t(o),...Bt(o),...Gt(o),...r?r(o):[]]}function ie(t){return $t(t)}function it(t,e={}){return $t(t,{validators:e.validators,suggest:W,warnings:re})}function ot(t,e){let n=$t(t,{suggest:W});if(n.length)throw new $(n);return t}function st(t){var e,n;return [...(e=t.show)!=null?e:[],...(n=t.showAny)!=null?n:[]].map(r=>r.field)}function at(t){var e,n;return (e=t.steps)!=null&&e.length?t.steps.flatMap(r=>r.fields):(n=t.fields)!=null?n:[]}function _(t,e){let n={};for(let r of t)r.defaultValue!==void 0&&(n[r.key]=r.defaultValue);return Object.assign(n,e)}function M(t,e){let n=new Set([...Object.keys(t),...Object.keys(e)]);return new Set([...n].filter(r=>!Object.is(t[r],e[r])))}var Dt=class extends Error{constructor(n,r){super(`The action completed, but ${n} failed: ${r instanceof Error?r.message:String(r)}`);this.phase=n;this.committed=true;this.name="FormLifecycleError",this.cause=r;}};async function ut(t,e){try{await e();}catch(n){throw new Dt(t,n)}}function oe(t){return t.visibleSteps.map(e=>e.id).join(`
5
+ `)}function Z(t,e){let n=oe(t);return ()=>oe(t)!==n||Object.keys(e).some(r=>e[r]!==void 0&&!Object.is(t.values[r],e[r]))}function I(t,e){var r,i;let n=o=>Ft(o,e);return ((r=t.show)!=null?r:[]).every(n)&&(!((i=t.showAny)!=null&&i.length)||t.showAny.some(n))}function yn(t,e){return U(t)||t===false&&P.includes(e.type)}function se(t,e,n,r){var s,a;let i=n[`min${e}`],o=n[`max${e}`];if(i!==void 0&&t<i)return (s=n[`min${e}Message`])!=null?s:R(`min${e}`,{min:i,unit:r});if(o!==void 0&&t>o)return (a=n[`max${e}Message`])!=null?a:R(`max${e}`,{max:o,unit:r})}function bn(t,e){var n;if(e.pattern!==void 0)try{return new RegExp(e.pattern).test(String(t))?void 0:(n=e.patternMessage)!=null?n:R("pattern")}catch(r){return}}function q(t,e,n,r){var d,l,c,f,b;let i=(d=t.validation)!=null?d:{},o=(l=i.matchFieldMessage)!=null?l:R("matchField");if(yn(e,t))return i.required?typeof i.required=="string"?i.required:R("required"):i.matchField!==void 0&&!U(n[i.matchField])?o:null;let s=ne(t,e);if(s)return s;let a=typeof e=="string"||Array.isArray(e)?se(e.length,"Length",i,Array.isArray(e)?"items":void 0):typeof e=="number"?se(e,"",i):void 0,u=i.matchField!==void 0&&e!==n[i.matchField]?o:void 0;return ((b=(c=a!=null?a:bn(e,i))!=null?c:u)!=null?b:i.validator?(f=r==null?void 0:r[i.validator])==null?void 0:f.call(r,e,n):void 0)||null}function L(t,e,n){return lt(t.fields,e,n)}function lt(t,e,n){let r={};for(let i of t){if(!I(i,e))continue;let o=q(i,e[i.key],e,n);o&&(r[i.key]=o);}return r}function dt(t,e,n=false){let r=t.errors;t.state.errors={},t.state.topLevelErrors=[];for(let[o,s]of Object.entries(e))t.visibility.activeField(o,t.values)?t.errors[o]=s:t.topLevelErrors.push(s);let i=n&&ae(t,e);t.notify({fieldKeys:M(r,t.errors),structureChanged:i});}function ae(t,e){let n=Object.keys(e).find(i=>t.errors[i]!==void 0),r=n&&t.isMultiStep?t.visibility.findStepIndex(n,t.values,t.currentStepIndex):null;return r===null||r===t.currentStepIndex?false:(t.state.currentStepIndex=r,true)}function ue(t,e){var r;let n=[];for(let i of t.visibility.allFields)((r=i.validation)==null?void 0:r.matchField)!==e||t.errors[i.key]===void 0||q(i,t.values[i.key],T(t),t.validators)||(delete t.errors[i.key],n.push(i.key));return n}function ct(t){let e=new Set(t.visibleSteps.flatMap(r=>r.fields.map(i=>i.key))),n=Object.keys(t.errors).filter(r=>!e.has(r));for(let r of n)delete t.errors[r];return n}function T(t){return K(t)}function Fn(t,e){for(let n of [...t.skipped.values()].flat())delete e[n];return e}function Q(t,e=false){var o;let n=t.errors,r={};if(t.isMultiStep)for(let s of t.visibleSteps)t.skipped.has(s.id)||Object.assign(r,L(s,T(t),t.validators));else Object.assign(r,lt((o=t.definition.fields)!=null?o:[],T(t),t.validators));t.state.errors=r;let i=e&&ae(t,r);return t.notify({fieldKeys:M(n,r),structureChanged:i}),r}function le(t,e){let n=t.visibility.activeField(e,t.values);if(!n)return null;let r=t.errors[e],i=q(n,t.values[e],T(t),t.validators);i?t.errors[e]=i:delete t.errors[e];let o=Object.is(r,t.errors[e])?[]:[e];return t.notify({fieldKeys:o}),i}function K(t){return Fn(t,m({},t.visibility.conditionValues(t.values)))}function de(t,e){let n=t.values,r=t.errors,i=Object.keys(t.fieldLoading);t.validationEpoch++,t.operationEpoch++,t.state.submitting=false,t.state.values=_(t.visibility.allFields,e),t.state.errors={},t.state.topLevelErrors=[],t.state.fieldLoading={},t.state.stepValidating=false,t.state.currentStepIndex=0,t.skipped.clear(),t.visibility.reconcileHidden(t.values,t.errors);let o=M(n,t.values),s=new Set([...o,...M(r,t.errors),...i]);t.notify({fieldKeys:s,structureChanged:true,valuesChanged:o.size>0});}function Rt(t,e){var s,a;let n=(s=t.steps)!=null?s:[],r=new Map(n.map((u,d)=>[u.id,d])),i=[],o={};for(let u=0;u<n.length;){let d=n[u];if(!I(d,o)){u++;continue}i.push(d),Object.assign(o,fe(d,e,o));let l=(a=d.routes)==null?void 0:a.find(c=>{var f;return I(c,o)&&(c.to===null||((f=r.get(c.to))!=null?f:-1)>u&&I(n[r.get(c.to)],o))});if((l==null?void 0:l.to)===null)break;u=l?r.get(l.to):u+1;}return i}function ce(t,e,n){var s;let r=(s=t[n])!=null?s:t[t.length-1],i=e.findIndex(a=>a.id===(r==null?void 0:r.id));if(i!==-1)return i;let o=new Map(e.map((a,u)=>[a.id,u]));for(let a=Math.min(n-1,t.length-1);a>=0;a--){let u=o.get(t[a].id);if(u!==void 0)return u}return 0}function fe(t,e,n){let r=m({},n);for(let o of t.fields)r[o.key]=e[o.key];let i={};for(let o of t.fields)I(o,r)&&e[o.key]!==void 0&&(i[o.key]=e[o.key]);return i}function pe(t){let e=null,n=[],r={},i=o=>{var u,d;if(e===o)return;e=o,n=Rt(t,o);let s={},a=(u=t.steps)!=null&&u.length?n:[{fields:(d=t.fields)!=null?d:[]}];for(let l of a)Object.assign(s,fe(l,o,s));r=s;};return {invalidate(){e=null;},steps(o){return i(o),n},values(o){return i(o),r}}}function me(t){var r,i;let e=(i=(r=t.currentStep)==null?void 0:r.fields)!=null?i:[],n=m({},t.values);for(let{key:o}of e)delete n[o];return Object.assign(n,_(e))}function Vt(t){return Rt(t.definition,me(t))[t.currentStepIndex+1]}function ft(t){let e=t.currentStep,n=e.fields.map(({key:i})=>i);t.state.values=me(t);for(let i of n)delete t.errors[i];t.skipped.set(e.id,n),t.visibility.reconcileHidden(t.values,t.errors),t.visibility.markChanged(true,true);let r=ct(t);return t.notify({fieldKeys:[...n,...r],structureChanged:true,valuesChanged:true}),n}function pt(t){let e=t.currentStep;e&&t.skipped.delete(e.id);}function he(t,e){return t.state.currentStepIndex=e,t.notify({structureChanged:true}),ft(t)}async function mt(t,e,n=false){if(t.submitting||t.stepValidating)return false;n||pt(t);let r=m({},t.lifecycle),i=false,o=t.validationEpoch,s=++t.operationEpoch,a=K(t),u=Z(t,a),d=()=>o!==t.validationEpoch||s!==t.operationEpoch||u();t.state.submitting=true,t.notify();try{if(d()||Object.keys(Q(t,!0)).length>0||d())return !1;if(r.onBeforeSubmit){let c=await r.onBeforeSubmit(a);if(d()||c===!1)return !1}if(d())return !1;if(r.onBeforeSubmit){if(Object.keys(Q(t,!0)).length>0||d())return !1;a=K(t);}i=!0;let l=[...t.skipped.keys()];return await e(a,[...l]),s!==t.operationEpoch||await ut("afterSubmit",()=>{var c;return (c=r.onAfterSubmit)==null?void 0:c.call(r,a,l)}),!0}catch(l){if(!i&&d())return false;throw l}finally{s===t.operationEpoch&&(t.state.submitting=false,t.notify());}}function ge(t){let e=t.currentStep;if(!e)return true;let n=L(e,T(t),t.validators);if(Object.keys(n).length===0)return false;let r=m({},t.errors);return Object.assign(t.errors,n),t.notify({fieldKeys:M(r,t.errors)}),true}function ye(t,e){t.validationEpoch++,t.state.currentStepIndex=e,t.notify({structureChanged:true});}async function be(t,e){var d;if(!t.isMultiStep||t.stepValidating||t.submitting||!((d=t.currentStep)!=null&&d.skip))return false;if(Vt(t))return ht(t,"next","skip");let n=t.currentStep;if(!e||!n)return false;let r=t.values,i=m({},t.errors),o=false,s=ft(t),a=t.values,u=Z(t,m({},a));try{return await mt(t,async(l,c)=>{await e(l,c),o=!0;},!0)}finally{!o&&t.values===a&&!u()&&(t.state.values=r,t.state.errors=m(m({},i),t.errors),t.skipped.delete(n.id),t.notify({fieldKeys:s,structureChanged:true,valuesChanged:true}));}}async function ht(t,e,n=e){let r=n==="skip";if(!t.isMultiStep||t.stepValidating||t.submitting||!r&&(e==="next"?t.isLastStep:t.isFirstStep))return false;let i=t.currentStep,o=e==="next"&&!r;if(o&&pt(t),o&&ge(t))return false;let s=m({},t.lifecycle),a=t.onStepValidate,u=false,l=t.currentStepIndex+(e==="next"?1:-1),c=r?Vt(t):t.visibleSteps[l];if(!c)return false;let f={fromStepId:i.id,toStepId:c.id,reason:n,values:m({},T(t))},b=t.validationEpoch,F=++t.operationEpoch,V=Z(t,f.values),x=()=>{var k;return b!==t.validationEpoch||F!==t.operationEpoch||((k=t.currentStep)==null?void 0:k.id)!==i.id||V()};t.state.stepValidating=true,t.notify();try{if(x())return !1;if(o&&a){let k=await a(i.id,f.values);if(x())return !1;if(k&&Object.keys(k).length>0)return dt(t,k),!1}if(s.onBeforeStepChange){let k=await s.onBeforeStepChange(f);if(x()||k===!1)return !1}return x()||o&&ge(t)?!1:(u=!0,r&&ft(t),ye(t,l),await ut("afterStepChange",()=>{var k;return (k=s.onAfterStepChange)==null?void 0:k.call(s,f)}),!0)}catch(k){if(!u&&x())return false;throw k}finally{F===t.operationEpoch&&(t.state.stepValidating=false,t.notify());}}function Fe(t,e){if(!t.isMultiStep)return;let n=t.visibility.findStepIndex(e,t.values,t.currentStepIndex);n===t.currentStepIndex?t.notify():n!==null&&ye(t,n);}function ke(t,e){return t.add(e),()=>t.delete(e)}function Se(){let t=0,e=0,n=new Set,r=new Set,i=new Map,o=new Map;return {subscribe:s=>ke(n,s),getSnapshot:()=>t,subscribeStructure:s=>ke(r,s),getStructureSnapshot:()=>e,getFieldSnapshot:s=>{var a;return (a=i.get(s))!=null?a:0},subscribeField(s,a){var d;let u=(d=o.get(s))!=null?d:new Set;return u.add(a),o.set(s,u),()=>{u.delete(a),u.size===0&&o.delete(s);}},notify({fieldKeys:s=[],structureChanged:a=false}={}){var u,d;for(let l of new Set(s)){i.set(l,((u=i.get(l))!=null?u:0)+1);for(let c of (d=o.get(l))!=null?d:[])c();}if(a){e++;for(let l of r)l();}t++;for(let l of n)l();}}}function kn(t,e){try{if(process.env.NODE_ENV!=="production")return it(t,{validators:e})}catch(n){if(!(n instanceof ReferenceError))throw n}}function we(t,e,n){var s,a;let r=(s=kn(t,n))!=null?s:ie(t),i=r.filter(Pt);if(i.length)throw new $(i);let o=(a=e.onWarning)!=null?a:(u=>console.warn(`[formhaus] ${u.message}`));for(let u of r)o(u);}function Ot(t,e){var n;for(let r of st(t)){let i=(n=e.get(r))!=null?n:new Set;i.add(t),e.set(r,i);}}function ve(t){var V,x,k;let e=at(t),n=new Map,r=new Set,i=pe(t),o=new Map,s=new Map,a=new Map,u=true,d=true,l={visibleSteps:[],currentStep:null,visibleFields:[],canGoNext:false};for(let p of e)n.set(p.key,[...(V=n.get(p.key))!=null?V:[],p]),Ot(p,o);for(let p of (x=t.steps)!=null?x:[]){for(let g of p.fields)a.set(g,p);Ot(p,s);for(let g of (k=p.routes)!=null?k:[])for(let y of st(g))r.add(y);}let c=()=>{var p;return ((p=t.steps)!=null?p:[]).length>0},f=(p,g)=>I(p,i.values(g)),b=(p,g)=>{let y=a.get(p);return !y||i.steps(g).includes(y)};function F(p,g){var C,O,B;if(!u)return l;if(u=false,!c())return l.visibleSteps=[],l.currentStep=null,l.visibleFields=((C=t.fields)!=null?C:[]).filter(j=>f(j,p)),l;let y=l.visibleSteps=i.steps(p),S=l.currentStep=(B=(O=y[g])!=null?O:y[y.length-1])!=null?B:null;return l.visibleFields=S?S.fields.filter(j=>f(j,p)):[],l}return {allFields:e,conditionValues:i.values,state:F,markChanged(p,g){(p||g)&&i.invalidate(),p&&(u=true),(p||g)&&(d=true);},getCanGoNext(p,g,y){let S=F(p,g).currentStep;if(!d)return l.canGoNext;d=false;let C=S?L(S,i.values(p),y):{};return l.canGoNext=c()&&Object.keys(C).length===0},findStepIndex(p,g,y){let S=F(g,y).visibleSteps.findIndex(C=>C.fields.some(O=>O.key===p));return S===-1?null:S},affectsStructure(p,g){return r.has(p)||o.has(p)||s.has(p)||g.size>0},activeField(p,g){var y;return (y=n.get(p))==null?void 0:y.find(S=>b(S,g)&&f(S,g))},reconcileHidden(p,g){var j,At;i.invalidate();let y=[...new Set([...o.keys(),...s.keys()])],S=new Set(y),C=new Set,O=v=>p[v]!==void 0||g[v]!==void 0,B=v=>{delete p[v],delete g[v],i.invalidate(),C.add(v),!S.has(v)&&(S.add(v),y.push(v));};for(let v=0;v<y.length;v++){let bt=y[v];S.delete(bt);for(let A of (j=o.get(bt))!=null?j:[])b(A,p)&&!f(A,p)&&O(A.key)&&B(A.key);for(let A of (At=s.get(bt))!=null?At:[])if(!f(A,p))for(let Mt of A.fields)O(Mt.key)&&B(Mt.key);}return C}}}var gt=class{constructor(e,n,r){this.definition=e;this.skipped=new Map;this.validationEpoch=0;this.operationEpoch=0;this.subscriptions=Se();var o;this.lifecycle=r!=null?r:{},this.validators=(o=r==null?void 0:r.validators)!=null?o:{},we(e,this.lifecycle,this.validators),this.visibility=ve(e);let i=_(this.visibility.allFields,n);this.state={values:i,errors:{},topLevelErrors:[],currentStepIndex:0,fieldLoading:{},stepValidating:false,submitting:false},this.visibility.reconcileHidden(i,this.state.errors);}get onStepValidate(){return this.lifecycle.onStepValidate}get values(){return this.state.values}get errors(){return this.state.errors}get topLevelErrors(){return this.state.topLevelErrors}get currentStepIndex(){return this.state.currentStepIndex}get fieldLoading(){return this.state.fieldLoading}get stepValidating(){return this.state.stepValidating}get submitting(){return this.state.submitting}get isMultiStep(){var e;return ((e=this.definition.steps)!=null?e:[]).length>0}get visibleSteps(){return this.view.visibleSteps}get currentStep(){return this.view.currentStep}get visibleFields(){return this.view.visibleFields}get isFirstStep(){return this.currentStepIndex===0}get isLastStep(){return this.currentStepIndex>=this.visibleSteps.length-1}get canGoNext(){return this.visibility.getCanGoNext(this.state.values,this.currentStepIndex,this.validators)}get progress(){let e=this.visibleSteps.length;return {current:Math.min(this.currentStepIndex+1,e),total:e}}subscribe(e){return this.subscriptions.subscribe(e)}getSnapshot(){return this.subscriptions.getSnapshot()}subscribeField(e,n){return this.subscriptions.subscribeField(e,n)}getFieldSnapshot(e){return this.subscriptions.getFieldSnapshot(e)}subscribeStructure(e){return this.subscriptions.subscribeStructure(e)}getStructureSnapshot(){return this.subscriptions.getStructureSnapshot()}setValue(e,n){let{values:r,errors:i}=this.state,o=this.isMultiStep?this.visibleSteps:null,s=!Object.is(r[e],n),a=i[e]!==void 0;r[e]=n,delete i[e];for(let[b,F]of this.skipped)s&&F.includes(e)&&this.skipped.delete(b);let u=this.visibility.reconcileHidden(r,i),d=ue(this.internals,e),l=new Set([...u,...d]);(s||a)&&l.add(e);let c=s||u.size>0,f=c&&this.visibility.affectsStructure(e,u);if(o&&f){this.visibility.markChanged(true,true),this.state.currentStepIndex=ce(o,this.visibleSteps,this.currentStepIndex);for(let b of ct(this.internals))l.add(b);}this.notify({fieldKeys:l,structureChanged:f,valuesChanged:c});}setErrors(e){dt(this.internals,e,true);}setFieldLoading(e,n){let r=this.state.fieldLoading[e]===true;n?this.state.fieldLoading[e]=true:delete this.state.fieldLoading[e],this.notify({fieldKeys:r===n?[]:[e]});}cancelPendingActions(){this.validationEpoch++,this.operationEpoch++,this.state.stepValidating=false,this.state.submitting=false,this.notify();}next(){return ht(this.internals,"next")}back(){return ht(this.internals,"back")}skip(e){return be(this.internals,e)}submit(e){return mt(this.internals,e)}isStepSkipped(e){return this.skipped.has(e)}validate(){return Q(this.internals)}validateField(e){return le(this.internals,e)}getSubmitValues(){return K(this.internals)}goToStepWithField(e){Fe(this.internals,e);}reset(e){de(this.internals,e);}get view(){return this.visibility.state(this.state.values,this.currentStepIndex)}get internals(){return this}notify(e={}){this.visibility.markChanged(!!e.structureChanged,!!e.valuesChanged),this.subscriptions.notify(e);}};var Sn='Pass the values object as the second argument, not the request body with "values" and "skippedSteps".',wn=()=>null,yt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function vn(t,e){let n=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},r={};for(let i of t)yt(n,i.key)&&(r[i.key]=Qt(i,n[i.key]));return r}function xn(t,e){let n=new Map;for(let r of t){let i=yt(e,r.key)?Ct(r,e[r.key]):null;i&&n.set(r.key,i);}return n}function En(t,e){var i;let n=o=>o.map(s=>e.has(s.key)?G(m({},s),{validation:void 0}):s),r=(i=t.steps)==null?void 0:i.map(o=>G(m({},o),{fields:n(o.fields)}));return m(m(m({},t),t.fields&&{fields:n(t.fields)}),r&&{steps:r})}function In(t,e={}){let n={};for(let{validation:r}of t)r!=null&&r.validator&&(n[r.validator]=wn);return m(m({},n),e)}function Cn(t,e){return e===null||typeof e!="object"||!yt(e,"values")?false:!t.some(n=>n.key==="values"||n.key==="skippedSteps")}function $n(t,e){if(!Array.isArray(e))return;let n=new Set(e);for(let r=0;r<t.visibleSteps.length;r++){let i=t.visibleSteps[r];i.skip&&n.has(i.id)&&he(t,r);}}function Dn(t,e,n={}){ot(t);let r=at(t),i=vn(r,e),o=xn(r,i),s={validators:In(r,n.validators),onWarning:()=>{}},a=new gt(En(t,o),i,s);$n(a,n.skippedSteps);let u=a.validate(),d=a.getSubmitValues();for(let[l,c]of o)yt(d,l)&&(u[l]=c);return Cn(r,e)&&(u.values=Sn),{values:d,errors:u}}exports.FormDefinitionError=$;exports.checkDefinition=it;exports.parseDefinition=ot;exports.validateSubmission=Dn;return exports;})({});//# sourceMappingURL=server.iife.js.map
6
6
  //# sourceMappingURL=server.iife.js.map