@usefillo/dom 0.30.0 → 0.30.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.
@@ -1 +1 @@
1
- "use strict";var Fillo=(()=>{var zn=Object.defineProperty;var As=Object.getOwnPropertyDescriptor;var Fs=Object.getOwnPropertyNames;var Es=Object.prototype.hasOwnProperty;var zs=(e,t)=>{for(var n in t)zn(e,n,{get:t[n],enumerable:!0})},Cs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Fs(t))!Es.call(e,i)&&i!==n&&zn(e,i,{get:()=>t[i],enumerable:!(r=As(t,i))||r.enumerable});return e};var Is=e=>Cs(zn({},"__esModule",{value:!0}),e);var kc={};zs(kc,{FilloClient:()=>vn,FilloError:()=>C,createClient:()=>Te,createFormElement:()=>bs,defineForm:()=>Mr,registerFilloElement:()=>Ur,renderForm:()=>xn});var ni;function N(e,t,n){function r(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let c=s.prototype,u=Object.keys(c);for(let m=0;m<u.length;m++){let f=u[m];f in a||(a[f]=c[f].bind(a))}}let i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var l;let c=n?.Parent?new o:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var Re=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(ni=globalThis).__zod_globalConfig??(ni.__zod_globalConfig={});var Cn=globalThis.__zod_globalConfig;function Ve(e){return e&&Object.assign(Cn,e),Cn}function ii(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function oi(e,t){return typeof t=="bigint"?t.toString():t}function si(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Mn(e){return e==null}function ai(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var ri=Symbol("evaluating");function He(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==ri)return r===void 0&&(r=ri,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}var Nn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ln(e){if(Jt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(Jt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Tn(e){return Ln(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var li=new Set(["string","number","symbol"]);function _t(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pn(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function ae(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ci(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ms={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function xt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ui(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Ge(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Kt(e){return typeof e=="string"?e:e?.message}function qe(e,t,n){let r=e.message?e.message:Kt(e.inst?._zod.def?.error?.(e))??Kt(t?.error?.(e))??Kt(n.customError?.(e))??Kt(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=s),a}function Rn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}var di=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,oi,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},fi=N("$ZodError",di),kt=N("$ZodError",di,{Parent:Error});var Ls=e=>(t,n,r,i)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Re;if(s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>qe(l,o,Ve())));throw Nn(a,i?.callee),a}return s.value},Xt=Ls(kt),Ts=e=>async(t,n,r,i)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>qe(l,o,Ve())));throw Nn(a,i?.callee),a}return s.value},Yt=Ts(kt),Ps=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Re;return o.issues.length?{success:!1,error:new(e??fi)(o.issues.map(s=>qe(s,i,Ve())))}:{success:!0,data:o.value}},$t=Ps(kt),Rs=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>qe(s,i,Ve())))}:{success:!0,data:o.value}},St=Rs(kt);var pi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Os="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Zs=new RegExp(`^${Os}$`);var hi=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var On=/^-?\d+(?:\.\d+)?$/;var et=N("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ds={number:"number",bigint:"bigint",object:"date"};var gi=N("$ZodCheckGreaterThan",(e,t)=>{et.init(e,t);let n=Ds[typeof t.value];e._zod.onattach.push(r=>{let i=r._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var bi=N("$ZodCheckMaxLength",(e,t)=>{var n;et.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!Mn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let i=r.value;if(i.length<=t.maximum)return;let s=Rn(i);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),vi=N("$ZodCheckMinLength",(e,t)=>{var n;et.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!Mn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let i=r.value;if(i.length>=t.minimum)return;let s=Rn(i);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}});var Zn=N("$ZodCheckStringFormat",(e,t)=>{var n,r;et.init(e,t),e._zod.onattach.push(i=>{let o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),yi=N("$ZodCheckRegex",(e,t)=>{Zn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}});var _i={major:4,minor:4,patch:3};var we=N("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=_i;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let i of r)for(let o of i._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,a,l)=>{let c=xt(s),u;for(let m of a){if(m._zod.def.when){if(ui(s)||!m._zod.def.when(s))continue}else if(c)continue;let f=s.issues.length,h=m._zod.check(s);if(h instanceof Promise&&l?.async===!1)throw new Re;if(u||h instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await h,s.issues.length!==f&&(c||(c=xt(s,f)))});else{if(s.issues.length===f)continue;c||(c=xt(s,f))}}return u?u.then(()=>s):s},o=(s,a,l)=>{if(xt(s))return s.aborted=!0,s;let c=i(a,r,l);if(c instanceof Promise){if(l.async===!1)throw new Re;return c.then(u=>e._zod.parse(u,l))}return e._zod.parse(c,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let c=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(u=>o(u,s,a)):o(c,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Re;return l.then(c=>i(c,r,a))}return i(l,r,a)}}He(e,"~standard",()=>({validate:i=>{try{let o=$t(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return St(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Dn=N("$ZodString",(e,t)=>{we.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??hi(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Un=N("$ZodStringFormat",(e,t)=>{Zn.init(e,t),Dn.init(e,t)});var Si=N("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=pi),Un.init(e,t)});var Ai=N("$ZodNumber",(e,t)=>{we.init(e,t),e._zod.pattern=e._zod.bag.pattern??On,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}});var Fi=N("$ZodUnknown",(e,t)=>{we.init(e,t),e._zod.parse=n=>n});function xi(e,t,n){e.issues.length&&t.issues.push(...Ge(n,e.issues)),t.value[n]=e.value}var Ei=N("$ZodArray",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],l=t.element._zod.run({value:a,issues:[]},r);l instanceof Promise?o.push(l.then(c=>xi(c,n,s))):xi(l,n,s)}return o.length?Promise.all(o).then(()=>n):n}});function Qt(e,t,n,r,i,o){let s=n in r;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...Ge(n,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function Bs(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=ci(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function js(e,t,n,r,i,o){let s=[],a=i.keySet,l=i.catchall._zod,c=l.def.type,u=l.optin==="optional",m=l.optout==="optional";for(let f in t){if(f==="__proto__"||a.has(f))continue;if(c==="never"){s.push(f);continue}let h=l.run({value:t[f],issues:[]},r);h instanceof Promise?e.push(h.then(p=>Qt(p,n,f,t,u,m))):Qt(h,n,f,t,u,m)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}var zi=N("$ZodObject",(e,t)=>{if(we.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let r=si(()=>Bs(t));He(e._zod,"propValues",()=>{let a=t.shape,l={};for(let c in a){let u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let m of u.values)l[c].add(m)}}return l});let i=Jt,o=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=r.value);let c=a.value;if(!i(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),a;a.value={};let u=[],m=s.shape;for(let f of s.keys){let h=m[f],p=h._zod.optin==="optional",b=h._zod.optout==="optional",v=h._zod.run({value:c[f],issues:[]},l);v instanceof Promise?u.push(v.then(y=>Qt(y,a,f,c,p,b))):Qt(v,a,f,c,p,b)}return o?js(u,c,a,l,r.value,e):u.length?Promise.all(u).then(()=>a):a}});var Ci=N("$ZodRecord",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Ln(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let a=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);let u=t.keyType._zod.run({value:c,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(h=>qe(h,r,Ve())),input:c,path:[c],inst:e});continue}let m=u.value,f=t.valueType._zod.run({value:i[c],issues:[]},r);f instanceof Promise?o.push(f.then(h=>{h.issues.length&&n.issues.push(...Ge(c,h.issues)),n.value[m]=h.value})):(f.issues.length&&n.issues.push(...Ge(c,f.issues)),n.value[m]=f.value)}let l;for(let c in i)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l})}else{n.value={};for(let a of Reflect.ownKeys(i)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&On.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},r);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");m.issues.length===0&&(l=m)}if(l.issues.length){t.mode==="loose"?n.value[a]=i[a]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(m=>qe(m,r,Ve())),input:a,path:[a],inst:e});continue}let u=t.valueType._zod.run({value:i[a],issues:[]},r);u instanceof Promise?o.push(u.then(m=>{m.issues.length&&n.issues.push(...Ge(a,m.issues)),n.value[l.value]=m.value})):(u.issues.length&&n.issues.push(...Ge(a,u.issues)),n.value[l.value]=u.value)}}return o.length?Promise.all(o).then(()=>n):n}});var Ii=N("$ZodEnum",(e,t)=>{we.init(e,t);let n=ii(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>li.has(typeof i)).map(i=>typeof i=="string"?_t(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{let s=i.value;return r.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),Mi=N("$ZodLiteral",(e,t)=>{if(we.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?_t(r):r?_t(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,i)=>{let o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});function ki(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Ni=N("$ZodOptional",(e,t)=>{we.init(e,t),e._zod.optin="optional",e._zod.optout="optional",He(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),He(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${ai(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let i=n.value,o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>ki(s,i)):ki(o,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}});var Li=N("$ZodDefault",(e,t)=>{we.init(e,t),e._zod.optin="optional",He(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>$i(o,t)):$i(i,t)}});function $i(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function Ti(e,t){return new e({type:"string",...ae(t)})}function Pi(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ae(t)})}function Ri(e,t){return new e({type:"number",checks:[],...ae(t)})}function Oi(e){return new e({type:"unknown"})}function Bn(e,t){return new gi({check:"greater_than",...ae(t),value:e,inclusive:!0})}function jn(e){return Bn(0,e)}function le(e,t){return new bi({check:"max_length",...ae(t),maximum:e})}function tt(e,t){return new vi({check:"min_length",...ae(t),minimum:e})}function Vn(e,t){return new yi({check:"string_format",format:"regex",...ae(t),pattern:e})}var Ce=N("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");we.init(e,t),e.def=t,e.type=t.type,e.parse=(n,r)=>Xt(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>$t(e,n,r),e.parseAsync=async(n,r)=>Yt(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>St(e,n,r),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0}),e.with=e.check,e.clone=(n,r)=>Pn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.apply=n=>n(e)}),Di=N("ZodMiniString",(e,t)=>{Dn.init(e,t),Ce.init(e,t)});function fe(e){return Ti(Di,e)}var Hs=N("ZodMiniStringFormat",(e,t)=>{Un.init(e,t),Di.init(e,t)}),Gs=N("ZodMiniEmail",(e,t)=>{Si.init(e,t),Hs.init(e,t)});function en(e){return Pi(Gs,e)}var qs=N("ZodMiniNumber",(e,t)=>{Ai.init(e,t),Ce.init(e,t)});function Ui(e){return Ri(qs,e)}var Ws=N("ZodMiniUnknown",(e,t)=>{Fi.init(e,t),Ce.init(e,t)});function At(){return Oi(Ws)}var Ks=N("ZodMiniArray",(e,t)=>{Ei.init(e,t),Ce.init(e,t)});function Oe(e,t){return new Ks({type:"array",element:e,...ae(t)})}var Bi=N("ZodMiniObject",(e,t)=>{zi.init(e,t),Ce.init(e,t),He(e,"shape",()=>t.shape)});function Ft(e,t){let n={type:"object",shape:e??{},...ae(t)};return new Bi(n)}function Hn(e,t){return new Bi({type:"object",shape:e,catchall:At(),...ae(t)})}var Zi=N("ZodMiniRecord",(e,t)=>{Ci.init(e,t),Ce.init(e,t)});function ji(e,t,n){return!t||!t._zod?new Zi({type:"record",keyType:fe(),valueType:e,...ae(t)}):new Zi({type:"record",keyType:e,valueType:t,...ae(n)})}var Js=N("ZodMiniEnum",(e,t)=>{Ii.init(e,t),Ce.init(e,t),e.options=Object.values(t.entries)});function Vi(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Js({type:"enum",entries:n,...ae(t)})}var Xs=N("ZodMiniLiteral",(e,t)=>{Mi.init(e,t),Ce.init(e,t)});function Hi(e,t){return new Xs({type:"literal",values:Array.isArray(e)?e:[e],...ae(t)})}var Ys=N("ZodMiniOptional",(e,t)=>{Ni.init(e,t),Ce.init(e,t)});function ge(e){return new Ys({type:"optional",innerType:e})}var Qs=N("ZodMiniDefault",(e,t)=>{Li.init(e,t),Ce.init(e,t)});function Gn(e,t){return new Qs({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Tn(t)}})}var na=200,ra=["heading","paragraph","divider"];function ce(e){return!ra.includes(e.kind)}function mn(e){return e==null?!0:typeof e=="string"?e.trim()==="":Array.isArray(e)?e.length===0:typeof e=="boolean"?e===!1:typeof e=="object"?Object.keys(e).length===0:!1}function ia(e,t){if(!Array.isArray(t))return;let n=new Map(e.fields.map(o=>[o.id,o])),r=!1,i=t.map(o=>{if(!o||typeof o!="object"||Array.isArray(o))return o;let s=!1,a={};for(let[l,c]of Object.entries(o)){let u=n.get(l);if(!u){s=!0;continue}let m=ho(u,c);if(m===void 0){s=!0;continue}a[l]=m,m!==c&&(s=!0)}return s?(r=!0,a):o});return r?i:t}function po(e,t){if(t==null||e.kind==="custom")return t;if(e.kind==="repeating_group")return ia(e,t);if(e.kind==="number"&&typeof t=="string"&&t.trim()!==""){let n=Number(t);return Number.isNaN(n)?t:n}if((e.kind==="rating"||e.kind==="linear_scale")&&typeof t=="string"){let n=Number(t);return Number.isNaN(n)?t:n}return typeof t=="string"?t.trim():t}function ho(e,t){let n=po(e,t);return mn(n)?void 0:n}function mo(e){return e===void 0||!Number.isFinite(e)?0:Math.max(0,Math.min(6,Math.round(e)))}function go(e,t){let n=10**t,r=Math.round(Math.abs(e)*n)/n;return e<0?-r:r}function it(e){return Number.isFinite(e)?e:null}function pt(e,t){switch(e.op){case"value":return cr(t(e.fieldId));case"const":return it(e.value);case"add":case"mul":case"min":case"max":{if(e.args.length===0)return null;let n=[];for(let r of e.args){let i=pt(r,t);if(i===null)return null;n.push(i)}return e.op==="add"?it(n.reduce((r,i)=>r+i,0)):e.op==="mul"?it(n.reduce((r,i)=>r*i,1)):e.op==="min"?Math.min(...n):Math.max(...n)}case"sub":case"div":{let n=pt(e.left,t);if(n===null)return null;let r=pt(e.right,t);return r===null?null:e.op==="sub"?it(n-r):r===0?null:it(n/r)}case"round":{let n=pt(e.arg,t);return n===null?null:it(go(n,mo(e.decimals)))}case"if":return pt(wr(e.when,t)?e.then:e.else,t)}}function oa(e,t){let n=pt(e.calc,t);return n===null||e.decimals===void 0?n:it(go(n,mo(e.decimals)))}function nt(e,t){let n=Le(e);if(!n.some(a=>a.kind==="calculated"))return t;let r=t,i=dr(e,r);for(let a=0;a<=n.length;a++){let l={},c=!1;for(let[u,m]of Object.entries(r))i.has(u)?l[u]=m:c=!0;if(!c)break;r=l,i=dr(e,r)}let o=zt(n,r),s={};for(let[a,l]of Object.entries(t))o.calcIds.has(a)||(s[a]=l);for(let[a,l]of Object.entries(o.calc))i.has(a)&&(s[a]=l);return s}function qn(e){return e==null?!1:typeof e=="string"?e.trim()!=="":Array.isArray(e)?e.length>0:typeof e=="boolean"?e:typeof e=="object"?Object.keys(e).length>0:!0}function Gi(e,t){return e===t?!0:typeof e=="number"&&typeof t=="string"&&t.trim()!==""?Number(t)===e:typeof t=="number"&&typeof e=="string"&&e.trim()!==""?Number(e)===t:!1}function cr(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}function sa(e,t){let n=t(e.fieldId);switch(e.op){case"answered":return qn(n);case"not_answered":return!qn(n);case"eq":return Array.isArray(n)?n.some(r=>r===e.value):Gi(n,e.value);case"neq":return qn(n)?Array.isArray(n)?!n.some(r=>r===e.value):!Gi(n,e.value):!1;case"contains":return typeof n=="string"?n.toLowerCase().includes(String(e.value??"").toLowerCase()):Array.isArray(n)?n.some(r=>r===e.value):!1;case"gt":case"lt":{let r=cr(n),i=cr(e.value);return r!==null&&i!==null&&(e.op==="gt"?r>i:r<i)}}}function wr(e,t){return e.length===0?!0:e.every(n=>sa(n,t))}function bo(e,t){return!e.visibleIf||e.visibleIf.length===0?!0:wr(e.visibleIf,t)}function Wn(e,t,n,r,i,o){return s=>n.has(s)?r.has(s)?i.has(s)?o[s]:e[s]:void 0:t[s]}function zt(e,t){let n=new Set(e.map(l=>l.id)),r=e.filter(l=>l.kind==="calculated"),i=new Set(r.map(l=>l.id)),o={};for(let l of e){if(l.kind==="calculated")continue;let c=ho(l,t[l.id]);c!==void 0&&(l.kind==="repeating_group"&&(Array.isArray(c)?c.length:0)<Math.max(1,l.minInstances??1)||(o[l.id]=c))}let s=n,a={};for(let l=0;l<=e.length;l++){let c=a;if(r.length>0){c={...a};let h=Wn(o,t,n,s,i,c);for(let p of r){let b=s.has(p.id)?oa(p,h):null;b===null?delete c[p.id]:c[p.id]=b}}let u=Wn(o,t,n,s,i,c),m=new Set;for(let h of e)bo(h,u)&&m.add(h.id);let f=m.size===s.size&&[...m].every(h=>s.has(h))&&aa(a,c);if(s=m,a=c,f)break}return{visible:s,calc:a,calcIds:i,resolve:Wn(o,t,n,s,i,a)}}function aa(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>e[r]===t[r])}function vo(e,t){return zt(e,t).visible}function tn(e,t,n){let r=zt(Le(e),n);return t.blocks.filter(i=>ce(i)?r.visible.has(i.id):bo(i,r.resolve))}function Le(e){return e.pages.flatMap(t=>t.blocks.filter(ce))}function yo(e,t){let n=e.responseLimit?.scopeField;if(!n)return null;let r=t[n];return typeof r=="number"?Number.isFinite(r)?String(r):null:typeof r!="string"?null:r.trim()||null}function wo(e,t){let n=Le(e),r=vo(n,t);return n.filter(i=>r.has(i.id))}function gn(e,t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=zt(e.fields,n);return e.fields.filter(i=>r.visible.has(i.id))}function la(e,t){return zt(Le(e),t).resolve}function _o(e,t,n){let i=e.pages.find(s=>s.id===t)?.next;if(!i||i.length===0)return{linear:!0};let o=la(e,n);for(let s of i)if(wr(s.when,o))return s.to==="end"?{end:!0}:{to:s.to};return{linear:!0}}function ht(e,t,n){let r=[];if(e.pages.length===0)return r;let i=new Set,o=n===void 0?0:e.pages.findIndex(s=>s.id===n);for(let s=0;s<=e.pages.length;s++){let a=e.pages[o];if(!a||i.has(a.id))break;i.add(a.id),r.push(a.id);let l=_o(e,a.id,t);if("end"in l)break;if("to"in l){let c=e.pages.findIndex(u=>u.id===l.to);if(c<0)break;o=c}else if(o+=1,o>=e.pages.length)break}return r}function ca(e,t){return new Set(ht(e,t))}function ur(e,t,n){if("end"in _o(e,t,n))return!0;let r=ht(e,n);return r.length>0&&r[r.length-1]===t}function dr(e,t){let n=ca(e,t),r=vo(Le(e),t),i=new Set;for(let o of e.pages)if(n.has(o.id))for(let s of o.blocks)ce(s)&&r.has(s.id)&&i.add(s.id);return i}function xo(e,t){let n=dr(e,t);return Le(e).filter(r=>n.has(r.id))}var ut;function ua(){if(ut!==void 0)return ut??void 0;if(typeof Intl>"u"||typeof Intl.DisplayNames>"u"){ut=null;return}try{ut=new Intl.DisplayNames(void 0,{type:"region"})}catch{ut=null}return ut??void 0}function ko(e){try{return ua()?.of(e)??e}catch{return e}}var k=(e,t,n=[],r=[],i="")=>({iso2:e,name:ko(e),dialCode:t,lengths:n,groups:r,example:i}),da=[k("US","1",[10],[3,3,4],"2015550123"),k("CA","1",[10],[3,3,4],"5145550123"),k("GB","44",[10],[4,6],"7400123456"),k("AU","61",[9],[3,3,3],"412345678"),k("DE","49",[10,11],[4,7],"15123456789"),k("FR","33",[9],[1,2,2,2,2],"612345678"),k("IN","91",[10],[5,5],"8123456789"),k("DK","45",[8],[2,2,2,2],"32123456"),k("SE","46",[9],[2,3,4],"701234567"),k("NO","47",[8],[3,2,3],"40612345"),k("FI","358",[9,10],[2,3,4],"412345678"),k("NL","31",[9],[1,4,4],"612345678"),k("BE","32",[9],[3,2,2,2],"470123456"),k("ES","34",[9],[3,3,3],"612345678"),k("IT","39",[9,10],[3,3,4],"3123456789"),k("PT","351",[9],[3,3,3],"912345678"),k("IE","353",[9],[2,3,4],"851234567"),k("CH","41",[9],[2,3,2,2],"781234567"),k("AT","43",[10,11],[3,7],"6641234567"),k("PL","48",[9],[3,3,3],"512345678"),k("CZ","420",[9],[3,3,3],"601123456"),k("GR","30",[10],[3,3,4],"6912345678"),k("RO","40",[9],[3,3,3],"712345678"),k("HU","36",[9],[2,3,4],"201234567"),k("UA","380",[9],[2,3,2,2],"501234567"),k("RU","7",[10],[3,3,2,2],"9123456789"),k("TR","90",[10],[3,3,2,2],"5012345678"),k("IL","972",[9],[2,3,4],"501234567"),k("AE","971",[9],[2,3,4],"501234567"),k("SA","966",[9],[2,3,4],"512345678"),k("ZA","27",[9],[2,3,4],"711234567"),k("NG","234",[10],[3,3,4],"8021234567"),k("KE","254",[9],[3,3,3],"712123456"),k("EG","20",[10],[3,3,4],"1001234567"),k("BR","55",[10,11],[2,5,4],"11961234567"),k("MX","52",[10],[3,3,4],"2221234567"),k("AR","54",[10],[4,6],"1123456789"),k("CL","56",[9],[1,4,4],"221234567"),k("CO","57",[10],[3,3,4],"3211234567"),k("PE","51",[9],[3,3,3],"912345678"),k("CN","86",[11],[3,4,4],"13123456789"),k("JP","81",[10],[2,4,4],"9012345678"),k("KR","82",[9,10],[2,4,4],"1023456789"),k("SG","65",[8],[4,4],"81234567"),k("HK","852",[8],[4,4],"51234567"),k("TW","886",[9],[3,3,3],"912345678"),k("MY","60",[9,10],[2,3,4],"123456789"),k("ID","62",[10,11],[3,4,4],"81234567890"),k("TH","66",[9],[2,3,4],"812345678"),k("PH","63",[10],[3,3,4],"9171234567"),k("VN","84",[9],[3,3,3],"912345678"),k("PK","92",[10],[3,3,4],"3012345678"),k("BD","880",[10],[2,4,4],"1812345678"),k("NZ","64",[9,10],[2,3,4],"211234567"),k("SK","421",[9],[3,3,3],"912123456"),k("BG","359",[9],[2,3,4],"481234567"),k("HR","385",[8,9],[2,3,4],"921234567"),k("RS","381",[8,9],[2,3,4],"601234567"),k("SI","386",[8],[2,3,3],"31234567"),k("LT","370",[8],[3,2,3],"61234567"),k("LV","371",[8],[2,3,3],"21234567"),k("EE","372",[7,8],[3,4],"51234567"),k("IS","354",[7],[3,4],"6111234"),k("LU","352",[9],[3,3,3],"628123456"),k("MA","212",[9],[3,3,3],"650123456"),k("CR","506",[8],[4,4],"83123456"),k("EC","593",[9],[2,3,4],"991234567"),k("UY","598",[8],[1,3,4],"94231234"),k("QA","974",[8],[4,4],"33123456"),k("KW","965",[8],[4,4],"50012345")],fa="AD376 AF93 AG1 AI1 AL355 AM374 AO244 AS1 AW297 AX358 AZ994 BA387 BB1 BF226 BH973 BI257 BJ229 BL590 BM1 BN673 BO591 BQ599 BS1 BT975 BV47 BW267 BY375 BZ501 CC61 CD243 CF236 CG242 CI225 CK682 CM237 CU53 CV238 CW599 CX61 CY357 DJ253 DM1 DO1 DZ213 EH212 ER291 ET251 FJ679 FK500 FM691 FO298 GA241 GD1 GE995 GF594 GG44 GH233 GI350 GL299 GM220 GN224 GP590 GQ240 GS500 GT502 GU1 GW245 GY592 HN504 HT509 IM44 IO246 IQ964 IR98 JE44 JM1 JO962 KG996 KH855 KI686 KM269 KN1 KP850 KY1 KZ7 LA856 LB961 LC1 LI423 LK94 LR231 LS266 LY218 MC377 MD373 ME382 MF590 MG261 MH692 MK389 ML223 MM95 MN976 MO853 MP1 MQ596 MR222 MS1 MT356 MU230 MV960 MW265 MZ258 NA264 NC687 NE227 NF672 NI505 NP977 NR674 NU683 OM968 PA507 PF689 PG675 PM508 PN64 PR1 PS970 PW680 PY595 RE262 RW250 SB677 SC248 SD249 SH290 SJ47 SL232 SM378 SN221 SO252 SR597 SS211 ST239 SV503 SX1 SY963 SZ268 TC1 TD235 TF262 TG228 TJ992 TK690 TL670 TM993 TN216 TO676 TT1 TV688 TZ255 UG256 UZ998 VA379 VC1 VE58 VG1 VI1 VU678 WF681 WS685 XK383 YE967 YT262 ZM260 ZW263";function pa(e){let t=[];for(let n of e.trim().split(/\s+/)){let r=n.slice(0,2),i=n.slice(2);t.push({iso2:r,name:ko(r),dialCode:i,lengths:[],groups:[],example:""})}return t}var Ct=[...da,...pa(fa)],mt=ha(Ct);function ha(e){if(typeof Intl>"u"||typeof Intl.Collator>"u")return[...e].sort((n,r)=>n.iso2<r.iso2?-1:n.iso2>r.iso2?1:0);let t=new Intl.Collator(void 0,{sensitivity:"base"});return[...e].sort((n,r)=>t.compare(n.name,r.name))}var ma=new Map(Ct.map(e=>[e.iso2,e])),ga={"Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Johannesburg":"ZA","Africa/Lagos":"NG","Africa/Nairobi":"KE","America/Adak":"US","America/Anchorage":"US","America/Argentina/Buenos_Aires":"AR","America/Argentina/Cordoba":"AR","America/Argentina/Mendoza":"AR","America/Bahia":"BR","America/Belem":"BR","America/Bogota":"CO","America/Boise":"US","America/Boa_Vista":"BR","America/Cancun":"MX","America/Chicago":"US","America/Chihuahua":"MX","America/Campo_Grande":"BR","America/Costa_Rica":"CR","America/Cuiaba":"BR","America/Denver":"US","America/Detroit":"US","America/Edmonton":"CA","America/Fortaleza":"BR","America/Guayaquil":"EC","America/Halifax":"CA","America/Hermosillo":"MX","America/Indiana/Indianapolis":"US","America/Indianapolis":"US","America/Juneau":"US","America/Kentucky/Louisville":"US","America/Lima":"PE","America/Los_Angeles":"US","America/Maceio":"BR","America/Manaus":"BR","America/Matamoros":"MX","America/Mazatlan":"MX","America/Merida":"MX","America/Mexico_City":"MX","America/Moncton":"CA","America/Monterrey":"MX","America/Montevideo":"UY","America/New_York":"US","America/Noronha":"BR","America/Nome":"US","America/North_Dakota/Center":"US","America/Ojinaga":"MX","America/Phoenix":"US","America/Porto_Velho":"BR","America/Punta_Arenas":"CL","America/Recife":"BR","America/Regina":"CA","America/Rio_Branco":"BR","America/Santiago":"CL","America/Sao_Paulo":"BR","America/Sitka":"US","America/St_Johns":"CA","America/Tijuana":"MX","America/Toronto":"CA","America/Vancouver":"CA","America/Whitehorse":"CA","America/Winnipeg":"CA","America/Yakutat":"US","Asia/Bangkok":"TH","Asia/Calcutta":"IN","Asia/Dacca":"BD","Asia/Dhaka":"BD","Asia/Dubai":"AE","Asia/Hong_Kong":"HK","Asia/Ho_Chi_Minh":"VN","Asia/Jakarta":"ID","Asia/Jerusalem":"IL","Asia/Karachi":"PK","Asia/Kolkata":"IN","Asia/Kuala_Lumpur":"MY","Asia/Kuwait":"KW","Asia/Manila":"PH","Asia/Qatar":"QA","Asia/Riyadh":"SA","Asia/Seoul":"KR","Asia/Shanghai":"CN","Asia/Saigon":"VN","Asia/Singapore":"SG","Asia/Taipei":"TW","Asia/Tel_Aviv":"IL","Asia/Tokyo":"JP","Asia/Urumqi":"CN","Atlantic/Reykjavik":"IS","Australia/Adelaide":"AU","Australia/Brisbane":"AU","Australia/Darwin":"AU","Australia/Hobart":"AU","Australia/Melbourne":"AU","Australia/Perth":"AU","Australia/Sydney":"AU","Europe/Amsterdam":"NL","Europe/Athens":"GR","Europe/Belgrade":"RS","Europe/Berlin":"DE","Europe/Bratislava":"SK","Europe/Brussels":"BE","Europe/Bucharest":"RO","Europe/Budapest":"HU","Europe/Copenhagen":"DK","Europe/Dublin":"IE","Europe/Helsinki":"FI","Europe/Zagreb":"HR","Europe/Istanbul":"TR","Europe/Kiev":"UA","Europe/Kyiv":"UA","Europe/Lisbon":"PT","Europe/Ljubljana":"SI","Europe/London":"GB","Europe/Luxembourg":"LU","Europe/Madrid":"ES","Europe/Moscow":"RU","Europe/Oslo":"NO","Europe/Paris":"FR","Europe/Prague":"CZ","Europe/Riga":"LV","Europe/Rome":"IT","Europe/Sofia":"BG","Europe/Stockholm":"SE","Europe/Tallinn":"EE","Europe/Vienna":"AT","Europe/Vilnius":"LT","Europe/Warsaw":"PL","Europe/Zurich":"CH","Pacific/Auckland":"NZ"};function _r(e){let t=e.toUpperCase();return/^[A-Z]{2}$/.test(t)?String.fromCodePoint(...[...t].map(n=>127462+n.charCodeAt(0)-65)):"\u{1F3F3}\uFE0F"}function bn(e){return e?ma.get(e.toUpperCase()):void 0}function $o(e){return bn(e?ga[e]:void 0)}function ba(e){let t;for(let n of Ct)e.startsWith(n.dialCode)&&(!t||n.dialCode.length>t.dialCode.length)&&(t=n);return t}function Ne(e){return e.replace(/[^\d]/g,"")}function It(e,t){let n=Ne(t);if(!n)return"";let r=e?.groups?.length?e.groups:[],i=[],o=0;for(let s of r){if(o>=n.length)break;i.push(n.slice(o,o+s)),o+=s}for(;o<n.length;)i.push(n.slice(o,o+3)),o+=3;return i.join(" ")}function So(e,t){let n=Ne(t);return n?`+${e.dialCode}${n}`:""}function Mt(e,t,n){let r=(e??"").trim(),i=r.startsWith("+"),o=Ne(r);if(i){if(!o)return{national:"",e164:"",pending:!0,raw:r};let s=n?.previousDigits?Ne(n.previousDigits):"";if(s&&o===s)return{national:o,e164:`+${o}`,pending:!0,raw:r};let a=ba(o);if(a){let l=o.slice(a.dialCode.length);return{country:a,national:l,e164:`+${o}`}}return{national:o,e164:`+${o}`,pending:!0,raw:r}}if(!o)return{country:t,national:"",e164:""};if(t){let s=o.startsWith(t.dialCode)?o.slice(t.dialCode.length):o;return{country:t,national:s,e164:`+${t.dialCode}${s}`}}return{national:o,e164:`+${o}`}}function va(e){let{country:t,national:n,e164:r}=Mt(e);if(!r)return!1;let i=Ne(r).length;return i<8||i>15?!1:t?.lengths.length?t.lengths.includes(n.length):n.length>=4}var ya=8;function Ao(e,t){if(!e||!t||typeof window>"u")return"below";let n=ya,r=document.documentElement.clientWidth||window.innerWidth,i=document.documentElement.clientHeight||window.innerHeight,o=e.getBoundingClientRect(),s=Math.max(0,i-o.bottom-n),a=Math.max(0,o.top-n),l=s<t.scrollHeight&&a>s?"above":"below",u=Math.max(0,Math.min(l==="above"?a:s,i-n*2)),m=Math.max(0,r-n*2);t.style.setProperty("--fillo-phone-popover-max-height",`${Math.floor(u)}px`),t.style.setProperty("--fillo-phone-popover-max-width",`${Math.floor(m)}px`),t.style.setProperty("--fillo-phone-popover-offset-x","0px");let f=Math.min(t.offsetWidth,m),p=getComputedStyle(e).direction==="rtl"?o.right-f:o.left,b=0,v=p+f-(r-n);v>0&&(b-=v);let y=n-(p+b);return y>0&&(b+=y),t.style.setProperty("--fillo-phone-popover-offset-x",`${Math.round(b)}px`),l}var Nt="This field is required",P={back:"Back",next:"Next",submit:"Submit",submitting:"Submitting\u2026",uploading:"Uploading\u2026",optional:" (optional)",other:"Other",otherPrompt:"Other \u2014 please specify",otherPlaceholder:"Your answer",choosePlaceholder:"Choose\u2026",successTitle:"Thanks!",successMessage:"Your response has been recorded.",closed:"This form is no longer accepting responses.",notLive:"This form isn't live yet.",notOpenTitle:"This form isn't open yet",notOpenBody:"The form owner is still setting things up. Please check back soon.",closedTitle:"Responses are closed",submitFailed:"This form can't submit right now. Please try again in a moment.",loadFailedNotFound:"Form not found. Check the link or ask the form owner for help.",loadFailedNetwork:"Couldn't reach the server \u2014 check your connection and try again.",loadFailed:"This form could not be loaded.",renderFailed:"This form could not be rendered.",resumeNotice:"Picked up where you left off.",editNotice:"You're updating your earlier response.",resumeStartOver:"Start over",challengeUnavailable:"The verification check couldn't load. Refresh the page and try again."},qi={submitFailed:P.submitFailed,loadFailedNotFound:P.loadFailedNotFound,loadFailedNetwork:P.loadFailedNetwork,formUnavailable:"This form is unavailable.",formClosed:P.closed,submitRateLimited:"Too many responses are being submitted right now. Wait a moment, then try again.",respondentUnrecognized:"This form couldn't verify who is responding. Ask the form owner for help.",fileUnavailable:"One of the uploaded files is no longer available. Remove it and upload it again.",scopeMissing:"We couldn't tell which entry this response belongs to. Answer the required field and try again.",challengeIncomplete:"Please complete the verification check, then submit.",challengeRetry:"That verification didn't go through. Please complete the check again and resubmit.",reviewAnswers:"We couldn't submit \u2014 please review your answers."};var wa={short_text:"Enter your answer",long_text:"Enter your answer",email:"Enter an email address",url:"Enter a URL",phone:"Enter a phone number",number:"Enter a number",select:"Choose an option",dropdown:"Choose an option",multi_select:"Select at least one option",checkbox:"Select this checkbox",rating:"Choose a rating",linear_scale:"Choose a value",ranking:"Rank every option",matrix:"Answer every row",signature:"Add your signature",date:"Enter a date",file_upload:"Add a file"};function _a(e){return wa[e.kind]??Nt}var R={previewSkip:"Skip",required:Nt,requiredForField:_a,resumeLinkExpired:"That saved-progress link expired or was already used \u2014 start again below.",alreadyAnswered:"You've already answered this form.",uploadRetry:"Retry",uploadCancel:"Cancel",uploadRemove:"Remove",uploadDismiss:"Dismiss",uploadingFile:(e,t)=>`Uploading \xB7 ${e}% \xB7 ${t}`,uploadedFile:e=>`Uploaded \xB7 ${e}`,uploadsDisabled:"Connect this form to Fillo to enable uploads",uploadsRenderOnly:"Uploads are unavailable in this render-only preview",uploadsUnavailable:"Uploads are temporarily unavailable",uploadUnavailable:"We couldn't upload this file right now. Try again in a moment.",uploadFailed:"Upload failed \u2014 try again",dropzoneTitle:e=>`Drop ${e?"files":"a file"} here or click to browse`,dropzoneHint:e=>`Up to ${e} MB per file`,fileTooLarge:e=>`Larger than ${e} MB limit`,filesUploading:e=>`Uploading ${e} ${e===1?"file":"files"}, please wait\u2026`,uploadsFailed:e=>`${e} ${e===1?"upload":"uploads"} failed.`,filesUploaded:e=>`${e} ${e===1?"file":"files"} uploaded.`,submittingAnnouncement:"Submitting your response\u2026",errorSummaryTitle:"Check these fields",rankingPosition:(e,t,n)=>`${e}, position ${t} of ${n}`,groupAdd:"Add another",groupInstanceLabel:(e,t,n)=>`${e} ${t} of ${n}`,groupRemoveLabel:(e,t)=>`Remove ${e} ${t}`,groupInstanceAdded:(e,t,n)=>`${e} ${t} added, ${t} of ${n}`,groupInstanceRemoved:(e,t)=>t===0?`${e} removed, none left`:`${e} removed, ${t} remaining`,phoneCountrySelected:e=>`${e} selected`,phoneResultsCount:e=>`${e} ${e===1?"result":"results"}`,signatureEmpty:"No signature yet",signatureSigned:"Signature saved"};function Fo(e,t){return t.requiredForField?.(e)??t.required}var xa=Ft({fileId:fe().check(tt(1)),name:fe(),size:Ui().check(jn()),mime:fe(),url:ge(fe())});function Kn(e,t){let n=Math.max(0,e.minInstances??1);return t<n?`Add at least ${n} ${n===1?"entry":"entries"}`:Number.isFinite(e.maxInstances)&&t>e.maxInstances?`At most ${e.maxInstances} ${e.maxInstances===1?"entry":"entries"}`:null}function fr(e,t){if(mn(t))return e.kind==="calculated"?null:e.kind==="repeating_group"?Kn(e,0):e.required?Nt:null;switch(e.kind){case"short_text":case"long_text":{if(typeof t!="string")return"Expected text";if(e.maxLength&&t.length>e.maxLength)return`Must be at most ${e.maxLength} characters`;let n=e.kind==="long_text"?2e4:2e3;return!e.maxLength&&t.length>n?"Answer is too long":null}case"email":return typeof t!="string"?"Enter a valid email address":e.maxLength&&t.length>e.maxLength?`Must be at most ${e.maxLength} characters`:en().safeParse(t).success?null:"Enter a valid email address";case"url":{if(typeof t!="string")return"Enter a valid URL (including https://)";if(e.maxLength&&t.length>e.maxLength)return`Must be at most ${e.maxLength} characters`;try{let n=new URL(t);if(n.protocol!=="http:"&&n.protocol!=="https:")return"Enter an http(s) URL"}catch{return"Enter a valid URL (including https://)"}return null}case"phone":return typeof t!="string"||!va(t)?"Enter a valid phone number":null;case"number":{let n=typeof t=="string"?Number(t):t;return typeof n!="number"||!Number.isFinite(n)?"Enter a number":e.min!==void 0&&n<e.min?`Must be at least ${e.min}`:e.max!==void 0&&n>e.max?`Must be at most ${e.max}`:null}case"select":case"dropdown":return typeof t!="string"||t===""?"Pick an option":e.options.some(n=>n.id===t)||e.allowOther&&t.length<=500?null:"Pick a valid option";case"multi_select":{if(!Array.isArray(t))return"Pick at least one option";let n=new Set(e.options.map(s=>s.id)),r=t,i=0,o=new Set;for(let s of r){if(typeof s!="string")return"Pick valid options";if(o.has(s))return"Pick each option only once";if(o.add(s),!n.has(s)){if(e.allowOther!==!0||s.length===0||s.length>500)return"Pick valid options";if(++i>1)return"Only one 'Other' answer is allowed"}}return null}case"checkbox":return typeof t=="boolean"?null:"Invalid value";case"rating":{let n=e.max??5,r=typeof t=="string"?Number(t):t;return typeof r!="number"||!Number.isInteger(r)||r<1||r>n?`Pick a rating between 1 and ${n}`:null}case"linear_scale":{let n=e.min??1,r=e.max??10,i=typeof t=="string"?Number(t):t;return typeof i!="number"||!Number.isInteger(i)||i<n||i>r?`Pick a value between ${n} and ${r}`:null}case"ranking":{if(!Array.isArray(t))return"Drag the options into order";let n=e.options.map(i=>i.id).sort(),r=[...t].sort();return n.length!==r.length||n.some((i,o)=>i!==r[o])?"Rank every option":null}case"matrix":{if(typeof t!="object"||t===null||Array.isArray(t))return"Answer the grid";let n=t,r=new Set(e.columns.map(o=>o.id)),i=new Set(e.rows.map(o=>o.id));for(let[o,s]of Object.entries(n))if(!i.has(o)||!r.has(s))return"Invalid grid answer";return e.required&&Object.keys(n).length<e.rows.length?"Answer every row":null}case"signature":return typeof t!="string"||!t.startsWith("data:image/")?"Sign in the box":null;case"hidden":return typeof t=="string"?null:"Invalid value";case"calculated":return null;case"repeating_group":{if(!Array.isArray(t))return Kn(e,0);let n=t;for(let r of n)if(!r||typeof r!="object"||Array.isArray(r))return"Invalid value";return Kn(e,n.length)}case"custom":return null;case"date":{if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(t))return"Enter a valid date";let[n,r,i]=t.split("-").map(Number),o=new Date(Date.UTC(n,r-1,i));return o.getUTCFullYear()!==n||o.getUTCMonth()!==r-1||o.getUTCDate()!==i?"Enter a valid date":null}case"file_upload":{let n=Oe(xa).safeParse(t);if(!n.success)return"Upload did not complete";let r=e.maxFiles??1;return n.data.length>r?`At most ${r} file${r===1?"":"s"}`:null}}}function pr(e,t){let n={},r={};if(e.kind!=="calculated"){let i=po(e,t);if(e.kind==="repeating_group")ka(e,i,n,r);else{let o=fr(e,i);o?n[e.id]=o:mn(i)||(r[e.id]=i)}}return{ok:Object.keys(n).length===0,errors:n,data:r}}function Eo(e,t){let n=xo(e,t),r={},i={};for(let o of n){let s=pr(o,t[o.id]);Object.assign(r,s.errors),Object.assign(i,s.data)}return{ok:Object.keys(r).length===0,errors:r,data:i}}function ka(e,t,n,r){let i=fr(e,t);if(i&&(n[e.id]=i),!Array.isArray(t))return;let o=t,s=[];for(let a=0;a<o.length;a++){let l=o[a];if(!l||typeof l!="object"||Array.isArray(l))continue;let c={};for(let u of gn(e,l)){let m=l[u.id],f=fr(u,m);f?n[`${e.id}.${a}.${u.id}`]=f:mn(m)||(c[u.id]=m)}s.push(c)}!i&&s.length>0&&(r[e.id]=s)}var $a=["short_text","long_text","email","url","phone","number","select","multi_select","dropdown","checkbox","rating","linear_scale","ranking","matrix","signature","date","file_upload","hidden","calculated","repeating_group","custom"],Sa=["heading","paragraph","divider"],Aa=[...$a,...Sa],xr=fe().check(tt(1),le(128)),Jn=Hn({id:xr,label:fe().check(le(1e3)),icon:ge(At())}),Fa=Hn({id:xr,kind:Vi(Aa),label:ge(fe().check(le(2e3))),options:ge(Oe(Jn).check(le(200))),rows:ge(Oe(Jn).check(le(200))),columns:ge(Oe(Jn).check(le(200)))}),Ea=Ft({id:xr,title:ge(fe().check(le(500))),blocks:Oe(Fa).check(le(500)),next:ge(At())}),za=Ft({version:Hi(1),title:Gn(ge(fe().check(le(2e3))),""),description:ge(fe().check(le(5e3))),pages:Oe(Ea).check(tt(1),le(50)),settings:Gn(ge(ji(fe(),At())),{})}),Ca=1,hr=1,mr="0.30.0";function _e(e,t,n=""){return typeof e=="string"?e.trim().slice(0,t):n}function K(e,t){let n=_e(e,t);return n===""?void 0:n}function nn(e,t){if(typeof e!="string")return;let n=e.slice(0,t);return n.trim()===""?void 0:n}function Me(e){return typeof e=="boolean"?e:void 0}function Se(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Ie(e,t,n,r){let i=Se(e);return i===void 0?r:Math.max(t,Math.min(n,Math.round(i)))}function rn(e,t=200){return Array.isArray(e)?e.slice(0,t).flatMap(n=>{if(!n||typeof n!="object")return[];let r=n,i=_e(r.id,128),o=_e(r.label,1e3),s=r.icon==="thumbs_up"||r.icon==="thumbs_down"?r.icon:void 0;return i&&o?[j({id:i,label:o,icon:s})]:[]}):[]}function fn(e){let t=new Set;for(let{id:n}of e){if(t.has(n))return n;t.add(n)}}function kr(e){if(!Array.isArray(e))return;let t=e.slice(0,20).flatMap(n=>{if(!n||typeof n!="object")return[];let r=n,i=r.op;if(i!=="eq"&&i!=="neq"&&i!=="contains"&&i!=="gt"&&i!=="lt"&&i!=="answered"&&i!=="not_answered")return[];let o=_e(r.fieldId,128);if(!o)return[];let s=r.value,a=typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:void 0;return[{fieldId:o,op:i,...a!==void 0?{value:a}:{}}]});return t.length?t:void 0}function zo(e,t,n,r){let i=t.get(e);if(i===void 0)return n.has(e);if(r.has(e))return!0;r.add(e);for(let o of i)if(!zo(o,t,n,r))return!1;return!0}function Ia(e,t,n,r,i){if(!Array.isArray(e))return;let o=e.slice(0,50).flatMap(s=>{if(!s||typeof s!="object")return[];let a=s,l=typeof a.to=="string"?a.to:void 0;if(!l||l!=="end"&&!t.has(l))return[];if(l===n)return[];let c=a.when;if(c!==void 0&&!Array.isArray(c))return[];let u=kr(c);return Array.isArray(c)&&c.length>0&&u===void 0?[]:u&&u.some(m=>!zo(m.fieldId,i,r,new Set))?[]:[{when:u??[],to:l}]});return o.length?o:void 0}var Ma=["number","rating","linear_scale","calculated"];function Je(e,t=0){if(t>32||!e||typeof e!="object"||Array.isArray(e))return null;let n=e;switch(n.op){case"value":{let r=_e(n.fieldId,128);return r?{op:"value",fieldId:r}:null}case"const":{let r=Se(n.value);return r===void 0?null:{op:"const",value:r}}case"add":case"mul":case"min":case"max":{if(!Array.isArray(n.args)||n.args.length<1||n.args.length>50)return null;let r=[];for(let i of n.args){let o=Je(i,t+1);if(!o)return null;r.push(o)}return{op:n.op,args:r}}case"sub":case"div":{let r=Je(n.left,t+1),i=Je(n.right,t+1);return r&&i?{op:n.op,left:r,right:i}:null}case"round":{let r=Je(n.arg,t+1);return r?j({op:"round",arg:r,decimals:Se(n.decimals)===void 0?void 0:Ie(n.decimals,0,6,0)}):null}case"if":{if(!Array.isArray(n.when))return null;let r=kr(n.when)??[];if(r.length!==n.when.length)return null;let i=Je(n.then,t+1),o=Je(n.else,t+1);return i&&o?{op:"if",when:r,then:i,else:o}:null}default:return null}}function Xe(e,t,n){switch(e.op){case"value":t.add(e.fieldId);return;case"const":return;case"add":case"mul":case"min":case"max":for(let r of e.args)Xe(r,t,n);return;case"sub":case"div":Xe(e.left,t,n),Xe(e.right,t,n);return;case"round":Xe(e.arg,t,n);return;case"if":for(let r of e.when)n.add(r.fieldId);Xe(e.then,t,n),Xe(e.else,t,n);return}}function Na(e,t){let n=new Map;for(let s of e)for(let a of s.blocks)ce(a)&&n.set(a.id,a.kind);let r=new Map;for(let s of e)for(let a of s.blocks){if(a.kind!=="calculated")continue;let l=Je(a.calc);if(!l)return`Field ${a.id} has a malformed calc expression \u2014 build it from value/const/add/sub/mul/div/min/max/round/if nodes`;a.calc=l;let c=new Set,u=new Set;Xe(l,c,u);for(let m of c){let f=n.get(m);if(f===void 0){let h=t.get(m);return h!==void 0?`Calculated field ${a.id} references ${m}, which is a child of repeating group ${h} \u2014 calculations can't reach inside a repeating group (calc operands must be top-level fields)`:`Calculated field ${a.id} references a missing field: ${m} \u2014 remove the reference or restore that field`}if(!Ma.includes(f))return`Calculated field ${a.id} references non-numeric field ${m} (${f}) \u2014 calculations can read number, rating, linear_scale, and calculated fields only`}r.set(a.id,[...c,...u].filter(m=>n.get(m)==="calculated"))}let i=new Map,o=(s,a)=>{let l=i.get(s);if(l==="done")return null;if(l==="visiting"){let c=[...a.slice(a.indexOf(s)),s].join(" \u2192 ");return`Calculated field ${s} depends on its own result (${c}) \u2014 break the cycle so the value can be computed`}i.set(s,"visiting");for(let c of r.get(s)??[]){let u=o(c,[...a,s]);if(u)return u}return i.set(s,"done"),null};for(let s of r.keys()){let a=o(s,[]);if(a)return a}return null}var Wi=100,Ki=5e3;function ot(e){switch(e.op){case"value":case"const":return 1;case"add":case"mul":case"min":case"max":return 1+e.args.reduce((t,n)=>t+ot(n),0);case"sub":case"div":return 1+ot(e.left)+ot(e.right);case"round":return 1+ot(e.arg);case"if":return 1+ot(e.then)+ot(e.else)}}function La(e){let t=0,n=0;for(let r of e)for(let i of r.blocks)i.kind==="calculated"&&(t+=1,n+=ot(i.calc));return t>Wi?`Form has ${t} calculated fields \u2014 the maximum is ${Wi}; remove some or consolidate them into fewer expressions`:n>Ki?`Calculated expressions total ${n} operations \u2014 the maximum is ${Ki} across the form; simplify or split up the calculations`:null}var Ji=["short_text","long_text","email","url","phone","number","select","multi_select","dropdown","checkbox","date","rating","linear_scale"],Xi=12,Yi=18e4;function Ta(e){let t=e.id.length+20;switch(e.kind){case"short_text":case"email":case"url":return t+(e.maxLength??2e3);case"long_text":return t+(e.maxLength??2e4);case"phone":return t+32;case"number":return t+32;case"select":case"dropdown":{let n=e.options.reduce((r,i)=>Math.max(r,i.id.length),0);return t+Math.max(n,e.allowOther?500:0)}case"multi_select":{let n=e.options.reduce((r,i)=>r+i.id.length+3,0);return t+n+(e.allowOther?500:0)}case"checkbox":return t+8;case"date":return t+16;case"rating":case"linear_scale":return t+8;default:return t+64}}function Pa(e){return e.fields.reduce((n,r)=>n+Ta(r),24)*(Number.isFinite(e.maxInstances)?e.maxInstances:0)}function Ra(e){for(let t of e)for(let n of t.blocks){if(n.kind!=="repeating_group")continue;if(!Number.isInteger(n.maxInstances)||n.maxInstances<1||n.maxInstances>20)return`Repeating group ${n.id} needs maxInstances to be a whole number between 1 and 20`;let r=n.minInstances??1;if(!Number.isInteger(r)||r<0||r>n.maxInstances)return`Repeating group ${n.id} needs minInstances to be a whole number between 0 and maxInstances (${n.maxInstances})`;if(n.minInstances=r,n.fields.length===0)return`Repeating group ${n.id} has no template fields \u2014 add at least one field to repeat`;if(n.fields.length>Xi)return`Repeating group ${n.id} has ${n.fields.length} template fields \u2014 the maximum is ${Xi}; split it into fewer fields`;for(let a of n.fields)if(!Ji.includes(a.kind))return`Repeating group ${n.id} has a "${a.kind}" child (${a.id}) \u2014 allowed child kinds are ${Ji.join(", ")}`;let i=fn(n.fields);if(i)return`Duplicate child id in repeating group ${n.id}: ${i}`;let o=new Set(n.fields.map(a=>a.id));for(let a of n.fields)for(let l of a.visibleIf??[])if(!o.has(l.fieldId))return`Field ${a.id} in repeating group ${n.id} has a visibleIf referencing "${l.fieldId}" \u2014 a child's visibleIf can only reference another field in the SAME group`;let s=Pa(n);if(s>Yi)return`Repeating group ${n.id} could reach ~${Math.ceil(s/1e3)}KB at ${n.maxInstances} instances \u2014 the maximum is ~${Math.round(Yi/1e3)}KB; lower maxInstances, shorten text limits, or trim the template`}return null}function Oa(e){let t=new Set;for(let r of e)for(let i of r.blocks)ce(i)&&t.add(i.id);let n=new Map;for(let r of e)for(let i of r.blocks)if(i.kind==="repeating_group")for(let o of i.fields)!t.has(o.id)&&!n.has(o.id)&&n.set(o.id,i.id);return n}function Za(e,t,n){for(let r of e)for(let i of r.blocks)for(let o of i.visibleIf??[]){let s=n.get(o.fieldId);if(s!==void 0)return`Field ${i.id}'s visibleIf references "${o.fieldId}", which is a child of repeating group ${s} \u2014 fields outside a repeating group can't reference its children`}for(let r of t)if(Array.isArray(r.next))for(let i of r.next){if(!i||typeof i!="object")continue;let o=i.when;if(Array.isArray(o))for(let s of o){if(!s||typeof s!="object")continue;let a=s.fieldId;if(typeof a!="string")continue;let l=n.get(a);if(l!==void 0)return`A jump rule on page ${r.id} references "${a}", which is a child of repeating group ${l} \u2014 jumps can't reference a repeating group's children`}}return null}function Co(e){return{id:_e(e.id,128),visibleIf:kr(e.visibleIf)}}function te(e,t){return{...Co(e),kind:t,label:_e(e.label,2e3,"Untitled field"),description:K(e.description,5e3),required:Me(e.required),placeholder:K(e.placeholder,500)}}function Qi(e){let t=K(e,2e3);if(t)try{let n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"?t:void 0}catch{return}}function Da(e){if(!e||typeof e!="object")return;let t=e,n=t.by==="browser"||t.by==="field"||t.by==="identify"||t.by==="email"?t.by:void 0;if(!n)return;let r=n==="field"?K(t.field,128):void 0;if(n==="field"&&!r)return;let i=K(t.scopeField,128),o=t.onRepeat==="update"&&(n==="identify"||n==="email")?"update":"keep";return{by:n,...r?{field:r}:{},...i?{scopeField:i}:{},onRepeat:o}}function Ua(e){if(!e||typeof e!="object")return;let t=e,n=t.unverified==="allow"||t.unverified==="quarantine"?t.unverified:void 0,r=t.challenge==="turnstile"?"turnstile":void 0;if(!(!n&&!r))return{...n?{unverified:n}:{},...r?{challenge:r}:{}}}function Ba(e){let t=e&&typeof e=="object"?e:{};return{submitMode:t.submitMode==="button"||t.submitMode==="auto"?t.submitMode:void 0,submitLabel:K(t.submitLabel,100),successTitle:K(t.successTitle,200),successMessage:K(t.successMessage,5e3),redirectUrl:Qi(t.redirectUrl),showProgress:Me(t.showProgress),responseLimit:Da(t.responseLimit),trust:Ua(t.trust),notifyEmail:en().check(le(254)).safeParse(t.notifyEmail).success?t.notifyEmail:void 0,notifyEmailIncludeAnswers:Me(t.notifyEmailIncludeAnswers),notifyEmailAnswerFields:Oe(fe().check(tt(1),le(128),Vn(/\S/))).check(le(500)).safeParse(t.notifyEmailAnswerFields).success?[...new Set(t.notifyEmailAnswerFields.map(r=>r.trim()))]:void 0,notifyEmailReplyToField:K(t.notifyEmailReplyToField,128),sendReceipt:Me(t.sendReceipt),saveProgress:Me(t.saveProgress),draftAnswersVisible:Me(t.draftAnswersVisible),resumeEmails:Me(t.resumeEmails),resumeUrl:Qi(t.resumeUrl),draftDigest:Me(t.draftDigest)}}function j(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Io(e){if(!e||typeof e!="object")return null;let t=e,n=t.kind,r=Co(t);if(!r.id||typeof n!="string")return null;switch(n){case"heading":return j({...r,kind:n,text:_e(t.text,2e3,"Section")});case"paragraph":return j({...r,kind:n,text:_e(t.text,5e3)});case"divider":return j({...r,kind:n});case"short_text":case"email":case"url":return j({...te(t,n),maxLength:Se(t.maxLength)===void 0?void 0:Ie(t.maxLength,1,2e3,2e3)});case"phone":{let i=K(t.defaultCountry,2)?.toUpperCase();return j({...te(t,n),defaultCountry:i&&/^[A-Z]{2}$/.test(i)?i:void 0})}case"long_text":return j({...te(t,n),maxLength:Se(t.maxLength)===void 0?void 0:Ie(t.maxLength,1,2e4,2e4)});case"number":return j({...te(t,n),min:Se(t.min),max:Se(t.max),decimals:Se(t.decimals)===void 0?void 0:Ie(t.decimals,0,6,0),prefix:nn(t.prefix,100),suffix:nn(t.suffix,100),notation:t.notation==="grouped"?"grouped":t.notation==="grouped-comma"?"grouped-comma":t.notation==="grouped-dot"?"grouped-dot":void 0});case"select":case"multi_select":case"dropdown":{let i=rn(t.options);return i.length===0?null:j({...te(t,n),options:i,allowOther:Me(t.allowOther),shuffleOptions:Me(t.shuffleOptions)})}case"checkbox":{let i=t.appearance==="toggle"?"toggle":void 0;return j({...te(t,n),appearance:i})}case"signature":return j(te(t,n));case"date":return j({...te(t,n),defaultToday:t.defaultToday===!0?!0:void 0});case"rating":{let i=Ie(t.max,1,10,5);return j({...te(t,n),max:i,insightsMetric:t.insightsMetric==="csat"&&i===5?"csat":void 0})}case"linear_scale":{let i=Ie(t.min,0,9,1),o=Ie(t.max,i+1,10,10),s=t.insightsMetric==="nps"&&i===0&&o===10?"nps":t.insightsMetric==="csat"&&i===1&&o===5?"csat":void 0;return j({...te(t,n),min:i,max:o,minLabel:K(t.minLabel,100),maxLabel:K(t.maxLabel,100),insightsMetric:s})}case"ranking":{let i=rn(t.options);return i.length<2?null:j({...te(t,n),options:i})}case"matrix":{let i=rn(t.rows),o=rn(t.columns);return i.length===0||o.length===0?null:j({...te(t,n),rows:i,columns:o})}case"hidden":return j({...te(t,n),required:!1,paramName:K(t.paramName,128),defaultValue:K(t.defaultValue,1e3)});case"calculated":return j({...te(t,n),required:!1,calc:t.calc,decimals:Se(t.decimals)===void 0?void 0:Ie(t.decimals,0,6,0),prefix:nn(t.prefix,100),suffix:nn(t.suffix,100)});case"file_upload":return j({...te(t,n),maxFiles:Ie(t.maxFiles,1,na,1),maxFileSizeMb:Ie(t.maxFileSizeMb,1,5e3,500),accept:Array.isArray(t.accept)?t.accept.flatMap(i=>{let o=K(i,100);return o?[o]:[]}).slice(0,50):void 0});case"repeating_group":{let o=(Array.isArray(t.fields)?t.fields:[]).slice(0,50).flatMap(s=>{let a=Io(s);return a&&ce(a)?[a]:[]});return j({...te(t,n),required:!1,fields:o,maxInstances:Se(t.maxInstances)??Number.NaN,minInstances:Se(t.minInstances),addLabel:K(t.addLabel,100),itemLabel:K(t.itemLabel,100)})}case"custom":return j({...te(t,n),component:_e(t.component,128),config:t.config&&typeof t.config=="object"&&!Array.isArray(t.config)?t.config:void 0});default:return null}}function Ye(e){let t=za.safeParse(e);if(!t.success){let v=t.error.issues[0],y=v?.path.join(".");return{ok:!1,error:v?`${y?`${y}: `:""}${v.message}`:"Invalid schema"}}if(t.data.version>Ca)return{ok:!1,error:`Unsupported schema version: ${t.data.version}`};let n=t.data.pages.map(v=>{let y=v.blocks.flatMap(F=>{let I=Io(F);return I?[I]:[]});return{id:_e(v.id,128),title:K(v.title,500),blocks:y,next:v.next}}),r=new Set(n.map(v=>v.id)),i=new Map;for(let v of n)for(let y of v.blocks){if(y.kind!=="calculated")continue;let F=new Set,I=Je(y.calc);if(I){let ee=new Set,xe=new Set;Xe(I,ee,xe);for(let M of ee)F.add(M);for(let M of xe)F.add(M)}i.set(y.id,F)}let o=new Set,s=n.map(v=>{for(let y of v.blocks)ce(y)&&o.add(y.id);return j({id:v.id,title:v.title,blocks:v.blocks,next:Ia(v.next,r,v.id,new Set(o),i)})}),a=new Set,l=new Set;for(let v of s){if(!v.id)return{ok:!1,error:"Page ids cannot be blank"};if(a.has(v.id))return{ok:!1,error:`Duplicate page id: ${v.id}`};a.add(v.id);for(let y of v.blocks){if(l.has(y.id))return{ok:!1,error:`Duplicate block id: ${y.id}`};if(l.add(y.id),y.kind==="number"&&y.min!==void 0&&y.max!==void 0&&y.min>y.max)return{ok:!1,error:`Field ${y.id} has min greater than max`};if(y.kind==="select"||y.kind==="multi_select"||y.kind==="dropdown"||y.kind==="ranking"){let F=fn(y.options);if(F)return{ok:!1,error:`Duplicate option id in field ${y.id}: ${F}`}}else if(y.kind==="matrix"){let F=fn(y.rows);if(F)return{ok:!1,error:`Duplicate matrix row id in field ${y.id}: ${F}`};let I=fn(y.columns);if(I)return{ok:!1,error:`Duplicate matrix column id in field ${y.id}: ${I}`}}}}let c=Ra(s);if(c)return{ok:!1,error:c};let u=Oa(s),m=Za(s,n,u);if(m)return{ok:!1,error:m};let f=Na(s,u);if(f)return{ok:!1,error:f};let h=La(s);if(h)return{ok:!1,error:h};if(s.every(v=>v.blocks.length===0))return{ok:!1,error:"Schema must contain at least one valid block"};let p={version:hr,title:_e(t.data.title,2e3),pages:s,settings:Ba(t.data.settings)},b=K(t.data.description,5e3);return b&&(p.description=b),{ok:!0,schema:p}}function Et(e,t){let n=K(e,t);if(n&&!(/[;{}<>]/.test(n)||/url\s*\(/i.test(n)))return n}function ja(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{8,64}$/.test(e)?e:void 0}function eo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n=j({primary:Et(t.primary,200),background:Et(t.background,200),text:Et(t.text,200),logo:ja(t.logo)});return Object.keys(n).length>0?n:void 0}function Mo(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=t.colorScheme==="light"||t.colorScheme==="dark"||t.colorScheme==="auto"?t.colorScheme:void 0,r=j({colorScheme:n,...eo(t),radius:Et(t.radius,64),fontFamily:Et(t.fontFamily,200),dark:eo(t.dark)});return Object.keys(r).length>0?r:null}function gt(e){return e.label.trim()||e.placeholder?.trim()||"Untitled field"}function Va(e){throw new Error(`Unhandled field kind: ${JSON.stringify(e)}`)}function $r(e,t){if(t==null||t==="")return"";switch(e.kind){case"file_upload":return Array.isArray(t)?t.map(n=>n.name).join(", "):String(t);case"select":case"dropdown":return e.options.find(n=>n.id===t)?.label??String(t);case"multi_select":return Array.isArray(t)?t.map(n=>e.options.find(r=>r.id===n)?.label??n).join(", "):String(t);case"ranking":return Array.isArray(t)?t.map((n,r)=>`${r+1}. ${e.options.find(i=>i.id===n)?.label??n}`).join(", "):String(t);case"matrix":{if(typeof t!="object"||t===null||Array.isArray(t))return String(t);let n=t;return e.rows.filter(r=>n[r.id]).map(r=>`${r.label}: ${e.columns.find(i=>i.id===n[r.id])?.label??""}`).join(", ")}case"signature":return typeof t=="string"&&t.startsWith("data:image/")?"\u270D signed":"";case"checkbox":return t===!0?"Yes":"No";case"rating":case"linear_scale":return String(t);case"number":{let n=typeof t=="number"?t:Number(t);if(!Number.isFinite(n))return String(t);let r=e.decimals===void 0?String(n):n.toFixed(Math.max(0,Math.min(6,e.decimals)));return`${e.prefix??""}${r}${e.suffix??""}`}case"calculated":{let n=typeof t=="number"?t:Number(t);if(!Number.isFinite(n))return String(t);let r=e.decimals===void 0?String(n):n.toFixed(Math.max(0,Math.min(6,e.decimals)));return`${e.prefix??""}${r}${e.suffix??""}`}case"repeating_group":{if(!Array.isArray(t))return String(t);let n=t;if(n.length===0)return"";let r=e.itemLabel??e.label,i=`${n.length} \xD7 ${r}`,o=e.fields[0];if(!o)return i;let s=n.map(a=>a&&typeof a=="object"&&!Array.isArray(a)?$r(o,a[o.id]):"").filter(a=>a!=="");return s.length>0?`${i}: ${s.join(", ")}`:i}case"phone":{let{country:n,national:r,e164:i}=Mt(String(t));if(!i)return String(t);let o=It(n,r),s=n?`+${n.dialCode}`:i.replace(r,"");return o?`${s} ${o}`:i}case"short_text":case"long_text":case"email":case"url":case"date":case"hidden":return String(t);case"custom":return typeof t=="object"?JSON.stringify(t):String(t);default:return Va(e)}}function Ha(e){return Math.max(0,Math.min(6,Math.round(e)))}function No(e){switch(e){case"grouped-comma":return"en-US";case"grouped-dot":return"de-DE";case"grouped":case void 0:return}}function Lo(e,t){if(!Number.isFinite(e))return String(e);let n=t?.decimals===void 0?void 0:Ha(t.decimals);if(typeof Intl>"u")return n===void 0?String(e):e.toFixed(n);let r={useGrouping:!0};return n===void 0?r.maximumFractionDigits=20:(r.minimumFractionDigits=n,r.maximumFractionDigits=n),new Intl.NumberFormat(t?.locale,r).format(e)}function To(e,t){return t?e.split(t).join(""):e}function to(e,t){return t==="."?e:e.split(t).join(".")}function Ga(e,t,n){if(n!==t&&e.includes(n)){let o=e.lastIndexOf(n),s=To(e.slice(0,o),t),a=e.slice(o+n.length);return`${s}.${a}`}let r=e.split(t);return r.length===1?e:r.every((o,s)=>s===0?/^[1-9]\d{0,2}$/.test(o):/^\d{3}$/.test(o))?r.join(""):`${r.slice(0,-1).join("")}.${r.at(-1)??""}`}function Sr(e,t){if(typeof Intl>"u"||e.trim()==="")return e;let n=new Intl.NumberFormat(t).formatToParts(12345678e-1),r=n.find(a=>a.type==="group")?.value??",",i=n.find(a=>a.type==="decimal")?.value??".",o=e.trim(),s=o.startsWith("-");return s&&(o=o.slice(1)),/^\s$/.test(r)?o=to(o.replace(/\s/g,""),i):r==="."||r===","?o=Ga(o,r,i):o=to(To(o,r),i),o===""||o==="."||!/^\d*\.?\d*$/.test(o)?e:s?`-${o}`:o}function Lt(e,t){let r=e.startsWith("-")?e.slice(1):e;if(r.includes("-"))return!1;if(r==="")return!0;if(typeof Intl>"u")return/^[\d.,]*$/.test(r);let i=new Intl.NumberFormat(t).formatToParts(12345678e-1),o=i.find(m=>m.type==="group")?.value??",",s=i.find(m=>m.type==="decimal")?.value??".",a=o===".",l=/^\s$/.test(o),c=a?[s]:Array.from(new Set([".",s])),u=0;for(let m of r)if(!/\d/.test(m)){if(c.includes(m)){if(++u>1)return!1;continue}if(!(l?/\s/.test(m):m===o))return!1}return!0}var gr="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",qa=256-256%gr.length;function no(e=12){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError("createId size must be a positive safe integer");let t=globalThis.crypto;if(typeof t>"u"||typeof t.getRandomValues!="function")throw new Error("createId requires Web Crypto (globalThis.crypto.getRandomValues)");let n="";for(;n.length<e;){let r=new Uint8Array(e);t.getRandomValues(r);for(let i=0;i<e&&n.length<e;i++){let o=r[i];o<qa&&(n+=gr[o%gr.length])}}return n}var Po=class{h0=1732584193;h1=4023233417;h2=2562383102;h3=271733878;h4=3285377520;block=new Uint8Array(64);blockLen=0;totalLen=0;w=new Int32Array(80);update(e){this.totalLen+=e.length;let t=0;if(this.blockLen>0){for(;t<e.length&&this.blockLen<64;)this.block[this.blockLen++]=e[t++];this.blockLen===64&&(this.process(this.block),this.blockLen=0)}for(;t+64<=e.length;)this.process(e.subarray(t,t+64)),t+=64;for(;t<e.length;)this.block[this.blockLen++]=e[t++];return this}digest(){let e=Math.floor(this.totalLen/536870912),t=this.totalLen*8>>>0,n=[128],r=this.blockLen+1;for(;r%64!==56;)n.push(0),r++;n.push(e>>>24&255,e>>>16&255,e>>>8&255,e&255),n.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255),this.update(new Uint8Array(n));let i=new Uint8Array(20),o=[this.h0,this.h1,this.h2,this.h3,this.h4];for(let s=0;s<5;s++)i[s*4]=o[s]>>>24&255,i[s*4+1]=o[s]>>>16&255,i[s*4+2]=o[s]>>>8&255,i[s*4+3]=o[s]&255;return i}process(e){let t=this.w;for(let a=0;a<16;a++)t[a]=e[a*4]<<24|e[a*4+1]<<16|e[a*4+2]<<8|e[a*4+3];for(let a=16;a<80;a++){let l=t[a-3]^t[a-8]^t[a-14]^t[a-16];t[a]=l<<1|l>>>31}let n=this.h0,r=this.h1,i=this.h2,o=this.h3,s=this.h4;for(let a=0;a<80;a++){let l,c;a<20?(l=r&i|~r&o,c=1518500249):a<40?(l=r^i^o,c=1859775393):a<60?(l=r&i|r&o|i&o,c=2400959708):(l=r^i^o,c=3395469782);let u=(n<<5|n>>>27)+l+s+c+t[a]|0;s=o,o=i,i=r<<30|r>>>2,r=n,n=u}this.h0=this.h0+n|0,this.h1=this.h1+r|0,this.h2=this.h2+i|0,this.h3=this.h3+o|0,this.h4=this.h4+s|0}},on="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Ar(e){let t="";for(let n=0;n<e.length;n+=3){let r=e[n],i=n+1<e.length?e[n+1]:0,o=n+2<e.length?e[n+2]:0;t+=on[r>>2],t+=on[(r&3)<<4|i>>4],t+=n+1<e.length?on[(i&15)<<2|o>>6]:"=",t+=n+2<e.length?on[o&63]:"="}return t}var Wa=e=>Ar(new Po().update(e).digest()),C=class extends Error{constructor(e,t,n,r){super(e),this.status=t,this.retryAfterSec=n,this.code=r,this.name="FilloError"}status;retryAfterSec;code};function be(e){return e instanceof Error&&e.name==="FilloError"}async function ro(e,t){try{let n=await e.json();return{message:typeof n.error=="string"&&n.error?n.error:t,code:typeof n.code=="string"&&n.code?n.code:void 0}}catch{}return{message:t}}function sn(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t:void 0}var dt=3,Ka=4,rt=3e4,Ja=5*6e4,$e=10*6e4;function an(e,t){return t?.throwIfAborted(),new Promise((n,r)=>{let i=()=>{clearTimeout(o),r(t?.reason)},o=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);t?.addEventListener("abort",i,{once:!0})})}function Xn(e,t=!1){let n=be(e)?e.status??0:0;return n===0||n===503||n===504||t&&n===409&&be(e)&&e.retryAfterSec!==void 0}function ln(e){return e>=500||e===429||e===408}function Yn(e){return typeof DOMException<"u"&&e instanceof DOMException&&e.name==="TimeoutError"?new C("Request timed out",0):e}function Xa(e,t){let n=e.split(".").map(i=>Number(i)||0),r=t.split(".").map(i=>Number(i)||0);for(let i=0;i<Math.max(n.length,r.length);i++){let o=(n[i]??0)-(r[i]??0);if(o!==0)return o}return 0}function Ya(e){if(e.schemaVersion!==void 0&&e.schemaVersion!==hr)throw new C(`This form uses schema version ${e.schemaVersion}; this SDK supports version ${hr}. Update @usefillo/* to render it.`,426);if(e.minSdkVersion&&Xa(mr,e.minSdkVersion)<0)throw new C(`This form requires @usefillo/* ${e.minSdkVersion} or newer. Current SDK is ${mr}.`,426)}function cn(e,t){return n=>t.onProgress?.({uploadedBytes:n,totalBytes:e,fraction:e===0?1:n/e})}async function Qa(e){let t=globalThis.crypto?.subtle;if(t){let n=await t.digest("SHA-1",e);return Ar(new Uint8Array(n))}return Wa(e)}var el="https://fillo.so",Qn={"X-Fillo-Client":`@usefillo/core@${mr}`},vn=class{baseUrl;fetch;activeUploads=0;uploadQueue=new Set;key;constructor(e={}){this.baseUrl=e.baseUrl?e.baseUrl.replace(/\/$/,""):e.sameOrigin?"":el,this.key=e.key,this.fetch=e.fetch??((...t)=>globalThis.fetch(...t))}url(e){return`${this.baseUrl}/api/v1${e}`}async json(e,t){let n=t?.body!=null?{"Content-Type":"application/json",...Qn,...t?.headers}:t?.headers,r;try{r=await this.fetch(this.url(e),{...t,headers:n,signal:t?.signal??AbortSignal.timeout(rt)})}catch(i){throw Yn(i)}if(!r.ok){let{message:i,code:o}=await ro(r,`Request failed: ${r.status}`);throw new C(i,r.status,sn(r),o)}return await r.json()}async getForm(e){let t=await this.json(`/forms/${encodeURIComponent(e)}`);return Ya(t),t}syncForm(e,t,n){if(!this.key)return Promise.reject(new C("createClient needs a `key` (pk_\u2026) to sync code-defined forms",401));let r=Ye(t);return r.ok?this.json("/forms/sync",{method:"POST",body:JSON.stringify({key:this.key,id:e,schema:r.schema,theme:Mo(n)})}):Promise.reject(new C(`Invalid form schema: ${r.error}`,400))}async reportInvalidDefinition(e,t){try{let n="formId"in e?{formId:e.formId}:this.key?{key:this.key,id:e.handle}:null;if(!n)return null;let r=await this.fetch(this.url("/forms/definition-report"),{method:"POST",headers:{"Content-Type":"application/json",...Qn},body:JSON.stringify({...n,schema:t}),signal:AbortSignal.timeout(rt)});if(!r.ok)return null;let i=await r.json();return typeof i.formId=="string"&&i.formId?i.formId:null}catch{return null}}async submit(e,t,n){let r;try{r=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/responses`),{method:"POST",headers:{"Content-Type":"application/json",...Qn},body:JSON.stringify({data:t,meta:n}),signal:AbortSignal.timeout(rt)})}catch(o){throw Yn(o)}if(r.status===422){let o=await r.json().catch(()=>null);if(o?.errors&&typeof o.errors=="object"&&!Array.isArray(o.errors))return{ok:!1,errors:o.errors};throw new C(typeof o?.error=="string"&&o.error?o.error:"Submit failed: 422",422,sn(r),typeof o?.code=="string"&&o.code?o.code:void 0)}if(!r.ok){let{message:o,code:s}=await ro(r,`Submit failed: ${r.status}`);throw new C(o,r.status,sn(r),s)}let i=await r.json();return{ok:!0,responseId:i.id,duplicate:i.duplicate,updated:i.updated}}async fetchOwnResponse(e,t,n){try{return await this.json(`/forms/${encodeURIComponent(e)}/respondent-response`,{method:"POST",body:JSON.stringify({respondent:t,scopeValue:n})})}catch(r){if(be(r)&&(r.status===404||r.status===403))return null;throw r}}async startSession(e,t){try{let n=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/sessions`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pageCount:t}),signal:AbortSignal.timeout(rt)});return n.ok?(await n.json()).id:null}catch{return null}}reportProgress(e,t){try{this.fetch(this.url(`/sessions/${encodeURIComponent(e)}/progress`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0,signal:AbortSignal.timeout(rt)}).catch(()=>{})}catch{}}createDraft(e,t){return this.json(`/forms/${encodeURIComponent(e)}/drafts`,{method:"POST",body:JSON.stringify(t)})}getDraft(e,t,n){return this.json(`/drafts/${encodeURIComponent(e)}`,{headers:n?{"X-Fillo-Draft-Token":t,"X-Fillo-Draft-Adopt":"1"}:{"X-Fillo-Draft-Token":t}})}async saveDraft(e,t,n,r){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"X-Fillo-Draft-Token":t},body:JSON.stringify(n),...r?.keepalive?{keepalive:!0}:{}})}async deleteDraft(e,t){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-Fillo-Draft-Token":t}})}getUploadSession(e,t,n=AbortSignal.timeout($e)){return this.json(`/uploads/${encodeURIComponent(e)}`,{...t?{headers:{"X-Fillo-Upload-Token":t}}:{},signal:n})}async uploadFile(e,t,n){await this.acquireUploadSlot(n.signal);try{return n.signal?.throwIfAborted(),await this.performUpload(e,t,n)}finally{this.activeUploads-=1;let r=this.uploadQueue.values().next().value;r&&(this.uploadQueue.delete(r),r())}}async acquireUploadSlot(e){if(e?.throwIfAborted(),this.activeUploads<Ka){this.activeUploads+=1;return}await new Promise((t,n)=>{let r=()=>{e?.removeEventListener("abort",i),this.activeUploads+=1,t()},i=()=>{this.uploadQueue.delete(r),n(e?.reason)};this.uploadQueue.add(r),e?.addEventListener("abort",i,{once:!0})})}async performUpload(e,t,n){let r=typeof File<"u"&&t instanceof File?t.name:"upload.bin",i=(t.type||"application/octet-stream").trim().toLowerCase(),o;if(n.sessionId){let c=await this.getUploadSession(n.sessionId,n.uploadToken,this.uploadSignal(n,$e));if(c.formId!==e||c.fieldId!==n.fieldId||c.fileName!==r||c.size!==t.size||c.mime.trim().toLowerCase()!==i)throw new C("File does not match this upload session",400);o=c,o.token||=n.uploadToken}else{let c=no(24),u=no(32),m=()=>this.json(`/forms/${encodeURIComponent(e)}/uploads`,{method:"POST",body:JSON.stringify({requestId:c,uploadToken:u,fieldId:n.fieldId,fileName:r,size:t.size,mime:i}),signal:this.uploadSignal(n,$e)}),f=Date.now()+$e,h=250;for(;;)try{o=await m();break}catch(p){if(n.signal?.aborted||!Xn(p,!0))throw p;let b=f-Date.now();if(b<=0)throw p;await an(Math.min(h,b),n.signal),h=Math.min(h*2,5e3)}}if(n.onSession?.({sessionId:o.id,uploadToken:o.token}),o.status==="complete"&&o.file)return o.file;if(o.status==="aborted")throw new C("This upload session was cancelled",409);let s;if(o.transport?.type==="gdrive")await this.driveUploadLoop(o,o.transport.uploadUrl,t,n);else if(o.transport?.type==="s3-multipart")await this.s3MultipartUploadLoop(o,t,n);else if(o.transport?.type==="s3-put")await this.s3PutUpload(o.transport.uploadUrl,t,n);else if(o.transport?.type==="box")s=await this.boxUpload(o.transport,t,n);else throw new C("This form's storage doesn't support uploads \u2014 connect Drive, S3, or Box.");let a=()=>this.json(`/uploads/${encodeURIComponent(o.id)}/complete`,{method:"POST",headers:o.token?{"X-Fillo-Upload-Token":o.token}:void 0,...s?{body:JSON.stringify(s)}:{},signal:this.uploadSignal(n,$e)}),l;try{l=await a()}catch(c){if(n.signal?.aborted||!Xn(c))throw c;let u=Date.now()+$e,m=250;for(;;){let f=await this.getUploadSession(o.id,o.token,this.uploadSignal(n,Math.max(1,u-Date.now())));if(f.status==="complete"&&f.file)return f.file;if(f.status==="aborted")throw c;try{l=await a();break}catch(p){if(n.signal?.aborted||!Xn(p,!0))throw p}let h=u-Date.now();if(h<=0)throw c;await an(Math.min(m,h),n.signal),m=Math.min(m*2,5e3)}}if(!l.file)throw new C("Upload completed but no file was returned");return l.file}async boxUpload(e,t,n){let r=cn(t.size,n);r(0);let i={Authorization:`Bearer ${e.token}`};if(e.mode==="simple"){let p=new FormData;p.append("attributes",JSON.stringify({name:e.fileName,parent:{id:e.folderId}})),p.append("file",t,e.fileName);let b=await this.retry(n,async()=>{let y=await this.fetch(e.uploadUrl,{method:"POST",headers:i,body:p,signal:this.uploadSignal(n)});if(!y.ok&&ln(y.status))throw new C(`Box upload failed: ${y.status}`,y.status);return y});if(!b.ok)throw new C(`Box upload failed: ${b.status}`,b.status);let v=await b.json();return r(t.size),{providerFileId:v.entries?.[0]?.id}}if(e.size!==t.size)throw new C(`File size changed since the upload was requested (${t.size} vs ${e.size}).`,400);let o=await this.retry(n,async()=>{let p=await this.fetch(e.sessionUrl,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify({folder_id:e.folderId,file_size:e.size,file_name:e.fileName}),signal:this.uploadSignal(n)});if(!p.ok&&ln(p.status))throw new C(`Box session failed: ${p.status}`,p.status);return p});if(!o.ok)throw new C(`Box session failed: ${o.status}`,o.status);let s=await o.json(),a=new Po,l=[],c=0;for(;c<t.size;){n.signal?.throwIfAborted();let p=Math.min(c+s.part_size,t.size),b=new Uint8Array(await t.slice(c,p).arrayBuffer());a.update(b);let v=await Qa(b),y=await this.retry(n,async()=>{let F=await this.fetch(s.session_endpoints.upload_part,{method:"PUT",headers:{...i,"Content-Type":"application/octet-stream",Digest:`sha=${v}`,"Content-Range":`bytes ${c}-${p-1}/${t.size}`},body:b,signal:this.uploadSignal(n)});if(!F.ok&&ln(F.status))throw new C(`Box part failed: ${F.status}`,F.status);return F});if(!y.ok)throw new C(`Box part failed: ${y.status}`,y.status);l.push((await y.json()).part),c=p,r(c)}let u=Date.now()+$e,m=JSON.stringify({parts:l}),f={...i,"Content-Type":"application/json",Digest:`sha=${Ar(a.digest())}`},h=0;for(;;){n.signal?.throwIfAborted();let p=u-Date.now();if(p<=0)throw new C("Box upload processing timed out",0);let b;try{if(b=await this.fetch(s.session_endpoints.commit,{method:"POST",headers:f,body:m,signal:this.uploadSignal(n,Math.min(rt,p))}),!b.ok&&ln(b.status))throw new C(`Box commit failed: ${b.status}`,b.status)}catch(F){if(n.signal?.throwIfAborted(),++h>=dt)throw Yn(F);await an(Math.min(500*2**h,Math.max(0,u-Date.now())),n.signal);continue}if(h=0,b.status===202){let F=sn(b),I=Date.parse(b.headers.get("retry-after")??""),ee=F!==void 0?F*1e3:Number.isFinite(I)?Math.max(1e3,I-Date.now()):1e3;await b.body?.cancel().catch(()=>{}),await an(Math.min(ee,Math.max(0,u-Date.now())),n.signal);continue}if(!b.ok)throw new C(`Box commit failed: ${b.status}`,b.status);let y=(await b.json()).entries?.[0]?.id;if(typeof y!="string"||!y)throw new C("Box upload completed but no file was returned",502);return{providerFileId:y}}}uploadSignal(e,t=rt){let n=AbortSignal.timeout(t);return e.signal?AbortSignal.any([e.signal,n]):n}async retry(e,t){let n=0;for(;;)try{return await t()}catch(r){if(e.signal?.aborted||(n+=1,n>=dt))throw r;await new Promise(i=>setTimeout(i,500*2**n))}}async driveUploadLoop(e,t,n,r){let i=e.uploadedBytes,o=cn(n.size,r);o(i);let s=0;for(;i<n.size;){r.signal?.throwIfAborted();let a=i,l=Math.min(i+e.chunkSize,n.size),c=n.slice(i,l),u=0;for(;;)try{let m=await this.fetch(t,{method:"PUT",headers:{"Content-Range":`bytes ${i}-${l-1}/${n.size}`},body:c,signal:this.uploadSignal(r)});if(m.status===308){let f=m.headers.get("Range")??m.headers.get("range"),h=f?.match(/bytes=0-(\d+)/);h?i=Number(h[1])+1:f==null?i=0:i=(await this.getUploadSession(e.id,e.token,this.uploadSignal(r,$e))).uploadedBytes;break}if(m.ok){i=n.size;break}throw new C(`Drive chunk failed: ${m.status}`,m.status)}catch(m){if(r.signal?.aborted||(u+=1,u>=dt))throw m;if(await new Promise(h=>setTimeout(h,500*2**u)),i=(await this.getUploadSession(e.id,e.token,this.uploadSignal(r,$e))).uploadedBytes,i>=n.size)break;l=Math.min(i+e.chunkSize,n.size),c=n.slice(i,l)}if(o(i),i<=a){if(++s>=dt)throw new C("Drive upload stalled \u2014 the storage endpoint stopped accepting progress",0)}else s=0}}async s3MultipartUploadLoop(e,t,n){if(!Number.isSafeInteger(e.chunkSize)||e.chunkSize<=0||!Number.isSafeInteger(e.uploadedBytes)||e.uploadedBytes<0||e.uploadedBytes>t.size||e.uploadedBytes<t.size&&e.uploadedBytes%e.chunkSize!==0)throw new C("S3 upload session returned invalid progress",502);let r=cn(t.size,n),i=e.uploadedBytes;for(r(i);i<t.size;){n.signal?.throwIfAborted();let o=Math.floor(i/e.chunkSize)+1;if(o>1e4)throw new C("S3 upload needs too many parts",413);let s=Math.min(i+e.chunkSize,t.size),a=t.slice(i,s),l=0;for(;;){let c;try{let u=await this.json(`/uploads/${encodeURIComponent(e.id)}/parts`,{method:"POST",headers:e.token?{"X-Fillo-Upload-Token":e.token}:void 0,body:JSON.stringify({partNumber:o}),signal:this.uploadSignal(n,$e)});if(typeof u.uploadUrl!="string"||!u.uploadUrl)throw new C("S3 part URL was unavailable",502);c=u.uploadUrl;let m=await this.fetch(c,{method:"PUT",body:a,signal:this.uploadSignal(n,Ja)});if(!m.ok)throw new C(`S3 part upload failed: ${m.status}`,m.status);i=s,r(i);break}catch(u){if(n.signal?.aborted)throw u;let m=await this.getUploadSession(e.id,e.token,this.uploadSignal(n,$e));if(m.status==="aborted")throw new C("This upload session was cancelled",409);if(!Number.isSafeInteger(m.uploadedBytes)||m.uploadedBytes<i||m.uploadedBytes>t.size||m.uploadedBytes<t.size&&m.uploadedBytes%e.chunkSize!==0)throw new C("S3 upload session returned invalid progress",502);if(m.uploadedBytes>i){i=m.uploadedBytes,r(i);break}if(l+=1,l>=dt)throw u;await new Promise(f=>setTimeout(f,500*2**l))}}}}async s3PutUpload(e,t,n){let r=cn(t.size,n);r(0);let i=0;for(;;)try{let o=await this.fetch(e,{method:"PUT",headers:{"Content-Type":t.type||"application/octet-stream"},body:t,signal:this.uploadSignal(n)});if(!o.ok)throw new C(`S3 upload failed: ${o.status}`,o.status);r(t.size);return}catch(o){if(n.signal?.aborted||(i+=1,i>=dt))throw o;await new Promise(s=>setTimeout(s,500*2**i))}}};function Te(e={}){return new vn(e)}function er(e){let t=e.trim();if(!/^-?\d*\.?\d+$/.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}function tl(e=new Date){let t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${n}`}function io(e,t,n=new Date){let r=null;for(let i of Le(e))i.kind!=="date"||!i.defaultToday||t[i.id]!==void 0||(r=r??{...t},r[i.id]=tl(n));return r??t}function oo(e,t){let n={};for(let r of Le(e)){let i=r.kind==="hidden"?t[r.paramName??r.id]??r.defaultValue:t[r.id];if(!(i===void 0||i===""))switch(r.kind){case"number":{let o=er(i);if(o===null||r.min!==void 0&&o<r.min||r.max!==void 0&&o>r.max)break;n[r.id]=o;break}case"rating":{let o=er(i);o!==null&&Number.isInteger(o)&&o>=1&&o<=(r.max??5)&&(n[r.id]=o);break}case"linear_scale":{let o=er(i),s=r.min??1,a=r.max??10;o!==null&&Number.isInteger(o)&&o>=s&&o<=a&&(n[r.id]=o);break}case"checkbox":n[r.id]=i==="true"||i==="1"||i==="yes";break;case"select":case"dropdown":{r.options.some(o=>o.id===i)&&(n[r.id]=i);break}case"multi_select":{let o=new Set(r.options.map(a=>a.id)),s=[...new Set(i.split(",").filter(a=>o.has(a)))];s.length>0&&(n[r.id]=s);break}case"file_upload":case"ranking":case"matrix":case"signature":case"custom":break;case"calculated":break;case"repeating_group":break;default:n[r.id]=i}}return n}function nl(){if(!(typeof document>"u"||typeof window>"u"))try{let e=new URL(window.location.href);e.hash="";let t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("hubspotutk="))?.slice(11),n={pageUri:e.href.slice(0,2048),pageName:document.title.trim().slice(0,200)||void 0,hubspotutk:t&&/^[a-f0-9]{32}$/i.test(t)?t:void 0};return Object.values(n).some(Boolean)?n:void 0}catch{return}}var rl={id:"empty",blocks:[]},so=!1,ao=!1;function il(){ao||(ao=!0,console.warn("[fillo] This form has a client but no submission target \u2014 a bare schema can't sync. Wrap it in defineForm({ id, pages }) (or author it with <Fillo.Form id=\u2026>) so it gets a project handle, or pass formId for a dashboard-built form: https://fillo.so/docs"))}function ol(){so||(so=!0,console.warn("[fillo] This form has no `client`, so responses can't be submitted \u2014 it's render-only. Pass a client (createClient) to collect responses in Fillo, or forward them to your own backend with webhooks: https://fillo.so/docs"))}var Ro=new Map,st=new Set;function Fr(){try{return globalThis.localStorage??null}catch{return null}}function Oo(e){return`fillo:submission:${e}`}function pn(){let e=globalThis.crypto;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);return e?.getRandomValues?(e.getRandomValues(t),Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function Zo(e,t,n,r){if(st.has(t))return e.get(n)??null;let i=Fr();if(!i)return e.get(n)??null;let o;try{o=i.getItem(t)}catch{return e.get(n)??null}try{let s=JSON.parse(o??"null");if(s&&r(s))return s}catch{}return null}function Do(e,t,n,r){e.set(n,r);let i=Fr();if(!i){st.add(t);return}try{i.setItem(t,JSON.stringify(r)),st.delete(t)}catch{st.add(t)}}function Er(e){return Zo(Ro,Oo(e),e,t=>typeof t.key=="string")}function Uo(e,t){Do(Ro,Oo(e),e,t)}function sl(e){let t=Er(e);if(t?.key)return t.key;let n={key:pn()};return Uo(e,n),n.key}function al(e,t){let n=Er(e);Uo(e,{key:n?.key??pn(),submittedAt:new Date().toISOString(),responseId:t})}function br(e,t,n){let r=yo(e.settings,n);return r===null?t:`${t}::${r}`}function tr(e,t,n){return e.settings.responseLimit?.by!=="browser"||!t?!1:!!Er(br(e,t,n))?.submittedAt}var zr=new Map,Cr=new Map,hn=new Map;function W(e){return Cr.get(e)??0}function un(e,t,n){return Math.max(hn.get(JSON.stringify(["person",e,t??null]))??0,n?hn.get(JSON.stringify(["draft",e,n]))??0:0)}function Ir(e){return`fillo:draft:${e}`}function Ke(e,t){let n=Zo(zr,Ir(e),e,r=>{let i=r;return typeof i.id=="string"&&typeof i.token=="string"});return n?.respondentId&&t&&n.respondentId!==t?null:n}function ft(e,t,n){Cr.set(e,W(e)+1),Do(zr,Ir(e),e,{...t,respondentId:n??t.respondentId})}function nr(e,t=!1,n){let r=t?Ke(e):null,i=W(e)+1;Cr.set(e,i),t&&(hn.set(JSON.stringify(["person",e,n??r?.respondentId??null]),i),r&&hn.set(JSON.stringify(["draft",e,r.id]),i)),zr.delete(e);let o=Ir(e),s=Fr();if(!s){st.add(o);return}try{s.removeItem(o),st.delete(o)}catch{st.add(o)}}function rr(e){return be(e)&&(e.status===401||e.status===403||e.status===404)}var ll=1500;function Bo(e,t){if(be(e)){let n=e.status??0;if(n===404)return t.loadFailedNotFound;switch(e.code){case"submit_rate_limited":return t.submitRateLimited;case"workspace_unavailable":case"provision_closed":return t.formClosed;case"respondent_unrecognized":return t.respondentUnrecognized;case"invalid_file_reference":return t.fileUnavailable;case"response_scope_missing":return t.scopeMissing}if(n>0)return t.submitFailed}return t.loadFailedNetwork}function cl(e,t,n){if(be(e)){let r=e.status??0;if(t&&r>0&&e.message)return e.code?`${e.message} (${e.code})`:e.message;if(r>0&&r<500&&r!==408&&r!==429)return n.formUnavailable;if(r>0)return n.submitFailed}return Bo(e,n)}function jo(e){let{onChange:t,onSubmitted:n}=e,r={...qi,...e.respondentErrorStrings},i=Ye(e.form);if(!i.ok)throw new Error(`Invalid form schema: ${i.error}`);let o=i.schema,s=e.formId,a=e.client,l=e.respondent,c=l?.id,u=0,m={...e.initialData??{}},f=nt(o,{...m}),h={},p={},b=new Set,v=0,y,F=[];function I(){return e.previewNavigation===!0&&e.skipValidation===!0&&!a&&!s&&!e.resolveFormId}function ee(){return ht(o,f,I()?y:void 0)}function xe(){I()&&F.push({pageIndex:v,startPageId:y})}let M="idle",ne=!1,re=!1,Qe=!1,U=0,ie=new Set,Ae=!1;queueMicrotask(()=>{if(re||Qe)return;if(typeof location<"u"&&location.search){let _=Object.fromEntries(new URLSearchParams(location.search)),x=null;for(let[$,A]of Object.entries(oo(o,_)))f[$]===void 0&&(x=x??{...f},x[$]=A);x&&M==="idle"&&(f=nt(o,x),T())}let g=io(o,f);g!==f&&M==="idle"&&(f=nt(o,g),T()),M==="idle"&&tr(o,s,f)&&(M="submitted",ne=!0,T());let w=!1;if(o.settings.saveProgress&&(!c||l?.id)&&s&&a&&typeof location<"u"&&location.hash.includes("fillo-draft=")){let _=/fillo-draft=([^&]+)/.exec(location.hash),x="";try{x=_?.[1]?decodeURIComponent(_[1]):""}catch{}let $=x.indexOf(".");if($>0&&$<x.length-1){w=!0;let A=U,S=ke,z=s,H=a,D=W(z),X=l?.id,B=x.slice(0,$),G=x.slice($+1);H.getDraft(B,G,!0).then(Q=>{if(S.refs.set(A,{id:B,token:Q.token??G}),!he(A,z,H)||W(z)!==D){Sn(z,H,A,D,X,{id:B,token:Q.token??G,existing:!0});return}ft(z,{id:B,token:Q.token??G},X);try{history.replaceState(null,"",location.pathname+location.search)}catch{}}).catch(Q=>{he(A,z,H)&&rr(Q)&&(Ae=!0,T())}).finally(()=>{he(A,z,H)&&qt()})}else Ae=!0,T()}w||qt()});let oe,Ze=new Set,E=new Set,Fe=Date.now(),Y=pn(),J=null,Pe=!1,De=0,Ee=!1,Z=!1,ue="created",ye=!1,O=null,ke={ownerId:c,first:U,last:U,refs:new Map};function yt(g){let w=Ke(g,l?.id);return!l?.id&&(c||w?.respondentId)?null:w}let se=null,jt=Promise.resolve(),Ue=!1,kn=!1,$n=!1,Vt=!1;function Br(){De+=1,Pe=!1,J=null}function jr(){b.clear(),p={},Y=pn(),M="idle",oe=void 0,ne=!1,ue="created",Br()}function Vr(){let g={...m};if(typeof location<"u"&&location.search){let w=Object.fromEntries(new URLSearchParams(location.search));for(let[_,x]of Object.entries(oo(o,w)))g[_]===void 0&&(g[_]=x)}return nt(o,io(o,g))}function he(g,w,_){return!re&&U===g&&s===w&&a===_}function Hr(g,w,_,x,$,A){return he(g,w,_)&&!ie.has(g)&&un(w,$,A)<=x&&(W(w)===x||!Ke(w))}function Sn(g,w,_,x,$,A){let S=Ke(g),z=ie.has(_)||un(g,$,A.id)>x,H=!$||$===(l?.id??c)||g!==s;if(S?.id===A.id){if(!z&&H&&A.existing&&S.token!==A.token){let D=W(g);w.getDraft(A.id,A.token).then(X=>{let B=Ke(g);if(W(g)!==D||B?.id!==S.id||B.token!==S.token){un(g,$,A.id)>x&&B?.id!==A.id&&w.deleteDraft(A.id,A.token).catch(()=>{});return}if($&&$!==(l?.id??c)&&g===s)return;let G={id:A.id,token:A.token};ft(g,G,$),he(_,g,w)&&(O=G,Gt(X))}).catch(()=>{})}return}O?.id!==A.id&&(z?w.deleteDraft(A.id,A.token).catch(()=>{}):!S&&H&&ft(g,{id:A.id,token:A.token},$))}function Gr(){let g=o.pages.length,w=Math.min(v,Math.max(g-1,0)),_=o.pages[w]??rl;return{data:f,errors:h,status:M,pageIndex:w,pageCount:g,page:_,blocks:tn(o,_,f),isFirstPage:w===0,isLastPage:I()&&y!==void 0?ee().at(-1)===_.id:ur(o,_.id,f),uploading:Ze.size>0,submitError:oe,restoredSubmission:ne,resumedDraft:Ee,editingPrevious:Z,duplicateSubmission:ue==="duplicate",updatedSubmission:ue==="updated",resumeLinkFailed:Ae}}let qr=Gr();function T(){qr=Gr();for(let g of E)g()}function An(g,w){try{n?.(g,w)}catch(_){console.error("[fillo] onSubmitted handler threw:",_)}}function Wr(g){let w=o.pages[g];if(!w)return{};let _={};for(let x of tn(o,w,f))ce(x)&&(I()&&x.kind==="file_upload"||Object.assign(_,pr(x,f[x.id]).errors));return _}function Fn(g){for(let w of o.pages)for(let _ of w.blocks)ce(_)&&(Object.hasOwn(g,_.id)||_.kind==="repeating_group"&&Object.keys(g).some(x=>x.startsWith(`${_.id}.`)))&&b.add(_.id)}function Kr(g){if(b.size===0&&Object.keys(h).length===0)return;let w=new Set(ee()),_=new Map(o.pages.filter(S=>w.has(S.id)).flatMap(S=>tn(o,S,f)).filter(ce).map(S=>[S.id,S])),x=[..._.values()].filter(S=>S.kind==="repeating_group").sort((S,z)=>z.id.length-S.id.length),$=new Map,A=Object.fromEntries(Object.entries(h).filter(([S])=>{let z=_.get(S)??x.find(D=>S.startsWith(`${D.id}.`));if(!z)return delete p[S],!1;let H=$.get(z.id)??[];return H.push(S),$.set(z.id,H),!0}));for(let S of _.values()){let z=$.get(S.id)??[];if(S.id!==g&&z.some(X=>Object.hasOwn(p,X))||!(b.has(S.id)||S.id===g&&z.length>0))continue;for(let X of z)delete A[X],delete p[X];if(Ze.has(S.id)||e.skipValidation&&!(a&&s)&&S.kind==="file_upload")continue;let D=pr(S,f[S.id]).errors;Object.assign(A,D),Object.keys(D).length>0&&b.add(S.id)}h=A}function Jr(g){return o.pages.findIndex(w=>tn(o,w,f).some(_=>{if(_.id in g)return!0;if(_.kind!=="repeating_group")return!1;let x=f[_.id];return Array.isArray(x)?x.some(($,A)=>$&&typeof $=="object"&&!Array.isArray($)?gn(_,$).some(S=>`${_.id}.${A}.${S.id}`in g):!1):!1}))}function Ht(){return!!(!re&&o.settings.saveProgress&&a&&s&&!kn)}function vs(){let g=new Set;for(let w of o.pages)for(let _ of w.blocks)ce(_)&&g.add(_.id);return g}function Gt(g){if(M!=="idle"||Pe)return;let w=vs(),_=null;for(let[A,S]of Object.entries(g.data??{}))f[A]===void 0&&w.has(A)&&(_=_??{...f},_[A]=S);let x=typeof g.page=="number"&&Number.isFinite(g.page)?Math.max(0,Math.min(Math.floor(g.page),o.pages.length-1)):0,$=x>0&&v===0;!_&&!$||(_&&(f=nt(o,_)),$&&(v=x),Ee=!0,T())}function qt(){if(re||M!=="idle"||!l?.id&&c)return;if(!Ht()){Xr();return}let g=s,w=a,_=U,x=ke,$=W(g),A=l?.id,S=O??yt(g);if(S&&!$n){$n=!0,A&&!S.respondentId&&(ft(g,S,A),$=W(g)),O=S,x.refs.set(_,S),w.getDraft(S.id,S.token).then(z=>{he(_,g,w)&&W(g)===$&&Gt(z)}).catch(z=>{!he(_,g,w)||W(g)!==$||rr(z)&&(nr(g),O=null,l?.hash&&qt())});return}!S&&!Vt&&l?.hash&&(Vt=!0,w.createDraft(g,{data:{},page:0,respondent:l}).then(z=>{if(x.refs.set(_,z),!Hr(_,g,w,$,A,z.id)||O){Sn(g,w,_,$,A,z);return}if(O={id:z.id,token:z.token},ft(g,O,A),z.existing){let H=W(g);return w.getDraft(z.id,z.token).then(D=>{he(_,g,w)&&W(g)===H&&Gt(D)})}Xr()}).catch(z=>{he(_,g,w)&&(be(z)&&z.status!==void 0&&z.status>=400&&z.status<500||(Vt=!1))}))}function Xr(){if(ye||o.settings.responseLimit?.onRepeat!=="update"||!a||!s||!l?.hash||M!=="idle")return;ye=!0;let g=a,w=s,_=U,x=yo(o.settings,f)??void 0;g.fetchOwnResponse(w,l,x).then($=>{!he(_,w,g)||!$||M!=="idle"||Pe||Ee||(Gt({data:$.data,page:0}),Ee&&(Ee=!1,Z=!0,T()))}).catch(()=>{})}function En(g=!1){if(se&&(clearTimeout(se),se=null),!Ht()||M!=="idle"||!Ue)return;let w=s,_=a,x=U,$=ke;Ue=!1;let A=l,S=l?.id??c,z={data:f,page:Math.max(0,Math.min(v,o.pages.length-1))},H=O??yt(w),D=W(w),X=()=>ie.has(x)||un(w,S,H?.id)>D;jt=jt.then(async()=>{if(X())return;let B=he(x,w,_),G=B?W(w):D,Q=B?l:A,Be=B?l?.id??c:S,je=B?{data:f,page:Math.max(0,Math.min(v,o.pages.length-1))}:z,me=$.refs.get(x),lt=Ke(w,Be),ze=B?O??yt(w):H??(me?.id===lt?.id&&me?.token===lt?.token?lt:null);!B&&ze&&ze!==H&&(G=W(w));try{if(ze)try{await _.saveDraft(ze.id,ze.token,je,g?{keepalive:!0}:void 0),he(x,w,_)&&W(w)===G&&(O=ze);return}catch(wt){if(X()||W(w)!==G)return;if(!rr(wt))throw wt;nr(w),G=W(w),he(x,w,_)&&(O=null)}let de=await _.createDraft(w,Q?.hash?{...je,respondent:Q}:je);if($.refs.set(x,de),!Hr(x,w,_,G,Be,de.id)){Sn(w,_,x,G,Be,de);return}O={id:de.id,token:de.token},ft(w,O,Be),de.existing&&(Ue=!0)}catch(de){if(!he(x,w,_))return;be(de)&&de.status!==void 0&&de.status>=400&&de.status<500&&de.status!==429?kn=!0:Ue=!0}})}function ys(){!Ht()||M!=="idle"||(Ue=!0,se&&clearTimeout(se),se=setTimeout(()=>{se=null,En()},ll))}function Yr(){!Ht()||!Pe&&!O||(Ue=!0,En())}function Qr(g=s,w=U,_=!0,x=ke.ownerId){if(ie.add(w),g&&_&&nr(g,!0,x),!(w!==U||g!==s)){for(let $=ke.first;$<=ke.last;$++)ie.add($);Qe=!0,u+=1,U+=1,ke={ownerId:l?.id??c,first:U,last:U,refs:new Map},jt=Promise.resolve(),se&&(clearTimeout(se),se=null),Ue=!1,O=null}}function ws(g,w){if(!Pe&&a&&s){Pe=!0;let _=a,x=s,$=De;_.startSession(x,o.pages.length).then(A=>{!re&&$===De&&a===_&&s===x&&(J=A)})}f=nt(o,{...f,[g]:w}),t?.(f),oe=void 0,Kr(g),T(),ys()}function _s(g,w){w?(Ze.add(g),g in h&&(h=Object.fromEntries(Object.entries(h).filter(([_])=>_!==g)))):Ze.delete(g),T()}function ei(g){if(g.length===0)return-1;let w=o.pages.length,_=Math.min(v,Math.max(w-1,0)),x=o.pages[_]?.id,$=x===void 0?-1:g.indexOf(x);if($>=0)return $;let A=0;for(let S=0;S<g.length;S++){let z=o.pages.findIndex(H=>H.id===g[S]);z>=0&&z<=_&&(A=S)}return A}function xs(){let g=o.pages.length,w=Math.min(v,Math.max(g-1,0));if(!e.skipValidation||e.previewNavigation===!0){let z=Wr(w);if(h=z,p={},Fn(z),Object.keys(z).length>0){T();return}}let _=o.pages[w],x=ee(),$=ei(x);if((I()&&y!==void 0?x.at(-1)===_?.id:_?ur(o,_.id,f):!0)||$<0||$+1>=x.length){ti();return}let S=o.pages.findIndex(z=>z.id===x[$+1]);xe(),v=S>=0?S:Math.min(w+1,g-1),J&&a&&a.reportProgress(J,{furthestPage:v}),T(),Yr()}function ks(){h={};let g=I()?F.pop():void 0;if(g){v=Math.min(g.pageIndex,o.pages.length-1),y=g.startPageId,oe=void 0,T();return}let w=ht(o,f),_=ei(w);if(_>0){let x=o.pages.findIndex($=>$.id===w[_-1]);v=x>=0?x:Math.max(Math.min(v,o.pages.length-1)-1,0)}else if(w.length>0){let x=o.pages.findIndex($=>$.id===w[0]);v=x>=0?x:0}T(),Yr()}function $s(){!I()||M==="submitting"||M==="submitted"||v>=o.pages.length-1||(xe(),v+=1,y=o.pages[v]?.id,h={},oe=void 0,T())}async function ti(){if(re||M==="submitting"||M==="submitted")return;if(I()&&(h=Wr(v),p={},Fn(h),Object.keys(h).length>0)){T();return}let g=Eo(o,f);if(!g.ok){let B=e.skipValidation&&!(a&&s),G=B?Object.fromEntries(Object.entries(g.errors).filter(([Be])=>o.pages.every(je=>je.blocks.every(me=>!(ce(me)&&me.id===Be&&me.kind==="file_upload"))))):g.errors;if(B&&Object.keys(G).length===0){h={},M="submitted",T(),An(void 0,f);return}h=G,p={},Fn(G);let Q=Jr(G);Q>=0&&(v=Q,y=void 0,F.length=0),T();return}let w=a,_=U,x=u,$=ke,A=o,S=l,z=J,H=Y,D=s,X=()=>!re&&x===u&&a===w;if(w&&e.resolveFormId){M="submitting",oe=void 0,T();try{if(D=await e.resolveFormId(),!X())return;s=D}catch(B){throw X()&&(M="idle",oe=cl(B,e.verboseResolutionErrors===!0,r),T()),B}}if(w&&D){let B=A.settings.responseLimit?.by==="browser"?sl(br(A,D,g.data)):void 0,G=B??H,Q=A.settings.saveProgress?O??yt(D):null,Be=W(D),je=e.challengeRequired?e.getChallengeToken?.():void 0;if(e.challengeRequired&&!je){M="idle",oe=r.challengeIncomplete,T();return}M="submitting",oe=void 0,T();let me;try{me=await w.submit(D,g.data,{hp:e.getHoneypot?.()??"",elapsedMs:Date.now()-Fe,surface:e.surface??"headless",attribution:nl(),submissionKey:G,draft:Q?{id:Q.id,token:Q.token}:void 0,respondent:S,challengeToken:je})}catch(V){if(!X())throw V;if(M="idle",be(V)&&V.code==="challenge_failed"){oe=r.challengeRetry,e.onChallengeFailed?.(),T();return}throw oe=Bo(V,r),T(),V}if(!me.ok){if(!X())return;h=me.errors??{},p={...h};let V=Jr(h);V>=0?v=V:oe=r.reviewAnswers,M="idle",T();return}let lt=X()?J:z;lt&&w.reportProgress(lt,{completed:!0}),B&&al(br(A,D,g.data),me.responseId);let ze=X(),de=[...$.refs.values()];ze&&O&&de.push(O);let wt=[...new Map(de.map(V=>[JSON.stringify([V.id,V.token]),V])).values()];for(let V of wt)(V.id!==Q?.id||V.token!==Q?.token)&&w.deleteDraft(V.id,V.token).catch(()=>{});let Wt=Ke(D),Ss=!Wt&&W(D)===Be||!!(Wt&&[...wt,Q].some(V=>V?.id===Wt.id&&V.token===Wt.token));for(let V=$.first;V<=$.last;V++)ie.add(V);if(Qr(D,ze?U:_,Ss,$.ownerId),!ze)return;ue=me.duplicate?"duplicate":me.updated?"updated":"created",M="submitted",T(),An(me.responseId,g.data);return}if(e.skipValidation){M="submitted",T(),An(void 0,g.data);return}a&&!s?il():ol(),M="error",T()}return{getState:()=>qr,subscribe(g){return E.add(g),()=>{E.delete(g)}},setValue:ws,setUploading:_s,next:xs,skipPreviewPage:$s,back:ks,submit:ti,setContext(g){let w="formId"in g&&g.formId!==s||"client"in g&&g.client!==a,_="respondent"in g&&!!(l?.id&&!g.respondent?.id||g.respondent?.id&&c&&c!==g.respondent.id);if((w||"respondent"in g&&(g.respondent?.id!==l?.id||g.respondent?.hash!==l?.hash))&&(U+=1,jt=Promise.resolve(),w||_?(u+=1,ke={ownerId:"respondent"in g?g.respondent?.id??c:l?.id??c,first:U,last:U,refs:new Map},_?jr():(M==="submitting"&&(M="idle"),Br())):(ke.last=U,ke.ownerId=g.respondent?.id??c),_&&(m={},Ee=!1,Z=!1,h={},b.clear(),v=0),(w||_)&&(se&&clearTimeout(se),se=null,Ue=!1),O=null,$n=!1,Vt=!1,ye=!1,kn=!1),"formId"in g&&(s=g.formId),"client"in g&&(a=g.client),"respondent"in g&&(l=g.respondent,l?.id&&(c=l.id)),g.respondentErrorStrings&&(r={...qi,...g.respondentErrorStrings}),g.form&&g.form!==o){let $=Ye(g.form);if(!$.ok)throw new Error(`Invalid form schema: ${$.error}`);o=$.schema,f=nt(o,f),Kr("")}_&&(f=Vr()),M==="idle"&&tr(o,s,f)&&(M="submitted",ne=!0),qt(),T()},flushDraft(){En(!0)},resetDraft(){if(M==="submitting")return;let g=O??(s?yt(s):null),w=s?Ke(s):null,_=!w||!!(g&&g.id===w.id&&g.token===w.token);Qr(s,U,_),jr(),g&&a&&a.deleteDraft(g.id,g.token).catch(()=>{}),f=Vr(),h={},b.clear(),v=0,y=void 0,F.length=0,oe=void 0,Ee=!1,Z=!1,tr(o,s,f)&&(M="submitted",ne=!0),T()},destroy(){re=!0,u+=1,U+=1,se&&(clearTimeout(se),se=null),E.clear()}}}function ul(e){return ce(e)&&(e.kind==="select"||e.kind==="dropdown"||e.kind==="checkbox"||e.kind==="rating"||e.kind==="linear_scale")}function Vo(e){let t=e.filter(n=>ce(n)&&n.kind!=="hidden"&&n.kind!=="calculated");return t.length!==1?!0:!ul(t[0])}function Ho(e,t,n){if(n.form.settings.submitMode!=="auto"||n.status!=="idle"||n.uploading||!(()=>{switch(e.kind){case"select":case"dropdown":return typeof t=="string"&&e.options.some(a=>a.id===t);case"checkbox":return t===!0;case"rating":case"linear_scale":return typeof t=="number";default:return!1}})()||t===n.data[e.id])return!1;let i={...n.data,[e.id]:t},o=n.form.pages.find(a=>a.blocks.some(l=>l.id===e.id));if(!o||!ur(n.form,o.id,i))return!1;let s=xo(n.form,i).filter(a=>a.kind!=="hidden"&&a.kind!=="calculated");return s.length!==1||s[0]?.id!==e.id?!1:Eo(n.form,i).ok}function Go(e,t,n,r){if(n<=0)return null;let i=r?.rtl??!1;if(e==="Home")return 0;if(e==="End")return n-1;let o;switch(e){case"ArrowRight":o=i?-1:1;break;case"ArrowLeft":o=i?1:-1;break;case"ArrowDown":o=1;break;case"ArrowUp":o=-1;break;default:return null}let s=t+o;return Math.min(n-1,Math.max(0,s))}var dl=Math.sqrt(1.05*.05)-.05,fl=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i,pl=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i;function ir(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function vr(e){let t=e.trim(),n=null,r=fl.exec(t);if(r)n=`${r[1]}${r[2]}${r[3]}`;else{let a=pl.exec(t);a&&(n=`${a[1]}${a[1]}${a[2]}${a[2]}${a[3]}${a[3]}`)}if(!n)return null;let i=parseInt(n.slice(0,2),16),o=parseInt(n.slice(2,4),16),s=parseInt(n.slice(4,6),16);return .2126*ir(i)+.7152*ir(o)+.0722*ir(s)}function hl(e){if(!e||e.colorScheme==="light"||e.colorScheme==="dark"||!e.background||qo(e))return e;let t=vr(e.background);return t==null?e:{...e,colorScheme:t>dl?"light":"dark"}}function qo(e){if(!e||e.colorScheme==="light"||e.colorScheme==="dark")return!1;let t=e.dark;return!!(t&&(t.primary||t.background||t.text))}var ml="#18181b";function or(e){let t=vr(e);if(t==null)return null;let n=1.05/(t+.05),r=(t+.05)/((vr(ml)??0)+.05);return n>=r?"light":"dark"}var gl=[["primary","--fillo-primary"],["background","--fillo-bg"],["text","--fillo-text"]],dn={light:{primary:"#18181b",background:"transparent",text:"#18181b"},dark:{primary:"#fafafa",background:"transparent",text:"#f4f4f5"}};function Wo(e){let t=hl(Mo(e));if(!t)return null;let n={},r={};t.colorScheme&&(r["data-fillo-color-scheme"]=t.colorScheme);let i=qo(t)?t.dark:void 0;for(let[o,s]of gl){let a=t[o];if(!i){a&&(n[s]=a);continue}let l=i[o];!a&&!l||(n[s]=`light-dark(${a??dn.light[o]}, ${l??dn.dark[o]})`)}if(t.radius&&(n["--fillo-radius"]=t.radius),t.fontFamily&&(n["--fillo-font"]=t.fontFamily),i){let o=or(t.primary??dn.light.primary),s=or(i.primary??dn.dark.primary);o&&s&&(r["data-fillo-on-primary"]=o,r["data-fillo-on-primary-dark"]=s)}else if(t.primary){let o=or(t.primary);o&&(r["data-fillo-on-primary"]=o)}return(t.primary||t.background||t.text||i)&&(r["data-fillo-has-color-theme"]=""),{vars:n,attrs:r}}function Mr(e){return{id:e.id,theme:e.theme,schema:{version:1,title:e.title??"",description:e.description,pages:e.pages,settings:e.settings??{}},__filloCodeForm:!0}}function Nr(e){return typeof e=="object"&&e!==null&&"__filloCodeForm"in e}var We=new Map,bl=e=>new Promise(t=>setTimeout(t,e));function vl(e){if(!be(e))return!0;let t=e.status??0;return t===0||t===408||t===429||t>=500}async function yl(e,t){let n=800;for(let r=0;;r++)try{return await e.syncForm(t.id,t.schema,t.theme??null)}catch(i){if(!vl(i)||r>=2)throw i;let o=be(i)?i.retryAfterSec:void 0;await bl(Math.min(o?o*1e3:n*(1+Math.random()*.5),15e3)),n*=2}}function Ko(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function Jo(e,t){let n=r=>{if(Array.isArray(r))return r.map(n);if(r&&typeof r=="object"){let i=r;return Object.fromEntries(Object.keys(i).sort().map(o=>[o,n(i[o])]))}return r};return JSON.stringify(n(e))===JSON.stringify(n(t))}var yr=e=>e==="published"?36e5:6e4,wl=e=>!!(e.staged||e.resolvedSchema||e.syncError||e.accepting===!1||e.uploadsAvailable===!1);function Xo(e,t){return`fillo:sync:v5:${e.baseUrl}|${e.key}|${t}`}function _l(e,t,n){try{let r=globalThis.localStorage?.getItem(Xo(e,t));if(!r)return null;let i=JSON.parse(r);if(typeof i.formId!="string"||typeof i.slug!="string"||i.hash!==n||typeof i.ts!="number"||i.uploadFileSizeLimitMb!==void 0&&(typeof i.uploadFileSizeLimitMb!="number"||!Number.isFinite(i.uploadFileSizeLimitMb)||i.uploadFileSizeLimitMb<=0)||i.manageUrl!==void 0&&typeof i.manageUrl!="string"||i.status!==void 0&&i.status!=="draft"&&i.status!=="published")return null;let o=yr(i.status);return Date.now()-i.ts>o?null:i}catch{return null}}function xl(e,t,n,r){if(!(r.staged||r.resolvedSchema||r.syncError||r.accepting===!1)&&!r.challenge)try{globalThis.localStorage?.setItem(Xo(e,t),JSON.stringify({formId:r.formId,slug:r.slug,manageUrl:r.manageUrl,status:r.status,uploadFileSizeLimitMb:r.uploadFileSizeLimitMb,hash:n,ts:Date.now()}))}catch{}}function Lr(e,t,n){let r=JSON.stringify(t.schema)+JSON.stringify(t.theme??null),i=Ko(r),o=`${e.baseUrl}:${e.key}:${t.id}:${i}`,s=Le(t.schema).some(u=>u.kind==="file_upload"),a=We.get(o);if(a&&!n?.bypassCache){if(a.expiresAt===null||!s&&a.expiresAt>Date.now())return a.promise;We.delete(o)}if(!n?.bypassCache&&!s){let u=_l(e,t.id,i);if(u){let m=Promise.resolve({formId:u.formId,slug:u.slug,manageUrl:u.manageUrl,status:u.status,uploadFileSizeLimitMb:u.uploadFileSizeLimitMb});return We.set(o,{promise:m,expiresAt:u.ts+yr(u.status)}),m}}let l=yl(e,t),c={promise:l,expiresAt:null};return We.set(o,c),l.then(u=>{if(We.get(o)===c){if(s||wl(u)){We.delete(o);return}c.expiresAt=Date.now()+yr(u.status),xl(e,t.id,i,u)}},()=>{We.get(o)===c&&We.delete(o)}),l}var kl=class extends Error{constructor(e,t){super(`[fillo] ${t} \u2014 https://fillo.so/docs/troubleshooting#jsx-${e.toLowerCase()}`),this.code=e,this.name="FilloJsxError"}code},$l=Symbol.for("fillo.block");var Sl=["label","description","required","placeholder"],q=(e,t,n,r={})=>({name:e,kind:t,props:[...Sl,...n],...r}),lo=(e,t,n)=>({name:e,kind:t,props:n?["text"]:[],textChildren:n,content:!0}),sr=["options","allowOther","shuffleOptions"],Al=[q("Text","short_text",["maxLength"]),q("LongText","long_text",["maxLength"]),q("Email","email",["maxLength"]),q("Url","url",["maxLength"]),q("Phone","phone",["defaultCountry"]),q("Number","number",["min","max","decimals","prefix","suffix","notation"]),q("Select","select",sr,{optionChildren:!0}),q("MultiSelect","multi_select",sr,{optionChildren:!0}),q("Dropdown","dropdown",sr,{optionChildren:!0}),q("Checkbox","checkbox",["appearance"]),q("Rating","rating",["max","insightsMetric"]),q("Scale","linear_scale",["min","max","minLabel","maxLabel","insightsMetric"]),q("Ranking","ranking",["options"],{optionChildren:!0}),q("Matrix","matrix",["rows","columns"]),q("Signature","signature",[]),q("Date","date",["defaultToday"]),q("FileUpload","file_upload",["maxFiles","maxFileSizeMb","accept"]),q("Hidden","hidden",["paramName","defaultValue"]),q("Calculated","calculated",["calc","decimals","prefix","suffix"]),q("RepeatingGroup","repeating_group",["minInstances","maxInstances","addLabel","itemLabel"],{blockChildren:!0}),q("Custom","custom",["component","config"]),lo("Heading","heading",!0),lo("Paragraph","paragraph",!0),{name:"Divider",kind:"divider",props:[],content:!0}],Fl={name:"Page",kind:"__page",props:["title"]},El={name:"Option",kind:"__option",props:["label","icon"]};function ar(e){let t=()=>{throw new kl("RENDERED_INERT",`<Fillo.${e.name}> was rendered by React. Fillo fields are schema declarations, valid only inside <Fillo.Form> or Fillo.defineForm(). If this form lives in a server component, move it to a client module ("use client")`)};return t[$l]=e,t}var up=Object.fromEntries([...Al.map(e=>[e.name,ar(e)]),["Page",ar(Fl)],["Option",ar(El)]]);var zl=1440*6e4,co=new Map,uo=new Set;function Cl(e){try{return Ko(JSON.stringify(e)??"")}catch{return"unserializable"}}function Il(e){let t=`fillo:definition-report:v1:${e}`;try{let n=Number(globalThis.localStorage?.getItem(t));if(Number.isFinite(n)&&Date.now()-n<zl)return!1;globalThis.localStorage?.setItem(t,String(Date.now()))}catch{}return!0}function fo(e,t,n){return typeof e.reportInvalidDefinition=="function"?e.reportInvalidDefinition(t,n):Promise.resolve(null)}function Yo(e,t){let n=t.formId??(t.handle?`handle:${t.handle}`:""),r=`${e?.baseUrl??""}|${e?.key??""}|${n}|${Cl(t.definition)}`,i=co.get(r);if(i)return i;let o;return t.formId?(e&&Il(r)&&fo(e,{formId:t.formId},t.definition),o=Promise.resolve(t.formId)):t.handle&&e?.key?o=fo(e,{handle:t.handle},t.definition):o=Promise.resolve(null),o=o.then(s=>{if(!uo.has(r)){uo.add(r);let a=s?t.formId?"Showing the version published on Fillo instead, or hiding the form if nothing is published":"Showing the version published on Fillo instead":"Nothing is published to show instead, so the form is hidden";console.error(`[fillo] This form's definition is invalid: ${t.reason}. ${a}. Fix the definition in your code.`)}return s}),co.set(r,o),o}function Ml(e){let t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)||t==="::1"||t==="[::1]"||t==="0.0.0.0"}function Tr(){return typeof process<"u"&&process.env?.NODE_ENV!=="production"}function Qo(){if(Tr())return!0;if(typeof window>"u")return!1;let e=window.location?.hostname;return typeof e=="string"&&Ml(e)}var Nl=/\{\{\s*([\w-]+)\s*\}\}/g;function lr(e,t,n){if(!e.includes("{{"))return e;let r=Le(n);return e.replace(Nl,(i,o)=>{let s=r.find(c=>c.id===o),a=t[o];if(a==null||a==="")return"";let l=c=>s&&"options"in s?s.options.find(u=>u.id===c)?.label??c:c;return Array.isArray(a)?a.map(c=>l(String(c))).join(", "):typeof a=="string"?l(a):String(a)})}function es(e,t,n){let r=i=>i===void 0?i:lr(i,t,n);switch(e.kind){case"heading":case"paragraph":return{...e,text:lr(e.text,t,n)};case"divider":return e;default:return{...e,label:lr(e.label,t,n),description:r(e.description)}}}var Ll="fillo-",Tl=0,Ut='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Pl(e){return e.matches(Ut)?e:e.querySelector(Ut)}function Rl(e){return Array.from(e.querySelectorAll(Ut)).find(n=>!n.closest(".fillo-group-instance-header"))??null}function fs(e,t){let n=`${Ll}${e}-${t}`;return{inputId:n,labelId:`${n}-label`,descriptionId:`${n}-desc`,errorId:`${n}-error`,name:n}}function d(e,t={}){let n=document.createElement(e);t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text);for(let[r,i]of Object.entries(t.attrs??{}))n.setAttribute(r,i);return n}function bt(e,t){let n=Wo(t);if(n){for(let[r,i]of Object.entries(n.attrs))e.setAttribute(r,i);for(let[r,i]of Object.entries(n.vars))e.style.setProperty(r,i)}}function at(e){try{if(!e)return null;let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function Ol(e){let t=new URL(at(e)??"https://fillo.so");return t.searchParams.set("utm_source","form_badge"),t.toString()}function wn(e){return typeof e=="string"||typeof e=="number"?String(e):""}function ts(e,t,n){let r=wn(e);if(r==="")return r;let i=Number(r);return Number.isFinite(i)?Lo(i,{locale:n,decimals:t}):r}function L(e,t){for(let n of t)n&&e.appendChild(n);return e}var _n="http://www.w3.org/2000/svg",Zl={thumbs_up:"M7 10v10M7 10l4.8-6.1a2 2 0 0 1 3.5 1.7L14.6 10h4.8a2.1 2.1 0 0 1 2 2.5l-1.1 5.4A3 3 0 0 1 17.4 20H7M3 10h4v10H3z",thumbs_down:"M7 14V4M7 14l4.8 6.1a2 2 0 0 0 3.5-1.7L14.6 14h4.8a2.1 2.1 0 0 0 2-2.5l-1.1-5.4A3 3 0 0 0 17.4 4H7M3 4h4v10H3z"};function ps(e){if(!e)return null;let t=document.createElementNS(_n,"svg");t.setAttribute("class","fillo-option-icon"),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(_n,"path");return n.setAttribute("d",Zl[e]),t.appendChild(n),t}function hs(){let e=document.createElementNS(_n,"svg");e.setAttribute("class","fillo-option-check"),e.setAttribute("width","1em"),e.setAttribute("height","1em"),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2"),e.setAttribute("stroke-linecap","square"),e.setAttribute("stroke-linejoin","miter"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let t=document.createElementNS(_n,"path");return t.setAttribute("d","M4 12l5 5L20 6"),e.appendChild(t),e}function pe(e,t,n,r,i={}){n&&e.setAttribute("aria-invalid","true"),(i.requiredSupported??!0)&&t.required&&e.setAttribute("aria-required","true");let o=[t.description?r.descriptionId:null,n?r.errorId:null].filter(Boolean).join(" ");o&&e.setAttribute("aria-describedby",o)}function ms(e,t,n,r){e.addEventListener("keydown",i=>{let o=getComputedStyle(e).direction==="rtl",s=n===null?-1:t.indexOf(n),a=Go(i.key,s,t.length,{rtl:o});if(a===null)return;i.preventDefault();let l=t[a];l!==void 0&&(r(l),e.querySelectorAll('[role="radio"]')[a]?.focus())})}function ve(e,t,n,r){let i=d("div",{className:`fillo-field fillo-field--${e.kind}${t?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.id,"data-kind":e.kind}});i.toggleAttribute("data-invalid",!!t),i.toggleAttribute("data-required",!!e.required);let o=d("label",{className:"fillo-label",text:gt(e),attrs:{id:r.labelId,for:r.inputId,"data-fillo":"label"}});return!e.required&&!(e.kind==="repeating_group"&&(e.minInstances??1)>0)&&o.appendChild(d("span",{className:"fillo-optional",text:" (optional)"})),i.appendChild(o),e.description&&i.appendChild(d("p",{className:"fillo-description",text:e.description,attrs:{id:r.descriptionId,"data-fillo":"fieldDescription"}})),i.appendChild(n),t&&i.appendChild(d("p",{className:"fillo-error",text:t,attrs:{id:r.errorId,"data-fillo":"error"}})),i}function Tt(e,t){let n=t.field,r=n.kind==="number"?n:void 0,i=r?.notation!==void 0,o=No(r?.notation),s=i||!!r?.prefix||!!r?.suffix,a=d("input",{className:"fillo-input",attrs:{id:t.ids.inputId,type:s?"text":e,"data-fillo":"control"}});if(s&&a.setAttribute("inputmode","decimal"),e==="email"?a.setAttribute("autocomplete","email"):e==="url"&&a.setAttribute("autocomplete","url"),a.value=i?ts(t.value,r?.decimals,o):wn(t.value),n.placeholder&&(a.placeholder=n.placeholder),"maxLength"in n&&n.maxLength!==void 0&&(a.maxLength=n.maxLength),r&&!s&&(r.min!==void 0&&(a.min=String(r.min)),r.max!==void 0&&(a.max=String(r.max))),s){let c=a.value,u=a.value.length,m=()=>{a.value=c,a.setSelectionRange(u,u)};i?(a.addEventListener("input",()=>{if(!Lt(a.value,o))return m();c=a.value,u=a.selectionStart??a.value.length,t.setValue(Sr(a.value,o),{render:!1})}),a.addEventListener("change",()=>{if(!Lt(a.value,o))return m();c=a.value,t.setValue(Sr(a.value,o))}),a.addEventListener("blur",()=>{let f=t.getValue?.()??t.value;a.value=ts(f,r?.decimals,o),c=a.value,u=a.value.length})):(a.addEventListener("input",()=>{if(!Lt(a.value,o))return m();c=a.value,u=a.selectionStart??a.value.length,t.setValue(a.value,{render:!1})}),a.addEventListener("change",()=>{if(!Lt(a.value,o))return m();c=a.value,t.setValue(a.value)}))}else a.addEventListener("input",()=>t.setValue(a.value,{render:!1})),a.addEventListener("change",()=>t.setValue(a.value));pe(a,n,t.error,t.ids);let l=a;return r&&(r.prefix||r.suffix)&&(l=L(d("div",{className:"fillo-number"}),[r.prefix?d("span",{className:"fillo-number-prefix",text:r.prefix}):null,a,r.suffix?d("span",{className:"fillo-number-suffix",text:r.suffix}):null])),ve(n,t.error,l,t.ids)}function Dl(){if(typeof navigator>"u")return;let t=(navigator.languages?.[0]||navigator.language||"").split("-")[1];return t&&/^[A-Za-z]{2}$/.test(t)?t.toUpperCase():void 0}function Ul(){if(!(typeof Intl>"u"))try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof e=="string"&&e?e:void 0}catch{return}}function Bl(e,t){if(t<=0)return e.setSelectionRange(0,0);let n=e.value,r=0,i=n.length;for(let o=0;o<n.length;o++)if(/\d/.test(n[o])&&++r===t){i=o+1;break}e.setSelectionRange(i,i)}function jl(e){let t=e.field,n=Mt(wn(e.value)).country??bn(t.defaultCountry)??$o(Ul())??bn(Dl())??Ct[0],r=d("div",{className:"fillo-phone"}),i=d("div",{className:"fillo-phone-country"}),o=d("button",{className:"fillo-phone-flag",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false"}}),s=d("span",{className:"fillo-phone-flag-emoji",attrs:{"aria-hidden":"true"}}),a=d("span",{className:"fillo-phone-dial"});L(o,[s,a,d("span",{className:"fillo-phone-caret",text:"\u25BE",attrs:{"aria-hidden":"true"}})]),L(i,[o]);let l=d("input",{className:"fillo-input fillo-phone-input",attrs:{id:e.ids.inputId,type:"tel",inputmode:"tel",autocomplete:"tel-national","data-fillo":"control"}});pe(l,e.field,e.error,e.ids);let c=()=>e.getValue?.()??e.value,u=()=>{let E=Ne(wn(c()));return E.startsWith(n.dialCode)?E.slice(n.dialCode.length):E},m=()=>{s.textContent=_r(n.iso2),a.textContent=`+${n.dialCode}`,o.setAttribute("aria-label",`Country: ${n.name} (+${n.dialCode})`)},f=()=>{l.value=It(n,u()),l.placeholder=It(n,n.example)},h=E=>e.setValue(E?So(n,E):"",{render:!1}),p=E=>e.setValue(E,{render:!1});m(),f(),l.addEventListener("input",()=>{let E=l.value,Fe=l.selectionStart??E.length,Y=Ne(E.slice(0,Fe)).length;if(E.trimStart().startsWith("+")){let J=Mt(E,n,{previousDigits:u()});if(J.pending){p(J.raw??E);return}J.country&&(n=J.country,m()),h(J.country?J.national:Ne(E))}else h(Ne(E));l.value=It(n,u()),Bl(l,Y)});let b=e.registerOverlay,v=e.announce,y=null,F=0,I=mt,ee=null,xe=null,M,ne=`${e.ids.inputId}-countries`,re=()=>{if(!y)return;let E=Ao(i,y);y.classList.toggle("fillo-phone-popover--above",E==="above"),y.classList.toggle("fillo-phone-popover--below",E==="below")},Qe=()=>{ee?.();let E=()=>re();re(),window.addEventListener("resize",E),window.addEventListener("scroll",E,!0),ee=()=>{window.removeEventListener("resize",E),window.removeEventListener("scroll",E,!0)}},U=E=>{let Fe=E.relatedTarget;if(Fe){i.contains(Fe)||ie();return}queueMicrotask(()=>{y&&!i.contains(document.activeElement)&&ie()})},ie=()=>{clearTimeout(M),ee?.(),ee=null,y?.remove(),y=null,o.setAttribute("aria-expanded","false"),o.removeAttribute("aria-controls"),document.removeEventListener("mousedown",Ae),i.removeEventListener("focusout",U),xe?.(),xe=null},Ae=E=>{i.contains(E.target)||ie()},oe=E=>{E&&(n=E,m(),h(u()),f(),ie(),v?.(R.phoneCountrySelected(E.name)),l.focus())},Ze=E=>{let Fe=d("div",{className:"fillo-phone-popover fillo-phone-popover--below"}),Y=d("input",{className:"fillo-phone-search",attrs:{type:"text",role:"combobox","aria-expanded":"true","aria-controls":ne,"aria-autocomplete":"list","aria-label":"Search country or code",placeholder:"Search country or code"}});E&&(Y.value=E);let J=d("ul",{className:"fillo-phone-list",attrs:{role:"listbox",id:ne,"aria-label":"Country"}}),Pe=()=>{if(J.replaceChildren(),I.length===0){J.appendChild(d("li",{className:"fillo-phone-empty",text:"No matches",attrs:{role:"option","aria-disabled":"true"}})),Y.removeAttribute("aria-activedescendant"),re();return}I.forEach((Z,ue)=>{let ye=d("li",{className:`fillo-phone-option${ue===F?" fillo-phone-option--active":""}`,attrs:{id:`${ne}-opt-${ue}`,role:"option","aria-selected":String(Z.iso2===n.iso2)}});L(ye,[d("span",{className:"fillo-phone-flag-emoji",text:_r(Z.iso2),attrs:{"aria-hidden":"true"}}),d("span",{className:"fillo-phone-option-name",text:Z.name}),d("span",{className:"fillo-phone-option-dial",text:`+${Z.dialCode}`})]),ye.addEventListener("mouseenter",()=>{F=ue,Y.setAttribute("aria-activedescendant",ye.id),De()}),ye.addEventListener("mousedown",O=>{O.preventDefault(),oe(Z)}),J.appendChild(ye)}),Y.setAttribute("aria-activedescendant",`${ne}-opt-${F}`),re()},De=()=>{[...J.children].forEach((Z,ue)=>Z.classList.toggle("fillo-phone-option--active",ue===F)),document.getElementById(`${ne}-opt-${F}`)?.scrollIntoView({block:"nearest"})},Ee=Z=>{let ue=Z.trim().toLowerCase(),ye=ue.replace(/[^\d]/g,"");I=ue?mt.filter(O=>O.name.toLowerCase().includes(ue)||O.iso2.toLowerCase()===ue||ye.length>0&&O.dialCode.startsWith(ye)):mt,F=0,Pe(),clearTimeout(M),M=setTimeout(()=>v?.(R.phoneResultsCount(I.length)),300)};Y.addEventListener("input",()=>Ee(Y.value)),Y.addEventListener("keydown",Z=>{if(Z.key==="ArrowDown"){if(Z.preventDefault(),I.length===0)return;F=Math.min(F+1,I.length-1),De(),Y.setAttribute("aria-activedescendant",`${ne}-opt-${F}`)}else if(Z.key==="ArrowUp"){if(Z.preventDefault(),I.length===0)return;F=Math.max(F-1,0),De(),Y.setAttribute("aria-activedescendant",`${ne}-opt-${F}`)}else Z.key==="Enter"?(Z.preventDefault(),oe(I[F])):Z.key==="Escape"&&(Z.preventDefault(),ie(),o.focus())}),L(Fe,[Y,J]),y=Fe,i.appendChild(Fe),o.setAttribute("aria-expanded","true"),o.setAttribute("aria-controls",ne),E?Ee(E):(I=mt,F=Math.max(0,mt.indexOf(n)),Pe()),Qe(),De(),document.addEventListener("mousedown",Ae),i.addEventListener("focusout",U),xe=b?.(ie)??null,requestAnimationFrame(()=>{if(Y.focus(),E){let Z=Y.value.length;Y.setSelectionRange(Z,Z)}})};return o.addEventListener("click",()=>y?ie():Ze()),o.addEventListener("keydown",E=>{if(!y){if(E.key==="ArrowDown"||E.key==="ArrowUp"){E.preventDefault(),Ze();return}E.key.length===1&&E.key!==" "&&!E.ctrlKey&&!E.metaKey&&!E.altKey&&(E.preventDefault(),Ze(E.key))}}),L(r,[i,l]),ve(e.field,e.error,r,e.ids)}function Vl(e){let t=d("textarea",{className:"fillo-input fillo-textarea",attrs:{id:e.ids.inputId,rows:"4","data-fillo":"control"}});return t.value=typeof e.value=="string"?e.value:"",e.field.placeholder&&(t.placeholder=e.field.placeholder),"maxLength"in e.field&&e.field.maxLength!==void 0&&(t.maxLength=e.field.maxLength),t.addEventListener("input",()=>e.setValue(t.value,{render:!1})),t.addEventListener("change",()=>e.setValue(t.value)),pe(t,e.field,e.error,e.ids),ve(e.field,e.error,t,e.ids)}function Hl(e){let t=e.field,n=Dr(t),r=typeof e.value=="string"?e.value:"",i=e.activeOtherFields,o=r!==""&&!t.options.some(l=>l.id===r),s=o||r===""&&i?.has(t.id)===!0,a=d("div",{className:"fillo-options",attrs:{role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"options"}});pe(a,t,e.error,e.ids);for(let l of n){let c=d("label",{className:`fillo-option${l.icon?" fillo-option--has-icon":""}${r===l.id?" fillo-option--selected":""}`,attrs:{"data-option":l.id,"data-fillo":"option"}});c.toggleAttribute("data-selected",r===l.id);let u=d("input",{className:"fillo-option-input",attrs:{type:"radio",name:e.ids.name}});u.checked=r===l.id,u.addEventListener("change",()=>{i?.delete(t.id),e.setValue(l.id)}),L(c,[u,ps(l.icon),d("span",{className:"fillo-option-label",text:l.label,attrs:{"data-fillo":"optionLabel"}}),l.icon&&r===l.id?hs():null]),a.appendChild(c)}if(t.allowOther){let l=d("label",{className:`fillo-option fillo-option--other${s?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});l.toggleAttribute("data-selected",s);let c=d("input",{className:"fillo-option-input",attrs:{type:"radio",name:e.ids.name}});if(c.checked=s,c.addEventListener("change",()=>{i?.add(t.id),e.setValue("",{render:!0})}),L(l,[L(d("span",{className:"fillo-option-main"}),[c,d("span",{className:"fillo-option-label",text:P.other,attrs:{"data-fillo":"optionLabel"}})])]),s){let u=d("input",{className:"fillo-input fillo-other-input",attrs:{type:"text","aria-label":P.otherPrompt}});u.value=o?r:"",u.placeholder=P.otherPlaceholder,u.addEventListener("input",()=>{i?.add(t.id),e.setValue(u.value,{render:!1})}),u.addEventListener("change",()=>{i?.add(t.id),e.setValue(u.value)}),l.appendChild(u),o||queueMicrotask(()=>u.focus())}a.appendChild(l)}return ve(t,e.error,a,e.ids)}function Gl(e){let t=e.field,n=Dr(t),r=Array.isArray(e.value)?e.value:[],i=new Set(t.options.map(u=>u.id)),o=r.find(u=>!i.has(u)),s=e.activeOtherFields,a=()=>{let u=e.getValue?.()??e.value;return Array.isArray(u)?u:[]},l=d("div",{className:"fillo-options",attrs:{role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"options"}});pe(l,t,e.error,e.ids,{requiredSupported:!1});let c=u=>e.setValue(u);for(let u of n){let m=d("label",{className:`fillo-option${u.icon?" fillo-option--has-icon":""}${r.includes(u.id)?" fillo-option--selected":""}`,attrs:{"data-option":u.id,"data-fillo":"option"}});m.toggleAttribute("data-selected",r.includes(u.id));let f=d("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});f.checked=r.includes(u.id),f.addEventListener("change",()=>{let h=a();c(f.checked?[...h,u.id]:h.filter(p=>p!==u.id))}),L(m,[f,ps(u.icon),d("span",{className:"fillo-option-label",text:u.label,attrs:{"data-fillo":"optionLabel"}}),u.icon&&r.includes(u.id)?hs():null]),l.appendChild(m)}if(t.allowOther){let u=o!==void 0||s?.has(t.id)===!0,m=d("label",{className:`fillo-option fillo-option--other${u?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});m.toggleAttribute("data-selected",u);let f=d("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});if(f.checked=u,f.addEventListener("change",()=>{let h=a().filter(p=>i.has(p));f.checked?(s?.add(t.id),c(h)):(s?.delete(t.id),c(h))}),L(m,[L(d("span",{className:"fillo-option-main"}),[f,d("span",{className:"fillo-option-label",text:P.other,attrs:{"data-fillo":"optionLabel"}})])]),u){let h=d("input",{className:"fillo-input fillo-other-input",attrs:{type:"text","aria-label":P.otherPrompt}});h.value=o??"",h.placeholder=P.otherPlaceholder,h.addEventListener("input",()=>{s?.add(t.id);let p=a().filter(b=>i.has(b));e.setValue(h.value?[...p,h.value]:p,{render:!1})}),h.addEventListener("change",()=>{s?.add(t.id);let p=a().filter(b=>i.has(b));e.setValue(h.value?[...p,h.value]:p)}),m.appendChild(h),o===void 0&&queueMicrotask(()=>h.focus())}l.appendChild(m)}return ve(t,e.error,l,e.ids)}function ql(e){let t="__fillo_other__",n=new Set(e.options.map(r=>r.id));for(;n.has(t);)t+="_";return t}function Wl(e){let t=e.field,n=typeof e.value=="string"?e.value:"",r=ql(t),i=e.activeOtherFields,o=n!==""&&!t.options.some(u=>u.id===n),s=o||n===""&&i?.has(t.id)===!0,a=d("div"),l=d("div",{className:"fillo-select-wrap"}),c=d("select",{className:"fillo-input fillo-select",attrs:{id:e.ids.inputId,"data-fillo":"control"}});c.appendChild(d("option",{text:t.placeholder??"Choose...",attrs:{value:""}}));for(let u of Dr(t))c.appendChild(d("option",{text:u.label,attrs:{value:u.id}}));if(t.allowOther&&c.appendChild(d("option",{text:`${P.other}\u2026`,attrs:{value:r}})),c.value=s?r:n,c.addEventListener("change",()=>{c.value===r?(i?.add(t.id),e.setValue("",{render:!0})):(i?.delete(t.id),e.setValue(c.value||null))}),pe(c,t,e.error,e.ids),L(l,[c,d("span",{className:"fillo-select-icon",attrs:{"aria-hidden":"true"}})]),a.appendChild(l),s){let u=d("input",{className:"fillo-input fillo-other-input fillo-other-input--block",attrs:{type:"text","aria-label":P.otherPrompt}});u.value=o?n:"",u.placeholder=P.otherPlaceholder,u.addEventListener("input",()=>{i?.add(t.id),e.setValue(u.value,{render:!1})}),u.addEventListener("change",()=>{i?.add(t.id),e.setValue(u.value)}),a.appendChild(u),o||queueMicrotask(()=>u.focus())}return ve(t,e.error,a,e.ids)}function Kl(e){if(e.field.kind==="checkbox"&&e.field.appearance==="toggle"){let o=d("div",{className:`fillo-field fillo-field--checkbox fillo-field--toggle${e.error?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.field.id,"data-kind":e.field.kind}});o.toggleAttribute("data-invalid",!!e.error),o.toggleAttribute("data-required",!!e.field.required);let s=d("label",{className:"fillo-toggle",attrs:{"data-fillo":"option"}});s.toggleAttribute("data-checked",e.value===!0);let a=d("span",{className:"fillo-option-label",text:gt(e.field),attrs:{"data-fillo":"optionLabel"}});e.field.required||a.appendChild(d("span",{className:"fillo-optional",text:" (optional)"}));let l=d("span",{className:"fillo-toggle-copy"});l.appendChild(a);let c=d("input",{className:"fillo-toggle-input",attrs:{id:e.ids.inputId,type:"checkbox"}});return c.checked=e.value===!0,c.addEventListener("change",()=>{e.setValue(c.checked)}),pe(c,e.field,e.error,e.ids),L(s,[l,c,L(d("span",{className:"fillo-toggle-track",attrs:{"aria-hidden":"true"}}),[d("span",{className:"fillo-toggle-thumb"})])]),o.appendChild(s),e.field.description&&o.appendChild(d("p",{className:"fillo-description",text:e.field.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}})),e.error&&o.appendChild(d("p",{className:"fillo-error",text:e.error,attrs:{id:e.ids.errorId,"data-fillo":"error"}})),o}let t=d("div",{className:`fillo-field fillo-field--checkbox${e.error?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.field.id,"data-kind":e.field.kind}});t.toggleAttribute("data-invalid",!!e.error),t.toggleAttribute("data-required",!!e.field.required);let n=d("label",{className:"fillo-option",attrs:{"data-fillo":"option"}});n.toggleAttribute("data-checked",e.value===!0);let r=d("input",{className:"fillo-option-input",attrs:{id:e.ids.inputId,type:"checkbox"}});r.checked=e.value===!0,r.addEventListener("change",()=>e.setValue(r.checked)),pe(r,e.field,e.error,e.ids);let i=d("span",{className:"fillo-option-label",text:gt(e.field),attrs:{"data-fillo":"optionLabel"}});return e.field.required||i.appendChild(d("span",{className:"fillo-optional",text:" (optional)"})),L(n,[r,i]),t.appendChild(n),e.field.description&&t.appendChild(d("p",{className:"fillo-description",text:e.field.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}})),e.error&&t.appendChild(d("p",{className:"fillo-error",text:e.error,attrs:{id:e.ids.errorId,"data-fillo":"error"}})),t}function Jl(e){if(e.field.kind!=="rating")return d("div");let t=typeof e.field.max=="number"?e.field.max:5,n=typeof e.value=="number"?e.value:0,r=Array.from({length:t},(a,l)=>l+1),i=n>0?n:null,o=i===null?0:Math.max(0,r.indexOf(i)),s=d("div",{className:"fillo-rating",attrs:{id:e.ids.inputId,role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});pe(s,e.field,e.error,e.ids);for(let[a,l]of r.entries()){let c=d("button",{className:`fillo-star${l<=n?" fillo-star--active":""}`,text:l<=n?"\u2605":"\u2606",attrs:{type:"button",role:"radio","aria-label":`${l} of ${t}`,"aria-checked":String(l===n),tabindex:String(a===o?0:-1),"data-fillo":"option"}});c.toggleAttribute("data-selected",l<=n),c.addEventListener("click",u=>{u.detail===0&&l===n||e.setValue(l===n?null:l)}),s.appendChild(c)}return ms(s,r,i,a=>e.setValue(a)),ve(e.field,e.error,s,e.ids)}function Xl(e){if(e.field.kind!=="linear_scale")return d("div");let t=typeof e.field.min=="number"?e.field.min:1,n=typeof e.field.max=="number"?e.field.max:10,r=typeof e.value=="number"?e.value:null,i=Array.from({length:n-t+1},(m,f)=>t+f),o=r===null?0:Math.max(0,i.indexOf(r)),s=`${e.ids.inputId}-min`,a=`${e.ids.inputId}-max`,l=d("div"),c=d("div",{className:"fillo-scale",attrs:{id:e.ids.inputId,role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});pe(c,e.field,e.error,e.ids);let u=[e.field.minLabel?s:null,e.field.maxLabel?a:null,c.getAttribute("aria-describedby")].filter(Boolean).join(" ");u&&c.setAttribute("aria-describedby",u);for(let[m,f]of i.entries()){let h=d("button",{className:`fillo-scale-step${e.value===f?" fillo-scale-step--active":""}`,text:String(f),attrs:{type:"button",role:"radio","aria-label":String(f),"aria-checked":String(e.value===f),tabindex:String(m===o?0:-1),"data-fillo":"option"}});h.toggleAttribute("data-selected",e.value===f),h.addEventListener("click",p=>{p.detail===0&&e.value===f||e.setValue(e.value===f?null:f)}),c.appendChild(h)}return ms(c,i,r,m=>e.setValue(m)),l.appendChild(c),("minLabel"in e.field||"maxLabel"in e.field)&&L(l,[L(d("div",{className:"fillo-scale-labels"}),[d("span",{text:String(e.field.minLabel??""),attrs:{id:s}}),d("span",{text:String(e.field.maxLabel??""),attrs:{id:a}})])]),ve(e.field,e.error,l,e.ids)}function Yl(e){let t=e.field;if(t.kind!=="ranking")return null;let n=e.announce,r=Array.isArray(e.value)?e.value:[],i=[...r.filter(a=>t.options.some(l=>l.id===a)),...t.options.map(a=>a.id).filter(a=>!r.includes(a))],o=d("div",{attrs:{id:e.ids.inputId,role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});pe(o,e.field,e.error,e.ids,{requiredSupported:!1});let s=d("ol",{className:"fillo-ranking"});for(let[a,l]of i.entries()){let c=t.options.find(b=>b.id===l);if(!c)continue;let u=d("li",{className:"fillo-ranking-item"}),m=d("span",{className:"fillo-ranking-controls"}),f=b=>{let v=a+b;if(v<0||v>=i.length)return;let y=[...i];[y[a],y[v]]=[y[v],y[a]],e.setValue(y),n?.(R.rankingPosition(c.label,v+1,i.length))},h=d("button",{className:"fillo-ranking-move",text:"\u2191",attrs:{type:"button","data-fillo-rank-opt":l,"data-fillo-rank-dir":"up","aria-label":`Move ${c.label} up`}});h.toggleAttribute("disabled",a===0),h.addEventListener("click",()=>f(-1));let p=d("button",{className:"fillo-ranking-move",text:"\u2193",attrs:{type:"button","data-fillo-rank-opt":l,"data-fillo-rank-dir":"down","aria-label":`Move ${c.label} down`}});p.toggleAttribute("disabled",a===i.length-1),p.addEventListener("click",()=>f(1)),L(m,[h,p]),L(u,[d("span",{className:"fillo-ranking-index",text:String(a+1)}),d("span",{className:"fillo-ranking-label",text:c.label}),m]),s.appendChild(u)}return o.appendChild(s),ve(e.field,e.error,o,e.ids)}function Ql(e){let t=e.field;if(t.kind!=="matrix")return null;let n=e.value&&typeof e.value=="object"&&!Array.isArray(e.value)?e.value:{},r=d("table",{className:"fillo-matrix"}),i=document.createElement("thead"),o=document.createElement("tr");o.appendChild(document.createElement("td"));for(let l of t.columns)o.appendChild(d("th",{text:l.label,attrs:{scope:"col"}}));i.appendChild(o),r.appendChild(i);let s=document.createElement("tbody");for(let l of t.rows){let c=`${e.ids.inputId}-${l.id}`,u=n[l.id]!==void 0,m=!!e.error&&!!t.required&&!u,f=v=>`${e.ids.inputId}-${l.id}-${v.id}`,h=document.createElement("tr"),p=d("th",{attrs:{scope:"row"}}),b=d("div",{attrs:{role:"radiogroup","aria-labelledby":`${e.ids.labelId} ${c}`,"aria-owns":t.columns.map(f).join(" ")}});b.appendChild(d("span",{text:l.label,attrs:{id:c}})),p.appendChild(b),h.appendChild(p);for(let v of t.columns){let y=d("td",{attrs:{"data-label":v.label}}),F=d("label",{className:"fillo-matrix-cell"}),I=d("input",{className:"fillo-option-input",attrs:{id:f(v),type:"radio",name:`${e.ids.name}-${l.id}`,"aria-label":`${l.label}: ${v.label}`}});t.required&&I.setAttribute("aria-required","true"),m&&I.setAttribute("aria-invalid","true"),I.checked=n[l.id]===v.id,I.addEventListener("change",()=>e.setValue({...n,[l.id]:v.id})),F.appendChild(I),y.appendChild(F),h.appendChild(y)}s.appendChild(h)}r.appendChild(s);let a=d("div",{className:"fillo-matrix-wrap",attrs:{id:e.ids.inputId,role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});return pe(a,e.field,e.error,e.ids,{requiredSupported:!1}),a.appendChild(r),ve(e.field,e.error,a,e.ids)}function ec(e){let t=d("div",{className:"fillo-signature-field"}),n=d("div",{className:"fillo-signature",attrs:{"data-fillo":"control"}}),r=d("canvas",{className:"fillo-signature-canvas",attrs:{role:"img"}}),i=d("button",{className:"fillo-signature-clear",text:"Clear",attrs:{type:"button"}}),o=d("div",{className:"fillo-signature-hint",text:"Sign here",attrs:{"aria-hidden":"true"}});r.width=720,r.height=220;let s=r.getContext("2d"),a=!1,l=typeof e.value=="string"&&e.value.startsWith("data:image/"),c=()=>{r.setAttribute("aria-label",l?R.signatureSigned:R.signatureEmpty)};if(c(),l&&s){let v=new Image;v.onload=()=>s.drawImage(v,0,0,r.width,r.height),v.src=String(e.value),o.style.display="none"}let u=d("input",{className:"fillo-input fillo-signature-type-input",attrs:{id:e.ids.inputId,type:"text",autocomplete:"name"}});pe(u,e.field,e.error,e.ids);let m=v=>{s&&(s.clearRect(0,0,r.width,r.height),v.trim()?(s.fillStyle=getComputedStyle(r).color||"#18181b",s.font=`italic ${Math.min(96,r.height*.45)}px "Segoe Script", "Brush Script MT", cursive`,s.textBaseline="middle",s.fillText(v,24,r.height/2),l=!0,o.style.display="none",e.setValue(r.toDataURL("image/png"),{render:!1})):(l=!1,o.style.display="",e.setValue(null,{render:!1})),c())};u.addEventListener("input",()=>m(u.value));let f=v=>{let y=r.getBoundingClientRect();return{x:(v.clientX-y.left)/y.width*r.width,y:(v.clientY-y.top)/y.height*r.height}};r.addEventListener("pointerdown",v=>{if(!s)return;a=!0,l=!0,o.style.display="none",c(),u.value&&(u.value=""),r.setPointerCapture(v.pointerId);let y=f(v);s.beginPath(),s.moveTo(y.x,y.y)}),r.addEventListener("pointermove",v=>{if(!a||!s)return;let y=f(v);s.lineWidth=2.4,s.lineCap="round",s.strokeStyle=getComputedStyle(r).color||"#18181b",s.lineTo(y.x,y.y),s.stroke()});let h=()=>{a&&(a=!1,l&&e.setValue(r.toDataURL("image/png"),{render:!1}))};r.addEventListener("pointerup",h),r.addEventListener("pointercancel",h),i.addEventListener("click",()=>{s?.clearRect(0,0,r.width,r.height),l=!1,o.style.display="",u.value="",c(),e.setValue(null,{render:!1})}),L(n,[r,o,i]);let p=d("div",{className:"fillo-signature-type"}),b=d("label",{className:"fillo-signature-type-label",text:"Or type your full name to sign",attrs:{for:e.ids.inputId}});return L(p,[b,u]),L(t,[n,p]),ve(e.field,e.error,t,e.ids)}function ns(e){return e<1024?`${e} B`:e<1024**2?`${(e/1024).toFixed(0)} KB`:e<1024**3?`${(e/1024**2).toFixed(1)} MB`:`${(e/1024**3).toFixed(2)} GB`}function Dt(e,t=22){let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("class","fillo-file-state-icon"),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("fill","none"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");for(let r of e){let i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d",r),n.appendChild(i)}return n}function rs(e){let t=d("span",{className:`fillo-file-state fillo-file-state--${e}`,attrs:{"aria-hidden":"true"}});return t.appendChild(Dt(e==="done"?["M3.75 12a8.25 8.25 0 1 0 16.5 0 8.25 8.25 0 1 0-16.5 0","m8.5 12 2.25 2.25 4.75-5"]:e==="failed"?["M3.75 12a8.25 8.25 0 1 0 16.5 0 8.25 8.25 0 1 0-16.5 0","M12 7.75v5.5","M12 16.5h.01"]:["M7.25 3.75h6.5l3 3v13.5h-9.5z","M13.75 3.75v3h3"])),t}function Pr(){let e=Dt(["m7 7 10 10M17 7 7 17"],16);return e.setAttribute("class","fillo-file-action-icon"),e}function is(e){let t=Dt([e],16);return t.setAttribute("class","fillo-group-icon"),t}function yn(e,t,n,r){let i=d("button",{className:e,attrs:{type:"button","aria-label":t}});return i.append(n),i.addEventListener("click",r),i}function tc(e){let t=e.field;if(t.kind!=="file_upload")return null;let n=e,r=n.uploadDisabledReason,i=r===void 0,o=t.maxFiles??1,s=t.maxFileSizeMb??500,a=Array.isArray(e.value)?e.value:[],l=n.uploadRows??[],c=o-a.length-l.filter(f=>f.error===void 0).length,u=d("div");if(c>0){let f=d("input",{className:"fillo-input",attrs:{id:e.ids.inputId,type:"file",hidden:""}});o>1&&(f.multiple=!0),t.accept?.length&&(f.accept=t.accept.join(",")),f.disabled=!i,f.addEventListener("change",()=>{if(!i)return;let p=Array.from(f.files??[]);f.value="",e.uploadFiles?.(t,p)});let h=d("div",{className:`fillo-dropzone${i?"":" fillo-dropzone--disabled"}`,attrs:{role:"button",tabindex:"0","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});if(pe(h,t,e.error,e.ids,{requiredSupported:!1}),i||h.setAttribute("aria-disabled","true"),h.addEventListener("dragover",p=>{p.preventDefault(),h.classList.add("fillo-dropzone--over"),h.setAttribute("data-drag-over","")}),h.addEventListener("dragleave",()=>{h.classList.remove("fillo-dropzone--over"),h.removeAttribute("data-drag-over")}),h.addEventListener("drop",p=>{p.preventDefault(),h.classList.remove("fillo-dropzone--over"),h.removeAttribute("data-drag-over"),i&&e.uploadFiles?.(t,Array.from(p.dataTransfer?.files??[]))}),h.addEventListener("click",()=>{i&&f.click()}),h.addEventListener("keydown",p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),i&&f.click())}),h.appendChild(f),i)L(h,[d("span",{className:"fillo-dropzone-title",text:R.dropzoneTitle(o>1)}),d("span",{className:"fillo-dropzone-hint",text:R.dropzoneHint(s)})]);else if(r==="render_only")h.appendChild(d("span",{className:"fillo-dropzone-hint",text:R.uploadsRenderOnly}));else if(n.storageFixUrl){let p=d("span",{className:"fillo-dropzone-hint",text:"Connect file storage to enable uploads"});p.append(" \u2014 "),p.appendChild(d("a",{text:n.storageFixUrl,attrs:{href:n.storageFixUrl,target:"_blank",rel:"noopener noreferrer"}})),h.appendChild(p)}else h.appendChild(d("span",{className:"fillo-dropzone-hint",text:R.uploadsUnavailable}));u.appendChild(h)}if(a.length>0||l.length>0){let f=d("ul",{className:"fillo-files"});for(let h of a){let p=d("li",{className:"fillo-file fillo-file--done"}),b=d("span",{className:"fillo-file-content"});L(b,[d("span",{className:"fillo-file-name",text:h.name}),d("span",{className:"fillo-file-meta",text:R.uploadedFile(ns(h.size))})]);let v=d("span",{className:"fillo-file-actions"});v.appendChild(yn("fillo-file-remove",`${R.uploadRemove} ${h.name}`,Pr(),()=>e.setValue(a.filter(y=>y.fileId!==h.fileId)))),L(p,[rs("done"),b,v]),f.appendChild(p)}for(let h of l){let p=h.error!==void 0,b=d("li",{className:`fillo-file${p?" fillo-file--failed":""}`});b.appendChild(rs(p?"failed":"uploading"));let v=d("span",{className:"fillo-file-content"});if(v.appendChild(d("span",{className:"fillo-file-name",text:h.name})),p){let y=d("span",{className:"fillo-file-actions"});v.appendChild(d("span",{className:"fillo-file-error",text:h.error??""})),b.appendChild(v),!h.tooLarge&&c>0&&y.appendChild(yn("fillo-file-retry",`${R.uploadRetry} ${h.name}`,R.uploadRetry,()=>n.uploadAction?.(h.key,"retry"))),y.appendChild(yn("fillo-file-remove",`${R.uploadDismiss} ${h.name}`,Pr(),()=>n.uploadAction?.(h.key,"dismiss"))),b.appendChild(y)}else{let y=d("span",{className:"fillo-progress-bar"});y.style.width=`${h.fraction*100}%`,v.appendChild(d("span",{className:"fillo-file-meta",text:R.uploadingFile(Math.round(h.fraction*100),ns(h.size))}));let F=d("span",{className:"fillo-file-actions"});F.appendChild(yn("fillo-file-remove",`${R.uploadCancel} ${h.name}`,Pr(),()=>n.uploadAction?.(h.key,"cancel"))),L(b,[v,F,L(d("span",{className:"fillo-progress",attrs:{role:"progressbar","aria-label":`Uploading ${h.name}`,"aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":String(Math.round(h.fraction*100))}}),[y])])}f.appendChild(b)}u.appendChild(f)}let m=n.uploadNotice;return m&&u.appendChild(d("p",{className:"fillo-upload-notice",text:m})),ve(t,e.error,u,e.ids)}function nc(e){let t=e.field,n=d("div",{className:"fillo-field fillo-field--calculated fillo-calculated",attrs:{"data-fillo":"calculated","data-field":t.id,"data-kind":t.kind}});n.appendChild(d("label",{className:"fillo-label",text:gt(t),attrs:{id:e.ids.labelId,for:e.ids.inputId,"data-fillo":"label"}})),t.description&&n.appendChild(d("p",{className:"fillo-description",text:t.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}}));let r=e.value,i=r!=null&&r!=="",o=d("output",{className:`fillo-calculated-value${i?"":" fillo-calculated-value--empty"}`,text:i?$r(t,r):"\u2014",attrs:{id:e.ids.inputId}});return t.description&&o.setAttribute("aria-describedby",e.ids.descriptionId),n.appendChild(o),n}var os=new Map;function Dr(e){if(!e.shuffleOptions)return e.options;let t=`${e.id}|${e.options.map(o=>o.id).join(",")}`,n=os.get(t);if(!n){n=e.options.map(o=>o.id);for(let o=n.length-1;o>0;o--){let s=Math.floor(Math.random()*(o+1));[n[o],n[s]]=[n[s],n[o]]}os.set(t,n)}let r=new Map(e.options.map(o=>[o.id,o])),i=n.flatMap(o=>r.get(o)??[]);return i.length===e.options.length?i:e.options}function Pt(e){let t=e.getValue?.()??e.value;return Array.isArray(t)?t:[]}function rc(e,t){return Math.max(t.length,e.minInstances??1)}function ic(e){return Math.max(e.minInstances??1,0)}function Rr(e,t){let n=[...e];for(;n.length<t;)n.push({});return n}function oc(e){let t=e.field;if(t.kind!=="repeating_group")return null;let n=e,r=n.announce,i=n.instanceId??"",o=t.itemLabel?.trim()||gt(t),s=Pt(e),a=rc(t,s),l=ic(t),c=d("div",{className:"fillo-group",attrs:{id:e.ids.inputId,"data-fillo":"control"}});pe(c,t,e.error,e.ids,{requiredSupported:!1});for(let f=0;f<a;f++){let h=s[f]??{},p=R.groupInstanceLabel(o,f+1,a),b=d("div",{className:"fillo-group-instance",attrs:{role:"group","aria-label":p,tabindex:"-1"}}),v=d("div",{className:"fillo-group-instance-header"}),y=d("button",{className:"fillo-group-remove",attrs:{type:"button","aria-label":R.groupRemoveLabel(o,f+1)}});y.appendChild(is("M6 6l12 12M18 6 6 18"));let F=a>l;y.toggleAttribute("disabled",!F),F||(y.setAttribute("aria-disabled","true"),y.setAttribute("title",`At least ${l} ${l===1?"entry":"entries"} required`)),y.addEventListener("click",()=>{if(a<=l)return;let I=Rr(Pt(e),a);I.splice(f,1),e.setValue(I),n.setGroupFocus?.({groupId:t.id,cardIndex:f-1,intoControl:!1}),r?.(R.groupInstanceRemoved(o,I.length))}),L(v,[d("p",{className:"fillo-group-instance-title",text:p}),y]),b.appendChild(v);for(let I of gn(t,h)){let ee=`${t.id}.${f}.${I.id}`,xe={...I,id:ee},M=fs(i,ee),ne=(U,ie)=>{let Ae=Rr(Pt(e),a);Ae[f]={...Ae[f]??{},[I.id]:U},e.setValue(Ae,ie)},re={field:xe,value:h[I.id],error:e.api.errors[ee],ids:M,api:e.api,setValue:ne,getValue:()=>Pt(e)[f]?.[I.id],announce:n.announce,announceAlert:n.announceAlert,registerOverlay:n.registerOverlay,activeOtherFields:n.activeOtherFields},Qe=n.renderChildField?.(re)??gs(re);Qe&&b.appendChild(Qe)}c.appendChild(b)}let u=a>=t.maxInstances,m=d("button",{className:"fillo-group-add",attrs:{type:"button"}});return m.append(is("M12 5v14M5 12h14"),t.addLabel||R.groupAdd),m.toggleAttribute("disabled",u),u&&(m.setAttribute("aria-disabled","true"),m.setAttribute("title",`Maximum ${t.maxInstances} ${t.maxInstances===1?"entry":"entries"}`)),m.addEventListener("click",()=>{if(a>=t.maxInstances)return;let f=Rr(Pt(e),a);f.push({}),e.setValue(f),n.setGroupFocus?.({groupId:t.id,cardIndex:f.length-1,intoControl:!0}),r?.(R.groupInstanceAdded(o,f.length,f.length))}),c.appendChild(m),ve(t,e.error,c,e.ids)}var sc={short_text:e=>Tt("text",e),email:e=>Tt("email",e),url:e=>Tt("url",e),phone:jl,number:e=>Tt("number",e),date:e=>Tt("date",e),long_text:Vl,select:Hl,multi_select:Gl,dropdown:Wl,checkbox:Kl,rating:Jl,linear_scale:Xl,ranking:Yl,matrix:Ql,signature:ec,file_upload:tc,calculated:nc,repeating_group:oc};function gs(e){if(e.field.kind==="hidden"||e.field.kind==="custom")return null;let t=sc[e.field.kind];return t?t(e):null}var ac="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",ss="fillo-turnstile-script",lc=2e4,cc=/^[A-Za-z0-9_-]{1,255}$/,Rt=null;function vt(){return globalThis.turnstile}function uc(){return typeof window>"u"||typeof document>"u"?Promise.reject(new Error("Turnstile needs a browser")):vt()?Promise.resolve():Rt||(Rt=new Promise((e,t)=>{let n=()=>{vt()?e():t(new Error("Turnstile loaded without its global"))},r=document.getElementById(ss);if(r){if(vt()){e();return}r.addEventListener("load",n,{once:!0}),r.addEventListener("error",()=>t(new Error("Turnstile script failed to load")),{once:!0});return}let i=document.createElement("script");i.id=ss,i.src=ac,i.async=!0,i.defer=!0,i.addEventListener("load",n,{once:!0}),i.addEventListener("error",()=>{i.remove(),Rt=null,t(new Error("Turnstile script failed to load"))},{once:!0}),document.head.appendChild(i)}),Rt)}function as(){return d("div",{className:"fillo-turnstile",attrs:{"data-fillo":"turnstile"}})}var Bt=class{constructor(t,n){this.target=t;this.options=n;this.element.className="fillo-dom-root",n.preview===!0&&yc(),t.replaceChildren(this.element,this.statusEl,this.alertEl),this.resolve()}target;options;element=d("div");statusEl=d("span",{className:"fillo-sr-only",attrs:{role:"status","aria-live":"polite","data-fillo":"announce"}});alertEl=d("span",{className:"fillo-sr-only",attrs:{role:"alert","data-fillo":"announce-alert"}});instanceId=`d${++Tl}`;schema=null;theme;formId;closed=!1;fetchedPoweredBy=null;fetchedBrandLabel;fetchedBrandHref;phase="loading";engine=null;destroyed=!1;renderQueued=!1;hpValue="";liveSubmissionHandled=!1;activeOtherFields=new Set;inFlight=new Map;uploadNotices=new Map;focusIntent=null;overlays=new Set;challenge;challengeToken;challengeError=!1;turnstileContainer=as();turnstileWidgetId=null;turnstileSiteKey;turnstileLoadInFlight=!1;turnstileAttempt=0;challengeFrame=null;challengeFrameSrc=null;challengeFrameOrigin=null;challengeMessageHandler=null;challengeWatchdog=null;announce=t=>{this.statusEl.textContent="",requestAnimationFrame(()=>{this.statusEl.textContent=t})};announceAlert=t=>{this.alertEl.textContent="",requestAnimationFrame(()=>{this.alertEl.textContent=t})};devChrome(){return this.options.preview===!0||pc()}get status(){return this.phase==="ready"?this.engine?.getState().status??"idle":this.phase}get data(){return this.engine?.getState().data??this.options.initialData??{}}get form(){return this.schema}get mutableData(){return this.engine?.getState().data??this.options.initialData??{}}api(){let t=this.schema??{version:1,title:"",pages:[],settings:{}},n=this.engine?.getState(),r=n?.pageCount??t.pages.length;return{form:t,formId:this.formId,client:this.options.renderOnly?void 0:this.options.client,data:n?.data??this.mutableData,errors:n?.errors??{},status:this.status,pageIndex:n?.pageIndex??0,pageCount:r,page:n?.page??t.pages[0]??{id:"empty",blocks:[]},blocks:n?.blocks??[],isFirstPage:n?.isFirstPage??!0,isLastPage:n?.isLastPage??r<=1,setValue:(i,o,s)=>this.setValueInternal(i,o,s),next:()=>this.next(),back:()=>this.back(),submit:()=>this.submit()}}resolveFormIdFn;notOpenVariant=null;fatalError=null;genericUnavailable=!1;syncErrorNotice=null;stagedNotice=!1;draftNotice=!1;syncWarningCode;syncWarningUrl;syncFormUrl;uploadsAvailable;uploadFileSizeLimitMb;resolutionFailureCode=null;async resolve(){try{this.challenge=this.options.renderOnly?void 0:this.options.challenge;let t=Nr(this.options.form)?this.options.form:null;if(t){if(this.options.renderOnly){this.setSchema(t.schema,this.options.theme??t.theme,void 0);return}let r=us(t.schema);if(r){await this.showPublishedInstead(r,t.schema,t.id);return}!this.options.client&&this.options.formId&&(this.options.client=Te());let i=this.options.client;if(i?.key&&(this.resolveFormIdFn=async()=>{try{let o=await Lr(i,t,{bypassCache:!0});if(this.syncWarningCode=o.warningCode,this.syncWarningUrl=o.warningUrl,this.syncFormUrl=o.manageUrl,this.uploadsAvailable=o.uploadsAvailable,this.uploadFileSizeLimitMb=o.uploadFileSizeLimitMb,o.status==="draft")throw new C("This form is no longer published. Submission was stopped before sending answers.",403,void 0,"form_not_published");if(o.accepting===!1)throw new C("This form is no longer accepting responses. Submission was stopped before sending answers.",403,void 0,o.acceptingReason??"form_not_accepting");let s=Ye(o.resolvedSchema??t.schema);if(!s.ok)throw new C(`The canonical form schema was invalid: ${s.error}`,502,void 0,"invalid_sync_schema");if(this.schema&&!Jo(this.schema,s.schema))throw new C("The live form changed after this page loaded. Submission stopped before incompatible answers were sent. Reload to use the published schema.",409,void 0,"form_schema_changed");return o.syncError&&this.reportSyncNotice(new C(o.syncError.message,403,void 0,o.syncError.code)),this.resolutionFailureCode=null,o.formId}catch(o){let s=Zt(o);throw this.resolutionFailureCode=s.code??"sync_failed",this.reportSubmitSyncFailure(s),s}}),!i?.key&&this.options.formId&&this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId),!i&&!this.options.formId)throw this.genericUnavailable=!this.devChrome(),ds();if(i&&!i.key&&!this.options.formId){this.reportSyncFailure(new C('Code forms need createClient({ key: "pk_\u2026" }) to resolve the live form. Pass a publishable key or a published formId.',401,void 0,"sync_key_required"));return}if(!i?.key)return;this.devChrome()?this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId):(this.theme=this.options.theme??t.theme,this.render());try{let o=await Lr(i,t);if(this.destroyed)return;if((o.staged||o.syncError)&&!o.resolvedSchema)throw new C("Sync did not return the live schema needed to render safely. Publish changes before deploy, and update @usefillo/* or your API.",409,void 0,"sync_snapshot_required");let s=this.devChrome();if(this.notOpenVariant=s?null:o.status==="draft"?"notOpen":o.accepting===!1?ls(o.acceptingReason):null,this.stagedNotice=!!o.staged,this.draftNotice=o.status==="draft",this.syncWarningCode=o.warningCode,this.syncWarningUrl=o.warningUrl,this.syncFormUrl=o.manageUrl,this.uploadsAvailable=o.uploadsAvailable,this.uploadFileSizeLimitMb=o.uploadFileSizeLimitMb,this.challenge=this.options.challenge??o.challenge,o.branding&&(this.fetchedPoweredBy=o.branding.poweredBy,this.fetchedBrandLabel=o.branding.label,this.fetchedBrandHref=o.branding.href),s&&o.resolvedSchema)this.formId=o.formId,this.engine?.setContext({formId:o.formId}),this.render();else{let l=o.resolvedSchema??t.schema,c=this.options.theme??(o.resolvedSchema?o.resolvedTheme??void 0:t.theme);this.applyCanonicalSchema(l,c,o.formId)}o.warning&&console.warn(`[fillo] ${o.warning}`),o.syncError&&this.reportSyncNotice(new C(o.syncError.message,403,void 0,o.syncError.code));let a=o.warningUrl?` \u2014 connect storage to publish: ${o.warningUrl}`:"";o.staged?console.info(`[fillo] "${t.id}" changes staged as a draft \u2014 rendering the live version until you publish them in your Fillo dashboard${a}`):o.status==="draft"&&console.info(`[fillo] "${t.id}" is a draft \u2014 it renders here but won't accept responses until published${a}`)}catch(o){if(this.destroyed)return;this.reportSyncFailure(Zt(o))}return}let n=this.options.form&&!Nr(this.options.form)?this.options.form:null;if(n){if(this.options.renderOnly){this.setSchema(n,this.options.theme,void 0);return}if(!this.options.formId)throw this.genericUnavailable=!this.devChrome(),ds();this.options.client??=Te();let r=us(n);if(r){await this.showPublishedInstead(r,n,void 0);return}this.setSchema(n,this.options.theme,this.options.formId);return}if(!this.options.formId)throw new C("Provide either `form`, or a `formId`.",0);this.options.client??=Te(),await this.loadPublished(this.options.formId)}catch(t){if(this.destroyed)return;this.handleError(Zt(t))}}async showPublishedInstead(t,n,r){let i=new C(`This form's definition is invalid: ${t}. In production, Fillo shows the published version of this form instead.`,422,void 0,Ot);if(this.devChrome()){this.handleError(i);return}this.options.onError?.(i),this.render(),!this.options.client&&this.options.formId&&(this.options.client=Te());let o=await Yo(this.options.client,{formId:this.options.formId,handle:r,definition:n,reason:t});if(!this.destroyed){if(!o){this.fatalError=i,this.phase="error",this.render(i);return}this.options.client??=Te();try{await this.loadPublished(o)}catch{if(this.destroyed)return;this.fatalError=i,this.phase="error",this.render(i)}}}async loadPublished(t){let n=this.options.client??Te();this.options.client=n,this.render();let r=await n.getForm(t);if(!this.destroyed){if(r.accepting===!1?this.notOpenVariant=ls(r.acceptingReason):this.closed=!!r.closed,this.uploadsAvailable=r.uploadsAvailable,this.uploadFileSizeLimitMb=r.uploadFileSizeLimitMb,this.fetchedPoweredBy=r.branding?.poweredBy??null,this.fetchedBrandLabel=r.branding?.label,this.fetchedBrandHref=r.branding?.href,this.challenge=this.options.challenge??r.challenge,r.accepting===!1&&this.options.renderError){let i=this.notOpenVariant==="closed"?"This form is no longer accepting responses.":"This form isn't accepting responses yet.";this.fatalError=new C(i,403,void 0,r.acceptingReason),this.phase="error",this.render(this.fatalError);return}this.setSchema(r.schema,this.options.theme??r.theme??void 0,r.id)}}setSchema(t,n,r){if(this.destroyed)return;let i=Ye(t);if(!i.ok)throw new C(`This form could not be rendered: ${i.error}`,422,void 0,Ot);let o=i.schema;this.schema=o,this.theme=n;let s=this.options.renderOnly===!0;this.formId=s?void 0:r;let a=this.notOpenVariant!==null,l=a||s,c=this;this.engine=jo({form:o,formId:l?void 0:r,client:l?void 0:this.options.client,initialData:this.options.initialData,onChange:a?void 0:this.options.onChange,onSubmitted:l?void 0:this.options.onSubmitted,getHoneypot:()=>this.element.querySelector('input[name="fillo_hp_field"]')?.value??this.hpValue,surface:"default",resolveFormId:l?void 0:this.resolveFormIdFn,skipValidation:s,verboseResolutionErrors:this.devChrome(),respondent:l?void 0:this.options.respondent,get challengeRequired(){return!l&&!!c.challenge},getChallengeToken:()=>this.challengeToken,onChallengeFailed:()=>this.resetChallengeWidget()});let u=this.engine.getState().status,m=this.engine.getState().resumedDraft,f=this.engine.getState().editingPrevious,h=this.engine.getState().errors,p=this.engine.getState().resumeLinkFailed;this.engine.subscribe(()=>{let b=this.engine?.getState();b&&(b.status!==u||b.resumedDraft!==m||b.editingPrevious!==f||b.errors!==h||b.resumeLinkFailed!==p)&&(b.editingPrevious&&!f?this.announce(P.editNotice):b.resumedDraft&&!m?this.announce(P.resumeNotice):b.resumeLinkFailed&&!p&&this.announce(R.resumeLinkExpired),u=b.status,m=b.resumedDraft,f=b.editingPrevious,h=b.errors,p=b.resumeLinkFailed,this.queueRender())}),l||this.configureDraftFlush(o),this.phase=this.closed?"closed":"ready",this.render()}applyCanonicalSchema(t,n,r){if(!this.engine){this.setSchema(t,n,r);return}let i=Ye(t);if(!i.ok)throw new C(`This form could not be rendered: ${i.error}`,422,void 0,Ot);let o=i.schema;this.schema=o,this.theme=n,this.formId=r,this.engine.setContext({form:o,formId:r}),this.notOpenVariant===null&&this.configureDraftFlush(o),this.phase=this.closed?"closed":"ready",this.render()}draftFlushWired=!1;flushDraftBound=()=>this.engine?.flushDraft();visibilityFlushBound=()=>{document.visibilityState==="hidden"&&this.engine?.flushDraft()};configureDraftFlush(t){this.teardownDraftFlush(),t.settings.saveProgress&&typeof window<"u"&&(window.addEventListener("pagehide",this.flushDraftBound),document.addEventListener("visibilitychange",this.visibilityFlushBound),this.draftFlushWired=!0)}teardownDraftFlush(){!this.draftFlushWired||typeof window>"u"||(window.removeEventListener("pagehide",this.flushDraftBound),document.removeEventListener("visibilitychange",this.visibilityFlushBound),this.draftFlushWired=!1)}flushDraft(){this.engine?.flushDraft()}resetDraft(){this.engine?.resetDraft(),this.queueRender()}setValue(t,n){this.setValueInternal(t,n)}setValueInternal(t,n,r={}){this.notOpenVariant||(this.engine?.setValue(t,n),r.render!==!1&&this.queueRender())}next(){if(!this.engine||this.notOpenVariant)return;let t=this.engine.getState().pageIndex;this.engine.next(),this.focusIntent=this.engine.getState().pageIndex!==t?"page":"error",this.render()}back(){!this.engine||this.notOpenVariant||(this.engine.back(),this.focusIntent="page",this.render())}async submit(){if(!this.engine||this.phase!=="ready"||this.notOpenVariant)return;let t=this.engine.submit();this.hasErrors()?this.focusIntent="error":this.engine.getState().status==="submitting"&&this.announce(R.submittingAnnouncement),this.render();try{await t}catch(n){this.options.onError?.(Zt(n)),this.focusIntent="error",this.render();return}this.hasErrors()&&(this.focusIntent="error"),this.render()}hasErrors(){return Object.keys(this.engine?.getState().errors??{}).length>0}setTheme(t){this.options.theme=t,this.theme=t,this.render()}setClient(t){this.options.client=t,this.engine?.setContext({client:t}),this.render()}setRespondent(t){this.options.respondent=t,this.engine?.setContext({respondent:t})}fieldActive(t){let n=0;for(let r of this.inFlight.values())r.fieldId===t&&r.error===void 0&&n++;return n}uploadRowsFor(t){let n=[];for(let[r,i]of this.inFlight)i.fieldId===t&&n.push({key:r,name:i.name,size:i.size,fraction:i.fraction,error:i.error,tooLarge:i.tooLarge});return n}uploadAction=(t,n)=>{let r=this.inFlight.get(t);if(r){if(n==="cancel")r.controller.abort(),this.inFlight.delete(t);else if(n==="dismiss")this.inFlight.delete(t);else{if(r.tooLarge)return;this.inFlight.delete(t),this.startUpload(r.fieldId,r.file,r.maxFiles)}this.fieldActive(r.fieldId)===0&&this.engine?.setUploading(r.fieldId,!1),this.queueRender()}};async startUpload(t,n,r){let i=`${n.name}-${n.size}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,o=new AbortController;this.inFlight.set(i,{fieldId:t,name:n.name,size:n.size,fraction:0,file:n,controller:o,maxFiles:r}),this.engine?.setUploading(t,!0),this.queueRender();try{let s=this.options.client&&this.formId?await this.options.client.uploadFile(this.formId,n,{fieldId:t,signal:o.signal,onProgress:l=>{let c=this.inFlight.get(i);c&&(c.fraction=l.fraction,this.queueRender())}}):{fileId:`local:${n.name}:${n.size}`,name:n.name,size:n.size,mime:n.type||"application/octet-stream"};if(this.destroyed)return;this.inFlight.delete(i);let a=r>1&&Array.isArray(this.mutableData[t])?this.mutableData[t]:[];this.setValueInternal(t,[...a,s])}catch(s){if(this.destroyed||o.signal.aborted)return;let a=Zt(s),l=a.status===0||a.status!==void 0&&a.status>=500?R.uploadUnavailable:R.uploadFailed,c=this.inFlight.get(i);c&&(c.error=l),this.announceAlert(l),this.options.onError?.(a)}finally{this.fieldActive(t)===0&&this.engine?.setUploading(t,!1),this.queueRender()}}async uploadFiles(t,n){if(!this.schema||this.notOpenVariant)return;let r=t.maxFiles??1,i=r>1&&Array.isArray(this.mutableData[t.id])?this.mutableData[t.id].length:0,o=Math.max(0,r-i-this.fieldActive(t.id)),s=n.slice(0,o),a=t.maxFileSizeMb??500,l=this.uploadFileSizeLimitMb?Math.min(a,this.uploadFileSizeLimitMb):a,c=l*1024*1024,u=s.filter(p=>p.size<=c),m=s.filter(p=>p.size>c),f=n.length-s.length,h=s.length-u.length;if(f>0||h>0){let p=[];f>0&&p.push(`You can attach up to ${r} file${r===1?"":"s"}. ${f} ${f===1?"file was":"files were"} not added.`);let b=p.join(" ");b?this.uploadNotices.set(t.id,b):this.uploadNotices.delete(t.id),b&&this.announce(b)}else this.uploadNotices.delete(t.id);for(let p of m){let b=R.fileTooLarge(l),v=`${p.name}-${p.size}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`;this.inFlight.set(v,{fieldId:t.id,name:p.name,size:p.size,fraction:0,error:b,tooLarge:!0,file:p,controller:new AbortController,maxFiles:r}),this.announceAlert(b)}if(u.length===0){this.queueRender();return}await Promise.all(u.map(p=>this.startUpload(t.id,p,r)))}destroy(){this.destroyed=!0,this.teardownDraftFlush(),this.closeOverlays(),this.teardownTurnstileWidget();for(let t of this.inFlight.values())t.controller.abort();this.inFlight.clear(),this.engine?.destroy(),this.engine=null,this.target.replaceChildren()}storageBlocked(){return this.uploadsAvailable===!1}registerOverlay=t=>(this.overlays.add(t),()=>this.overlays.delete(t));closeOverlays(){if(this.overlays.size!==0){for(let t of Array.from(this.overlays))try{t()}catch{}this.overlays.clear()}}ensureChallengeWidget(t){t.bridgeUrl?this.ensureChallengeBridge(t.bridgeUrl):this.ensureTurnstileWidget(t.siteKey)}ensureChallengeBridge(t){if(typeof window>"u")return;let n;try{n=new URL(t)}catch{this.handleChallengeError();return}if(n.protocol!=="https:"&&n.protocol!=="http:"){this.handleChallengeError();return}n.searchParams.set("origin",window.location.origin),n.searchParams.set("theme",this.options.challengeTheme??"auto"),this.formId&&cc.test(this.formId)&&n.searchParams.set("cdata",this.formId),n.searchParams.set("appearance",(this.options.challengeAppearance??"interaction-only")==="interaction-only"?"interaction-only":"always");let r=n.toString();if(this.challengeFrame&&this.challengeFrameSrc===r)return;this.teardownTurnstileWidget();let i=++this.turnstileAttempt,o=d("iframe",{className:"fillo-turnstile-frame",attrs:{src:r,title:"Human verification",width:"300",height:"65",referrerpolicy:"no-referrer"}});this.challengeFrame=o,this.challengeFrameSrc=r,this.challengeFrameOrigin=n.origin,this.turnstileContainer.appendChild(o),this.setChallengeFrameVisible((this.options.challengeAppearance??"interaction-only")!=="interaction-only");let s=a=>{if(i!==this.turnstileAttempt||this.destroyed||a.origin!==this.challengeFrameOrigin||!this.challengeFrame||a.source!==this.challengeFrame.contentWindow)return;let l=a.data;switch(l?.type){case"fillo:challenge:ready":this.settleChallengeWatchdog();break;case"fillo:challenge:token":this.settleChallengeWatchdog(),typeof l.token=="string"&&l.token.length>0&&this.handleChallengeToken(l.token),(this.options.challengeAppearance??"interaction-only")==="interaction-only"&&this.setChallengeFrameVisible(!1);break;case"fillo:challenge:interactive":this.setChallengeFrameVisible(!0);break;case"fillo:challenge:interactive-done":(this.options.challengeAppearance??"interaction-only")==="interaction-only"&&this.setChallengeFrameVisible(!1);break;case"fillo:challenge:expired":this.handleChallengeToken(void 0);break;case"fillo:challenge:error":this.settleChallengeWatchdog(),this.handleChallengeToken(void 0),this.handleChallengeError();break}};this.challengeMessageHandler=s,window.addEventListener("message",s),this.challengeWatchdog=window.setTimeout(()=>{i!==this.turnstileAttempt||this.destroyed||(this.handleChallengeToken(void 0),this.handleChallengeError())},lc)}setChallengeFrameVisible(t){let n=this.challengeFrame;n&&(n.setAttribute("height",t?"65":"0"),t?(n.removeAttribute("aria-hidden"),n.removeAttribute("tabindex")):(n.setAttribute("aria-hidden","true"),n.setAttribute("tabindex","-1")),this.turnstileContainer.setAttribute("data-fillo-challenge-visible",t?"true":"false"))}settleChallengeWatchdog(){this.challengeWatchdog!==null&&typeof window<"u"&&window.clearTimeout(this.challengeWatchdog),this.challengeWatchdog=null}teardownChallengeBridge(){this.challengeMessageHandler&&typeof window<"u"&&window.removeEventListener("message",this.challengeMessageHandler),this.challengeMessageHandler=null,this.settleChallengeWatchdog(),this.challengeFrame?.remove(),this.challengeFrame=null,this.challengeFrameSrc=null,this.challengeFrameOrigin=null}ensureTurnstileWidget(t){if(this.turnstileSiteKey!==t&&(this.teardownTurnstileWidget(),this.turnstileSiteKey=t),this.turnstileWidgetId!==null||this.turnstileLoadInFlight||this.challengeError)return;this.turnstileLoadInFlight=!0;let n=++this.turnstileAttempt;uc().then(()=>{if(this.destroyed||n!==this.turnstileAttempt)return;let r=vt();if(!r){this.turnstileLoadInFlight=!1,this.handleChallengeError();return}this.turnstileWidgetId=r.render(this.turnstileContainer,{sitekey:t,theme:"auto",callback:i=>this.handleChallengeToken(i),"error-callback":()=>{this.handleChallengeToken(void 0),this.handleChallengeError()},"expired-callback":()=>this.resetChallengeWidget(),"timeout-callback":()=>this.resetChallengeWidget()}),this.turnstileLoadInFlight=!1}).catch(()=>{this.destroyed||n!==this.turnstileAttempt||(this.turnstileLoadInFlight=!1,this.handleChallengeError())})}handleChallengeToken(t){this.challengeToken=t,t&&(this.challengeError=!1),this.queueRender()}handleChallengeError(){this.challengeError=!0,this.announceAlert(P.challengeUnavailable),this.queueRender()}resetChallengeWidget(){this.challengeToken=void 0,this.challengeFrame&&this.challengeFrameOrigin?this.challengeFrame.contentWindow?.postMessage({type:"fillo:challenge:reset"},this.challengeFrameOrigin):this.turnstileWidgetId&&vt()?.reset(this.turnstileWidgetId),this.queueRender()}teardownTurnstileWidget(){if(this.turnstileWidgetId===null&&!this.turnstileLoadInFlight&&this.challengeFrame===null)return;this.turnstileAttempt++,this.teardownChallengeBridge();let t=vt();if(this.turnstileWidgetId&&t)try{t.remove(this.turnstileWidgetId)}catch{}this.turnstileWidgetId=null,this.turnstileLoadInFlight=!1,this.challengeError=!1,this.turnstileContainer=as(),this.challengeToken=void 0}captureFocus(){if(typeof document>"u")return null;let t=document.activeElement;if(!t||!this.element.contains(t))return null;let n={};t.id&&(n.id=t.id);let r=t.getAttribute("data-fillo-rank-opt");r&&(n.rankOpt=r,n.rankDir=t.getAttribute("data-fillo-rank-dir")??void 0);let i=t.closest("[data-field]");if(i&&(n.fieldId=i.getAttribute("data-field")??void 0,n.controlIndex=Array.from(i.querySelectorAll(Ut)).indexOf(t)),t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)try{n.selStart=t.selectionStart,n.selEnd=t.selectionEnd}catch{}return n.id||n.rankOpt||n.fieldId?n:null}restoreFocus(t){if(typeof document>"u")return;let n=null;if(t.rankOpt){let r=Array.from(this.element.querySelectorAll("[data-fillo-rank-opt]")).filter(i=>i.getAttribute("data-fillo-rank-opt")===t.rankOpt);n=r.find(i=>i.getAttribute("data-fillo-rank-dir")===t.rankDir&&!i.disabled)??r.find(i=>!i.disabled)??null}if(!n&&t.id&&(n=document.getElementById(t.id)),!n&&t.fieldId!=null&&t.controlIndex!=null&&t.controlIndex>=0){let r=Array.from(this.element.querySelectorAll("[data-field]")).find(i=>i.getAttribute("data-field")===t.fieldId);r&&(n=Array.from(r.querySelectorAll(Ut))[t.controlIndex]??null)}if(!(!n||typeof n.focus!="function")&&(n.focus(),(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&t.selStart!=null))try{n.setSelectionRange(t.selStart,t.selEnd??t.selStart)}catch{}}applyFocus(t,n){if(!(typeof document>"u")){if(t==="error"){let r=this.element.querySelector('[aria-invalid="true"]');r&&Pl(r)?.focus();return}if(t==="page"){let i=this.element.querySelector(".fillo-page-title, .fillo-title")??this.element.querySelector(".fillo-blocks");i&&(i.hasAttribute("tabindex")||i.setAttribute("tabindex","-1"),i.focus?.());return}if(t){this.applyGroupFocus(t);return}n&&this.restoreFocus(n)}}applyGroupFocus(t){let n=Array.from(this.element.querySelectorAll("[data-field]")).find(o=>o.getAttribute("data-field")===t.groupId),r=n?Array.from(n.querySelectorAll(".fillo-group-instance")):[],i=t.cardIndex>=0?r[t.cardIndex]:void 0;if(i){(t.intoControl?Rl(i)??i:i).focus();return}n?.querySelector(".fillo-group-add")?.focus()}handleError(t){this.destroyed||(this.fatalError=t,this.phase="error",this.options.onError?.(t),this.render(t))}reportSyncFailure(t){if(this.destroyed)return;console.warn(`[fillo] form sync failed${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t;let n=this.devChrome();if(!n||this.options.renderError){this.genericUnavailable=!n,this.handleError(t);return}this.options.onError?.(t),n&&this.render()}reportSyncNotice(t){this.destroyed||(console.warn(`[fillo] form sync needs attention${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t,this.options.onError?.(t),this.devChrome()&&this.render())}reportSubmitSyncFailure(t){this.destroyed||(console.warn(`[fillo] form sync failed${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t)}queueRender(){this.renderQueued||this.destroyed||(this.renderQueued=!0,setTimeout(()=>{this.renderQueued=!1,this.render()},0))}render(t){if(this.destroyed)return;let n=this.focusIntent;this.focusIntent=null;let r=n?null:this.captureFocus();if(this.closeOverlays(),this.phase==="ready"&&this.engine?.getState().status!=="submitted"||this.teardownTurnstileWidget(),this.element.replaceChildren(),this.phase==="loading"){let s=d("div",{className:`fillo-form fillo-form--loading ${this.options.className??""}`,attrs:{"aria-busy":"true","data-fillo":"root","data-state":"loading"}});bt(s,this.theme),L(s,[d("div",{className:"fillo-skeleton"}),d("div",{className:"fillo-skeleton"}),d("div",{className:"fillo-skeleton fillo-skeleton--short"})]),this.element.appendChild(s);return}let o=t??this.fatalError;if(this.phase==="error"&&o){let s=o.code===Ot;if(s&&!this.devChrome()&&!this.options.renderOnly&&!this.options.renderError){let c=d("div",{attrs:{"data-fillo":"root","data-state":"unavailable","data-error-code":Ot}});c.hidden=!0,this.element.appendChild(c);return}let a=o.code==="form_target_required"&&this.devChrome()?`${o.message} (${o.code})`:s&&this.devChrome()?o.message:null,l=this.options.renderError?.(o)??d("div",{className:"fillo-form fillo-form--error",text:a??(this.genericUnavailable?"This form is unavailable.":_c(o))});l.hasAttribute("data-fillo")||l.setAttribute("data-fillo","root"),l.hasAttribute("data-state")||l.setAttribute("data-state","error"),o.code&&!l.hasAttribute("data-error-code")&&l.setAttribute("data-error-code",o.code),l.hasAttribute("role")||l.setAttribute("role","alert"),bt(l,this.theme),this.element.appendChild(l);return}if(this.phase==="closed"){let s=d("div",{className:`fillo-form fillo-form--closed ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});bt(s,this.theme),s.appendChild(d("p",{className:"fillo-closed",text:"This form is no longer accepting responses."})),this.element.appendChild(s);return}if(this.notOpenVariant&&this.schema){this.element.appendChild(this.renderNotOpen(this.notOpenVariant)),this.brandingVisible()&&this.element.appendChild(Or(this.fetchedBrandLabel,this.fetchedBrandHref));return}if(this.schema){if(this.engine?.getState().status==="submitted"){let s=this.api(),a=this.engine.getState(),l=this.options.renderSuccess?.(s)??fc(this.schema);if(l.setAttribute("data-fillo",l.getAttribute("data-fillo")??"root"),this.formId&&!l.hasAttribute("data-fillo-form-id")&&l.setAttribute("data-fillo-form-id",this.formId),l.setAttribute("data-state",l.getAttribute("data-state")??"submitted"),l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1"),bt(l,this.theme),this.element.appendChild(l),this.brandingVisible()&&this.element.appendChild(Or(this.fetchedBrandLabel,this.fetchedBrandHref)),!a.restoredSubmission&&!this.liveSubmissionHandled){this.liveSubmissionHandled=!0;let c=at(this.schema.settings.redirectUrl);c&&typeof window<"u"?window.location.assign(c):(l.focus(),this.announce(l.textContent??""))}return}this.devChrome()&&L(this.element,wc({preview:this.options.preview===!0,devNotices:this.options.devNotices,syncError:this.syncErrorNotice,staged:this.stagedNotice,draft:this.draftNotice,warningUrl:this.syncWarningUrl,formUrl:this.syncFormUrl,noClient:!this.options.client&&!this.options.renderOnly})),this.element.appendChild(this.renderForm()),this.brandingVisible()&&this.element.appendChild(Or(this.fetchedBrandLabel,this.fetchedBrandHref)),this.applyFocus(n,r)}}brandingVisible(){return this.fetchedPoweredBy??!0}renderNotOpen(t){let n=d("div",{className:`fillo-form fillo-form--not-open ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});bt(n,this.theme);let r=d("div",{className:"fillo-not-open-preview",attrs:{"aria-hidden":"true",inert:""}});r.appendChild(this.renderForm());let i=d("div",{className:"fillo-not-open-card",attrs:{role:"status","data-fillo":"not-open-card"}});return i.appendChild(d("h2",{className:"fillo-not-open-title",text:t==="closed"?P.closedTitle:P.notOpenTitle})),i.appendChild(d("p",{className:"fillo-not-open-body",text:t==="closed"?P.closed:P.notOpenBody})),L(n,[r,i]),n}renderForm(){let t=this.api(),n=this.notOpenVariant!==null,r=!!this.challenge,i=!n&&r&&t.isLastPage,o=d(n?"div":"form",{className:`fillo-form ${this.options.className??""}`,attrs:{"data-fillo":n?"preview-form":"root","data-state":n?"preview":t.status,"data-page":String(t.pageIndex+1)}});!n&&this.formId&&o.setAttribute("data-fillo-form-id",this.formId),o.toggleAttribute("data-last-page",t.isLastPage),bt(o,this.theme);let s=()=>{t.isLastPage?this.submit():this.next()};if(!n){let p=o;p.noValidate=!0,p.addEventListener("submit",b=>{b.preventDefault(),s()})}let a=n?o.appendChild(d("fieldset",{className:"fillo-not-open-fields",attrs:{disabled:""}})):o,l=this.engine?.getState();if(l?.resumedDraft||l?.editingPrevious){let p=d("div",{className:"fillo-resume",attrs:{"data-fillo":"resume"}});p.appendChild(d("span",{className:"fillo-resume-text",text:l.editingPrevious?P.editNotice:P.resumeNotice}));let b=d("button",{className:"fillo-resume-clear",text:P.resumeStartOver,attrs:{type:"button"}});b.addEventListener("click",()=>this.resetDraft()),p.appendChild(b),a.appendChild(p)}else l?.resumeLinkFailed&&a.appendChild(d("div",{className:"fillo-resume fillo-resume--expired",attrs:{"data-fillo":"resume"},text:R.resumeLinkExpired}));if(t.pageCount>1&&this.schema?.settings.showProgress!==!1){let p=ht(t.form,t.data),b=Math.max(p.length,1),v=p.indexOf(t.page.id),y=v>=0?v+1:Math.min(t.pageIndex+1,b),F=d("div",{className:"fillo-progress-track",attrs:{role:"progressbar","data-fillo":"progress","aria-label":t.form.title||"Form progress","aria-valuemin":"1","aria-valuemax":String(b),"aria-valuenow":String(y)}});F.appendChild(d("div",{className:"fillo-progress-fill",attrs:{"data-fillo":"progressFill"}})),F.firstElementChild?.style.setProperty("--fillo-progress-value",`${y/b*100}%`),a.appendChild(F)}if(t.pageIndex===0){let p=d("header",{className:"fillo-header",attrs:{"data-fillo":"header"}});t.form.title&&p.appendChild(d("h1",{className:"fillo-title",text:t.form.title,attrs:{"data-fillo":"title"}})),t.form.description&&p.appendChild(d("p",{className:"fillo-form-description",text:t.form.description,attrs:{"data-fillo":"description"}})),a.appendChild(p)}else t.page.title&&a.appendChild(d("h2",{className:"fillo-page-title",text:t.page.title,attrs:{"data-fillo":"pageTitle"}}));let c=d("div",{className:"fillo-blocks",attrs:{"data-fillo":"blocks"}});for(let p of t.blocks){let b=this.renderBlock(es(p,this.mutableData,t.form),t);b&&c.appendChild(b)}if(a.appendChild(c),!n){let p=d("input",{className:"fillo-hp",attrs:{type:"text",name:"fillo_hp_field",tabindex:"-1",autocomplete:"off","aria-hidden":"true"}});p.style.position="absolute",p.style.left="-9999px",p.style.top="auto",p.style.width="1px",p.style.height="1px",p.style.opacity="0",p.style.overflow="hidden",p.style.pointerEvents="none",p.addEventListener("input",()=>{this.hpValue=p.value}),a.appendChild(p)}if(i){let p=d("div",{className:"fillo-turnstile-slot",attrs:{"data-fillo":"turnstile-slot"}});p.appendChild(this.turnstileContainer),this.challengeError&&p.appendChild(d("p",{className:"fillo-turnstile-error",attrs:{role:"alert"},text:P.challengeUnavailable})),a.appendChild(p),this.ensureChallengeWidget(this.challenge)}else(this.turnstileWidgetId!==null||this.turnstileLoadInFlight||this.challengeFrame!==null)&&this.teardownTurnstileWidget();let u=t.status==="error"?"This form can't submit right now. Please try again in a moment.":this.engine?.getState().submitError;if(u){let p=d("p",{className:"fillo-submit-error",attrs:{role:"alert"},text:u}),b=this.devChrome()&&this.resolutionFailureCode==="form_not_published"&&this.syncWarningCode==="storage_required"?at(this.syncWarningUrl):null;b&&(p.append(" Connect storage: "),p.appendChild(d("a",{text:b,attrs:{href:b,target:"_blank",rel:"noopener noreferrer"}}))),a.appendChild(p)}let f=!(t.form.settings.submitMode==="auto")||!t.isLastPage||Vo(wo(t.form,t.data))||i;if(f||t.pageCount>1&&!t.isFirstPage){let p=d("footer",{className:"fillo-footer",attrs:{"data-fillo":"footer"}});if(t.pageCount>1&&!t.isFirstPage){let b=d("button",{className:"fillo-button fillo-button--ghost",text:"Back",attrs:{type:"button","data-fillo":"button"}});b.addEventListener("click",()=>this.back()),p.appendChild(b)}if(f){let b=d("button",{className:"fillo-button fillo-button--primary",text:t.status==="submitting"?"Submitting...":t.isLastPage?t.form.settings.submitLabel??"Submit":"Next",attrs:{type:"submit","data-fillo":"button"}});b.toggleAttribute("disabled",t.status==="submitting"||this.engine?.getState().uploading===!0||i&&!this.challengeToken),b.addEventListener("click",v=>{v.preventDefault(),s()}),p.appendChild(b)}a.appendChild(p)}return o}fieldRenderer(t){return t.kind==="custom"?this.options.customComponents?.[t.component]??this.options.components?.custom:this.options.components?.[t.kind]??gs}renderChildField=t=>this.fieldRenderer(t.field)?.(t)??null;setGroupFocus=t=>{this.focusIntent=t};renderBlock(t,n){if(!ce(t))return dc(t);let r=(o,s)=>{if(this.setValueInternal(t.id,o,s),s?.render===!1)return;let a={form:n.form,data:n.data,status:n.status,isLastPage:n.isLastPage,uploading:this.engine?.getState().uploading===!0};Ho(t,o,a)&&this.submit()},i={field:t,value:n.data[t.id],error:n.errors[t.id]===Nt?Fo(t,R):n.errors[t.id],ids:fs(this.instanceId,t.id),api:n,setValue:r,uploadFiles:(o,s)=>this.uploadFiles(o,s),uploadRows:this.uploadRowsFor(t.id),uploadAction:this.uploadAction,activeOtherFields:this.activeOtherFields,getValue:()=>this.engine?.getState().data[t.id],registerOverlay:this.registerOverlay,uploadNotice:this.uploadNotices.get(t.id),uploadDisabledReason:this.options.renderOnly?"render_only":this.storageBlocked()?"storage_unavailable":void 0,storageFixUrl:this.storageBlocked()&&this.devChrome()?at(this.syncWarningUrl):null,announce:this.announce,announceAlert:this.announceAlert,instanceId:this.instanceId,renderChildField:this.renderChildField,setGroupFocus:this.setGroupFocus};return this.fieldRenderer(t)?.(i)??null}};function dc(e){switch(e.kind){case"heading":return d("h3",{className:"fillo-heading",text:e.text});case"paragraph":return d("p",{className:"fillo-paragraph",text:e.text});case"divider":return d("hr",{className:"fillo-divider"})}return d("div")}function fc(e){let t=d("div",{className:"fillo-form fillo-form--success"}),n=d("div",{className:"fillo-success"});return L(n,[d("div",{className:"fillo-success-mark",attrs:{"aria-hidden":"true"}}),d("h2",{className:"fillo-success-title",text:e.settings.successTitle??"Thanks!"}),d("p",{className:"fillo-success-message",text:e.settings.successMessage??"Your response has been recorded."})]),t.appendChild(n),t}function Or(e,t){return d("a",{className:"fillo-powered",text:e??"Powered by Fillo",attrs:{href:Ol(t),target:"_blank",rel:"nofollow noopener noreferrer"}})}function ls(e){return e==="expired"||e==="capped"||e==="storage_full"?"closed":"notOpen"}function pc(){return Qo()}function hc(){return d("div",{className:"fillo-devwarning",text:"No Fillo client connected \u2014 this form is render-only and won't save responses. Pass a client to collect them in Fillo, or forward with webhooks. (Shown only in development and preview.)",attrs:{role:"alert"}})}function mc(e){return d("div",{className:"fillo-devwarning",text:`Form sync needs attention${e.code?` (${e.code})`:""}: ${e.message} The safe form remains available for development.`,attrs:{role:"alert"}})}function gc(e){let t=d("div",{className:"fillo-devwarning",attrs:{role:"alert"}});t.append("Code changes are staged, not live. This page shows your draft, while respondents still get the live version. ");let n=at(e);return n?(t.appendChild(d("a",{text:"Review and publish in Fillo",attrs:{href:n,target:"_blank",rel:"noopener noreferrer"}})),t.append(".")):t.append("Review and publish the changes in Fillo."),t}function bc(e,t){let n=d("div",{className:"fillo-devwarning",attrs:{role:"alert"}});n.append("Draft form preview \u2014 the form renders for local testing, but Fillo will reject the submission and save no response until you publish it. ");let r=at(e),i=at(t);return r?(n.appendChild(d("a",{text:"Connect storage to publish",attrs:{href:r,target:"_blank",rel:"noopener noreferrer"}})),n.append(". ")):i&&(n.appendChild(d("a",{text:"Open in Fillo to publish",attrs:{href:i,target:"_blank",rel:"noopener noreferrer"}})),n.append(". ")),n.append("(Shown only in development and preview.)"),n}function vc(){return d("span",{className:"fillo-preview-badge",text:"Preview",attrs:{"data-fillo":"preview-badge"}})}var cs=!1;function yc(){cs||Tr()||(cs=!0,console.warn("[fillo] `preview` is enabled in a production build. Preview is cosmetic only \u2014 it shows developer chrome and never changes where submissions go or whether they are accepted \u2014 but remove it before respondents see this page."))}function wc(e){let t=[];return e.preview&&t.push(vc()),e.devNotices===!1||(e.syncError?t.push(mc(e.syncError)):e.staged?t.push(gc(e.formUrl)):e.draft?t.push(bc(e.warningUrl,e.formUrl)):e.noClient&&t.push(hc())),t}var Ot="invalid_form_definition";function us(e){let t=Ye(e);return t.ok?null:t.error??"invalid form definition"}function _c(e){return e.status===404?P.loadFailedNotFound:e.status===0?P.loadFailedNetwork:e.status===422?P.renderFailed:P.loadFailed}function ds(){return new C("This form has no Fillo target. Pass formId with the schema, use a defineForm() value with client, or set renderOnly for a non-submitting preview.",422,void 0,"form_target_required")}function Zt(e){return be(e)?e:new C(e instanceof Error?e.message:String(e),0)}function xn(e,t){let n=typeof e=="string"?document.querySelector(e):e;if(!n)throw new C(`Fillo mount target not found: ${String(e)}`,0);let r={...t,initialData:t.initialData??{}};return new Bt(n,r)}function bs(e){let t=d("div");return xn(t,e),t}var xc=typeof HTMLElement<"u"?HTMLElement:class{},Zr=class extends xc{instance=null;assignedForm;assignedClient;assignedTheme;assignedInitialData;mounted=!1;mountScheduled=!1;static get observedAttributes(){return["publishable-key","form-id","data-preview","data-render-only"]}connectedCallback(){this.scheduleMount()}disconnectedCallback(){this.instance?.destroy(),this.instance=null,this.mounted=!1}attributeChangedCallback(){this.mounted&&this.isConnected&&this.scheduleMount()}set form(t){this.assignedForm=t,this.mounted&&this.scheduleMount()}get form(){return this.assignedForm}set client(t){this.assignedClient=t,this.mounted&&this.instance instanceof Bt&&this.instance.setClient(t)}set theme(t){this.assignedTheme=t,this.mounted&&this.instance instanceof Bt&&this.instance.setTheme(t)}set initialData(t){this.assignedInitialData=t,this.mounted&&this.scheduleMount()}scheduleMount(){this.mountScheduled||(this.mountScheduled=!0,queueMicrotask(()=>{this.mountScheduled=!1,this.isConnected&&this.mount()}))}previewAttrEnabled(){let t=this.getAttribute("data-preview");return t!==null&&t!=="false"&&t!=="0"}renderOnlyAttrEnabled(){let t=this.getAttribute("data-render-only");return t!==null&&t!=="false"&&t!=="0"}mount(){this.instance?.destroy();let t=this.getAttribute("publishable-key")??void 0,n=this.getAttribute("form-id")??void 0,r=this.assignedClient??(n||t?Te({key:t}):void 0);this.instance=xn(this,{form:this.assignedForm,client:r,formId:n,theme:this.assignedTheme,initialData:this.assignedInitialData,preview:this.previewAttrEnabled()?!0:void 0,renderOnly:this.renderOnlyAttrEnabled()?!0:void 0,onChange:i=>this.dispatchEvent(new CustomEvent("fillo-change",{detail:{data:i}})),onSubmitted:(i,o)=>this.dispatchEvent(new CustomEvent("fillo-submit",{detail:{responseId:i,data:o}})),onError:i=>this.dispatchEvent(new CustomEvent("fillo-error",{detail:{error:i}}))}),this.mounted=!0}};function Ur(e="fillo-form"){typeof customElements>"u"||customElements.get(e)||customElements.define(e,Zr)}typeof customElements<"u"&&Ur();return Is(kc);})();
1
+ "use strict";var Fillo=(()=>{var zn=Object.defineProperty;var As=Object.getOwnPropertyDescriptor;var Fs=Object.getOwnPropertyNames;var Es=Object.prototype.hasOwnProperty;var zs=(e,t)=>{for(var n in t)zn(e,n,{get:t[n],enumerable:!0})},Cs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Fs(t))!Es.call(e,i)&&i!==n&&zn(e,i,{get:()=>t[i],enumerable:!(r=As(t,i))||r.enumerable});return e};var Is=e=>Cs(zn({},"__esModule",{value:!0}),e);var kc={};zs(kc,{FilloClient:()=>vn,FilloError:()=>C,createClient:()=>Te,createFormElement:()=>bs,defineForm:()=>Mr,registerFilloElement:()=>Ur,renderForm:()=>xn});var ni;function N(e,t,n){function r(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let c=s.prototype,u=Object.keys(c);for(let m=0;m<u.length;m++){let f=u[m];f in a||(a[f]=c[f].bind(a))}}let i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var l;let c=n?.Parent?new o:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var Re=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(ni=globalThis).__zod_globalConfig??(ni.__zod_globalConfig={});var Cn=globalThis.__zod_globalConfig;function Ve(e){return e&&Object.assign(Cn,e),Cn}function ii(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function oi(e,t){return typeof t=="bigint"?t.toString():t}function si(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Mn(e){return e==null}function ai(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var ri=Symbol("evaluating");function He(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==ri)return r===void 0&&(r=ri,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}var Nn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ln(e){if(Jt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(Jt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Tn(e){return Ln(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var li=new Set(["string","number","symbol"]);function _t(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pn(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function ae(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ci(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ms={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function xt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ui(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Ge(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Kt(e){return typeof e=="string"?e:e?.message}function qe(e,t,n){let r=e.message?e.message:Kt(e.inst?._zod.def?.error?.(e))??Kt(t?.error?.(e))??Kt(n.customError?.(e))??Kt(n.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=s),a}function Rn(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}var di=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,oi,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},fi=N("$ZodError",di),kt=N("$ZodError",di,{Parent:Error});var Ls=e=>(t,n,r,i)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Re;if(s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>qe(l,o,Ve())));throw Nn(a,i?.callee),a}return s.value},Xt=Ls(kt),Ts=e=>async(t,n,r,i)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>qe(l,o,Ve())));throw Nn(a,i?.callee),a}return s.value},Yt=Ts(kt),Ps=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Re;return o.issues.length?{success:!1,error:new(e??fi)(o.issues.map(s=>qe(s,i,Ve())))}:{success:!0,data:o.value}},$t=Ps(kt),Rs=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>qe(s,i,Ve())))}:{success:!0,data:o.value}},St=Rs(kt);var pi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Os="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Zs=new RegExp(`^${Os}$`);var hi=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var On=/^-?\d+(?:\.\d+)?$/;var et=N("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ds={number:"number",bigint:"bigint",object:"date"};var gi=N("$ZodCheckGreaterThan",(e,t)=>{et.init(e,t);let n=Ds[typeof t.value];e._zod.onattach.push(r=>{let i=r._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var bi=N("$ZodCheckMaxLength",(e,t)=>{var n;et.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!Mn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let i=r.value;if(i.length<=t.maximum)return;let s=Rn(i);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),vi=N("$ZodCheckMinLength",(e,t)=>{var n;et.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!Mn(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let i=r.value;if(i.length>=t.minimum)return;let s=Rn(i);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}});var Zn=N("$ZodCheckStringFormat",(e,t)=>{var n,r;et.init(e,t),e._zod.onattach.push(i=>{let o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),yi=N("$ZodCheckRegex",(e,t)=>{Zn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}});var _i={major:4,minor:4,patch:3};var we=N("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=_i;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let i of r)for(let o of i._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,a,l)=>{let c=xt(s),u;for(let m of a){if(m._zod.def.when){if(ui(s)||!m._zod.def.when(s))continue}else if(c)continue;let f=s.issues.length,h=m._zod.check(s);if(h instanceof Promise&&l?.async===!1)throw new Re;if(u||h instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await h,s.issues.length!==f&&(c||(c=xt(s,f)))});else{if(s.issues.length===f)continue;c||(c=xt(s,f))}}return u?u.then(()=>s):s},o=(s,a,l)=>{if(xt(s))return s.aborted=!0,s;let c=i(a,r,l);if(c instanceof Promise){if(l.async===!1)throw new Re;return c.then(u=>e._zod.parse(u,l))}return e._zod.parse(c,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let c=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(u=>o(u,s,a)):o(c,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Re;return l.then(c=>i(c,r,a))}return i(l,r,a)}}He(e,"~standard",()=>({validate:i=>{try{let o=$t(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return St(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Dn=N("$ZodString",(e,t)=>{we.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??hi(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Un=N("$ZodStringFormat",(e,t)=>{Zn.init(e,t),Dn.init(e,t)});var Si=N("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=pi),Un.init(e,t)});var Ai=N("$ZodNumber",(e,t)=>{we.init(e,t),e._zod.pattern=e._zod.bag.pattern??On,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}});var Fi=N("$ZodUnknown",(e,t)=>{we.init(e,t),e._zod.parse=n=>n});function xi(e,t,n){e.issues.length&&t.issues.push(...Ge(n,e.issues)),t.value[n]=e.value}var Ei=N("$ZodArray",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],l=t.element._zod.run({value:a,issues:[]},r);l instanceof Promise?o.push(l.then(c=>xi(c,n,s))):xi(l,n,s)}return o.length?Promise.all(o).then(()=>n):n}});function Qt(e,t,n,r,i,o){let s=n in r;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...Ge(n,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function Bs(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=ci(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function js(e,t,n,r,i,o){let s=[],a=i.keySet,l=i.catchall._zod,c=l.def.type,u=l.optin==="optional",m=l.optout==="optional";for(let f in t){if(f==="__proto__"||a.has(f))continue;if(c==="never"){s.push(f);continue}let h=l.run({value:t[f],issues:[]},r);h instanceof Promise?e.push(h.then(p=>Qt(p,n,f,t,u,m))):Qt(h,n,f,t,u,m)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}var zi=N("$ZodObject",(e,t)=>{if(we.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let r=si(()=>Bs(t));He(e._zod,"propValues",()=>{let a=t.shape,l={};for(let c in a){let u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let m of u.values)l[c].add(m)}}return l});let i=Jt,o=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=r.value);let c=a.value;if(!i(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),a;a.value={};let u=[],m=s.shape;for(let f of s.keys){let h=m[f],p=h._zod.optin==="optional",b=h._zod.optout==="optional",v=h._zod.run({value:c[f],issues:[]},l);v instanceof Promise?u.push(v.then(y=>Qt(y,a,f,c,p,b))):Qt(v,a,f,c,p,b)}return o?js(u,c,a,l,r.value,e):u.length?Promise.all(u).then(()=>a):a}});var Ci=N("$ZodRecord",(e,t)=>{we.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Ln(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let a=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);let u=t.keyType._zod.run({value:c,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(h=>qe(h,r,Ve())),input:c,path:[c],inst:e});continue}let m=u.value,f=t.valueType._zod.run({value:i[c],issues:[]},r);f instanceof Promise?o.push(f.then(h=>{h.issues.length&&n.issues.push(...Ge(c,h.issues)),n.value[m]=h.value})):(f.issues.length&&n.issues.push(...Ge(c,f.issues)),n.value[m]=f.value)}let l;for(let c in i)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l})}else{n.value={};for(let a of Reflect.ownKeys(i)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&On.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},r);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");m.issues.length===0&&(l=m)}if(l.issues.length){t.mode==="loose"?n.value[a]=i[a]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(m=>qe(m,r,Ve())),input:a,path:[a],inst:e});continue}let u=t.valueType._zod.run({value:i[a],issues:[]},r);u instanceof Promise?o.push(u.then(m=>{m.issues.length&&n.issues.push(...Ge(a,m.issues)),n.value[l.value]=m.value})):(u.issues.length&&n.issues.push(...Ge(a,u.issues)),n.value[l.value]=u.value)}}return o.length?Promise.all(o).then(()=>n):n}});var Ii=N("$ZodEnum",(e,t)=>{we.init(e,t);let n=ii(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>li.has(typeof i)).map(i=>typeof i=="string"?_t(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{let s=i.value;return r.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),Mi=N("$ZodLiteral",(e,t)=>{if(we.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?_t(r):r?_t(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,i)=>{let o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});function ki(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Ni=N("$ZodOptional",(e,t)=>{we.init(e,t),e._zod.optin="optional",e._zod.optout="optional",He(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),He(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${ai(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let i=n.value,o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>ki(s,i)):ki(o,i)}return n.value===void 0?n:t.innerType._zod.run(n,r)}});var Li=N("$ZodDefault",(e,t)=>{we.init(e,t),e._zod.optin="optional",He(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>$i(o,t)):$i(i,t)}});function $i(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function Ti(e,t){return new e({type:"string",...ae(t)})}function Pi(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ae(t)})}function Ri(e,t){return new e({type:"number",checks:[],...ae(t)})}function Oi(e){return new e({type:"unknown"})}function Bn(e,t){return new gi({check:"greater_than",...ae(t),value:e,inclusive:!0})}function jn(e){return Bn(0,e)}function le(e,t){return new bi({check:"max_length",...ae(t),maximum:e})}function tt(e,t){return new vi({check:"min_length",...ae(t),minimum:e})}function Vn(e,t){return new yi({check:"string_format",format:"regex",...ae(t),pattern:e})}var Ce=N("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");we.init(e,t),e.def=t,e.type=t.type,e.parse=(n,r)=>Xt(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>$t(e,n,r),e.parseAsync=async(n,r)=>Yt(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>St(e,n,r),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0}),e.with=e.check,e.clone=(n,r)=>Pn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.apply=n=>n(e)}),Di=N("ZodMiniString",(e,t)=>{Dn.init(e,t),Ce.init(e,t)});function fe(e){return Ti(Di,e)}var Hs=N("ZodMiniStringFormat",(e,t)=>{Un.init(e,t),Di.init(e,t)}),Gs=N("ZodMiniEmail",(e,t)=>{Si.init(e,t),Hs.init(e,t)});function en(e){return Pi(Gs,e)}var qs=N("ZodMiniNumber",(e,t)=>{Ai.init(e,t),Ce.init(e,t)});function Ui(e){return Ri(qs,e)}var Ws=N("ZodMiniUnknown",(e,t)=>{Fi.init(e,t),Ce.init(e,t)});function At(){return Oi(Ws)}var Ks=N("ZodMiniArray",(e,t)=>{Ei.init(e,t),Ce.init(e,t)});function Oe(e,t){return new Ks({type:"array",element:e,...ae(t)})}var Bi=N("ZodMiniObject",(e,t)=>{zi.init(e,t),Ce.init(e,t),He(e,"shape",()=>t.shape)});function Ft(e,t){let n={type:"object",shape:e??{},...ae(t)};return new Bi(n)}function Hn(e,t){return new Bi({type:"object",shape:e,catchall:At(),...ae(t)})}var Zi=N("ZodMiniRecord",(e,t)=>{Ci.init(e,t),Ce.init(e,t)});function ji(e,t,n){return!t||!t._zod?new Zi({type:"record",keyType:fe(),valueType:e,...ae(t)}):new Zi({type:"record",keyType:e,valueType:t,...ae(n)})}var Js=N("ZodMiniEnum",(e,t)=>{Ii.init(e,t),Ce.init(e,t),e.options=Object.values(t.entries)});function Vi(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Js({type:"enum",entries:n,...ae(t)})}var Xs=N("ZodMiniLiteral",(e,t)=>{Mi.init(e,t),Ce.init(e,t)});function Hi(e,t){return new Xs({type:"literal",values:Array.isArray(e)?e:[e],...ae(t)})}var Ys=N("ZodMiniOptional",(e,t)=>{Ni.init(e,t),Ce.init(e,t)});function ge(e){return new Ys({type:"optional",innerType:e})}var Qs=N("ZodMiniDefault",(e,t)=>{Li.init(e,t),Ce.init(e,t)});function Gn(e,t){return new Qs({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Tn(t)}})}var na=200,ra=["heading","paragraph","divider"];function ce(e){return!ra.includes(e.kind)}function mn(e){return e==null?!0:typeof e=="string"?e.trim()==="":Array.isArray(e)?e.length===0:typeof e=="boolean"?e===!1:typeof e=="object"?Object.keys(e).length===0:!1}function ia(e,t){if(!Array.isArray(t))return;let n=new Map(e.fields.map(o=>[o.id,o])),r=!1,i=t.map(o=>{if(!o||typeof o!="object"||Array.isArray(o))return o;let s=!1,a={};for(let[l,c]of Object.entries(o)){let u=n.get(l);if(!u){s=!0;continue}let m=ho(u,c);if(m===void 0){s=!0;continue}a[l]=m,m!==c&&(s=!0)}return s?(r=!0,a):o});return r?i:t}function po(e,t){if(t==null||e.kind==="custom")return t;if(e.kind==="repeating_group")return ia(e,t);if(e.kind==="number"&&typeof t=="string"&&t.trim()!==""){let n=Number(t);return Number.isNaN(n)?t:n}if((e.kind==="rating"||e.kind==="linear_scale")&&typeof t=="string"){let n=Number(t);return Number.isNaN(n)?t:n}return typeof t=="string"?t.trim():t}function ho(e,t){let n=po(e,t);return mn(n)?void 0:n}function mo(e){return e===void 0||!Number.isFinite(e)?0:Math.max(0,Math.min(6,Math.round(e)))}function go(e,t){let n=10**t,r=Math.round(Math.abs(e)*n)/n;return e<0?-r:r}function it(e){return Number.isFinite(e)?e:null}function pt(e,t){switch(e.op){case"value":return cr(t(e.fieldId));case"const":return it(e.value);case"add":case"mul":case"min":case"max":{if(e.args.length===0)return null;let n=[];for(let r of e.args){let i=pt(r,t);if(i===null)return null;n.push(i)}return e.op==="add"?it(n.reduce((r,i)=>r+i,0)):e.op==="mul"?it(n.reduce((r,i)=>r*i,1)):e.op==="min"?Math.min(...n):Math.max(...n)}case"sub":case"div":{let n=pt(e.left,t);if(n===null)return null;let r=pt(e.right,t);return r===null?null:e.op==="sub"?it(n-r):r===0?null:it(n/r)}case"round":{let n=pt(e.arg,t);return n===null?null:it(go(n,mo(e.decimals)))}case"if":return pt(wr(e.when,t)?e.then:e.else,t)}}function oa(e,t){let n=pt(e.calc,t);return n===null||e.decimals===void 0?n:it(go(n,mo(e.decimals)))}function nt(e,t){let n=Le(e);if(!n.some(a=>a.kind==="calculated"))return t;let r=t,i=dr(e,r);for(let a=0;a<=n.length;a++){let l={},c=!1;for(let[u,m]of Object.entries(r))i.has(u)?l[u]=m:c=!0;if(!c)break;r=l,i=dr(e,r)}let o=zt(n,r),s={};for(let[a,l]of Object.entries(t))o.calcIds.has(a)||(s[a]=l);for(let[a,l]of Object.entries(o.calc))i.has(a)&&(s[a]=l);return s}function qn(e){return e==null?!1:typeof e=="string"?e.trim()!=="":Array.isArray(e)?e.length>0:typeof e=="boolean"?e:typeof e=="object"?Object.keys(e).length>0:!0}function Gi(e,t){return e===t?!0:typeof e=="number"&&typeof t=="string"&&t.trim()!==""?Number(t)===e:typeof t=="number"&&typeof e=="string"&&e.trim()!==""?Number(e)===t:!1}function cr(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string"||e.trim()==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}function sa(e,t){let n=t(e.fieldId);switch(e.op){case"answered":return qn(n);case"not_answered":return!qn(n);case"eq":return Array.isArray(n)?n.some(r=>r===e.value):Gi(n,e.value);case"neq":return qn(n)?Array.isArray(n)?!n.some(r=>r===e.value):!Gi(n,e.value):!1;case"contains":return typeof n=="string"?n.toLowerCase().includes(String(e.value??"").toLowerCase()):Array.isArray(n)?n.some(r=>r===e.value):!1;case"gt":case"lt":{let r=cr(n),i=cr(e.value);return r!==null&&i!==null&&(e.op==="gt"?r>i:r<i)}}}function wr(e,t){return e.length===0?!0:e.every(n=>sa(n,t))}function bo(e,t){return!e.visibleIf||e.visibleIf.length===0?!0:wr(e.visibleIf,t)}function Wn(e,t,n,r,i,o){return s=>n.has(s)?r.has(s)?i.has(s)?o[s]:e[s]:void 0:t[s]}function zt(e,t){let n=new Set(e.map(l=>l.id)),r=e.filter(l=>l.kind==="calculated"),i=new Set(r.map(l=>l.id)),o={};for(let l of e){if(l.kind==="calculated")continue;let c=ho(l,t[l.id]);c!==void 0&&(l.kind==="repeating_group"&&(Array.isArray(c)?c.length:0)<Math.max(1,l.minInstances??1)||(o[l.id]=c))}let s=n,a={};for(let l=0;l<=e.length;l++){let c=a;if(r.length>0){c={...a};let h=Wn(o,t,n,s,i,c);for(let p of r){let b=s.has(p.id)?oa(p,h):null;b===null?delete c[p.id]:c[p.id]=b}}let u=Wn(o,t,n,s,i,c),m=new Set;for(let h of e)bo(h,u)&&m.add(h.id);let f=m.size===s.size&&[...m].every(h=>s.has(h))&&aa(a,c);if(s=m,a=c,f)break}return{visible:s,calc:a,calcIds:i,resolve:Wn(o,t,n,s,i,a)}}function aa(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>e[r]===t[r])}function vo(e,t){return zt(e,t).visible}function tn(e,t,n){let r=zt(Le(e),n);return t.blocks.filter(i=>ce(i)?r.visible.has(i.id):bo(i,r.resolve))}function Le(e){return e.pages.flatMap(t=>t.blocks.filter(ce))}function yo(e,t){let n=e.responseLimit?.scopeField;if(!n)return null;let r=t[n];return typeof r=="number"?Number.isFinite(r)?String(r):null:typeof r!="string"?null:r.trim()||null}function wo(e,t){let n=Le(e),r=vo(n,t);return n.filter(i=>r.has(i.id))}function gn(e,t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=zt(e.fields,n);return e.fields.filter(i=>r.visible.has(i.id))}function la(e,t){return zt(Le(e),t).resolve}function _o(e,t,n){let i=e.pages.find(s=>s.id===t)?.next;if(!i||i.length===0)return{linear:!0};let o=la(e,n);for(let s of i)if(wr(s.when,o))return s.to==="end"?{end:!0}:{to:s.to};return{linear:!0}}function ht(e,t,n){let r=[];if(e.pages.length===0)return r;let i=new Set,o=n===void 0?0:e.pages.findIndex(s=>s.id===n);for(let s=0;s<=e.pages.length;s++){let a=e.pages[o];if(!a||i.has(a.id))break;i.add(a.id),r.push(a.id);let l=_o(e,a.id,t);if("end"in l)break;if("to"in l){let c=e.pages.findIndex(u=>u.id===l.to);if(c<0)break;o=c}else if(o+=1,o>=e.pages.length)break}return r}function ca(e,t){return new Set(ht(e,t))}function ur(e,t,n){if("end"in _o(e,t,n))return!0;let r=ht(e,n);return r.length>0&&r[r.length-1]===t}function dr(e,t){let n=ca(e,t),r=vo(Le(e),t),i=new Set;for(let o of e.pages)if(n.has(o.id))for(let s of o.blocks)ce(s)&&r.has(s.id)&&i.add(s.id);return i}function xo(e,t){let n=dr(e,t);return Le(e).filter(r=>n.has(r.id))}var ut;function ua(){if(ut!==void 0)return ut??void 0;if(typeof Intl>"u"||typeof Intl.DisplayNames>"u"){ut=null;return}try{ut=new Intl.DisplayNames(void 0,{type:"region"})}catch{ut=null}return ut??void 0}function ko(e){try{return ua()?.of(e)??e}catch{return e}}var k=(e,t,n=[],r=[],i="")=>({iso2:e,name:ko(e),dialCode:t,lengths:n,groups:r,example:i}),da=[k("US","1",[10],[3,3,4],"2015550123"),k("CA","1",[10],[3,3,4],"5145550123"),k("GB","44",[10],[4,6],"7400123456"),k("AU","61",[9],[3,3,3],"412345678"),k("DE","49",[10,11],[4,7],"15123456789"),k("FR","33",[9],[1,2,2,2,2],"612345678"),k("IN","91",[10],[5,5],"8123456789"),k("DK","45",[8],[2,2,2,2],"32123456"),k("SE","46",[9],[2,3,4],"701234567"),k("NO","47",[8],[3,2,3],"40612345"),k("FI","358",[9,10],[2,3,4],"412345678"),k("NL","31",[9],[1,4,4],"612345678"),k("BE","32",[9],[3,2,2,2],"470123456"),k("ES","34",[9],[3,3,3],"612345678"),k("IT","39",[9,10],[3,3,4],"3123456789"),k("PT","351",[9],[3,3,3],"912345678"),k("IE","353",[9],[2,3,4],"851234567"),k("CH","41",[9],[2,3,2,2],"781234567"),k("AT","43",[10,11],[3,7],"6641234567"),k("PL","48",[9],[3,3,3],"512345678"),k("CZ","420",[9],[3,3,3],"601123456"),k("GR","30",[10],[3,3,4],"6912345678"),k("RO","40",[9],[3,3,3],"712345678"),k("HU","36",[9],[2,3,4],"201234567"),k("UA","380",[9],[2,3,2,2],"501234567"),k("RU","7",[10],[3,3,2,2],"9123456789"),k("TR","90",[10],[3,3,2,2],"5012345678"),k("IL","972",[9],[2,3,4],"501234567"),k("AE","971",[9],[2,3,4],"501234567"),k("SA","966",[9],[2,3,4],"512345678"),k("ZA","27",[9],[2,3,4],"711234567"),k("NG","234",[10],[3,3,4],"8021234567"),k("KE","254",[9],[3,3,3],"712123456"),k("EG","20",[10],[3,3,4],"1001234567"),k("BR","55",[10,11],[2,5,4],"11961234567"),k("MX","52",[10],[3,3,4],"2221234567"),k("AR","54",[10],[4,6],"1123456789"),k("CL","56",[9],[1,4,4],"221234567"),k("CO","57",[10],[3,3,4],"3211234567"),k("PE","51",[9],[3,3,3],"912345678"),k("CN","86",[11],[3,4,4],"13123456789"),k("JP","81",[10],[2,4,4],"9012345678"),k("KR","82",[9,10],[2,4,4],"1023456789"),k("SG","65",[8],[4,4],"81234567"),k("HK","852",[8],[4,4],"51234567"),k("TW","886",[9],[3,3,3],"912345678"),k("MY","60",[9,10],[2,3,4],"123456789"),k("ID","62",[10,11],[3,4,4],"81234567890"),k("TH","66",[9],[2,3,4],"812345678"),k("PH","63",[10],[3,3,4],"9171234567"),k("VN","84",[9],[3,3,3],"912345678"),k("PK","92",[10],[3,3,4],"3012345678"),k("BD","880",[10],[2,4,4],"1812345678"),k("NZ","64",[9,10],[2,3,4],"211234567"),k("SK","421",[9],[3,3,3],"912123456"),k("BG","359",[9],[2,3,4],"481234567"),k("HR","385",[8,9],[2,3,4],"921234567"),k("RS","381",[8,9],[2,3,4],"601234567"),k("SI","386",[8],[2,3,3],"31234567"),k("LT","370",[8],[3,2,3],"61234567"),k("LV","371",[8],[2,3,3],"21234567"),k("EE","372",[7,8],[3,4],"51234567"),k("IS","354",[7],[3,4],"6111234"),k("LU","352",[9],[3,3,3],"628123456"),k("MA","212",[9],[3,3,3],"650123456"),k("CR","506",[8],[4,4],"83123456"),k("EC","593",[9],[2,3,4],"991234567"),k("UY","598",[8],[1,3,4],"94231234"),k("QA","974",[8],[4,4],"33123456"),k("KW","965",[8],[4,4],"50012345")],fa="AD376 AF93 AG1 AI1 AL355 AM374 AO244 AS1 AW297 AX358 AZ994 BA387 BB1 BF226 BH973 BI257 BJ229 BL590 BM1 BN673 BO591 BQ599 BS1 BT975 BV47 BW267 BY375 BZ501 CC61 CD243 CF236 CG242 CI225 CK682 CM237 CU53 CV238 CW599 CX61 CY357 DJ253 DM1 DO1 DZ213 EH212 ER291 ET251 FJ679 FK500 FM691 FO298 GA241 GD1 GE995 GF594 GG44 GH233 GI350 GL299 GM220 GN224 GP590 GQ240 GS500 GT502 GU1 GW245 GY592 HN504 HT509 IM44 IO246 IQ964 IR98 JE44 JM1 JO962 KG996 KH855 KI686 KM269 KN1 KP850 KY1 KZ7 LA856 LB961 LC1 LI423 LK94 LR231 LS266 LY218 MC377 MD373 ME382 MF590 MG261 MH692 MK389 ML223 MM95 MN976 MO853 MP1 MQ596 MR222 MS1 MT356 MU230 MV960 MW265 MZ258 NA264 NC687 NE227 NF672 NI505 NP977 NR674 NU683 OM968 PA507 PF689 PG675 PM508 PN64 PR1 PS970 PW680 PY595 RE262 RW250 SB677 SC248 SD249 SH290 SJ47 SL232 SM378 SN221 SO252 SR597 SS211 ST239 SV503 SX1 SY963 SZ268 TC1 TD235 TF262 TG228 TJ992 TK690 TL670 TM993 TN216 TO676 TT1 TV688 TZ255 UG256 UZ998 VA379 VC1 VE58 VG1 VI1 VU678 WF681 WS685 XK383 YE967 YT262 ZM260 ZW263";function pa(e){let t=[];for(let n of e.trim().split(/\s+/)){let r=n.slice(0,2),i=n.slice(2);t.push({iso2:r,name:ko(r),dialCode:i,lengths:[],groups:[],example:""})}return t}var Ct=[...da,...pa(fa)],mt=ha(Ct);function ha(e){if(typeof Intl>"u"||typeof Intl.Collator>"u")return[...e].sort((n,r)=>n.iso2<r.iso2?-1:n.iso2>r.iso2?1:0);let t=new Intl.Collator(void 0,{sensitivity:"base"});return[...e].sort((n,r)=>t.compare(n.name,r.name))}var ma=new Map(Ct.map(e=>[e.iso2,e])),ga={"Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Johannesburg":"ZA","Africa/Lagos":"NG","Africa/Nairobi":"KE","America/Adak":"US","America/Anchorage":"US","America/Argentina/Buenos_Aires":"AR","America/Argentina/Cordoba":"AR","America/Argentina/Mendoza":"AR","America/Bahia":"BR","America/Belem":"BR","America/Bogota":"CO","America/Boise":"US","America/Boa_Vista":"BR","America/Cancun":"MX","America/Chicago":"US","America/Chihuahua":"MX","America/Campo_Grande":"BR","America/Costa_Rica":"CR","America/Cuiaba":"BR","America/Denver":"US","America/Detroit":"US","America/Edmonton":"CA","America/Fortaleza":"BR","America/Guayaquil":"EC","America/Halifax":"CA","America/Hermosillo":"MX","America/Indiana/Indianapolis":"US","America/Indianapolis":"US","America/Juneau":"US","America/Kentucky/Louisville":"US","America/Lima":"PE","America/Los_Angeles":"US","America/Maceio":"BR","America/Manaus":"BR","America/Matamoros":"MX","America/Mazatlan":"MX","America/Merida":"MX","America/Mexico_City":"MX","America/Moncton":"CA","America/Monterrey":"MX","America/Montevideo":"UY","America/New_York":"US","America/Noronha":"BR","America/Nome":"US","America/North_Dakota/Center":"US","America/Ojinaga":"MX","America/Phoenix":"US","America/Porto_Velho":"BR","America/Punta_Arenas":"CL","America/Recife":"BR","America/Regina":"CA","America/Rio_Branco":"BR","America/Santiago":"CL","America/Sao_Paulo":"BR","America/Sitka":"US","America/St_Johns":"CA","America/Tijuana":"MX","America/Toronto":"CA","America/Vancouver":"CA","America/Whitehorse":"CA","America/Winnipeg":"CA","America/Yakutat":"US","Asia/Bangkok":"TH","Asia/Calcutta":"IN","Asia/Dacca":"BD","Asia/Dhaka":"BD","Asia/Dubai":"AE","Asia/Hong_Kong":"HK","Asia/Ho_Chi_Minh":"VN","Asia/Jakarta":"ID","Asia/Jerusalem":"IL","Asia/Karachi":"PK","Asia/Kolkata":"IN","Asia/Kuala_Lumpur":"MY","Asia/Kuwait":"KW","Asia/Manila":"PH","Asia/Qatar":"QA","Asia/Riyadh":"SA","Asia/Seoul":"KR","Asia/Shanghai":"CN","Asia/Saigon":"VN","Asia/Singapore":"SG","Asia/Taipei":"TW","Asia/Tel_Aviv":"IL","Asia/Tokyo":"JP","Asia/Urumqi":"CN","Atlantic/Reykjavik":"IS","Australia/Adelaide":"AU","Australia/Brisbane":"AU","Australia/Darwin":"AU","Australia/Hobart":"AU","Australia/Melbourne":"AU","Australia/Perth":"AU","Australia/Sydney":"AU","Europe/Amsterdam":"NL","Europe/Athens":"GR","Europe/Belgrade":"RS","Europe/Berlin":"DE","Europe/Bratislava":"SK","Europe/Brussels":"BE","Europe/Bucharest":"RO","Europe/Budapest":"HU","Europe/Copenhagen":"DK","Europe/Dublin":"IE","Europe/Helsinki":"FI","Europe/Zagreb":"HR","Europe/Istanbul":"TR","Europe/Kiev":"UA","Europe/Kyiv":"UA","Europe/Lisbon":"PT","Europe/Ljubljana":"SI","Europe/London":"GB","Europe/Luxembourg":"LU","Europe/Madrid":"ES","Europe/Moscow":"RU","Europe/Oslo":"NO","Europe/Paris":"FR","Europe/Prague":"CZ","Europe/Riga":"LV","Europe/Rome":"IT","Europe/Sofia":"BG","Europe/Stockholm":"SE","Europe/Tallinn":"EE","Europe/Vienna":"AT","Europe/Vilnius":"LT","Europe/Warsaw":"PL","Europe/Zurich":"CH","Pacific/Auckland":"NZ"};function _r(e){let t=e.toUpperCase();return/^[A-Z]{2}$/.test(t)?String.fromCodePoint(...[...t].map(n=>127462+n.charCodeAt(0)-65)):"\u{1F3F3}\uFE0F"}function bn(e){return e?ma.get(e.toUpperCase()):void 0}function $o(e){return bn(e?ga[e]:void 0)}function ba(e){let t;for(let n of Ct)e.startsWith(n.dialCode)&&(!t||n.dialCode.length>t.dialCode.length)&&(t=n);return t}function Ne(e){return e.replace(/[^\d]/g,"")}function It(e,t){let n=Ne(t);if(!n)return"";let r=e?.groups?.length?e.groups:[],i=[],o=0;for(let s of r){if(o>=n.length)break;i.push(n.slice(o,o+s)),o+=s}for(;o<n.length;)i.push(n.slice(o,o+3)),o+=3;return i.join(" ")}function So(e,t){let n=Ne(t);return n?`+${e.dialCode}${n}`:""}function Mt(e,t,n){let r=(e??"").trim(),i=r.startsWith("+"),o=Ne(r);if(i){if(!o)return{national:"",e164:"",pending:!0,raw:r};let s=n?.previousDigits?Ne(n.previousDigits):"";if(s&&o===s)return{national:o,e164:`+${o}`,pending:!0,raw:r};let a=ba(o);if(a){let l=o.slice(a.dialCode.length);return{country:a,national:l,e164:`+${o}`}}return{national:o,e164:`+${o}`,pending:!0,raw:r}}if(!o)return{country:t,national:"",e164:""};if(t){let s=o.startsWith(t.dialCode)?o.slice(t.dialCode.length):o;return{country:t,national:s,e164:`+${t.dialCode}${s}`}}return{national:o,e164:`+${o}`}}function va(e){let{country:t,national:n,e164:r}=Mt(e);if(!r)return!1;let i=Ne(r).length;return i<8||i>15?!1:t?.lengths.length?t.lengths.includes(n.length):n.length>=4}var ya=8;function Ao(e,t){if(!e||!t||typeof window>"u")return"below";let n=ya,r=document.documentElement.clientWidth||window.innerWidth,i=document.documentElement.clientHeight||window.innerHeight,o=e.getBoundingClientRect(),s=Math.max(0,i-o.bottom-n),a=Math.max(0,o.top-n),l=s<t.scrollHeight&&a>s?"above":"below",u=Math.max(0,Math.min(l==="above"?a:s,i-n*2)),m=Math.max(0,r-n*2);t.style.setProperty("--fillo-phone-popover-max-height",`${Math.floor(u)}px`),t.style.setProperty("--fillo-phone-popover-max-width",`${Math.floor(m)}px`),t.style.setProperty("--fillo-phone-popover-offset-x","0px");let f=Math.min(t.offsetWidth,m),p=getComputedStyle(e).direction==="rtl"?o.right-f:o.left,b=0,v=p+f-(r-n);v>0&&(b-=v);let y=n-(p+b);return y>0&&(b+=y),t.style.setProperty("--fillo-phone-popover-offset-x",`${Math.round(b)}px`),l}var Nt="This field is required",P={back:"Back",next:"Next",submit:"Submit",submitting:"Submitting\u2026",uploading:"Uploading\u2026",optional:" (optional)",other:"Other",otherPrompt:"Other \u2014 please specify",otherPlaceholder:"Your answer",choosePlaceholder:"Choose\u2026",successTitle:"Thanks!",successMessage:"Your response has been recorded.",closed:"This form is no longer accepting responses.",notLive:"This form isn't live yet.",notOpenTitle:"This form isn't open yet",notOpenBody:"The form owner is still setting things up. Please check back soon.",closedTitle:"Responses are closed",submitFailed:"This form can't submit right now. Please try again in a moment.",loadFailedNotFound:"Form not found. Check the link or ask the form owner for help.",loadFailedNetwork:"Couldn't reach the server \u2014 check your connection and try again.",loadFailed:"This form could not be loaded.",renderFailed:"This form could not be rendered.",resumeNotice:"Picked up where you left off.",editNotice:"You're updating your earlier response.",resumeStartOver:"Start over",challengeUnavailable:"The verification check couldn't load. Refresh the page and try again."},qi={submitFailed:P.submitFailed,loadFailedNotFound:P.loadFailedNotFound,loadFailedNetwork:P.loadFailedNetwork,formUnavailable:"This form is unavailable.",formClosed:P.closed,submitRateLimited:"Too many responses are being submitted right now. Wait a moment, then try again.",respondentUnrecognized:"This form couldn't verify who is responding. Ask the form owner for help.",fileUnavailable:"One of the uploaded files is no longer available. Remove it and upload it again.",scopeMissing:"We couldn't tell which entry this response belongs to. Answer the required field and try again.",challengeIncomplete:"Please complete the verification check, then submit.",challengeRetry:"That verification didn't go through. Please complete the check again and resubmit.",reviewAnswers:"We couldn't submit \u2014 please review your answers."};var wa={short_text:"Enter your answer",long_text:"Enter your answer",email:"Enter an email address",url:"Enter a URL",phone:"Enter a phone number",number:"Enter a number",select:"Choose an option",dropdown:"Choose an option",multi_select:"Select at least one option",checkbox:"Select this checkbox",rating:"Choose a rating",linear_scale:"Choose a value",ranking:"Rank every option",matrix:"Answer every row",signature:"Add your signature",date:"Enter a date",file_upload:"Add a file"};function _a(e){return wa[e.kind]??Nt}var R={previewSkip:"Skip",required:Nt,requiredForField:_a,resumeLinkExpired:"That saved-progress link expired or was already used \u2014 start again below.",alreadyAnswered:"You've already answered this form.",uploadRetry:"Retry",uploadCancel:"Cancel",uploadRemove:"Remove",uploadDismiss:"Dismiss",uploadingFile:(e,t)=>`Uploading \xB7 ${e}% \xB7 ${t}`,uploadedFile:e=>`Uploaded \xB7 ${e}`,uploadsDisabled:"Connect this form to Fillo to enable uploads",uploadsRenderOnly:"Uploads are unavailable in this render-only preview",uploadsUnavailable:"Uploads are temporarily unavailable",uploadUnavailable:"We couldn't upload this file right now. Try again in a moment.",uploadFailed:"Upload failed \u2014 try again",dropzoneTitle:e=>`Drop ${e?"files":"a file"} here or click to browse`,dropzoneHint:e=>`Up to ${e} MB per file`,fileTooLarge:e=>`Larger than ${e} MB limit`,filesUploading:e=>`Uploading ${e} ${e===1?"file":"files"}, please wait\u2026`,uploadsFailed:e=>`${e} ${e===1?"upload":"uploads"} failed.`,filesUploaded:e=>`${e} ${e===1?"file":"files"} uploaded.`,submittingAnnouncement:"Submitting your response\u2026",errorSummaryTitle:"Check these fields",rankingPosition:(e,t,n)=>`${e}, position ${t} of ${n}`,groupAdd:"Add another",groupInstanceLabel:(e,t,n)=>`${e} ${t} of ${n}`,groupRemoveLabel:(e,t)=>`Remove ${e} ${t}`,groupInstanceAdded:(e,t,n)=>`${e} ${t} added, ${t} of ${n}`,groupInstanceRemoved:(e,t)=>t===0?`${e} removed, none left`:`${e} removed, ${t} remaining`,phoneCountrySelected:e=>`${e} selected`,phoneResultsCount:e=>`${e} ${e===1?"result":"results"}`,signatureEmpty:"No signature yet",signatureSigned:"Signature saved"};function Fo(e,t){return t.requiredForField?.(e)??t.required}var xa=Ft({fileId:fe().check(tt(1)),name:fe(),size:Ui().check(jn()),mime:fe(),url:ge(fe())});function Kn(e,t){let n=Math.max(0,e.minInstances??1);return t<n?`Add at least ${n} ${n===1?"entry":"entries"}`:Number.isFinite(e.maxInstances)&&t>e.maxInstances?`At most ${e.maxInstances} ${e.maxInstances===1?"entry":"entries"}`:null}function fr(e,t){if(mn(t))return e.kind==="calculated"?null:e.kind==="repeating_group"?Kn(e,0):e.required?Nt:null;switch(e.kind){case"short_text":case"long_text":{if(typeof t!="string")return"Expected text";if(e.maxLength&&t.length>e.maxLength)return`Must be at most ${e.maxLength} characters`;let n=e.kind==="long_text"?2e4:2e3;return!e.maxLength&&t.length>n?"Answer is too long":null}case"email":return typeof t!="string"?"Enter a valid email address":e.maxLength&&t.length>e.maxLength?`Must be at most ${e.maxLength} characters`:en().safeParse(t).success?null:"Enter a valid email address";case"url":{if(typeof t!="string")return"Enter a valid URL (including https://)";if(e.maxLength&&t.length>e.maxLength)return`Must be at most ${e.maxLength} characters`;try{let n=new URL(t);if(n.protocol!=="http:"&&n.protocol!=="https:")return"Enter an http(s) URL"}catch{return"Enter a valid URL (including https://)"}return null}case"phone":return typeof t!="string"||!va(t)?"Enter a valid phone number":null;case"number":{let n=typeof t=="string"?Number(t):t;return typeof n!="number"||!Number.isFinite(n)?"Enter a number":e.min!==void 0&&n<e.min?`Must be at least ${e.min}`:e.max!==void 0&&n>e.max?`Must be at most ${e.max}`:null}case"select":case"dropdown":return typeof t!="string"||t===""?"Pick an option":e.options.some(n=>n.id===t)||e.allowOther&&t.length<=500?null:"Pick a valid option";case"multi_select":{if(!Array.isArray(t))return"Pick at least one option";let n=new Set(e.options.map(s=>s.id)),r=t,i=0,o=new Set;for(let s of r){if(typeof s!="string")return"Pick valid options";if(o.has(s))return"Pick each option only once";if(o.add(s),!n.has(s)){if(e.allowOther!==!0||s.length===0||s.length>500)return"Pick valid options";if(++i>1)return"Only one 'Other' answer is allowed"}}return null}case"checkbox":return typeof t=="boolean"?null:"Invalid value";case"rating":{let n=e.max??5,r=typeof t=="string"?Number(t):t;return typeof r!="number"||!Number.isInteger(r)||r<1||r>n?`Pick a rating between 1 and ${n}`:null}case"linear_scale":{let n=e.min??1,r=e.max??10,i=typeof t=="string"?Number(t):t;return typeof i!="number"||!Number.isInteger(i)||i<n||i>r?`Pick a value between ${n} and ${r}`:null}case"ranking":{if(!Array.isArray(t))return"Drag the options into order";let n=e.options.map(i=>i.id).sort(),r=[...t].sort();return n.length!==r.length||n.some((i,o)=>i!==r[o])?"Rank every option":null}case"matrix":{if(typeof t!="object"||t===null||Array.isArray(t))return"Answer the grid";let n=t,r=new Set(e.columns.map(o=>o.id)),i=new Set(e.rows.map(o=>o.id));for(let[o,s]of Object.entries(n))if(!i.has(o)||!r.has(s))return"Invalid grid answer";return e.required&&Object.keys(n).length<e.rows.length?"Answer every row":null}case"signature":return typeof t!="string"||!t.startsWith("data:image/")?"Sign in the box":null;case"hidden":return typeof t=="string"?null:"Invalid value";case"calculated":return null;case"repeating_group":{if(!Array.isArray(t))return Kn(e,0);let n=t;for(let r of n)if(!r||typeof r!="object"||Array.isArray(r))return"Invalid value";return Kn(e,n.length)}case"custom":return null;case"date":{if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(t))return"Enter a valid date";let[n,r,i]=t.split("-").map(Number),o=new Date(Date.UTC(n,r-1,i));return o.getUTCFullYear()!==n||o.getUTCMonth()!==r-1||o.getUTCDate()!==i?"Enter a valid date":null}case"file_upload":{let n=Oe(xa).safeParse(t);if(!n.success)return"Upload did not complete";let r=e.maxFiles??1;return n.data.length>r?`At most ${r} file${r===1?"":"s"}`:null}}}function pr(e,t){let n={},r={};if(e.kind!=="calculated"){let i=po(e,t);if(e.kind==="repeating_group")ka(e,i,n,r);else{let o=fr(e,i);o?n[e.id]=o:mn(i)||(r[e.id]=i)}}return{ok:Object.keys(n).length===0,errors:n,data:r}}function Eo(e,t){let n=xo(e,t),r={},i={};for(let o of n){let s=pr(o,t[o.id]);Object.assign(r,s.errors),Object.assign(i,s.data)}return{ok:Object.keys(r).length===0,errors:r,data:i}}function ka(e,t,n,r){let i=fr(e,t);if(i&&(n[e.id]=i),!Array.isArray(t))return;let o=t,s=[];for(let a=0;a<o.length;a++){let l=o[a];if(!l||typeof l!="object"||Array.isArray(l))continue;let c={};for(let u of gn(e,l)){let m=l[u.id],f=fr(u,m);f?n[`${e.id}.${a}.${u.id}`]=f:mn(m)||(c[u.id]=m)}s.push(c)}!i&&s.length>0&&(r[e.id]=s)}var $a=["short_text","long_text","email","url","phone","number","select","multi_select","dropdown","checkbox","rating","linear_scale","ranking","matrix","signature","date","file_upload","hidden","calculated","repeating_group","custom"],Sa=["heading","paragraph","divider"],Aa=[...$a,...Sa],xr=fe().check(tt(1),le(128)),Jn=Hn({id:xr,label:fe().check(le(1e3)),icon:ge(At())}),Fa=Hn({id:xr,kind:Vi(Aa),label:ge(fe().check(le(2e3))),options:ge(Oe(Jn).check(le(200))),rows:ge(Oe(Jn).check(le(200))),columns:ge(Oe(Jn).check(le(200)))}),Ea=Ft({id:xr,title:ge(fe().check(le(500))),blocks:Oe(Fa).check(le(500)),next:ge(At())}),za=Ft({version:Hi(1),title:Gn(ge(fe().check(le(2e3))),""),description:ge(fe().check(le(5e3))),pages:Oe(Ea).check(tt(1),le(50)),settings:Gn(ge(ji(fe(),At())),{})}),Ca=1,hr=1,mr="0.30.1";function _e(e,t,n=""){return typeof e=="string"?e.trim().slice(0,t):n}function K(e,t){let n=_e(e,t);return n===""?void 0:n}function nn(e,t){if(typeof e!="string")return;let n=e.slice(0,t);return n.trim()===""?void 0:n}function Me(e){return typeof e=="boolean"?e:void 0}function Se(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Ie(e,t,n,r){let i=Se(e);return i===void 0?r:Math.max(t,Math.min(n,Math.round(i)))}function rn(e,t=200){return Array.isArray(e)?e.slice(0,t).flatMap(n=>{if(!n||typeof n!="object")return[];let r=n,i=_e(r.id,128),o=_e(r.label,1e3),s=r.icon==="thumbs_up"||r.icon==="thumbs_down"?r.icon:void 0;return i&&o?[j({id:i,label:o,icon:s})]:[]}):[]}function fn(e){let t=new Set;for(let{id:n}of e){if(t.has(n))return n;t.add(n)}}function kr(e){if(!Array.isArray(e))return;let t=e.slice(0,20).flatMap(n=>{if(!n||typeof n!="object")return[];let r=n,i=r.op;if(i!=="eq"&&i!=="neq"&&i!=="contains"&&i!=="gt"&&i!=="lt"&&i!=="answered"&&i!=="not_answered")return[];let o=_e(r.fieldId,128);if(!o)return[];let s=r.value,a=typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:void 0;return[{fieldId:o,op:i,...a!==void 0?{value:a}:{}}]});return t.length?t:void 0}function zo(e,t,n,r){let i=t.get(e);if(i===void 0)return n.has(e);if(r.has(e))return!0;r.add(e);for(let o of i)if(!zo(o,t,n,r))return!1;return!0}function Ia(e,t,n,r,i){if(!Array.isArray(e))return;let o=e.slice(0,50).flatMap(s=>{if(!s||typeof s!="object")return[];let a=s,l=typeof a.to=="string"?a.to:void 0;if(!l||l!=="end"&&!t.has(l))return[];if(l===n)return[];let c=a.when;if(c!==void 0&&!Array.isArray(c))return[];let u=kr(c);return Array.isArray(c)&&c.length>0&&u===void 0?[]:u&&u.some(m=>!zo(m.fieldId,i,r,new Set))?[]:[{when:u??[],to:l}]});return o.length?o:void 0}var Ma=["number","rating","linear_scale","calculated"];function Je(e,t=0){if(t>32||!e||typeof e!="object"||Array.isArray(e))return null;let n=e;switch(n.op){case"value":{let r=_e(n.fieldId,128);return r?{op:"value",fieldId:r}:null}case"const":{let r=Se(n.value);return r===void 0?null:{op:"const",value:r}}case"add":case"mul":case"min":case"max":{if(!Array.isArray(n.args)||n.args.length<1||n.args.length>50)return null;let r=[];for(let i of n.args){let o=Je(i,t+1);if(!o)return null;r.push(o)}return{op:n.op,args:r}}case"sub":case"div":{let r=Je(n.left,t+1),i=Je(n.right,t+1);return r&&i?{op:n.op,left:r,right:i}:null}case"round":{let r=Je(n.arg,t+1);return r?j({op:"round",arg:r,decimals:Se(n.decimals)===void 0?void 0:Ie(n.decimals,0,6,0)}):null}case"if":{if(!Array.isArray(n.when))return null;let r=kr(n.when)??[];if(r.length!==n.when.length)return null;let i=Je(n.then,t+1),o=Je(n.else,t+1);return i&&o?{op:"if",when:r,then:i,else:o}:null}default:return null}}function Xe(e,t,n){switch(e.op){case"value":t.add(e.fieldId);return;case"const":return;case"add":case"mul":case"min":case"max":for(let r of e.args)Xe(r,t,n);return;case"sub":case"div":Xe(e.left,t,n),Xe(e.right,t,n);return;case"round":Xe(e.arg,t,n);return;case"if":for(let r of e.when)n.add(r.fieldId);Xe(e.then,t,n),Xe(e.else,t,n);return}}function Na(e,t){let n=new Map;for(let s of e)for(let a of s.blocks)ce(a)&&n.set(a.id,a.kind);let r=new Map;for(let s of e)for(let a of s.blocks){if(a.kind!=="calculated")continue;let l=Je(a.calc);if(!l)return`Field ${a.id} has a malformed calc expression \u2014 build it from value/const/add/sub/mul/div/min/max/round/if nodes`;a.calc=l;let c=new Set,u=new Set;Xe(l,c,u);for(let m of c){let f=n.get(m);if(f===void 0){let h=t.get(m);return h!==void 0?`Calculated field ${a.id} references ${m}, which is a child of repeating group ${h} \u2014 calculations can't reach inside a repeating group (calc operands must be top-level fields)`:`Calculated field ${a.id} references a missing field: ${m} \u2014 remove the reference or restore that field`}if(!Ma.includes(f))return`Calculated field ${a.id} references non-numeric field ${m} (${f}) \u2014 calculations can read number, rating, linear_scale, and calculated fields only`}r.set(a.id,[...c,...u].filter(m=>n.get(m)==="calculated"))}let i=new Map,o=(s,a)=>{let l=i.get(s);if(l==="done")return null;if(l==="visiting"){let c=[...a.slice(a.indexOf(s)),s].join(" \u2192 ");return`Calculated field ${s} depends on its own result (${c}) \u2014 break the cycle so the value can be computed`}i.set(s,"visiting");for(let c of r.get(s)??[]){let u=o(c,[...a,s]);if(u)return u}return i.set(s,"done"),null};for(let s of r.keys()){let a=o(s,[]);if(a)return a}return null}var Wi=100,Ki=5e3;function ot(e){switch(e.op){case"value":case"const":return 1;case"add":case"mul":case"min":case"max":return 1+e.args.reduce((t,n)=>t+ot(n),0);case"sub":case"div":return 1+ot(e.left)+ot(e.right);case"round":return 1+ot(e.arg);case"if":return 1+ot(e.then)+ot(e.else)}}function La(e){let t=0,n=0;for(let r of e)for(let i of r.blocks)i.kind==="calculated"&&(t+=1,n+=ot(i.calc));return t>Wi?`Form has ${t} calculated fields \u2014 the maximum is ${Wi}; remove some or consolidate them into fewer expressions`:n>Ki?`Calculated expressions total ${n} operations \u2014 the maximum is ${Ki} across the form; simplify or split up the calculations`:null}var Ji=["short_text","long_text","email","url","phone","number","select","multi_select","dropdown","checkbox","date","rating","linear_scale"],Xi=12,Yi=18e4;function Ta(e){let t=e.id.length+20;switch(e.kind){case"short_text":case"email":case"url":return t+(e.maxLength??2e3);case"long_text":return t+(e.maxLength??2e4);case"phone":return t+32;case"number":return t+32;case"select":case"dropdown":{let n=e.options.reduce((r,i)=>Math.max(r,i.id.length),0);return t+Math.max(n,e.allowOther?500:0)}case"multi_select":{let n=e.options.reduce((r,i)=>r+i.id.length+3,0);return t+n+(e.allowOther?500:0)}case"checkbox":return t+8;case"date":return t+16;case"rating":case"linear_scale":return t+8;default:return t+64}}function Pa(e){return e.fields.reduce((n,r)=>n+Ta(r),24)*(Number.isFinite(e.maxInstances)?e.maxInstances:0)}function Ra(e){for(let t of e)for(let n of t.blocks){if(n.kind!=="repeating_group")continue;if(!Number.isInteger(n.maxInstances)||n.maxInstances<1||n.maxInstances>20)return`Repeating group ${n.id} needs maxInstances to be a whole number between 1 and 20`;let r=n.minInstances??1;if(!Number.isInteger(r)||r<0||r>n.maxInstances)return`Repeating group ${n.id} needs minInstances to be a whole number between 0 and maxInstances (${n.maxInstances})`;if(n.minInstances=r,n.fields.length===0)return`Repeating group ${n.id} has no template fields \u2014 add at least one field to repeat`;if(n.fields.length>Xi)return`Repeating group ${n.id} has ${n.fields.length} template fields \u2014 the maximum is ${Xi}; split it into fewer fields`;for(let a of n.fields)if(!Ji.includes(a.kind))return`Repeating group ${n.id} has a "${a.kind}" child (${a.id}) \u2014 allowed child kinds are ${Ji.join(", ")}`;let i=fn(n.fields);if(i)return`Duplicate child id in repeating group ${n.id}: ${i}`;let o=new Set(n.fields.map(a=>a.id));for(let a of n.fields)for(let l of a.visibleIf??[])if(!o.has(l.fieldId))return`Field ${a.id} in repeating group ${n.id} has a visibleIf referencing "${l.fieldId}" \u2014 a child's visibleIf can only reference another field in the SAME group`;let s=Pa(n);if(s>Yi)return`Repeating group ${n.id} could reach ~${Math.ceil(s/1e3)}KB at ${n.maxInstances} instances \u2014 the maximum is ~${Math.round(Yi/1e3)}KB; lower maxInstances, shorten text limits, or trim the template`}return null}function Oa(e){let t=new Set;for(let r of e)for(let i of r.blocks)ce(i)&&t.add(i.id);let n=new Map;for(let r of e)for(let i of r.blocks)if(i.kind==="repeating_group")for(let o of i.fields)!t.has(o.id)&&!n.has(o.id)&&n.set(o.id,i.id);return n}function Za(e,t,n){for(let r of e)for(let i of r.blocks)for(let o of i.visibleIf??[]){let s=n.get(o.fieldId);if(s!==void 0)return`Field ${i.id}'s visibleIf references "${o.fieldId}", which is a child of repeating group ${s} \u2014 fields outside a repeating group can't reference its children`}for(let r of t)if(Array.isArray(r.next))for(let i of r.next){if(!i||typeof i!="object")continue;let o=i.when;if(Array.isArray(o))for(let s of o){if(!s||typeof s!="object")continue;let a=s.fieldId;if(typeof a!="string")continue;let l=n.get(a);if(l!==void 0)return`A jump rule on page ${r.id} references "${a}", which is a child of repeating group ${l} \u2014 jumps can't reference a repeating group's children`}}return null}function Co(e){return{id:_e(e.id,128),visibleIf:kr(e.visibleIf)}}function te(e,t){return{...Co(e),kind:t,label:_e(e.label,2e3,"Untitled field"),description:K(e.description,5e3),required:Me(e.required),placeholder:K(e.placeholder,500)}}function Qi(e){let t=K(e,2e3);if(t)try{let n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"?t:void 0}catch{return}}function Da(e){if(!e||typeof e!="object")return;let t=e,n=t.by==="browser"||t.by==="field"||t.by==="identify"||t.by==="email"?t.by:void 0;if(!n)return;let r=n==="field"?K(t.field,128):void 0;if(n==="field"&&!r)return;let i=K(t.scopeField,128),o=t.onRepeat==="update"&&(n==="identify"||n==="email")?"update":"keep";return{by:n,...r?{field:r}:{},...i?{scopeField:i}:{},onRepeat:o}}function Ua(e){if(!e||typeof e!="object")return;let t=e,n=t.unverified==="allow"||t.unverified==="quarantine"?t.unverified:void 0,r=t.challenge==="turnstile"?"turnstile":void 0;if(!(!n&&!r))return{...n?{unverified:n}:{},...r?{challenge:r}:{}}}function Ba(e){let t=e&&typeof e=="object"?e:{};return{submitMode:t.submitMode==="button"||t.submitMode==="auto"?t.submitMode:void 0,submitLabel:K(t.submitLabel,100),successTitle:K(t.successTitle,200),successMessage:K(t.successMessage,5e3),redirectUrl:Qi(t.redirectUrl),showProgress:Me(t.showProgress),responseLimit:Da(t.responseLimit),trust:Ua(t.trust),notifyEmail:en().check(le(254)).safeParse(t.notifyEmail).success?t.notifyEmail:void 0,notifyEmailIncludeAnswers:Me(t.notifyEmailIncludeAnswers),notifyEmailAnswerFields:Oe(fe().check(tt(1),le(128),Vn(/\S/))).check(le(500)).safeParse(t.notifyEmailAnswerFields).success?[...new Set(t.notifyEmailAnswerFields.map(r=>r.trim()))]:void 0,notifyEmailReplyToField:K(t.notifyEmailReplyToField,128),sendReceipt:Me(t.sendReceipt),saveProgress:Me(t.saveProgress),draftAnswersVisible:Me(t.draftAnswersVisible),resumeEmails:Me(t.resumeEmails),resumeUrl:Qi(t.resumeUrl),draftDigest:Me(t.draftDigest)}}function j(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Io(e){if(!e||typeof e!="object")return null;let t=e,n=t.kind,r=Co(t);if(!r.id||typeof n!="string")return null;switch(n){case"heading":return j({...r,kind:n,text:_e(t.text,2e3,"Section")});case"paragraph":return j({...r,kind:n,text:_e(t.text,5e3)});case"divider":return j({...r,kind:n});case"short_text":case"email":case"url":return j({...te(t,n),maxLength:Se(t.maxLength)===void 0?void 0:Ie(t.maxLength,1,2e3,2e3)});case"phone":{let i=K(t.defaultCountry,2)?.toUpperCase();return j({...te(t,n),defaultCountry:i&&/^[A-Z]{2}$/.test(i)?i:void 0})}case"long_text":return j({...te(t,n),maxLength:Se(t.maxLength)===void 0?void 0:Ie(t.maxLength,1,2e4,2e4)});case"number":return j({...te(t,n),min:Se(t.min),max:Se(t.max),decimals:Se(t.decimals)===void 0?void 0:Ie(t.decimals,0,6,0),prefix:nn(t.prefix,100),suffix:nn(t.suffix,100),notation:t.notation==="grouped"?"grouped":t.notation==="grouped-comma"?"grouped-comma":t.notation==="grouped-dot"?"grouped-dot":void 0});case"select":case"multi_select":case"dropdown":{let i=rn(t.options);return i.length===0?null:j({...te(t,n),options:i,allowOther:Me(t.allowOther),shuffleOptions:Me(t.shuffleOptions)})}case"checkbox":{let i=t.appearance==="toggle"?"toggle":void 0;return j({...te(t,n),appearance:i})}case"signature":return j(te(t,n));case"date":return j({...te(t,n),defaultToday:t.defaultToday===!0?!0:void 0});case"rating":{let i=Ie(t.max,1,10,5);return j({...te(t,n),max:i,insightsMetric:t.insightsMetric==="csat"&&i===5?"csat":void 0})}case"linear_scale":{let i=Ie(t.min,0,9,1),o=Ie(t.max,i+1,10,10),s=t.insightsMetric==="nps"&&i===0&&o===10?"nps":t.insightsMetric==="csat"&&i===1&&o===5?"csat":void 0;return j({...te(t,n),min:i,max:o,minLabel:K(t.minLabel,100),maxLabel:K(t.maxLabel,100),insightsMetric:s})}case"ranking":{let i=rn(t.options);return i.length<2?null:j({...te(t,n),options:i})}case"matrix":{let i=rn(t.rows),o=rn(t.columns);return i.length===0||o.length===0?null:j({...te(t,n),rows:i,columns:o})}case"hidden":return j({...te(t,n),required:!1,paramName:K(t.paramName,128),defaultValue:K(t.defaultValue,1e3)});case"calculated":return j({...te(t,n),required:!1,calc:t.calc,decimals:Se(t.decimals)===void 0?void 0:Ie(t.decimals,0,6,0),prefix:nn(t.prefix,100),suffix:nn(t.suffix,100)});case"file_upload":return j({...te(t,n),maxFiles:Ie(t.maxFiles,1,na,1),maxFileSizeMb:Ie(t.maxFileSizeMb,1,5e3,500),accept:Array.isArray(t.accept)?t.accept.flatMap(i=>{let o=K(i,100);return o?[o]:[]}).slice(0,50):void 0});case"repeating_group":{let o=(Array.isArray(t.fields)?t.fields:[]).slice(0,50).flatMap(s=>{let a=Io(s);return a&&ce(a)?[a]:[]});return j({...te(t,n),required:!1,fields:o,maxInstances:Se(t.maxInstances)??Number.NaN,minInstances:Se(t.minInstances),addLabel:K(t.addLabel,100),itemLabel:K(t.itemLabel,100)})}case"custom":return j({...te(t,n),component:_e(t.component,128),config:t.config&&typeof t.config=="object"&&!Array.isArray(t.config)?t.config:void 0});default:return null}}function Ye(e){let t=za.safeParse(e);if(!t.success){let v=t.error.issues[0],y=v?.path.join(".");return{ok:!1,error:v?`${y?`${y}: `:""}${v.message}`:"Invalid schema"}}if(t.data.version>Ca)return{ok:!1,error:`Unsupported schema version: ${t.data.version}`};let n=t.data.pages.map(v=>{let y=v.blocks.flatMap(F=>{let I=Io(F);return I?[I]:[]});return{id:_e(v.id,128),title:K(v.title,500),blocks:y,next:v.next}}),r=new Set(n.map(v=>v.id)),i=new Map;for(let v of n)for(let y of v.blocks){if(y.kind!=="calculated")continue;let F=new Set,I=Je(y.calc);if(I){let ee=new Set,xe=new Set;Xe(I,ee,xe);for(let M of ee)F.add(M);for(let M of xe)F.add(M)}i.set(y.id,F)}let o=new Set,s=n.map(v=>{for(let y of v.blocks)ce(y)&&o.add(y.id);return j({id:v.id,title:v.title,blocks:v.blocks,next:Ia(v.next,r,v.id,new Set(o),i)})}),a=new Set,l=new Set;for(let v of s){if(!v.id)return{ok:!1,error:"Page ids cannot be blank"};if(a.has(v.id))return{ok:!1,error:`Duplicate page id: ${v.id}`};a.add(v.id);for(let y of v.blocks){if(l.has(y.id))return{ok:!1,error:`Duplicate block id: ${y.id}`};if(l.add(y.id),y.kind==="number"&&y.min!==void 0&&y.max!==void 0&&y.min>y.max)return{ok:!1,error:`Field ${y.id} has min greater than max`};if(y.kind==="select"||y.kind==="multi_select"||y.kind==="dropdown"||y.kind==="ranking"){let F=fn(y.options);if(F)return{ok:!1,error:`Duplicate option id in field ${y.id}: ${F}`}}else if(y.kind==="matrix"){let F=fn(y.rows);if(F)return{ok:!1,error:`Duplicate matrix row id in field ${y.id}: ${F}`};let I=fn(y.columns);if(I)return{ok:!1,error:`Duplicate matrix column id in field ${y.id}: ${I}`}}}}let c=Ra(s);if(c)return{ok:!1,error:c};let u=Oa(s),m=Za(s,n,u);if(m)return{ok:!1,error:m};let f=Na(s,u);if(f)return{ok:!1,error:f};let h=La(s);if(h)return{ok:!1,error:h};if(s.every(v=>v.blocks.length===0))return{ok:!1,error:"Schema must contain at least one valid block"};let p={version:hr,title:_e(t.data.title,2e3),pages:s,settings:Ba(t.data.settings)},b=K(t.data.description,5e3);return b&&(p.description=b),{ok:!0,schema:p}}function Et(e,t){let n=K(e,t);if(n&&!(/[;{}<>]/.test(n)||/url\s*\(/i.test(n)))return n}function ja(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{8,64}$/.test(e)?e:void 0}function eo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,n=j({primary:Et(t.primary,200),background:Et(t.background,200),text:Et(t.text,200),logo:ja(t.logo)});return Object.keys(n).length>0?n:void 0}function Mo(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=t.colorScheme==="light"||t.colorScheme==="dark"||t.colorScheme==="auto"?t.colorScheme:void 0,r=j({colorScheme:n,...eo(t),radius:Et(t.radius,64),fontFamily:Et(t.fontFamily,200),dark:eo(t.dark)});return Object.keys(r).length>0?r:null}function gt(e){return e.label.trim()||e.placeholder?.trim()||"Untitled field"}function Va(e){throw new Error(`Unhandled field kind: ${JSON.stringify(e)}`)}function $r(e,t){if(t==null||t==="")return"";switch(e.kind){case"file_upload":return Array.isArray(t)?t.map(n=>n.name).join(", "):String(t);case"select":case"dropdown":return e.options.find(n=>n.id===t)?.label??String(t);case"multi_select":return Array.isArray(t)?t.map(n=>e.options.find(r=>r.id===n)?.label??n).join(", "):String(t);case"ranking":return Array.isArray(t)?t.map((n,r)=>`${r+1}. ${e.options.find(i=>i.id===n)?.label??n}`).join(", "):String(t);case"matrix":{if(typeof t!="object"||t===null||Array.isArray(t))return String(t);let n=t;return e.rows.filter(r=>n[r.id]).map(r=>`${r.label}: ${e.columns.find(i=>i.id===n[r.id])?.label??""}`).join(", ")}case"signature":return typeof t=="string"&&t.startsWith("data:image/")?"\u270D signed":"";case"checkbox":return t===!0?"Yes":"No";case"rating":case"linear_scale":return String(t);case"number":{let n=typeof t=="number"?t:Number(t);if(!Number.isFinite(n))return String(t);let r=e.decimals===void 0?String(n):n.toFixed(Math.max(0,Math.min(6,e.decimals)));return`${e.prefix??""}${r}${e.suffix??""}`}case"calculated":{let n=typeof t=="number"?t:Number(t);if(!Number.isFinite(n))return String(t);let r=e.decimals===void 0?String(n):n.toFixed(Math.max(0,Math.min(6,e.decimals)));return`${e.prefix??""}${r}${e.suffix??""}`}case"repeating_group":{if(!Array.isArray(t))return String(t);let n=t;if(n.length===0)return"";let r=e.itemLabel??e.label,i=`${n.length} \xD7 ${r}`,o=e.fields[0];if(!o)return i;let s=n.map(a=>a&&typeof a=="object"&&!Array.isArray(a)?$r(o,a[o.id]):"").filter(a=>a!=="");return s.length>0?`${i}: ${s.join(", ")}`:i}case"phone":{let{country:n,national:r,e164:i}=Mt(String(t));if(!i)return String(t);let o=It(n,r),s=n?`+${n.dialCode}`:i.replace(r,"");return o?`${s} ${o}`:i}case"short_text":case"long_text":case"email":case"url":case"date":case"hidden":return String(t);case"custom":return typeof t=="object"?JSON.stringify(t):String(t);default:return Va(e)}}function Ha(e){return Math.max(0,Math.min(6,Math.round(e)))}function No(e){switch(e){case"grouped-comma":return"en-US";case"grouped-dot":return"de-DE";case"grouped":case void 0:return}}function Lo(e,t){if(!Number.isFinite(e))return String(e);let n=t?.decimals===void 0?void 0:Ha(t.decimals);if(typeof Intl>"u")return n===void 0?String(e):e.toFixed(n);let r={useGrouping:!0};return n===void 0?r.maximumFractionDigits=20:(r.minimumFractionDigits=n,r.maximumFractionDigits=n),new Intl.NumberFormat(t?.locale,r).format(e)}function To(e,t){return t?e.split(t).join(""):e}function to(e,t){return t==="."?e:e.split(t).join(".")}function Ga(e,t,n){if(n!==t&&e.includes(n)){let o=e.lastIndexOf(n),s=To(e.slice(0,o),t),a=e.slice(o+n.length);return`${s}.${a}`}let r=e.split(t);return r.length===1?e:r.every((o,s)=>s===0?/^[1-9]\d{0,2}$/.test(o):/^\d{3}$/.test(o))?r.join(""):`${r.slice(0,-1).join("")}.${r.at(-1)??""}`}function Sr(e,t){if(typeof Intl>"u"||e.trim()==="")return e;let n=new Intl.NumberFormat(t).formatToParts(12345678e-1),r=n.find(a=>a.type==="group")?.value??",",i=n.find(a=>a.type==="decimal")?.value??".",o=e.trim(),s=o.startsWith("-");return s&&(o=o.slice(1)),/^\s$/.test(r)?o=to(o.replace(/\s/g,""),i):r==="."||r===","?o=Ga(o,r,i):o=to(To(o,r),i),o===""||o==="."||!/^\d*\.?\d*$/.test(o)?e:s?`-${o}`:o}function Lt(e,t){let r=e.startsWith("-")?e.slice(1):e;if(r.includes("-"))return!1;if(r==="")return!0;if(typeof Intl>"u")return/^[\d.,]*$/.test(r);let i=new Intl.NumberFormat(t).formatToParts(12345678e-1),o=i.find(m=>m.type==="group")?.value??",",s=i.find(m=>m.type==="decimal")?.value??".",a=o===".",l=/^\s$/.test(o),c=a?[s]:Array.from(new Set([".",s])),u=0;for(let m of r)if(!/\d/.test(m)){if(c.includes(m)){if(++u>1)return!1;continue}if(!(l?/\s/.test(m):m===o))return!1}return!0}var gr="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",qa=256-256%gr.length;function no(e=12){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError("createId size must be a positive safe integer");let t=globalThis.crypto;if(typeof t>"u"||typeof t.getRandomValues!="function")throw new Error("createId requires Web Crypto (globalThis.crypto.getRandomValues)");let n="";for(;n.length<e;){let r=new Uint8Array(e);t.getRandomValues(r);for(let i=0;i<e&&n.length<e;i++){let o=r[i];o<qa&&(n+=gr[o%gr.length])}}return n}var Po=class{h0=1732584193;h1=4023233417;h2=2562383102;h3=271733878;h4=3285377520;block=new Uint8Array(64);blockLen=0;totalLen=0;w=new Int32Array(80);update(e){this.totalLen+=e.length;let t=0;if(this.blockLen>0){for(;t<e.length&&this.blockLen<64;)this.block[this.blockLen++]=e[t++];this.blockLen===64&&(this.process(this.block),this.blockLen=0)}for(;t+64<=e.length;)this.process(e.subarray(t,t+64)),t+=64;for(;t<e.length;)this.block[this.blockLen++]=e[t++];return this}digest(){let e=Math.floor(this.totalLen/536870912),t=this.totalLen*8>>>0,n=[128],r=this.blockLen+1;for(;r%64!==56;)n.push(0),r++;n.push(e>>>24&255,e>>>16&255,e>>>8&255,e&255),n.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255),this.update(new Uint8Array(n));let i=new Uint8Array(20),o=[this.h0,this.h1,this.h2,this.h3,this.h4];for(let s=0;s<5;s++)i[s*4]=o[s]>>>24&255,i[s*4+1]=o[s]>>>16&255,i[s*4+2]=o[s]>>>8&255,i[s*4+3]=o[s]&255;return i}process(e){let t=this.w;for(let a=0;a<16;a++)t[a]=e[a*4]<<24|e[a*4+1]<<16|e[a*4+2]<<8|e[a*4+3];for(let a=16;a<80;a++){let l=t[a-3]^t[a-8]^t[a-14]^t[a-16];t[a]=l<<1|l>>>31}let n=this.h0,r=this.h1,i=this.h2,o=this.h3,s=this.h4;for(let a=0;a<80;a++){let l,c;a<20?(l=r&i|~r&o,c=1518500249):a<40?(l=r^i^o,c=1859775393):a<60?(l=r&i|r&o|i&o,c=2400959708):(l=r^i^o,c=3395469782);let u=(n<<5|n>>>27)+l+s+c+t[a]|0;s=o,o=i,i=r<<30|r>>>2,r=n,n=u}this.h0=this.h0+n|0,this.h1=this.h1+r|0,this.h2=this.h2+i|0,this.h3=this.h3+o|0,this.h4=this.h4+s|0}},on="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Ar(e){let t="";for(let n=0;n<e.length;n+=3){let r=e[n],i=n+1<e.length?e[n+1]:0,o=n+2<e.length?e[n+2]:0;t+=on[r>>2],t+=on[(r&3)<<4|i>>4],t+=n+1<e.length?on[(i&15)<<2|o>>6]:"=",t+=n+2<e.length?on[o&63]:"="}return t}var Wa=e=>Ar(new Po().update(e).digest()),C=class extends Error{constructor(e,t,n,r){super(e),this.status=t,this.retryAfterSec=n,this.code=r,this.name="FilloError"}status;retryAfterSec;code};function be(e){return e instanceof Error&&e.name==="FilloError"}async function ro(e,t){try{let n=await e.json();return{message:typeof n.error=="string"&&n.error?n.error:t,code:typeof n.code=="string"&&n.code?n.code:void 0}}catch{}return{message:t}}function sn(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t:void 0}var dt=3,Ka=4,rt=3e4,Ja=5*6e4,$e=10*6e4;function an(e,t){return t?.throwIfAborted(),new Promise((n,r)=>{let i=()=>{clearTimeout(o),r(t?.reason)},o=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);t?.addEventListener("abort",i,{once:!0})})}function Xn(e,t=!1){let n=be(e)?e.status??0:0;return n===0||n===503||n===504||t&&n===409&&be(e)&&e.retryAfterSec!==void 0}function ln(e){return e>=500||e===429||e===408}function Yn(e){return typeof DOMException<"u"&&e instanceof DOMException&&e.name==="TimeoutError"?new C("Request timed out",0):e}function Xa(e,t){let n=e.split(".").map(i=>Number(i)||0),r=t.split(".").map(i=>Number(i)||0);for(let i=0;i<Math.max(n.length,r.length);i++){let o=(n[i]??0)-(r[i]??0);if(o!==0)return o}return 0}function Ya(e){if(e.schemaVersion!==void 0&&e.schemaVersion!==hr)throw new C(`This form uses schema version ${e.schemaVersion}; this SDK supports version ${hr}. Update @usefillo/* to render it.`,426);if(e.minSdkVersion&&Xa(mr,e.minSdkVersion)<0)throw new C(`This form requires @usefillo/* ${e.minSdkVersion} or newer. Current SDK is ${mr}.`,426)}function cn(e,t){return n=>t.onProgress?.({uploadedBytes:n,totalBytes:e,fraction:e===0?1:n/e})}async function Qa(e){let t=globalThis.crypto?.subtle;if(t){let n=await t.digest("SHA-1",e);return Ar(new Uint8Array(n))}return Wa(e)}var el="https://fillo.so",Qn={"X-Fillo-Client":`@usefillo/core@${mr}`},vn=class{baseUrl;fetch;activeUploads=0;uploadQueue=new Set;key;constructor(e={}){this.baseUrl=e.baseUrl?e.baseUrl.replace(/\/$/,""):e.sameOrigin?"":el,this.key=e.key,this.fetch=e.fetch??((...t)=>globalThis.fetch(...t))}url(e){return`${this.baseUrl}/api/v1${e}`}async json(e,t){let n=t?.body!=null?{"Content-Type":"application/json",...Qn,...t?.headers}:t?.headers,r;try{r=await this.fetch(this.url(e),{...t,headers:n,signal:t?.signal??AbortSignal.timeout(rt)})}catch(i){throw Yn(i)}if(!r.ok){let{message:i,code:o}=await ro(r,`Request failed: ${r.status}`);throw new C(i,r.status,sn(r),o)}return await r.json()}async getForm(e){let t=await this.json(`/forms/${encodeURIComponent(e)}`);return Ya(t),t}syncForm(e,t,n){if(!this.key)return Promise.reject(new C("createClient needs a `key` (pk_\u2026) to sync code-defined forms",401));let r=Ye(t);return r.ok?this.json("/forms/sync",{method:"POST",body:JSON.stringify({key:this.key,id:e,schema:r.schema,theme:Mo(n)})}):Promise.reject(new C(`Invalid form schema: ${r.error}`,400))}async reportInvalidDefinition(e,t){try{let n="formId"in e?{formId:e.formId}:this.key?{key:this.key,id:e.handle}:null;if(!n)return null;let r=await this.fetch(this.url("/forms/definition-report"),{method:"POST",headers:{"Content-Type":"application/json",...Qn},body:JSON.stringify({...n,schema:t}),signal:AbortSignal.timeout(rt)});if(!r.ok)return null;let i=await r.json();return typeof i.formId=="string"&&i.formId?i.formId:null}catch{return null}}async submit(e,t,n){let r;try{r=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/responses`),{method:"POST",headers:{"Content-Type":"application/json",...Qn},body:JSON.stringify({data:t,meta:n}),signal:AbortSignal.timeout(rt)})}catch(o){throw Yn(o)}if(r.status===422){let o=await r.json().catch(()=>null);if(o?.errors&&typeof o.errors=="object"&&!Array.isArray(o.errors))return{ok:!1,errors:o.errors};throw new C(typeof o?.error=="string"&&o.error?o.error:"Submit failed: 422",422,sn(r),typeof o?.code=="string"&&o.code?o.code:void 0)}if(!r.ok){let{message:o,code:s}=await ro(r,`Submit failed: ${r.status}`);throw new C(o,r.status,sn(r),s)}let i=await r.json();return{ok:!0,responseId:i.id,duplicate:i.duplicate,updated:i.updated}}async fetchOwnResponse(e,t,n){try{return await this.json(`/forms/${encodeURIComponent(e)}/respondent-response`,{method:"POST",body:JSON.stringify({respondent:t,scopeValue:n})})}catch(r){if(be(r)&&(r.status===404||r.status===403))return null;throw r}}async startSession(e,t){try{let n=await this.fetch(this.url(`/forms/${encodeURIComponent(e)}/sessions`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pageCount:t}),signal:AbortSignal.timeout(rt)});return n.ok?(await n.json()).id:null}catch{return null}}reportProgress(e,t){try{this.fetch(this.url(`/sessions/${encodeURIComponent(e)}/progress`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0,signal:AbortSignal.timeout(rt)}).catch(()=>{})}catch{}}createDraft(e,t){return this.json(`/forms/${encodeURIComponent(e)}/drafts`,{method:"POST",body:JSON.stringify(t)})}getDraft(e,t,n){return this.json(`/drafts/${encodeURIComponent(e)}`,{headers:n?{"X-Fillo-Draft-Token":t,"X-Fillo-Draft-Adopt":"1"}:{"X-Fillo-Draft-Token":t}})}async saveDraft(e,t,n,r){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"X-Fillo-Draft-Token":t},body:JSON.stringify(n),...r?.keepalive?{keepalive:!0}:{}})}async deleteDraft(e,t){await this.json(`/drafts/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-Fillo-Draft-Token":t}})}getUploadSession(e,t,n=AbortSignal.timeout($e)){return this.json(`/uploads/${encodeURIComponent(e)}`,{...t?{headers:{"X-Fillo-Upload-Token":t}}:{},signal:n})}async uploadFile(e,t,n){await this.acquireUploadSlot(n.signal);try{return n.signal?.throwIfAborted(),await this.performUpload(e,t,n)}finally{this.activeUploads-=1;let r=this.uploadQueue.values().next().value;r&&(this.uploadQueue.delete(r),r())}}async acquireUploadSlot(e){if(e?.throwIfAborted(),this.activeUploads<Ka){this.activeUploads+=1;return}await new Promise((t,n)=>{let r=()=>{e?.removeEventListener("abort",i),this.activeUploads+=1,t()},i=()=>{this.uploadQueue.delete(r),n(e?.reason)};this.uploadQueue.add(r),e?.addEventListener("abort",i,{once:!0})})}async performUpload(e,t,n){let r=typeof File<"u"&&t instanceof File?t.name:"upload.bin",i=(t.type||"application/octet-stream").trim().toLowerCase(),o;if(n.sessionId){let c=await this.getUploadSession(n.sessionId,n.uploadToken,this.uploadSignal(n,$e));if(c.formId!==e||c.fieldId!==n.fieldId||c.fileName!==r||c.size!==t.size||c.mime.trim().toLowerCase()!==i)throw new C("File does not match this upload session",400);o=c,o.token||=n.uploadToken}else{let c=no(24),u=no(32),m=()=>this.json(`/forms/${encodeURIComponent(e)}/uploads`,{method:"POST",body:JSON.stringify({requestId:c,uploadToken:u,fieldId:n.fieldId,fileName:r,size:t.size,mime:i}),signal:this.uploadSignal(n,$e)}),f=Date.now()+$e,h=250;for(;;)try{o=await m();break}catch(p){if(n.signal?.aborted||!Xn(p,!0))throw p;let b=f-Date.now();if(b<=0)throw p;await an(Math.min(h,b),n.signal),h=Math.min(h*2,5e3)}}if(n.onSession?.({sessionId:o.id,uploadToken:o.token}),o.status==="complete"&&o.file)return o.file;if(o.status==="aborted")throw new C("This upload session was cancelled",409);let s;if(o.transport?.type==="gdrive")await this.driveUploadLoop(o,o.transport.uploadUrl,t,n);else if(o.transport?.type==="s3-multipart")await this.s3MultipartUploadLoop(o,t,n);else if(o.transport?.type==="s3-put")await this.s3PutUpload(o.transport.uploadUrl,t,n);else if(o.transport?.type==="box")s=await this.boxUpload(o.transport,t,n);else throw new C("This form's storage doesn't support uploads \u2014 connect Drive, S3, or Box.");let a=()=>this.json(`/uploads/${encodeURIComponent(o.id)}/complete`,{method:"POST",headers:o.token?{"X-Fillo-Upload-Token":o.token}:void 0,...s?{body:JSON.stringify(s)}:{},signal:this.uploadSignal(n,$e)}),l;try{l=await a()}catch(c){if(n.signal?.aborted||!Xn(c))throw c;let u=Date.now()+$e,m=250;for(;;){let f=await this.getUploadSession(o.id,o.token,this.uploadSignal(n,Math.max(1,u-Date.now())));if(f.status==="complete"&&f.file)return f.file;if(f.status==="aborted")throw c;try{l=await a();break}catch(p){if(n.signal?.aborted||!Xn(p,!0))throw p}let h=u-Date.now();if(h<=0)throw c;await an(Math.min(m,h),n.signal),m=Math.min(m*2,5e3)}}if(!l.file)throw new C("Upload completed but no file was returned");return l.file}async boxUpload(e,t,n){let r=cn(t.size,n);r(0);let i={Authorization:`Bearer ${e.token}`};if(e.mode==="simple"){let p=new FormData;p.append("attributes",JSON.stringify({name:e.fileName,parent:{id:e.folderId}})),p.append("file",t,e.fileName);let b=await this.retry(n,async()=>{let y=await this.fetch(e.uploadUrl,{method:"POST",headers:i,body:p,signal:this.uploadSignal(n)});if(!y.ok&&ln(y.status))throw new C(`Box upload failed: ${y.status}`,y.status);return y});if(!b.ok)throw new C(`Box upload failed: ${b.status}`,b.status);let v=await b.json();return r(t.size),{providerFileId:v.entries?.[0]?.id}}if(e.size!==t.size)throw new C(`File size changed since the upload was requested (${t.size} vs ${e.size}).`,400);let o=await this.retry(n,async()=>{let p=await this.fetch(e.sessionUrl,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify({folder_id:e.folderId,file_size:e.size,file_name:e.fileName}),signal:this.uploadSignal(n)});if(!p.ok&&ln(p.status))throw new C(`Box session failed: ${p.status}`,p.status);return p});if(!o.ok)throw new C(`Box session failed: ${o.status}`,o.status);let s=await o.json(),a=new Po,l=[],c=0;for(;c<t.size;){n.signal?.throwIfAborted();let p=Math.min(c+s.part_size,t.size),b=new Uint8Array(await t.slice(c,p).arrayBuffer());a.update(b);let v=await Qa(b),y=await this.retry(n,async()=>{let F=await this.fetch(s.session_endpoints.upload_part,{method:"PUT",headers:{...i,"Content-Type":"application/octet-stream",Digest:`sha=${v}`,"Content-Range":`bytes ${c}-${p-1}/${t.size}`},body:b,signal:this.uploadSignal(n)});if(!F.ok&&ln(F.status))throw new C(`Box part failed: ${F.status}`,F.status);return F});if(!y.ok)throw new C(`Box part failed: ${y.status}`,y.status);l.push((await y.json()).part),c=p,r(c)}let u=Date.now()+$e,m=JSON.stringify({parts:l}),f={...i,"Content-Type":"application/json",Digest:`sha=${Ar(a.digest())}`},h=0;for(;;){n.signal?.throwIfAborted();let p=u-Date.now();if(p<=0)throw new C("Box upload processing timed out",0);let b;try{if(b=await this.fetch(s.session_endpoints.commit,{method:"POST",headers:f,body:m,signal:this.uploadSignal(n,Math.min(rt,p))}),!b.ok&&ln(b.status))throw new C(`Box commit failed: ${b.status}`,b.status)}catch(F){if(n.signal?.throwIfAborted(),++h>=dt)throw Yn(F);await an(Math.min(500*2**h,Math.max(0,u-Date.now())),n.signal);continue}if(h=0,b.status===202){let F=sn(b),I=Date.parse(b.headers.get("retry-after")??""),ee=F!==void 0?F*1e3:Number.isFinite(I)?Math.max(1e3,I-Date.now()):1e3;await b.body?.cancel().catch(()=>{}),await an(Math.min(ee,Math.max(0,u-Date.now())),n.signal);continue}if(!b.ok)throw new C(`Box commit failed: ${b.status}`,b.status);let y=(await b.json()).entries?.[0]?.id;if(typeof y!="string"||!y)throw new C("Box upload completed but no file was returned",502);return{providerFileId:y}}}uploadSignal(e,t=rt){let n=AbortSignal.timeout(t);return e.signal?AbortSignal.any([e.signal,n]):n}async retry(e,t){let n=0;for(;;)try{return await t()}catch(r){if(e.signal?.aborted||(n+=1,n>=dt))throw r;await new Promise(i=>setTimeout(i,500*2**n))}}async driveUploadLoop(e,t,n,r){let i=e.uploadedBytes,o=cn(n.size,r);o(i);let s=0;for(;i<n.size;){r.signal?.throwIfAborted();let a=i,l=Math.min(i+e.chunkSize,n.size),c=n.slice(i,l),u=0;for(;;)try{let m=await this.fetch(t,{method:"PUT",headers:{"Content-Range":`bytes ${i}-${l-1}/${n.size}`},body:c,signal:this.uploadSignal(r)});if(m.status===308){let f=m.headers.get("Range")??m.headers.get("range"),h=f?.match(/bytes=0-(\d+)/);h?i=Number(h[1])+1:f==null?i=0:i=(await this.getUploadSession(e.id,e.token,this.uploadSignal(r,$e))).uploadedBytes;break}if(m.ok){i=n.size;break}throw new C(`Drive chunk failed: ${m.status}`,m.status)}catch(m){if(r.signal?.aborted||(u+=1,u>=dt))throw m;if(await new Promise(h=>setTimeout(h,500*2**u)),i=(await this.getUploadSession(e.id,e.token,this.uploadSignal(r,$e))).uploadedBytes,i>=n.size)break;l=Math.min(i+e.chunkSize,n.size),c=n.slice(i,l)}if(o(i),i<=a){if(++s>=dt)throw new C("Drive upload stalled \u2014 the storage endpoint stopped accepting progress",0)}else s=0}}async s3MultipartUploadLoop(e,t,n){if(!Number.isSafeInteger(e.chunkSize)||e.chunkSize<=0||!Number.isSafeInteger(e.uploadedBytes)||e.uploadedBytes<0||e.uploadedBytes>t.size||e.uploadedBytes<t.size&&e.uploadedBytes%e.chunkSize!==0)throw new C("S3 upload session returned invalid progress",502);let r=cn(t.size,n),i=e.uploadedBytes;for(r(i);i<t.size;){n.signal?.throwIfAborted();let o=Math.floor(i/e.chunkSize)+1;if(o>1e4)throw new C("S3 upload needs too many parts",413);let s=Math.min(i+e.chunkSize,t.size),a=t.slice(i,s),l=0;for(;;){let c;try{let u=await this.json(`/uploads/${encodeURIComponent(e.id)}/parts`,{method:"POST",headers:e.token?{"X-Fillo-Upload-Token":e.token}:void 0,body:JSON.stringify({partNumber:o}),signal:this.uploadSignal(n,$e)});if(typeof u.uploadUrl!="string"||!u.uploadUrl)throw new C("S3 part URL was unavailable",502);c=u.uploadUrl;let m=await this.fetch(c,{method:"PUT",body:a,signal:this.uploadSignal(n,Ja)});if(!m.ok)throw new C(`S3 part upload failed: ${m.status}`,m.status);i=s,r(i);break}catch(u){if(n.signal?.aborted)throw u;let m=await this.getUploadSession(e.id,e.token,this.uploadSignal(n,$e));if(m.status==="aborted")throw new C("This upload session was cancelled",409);if(!Number.isSafeInteger(m.uploadedBytes)||m.uploadedBytes<i||m.uploadedBytes>t.size||m.uploadedBytes<t.size&&m.uploadedBytes%e.chunkSize!==0)throw new C("S3 upload session returned invalid progress",502);if(m.uploadedBytes>i){i=m.uploadedBytes,r(i);break}if(l+=1,l>=dt)throw u;await new Promise(f=>setTimeout(f,500*2**l))}}}}async s3PutUpload(e,t,n){let r=cn(t.size,n);r(0);let i=0;for(;;)try{let o=await this.fetch(e,{method:"PUT",headers:{"Content-Type":t.type||"application/octet-stream"},body:t,signal:this.uploadSignal(n)});if(!o.ok)throw new C(`S3 upload failed: ${o.status}`,o.status);r(t.size);return}catch(o){if(n.signal?.aborted||(i+=1,i>=dt))throw o;await new Promise(s=>setTimeout(s,500*2**i))}}};function Te(e={}){return new vn(e)}function er(e){let t=e.trim();if(!/^-?\d*\.?\d+$/.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}function tl(e=new Date){let t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${n}`}function io(e,t,n=new Date){let r=null;for(let i of Le(e))i.kind!=="date"||!i.defaultToday||t[i.id]!==void 0||(r=r??{...t},r[i.id]=tl(n));return r??t}function oo(e,t){let n={};for(let r of Le(e)){let i=r.kind==="hidden"?t[r.paramName??r.id]??r.defaultValue:t[r.id];if(!(i===void 0||i===""))switch(r.kind){case"number":{let o=er(i);if(o===null||r.min!==void 0&&o<r.min||r.max!==void 0&&o>r.max)break;n[r.id]=o;break}case"rating":{let o=er(i);o!==null&&Number.isInteger(o)&&o>=1&&o<=(r.max??5)&&(n[r.id]=o);break}case"linear_scale":{let o=er(i),s=r.min??1,a=r.max??10;o!==null&&Number.isInteger(o)&&o>=s&&o<=a&&(n[r.id]=o);break}case"checkbox":n[r.id]=i==="true"||i==="1"||i==="yes";break;case"select":case"dropdown":{r.options.some(o=>o.id===i)&&(n[r.id]=i);break}case"multi_select":{let o=new Set(r.options.map(a=>a.id)),s=[...new Set(i.split(",").filter(a=>o.has(a)))];s.length>0&&(n[r.id]=s);break}case"file_upload":case"ranking":case"matrix":case"signature":case"custom":break;case"calculated":break;case"repeating_group":break;default:n[r.id]=i}}return n}function nl(){if(!(typeof document>"u"||typeof window>"u"))try{let e=new URL(window.location.href);e.hash="";let t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("hubspotutk="))?.slice(11),n={pageUri:e.href.slice(0,2048),pageName:document.title.trim().slice(0,200)||void 0,hubspotutk:t&&/^[a-f0-9]{32}$/i.test(t)?t:void 0};return Object.values(n).some(Boolean)?n:void 0}catch{return}}var rl={id:"empty",blocks:[]},so=!1,ao=!1;function il(){ao||(ao=!0,console.warn("[fillo] This form has a client but no submission target \u2014 a bare schema can't sync. Wrap it in defineForm({ id, pages }) (or author it with <Fillo.Form id=\u2026>) so it gets a project handle, or pass formId for a dashboard-built form: https://fillo.so/docs"))}function ol(){so||(so=!0,console.warn("[fillo] This form has no `client`, so responses can't be submitted \u2014 it's render-only. Pass a client (createClient) to collect responses in Fillo, or forward them to your own backend with webhooks: https://fillo.so/docs"))}var Ro=new Map,st=new Set;function Fr(){try{return globalThis.localStorage??null}catch{return null}}function Oo(e){return`fillo:submission:${e}`}function pn(){let e=globalThis.crypto;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);return e?.getRandomValues?(e.getRandomValues(t),Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function Zo(e,t,n,r){if(st.has(t))return e.get(n)??null;let i=Fr();if(!i)return e.get(n)??null;let o;try{o=i.getItem(t)}catch{return e.get(n)??null}try{let s=JSON.parse(o??"null");if(s&&r(s))return s}catch{}return null}function Do(e,t,n,r){e.set(n,r);let i=Fr();if(!i){st.add(t);return}try{i.setItem(t,JSON.stringify(r)),st.delete(t)}catch{st.add(t)}}function Er(e){return Zo(Ro,Oo(e),e,t=>typeof t.key=="string")}function Uo(e,t){Do(Ro,Oo(e),e,t)}function sl(e){let t=Er(e);if(t?.key)return t.key;let n={key:pn()};return Uo(e,n),n.key}function al(e,t){let n=Er(e);Uo(e,{key:n?.key??pn(),submittedAt:new Date().toISOString(),responseId:t})}function br(e,t,n){let r=yo(e.settings,n);return r===null?t:`${t}::${r}`}function tr(e,t,n){return e.settings.responseLimit?.by!=="browser"||!t?!1:!!Er(br(e,t,n))?.submittedAt}var zr=new Map,Cr=new Map,hn=new Map;function W(e){return Cr.get(e)??0}function un(e,t,n){return Math.max(hn.get(JSON.stringify(["person",e,t??null]))??0,n?hn.get(JSON.stringify(["draft",e,n]))??0:0)}function Ir(e){return`fillo:draft:${e}`}function Ke(e,t){let n=Zo(zr,Ir(e),e,r=>{let i=r;return typeof i.id=="string"&&typeof i.token=="string"});return n?.respondentId&&t&&n.respondentId!==t?null:n}function ft(e,t,n){Cr.set(e,W(e)+1),Do(zr,Ir(e),e,{...t,respondentId:n??t.respondentId})}function nr(e,t=!1,n){let r=t?Ke(e):null,i=W(e)+1;Cr.set(e,i),t&&(hn.set(JSON.stringify(["person",e,n??r?.respondentId??null]),i),r&&hn.set(JSON.stringify(["draft",e,r.id]),i)),zr.delete(e);let o=Ir(e),s=Fr();if(!s){st.add(o);return}try{s.removeItem(o),st.delete(o)}catch{st.add(o)}}function rr(e){return be(e)&&(e.status===401||e.status===403||e.status===404)}var ll=1500;function Bo(e,t){if(be(e)){let n=e.status??0;if(n===404)return t.loadFailedNotFound;switch(e.code){case"submit_rate_limited":return t.submitRateLimited;case"workspace_unavailable":case"provision_closed":return t.formClosed;case"respondent_unrecognized":return t.respondentUnrecognized;case"invalid_file_reference":return t.fileUnavailable;case"response_scope_missing":return t.scopeMissing}if(n>0)return t.submitFailed}return t.loadFailedNetwork}function cl(e,t,n){if(be(e)){let r=e.status??0;if(t&&r>0&&e.message)return e.code?`${e.message} (${e.code})`:e.message;if(r>0&&r<500&&r!==408&&r!==429)return n.formUnavailable;if(r>0)return n.submitFailed}return Bo(e,n)}function jo(e){let{onChange:t,onSubmitted:n}=e,r={...qi,...e.respondentErrorStrings},i=Ye(e.form);if(!i.ok)throw new Error(`Invalid form schema: ${i.error}`);let o=i.schema,s=e.formId,a=e.client,l=e.respondent,c=l?.id,u=0,m={...e.initialData??{}},f=nt(o,{...m}),h={},p={},b=new Set,v=0,y,F=[];function I(){return e.previewNavigation===!0&&e.skipValidation===!0&&!a&&!s&&!e.resolveFormId}function ee(){return ht(o,f,I()?y:void 0)}function xe(){I()&&F.push({pageIndex:v,startPageId:y})}let M="idle",ne=!1,re=!1,Qe=!1,U=0,ie=new Set,Ae=!1;queueMicrotask(()=>{if(re||Qe)return;if(typeof location<"u"&&location.search){let _=Object.fromEntries(new URLSearchParams(location.search)),x=null;for(let[$,A]of Object.entries(oo(o,_)))f[$]===void 0&&(x=x??{...f},x[$]=A);x&&M==="idle"&&(f=nt(o,x),T())}let g=io(o,f);g!==f&&M==="idle"&&(f=nt(o,g),T()),M==="idle"&&tr(o,s,f)&&(M="submitted",ne=!0,T());let w=!1;if(o.settings.saveProgress&&(!c||l?.id)&&s&&a&&typeof location<"u"&&location.hash.includes("fillo-draft=")){let _=/fillo-draft=([^&]+)/.exec(location.hash),x="";try{x=_?.[1]?decodeURIComponent(_[1]):""}catch{}let $=x.indexOf(".");if($>0&&$<x.length-1){w=!0;let A=U,S=ke,z=s,H=a,D=W(z),X=l?.id,B=x.slice(0,$),G=x.slice($+1);H.getDraft(B,G,!0).then(Q=>{if(S.refs.set(A,{id:B,token:Q.token??G}),!he(A,z,H)||W(z)!==D){Sn(z,H,A,D,X,{id:B,token:Q.token??G,existing:!0});return}ft(z,{id:B,token:Q.token??G},X);try{history.replaceState(null,"",location.pathname+location.search)}catch{}}).catch(Q=>{he(A,z,H)&&rr(Q)&&(Ae=!0,T())}).finally(()=>{he(A,z,H)&&qt()})}else Ae=!0,T()}w||qt()});let oe,Ze=new Set,E=new Set,Fe=Date.now(),Y=pn(),J=null,Pe=!1,De=0,Ee=!1,Z=!1,ue="created",ye=!1,O=null,ke={ownerId:c,first:U,last:U,refs:new Map};function yt(g){let w=Ke(g,l?.id);return!l?.id&&(c||w?.respondentId)?null:w}let se=null,jt=Promise.resolve(),Ue=!1,kn=!1,$n=!1,Vt=!1;function Br(){De+=1,Pe=!1,J=null}function jr(){b.clear(),p={},Y=pn(),M="idle",oe=void 0,ne=!1,ue="created",Br()}function Vr(){let g={...m};if(typeof location<"u"&&location.search){let w=Object.fromEntries(new URLSearchParams(location.search));for(let[_,x]of Object.entries(oo(o,w)))g[_]===void 0&&(g[_]=x)}return nt(o,io(o,g))}function he(g,w,_){return!re&&U===g&&s===w&&a===_}function Hr(g,w,_,x,$,A){return he(g,w,_)&&!ie.has(g)&&un(w,$,A)<=x&&(W(w)===x||!Ke(w))}function Sn(g,w,_,x,$,A){let S=Ke(g),z=ie.has(_)||un(g,$,A.id)>x,H=!$||$===(l?.id??c)||g!==s;if(S?.id===A.id){if(!z&&H&&A.existing&&S.token!==A.token){let D=W(g);w.getDraft(A.id,A.token).then(X=>{let B=Ke(g);if(W(g)!==D||B?.id!==S.id||B.token!==S.token){un(g,$,A.id)>x&&B?.id!==A.id&&w.deleteDraft(A.id,A.token).catch(()=>{});return}if($&&$!==(l?.id??c)&&g===s)return;let G={id:A.id,token:A.token};ft(g,G,$),he(_,g,w)&&(O=G,Gt(X))}).catch(()=>{})}return}O?.id!==A.id&&(z?w.deleteDraft(A.id,A.token).catch(()=>{}):!S&&H&&ft(g,{id:A.id,token:A.token},$))}function Gr(){let g=o.pages.length,w=Math.min(v,Math.max(g-1,0)),_=o.pages[w]??rl;return{data:f,errors:h,status:M,pageIndex:w,pageCount:g,page:_,blocks:tn(o,_,f),isFirstPage:w===0,isLastPage:I()&&y!==void 0?ee().at(-1)===_.id:ur(o,_.id,f),uploading:Ze.size>0,submitError:oe,restoredSubmission:ne,resumedDraft:Ee,editingPrevious:Z,duplicateSubmission:ue==="duplicate",updatedSubmission:ue==="updated",resumeLinkFailed:Ae}}let qr=Gr();function T(){qr=Gr();for(let g of E)g()}function An(g,w){try{n?.(g,w)}catch(_){console.error("[fillo] onSubmitted handler threw:",_)}}function Wr(g){let w=o.pages[g];if(!w)return{};let _={};for(let x of tn(o,w,f))ce(x)&&(I()&&x.kind==="file_upload"||Object.assign(_,pr(x,f[x.id]).errors));return _}function Fn(g){for(let w of o.pages)for(let _ of w.blocks)ce(_)&&(Object.hasOwn(g,_.id)||_.kind==="repeating_group"&&Object.keys(g).some(x=>x.startsWith(`${_.id}.`)))&&b.add(_.id)}function Kr(g){if(b.size===0&&Object.keys(h).length===0)return;let w=new Set(ee()),_=new Map(o.pages.filter(S=>w.has(S.id)).flatMap(S=>tn(o,S,f)).filter(ce).map(S=>[S.id,S])),x=[..._.values()].filter(S=>S.kind==="repeating_group").sort((S,z)=>z.id.length-S.id.length),$=new Map,A=Object.fromEntries(Object.entries(h).filter(([S])=>{let z=_.get(S)??x.find(D=>S.startsWith(`${D.id}.`));if(!z)return delete p[S],!1;let H=$.get(z.id)??[];return H.push(S),$.set(z.id,H),!0}));for(let S of _.values()){let z=$.get(S.id)??[];if(S.id!==g&&z.some(X=>Object.hasOwn(p,X))||!(b.has(S.id)||S.id===g&&z.length>0))continue;for(let X of z)delete A[X],delete p[X];if(Ze.has(S.id)||e.skipValidation&&!(a&&s)&&S.kind==="file_upload")continue;let D=pr(S,f[S.id]).errors;Object.assign(A,D),Object.keys(D).length>0&&b.add(S.id)}h=A}function Jr(g){return o.pages.findIndex(w=>tn(o,w,f).some(_=>{if(_.id in g)return!0;if(_.kind!=="repeating_group")return!1;let x=f[_.id];return Array.isArray(x)?x.some(($,A)=>$&&typeof $=="object"&&!Array.isArray($)?gn(_,$).some(S=>`${_.id}.${A}.${S.id}`in g):!1):!1}))}function Ht(){return!!(!re&&o.settings.saveProgress&&a&&s&&!kn)}function vs(){let g=new Set;for(let w of o.pages)for(let _ of w.blocks)ce(_)&&g.add(_.id);return g}function Gt(g){if(M!=="idle"||Pe)return;let w=vs(),_=null;for(let[A,S]of Object.entries(g.data??{}))f[A]===void 0&&w.has(A)&&(_=_??{...f},_[A]=S);let x=typeof g.page=="number"&&Number.isFinite(g.page)?Math.max(0,Math.min(Math.floor(g.page),o.pages.length-1)):0,$=x>0&&v===0;!_&&!$||(_&&(f=nt(o,_)),$&&(v=x),Ee=!0,T())}function qt(){if(re||M!=="idle"||!l?.id&&c)return;if(!Ht()){Xr();return}let g=s,w=a,_=U,x=ke,$=W(g),A=l?.id,S=O??yt(g);if(S&&!$n){$n=!0,A&&!S.respondentId&&(ft(g,S,A),$=W(g)),O=S,x.refs.set(_,S),w.getDraft(S.id,S.token).then(z=>{he(_,g,w)&&W(g)===$&&Gt(z)}).catch(z=>{!he(_,g,w)||W(g)!==$||rr(z)&&(nr(g),O=null,l?.hash&&qt())});return}!S&&!Vt&&l?.hash&&(Vt=!0,w.createDraft(g,{data:{},page:0,respondent:l}).then(z=>{if(x.refs.set(_,z),!Hr(_,g,w,$,A,z.id)||O){Sn(g,w,_,$,A,z);return}if(O={id:z.id,token:z.token},ft(g,O,A),z.existing){let H=W(g);return w.getDraft(z.id,z.token).then(D=>{he(_,g,w)&&W(g)===H&&Gt(D)})}Xr()}).catch(z=>{he(_,g,w)&&(be(z)&&z.status!==void 0&&z.status>=400&&z.status<500||(Vt=!1))}))}function Xr(){if(ye||o.settings.responseLimit?.onRepeat!=="update"||!a||!s||!l?.hash||M!=="idle")return;ye=!0;let g=a,w=s,_=U,x=yo(o.settings,f)??void 0;g.fetchOwnResponse(w,l,x).then($=>{!he(_,w,g)||!$||M!=="idle"||Pe||Ee||(Gt({data:$.data,page:0}),Ee&&(Ee=!1,Z=!0,T()))}).catch(()=>{})}function En(g=!1){if(se&&(clearTimeout(se),se=null),!Ht()||M!=="idle"||!Ue)return;let w=s,_=a,x=U,$=ke;Ue=!1;let A=l,S=l?.id??c,z={data:f,page:Math.max(0,Math.min(v,o.pages.length-1))},H=O??yt(w),D=W(w),X=()=>ie.has(x)||un(w,S,H?.id)>D;jt=jt.then(async()=>{if(X())return;let B=he(x,w,_),G=B?W(w):D,Q=B?l:A,Be=B?l?.id??c:S,je=B?{data:f,page:Math.max(0,Math.min(v,o.pages.length-1))}:z,me=$.refs.get(x),lt=Ke(w,Be),ze=B?O??yt(w):H??(me?.id===lt?.id&&me?.token===lt?.token?lt:null);!B&&ze&&ze!==H&&(G=W(w));try{if(ze)try{await _.saveDraft(ze.id,ze.token,je,g?{keepalive:!0}:void 0),he(x,w,_)&&W(w)===G&&(O=ze);return}catch(wt){if(X()||W(w)!==G)return;if(!rr(wt))throw wt;nr(w),G=W(w),he(x,w,_)&&(O=null)}let de=await _.createDraft(w,Q?.hash?{...je,respondent:Q}:je);if($.refs.set(x,de),!Hr(x,w,_,G,Be,de.id)){Sn(w,_,x,G,Be,de);return}O={id:de.id,token:de.token},ft(w,O,Be),de.existing&&(Ue=!0)}catch(de){if(!he(x,w,_))return;be(de)&&de.status!==void 0&&de.status>=400&&de.status<500&&de.status!==429?kn=!0:Ue=!0}})}function ys(){!Ht()||M!=="idle"||(Ue=!0,se&&clearTimeout(se),se=setTimeout(()=>{se=null,En()},ll))}function Yr(){!Ht()||!Pe&&!O||(Ue=!0,En())}function Qr(g=s,w=U,_=!0,x=ke.ownerId){if(ie.add(w),g&&_&&nr(g,!0,x),!(w!==U||g!==s)){for(let $=ke.first;$<=ke.last;$++)ie.add($);Qe=!0,u+=1,U+=1,ke={ownerId:l?.id??c,first:U,last:U,refs:new Map},jt=Promise.resolve(),se&&(clearTimeout(se),se=null),Ue=!1,O=null}}function ws(g,w){if(!Pe&&a&&s){Pe=!0;let _=a,x=s,$=De;_.startSession(x,o.pages.length).then(A=>{!re&&$===De&&a===_&&s===x&&(J=A)})}f=nt(o,{...f,[g]:w}),t?.(f),oe=void 0,Kr(g),T(),ys()}function _s(g,w){w?(Ze.add(g),g in h&&(h=Object.fromEntries(Object.entries(h).filter(([_])=>_!==g)))):Ze.delete(g),T()}function ei(g){if(g.length===0)return-1;let w=o.pages.length,_=Math.min(v,Math.max(w-1,0)),x=o.pages[_]?.id,$=x===void 0?-1:g.indexOf(x);if($>=0)return $;let A=0;for(let S=0;S<g.length;S++){let z=o.pages.findIndex(H=>H.id===g[S]);z>=0&&z<=_&&(A=S)}return A}function xs(){let g=o.pages.length,w=Math.min(v,Math.max(g-1,0));if(!e.skipValidation||e.previewNavigation===!0){let z=Wr(w);if(h=z,p={},Fn(z),Object.keys(z).length>0){T();return}}let _=o.pages[w],x=ee(),$=ei(x);if((I()&&y!==void 0?x.at(-1)===_?.id:_?ur(o,_.id,f):!0)||$<0||$+1>=x.length){ti();return}let S=o.pages.findIndex(z=>z.id===x[$+1]);xe(),v=S>=0?S:Math.min(w+1,g-1),J&&a&&a.reportProgress(J,{furthestPage:v}),T(),Yr()}function ks(){h={};let g=I()?F.pop():void 0;if(g){v=Math.min(g.pageIndex,o.pages.length-1),y=g.startPageId,oe=void 0,T();return}let w=ht(o,f),_=ei(w);if(_>0){let x=o.pages.findIndex($=>$.id===w[_-1]);v=x>=0?x:Math.max(Math.min(v,o.pages.length-1)-1,0)}else if(w.length>0){let x=o.pages.findIndex($=>$.id===w[0]);v=x>=0?x:0}T(),Yr()}function $s(){!I()||M==="submitting"||M==="submitted"||v>=o.pages.length-1||(xe(),v+=1,y=o.pages[v]?.id,h={},oe=void 0,T())}async function ti(){if(re||M==="submitting"||M==="submitted")return;if(I()&&(h=Wr(v),p={},Fn(h),Object.keys(h).length>0)){T();return}let g=Eo(o,f);if(!g.ok){let B=e.skipValidation&&!(a&&s),G=B?Object.fromEntries(Object.entries(g.errors).filter(([Be])=>o.pages.every(je=>je.blocks.every(me=>!(ce(me)&&me.id===Be&&me.kind==="file_upload"))))):g.errors;if(B&&Object.keys(G).length===0){h={},M="submitted",T(),An(void 0,f);return}h=G,p={},Fn(G);let Q=Jr(G);Q>=0&&(v=Q,y=void 0,F.length=0),T();return}let w=a,_=U,x=u,$=ke,A=o,S=l,z=J,H=Y,D=s,X=()=>!re&&x===u&&a===w;if(w&&e.resolveFormId){M="submitting",oe=void 0,T();try{if(D=await e.resolveFormId(),!X())return;s=D}catch(B){throw X()&&(M="idle",oe=cl(B,e.verboseResolutionErrors===!0,r),T()),B}}if(w&&D){let B=A.settings.responseLimit?.by==="browser"?sl(br(A,D,g.data)):void 0,G=B??H,Q=A.settings.saveProgress?O??yt(D):null,Be=W(D),je=e.challengeRequired?e.getChallengeToken?.():void 0;if(e.challengeRequired&&!je){M="idle",oe=r.challengeIncomplete,T();return}M="submitting",oe=void 0,T();let me;try{me=await w.submit(D,g.data,{hp:e.getHoneypot?.()??"",elapsedMs:Date.now()-Fe,surface:e.surface??"headless",attribution:nl(),submissionKey:G,draft:Q?{id:Q.id,token:Q.token}:void 0,respondent:S,challengeToken:je})}catch(V){if(!X())throw V;if(M="idle",be(V)&&V.code==="challenge_failed"){oe=r.challengeRetry,e.onChallengeFailed?.(),T();return}throw oe=Bo(V,r),T(),V}if(!me.ok){if(!X())return;h=me.errors??{},p={...h};let V=Jr(h);V>=0?v=V:oe=r.reviewAnswers,M="idle",T();return}let lt=X()?J:z;lt&&w.reportProgress(lt,{completed:!0}),B&&al(br(A,D,g.data),me.responseId);let ze=X(),de=[...$.refs.values()];ze&&O&&de.push(O);let wt=[...new Map(de.map(V=>[JSON.stringify([V.id,V.token]),V])).values()];for(let V of wt)(V.id!==Q?.id||V.token!==Q?.token)&&w.deleteDraft(V.id,V.token).catch(()=>{});let Wt=Ke(D),Ss=!Wt&&W(D)===Be||!!(Wt&&[...wt,Q].some(V=>V?.id===Wt.id&&V.token===Wt.token));for(let V=$.first;V<=$.last;V++)ie.add(V);if(Qr(D,ze?U:_,Ss,$.ownerId),!ze)return;ue=me.duplicate?"duplicate":me.updated?"updated":"created",M="submitted",T(),An(me.responseId,g.data);return}if(e.skipValidation){M="submitted",T(),An(void 0,g.data);return}a&&!s?il():ol(),M="error",T()}return{getState:()=>qr,subscribe(g){return E.add(g),()=>{E.delete(g)}},setValue:ws,setUploading:_s,next:xs,skipPreviewPage:$s,back:ks,submit:ti,setContext(g){let w="formId"in g&&g.formId!==s||"client"in g&&g.client!==a,_="respondent"in g&&!!(l?.id&&!g.respondent?.id||g.respondent?.id&&c&&c!==g.respondent.id);if((w||"respondent"in g&&(g.respondent?.id!==l?.id||g.respondent?.hash!==l?.hash))&&(U+=1,jt=Promise.resolve(),w||_?(u+=1,ke={ownerId:"respondent"in g?g.respondent?.id??c:l?.id??c,first:U,last:U,refs:new Map},_?jr():(M==="submitting"&&(M="idle"),Br())):(ke.last=U,ke.ownerId=g.respondent?.id??c),_&&(m={},Ee=!1,Z=!1,h={},b.clear(),v=0),(w||_)&&(se&&clearTimeout(se),se=null,Ue=!1),O=null,$n=!1,Vt=!1,ye=!1,kn=!1),"formId"in g&&(s=g.formId),"client"in g&&(a=g.client),"respondent"in g&&(l=g.respondent,l?.id&&(c=l.id)),g.respondentErrorStrings&&(r={...qi,...g.respondentErrorStrings}),g.form&&g.form!==o){let $=Ye(g.form);if(!$.ok)throw new Error(`Invalid form schema: ${$.error}`);o=$.schema,f=nt(o,f),Kr("")}_&&(f=Vr()),M==="idle"&&tr(o,s,f)&&(M="submitted",ne=!0),qt(),T()},flushDraft(){En(!0)},resetDraft(){if(M==="submitting")return;let g=O??(s?yt(s):null),w=s?Ke(s):null,_=!w||!!(g&&g.id===w.id&&g.token===w.token);Qr(s,U,_),jr(),g&&a&&a.deleteDraft(g.id,g.token).catch(()=>{}),f=Vr(),h={},b.clear(),v=0,y=void 0,F.length=0,oe=void 0,Ee=!1,Z=!1,tr(o,s,f)&&(M="submitted",ne=!0),T()},destroy(){re=!0,u+=1,U+=1,se&&(clearTimeout(se),se=null),E.clear()}}}function ul(e){return ce(e)&&(e.kind==="select"||e.kind==="dropdown"||e.kind==="checkbox"||e.kind==="rating"||e.kind==="linear_scale")}function Vo(e){let t=e.filter(n=>ce(n)&&n.kind!=="hidden"&&n.kind!=="calculated");return t.length!==1?!0:!ul(t[0])}function Ho(e,t,n){if(n.form.settings.submitMode!=="auto"||n.status!=="idle"||n.uploading||!(()=>{switch(e.kind){case"select":case"dropdown":return typeof t=="string"&&e.options.some(a=>a.id===t);case"checkbox":return t===!0;case"rating":case"linear_scale":return typeof t=="number";default:return!1}})()||t===n.data[e.id])return!1;let i={...n.data,[e.id]:t},o=n.form.pages.find(a=>a.blocks.some(l=>l.id===e.id));if(!o||!ur(n.form,o.id,i))return!1;let s=xo(n.form,i).filter(a=>a.kind!=="hidden"&&a.kind!=="calculated");return s.length!==1||s[0]?.id!==e.id?!1:Eo(n.form,i).ok}function Go(e,t,n,r){if(n<=0)return null;let i=r?.rtl??!1;if(e==="Home")return 0;if(e==="End")return n-1;let o;switch(e){case"ArrowRight":o=i?-1:1;break;case"ArrowLeft":o=i?1:-1;break;case"ArrowDown":o=1;break;case"ArrowUp":o=-1;break;default:return null}let s=t+o;return Math.min(n-1,Math.max(0,s))}var dl=Math.sqrt(1.05*.05)-.05,fl=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i,pl=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i;function ir(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function vr(e){let t=e.trim(),n=null,r=fl.exec(t);if(r)n=`${r[1]}${r[2]}${r[3]}`;else{let a=pl.exec(t);a&&(n=`${a[1]}${a[1]}${a[2]}${a[2]}${a[3]}${a[3]}`)}if(!n)return null;let i=parseInt(n.slice(0,2),16),o=parseInt(n.slice(2,4),16),s=parseInt(n.slice(4,6),16);return .2126*ir(i)+.7152*ir(o)+.0722*ir(s)}function hl(e){if(!e||e.colorScheme==="light"||e.colorScheme==="dark"||!e.background||qo(e))return e;let t=vr(e.background);return t==null?e:{...e,colorScheme:t>dl?"light":"dark"}}function qo(e){if(!e||e.colorScheme==="light"||e.colorScheme==="dark")return!1;let t=e.dark;return!!(t&&(t.primary||t.background||t.text))}var ml="#18181b";function or(e){let t=vr(e);if(t==null)return null;let n=1.05/(t+.05),r=(t+.05)/((vr(ml)??0)+.05);return n>=r?"light":"dark"}var gl=[["primary","--fillo-primary"],["background","--fillo-bg"],["text","--fillo-text"]],dn={light:{primary:"#18181b",background:"transparent",text:"#18181b"},dark:{primary:"#fafafa",background:"transparent",text:"#f4f4f5"}};function Wo(e){let t=hl(Mo(e));if(!t)return null;let n={},r={};t.colorScheme&&(r["data-fillo-color-scheme"]=t.colorScheme);let i=qo(t)?t.dark:void 0;for(let[o,s]of gl){let a=t[o];if(!i){a&&(n[s]=a);continue}let l=i[o];!a&&!l||(n[s]=`light-dark(${a??dn.light[o]}, ${l??dn.dark[o]})`)}if(t.radius&&(n["--fillo-radius"]=t.radius),t.fontFamily&&(n["--fillo-font"]=t.fontFamily),i){let o=or(t.primary??dn.light.primary),s=or(i.primary??dn.dark.primary);o&&s&&(r["data-fillo-on-primary"]=o,r["data-fillo-on-primary-dark"]=s)}else if(t.primary){let o=or(t.primary);o&&(r["data-fillo-on-primary"]=o)}return(t.primary||t.background||t.text||i)&&(r["data-fillo-has-color-theme"]=""),{vars:n,attrs:r}}function Mr(e){return{id:e.id,theme:e.theme,schema:{version:1,title:e.title??"",description:e.description,pages:e.pages,settings:e.settings??{}},__filloCodeForm:!0}}function Nr(e){return typeof e=="object"&&e!==null&&"__filloCodeForm"in e}var We=new Map,bl=e=>new Promise(t=>setTimeout(t,e));function vl(e){if(!be(e))return!0;let t=e.status??0;return t===0||t===408||t===429||t>=500}async function yl(e,t){let n=800;for(let r=0;;r++)try{return await e.syncForm(t.id,t.schema,t.theme??null)}catch(i){if(!vl(i)||r>=2)throw i;let o=be(i)?i.retryAfterSec:void 0;await bl(Math.min(o?o*1e3:n*(1+Math.random()*.5),15e3)),n*=2}}function Ko(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function Jo(e,t){let n=r=>{if(Array.isArray(r))return r.map(n);if(r&&typeof r=="object"){let i=r;return Object.fromEntries(Object.keys(i).sort().map(o=>[o,n(i[o])]))}return r};return JSON.stringify(n(e))===JSON.stringify(n(t))}var yr=e=>e==="published"?36e5:6e4,wl=e=>!!(e.staged||e.resolvedSchema||e.syncError||e.accepting===!1||e.uploadsAvailable===!1);function Xo(e,t){return`fillo:sync:v5:${e.baseUrl}|${e.key}|${t}`}function _l(e,t,n){try{let r=globalThis.localStorage?.getItem(Xo(e,t));if(!r)return null;let i=JSON.parse(r);if(typeof i.formId!="string"||typeof i.slug!="string"||i.hash!==n||typeof i.ts!="number"||i.uploadFileSizeLimitMb!==void 0&&(typeof i.uploadFileSizeLimitMb!="number"||!Number.isFinite(i.uploadFileSizeLimitMb)||i.uploadFileSizeLimitMb<=0)||i.manageUrl!==void 0&&typeof i.manageUrl!="string"||i.status!==void 0&&i.status!=="draft"&&i.status!=="published")return null;let o=yr(i.status);return Date.now()-i.ts>o?null:i}catch{return null}}function xl(e,t,n,r){if(!(r.staged||r.resolvedSchema||r.syncError||r.accepting===!1)&&!r.challenge)try{globalThis.localStorage?.setItem(Xo(e,t),JSON.stringify({formId:r.formId,slug:r.slug,manageUrl:r.manageUrl,status:r.status,uploadFileSizeLimitMb:r.uploadFileSizeLimitMb,hash:n,ts:Date.now()}))}catch{}}function Lr(e,t,n){let r=JSON.stringify(t.schema)+JSON.stringify(t.theme??null),i=Ko(r),o=`${e.baseUrl}:${e.key}:${t.id}:${i}`,s=Le(t.schema).some(u=>u.kind==="file_upload"),a=We.get(o);if(a&&!n?.bypassCache){if(a.expiresAt===null||!s&&a.expiresAt>Date.now())return a.promise;We.delete(o)}if(!n?.bypassCache&&!s){let u=_l(e,t.id,i);if(u){let m=Promise.resolve({formId:u.formId,slug:u.slug,manageUrl:u.manageUrl,status:u.status,uploadFileSizeLimitMb:u.uploadFileSizeLimitMb});return We.set(o,{promise:m,expiresAt:u.ts+yr(u.status)}),m}}let l=yl(e,t),c={promise:l,expiresAt:null};return We.set(o,c),l.then(u=>{if(We.get(o)===c){if(s||wl(u)){We.delete(o);return}c.expiresAt=Date.now()+yr(u.status),xl(e,t.id,i,u)}},()=>{We.get(o)===c&&We.delete(o)}),l}var kl=class extends Error{constructor(e,t){super(`[fillo] ${t} \u2014 https://fillo.so/docs/troubleshooting#jsx-${e.toLowerCase()}`),this.code=e,this.name="FilloJsxError"}code},$l=Symbol.for("fillo.block");var Sl=["label","description","required","placeholder"],q=(e,t,n,r={})=>({name:e,kind:t,props:[...Sl,...n],...r}),lo=(e,t,n)=>({name:e,kind:t,props:n?["text"]:[],textChildren:n,content:!0}),sr=["options","allowOther","shuffleOptions"],Al=[q("Text","short_text",["maxLength"]),q("LongText","long_text",["maxLength"]),q("Email","email",["maxLength"]),q("Url","url",["maxLength"]),q("Phone","phone",["defaultCountry"]),q("Number","number",["min","max","decimals","prefix","suffix","notation"]),q("Select","select",sr,{optionChildren:!0}),q("MultiSelect","multi_select",sr,{optionChildren:!0}),q("Dropdown","dropdown",sr,{optionChildren:!0}),q("Checkbox","checkbox",["appearance"]),q("Rating","rating",["max","insightsMetric"]),q("Scale","linear_scale",["min","max","minLabel","maxLabel","insightsMetric"]),q("Ranking","ranking",["options"],{optionChildren:!0}),q("Matrix","matrix",["rows","columns"]),q("Signature","signature",[]),q("Date","date",["defaultToday"]),q("FileUpload","file_upload",["maxFiles","maxFileSizeMb","accept"]),q("Hidden","hidden",["paramName","defaultValue"]),q("Calculated","calculated",["calc","decimals","prefix","suffix"]),q("RepeatingGroup","repeating_group",["minInstances","maxInstances","addLabel","itemLabel"],{blockChildren:!0}),q("Custom","custom",["component","config"]),lo("Heading","heading",!0),lo("Paragraph","paragraph",!0),{name:"Divider",kind:"divider",props:[],content:!0}],Fl={name:"Page",kind:"__page",props:["title"]},El={name:"Option",kind:"__option",props:["label","icon"]};function ar(e){let t=()=>{throw new kl("RENDERED_INERT",`<Fillo.${e.name}> was rendered by React. Fillo fields are schema declarations, valid only inside <Fillo.Form> or Fillo.defineForm(). If this form lives in a server component, move it to a client module ("use client")`)};return t[$l]=e,t}var up=Object.fromEntries([...Al.map(e=>[e.name,ar(e)]),["Page",ar(Fl)],["Option",ar(El)]]);var zl=1440*6e4,co=new Map,uo=new Set;function Cl(e){try{return Ko(JSON.stringify(e)??"")}catch{return"unserializable"}}function Il(e){let t=`fillo:definition-report:v1:${e}`;try{let n=Number(globalThis.localStorage?.getItem(t));if(Number.isFinite(n)&&Date.now()-n<zl)return!1;globalThis.localStorage?.setItem(t,String(Date.now()))}catch{}return!0}function fo(e,t,n){return typeof e.reportInvalidDefinition=="function"?e.reportInvalidDefinition(t,n):Promise.resolve(null)}function Yo(e,t){let n=t.formId??(t.handle?`handle:${t.handle}`:""),r=`${e?.baseUrl??""}|${e?.key??""}|${n}|${Cl(t.definition)}`,i=co.get(r);if(i)return i;let o;return t.formId?(e&&Il(r)&&fo(e,{formId:t.formId},t.definition),o=Promise.resolve(t.formId)):t.handle&&e?.key?o=fo(e,{handle:t.handle},t.definition):o=Promise.resolve(null),o=o.then(s=>{if(!uo.has(r)){uo.add(r);let a=s?t.formId?"Showing the version published on Fillo instead, or hiding the form if nothing is published":"Showing the version published on Fillo instead":"Nothing is published to show instead, so the form is hidden";console.error(`[fillo] This form's definition is invalid: ${t.reason}. ${a}. Fix the definition in your code.`)}return s}),co.set(r,o),o}function Ml(e){let t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)||t==="::1"||t==="[::1]"||t==="0.0.0.0"}function Tr(){return typeof process<"u"&&process.env?.NODE_ENV!=="production"}function Qo(){if(Tr())return!0;if(typeof window>"u")return!1;let e=window.location?.hostname;return typeof e=="string"&&Ml(e)}var Nl=/\{\{\s*([\w-]+)\s*\}\}/g;function lr(e,t,n){if(!e.includes("{{"))return e;let r=Le(n);return e.replace(Nl,(i,o)=>{let s=r.find(c=>c.id===o),a=t[o];if(a==null||a==="")return"";let l=c=>s&&"options"in s?s.options.find(u=>u.id===c)?.label??c:c;return Array.isArray(a)?a.map(c=>l(String(c))).join(", "):typeof a=="string"?l(a):String(a)})}function es(e,t,n){let r=i=>i===void 0?i:lr(i,t,n);switch(e.kind){case"heading":case"paragraph":return{...e,text:lr(e.text,t,n)};case"divider":return e;default:return{...e,label:lr(e.label,t,n),description:r(e.description)}}}var Ll="fillo-",Tl=0,Ut='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Pl(e){return e.matches(Ut)?e:e.querySelector(Ut)}function Rl(e){return Array.from(e.querySelectorAll(Ut)).find(n=>!n.closest(".fillo-group-instance-header"))??null}function fs(e,t){let n=`${Ll}${e}-${t}`;return{inputId:n,labelId:`${n}-label`,descriptionId:`${n}-desc`,errorId:`${n}-error`,name:n}}function d(e,t={}){let n=document.createElement(e);t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text);for(let[r,i]of Object.entries(t.attrs??{}))n.setAttribute(r,i);return n}function bt(e,t){let n=Wo(t);if(n){for(let[r,i]of Object.entries(n.attrs))e.setAttribute(r,i);for(let[r,i]of Object.entries(n.vars))e.style.setProperty(r,i)}}function at(e){try{if(!e)return null;let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function Ol(e){let t=new URL(at(e)??"https://fillo.so");return t.searchParams.set("utm_source","form_badge"),t.toString()}function wn(e){return typeof e=="string"||typeof e=="number"?String(e):""}function ts(e,t,n){let r=wn(e);if(r==="")return r;let i=Number(r);return Number.isFinite(i)?Lo(i,{locale:n,decimals:t}):r}function L(e,t){for(let n of t)n&&e.appendChild(n);return e}var _n="http://www.w3.org/2000/svg",Zl={thumbs_up:"M7 10v10M7 10l4.8-6.1a2 2 0 0 1 3.5 1.7L14.6 10h4.8a2.1 2.1 0 0 1 2 2.5l-1.1 5.4A3 3 0 0 1 17.4 20H7M3 10h4v10H3z",thumbs_down:"M7 14V4M7 14l4.8 6.1a2 2 0 0 0 3.5-1.7L14.6 14h4.8a2.1 2.1 0 0 0 2-2.5l-1.1-5.4A3 3 0 0 0 17.4 4H7M3 4h4v10H3z"};function ps(e){if(!e)return null;let t=document.createElementNS(_n,"svg");t.setAttribute("class","fillo-option-icon"),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(_n,"path");return n.setAttribute("d",Zl[e]),t.appendChild(n),t}function hs(){let e=document.createElementNS(_n,"svg");e.setAttribute("class","fillo-option-check"),e.setAttribute("width","1em"),e.setAttribute("height","1em"),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","2"),e.setAttribute("stroke-linecap","square"),e.setAttribute("stroke-linejoin","miter"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let t=document.createElementNS(_n,"path");return t.setAttribute("d","M4 12l5 5L20 6"),e.appendChild(t),e}function pe(e,t,n,r,i={}){n&&e.setAttribute("aria-invalid","true"),(i.requiredSupported??!0)&&t.required&&e.setAttribute("aria-required","true");let o=[t.description?r.descriptionId:null,n?r.errorId:null].filter(Boolean).join(" ");o&&e.setAttribute("aria-describedby",o)}function ms(e,t,n,r){e.addEventListener("keydown",i=>{let o=getComputedStyle(e).direction==="rtl",s=n===null?-1:t.indexOf(n),a=Go(i.key,s,t.length,{rtl:o});if(a===null)return;i.preventDefault();let l=t[a];l!==void 0&&(r(l),e.querySelectorAll('[role="radio"]')[a]?.focus())})}function ve(e,t,n,r){let i=d("div",{className:`fillo-field fillo-field--${e.kind}${t?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.id,"data-kind":e.kind}});i.toggleAttribute("data-invalid",!!t),i.toggleAttribute("data-required",!!e.required);let o=d("label",{className:"fillo-label",text:gt(e),attrs:{id:r.labelId,for:r.inputId,"data-fillo":"label"}});return!e.required&&!(e.kind==="repeating_group"&&(e.minInstances??1)>0)&&o.appendChild(d("span",{className:"fillo-optional",text:" (optional)"})),i.appendChild(o),e.description&&i.appendChild(d("p",{className:"fillo-description",text:e.description,attrs:{id:r.descriptionId,"data-fillo":"fieldDescription"}})),i.appendChild(n),t&&i.appendChild(d("p",{className:"fillo-error",text:t,attrs:{id:r.errorId,"data-fillo":"error"}})),i}function Tt(e,t){let n=t.field,r=n.kind==="number"?n:void 0,i=r?.notation!==void 0,o=No(r?.notation),s=i||!!r?.prefix||!!r?.suffix,a=d("input",{className:"fillo-input",attrs:{id:t.ids.inputId,type:s?"text":e,"data-fillo":"control"}});if(s&&a.setAttribute("inputmode","decimal"),e==="email"?a.setAttribute("autocomplete","email"):e==="url"&&a.setAttribute("autocomplete","url"),a.value=i?ts(t.value,r?.decimals,o):wn(t.value),n.placeholder&&(a.placeholder=n.placeholder),"maxLength"in n&&n.maxLength!==void 0&&(a.maxLength=n.maxLength),r&&!s&&(r.min!==void 0&&(a.min=String(r.min)),r.max!==void 0&&(a.max=String(r.max))),s){let c=a.value,u=a.value.length,m=()=>{a.value=c,a.setSelectionRange(u,u)};i?(a.addEventListener("input",()=>{if(!Lt(a.value,o))return m();c=a.value,u=a.selectionStart??a.value.length,t.setValue(Sr(a.value,o),{render:!1})}),a.addEventListener("change",()=>{if(!Lt(a.value,o))return m();c=a.value,t.setValue(Sr(a.value,o))}),a.addEventListener("blur",()=>{let f=t.getValue?.()??t.value;a.value=ts(f,r?.decimals,o),c=a.value,u=a.value.length})):(a.addEventListener("input",()=>{if(!Lt(a.value,o))return m();c=a.value,u=a.selectionStart??a.value.length,t.setValue(a.value,{render:!1})}),a.addEventListener("change",()=>{if(!Lt(a.value,o))return m();c=a.value,t.setValue(a.value)}))}else a.addEventListener("input",()=>t.setValue(a.value,{render:!1})),a.addEventListener("change",()=>t.setValue(a.value));pe(a,n,t.error,t.ids);let l=a;return r&&(r.prefix||r.suffix)&&(l=L(d("div",{className:"fillo-number"}),[r.prefix?d("span",{className:"fillo-number-prefix",text:r.prefix}):null,a,r.suffix?d("span",{className:"fillo-number-suffix",text:r.suffix}):null])),ve(n,t.error,l,t.ids)}function Dl(){if(typeof navigator>"u")return;let t=(navigator.languages?.[0]||navigator.language||"").split("-")[1];return t&&/^[A-Za-z]{2}$/.test(t)?t.toUpperCase():void 0}function Ul(){if(!(typeof Intl>"u"))try{let e=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof e=="string"&&e?e:void 0}catch{return}}function Bl(e,t){if(t<=0)return e.setSelectionRange(0,0);let n=e.value,r=0,i=n.length;for(let o=0;o<n.length;o++)if(/\d/.test(n[o])&&++r===t){i=o+1;break}e.setSelectionRange(i,i)}function jl(e){let t=e.field,n=Mt(wn(e.value)).country??bn(t.defaultCountry)??$o(Ul())??bn(Dl())??Ct[0],r=d("div",{className:"fillo-phone"}),i=d("div",{className:"fillo-phone-country"}),o=d("button",{className:"fillo-phone-flag",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false"}}),s=d("span",{className:"fillo-phone-flag-emoji",attrs:{"aria-hidden":"true"}}),a=d("span",{className:"fillo-phone-dial"});L(o,[s,a,d("span",{className:"fillo-phone-caret",text:"\u25BE",attrs:{"aria-hidden":"true"}})]),L(i,[o]);let l=d("input",{className:"fillo-input fillo-phone-input",attrs:{id:e.ids.inputId,type:"tel",inputmode:"tel",autocomplete:"tel-national","data-fillo":"control"}});pe(l,e.field,e.error,e.ids);let c=()=>e.getValue?.()??e.value,u=()=>{let E=Ne(wn(c()));return E.startsWith(n.dialCode)?E.slice(n.dialCode.length):E},m=()=>{s.textContent=_r(n.iso2),a.textContent=`+${n.dialCode}`,o.setAttribute("aria-label",`Country: ${n.name} (+${n.dialCode})`)},f=()=>{l.value=It(n,u()),l.placeholder=It(n,n.example)},h=E=>e.setValue(E?So(n,E):"",{render:!1}),p=E=>e.setValue(E,{render:!1});m(),f(),l.addEventListener("input",()=>{let E=l.value,Fe=l.selectionStart??E.length,Y=Ne(E.slice(0,Fe)).length;if(E.trimStart().startsWith("+")){let J=Mt(E,n,{previousDigits:u()});if(J.pending){p(J.raw??E);return}J.country&&(n=J.country,m()),h(J.country?J.national:Ne(E))}else h(Ne(E));l.value=It(n,u()),Bl(l,Y)});let b=e.registerOverlay,v=e.announce,y=null,F=0,I=mt,ee=null,xe=null,M,ne=`${e.ids.inputId}-countries`,re=()=>{if(!y)return;let E=Ao(i,y);y.classList.toggle("fillo-phone-popover--above",E==="above"),y.classList.toggle("fillo-phone-popover--below",E==="below")},Qe=()=>{ee?.();let E=()=>re();re(),window.addEventListener("resize",E),window.addEventListener("scroll",E,!0),ee=()=>{window.removeEventListener("resize",E),window.removeEventListener("scroll",E,!0)}},U=E=>{let Fe=E.relatedTarget;if(Fe){i.contains(Fe)||ie();return}queueMicrotask(()=>{y&&!i.contains(document.activeElement)&&ie()})},ie=()=>{clearTimeout(M),ee?.(),ee=null,y?.remove(),y=null,o.setAttribute("aria-expanded","false"),o.removeAttribute("aria-controls"),document.removeEventListener("mousedown",Ae),i.removeEventListener("focusout",U),xe?.(),xe=null},Ae=E=>{i.contains(E.target)||ie()},oe=E=>{E&&(n=E,m(),h(u()),f(),ie(),v?.(R.phoneCountrySelected(E.name)),l.focus())},Ze=E=>{let Fe=d("div",{className:"fillo-phone-popover fillo-phone-popover--below"}),Y=d("input",{className:"fillo-phone-search",attrs:{type:"text",role:"combobox","aria-expanded":"true","aria-controls":ne,"aria-autocomplete":"list","aria-label":"Search country or code",placeholder:"Search country or code"}});E&&(Y.value=E);let J=d("ul",{className:"fillo-phone-list",attrs:{role:"listbox",id:ne,"aria-label":"Country"}}),Pe=()=>{if(J.replaceChildren(),I.length===0){J.appendChild(d("li",{className:"fillo-phone-empty",text:"No matches",attrs:{role:"option","aria-disabled":"true"}})),Y.removeAttribute("aria-activedescendant"),re();return}I.forEach((Z,ue)=>{let ye=d("li",{className:`fillo-phone-option${ue===F?" fillo-phone-option--active":""}`,attrs:{id:`${ne}-opt-${ue}`,role:"option","aria-selected":String(Z.iso2===n.iso2)}});L(ye,[d("span",{className:"fillo-phone-flag-emoji",text:_r(Z.iso2),attrs:{"aria-hidden":"true"}}),d("span",{className:"fillo-phone-option-name",text:Z.name}),d("span",{className:"fillo-phone-option-dial",text:`+${Z.dialCode}`})]),ye.addEventListener("mouseenter",()=>{F=ue,Y.setAttribute("aria-activedescendant",ye.id),De()}),ye.addEventListener("mousedown",O=>{O.preventDefault(),oe(Z)}),J.appendChild(ye)}),Y.setAttribute("aria-activedescendant",`${ne}-opt-${F}`),re()},De=()=>{[...J.children].forEach((Z,ue)=>Z.classList.toggle("fillo-phone-option--active",ue===F)),document.getElementById(`${ne}-opt-${F}`)?.scrollIntoView({block:"nearest"})},Ee=Z=>{let ue=Z.trim().toLowerCase(),ye=ue.replace(/[^\d]/g,"");I=ue?mt.filter(O=>O.name.toLowerCase().includes(ue)||O.iso2.toLowerCase()===ue||ye.length>0&&O.dialCode.startsWith(ye)):mt,F=0,Pe(),clearTimeout(M),M=setTimeout(()=>v?.(R.phoneResultsCount(I.length)),300)};Y.addEventListener("input",()=>Ee(Y.value)),Y.addEventListener("keydown",Z=>{if(Z.key==="ArrowDown"){if(Z.preventDefault(),I.length===0)return;F=Math.min(F+1,I.length-1),De(),Y.setAttribute("aria-activedescendant",`${ne}-opt-${F}`)}else if(Z.key==="ArrowUp"){if(Z.preventDefault(),I.length===0)return;F=Math.max(F-1,0),De(),Y.setAttribute("aria-activedescendant",`${ne}-opt-${F}`)}else Z.key==="Enter"?(Z.preventDefault(),oe(I[F])):Z.key==="Escape"&&(Z.preventDefault(),ie(),o.focus())}),L(Fe,[Y,J]),y=Fe,i.appendChild(Fe),o.setAttribute("aria-expanded","true"),o.setAttribute("aria-controls",ne),E?Ee(E):(I=mt,F=Math.max(0,mt.indexOf(n)),Pe()),Qe(),De(),document.addEventListener("mousedown",Ae),i.addEventListener("focusout",U),xe=b?.(ie)??null,requestAnimationFrame(()=>{if(Y.focus(),E){let Z=Y.value.length;Y.setSelectionRange(Z,Z)}})};return o.addEventListener("click",()=>y?ie():Ze()),o.addEventListener("keydown",E=>{if(!y){if(E.key==="ArrowDown"||E.key==="ArrowUp"){E.preventDefault(),Ze();return}E.key.length===1&&E.key!==" "&&!E.ctrlKey&&!E.metaKey&&!E.altKey&&(E.preventDefault(),Ze(E.key))}}),L(r,[i,l]),ve(e.field,e.error,r,e.ids)}function Vl(e){let t=d("textarea",{className:"fillo-input fillo-textarea",attrs:{id:e.ids.inputId,rows:"4","data-fillo":"control"}});return t.value=typeof e.value=="string"?e.value:"",e.field.placeholder&&(t.placeholder=e.field.placeholder),"maxLength"in e.field&&e.field.maxLength!==void 0&&(t.maxLength=e.field.maxLength),t.addEventListener("input",()=>e.setValue(t.value,{render:!1})),t.addEventListener("change",()=>e.setValue(t.value)),pe(t,e.field,e.error,e.ids),ve(e.field,e.error,t,e.ids)}function Hl(e){let t=e.field,n=Dr(t),r=typeof e.value=="string"?e.value:"",i=e.activeOtherFields,o=r!==""&&!t.options.some(l=>l.id===r),s=o||r===""&&i?.has(t.id)===!0,a=d("div",{className:"fillo-options",attrs:{role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"options"}});pe(a,t,e.error,e.ids);for(let l of n){let c=d("label",{className:`fillo-option${l.icon?" fillo-option--has-icon":""}${r===l.id?" fillo-option--selected":""}`,attrs:{"data-option":l.id,"data-fillo":"option"}});c.toggleAttribute("data-selected",r===l.id);let u=d("input",{className:"fillo-option-input",attrs:{type:"radio",name:e.ids.name}});u.checked=r===l.id,u.addEventListener("change",()=>{i?.delete(t.id),e.setValue(l.id)}),L(c,[u,ps(l.icon),d("span",{className:"fillo-option-label",text:l.label,attrs:{"data-fillo":"optionLabel"}}),l.icon&&r===l.id?hs():null]),a.appendChild(c)}if(t.allowOther){let l=d("label",{className:`fillo-option fillo-option--other${s?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});l.toggleAttribute("data-selected",s);let c=d("input",{className:"fillo-option-input",attrs:{type:"radio",name:e.ids.name}});if(c.checked=s,c.addEventListener("change",()=>{i?.add(t.id),e.setValue("",{render:!0})}),L(l,[L(d("span",{className:"fillo-option-main"}),[c,d("span",{className:"fillo-option-label",text:P.other,attrs:{"data-fillo":"optionLabel"}})])]),s){let u=d("input",{className:"fillo-input fillo-other-input",attrs:{type:"text","aria-label":P.otherPrompt}});u.value=o?r:"",u.placeholder=P.otherPlaceholder,u.addEventListener("input",()=>{i?.add(t.id),e.setValue(u.value,{render:!1})}),u.addEventListener("change",()=>{i?.add(t.id),e.setValue(u.value)}),l.appendChild(u),o||queueMicrotask(()=>u.focus())}a.appendChild(l)}return ve(t,e.error,a,e.ids)}function Gl(e){let t=e.field,n=Dr(t),r=Array.isArray(e.value)?e.value:[],i=new Set(t.options.map(u=>u.id)),o=r.find(u=>!i.has(u)),s=e.activeOtherFields,a=()=>{let u=e.getValue?.()??e.value;return Array.isArray(u)?u:[]},l=d("div",{className:"fillo-options",attrs:{role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"options"}});pe(l,t,e.error,e.ids,{requiredSupported:!1});let c=u=>e.setValue(u);for(let u of n){let m=d("label",{className:`fillo-option${u.icon?" fillo-option--has-icon":""}${r.includes(u.id)?" fillo-option--selected":""}`,attrs:{"data-option":u.id,"data-fillo":"option"}});m.toggleAttribute("data-selected",r.includes(u.id));let f=d("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});f.checked=r.includes(u.id),f.addEventListener("change",()=>{let h=a();c(f.checked?[...h,u.id]:h.filter(p=>p!==u.id))}),L(m,[f,ps(u.icon),d("span",{className:"fillo-option-label",text:u.label,attrs:{"data-fillo":"optionLabel"}}),u.icon&&r.includes(u.id)?hs():null]),l.appendChild(m)}if(t.allowOther){let u=o!==void 0||s?.has(t.id)===!0,m=d("label",{className:`fillo-option fillo-option--other${u?" fillo-option--selected fillo-option--with-other":""}`,attrs:{"data-fillo":"option"}});m.toggleAttribute("data-selected",u);let f=d("input",{className:"fillo-option-input",attrs:{type:"checkbox"}});if(f.checked=u,f.addEventListener("change",()=>{let h=a().filter(p=>i.has(p));f.checked?(s?.add(t.id),c(h)):(s?.delete(t.id),c(h))}),L(m,[L(d("span",{className:"fillo-option-main"}),[f,d("span",{className:"fillo-option-label",text:P.other,attrs:{"data-fillo":"optionLabel"}})])]),u){let h=d("input",{className:"fillo-input fillo-other-input",attrs:{type:"text","aria-label":P.otherPrompt}});h.value=o??"",h.placeholder=P.otherPlaceholder,h.addEventListener("input",()=>{s?.add(t.id);let p=a().filter(b=>i.has(b));e.setValue(h.value?[...p,h.value]:p,{render:!1})}),h.addEventListener("change",()=>{s?.add(t.id);let p=a().filter(b=>i.has(b));e.setValue(h.value?[...p,h.value]:p)}),m.appendChild(h),o===void 0&&queueMicrotask(()=>h.focus())}l.appendChild(m)}return ve(t,e.error,l,e.ids)}function ql(e){let t="__fillo_other__",n=new Set(e.options.map(r=>r.id));for(;n.has(t);)t+="_";return t}function Wl(e){let t=e.field,n=typeof e.value=="string"?e.value:"",r=ql(t),i=e.activeOtherFields,o=n!==""&&!t.options.some(u=>u.id===n),s=o||n===""&&i?.has(t.id)===!0,a=d("div"),l=d("div",{className:"fillo-select-wrap"}),c=d("select",{className:"fillo-input fillo-select",attrs:{id:e.ids.inputId,"data-fillo":"control"}});c.appendChild(d("option",{text:t.placeholder??"Choose...",attrs:{value:""}}));for(let u of Dr(t))c.appendChild(d("option",{text:u.label,attrs:{value:u.id}}));if(t.allowOther&&c.appendChild(d("option",{text:`${P.other}\u2026`,attrs:{value:r}})),c.value=s?r:n,c.addEventListener("change",()=>{c.value===r?(i?.add(t.id),e.setValue("",{render:!0})):(i?.delete(t.id),e.setValue(c.value||null))}),pe(c,t,e.error,e.ids),L(l,[c,d("span",{className:"fillo-select-icon",attrs:{"aria-hidden":"true"}})]),a.appendChild(l),s){let u=d("input",{className:"fillo-input fillo-other-input fillo-other-input--block",attrs:{type:"text","aria-label":P.otherPrompt}});u.value=o?n:"",u.placeholder=P.otherPlaceholder,u.addEventListener("input",()=>{i?.add(t.id),e.setValue(u.value,{render:!1})}),u.addEventListener("change",()=>{i?.add(t.id),e.setValue(u.value)}),a.appendChild(u),o||queueMicrotask(()=>u.focus())}return ve(t,e.error,a,e.ids)}function Kl(e){if(e.field.kind==="checkbox"&&e.field.appearance==="toggle"){let o=d("div",{className:`fillo-field fillo-field--checkbox fillo-field--toggle${e.error?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.field.id,"data-kind":e.field.kind}});o.toggleAttribute("data-invalid",!!e.error),o.toggleAttribute("data-required",!!e.field.required);let s=d("label",{className:"fillo-toggle",attrs:{"data-fillo":"option"}});s.toggleAttribute("data-checked",e.value===!0);let a=d("span",{className:"fillo-option-label",text:gt(e.field),attrs:{"data-fillo":"optionLabel"}});e.field.required||a.appendChild(d("span",{className:"fillo-optional",text:" (optional)"}));let l=d("span",{className:"fillo-toggle-copy"});l.appendChild(a);let c=d("input",{className:"fillo-toggle-input",attrs:{id:e.ids.inputId,type:"checkbox"}});return c.checked=e.value===!0,c.addEventListener("change",()=>{e.setValue(c.checked)}),pe(c,e.field,e.error,e.ids),L(s,[l,c,L(d("span",{className:"fillo-toggle-track",attrs:{"aria-hidden":"true"}}),[d("span",{className:"fillo-toggle-thumb"})])]),o.appendChild(s),e.field.description&&o.appendChild(d("p",{className:"fillo-description",text:e.field.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}})),e.error&&o.appendChild(d("p",{className:"fillo-error",text:e.error,attrs:{id:e.ids.errorId,"data-fillo":"error"}})),o}let t=d("div",{className:`fillo-field fillo-field--checkbox${e.error?" fillo-field--error":""}`,attrs:{"data-fillo":"field","data-field":e.field.id,"data-kind":e.field.kind}});t.toggleAttribute("data-invalid",!!e.error),t.toggleAttribute("data-required",!!e.field.required);let n=d("label",{className:"fillo-option",attrs:{"data-fillo":"option"}});n.toggleAttribute("data-checked",e.value===!0);let r=d("input",{className:"fillo-option-input",attrs:{id:e.ids.inputId,type:"checkbox"}});r.checked=e.value===!0,r.addEventListener("change",()=>e.setValue(r.checked)),pe(r,e.field,e.error,e.ids);let i=d("span",{className:"fillo-option-label",text:gt(e.field),attrs:{"data-fillo":"optionLabel"}});return e.field.required||i.appendChild(d("span",{className:"fillo-optional",text:" (optional)"})),L(n,[r,i]),t.appendChild(n),e.field.description&&t.appendChild(d("p",{className:"fillo-description",text:e.field.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}})),e.error&&t.appendChild(d("p",{className:"fillo-error",text:e.error,attrs:{id:e.ids.errorId,"data-fillo":"error"}})),t}function Jl(e){if(e.field.kind!=="rating")return d("div");let t=typeof e.field.max=="number"?e.field.max:5,n=typeof e.value=="number"?e.value:0,r=Array.from({length:t},(a,l)=>l+1),i=n>0?n:null,o=i===null?0:Math.max(0,r.indexOf(i)),s=d("div",{className:"fillo-rating",attrs:{id:e.ids.inputId,role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});pe(s,e.field,e.error,e.ids);for(let[a,l]of r.entries()){let c=d("button",{className:`fillo-star${l<=n?" fillo-star--active":""}`,text:l<=n?"\u2605":"\u2606",attrs:{type:"button",role:"radio","aria-label":`${l} of ${t}`,"aria-checked":String(l===n),tabindex:String(a===o?0:-1),"data-fillo":"option"}});c.toggleAttribute("data-selected",l<=n),c.addEventListener("click",u=>{u.detail===0&&l===n||e.setValue(l===n?null:l)}),s.appendChild(c)}return ms(s,r,i,a=>e.setValue(a)),ve(e.field,e.error,s,e.ids)}function Xl(e){if(e.field.kind!=="linear_scale")return d("div");let t=typeof e.field.min=="number"?e.field.min:1,n=typeof e.field.max=="number"?e.field.max:10,r=typeof e.value=="number"?e.value:null,i=Array.from({length:n-t+1},(m,f)=>t+f),o=r===null?0:Math.max(0,i.indexOf(r)),s=`${e.ids.inputId}-min`,a=`${e.ids.inputId}-max`,l=d("div"),c=d("div",{className:"fillo-scale",attrs:{id:e.ids.inputId,role:"radiogroup","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});pe(c,e.field,e.error,e.ids);let u=[e.field.minLabel?s:null,e.field.maxLabel?a:null,c.getAttribute("aria-describedby")].filter(Boolean).join(" ");u&&c.setAttribute("aria-describedby",u);for(let[m,f]of i.entries()){let h=d("button",{className:`fillo-scale-step${e.value===f?" fillo-scale-step--active":""}`,text:String(f),attrs:{type:"button",role:"radio","aria-label":String(f),"aria-checked":String(e.value===f),tabindex:String(m===o?0:-1),"data-fillo":"option"}});h.toggleAttribute("data-selected",e.value===f),h.addEventListener("click",p=>{p.detail===0&&e.value===f||e.setValue(e.value===f?null:f)}),c.appendChild(h)}return ms(c,i,r,m=>e.setValue(m)),l.appendChild(c),("minLabel"in e.field||"maxLabel"in e.field)&&L(l,[L(d("div",{className:"fillo-scale-labels"}),[d("span",{text:String(e.field.minLabel??""),attrs:{id:s}}),d("span",{text:String(e.field.maxLabel??""),attrs:{id:a}})])]),ve(e.field,e.error,l,e.ids)}function Yl(e){let t=e.field;if(t.kind!=="ranking")return null;let n=e.announce,r=Array.isArray(e.value)?e.value:[],i=[...r.filter(a=>t.options.some(l=>l.id===a)),...t.options.map(a=>a.id).filter(a=>!r.includes(a))],o=d("div",{attrs:{id:e.ids.inputId,role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});pe(o,e.field,e.error,e.ids,{requiredSupported:!1});let s=d("ol",{className:"fillo-ranking"});for(let[a,l]of i.entries()){let c=t.options.find(b=>b.id===l);if(!c)continue;let u=d("li",{className:"fillo-ranking-item"}),m=d("span",{className:"fillo-ranking-controls"}),f=b=>{let v=a+b;if(v<0||v>=i.length)return;let y=[...i];[y[a],y[v]]=[y[v],y[a]],e.setValue(y),n?.(R.rankingPosition(c.label,v+1,i.length))},h=d("button",{className:"fillo-ranking-move",text:"\u2191",attrs:{type:"button","data-fillo-rank-opt":l,"data-fillo-rank-dir":"up","aria-label":`Move ${c.label} up`}});h.toggleAttribute("disabled",a===0),h.addEventListener("click",()=>f(-1));let p=d("button",{className:"fillo-ranking-move",text:"\u2193",attrs:{type:"button","data-fillo-rank-opt":l,"data-fillo-rank-dir":"down","aria-label":`Move ${c.label} down`}});p.toggleAttribute("disabled",a===i.length-1),p.addEventListener("click",()=>f(1)),L(m,[h,p]),L(u,[d("span",{className:"fillo-ranking-index",text:String(a+1)}),d("span",{className:"fillo-ranking-label",text:c.label}),m]),s.appendChild(u)}return o.appendChild(s),ve(e.field,e.error,o,e.ids)}function Ql(e){let t=e.field;if(t.kind!=="matrix")return null;let n=e.value&&typeof e.value=="object"&&!Array.isArray(e.value)?e.value:{},r=d("table",{className:"fillo-matrix"}),i=document.createElement("thead"),o=document.createElement("tr");o.appendChild(document.createElement("td"));for(let l of t.columns)o.appendChild(d("th",{text:l.label,attrs:{scope:"col"}}));i.appendChild(o),r.appendChild(i);let s=document.createElement("tbody");for(let l of t.rows){let c=`${e.ids.inputId}-${l.id}`,u=n[l.id]!==void 0,m=!!e.error&&!!t.required&&!u,f=v=>`${e.ids.inputId}-${l.id}-${v.id}`,h=document.createElement("tr"),p=d("th",{attrs:{scope:"row"}}),b=d("div",{attrs:{role:"radiogroup","aria-labelledby":`${e.ids.labelId} ${c}`,"aria-owns":t.columns.map(f).join(" ")}});b.appendChild(d("span",{text:l.label,attrs:{id:c}})),p.appendChild(b),h.appendChild(p);for(let v of t.columns){let y=d("td",{attrs:{"data-label":v.label}}),F=d("label",{className:"fillo-matrix-cell"}),I=d("input",{className:"fillo-option-input",attrs:{id:f(v),type:"radio",name:`${e.ids.name}-${l.id}`,"aria-label":`${l.label}: ${v.label}`}});t.required&&I.setAttribute("aria-required","true"),m&&I.setAttribute("aria-invalid","true"),I.checked=n[l.id]===v.id,I.addEventListener("change",()=>e.setValue({...n,[l.id]:v.id})),F.appendChild(I),y.appendChild(F),h.appendChild(y)}s.appendChild(h)}r.appendChild(s);let a=d("div",{className:"fillo-matrix-wrap",attrs:{id:e.ids.inputId,role:"group","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});return pe(a,e.field,e.error,e.ids,{requiredSupported:!1}),a.appendChild(r),ve(e.field,e.error,a,e.ids)}function ec(e){let t=d("div",{className:"fillo-signature-field"}),n=d("div",{className:"fillo-signature",attrs:{"data-fillo":"control"}}),r=d("canvas",{className:"fillo-signature-canvas",attrs:{role:"img"}}),i=d("button",{className:"fillo-signature-clear",text:"Clear",attrs:{type:"button"}}),o=d("div",{className:"fillo-signature-hint",text:"Sign here",attrs:{"aria-hidden":"true"}});r.width=720,r.height=220;let s=r.getContext("2d"),a=!1,l=typeof e.value=="string"&&e.value.startsWith("data:image/"),c=()=>{r.setAttribute("aria-label",l?R.signatureSigned:R.signatureEmpty)};if(c(),l&&s){let v=new Image;v.onload=()=>s.drawImage(v,0,0,r.width,r.height),v.src=String(e.value),o.style.display="none"}let u=d("input",{className:"fillo-input fillo-signature-type-input",attrs:{id:e.ids.inputId,type:"text",autocomplete:"name"}});pe(u,e.field,e.error,e.ids);let m=v=>{s&&(s.clearRect(0,0,r.width,r.height),v.trim()?(s.fillStyle=getComputedStyle(r).color||"#18181b",s.font=`italic ${Math.min(96,r.height*.45)}px "Segoe Script", "Brush Script MT", cursive`,s.textBaseline="middle",s.fillText(v,24,r.height/2),l=!0,o.style.display="none",e.setValue(r.toDataURL("image/png"),{render:!1})):(l=!1,o.style.display="",e.setValue(null,{render:!1})),c())};u.addEventListener("input",()=>m(u.value));let f=v=>{let y=r.getBoundingClientRect();return{x:(v.clientX-y.left)/y.width*r.width,y:(v.clientY-y.top)/y.height*r.height}};r.addEventListener("pointerdown",v=>{if(!s)return;a=!0,l=!0,o.style.display="none",c(),u.value&&(u.value=""),r.setPointerCapture(v.pointerId);let y=f(v);s.beginPath(),s.moveTo(y.x,y.y)}),r.addEventListener("pointermove",v=>{if(!a||!s)return;let y=f(v);s.lineWidth=2.4,s.lineCap="round",s.strokeStyle=getComputedStyle(r).color||"#18181b",s.lineTo(y.x,y.y),s.stroke()});let h=()=>{a&&(a=!1,l&&e.setValue(r.toDataURL("image/png"),{render:!1}))};r.addEventListener("pointerup",h),r.addEventListener("pointercancel",h),i.addEventListener("click",()=>{s?.clearRect(0,0,r.width,r.height),l=!1,o.style.display="",u.value="",c(),e.setValue(null,{render:!1})}),L(n,[r,o,i]);let p=d("div",{className:"fillo-signature-type"}),b=d("label",{className:"fillo-signature-type-label",text:"Or type your full name to sign",attrs:{for:e.ids.inputId}});return L(p,[b,u]),L(t,[n,p]),ve(e.field,e.error,t,e.ids)}function ns(e){return e<1024?`${e} B`:e<1024**2?`${(e/1024).toFixed(0)} KB`:e<1024**3?`${(e/1024**2).toFixed(1)} MB`:`${(e/1024**3).toFixed(2)} GB`}function Dt(e,t=22){let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("class","fillo-file-state-icon"),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("fill","none"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");for(let r of e){let i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d",r),n.appendChild(i)}return n}function rs(e){let t=d("span",{className:`fillo-file-state fillo-file-state--${e}`,attrs:{"aria-hidden":"true"}});return t.appendChild(Dt(e==="done"?["M3.75 12a8.25 8.25 0 1 0 16.5 0 8.25 8.25 0 1 0-16.5 0","m8.5 12 2.25 2.25 4.75-5"]:e==="failed"?["M3.75 12a8.25 8.25 0 1 0 16.5 0 8.25 8.25 0 1 0-16.5 0","M12 7.75v5.5","M12 16.5h.01"]:["M7.25 3.75h6.5l3 3v13.5h-9.5z","M13.75 3.75v3h3"])),t}function Pr(){let e=Dt(["m7 7 10 10M17 7 7 17"],16);return e.setAttribute("class","fillo-file-action-icon"),e}function is(e){let t=Dt([e],16);return t.setAttribute("class","fillo-group-icon"),t}function yn(e,t,n,r){let i=d("button",{className:e,attrs:{type:"button","aria-label":t}});return i.append(n),i.addEventListener("click",r),i}function tc(e){let t=e.field;if(t.kind!=="file_upload")return null;let n=e,r=n.uploadDisabledReason,i=r===void 0,o=t.maxFiles??1,s=t.maxFileSizeMb??500,a=Array.isArray(e.value)?e.value:[],l=n.uploadRows??[],c=o-a.length-l.filter(f=>f.error===void 0).length,u=d("div");if(c>0){let f=d("input",{className:"fillo-input",attrs:{id:e.ids.inputId,type:"file",hidden:""}});o>1&&(f.multiple=!0),t.accept?.length&&(f.accept=t.accept.join(",")),f.disabled=!i,f.addEventListener("change",()=>{if(!i)return;let p=Array.from(f.files??[]);f.value="",e.uploadFiles?.(t,p)});let h=d("div",{className:`fillo-dropzone${i?"":" fillo-dropzone--disabled"}`,attrs:{role:"button",tabindex:"0","aria-labelledby":e.ids.labelId,"data-fillo":"control"}});if(pe(h,t,e.error,e.ids,{requiredSupported:!1}),i||h.setAttribute("aria-disabled","true"),h.addEventListener("dragover",p=>{p.preventDefault(),h.classList.add("fillo-dropzone--over"),h.setAttribute("data-drag-over","")}),h.addEventListener("dragleave",()=>{h.classList.remove("fillo-dropzone--over"),h.removeAttribute("data-drag-over")}),h.addEventListener("drop",p=>{p.preventDefault(),h.classList.remove("fillo-dropzone--over"),h.removeAttribute("data-drag-over"),i&&e.uploadFiles?.(t,Array.from(p.dataTransfer?.files??[]))}),h.addEventListener("click",()=>{i&&f.click()}),h.addEventListener("keydown",p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),i&&f.click())}),h.appendChild(f),i)L(h,[d("span",{className:"fillo-dropzone-title",text:R.dropzoneTitle(o>1)}),d("span",{className:"fillo-dropzone-hint",text:R.dropzoneHint(s)})]);else if(r==="render_only")h.appendChild(d("span",{className:"fillo-dropzone-hint",text:R.uploadsRenderOnly}));else if(n.storageFixUrl){let p=d("span",{className:"fillo-dropzone-hint",text:"Connect file storage to enable uploads"});p.append(" \u2014 "),p.appendChild(d("a",{text:n.storageFixUrl,attrs:{href:n.storageFixUrl,target:"_blank",rel:"noopener noreferrer"}})),h.appendChild(p)}else h.appendChild(d("span",{className:"fillo-dropzone-hint",text:R.uploadsUnavailable}));u.appendChild(h)}if(a.length>0||l.length>0){let f=d("ul",{className:"fillo-files"});for(let h of a){let p=d("li",{className:"fillo-file fillo-file--done"}),b=d("span",{className:"fillo-file-content"});L(b,[d("span",{className:"fillo-file-name",text:h.name}),d("span",{className:"fillo-file-meta",text:R.uploadedFile(ns(h.size))})]);let v=d("span",{className:"fillo-file-actions"});v.appendChild(yn("fillo-file-remove",`${R.uploadRemove} ${h.name}`,Pr(),()=>e.setValue(a.filter(y=>y.fileId!==h.fileId)))),L(p,[rs("done"),b,v]),f.appendChild(p)}for(let h of l){let p=h.error!==void 0,b=d("li",{className:`fillo-file${p?" fillo-file--failed":""}`});b.appendChild(rs(p?"failed":"uploading"));let v=d("span",{className:"fillo-file-content"});if(v.appendChild(d("span",{className:"fillo-file-name",text:h.name})),p){let y=d("span",{className:"fillo-file-actions"});v.appendChild(d("span",{className:"fillo-file-error",text:h.error??""})),b.appendChild(v),!h.tooLarge&&c>0&&y.appendChild(yn("fillo-file-retry",`${R.uploadRetry} ${h.name}`,R.uploadRetry,()=>n.uploadAction?.(h.key,"retry"))),y.appendChild(yn("fillo-file-remove",`${R.uploadDismiss} ${h.name}`,Pr(),()=>n.uploadAction?.(h.key,"dismiss"))),b.appendChild(y)}else{let y=d("span",{className:"fillo-progress-bar"});y.style.width=`${h.fraction*100}%`,v.appendChild(d("span",{className:"fillo-file-meta",text:R.uploadingFile(Math.round(h.fraction*100),ns(h.size))}));let F=d("span",{className:"fillo-file-actions"});F.appendChild(yn("fillo-file-remove",`${R.uploadCancel} ${h.name}`,Pr(),()=>n.uploadAction?.(h.key,"cancel"))),L(b,[v,F,L(d("span",{className:"fillo-progress",attrs:{role:"progressbar","aria-label":`Uploading ${h.name}`,"aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":String(Math.round(h.fraction*100))}}),[y])])}f.appendChild(b)}u.appendChild(f)}let m=n.uploadNotice;return m&&u.appendChild(d("p",{className:"fillo-upload-notice",text:m})),ve(t,e.error,u,e.ids)}function nc(e){let t=e.field,n=d("div",{className:"fillo-field fillo-field--calculated fillo-calculated",attrs:{"data-fillo":"calculated","data-field":t.id,"data-kind":t.kind}});n.appendChild(d("label",{className:"fillo-label",text:gt(t),attrs:{id:e.ids.labelId,for:e.ids.inputId,"data-fillo":"label"}})),t.description&&n.appendChild(d("p",{className:"fillo-description",text:t.description,attrs:{id:e.ids.descriptionId,"data-fillo":"fieldDescription"}}));let r=e.value,i=r!=null&&r!=="",o=d("output",{className:`fillo-calculated-value${i?"":" fillo-calculated-value--empty"}`,text:i?$r(t,r):"\u2014",attrs:{id:e.ids.inputId}});return t.description&&o.setAttribute("aria-describedby",e.ids.descriptionId),n.appendChild(o),n}var os=new Map;function Dr(e){if(!e.shuffleOptions)return e.options;let t=`${e.id}|${e.options.map(o=>o.id).join(",")}`,n=os.get(t);if(!n){n=e.options.map(o=>o.id);for(let o=n.length-1;o>0;o--){let s=Math.floor(Math.random()*(o+1));[n[o],n[s]]=[n[s],n[o]]}os.set(t,n)}let r=new Map(e.options.map(o=>[o.id,o])),i=n.flatMap(o=>r.get(o)??[]);return i.length===e.options.length?i:e.options}function Pt(e){let t=e.getValue?.()??e.value;return Array.isArray(t)?t:[]}function rc(e,t){return Math.max(t.length,e.minInstances??1)}function ic(e){return Math.max(e.minInstances??1,0)}function Rr(e,t){let n=[...e];for(;n.length<t;)n.push({});return n}function oc(e){let t=e.field;if(t.kind!=="repeating_group")return null;let n=e,r=n.announce,i=n.instanceId??"",o=t.itemLabel?.trim()||gt(t),s=Pt(e),a=rc(t,s),l=ic(t),c=d("div",{className:"fillo-group",attrs:{id:e.ids.inputId,"data-fillo":"control"}});pe(c,t,e.error,e.ids,{requiredSupported:!1});for(let f=0;f<a;f++){let h=s[f]??{},p=R.groupInstanceLabel(o,f+1,a),b=d("div",{className:"fillo-group-instance",attrs:{role:"group","aria-label":p,tabindex:"-1"}}),v=d("div",{className:"fillo-group-instance-header"}),y=d("button",{className:"fillo-group-remove",attrs:{type:"button","aria-label":R.groupRemoveLabel(o,f+1)}});y.appendChild(is("M6 6l12 12M18 6 6 18"));let F=a>l;y.toggleAttribute("disabled",!F),F||(y.setAttribute("aria-disabled","true"),y.setAttribute("title",`At least ${l} ${l===1?"entry":"entries"} required`)),y.addEventListener("click",()=>{if(a<=l)return;let I=Rr(Pt(e),a);I.splice(f,1),e.setValue(I),n.setGroupFocus?.({groupId:t.id,cardIndex:f-1,intoControl:!1}),r?.(R.groupInstanceRemoved(o,I.length))}),L(v,[d("p",{className:"fillo-group-instance-title",text:p}),y]),b.appendChild(v);for(let I of gn(t,h)){let ee=`${t.id}.${f}.${I.id}`,xe={...I,id:ee},M=fs(i,ee),ne=(U,ie)=>{let Ae=Rr(Pt(e),a);Ae[f]={...Ae[f]??{},[I.id]:U},e.setValue(Ae,ie)},re={field:xe,value:h[I.id],error:e.api.errors[ee],ids:M,api:e.api,setValue:ne,getValue:()=>Pt(e)[f]?.[I.id],announce:n.announce,announceAlert:n.announceAlert,registerOverlay:n.registerOverlay,activeOtherFields:n.activeOtherFields},Qe=n.renderChildField?.(re)??gs(re);Qe&&b.appendChild(Qe)}c.appendChild(b)}let u=a>=t.maxInstances,m=d("button",{className:"fillo-group-add",attrs:{type:"button"}});return m.append(is("M12 5v14M5 12h14"),t.addLabel||R.groupAdd),m.toggleAttribute("disabled",u),u&&(m.setAttribute("aria-disabled","true"),m.setAttribute("title",`Maximum ${t.maxInstances} ${t.maxInstances===1?"entry":"entries"}`)),m.addEventListener("click",()=>{if(a>=t.maxInstances)return;let f=Rr(Pt(e),a);f.push({}),e.setValue(f),n.setGroupFocus?.({groupId:t.id,cardIndex:f.length-1,intoControl:!0}),r?.(R.groupInstanceAdded(o,f.length,f.length))}),c.appendChild(m),ve(t,e.error,c,e.ids)}var sc={short_text:e=>Tt("text",e),email:e=>Tt("email",e),url:e=>Tt("url",e),phone:jl,number:e=>Tt("number",e),date:e=>Tt("date",e),long_text:Vl,select:Hl,multi_select:Gl,dropdown:Wl,checkbox:Kl,rating:Jl,linear_scale:Xl,ranking:Yl,matrix:Ql,signature:ec,file_upload:tc,calculated:nc,repeating_group:oc};function gs(e){if(e.field.kind==="hidden"||e.field.kind==="custom")return null;let t=sc[e.field.kind];return t?t(e):null}var ac="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",ss="fillo-turnstile-script",lc=2e4,cc=/^[A-Za-z0-9_-]{1,255}$/,Rt=null;function vt(){return globalThis.turnstile}function uc(){return typeof window>"u"||typeof document>"u"?Promise.reject(new Error("Turnstile needs a browser")):vt()?Promise.resolve():Rt||(Rt=new Promise((e,t)=>{let n=()=>{vt()?e():t(new Error("Turnstile loaded without its global"))},r=document.getElementById(ss);if(r){if(vt()){e();return}r.addEventListener("load",n,{once:!0}),r.addEventListener("error",()=>t(new Error("Turnstile script failed to load")),{once:!0});return}let i=document.createElement("script");i.id=ss,i.src=ac,i.async=!0,i.defer=!0,i.addEventListener("load",n,{once:!0}),i.addEventListener("error",()=>{i.remove(),Rt=null,t(new Error("Turnstile script failed to load"))},{once:!0}),document.head.appendChild(i)}),Rt)}function as(){return d("div",{className:"fillo-turnstile",attrs:{"data-fillo":"turnstile"}})}var Bt=class{constructor(t,n){this.target=t;this.options=n;this.element.className="fillo-dom-root",n.preview===!0&&yc(),t.replaceChildren(this.element,this.statusEl,this.alertEl),this.resolve()}target;options;element=d("div");statusEl=d("span",{className:"fillo-sr-only",attrs:{role:"status","aria-live":"polite","data-fillo":"announce"}});alertEl=d("span",{className:"fillo-sr-only",attrs:{role:"alert","data-fillo":"announce-alert"}});instanceId=`d${++Tl}`;schema=null;theme;formId;closed=!1;fetchedPoweredBy=null;fetchedBrandLabel;fetchedBrandHref;phase="loading";engine=null;destroyed=!1;renderQueued=!1;hpValue="";liveSubmissionHandled=!1;activeOtherFields=new Set;inFlight=new Map;uploadNotices=new Map;focusIntent=null;overlays=new Set;challenge;challengeToken;challengeError=!1;turnstileContainer=as();turnstileWidgetId=null;turnstileSiteKey;turnstileLoadInFlight=!1;turnstileAttempt=0;challengeFrame=null;challengeFrameSrc=null;challengeFrameOrigin=null;challengeMessageHandler=null;challengeWatchdog=null;announce=t=>{this.statusEl.textContent="",requestAnimationFrame(()=>{this.statusEl.textContent=t})};announceAlert=t=>{this.alertEl.textContent="",requestAnimationFrame(()=>{this.alertEl.textContent=t})};devChrome(){return this.options.preview===!0||pc()}get status(){return this.phase==="ready"?this.engine?.getState().status??"idle":this.phase}get data(){return this.engine?.getState().data??this.options.initialData??{}}get form(){return this.schema}get mutableData(){return this.engine?.getState().data??this.options.initialData??{}}api(){let t=this.schema??{version:1,title:"",pages:[],settings:{}},n=this.engine?.getState(),r=n?.pageCount??t.pages.length;return{form:t,formId:this.formId,client:this.options.renderOnly?void 0:this.options.client,data:n?.data??this.mutableData,errors:n?.errors??{},status:this.status,pageIndex:n?.pageIndex??0,pageCount:r,page:n?.page??t.pages[0]??{id:"empty",blocks:[]},blocks:n?.blocks??[],isFirstPage:n?.isFirstPage??!0,isLastPage:n?.isLastPage??r<=1,setValue:(i,o,s)=>this.setValueInternal(i,o,s),next:()=>this.next(),back:()=>this.back(),submit:()=>this.submit()}}resolveFormIdFn;notOpenVariant=null;fatalError=null;genericUnavailable=!1;syncErrorNotice=null;stagedNotice=!1;draftNotice=!1;syncWarningCode;syncWarningUrl;syncFormUrl;uploadsAvailable;uploadFileSizeLimitMb;resolutionFailureCode=null;async resolve(){try{this.challenge=this.options.renderOnly?void 0:this.options.challenge;let t=Nr(this.options.form)?this.options.form:null;if(t){if(this.options.renderOnly){this.setSchema(t.schema,this.options.theme??t.theme,void 0);return}let r=us(t.schema);if(r){await this.showPublishedInstead(r,t.schema,t.id);return}!this.options.client&&this.options.formId&&(this.options.client=Te());let i=this.options.client;if(i?.key&&(this.resolveFormIdFn=async()=>{try{let o=await Lr(i,t,{bypassCache:!0});if(this.syncWarningCode=o.warningCode,this.syncWarningUrl=o.warningUrl,this.syncFormUrl=o.manageUrl,this.uploadsAvailable=o.uploadsAvailable,this.uploadFileSizeLimitMb=o.uploadFileSizeLimitMb,o.status==="draft")throw new C("This form is no longer published. Submission was stopped before sending answers.",403,void 0,"form_not_published");if(o.accepting===!1)throw new C("This form is no longer accepting responses. Submission was stopped before sending answers.",403,void 0,o.acceptingReason??"form_not_accepting");let s=Ye(o.resolvedSchema??t.schema);if(!s.ok)throw new C(`The canonical form schema was invalid: ${s.error}`,502,void 0,"invalid_sync_schema");if(this.schema&&!Jo(this.schema,s.schema))throw new C("The live form changed after this page loaded. Submission stopped before incompatible answers were sent. Reload to use the published schema.",409,void 0,"form_schema_changed");return o.syncError&&this.reportSyncNotice(new C(o.syncError.message,403,void 0,o.syncError.code)),this.resolutionFailureCode=null,o.formId}catch(o){let s=Zt(o);throw this.resolutionFailureCode=s.code??"sync_failed",this.reportSubmitSyncFailure(s),s}}),!i?.key&&this.options.formId&&this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId),!i&&!this.options.formId)throw this.genericUnavailable=!this.devChrome(),ds();if(i&&!i.key&&!this.options.formId){this.reportSyncFailure(new C('Code forms need createClient({ key: "pk_\u2026" }) to resolve the live form. Pass a publishable key or a published formId.',401,void 0,"sync_key_required"));return}if(!i?.key)return;this.devChrome()?this.setSchema(t.schema,this.options.theme??t.theme,this.options.formId):(this.theme=this.options.theme??t.theme,this.render());try{let o=await Lr(i,t);if(this.destroyed)return;if((o.staged||o.syncError)&&!o.resolvedSchema)throw new C("Sync did not return the live schema needed to render safely. Publish changes before deploy, and update @usefillo/* or your API.",409,void 0,"sync_snapshot_required");let s=this.devChrome();if(this.notOpenVariant=s?null:o.status==="draft"?"notOpen":o.accepting===!1?ls(o.acceptingReason):null,this.stagedNotice=!!o.staged,this.draftNotice=o.status==="draft",this.syncWarningCode=o.warningCode,this.syncWarningUrl=o.warningUrl,this.syncFormUrl=o.manageUrl,this.uploadsAvailable=o.uploadsAvailable,this.uploadFileSizeLimitMb=o.uploadFileSizeLimitMb,this.challenge=this.options.challenge??o.challenge,o.branding&&(this.fetchedPoweredBy=o.branding.poweredBy,this.fetchedBrandLabel=o.branding.label,this.fetchedBrandHref=o.branding.href),s&&o.resolvedSchema)this.formId=o.formId,this.engine?.setContext({formId:o.formId}),this.render();else{let l=o.resolvedSchema??t.schema,c=this.options.theme??(o.resolvedSchema?o.resolvedTheme??void 0:t.theme);this.applyCanonicalSchema(l,c,o.formId)}o.warning&&console.warn(`[fillo] ${o.warning}`),o.syncError&&this.reportSyncNotice(new C(o.syncError.message,403,void 0,o.syncError.code));let a=o.warningUrl?` \u2014 connect storage to publish: ${o.warningUrl}`:"";o.staged?console.info(`[fillo] "${t.id}" changes staged as a draft \u2014 rendering the live version until you publish them in your Fillo dashboard${a}`):o.status==="draft"&&console.info(`[fillo] "${t.id}" is a draft \u2014 it renders here but won't accept responses until published${a}`)}catch(o){if(this.destroyed)return;this.reportSyncFailure(Zt(o))}return}let n=this.options.form&&!Nr(this.options.form)?this.options.form:null;if(n){if(this.options.renderOnly){this.setSchema(n,this.options.theme,void 0);return}if(!this.options.formId)throw this.genericUnavailable=!this.devChrome(),ds();this.options.client??=Te();let r=us(n);if(r){await this.showPublishedInstead(r,n,void 0);return}this.setSchema(n,this.options.theme,this.options.formId);return}if(!this.options.formId)throw new C("Provide either `form`, or a `formId`.",0);this.options.client??=Te(),await this.loadPublished(this.options.formId)}catch(t){if(this.destroyed)return;this.handleError(Zt(t))}}async showPublishedInstead(t,n,r){let i=new C(`This form's definition is invalid: ${t}. In production, Fillo shows the published version of this form instead.`,422,void 0,Ot);if(this.devChrome()){this.handleError(i);return}this.options.onError?.(i),this.render(),!this.options.client&&this.options.formId&&(this.options.client=Te());let o=await Yo(this.options.client,{formId:this.options.formId,handle:r,definition:n,reason:t});if(!this.destroyed){if(!o){this.fatalError=i,this.phase="error",this.render(i);return}this.options.client??=Te();try{await this.loadPublished(o)}catch{if(this.destroyed)return;this.fatalError=i,this.phase="error",this.render(i)}}}async loadPublished(t){let n=this.options.client??Te();this.options.client=n,this.render();let r=await n.getForm(t);if(!this.destroyed){if(r.accepting===!1?this.notOpenVariant=ls(r.acceptingReason):this.closed=!!r.closed,this.uploadsAvailable=r.uploadsAvailable,this.uploadFileSizeLimitMb=r.uploadFileSizeLimitMb,this.fetchedPoweredBy=r.branding?.poweredBy??null,this.fetchedBrandLabel=r.branding?.label,this.fetchedBrandHref=r.branding?.href,this.challenge=this.options.challenge??r.challenge,r.accepting===!1&&this.options.renderError){let i=this.notOpenVariant==="closed"?"This form is no longer accepting responses.":"This form isn't accepting responses yet.";this.fatalError=new C(i,403,void 0,r.acceptingReason),this.phase="error",this.render(this.fatalError);return}this.setSchema(r.schema,this.options.theme??r.theme??void 0,r.id)}}setSchema(t,n,r){if(this.destroyed)return;let i=Ye(t);if(!i.ok)throw new C(`This form could not be rendered: ${i.error}`,422,void 0,Ot);let o=i.schema;this.schema=o,this.theme=n;let s=this.options.renderOnly===!0;this.formId=s?void 0:r;let a=this.notOpenVariant!==null,l=a||s,c=this;this.engine=jo({form:o,formId:l?void 0:r,client:l?void 0:this.options.client,initialData:this.options.initialData,onChange:a?void 0:this.options.onChange,onSubmitted:l?void 0:this.options.onSubmitted,getHoneypot:()=>this.element.querySelector('input[name="fillo_hp_field"]')?.value??this.hpValue,surface:"default",resolveFormId:l?void 0:this.resolveFormIdFn,skipValidation:s,verboseResolutionErrors:this.devChrome(),respondent:l?void 0:this.options.respondent,get challengeRequired(){return!l&&!!c.challenge},getChallengeToken:()=>this.challengeToken,onChallengeFailed:()=>this.resetChallengeWidget()});let u=this.engine.getState().status,m=this.engine.getState().resumedDraft,f=this.engine.getState().editingPrevious,h=this.engine.getState().errors,p=this.engine.getState().resumeLinkFailed;this.engine.subscribe(()=>{let b=this.engine?.getState();b&&(b.status!==u||b.resumedDraft!==m||b.editingPrevious!==f||b.errors!==h||b.resumeLinkFailed!==p)&&(b.editingPrevious&&!f?this.announce(P.editNotice):b.resumedDraft&&!m?this.announce(P.resumeNotice):b.resumeLinkFailed&&!p&&this.announce(R.resumeLinkExpired),u=b.status,m=b.resumedDraft,f=b.editingPrevious,h=b.errors,p=b.resumeLinkFailed,this.queueRender())}),l||this.configureDraftFlush(o),this.phase=this.closed?"closed":"ready",this.render()}applyCanonicalSchema(t,n,r){if(!this.engine){this.setSchema(t,n,r);return}let i=Ye(t);if(!i.ok)throw new C(`This form could not be rendered: ${i.error}`,422,void 0,Ot);let o=i.schema;this.schema=o,this.theme=n,this.formId=r,this.engine.setContext({form:o,formId:r}),this.notOpenVariant===null&&this.configureDraftFlush(o),this.phase=this.closed?"closed":"ready",this.render()}draftFlushWired=!1;flushDraftBound=()=>this.engine?.flushDraft();visibilityFlushBound=()=>{document.visibilityState==="hidden"&&this.engine?.flushDraft()};configureDraftFlush(t){this.teardownDraftFlush(),t.settings.saveProgress&&typeof window<"u"&&(window.addEventListener("pagehide",this.flushDraftBound),document.addEventListener("visibilitychange",this.visibilityFlushBound),this.draftFlushWired=!0)}teardownDraftFlush(){!this.draftFlushWired||typeof window>"u"||(window.removeEventListener("pagehide",this.flushDraftBound),document.removeEventListener("visibilitychange",this.visibilityFlushBound),this.draftFlushWired=!1)}flushDraft(){this.engine?.flushDraft()}resetDraft(){this.engine?.resetDraft(),this.queueRender()}setValue(t,n){this.setValueInternal(t,n)}setValueInternal(t,n,r={}){this.notOpenVariant||(this.engine?.setValue(t,n),r.render!==!1&&this.queueRender())}next(){if(!this.engine||this.notOpenVariant)return;let t=this.engine.getState().pageIndex;this.engine.next(),this.focusIntent=this.engine.getState().pageIndex!==t?"page":"error",this.render()}back(){!this.engine||this.notOpenVariant||(this.engine.back(),this.focusIntent="page",this.render())}async submit(){if(!this.engine||this.phase!=="ready"||this.notOpenVariant)return;let t=this.engine.submit();this.hasErrors()?this.focusIntent="error":this.engine.getState().status==="submitting"&&this.announce(R.submittingAnnouncement),this.render();try{await t}catch(n){this.options.onError?.(Zt(n)),this.focusIntent="error",this.render();return}this.hasErrors()&&(this.focusIntent="error"),this.render()}hasErrors(){return Object.keys(this.engine?.getState().errors??{}).length>0}setTheme(t){this.options.theme=t,this.theme=t,this.render()}setClient(t){this.options.client=t,this.engine?.setContext({client:t}),this.render()}setRespondent(t){this.options.respondent=t,this.engine?.setContext({respondent:t})}fieldActive(t){let n=0;for(let r of this.inFlight.values())r.fieldId===t&&r.error===void 0&&n++;return n}uploadRowsFor(t){let n=[];for(let[r,i]of this.inFlight)i.fieldId===t&&n.push({key:r,name:i.name,size:i.size,fraction:i.fraction,error:i.error,tooLarge:i.tooLarge});return n}uploadAction=(t,n)=>{let r=this.inFlight.get(t);if(r){if(n==="cancel")r.controller.abort(),this.inFlight.delete(t);else if(n==="dismiss")this.inFlight.delete(t);else{if(r.tooLarge)return;this.inFlight.delete(t),this.startUpload(r.fieldId,r.file,r.maxFiles)}this.fieldActive(r.fieldId)===0&&this.engine?.setUploading(r.fieldId,!1),this.queueRender()}};async startUpload(t,n,r){let i=`${n.name}-${n.size}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,o=new AbortController;this.inFlight.set(i,{fieldId:t,name:n.name,size:n.size,fraction:0,file:n,controller:o,maxFiles:r}),this.engine?.setUploading(t,!0),this.queueRender();try{let s=this.options.client&&this.formId?await this.options.client.uploadFile(this.formId,n,{fieldId:t,signal:o.signal,onProgress:l=>{let c=this.inFlight.get(i);c&&(c.fraction=l.fraction,this.queueRender())}}):{fileId:`local:${n.name}:${n.size}`,name:n.name,size:n.size,mime:n.type||"application/octet-stream"};if(this.destroyed)return;this.inFlight.delete(i);let a=r>1&&Array.isArray(this.mutableData[t])?this.mutableData[t]:[];this.setValueInternal(t,[...a,s])}catch(s){if(this.destroyed||o.signal.aborted)return;let a=Zt(s),l=a.status===0||a.status!==void 0&&a.status>=500?R.uploadUnavailable:R.uploadFailed,c=this.inFlight.get(i);c&&(c.error=l),this.announceAlert(l),this.options.onError?.(a)}finally{this.fieldActive(t)===0&&this.engine?.setUploading(t,!1),this.queueRender()}}async uploadFiles(t,n){if(!this.schema||this.notOpenVariant)return;let r=t.maxFiles??1,i=r>1&&Array.isArray(this.mutableData[t.id])?this.mutableData[t.id].length:0,o=Math.max(0,r-i-this.fieldActive(t.id)),s=n.slice(0,o),a=t.maxFileSizeMb??500,l=this.uploadFileSizeLimitMb?Math.min(a,this.uploadFileSizeLimitMb):a,c=l*1024*1024,u=s.filter(p=>p.size<=c),m=s.filter(p=>p.size>c),f=n.length-s.length,h=s.length-u.length;if(f>0||h>0){let p=[];f>0&&p.push(`You can attach up to ${r} file${r===1?"":"s"}. ${f} ${f===1?"file was":"files were"} not added.`);let b=p.join(" ");b?this.uploadNotices.set(t.id,b):this.uploadNotices.delete(t.id),b&&this.announce(b)}else this.uploadNotices.delete(t.id);for(let p of m){let b=R.fileTooLarge(l),v=`${p.name}-${p.size}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`;this.inFlight.set(v,{fieldId:t.id,name:p.name,size:p.size,fraction:0,error:b,tooLarge:!0,file:p,controller:new AbortController,maxFiles:r}),this.announceAlert(b)}if(u.length===0){this.queueRender();return}await Promise.all(u.map(p=>this.startUpload(t.id,p,r)))}destroy(){this.destroyed=!0,this.teardownDraftFlush(),this.closeOverlays(),this.teardownTurnstileWidget();for(let t of this.inFlight.values())t.controller.abort();this.inFlight.clear(),this.engine?.destroy(),this.engine=null,this.target.replaceChildren()}storageBlocked(){return this.uploadsAvailable===!1}registerOverlay=t=>(this.overlays.add(t),()=>this.overlays.delete(t));closeOverlays(){if(this.overlays.size!==0){for(let t of Array.from(this.overlays))try{t()}catch{}this.overlays.clear()}}ensureChallengeWidget(t){t.bridgeUrl?this.ensureChallengeBridge(t.bridgeUrl):this.ensureTurnstileWidget(t.siteKey)}ensureChallengeBridge(t){if(typeof window>"u")return;let n;try{n=new URL(t)}catch{this.handleChallengeError();return}if(n.protocol!=="https:"&&n.protocol!=="http:"){this.handleChallengeError();return}n.searchParams.set("origin",window.location.origin),n.searchParams.set("theme",this.options.challengeTheme??"auto"),this.formId&&cc.test(this.formId)&&n.searchParams.set("cdata",this.formId),n.searchParams.set("appearance",(this.options.challengeAppearance??"interaction-only")==="interaction-only"?"interaction-only":"always");let r=n.toString();if(this.challengeFrame&&this.challengeFrameSrc===r)return;this.teardownTurnstileWidget();let i=++this.turnstileAttempt,o=d("iframe",{className:"fillo-turnstile-frame",attrs:{src:r,title:"Human verification",width:"300",height:"65",referrerpolicy:"no-referrer"}});this.challengeFrame=o,this.challengeFrameSrc=r,this.challengeFrameOrigin=n.origin,this.turnstileContainer.appendChild(o),this.setChallengeFrameVisible((this.options.challengeAppearance??"interaction-only")!=="interaction-only");let s=a=>{if(i!==this.turnstileAttempt||this.destroyed||a.origin!==this.challengeFrameOrigin||!this.challengeFrame||a.source!==this.challengeFrame.contentWindow)return;let l=a.data;switch(l?.type){case"fillo:challenge:ready":this.settleChallengeWatchdog();break;case"fillo:challenge:token":this.settleChallengeWatchdog(),typeof l.token=="string"&&l.token.length>0&&this.handleChallengeToken(l.token),(this.options.challengeAppearance??"interaction-only")==="interaction-only"&&this.setChallengeFrameVisible(!1);break;case"fillo:challenge:interactive":this.setChallengeFrameVisible(!0);break;case"fillo:challenge:interactive-done":(this.options.challengeAppearance??"interaction-only")==="interaction-only"&&this.setChallengeFrameVisible(!1);break;case"fillo:challenge:expired":this.handleChallengeToken(void 0);break;case"fillo:challenge:error":this.settleChallengeWatchdog(),this.handleChallengeToken(void 0),this.handleChallengeError();break}};this.challengeMessageHandler=s,window.addEventListener("message",s),this.challengeWatchdog=window.setTimeout(()=>{i!==this.turnstileAttempt||this.destroyed||(this.handleChallengeToken(void 0),this.handleChallengeError())},lc)}setChallengeFrameVisible(t){let n=this.challengeFrame;n&&(n.setAttribute("height",t?"65":"0"),t?(n.removeAttribute("aria-hidden"),n.removeAttribute("tabindex")):(n.setAttribute("aria-hidden","true"),n.setAttribute("tabindex","-1")),this.turnstileContainer.setAttribute("data-fillo-challenge-visible",t?"true":"false"))}settleChallengeWatchdog(){this.challengeWatchdog!==null&&typeof window<"u"&&window.clearTimeout(this.challengeWatchdog),this.challengeWatchdog=null}teardownChallengeBridge(){this.challengeMessageHandler&&typeof window<"u"&&window.removeEventListener("message",this.challengeMessageHandler),this.challengeMessageHandler=null,this.settleChallengeWatchdog(),this.challengeFrame?.remove(),this.challengeFrame=null,this.challengeFrameSrc=null,this.challengeFrameOrigin=null}ensureTurnstileWidget(t){if(this.turnstileSiteKey!==t&&(this.teardownTurnstileWidget(),this.turnstileSiteKey=t),this.turnstileWidgetId!==null||this.turnstileLoadInFlight||this.challengeError)return;this.turnstileLoadInFlight=!0;let n=++this.turnstileAttempt;uc().then(()=>{if(this.destroyed||n!==this.turnstileAttempt)return;let r=vt();if(!r){this.turnstileLoadInFlight=!1,this.handleChallengeError();return}this.turnstileWidgetId=r.render(this.turnstileContainer,{sitekey:t,theme:"auto",callback:i=>this.handleChallengeToken(i),"error-callback":()=>{this.handleChallengeToken(void 0),this.handleChallengeError()},"expired-callback":()=>this.resetChallengeWidget(),"timeout-callback":()=>this.resetChallengeWidget()}),this.turnstileLoadInFlight=!1}).catch(()=>{this.destroyed||n!==this.turnstileAttempt||(this.turnstileLoadInFlight=!1,this.handleChallengeError())})}handleChallengeToken(t){this.challengeToken=t,t&&(this.challengeError=!1),this.queueRender()}handleChallengeError(){this.challengeError=!0,this.announceAlert(P.challengeUnavailable),this.queueRender()}resetChallengeWidget(){this.challengeToken=void 0,this.challengeFrame&&this.challengeFrameOrigin?this.challengeFrame.contentWindow?.postMessage({type:"fillo:challenge:reset"},this.challengeFrameOrigin):this.turnstileWidgetId&&vt()?.reset(this.turnstileWidgetId),this.queueRender()}teardownTurnstileWidget(){if(this.turnstileWidgetId===null&&!this.turnstileLoadInFlight&&this.challengeFrame===null)return;this.turnstileAttempt++,this.teardownChallengeBridge();let t=vt();if(this.turnstileWidgetId&&t)try{t.remove(this.turnstileWidgetId)}catch{}this.turnstileWidgetId=null,this.turnstileLoadInFlight=!1,this.challengeError=!1,this.turnstileContainer=as(),this.challengeToken=void 0}captureFocus(){if(typeof document>"u")return null;let t=document.activeElement;if(!t||!this.element.contains(t))return null;let n={};t.id&&(n.id=t.id);let r=t.getAttribute("data-fillo-rank-opt");r&&(n.rankOpt=r,n.rankDir=t.getAttribute("data-fillo-rank-dir")??void 0);let i=t.closest("[data-field]");if(i&&(n.fieldId=i.getAttribute("data-field")??void 0,n.controlIndex=Array.from(i.querySelectorAll(Ut)).indexOf(t)),t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)try{n.selStart=t.selectionStart,n.selEnd=t.selectionEnd}catch{}return n.id||n.rankOpt||n.fieldId?n:null}restoreFocus(t){if(typeof document>"u")return;let n=null;if(t.rankOpt){let r=Array.from(this.element.querySelectorAll("[data-fillo-rank-opt]")).filter(i=>i.getAttribute("data-fillo-rank-opt")===t.rankOpt);n=r.find(i=>i.getAttribute("data-fillo-rank-dir")===t.rankDir&&!i.disabled)??r.find(i=>!i.disabled)??null}if(!n&&t.id&&(n=document.getElementById(t.id)),!n&&t.fieldId!=null&&t.controlIndex!=null&&t.controlIndex>=0){let r=Array.from(this.element.querySelectorAll("[data-field]")).find(i=>i.getAttribute("data-field")===t.fieldId);r&&(n=Array.from(r.querySelectorAll(Ut))[t.controlIndex]??null)}if(!(!n||typeof n.focus!="function")&&(n.focus(),(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&t.selStart!=null))try{n.setSelectionRange(t.selStart,t.selEnd??t.selStart)}catch{}}applyFocus(t,n){if(!(typeof document>"u")){if(t==="error"){let r=this.element.querySelector('[aria-invalid="true"]');r&&Pl(r)?.focus();return}if(t==="page"){let i=this.element.querySelector(".fillo-page-title, .fillo-title")??this.element.querySelector(".fillo-blocks");i&&(i.hasAttribute("tabindex")||i.setAttribute("tabindex","-1"),i.focus?.());return}if(t){this.applyGroupFocus(t);return}n&&this.restoreFocus(n)}}applyGroupFocus(t){let n=Array.from(this.element.querySelectorAll("[data-field]")).find(o=>o.getAttribute("data-field")===t.groupId),r=n?Array.from(n.querySelectorAll(".fillo-group-instance")):[],i=t.cardIndex>=0?r[t.cardIndex]:void 0;if(i){(t.intoControl?Rl(i)??i:i).focus();return}n?.querySelector(".fillo-group-add")?.focus()}handleError(t){this.destroyed||(this.fatalError=t,this.phase="error",this.options.onError?.(t),this.render(t))}reportSyncFailure(t){if(this.destroyed)return;console.warn(`[fillo] form sync failed${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t;let n=this.devChrome();if(!n||this.options.renderError){this.genericUnavailable=!n,this.handleError(t);return}this.options.onError?.(t),n&&this.render()}reportSyncNotice(t){this.destroyed||(console.warn(`[fillo] form sync needs attention${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t,this.options.onError?.(t),this.devChrome()&&this.render())}reportSubmitSyncFailure(t){this.destroyed||(console.warn(`[fillo] form sync failed${t.code?` (${t.code})`:""}: ${t.message}`),this.syncErrorNotice=t)}queueRender(){this.renderQueued||this.destroyed||(this.renderQueued=!0,setTimeout(()=>{this.renderQueued=!1,this.render()},0))}render(t){if(this.destroyed)return;let n=this.focusIntent;this.focusIntent=null;let r=n?null:this.captureFocus();if(this.closeOverlays(),this.phase==="ready"&&this.engine?.getState().status!=="submitted"||this.teardownTurnstileWidget(),this.element.replaceChildren(),this.phase==="loading"){let s=d("div",{className:`fillo-form fillo-form--loading ${this.options.className??""}`,attrs:{"aria-busy":"true","data-fillo":"root","data-state":"loading"}});bt(s,this.theme),L(s,[d("div",{className:"fillo-skeleton"}),d("div",{className:"fillo-skeleton"}),d("div",{className:"fillo-skeleton fillo-skeleton--short"})]),this.element.appendChild(s);return}let o=t??this.fatalError;if(this.phase==="error"&&o){let s=o.code===Ot;if(s&&!this.devChrome()&&!this.options.renderOnly&&!this.options.renderError){let c=d("div",{attrs:{"data-fillo":"root","data-state":"unavailable","data-error-code":Ot}});c.hidden=!0,this.element.appendChild(c);return}let a=o.code==="form_target_required"&&this.devChrome()?`${o.message} (${o.code})`:s&&this.devChrome()?o.message:null,l=this.options.renderError?.(o)??d("div",{className:"fillo-form fillo-form--error",text:a??(this.genericUnavailable?"This form is unavailable.":_c(o))});l.hasAttribute("data-fillo")||l.setAttribute("data-fillo","root"),l.hasAttribute("data-state")||l.setAttribute("data-state","error"),o.code&&!l.hasAttribute("data-error-code")&&l.setAttribute("data-error-code",o.code),l.hasAttribute("role")||l.setAttribute("role","alert"),bt(l,this.theme),this.element.appendChild(l);return}if(this.phase==="closed"){let s=d("div",{className:`fillo-form fillo-form--closed ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});bt(s,this.theme),s.appendChild(d("p",{className:"fillo-closed",text:"This form is no longer accepting responses."})),this.element.appendChild(s);return}if(this.notOpenVariant&&this.schema){this.element.appendChild(this.renderNotOpen(this.notOpenVariant)),this.brandingVisible()&&this.element.appendChild(Or(this.fetchedBrandLabel,this.fetchedBrandHref));return}if(this.schema){if(this.engine?.getState().status==="submitted"){let s=this.api(),a=this.engine.getState(),l=this.options.renderSuccess?.(s)??fc(this.schema);if(l.setAttribute("data-fillo",l.getAttribute("data-fillo")??"root"),this.formId&&!l.hasAttribute("data-fillo-form-id")&&l.setAttribute("data-fillo-form-id",this.formId),l.setAttribute("data-state",l.getAttribute("data-state")??"submitted"),l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1"),bt(l,this.theme),this.element.appendChild(l),this.brandingVisible()&&this.element.appendChild(Or(this.fetchedBrandLabel,this.fetchedBrandHref)),!a.restoredSubmission&&!this.liveSubmissionHandled){this.liveSubmissionHandled=!0;let c=at(this.schema.settings.redirectUrl);c&&typeof window<"u"?window.location.assign(c):(l.focus(),this.announce(l.textContent??""))}return}this.devChrome()&&L(this.element,wc({preview:this.options.preview===!0,devNotices:this.options.devNotices,syncError:this.syncErrorNotice,staged:this.stagedNotice,draft:this.draftNotice,warningUrl:this.syncWarningUrl,formUrl:this.syncFormUrl,noClient:!this.options.client&&!this.options.renderOnly})),this.element.appendChild(this.renderForm()),this.brandingVisible()&&this.element.appendChild(Or(this.fetchedBrandLabel,this.fetchedBrandHref)),this.applyFocus(n,r)}}brandingVisible(){return this.fetchedPoweredBy??!0}renderNotOpen(t){let n=d("div",{className:`fillo-form fillo-form--not-open ${this.options.className??""}`,attrs:{"data-fillo":"root","data-state":"closed"}});bt(n,this.theme);let r=d("div",{className:"fillo-not-open-preview",attrs:{"aria-hidden":"true",inert:""}});r.appendChild(this.renderForm());let i=d("div",{className:"fillo-not-open-card",attrs:{role:"status","data-fillo":"not-open-card"}});return i.appendChild(d("h2",{className:"fillo-not-open-title",text:t==="closed"?P.closedTitle:P.notOpenTitle})),i.appendChild(d("p",{className:"fillo-not-open-body",text:t==="closed"?P.closed:P.notOpenBody})),L(n,[r,i]),n}renderForm(){let t=this.api(),n=this.notOpenVariant!==null,r=!!this.challenge,i=!n&&r&&t.isLastPage,o=d(n?"div":"form",{className:`fillo-form ${this.options.className??""}`,attrs:{"data-fillo":n?"preview-form":"root","data-state":n?"preview":t.status,"data-page":String(t.pageIndex+1)}});!n&&this.formId&&o.setAttribute("data-fillo-form-id",this.formId),o.toggleAttribute("data-last-page",t.isLastPage),bt(o,this.theme);let s=()=>{t.isLastPage?this.submit():this.next()};if(!n){let p=o;p.noValidate=!0,p.addEventListener("submit",b=>{b.preventDefault(),s()})}let a=n?o.appendChild(d("fieldset",{className:"fillo-not-open-fields",attrs:{disabled:""}})):o,l=this.engine?.getState();if(l?.resumedDraft||l?.editingPrevious){let p=d("div",{className:"fillo-resume",attrs:{"data-fillo":"resume"}});p.appendChild(d("span",{className:"fillo-resume-text",text:l.editingPrevious?P.editNotice:P.resumeNotice}));let b=d("button",{className:"fillo-resume-clear",text:P.resumeStartOver,attrs:{type:"button"}});b.addEventListener("click",()=>this.resetDraft()),p.appendChild(b),a.appendChild(p)}else l?.resumeLinkFailed&&a.appendChild(d("div",{className:"fillo-resume fillo-resume--expired",attrs:{"data-fillo":"resume"},text:R.resumeLinkExpired}));if(t.pageCount>1&&this.schema?.settings.showProgress!==!1){let p=ht(t.form,t.data),b=Math.max(p.length,1),v=p.indexOf(t.page.id),y=v>=0?v+1:Math.min(t.pageIndex+1,b),F=d("div",{className:"fillo-progress-track",attrs:{role:"progressbar","data-fillo":"progress","aria-label":t.form.title||"Form progress","aria-valuemin":"1","aria-valuemax":String(b),"aria-valuenow":String(y)}});F.appendChild(d("div",{className:"fillo-progress-fill",attrs:{"data-fillo":"progressFill"}})),F.firstElementChild?.style.setProperty("--fillo-progress-value",`${y/b*100}%`),a.appendChild(F)}if(t.pageIndex===0){let p=d("header",{className:"fillo-header",attrs:{"data-fillo":"header"}});t.form.title&&p.appendChild(d("h1",{className:"fillo-title",text:t.form.title,attrs:{"data-fillo":"title"}})),t.form.description&&p.appendChild(d("p",{className:"fillo-form-description",text:t.form.description,attrs:{"data-fillo":"description"}})),a.appendChild(p)}else t.page.title&&a.appendChild(d("h2",{className:"fillo-page-title",text:t.page.title,attrs:{"data-fillo":"pageTitle"}}));let c=d("div",{className:"fillo-blocks",attrs:{"data-fillo":"blocks"}});for(let p of t.blocks){let b=this.renderBlock(es(p,this.mutableData,t.form),t);b&&c.appendChild(b)}if(a.appendChild(c),!n){let p=d("input",{className:"fillo-hp",attrs:{type:"text",name:"fillo_hp_field",tabindex:"-1",autocomplete:"off","aria-hidden":"true"}});p.style.position="absolute",p.style.left="-9999px",p.style.top="auto",p.style.width="1px",p.style.height="1px",p.style.opacity="0",p.style.overflow="hidden",p.style.pointerEvents="none",p.addEventListener("input",()=>{this.hpValue=p.value}),a.appendChild(p)}if(i){let p=d("div",{className:"fillo-turnstile-slot",attrs:{"data-fillo":"turnstile-slot"}});p.appendChild(this.turnstileContainer),this.challengeError&&p.appendChild(d("p",{className:"fillo-turnstile-error",attrs:{role:"alert"},text:P.challengeUnavailable})),a.appendChild(p),this.ensureChallengeWidget(this.challenge)}else(this.turnstileWidgetId!==null||this.turnstileLoadInFlight||this.challengeFrame!==null)&&this.teardownTurnstileWidget();let u=t.status==="error"?"This form can't submit right now. Please try again in a moment.":this.engine?.getState().submitError;if(u){let p=d("p",{className:"fillo-submit-error",attrs:{role:"alert"},text:u}),b=this.devChrome()&&this.resolutionFailureCode==="form_not_published"&&this.syncWarningCode==="storage_required"?at(this.syncWarningUrl):null;b&&(p.append(" Connect storage: "),p.appendChild(d("a",{text:b,attrs:{href:b,target:"_blank",rel:"noopener noreferrer"}}))),a.appendChild(p)}let f=!(t.form.settings.submitMode==="auto")||!t.isLastPage||Vo(wo(t.form,t.data))||i;if(f||t.pageCount>1&&!t.isFirstPage){let p=d("footer",{className:"fillo-footer",attrs:{"data-fillo":"footer"}});if(t.pageCount>1&&!t.isFirstPage){let b=d("button",{className:"fillo-button fillo-button--ghost",text:"Back",attrs:{type:"button","data-fillo":"button"}});b.addEventListener("click",()=>this.back()),p.appendChild(b)}if(f){let b=d("button",{className:"fillo-button fillo-button--primary",text:t.status==="submitting"?"Submitting...":t.isLastPage?t.form.settings.submitLabel??"Submit":"Next",attrs:{type:"submit","data-fillo":"button"}});b.toggleAttribute("disabled",t.status==="submitting"||this.engine?.getState().uploading===!0||i&&!this.challengeToken),b.addEventListener("click",v=>{v.preventDefault(),s()}),p.appendChild(b)}a.appendChild(p)}return o}fieldRenderer(t){return t.kind==="custom"?this.options.customComponents?.[t.component]??this.options.components?.custom:this.options.components?.[t.kind]??gs}renderChildField=t=>this.fieldRenderer(t.field)?.(t)??null;setGroupFocus=t=>{this.focusIntent=t};renderBlock(t,n){if(!ce(t))return dc(t);let r=(o,s)=>{if(this.setValueInternal(t.id,o,s),s?.render===!1)return;let a={form:n.form,data:n.data,status:n.status,isLastPage:n.isLastPage,uploading:this.engine?.getState().uploading===!0};Ho(t,o,a)&&this.submit()},i={field:t,value:n.data[t.id],error:n.errors[t.id]===Nt?Fo(t,R):n.errors[t.id],ids:fs(this.instanceId,t.id),api:n,setValue:r,uploadFiles:(o,s)=>this.uploadFiles(o,s),uploadRows:this.uploadRowsFor(t.id),uploadAction:this.uploadAction,activeOtherFields:this.activeOtherFields,getValue:()=>this.engine?.getState().data[t.id],registerOverlay:this.registerOverlay,uploadNotice:this.uploadNotices.get(t.id),uploadDisabledReason:this.options.renderOnly?"render_only":this.storageBlocked()?"storage_unavailable":void 0,storageFixUrl:this.storageBlocked()&&this.devChrome()?at(this.syncWarningUrl):null,announce:this.announce,announceAlert:this.announceAlert,instanceId:this.instanceId,renderChildField:this.renderChildField,setGroupFocus:this.setGroupFocus};return this.fieldRenderer(t)?.(i)??null}};function dc(e){switch(e.kind){case"heading":return d("h3",{className:"fillo-heading",text:e.text});case"paragraph":return d("p",{className:"fillo-paragraph",text:e.text});case"divider":return d("hr",{className:"fillo-divider"})}return d("div")}function fc(e){let t=d("div",{className:"fillo-form fillo-form--success"}),n=d("div",{className:"fillo-success"});return L(n,[d("div",{className:"fillo-success-mark",attrs:{"aria-hidden":"true"}}),d("h2",{className:"fillo-success-title",text:e.settings.successTitle??"Thanks!"}),d("p",{className:"fillo-success-message",text:e.settings.successMessage??"Your response has been recorded."})]),t.appendChild(n),t}function Or(e,t){return d("a",{className:"fillo-powered",text:e??"Powered by Fillo",attrs:{href:Ol(t),target:"_blank",rel:"nofollow noopener noreferrer"}})}function ls(e){return e==="expired"||e==="capped"||e==="storage_full"?"closed":"notOpen"}function pc(){return Qo()}function hc(){return d("div",{className:"fillo-devwarning",text:"No Fillo client connected \u2014 this form is render-only and won't save responses. Pass a client to collect them in Fillo, or forward with webhooks. (Shown only in development and preview.)",attrs:{role:"alert"}})}function mc(e){return d("div",{className:"fillo-devwarning",text:`Form sync needs attention${e.code?` (${e.code})`:""}: ${e.message} The safe form remains available for development.`,attrs:{role:"alert"}})}function gc(e){let t=d("div",{className:"fillo-devwarning",attrs:{role:"alert"}});t.append("Code changes are staged, not live. This page shows your draft, while respondents still get the live version. ");let n=at(e);return n?(t.appendChild(d("a",{text:"Review and publish in Fillo",attrs:{href:n,target:"_blank",rel:"noopener noreferrer"}})),t.append(".")):t.append("Review and publish the changes in Fillo."),t}function bc(e,t){let n=d("div",{className:"fillo-devwarning",attrs:{role:"alert"}});n.append("Draft form preview \u2014 the form renders for local testing, but Fillo will reject the submission and save no response until you publish it. ");let r=at(e),i=at(t);return r?(n.appendChild(d("a",{text:"Connect storage to publish",attrs:{href:r,target:"_blank",rel:"noopener noreferrer"}})),n.append(". ")):i&&(n.appendChild(d("a",{text:"Open in Fillo to publish",attrs:{href:i,target:"_blank",rel:"noopener noreferrer"}})),n.append(". ")),n.append("(Shown only in development and preview.)"),n}function vc(){return d("span",{className:"fillo-preview-badge",text:"Preview",attrs:{"data-fillo":"preview-badge"}})}var cs=!1;function yc(){cs||Tr()||(cs=!0,console.warn("[fillo] `preview` is enabled in a production build. Preview is cosmetic only \u2014 it shows developer chrome and never changes where submissions go or whether they are accepted \u2014 but remove it before respondents see this page."))}function wc(e){let t=[];return e.preview&&t.push(vc()),e.devNotices===!1||(e.syncError?t.push(mc(e.syncError)):e.staged?t.push(gc(e.formUrl)):e.draft?t.push(bc(e.warningUrl,e.formUrl)):e.noClient&&t.push(hc())),t}var Ot="invalid_form_definition";function us(e){let t=Ye(e);return t.ok?null:t.error??"invalid form definition"}function _c(e){return e.status===404?P.loadFailedNotFound:e.status===0?P.loadFailedNetwork:e.status===422?P.renderFailed:P.loadFailed}function ds(){return new C("This form has no Fillo target. Pass formId with the schema, use a defineForm() value with client, or set renderOnly for a non-submitting preview.",422,void 0,"form_target_required")}function Zt(e){return be(e)?e:new C(e instanceof Error?e.message:String(e),0)}function xn(e,t){let n=typeof e=="string"?document.querySelector(e):e;if(!n)throw new C(`Fillo mount target not found: ${String(e)}`,0);let r={...t,initialData:t.initialData??{}};return new Bt(n,r)}function bs(e){let t=d("div");return xn(t,e),t}var xc=typeof HTMLElement<"u"?HTMLElement:class{},Zr=class extends xc{instance=null;assignedForm;assignedClient;assignedTheme;assignedInitialData;mounted=!1;mountScheduled=!1;static get observedAttributes(){return["publishable-key","form-id","data-preview","data-render-only"]}connectedCallback(){this.scheduleMount()}disconnectedCallback(){this.instance?.destroy(),this.instance=null,this.mounted=!1}attributeChangedCallback(){this.mounted&&this.isConnected&&this.scheduleMount()}set form(t){this.assignedForm=t,this.mounted&&this.scheduleMount()}get form(){return this.assignedForm}set client(t){this.assignedClient=t,this.mounted&&this.instance instanceof Bt&&this.instance.setClient(t)}set theme(t){this.assignedTheme=t,this.mounted&&this.instance instanceof Bt&&this.instance.setTheme(t)}set initialData(t){this.assignedInitialData=t,this.mounted&&this.scheduleMount()}scheduleMount(){this.mountScheduled||(this.mountScheduled=!0,queueMicrotask(()=>{this.mountScheduled=!1,this.isConnected&&this.mount()}))}previewAttrEnabled(){let t=this.getAttribute("data-preview");return t!==null&&t!=="false"&&t!=="0"}renderOnlyAttrEnabled(){let t=this.getAttribute("data-render-only");return t!==null&&t!=="false"&&t!=="0"}mount(){this.instance?.destroy();let t=this.getAttribute("publishable-key")??void 0,n=this.getAttribute("form-id")??void 0,r=this.assignedClient??(n||t?Te({key:t}):void 0);this.instance=xn(this,{form:this.assignedForm,client:r,formId:n,theme:this.assignedTheme,initialData:this.assignedInitialData,preview:this.previewAttrEnabled()?!0:void 0,renderOnly:this.renderOnlyAttrEnabled()?!0:void 0,onChange:i=>this.dispatchEvent(new CustomEvent("fillo-change",{detail:{data:i}})),onSubmitted:(i,o)=>this.dispatchEvent(new CustomEvent("fillo-submit",{detail:{responseId:i,data:o}})),onError:i=>this.dispatchEvent(new CustomEvent("fillo-error",{detail:{error:i}}))}),this.mounted=!0}};function Ur(e="fillo-form"){typeof customElements>"u"||customElements.get(e)||customElements.define(e,Zr)}typeof customElements<"u"&&Ur();return Is(kc);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usefillo/dom",
3
- "version": "0.30.0",
3
+ "version": "0.30.1",
4
4
  "description": "Framework-agnostic DOM renderer and web component for embedding Fillo forms.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -45,7 +45,7 @@
45
45
  "access": "public"
46
46
  },
47
47
  "dependencies": {
48
- "@usefillo/core": "^0.30.0"
48
+ "@usefillo/core": "^0.30.1"
49
49
  },
50
50
  "devDependencies": {
51
51
  "axe-core": "^4.10.0",