@spiffcommerce/core 44.5.5-alpha.3 → 44.5.5

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.
@@ -52,7 +52,7 @@ spurious results.`)}}return!1};class _2{constructor(e,t="GraphQL request",n={lin
52
52
  `)),`
53
53
  }`)}function Zt(r,e,t=""){return e!=null&&e!==""?r+e+t:""}function Op(r){return Zt(" ",r.replace(/\n/g,`
54
54
  `))}function Jm(r){var e;return(e=r?.some(t=>t.includes(`
55
- `)))!==null&&e!==void 0?e:!1}function dw(r){return r.kind===et.FIELD||r.kind===et.FRAGMENT_SPREAD||r.kind===et.INLINE_FRAGMENT}function Pf(r,e){var t=r.directives;return!t||!t.length?!0:JD(t).every(function(n){var i=n.directive,a=n.ifArgument,s=!1;return a.value.kind==="Variable"?(s=e&&e[a.value.name.value],Mr(s!==void 0,105,i.name.value)):s=a.value.value,i.name.value==="skip"?!s:s})}function lf(r,e,t){var n=new Set(r),i=n.size;return Ia(e,{Directive:function(a){if(n.delete(a.name.value)&&(!t||!n.size))return IA}}),t?!n.size:n.size<i}function YD(r){return r&&lf(["client","export"],r,!0)}function XD(r){var e=r.name.value;return e==="skip"||e==="include"}function JD(r){var e=[];return r&&r.length&&r.forEach(function(t){if(XD(t)){var n=t.arguments,i=t.name.value;Mr(n&&n.length===1,106,i);var a=n[0];Mr(a.name&&a.name.value==="if",107,i);var s=a.value;Mr(s&&(s.kind==="Variable"||s.kind==="BooleanValue"),108,i),e.push({directive:t,ifArgument:a})}}),e}function KD(r){var e,t,n=(e=r.directives)===null||e===void 0?void 0:e.find(function(a){var s=a.name;return s.value==="unmask"});if(!n)return"mask";var i=(t=n.arguments)===null||t===void 0?void 0:t.find(function(a){var s=a.name;return s.value==="mode"});return i&&"value"in i.value&&i.value.value==="migrate"?"migrate":"unmask"}const ZD=()=>Object.create(null),{forEach:eR,slice:fw}=Array.prototype,{hasOwnProperty:tR}=Object.prototype;class _s{constructor(e=!0,t=ZD){this.weakness=e,this.makeData=t}lookup(){return this.lookupArray(arguments)}lookupArray(e){let t=this;return eR.call(e,n=>t=t.getChildTrie(n)),tR.call(t,"data")?t.data:t.data=this.makeData(fw.call(e))}peek(){return this.peekArray(arguments)}peekArray(e){let t=this;for(let n=0,i=e.length;t&&n<i;++n){const a=t.mapFor(e[n],!1);t=a&&a.get(e[n])}return t&&t.data}remove(){return this.removeArray(arguments)}removeArray(e){let t;if(e.length){const n=e[0],i=this.mapFor(n,!1),a=i&&i.get(n);a&&(t=a.removeArray(fw.call(e,1)),!a.data&&!a.weak&&!(a.strong&&a.strong.size)&&i.delete(n))}else t=this.data,delete this.data;return t}getChildTrie(e){const t=this.mapFor(e,!0);let n=t.get(e);return n||t.set(e,n=new _s(this.weakness,this.makeData)),n}mapFor(e,t){return this.weakness&&rR(e)?this.weak||(t?this.weak=new WeakMap:void 0):this.strong||(t?this.strong=new Map:void 0)}}function rR(r){switch(typeof r){case"object":if(r===null)break;case"function":return!0}return!1}var nR=Ta(function(){return navigator.product})=="ReactNative",Tl=typeof WeakMap=="function"&&!(nR&&!global.HermesInternal),PA=typeof WeakSet=="function",U2=typeof Symbol=="function"&&typeof Symbol.for=="function",Tg=U2&&Symbol.asyncIterator;Ta(function(){return window.document.createElement});Ta(function(){return navigator.userAgent.indexOf("jsdom")>=0});function ci(r){return r!==null&&typeof r=="object"}function V2(r){return r!==null&&typeof r=="object"&&(Object.getPrototypeOf(r)===Object.prototype||Object.getPrototypeOf(r)===null)}function iR(r,e){var t=e,n=[];r.definitions.forEach(function(a){if(a.kind==="OperationDefinition")throw ji(112,a.operation,a.name?" named '".concat(a.name.value,"'"):"");a.kind==="FragmentDefinition"&&n.push(a)}),typeof t>"u"&&(Mr(n.length===1,113,n.length),t=n[0].name.value);var i=me(me({},r),{definitions:ta([{kind:"OperationDefinition",operation:"query",selectionSet:{kind:"SelectionSet",selections:[{kind:"FragmentSpread",name:{kind:"Name",value:t}}]}}],r.definitions,!0)});return i}function lc(r){r===void 0&&(r=[]);var e={};return r.forEach(function(t){e[t.name.value]=t}),e}function Fg(r,e){switch(r.kind){case"InlineFragment":return r;case"FragmentSpread":{var t=r.name.value;if(typeof e=="function")return e(t);var n=e&&e[t];return Mr(n,114,t),n||null}default:return null}}function aR(){}class dy{constructor(e=1/0,t=aR){this.max=e,this.dispose=t,this.map=new Map,this.newest=null,this.oldest=null}has(e){return this.map.has(e)}get(e){const t=this.getNode(e);return t&&t.value}get size(){return this.map.size}getNode(e){const t=this.map.get(e);if(t&&t!==this.newest){const{older:n,newer:i}=t;i&&(i.older=n),n&&(n.newer=i),t.older=this.newest,t.older.newer=t,t.newer=null,this.newest=t,t===this.oldest&&(this.oldest=i)}return t}set(e,t){let n=this.getNode(e);return n?n.value=t:(n={key:e,value:t,newer:null,older:this.newest},this.newest&&(this.newest.newer=n),this.newest=n,this.oldest=this.oldest||n,this.map.set(e,n),n.value)}clean(){for(;this.oldest&&this.map.size>this.max;)this.delete(this.oldest.key)}delete(e){const t=this.map.get(e);return t?(t===this.newest&&(this.newest=t.older),t===this.oldest&&(this.oldest=t.newer),t.newer&&(t.newer.older=t.older),t.older&&(t.older.newer=t.newer),this.map.delete(e),this.dispose(t.value,e),!0):!1}}function fy(){}const sR=fy,oR=typeof WeakRef<"u"?WeakRef:function(r){return{deref:()=>r}},lR=typeof WeakMap<"u"?WeakMap:Map,uR=typeof FinalizationRegistry<"u"?FinalizationRegistry:function(){return{register:fy,unregister:fy}},cR=10024;class uf{constructor(e=1/0,t=sR){this.max=e,this.dispose=t,this.map=new lR,this.newest=null,this.oldest=null,this.unfinalizedNodes=new Set,this.finalizationScheduled=!1,this.size=0,this.finalize=()=>{const n=this.unfinalizedNodes.values();for(let i=0;i<cR;i++){const a=n.next().value;if(!a)break;this.unfinalizedNodes.delete(a);const s=a.key;delete a.key,a.keyRef=new oR(s),this.registry.register(s,a,a)}this.unfinalizedNodes.size>0?queueMicrotask(this.finalize):this.finalizationScheduled=!1},this.registry=new uR(this.deleteNode.bind(this))}has(e){return this.map.has(e)}get(e){const t=this.getNode(e);return t&&t.value}getNode(e){const t=this.map.get(e);if(t&&t!==this.newest){const{older:n,newer:i}=t;i&&(i.older=n),n&&(n.newer=i),t.older=this.newest,t.older.newer=t,t.newer=null,this.newest=t,t===this.oldest&&(this.oldest=i)}return t}set(e,t){let n=this.getNode(e);return n?n.value=t:(n={key:e,value:t,newer:null,older:this.newest},this.newest&&(this.newest.newer=n),this.newest=n,this.oldest=this.oldest||n,this.scheduleFinalization(n),this.map.set(e,n),this.size++,n.value)}clean(){for(;this.oldest&&this.size>this.max;)this.deleteNode(this.oldest)}deleteNode(e){e===this.newest&&(this.newest=e.older),e===this.oldest&&(this.oldest=e.newer),e.newer&&(e.newer.older=e.older),e.older&&(e.older.newer=e.newer),this.size--;const t=e.key||e.keyRef&&e.keyRef.deref();this.dispose(e.value,t),e.keyRef?this.registry.unregister(e):this.unfinalizedNodes.delete(e),t&&this.map.delete(t)}delete(e){const t=this.map.get(e);return t?(this.deleteNode(t),!0):!1}scheduleFinalization(e){this.unfinalizedNodes.add(e),this.finalizationScheduled||(this.finalizationScheduled=!0,queueMicrotask(this.finalize))}}var Km=new WeakSet;function z2(r){r.size<=(r.max||-1)||Km.has(r)||(Km.add(r),setTimeout(function(){r.clean(),Km.delete(r)},100))}var $2=function(r,e){var t=new uf(r,e);return t.set=function(n,i){var a=uf.prototype.set.call(this,n,i);return z2(this),a},t},dR=function(r,e){var t=new dy(r,e);return t.set=function(n,i){var a=dy.prototype.set.call(this,n,i);return z2(this),a},t},fR=Symbol.for("apollo.cacheSize"),Ms=me({},eg[fR]),go=Object.assign(function(e){return JSON.stringify(e,hR)},{reset:function(){Rd=new dR(Ms.canonicalStringify||1e3)}}),Rd;go.reset();function hR(r,e){if(e&&typeof e=="object"){var t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){var n=Object.keys(e);if(n.every(pR))return e;var i=JSON.stringify(n),a=Rd.get(i);if(!a){n.sort();var s=JSON.stringify(n);a=Rd.get(s)||n,Rd.set(i,a),Rd.set(s,a)}var o=Object.create(t);return a.forEach(function(l){o[l]=e[l]}),o}}return e}function pR(r,e,t){return e===0||t[e-1]<=r}function Uu(r){return{__ref:String(r)}}function Tn(r){return!!(r&&typeof r=="object"&&typeof r.__ref=="string")}function gR(r){return ci(r)&&r.kind==="Document"&&Array.isArray(r.definitions)}function mR(r){return r.kind==="StringValue"}function vR(r){return r.kind==="BooleanValue"}function yR(r){return r.kind==="IntValue"}function AR(r){return r.kind==="FloatValue"}function bR(r){return r.kind==="Variable"}function wR(r){return r.kind==="ObjectValue"}function CR(r){return r.kind==="ListValue"}function xR(r){return r.kind==="EnumValue"}function SR(r){return r.kind==="NullValue"}function qu(r,e,t,n){if(yR(t)||AR(t))r[e.value]=Number(t.value);else if(vR(t)||mR(t))r[e.value]=t.value;else if(wR(t)){var i={};t.fields.map(function(s){return qu(i,s.name,s.value,n)}),r[e.value]=i}else if(bR(t)){var a=(n||{})[t.name.value];r[e.value]=a}else if(CR(t))r[e.value]=t.values.map(function(s){var o={};return qu(o,e,s,n),o[e.value]});else if(xR(t))r[e.value]=t.value;else if(SR(t))r[e.value]=null;else throw ji(123,e.value,t.kind)}function ER(r,e){var t=null;r.directives&&(t={},r.directives.forEach(function(i){t[i.name.value]={},i.arguments&&i.arguments.forEach(function(a){var s=a.name,o=a.value;return qu(t[i.name.value],s,o,e)})}));var n=null;return r.arguments&&r.arguments.length&&(n={},r.arguments.forEach(function(i){var a=i.name,s=i.value;return qu(n,a,s,e)})),H2(r.name.value,n,t)}var kR=["connection","include","skip","client","rest","export","nonreactive"],td=go,H2=Object.assign(function(r,e,t){if(e&&t&&t.connection&&t.connection.key)if(t.connection.filter&&t.connection.filter.length>0){var n=t.connection.filter?t.connection.filter:[];n.sort();var i={};return n.forEach(function(o){i[o]=e[o]}),"".concat(t.connection.key,"(").concat(td(i),")")}else return t.connection.key;var a=r;if(e){var s=td(e);a+="(".concat(s,")")}return t&&Object.keys(t).forEach(function(o){kR.indexOf(o)===-1&&(t[o]&&Object.keys(t[o]).length?a+="@".concat(o,"(").concat(td(t[o]),")"):a+="@".concat(o))}),a},{setStringify:function(r){var e=td;return td=r,e}});function Ig(r,e){if(r.arguments&&r.arguments.length){var t={};return r.arguments.forEach(function(n){var i=n.name,a=n.value;return qu(t,i,a,e)}),t}return null}function bo(r){return r.alias?r.alias.value:r.name.value}function hy(r,e,t){for(var n,i=0,a=e.selections;i<a.length;i++){var s=a[i];if(wo(s)){if(s.name.value==="__typename")return r[bo(s)]}else n?n.push(s):n=[s]}if(typeof r.__typename=="string")return r.__typename;if(n)for(var o=0,l=n;o<l.length;o++){var s=l[o],u=hy(r,Fg(s,t).selectionSet,t);if(typeof u=="string")return u}}function wo(r){return r.kind==="Field"}function TR(r){return r.kind==="InlineFragment"}function uc(r){Mr(r&&r.kind==="Document",115);var e=r.definitions.filter(function(t){return t.kind!=="FragmentDefinition"}).map(function(t){if(t.kind!=="OperationDefinition")throw ji(116,t.kind);return t});return Mr(e.length<=1,117,e.length),r}function cc(r){return uc(r),r.definitions.filter(function(e){return e.kind==="OperationDefinition"})[0]}function Bp(r){return r.definitions.filter(function(e){return e.kind==="OperationDefinition"&&!!e.name}).map(function(e){return e.name.value})[0]||null}function dc(r){return r.definitions.filter(function(e){return e.kind==="FragmentDefinition"})}function FR(r){var e=cc(r);return Mr(e&&e.operation==="query",118),e}function IR(r){Mr(r.kind==="Document",119),Mr(r.definitions.length<=1,120);var e=r.definitions[0];return Mr(e.kind==="FragmentDefinition",121),e}function Df(r){uc(r);for(var e,t=0,n=r.definitions;t<n.length;t++){var i=n[t];if(i.kind==="OperationDefinition"){var a=i.operation;if(a==="query"||a==="mutation"||a==="subscription")return i}i.kind==="FragmentDefinition"&&!e&&(e=i)}if(e)return e;throw ji(122)}function DA(r){var e=Object.create(null),t=r&&r.variableDefinitions;return t&&t.length&&t.forEach(function(n){n.defaultValue&&qu(e,n.variable.name,n.defaultValue)}),e}let Si=null;const hw={};let PR=1;const DR=()=>class{constructor(){this.id=["slot",PR++,Date.now(),Math.random().toString(36).slice(2)].join(":")}hasValue(){for(let e=Si;e;e=e.parent)if(this.id in e.slots){const t=e.slots[this.id];if(t===hw)break;return e!==Si&&(Si.slots[this.id]=t),!0}return Si&&(Si.slots[this.id]=hw),!1}getValue(){if(this.hasValue())return Si.slots[this.id]}withValue(e,t,n,i){const a={__proto__:null,[this.id]:e},s=Si;Si={parent:s,slots:a};try{return t.apply(i,n)}finally{Si=s}}static bind(e){const t=Si;return function(){const n=Si;try{return Si=t,e.apply(this,arguments)}finally{Si=n}}}static noContext(e,t,n){if(Si){const i=Si;try{return Si=null,e.apply(n,t)}finally{Si=i}}else return e.apply(n,t)}};function pw(r){try{return r()}catch{}}const Zm="@wry/context:Slot",RR=pw(()=>globalThis)||pw(()=>global)||Object.create(null),gw=RR,fc=gw[Zm]||Array[Zm]||(function(r){try{Object.defineProperty(gw,Zm,{value:r,enumerable:!1,writable:!1,configurable:!0})}finally{return r}})(DR()),{bind:OY,noContext:BY}=fc,Pg=new fc,{hasOwnProperty:OR}=Object.prototype,RA=Array.from||function(r){const e=[];return r.forEach(t=>e.push(t)),e};function OA(r){const{unsubscribe:e}=r;typeof e=="function"&&(r.unsubscribe=void 0,e())}const cf=[],BR=100;function Wu(r,e){if(!r)throw new Error(e||"assertion failure")}function j2(r,e){const t=r.length;return t>0&&t===e.length&&r[t-1]===e[t-1]}function G2(r){switch(r.length){case 0:throw new Error("unknown value");case 1:return r[0];case 2:throw r[1]}}function q2(r){return r.slice(0)}class Dg{constructor(e){this.fn=e,this.parents=new Set,this.childValues=new Map,this.dirtyChildren=null,this.dirty=!0,this.recomputing=!1,this.value=[],this.deps=null,++Dg.count}peek(){if(this.value.length===1&&!Co(this))return mw(this),this.value[0]}recompute(e){return Wu(!this.recomputing,"already recomputing"),mw(this),Co(this)?MR(this,e):G2(this.value)}setDirty(){this.dirty||(this.dirty=!0,W2(this),OA(this))}dispose(){this.setDirty(),K2(this),BA(this,(e,t)=>{e.setDirty(),Z2(e,this)})}forget(){this.dispose()}dependOn(e){e.add(this),this.deps||(this.deps=cf.pop()||new Set),this.deps.add(e)}forgetDeps(){this.deps&&(RA(this.deps).forEach(e=>e.delete(this)),this.deps.clear(),cf.push(this.deps),this.deps=null)}}Dg.count=0;function mw(r){const e=Pg.getValue();if(e)return r.parents.add(e),e.childValues.has(r)||e.childValues.set(r,[]),Co(r)?Y2(e,r):X2(e,r),e}function MR(r,e){return K2(r),Pg.withValue(r,_R,[r,e]),LR(r,e)&&NR(r),G2(r.value)}function _R(r,e){r.recomputing=!0;const{normalizeResult:t}=r;let n;t&&r.value.length===1&&(n=q2(r.value)),r.value.length=0;try{if(r.value[0]=r.fn.apply(null,e),t&&n&&!j2(n,r.value))try{r.value[0]=t(r.value[0],n[0])}catch{}}catch(i){r.value[1]=i}r.recomputing=!1}function Co(r){return r.dirty||!!(r.dirtyChildren&&r.dirtyChildren.size)}function NR(r){r.dirty=!1,!Co(r)&&Q2(r)}function W2(r){BA(r,Y2)}function Q2(r){BA(r,X2)}function BA(r,e){const t=r.parents.size;if(t){const n=RA(r.parents);for(let i=0;i<t;++i)e(n[i],r)}}function Y2(r,e){Wu(r.childValues.has(e)),Wu(Co(e));const t=!Co(r);if(!r.dirtyChildren)r.dirtyChildren=cf.pop()||new Set;else if(r.dirtyChildren.has(e))return;r.dirtyChildren.add(e),t&&W2(r)}function X2(r,e){Wu(r.childValues.has(e)),Wu(!Co(e));const t=r.childValues.get(e);t.length===0?r.childValues.set(e,q2(e.value)):j2(t,e.value)||r.setDirty(),J2(r,e),!Co(r)&&Q2(r)}function J2(r,e){const t=r.dirtyChildren;t&&(t.delete(e),t.size===0&&(cf.length<BR&&cf.push(t),r.dirtyChildren=null))}function K2(r){r.childValues.size>0&&r.childValues.forEach((e,t)=>{Z2(r,t)}),r.forgetDeps(),Wu(r.dirtyChildren===null)}function Z2(r,e){e.parents.delete(r),r.childValues.delete(e),J2(r,e)}function LR(r,e){if(typeof r.subscribe=="function")try{OA(r),r.unsubscribe=r.subscribe.apply(null,e)}catch{return r.setDirty(),!1}return!0}const UR={setDirty:!0,dispose:!0,forget:!0};function ek(r){const e=new Map;function t(n){const i=Pg.getValue();if(i){let a=e.get(n);a||e.set(n,a=new Set),i.dependOn(a)}}return t.dirty=function(i,a){const s=e.get(i);if(s){const o=a&&OR.call(UR,a)?a:"setDirty";RA(s).forEach(l=>l[o]()),e.delete(i),OA(s)}},t}let vw;function VR(...r){return(vw||(vw=new _s(typeof WeakMap=="function"))).lookupArray(r)}const e0=new Set;function Qu(r,{max:e=Math.pow(2,16),keyArgs:t,makeCacheKey:n=VR,normalizeResult:i,subscribe:a,cache:s=dy}=Object.create(null)){const o=typeof s=="function"?new s(e,d=>d.dispose()):s,l=function(){const d=n.apply(null,t?t.apply(null,arguments):arguments);if(d===void 0)return r.apply(null,arguments);let h=o.get(d);h||(o.set(d,h=new Dg(r)),h.normalizeResult=i,h.subscribe=a,h.forget=()=>o.delete(d));const g=h.recompute(Array.prototype.slice.call(arguments));return o.set(d,h),e0.add(o),Pg.hasValue()||(e0.forEach(v=>v.clean()),e0.clear()),g};Object.defineProperty(l,"size",{get:()=>o.size,configurable:!1,enumerable:!1}),Object.freeze(l.options={max:e,keyArgs:t,makeCacheKey:n,normalizeResult:i,subscribe:a,cache:o});function u(d){const h=d&&o.get(d);h&&h.setDirty()}l.dirtyKey=u,l.dirty=function(){u(n.apply(null,arguments))};function c(d){const h=d&&o.get(d);if(h)return h.peek()}l.peekKey=c,l.peek=function(){return c(n.apply(null,arguments))};function f(d){return d?o.delete(d):!1}return l.forgetKey=f,l.forget=function(){return f(n.apply(null,arguments))},l.makeCacheKey=n,l.getKey=t?function(){return n.apply(null,t.apply(null,arguments))}:n,Object.freeze(l)}function zR(r){return r}var tk=(function(){function r(e,t){t===void 0&&(t=Object.create(null)),this.resultCache=PA?new WeakSet:new Set,this.transform=e,t.getCacheKey&&(this.getCacheKey=t.getCacheKey),this.cached=t.cache!==!1,this.resetCache()}return r.prototype.getCacheKey=function(e){return[e]},r.identity=function(){return new r(zR,{cache:!1})},r.split=function(e,t,n){return n===void 0&&(n=r.identity()),Object.assign(new r(function(i){var a=e(i)?t:n;return a.transformDocument(i)},{cache:!1}),{left:t,right:n})},r.prototype.resetCache=function(){var e=this;if(this.cached){var t=new _s(Tl);this.performWork=Qu(r.prototype.performWork.bind(this),{makeCacheKey:function(n){var i=e.getCacheKey(n);if(i)return Mr(Array.isArray(i),104),t.lookupArray(i)},max:Ms["documentTransform.cache"],cache:uf})}},r.prototype.performWork=function(e){return uc(e),this.transform(e)},r.prototype.transformDocument=function(e){if(this.resultCache.has(e))return e;var t=this.performWork(e);return this.resultCache.add(t),t},r.prototype.concat=function(e){var t=this;return Object.assign(new r(function(n){return e.transformDocument(t.transformDocument(n))},{cache:!1}),{left:this,right:e})},r})(),t0,yl=Object.assign(function(r){var e=t0.get(r);return e||(e=L2(r),t0.set(r,e)),e},{reset:function(){t0=new $2(Ms.print||2e3)}});yl.reset();var ii=Array.isArray;function ls(r){return Array.isArray(r)&&r.length>0}var yw={kind:et.FIELD,name:{kind:et.NAME,value:"__typename"}};function rk(r,e){return!r||r.selectionSet.selections.every(function(t){return t.kind===et.FRAGMENT_SPREAD&&rk(e[t.name.value],e)})}function $R(r){return rk(cc(r)||IR(r),lc(dc(r)))?null:r}function HR(r){var e=new Map,t=new Map;return r.forEach(function(n){n&&(n.name?e.set(n.name,n):n.test&&t.set(n.test,n))}),function(n){var i=e.get(n.name.value);return!i&&t.size&&t.forEach(function(a,s){s(n)&&(i=a)}),i}}function Aw(r){var e=new Map;return function(n){n===void 0&&(n=r);var i=e.get(n);return i||e.set(n,i={variables:new Set,fragmentSpreads:new Set}),i}}function nk(r,e){uc(e);for(var t=Aw(""),n=Aw(""),i=function(A){for(var C=0,S=void 0;C<A.length&&(S=A[C]);++C)if(!ii(S)){if(S.kind===et.OPERATION_DEFINITION)return t(S.name&&S.name.value);if(S.kind===et.FRAGMENT_DEFINITION)return n(S.name.value)}return null},a=0,s=e.definitions.length-1;s>=0;--s)e.definitions[s].kind===et.OPERATION_DEFINITION&&++a;var o=HR(r),l=function(A){return ls(A)&&A.map(o).some(function(C){return C&&C.remove})},u=new Map,c=!1,f={enter:function(A){if(l(A.directives))return c=!0,null}},d=Ia(e,{Field:f,InlineFragment:f,VariableDefinition:{enter:function(){return!1}},Variable:{enter:function(A,C,S,F,E){var R=i(E);R&&R.variables.add(A.name.value)}},FragmentSpread:{enter:function(A,C,S,F,E){if(l(A.directives))return c=!0,null;var R=i(E);R&&R.fragmentSpreads.add(A.name.value)}},FragmentDefinition:{enter:function(A,C,S,F){u.set(JSON.stringify(F),A)},leave:function(A,C,S,F){var E=u.get(JSON.stringify(F));if(A===E)return A;if(a>0&&A.selectionSet.selections.every(function(R){return R.kind===et.FIELD&&R.name.value==="__typename"}))return n(A.name.value).removed=!0,c=!0,null}},Directive:{leave:function(A){if(o(A))return c=!0,null}}});if(!c)return e;var h=function(A){return A.transitiveVars||(A.transitiveVars=new Set(A.variables),A.removed||A.fragmentSpreads.forEach(function(C){h(n(C)).transitiveVars.forEach(function(S){A.transitiveVars.add(S)})})),A},g=new Set;d.definitions.forEach(function(A){A.kind===et.OPERATION_DEFINITION?h(t(A.name&&A.name.value)).fragmentSpreads.forEach(function(C){g.add(C)}):A.kind===et.FRAGMENT_DEFINITION&&a===0&&!n(A.name.value).removed&&g.add(A.name.value)}),g.forEach(function(A){h(n(A)).fragmentSpreads.forEach(function(C){g.add(C)})});var v=function(A){return!!(!g.has(A)||n(A).removed)},y={enter:function(A){if(v(A.name.value))return null}};return $R(Ia(d,{FragmentSpread:y,FragmentDefinition:y,OperationDefinition:{leave:function(A){if(A.variableDefinitions){var C=h(t(A.name&&A.name.value)).transitiveVars;if(C.size<A.variableDefinitions.length)return me(me({},A),{variableDefinitions:A.variableDefinitions.filter(function(S){return C.has(S.variable.name.value)})})}}}}))}var ik=Object.assign(function(r){return Ia(r,{SelectionSet:{enter:function(e,t,n){if(!(n&&n.kind===et.OPERATION_DEFINITION)){var i=e.selections;if(i){var a=i.some(function(o){return wo(o)&&(o.name.value==="__typename"||o.name.value.lastIndexOf("__",0)===0)});if(!a){var s=n;if(!(wo(s)&&s.directives&&s.directives.some(function(o){return o.name.value==="export"})))return me(me({},e),{selections:ta(ta([],i,!0),[yw],!1)})}}}}}})},{added:function(r){return r===yw}});function jR(r){var e=Df(r),t=e.operation;if(t==="query")return r;var n=Ia(r,{OperationDefinition:{enter:function(i){return me(me({},i),{operation:"query"})}}});return n}function ak(r){uc(r);var e=nk([{test:function(t){return t.name.value==="client"},remove:!0}],r);return e}function GR(r){return uc(r),Ia(r,{FragmentSpread:function(e){var t;if(!(!((t=e.directives)===null||t===void 0)&&t.some(function(n){return n.name.value==="unmask"})))return me(me({},e),{directives:ta(ta([],e.directives||[],!0),[{kind:et.DIRECTIVE,name:{kind:et.NAME,value:"nonreactive"}}],!1)})}})}var qR=Object.prototype.hasOwnProperty;function bw(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return Rg(r)}function Rg(r){var e=r[0]||{},t=r.length;if(t>1)for(var n=new xo,i=1;i<t;++i)e=n.merge(e,r[i]);return e}var WR=function(r,e,t){return this.merge(r[t],e[t])},xo=(function(){function r(e){e===void 0&&(e=WR),this.reconciler=e,this.isObject=ci,this.pastCopies=new Set}return r.prototype.merge=function(e,t){for(var n=this,i=[],a=2;a<arguments.length;a++)i[a-2]=arguments[a];return ci(t)&&ci(e)?(Object.keys(t).forEach(function(s){if(qR.call(e,s)){var o=e[s];if(t[s]!==o){var l=n.reconciler.apply(n,ta([e,t,s],i,!1));l!==o&&(e=n.shallowCopyForMerge(e),e[s]=l)}}else e=n.shallowCopyForMerge(e),e[s]=t[s]}),e):t},r.prototype.shallowCopyForMerge=function(e){return ci(e)&&(this.pastCopies.has(e)||(Array.isArray(e)?e=e.slice(0):e=me({__proto__:Object.getPrototypeOf(e)},e),this.pastCopies.add(e))),e},r})();function QR(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=YR(r))||e){t&&(r=t);var n=0;return function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
55
+ `)))!==null&&e!==void 0?e:!1}function dw(r){return r.kind===et.FIELD||r.kind===et.FRAGMENT_SPREAD||r.kind===et.INLINE_FRAGMENT}function Pf(r,e){var t=r.directives;return!t||!t.length?!0:JD(t).every(function(n){var i=n.directive,a=n.ifArgument,s=!1;return a.value.kind==="Variable"?(s=e&&e[a.value.name.value],Mr(s!==void 0,105,i.name.value)):s=a.value.value,i.name.value==="skip"?!s:s})}function lf(r,e,t){var n=new Set(r),i=n.size;return Ia(e,{Directive:function(a){if(n.delete(a.name.value)&&(!t||!n.size))return IA}}),t?!n.size:n.size<i}function YD(r){return r&&lf(["client","export"],r,!0)}function XD(r){var e=r.name.value;return e==="skip"||e==="include"}function JD(r){var e=[];return r&&r.length&&r.forEach(function(t){if(XD(t)){var n=t.arguments,i=t.name.value;Mr(n&&n.length===1,106,i);var a=n[0];Mr(a.name&&a.name.value==="if",107,i);var s=a.value;Mr(s&&(s.kind==="Variable"||s.kind==="BooleanValue"),108,i),e.push({directive:t,ifArgument:a})}}),e}function KD(r){var e,t,n=(e=r.directives)===null||e===void 0?void 0:e.find(function(a){var s=a.name;return s.value==="unmask"});if(!n)return"mask";var i=(t=n.arguments)===null||t===void 0?void 0:t.find(function(a){var s=a.name;return s.value==="mode"});return i&&"value"in i.value&&i.value.value==="migrate"?"migrate":"unmask"}const ZD=()=>Object.create(null),{forEach:eR,slice:fw}=Array.prototype,{hasOwnProperty:tR}=Object.prototype;class _s{constructor(e=!0,t=ZD){this.weakness=e,this.makeData=t}lookup(){return this.lookupArray(arguments)}lookupArray(e){let t=this;return eR.call(e,n=>t=t.getChildTrie(n)),tR.call(t,"data")?t.data:t.data=this.makeData(fw.call(e))}peek(){return this.peekArray(arguments)}peekArray(e){let t=this;for(let n=0,i=e.length;t&&n<i;++n){const a=t.mapFor(e[n],!1);t=a&&a.get(e[n])}return t&&t.data}remove(){return this.removeArray(arguments)}removeArray(e){let t;if(e.length){const n=e[0],i=this.mapFor(n,!1),a=i&&i.get(n);a&&(t=a.removeArray(fw.call(e,1)),!a.data&&!a.weak&&!(a.strong&&a.strong.size)&&i.delete(n))}else t=this.data,delete this.data;return t}getChildTrie(e){const t=this.mapFor(e,!0);let n=t.get(e);return n||t.set(e,n=new _s(this.weakness,this.makeData)),n}mapFor(e,t){return this.weakness&&rR(e)?this.weak||(t?this.weak=new WeakMap:void 0):this.strong||(t?this.strong=new Map:void 0)}}function rR(r){switch(typeof r){case"object":if(r===null)break;case"function":return!0}return!1}var nR=Ta(function(){return navigator.product})=="ReactNative",Tl=typeof WeakMap=="function"&&!(nR&&!global.HermesInternal),PA=typeof WeakSet=="function",U2=typeof Symbol=="function"&&typeof Symbol.for=="function",Tg=U2&&Symbol.asyncIterator;Ta(function(){return window.document.createElement});Ta(function(){return navigator.userAgent.indexOf("jsdom")>=0});function ci(r){return r!==null&&typeof r=="object"}function V2(r){return r!==null&&typeof r=="object"&&(Object.getPrototypeOf(r)===Object.prototype||Object.getPrototypeOf(r)===null)}function iR(r,e){var t=e,n=[];r.definitions.forEach(function(a){if(a.kind==="OperationDefinition")throw ji(112,a.operation,a.name?" named '".concat(a.name.value,"'"):"");a.kind==="FragmentDefinition"&&n.push(a)}),typeof t>"u"&&(Mr(n.length===1,113,n.length),t=n[0].name.value);var i=me(me({},r),{definitions:ta([{kind:"OperationDefinition",operation:"query",selectionSet:{kind:"SelectionSet",selections:[{kind:"FragmentSpread",name:{kind:"Name",value:t}}]}}],r.definitions,!0)});return i}function lc(r){r===void 0&&(r=[]);var e={};return r.forEach(function(t){e[t.name.value]=t}),e}function Fg(r,e){switch(r.kind){case"InlineFragment":return r;case"FragmentSpread":{var t=r.name.value;if(typeof e=="function")return e(t);var n=e&&e[t];return Mr(n,114,t),n||null}default:return null}}function aR(){}class dy{constructor(e=1/0,t=aR){this.max=e,this.dispose=t,this.map=new Map,this.newest=null,this.oldest=null}has(e){return this.map.has(e)}get(e){const t=this.getNode(e);return t&&t.value}get size(){return this.map.size}getNode(e){const t=this.map.get(e);if(t&&t!==this.newest){const{older:n,newer:i}=t;i&&(i.older=n),n&&(n.newer=i),t.older=this.newest,t.older.newer=t,t.newer=null,this.newest=t,t===this.oldest&&(this.oldest=i)}return t}set(e,t){let n=this.getNode(e);return n?n.value=t:(n={key:e,value:t,newer:null,older:this.newest},this.newest&&(this.newest.newer=n),this.newest=n,this.oldest=this.oldest||n,this.map.set(e,n),n.value)}clean(){for(;this.oldest&&this.map.size>this.max;)this.delete(this.oldest.key)}delete(e){const t=this.map.get(e);return t?(t===this.newest&&(this.newest=t.older),t===this.oldest&&(this.oldest=t.newer),t.newer&&(t.newer.older=t.older),t.older&&(t.older.newer=t.newer),this.map.delete(e),this.dispose(t.value,e),!0):!1}}function fy(){}const sR=fy,oR=typeof WeakRef<"u"?WeakRef:function(r){return{deref:()=>r}},lR=typeof WeakMap<"u"?WeakMap:Map,uR=typeof FinalizationRegistry<"u"?FinalizationRegistry:function(){return{register:fy,unregister:fy}},cR=10024;class uf{constructor(e=1/0,t=sR){this.max=e,this.dispose=t,this.map=new lR,this.newest=null,this.oldest=null,this.unfinalizedNodes=new Set,this.finalizationScheduled=!1,this.size=0,this.finalize=()=>{const n=this.unfinalizedNodes.values();for(let i=0;i<cR;i++){const a=n.next().value;if(!a)break;this.unfinalizedNodes.delete(a);const s=a.key;delete a.key,a.keyRef=new oR(s),this.registry.register(s,a,a)}this.unfinalizedNodes.size>0?queueMicrotask(this.finalize):this.finalizationScheduled=!1},this.registry=new uR(this.deleteNode.bind(this))}has(e){return this.map.has(e)}get(e){const t=this.getNode(e);return t&&t.value}getNode(e){const t=this.map.get(e);if(t&&t!==this.newest){const{older:n,newer:i}=t;i&&(i.older=n),n&&(n.newer=i),t.older=this.newest,t.older.newer=t,t.newer=null,this.newest=t,t===this.oldest&&(this.oldest=i)}return t}set(e,t){let n=this.getNode(e);return n?n.value=t:(n={key:e,value:t,newer:null,older:this.newest},this.newest&&(this.newest.newer=n),this.newest=n,this.oldest=this.oldest||n,this.scheduleFinalization(n),this.map.set(e,n),this.size++,n.value)}clean(){for(;this.oldest&&this.size>this.max;)this.deleteNode(this.oldest)}deleteNode(e){e===this.newest&&(this.newest=e.older),e===this.oldest&&(this.oldest=e.newer),e.newer&&(e.newer.older=e.older),e.older&&(e.older.newer=e.newer),this.size--;const t=e.key||e.keyRef&&e.keyRef.deref();this.dispose(e.value,t),e.keyRef?this.registry.unregister(e):this.unfinalizedNodes.delete(e),t&&this.map.delete(t)}delete(e){const t=this.map.get(e);return t?(this.deleteNode(t),!0):!1}scheduleFinalization(e){this.unfinalizedNodes.add(e),this.finalizationScheduled||(this.finalizationScheduled=!0,queueMicrotask(this.finalize))}}var Km=new WeakSet;function z2(r){r.size<=(r.max||-1)||Km.has(r)||(Km.add(r),setTimeout(function(){r.clean(),Km.delete(r)},100))}var $2=function(r,e){var t=new uf(r,e);return t.set=function(n,i){var a=uf.prototype.set.call(this,n,i);return z2(this),a},t},dR=function(r,e){var t=new dy(r,e);return t.set=function(n,i){var a=dy.prototype.set.call(this,n,i);return z2(this),a},t},fR=Symbol.for("apollo.cacheSize"),Ms=me({},eg[fR]),go=Object.assign(function(e){return JSON.stringify(e,hR)},{reset:function(){Rd=new dR(Ms.canonicalStringify||1e3)}}),Rd;go.reset();function hR(r,e){if(e&&typeof e=="object"){var t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null){var n=Object.keys(e);if(n.every(pR))return e;var i=JSON.stringify(n),a=Rd.get(i);if(!a){n.sort();var s=JSON.stringify(n);a=Rd.get(s)||n,Rd.set(i,a),Rd.set(s,a)}var o=Object.create(t);return a.forEach(function(l){o[l]=e[l]}),o}}return e}function pR(r,e,t){return e===0||t[e-1]<=r}function Uu(r){return{__ref:String(r)}}function Tn(r){return!!(r&&typeof r=="object"&&typeof r.__ref=="string")}function gR(r){return ci(r)&&r.kind==="Document"&&Array.isArray(r.definitions)}function mR(r){return r.kind==="StringValue"}function vR(r){return r.kind==="BooleanValue"}function yR(r){return r.kind==="IntValue"}function AR(r){return r.kind==="FloatValue"}function bR(r){return r.kind==="Variable"}function wR(r){return r.kind==="ObjectValue"}function CR(r){return r.kind==="ListValue"}function xR(r){return r.kind==="EnumValue"}function SR(r){return r.kind==="NullValue"}function qu(r,e,t,n){if(yR(t)||AR(t))r[e.value]=Number(t.value);else if(vR(t)||mR(t))r[e.value]=t.value;else if(wR(t)){var i={};t.fields.map(function(s){return qu(i,s.name,s.value,n)}),r[e.value]=i}else if(bR(t)){var a=(n||{})[t.name.value];r[e.value]=a}else if(CR(t))r[e.value]=t.values.map(function(s){var o={};return qu(o,e,s,n),o[e.value]});else if(xR(t))r[e.value]=t.value;else if(SR(t))r[e.value]=null;else throw ji(123,e.value,t.kind)}function ER(r,e){var t=null;r.directives&&(t={},r.directives.forEach(function(i){t[i.name.value]={},i.arguments&&i.arguments.forEach(function(a){var s=a.name,o=a.value;return qu(t[i.name.value],s,o,e)})}));var n=null;return r.arguments&&r.arguments.length&&(n={},r.arguments.forEach(function(i){var a=i.name,s=i.value;return qu(n,a,s,e)})),H2(r.name.value,n,t)}var kR=["connection","include","skip","client","rest","export","nonreactive"],td=go,H2=Object.assign(function(r,e,t){if(e&&t&&t.connection&&t.connection.key)if(t.connection.filter&&t.connection.filter.length>0){var n=t.connection.filter?t.connection.filter:[];n.sort();var i={};return n.forEach(function(o){i[o]=e[o]}),"".concat(t.connection.key,"(").concat(td(i),")")}else return t.connection.key;var a=r;if(e){var s=td(e);a+="(".concat(s,")")}return t&&Object.keys(t).forEach(function(o){kR.indexOf(o)===-1&&(t[o]&&Object.keys(t[o]).length?a+="@".concat(o,"(").concat(td(t[o]),")"):a+="@".concat(o))}),a},{setStringify:function(r){var e=td;return td=r,e}});function Ig(r,e){if(r.arguments&&r.arguments.length){var t={};return r.arguments.forEach(function(n){var i=n.name,a=n.value;return qu(t,i,a,e)}),t}return null}function bo(r){return r.alias?r.alias.value:r.name.value}function hy(r,e,t){for(var n,i=0,a=e.selections;i<a.length;i++){var s=a[i];if(wo(s)){if(s.name.value==="__typename")return r[bo(s)]}else n?n.push(s):n=[s]}if(typeof r.__typename=="string")return r.__typename;if(n)for(var o=0,l=n;o<l.length;o++){var s=l[o],u=hy(r,Fg(s,t).selectionSet,t);if(typeof u=="string")return u}}function wo(r){return r.kind==="Field"}function TR(r){return r.kind==="InlineFragment"}function uc(r){Mr(r&&r.kind==="Document",115);var e=r.definitions.filter(function(t){return t.kind!=="FragmentDefinition"}).map(function(t){if(t.kind!=="OperationDefinition")throw ji(116,t.kind);return t});return Mr(e.length<=1,117,e.length),r}function cc(r){return uc(r),r.definitions.filter(function(e){return e.kind==="OperationDefinition"})[0]}function Bp(r){return r.definitions.filter(function(e){return e.kind==="OperationDefinition"&&!!e.name}).map(function(e){return e.name.value})[0]||null}function dc(r){return r.definitions.filter(function(e){return e.kind==="FragmentDefinition"})}function FR(r){var e=cc(r);return Mr(e&&e.operation==="query",118),e}function IR(r){Mr(r.kind==="Document",119),Mr(r.definitions.length<=1,120);var e=r.definitions[0];return Mr(e.kind==="FragmentDefinition",121),e}function Df(r){uc(r);for(var e,t=0,n=r.definitions;t<n.length;t++){var i=n[t];if(i.kind==="OperationDefinition"){var a=i.operation;if(a==="query"||a==="mutation"||a==="subscription")return i}i.kind==="FragmentDefinition"&&!e&&(e=i)}if(e)return e;throw ji(122)}function DA(r){var e=Object.create(null),t=r&&r.variableDefinitions;return t&&t.length&&t.forEach(function(n){n.defaultValue&&qu(e,n.variable.name,n.defaultValue)}),e}let Si=null;const hw={};let PR=1;const DR=()=>class{constructor(){this.id=["slot",PR++,Date.now(),Math.random().toString(36).slice(2)].join(":")}hasValue(){for(let e=Si;e;e=e.parent)if(this.id in e.slots){const t=e.slots[this.id];if(t===hw)break;return e!==Si&&(Si.slots[this.id]=t),!0}return Si&&(Si.slots[this.id]=hw),!1}getValue(){if(this.hasValue())return Si.slots[this.id]}withValue(e,t,n,i){const a={__proto__:null,[this.id]:e},s=Si;Si={parent:s,slots:a};try{return t.apply(i,n)}finally{Si=s}}static bind(e){const t=Si;return function(){const n=Si;try{return Si=t,e.apply(this,arguments)}finally{Si=n}}}static noContext(e,t,n){if(Si){const i=Si;try{return Si=null,e.apply(n,t)}finally{Si=i}}else return e.apply(n,t)}};function pw(r){try{return r()}catch{}}const Zm="@wry/context:Slot",RR=pw(()=>globalThis)||pw(()=>global)||Object.create(null),gw=RR,fc=gw[Zm]||Array[Zm]||(function(r){try{Object.defineProperty(gw,Zm,{value:r,enumerable:!1,writable:!1,configurable:!0})}finally{return r}})(DR()),{bind:MY,noContext:_Y}=fc,Pg=new fc,{hasOwnProperty:OR}=Object.prototype,RA=Array.from||function(r){const e=[];return r.forEach(t=>e.push(t)),e};function OA(r){const{unsubscribe:e}=r;typeof e=="function"&&(r.unsubscribe=void 0,e())}const cf=[],BR=100;function Wu(r,e){if(!r)throw new Error(e||"assertion failure")}function j2(r,e){const t=r.length;return t>0&&t===e.length&&r[t-1]===e[t-1]}function G2(r){switch(r.length){case 0:throw new Error("unknown value");case 1:return r[0];case 2:throw r[1]}}function q2(r){return r.slice(0)}class Dg{constructor(e){this.fn=e,this.parents=new Set,this.childValues=new Map,this.dirtyChildren=null,this.dirty=!0,this.recomputing=!1,this.value=[],this.deps=null,++Dg.count}peek(){if(this.value.length===1&&!Co(this))return mw(this),this.value[0]}recompute(e){return Wu(!this.recomputing,"already recomputing"),mw(this),Co(this)?MR(this,e):G2(this.value)}setDirty(){this.dirty||(this.dirty=!0,W2(this),OA(this))}dispose(){this.setDirty(),K2(this),BA(this,(e,t)=>{e.setDirty(),Z2(e,this)})}forget(){this.dispose()}dependOn(e){e.add(this),this.deps||(this.deps=cf.pop()||new Set),this.deps.add(e)}forgetDeps(){this.deps&&(RA(this.deps).forEach(e=>e.delete(this)),this.deps.clear(),cf.push(this.deps),this.deps=null)}}Dg.count=0;function mw(r){const e=Pg.getValue();if(e)return r.parents.add(e),e.childValues.has(r)||e.childValues.set(r,[]),Co(r)?Y2(e,r):X2(e,r),e}function MR(r,e){return K2(r),Pg.withValue(r,_R,[r,e]),LR(r,e)&&NR(r),G2(r.value)}function _R(r,e){r.recomputing=!0;const{normalizeResult:t}=r;let n;t&&r.value.length===1&&(n=q2(r.value)),r.value.length=0;try{if(r.value[0]=r.fn.apply(null,e),t&&n&&!j2(n,r.value))try{r.value[0]=t(r.value[0],n[0])}catch{}}catch(i){r.value[1]=i}r.recomputing=!1}function Co(r){return r.dirty||!!(r.dirtyChildren&&r.dirtyChildren.size)}function NR(r){r.dirty=!1,!Co(r)&&Q2(r)}function W2(r){BA(r,Y2)}function Q2(r){BA(r,X2)}function BA(r,e){const t=r.parents.size;if(t){const n=RA(r.parents);for(let i=0;i<t;++i)e(n[i],r)}}function Y2(r,e){Wu(r.childValues.has(e)),Wu(Co(e));const t=!Co(r);if(!r.dirtyChildren)r.dirtyChildren=cf.pop()||new Set;else if(r.dirtyChildren.has(e))return;r.dirtyChildren.add(e),t&&W2(r)}function X2(r,e){Wu(r.childValues.has(e)),Wu(!Co(e));const t=r.childValues.get(e);t.length===0?r.childValues.set(e,q2(e.value)):j2(t,e.value)||r.setDirty(),J2(r,e),!Co(r)&&Q2(r)}function J2(r,e){const t=r.dirtyChildren;t&&(t.delete(e),t.size===0&&(cf.length<BR&&cf.push(t),r.dirtyChildren=null))}function K2(r){r.childValues.size>0&&r.childValues.forEach((e,t)=>{Z2(r,t)}),r.forgetDeps(),Wu(r.dirtyChildren===null)}function Z2(r,e){e.parents.delete(r),r.childValues.delete(e),J2(r,e)}function LR(r,e){if(typeof r.subscribe=="function")try{OA(r),r.unsubscribe=r.subscribe.apply(null,e)}catch{return r.setDirty(),!1}return!0}const UR={setDirty:!0,dispose:!0,forget:!0};function ek(r){const e=new Map;function t(n){const i=Pg.getValue();if(i){let a=e.get(n);a||e.set(n,a=new Set),i.dependOn(a)}}return t.dirty=function(i,a){const s=e.get(i);if(s){const o=a&&OR.call(UR,a)?a:"setDirty";RA(s).forEach(l=>l[o]()),e.delete(i),OA(s)}},t}let vw;function VR(...r){return(vw||(vw=new _s(typeof WeakMap=="function"))).lookupArray(r)}const e0=new Set;function Qu(r,{max:e=Math.pow(2,16),keyArgs:t,makeCacheKey:n=VR,normalizeResult:i,subscribe:a,cache:s=dy}=Object.create(null)){const o=typeof s=="function"?new s(e,d=>d.dispose()):s,l=function(){const d=n.apply(null,t?t.apply(null,arguments):arguments);if(d===void 0)return r.apply(null,arguments);let h=o.get(d);h||(o.set(d,h=new Dg(r)),h.normalizeResult=i,h.subscribe=a,h.forget=()=>o.delete(d));const g=h.recompute(Array.prototype.slice.call(arguments));return o.set(d,h),e0.add(o),Pg.hasValue()||(e0.forEach(v=>v.clean()),e0.clear()),g};Object.defineProperty(l,"size",{get:()=>o.size,configurable:!1,enumerable:!1}),Object.freeze(l.options={max:e,keyArgs:t,makeCacheKey:n,normalizeResult:i,subscribe:a,cache:o});function u(d){const h=d&&o.get(d);h&&h.setDirty()}l.dirtyKey=u,l.dirty=function(){u(n.apply(null,arguments))};function c(d){const h=d&&o.get(d);if(h)return h.peek()}l.peekKey=c,l.peek=function(){return c(n.apply(null,arguments))};function f(d){return d?o.delete(d):!1}return l.forgetKey=f,l.forget=function(){return f(n.apply(null,arguments))},l.makeCacheKey=n,l.getKey=t?function(){return n.apply(null,t.apply(null,arguments))}:n,Object.freeze(l)}function zR(r){return r}var tk=(function(){function r(e,t){t===void 0&&(t=Object.create(null)),this.resultCache=PA?new WeakSet:new Set,this.transform=e,t.getCacheKey&&(this.getCacheKey=t.getCacheKey),this.cached=t.cache!==!1,this.resetCache()}return r.prototype.getCacheKey=function(e){return[e]},r.identity=function(){return new r(zR,{cache:!1})},r.split=function(e,t,n){return n===void 0&&(n=r.identity()),Object.assign(new r(function(i){var a=e(i)?t:n;return a.transformDocument(i)},{cache:!1}),{left:t,right:n})},r.prototype.resetCache=function(){var e=this;if(this.cached){var t=new _s(Tl);this.performWork=Qu(r.prototype.performWork.bind(this),{makeCacheKey:function(n){var i=e.getCacheKey(n);if(i)return Mr(Array.isArray(i),104),t.lookupArray(i)},max:Ms["documentTransform.cache"],cache:uf})}},r.prototype.performWork=function(e){return uc(e),this.transform(e)},r.prototype.transformDocument=function(e){if(this.resultCache.has(e))return e;var t=this.performWork(e);return this.resultCache.add(t),t},r.prototype.concat=function(e){var t=this;return Object.assign(new r(function(n){return e.transformDocument(t.transformDocument(n))},{cache:!1}),{left:this,right:e})},r})(),t0,yl=Object.assign(function(r){var e=t0.get(r);return e||(e=L2(r),t0.set(r,e)),e},{reset:function(){t0=new $2(Ms.print||2e3)}});yl.reset();var ii=Array.isArray;function ls(r){return Array.isArray(r)&&r.length>0}var yw={kind:et.FIELD,name:{kind:et.NAME,value:"__typename"}};function rk(r,e){return!r||r.selectionSet.selections.every(function(t){return t.kind===et.FRAGMENT_SPREAD&&rk(e[t.name.value],e)})}function $R(r){return rk(cc(r)||IR(r),lc(dc(r)))?null:r}function HR(r){var e=new Map,t=new Map;return r.forEach(function(n){n&&(n.name?e.set(n.name,n):n.test&&t.set(n.test,n))}),function(n){var i=e.get(n.name.value);return!i&&t.size&&t.forEach(function(a,s){s(n)&&(i=a)}),i}}function Aw(r){var e=new Map;return function(n){n===void 0&&(n=r);var i=e.get(n);return i||e.set(n,i={variables:new Set,fragmentSpreads:new Set}),i}}function nk(r,e){uc(e);for(var t=Aw(""),n=Aw(""),i=function(A){for(var C=0,S=void 0;C<A.length&&(S=A[C]);++C)if(!ii(S)){if(S.kind===et.OPERATION_DEFINITION)return t(S.name&&S.name.value);if(S.kind===et.FRAGMENT_DEFINITION)return n(S.name.value)}return null},a=0,s=e.definitions.length-1;s>=0;--s)e.definitions[s].kind===et.OPERATION_DEFINITION&&++a;var o=HR(r),l=function(A){return ls(A)&&A.map(o).some(function(C){return C&&C.remove})},u=new Map,c=!1,f={enter:function(A){if(l(A.directives))return c=!0,null}},d=Ia(e,{Field:f,InlineFragment:f,VariableDefinition:{enter:function(){return!1}},Variable:{enter:function(A,C,S,F,E){var R=i(E);R&&R.variables.add(A.name.value)}},FragmentSpread:{enter:function(A,C,S,F,E){if(l(A.directives))return c=!0,null;var R=i(E);R&&R.fragmentSpreads.add(A.name.value)}},FragmentDefinition:{enter:function(A,C,S,F){u.set(JSON.stringify(F),A)},leave:function(A,C,S,F){var E=u.get(JSON.stringify(F));if(A===E)return A;if(a>0&&A.selectionSet.selections.every(function(R){return R.kind===et.FIELD&&R.name.value==="__typename"}))return n(A.name.value).removed=!0,c=!0,null}},Directive:{leave:function(A){if(o(A))return c=!0,null}}});if(!c)return e;var h=function(A){return A.transitiveVars||(A.transitiveVars=new Set(A.variables),A.removed||A.fragmentSpreads.forEach(function(C){h(n(C)).transitiveVars.forEach(function(S){A.transitiveVars.add(S)})})),A},g=new Set;d.definitions.forEach(function(A){A.kind===et.OPERATION_DEFINITION?h(t(A.name&&A.name.value)).fragmentSpreads.forEach(function(C){g.add(C)}):A.kind===et.FRAGMENT_DEFINITION&&a===0&&!n(A.name.value).removed&&g.add(A.name.value)}),g.forEach(function(A){h(n(A)).fragmentSpreads.forEach(function(C){g.add(C)})});var v=function(A){return!!(!g.has(A)||n(A).removed)},y={enter:function(A){if(v(A.name.value))return null}};return $R(Ia(d,{FragmentSpread:y,FragmentDefinition:y,OperationDefinition:{leave:function(A){if(A.variableDefinitions){var C=h(t(A.name&&A.name.value)).transitiveVars;if(C.size<A.variableDefinitions.length)return me(me({},A),{variableDefinitions:A.variableDefinitions.filter(function(S){return C.has(S.variable.name.value)})})}}}}))}var ik=Object.assign(function(r){return Ia(r,{SelectionSet:{enter:function(e,t,n){if(!(n&&n.kind===et.OPERATION_DEFINITION)){var i=e.selections;if(i){var a=i.some(function(o){return wo(o)&&(o.name.value==="__typename"||o.name.value.lastIndexOf("__",0)===0)});if(!a){var s=n;if(!(wo(s)&&s.directives&&s.directives.some(function(o){return o.name.value==="export"})))return me(me({},e),{selections:ta(ta([],i,!0),[yw],!1)})}}}}}})},{added:function(r){return r===yw}});function jR(r){var e=Df(r),t=e.operation;if(t==="query")return r;var n=Ia(r,{OperationDefinition:{enter:function(i){return me(me({},i),{operation:"query"})}}});return n}function ak(r){uc(r);var e=nk([{test:function(t){return t.name.value==="client"},remove:!0}],r);return e}function GR(r){return uc(r),Ia(r,{FragmentSpread:function(e){var t;if(!(!((t=e.directives)===null||t===void 0)&&t.some(function(n){return n.name.value==="unmask"})))return me(me({},e),{directives:ta(ta([],e.directives||[],!0),[{kind:et.DIRECTIVE,name:{kind:et.NAME,value:"nonreactive"}}],!1)})}})}var qR=Object.prototype.hasOwnProperty;function bw(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return Rg(r)}function Rg(r){var e=r[0]||{},t=r.length;if(t>1)for(var n=new xo,i=1;i<t;++i)e=n.merge(e,r[i]);return e}var WR=function(r,e,t){return this.merge(r[t],e[t])},xo=(function(){function r(e){e===void 0&&(e=WR),this.reconciler=e,this.isObject=ci,this.pastCopies=new Set}return r.prototype.merge=function(e,t){for(var n=this,i=[],a=2;a<arguments.length;a++)i[a-2]=arguments[a];return ci(t)&&ci(e)?(Object.keys(t).forEach(function(s){if(qR.call(e,s)){var o=e[s];if(t[s]!==o){var l=n.reconciler.apply(n,ta([e,t,s],i,!1));l!==o&&(e=n.shallowCopyForMerge(e),e[s]=l)}}else e=n.shallowCopyForMerge(e),e[s]=t[s]}),e):t},r.prototype.shallowCopyForMerge=function(e){return ci(e)&&(this.pastCopies.has(e)||(Array.isArray(e)?e=e.slice(0):e=me({__proto__:Object.getPrototypeOf(e)},e),this.pastCopies.add(e))),e},r})();function QR(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t)return(t=t.call(r)).next.bind(t);if(Array.isArray(r)||(t=YR(r))||e){t&&(r=t);var n=0;return function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
56
56
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function YR(r,e){if(r){if(typeof r=="string")return ww(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return ww(r,e)}}function ww(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function Cw(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function MA(r,e,t){return e&&Cw(r.prototype,e),t&&Cw(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}var _A=function(){return typeof Symbol=="function"},NA=function(r){return _A()&&!!Symbol[r]},LA=function(r){return NA(r)?Symbol[r]:"@@"+r};_A()&&!NA("observable")&&(Symbol.observable=Symbol("observable"));var XR=LA("iterator"),py=LA("observable"),sk=LA("species");function tg(r,e){var t=r[e];if(t!=null){if(typeof t!="function")throw new TypeError(t+" is not a function");return t}}function rd(r){var e=r.constructor;return e!==void 0&&(e=e[sk],e===null&&(e=void 0)),e!==void 0?e:an}function JR(r){return r instanceof an}function Yu(r){Yu.log?Yu.log(r):setTimeout(function(){throw r})}function Mp(r){Promise.resolve().then(function(){try{r()}catch(e){Yu(e)}})}function ok(r){var e=r._cleanup;if(e!==void 0&&(r._cleanup=void 0,!!e))try{if(typeof e=="function")e();else{var t=tg(e,"unsubscribe");t&&t.call(e)}}catch(n){Yu(n)}}function gy(r){r._observer=void 0,r._queue=void 0,r._state="closed"}function KR(r){var e=r._queue;if(e){r._queue=void 0,r._state="ready";for(var t=0;t<e.length&&(lk(r,e[t].type,e[t].value),r._state!=="closed");++t);}}function lk(r,e,t){r._state="running";var n=r._observer;try{var i=tg(n,e);switch(e){case"next":i&&i.call(n,t);break;case"error":if(gy(r),i)i.call(n,t);else throw t;break;case"complete":gy(r),i&&i.call(n);break}}catch(a){Yu(a)}r._state==="closed"?ok(r):r._state==="running"&&(r._state="ready")}function r0(r,e,t){if(r._state!=="closed"){if(r._state==="buffering"){r._queue.push({type:e,value:t});return}if(r._state!=="ready"){r._state="buffering",r._queue=[{type:e,value:t}],Mp(function(){return KR(r)});return}lk(r,e,t)}}var ZR=(function(){function r(t,n){this._cleanup=void 0,this._observer=t,this._queue=void 0,this._state="initializing";var i=new eO(this);try{this._cleanup=n.call(void 0,i)}catch(a){i.error(a)}this._state==="initializing"&&(this._state="ready")}var e=r.prototype;return e.unsubscribe=function(){this._state!=="closed"&&(gy(this),ok(this))},MA(r,[{key:"closed",get:function(){return this._state==="closed"}}]),r})(),eO=(function(){function r(t){this._subscription=t}var e=r.prototype;return e.next=function(n){r0(this._subscription,"next",n)},e.error=function(n){r0(this._subscription,"error",n)},e.complete=function(){r0(this._subscription,"complete")},MA(r,[{key:"closed",get:function(){return this._subscription._state==="closed"}}]),r})(),an=(function(){function r(t){if(!(this instanceof r))throw new TypeError("Observable cannot be called as a function");if(typeof t!="function")throw new TypeError("Observable initializer must be a function");this._subscriber=t}var e=r.prototype;return e.subscribe=function(n){return(typeof n!="object"||n===null)&&(n={next:n,error:arguments[1],complete:arguments[2]}),new ZR(n,this._subscriber)},e.forEach=function(n){var i=this;return new Promise(function(a,s){if(typeof n!="function"){s(new TypeError(n+" is not a function"));return}function o(){l.unsubscribe(),a()}var l=i.subscribe({next:function(u){try{n(u,o)}catch(c){s(c),l.unsubscribe()}},error:s,complete:a})})},e.map=function(n){var i=this;if(typeof n!="function")throw new TypeError(n+" is not a function");var a=rd(this);return new a(function(s){return i.subscribe({next:function(o){try{o=n(o)}catch(l){return s.error(l)}s.next(o)},error:function(o){s.error(o)},complete:function(){s.complete()}})})},e.filter=function(n){var i=this;if(typeof n!="function")throw new TypeError(n+" is not a function");var a=rd(this);return new a(function(s){return i.subscribe({next:function(o){try{if(!n(o))return}catch(l){return s.error(l)}s.next(o)},error:function(o){s.error(o)},complete:function(){s.complete()}})})},e.reduce=function(n){var i=this;if(typeof n!="function")throw new TypeError(n+" is not a function");var a=rd(this),s=arguments.length>1,o=!1,l=arguments[1],u=l;return new a(function(c){return i.subscribe({next:function(f){var d=!o;if(o=!0,!d||s)try{u=n(u,f)}catch(h){return c.error(h)}else u=f},error:function(f){c.error(f)},complete:function(){if(!o&&!s)return c.error(new TypeError("Cannot reduce an empty sequence"));c.next(u),c.complete()}})})},e.concat=function(){for(var n=this,i=arguments.length,a=new Array(i),s=0;s<i;s++)a[s]=arguments[s];var o=rd(this);return new o(function(l){var u,c=0;function f(d){u=d.subscribe({next:function(h){l.next(h)},error:function(h){l.error(h)},complete:function(){c===a.length?(u=void 0,l.complete()):f(o.from(a[c++]))}})}return f(n),function(){u&&(u.unsubscribe(),u=void 0)}})},e.flatMap=function(n){var i=this;if(typeof n!="function")throw new TypeError(n+" is not a function");var a=rd(this);return new a(function(s){var o=[],l=i.subscribe({next:function(c){if(n)try{c=n(c)}catch(d){return s.error(d)}var f=a.from(c).subscribe({next:function(d){s.next(d)},error:function(d){s.error(d)},complete:function(){var d=o.indexOf(f);d>=0&&o.splice(d,1),u()}});o.push(f)},error:function(c){s.error(c)},complete:function(){u()}});function u(){l.closed&&o.length===0&&s.complete()}return function(){o.forEach(function(c){return c.unsubscribe()}),l.unsubscribe()}})},e[py]=function(){return this},r.from=function(n){var i=typeof this=="function"?this:r;if(n==null)throw new TypeError(n+" is not an object");var a=tg(n,py);if(a){var s=a.call(n);if(Object(s)!==s)throw new TypeError(s+" is not an object");return JR(s)&&s.constructor===i?s:new i(function(o){return s.subscribe(o)})}if(NA("iterator")&&(a=tg(n,XR),a))return new i(function(o){Mp(function(){if(!o.closed){for(var l=QR(a.call(n)),u;!(u=l()).done;){var c=u.value;if(o.next(c),o.closed)return}o.complete()}})});if(Array.isArray(n))return new i(function(o){Mp(function(){if(!o.closed){for(var l=0;l<n.length;++l)if(o.next(n[l]),o.closed)return;o.complete()}})});throw new TypeError(n+" is not observable")},r.of=function(){for(var n=arguments.length,i=new Array(n),a=0;a<n;a++)i[a]=arguments[a];var s=typeof this=="function"?this:r;return new s(function(o){Mp(function(){if(!o.closed){for(var l=0;l<i.length;++l)if(o.next(i[l]),o.closed)return;o.complete()}})})},MA(r,null,[{key:sk,get:function(){return this}}]),r})();_A()&&Object.defineProperty(an,Symbol("extensions"),{value:{symbol:py,hostReportError:Yu},configurable:!0});function tO(r){var e,t=r.Symbol;if(typeof t=="function")if(t.observable)e=t.observable;else{typeof t.for=="function"?e=t.for("https://github.com/benlesh/symbol-observable"):e=t("https://github.com/benlesh/symbol-observable");try{t.observable=e}catch{}}else e="@@observable";return e}var Tu;typeof self<"u"?Tu=self:typeof window<"u"?Tu=window:typeof global<"u"?Tu=global:typeof module<"u"?Tu=module:Tu=Function("return this")();tO(Tu);var xw=an.prototype,Sw="@@observable";xw[Sw]||(xw[Sw]=function(){return this});function rO(r){return r.catch(function(){}),r}var nO=Object.prototype.toString;function iO(r){return my(r)}function my(r,e){switch(nO.call(r)){case"[object Array]":{if(e=e||new Map,e.has(r))return e.get(r);var t=r.slice(0);return e.set(r,t),t.forEach(function(i,a){t[a]=my(i,e)}),t}case"[object Object]":{if(e=e||new Map,e.has(r))return e.get(r);var n=Object.create(Object.getPrototypeOf(r));return e.set(r,n),Object.keys(r).forEach(function(i){n[i]=my(r[i],e)}),n}default:return r}}function jd(r,e,t){var n=[];r.forEach(function(i){return i[e]&&n.push(i)}),n.forEach(function(i){return i[e](t)})}function n0(r,e,t){return new an(function(n){var i={then:function(l){return new Promise(function(u){return u(l())})}};function a(l,u){return function(c){if(l){var f=function(){return n.closed?0:l(c)};i=i.then(f,f).then(function(d){return n.next(d)},function(d){return n.error(d)})}else n[u](c)}}var s={next:a(e,"next"),error:a(t,"error"),complete:function(){i.then(function(){return n.complete()})}},o=r.subscribe(s);return function(){return o.unsubscribe()}})}function uk(r){function e(t){Object.defineProperty(r,t,{value:an})}return U2&&Symbol.species&&e(Symbol.species),e("@@species"),r}function Ew(r){return r&&typeof r.then=="function"}var Fu=(function(r){pa(e,r);function e(t){var n=r.call(this,function(i){return n.addObserver(i),function(){return n.removeObserver(i)}})||this;return n.observers=new Set,n.promise=new Promise(function(i,a){n.resolve=i,n.reject=a}),n.handlers={next:function(i){n.sub!==null&&(n.latest=["next",i],n.notify("next",i),jd(n.observers,"next",i))},error:function(i){var a=n.sub;a!==null&&(a&&setTimeout(function(){return a.unsubscribe()}),n.sub=null,n.latest=["error",i],n.reject(i),n.notify("error",i),jd(n.observers,"error",i))},complete:function(){var i=n,a=i.sub,s=i.sources,o=s===void 0?[]:s;if(a!==null){var l=o.shift();l?Ew(l)?l.then(function(u){return n.sub=u.subscribe(n.handlers)},n.handlers.error):n.sub=l.subscribe(n.handlers):(a&&setTimeout(function(){return a.unsubscribe()}),n.sub=null,n.latest&&n.latest[0]==="next"?n.resolve(n.latest[1]):n.resolve(),n.notify("complete"),jd(n.observers,"complete"))}}},n.nextResultListeners=new Set,n.cancel=function(i){n.reject(i),n.sources=[],n.handlers.error(i)},n.promise.catch(function(i){}),typeof t=="function"&&(t=[new an(t)]),Ew(t)?t.then(function(i){return n.start(i)},n.handlers.error):n.start(t),n}return e.prototype.start=function(t){this.sub===void 0&&(this.sources=Array.from(t),this.handlers.complete())},e.prototype.deliverLastMessage=function(t){if(this.latest){var n=this.latest[0],i=t[n];i&&i.call(t,this.latest[1]),this.sub===null&&n==="next"&&t.complete&&t.complete()}},e.prototype.addObserver=function(t){this.observers.has(t)||(this.deliverLastMessage(t),this.observers.add(t))},e.prototype.removeObserver=function(t){this.observers.delete(t)&&this.observers.size<1&&this.handlers.complete()},e.prototype.notify=function(t,n){var i=this.nextResultListeners;i.size&&(this.nextResultListeners=new Set,i.forEach(function(a){return a(t,n)}))},e.prototype.beforeNext=function(t){var n=!1;this.nextResultListeners.add(function(i,a){n||(n=!0,t(i,a))})},e})(an);uk(Fu);function Vu(r){return"incremental"in r}function aO(r){return"hasNext"in r&&"data"in r}function sO(r){return Vu(r)||aO(r)}function oO(r){return ci(r)&&"payload"in r}function ck(r,e){var t=r,n=new xo;return Vu(e)&&ls(e.incremental)&&e.incremental.forEach(function(i){for(var a=i.data,s=i.path,o=s.length-1;o>=0;--o){var l=s[o],u=!isNaN(+l),c=u?[]:{};c[l]=a,a=c}t=n.merge(t,a)}),t}function _p(r){var e=vy(r);return ls(e)}function vy(r){var e=ls(r.errors)?r.errors.slice(0):[];return Vu(r)&&ls(r.incremental)&&r.incremental.forEach(function(t){t.errors&&e.push.apply(e,t.errors)}),e}function Xu(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];var t=Object.create(null);return r.forEach(function(n){n&&Object.keys(n).forEach(function(i){var a=n[i];a!==void 0&&(t[i]=a)})}),t}function i0(r,e){return Xu(r,e,e.variables&&{variables:Xu(me(me({},r&&r.variables),e.variables))})}function lO(r,e){return yy(r,e)}function yy(r,e,t){if(t===void 0&&(t=new Map),t.has(r))return t.get(r);var n=!1;if(Array.isArray(r)){var i=[];if(t.set(r,i),r.forEach(function(s,o){var l=yy(s,e,t);n||(n=l!==s),i[o]=l}),n)return i}else if(V2(r)){var a=Object.create(Object.getPrototypeOf(r));if(t.set(r,a),Object.keys(r).forEach(function(s){if(s===e){n=!0;return}var o=yy(r[s],e,t);n||(n=o!==r[s]),a[s]=o}),n)return a}return r}function UA(r){return lO(r,"__typename")}var a0,kw=Symbol.for("apollo.deprecations.slot"),Tw=eg,Fw=(a0=Tw[kw])!==null&&a0!==void 0?a0:Tw[kw]=new fc;function Pi(r){for(var e=[],t=1;t<arguments.length;t++)e[t-1]=arguments[t];return Fw.withValue.apply(Fw,ta([Array.isArray(r)?r:[r]],e,!1))}function s0(r){return new an(function(e){e.error(r)})}var dk=function(r,e,t){var n=new Error(t);throw n.name="ServerError",n.response=r,n.statusCode=r.status,n.result=e,n};function uO(r){for(var e=["query","operationName","variables","extensions","context"],t=0,n=Object.keys(r);t<n.length;t++){var i=n[t];if(e.indexOf(i)<0)throw ji(58,i)}return r}function cO(r,e){var t=me({},r),n=function(a){typeof a=="function"?t=me(me({},t),a(t)):t=me(me({},t),a)},i=function(){return me({},t)};return Object.defineProperty(e,"setContext",{enumerable:!1,value:n}),Object.defineProperty(e,"getContext",{enumerable:!1,value:i}),e}function dO(r){var e={variables:r.variables||{},extensions:r.extensions||{},operationName:r.operationName,query:r.query};return e.operationName||(e.operationName=typeof e.query!="string"?Bp(e.query)||void 0:""),e}function fO(r,e){var t=me({},r),n=new Set(Object.keys(r));return Ia(e,{Variable:function(i,a,s){s&&s.kind!=="VariableDefinition"&&n.delete(i.name.value)}}),n.forEach(function(i){delete t[i]}),t}function Iw(r,e){return e?e(r):an.of()}function nd(r){return typeof r=="function"?new Ma(r):r}function Uh(r){return r.request.length<=1}var Ma=(function(){function r(e){e&&(this.request=e)}return r.empty=function(){return new r(function(){return an.of()})},r.from=function(e){return e.length===0?r.empty():e.map(nd).reduce(function(t,n){return t.concat(n)})},r.split=function(e,t,n){var i=nd(t),a=nd(n||new r(Iw)),s;return Uh(i)&&Uh(a)?s=new r(function(o){return e(o)?i.request(o)||an.of():a.request(o)||an.of()}):s=new r(function(o,l){return e(o)?i.request(o,l)||an.of():a.request(o,l)||an.of()}),Object.assign(s,{left:i,right:a})},r.execute=function(e,t){return e.request(cO(t.context,dO(uO(t))))||an.of()},r.concat=function(e,t){var n=nd(e);if(Uh(n))return n;var i=nd(t),a;return Uh(i)?a=new r(function(s){return n.request(s,function(o){return i.request(o)||an.of()})||an.of()}):a=new r(function(s,o){return n.request(s,function(l){return i.request(l,o)||an.of()})||an.of()}),Object.assign(a,{left:n,right:i})},r.prototype.split=function(e,t,n){return this.concat(r.split(e,t,n||new r(Iw)))},r.prototype.concat=function(e){return r.concat(this,e)},r.prototype.request=function(e,t){throw ji(48)},r.prototype.onError=function(e,t){if(t&&t.error)return t.error(e),!1;throw e},r.prototype.setOnError=function(e){return this.onError=e,this},r})(),hO=Ma.from,Ay=Ma.execute;function pO(r){var e,t=r[Symbol.asyncIterator]();return e={next:function(){return t.next()}},e[Symbol.asyncIterator]=function(){return this},e}function gO(r){var e=null,t=null,n=!1,i=[],a=[];function s(f){if(!t){if(a.length){var d=a.shift();if(Array.isArray(d)&&d[0])return d[0]({value:f,done:!1})}i.push(f)}}function o(f){t=f;var d=a.slice();d.forEach(function(h){h[1](f)}),!e||e()}function l(){n=!0;var f=a.slice();f.forEach(function(d){d[0]({value:void 0,done:!0})}),!e||e()}e=function(){e=null,r.removeListener("data",s),r.removeListener("error",o),r.removeListener("end",l),r.removeListener("finish",l),r.removeListener("close",l)},r.on("data",s),r.on("error",o),r.on("end",l),r.on("finish",l),r.on("close",l);function u(){return new Promise(function(f,d){if(t)return d(t);if(i.length)return f({value:i.shift(),done:!1});if(n)return f({value:void 0,done:!0});a.push([f,d])})}var c={next:function(){return u()}};return Tg&&(c[Symbol.asyncIterator]=function(){return this}),c}function mO(r){var e=!1,t={next:function(){return e?Promise.resolve({value:void 0,done:!0}):(e=!0,new Promise(function(n,i){r.then(function(a){n({value:a,done:!1})}).catch(i)}))}};return Tg&&(t[Symbol.asyncIterator]=function(){return this}),t}function Pw(r){var e={next:function(){return r.read()}};return Tg&&(e[Symbol.asyncIterator]=function(){return this}),e}function vO(r){return!!r.body}function yO(r){return!!r.getReader}function AO(r){return!!(Tg&&r[Symbol.asyncIterator])}function bO(r){return!!r.stream}function wO(r){return!!r.arrayBuffer}function CO(r){return!!r.pipe}function xO(r){var e=r;if(vO(r)&&(e=r.body),AO(e))return pO(e);if(yO(e))return Pw(e.getReader());if(bO(e))return Pw(e.stream().getReader());if(wO(e))return mO(e.arrayBuffer());if(CO(e))return gO(e);throw new Error("Unknown body type for responseIterator. Please pass a streamable response.")}var Rf=Symbol();function VA(r){return r.extensions?Array.isArray(r.extensions[Rf]):!1}function fk(r){return r.hasOwnProperty("graphQLErrors")}var SO=function(r){var e=ta(ta(ta([],r.graphQLErrors,!0),r.clientErrors,!0),r.protocolErrors,!0);return r.networkError&&e.push(r.networkError),e.map(function(t){return ci(t)&&t.message||"Error message not found."}).join(`
57
57
  `)},io=(function(r){pa(e,r);function e(t){var n=t.graphQLErrors,i=t.protocolErrors,a=t.clientErrors,s=t.networkError,o=t.errorMessage,l=t.extraInfo,u=r.call(this,o)||this;return u.name="ApolloError",u.graphQLErrors=n||[],u.protocolErrors=i||[],u.clientErrors=a||[],u.networkError=s||null,u.message=o||SO(u),u.extraInfo=l,u.cause=ta(ta(ta([s],n||[],!0),i||[],!0),a||[],!0).find(function(c){return!!c})||null,u.__proto__=e.prototype,u}return e})(Error),Dw=Object.prototype.hasOwnProperty;function EO(r,e){return es(this,void 0,void 0,function(){var t,n,i,a,s,o,l,u,c,f,d,h,g,v,y,A,C,S,F,E,R,B,j,G;return ts(this,function(ie){switch(ie.label){case 0:if(TextDecoder===void 0)throw new Error("TextDecoder must be defined in the environment: please import a polyfill.");t=new TextDecoder("utf-8"),n=(G=r.headers)===null||G===void 0?void 0:G.get("content-type"),i="boundary=",a=n?.includes(i)?n?.substring(n?.indexOf(i)+i.length).replace(/['"]/g,"").replace(/\;(.*)/gm,"").trim():"-",s=`\r
58
58
  --`.concat(a),o="",l=xO(r),u=!0,ie.label=1;case 1:return u?[4,l.next()]:[3,3];case 2:for(c=ie.sent(),f=c.value,d=c.done,h=typeof f=="string"?f:t.decode(f),g=o.length-s.length+1,u=!d,o+=h,v=o.indexOf(s,g);v>-1;){if(y=void 0,B=[o.slice(0,v),o.slice(v+s.length)],y=B[0],o=B[1],A=y.indexOf(`\r
@@ -1896,7 +1896,7 @@ Minimum version required to store current data is: `+q+`.
1896
1896
  />
1897
1897
  </svg>
1898
1898
  `,d={browserValue:s.color||"#000000"},h={"spiff-fill-shape":d},g=Ar();return console.log(`[handleShapeStep] Creating shape element ${g}.`,{panelId:u.panelId,fill:d.browserValue}),new ai({colors:h,id:g,svg:f,type:er.Illustration,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable},c)},l=n.data.regions;try{const u=l.map(o);return console.log(`[handleShapeStep] Done with ${u.length} command(s).`),u}catch(u){return console.error(`[handleShapeStep] Failed for step "${t.name}".`,u),[]}},_U=async(r,e,t)=>{console.log(`[handleSilentStep] Start for step "${e.stepName}".`,{stepType:e.type,layoutCount:r.length,regionCount:e.data.regions.length,productOverlayImageUrl:t});const n=[],a=e.type===Xe.ProductOverlay?t||e.data.asset?.fileLink||"":e.data.asset?.fileLink||"",o=a.endsWith(".jpeg")||a.endsWith(".jpg")||a.endsWith(".png")?er.Image:(a.endsWith(".svg"),er.Illustration),l=e.data.regions;if(console.log("[handleSilentStep] Resolved asset.",{assetSource:a,assetType:o}),o==="image")try{l.forEach(u=>{const c=r.find(h=>h.panelId===u.panelId);if(!c)throw console.error(`[handleSilentStep] No layout for panel ${u.panelId}.`),new Ai(u);const f=Ar();console.log(`[handleSilentStep] Creating image element ${f}.`,{panelId:u.panelId,excludeFromExport:e.data.excludeFromPrint});const d={id:f,src:a,type:o,y:u.top,x:u.left,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,productOverlay:e.type===Xe.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:u.rotation,excludeFromExport:e.data.excludeFromPrint,preserveAspectRatio:"none"};n.push(new ai(d,c))})}catch(u){console.error(`[handleSilentStep] Failed for step "${e.stepName}".`,u)}else{console.log("[handleSilentStep] Fetching SVG asset.",{assetSource:a});const u=await ra(a,!0),c=f=>{const d=/<svg.*?<\/svg>/s,h=f.match(d)||[],g=h?.length>0?h[0]:"",A=us().parseFromString(g,"image/svg+xml").firstElementChild;if(!A)throw console.error("[handleSilentStep] Failed to read SVG.",{assetSource:a,bodyLength:f.length}),new Al("Failed to read SVG.");return Vg(A),Do().serializeToString(A)};l.forEach(f=>{const d=r.find(v=>v.panelId===f.panelId);if(!d)throw console.error(`[handleSilentStep] No layout for panel ${f.panelId}.`),new Ai(f);const h=Ar();console.log(`[handleSilentStep] Creating illustration element ${h}.`,{panelId:f.panelId,excludeFromExport:e.data.excludeFromPrint});const g={id:h,src:a,asset_key:a,svg:c(u),colors:{},type:o,y:f.top,x:f.left,width:f.width,height:f.height,layer:f.layer,layerIndex:f.layerIndex,scaleX:1,scaleY:1,rotation:f.rotation,productOverlay:e.type===Xe.ProductOverlay?!0:void 0,excludeFromExport:e.data.excludeFromPrint};n.push(new ai(g,d))})}return console.log(`[handleSilentStep] Done with ${n.length} command(s).`),n},NU=async(r,e,t,n)=>{console.log(`[handleTextStep] Start for step "${t.name}".`,{stepName:n.stepName,layoutCount:r.length,regionCount:n.data.regions.length});const i=[],a=t.data,s=30,o=C=>C.vertical?"center":C.textAlign||"center",l=async()=>{const C=await ct.getOptionForStep(n);if(!C){console.warn(`[handleTextStep] No font option for step ${n.stepName}.`);return}const S=C.variants?.find(E=>E.id===a.fontVariantId)||await ct.getDefaultVariant(C,n.overrideDefaultVariantId);if(!S){console.warn(`[handleTextStep] No font variant with ID: ${a.fontVariantId}`);return}if(!S.asset){console.warn(`[handleTextStep] No asset for font variant with ID: ${S.id}`);return}console.log("[handleTextStep] Resolved font variant.",{optionId:C.id,variantId:S.id}),e[n.stepName]={selectedVariants:[S]};const F=S.asset.fileLink;if(!F){console.warn(`[handleTextStep] No asset link for font variant with ID: ${S.id}`);return}return F},c=await(async()=>{const C=await l();if(!C){console.warn("[handleTextStep] No font URL; falling back to default sizing.");return}console.log("[handleTextStep] Loading font.",{fontUrl:C});const S=await Rl(C),F={assetUrl:C,name:S.names.fullName.en};return console.log("[handleTextStep] Font loaded.",{name:F.name}),F})(),f=(n.data.replaceableText?n.data.replaceableText.replace("{{}}",a.text):a.text)||"",d=hg(f,{vertical:n.data.vertical,uppercase:n.data.uppercase});console.log("[handleTextStep] Text resolved.",{inputText:a.text,replaceableText:n.data.replaceableText,text:d,vertical:n.data.vertical,uppercase:n.data.uppercase});const h=async C=>{const S=C.colorOption;return S?(await ct.getDefaultVariant(S))?.color:void 0},g=a.color||await h(n.data);console.log("[handleTextStep] Colour resolved.",{inputColor:a.color,defaultColor:g});const y=await(async C=>{const S=C.strokeOption;if(!C.strokeEnabled||!S)return;const F=await ct.getDefaultVariant(S,n.overrideDefaultVariantId);if(!F?.color){console.warn(`[handleTextStep] No default stroke variant colour for step ${n.stepName}.`);return}return{browserValue:F.color,pmsValue:F.name}})(n.data);console.log("[handleTextStep] Stroke resolved.",{strokeEnabled:n.data.strokeEnabled,strokeColor:y,strokeThickness:n.data.strokeThickness});const A=n.data.regions;for(const C of A){const S=r.find(E=>E.panelId===C.panelId);if(!S){console.warn(`[handleTextStep] No layout for panel ${C.panelId}; skipping region.`);continue}const F={stepName:t.name,id:Ar(),align:o(n.data),curved:n.data.curved,fill:a.color||g||"#000000",fontData:c,fontSize:n.data.size||s,height:C.height,layer:C.layer,layerIndex:C.layerIndex,paths:n.data.paths,rotation:C.rotation,strokeColor:y,strokeThickness:y?n.data.strokeThickness:void 0,text:d,type:er.Textbox,vertical:n.data.vertical,verticalAlign:n.data.verticalAlign||"middle",width:C.width,x:C.left,y:C.top};if(c){const[E,R]=Kd(n.data.size||s,c,C,[hg(d,{vertical:n.data.vertical,uppercase:n.data.uppercase})],{size:n.data.size,minSize:n.data.minSize,maxSize:n.data.maxSize});console.log(`[handleTextStep] Creating autosized textbox element ${F.id}.`,{panelId:C.panelId,requestedFontSize:n.data.size||s,correctFontSize:E,lineCount:(R||[]).length}),i.push(new ai({...F,fontSize:E,text:F.curved?F.text:(R||[]).join(`
1899
- `)},S))}else console.log(`[handleTextStep] Creating textbox element ${F.id} without font data.`,{panelId:C.panelId,fontSize:F.fontSize}),i.push(new ai(F,S))}return console.log(`[handleTextStep] Done with ${i.length} command(s).`),i},lI=async(r,e,t,n)=>{console.log("[generateCommands] Start.",{workflowId:e.id,designInputStepCount:r.length,designInputStepNames:r.map(s=>s.name),workflowStepCount:e.steps.length,layoutCount:t.length,layoutPanelIds:t.map(s=>s.panelId),productOverlayImageUrl:n});const i=[],a={};for(const s of r){const o=e.steps.find(u=>u.stepName===s.name);if(!o){console.warn(`[generateCommands] No workflow step matching design input step "${s.name}"; skipping.`);continue}const l=i.length;switch(console.log(`[generateCommands] Handling step "${s.name}" of type ${o.type}.`),o.type){case Xe.DigitalContent:i.push(...await PU(t,s,o));break;case Xe.Frame:case Xe.Photo:i.push(...await DU(t,a,s,o));break;case Xe.Illustration:i.push(...await RU(t,a,s,o));break;case Xe.Module:i.push(...await OU(t,s,o));break;case Xe.Picture:i.push(...await BU(t,a,s,o));break;case Xe.Shape:i.push(...await MU(t,a,s,o));break;case Xe.Text:i.push(...await NU(t,a,s,o));break;default:console.warn(`[generateCommands] Unhandled step type ${o.type} for step "${s.name}"; no commands generated.`);break}console.log(`[generateCommands] Step "${s.name}" produced ${i.length-l} command(s). Running total: ${i.length}.`)}console.log("[generateCommands] Renderable steps done.",{commandCount:i.length,stepSelections:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.selectedVariants?.map(l=>l.id)]))});for(const s of e.steps){if(s.type!==Xe.SilentIllustration&&s.type!==Xe.ProductOverlay)continue;if(!await co(s,a)){console.log(`[generateCommands] Silent step "${s.stepName}" conditions not satisfied; skipping.`);continue}const o=i.length;console.log(`[generateCommands] Handling silent step "${s.stepName}" of type ${s.type}.`),i.push(...await _U(t,s,n)),console.log(`[generateCommands] Silent step "${s.stepName}" produced ${i.length-o} command(s). Running total: ${i.length}.`)}return console.log(`[generateCommands] Done with ${i.length} command(s).`),i};class LU{constructor(e){this.handleCompleteRender=null;const t=new Map;e.forEach(n=>t.set(n.id,new VU(n.id,n.name,this,{width:n.width,height:n.height},this.getWorkflowManager.bind(this)))),this.layouts=t}setCompleteRenderCallback(e){this.handleCompleteRender=e,e(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(e){this.workflowManager=e}getWorkflowManager(){return this.workflowManager}}const UU=()=>new Promise((r,e)=>{try{const n=Eo().getContext("webgl2");r(!!n)}catch{r(!1)}}),uI=UU();class VU{constructor(e,t,n,i,a){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Gg(2),this.id=e,this.name=t,this.service=n,this.panelSize=i,this.getWorkflowManager=a}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(e){this.textureCtx=e,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(e){this.staticCtxDirty=e}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(e){this.interactiveDirty=e}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(e){const t=mo(e);this.lastRequestedRenderArguments=t;const n=this.getStaticContext();if(!n){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new zU(this.getID(),n,await uI,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},t,this.getWorkflowManager))}}class zU extends jg{constructor(e,t,n,i,a,s){super(),this.layoutId=e,this.ctx=t,this.nonPOTSupport=n,this.onRender=i,this.layouts=a,this.getWorkflowManager=s}async execute(){const e=this.layouts.find(f=>f.layoutState.layout.id===this.layoutId);if(!e)return;const t=e.layoutState.elements||[],n=e.layoutState.layout.width,i=e.layoutState.layout.height,{width:a,height:s}=cI(n,i,this.nonPOTSupport),o=this.getWorkflowManager?.()?.getTemplatingContext(),l=Qg(e.layoutState.layout,t,{renderingConfiguration:{purpose:Ku.ThreeD,templatingContext:o}}),u=qk(l),c=await uo.from(this.ctx,u,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:Eo,createImage:Mf,DOMParser:QA(),fetch});c.resize(a,s),await c.render(),this.onRender()}}function cI(r,e,t){const n=r===1||e===1?{width:1,height:1}:$U(),i=n.width,a=n.height;let s,o;if(t){const l=i/a;r/e<l?(s=i,o=e*(i/r)):(s=r*(a/e),o=a);const c=HU({width:s,height:o});s=c.width,o=c.height}else s=n.width,o=n.height;return{width:s,height:o}}function $U(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}function HU(r,e=4096){const t=e/r.width,n=e/r.height,i=Math.min(t,n);return i>1?r:{width:r.width*i,height:r.height*i}}const jU=(r,e)=>{const t=[];return r.forEach(n=>{const i=e.steps.find(a=>a.stepName===n.stepName);i?.type===Xe.Text&&n.stepAspectType==="Text"&&t.push({name:i.stepName,data:{text:n.value}})}),t},GU=async(r,e,t,n)=>{let i={serializableWorkflow:{steps:[]},layouts:{}};i=new On(t.map(l=>new E1(l))).apply(i);const s=await lI(r,e,t,n);return new On(s).apply(i)},Yg=Se`
1899
+ `)},S))}else console.log(`[handleTextStep] Creating textbox element ${F.id} without font data.`,{panelId:C.panelId,fontSize:F.fontSize}),i.push(new ai(F,S))}return console.log(`[handleTextStep] Done with ${i.length} command(s).`),i},lI=async(r,e,t,n)=>{console.log("[generateCommands] Start.",{workflowId:e.id,designInputStepCount:r.length,designInputStepNames:r.map(s=>s.name),workflowStepCount:e.steps.length,layoutCount:t.length,layoutPanelIds:t.map(s=>s.panelId),productOverlayImageUrl:n});const i=[],a={};for(const s of r){const o=e.steps.find(u=>u.stepName===s.name);if(!o){console.warn(`[generateCommands] No workflow step matching design input step "${s.name}"; skipping.`);continue}const l=i.length;switch(console.log(`[generateCommands] Handling step "${s.name}" of type ${o.type}.`),o.type){case Xe.DigitalContent:i.push(...await PU(t,s,o));break;case Xe.Frame:case Xe.Photo:i.push(...await DU(t,a,s,o));break;case Xe.Illustration:i.push(...await RU(t,a,s,o));break;case Xe.Module:i.push(...await OU(t,s,o));break;case Xe.Picture:i.push(...await BU(t,a,s,o));break;case Xe.Shape:i.push(...await MU(t,a,s,o));break;case Xe.Text:i.push(...await NU(t,a,s,o));break;default:console.warn(`[generateCommands] Unhandled step type ${o.type} for step "${s.name}"; no commands generated.`);break}console.log(`[generateCommands] Step "${s.name}" produced ${i.length-l} command(s). Running total: ${i.length}.`)}console.log("[generateCommands] Renderable steps done.",{commandCount:i.length,stepSelections:Object.fromEntries(Object.entries(a).map(([s,o])=>[s,o.selectedVariants?.map(l=>l.id)]))});for(const s of e.steps){if(s.type!==Xe.SilentIllustration&&s.type!==Xe.ProductOverlay)continue;if(!await co(s,a)){console.log(`[generateCommands] Silent step "${s.stepName}" conditions not satisfied; skipping.`);continue}const o=i.length;console.log(`[generateCommands] Handling silent step "${s.stepName}" of type ${s.type}.`),i.push(...await _U(t,s,n)),console.log(`[generateCommands] Silent step "${s.stepName}" produced ${i.length-o} command(s). Running total: ${i.length}.`)}return console.log(`[generateCommands] Done with ${i.length} command(s).`),i};class LU{constructor(e){this.handleCompleteRender=null;const t=new Map;e.forEach(n=>t.set(n.id,new VU(n.id,n.name,this,{width:n.width,height:n.height},this.getWorkflowManager.bind(this)))),this.layouts=t}setCompleteRenderCallback(e){this.handleCompleteRender=e,e(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(e){this.workflowManager=e}getWorkflowManager(){return this.workflowManager}}const UU=()=>new Promise((r,e)=>{try{const n=Eo().getContext("webgl2");r(!!n)}catch{r(!1)}}),uI=UU();class VU{constructor(e,t,n,i,a){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Gg(2),this.id=e,this.name=t,this.service=n,this.panelSize=i,this.getWorkflowManager=a}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(e){this.textureCtx=e,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(e){this.staticCtxDirty=e}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(e){this.interactiveDirty=e}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(e){const t=mo(e);this.lastRequestedRenderArguments=t;const n=this.getStaticContext();if(!n){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new zU(this.getID(),n,await uI,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},t,this.getWorkflowManager))}}class zU extends jg{constructor(e,t,n,i,a,s){super(),this.layoutId=e,this.ctx=t,this.nonPOTSupport=n,this.onRender=i,this.layouts=a,this.getWorkflowManager=s}async execute(){const e=this.layouts.find(f=>f.layoutState.layout.id===this.layoutId);if(!e)return;const t=e.layoutState.elements||[],n=e.layoutState.layout.width,i=e.layoutState.layout.height,{width:a,height:s}=cI(n,i,this.nonPOTSupport),o=this.getWorkflowManager?.()?.getTemplatingContext(),l=Qg(e.layoutState.layout,t,{renderingConfiguration:{purpose:Ku.ThreeD,templatingContext:o}}),u=qk(l),c=await uo.from(this.ctx,u,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:Eo,createImage:Mf,DOMParser:QA(),fetch});c.resize(a,s),await c.render(),this.onRender()}}function cI(r,e,t){const n=r===1||e===1?{width:1,height:1}:$U(),i=n.width,a=n.height;let s,o;if(t){const l=i/a;r/e<l?(s=i,o=e*(i/r)):(s=r*(a/e),o=a);const c=GU({width:s,height:o});s=c.width,o=c.height}else s=n.width,o=n.height;return{width:s,height:o}}function $U(){return HU()||!jU()?{width:1024,height:1024}:{width:2048,height:2048}}function HU(){return window.innerWidth<=480}function jU(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}function GU(r,e=4096){const t=e/r.width,n=e/r.height,i=Math.min(t,n);return i>1?r:{width:r.width*i,height:r.height*i}}const qU=(r,e)=>{const t=[];return r.forEach(n=>{const i=e.steps.find(a=>a.stepName===n.stepName);i?.type===Xe.Text&&n.stepAspectType==="Text"&&t.push({name:i.stepName,data:{text:n.value}})}),t},WU=async(r,e,t,n)=>{let i={serializableWorkflow:{steps:[]},layouts:{}};i=new On(t.map(l=>new E1(l))).apply(i);const s=await lI(r,e,t,n);return new On(s).apply(i)},Yg=Se`
1900
1900
  fragment GlobalPropertyStateAspectFields on GlobalPropertyStateAspect {
1901
1901
  name
1902
1902
  value
@@ -1919,7 +1919,7 @@ Minimum version required to store current data is: `+q+`.
1919
1919
  }
1920
1920
  }
1921
1921
  }
1922
- `,qU=Se`
1922
+ `,QU=Se`
1923
1923
  ${Yg}
1924
1924
  mutation CreateGlobalPropertyState($bundleId: String!) {
1925
1925
  globalPropertyStateCreate(bundleId: $bundleId) {
@@ -1929,7 +1929,7 @@ Minimum version required to store current data is: `+q+`.
1929
1929
  }
1930
1930
  }
1931
1931
  }
1932
- `,WU=Se`
1932
+ `,YU=Se`
1933
1933
  ${Yg}
1934
1934
  mutation UpdateGlobalPropertyState($id: String!, $aspects: [GlobalPropertyStateAspectInput]!) {
1935
1935
  globalPropertyStateUpdate(id: $id, aspects: $aspects) {
@@ -1939,7 +1939,7 @@ Minimum version required to store current data is: `+q+`.
1939
1939
  }
1940
1940
  }
1941
1941
  }
1942
- `,QU=Se`
1942
+ `,XU=Se`
1943
1943
  ${Yg}
1944
1944
  query GetGlobalPropertyState($bundleId: String!) {
1945
1945
  globalPropertyState(bundleId: $bundleId) {
@@ -1949,7 +1949,7 @@ Minimum version required to store current data is: `+q+`.
1949
1949
  }
1950
1950
  }
1951
1951
  }
1952
- `,YU=async r=>(await ze.getShadowGraphqlClient().query({query:QU,fetchPolicy:"cache-first",errorPolicy:"all",variables:{bundleId:r}})).data.globalPropertyState,XU=Se`
1952
+ `,JU=async r=>(await ze.getShadowGraphqlClient().query({query:XU,fetchPolicy:"cache-first",errorPolicy:"all",variables:{bundleId:r}})).data.globalPropertyState,KU=Se`
1953
1953
  fragment WorkflowProductFields on WorkflowProduct {
1954
1954
  id
1955
1955
  index
@@ -1958,8 +1958,8 @@ Minimum version required to store current data is: `+q+`.
1958
1958
  workflowName
1959
1959
  imageUrl
1960
1960
  }
1961
- `,JU=r=>Se`
1962
- ${XU}
1961
+ `,ZU=r=>Se`
1962
+ ${KU}
1963
1963
  ${Nf}
1964
1964
  fragment ProductFields on Product {
1965
1965
  id
@@ -2010,7 +2010,7 @@ Minimum version required to store current data is: `+q+`.
2010
2010
  }
2011
2011
  }
2012
2012
  `,O1=r=>Se`
2013
- ${JU(r)}
2013
+ ${ZU(r)}
2014
2014
  fragment ProductCollectionProductFields on ProductCollectionProduct {
2015
2015
  id
2016
2016
  productId
@@ -2110,7 +2110,7 @@ Minimum version required to store current data is: `+q+`.
2110
2110
  workflowViewerLink
2111
2111
  workflowViewerAmendLink
2112
2112
  }
2113
- `,KU=r=>Se`
2113
+ `,e9=r=>Se`
2114
2114
  ${Yg}
2115
2115
  ${Xg(r)}
2116
2116
  ${fI}
@@ -2194,7 +2194,7 @@ Minimum version required to store current data is: `+q+`.
2194
2194
  }
2195
2195
  }
2196
2196
  }
2197
- `,ZU=Se`
2197
+ `,t9=Se`
2198
2198
  query GetBundlesForCustomer($id: String!) {
2199
2199
  customers(ids: [$id]) {
2200
2200
  bundleStakeholders {
@@ -2233,7 +2233,7 @@ Minimum version required to store current data is: `+q+`.
2233
2233
  }
2234
2234
  }
2235
2235
  }
2236
- `,e9=Se`
2236
+ `,r9=Se`
2237
2237
  query GetProductCollectionForFilteredProducts(
2238
2238
  $id: String!
2239
2239
  $productFilters: ProductCollectionProductFilterInput
@@ -2262,7 +2262,7 @@ Minimum version required to store current data is: `+q+`.
2262
2262
  }
2263
2263
  }
2264
2264
  }
2265
- `,t9=Se`
2265
+ `,n9=Se`
2266
2266
  ${O1(!0)}
2267
2267
  query GetProductCollectionForProductsFeed(
2268
2268
  $id: String!
@@ -2294,7 +2294,7 @@ Minimum version required to store current data is: `+q+`.
2294
2294
  }
2295
2295
  }
2296
2296
  }
2297
- `,r9=r=>Se`
2297
+ `,i9=r=>Se`
2298
2298
  ${Xg(r)}
2299
2299
  ${fI}
2300
2300
  mutation CreateBundle(
@@ -2332,7 +2332,7 @@ Minimum version required to store current data is: `+q+`.
2332
2332
  }
2333
2333
  }
2334
2334
  }
2335
- `,n9=()=>Se`
2335
+ `,a9=()=>Se`
2336
2336
  mutation DuplicateBundle(
2337
2337
  $id: String!
2338
2338
  $template: Boolean
@@ -2377,19 +2377,19 @@ Minimum version required to store current data is: `+q+`.
2377
2377
  id
2378
2378
  }
2379
2379
  }
2380
- `,i9=Se`
2380
+ `,s9=Se`
2381
2381
  mutation BundleAddTransaction($id: String!, $transactionId: String!) {
2382
2382
  bundleAddTransaction(id: $id, transactionId: $transactionId) {
2383
2383
  id
2384
2384
  }
2385
2385
  }
2386
- `,a9=Se`
2386
+ `,o9=Se`
2387
2387
  mutation BundleAddTransactions($id: String!, $transactionIds: [String!]!, $transactionOwnerIds: [String!]) {
2388
2388
  bundleAddTransactions(id: $id, transactionIds: $transactionIds, transactionOwnerIds: $transactionOwnerIds) {
2389
2389
  id
2390
2390
  }
2391
2391
  }
2392
- `,s9=Se`
2392
+ `,l9=Se`
2393
2393
  mutation BundleRemoveTransaction(
2394
2394
  $id: String!
2395
2395
  $transactionId: String!
@@ -2404,7 +2404,7 @@ Minimum version required to store current data is: `+q+`.
2404
2404
  id
2405
2405
  }
2406
2406
  }
2407
- `,o9=Se`
2407
+ `,u9=Se`
2408
2408
  mutation BundleRemoveTransactions(
2409
2409
  $id: String!
2410
2410
  $transactionIds: [String!]!
@@ -2419,7 +2419,7 @@ Minimum version required to store current data is: `+q+`.
2419
2419
  id
2420
2420
  }
2421
2421
  }
2422
- `,l9=Se`
2422
+ `,c9=Se`
2423
2423
  mutation BundleAddStakeholder($id: String!, $details: CustomerDetailsInput!, $type: String!) {
2424
2424
  bundleAddStakeholder(id: $id, details: $details, type: $type) {
2425
2425
  id
@@ -2439,13 +2439,13 @@ Minimum version required to store current data is: `+q+`.
2439
2439
  }
2440
2440
  }
2441
2441
  }
2442
- `,u9=Se`
2442
+ `,d9=Se`
2443
2443
  mutation BundleAddStakeholder($id: String!, $emailAddress: String!) {
2444
2444
  bundleRemoveStakeholder(id: $id, emailAddress: $emailAddress) {
2445
2445
  id
2446
2446
  }
2447
2447
  }
2448
- `,c9=Se`
2448
+ `,f9=Se`
2449
2449
  mutation BundleUpdateStakeholders($id: String!, $input: [BundleStakeholderInput!]!) {
2450
2450
  bundleUpdateStakeholders(id: $id, input: $input) {
2451
2451
  id
@@ -2465,13 +2465,13 @@ Minimum version required to store current data is: `+q+`.
2465
2465
  }
2466
2466
  }
2467
2467
  }
2468
- `,d9=Se`
2468
+ `,h9=Se`
2469
2469
  mutation BundleUpdateTransactionOrder($id: String!, $transactionIds: [String!]!) {
2470
2470
  bundleUpdateTransactionOrder(id: $id, transactionIds: $transactionIds) {
2471
2471
  id
2472
2472
  }
2473
2473
  }
2474
- `,f9=r=>Se`
2474
+ `,p9=r=>Se`
2475
2475
  ${Xg(r)}
2476
2476
  mutation BundleAssignProductCollection($id: String!, $productCollectionId: String!) {
2477
2477
  bundleAssignProductCollection(id: $id, collectionId: $productCollectionId) {
@@ -2481,13 +2481,13 @@ Minimum version required to store current data is: `+q+`.
2481
2481
  }
2482
2482
  }
2483
2483
  }
2484
- `,h9=Se`
2484
+ `,g9=Se`
2485
2485
  mutation AssignGlobalPropertyConfiguration($bundleId: String!, $globalPropertyConfigurationId: String!) {
2486
2486
  bundleUpdate(id: $bundleId, globalPropertyConfigurationId: $globalPropertyConfigurationId) {
2487
2487
  id
2488
2488
  }
2489
2489
  }
2490
- `,p9=r=>Se`
2490
+ `,m9=r=>Se`
2491
2491
  ${hI}
2492
2492
  query CustomerBundlesFeed($id: String!, $limit: Int!, $offset: Int!, $template: Boolean, $templateStatus: BundleTemplateStatus, $ordered: Boolean) {
2493
2493
  customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: $template, templateStatus: $templateStatus, ordered: $ordered) {
@@ -2519,27 +2519,27 @@ Minimum version required to store current data is: `+q+`.
2519
2519
  total
2520
2520
  }
2521
2521
  }
2522
- `,g9=Se`
2522
+ `,v9=Se`
2523
2523
  mutation FinalizeUpdateBundle($bundleId: String!) {
2524
2524
  bundleFinalizeUpdate(bundleId: $bundleId)
2525
2525
  }
2526
- `,m9=Se`
2526
+ `,y9=Se`
2527
2527
  mutation ApproveBundle($id: String!, $note: String, $stakeholderId: String) {
2528
2528
  bundleApprove(id: $id, note: $note, stakeholderId: $stakeholderId)
2529
2529
  }
2530
- `,v9=Se`
2530
+ `,A9=Se`
2531
2531
  mutation RejectBundle($id: String!, $note: String, $stakeholderId: String) {
2532
2532
  bundleReject(id: $id, note: $note, stakeholderId: $stakeholderId)
2533
2533
  }
2534
- `,y9=Se`
2534
+ `,b9=Se`
2535
2535
  mutation ApproveTransaction($id: String!, $note: String) {
2536
2536
  transactionApprove(id: $id, note: $note)
2537
2537
  }
2538
- `,A9=Se`
2538
+ `,w9=Se`
2539
2539
  mutation RejectTransaction($id: String!, $note: String) {
2540
2540
  transactionReject(id: $id, note: $note)
2541
2541
  }
2542
- `,b9=Se`
2542
+ `,C9=Se`
2543
2543
  mutation CreateRecipient(
2544
2544
  $firstName: String
2545
2545
  $lastName: String
@@ -2581,7 +2581,7 @@ Minimum version required to store current data is: `+q+`.
2581
2581
  id
2582
2582
  }
2583
2583
  }
2584
- `,w9=Se`
2584
+ `,x9=Se`
2585
2585
  mutation UpdateRecipient(
2586
2586
  $id: String!
2587
2587
  $firstName: String
@@ -2627,17 +2627,17 @@ Minimum version required to store current data is: `+q+`.
2627
2627
  id
2628
2628
  }
2629
2629
  }
2630
- `,C9=Se`
2630
+ `,S9=Se`
2631
2631
  mutation AtttachRecipient($id: String!, $recipientId: String!) {
2632
2632
  transactionAttachRecipient(id: $id, recipientId: $recipientId) {
2633
2633
  id
2634
2634
  }
2635
2635
  }
2636
- `,x9=Se`
2636
+ `,E9=Se`
2637
2637
  mutation DeleteBundle($id: String!) {
2638
2638
  bundleDelete(id: $id)
2639
2639
  }
2640
- `,S9=Se`
2640
+ `,k9=Se`
2641
2641
  query FindBundleForTransactions($ids: [String!]!) {
2642
2642
  transactions(ids: $ids) {
2643
2643
  id
@@ -2646,13 +2646,13 @@ Minimum version required to store current data is: `+q+`.
2646
2646
  }
2647
2647
  }
2648
2648
  }
2649
- `,E9=Se`
2649
+ `,T9=Se`
2650
2650
  mutation EmailBundleShareLink($bundleId: String!, $email: String!, $firstName: String, $lastName: String) {
2651
2651
  bundleEmailSharePageLink(bundleId: $bundleId, email: $email, firstName: $firstName, lastName: $lastName) {
2652
2652
  id
2653
2653
  }
2654
2654
  }
2655
- `,k9=(r,e)=>e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).sort().reduce((t,n)=>(t[n]=e[n],t),{}):e,T9=r=>{for(const e of Object.values(r.layouts).map(t=>t.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return pI(r,"__typename"),r},pI=(r,e)=>{if(!(typeof r!="object"||r===null))for(const t in r)t===e?delete r[t]:pI(r[t],e)};var Jf=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(Jf||{});const F9=1e3;class SE extends jg{constructor(e){super(),this.update=e}async execute(){await this.update(),await new Promise(e=>{window.setTimeout(()=>{e()},F9)})}}const I9=r=>r.sort((e,t)=>e.index-t.index).map(e=>({id:Ar(),panelId:e.name,name:e.name,title:e.title,index:e.index,createdAt:new Date,updatedAt:new Date,transparentBackground:e.transparentBackground,height:e.height,width:e.width,previewRegion:e.previewRegion,useEditableArea:e.useEditableArea,editableArea:e.editableArea})),P9=(r,e)=>{const t=r.workflowState,n=t?JSON.parse(t):void 0;return n?Object.values(n.layouts).map(i=>i.layout):I9(e.panels)},af=class af{constructor(e,t,n,i,a,s=!1,o,l=!1,u=!1,c=!1){this.workflowStatePromiseQueue=new Gg(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async d=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):d?this.layouts=P9(this.experience.getTransaction(),d):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new LU(this.layouts),this.renderableContextService.setWorkflowManager(this),d.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(d),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const d=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(d)},this.experience=e,this.client=t,this.updateTransaction=n,this.graphQlClient=i,this.reloadedState=a,this.readOnly=s,this.singleVariantsRenderable=u,this.commandContext=new GF,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=o,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,c&&(this.workflowStatePromiseQueue.enabled=!1);const f=this.experience.getWorkflow();f&&this.setWorkflow(f)}getTemplatingContext(){const e=this.experience.getTransaction().recipient,t={recipient:e};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(n=>{const i=n.uniqueIdentifier??n.title??"";n.type===Qd.FirstName?t[i]=e?.firstName:n.type===Qd.LastName?t[i]=e?.lastName:n.type===Qd.Custom&&(n.customFieldIndex===1?t[i]=e?.customField1:n.customFieldIndex===2?t[i]=e?.customField2:n.customFieldIndex===3?t[i]=e?.customField3:n.customFieldIndex===4?t[i]=e?.customField4:n.customFieldIndex===5&&(t[i]=e?.customField5),n.option&&(t[i]=n.option.variants?.find(a=>a.id===t[i])?.name))}),t}async updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,v,y,A,C){const S=this.experience.getTransaction();if(S.recipient?.id)this.experience.getTransaction().recipient={id:S.recipient.id,firstName:e??S.recipient.firstName,lastName:t??S.recipient.lastName,address:n??S.recipient.address,suburb:i??S.recipient.suburb,state:a??S.recipient.state,email:s??S.recipient.email,postalCode:o??S.recipient.postalCode,country:l??S.recipient.country,mobile:u??S.recipient.mobile,company:c??S.recipient.company,apartment:f??S.recipient.apartment,customField1:d??S.recipient.customField1,customField2:h??S.recipient.customField2,customField3:g??S.recipient.customField3,customField4:v??S.recipient.customField4,customField5:y??S.recipient.customField5,conversionConfigurationId:A||S.recipient.conversionConfigurationId},this.experience.callEvent(yg.RecipientChanged),await this.graphQlClient().mutate({mutation:w9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:S.recipient.id,firstName:e||S.recipient.firstName,lastName:t||S.recipient.lastName,address:n||S.recipient.address,suburb:i||S.recipient.suburb,state:a||S.recipient.state,email:s||S.recipient.email,postalCode:o||S.recipient.postalCode,country:l||S.recipient.country,mobile:u||S.recipient.mobile,company:c||S.recipient.company,apartment:f||S.recipient.apartment,customField1:d||S.recipient.customField1,customField2:h||S.recipient.customField2,customField3:g||S.recipient.customField3,customField4:v||S.recipient.customField4,customField5:y||S.recipient.customField5,conversionConfigurationId:A||S.recipient.conversionConfigurationId,prevalidated:C}});else{const F=await this.graphQlClient().mutate({mutation:b9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:e,lastName:t,address:n,suburb:i,state:a,email:s,postalCode:o,country:l,mobile:u,company:c,apartment:f,customField1:d,customField2:h,customField3:g,customField4:v,customField5:y,conversionConfigurationId:A}});S.recipient={id:F?.data?.recipientCreate?.id,firstName:e,lastName:t,address:n,suburb:i,state:a,email:s,postalCode:o,country:l,mobile:u,company:c,apartment:f,customField1:d,customField2:h,customField3:g,customField4:v,customField5:y,conversionConfigurationId:A},this.experience.callEvent(yg.RecipientChanged),await this.graphQlClient().mutate({mutation:C9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const e=this.experience.getTransaction().recipient;if(e?.conversionConfigurationId&&!this.recipientConversionConfiguration){const t=af.configurationPromiseMap.get(e.conversionConfigurationId);if(t)this.recipientConversionConfiguration=await t;else{const i=(async()=>(await this.graphQlClient().query({query:B3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e.conversionConfigurationId}})).data.conversionConfiguration)();af.configurationPromiseMap.set(e.conversionConfigurationId,i),this.recipientConversionConfiguration=await i}}}async initializeDefaultWorkflowState(e){const t=()=>{const c=e.finalizeStepConfig;if(!c)return;const f=c.lookAtAnimation,d=c.modelAnimation;f&&this.previewService?.executeCameraAnimation(f),d&&this.modelContainer?.executeAnimation(d)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(c=>{this.storage[c.stepName]=c.storage||{}});const n=await this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((c,f)=>(f.selectedVariants?.length&&(c[f.stepName]={selectedVariants:f.selectedVariants.map(d=>({id:d.id}))}),c),{})),i=ct.getOptions(Array.from(n)),a=this.fetchConversionConfiguration();await Promise.all([i,a]),this.allScenes=XC(e);const o=(await Ja(this.allScenes,this.stepSelections)).map(c=>c.silentSteps).flat(),{stepElements:l,commands:u}=await this.stepElementsForIntroducedSilentSteps(o,!!this.reloadedState);this.commandContext.apply(new On(u),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&t()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(e){this.workflowStatePromiseQueue.enabled=e}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}async getInitialOptionIds(e){const t=new Set,n=this.experience.getWorkflow();if(!n)return t;const i=XC(n),a={...e};let s=-1;for(;;){const u=(await Ja(i,a)).flatMap(c=>c.renderableSteps);if(u.length===s)break;s=u.length;for(const c of u){if(a[c.stepName])continue;const f=c.option?.defaultVariant?.id;f&&(a[c.stepName]={selectedVariants:[{id:f}]})}}return(await Ja(i,a)).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&t.add(l.option.id)}),t}addConfirmCallback(e){e(this.confirmedDesign),this.confirmCallbacks.push(e)}addEditedCallback(e){e(this.editedSteps),this.editedCallbacks.push(e)}addElementsCallback(e){e(this.stepElements),this.elementsCallbacks.push(e)}addInformationResultCallback(e){e(this.informationResults),this.informationResultCallbacks.push(e)}addInitCallback(e){e(this.stepInitialised),this.initCallbacks.push(e)}addMandatoryCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}addMetadataCallback(e){e(this.stepMetadata),this.metadataCallbacks.push(e)}async addSelectionCallback(e){e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(e)}addStepSpecificStorageCallback(e,t){Object.keys(this.storage).includes(t)||(this.storage[t]={}),e(this.storage[t]),Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].push(e)}addStorageCallback(e){e(this.storage),this.storageCallbacks.push(e)}addMakingAdjustmentsCallback(e){e(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(e)}addPoller(e){this.pollers.push(e)}addValidationCallback(e){this.validationCallbacks.push(e),e(this.validationErrors)}addRecipientCallback(e){this.recipientCallbacks.push(e),e(this.experience.getTransaction().recipient)}removeRecipientCallback(e){this.recipientCallbacks=this.recipientCallbacks.filter(t=>t!==e)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(e=>e.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(e){return this.stepElements[e]||[]}getStepSpecificServices(e){return this.stepSpecificServices[e]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(e){this.ownerCustomer=e}setTransactionCustomerDetails(e){this.ownerCustomer={...this.ownerCustomer,emailAddress:e.email}}getModelContainer(){return this.modelContainer}setModelContainer(e){(!e||this.previewService&&this.previewService.getAllModels().includes(e))&&(this.modelContainer=e,e&&e.metadata&&e.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return e=>this.commandContext.apply(e,!this.initialized)}getWorkflowSelections(){const e={};return this.experience.getWorkflow()?.steps.forEach(t=>{const n=this.stepSelections[t.stepName];n&&n.selectedVariants&&n.selectedVariants.length>0&&(e[t.stepName]={selections:n.selectedVariants})}),e}getStepSelections(){return this.stepSelections}markStepsAsInitialised(e){const t={...this.stepInitialised};e.forEach(n=>{t[n]=!0}),this.stepInitialised=t,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(e){this.pendingUpdates=this.pendingUpdates.filter(t=>t!==e)}markUpdatePending(){const e=Ar();return this.pendingUpdates=[...this.pendingUpdates,e],e}setEditedStatus(e,t){this.editedSteps={...this.editedSteps,[e]:t},this.onEditedChange()}setInformationResults(e){this.informationResults=[...e],this.onInformationResultChange()}setCurrentAdjustingStepId(e){this.currentAdjustingStepId=e,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(e,t){this.mandatorySteps[e]!==t&&(this.mandatorySteps={...this.mandatorySteps,[e]:t},this.onMandatoryChange())}async getMandatoryUnfulfilledSteps(){return(await Ja(this.allScenes,this.stepSelections)).flatMap(a=>a.renderableSteps).filter(a=>a.mandatory).filter(a=>!this.mandatorySteps[a.stepName]).map(a=>a.stepName)}setStepError(e,t,n){let i=!1;if(!this.validationErrors.steps.has(e)&&n)i=!0,this.validationErrors.steps.set(e,new Map([[t,n]]));else if(this.validationErrors.steps.has(e)){const a=this.validationErrors.steps.get(e);n&&n!==a.get(t)?(i=!0,a.set(t,n)):n||(i=!0,a.delete(t),a.size===0&&this.validationErrors.steps.delete(e))}i&&this.onValidationChange()}getStepErrors(e){return this.validationErrors.steps.get(e)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}async injectIntoPreviewService(e,t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=e;const n=this.experience.getProduct();if(!n?.modelUrl||!this.previewService)return;const i=e.loadModel({model:n.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:t});this.setModelContainer(i),(await Ja(this.allScenes,this.stepSelections)).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===Xe.Model||o.type===Xe.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const l=this.stepSelections[o.stepName]?.selectedVariants||[];if(l.length===0)return;const u=l[0];if(o.type===Xe.Model){if(!this.modelContainer)throw new nn("We should always have a model container when injecting a preview!");const c=u.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${u.id} for step: ${o.stepName}`);return}const f=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},f.replaceProductModel||!1)}else{const c=u.material;if(!c){console.error(`Failed to read material from variant: ${u.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(d=>{if(!this.modelContainer)throw new nn("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(d,o.option.id,c)})}}),await i.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(e,t){const n={...this.storage,[e]:{...this.storage[e],...t}};if(!vf(n,this.storage)){this.storage=n;const i=new BS(this.constructSerializableWorkflow());this.commandContext.apply(i,!0),this.onStepSpecificStorageChange(e),this.onStorageChange()}}constructSerializableWorkflow(){const e=[];return this.allScenes.forEach(t=>{t.renderableSteps.forEach(n=>{const i={stepName:n.stepName};i.storage=this.storage[n.stepName],i.selectedVariants=this.stepSelections[n.stepName]?.selectedVariants?.map(a=>({id:a.id,priceModifier:a.priceModifier})),e.push(i)})}),{steps:e}}updateStateWithServer(){if(this.readOnly)return;const e=this.serialize();this.workflowStatePromiseQueue.enqueue(new SE(async()=>{await new Promise(t=>{setTimeout(()=>{t()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:e}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const e=this.serialize();return new SE(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:e}})}).execute()}serialize(){const e=this.getCommandContext().getState();if(!e)throw new nn("Attempted to serialize state before it was initialized.");const t=mo(e.transaction),n=T9(t);return JSON.stringify(n,k9,void 0)}async getStateHash(){const e=this.getCommandContext().getState(),n=Object.values(e?.transaction.layouts||{}).map(s=>s.modificationID??"").sort().join(""),a=new TextEncoder().encode(n);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const s=await window.crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(s)).map(u=>u.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(n,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(e,t){this.stepMetadata={...this.stepMetadata,[e]:{...this.stepMetadata[e],...t}},this.onMetadataChange()}removeElements(e){const t=(n,i)=>Object.keys(n).reduce((a,s)=>{const o=[...n[s]||[]];return i.forEach(l=>{const u=o.findIndex(c=>c.id===l.id);u>-1&&o.splice(u,1)}),a[s]=o,a},{});this.stepElements=t(this.stepElements,e)}async getInvalidCanvasRegions(){let e=[];for(const t of this.experience.getWorkflow()?.steps||[])if(!await co(t,this.stepSelections)&&this.stepElements[t.stepName])for(const n of this.stepElements[t.stepName])e.push(n);return e}async getInvalidModelVariants(){let e=[];for(const t of this.experience.getWorkflow()?.steps||[])t.type===Xe.Model&&!await co(t,this.stepSelections)&&e.push(t.stepName);return e}async stepElementsForIntroducedSilentSteps(e,t){const n=this.experience.getProduct();if(!n)return Promise.resolve({stepElements:{},commands:[]});const i=async(u,c,f)=>{if(u.type===Xe.SilentIllustration){const d=await new MS(u,c).trigger();return{step:u,results:d}}else if(u.type===Xe.ProductOverlay){const d=await new MS(u,c,f).trigger();return{step:u,results:d}}return Promise.reject("Unknown silent step. This is a bug")},a=e.filter(u=>!this.stepInitialised[u.stepName]),s={stepElements:{},commands:[]},o=[];for(const u of a)this.markStepsAsInitialised([u.stepName]),t||o.push(i(u,this.layouts,n));const l=await Promise.all(o);for(const u of l)s.stepElements[u.step.stepName]=u.results.map(c=>c.regionElement),s.commands=[...s.commands,...u.results.map(c=>c.command)];return s}getStepStorage(e){return this.storage[e]}getMetadata(e){return this.stepMetadata[e]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(e){return this.stepTags[e]||[]}getSerializedStep(e,t){return t.find(n=>n.stepName===e)}async updateTransactionShareActions(){const e=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=e}async updateTransactionStakeholders(){const e=await ze.getShadowGraphqlClient().query({query:V3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!e?.data?.transactions||e.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=e.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=e.data.transactions[0].currentStakeholder)}async approveTransaction(e){await ze.getShadowGraphqlClient().mutate({mutation:y9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:e}})}async rejectTransaction(e){await ze.getShadowGraphqlClient().mutate({mutation:A9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:e}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(e,t,n,i){const a=this.experience.getWorkflow();if(!a)throw new Error("Attempted to set selections when no workflow is set!");const s=this.stepSelections;this.stepSelections={...this.stepSelections,[e]:{selectedVariants:t}};for(const R of a.steps)await co(R,this.stepSelections)||(this.stepInitialised[R.stepName]=!1,delete this.stepMetadata[R.stepName],delete this.stepSelections[R.stepName],delete this.storage[R.stepName]);const o=this.allScenes,l=await Ja(o,s),u=await Ja(o,this.stepSelections),c=l.map(R=>R.silentSteps).flat(),d=u.map(R=>R.silentSteps).flat().filter(R=>!c.some(B=>B.stepName===R.stepName));for(const R of c)await co(R,this.stepSelections)||(this.stepInitialised[R.stepName]=!1);const h=await this.getInvalidCanvasRegions(),{stepElements:g,commands:v}=await this.stepElementsForIntroducedSilentSteps(d,!1);this.stepElements={...this.stepElements,...g,[e]:n},this.removeElements(h);const y=a.steps.find(R=>R.stepName===e);y?.type===Xe.Frame&&this.getWorkflowExperience().getStepById(y.stepName)?.frameService?.setTargetElements(n.map(B=>B.id));const A=h.map(R=>new Ol(R.id)),C=new BS(this.constructSerializableWorkflow()),S=[...v,...A,C];S.length>0&&this.commandContext.apply(new On(S),!0),await this.ensureStepsAreLoaded(),this.selectionCost=Object.values(this.stepSelections).reduce((R,B)=>R+B.selectedVariants.map(j=>j.priceModifier||0).reduce((j,G)=>j+G,0),0),this.onElementsChange();const F=await this.getInvalidModelVariants(),E=this.modelContainer;if(E){const R=F.map(B=>E.applyModelVariant(B,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(R)}await this.onSelectionChange(),await this.reapplyMaterialSteps(),y?.type!==Xe.Frame&&y?.type!==Xe.Text&&this.setMandatoryFulfilled(e,!0),i&&await i()}async ensureStepsAreLoaded(){const t=(await Ja(this.allScenes,this.stepSelections)).map(l=>l.renderableSteps),n=[],i=t.flat();for(const l of i)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case Xe.DigitalContent:n.push(T1.init(l,this,this.reloadedState));break;case Xe.Frame:n.push(so.init(l,this,this.reloadedState));break;case Xe.Illustration:n.push(Jd.init(l,this,this.reloadedState));break;case Xe.Material:n.push(F1.init(l,this,this.reloadedState));break;case Xe.Model:n.push(I1.init(l,this,this.reloadedState));break;case Xe.Module:this.stepSpecificServices[l.stepName]={module:await oI(l.data.module)},n.push(P1.init(l,this,this.reloadedState));break;case Xe.Picture:n.push(D1.init(l,this,this.reloadedState));break;case Xe.Question:n.push(R1.init(l,this,this.reloadedState));break;case Xe.Shape:n.push(Nu.init(l,this,this.reloadedState));break;case Xe.Text:n.push(ri.init(l,this,this.reloadedState));break}const a=(await Promise.allSettled(n)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),s=a.flatMap(l=>l?.command?[l.command]:[]),o=a.flatMap(l=>l?.followup?[l.followup]:[]);s&&s.length>0&&this.commandContext.apply(new On(s),!0);for(const l of o)await l();o.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(e=>e(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(e=>e(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(e=>e(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(e=>e(this.informationResults))}onInitChange(){this.initCallbacks.forEach(e=>e(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(e=>{e(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(e=>e(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(e=>{e(this.stepMetadata)})}async onSelectionChange(){const e=await this.traversableScenes();for(const t of this.selectionCallbacks)t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:e})}onStepSpecificStorageChange(e){Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].forEach(t=>t(this.storage[e]))}onStorageChange(){this.storageCallbacks.forEach(e=>e(this.storage))}onValidationChange(){this.validationCallbacks.forEach(e=>e(this.validationErrors))}traversableScenes(){return P_(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}async reapplyMaterialSteps(){if(!this.modelContainer)return;const t=(await Ja(this.allScenes,this.stepSelections)).flatMap(n=>n.renderableSteps).filter(n=>n.type===Xe.Material);for(const n of t){const i=this.stepSelections[n.stepName]?.selectedVariants;if(!i||i.length===0)continue;const s=i[0].material;if(!s||!n.option?.id)continue;n.data.targetMaterials.forEach(l=>{this.modelContainer?.applyMaterialVariant(l,n.option.id,s)})}}};af.configurationPromiseMap=new Map;let dA=af;class Fa{constructor(e){this.variantData=e}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(e,t){return this.variantData.priceModifier.toLocaleString(e||"en-US",{style:"currency",currency:"USD",...t})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.fileLink}getAssetResource(){return this.variantData.asset}getThumbnail(e=256,t){const n=this.variantData.thumbnail;if(!(!n||!n.fileLink))return $g(n,e,"webp",t)}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}getCategory(){return this.variantData.category}getProduct(){return this.variantData.product}}const sf=class sf{constructor(e,t,n){this.manager=e,this.step=t,this.tags=n}setUpdateState(e){sf.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,e)}getUpdateState(){return!!sf.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const n=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(n)return new Fa(n)}async getAvailableVariants(){return(await this.getAllVariants()).filter(t=>t.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(t=>new Fa(t))||[];const e=await ct.getOption(this.step.option?.id);if(!e)throw new Error("Option not found, cannot fetch variants.");return(e.variants||[]).map(t=>new Fa(t))||[]}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(e){return this.tags.includes(e)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(e){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[e.toString()]??!1}setOverrideGlobalPropertyConfiguration(e,t){const n=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...n,[e.toString()]:t}})}getGlobalPropertyAspects(e){return this.step.globalPropertyAspectConfigurations?.filter(t=>t.globalPropertyConfigurationId===e&&t.aspectName).map(t=>t.aspectName)??[]}executeAnimations(e){const t=this.manager.getPreviewService(),n=this.manager.getModelContainer(),i=this.step.data.modelAnimation,a=this.step.data.lookAtAnimation;t?a&&t.executeCameraAnimation(a):console.warn("No preview service available, cannot execute camera animations."),n?i&&n.executeAnimation(i,e):console.warn("No model container available, cannot execute model animations.")}};sf.updateState=new Map;let Ui=sf;class gI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){if(!this.getUpdateState()&&this.getCurrentVariant()!==e)return Jd.selectVariant(this.step,e.getResource(),this.manager.getRegionElements(this.step.stepName)||[],t=>this.setUpdateState(t),this.manager)}getColors(){const e=this.manager.getRegionElements(this.step.stepName)||[];if(e.length===0)return;const n=Un(e[0].id,this.manager.getAllLayoutData()).colors,a=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,s=a?.defaultColorVariants||[];if(s.length!==0){const o={};return s.forEach(l=>{const u=a.channelNumbers.find(c=>c.number===l.channelNumber);if(u){const c=u.id.replace(/\W/g,"");o[l.channelNumber]={browserValue:n[c]?.browserValue||""}}}),o}try{return n}catch(o){console.error(o)}}setColor(e,t,n){const i=new Map,s=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(s?.defaultColorVariants||[]).length!==0?s.channelNumbers.forEach(l=>{if(l.number.toString()===e){const u=l.id.replace(/\W/g,"");n?i.set(u,{browserValue:t,pmsValue:n}):i.set(u,t)}}):n?i.set(e,{browserValue:t,pmsValue:n}):i.set(e,t),Jd.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,i)}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?Jd.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class mI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return F1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class vI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return I1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class yI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return D1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class AI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){if(!e.getId())throw new Error("Unable to select variant with a null ID");await R1.selectVariant(this.step,e.getId(),this.manager)}async getDisplayType(){return this.step.data.displayType?this.step.data.displayType:(await ct.getOptionForStep(this.step))?.displayType}}class bI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){const t=e.getResource();return Nu.selectVariant(this.step,{fill:t.color,stroke:t.color,variant:t},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(e){return Nu.selectVariant(this.step,e,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Nu.availableColours(this.step)}setCustomColor(e){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Nu.setCustomColor(e,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const e=this.manager.getStepStorage(this.step.stepName)?.colour;if(!e)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return e}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class wI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){await ri.selectVariant(this.step,e.getResource(),this.manager,t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:t,messageType:Jf.Error,stepID:this.step.stepName}]);else{const n=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(n)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?ri.availableFillColors(this.step):[]}async setFillColor(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeFillColor(this.step,e,t,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return ri.availableFillImages(this.step)}async setFillImage(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeFillImage(this.step,e,t,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return ri.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(e){const t=this.manager.getRegionElements(this.step.stepName);ri.changeAlignment(this.step,e,t,this.manager)}setFullTextCustomization(e){const t=this.manager.getStepStorage(this.step.stepName)?.inputText||"",n=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",t):t,i=e?n:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:e,text:i,defaultCleared:!1}),this.setText(i)}setText(e){const t={input:e,helperData:{}},n=ri.findLayoutElements(this.manager,this.step),i=ri.filterUnsupportedCharacters(e,n[0]?.fontData),a=ju(i,this.manager).length,s=!!this.step.data&&!!this.step.data.maxLength&&a>this.step.data.maxLength;s||(t.input=i);const o=n.length<=0,l=o?{inputText:i,text:i}:{inputText:i};this.manager.updateStorage(this.step.stepName,l);const u=this.manager.getStepStorage(this.step.stepName),c=ri.getProcessedInput(i,this.step.data,u?.customiseAllText??!1);if(o)s||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:f,errorData:d,helperData:h}=ri.updateInputText(i,n,this.step,this.manager);f&&this.manager.getCommandDispatcher()(f),t.helperData=h,t.errorData=d,!s&&!d&&this.manager.updateMetadata(this.step.stepName,{text:c})}return t}getText(){const e=this.step.data.defaultText,t=this.manager.getStepStorage(this.step.stepName);return e&&t?.defaultCleared!==void 0&&!t?.defaultCleared?e:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const t=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const n=ri.findLayoutElements(this.manager,this.step);return ri.updateInputText("",n,this.step,this.manager),t}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const e=this.step.data.maxLength;if(e===void 0)return;const t=ju(this.getText(),this.manager);return e-t.length}setCustomColor(e){this.getFillColor()!=="#custom"&&console.warn(`setting custom color for text step ${this.step.stepName} but current fill is not #custom`);const t=this.manager.getRegionElements(this.step.stepName);ri.applyCustomFillColor(this.step,e,t,this.manager)}getCustomColor(){return this.manager.getStepStorage(this.step.stepName)?.customColor||"#000000"}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?ri.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeStrokeColor(this.step,e,t,this.manager)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class CI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}getContent(){return this.step.data.content}}class xI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(e){return T1.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),e.key,this.manager,this.step)}}class SI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const e=this.step.data.maxLength;if(e===void 0)return;const t=ju(this.getText(),this.manager);return e-t.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(e){P1.changeText(this.step,e,this.manager,t=>{if(t){const n=[...this.manager.getInformationResults(),{message:t,messageType:Jf.Error,stepID:this.step.stepName}];this.manager.setInformationResults(n)}else{const n=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(n)}})}}class EI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}async getAvailableVariants(){const e=await super.getAvailableVariants();if(!this.cachedProductIds){this.cachedProductIds=new Set;for(const t of e){const n=t.getProduct();n?.id&&this.cachedProductIds.add(n.id)}}return e}isPersonalisable(e){const t=e.getProduct();return!!t?.workflows&&t.workflows.length>0}async addProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)throw new Error("Product step requires bundle context");const n=e.getProduct();if(!n)throw new Error("Variant has no product. Ensure the option query includes the product field on variants.");if(!this.isPersonalisable(e)){await this.incrementNonPersonalisable(e);return}const i=this.manager.getWorkflowExperience().getTransaction(),a=i.integrationProduct?.integration?.id;let s;if(a&&n.integrationProducts&&(s=n.integrationProducts.find(d=>d.integration?.id===a)?.id),!s)throw new Error("No integration product found for bundle context");const o=this.manager.getClient(),l=n?.workflows||[];let u;if(l.length===1)u=l[0].id;else if(l.length>1){const f=this.step.data.workflows,d=l.find(h=>f.includes(h.id));if(d)u=d.id;else throw new Error("Multiple workflows available but none match step configuration")}const c=await o.getWorkflowExperience({type:"integration",integrationProductId:s,workflowId:u,parentTransactionId:i.id});await t.addWorkflowExperience(c)}async incrementNonPersonalisable(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)return;const n=e.getProduct(),i=this.findExperienceForProduct(n.id);if(i){const c=i.getTransaction().quantity||1;await i.setQuantity(c+1);return}const a=this.manager.getWorkflowExperience().getTransaction(),s=a.integrationProduct?.integration?.id;let o;if(s&&n.integrationProducts&&(o=n.integrationProducts.find(f=>f.integration?.id===s)?.id),!o)throw new Error("No integration product found for bundle context");const u=await this.manager.getClient().getWorkflowExperience({type:"integration",integrationProductId:o,parentTransactionId:a.id});await t.addWorkflowExperience(u)}async removeProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)throw new Error("Product step requires bundle context");const i=t.getWorkflowExperiences().find(o=>o.getTransaction().id===e);if(!i)throw new Error("Transaction is not a child of this product step");const a=i.getTransaction(),s=a.quantity||1;if(s>1){await i.setQuantity(s-1);return}await t.removeWorkflowExperienceByTransaction(a)}isCategoryFilterEnabled(){return this.step.data.categoryFilterEnabled??!1}isSearchBarEnabled(){return this.step.data.searchBarEnabled??!1}getMin(){return this.step.data.min}getMax(){return this.step.data.max}getPricing(){return this.step.data.pricing}getWorkflows(){return this.step.data.workflows||[]}getChildTransactions(){const e=this.manager.getWorkflowExperience().getBundle();if(!e)return[];const t=this.manager.getWorkflowExperience().getTransaction().id,n=e.getWorkflowExperiences(),i=this.getStepProductIds();return n.map(a=>a.getTransaction()).filter(a=>a.parentTransaction?.id!==t||i.size===0?!1:a.product?.id?i.has(a.product.id):!1)}getStepProductIds(){if(this.cachedProductIds&&this.cachedProductIds.size>0)return this.cachedProductIds;const e=this.step.option?.variants||[],t=new Set;for(const n of e)n.product?.id&&t.add(n.product.id);return t}getLockedAddOns(){return this.step.data.lockedAddOns||[]}findExperienceForProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)return;const n=this.manager.getWorkflowExperience().getTransaction().id,i=this.getStepProductIds();return t.getWorkflowExperiences().find(a=>{const s=a.getTransaction();return s.parentTransaction?.id!==n||i.size>0&&!i.has(e)?!1:s.product?.id===e})}}class Ep{static get(e,t){switch(t.type){case Xe.DigitalContent:return new xI(e,t,e.getStepTags(t.stepName));case Xe.Information:return new CI(e,t,e.getStepTags(t.stepName));case Xe.Question:return new AI(e,t,e.getStepTags(t.stepName));case Xe.Text:return new wI(e,t,e.getStepTags(t.stepName));case Xe.Illustration:return new gI(e,t,e.getStepTags(t.stepName));case Xe.Picture:return new yI(e,t,e.getStepTags(t.stepName));case Xe.Shape:return new bI(e,t,e.getStepTags(t.stepName));case Xe.Material:return new mI(e,t,e.getStepTags(t.stepName));case Xe.Model:return new vI(e,t,e.getStepTags(t.stepName));case Xe.Frame:return new WP(e,t,e.getStepTags(t.stepName));case Xe.Module:return new SI(e,t,e.getStepTags(t.stepName));case Xe.Product:return new EI(e,t,e.getStepTags(t.stepName));default:throw new nn(`Step type ${t.type} not yet supported in Core SDK`)}}}var Pv,EE;function D9(){if(EE)return Pv;EE=1;var r=1/0,e=9007199254740991,t=17976931348623157e292,n=NaN,i="[object Function]",a="[object GeneratorFunction]",s="[object Symbol]",o=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,c=/^0o[0-7]+$/i,f=/^(?:0|[1-9]\d*)$/,d=parseInt,h=Object.prototype,g=h.toString,v=Math.ceil,y=Math.max;function A(oe,he,ye){var Ue=-1,Re=oe.length;he<0&&(he=-he>Re?0:Re+he),ye=ye>Re?Re:ye,ye<0&&(ye+=Re),Re=he>ye?0:ye-he>>>0,he>>>=0;for(var Oe=Array(Re);++Ue<Re;)Oe[Ue]=oe[Ue+he];return Oe}function C(oe,he){return he=he??e,!!he&&(typeof oe=="number"||f.test(oe))&&oe>-1&&oe%1==0&&oe<he}function S(oe,he,ye){if(!G(ye))return!1;var Ue=typeof he;return(Ue=="number"?R(ye)&&C(he,ye.length):Ue=="string"&&he in ye)?E(ye[he],oe):!1}function F(oe,he,ye){(ye?S(oe,he,ye):he===void 0)?he=1:he=y(J(he),0);var Ue=oe?oe.length:0;if(!Ue||he<1)return[];for(var Re=0,Oe=0,ee=Array(v(Ue/he));Re<Ue;)ee[Oe++]=A(oe,Re,Re+=he);return ee}function E(oe,he){return oe===he||oe!==oe&&he!==he}function R(oe){return oe!=null&&j(oe.length)&&!B(oe)}function B(oe){var he=G(oe)?g.call(oe):"";return he==i||he==a}function j(oe){return typeof oe=="number"&&oe>-1&&oe%1==0&&oe<=e}function G(oe){var he=typeof oe;return!!oe&&(he=="object"||he=="function")}function ie(oe){return!!oe&&typeof oe=="object"}function q(oe){return typeof oe=="symbol"||ie(oe)&&g.call(oe)==s}function Y(oe){if(!oe)return oe===0?oe:0;if(oe=ae(oe),oe===r||oe===-r){var he=oe<0?-1:1;return he*t}return oe===oe?oe:0}function J(oe){var he=Y(oe),ye=he%1;return he===he?ye?he-ye:he:0}function ae(oe){if(typeof oe=="number")return oe;if(q(oe))return n;if(G(oe)){var he=typeof oe.valueOf=="function"?oe.valueOf():oe;oe=G(he)?he+"":he}if(typeof oe!="string")return oe===0?oe:+oe;oe=oe.replace(o,"");var ye=u.test(oe);return ye||c.test(oe)?d(oe.slice(2),ye?2:8):l.test(oe)?n:+oe}return Pv=F,Pv}var R9=D9();const fA=Ns(R9),O9=Se`
2655
+ `,F9=(r,e)=>e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).sort().reduce((t,n)=>(t[n]=e[n],t),{}):e,I9=r=>{for(const e of Object.values(r.layouts).map(t=>t.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return pI(r,"__typename"),r},pI=(r,e)=>{if(!(typeof r!="object"||r===null))for(const t in r)t===e?delete r[t]:pI(r[t],e)};var Jf=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(Jf||{});const P9=1e3;class SE extends jg{constructor(e){super(),this.update=e}async execute(){await this.update(),await new Promise(e=>{window.setTimeout(()=>{e()},P9)})}}const D9=r=>r.sort((e,t)=>e.index-t.index).map(e=>({id:Ar(),panelId:e.name,name:e.name,title:e.title,index:e.index,createdAt:new Date,updatedAt:new Date,transparentBackground:e.transparentBackground,height:e.height,width:e.width,previewRegion:e.previewRegion,useEditableArea:e.useEditableArea,editableArea:e.editableArea})),R9=(r,e)=>{const t=r.workflowState,n=t?JSON.parse(t):void 0;return n?Object.values(n.layouts).map(i=>i.layout):D9(e.panels)},af=class af{constructor(e,t,n,i,a,s=!1,o,l=!1,u=!1,c=!1){this.workflowStatePromiseQueue=new Gg(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async d=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):d?this.layouts=R9(this.experience.getTransaction(),d):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new LU(this.layouts),this.renderableContextService.setWorkflowManager(this),d.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(d),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const d=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(d)},this.experience=e,this.client=t,this.updateTransaction=n,this.graphQlClient=i,this.reloadedState=a,this.readOnly=s,this.singleVariantsRenderable=u,this.commandContext=new GF,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=o,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,c&&(this.workflowStatePromiseQueue.enabled=!1);const f=this.experience.getWorkflow();f&&this.setWorkflow(f)}getTemplatingContext(){const e=this.experience.getTransaction().recipient,t={recipient:e};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(n=>{const i=n.uniqueIdentifier??n.title??"";n.type===Qd.FirstName?t[i]=e?.firstName:n.type===Qd.LastName?t[i]=e?.lastName:n.type===Qd.Custom&&(n.customFieldIndex===1?t[i]=e?.customField1:n.customFieldIndex===2?t[i]=e?.customField2:n.customFieldIndex===3?t[i]=e?.customField3:n.customFieldIndex===4?t[i]=e?.customField4:n.customFieldIndex===5&&(t[i]=e?.customField5),n.option&&(t[i]=n.option.variants?.find(a=>a.id===t[i])?.name))}),t}async updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,v,y,A,C){const S=this.experience.getTransaction();if(S.recipient?.id)this.experience.getTransaction().recipient={id:S.recipient.id,firstName:e??S.recipient.firstName,lastName:t??S.recipient.lastName,address:n??S.recipient.address,suburb:i??S.recipient.suburb,state:a??S.recipient.state,email:s??S.recipient.email,postalCode:o??S.recipient.postalCode,country:l??S.recipient.country,mobile:u??S.recipient.mobile,company:c??S.recipient.company,apartment:f??S.recipient.apartment,customField1:d??S.recipient.customField1,customField2:h??S.recipient.customField2,customField3:g??S.recipient.customField3,customField4:v??S.recipient.customField4,customField5:y??S.recipient.customField5,conversionConfigurationId:A||S.recipient.conversionConfigurationId},this.experience.callEvent(yg.RecipientChanged),await this.graphQlClient().mutate({mutation:x9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:S.recipient.id,firstName:e||S.recipient.firstName,lastName:t||S.recipient.lastName,address:n||S.recipient.address,suburb:i||S.recipient.suburb,state:a||S.recipient.state,email:s||S.recipient.email,postalCode:o||S.recipient.postalCode,country:l||S.recipient.country,mobile:u||S.recipient.mobile,company:c||S.recipient.company,apartment:f||S.recipient.apartment,customField1:d||S.recipient.customField1,customField2:h||S.recipient.customField2,customField3:g||S.recipient.customField3,customField4:v||S.recipient.customField4,customField5:y||S.recipient.customField5,conversionConfigurationId:A||S.recipient.conversionConfigurationId,prevalidated:C}});else{const F=await this.graphQlClient().mutate({mutation:C9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:e,lastName:t,address:n,suburb:i,state:a,email:s,postalCode:o,country:l,mobile:u,company:c,apartment:f,customField1:d,customField2:h,customField3:g,customField4:v,customField5:y,conversionConfigurationId:A}});S.recipient={id:F?.data?.recipientCreate?.id,firstName:e,lastName:t,address:n,suburb:i,state:a,email:s,postalCode:o,country:l,mobile:u,company:c,apartment:f,customField1:d,customField2:h,customField3:g,customField4:v,customField5:y,conversionConfigurationId:A},this.experience.callEvent(yg.RecipientChanged),await this.graphQlClient().mutate({mutation:S9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const e=this.experience.getTransaction().recipient;if(e?.conversionConfigurationId&&!this.recipientConversionConfiguration){const t=af.configurationPromiseMap.get(e.conversionConfigurationId);if(t)this.recipientConversionConfiguration=await t;else{const i=(async()=>(await this.graphQlClient().query({query:B3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e.conversionConfigurationId}})).data.conversionConfiguration)();af.configurationPromiseMap.set(e.conversionConfigurationId,i),this.recipientConversionConfiguration=await i}}}async initializeDefaultWorkflowState(e){const t=()=>{const c=e.finalizeStepConfig;if(!c)return;const f=c.lookAtAnimation,d=c.modelAnimation;f&&this.previewService?.executeCameraAnimation(f),d&&this.modelContainer?.executeAnimation(d)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(c=>{this.storage[c.stepName]=c.storage||{}});const n=await this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((c,f)=>(f.selectedVariants?.length&&(c[f.stepName]={selectedVariants:f.selectedVariants.map(d=>({id:d.id}))}),c),{})),i=ct.getOptions(Array.from(n)),a=this.fetchConversionConfiguration();await Promise.all([i,a]),this.allScenes=XC(e);const o=(await Ja(this.allScenes,this.stepSelections)).map(c=>c.silentSteps).flat(),{stepElements:l,commands:u}=await this.stepElementsForIntroducedSilentSteps(o,!!this.reloadedState);this.commandContext.apply(new On(u),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&t()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(e){this.workflowStatePromiseQueue.enabled=e}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}async getInitialOptionIds(e){const t=new Set,n=this.experience.getWorkflow();if(!n)return t;const i=XC(n),a={...e};let s=-1;for(;;){const u=(await Ja(i,a)).flatMap(c=>c.renderableSteps);if(u.length===s)break;s=u.length;for(const c of u){if(a[c.stepName])continue;const f=c.option?.defaultVariant?.id;f&&(a[c.stepName]={selectedVariants:[{id:f}]})}}return(await Ja(i,a)).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&t.add(l.option.id)}),t}addConfirmCallback(e){e(this.confirmedDesign),this.confirmCallbacks.push(e)}addEditedCallback(e){e(this.editedSteps),this.editedCallbacks.push(e)}addElementsCallback(e){e(this.stepElements),this.elementsCallbacks.push(e)}addInformationResultCallback(e){e(this.informationResults),this.informationResultCallbacks.push(e)}addInitCallback(e){e(this.stepInitialised),this.initCallbacks.push(e)}addMandatoryCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}addMetadataCallback(e){e(this.stepMetadata),this.metadataCallbacks.push(e)}async addSelectionCallback(e){e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(e)}addStepSpecificStorageCallback(e,t){Object.keys(this.storage).includes(t)||(this.storage[t]={}),e(this.storage[t]),Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].push(e)}addStorageCallback(e){e(this.storage),this.storageCallbacks.push(e)}addMakingAdjustmentsCallback(e){e(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(e)}addPoller(e){this.pollers.push(e)}addValidationCallback(e){this.validationCallbacks.push(e),e(this.validationErrors)}addRecipientCallback(e){this.recipientCallbacks.push(e),e(this.experience.getTransaction().recipient)}removeRecipientCallback(e){this.recipientCallbacks=this.recipientCallbacks.filter(t=>t!==e)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(e=>e.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(e){return this.stepElements[e]||[]}getStepSpecificServices(e){return this.stepSpecificServices[e]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(e){this.ownerCustomer=e}setTransactionCustomerDetails(e){this.ownerCustomer={...this.ownerCustomer,emailAddress:e.email}}getModelContainer(){return this.modelContainer}setModelContainer(e){(!e||this.previewService&&this.previewService.getAllModels().includes(e))&&(this.modelContainer=e,e&&e.metadata&&e.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return e=>this.commandContext.apply(e,!this.initialized)}getWorkflowSelections(){const e={};return this.experience.getWorkflow()?.steps.forEach(t=>{const n=this.stepSelections[t.stepName];n&&n.selectedVariants&&n.selectedVariants.length>0&&(e[t.stepName]={selections:n.selectedVariants})}),e}getStepSelections(){return this.stepSelections}markStepsAsInitialised(e){const t={...this.stepInitialised};e.forEach(n=>{t[n]=!0}),this.stepInitialised=t,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(e){this.pendingUpdates=this.pendingUpdates.filter(t=>t!==e)}markUpdatePending(){const e=Ar();return this.pendingUpdates=[...this.pendingUpdates,e],e}setEditedStatus(e,t){this.editedSteps={...this.editedSteps,[e]:t},this.onEditedChange()}setInformationResults(e){this.informationResults=[...e],this.onInformationResultChange()}setCurrentAdjustingStepId(e){this.currentAdjustingStepId=e,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(e,t){this.mandatorySteps[e]!==t&&(this.mandatorySteps={...this.mandatorySteps,[e]:t},this.onMandatoryChange())}async getMandatoryUnfulfilledSteps(){return(await Ja(this.allScenes,this.stepSelections)).flatMap(a=>a.renderableSteps).filter(a=>a.mandatory).filter(a=>!this.mandatorySteps[a.stepName]).map(a=>a.stepName)}setStepError(e,t,n){let i=!1;if(!this.validationErrors.steps.has(e)&&n)i=!0,this.validationErrors.steps.set(e,new Map([[t,n]]));else if(this.validationErrors.steps.has(e)){const a=this.validationErrors.steps.get(e);n&&n!==a.get(t)?(i=!0,a.set(t,n)):n||(i=!0,a.delete(t),a.size===0&&this.validationErrors.steps.delete(e))}i&&this.onValidationChange()}getStepErrors(e){return this.validationErrors.steps.get(e)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}async injectIntoPreviewService(e,t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=e;const n=this.experience.getProduct();if(!n?.modelUrl||!this.previewService)return;const i=e.loadModel({model:n.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:t});this.setModelContainer(i),(await Ja(this.allScenes,this.stepSelections)).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===Xe.Model||o.type===Xe.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const l=this.stepSelections[o.stepName]?.selectedVariants||[];if(l.length===0)return;const u=l[0];if(o.type===Xe.Model){if(!this.modelContainer)throw new nn("We should always have a model container when injecting a preview!");const c=u.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${u.id} for step: ${o.stepName}`);return}const f=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},f.replaceProductModel||!1)}else{const c=u.material;if(!c){console.error(`Failed to read material from variant: ${u.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(d=>{if(!this.modelContainer)throw new nn("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(d,o.option.id,c)})}}),await i.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(e,t){const n={...this.storage,[e]:{...this.storage[e],...t}};if(!vf(n,this.storage)){this.storage=n;const i=new BS(this.constructSerializableWorkflow());this.commandContext.apply(i,!0),this.onStepSpecificStorageChange(e),this.onStorageChange()}}constructSerializableWorkflow(){const e=[];return this.allScenes.forEach(t=>{t.renderableSteps.forEach(n=>{const i={stepName:n.stepName};i.storage=this.storage[n.stepName],i.selectedVariants=this.stepSelections[n.stepName]?.selectedVariants?.map(a=>({id:a.id,priceModifier:a.priceModifier})),e.push(i)})}),{steps:e}}updateStateWithServer(){if(this.readOnly)return;const e=this.serialize();this.workflowStatePromiseQueue.enqueue(new SE(async()=>{await new Promise(t=>{setTimeout(()=>{t()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:e}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const e=this.serialize();return new SE(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:e}})}).execute()}serialize(){const e=this.getCommandContext().getState();if(!e)throw new nn("Attempted to serialize state before it was initialized.");const t=mo(e.transaction),n=I9(t);return JSON.stringify(n,F9,void 0)}async getStateHash(){const e=this.getCommandContext().getState(),n=Object.values(e?.transaction.layouts||{}).map(s=>s.modificationID??"").sort().join(""),a=new TextEncoder().encode(n);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const s=await window.crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(s)).map(u=>u.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(n,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(e,t){this.stepMetadata={...this.stepMetadata,[e]:{...this.stepMetadata[e],...t}},this.onMetadataChange()}removeElements(e){const t=(n,i)=>Object.keys(n).reduce((a,s)=>{const o=[...n[s]||[]];return i.forEach(l=>{const u=o.findIndex(c=>c.id===l.id);u>-1&&o.splice(u,1)}),a[s]=o,a},{});this.stepElements=t(this.stepElements,e)}async getInvalidCanvasRegions(){let e=[];for(const t of this.experience.getWorkflow()?.steps||[])if(!await co(t,this.stepSelections)&&this.stepElements[t.stepName])for(const n of this.stepElements[t.stepName])e.push(n);return e}async getInvalidModelVariants(){let e=[];for(const t of this.experience.getWorkflow()?.steps||[])t.type===Xe.Model&&!await co(t,this.stepSelections)&&e.push(t.stepName);return e}async stepElementsForIntroducedSilentSteps(e,t){const n=this.experience.getProduct();if(!n)return Promise.resolve({stepElements:{},commands:[]});const i=async(u,c,f)=>{if(u.type===Xe.SilentIllustration){const d=await new MS(u,c).trigger();return{step:u,results:d}}else if(u.type===Xe.ProductOverlay){const d=await new MS(u,c,f).trigger();return{step:u,results:d}}return Promise.reject("Unknown silent step. This is a bug")},a=e.filter(u=>!this.stepInitialised[u.stepName]),s={stepElements:{},commands:[]},o=[];for(const u of a)this.markStepsAsInitialised([u.stepName]),t||o.push(i(u,this.layouts,n));const l=await Promise.all(o);for(const u of l)s.stepElements[u.step.stepName]=u.results.map(c=>c.regionElement),s.commands=[...s.commands,...u.results.map(c=>c.command)];return s}getStepStorage(e){return this.storage[e]}getMetadata(e){return this.stepMetadata[e]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(e){return this.stepTags[e]||[]}getSerializedStep(e,t){return t.find(n=>n.stepName===e)}async updateTransactionShareActions(){const e=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=e}async updateTransactionStakeholders(){const e=await ze.getShadowGraphqlClient().query({query:V3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!e?.data?.transactions||e.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=e.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=e.data.transactions[0].currentStakeholder)}async approveTransaction(e){await ze.getShadowGraphqlClient().mutate({mutation:b9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:e}})}async rejectTransaction(e){await ze.getShadowGraphqlClient().mutate({mutation:w9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:e}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(e,t,n,i){const a=this.experience.getWorkflow();if(!a)throw new Error("Attempted to set selections when no workflow is set!");const s=this.stepSelections;this.stepSelections={...this.stepSelections,[e]:{selectedVariants:t}};for(const R of a.steps)await co(R,this.stepSelections)||(this.stepInitialised[R.stepName]=!1,delete this.stepMetadata[R.stepName],delete this.stepSelections[R.stepName],delete this.storage[R.stepName]);const o=this.allScenes,l=await Ja(o,s),u=await Ja(o,this.stepSelections),c=l.map(R=>R.silentSteps).flat(),d=u.map(R=>R.silentSteps).flat().filter(R=>!c.some(B=>B.stepName===R.stepName));for(const R of c)await co(R,this.stepSelections)||(this.stepInitialised[R.stepName]=!1);const h=await this.getInvalidCanvasRegions(),{stepElements:g,commands:v}=await this.stepElementsForIntroducedSilentSteps(d,!1);this.stepElements={...this.stepElements,...g,[e]:n},this.removeElements(h);const y=a.steps.find(R=>R.stepName===e);y?.type===Xe.Frame&&this.getWorkflowExperience().getStepById(y.stepName)?.frameService?.setTargetElements(n.map(B=>B.id));const A=h.map(R=>new Ol(R.id)),C=new BS(this.constructSerializableWorkflow()),S=[...v,...A,C];S.length>0&&this.commandContext.apply(new On(S),!0),await this.ensureStepsAreLoaded(),this.selectionCost=Object.values(this.stepSelections).reduce((R,B)=>R+B.selectedVariants.map(j=>j.priceModifier||0).reduce((j,G)=>j+G,0),0),this.onElementsChange();const F=await this.getInvalidModelVariants(),E=this.modelContainer;if(E){const R=F.map(B=>E.applyModelVariant(B,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(R)}await this.onSelectionChange(),await this.reapplyMaterialSteps(),y?.type!==Xe.Frame&&y?.type!==Xe.Text&&this.setMandatoryFulfilled(e,!0),i&&await i()}async ensureStepsAreLoaded(){const t=(await Ja(this.allScenes,this.stepSelections)).map(l=>l.renderableSteps),n=[],i=t.flat();for(const l of i)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case Xe.DigitalContent:n.push(T1.init(l,this,this.reloadedState));break;case Xe.Frame:n.push(so.init(l,this,this.reloadedState));break;case Xe.Illustration:n.push(Jd.init(l,this,this.reloadedState));break;case Xe.Material:n.push(F1.init(l,this,this.reloadedState));break;case Xe.Model:n.push(I1.init(l,this,this.reloadedState));break;case Xe.Module:this.stepSpecificServices[l.stepName]={module:await oI(l.data.module)},n.push(P1.init(l,this,this.reloadedState));break;case Xe.Picture:n.push(D1.init(l,this,this.reloadedState));break;case Xe.Question:n.push(R1.init(l,this,this.reloadedState));break;case Xe.Shape:n.push(Nu.init(l,this,this.reloadedState));break;case Xe.Text:n.push(ri.init(l,this,this.reloadedState));break}const a=(await Promise.allSettled(n)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),s=a.flatMap(l=>l?.command?[l.command]:[]),o=a.flatMap(l=>l?.followup?[l.followup]:[]);s&&s.length>0&&this.commandContext.apply(new On(s),!0);for(const l of o)await l();o.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(e=>e(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(e=>e(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(e=>e(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(e=>e(this.informationResults))}onInitChange(){this.initCallbacks.forEach(e=>e(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(e=>{e(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(e=>e(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(e=>{e(this.stepMetadata)})}async onSelectionChange(){const e=await this.traversableScenes();for(const t of this.selectionCallbacks)t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:e})}onStepSpecificStorageChange(e){Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].forEach(t=>t(this.storage[e]))}onStorageChange(){this.storageCallbacks.forEach(e=>e(this.storage))}onValidationChange(){this.validationCallbacks.forEach(e=>e(this.validationErrors))}traversableScenes(){return P_(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}async reapplyMaterialSteps(){if(!this.modelContainer)return;const t=(await Ja(this.allScenes,this.stepSelections)).flatMap(n=>n.renderableSteps).filter(n=>n.type===Xe.Material);for(const n of t){const i=this.stepSelections[n.stepName]?.selectedVariants;if(!i||i.length===0)continue;const s=i[0].material;if(!s||!n.option?.id)continue;n.data.targetMaterials.forEach(l=>{this.modelContainer?.applyMaterialVariant(l,n.option.id,s)})}}};af.configurationPromiseMap=new Map;let dA=af;class Fa{constructor(e){this.variantData=e}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(e,t){return this.variantData.priceModifier.toLocaleString(e||"en-US",{style:"currency",currency:"USD",...t})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.fileLink}getAssetResource(){return this.variantData.asset}getThumbnail(e=256,t){const n=this.variantData.thumbnail;if(!(!n||!n.fileLink))return $g(n,e,"webp",t)}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}getCategory(){return this.variantData.category}getProduct(){return this.variantData.product}}const sf=class sf{constructor(e,t,n){this.manager=e,this.step=t,this.tags=n}setUpdateState(e){sf.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,e)}getUpdateState(){return!!sf.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const n=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(n)return new Fa(n)}async getAvailableVariants(){return(await this.getAllVariants()).filter(t=>t.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(t=>new Fa(t))||[];const e=await ct.getOption(this.step.option?.id);if(!e)throw new Error("Option not found, cannot fetch variants.");return(e.variants||[]).map(t=>new Fa(t))||[]}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(e){return this.tags.includes(e)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(e){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[e.toString()]??!1}setOverrideGlobalPropertyConfiguration(e,t){const n=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...n,[e.toString()]:t}})}getGlobalPropertyAspects(e){return this.step.globalPropertyAspectConfigurations?.filter(t=>t.globalPropertyConfigurationId===e&&t.aspectName).map(t=>t.aspectName)??[]}executeAnimations(e){const t=this.manager.getPreviewService(),n=this.manager.getModelContainer(),i=this.step.data.modelAnimation,a=this.step.data.lookAtAnimation;t?a&&t.executeCameraAnimation(a):console.warn("No preview service available, cannot execute camera animations."),n?i&&n.executeAnimation(i,e):console.warn("No model container available, cannot execute model animations.")}};sf.updateState=new Map;let Ui=sf;class gI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){if(!this.getUpdateState()&&this.getCurrentVariant()!==e)return Jd.selectVariant(this.step,e.getResource(),this.manager.getRegionElements(this.step.stepName)||[],t=>this.setUpdateState(t),this.manager)}getColors(){const e=this.manager.getRegionElements(this.step.stepName)||[];if(e.length===0)return;const n=Un(e[0].id,this.manager.getAllLayoutData()).colors,a=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,s=a?.defaultColorVariants||[];if(s.length!==0){const o={};return s.forEach(l=>{const u=a.channelNumbers.find(c=>c.number===l.channelNumber);if(u){const c=u.id.replace(/\W/g,"");o[l.channelNumber]={browserValue:n[c]?.browserValue||""}}}),o}try{return n}catch(o){console.error(o)}}setColor(e,t,n){const i=new Map,s=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(s?.defaultColorVariants||[]).length!==0?s.channelNumbers.forEach(l=>{if(l.number.toString()===e){const u=l.id.replace(/\W/g,"");n?i.set(u,{browserValue:t,pmsValue:n}):i.set(u,t)}}):n?i.set(e,{browserValue:t,pmsValue:n}):i.set(e,t),Jd.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,i)}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?Jd.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class mI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return F1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class vI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return I1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class yI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return D1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class AI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){if(!e.getId())throw new Error("Unable to select variant with a null ID");await R1.selectVariant(this.step,e.getId(),this.manager)}async getDisplayType(){return this.step.data.displayType?this.step.data.displayType:(await ct.getOptionForStep(this.step))?.displayType}}class bI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){const t=e.getResource();return Nu.selectVariant(this.step,{fill:t.color,stroke:t.color,variant:t},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(e){return Nu.selectVariant(this.step,e,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Nu.availableColours(this.step)}setCustomColor(e){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Nu.setCustomColor(e,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const e=this.manager.getStepStorage(this.step.stepName)?.colour;if(!e)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return e}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class wI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){await ri.selectVariant(this.step,e.getResource(),this.manager,t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:t,messageType:Jf.Error,stepID:this.step.stepName}]);else{const n=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(n)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?ri.availableFillColors(this.step):[]}async setFillColor(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeFillColor(this.step,e,t,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return ri.availableFillImages(this.step)}async setFillImage(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeFillImage(this.step,e,t,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return ri.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(e){const t=this.manager.getRegionElements(this.step.stepName);ri.changeAlignment(this.step,e,t,this.manager)}setFullTextCustomization(e){const t=this.manager.getStepStorage(this.step.stepName)?.inputText||"",n=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",t):t,i=e?n:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:e,text:i,defaultCleared:!1}),this.setText(i)}setText(e){const t={input:e,helperData:{}},n=ri.findLayoutElements(this.manager,this.step),i=ri.filterUnsupportedCharacters(e,n[0]?.fontData),a=ju(i,this.manager).length,s=!!this.step.data&&!!this.step.data.maxLength&&a>this.step.data.maxLength;s||(t.input=i);const o=n.length<=0,l=o?{inputText:i,text:i}:{inputText:i};this.manager.updateStorage(this.step.stepName,l);const u=this.manager.getStepStorage(this.step.stepName),c=ri.getProcessedInput(i,this.step.data,u?.customiseAllText??!1);if(o)s||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:f,errorData:d,helperData:h}=ri.updateInputText(i,n,this.step,this.manager);f&&this.manager.getCommandDispatcher()(f),t.helperData=h,t.errorData=d,!s&&!d&&this.manager.updateMetadata(this.step.stepName,{text:c})}return t}getText(){const e=this.step.data.defaultText,t=this.manager.getStepStorage(this.step.stepName);return e&&t?.defaultCleared!==void 0&&!t?.defaultCleared?e:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const t=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const n=ri.findLayoutElements(this.manager,this.step);return ri.updateInputText("",n,this.step,this.manager),t}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const e=this.step.data.maxLength;if(e===void 0)return;const t=ju(this.getText(),this.manager);return e-t.length}setCustomColor(e){this.getFillColor()!=="#custom"&&console.warn(`setting custom color for text step ${this.step.stepName} but current fill is not #custom`);const t=this.manager.getRegionElements(this.step.stepName);ri.applyCustomFillColor(this.step,e,t,this.manager)}getCustomColor(){return this.manager.getStepStorage(this.step.stepName)?.customColor||"#000000"}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?ri.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeStrokeColor(this.step,e,t,this.manager)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class CI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}getContent(){return this.step.data.content}}class xI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(e){return T1.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),e.key,this.manager,this.step)}}class SI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const e=this.step.data.maxLength;if(e===void 0)return;const t=ju(this.getText(),this.manager);return e-t.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(e){P1.changeText(this.step,e,this.manager,t=>{if(t){const n=[...this.manager.getInformationResults(),{message:t,messageType:Jf.Error,stepID:this.step.stepName}];this.manager.setInformationResults(n)}else{const n=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(n)}})}}class EI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}async getAvailableVariants(){const e=await super.getAvailableVariants();if(!this.cachedProductIds){this.cachedProductIds=new Set;for(const t of e){const n=t.getProduct();n?.id&&this.cachedProductIds.add(n.id)}}return e}isPersonalisable(e){const t=e.getProduct();return!!t?.workflows&&t.workflows.length>0}async addProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)throw new Error("Product step requires bundle context");const n=e.getProduct();if(!n)throw new Error("Variant has no product. Ensure the option query includes the product field on variants.");if(!this.isPersonalisable(e)){await this.incrementNonPersonalisable(e);return}const i=this.manager.getWorkflowExperience().getTransaction(),a=i.integrationProduct?.integration?.id;let s;if(a&&n.integrationProducts&&(s=n.integrationProducts.find(d=>d.integration?.id===a)?.id),!s)throw new Error("No integration product found for bundle context");const o=this.manager.getClient(),l=n?.workflows||[];let u;if(l.length===1)u=l[0].id;else if(l.length>1){const f=this.step.data.workflows,d=l.find(h=>f.includes(h.id));if(d)u=d.id;else throw new Error("Multiple workflows available but none match step configuration")}const c=await o.getWorkflowExperience({type:"integration",integrationProductId:s,workflowId:u,parentTransactionId:i.id});await t.addWorkflowExperience(c)}async incrementNonPersonalisable(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)return;const n=e.getProduct(),i=this.findExperienceForProduct(n.id);if(i){const c=i.getTransaction().quantity||1;await i.setQuantity(c+1);return}const a=this.manager.getWorkflowExperience().getTransaction(),s=a.integrationProduct?.integration?.id;let o;if(s&&n.integrationProducts&&(o=n.integrationProducts.find(f=>f.integration?.id===s)?.id),!o)throw new Error("No integration product found for bundle context");const u=await this.manager.getClient().getWorkflowExperience({type:"integration",integrationProductId:o,parentTransactionId:a.id});await t.addWorkflowExperience(u)}async removeProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)throw new Error("Product step requires bundle context");const i=t.getWorkflowExperiences().find(o=>o.getTransaction().id===e);if(!i)throw new Error("Transaction is not a child of this product step");const a=i.getTransaction(),s=a.quantity||1;if(s>1){await i.setQuantity(s-1);return}await t.removeWorkflowExperienceByTransaction(a)}isCategoryFilterEnabled(){return this.step.data.categoryFilterEnabled??!1}isSearchBarEnabled(){return this.step.data.searchBarEnabled??!1}getMin(){return this.step.data.min}getMax(){return this.step.data.max}getPricing(){return this.step.data.pricing}getWorkflows(){return this.step.data.workflows||[]}getChildTransactions(){const e=this.manager.getWorkflowExperience().getBundle();if(!e)return[];const t=this.manager.getWorkflowExperience().getTransaction().id,n=e.getWorkflowExperiences(),i=this.getStepProductIds();return n.map(a=>a.getTransaction()).filter(a=>a.parentTransaction?.id!==t||i.size===0?!1:a.product?.id?i.has(a.product.id):!1)}getStepProductIds(){if(this.cachedProductIds&&this.cachedProductIds.size>0)return this.cachedProductIds;const e=this.step.option?.variants||[],t=new Set;for(const n of e)n.product?.id&&t.add(n.product.id);return t}getLockedAddOns(){return this.step.data.lockedAddOns||[]}findExperienceForProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)return;const n=this.manager.getWorkflowExperience().getTransaction().id,i=this.getStepProductIds();return t.getWorkflowExperiences().find(a=>{const s=a.getTransaction();return s.parentTransaction?.id!==n||i.size>0&&!i.has(e)?!1:s.product?.id===e})}}class Ep{static get(e,t){switch(t.type){case Xe.DigitalContent:return new xI(e,t,e.getStepTags(t.stepName));case Xe.Information:return new CI(e,t,e.getStepTags(t.stepName));case Xe.Question:return new AI(e,t,e.getStepTags(t.stepName));case Xe.Text:return new wI(e,t,e.getStepTags(t.stepName));case Xe.Illustration:return new gI(e,t,e.getStepTags(t.stepName));case Xe.Picture:return new yI(e,t,e.getStepTags(t.stepName));case Xe.Shape:return new bI(e,t,e.getStepTags(t.stepName));case Xe.Material:return new mI(e,t,e.getStepTags(t.stepName));case Xe.Model:return new vI(e,t,e.getStepTags(t.stepName));case Xe.Frame:return new WP(e,t,e.getStepTags(t.stepName));case Xe.Module:return new SI(e,t,e.getStepTags(t.stepName));case Xe.Product:return new EI(e,t,e.getStepTags(t.stepName));default:throw new nn(`Step type ${t.type} not yet supported in Core SDK`)}}}var Pv,EE;function O9(){if(EE)return Pv;EE=1;var r=1/0,e=9007199254740991,t=17976931348623157e292,n=NaN,i="[object Function]",a="[object GeneratorFunction]",s="[object Symbol]",o=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,c=/^0o[0-7]+$/i,f=/^(?:0|[1-9]\d*)$/,d=parseInt,h=Object.prototype,g=h.toString,v=Math.ceil,y=Math.max;function A(oe,he,ye){var Ue=-1,Re=oe.length;he<0&&(he=-he>Re?0:Re+he),ye=ye>Re?Re:ye,ye<0&&(ye+=Re),Re=he>ye?0:ye-he>>>0,he>>>=0;for(var Oe=Array(Re);++Ue<Re;)Oe[Ue]=oe[Ue+he];return Oe}function C(oe,he){return he=he??e,!!he&&(typeof oe=="number"||f.test(oe))&&oe>-1&&oe%1==0&&oe<he}function S(oe,he,ye){if(!G(ye))return!1;var Ue=typeof he;return(Ue=="number"?R(ye)&&C(he,ye.length):Ue=="string"&&he in ye)?E(ye[he],oe):!1}function F(oe,he,ye){(ye?S(oe,he,ye):he===void 0)?he=1:he=y(J(he),0);var Ue=oe?oe.length:0;if(!Ue||he<1)return[];for(var Re=0,Oe=0,ee=Array(v(Ue/he));Re<Ue;)ee[Oe++]=A(oe,Re,Re+=he);return ee}function E(oe,he){return oe===he||oe!==oe&&he!==he}function R(oe){return oe!=null&&j(oe.length)&&!B(oe)}function B(oe){var he=G(oe)?g.call(oe):"";return he==i||he==a}function j(oe){return typeof oe=="number"&&oe>-1&&oe%1==0&&oe<=e}function G(oe){var he=typeof oe;return!!oe&&(he=="object"||he=="function")}function ie(oe){return!!oe&&typeof oe=="object"}function q(oe){return typeof oe=="symbol"||ie(oe)&&g.call(oe)==s}function Y(oe){if(!oe)return oe===0?oe:0;if(oe=ae(oe),oe===r||oe===-r){var he=oe<0?-1:1;return he*t}return oe===oe?oe:0}function J(oe){var he=Y(oe),ye=he%1;return he===he?ye?he-ye:he:0}function ae(oe){if(typeof oe=="number")return oe;if(q(oe))return n;if(G(oe)){var he=typeof oe.valueOf=="function"?oe.valueOf():oe;oe=G(he)?he+"":he}if(typeof oe!="string")return oe===0?oe:+oe;oe=oe.replace(o,"");var ye=u.test(oe);return ye||c.test(oe)?d(oe.slice(2),ye?2:8):l.test(oe)?n:+oe}return Pv=F,Pv}var B9=O9();const fA=Ns(B9),M9=Se`
2656
2656
  fragment CreateDesignTransaction on Transaction {
2657
2657
  id
2658
2658
  designName
@@ -2677,8 +2677,8 @@ Minimum version required to store current data is: `+q+`.
2677
2677
  externalProductVariantId
2678
2678
  }
2679
2679
  }
2680
- `,B9=Se`
2681
- ${O9}
2680
+ `,_9=Se`
2681
+ ${M9}
2682
2682
  mutation CreateDesigns($inputs: [DesignCreateInput]!) {
2683
2683
  designCreateMany(inputs: $inputs) {
2684
2684
  id
@@ -2691,7 +2691,7 @@ Minimum version required to store current data is: `+q+`.
2691
2691
  }
2692
2692
  }
2693
2693
  }
2694
- `;function vg(r){const e=JSON.parse(atob(r.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=e}const M9=async(r,e)=>{const t={};try{if(e){const i=await e.loggedInBearerToken();t.Authorization=`Bearer ${i}`}else throw new Error}catch{const s=Object.entries(localStorage).find(([l,u])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",o=localStorage.getItem(s);o&&!vg(o)&&(t.Authorization=`Bearer ${o}`)}return await e.getBetaEnabled()&&(t["X-Spiff-Beta"]="true"),(await ze.getShadowGraphqlClient().mutate({mutation:B9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:r.map(i=>({name:i.name,layouts:i.layouts,workflowId:i.workflowId,transactionId:i.transactionId,previewImage:i.previewImage,useThreeDimPreview:i.useThreeDimPreview,metadata:i.metadata,selectedVariants:i.selectedVariants}))},context:{headers:t}})).data?.designCreateMany},kE=(r,e,t)=>{const n=a=>{const s={};if(a.type==="Frame"){const o=r[a.stepName],l=a.data;if(!o||!o.image||l.hideImageInCart&&t)return s;s[`${a.stepTitle} image`]=o.image}if(a.type==="Illustration"){const o=r[a.stepName],l=a.data;if(!o||l.hideColorsInCart&&t||!o.colors)return s;if(o.colors.length>0){const u=o.colors.join(", ").toUpperCase();s[`${a.stepTitle} colors`]=u}}if(a.type==="Module"){const o=r[a.stepName],l=a.data;if(!o||o.text===void 0||o.text===null||l.hideTextInCart&&t)return s;s[`${a.stepTitle} text`]=o.text}if(a.type==="Text"){const o=r[a.stepName];if(!o)return s;const l=a.data;(!l.hideTextInCart||!t&&o.text!==void 0&&o.text!==null)&&(s[`${a.stepTitle} text`]=o.text),o.color&&(!l.hideColorInCart||!t)&&(s[`${a.stepTitle} color`]=o.color),o.strokeColor&&(!l.hideStrokeInCart||!t)&&(s[`${a.stepTitle} stroke`]=o.strokeColor)}return s},i={};return e.steps.forEach(a=>{Object.assign(i,n(a))}),i},_9=(r,e,t,n)=>{const i={};let a={};n&&(a=n);const o=e.steps.map(l=>l.stepTitle).filter((l,u,c)=>c.indexOf(l)==u);for(const l of o){if(Object.keys(r).includes(l)){const u=r[l],c=e.steps.find(f=>f.stepTitle===l);i[`${c?.stepTitle} selection`]={value:u[0].name,priceModifier:u[0].priceModifier}}for(const u of Object.keys(a))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(u)&&(i[u]={value:a[u],priceModifier:0})}return i},N9=(r,e,t,n,i,a,s,o)=>{const l=e.basePrice||0,u=r.priceModifierTotal||0,c=_9(n,t,void 0,a),d=(wr.getMap("transactionOwnerIds")||new Map).get(r.id),h={additionalExternalProductId:r.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:r.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:r.designExternalVariants,designProductId:r.externalDesignProductId,designProductVariantId:r.externalDesignProductVariantId,event:"onComplete",exportedData:c,externalCartProductId:r.externalCartProductId,externalCartProductVariantId:r.externalCartProductVariantId,lineItemImageUrl:s||"",optionsCost:u,processExecutionId:o,quantity:r.quantity,transactionId:r.id,transactionOwnerId:d,weight:e.weight,workflowViewerLink:r.workflowViewerLink||"",workflowViewerReadOnlyLink:r.workflowViewerReadOnlyLink||""};return a&&(h.metadata=a),n&&(h.selectedVariants=n),i&&(h.sku=i),h},L9=r=>{const e=r.integrationProductId||r.integrationProduct?.id,t=r.integrationProduct;if(t?.externalProductId&&t?.externalVariantId)return t;if(e&&r.product?.integrationProducts){const n=r.product.integrationProducts.find(i=>i.id===e);if(n)return{...t,...n}}return t},kI=r=>{const e=L9(r);return{id:r.id,externalProductId:r.externalCartProductId||r.externalDesignProductId||e?.externalProductId||e?.additionalExternalProductId,externalProductVariantId:r.externalCartProductVariantId||r.externalDesignProductVariantId||e?.externalVariantId||e?.additionalExternalVariantId}},U9=async r=>{const e=[...new Set(r.filter(i=>{const a=kI(i);return!a.externalProductId||!a.externalProductVariantId}).map(i=>i.integrationProductId||i.integrationProduct?.id).filter(i=>!!i))];if(e.length===0)return;const t=await LP(e),n=new Map(t.map(i=>[i.id,i]));for(const i of r){const a=i.integrationProductId||i.integrationProduct?.id;if(!a)continue;const s=n.get(a);s&&(i.integrationProduct={...i.integrationProduct,...s},s.product&&(i.product={...i.product,...s.product}))}},V9=(r,e)=>{for(const t of e){const n=t.parentTransaction?.id;if(!n)continue;const i=r.get(n);if(!i)throw new Error(`SpiffCommerce - Unable to attach product-step extra to parent - parent message not found: ${n}`);const a=t.quantity||1,s=kI(t);if(!s.externalProductId||!s.externalProductVariantId)throw new Error(`SpiffCommerce - Product-step extra is missing external product identifiers (transaction: ${t.id})`);const o=i.designExternalVariants||[];i.designExternalVariants=[...o,...Array.from({length:a},()=>({...s}))]}},z9=async(r,e,t,n,i,a,s,o,l,u)=>{u&&(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),await r.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const c=r.getPreviewService(),f=e?.finalizeStepConfig?.lookAtAnimation,d=c&&e.showModelOnFinishStep&&!!f,h=l&&kE(l,e,!0),g=l&&kE(l,e,!1),v=async R=>{const B={};let j=0;if(Object.keys(a).length>0)for(const G of Object.keys(a)){const ie=a[G],q=e.steps.find(Y=>Y.stepName===G);for(let Y=0;Y<ie.selections.length;++Y){const J=ie.selections[Y];if(q){const ae=await ct.getOptionForStep(q);if(!R||ae&&(ae.variants||[]).length>1&&!q.data.hideSelectionInCart&&!q.data.hideSelectionsInCart){const oe=q.stepTitle;B[oe]?B[oe].push({id:J.id||"",name:J.name,priceModifier:J.priceModifier}):B[oe]=[{id:J.id||"",name:J.name,priceModifier:J.priceModifier}]}}j+=J.priceModifier}}return[B,j]},[y]=await v(!0),A=Object.fromEntries(Object.keys(y).map(R=>[R,y[R].map(B=>B.id)])),[C]=await v(!1),S=Object.fromEntries(Object.keys(C).map(R=>[R,C[R].map(B=>B.id)]));let F=await o(d,i.id);if(F){const R=await(await Ls(F)).blob();F=(await Ln.uploadAsset({name:`${i.id}-preview-image.png`,blob:R},ff.Image,!0,!1)).fileLink}return{designDetails:(()=>{const R={name:s,layouts:t.map(B=>({index:B.index,panelId:B.panelId})),workflowId:e.id,transactionId:i.id,useThreeDimPreview:!!d,previewImage:F};if(g){const B=[];for(const[j,G]of Object.entries(g))B.push({key:j,value:G});R.metadata=B}if(A){const B=[];for(const[j,G]of Object.entries(S))B.push({key:j,ids:G});R.selectedVariants=B}return R})(),cartSelectionsWithPrices:y,cartMetadata:h}},TI=async(r,e)=>{await Promise.all(r.map(async o=>{await o.workflowManager.outstandingRequestsPromise()}));const n=await(async()=>{const o=ze.getShadowGraphqlClient(),l=await Promise.all(r.map(async d=>({id:d.transaction.id,hash:await d.workflowManager.getStateHash()}))),c=fA(l,100),f=[];for(const d of c){const h=await o.query({query:N3,variables:{transactions:d},fetchPolicy:"no-cache",errorPolicy:"all"});if(h.errors&&h.errors.length>0)return l.map(g=>g.id);f.push(...h.data?.transactionConfirmWorkflowStates??[])}return f})(),i=await Promise.all(r.map(async o=>await z9(o.workflowManager,o.workflow,o.layouts,o.getReducerState,o.transaction,o.workflowSelections,o.designName,e??(()=>Promise.resolve(void 0)),o.workflowMetadata,n.includes(o.transaction.id)))),a=r[0].workflowManager.getClient(),s=await M9(i.map(o=>o.designDetails),a);if(!s)throw new Error("Failed to create designs");return s.map((o,l)=>{const u=r[l],c=i[l],f=o.transaction;return N9(f,u.product,u.workflow,c.cartSelectionsWithPrices,o.sku,c.cartMetadata,f.previewImageLink,o.processExecution?.id)})};class $9{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(e){this.designSavedListeners.push(e)}detachSaveListener(e){this.designSavedListeners=this.designSavedListeners.filter(t=>t!==e)}async getSavedDesigns(){if(this.storageMethod==="Local"){const e=wr.get(this.localPersistenceKey);return e?JSON.parse(e):[]}throw new nn("Unexpected storage method requested")}async getSavedDesignByTransaction(e){return(await this.getSavedDesigns()).find(n=>n.transactionId===e)}async addDesign(e){const n=(await this.getSavedDesigns()).filter(i=>i.transactionId!==e.transactionId);n.unshift(e),await this.setDesigns(n),this.designSavedListeners.forEach(i=>i(e))}async renameDesign(e,t){const n=await this.getSavedDesigns(),i=n.find(a=>a.transactionId===e);if(!i)throw new Error(`No saved design for transaction ${e}.`);i.title=t,await this.setDesigns(n)}async removeDesign(e){const t=await this.getSavedDesigns();await this.setDesigns(t.filter(n=>n.transactionId!==e))}async setDesigns(e){if(this.storageMethod==="Local"){wr.set(this.localPersistenceKey,JSON.stringify(e));return}throw new nn("Unexpected storage method requested")}}const Qp=new $9;var Dv,TE;function H9(){if(TE)return Dv;TE=1;var r="Expected a function",e=NaN,t="[object Symbol]",n=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,s=/^0o[0-7]+$/i,o=parseInt,l=typeof di=="object"&&di&&di.Object===Object&&di,u=typeof self=="object"&&self&&self.Object===Object&&self,c=l||u||Function("return this")(),f=Object.prototype,d=f.toString,h=Math.max,g=Math.min,v=function(){return c.Date.now()};function y(E,R,B){var j,G,ie,q,Y,J,ae=0,oe=!1,he=!1,ye=!0;if(typeof E!="function")throw new TypeError(r);R=F(R)||0,A(B)&&(oe=!!B.leading,he="maxWait"in B,ie=he?h(F(B.maxWait)||0,R):ie,ye="trailing"in B?!!B.trailing:ye);function Ue(je){var qe=j,Ge=G;return j=G=void 0,ae=je,q=E.apply(Ge,qe),q}function Re(je){return ae=je,Y=setTimeout(re,R),oe?Ue(je):q}function Oe(je){var qe=je-J,Ge=je-ae,bt=R-qe;return he?g(bt,ie-Ge):bt}function ee(je){var qe=je-J,Ge=je-ae;return J===void 0||qe>=R||qe<0||he&&Ge>=ie}function re(){var je=v();if(ee(je))return fe(je);Y=setTimeout(re,Oe(je))}function fe(je){return Y=void 0,ye&&j?Ue(je):(j=G=void 0,q)}function Be(){Y!==void 0&&clearTimeout(Y),ae=0,j=J=G=Y=void 0}function ke(){return Y===void 0?q:fe(v())}function $e(){var je=v(),qe=ee(je);if(j=arguments,G=this,J=je,qe){if(Y===void 0)return Re(J);if(he)return Y=setTimeout(re,R),Ue(J)}return Y===void 0&&(Y=setTimeout(re,R)),q}return $e.cancel=Be,$e.flush=ke,$e}function A(E){var R=typeof E;return!!E&&(R=="object"||R=="function")}function C(E){return!!E&&typeof E=="object"}function S(E){return typeof E=="symbol"||C(E)&&d.call(E)==t}function F(E){if(typeof E=="number")return E;if(S(E))return e;if(A(E)){var R=typeof E.valueOf=="function"?E.valueOf():E;E=A(R)?R+"":R}if(typeof E!="string")return E===0?E:+E;E=E.replace(n,"");var B=a.test(E);return B||s.test(E)?o(E.slice(2),B?2:8):i.test(E)?e:+E}return Dv=y,Dv}var j9=H9();const FI=Ns(j9),G9=Se`
2694
+ `;function vg(r){const e=JSON.parse(atob(r.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=e}const N9=async(r,e)=>{const t={};try{if(e){const i=await e.loggedInBearerToken();t.Authorization=`Bearer ${i}`}else throw new Error}catch{const s=Object.entries(localStorage).find(([l,u])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",o=localStorage.getItem(s);o&&!vg(o)&&(t.Authorization=`Bearer ${o}`)}return await e.getBetaEnabled()&&(t["X-Spiff-Beta"]="true"),(await ze.getShadowGraphqlClient().mutate({mutation:_9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:r.map(i=>({name:i.name,layouts:i.layouts,workflowId:i.workflowId,transactionId:i.transactionId,previewImage:i.previewImage,useThreeDimPreview:i.useThreeDimPreview,metadata:i.metadata,selectedVariants:i.selectedVariants}))},context:{headers:t}})).data?.designCreateMany},kE=(r,e,t)=>{const n=a=>{const s={};if(a.type==="Frame"){const o=r[a.stepName],l=a.data;if(!o||!o.image||l.hideImageInCart&&t)return s;s[`${a.stepTitle} image`]=o.image}if(a.type==="Illustration"){const o=r[a.stepName],l=a.data;if(!o||l.hideColorsInCart&&t||!o.colors)return s;if(o.colors.length>0){const u=o.colors.join(", ").toUpperCase();s[`${a.stepTitle} colors`]=u}}if(a.type==="Module"){const o=r[a.stepName],l=a.data;if(!o||o.text===void 0||o.text===null||l.hideTextInCart&&t)return s;s[`${a.stepTitle} text`]=o.text}if(a.type==="Text"){const o=r[a.stepName];if(!o)return s;const l=a.data;(!l.hideTextInCart||!t&&o.text!==void 0&&o.text!==null)&&(s[`${a.stepTitle} text`]=o.text),o.color&&(!l.hideColorInCart||!t)&&(s[`${a.stepTitle} color`]=o.color),o.strokeColor&&(!l.hideStrokeInCart||!t)&&(s[`${a.stepTitle} stroke`]=o.strokeColor)}return s},i={};return e.steps.forEach(a=>{Object.assign(i,n(a))}),i},L9=(r,e,t,n)=>{const i={};let a={};n&&(a=n);const o=e.steps.map(l=>l.stepTitle).filter((l,u,c)=>c.indexOf(l)==u);for(const l of o){if(Object.keys(r).includes(l)){const u=r[l],c=e.steps.find(f=>f.stepTitle===l);i[`${c?.stepTitle} selection`]={value:u[0].name,priceModifier:u[0].priceModifier}}for(const u of Object.keys(a))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(u)&&(i[u]={value:a[u],priceModifier:0})}return i},U9=(r,e,t,n,i,a,s,o)=>{const l=e.basePrice||0,u=r.priceModifierTotal||0,c=L9(n,t,void 0,a),d=(wr.getMap("transactionOwnerIds")||new Map).get(r.id),h={additionalExternalProductId:r.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:r.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:r.designExternalVariants,designProductId:r.externalDesignProductId,designProductVariantId:r.externalDesignProductVariantId,event:"onComplete",exportedData:c,externalCartProductId:r.externalCartProductId,externalCartProductVariantId:r.externalCartProductVariantId,lineItemImageUrl:s||"",optionsCost:u,processExecutionId:o,quantity:r.quantity,transactionId:r.id,transactionOwnerId:d,weight:e.weight,workflowViewerLink:r.workflowViewerLink||"",workflowViewerReadOnlyLink:r.workflowViewerReadOnlyLink||""};return a&&(h.metadata=a),n&&(h.selectedVariants=n),i&&(h.sku=i),h},V9=r=>{const e=r.integrationProductId||r.integrationProduct?.id,t=r.integrationProduct;if(t?.externalProductId&&t?.externalVariantId)return t;if(e&&r.product?.integrationProducts){const n=r.product.integrationProducts.find(i=>i.id===e);if(n)return{...t,...n}}return t},kI=r=>{const e=V9(r);return{id:r.id,externalProductId:r.externalCartProductId||r.externalDesignProductId||e?.externalProductId||e?.additionalExternalProductId,externalProductVariantId:r.externalCartProductVariantId||r.externalDesignProductVariantId||e?.externalVariantId||e?.additionalExternalVariantId}},z9=async r=>{const e=[...new Set(r.filter(i=>{const a=kI(i);return!a.externalProductId||!a.externalProductVariantId}).map(i=>i.integrationProductId||i.integrationProduct?.id).filter(i=>!!i))];if(e.length===0)return;const t=await LP(e),n=new Map(t.map(i=>[i.id,i]));for(const i of r){const a=i.integrationProductId||i.integrationProduct?.id;if(!a)continue;const s=n.get(a);s&&(i.integrationProduct={...i.integrationProduct,...s},s.product&&(i.product={...i.product,...s.product}))}},$9=(r,e)=>{for(const t of e){const n=t.parentTransaction?.id;if(!n)continue;const i=r.get(n);if(!i)throw new Error(`SpiffCommerce - Unable to attach product-step extra to parent - parent message not found: ${n}`);const a=t.quantity||1,s=kI(t);if(!s.externalProductId||!s.externalProductVariantId)throw new Error(`SpiffCommerce - Product-step extra is missing external product identifiers (transaction: ${t.id})`);const o=i.designExternalVariants||[];i.designExternalVariants=[...o,...Array.from({length:a},()=>({...s}))]}},H9=async(r,e,t,n,i,a,s,o,l,u)=>{u&&(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),await r.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const c=r.getPreviewService(),f=e?.finalizeStepConfig?.lookAtAnimation,d=c&&e.showModelOnFinishStep&&!!f,h=l&&kE(l,e,!0),g=l&&kE(l,e,!1),v=async R=>{const B={};let j=0;if(Object.keys(a).length>0)for(const G of Object.keys(a)){const ie=a[G],q=e.steps.find(Y=>Y.stepName===G);for(let Y=0;Y<ie.selections.length;++Y){const J=ie.selections[Y];if(q){const ae=await ct.getOptionForStep(q);if(!R||ae&&(ae.variants||[]).length>1&&!q.data.hideSelectionInCart&&!q.data.hideSelectionsInCart){const oe=q.stepTitle;B[oe]?B[oe].push({id:J.id||"",name:J.name,priceModifier:J.priceModifier}):B[oe]=[{id:J.id||"",name:J.name,priceModifier:J.priceModifier}]}}j+=J.priceModifier}}return[B,j]},[y]=await v(!0),A=Object.fromEntries(Object.keys(y).map(R=>[R,y[R].map(B=>B.id)])),[C]=await v(!1),S=Object.fromEntries(Object.keys(C).map(R=>[R,C[R].map(B=>B.id)]));let F=await o(d,i.id);if(F){const R=await(await Ls(F)).blob();F=(await Ln.uploadAsset({name:`${i.id}-preview-image.png`,blob:R},ff.Image,!0,!1)).fileLink}return{designDetails:(()=>{const R={name:s,layouts:t.map(B=>({index:B.index,panelId:B.panelId})),workflowId:e.id,transactionId:i.id,useThreeDimPreview:!!d,previewImage:F};if(g){const B=[];for(const[j,G]of Object.entries(g))B.push({key:j,value:G});R.metadata=B}if(A){const B=[];for(const[j,G]of Object.entries(S))B.push({key:j,ids:G});R.selectedVariants=B}return R})(),cartSelectionsWithPrices:y,cartMetadata:h}},TI=async(r,e)=>{await Promise.all(r.map(async o=>{await o.workflowManager.outstandingRequestsPromise()}));const n=await(async()=>{const o=ze.getShadowGraphqlClient(),l=await Promise.all(r.map(async d=>({id:d.transaction.id,hash:await d.workflowManager.getStateHash()}))),c=fA(l,100),f=[];for(const d of c){const h=await o.query({query:N3,variables:{transactions:d},fetchPolicy:"no-cache",errorPolicy:"all"});if(h.errors&&h.errors.length>0)return l.map(g=>g.id);f.push(...h.data?.transactionConfirmWorkflowStates??[])}return f})(),i=await Promise.all(r.map(async o=>await H9(o.workflowManager,o.workflow,o.layouts,o.getReducerState,o.transaction,o.workflowSelections,o.designName,e??(()=>Promise.resolve(void 0)),o.workflowMetadata,n.includes(o.transaction.id)))),a=r[0].workflowManager.getClient(),s=await N9(i.map(o=>o.designDetails),a);if(!s)throw new Error("Failed to create designs");return s.map((o,l)=>{const u=r[l],c=i[l],f=o.transaction;return U9(f,u.product,u.workflow,c.cartSelectionsWithPrices,o.sku,c.cartMetadata,f.previewImageLink,o.processExecution?.id)})};class j9{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(e){this.designSavedListeners.push(e)}detachSaveListener(e){this.designSavedListeners=this.designSavedListeners.filter(t=>t!==e)}async getSavedDesigns(){if(this.storageMethod==="Local"){const e=wr.get(this.localPersistenceKey);return e?JSON.parse(e):[]}throw new nn("Unexpected storage method requested")}async getSavedDesignByTransaction(e){return(await this.getSavedDesigns()).find(n=>n.transactionId===e)}async addDesign(e){const n=(await this.getSavedDesigns()).filter(i=>i.transactionId!==e.transactionId);n.unshift(e),await this.setDesigns(n),this.designSavedListeners.forEach(i=>i(e))}async renameDesign(e,t){const n=await this.getSavedDesigns(),i=n.find(a=>a.transactionId===e);if(!i)throw new Error(`No saved design for transaction ${e}.`);i.title=t,await this.setDesigns(n)}async removeDesign(e){const t=await this.getSavedDesigns();await this.setDesigns(t.filter(n=>n.transactionId!==e))}async setDesigns(e){if(this.storageMethod==="Local"){wr.set(this.localPersistenceKey,JSON.stringify(e));return}throw new nn("Unexpected storage method requested")}}const Qp=new j9;var Dv,TE;function G9(){if(TE)return Dv;TE=1;var r="Expected a function",e=NaN,t="[object Symbol]",n=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,s=/^0o[0-7]+$/i,o=parseInt,l=typeof di=="object"&&di&&di.Object===Object&&di,u=typeof self=="object"&&self&&self.Object===Object&&self,c=l||u||Function("return this")(),f=Object.prototype,d=f.toString,h=Math.max,g=Math.min,v=function(){return c.Date.now()};function y(E,R,B){var j,G,ie,q,Y,J,ae=0,oe=!1,he=!1,ye=!0;if(typeof E!="function")throw new TypeError(r);R=F(R)||0,A(B)&&(oe=!!B.leading,he="maxWait"in B,ie=he?h(F(B.maxWait)||0,R):ie,ye="trailing"in B?!!B.trailing:ye);function Ue(je){var qe=j,Ge=G;return j=G=void 0,ae=je,q=E.apply(Ge,qe),q}function Re(je){return ae=je,Y=setTimeout(re,R),oe?Ue(je):q}function Oe(je){var qe=je-J,Ge=je-ae,bt=R-qe;return he?g(bt,ie-Ge):bt}function ee(je){var qe=je-J,Ge=je-ae;return J===void 0||qe>=R||qe<0||he&&Ge>=ie}function re(){var je=v();if(ee(je))return fe(je);Y=setTimeout(re,Oe(je))}function fe(je){return Y=void 0,ye&&j?Ue(je):(j=G=void 0,q)}function Be(){Y!==void 0&&clearTimeout(Y),ae=0,j=J=G=Y=void 0}function ke(){return Y===void 0?q:fe(v())}function $e(){var je=v(),qe=ee(je);if(j=arguments,G=this,J=je,qe){if(Y===void 0)return Re(J);if(he)return Y=setTimeout(re,R),Ue(J)}return Y===void 0&&(Y=setTimeout(re,R)),q}return $e.cancel=Be,$e.flush=ke,$e}function A(E){var R=typeof E;return!!E&&(R=="object"||R=="function")}function C(E){return!!E&&typeof E=="object"}function S(E){return typeof E=="symbol"||C(E)&&d.call(E)==t}function F(E){if(typeof E=="number")return E;if(S(E))return e;if(A(E)){var R=typeof E.valueOf=="function"?E.valueOf():E;E=A(R)?R+"":R}if(typeof E!="string")return E===0?E:+E;E=E.replace(n,"");var B=a.test(E);return B||s.test(E)?o(E.slice(2),B?2:8):i.test(E)?e:+E}return Dv=y,Dv}var q9=G9();const FI=Ns(q9),W9=Se`
2695
2695
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
2696
2696
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
2697
2697
  id
@@ -2705,7 +2705,7 @@ Minimum version required to store current data is: `+q+`.
2705
2705
  }
2706
2706
  }
2707
2707
  }
2708
- `,q9=Se`
2708
+ `,Q9=Se`
2709
2709
  mutation AddStakeholderToAllTransactions($ids: [String!]!, $type: String!, $details: CustomerDetailsInput!) {
2710
2710
  transactionsAddStakeholder(ids: $ids, details: $details, type: $type) {
2711
2711
  id
@@ -2719,7 +2719,7 @@ Minimum version required to store current data is: `+q+`.
2719
2719
  }
2720
2720
  }
2721
2721
  }
2722
- `,W9=Se`
2722
+ `,Y9=Se`
2723
2723
  mutation AddAddressToTransaction(
2724
2724
  $transactionId: String!
2725
2725
  $streetAddress: String
@@ -2741,7 +2741,7 @@ Minimum version required to store current data is: `+q+`.
2741
2741
  id
2742
2742
  }
2743
2743
  }
2744
- `,Q9=Se`
2744
+ `,X9=Se`
2745
2745
  mutation AddOrganizationToTransaction($transactionId: String!, $organizationName: String!) {
2746
2746
  organizationAttachToTransaction(transactionId: $transactionId, organizationName: $organizationName) {
2747
2747
  id
@@ -2831,7 +2831,7 @@ Minimum version required to store current data is: `+q+`.
2831
2831
  }
2832
2832
  }
2833
2833
  }
2834
- `;var yg=(r=>(r.PriceBreakChanged="PriceBreakChanged",r.ProductChanged="ProductChanged",r.QuantityChanged="QuantityChanged",r.RecipientChanged="RecipientChanged",r.SelectionChanged="SelectionChanged",r))(yg||{});class B1{constructor(e,t){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=FI(async()=>{await Qp.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async n=>new Promise((i,a)=>{try{n.toBlob(s=>{if(s){const o=URL.createObjectURL(s);i(o)}})}catch(s){a(s)}}),this.client=e,this.transaction=t.transaction,this.workflow=t.workflow,this.profanityList=this.transaction.product?.profanities?.map(n=>n.word)||[],this.isReadOnly=t.transaction.isOrdered||!!t.readOnly,this.graphQlClient=t.graphQlClient,this.workflowManager=new dA(this,e,n=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return t.stateMutationFunc(n)},t.graphQlClient,t.reloadedState,t.readOnly,t.modelContainer,t.isReloadedTransaction,t.singleVariantsRenderable,t.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(n=>{const i=n.traversableScenes.map(a=>{const s=a.renderableSteps.map(o=>o.stepName);return{id:a.name,title:a.title,renderableSteps:s,workflowScene:a}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(a=>a(i)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(e){this.workflow=void 0;const t=await this.graphQlClient().mutate({mutation:FE,variables:{id:this.getTransaction().id,integrationProductId:e}}),n=t.data?.transactionUpdateIntegrationProduct.product;if(!n)throw new nn("Failed to set product. No product returned from server.");if(!this.bundle)throw new nn("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...t.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...t.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const i=(await this.bundle.getProductCollection().fetchProducts()).find(a=>a.getId()===n.id);try{const a=i?.getDefaultWorkflow();if(a){const s=await NP(a.getId());await this.setWorkflow(s),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new nn("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:FE,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(e){return this.workflow=e,await this.graphQlClient().mutate({mutation:O3,variables:{id:this.getTransaction().id,workflowId:e.id}}),this.workflowManager.setWorkflow(e)}async attachAddress(e,t,n,i,a,s){await this.graphQlClient().mutate({mutation:W9,variables:{transactionId:this.getTransaction().id,streetAddress:e||void 0,apartment:t||void 0,city:n||void 0,country:i||void 0,state:a||void 0,postCode:s||void 0}})}async attachOrganization(e){await this.graphQlClient().mutate({mutation:Q9,variables:{transactionId:this.getTransaction().id,organizationName:e}})}getBundle(){return this.bundle}setBundle(e){this.bundle=e}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(e,t){const n=this.getWorkflow(),i=n?.finalizeStepConfig?.lookAtAnimation;if(!n)throw new Error("Failed to generate cart preview image! No workflow is set.");if(e){if(!i)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(t??512,i)||""}let a=2048;t&&t<=2048&&(a=t);const s=Eo(a,a),o=this.workflowManager.getCommandContext().getAllLayouts(),l=n.defaultPreviewPanelIndex||0,u=n.panels[l],c=o.find(S=>S.layoutState?.layout.panelId===u?.name)||o[0],f=c.layoutState.layout.previewRegion?{x:c.layoutState.layout.previewRegion.left,y:c.layoutState.layout.previewRegion.top,width:c.layoutState.layout.previewRegion.width,height:c.layoutState.layout.previewRegion.height}:{x:0,y:0,width:c.layoutState.layout.width,height:c.layoutState.layout.height},d=this.workflowManager.getCommandContext().getLayoutById(c.layoutState.layout.id),h=s.getContext("2d");if(!h)throw new _g("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),v=Qg(d.layoutState.layout,d.layoutState.elements,{renderingConfiguration:{purpose:Ku.Print,region:{left:f.x,top:f.y,width:f.width,height:f.height},templatingContext:g}}),y=qk(v);await(await uo.from(h,y,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:Eo,createImage:Mf,DOMParser:QA(),fetch})).render();const C=await this.getCanvasObjectURLAsync(s);return s.toDataURL(C)}getStepById(e){const t=this.getWorkflow()?.steps.find(a=>a.stepName===e);if(!t||!this.stepHasHandle(t))return;const n=this.cachedStepHandles.get(t.stepName);if(n)return n;const i=Ep.get(this.getWorkflowManager(),t);return this.cachedStepHandles.set(t.stepName,i),i}getSteps(){return this.getScenes().flatMap(e=>this.getStepsByScene(e))}async getStepsConditionallyActive(){const e=this.getScenes();return(await Promise.all(e.map(async n=>{const i=this.getStepsByScene(n),a=await Promise.all(i.map(s=>co(s.getRaw(),this.getWorkflowManager().getStepSelections())));return i.filter((s,o)=>a[o])}))).flat()}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(t=>({id:t.id,name:t.name,stepIds:t.stepNames}))}getSelectionPriceSubunits(e){const t=this.getWorkflowManager().getWorkflowSelections();let n=0;return Object.values(t).forEach(i=>{n+=i.selections.reduce((a,s)=>a+(s.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(n,e)}getBasePriceSubunits(e,t){const n=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,t);if(e){const i=this.getAdditionalProductPriceSubunits(t)||0;return n+i}return n}getAdditionalProductPriceSubunits(e){const t=this.getTransaction().integrationProduct;if(t?.additionalIntegrationProduct?.product){const n=t.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(n,e)}}getTotalPriceSubunits(e){return this.getBasePriceSubunits(!1,e)+this.getSelectionPriceSubunits(e)}getPriceSubUnitsAfterPriceBreaks(e,t){const n=t?1:this.priceBreakToBeApplied(),i=e*n;return Math.ceil(i)}priceBreakToBeApplied(){const e=(this.getProduct()?.priceBreaks||[]).sort((i,a)=>-(i.minQty-a.minQty)),n=[...this.getMatchingExperiencesFromBundle(),this].reduce((i,a)=>i+a.getQuantity(),0);for(const i of e)if(i.minQty<=n)return i.percentage;return 1}checkForPriceBreakChanges(){const e=this.priceBreakToBeApplied();this.currentPriceBreak!==e&&(this.updatePriceBreak(e),this.getMatchingExperiencesFromBundle().forEach(t=>t.updatePriceBreak(e)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(e=>{const t=e.getTransaction().id,n=this.getTransaction().id,i=e.getProduct()?.id,a=this.getProduct()?.id;return t!==n&&i===a})}updatePriceBreak(e){this.currentPriceBreak=e,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(e,t,n){const i=await e.getGlobalProperties(),a=n?.map(u=>u.getId()),s=this.getSteps().filter(u=>a===void 0||a.includes(u.getId())),o=t.getSteps(),l=u=>i.find(c=>c.getRawProperty().name===u.aspectName);s.forEach(u=>{const c=new Set,f=u.getRaw().globalPropertyAspectConfigurations;f!==void 0&&(f.forEach(d=>c.add(JSON.stringify(d))),o.forEach(d=>{const h=d.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const v=l(g),y=c.has(JSON.stringify(g));if(y&&v?.getType()==="Option"){const A=d.getCurrentVariant();if(!A)return;u.selectVariant(A),c.delete(JSON.stringify(g))}else if(y&&v?.getType()==="Text"){const A=d.getText();u.setText(A),c.delete(JSON.stringify(g))}})}))})}getStepByName(e){const t=this.getWorkflow()?.steps.find(n=>n.stepTitle===e);if(!(!t||!this.stepHasHandle(t)))return Ep.get(this.getWorkflowManager(),t)}getStepsByType(e){return this.getWorkflow()?.steps.filter(t=>t.type===e).map(t=>Ep.get(this.getWorkflowManager(),t))||[]}getStepsByScene(e){const t=this.getWorkflow();if(!t?.stepGroups.find(i=>i.name===e.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return e.stepIds.map(i=>t.steps.find(a=>a.stepName===i)).filter(i=>!!i&&this.stepHasHandle(i)).map(i=>Ep.get(this.getWorkflowManager(),i))}async attachCustomerDetails(e){return this.assignCustomerDetails({emailAddress:e.email})}async assignCustomerDetails(e){const n=(await this.graphQlClient().mutate({mutation:G9,variables:{id:this.getTransaction().id,details:e,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(i=>i.customer?.emailAddress===e.emailAddress);n?.customer&&this.assignCustomerInternal(n.customer)}assignCustomerInternal(e){this.getWorkflowManager().setTransactionCustomer(e);const t=wr.getMap("transactionCustomerIds")||new Map;t.set(this.getTransaction().id,e.id),wr.setMap("transactionCustomerIds",t)}attachRenderableSceneListener(e){this.renderableSceneCallbacks.push(e),e(this.renderableScenes)}detachRenderableSceneListener(e){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(t=>t!==e)}async save(e){const t=this.getProduct(),n=this.getWorkflow(),i=this.getCommandContext().getState();if(!t)throw new nn("Product undefined!");if(!n)throw new nn("Workflow undefined!");if(!i)throw new nn("State undefined!");const s={title:await(async()=>{if(e)return e;const o=this.getTransaction().id,u=(await Qp.getSavedDesigns()).find(c=>c.transactionId===o)?.title;return u||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:t.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:n.name,workflowId:n.id,lastEdited:new Date};return await Qp.addDesign(s),s}async copy(){const e=mo(this.getCommandContext().getState());if(!e)throw new nn("Internal state is undefined! Cannot copy experience!");const t=JSON.stringify(e.transaction),n=this.getWorkflow();if(!n)throw new nn("Workflow is undefined! Cannot copy experience!");const i=this.getTransaction().integrationProduct?.id;if(!i)throw new nn("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:i,workflowId:n.id,workflowState:t})}async onDesignFinished(e=!0){const t=this.getTransaction(),n=this.getProduct(),i=this.getWorkflow();if(!n)throw new nn("Product undefined! Cannot finish an experience without a product.");if(!i)throw new nn("Workflow undefined! Cannot finish an experience without a workflow.");if(t.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:t.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const a=await TI([{workflowManager:this.workflowManager,workflow:i,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:n,transaction:t,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:i.name}],s=>e?this.createPreviewImage(s,1024):Promise.resolve(void 0));return t.completed&&await this.graphQlClient().mutate({mutation:z3,variables:{transactionId:t.id}}),a[0]}stepHasHandle(e){return e.type!==Xe.SilentIllustration&&e.type!==Xe.ProductOverlay}async getExportedStepData(){const e=this.getWorkflow(),t=this.getWorkflowManager().getWorkflowMetadata(),n=this.getWorkflowManager().getWorkflowSelections(),i=[];for(const a of e?.steps||[]){const s=a.stepName,o=t[s],l=n[s]?.selections[0],u={stepId:s,title:a.stepTitle,properties:[]};if(l&&await X9(a,n)&&u.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!o){i.push(u);continue}switch(a.type){case Xe.Frame:{const c=a.data,f=o;f.image&&c.displayImageOnFinishStep&&u.properties.push({type:"image",value:f.image,priceModifier:0})}break;case Xe.Illustration:{const c=a.data,f=o;if(f&&f.colors&&f.colors.length>0&&c.displayColorsOnFinishStep){const d=f.colors.join(", ").toUpperCase();u.properties.push({type:"color",value:d,priceModifier:0})}}break;case Xe.Module:{const c=a.data,f=o;f&&f.text&&c.displayTextOnFinishStep&&u.properties.push({type:"text",value:f.text,priceModifier:0})}break;case Xe.Text:{const c=a.data,f=o;f&&f.text&&c.displayTextOnFinishStep&&u.properties.push({type:"text",value:f.text,priceModifier:0}),f&&f.color&&c.displayColorOnFinishStep&&u.properties.push({type:"color",value:f.color,priceModifier:0})}}i.push(u)}return i.filter(a=>a.properties&&a.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(e){if(e<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getTransaction().quantity=e,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const t=this.getTransaction();await this.graphQlClient().mutate({mutation:R3,variables:{id:t.id,quantity:e}})}addEventListener(e,t){const n=this.eventCallbacks.get(e)||[];n.push(t),this.eventCallbacks.set(e,n)}removeEventListener(e,t){const n=this.eventCallbacks.get(e)||[];this.eventCallbacks.set(e,n.filter(i=>i!==t))}callEvent(e){(this.eventCallbacks.get(e)||[]).forEach(t=>t(this))}}const Y9=r=>{if([Xe.Question,Xe.Frame,Xe.Illustration,Xe.Material,Xe.Model,Xe.Picture,Xe.Shape,Xe.Text].includes(r.type)){const t=r.data;return!!t.displaySelectionOnFinishStep||!!t.displaySelectionsOnFinishStep}return!1},X9=async(r,e)=>{if(!Y9(r))return!1;const t=await ct.getOptionForStep(r);if(t&&(t.variants||[]).length>1){const n=e[r.stepName];return!!(n&&n.selections.length>0)}return!1};class J9{constructor(e){this.handleCache={},this.bundle=e}async getHandle(e){if(this.handleCache[e.name])return this.handleCache[e.name];const t=await this.createHandle(e);return this.handleCache[e.name]=t,t}async getHandles(){if(!this.bundle.getGlobalPropertyConfiguration())return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const e=this.bundle.getGlobalPropertyConfiguration();return e?Promise.all(e.aspects.map(t=>this.getHandle(t))):[]}applyConditionsFromState(e,t){return t?e.filter(n=>this.aspectConditionsSatisfied(n.getRawProperty(),t)):e}aspectConditionsSatisfied(e,t){return!e.conditions||e.conditions.length===0?!0:(e.conditionMode===Mk.AND?Array.prototype.every.bind(e.conditions):Array.prototype.some.bind(e.conditions))(i=>{const a=t.aspects.find(s=>s.name===i.targetAspectName);return a?i.requiredVariantSelections.some(s=>s===a.value):!1})}async createHandle(e){switch(e.type){case Hn.FileUpload:return new II(this.bundle,e).initialize();case Hn.ColorOption:return new hA(this.bundle,e,e.entityId?await ct.getOption(e.entityId):void 0);case Hn.Option:{const t=e.entityId?await ct.getOption(e.entityId):void 0;return t?.type==="Color"?new hA(this.bundle,e,t):new M1(this.bundle,e,t)}case Hn.Text:return new PI(this.bundle,e);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Jg{constructor(e,t){this.bundle=e,this.property=t}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}isSilent(){return!!this.property.silent||this.bundle.getGlobalPropertyStateManager().getAspectHidden(this.property.name)}async getSharedSteps(e){const t=e??this.bundle.getWorkflowExperiences();return(await Promise.all(t.map(a=>a.getStepsConditionallyActive()))).map(a=>a.filter(s=>s.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:s.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getGlobalPropertyConfiguration()?.id&&o.aspectName===this.property.name))).flat()}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class II extends Jg{constructor(e,t){super(e,t)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await ct.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const e=await this.getImage();if(e?.fileLink)if(e?.fileLink.endsWith(".svg")){const t=await ra(e?.fileLink),n=await x1(e?.fileLink),i=n.width,a=n.height,s=await Pa(t);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(u=>{s.colors[u.key]={browserValue:u.browserValue,pmsValue:u.pmsValue}});const l={src:e?.fileLink,width:i,height:a,aspect:i/a,svg:s.svg,colors:s.colors};Ds.set(e?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(e){const t=this.bundle.getGlobalPropertyStateManager();await Promise.all([t.setAspect(this.property.name,e.key,{...t.getAspectStorage(this.property.name)||{},originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(e),this.loadImageData()])}async canUseAdvancedImageManipulation(){return this.bundle.getClient().canUseAddon(Bg.AdvancedImageManipulation)}async removeBackgroundFromImage(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Advanced Image Manipulation addon. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImage();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const n=this.bundle.getGlobalPropertyStateManager(),i=await Ln.removeBackgroundFromAsset(t),s={...n.getAspectStorage(this.property.name),backgroundRemovedAssetKey:i.key,useOriginalAsset:!e},l=[e?n.setAspect(this.property.name,i.key,s):n.setAspectStorage(this.property.name,s)];return e&&(l.push(this.applyImageSelection(i,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),i}async vectorizeImage(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Advanced Image Manipulation addon. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImage();if(!t)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=this.bundle.getGlobalPropertyStateManager(),i=await Ln.vectorizeAsset(t),s={...n.getAspectStorage(this.property.name),vectorizedAssetKey:i.key,useOriginalAsset:!e},l=[e?n.setAspect(this.property.name,i.key,s):n.setAspectStorage(this.property.name,s)];return e&&(l.push(this.applyImageSelection(i,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),i}hasImage(){return!!this.getStateValue()}async getImage(){const e=this.getStateValue();if(e)return Ln.getLocalOrFromServer(e)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Ug(zg(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(e?.originalAssetKey)return Ln.getLocalOrFromServer(e.originalAssetKey)}async getBackgroundRemovedImage(){const e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(e?.backgroundRemovedAssetKey)return Ln.getLocalOrFromServer(e.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(e){const t=await this.getOriginalImage();if(!t)throw new Error("You must select an image before calling setUseOriginalImage");const n=this.bundle.getGlobalPropertyStateManager(),i=n.getAspectStorage(this.property.name);if(i?.useOriginalAsset===e)return;const a={...i,useOriginalAsset:e},s=e?i?.originalAssetKey:i?.backgroundRemovedAssetKey,o=[n.setAspect(this.property.name,s||"",a)];if(e)o.push(this.applyImageSelection(t,void 0,!1,!1));else{const l=async()=>{const u=await this.getBackgroundRemovedImage();if(!u)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(u,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(a)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return;const n=await Ln.getLocalOrFromServer(t);if(!n)return;await this.applyImageSelection(n,e,!1,!0);const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(i){if(this.updateSharedStepStorage({...i}),i.colors){const a=new Map(i.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);await Promise.all((await this.getSharedSteps(e)).map(async s=>{await s.changeColors(a)}))}}else this.updateSharedStepStorage({originalAssetKey:t}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:t})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(e=>({fill:e.color,stroke:e.color,variant:e,pmsValue:e.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await Pa(this.imageData.svg)).colors:void 0}async changeColors(e){if(!this.imageData?.svg)return;const t=this.getSharedSteps(),n=new Map(Object.entries(e));await Promise.all((await t).map(async a=>{await a.changeColors(n)}));const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...i,colors:Object.entries(e).map(([a,s])=>({key:a,browserValue:s.browserValue,pmsValue:s.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(e,t,n=!0,i=!0){const s=(await this.getSharedSteps(t)).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(e,n,i)});await Promise.all(s)}updateSharedStepStorage(e){this.bundle.getWorkflowExperiences().forEach(n=>n.getSteps().forEach(i=>{if(i.getOverrideGlobalPropertyConfiguration(this.property.type))return;i.getRaw().globalPropertyAspectConfigurations?.some(s=>s.globalPropertyConfigurationId===this.bundle.getGlobalPropertyConfiguration()?.id&&s.aspectName===this.property.name)&&n.getWorkflowManager().updateStorage(i.getId(),{framePatternData:{originalAssetKey:e.originalAssetKey,backgroundRemovedAssetKey:e.backgroundRemovedAssetKey,useOriginalAsset:e.useOriginalAsset}})}))}}class PI extends Jg{constructor(e,t){super(e,t)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const e=this.getStateValue();return e||""}async setText(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e,void 0,void 0),this.applyTextSelection(e)])}async applyGlobalState(e){const t=this.getStateValue();if(!t)return Promise.resolve();await this.applyTextSelection(t,e)}async applyTextSelection(e,t){const i=(await this.getSharedSteps(t)).map(a=>{a.setText(e)});await Promise.all(i)}}class M1 extends Jg{constructor(e,t,n){super(e,t),this.optionResource=n}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const e=await ct.getOption(this.property.entityId);return e&&(this.optionResource=e),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const e=this.optionResource?.variants?.find(t=>t.id===this.optionResource?.defaultVariant?.id);e&&await this.selectVariant(new Fa(e))}getCurrentVariant(){if(!this.optionResource)return;const e=this.getStateValue();if(e){const t=this.optionResource.variants?.find(n=>n.id===e);return t?new Fa(t):void 0}else{const t=this.optionResource.variants?.find(n=>n.id===this.optionResource?.defaultVariant?.id);return t?new Fa(t):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(t=>t.enabled)||[]).map(t=>new Fa(t))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(t=>new Fa(t))}async selectVariant(e,t){await this.applyVariantSelection(e),await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.getId(),void 0,t)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return;await this.ensureOptionLoaded();const n=this.optionResource?.variants?.find(i=>i.id===t);if(n)return this.applyVariantSelection(new Fa(n),e)}async applyVariantSelection(e,t){const i=(await this.getSharedSteps(t)).map(a=>a.selectVariant(e));await Promise.all(i)}}class hA extends M1{constructor(e,t,n){super(e,t,n)}async selectVariant(e,t){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.getId(),void 0,t),await this.applyColorVariant(e,void 0,t)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return;await this.ensureOptionLoaded();const n=this.optionResource?.variants?.find(a=>a.id===t);if(!n)return;await this.applyColorVariant(new Fa(n),e);const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;i&&await this.setCustomColor(i)}async applyColorVariant(e,t,n){const a=(await this.getSharedSteps(t)).map(s=>{switch(s.getType()){case Xe.Shape:return s.selectVariant(e);case Xe.Text:return s.setFillColor({fill:e.getColor(),stroke:e.getColor(),variant:e.getResource()});case Xe.Illustration:return s.setColor(n?.toString()||"",e.getColor()||"")}});await Promise.all(a)}async setCustomColor(e){const t=this.getCurrentVariant()?.getColor();t&&t.toLowerCase()==="#custom"&&(await this.getSharedSteps()).forEach(i=>i.setCustomColor(e)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:e})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const K9=(r,e,t)=>{const n=r.getWorkflowExperiences(),i=r.getGlobalPropertyConfiguration();return i?n.flatMap(s=>s.getSteps()).filter(s=>s.getGlobalPropertyAspects(i.id).includes(e)&&s.getType()===t):[]},DI=(r,e)=>{const n=K9(r,e,Xe.Illustration).map(i=>{if(!i.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const s=i.getColors();return s?Object.getOwnPropertyNames(s).length:0});return Math.max(...n)};var Ud={exports:{}};Ud.exports;var IE;function Z9(){return IE||(IE=1,(function(r,e){var t=200,n="Expected a function",i="__lodash_hash_undefined__",a=500,s=1,o=2,l=4,u=800,c=16,f=9007199254740991,d="[object Arguments]",h="[object Array]",g="[object AsyncFunction]",v="[object Boolean]",y="[object Date]",A="[object Error]",C="[object Function]",S="[object GeneratorFunction]",F="[object Map]",E="[object Number]",R="[object Null]",B="[object Object]",j="[object Promise]",G="[object Proxy]",ie="[object RegExp]",q="[object Set]",Y="[object String]",J="[object Symbol]",ae="[object Undefined]",oe="[object WeakMap]",he="[object ArrayBuffer]",ye="[object DataView]",Ue="[object Float32Array]",Re="[object Float64Array]",Oe="[object Int8Array]",ee="[object Int16Array]",re="[object Int32Array]",fe="[object Uint8Array]",Be="[object Uint8ClampedArray]",ke="[object Uint16Array]",$e="[object Uint32Array]",je=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,qe=/^\w*$/,Ge=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,bt=/[\\^$.*+?()[\]{}|]/g,rr=/\\(\\)?/g,Dr=/\w*$/,Gt=/^\[object .+?Constructor\]$/,ar=/^(?:0|[1-9]\d*)$/,St={};St[Ue]=St[Re]=St[Oe]=St[ee]=St[re]=St[fe]=St[Be]=St[ke]=St[$e]=!0,St[d]=St[h]=St[he]=St[v]=St[ye]=St[y]=St[A]=St[C]=St[F]=St[E]=St[B]=St[ie]=St[q]=St[Y]=St[oe]=!1;var st={};st[d]=st[h]=st[he]=st[ye]=st[v]=st[y]=st[Ue]=st[Re]=st[Oe]=st[ee]=st[re]=st[F]=st[E]=st[B]=st[ie]=st[q]=st[Y]=st[J]=st[fe]=st[Be]=st[ke]=st[$e]=!0,st[A]=st[C]=st[oe]=!1;var Qr=typeof di=="object"&&di&&di.Object===Object&&di,Sr=typeof self=="object"&&self&&self.Object===Object&&self,gr=Qr||Sr||Function("return this")(),nr=e&&!e.nodeType&&e,dr=nr&&!0&&r&&!r.nodeType&&r,Yt=dr&&dr.exports===nr,Xt=Yt&&Qr.process,mt=(function(){try{var L=dr&&dr.require&&dr.require("util").types;return L||Xt&&Xt.binding&&Xt.binding("util")}catch{}})(),Cr=mt&&mt.isMap,sn=mt&&mt.isSet,_r=mt&&mt.isTypedArray;function ir(L,te,le){switch(le.length){case 0:return L.call(te);case 1:return L.call(te,le[0]);case 2:return L.call(te,le[0],le[1]);case 3:return L.call(te,le[0],le[1],le[2])}return L.apply(te,le)}function Yr(L,te){for(var le=-1,Ve=L==null?0:L.length;++le<Ve&&te(L[le],le,L)!==!1;);return L}function kr(L,te){for(var le=-1,Ve=L==null?0:L.length,pt=0,_t=[];++le<Ve;){var Wr=L[le];te(Wr,le,L)&&(_t[pt++]=Wr)}return _t}function Zr(L,te){for(var le=-1,Ve=L==null?0:L.length,pt=Array(Ve);++le<Ve;)pt[le]=te(L[le],le,L);return pt}function Vr(L,te){for(var le=-1,Ve=te.length,pt=L.length;++le<Ve;)L[pt+le]=te[le];return L}function pn(L,te){for(var le=-1,Ve=Array(L);++le<L;)Ve[le]=te(le);return Ve}function gn(L){return function(te){return L(te)}}function Tr(L,te){return L?.[te]}function zr(L,te){return function(le){return L(te(le))}}var en=Array.prototype,$r=Function.prototype,zt=Object.prototype,sr=gr["__core-js_shared__"],Er=$r.toString,tt=zt.hasOwnProperty,Nr=(function(){var L=/[^.]+$/.exec(sr&&sr.keys&&sr.keys.IE_PROTO||"");return L?"Symbol(src)_1."+L:""})(),Xr=zt.toString,Ee=Er.call(Object),D=RegExp("^"+Er.call(tt).replace(bt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),U=Yt?gr.Buffer:void 0,X=gr.Symbol,ue=gr.Uint8Array;U&&U.allocUnsafe;var Fe=zr(Object.getPrototypeOf,Object),We=zt.propertyIsEnumerable,wt=en.splice,Dt=X?X.isConcatSpreadable:void 0,Nt=X?X.toStringTag:void 0,or=(function(){try{var L=Ut(Object,"defineProperty");return L({},"",{}),L}catch{}})(),Lt=Object.getOwnPropertySymbols,K=U?U.isBuffer:void 0,Ie=Math.max,Qe=Date.now,Ye=Ut(gr,"DataView"),xt=Ut(gr,"Map"),ft=Ut(gr,"Promise"),Rt=Ut(gr,"Set"),Et=Ut(gr,"WeakMap"),hr=Ut(Object,"create"),tr=hi(Ye),fr=hi(xt),$t=hi(ft),Bn=hi(Rt),In=hi(Et),mr=X?X.prototype:void 0,xr=mr?mr.valueOf:void 0,wn=mr?mr.toString:void 0;function Rr(L){var te=-1,le=L==null?0:L.length;for(this.clear();++te<le;){var Ve=L[te];this.set(Ve[0],Ve[1])}}function Gn(){this.__data__=hr?hr(null):{},this.size=0}function Cn(L){var te=this.has(L)&&delete this.__data__[L];return this.size-=te?1:0,te}function Hr(L){var te=this.__data__;if(hr){var le=te[L];return le===i?void 0:le}return tt.call(te,L)?te[L]:void 0}function xn(L){var te=this.__data__;return hr?te[L]!==void 0:tt.call(te,L)}function cn(L,te){var le=this.__data__;return this.size+=this.has(L)?0:1,le[L]=hr&&te===void 0?i:te,this}Rr.prototype.clear=Gn,Rr.prototype.delete=Cn,Rr.prototype.get=Hr,Rr.prototype.has=xn,Rr.prototype.set=cn;function tn(L){var te=-1,le=L==null?0:L.length;for(this.clear();++te<le;){var Ve=L[te];this.set(Ve[0],Ve[1])}}function Jn(){this.__data__=[],this.size=0}function si(L){var te=this.__data__,le=Jt(te,L);if(le<0)return!1;var Ve=te.length-1;return le==Ve?te.pop():wt.call(te,le,1),--this.size,!0}function Sn(L){var te=this.__data__,le=Jt(te,L);return le<0?void 0:te[le][1]}function mn(L){return Jt(this.__data__,L)>-1}function on(L,te){var le=this.__data__,Ve=Jt(le,L);return Ve<0?(++this.size,le.push([L,te])):le[Ve][1]=te,this}tn.prototype.clear=Jn,tn.prototype.delete=si,tn.prototype.get=Sn,tn.prototype.has=mn,tn.prototype.set=on;function rn(L){var te=-1,le=L==null?0:L.length;for(this.clear();++te<le;){var Ve=L[te];this.set(Ve[0],Ve[1])}}function Lr(){this.size=0,this.__data__={hash:new Rr,map:new(xt||tn),string:new Rr}}function ln(L){var te=Ht(this,L).delete(L);return this.size-=te?1:0,te}function k(L){return Ht(this,L).get(L)}function O(L){return Ht(this,L).has(L)}function z(L,te){var le=Ht(this,L),Ve=le.size;return le.set(L,te),this.size+=le.size==Ve?0:1,this}rn.prototype.clear=Lr,rn.prototype.delete=ln,rn.prototype.get=k,rn.prototype.has=O,rn.prototype.set=z;function W(L){var te=this.__data__=new tn(L);this.size=te.size}function pe(){this.__data__=new tn,this.size=0}function ce(L){var te=this.__data__,le=te.delete(L);return this.size=te.size,le}function xe(L){return this.__data__.get(L)}function _e(L){return this.__data__.has(L)}function rt(L,te){var le=this.__data__;if(le instanceof tn){var Ve=le.__data__;if(!xt||Ve.length<t-1)return Ve.push([L,te]),this.size=++le.size,this;le=this.__data__=new rn(Ve)}return le.set(L,te),this.size=le.size,this}W.prototype.clear=pe,W.prototype.delete=ce,W.prototype.get=xe,W.prototype.has=_e,W.prototype.set=rt;function ut(L,te){var le=Ti(L),Ve=!le&&ds(L),pt=!le&&!Ve&&fs(L),_t=!le&&!Ve&&!pt&&Ae(L),Wr=le||Ve||pt||_t,$n=Wr?pn(L.length,String):[],oi=$n.length;for(var zi in L)Wr&&(zi=="length"||pt&&(zi=="offset"||zi=="parent")||_t&&(zi=="buffer"||zi=="byteLength"||zi=="byteOffset")||Je(zi,oi))||$n.push(zi);return $n}function nt(L,te,le){var Ve=L[te];(!(tt.call(L,te)&&cs(Ve,le))||le===void 0&&!(te in L))&&vr(L,te,le)}function Jt(L,te){for(var le=L.length;le--;)if(cs(L[le][0],te))return le;return-1}function vr(L,te,le){te=="__proto__"&&or?or(L,te,{configurable:!0,enumerable:!0,value:le,writable:!0}):L[te]=le}function jr(L,te,le,Ve,pt,_t){var Wr;if(le&&(Wr=pt?le(L,Ve,pt,_t):le(L)),Wr!==void 0)return Wr;if(!la(L))return L;var $n=Ti(L);if($n)Wr=be(L);else{var oi=de(L),zi=oi==C||oi==S;if(fs(L))return Zn(L);if(oi==B||oi==d||zi&&!pt)Wr={};else{if(!st[oi])return pt?L:{};Wr=Me(L,oi)}}_t||(_t=new W);var _l=_t.get(L);if(_l)return _l;_t.set(L,Wr),V(L)?L.forEach(function(ua){Wr.add(jr(ua,te,le,ua,L,_t))}):T(L)&&L.forEach(function(ua,va){Wr.set(va,jr(ua,te,le,va,L,_t))});var Nl=lt,Mo=$n?void 0:Nl(L);return Yr(Mo||L,function(ua,va){Mo&&(va=ua,ua=L[va]),nt(Wr,va,jr(ua,te,le,va,L,_t))}),Wr}function dn(L,te,le,Ve,pt){var _t=-1,Wr=L.length;for(le||(le=Ke),pt||(pt=[]);++_t<Wr;){var $n=L[_t];le($n)?Vr(pt,$n):pt[pt.length]=$n}return pt}function Kn(L,te){te=En(te,L);for(var le=0,Ve=te.length;L!=null&&le<Ve;)L=L[Yi(te[le++])];return le&&le==Ve?L:void 0}function Vn(L,te,le){var Ve=te(L);return Ti(L)?Ve:Vr(Ve,le(L))}function vn(L){return L==null?L===void 0?ae:R:Nt&&Nt in Object(L)?Br(L):Gr(L)}function Or(L){return Vi(L)&&vn(L)==d}function qn(L){return Vi(L)&&de(L)==F}function Mn(L){if(!la(L)||pr(L))return!1;var te=hs(L)?D:Gt;return te.test(hi(L))}function _n(L){return Vi(L)&&de(L)==q}function Ri(L){return Vi(L)&&ps(L.length)&&!!St[vn(L)]}function bi(L){if(!la(L))return Fr(L);var te=yr(L),le=[];for(var Ve in L)Ve=="constructor"&&(te||!tt.call(L,Ve))||le.push(Ve);return le}var wi=or?function(L,te){return or(L,"toString",{configurable:!0,enumerable:!1,value:Bt(te),writable:!0})}:Kt;function Nn(L,te,le){var Ve=-1,pt=L.length;te<0&&(te=-te>pt?0:pt+te),le=le>pt?pt:le,le<0&&(le+=pt),pt=te>le?0:le-te>>>0,te>>>=0;for(var _t=Array(pt);++Ve<pt;)_t[Ve]=L[Ve+te];return _t}function ki(L){if(typeof L=="string")return L;if(Ti(L))return Zr(L,ki)+"";if(Q(L))return wn?wn.call(L):"";var te=L+"";return te=="0"&&1/L==-1/0?"-0":te}function zn(L,te){te=En(te,L);var le=-1,Ve=te.length;if(!Ve)return!0;for(;++le<Ve;){var pt=Yi(te[le]);if(pt==="__proto__"&&!tt.call(L,"__proto__")||(pt==="constructor"||pt==="prototype")&&le<Ve-1)return!1}var _t=Wi(L,te);return _t==null||delete _t[Yi(Va(te))]}function En(L,te){return Ti(L)?L:yt(L,te)?[L]:Wn(ve(L))}function Zn(L,te){return L.slice()}function lr(L){var te=new L.constructor(L.byteLength);return new ue(te).set(new ue(L)),te}function Pn(L,te){var le=lr(L.buffer);return new L.constructor(le,L.byteOffset,L.byteLength)}function Ci(L){var te=new L.constructor(L.source,Dr.exec(L));return te.lastIndex=L.lastIndex,te}function I(L){return xr?Object(xr.call(L)):{}}function $(L,te){var le=lr(L.buffer);return new L.constructor(le,L.byteOffset,L.length)}function se(L,te,le,Ve){var pt=!le;le||(le={});for(var _t=-1,Wr=te.length;++_t<Wr;){var $n=te[_t],oi=void 0;oi===void 0&&(oi=L[$n]),pt?vr(le,$n,oi):nt(le,$n,oi)}return le}function Ce(L){return _(L)?void 0:L}function ht(L){return sa(yn(L,void 0,Ua),L+"")}function lt(L){return Vn(L,Te,Z)}function Ht(L,te){var le=L.__data__;return Ot(te)?le[typeof te=="string"?"string":"hash"]:le.map}function Ut(L,te){var le=Tr(L,te);return Mn(le)?le:void 0}function Br(L){var te=tt.call(L,Nt),le=L[Nt];try{L[Nt]=void 0;var Ve=!0}catch{}var pt=Xr.call(L);return Ve&&(te?L[Nt]=le:delete L[Nt]),pt}var M=Lt?function(L){return L==null?[]:(L=Object(L),kr(Lt(L),function(te){return We.call(L,te)}))}:qt,Z=Lt?function(L){for(var te=[];L;)Vr(te,M(L)),L=Fe(L);return te}:qt,de=vn;(Ye&&de(new Ye(new ArrayBuffer(1)))!=ye||xt&&de(new xt)!=F||ft&&de(ft.resolve())!=j||Rt&&de(new Rt)!=q||Et&&de(new Et)!=oe)&&(de=function(L){var te=vn(L),le=te==B?L.constructor:void 0,Ve=le?hi(le):"";if(Ve)switch(Ve){case tr:return ye;case fr:return F;case $t:return j;case Bn:return q;case In:return oe}return te});function be(L){var te=L.length,le=new L.constructor(te);return te&&typeof L[0]=="string"&&tt.call(L,"index")&&(le.index=L.index,le.input=L.input),le}function Me(L,te,le){var Ve=L.constructor;switch(te){case he:return lr(L);case v:case y:return new Ve(+L);case ye:return Pn(L);case Ue:case Re:case Oe:case ee:case re:case fe:case Be:case ke:case $e:return $(L);case F:return new Ve;case E:case Y:return new Ve(L);case ie:return Ci(L);case q:return new Ve;case J:return I(L)}}function Ke(L){return Ti(L)||ds(L)||!!(Dt&&L&&L[Dt])}function Je(L,te){var le=typeof L;return te=te??f,!!te&&(le=="number"||le!="symbol"&&ar.test(L))&&L>-1&&L%1==0&&L<te}function yt(L,te){if(Ti(L))return!1;var le=typeof L;return le=="number"||le=="symbol"||le=="boolean"||L==null||Q(L)?!0:qe.test(L)||!je.test(L)||te!=null&&L in Object(te)}function Ot(L){var te=typeof L;return te=="string"||te=="number"||te=="symbol"||te=="boolean"?L!=="__proto__":L===null}function pr(L){return!!Nr&&Nr in L}function yr(L){var te=L&&L.constructor,le=typeof te=="function"&&te.prototype||zt;return L===le}function ur(L){var te=oa(L,function(Ve){return le.size===a&&le.clear(),Ve}),le=te.cache;return te}function Fr(L){var te=[];if(L!=null)for(var le in Object(L))te.push(le);return te}function Gr(L){return Xr.call(L)}function yn(L,te,le){return te=Ie(te===void 0?L.length-1:te,0),function(){for(var Ve=arguments,pt=-1,_t=Ie(Ve.length-te,0),Wr=Array(_t);++pt<_t;)Wr[pt]=Ve[te+pt];pt=-1;for(var $n=Array(te+1);++pt<te;)$n[pt]=Ve[pt];return $n[te]=le(Wr),ir(L,this,$n)}}function Wi(L,te){return te.length<2?L:Kn(L,Nn(te,0,-1))}var sa=Qi(wi);function Qi(L){var te=0,le=0;return function(){var Ve=Qe(),pt=c-(Ve-le);if(le=Ve,pt>0){if(++te>=u)return arguments[0]}else te=0;return L.apply(void 0,arguments)}}var Wn=ur(function(L){var te=[];return L.charCodeAt(0)===46&&te.push(""),L.replace(Ge,function(le,Ve,pt,_t){te.push(pt?_t.replace(rr,"$1"):Ve||le)}),te});function Yi(L){if(typeof L=="string"||Q(L))return L;var te=L+"";return te=="0"&&1/L==-1/0?"-0":te}function hi(L){if(L!=null){try{return Er.call(L)}catch{}try{return L+""}catch{}}return""}function Ua(L){var te=L==null?0:L.length;return te?dn(L):[]}function Va(L){var te=L==null?0:L.length;return te?L[te-1]:void 0}function oa(L,te){if(typeof L!="function"||te!=null&&typeof te!="function")throw new TypeError(n);var le=function(){var Ve=arguments,pt=te?te.apply(this,Ve):Ve[0],_t=le.cache;if(_t.has(pt))return _t.get(pt);var Wr=L.apply(this,Ve);return le.cache=_t.set(pt,Wr)||_t,Wr};return le.cache=new(oa.Cache||rn),le}oa.Cache=rn;function cs(L,te){return L===te||L!==L&&te!==te}var ds=Or((function(){return arguments})())?Or:function(L){return Vi(L)&&tt.call(L,"callee")&&!We.call(L,"callee")},Ti=Array.isArray;function za(L){return L!=null&&ps(L.length)&&!hs(L)}var fs=K||qr;function hs(L){if(!la(L))return!1;var te=vn(L);return te==C||te==S||te==g||te==G}function ps(L){return typeof L=="number"&&L>-1&&L%1==0&&L<=f}function la(L){var te=typeof L;return L!=null&&(te=="object"||te=="function")}function Vi(L){return L!=null&&typeof L=="object"}var T=Cr?gn(Cr):qn;function _(L){if(!Vi(L)||vn(L)!=B)return!1;var te=Fe(L);if(te===null)return!0;var le=tt.call(te,"constructor")&&te.constructor;return typeof le=="function"&&le instanceof le&&Er.call(le)==Ee}var V=sn?gn(sn):_n;function Q(L){return typeof L=="symbol"||Vi(L)&&vn(L)==J}var Ae=_r?gn(_r):Ri;function ve(L){return L==null?"":ki(L)}function Te(L){return za(L)?ut(L):bi(L)}var He=ht(function(L,te){var le={};if(L==null)return le;var Ve=!1;te=Zr(te,function(_t){return _t=En(_t,L),Ve||(Ve=_t.length>1),_t}),se(L,lt(L),le),Ve&&(le=jr(le,s|o|l,Ce));for(var pt=te.length;pt--;)zn(le,te[pt]);return le});function Bt(L){return function(){return L}}function Kt(L){return L}function qt(){return[]}function qr(){return!1}r.exports=He})(Ud,Ud.exports)),Ud.exports}var eV=Z9();const tV=Ns(eV);function pA(r,e){function t(n){if(typeof n>"u"||!Array.isArray(n)&&!nV(n))return n;if(Array.isArray(n))return pA(n,e);let i={};for(const[a,s]of Object.entries(n))i[a]=rV(s)?s:pA(s,e);return tV(i,e)}return Array.isArray(r)?r.map(t):t(r)}function rV(r){return r==null}function nV(r){return typeof r=="object"&&!Array.isArray(r)&&r!==null}function PE(r,e){return r==null&&e==null?!0:r===e}function RI(r){const e=new Map;return r?.aspects?.forEach(t=>{t.value!==""&&e.set(t.name,!0)}),e}class iV extends jg{constructor(e){super(),this.update=e}async execute(){await this.update(),await new Promise(e=>{window.setTimeout(()=>{e()},1e3)})}}function Rv(r){return pA(r,["__typename"])}class aV{constructor(e,t,n,i,a){this.stateUpdateQueue=new Gg(1),this.mandatoryFulfilledAspects=new Map,this.bundleId=e,this.bundleOwnerId=t,this.configuration=n,this.bundleOptions=a;const s=a?.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=Rv(s),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=Rv(o),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=i}async clearAspects(e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=this.globalPropertyState.aspects;this.globalPropertyState.aspects=t.filter(n=>!e.includes(n.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=RI(this.globalPropertyState)}setBundleOptions(e){this.bundleOptions=e}getBundleOptions(){return this.bundleOptions}setConfiguration(e){this.configuration=e}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(e){this.globalPropertyState||await this.initPromise;const t=mo(this.globalPropertyState);this.globalPropertyState={...Rv(e),id:t.id},this.recalculateMandatoryStates(),this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(t,this.globalPropertyState)}getAspectMandatoryFulfilled(e){return this.mandatoryFulfilledAspects.get(e)}getAspectHidden(e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return!!this.globalPropertyState.aspects.find(t=>t.name===e)?.hidden}getAspect(e,t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const n=this.globalPropertyState.aspects.find(i=>i.name===e&&PE(i.channel,t));if(n)return n.value}getAspectStorage(e,t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(n=>n.name===e&&PE(n.channel,t))?.storage}async setAspect(e,t,n,i,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const s=this.configuration.aspects.find(u=>u.name===e);if(!s)throw new Error(`Failed to find configuration aspect with name: ${e}`);this.mandatoryFulfilledAspects.set(e,t!=="");const o=mo(this.globalPropertyState),l=this.globalPropertyState.aspects.filter(u=>u.name===e);if(l.length>0)if(i){const u=l.find(c=>c.channel===i);if(u)u.value=t,u.type=s.type,u.channel=i,u.hidden=a??u.hidden,n!==void 0&&(u.storage=n!==null?n:void 0);else{let c;if(i===1){const f=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===e);f&&f>0&&(c=this.globalPropertyState.aspects.splice(f,1)[0].hidden)}this.globalPropertyState.aspects.push({name:e,value:t,type:s.type,storage:n!==null?n:void 0,channel:i,hidden:a??c})}}else{const u=l[0];u.value=t,u.type=s.type,u.hidden=a??u.hidden,n!==void 0&&(u.storage=n!==null?n:void 0)}else this.globalPropertyState.aspects.push({name:e,value:t,type:s.type,storage:n!==null?n:void 0,channel:i,hidden:a});vf(o,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(e,t,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(o=>o.name===e);if(!i)throw new Error(`Failed to find configuration aspect with name: ${e}`);const a=mo(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===e);if(s.length>0)if(n){const o=s.find(l=>l.channel===n);o&&(o.storage=t!==null?t:void 0,o.type=i.type)}else{const o=s[0];o.storage=t!==null?t:void 0,o.type=i.type}else this.globalPropertyState.aspects.push({name:e,value:"",type:i.type,storage:t!==null?t:void 0,channel:n});vf(a,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(a,this.globalPropertyState))}queueGlobalPropertyStateUpdate(){this.stateUpdateQueue.enqueue(new iV(async()=>{await this.updateGlobalPropertyState()}))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!(await ze.getShadowGraphqlClient().mutate({mutation:WU,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(t=>{let n=t.type&&t.storage?{}:void 0;if(n)switch(t.type){case Hn.FileUpload:{n.fileUpload=t.storage;break}case Hn.ColorOption:case Hn.Option:{n.option=t.storage;break}}return{name:t.name,value:t.value,type:t.type,storage:n,channel:t.channel,hidden:t.hidden}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}})).data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const e=await ze.getShadowGraphqlClient().mutate({mutation:qU,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class sV{constructor(e){this.setState(e||'{"transactions": []}')}setState(e){e&&(this.state=JSON.parse(e))}getState(){return this.state}removeStateForTransaction(e){if(!this.state||!this.state.transactions)return;const t=this.state.transactions.findIndex(n=>n.transactionId===e);t!==-1&&this.state.transactions.splice(t,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(e,t){if(!(typeof e!="object"||e===null))for(const n in e)n===t?delete e[n]:this.deleteFieldNameFromObjectRecursive(e[n],t)}}const oV=Se`
2834
+ `;var yg=(r=>(r.PriceBreakChanged="PriceBreakChanged",r.ProductChanged="ProductChanged",r.QuantityChanged="QuantityChanged",r.RecipientChanged="RecipientChanged",r.SelectionChanged="SelectionChanged",r))(yg||{});class B1{constructor(e,t){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=FI(async()=>{await Qp.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async n=>new Promise((i,a)=>{try{n.toBlob(s=>{if(s){const o=URL.createObjectURL(s);i(o)}})}catch(s){a(s)}}),this.client=e,this.transaction=t.transaction,this.workflow=t.workflow,this.profanityList=this.transaction.product?.profanities?.map(n=>n.word)||[],this.isReadOnly=t.transaction.isOrdered||!!t.readOnly,this.graphQlClient=t.graphQlClient,this.workflowManager=new dA(this,e,n=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return t.stateMutationFunc(n)},t.graphQlClient,t.reloadedState,t.readOnly,t.modelContainer,t.isReloadedTransaction,t.singleVariantsRenderable,t.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(n=>{const i=n.traversableScenes.map(a=>{const s=a.renderableSteps.map(o=>o.stepName);return{id:a.name,title:a.title,renderableSteps:s,workflowScene:a}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(a=>a(i)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(e){this.workflow=void 0;const t=await this.graphQlClient().mutate({mutation:FE,variables:{id:this.getTransaction().id,integrationProductId:e}}),n=t.data?.transactionUpdateIntegrationProduct.product;if(!n)throw new nn("Failed to set product. No product returned from server.");if(!this.bundle)throw new nn("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...t.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...t.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const i=(await this.bundle.getProductCollection().fetchProducts()).find(a=>a.getId()===n.id);try{const a=i?.getDefaultWorkflow();if(a){const s=await NP(a.getId());await this.setWorkflow(s),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new nn("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:FE,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(e){return this.workflow=e,await this.graphQlClient().mutate({mutation:O3,variables:{id:this.getTransaction().id,workflowId:e.id}}),this.workflowManager.setWorkflow(e)}async attachAddress(e,t,n,i,a,s){await this.graphQlClient().mutate({mutation:Y9,variables:{transactionId:this.getTransaction().id,streetAddress:e||void 0,apartment:t||void 0,city:n||void 0,country:i||void 0,state:a||void 0,postCode:s||void 0}})}async attachOrganization(e){await this.graphQlClient().mutate({mutation:X9,variables:{transactionId:this.getTransaction().id,organizationName:e}})}getBundle(){return this.bundle}setBundle(e){this.bundle=e}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(e,t){const n=this.getWorkflow(),i=n?.finalizeStepConfig?.lookAtAnimation;if(!n)throw new Error("Failed to generate cart preview image! No workflow is set.");if(e){if(!i)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(t??512,i)||""}let a=2048;t&&t<=2048&&(a=t);const s=Eo(a,a),o=this.workflowManager.getCommandContext().getAllLayouts(),l=n.defaultPreviewPanelIndex||0,u=n.panels[l],c=o.find(S=>S.layoutState?.layout.panelId===u?.name)||o[0],f=c.layoutState.layout.previewRegion?{x:c.layoutState.layout.previewRegion.left,y:c.layoutState.layout.previewRegion.top,width:c.layoutState.layout.previewRegion.width,height:c.layoutState.layout.previewRegion.height}:{x:0,y:0,width:c.layoutState.layout.width,height:c.layoutState.layout.height},d=this.workflowManager.getCommandContext().getLayoutById(c.layoutState.layout.id),h=s.getContext("2d");if(!h)throw new _g("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),v=Qg(d.layoutState.layout,d.layoutState.elements,{renderingConfiguration:{purpose:Ku.Print,region:{left:f.x,top:f.y,width:f.width,height:f.height},templatingContext:g}}),y=qk(v);await(await uo.from(h,y,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:Eo,createImage:Mf,DOMParser:QA(),fetch})).render();const C=await this.getCanvasObjectURLAsync(s);return s.toDataURL(C)}getStepById(e){const t=this.getWorkflow()?.steps.find(a=>a.stepName===e);if(!t||!this.stepHasHandle(t))return;const n=this.cachedStepHandles.get(t.stepName);if(n)return n;const i=Ep.get(this.getWorkflowManager(),t);return this.cachedStepHandles.set(t.stepName,i),i}getSteps(){return this.getScenes().flatMap(e=>this.getStepsByScene(e))}async getStepsConditionallyActive(){const e=this.getScenes();return(await Promise.all(e.map(async n=>{const i=this.getStepsByScene(n),a=await Promise.all(i.map(s=>co(s.getRaw(),this.getWorkflowManager().getStepSelections())));return i.filter((s,o)=>a[o])}))).flat()}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(t=>({id:t.id,name:t.name,stepIds:t.stepNames}))}getSelectionPriceSubunits(e){const t=this.getWorkflowManager().getWorkflowSelections();let n=0;return Object.values(t).forEach(i=>{n+=i.selections.reduce((a,s)=>a+(s.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(n,e)}getBasePriceSubunits(e,t){const n=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,t);if(e){const i=this.getAdditionalProductPriceSubunits(t)||0;return n+i}return n}getAdditionalProductPriceSubunits(e){const t=this.getTransaction().integrationProduct;if(t?.additionalIntegrationProduct?.product){const n=t.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(n,e)}}getTotalPriceSubunits(e){return this.getBasePriceSubunits(!1,e)+this.getSelectionPriceSubunits(e)}getPriceSubUnitsAfterPriceBreaks(e,t){const n=t?1:this.priceBreakToBeApplied(),i=e*n;return Math.ceil(i)}priceBreakToBeApplied(){const e=(this.getProduct()?.priceBreaks||[]).sort((i,a)=>-(i.minQty-a.minQty)),n=[...this.getMatchingExperiencesFromBundle(),this].reduce((i,a)=>i+a.getQuantity(),0);for(const i of e)if(i.minQty<=n)return i.percentage;return 1}checkForPriceBreakChanges(){const e=this.priceBreakToBeApplied();this.currentPriceBreak!==e&&(this.updatePriceBreak(e),this.getMatchingExperiencesFromBundle().forEach(t=>t.updatePriceBreak(e)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(e=>{const t=e.getTransaction().id,n=this.getTransaction().id,i=e.getProduct()?.id,a=this.getProduct()?.id;return t!==n&&i===a})}updatePriceBreak(e){this.currentPriceBreak=e,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(e,t,n){const i=await e.getGlobalProperties(),a=n?.map(u=>u.getId()),s=this.getSteps().filter(u=>a===void 0||a.includes(u.getId())),o=t.getSteps(),l=u=>i.find(c=>c.getRawProperty().name===u.aspectName);s.forEach(u=>{const c=new Set,f=u.getRaw().globalPropertyAspectConfigurations;f!==void 0&&(f.forEach(d=>c.add(JSON.stringify(d))),o.forEach(d=>{const h=d.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const v=l(g),y=c.has(JSON.stringify(g));if(y&&v?.getType()==="Option"){const A=d.getCurrentVariant();if(!A)return;u.selectVariant(A),c.delete(JSON.stringify(g))}else if(y&&v?.getType()==="Text"){const A=d.getText();u.setText(A),c.delete(JSON.stringify(g))}})}))})}getStepByName(e){const t=this.getWorkflow()?.steps.find(n=>n.stepTitle===e);if(!(!t||!this.stepHasHandle(t)))return Ep.get(this.getWorkflowManager(),t)}getStepsByType(e){return this.getWorkflow()?.steps.filter(t=>t.type===e).map(t=>Ep.get(this.getWorkflowManager(),t))||[]}getStepsByScene(e){const t=this.getWorkflow();if(!t?.stepGroups.find(i=>i.name===e.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return e.stepIds.map(i=>t.steps.find(a=>a.stepName===i)).filter(i=>!!i&&this.stepHasHandle(i)).map(i=>Ep.get(this.getWorkflowManager(),i))}async attachCustomerDetails(e){return this.assignCustomerDetails({emailAddress:e.email})}async assignCustomerDetails(e){const n=(await this.graphQlClient().mutate({mutation:W9,variables:{id:this.getTransaction().id,details:e,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(i=>i.customer?.emailAddress===e.emailAddress);n?.customer&&this.assignCustomerInternal(n.customer)}assignCustomerInternal(e){this.getWorkflowManager().setTransactionCustomer(e);const t=wr.getMap("transactionCustomerIds")||new Map;t.set(this.getTransaction().id,e.id),wr.setMap("transactionCustomerIds",t)}attachRenderableSceneListener(e){this.renderableSceneCallbacks.push(e),e(this.renderableScenes)}detachRenderableSceneListener(e){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(t=>t!==e)}async save(e){const t=this.getProduct(),n=this.getWorkflow(),i=this.getCommandContext().getState();if(!t)throw new nn("Product undefined!");if(!n)throw new nn("Workflow undefined!");if(!i)throw new nn("State undefined!");const s={title:await(async()=>{if(e)return e;const o=this.getTransaction().id,u=(await Qp.getSavedDesigns()).find(c=>c.transactionId===o)?.title;return u||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:t.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:n.name,workflowId:n.id,lastEdited:new Date};return await Qp.addDesign(s),s}async copy(){const e=mo(this.getCommandContext().getState());if(!e)throw new nn("Internal state is undefined! Cannot copy experience!");const t=JSON.stringify(e.transaction),n=this.getWorkflow();if(!n)throw new nn("Workflow is undefined! Cannot copy experience!");const i=this.getTransaction().integrationProduct?.id;if(!i)throw new nn("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:i,workflowId:n.id,workflowState:t})}async onDesignFinished(e=!0){const t=this.getTransaction(),n=this.getProduct(),i=this.getWorkflow();if(!n)throw new nn("Product undefined! Cannot finish an experience without a product.");if(!i)throw new nn("Workflow undefined! Cannot finish an experience without a workflow.");if(t.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:t.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const a=await TI([{workflowManager:this.workflowManager,workflow:i,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:n,transaction:t,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:i.name}],s=>e?this.createPreviewImage(s,1024):Promise.resolve(void 0));return t.completed&&await this.graphQlClient().mutate({mutation:z3,variables:{transactionId:t.id}}),a[0]}stepHasHandle(e){return e.type!==Xe.SilentIllustration&&e.type!==Xe.ProductOverlay}async getExportedStepData(){const e=this.getWorkflow(),t=this.getWorkflowManager().getWorkflowMetadata(),n=this.getWorkflowManager().getWorkflowSelections(),i=[];for(const a of e?.steps||[]){const s=a.stepName,o=t[s],l=n[s]?.selections[0],u={stepId:s,title:a.stepTitle,properties:[]};if(l&&await K9(a,n)&&u.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!o){i.push(u);continue}switch(a.type){case Xe.Frame:{const c=a.data,f=o;f.image&&c.displayImageOnFinishStep&&u.properties.push({type:"image",value:f.image,priceModifier:0})}break;case Xe.Illustration:{const c=a.data,f=o;if(f&&f.colors&&f.colors.length>0&&c.displayColorsOnFinishStep){const d=f.colors.join(", ").toUpperCase();u.properties.push({type:"color",value:d,priceModifier:0})}}break;case Xe.Module:{const c=a.data,f=o;f&&f.text&&c.displayTextOnFinishStep&&u.properties.push({type:"text",value:f.text,priceModifier:0})}break;case Xe.Text:{const c=a.data,f=o;f&&f.text&&c.displayTextOnFinishStep&&u.properties.push({type:"text",value:f.text,priceModifier:0}),f&&f.color&&c.displayColorOnFinishStep&&u.properties.push({type:"color",value:f.color,priceModifier:0})}}i.push(u)}return i.filter(a=>a.properties&&a.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(e){if(e<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getTransaction().quantity=e,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const t=this.getTransaction();await this.graphQlClient().mutate({mutation:R3,variables:{id:t.id,quantity:e}})}addEventListener(e,t){const n=this.eventCallbacks.get(e)||[];n.push(t),this.eventCallbacks.set(e,n)}removeEventListener(e,t){const n=this.eventCallbacks.get(e)||[];this.eventCallbacks.set(e,n.filter(i=>i!==t))}callEvent(e){(this.eventCallbacks.get(e)||[]).forEach(t=>t(this))}}const J9=r=>{if([Xe.Question,Xe.Frame,Xe.Illustration,Xe.Material,Xe.Model,Xe.Picture,Xe.Shape,Xe.Text].includes(r.type)){const t=r.data;return!!t.displaySelectionOnFinishStep||!!t.displaySelectionsOnFinishStep}return!1},K9=async(r,e)=>{if(!J9(r))return!1;const t=await ct.getOptionForStep(r);if(t&&(t.variants||[]).length>1){const n=e[r.stepName];return!!(n&&n.selections.length>0)}return!1};class Z9{constructor(e){this.handleCache={},this.bundle=e}async getHandle(e){if(this.handleCache[e.name])return this.handleCache[e.name];const t=await this.createHandle(e);return this.handleCache[e.name]=t,t}async getHandles(){if(!this.bundle.getGlobalPropertyConfiguration())return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const e=this.bundle.getGlobalPropertyConfiguration();return e?Promise.all(e.aspects.map(t=>this.getHandle(t))):[]}applyConditionsFromState(e,t){return t?e.filter(n=>this.aspectConditionsSatisfied(n.getRawProperty(),t)):e}aspectConditionsSatisfied(e,t){return!e.conditions||e.conditions.length===0?!0:(e.conditionMode===Mk.AND?Array.prototype.every.bind(e.conditions):Array.prototype.some.bind(e.conditions))(i=>{const a=t.aspects.find(s=>s.name===i.targetAspectName);return a?i.requiredVariantSelections.some(s=>s===a.value):!1})}async createHandle(e){switch(e.type){case Hn.FileUpload:return new II(this.bundle,e).initialize();case Hn.ColorOption:return new hA(this.bundle,e,e.entityId?await ct.getOption(e.entityId):void 0);case Hn.Option:{const t=e.entityId?await ct.getOption(e.entityId):void 0;return t?.type==="Color"?new hA(this.bundle,e,t):new M1(this.bundle,e,t)}case Hn.Text:return new PI(this.bundle,e);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Jg{constructor(e,t){this.bundle=e,this.property=t}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}isSilent(){return!!this.property.silent||this.bundle.getGlobalPropertyStateManager().getAspectHidden(this.property.name)}async getSharedSteps(e){const t=e??this.bundle.getWorkflowExperiences();return(await Promise.all(t.map(a=>a.getStepsConditionallyActive()))).map(a=>a.filter(s=>s.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:s.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getGlobalPropertyConfiguration()?.id&&o.aspectName===this.property.name))).flat()}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class II extends Jg{constructor(e,t){super(e,t)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await ct.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const e=await this.getImage();if(e?.fileLink)if(e?.fileLink.endsWith(".svg")){const t=await ra(e?.fileLink),n=await x1(e?.fileLink),i=n.width,a=n.height,s=await Pa(t);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(u=>{s.colors[u.key]={browserValue:u.browserValue,pmsValue:u.pmsValue}});const l={src:e?.fileLink,width:i,height:a,aspect:i/a,svg:s.svg,colors:s.colors};Ds.set(e?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(e){const t=this.bundle.getGlobalPropertyStateManager();await Promise.all([t.setAspect(this.property.name,e.key,{...t.getAspectStorage(this.property.name)||{},originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(e),this.loadImageData()])}async canUseAdvancedImageManipulation(){return this.bundle.getClient().canUseAddon(Bg.AdvancedImageManipulation)}async removeBackgroundFromImage(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Advanced Image Manipulation addon. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImage();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const n=this.bundle.getGlobalPropertyStateManager(),i=await Ln.removeBackgroundFromAsset(t),s={...n.getAspectStorage(this.property.name),backgroundRemovedAssetKey:i.key,useOriginalAsset:!e},l=[e?n.setAspect(this.property.name,i.key,s):n.setAspectStorage(this.property.name,s)];return e&&(l.push(this.applyImageSelection(i,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),i}async vectorizeImage(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Advanced Image Manipulation addon. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImage();if(!t)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=this.bundle.getGlobalPropertyStateManager(),i=await Ln.vectorizeAsset(t),s={...n.getAspectStorage(this.property.name),vectorizedAssetKey:i.key,useOriginalAsset:!e},l=[e?n.setAspect(this.property.name,i.key,s):n.setAspectStorage(this.property.name,s)];return e&&(l.push(this.applyImageSelection(i,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),i}hasImage(){return!!this.getStateValue()}async getImage(){const e=this.getStateValue();if(e)return Ln.getLocalOrFromServer(e)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Ug(zg(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(e?.originalAssetKey)return Ln.getLocalOrFromServer(e.originalAssetKey)}async getBackgroundRemovedImage(){const e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(e?.backgroundRemovedAssetKey)return Ln.getLocalOrFromServer(e.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(e){const t=await this.getOriginalImage();if(!t)throw new Error("You must select an image before calling setUseOriginalImage");const n=this.bundle.getGlobalPropertyStateManager(),i=n.getAspectStorage(this.property.name);if(i?.useOriginalAsset===e)return;const a={...i,useOriginalAsset:e},s=e?i?.originalAssetKey:i?.backgroundRemovedAssetKey,o=[n.setAspect(this.property.name,s||"",a)];if(e)o.push(this.applyImageSelection(t,void 0,!1,!1));else{const l=async()=>{const u=await this.getBackgroundRemovedImage();if(!u)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(u,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(a)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return;const n=await Ln.getLocalOrFromServer(t);if(!n)return;await this.applyImageSelection(n,e,!1,!0);const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(i){if(this.updateSharedStepStorage({...i}),i.colors){const a=new Map(i.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);await Promise.all((await this.getSharedSteps(e)).map(async s=>{await s.changeColors(a)}))}}else this.updateSharedStepStorage({originalAssetKey:t}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:t})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(e=>({fill:e.color,stroke:e.color,variant:e,pmsValue:e.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await Pa(this.imageData.svg)).colors:void 0}async changeColors(e){if(!this.imageData?.svg)return;const t=this.getSharedSteps(),n=new Map(Object.entries(e));await Promise.all((await t).map(async a=>{await a.changeColors(n)}));const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...i,colors:Object.entries(e).map(([a,s])=>({key:a,browserValue:s.browserValue,pmsValue:s.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(e,t,n=!0,i=!0){const s=(await this.getSharedSteps(t)).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(e,n,i)});await Promise.all(s)}updateSharedStepStorage(e){this.bundle.getWorkflowExperiences().forEach(n=>n.getSteps().forEach(i=>{if(i.getOverrideGlobalPropertyConfiguration(this.property.type))return;i.getRaw().globalPropertyAspectConfigurations?.some(s=>s.globalPropertyConfigurationId===this.bundle.getGlobalPropertyConfiguration()?.id&&s.aspectName===this.property.name)&&n.getWorkflowManager().updateStorage(i.getId(),{framePatternData:{originalAssetKey:e.originalAssetKey,backgroundRemovedAssetKey:e.backgroundRemovedAssetKey,useOriginalAsset:e.useOriginalAsset}})}))}}class PI extends Jg{constructor(e,t){super(e,t)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const e=this.getStateValue();return e||""}async setText(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e,void 0,void 0),this.applyTextSelection(e)])}async applyGlobalState(e){const t=this.getStateValue();if(!t)return Promise.resolve();await this.applyTextSelection(t,e)}async applyTextSelection(e,t){const i=(await this.getSharedSteps(t)).map(a=>{a.setText(e)});await Promise.all(i)}}class M1 extends Jg{constructor(e,t,n){super(e,t),this.optionResource=n}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const e=await ct.getOption(this.property.entityId);return e&&(this.optionResource=e),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const e=this.optionResource?.variants?.find(t=>t.id===this.optionResource?.defaultVariant?.id);e&&await this.selectVariant(new Fa(e))}getCurrentVariant(){if(!this.optionResource)return;const e=this.getStateValue();if(e){const t=this.optionResource.variants?.find(n=>n.id===e);return t?new Fa(t):void 0}else{const t=this.optionResource.variants?.find(n=>n.id===this.optionResource?.defaultVariant?.id);return t?new Fa(t):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(t=>t.enabled)||[]).map(t=>new Fa(t))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(t=>new Fa(t))}async selectVariant(e,t){await this.applyVariantSelection(e),await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.getId(),void 0,t)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return;await this.ensureOptionLoaded();const n=this.optionResource?.variants?.find(i=>i.id===t);if(n)return this.applyVariantSelection(new Fa(n),e)}async applyVariantSelection(e,t){const i=(await this.getSharedSteps(t)).map(a=>a.selectVariant(e));await Promise.all(i)}}class hA extends M1{constructor(e,t,n){super(e,t,n)}async selectVariant(e,t){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.getId(),void 0,t),await this.applyColorVariant(e,void 0,t)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return;await this.ensureOptionLoaded();const n=this.optionResource?.variants?.find(a=>a.id===t);if(!n)return;await this.applyColorVariant(new Fa(n),e);const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;i&&await this.setCustomColor(i)}async applyColorVariant(e,t,n){const a=(await this.getSharedSteps(t)).map(s=>{switch(s.getType()){case Xe.Shape:return s.selectVariant(e);case Xe.Text:return s.setFillColor({fill:e.getColor(),stroke:e.getColor(),variant:e.getResource()});case Xe.Illustration:return s.setColor(n?.toString()||"",e.getColor()||"")}});await Promise.all(a)}async setCustomColor(e){const t=this.getCurrentVariant()?.getColor();t&&t.toLowerCase()==="#custom"&&(await this.getSharedSteps()).forEach(i=>i.setCustomColor(e)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:e})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const eV=(r,e,t)=>{const n=r.getWorkflowExperiences(),i=r.getGlobalPropertyConfiguration();return i?n.flatMap(s=>s.getSteps()).filter(s=>s.getGlobalPropertyAspects(i.id).includes(e)&&s.getType()===t):[]},DI=(r,e)=>{const n=eV(r,e,Xe.Illustration).map(i=>{if(!i.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const s=i.getColors();return s?Object.getOwnPropertyNames(s).length:0});return Math.max(...n)};var Ud={exports:{}};Ud.exports;var IE;function tV(){return IE||(IE=1,(function(r,e){var t=200,n="Expected a function",i="__lodash_hash_undefined__",a=500,s=1,o=2,l=4,u=800,c=16,f=9007199254740991,d="[object Arguments]",h="[object Array]",g="[object AsyncFunction]",v="[object Boolean]",y="[object Date]",A="[object Error]",C="[object Function]",S="[object GeneratorFunction]",F="[object Map]",E="[object Number]",R="[object Null]",B="[object Object]",j="[object Promise]",G="[object Proxy]",ie="[object RegExp]",q="[object Set]",Y="[object String]",J="[object Symbol]",ae="[object Undefined]",oe="[object WeakMap]",he="[object ArrayBuffer]",ye="[object DataView]",Ue="[object Float32Array]",Re="[object Float64Array]",Oe="[object Int8Array]",ee="[object Int16Array]",re="[object Int32Array]",fe="[object Uint8Array]",Be="[object Uint8ClampedArray]",ke="[object Uint16Array]",$e="[object Uint32Array]",je=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,qe=/^\w*$/,Ge=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,bt=/[\\^$.*+?()[\]{}|]/g,rr=/\\(\\)?/g,Dr=/\w*$/,Gt=/^\[object .+?Constructor\]$/,ar=/^(?:0|[1-9]\d*)$/,St={};St[Ue]=St[Re]=St[Oe]=St[ee]=St[re]=St[fe]=St[Be]=St[ke]=St[$e]=!0,St[d]=St[h]=St[he]=St[v]=St[ye]=St[y]=St[A]=St[C]=St[F]=St[E]=St[B]=St[ie]=St[q]=St[Y]=St[oe]=!1;var st={};st[d]=st[h]=st[he]=st[ye]=st[v]=st[y]=st[Ue]=st[Re]=st[Oe]=st[ee]=st[re]=st[F]=st[E]=st[B]=st[ie]=st[q]=st[Y]=st[J]=st[fe]=st[Be]=st[ke]=st[$e]=!0,st[A]=st[C]=st[oe]=!1;var Qr=typeof di=="object"&&di&&di.Object===Object&&di,Sr=typeof self=="object"&&self&&self.Object===Object&&self,gr=Qr||Sr||Function("return this")(),nr=e&&!e.nodeType&&e,dr=nr&&!0&&r&&!r.nodeType&&r,Yt=dr&&dr.exports===nr,Xt=Yt&&Qr.process,mt=(function(){try{var L=dr&&dr.require&&dr.require("util").types;return L||Xt&&Xt.binding&&Xt.binding("util")}catch{}})(),Cr=mt&&mt.isMap,sn=mt&&mt.isSet,_r=mt&&mt.isTypedArray;function ir(L,te,le){switch(le.length){case 0:return L.call(te);case 1:return L.call(te,le[0]);case 2:return L.call(te,le[0],le[1]);case 3:return L.call(te,le[0],le[1],le[2])}return L.apply(te,le)}function Yr(L,te){for(var le=-1,Ve=L==null?0:L.length;++le<Ve&&te(L[le],le,L)!==!1;);return L}function kr(L,te){for(var le=-1,Ve=L==null?0:L.length,pt=0,_t=[];++le<Ve;){var Wr=L[le];te(Wr,le,L)&&(_t[pt++]=Wr)}return _t}function Zr(L,te){for(var le=-1,Ve=L==null?0:L.length,pt=Array(Ve);++le<Ve;)pt[le]=te(L[le],le,L);return pt}function Vr(L,te){for(var le=-1,Ve=te.length,pt=L.length;++le<Ve;)L[pt+le]=te[le];return L}function pn(L,te){for(var le=-1,Ve=Array(L);++le<L;)Ve[le]=te(le);return Ve}function gn(L){return function(te){return L(te)}}function Tr(L,te){return L?.[te]}function zr(L,te){return function(le){return L(te(le))}}var en=Array.prototype,$r=Function.prototype,zt=Object.prototype,sr=gr["__core-js_shared__"],Er=$r.toString,tt=zt.hasOwnProperty,Nr=(function(){var L=/[^.]+$/.exec(sr&&sr.keys&&sr.keys.IE_PROTO||"");return L?"Symbol(src)_1."+L:""})(),Xr=zt.toString,Ee=Er.call(Object),D=RegExp("^"+Er.call(tt).replace(bt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),U=Yt?gr.Buffer:void 0,X=gr.Symbol,ue=gr.Uint8Array;U&&U.allocUnsafe;var Fe=zr(Object.getPrototypeOf,Object),We=zt.propertyIsEnumerable,wt=en.splice,Dt=X?X.isConcatSpreadable:void 0,Nt=X?X.toStringTag:void 0,or=(function(){try{var L=Ut(Object,"defineProperty");return L({},"",{}),L}catch{}})(),Lt=Object.getOwnPropertySymbols,K=U?U.isBuffer:void 0,Ie=Math.max,Qe=Date.now,Ye=Ut(gr,"DataView"),xt=Ut(gr,"Map"),ft=Ut(gr,"Promise"),Rt=Ut(gr,"Set"),Et=Ut(gr,"WeakMap"),hr=Ut(Object,"create"),tr=hi(Ye),fr=hi(xt),$t=hi(ft),Bn=hi(Rt),In=hi(Et),mr=X?X.prototype:void 0,xr=mr?mr.valueOf:void 0,wn=mr?mr.toString:void 0;function Rr(L){var te=-1,le=L==null?0:L.length;for(this.clear();++te<le;){var Ve=L[te];this.set(Ve[0],Ve[1])}}function Gn(){this.__data__=hr?hr(null):{},this.size=0}function Cn(L){var te=this.has(L)&&delete this.__data__[L];return this.size-=te?1:0,te}function Hr(L){var te=this.__data__;if(hr){var le=te[L];return le===i?void 0:le}return tt.call(te,L)?te[L]:void 0}function xn(L){var te=this.__data__;return hr?te[L]!==void 0:tt.call(te,L)}function cn(L,te){var le=this.__data__;return this.size+=this.has(L)?0:1,le[L]=hr&&te===void 0?i:te,this}Rr.prototype.clear=Gn,Rr.prototype.delete=Cn,Rr.prototype.get=Hr,Rr.prototype.has=xn,Rr.prototype.set=cn;function tn(L){var te=-1,le=L==null?0:L.length;for(this.clear();++te<le;){var Ve=L[te];this.set(Ve[0],Ve[1])}}function Jn(){this.__data__=[],this.size=0}function si(L){var te=this.__data__,le=Jt(te,L);if(le<0)return!1;var Ve=te.length-1;return le==Ve?te.pop():wt.call(te,le,1),--this.size,!0}function Sn(L){var te=this.__data__,le=Jt(te,L);return le<0?void 0:te[le][1]}function mn(L){return Jt(this.__data__,L)>-1}function on(L,te){var le=this.__data__,Ve=Jt(le,L);return Ve<0?(++this.size,le.push([L,te])):le[Ve][1]=te,this}tn.prototype.clear=Jn,tn.prototype.delete=si,tn.prototype.get=Sn,tn.prototype.has=mn,tn.prototype.set=on;function rn(L){var te=-1,le=L==null?0:L.length;for(this.clear();++te<le;){var Ve=L[te];this.set(Ve[0],Ve[1])}}function Lr(){this.size=0,this.__data__={hash:new Rr,map:new(xt||tn),string:new Rr}}function ln(L){var te=Ht(this,L).delete(L);return this.size-=te?1:0,te}function k(L){return Ht(this,L).get(L)}function O(L){return Ht(this,L).has(L)}function z(L,te){var le=Ht(this,L),Ve=le.size;return le.set(L,te),this.size+=le.size==Ve?0:1,this}rn.prototype.clear=Lr,rn.prototype.delete=ln,rn.prototype.get=k,rn.prototype.has=O,rn.prototype.set=z;function W(L){var te=this.__data__=new tn(L);this.size=te.size}function pe(){this.__data__=new tn,this.size=0}function ce(L){var te=this.__data__,le=te.delete(L);return this.size=te.size,le}function xe(L){return this.__data__.get(L)}function _e(L){return this.__data__.has(L)}function rt(L,te){var le=this.__data__;if(le instanceof tn){var Ve=le.__data__;if(!xt||Ve.length<t-1)return Ve.push([L,te]),this.size=++le.size,this;le=this.__data__=new rn(Ve)}return le.set(L,te),this.size=le.size,this}W.prototype.clear=pe,W.prototype.delete=ce,W.prototype.get=xe,W.prototype.has=_e,W.prototype.set=rt;function ut(L,te){var le=Ti(L),Ve=!le&&ds(L),pt=!le&&!Ve&&fs(L),_t=!le&&!Ve&&!pt&&Ae(L),Wr=le||Ve||pt||_t,$n=Wr?pn(L.length,String):[],oi=$n.length;for(var zi in L)Wr&&(zi=="length"||pt&&(zi=="offset"||zi=="parent")||_t&&(zi=="buffer"||zi=="byteLength"||zi=="byteOffset")||Je(zi,oi))||$n.push(zi);return $n}function nt(L,te,le){var Ve=L[te];(!(tt.call(L,te)&&cs(Ve,le))||le===void 0&&!(te in L))&&vr(L,te,le)}function Jt(L,te){for(var le=L.length;le--;)if(cs(L[le][0],te))return le;return-1}function vr(L,te,le){te=="__proto__"&&or?or(L,te,{configurable:!0,enumerable:!0,value:le,writable:!0}):L[te]=le}function jr(L,te,le,Ve,pt,_t){var Wr;if(le&&(Wr=pt?le(L,Ve,pt,_t):le(L)),Wr!==void 0)return Wr;if(!la(L))return L;var $n=Ti(L);if($n)Wr=be(L);else{var oi=de(L),zi=oi==C||oi==S;if(fs(L))return Zn(L);if(oi==B||oi==d||zi&&!pt)Wr={};else{if(!st[oi])return pt?L:{};Wr=Me(L,oi)}}_t||(_t=new W);var _l=_t.get(L);if(_l)return _l;_t.set(L,Wr),V(L)?L.forEach(function(ua){Wr.add(jr(ua,te,le,ua,L,_t))}):T(L)&&L.forEach(function(ua,va){Wr.set(va,jr(ua,te,le,va,L,_t))});var Nl=lt,Mo=$n?void 0:Nl(L);return Yr(Mo||L,function(ua,va){Mo&&(va=ua,ua=L[va]),nt(Wr,va,jr(ua,te,le,va,L,_t))}),Wr}function dn(L,te,le,Ve,pt){var _t=-1,Wr=L.length;for(le||(le=Ke),pt||(pt=[]);++_t<Wr;){var $n=L[_t];le($n)?Vr(pt,$n):pt[pt.length]=$n}return pt}function Kn(L,te){te=En(te,L);for(var le=0,Ve=te.length;L!=null&&le<Ve;)L=L[Yi(te[le++])];return le&&le==Ve?L:void 0}function Vn(L,te,le){var Ve=te(L);return Ti(L)?Ve:Vr(Ve,le(L))}function vn(L){return L==null?L===void 0?ae:R:Nt&&Nt in Object(L)?Br(L):Gr(L)}function Or(L){return Vi(L)&&vn(L)==d}function qn(L){return Vi(L)&&de(L)==F}function Mn(L){if(!la(L)||pr(L))return!1;var te=hs(L)?D:Gt;return te.test(hi(L))}function _n(L){return Vi(L)&&de(L)==q}function Ri(L){return Vi(L)&&ps(L.length)&&!!St[vn(L)]}function bi(L){if(!la(L))return Fr(L);var te=yr(L),le=[];for(var Ve in L)Ve=="constructor"&&(te||!tt.call(L,Ve))||le.push(Ve);return le}var wi=or?function(L,te){return or(L,"toString",{configurable:!0,enumerable:!1,value:Bt(te),writable:!0})}:Kt;function Nn(L,te,le){var Ve=-1,pt=L.length;te<0&&(te=-te>pt?0:pt+te),le=le>pt?pt:le,le<0&&(le+=pt),pt=te>le?0:le-te>>>0,te>>>=0;for(var _t=Array(pt);++Ve<pt;)_t[Ve]=L[Ve+te];return _t}function ki(L){if(typeof L=="string")return L;if(Ti(L))return Zr(L,ki)+"";if(Q(L))return wn?wn.call(L):"";var te=L+"";return te=="0"&&1/L==-1/0?"-0":te}function zn(L,te){te=En(te,L);var le=-1,Ve=te.length;if(!Ve)return!0;for(;++le<Ve;){var pt=Yi(te[le]);if(pt==="__proto__"&&!tt.call(L,"__proto__")||(pt==="constructor"||pt==="prototype")&&le<Ve-1)return!1}var _t=Wi(L,te);return _t==null||delete _t[Yi(Va(te))]}function En(L,te){return Ti(L)?L:yt(L,te)?[L]:Wn(ve(L))}function Zn(L,te){return L.slice()}function lr(L){var te=new L.constructor(L.byteLength);return new ue(te).set(new ue(L)),te}function Pn(L,te){var le=lr(L.buffer);return new L.constructor(le,L.byteOffset,L.byteLength)}function Ci(L){var te=new L.constructor(L.source,Dr.exec(L));return te.lastIndex=L.lastIndex,te}function I(L){return xr?Object(xr.call(L)):{}}function $(L,te){var le=lr(L.buffer);return new L.constructor(le,L.byteOffset,L.length)}function se(L,te,le,Ve){var pt=!le;le||(le={});for(var _t=-1,Wr=te.length;++_t<Wr;){var $n=te[_t],oi=void 0;oi===void 0&&(oi=L[$n]),pt?vr(le,$n,oi):nt(le,$n,oi)}return le}function Ce(L){return _(L)?void 0:L}function ht(L){return sa(yn(L,void 0,Ua),L+"")}function lt(L){return Vn(L,Te,Z)}function Ht(L,te){var le=L.__data__;return Ot(te)?le[typeof te=="string"?"string":"hash"]:le.map}function Ut(L,te){var le=Tr(L,te);return Mn(le)?le:void 0}function Br(L){var te=tt.call(L,Nt),le=L[Nt];try{L[Nt]=void 0;var Ve=!0}catch{}var pt=Xr.call(L);return Ve&&(te?L[Nt]=le:delete L[Nt]),pt}var M=Lt?function(L){return L==null?[]:(L=Object(L),kr(Lt(L),function(te){return We.call(L,te)}))}:qt,Z=Lt?function(L){for(var te=[];L;)Vr(te,M(L)),L=Fe(L);return te}:qt,de=vn;(Ye&&de(new Ye(new ArrayBuffer(1)))!=ye||xt&&de(new xt)!=F||ft&&de(ft.resolve())!=j||Rt&&de(new Rt)!=q||Et&&de(new Et)!=oe)&&(de=function(L){var te=vn(L),le=te==B?L.constructor:void 0,Ve=le?hi(le):"";if(Ve)switch(Ve){case tr:return ye;case fr:return F;case $t:return j;case Bn:return q;case In:return oe}return te});function be(L){var te=L.length,le=new L.constructor(te);return te&&typeof L[0]=="string"&&tt.call(L,"index")&&(le.index=L.index,le.input=L.input),le}function Me(L,te,le){var Ve=L.constructor;switch(te){case he:return lr(L);case v:case y:return new Ve(+L);case ye:return Pn(L);case Ue:case Re:case Oe:case ee:case re:case fe:case Be:case ke:case $e:return $(L);case F:return new Ve;case E:case Y:return new Ve(L);case ie:return Ci(L);case q:return new Ve;case J:return I(L)}}function Ke(L){return Ti(L)||ds(L)||!!(Dt&&L&&L[Dt])}function Je(L,te){var le=typeof L;return te=te??f,!!te&&(le=="number"||le!="symbol"&&ar.test(L))&&L>-1&&L%1==0&&L<te}function yt(L,te){if(Ti(L))return!1;var le=typeof L;return le=="number"||le=="symbol"||le=="boolean"||L==null||Q(L)?!0:qe.test(L)||!je.test(L)||te!=null&&L in Object(te)}function Ot(L){var te=typeof L;return te=="string"||te=="number"||te=="symbol"||te=="boolean"?L!=="__proto__":L===null}function pr(L){return!!Nr&&Nr in L}function yr(L){var te=L&&L.constructor,le=typeof te=="function"&&te.prototype||zt;return L===le}function ur(L){var te=oa(L,function(Ve){return le.size===a&&le.clear(),Ve}),le=te.cache;return te}function Fr(L){var te=[];if(L!=null)for(var le in Object(L))te.push(le);return te}function Gr(L){return Xr.call(L)}function yn(L,te,le){return te=Ie(te===void 0?L.length-1:te,0),function(){for(var Ve=arguments,pt=-1,_t=Ie(Ve.length-te,0),Wr=Array(_t);++pt<_t;)Wr[pt]=Ve[te+pt];pt=-1;for(var $n=Array(te+1);++pt<te;)$n[pt]=Ve[pt];return $n[te]=le(Wr),ir(L,this,$n)}}function Wi(L,te){return te.length<2?L:Kn(L,Nn(te,0,-1))}var sa=Qi(wi);function Qi(L){var te=0,le=0;return function(){var Ve=Qe(),pt=c-(Ve-le);if(le=Ve,pt>0){if(++te>=u)return arguments[0]}else te=0;return L.apply(void 0,arguments)}}var Wn=ur(function(L){var te=[];return L.charCodeAt(0)===46&&te.push(""),L.replace(Ge,function(le,Ve,pt,_t){te.push(pt?_t.replace(rr,"$1"):Ve||le)}),te});function Yi(L){if(typeof L=="string"||Q(L))return L;var te=L+"";return te=="0"&&1/L==-1/0?"-0":te}function hi(L){if(L!=null){try{return Er.call(L)}catch{}try{return L+""}catch{}}return""}function Ua(L){var te=L==null?0:L.length;return te?dn(L):[]}function Va(L){var te=L==null?0:L.length;return te?L[te-1]:void 0}function oa(L,te){if(typeof L!="function"||te!=null&&typeof te!="function")throw new TypeError(n);var le=function(){var Ve=arguments,pt=te?te.apply(this,Ve):Ve[0],_t=le.cache;if(_t.has(pt))return _t.get(pt);var Wr=L.apply(this,Ve);return le.cache=_t.set(pt,Wr)||_t,Wr};return le.cache=new(oa.Cache||rn),le}oa.Cache=rn;function cs(L,te){return L===te||L!==L&&te!==te}var ds=Or((function(){return arguments})())?Or:function(L){return Vi(L)&&tt.call(L,"callee")&&!We.call(L,"callee")},Ti=Array.isArray;function za(L){return L!=null&&ps(L.length)&&!hs(L)}var fs=K||qr;function hs(L){if(!la(L))return!1;var te=vn(L);return te==C||te==S||te==g||te==G}function ps(L){return typeof L=="number"&&L>-1&&L%1==0&&L<=f}function la(L){var te=typeof L;return L!=null&&(te=="object"||te=="function")}function Vi(L){return L!=null&&typeof L=="object"}var T=Cr?gn(Cr):qn;function _(L){if(!Vi(L)||vn(L)!=B)return!1;var te=Fe(L);if(te===null)return!0;var le=tt.call(te,"constructor")&&te.constructor;return typeof le=="function"&&le instanceof le&&Er.call(le)==Ee}var V=sn?gn(sn):_n;function Q(L){return typeof L=="symbol"||Vi(L)&&vn(L)==J}var Ae=_r?gn(_r):Ri;function ve(L){return L==null?"":ki(L)}function Te(L){return za(L)?ut(L):bi(L)}var He=ht(function(L,te){var le={};if(L==null)return le;var Ve=!1;te=Zr(te,function(_t){return _t=En(_t,L),Ve||(Ve=_t.length>1),_t}),se(L,lt(L),le),Ve&&(le=jr(le,s|o|l,Ce));for(var pt=te.length;pt--;)zn(le,te[pt]);return le});function Bt(L){return function(){return L}}function Kt(L){return L}function qt(){return[]}function qr(){return!1}r.exports=He})(Ud,Ud.exports)),Ud.exports}var rV=tV();const nV=Ns(rV);function pA(r,e){function t(n){if(typeof n>"u"||!Array.isArray(n)&&!aV(n))return n;if(Array.isArray(n))return pA(n,e);let i={};for(const[a,s]of Object.entries(n))i[a]=iV(s)?s:pA(s,e);return nV(i,e)}return Array.isArray(r)?r.map(t):t(r)}function iV(r){return r==null}function aV(r){return typeof r=="object"&&!Array.isArray(r)&&r!==null}function PE(r,e){return r==null&&e==null?!0:r===e}function RI(r){const e=new Map;return r?.aspects?.forEach(t=>{t.value!==""&&e.set(t.name,!0)}),e}class sV extends jg{constructor(e){super(),this.update=e}async execute(){await this.update(),await new Promise(e=>{window.setTimeout(()=>{e()},1e3)})}}function Rv(r){return pA(r,["__typename"])}class oV{constructor(e,t,n,i,a){this.stateUpdateQueue=new Gg(1),this.mandatoryFulfilledAspects=new Map,this.bundleId=e,this.bundleOwnerId=t,this.configuration=n,this.bundleOptions=a;const s=a?.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=Rv(s),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=Rv(o),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=i}async clearAspects(e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=this.globalPropertyState.aspects;this.globalPropertyState.aspects=t.filter(n=>!e.includes(n.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=RI(this.globalPropertyState)}setBundleOptions(e){this.bundleOptions=e}getBundleOptions(){return this.bundleOptions}setConfiguration(e){this.configuration=e}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(e){this.globalPropertyState||await this.initPromise;const t=mo(this.globalPropertyState);this.globalPropertyState={...Rv(e),id:t.id},this.recalculateMandatoryStates(),this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(t,this.globalPropertyState)}getAspectMandatoryFulfilled(e){return this.mandatoryFulfilledAspects.get(e)}getAspectHidden(e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return!!this.globalPropertyState.aspects.find(t=>t.name===e)?.hidden}getAspect(e,t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const n=this.globalPropertyState.aspects.find(i=>i.name===e&&PE(i.channel,t));if(n)return n.value}getAspectStorage(e,t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(n=>n.name===e&&PE(n.channel,t))?.storage}async setAspect(e,t,n,i,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const s=this.configuration.aspects.find(u=>u.name===e);if(!s)throw new Error(`Failed to find configuration aspect with name: ${e}`);this.mandatoryFulfilledAspects.set(e,t!=="");const o=mo(this.globalPropertyState),l=this.globalPropertyState.aspects.filter(u=>u.name===e);if(l.length>0)if(i){const u=l.find(c=>c.channel===i);if(u)u.value=t,u.type=s.type,u.channel=i,u.hidden=a??u.hidden,n!==void 0&&(u.storage=n!==null?n:void 0);else{let c;if(i===1){const f=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===e);f&&f>0&&(c=this.globalPropertyState.aspects.splice(f,1)[0].hidden)}this.globalPropertyState.aspects.push({name:e,value:t,type:s.type,storage:n!==null?n:void 0,channel:i,hidden:a??c})}}else{const u=l[0];u.value=t,u.type=s.type,u.hidden=a??u.hidden,n!==void 0&&(u.storage=n!==null?n:void 0)}else this.globalPropertyState.aspects.push({name:e,value:t,type:s.type,storage:n!==null?n:void 0,channel:i,hidden:a});vf(o,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(e,t,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(o=>o.name===e);if(!i)throw new Error(`Failed to find configuration aspect with name: ${e}`);const a=mo(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===e);if(s.length>0)if(n){const o=s.find(l=>l.channel===n);o&&(o.storage=t!==null?t:void 0,o.type=i.type)}else{const o=s[0];o.storage=t!==null?t:void 0,o.type=i.type}else this.globalPropertyState.aspects.push({name:e,value:"",type:i.type,storage:t!==null?t:void 0,channel:n});vf(a,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(a,this.globalPropertyState))}queueGlobalPropertyStateUpdate(){this.stateUpdateQueue.enqueue(new sV(async()=>{await this.updateGlobalPropertyState()}))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!(await ze.getShadowGraphqlClient().mutate({mutation:YU,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(t=>{let n=t.type&&t.storage?{}:void 0;if(n)switch(t.type){case Hn.FileUpload:{n.fileUpload=t.storage;break}case Hn.ColorOption:case Hn.Option:{n.option=t.storage;break}}return{name:t.name,value:t.value,type:t.type,storage:n,channel:t.channel,hidden:t.hidden}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}})).data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const e=await ze.getShadowGraphqlClient().mutate({mutation:QU,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class lV{constructor(e){this.setState(e||'{"transactions": []}')}setState(e){e&&(this.state=JSON.parse(e))}getState(){return this.state}removeStateForTransaction(e){if(!this.state||!this.state.transactions)return;const t=this.state.transactions.findIndex(n=>n.transactionId===e);t!==-1&&this.state.transactions.splice(t,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(e,t){if(!(typeof e!="object"||e===null))for(const n in e)n===t?delete e[n]:this.deleteFieldNameFromObjectRecursive(e[n],t)}}const uV=Se`
2835
2835
  query GetManyMetafields($entityIds: [String!]!) {
2836
2836
  metafieldsMany(entityIds: $entityIds) {
2837
2837
  id
@@ -2843,14 +2843,14 @@ Minimum version required to store current data is: `+q+`.
2843
2843
  }
2844
2844
  }
2845
2845
  }
2846
- `;class lV{constructor(){this.internalMap=new Map}async requestKeysForEntity(e,t){const n=new Map;return await this.ensureIdsArePresent([e]),t.forEach(i=>{const a=this.requestKeyForEntityIfAvailable(e,i);a&&n.set(i,a)}),n}async ensureIdsArePresent(e){if(e.every(n=>this.internalMap.has(n)))return;const t=await ze.getShadowGraphqlClient().query({query:oV,errorPolicy:"all",variables:{entityIds:e.filter(n=>!this.internalMap.has(n))}});e.forEach((n,i)=>{const a=t.data.metafieldsMany[i];this.internalMap.set(n,a.map(s=>({key:s.metafieldConfiguration.name,value:s.value,metafieldConfigurationId:s.metafieldConfiguration.id,metafieldType:s.metafieldConfiguration.metafieldType})))})}async requestKeyForEntity(e,t){if(!this.internalMap.has(e))return;let n=this.internalMap.get(e);const i=n.find(a=>a.key===t);return i||(await this.ensureIdsArePresent([e]),n=this.internalMap.get(e)),i?JSON.parse(i.value):void 0}requestKeyForEntityIfAvailable(e,t){if(!this.internalMap.has(e))return;const i=this.internalMap.get(e).find(a=>a.key===t);if(i)return JSON.parse(i.value)}requestIfAvailable(e,t){return this.internalMap.has(e)?this.internalMap.get(e).find(a=>a.metafieldConfigurationId===t):void 0}}const Ag=new lV;var OI=(r=>(r.Default="Default",r.Name="Name",r.Price="Price",r))(OI||{});class _1{constructor(e){this.fullFetched=!1,this.collection=e;const t=this.collection.productCollectionProducts;t&&t.length>=this.collection.total&&(this.fullFetched=!0)}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getDispatchStartDate(){if(this.collection.dispatchStartDate)return new Date(this.collection.dispatchStartDate)}getDispatchEndDate(){if(this.collection.dispatchEndDate)return new Date(this.collection.dispatchEndDate)}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.filter(e=>!!e.product).map(e=>new Pu(e))}async fetchProducts(e){if(this.fullFetched)return(this.collection.productCollectionProducts??[]).filter(i=>!!i.product).map(i=>new Pu(i));const t=await ze.getShadowGraphqlClient().query({query:xE,variables:{id:this.getId(),productIds:e},errorPolicy:"all"}),n=this.collection.productCollectionProducts||[];return this.collection.productCollectionProducts=[...n,...t.data.productCollections[0].productCollectionProducts?.filter(i=>!n.some(a=>i.id===a.id))||[]],this.collection.productCollectionProducts.length>=this.collection.total&&(this.fullFetched=!0),this.collection.productCollectionProducts.filter(i=>!!i.product&&(!e||e.includes(i.product.id))).map(i=>new Pu(i))}async fetchProductsFeed(e,t,n,i,a,s,o,l){const u={id:this.getId(),productFilters:n?{link:"And",metafields:n}:void 0,productWorkflowFilters:l?{link:"And",metafields:l}:void 0,tags:i?{include:i.include??[],exclude:i.exclude??[]}:void 0,sortKey:a,sortDescending:s,quickSearch:o};if(this.fullFetched){const h=await ze.getShadowGraphqlClient().query({query:e9,errorPolicy:"all",variables:u});if(!h.data?.productCollections||h.data?.productCollections.length===0)throw new Error("Failed to filter product collection products.");const g=this.getProducts(),v=new Map;for(const A of g)v.set(A.getId(),A);const y=h.data.productCollections[0].productCollectionProductsFeed.items.map(A=>v.get(A.product.id)).filter(A=>!!A);return{total:y.length,items:y.slice(e,e+t)}}const c=new AbortController,{signal:f}=c,d=ze.getShadowGraphqlClient().watchQuery({query:t9,variables:{...u,limit:t,offset:e},errorPolicy:"all",fetchPolicy:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:f}}});return new Promise(h=>{let g=!1;const v=d.subscribe({next(y){if(g||y.partial&&(!y.data.productCollections||y.data.productCollections.length===0||!y.data.productCollections[0].productCollectionProductsFeed?.items||y.data.productCollections[0].productCollectionProductsFeed?.items.length===0))return;c.abort(),g=!0,v.unsubscribe();const A=y.data.productCollections?.[0].productCollectionProductsFeed?.items.filter(C=>!!C.product).map(C=>new Pu(mo(C)))||[];h({items:A,total:y.data.productCollections?.[0].productCollectionProductsFeed?.total??0})},error(){g||(g=!0,v.unsubscribe(),h({items:[],total:0}))}})})}async fetchProductsById(e){const t=await ze.getShadowGraphqlClient().query({query:xE,variables:{collectionId:this.collection.id,productIds:e},errorPolicy:"all"});if(t.data?.productCollection?.productCollectionProducts)return t.data.productCollection.productCollectionProducts.map(n=>new Pu(n))}getResource(){return this.collection}}class Pu{constructor(e){this.product=e.product,this.collectionProductResource=e}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(e,t){const i=(this.product.integrationProducts||[]).find(a=>{const s=a.integration?.type,o=a.integration?.type===e,l=t?a.integration?.externalIntegrationId===t:!0;return s&&o&&l});if(!i)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return i}getCurrentIntegration(){const t=(this.product.integrationProducts||[]).find(n=>n.integration?.isCurrent);if(!t)throw new Error(`Product: ${this.collectionProductResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return t}getDefaultWorkflow(){const e=this.product.workflows;if(e===void 0)throw new lo("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(e.length===0)throw new lo("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const t=this.collectionProductResource.workflowId;if(t){const n=e.find(i=>i.workflowName===t);if(n)return new oo(n)}if(this.collectionProductResource.workflows){if(this.collectionProductResource.workflows.length===1)return new oo(this.collectionProductResource.workflows[0].workflowProduct)}else if(e.length===1)return new oo(e[0]);throw new lo("Called getDefaultWorkflow() but no default workflow is configured for the requested product. Multiple workflows exist so we can't assume!")}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new lo("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.collectionProductResource.workflows&&this.collectionProductResource.workflows.length>0?this.collectionProductResource.workflows.map(t=>new oo(t.workflowProduct)):this.product.workflows.sort((t,n)=>(t.index??0)-(n.index??0)).map(t=>new oo(t))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(e){const t=this.product.basePrice||0;if(!e)return t;if(!e.integrationType&&!e.externalId&&!e.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let n;return e.integrationId?n=this.product.integrationProducts?.find(i=>i.integration?.id===e.integrationId):e.externalId?n=this.product.integrationProducts?.find(i=>i.integration?.externalIntegrationId===e.externalId):n=this.product.integrationProducts?.find(i=>i.integration?.type===e.integrationType),n?.additionalIntegrationProduct?.product?t+(n.additionalIntegrationProduct.product.basePrice||0):t}async requestMetafields(e){return Ag.requestKeysForEntity(this.product.id,e)}}class oo{constructor(e){this.workflow=e}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(e=128,t){const n=this.workflow?.imageUrl,i=window?.devicePixelRatio||1;if(n)return $g(n,e*i,"webp",t)}}const uV=Se`
2846
+ `;class cV{constructor(){this.internalMap=new Map}async requestKeysForEntity(e,t){const n=new Map;return await this.ensureIdsArePresent([e]),t.forEach(i=>{const a=this.requestKeyForEntityIfAvailable(e,i);a&&n.set(i,a)}),n}async ensureIdsArePresent(e){if(e.every(n=>this.internalMap.has(n)))return;const t=await ze.getShadowGraphqlClient().query({query:uV,errorPolicy:"all",variables:{entityIds:e.filter(n=>!this.internalMap.has(n))}});e.forEach((n,i)=>{const a=t.data.metafieldsMany[i];this.internalMap.set(n,a.map(s=>({key:s.metafieldConfiguration.name,value:s.value,metafieldConfigurationId:s.metafieldConfiguration.id,metafieldType:s.metafieldConfiguration.metafieldType})))})}async requestKeyForEntity(e,t){if(!this.internalMap.has(e))return;let n=this.internalMap.get(e);const i=n.find(a=>a.key===t);return i||(await this.ensureIdsArePresent([e]),n=this.internalMap.get(e)),i?JSON.parse(i.value):void 0}requestKeyForEntityIfAvailable(e,t){if(!this.internalMap.has(e))return;const i=this.internalMap.get(e).find(a=>a.key===t);if(i)return JSON.parse(i.value)}requestIfAvailable(e,t){return this.internalMap.has(e)?this.internalMap.get(e).find(a=>a.metafieldConfigurationId===t):void 0}}const Ag=new cV;var OI=(r=>(r.Default="Default",r.Name="Name",r.Price="Price",r))(OI||{});class _1{constructor(e){this.fullFetched=!1,this.collection=e;const t=this.collection.productCollectionProducts;t&&t.length>=this.collection.total&&(this.fullFetched=!0)}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getDispatchStartDate(){if(this.collection.dispatchStartDate)return new Date(this.collection.dispatchStartDate)}getDispatchEndDate(){if(this.collection.dispatchEndDate)return new Date(this.collection.dispatchEndDate)}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.filter(e=>!!e.product).map(e=>new Pu(e))}async fetchProducts(e){if(this.fullFetched)return(this.collection.productCollectionProducts??[]).filter(i=>!!i.product).map(i=>new Pu(i));const t=await ze.getShadowGraphqlClient().query({query:xE,variables:{id:this.getId(),productIds:e},errorPolicy:"all"}),n=this.collection.productCollectionProducts||[];return this.collection.productCollectionProducts=[...n,...t.data.productCollections[0].productCollectionProducts?.filter(i=>!n.some(a=>i.id===a.id))||[]],this.collection.productCollectionProducts.length>=this.collection.total&&(this.fullFetched=!0),this.collection.productCollectionProducts.filter(i=>!!i.product&&(!e||e.includes(i.product.id))).map(i=>new Pu(i))}async fetchProductsFeed(e,t,n,i,a,s,o,l){const u={id:this.getId(),productFilters:n?{link:"And",metafields:n}:void 0,productWorkflowFilters:l?{link:"And",metafields:l}:void 0,tags:i?{include:i.include??[],exclude:i.exclude??[]}:void 0,sortKey:a,sortDescending:s,quickSearch:o};if(this.fullFetched){const h=await ze.getShadowGraphqlClient().query({query:r9,errorPolicy:"all",variables:u});if(!h.data?.productCollections||h.data?.productCollections.length===0)throw new Error("Failed to filter product collection products.");const g=this.getProducts(),v=new Map;for(const A of g)v.set(A.getId(),A);const y=h.data.productCollections[0].productCollectionProductsFeed.items.map(A=>v.get(A.product.id)).filter(A=>!!A);return{total:y.length,items:y.slice(e,e+t)}}const c=new AbortController,{signal:f}=c,d=ze.getShadowGraphqlClient().watchQuery({query:n9,variables:{...u,limit:t,offset:e},errorPolicy:"all",fetchPolicy:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:f}}});return new Promise(h=>{let g=!1;const v=d.subscribe({next(y){if(g||y.partial&&(!y.data.productCollections||y.data.productCollections.length===0||!y.data.productCollections[0].productCollectionProductsFeed?.items||y.data.productCollections[0].productCollectionProductsFeed?.items.length===0))return;c.abort(),g=!0,v.unsubscribe();const A=y.data.productCollections?.[0].productCollectionProductsFeed?.items.filter(C=>!!C.product).map(C=>new Pu(mo(C)))||[];h({items:A,total:y.data.productCollections?.[0].productCollectionProductsFeed?.total??0})},error(){g||(g=!0,v.unsubscribe(),h({items:[],total:0}))}})})}async fetchProductsById(e){const t=await ze.getShadowGraphqlClient().query({query:xE,variables:{collectionId:this.collection.id,productIds:e},errorPolicy:"all"});if(t.data?.productCollection?.productCollectionProducts)return t.data.productCollection.productCollectionProducts.map(n=>new Pu(n))}getResource(){return this.collection}}class Pu{constructor(e){this.product=e.product,this.collectionProductResource=e}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(e,t){const i=(this.product.integrationProducts||[]).find(a=>{const s=a.integration?.type,o=a.integration?.type===e,l=t?a.integration?.externalIntegrationId===t:!0;return s&&o&&l});if(!i)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return i}getCurrentIntegration(){const t=(this.product.integrationProducts||[]).find(n=>n.integration?.isCurrent);if(!t)throw new Error(`Product: ${this.collectionProductResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return t}getDefaultWorkflow(){const e=this.product.workflows;if(e===void 0)throw new lo("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(e.length===0)throw new lo("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const t=this.collectionProductResource.workflowId;if(t){const n=e.find(i=>i.workflowName===t);if(n)return new oo(n)}if(this.collectionProductResource.workflows){if(this.collectionProductResource.workflows.length===1)return new oo(this.collectionProductResource.workflows[0].workflowProduct)}else if(e.length===1)return new oo(e[0]);throw new lo("Called getDefaultWorkflow() but no default workflow is configured for the requested product. Multiple workflows exist so we can't assume!")}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new lo("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.collectionProductResource.workflows&&this.collectionProductResource.workflows.length>0?this.collectionProductResource.workflows.map(t=>new oo(t.workflowProduct)):this.product.workflows.sort((t,n)=>(t.index??0)-(n.index??0)).map(t=>new oo(t))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(e){const t=this.product.basePrice||0;if(!e)return t;if(!e.integrationType&&!e.externalId&&!e.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let n;return e.integrationId?n=this.product.integrationProducts?.find(i=>i.integration?.id===e.integrationId):e.externalId?n=this.product.integrationProducts?.find(i=>i.integration?.externalIntegrationId===e.externalId):n=this.product.integrationProducts?.find(i=>i.integration?.type===e.integrationType),n?.additionalIntegrationProduct?.product?t+(n.additionalIntegrationProduct.product.basePrice||0):t}async requestMetafields(e){return Ag.requestKeysForEntity(this.product.id,e)}}class oo{constructor(e){this.workflow=e}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(e=128,t){const n=this.workflow?.imageUrl,i=window?.devicePixelRatio||1;if(n)return $g(n,e*i,"webp",t)}}const dV=Se`
2847
2847
  ${Xg(!1)}
2848
2848
  query GetProductCollections($ids: [String!]!) {
2849
2849
  productCollections(ids: $ids) {
2850
2850
  ...ProductCollectionFields
2851
2851
  }
2852
2852
  }
2853
- `,cV=async r=>(await ze.getShadowGraphqlClient().query({query:uV,errorPolicy:"all",variables:{ids:r}})).data?.productCollections?.map(t=>new _1(t));class dV{constructor(){this.listeners={}}on(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}off(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(n=>n!==t))}emit(e,t){if(this.listeners[e])for(const n of this.listeners[e])n(t)}clear(e){if(e)delete this.listeners[e];else for(const t in this.listeners)delete this.listeners[t]}}const fV=Se`
2853
+ `,fV=async r=>(await ze.getShadowGraphqlClient().query({query:dV,errorPolicy:"all",variables:{ids:r}})).data?.productCollections?.map(t=>new _1(t));class hV{constructor(){this.listeners={}}on(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}off(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(n=>n!==t))}emit(e,t){if(this.listeners[e])for(const n of this.listeners[e])n(t)}clear(e){if(e)delete this.listeners[e];else for(const t in this.listeners)delete this.listeners[t]}}const pV=Se`
2854
2854
  mutation AddAddressToBundle(
2855
2855
  $bundleId: String!
2856
2856
  $streetAddress: String
@@ -2872,26 +2872,26 @@ Minimum version required to store current data is: `+q+`.
2872
2872
  id
2873
2873
  }
2874
2874
  }
2875
- `,hV=Se`
2875
+ `,gV=Se`
2876
2876
  mutation AddOrganizationToBundle($bundleId: String!, $organizationName: String!) {
2877
2877
  organizationAttachToBundle(bundleId: $bundleId, organizationName: $organizationName) {
2878
2878
  id
2879
2879
  }
2880
2880
  }
2881
- `,pV=Se`
2881
+ `,mV=Se`
2882
2882
  mutation GenerateQuoteId($id: String!) {
2883
2883
  bundleGenerateQuoteId(id: $id) {
2884
2884
  id
2885
2885
  quoteId
2886
2886
  }
2887
2887
  }
2888
- `;class DE{constructor(e,t,n,i,a,s,o){this.workflowExperiences=[],this.eventEmitter=new dV,this.updatesLocked=!1,this.client=e,this.id=t.id,this.name=t.name||"",this.dispatchDate=t.dispatchDate,this.purchaseOrder=t.purchaseOrder,this.template=t.template||!1,this.test=t.test||!1,this.quoteId=t.quoteId,this.shareActions=t.bundleShareActions,this.workflowViewerLink=t.workflowViewerLink,this.workflowViewerAmendLink=t.workflowViewerAmendLink,this.ownerId=a,this.metadata=new Map(t.metadata?.map(u=>[u.key,u.value])||[]),this.completed=t.completed??!1,this.productCollection=t.productCollection,this.activation=t.activation,this.bundleStateManager=new sV(t.bundleStateData);const l=this.getGlobalPropertyConfiguration();this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new aV(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),s),this.globalPropertyHandleService=new J9(this),this.setPreviewService(n),this.initializationPromise=(async()=>{if(!s?.readonly){const u=this.bundleStateManager.getState();if(u.integrationProductIds&&u.integrationProductIds.length>0){const c=await ze.getShadowGraphqlClient().query({query:yT,variables:{ids:u.integrationProductIds},errorPolicy:"all",fetchPolicy:"no-cache"});if(c.errors)throw new Error(`Failed to fetch integration products for Bundle ${t.id}`);const f=c.data.integrationProducts?.filter(h=>!!h.product?.id&&u.integrationProductIds.includes(h.id)).map(h=>h.product.id);u.integrationProductIds=[],u.productIds=Array.from(new Set([...u.productIds||[],...f||[]]));const d=JSON.stringify(u);this.bundleStateManager.setState(d),await ze.getShadowGraphqlClient().mutate({mutation:Sp,variables:{id:this.id,bundleStateData:d},context:{bundleOwnerId:a}})}}return Promise.all([this.loadExistingWorkflowExperiences(t.transactionIds||[],{...i,bundleOwnerId:a},o),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>new Promise((u,c)=>{if(s?.readonly){u([]);return}console.log("Setting default global variants."),this.initializeUninitializedHandles().then(u).catch(c)}))})(),this.initializationPromise.catch(u=>{console.error(`Bundle initialization failed: ${u}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(u=>this.checkMandatoryHandlesChanged(void 0,u))})}async initializeUninitializedHandles(){const e=this.globalPropertyStateManager.getGlobalPropertyState();if(!e)return console.log("Attempted to set global default variant before state was initialized."),[];const n=(await this.globalPropertyHandleService.getHandles()).map(async i=>{if(i.getType()===Hn.ColorOption||i.getType()===Hn.Option){const a=i;if(!e.aspects.find(o=>o.name===a.getName()))try{return await a.initDefaultVariant()}catch(o){console.error(`Failed to initialize default global variant - ${o}`)}}});return Promise.all(n)}getProductIds(){return this.bundleStateManager.getState()?.productIds}async addProductId(e){const t=this.bundleStateManager.getState();if(t){if(!t.productIds)t.productIds=[];else if(t.productIds.some(i=>i===e)){this.fireEvent("bundle-products-added",{productIds:t.productIds,added:[]});return}t.productIds=[...t.productIds,e];const n=JSON.stringify(t);this.bundleStateManager.setState(n),this.fireEvent("bundle-products-added",{productIds:t.productIds,added:[e]}),await ze.getShadowGraphqlClient().mutate({mutation:Sp,variables:{id:this.id,bundleStateData:n},context:{bundleOwnerId:this.ownerId}})}}async removeProductIds(e){const t=this.bundleStateManager.getState();if(t){const n=e.filter(a=>(t.productIds??[]).includes(a));if(n.length===0)return;t.productIds=(t.productIds??[]).filter(a=>!n.includes(a));const i=JSON.stringify(t);this.bundleStateManager.setState(i),this.fireEvent("bundle-products-removed",{productIds:t.productIds,removed:n}),await ze.getShadowGraphqlClient().mutate({mutation:Sp,variables:{id:this.id,bundleStateData:i},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}getTest(){return this.test}async generateQuoteId(){const t=(await ze.getShadowGraphqlClient().mutate({mutation:pV,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=t,t||""}async attachAddress(e,t,n,i,a,s){await ze.getShadowGraphqlClient().mutate({mutation:fV,variables:{bundleId:this.id,streetAddress:e||void 0,apartment:t||void 0,city:n||void 0,country:i||void 0,state:a||void 0,postCode:s||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(e){await ze.getShadowGraphqlClient().mutate({mutation:hV,variables:{bundleId:this.id,organizationName:e},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(e){this.globalPropertyStateManager.setBundleOptions(e)}getInitializationPromise(){return this.initializationPromise}addEventListener(e,t){this.eventEmitter.on(e,t)}removeEventListener(e,t){this.eventEmitter.off(e,t)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(e){return this.name=e,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(e){return this.dispatchDate=e,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(e){return this.purchaseOrder=e,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(e){return this.metadata=new Map(e),this.updateBundle()}setNameAndMetadata(e,t){return this.name=e,this.metadata=new Map(t),this.updateBundle()}hasGlobalProperties(){return!!this.getGlobalPropertyConfiguration()}getGlobalPropertyConfiguration(){return this.activation?.globalPropertyConfiguration??this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(e){this.updatesLocked=!0;const t=await this.globalPropertyHandleService.getHandles();try{for(const n of e.aspects){const i=n?.name;await this.getGlobalPropertyStateManager().setAspect(i,n.value,void 0,void 0,n.hidden)}for(const n of e.aspects){const i=n?.name,a=t.find(s=>s.getName()===i);if(a)switch(n.type){case Hn.FileUpload:{const s=a,o=await ag([n.value]);o.length>0&&await s.selectImage(o[0]);const l=n.storage?.colors;if(l){const u=Object.fromEntries(l.map(c=>[c.key,{browserValue:c.browserValue,pmsValue:c.pmsValue}])??[]);await s.changeColors(u)}break}case Hn.ColorOption:{const s=a,l=(await s.getAllVariants()).find(c=>c.getId()===n.value),u=n.storage?n.storage:void 0;l&&await s.selectVariant(l),u?.customColor&&s.setCustomColor(u.customColor);break}case Hn.Option:{const s=a,l=(await s.getAllVariants()).find(u=>u.getId()===n.value);l&&await s.selectVariant(l);break}case Hn.Text:{await a.setText(n.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(n=>n.getType()===Hn.Option).map(n=>n.getCurrentVariant()?.getPrice()||0).reduce((n,i)=>n+i,0)}getTotalSubunits(){return this.workflowExperiences.map(e=>e.getTotalPriceSubunits()).reduce((e,t)=>e+t,0)}getProductCollection(){return this.productCollection?new _1(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(e){for(const t of e.getStepsByType(Xe.Illustration)){const n=t.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const i of n){const a=this.getGlobalPropertyConfiguration()?.aspects.find(s=>s.name===i);if(a&&a.type===Hn.ColorOption){const s=t.getCurrentVariant()?.getAssetResource(),o=s?.assetConfiguration?.channelNumbers||[],l=s?.assetConfiguration?.defaultColorVariants||[],u=DI(this,i),c=[...new Set(o.map(d=>d.number))];if(c.length>u)for(const d of c){const h=this.getGlobalPropertyStateManager(),g=l.find(v=>v.channelNumber===d);g&&await h.setAspect(i,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(e){await this.initializeAdditionalRequiredColorChannels(e),e.setBundle(this),await this.appendWorkflowExperience(e),await this.injectExperienceIntoPreviewService(e),await e.getWorkflowManager().getInitializationPromise();const t=await this.getGlobalProperties();for(const n of t)await n.applyGlobalState([e]);this.fireEvent("workflow-experience-added",{workflowExperiences:[e]})}async addWorkflowExperiences(e){for(const o of e)await this.initializeAdditionalRequiredColorChannels(o);const t=e.map(o=>o.getTransaction().id),n=t.map(o=>this.workflowExperiences.find(l=>l.getTransaction().id===o));if(n.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+n.filter(o=>!!o).map(o=>o?.getTransaction().id).join(", "));const i=wr.getMap("transactionOwnerIds")||new Map,a=t.map(o=>i.get(o));await ze.getShadowGraphqlClient().mutate({mutation:a9,variables:{id:this.id,transactionIds:t,transactionOwnerIds:a},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...e);const s=async()=>{for(const l of e)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(e.map(l=>l.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const l of o)await l.applyGlobalState(e)};await Promise.all([this.updateTransactionOrder(),s()]),await this.initializeUninitializedHandles(),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(e,t=!0){const n=e.getTransaction().id;if(this.workflowExperiences.find(o=>o.getTransaction().id===n))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(wr.getMap("transactionOwnerIds")||new Map).get(n);await ze.getShadowGraphqlClient().mutate({mutation:i9,variables:{id:this.id,transactionId:n},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),t&&(this.workflowExperiences.push(e),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(e){const t=this.workflowExperiences.indexOf(e);await this.removeTransaction(t,this.workflowExperiences[t].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[e]})}async removeWorkflowExperiences(e){await this.removeTransactions(e.map(t=>t.getTransaction()))}async removeWorkflowExperienceByTransaction(e){const t=this.workflowExperiences.findIndex(n=>n.getTransaction().id===e.id);await this.removeTransaction(t,e)}async removeWorkflowExperiencesByTransactions(e){await this.removeTransactions(e)}async removeTransaction(e,t,n=!0){if(e>-1){const i=this.workflowExperiences.find(a=>a.getTransaction().id===t.id);if(i.setBundle(void 0),this.previewService&&i.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(t.id),await ze.getShadowGraphqlClient().mutate({mutation:s9,variables:{id:this.id,transactionId:t.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,s])=>({key:a,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),n){const a=this.workflowExperiences.splice(e,1);this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),i.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:a})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+t.id)}async removeTransactions(e){const t=e.map(i=>this.workflowExperiences.findIndex(a=>a.getTransaction().id===i.id));if(t.some(i=>i===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+e.filter((i,a)=>t[a]===-1).map(i=>i.id).join(", "));const n=e.map(i=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(a=>a.getTransaction().id===i.id),1)[0]);n.forEach(i=>i.setBundle(void 0)),[...this.workflowExperiences,...n].forEach(i=>i.checkForPriceBreakChanges()),this.previewService&&n.forEach(i=>i.getWorkflowManager().ejectFromPreviewService()),e.forEach(i=>this.bundleStateManager.removeStateForTransaction(i.id)),await ze.getShadowGraphqlClient().mutate({mutation:o9,variables:{id:this.id,transactionIds:e.map(i=>i.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,a])=>({key:i,value:a})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:n}),await this.updateTransactionOrder()}async insertWorkflowExperience(e,t){await this.appendWorkflowExperience(e,!1),this.workflowExperiences.splice(t,0,e),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async replaceWorkflowExperience(e,t){if(e<0||e>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const n=this.workflowExperiences[e];if(n.getTransaction().id===t.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(e,n.getTransaction(),!1),this.appendWorkflowExperience(t,!1)]),this.workflowExperiences[e]=t,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const i=await this.getGlobalProperties();await Promise.all(i.map(a=>a.applyGlobalState([t])))})()])}async swapWorkflowExperiences(e,t){if(e<0||e>=this.workflowExperiences.length||t<0||t>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(e===t)return;const n=this.workflowExperiences[e];this.workflowExperiences[e]=this.workflowExperiences[t],this.workflowExperiences[t]=n,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}getTopLevelWorkflowExperiences(){return this.workflowExperiences.filter(e=>!e.getTransaction().parentTransaction)}getChildWorkflowExperiences(e){return this.workflowExperiences.filter(t=>t.getTransaction().parentTransaction?.id===e)}async sortWorkflowExperiences(e){this.workflowExperiences=this.workflowExperiences.sort(e),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(e,t){const n=await ze.getShadowGraphqlClient().mutate({mutation:l9,variables:{id:this.id,details:e,type:t||GA.Owner},context:{bundleOwnerId:this.ownerId}});if(!n.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const i=n.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(i)}async removeStakeholder(e){if(!(await ze.getShadowGraphqlClient().mutate({mutation:u9,variables:{id:this.id,emailAddress:e},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(e){const t=await ze.getShadowGraphqlClient().mutate({mutation:c9,variables:{id:this.id,input:e},context:{bundleOwnerId:this.ownerId}});if(!t.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const n=t.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async getAllStakeholders(){const e=await ze.getShadowGraphqlClient().query({query:CE,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!e.data.bundles||e.data.bundles.length===0)throw new Error("Bundle not found!");const t=e.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(t),t}async getCurrentStakeholder(){const e=await ze.getShadowGraphqlClient().query({query:CE,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!e.data.bundles||e.data.bundles.length===0)throw new Error("Bundle not found!");return e.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(e){e.forEach(t=>{t.customer&&this.client.storeCustomer(t.customer)})}async finish(e,t){this.completed&&await ze.getShadowGraphqlClient().mutate({mutation:g9,variables:{bundleId:this.id}});const n=this.workflowExperiences.filter(o=>!!o.getWorkflow()),i=this.workflowExperiences.filter(o=>!o.getWorkflow()&&!!o.getTransaction().parentTransaction?.id).map(o=>o.getTransaction()),a=await TI(n.map(o=>{const l=o.getWorkflow();if(!l)throw new Error("Unable to create designs - Workflow not found!");const u=o.getProduct();if(!u)throw new Error("Unable to create designs - Product not found!");return{workflowManager:o.getWorkflowManager(),workflow:l,layouts:o.getWorkflowManager().getLayouts(),getReducerState:()=>o.getCommandContext().getState(),product:u,transaction:o.getTransaction(),workflowSelections:o.getWorkflowManager().getWorkflowSelections(),designName:l.name,workflowMetadata:o.getWorkflowManager().getWorkflowMetadata()}}),t?(o,l)=>{const u=n.find(c=>c.getTransaction().id===l);return u?t(u,o):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+l),Promise.resolve(void 0))}:void 0),s=new Map;return n.forEach((o,l)=>{s.set(o.getTransaction().id,a[l])}),await U9(i),V9(s,i),{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const e=this.workflowExperiences.map(t=>({transactionId:t.getTransaction().id,amountToOrder:t.getTransaction().quantity||1}));return await this.getClient().placeOrder(e)}getPreviewService(){return this.previewService}async setPreviewService(e){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(t=>t.getWorkflowManager().ejectFromPreviewService()),e))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t);e&&e.registerModelLoadEventListener&&e.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==e&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=e}async assignGlobalPropertyConfiguration(e){await ze.getShadowGraphqlClient().mutate({mutation:h9,variables:{bundleId:this.id,globalPropertyConfigurationId:e},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=e}async assignProductCollection(e){const t=await ze.getShadowGraphqlClient().mutate({mutation:f9(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:e??""},context:{bundleOwnerId:this.ownerId}});if(t.data?.bundleAssignProductCollection.productCollection){this.productCollection=t.data.bundleAssignProductCollection.productCollection;const n=this.getGlobalPropertyConfiguration();this.globalPropertyStateManager.setConfiguration(n),await this.globalPropertyHandleService.getHandles(),this.globalConfigurationPropertyId=n?.id,await this.clearOldProducts(this.workflowExperiences)}}onModelLoadEvent(e){e.eventType==="unload"||!e.modelContainer||(e.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(e.modelContainer,!0)),e.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(e.modelContainer,!1)))}onModelSelectedEvent(e,t){if(e&&e.metadata&&e.metadata instanceof Map&&e.metadata.has("workflowManager")){const i=e.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),a=this.workflowExperiences.find(s=>s.getTransaction().id===i.id);a&&this.fireEvent(t?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:a})}}async injectExperienceIntoPreviewService(e){this.previewService&&await e.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingWorkflowExperiences(e,t,n){let i=[];if(e.length>0&&(i=await this.client.getWorkflowExperiences(e.map(a=>({type:"transaction",transactionId:a})),t,void 0,n),i.forEach(a=>a.setBundle(this)),i.forEach(a=>a.checkForPriceBreakChanges()),this.workflowExperiences=i,this.previewService))for(const a of i)await this.injectExperienceIntoPreviewService(a);await this.clearOldProducts(i)}async clearOldProducts(e){if(!this.globalPropertyStateManager.getBundleOptions()?.readonly){const t=this.getProductIds()||[],n=this.getProductCollection();if(n&&t.length>0){await n.fetchProducts();const i=n.getProducts(),a=[],s=[];for(const l of t)if(!i.find(c=>c.getId()===l)){for(const c of e)c.getProduct()?.id===l&&s.push(c);a.push(l)}const o=[];a.length>0&&o.push(this.removeProductIds(a)),s.length>0&&o.push(Promise.all(s.map(l=>l.clearProduct()))),o.length>0&&await Promise.all(o)}}}async updateBundle(){if(!(await ze.getShadowGraphqlClient().mutate({mutation:Sp,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([t,n])=>({key:t,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await ze.getShadowGraphqlClient().mutate({mutation:d9,variables:{id:this.id,transactionIds:this.workflowExperiences.map(e=>e.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(e,t){if(this.updatesLocked)return;const n=await this.globalPropertyHandleService.getHandles(),i=this.globalPropertyHandleService.applyConditionsFromState(n,e),a=this.globalPropertyHandleService.applyConditionsFromState(n,t);this.checkConditionalHandlesChanged(i,a),this.checkMandatoryHandlesChanged(e,a);const s=this.getGlobalPropertyStateManager();let o=[];for(const f of n)a.find(d=>d.getName()==f.getName())||(o=[...o,f.getName()]);await s.clearAspects(o);const l=a.map(f=>{if(f.getType()===Hn.ColorOption||f.getType()===Hn.Option){const d=f;if(!t.aspects.find(g=>g.name===d.getName()))return d.initDefaultVariant()}});await Promise.all(l),await Promise.all(a.map(f=>f.applyGlobalState()));const u=this.globalPropertyStateManager.getGlobalPropertyState(),c=this.globalPropertyHandleService.applyConditionsFromState(n,u);vf(a.sort(),c.sort())||(this.checkConditionalHandlesChanged(a,c),this.checkMandatoryHandlesChanged(u,c),await this.onGlobalPropertiesChanged(t,u))}checkConditionalHandlesChanged(e,t){(()=>{if(e.length!==t.length)return!0;for(let a=0;a<e.length;a++)if(e[a].getName()!==t[a].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:t})}checkMandatoryHandlesChanged(e,t){const n=[],i=[],a=[],s=RI(e);t.forEach(o=>{if(o.isMandatory()){const l=o.isMandatoryFulfilled();l?i.push(o):a.push(o);const u=s.get(o.getName());(u===void 0||u!==l)&&n.push(o)}}),this.fireEvent("global-properties-mandatory-changed",{changed:n,completed:i,remaining:a})}fireEvent(e,t){this.eventEmitter.emit(e,t)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(e,t){await ze.getShadowGraphqlClient().mutate({mutation:m9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:e,stakeholderId:t}})}async reject(e,t){await ze.getShadowGraphqlClient().mutate({mutation:v9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:e,stakeholderId:t}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const gV=Se`
2888
+ `;class DE{constructor(e,t,n,i,a,s,o){this.workflowExperiences=[],this.eventEmitter=new hV,this.updatesLocked=!1,this.client=e,this.id=t.id,this.name=t.name||"",this.dispatchDate=t.dispatchDate,this.purchaseOrder=t.purchaseOrder,this.template=t.template||!1,this.test=t.test||!1,this.quoteId=t.quoteId,this.shareActions=t.bundleShareActions,this.workflowViewerLink=t.workflowViewerLink,this.workflowViewerAmendLink=t.workflowViewerAmendLink,this.ownerId=a,this.metadata=new Map(t.metadata?.map(u=>[u.key,u.value])||[]),this.completed=t.completed??!1,this.productCollection=t.productCollection,this.activation=t.activation,this.bundleStateManager=new lV(t.bundleStateData);const l=this.getGlobalPropertyConfiguration();this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new oV(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),s),this.globalPropertyHandleService=new Z9(this),this.setPreviewService(n),this.initializationPromise=(async()=>{if(!s?.readonly){const u=this.bundleStateManager.getState();if(u.integrationProductIds&&u.integrationProductIds.length>0){const c=await ze.getShadowGraphqlClient().query({query:yT,variables:{ids:u.integrationProductIds},errorPolicy:"all",fetchPolicy:"no-cache"});if(c.errors)throw new Error(`Failed to fetch integration products for Bundle ${t.id}`);const f=c.data.integrationProducts?.filter(h=>!!h.product?.id&&u.integrationProductIds.includes(h.id)).map(h=>h.product.id);u.integrationProductIds=[],u.productIds=Array.from(new Set([...u.productIds||[],...f||[]]));const d=JSON.stringify(u);this.bundleStateManager.setState(d),await ze.getShadowGraphqlClient().mutate({mutation:Sp,variables:{id:this.id,bundleStateData:d},context:{bundleOwnerId:a}})}}return Promise.all([this.loadExistingWorkflowExperiences(t.transactionIds||[],{...i,bundleOwnerId:a},o),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>new Promise((u,c)=>{if(s?.readonly){u([]);return}console.log("Setting default global variants."),this.initializeUninitializedHandles().then(u).catch(c)}))})(),this.initializationPromise.catch(u=>{console.error(`Bundle initialization failed: ${u}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(u=>this.checkMandatoryHandlesChanged(void 0,u))})}async initializeUninitializedHandles(){const e=this.globalPropertyStateManager.getGlobalPropertyState();if(!e)return console.log("Attempted to set global default variant before state was initialized."),[];const n=(await this.globalPropertyHandleService.getHandles()).map(async i=>{if(i.getType()===Hn.ColorOption||i.getType()===Hn.Option){const a=i;if(!e.aspects.find(o=>o.name===a.getName()))try{return await a.initDefaultVariant()}catch(o){console.error(`Failed to initialize default global variant - ${o}`)}}});return Promise.all(n)}getProductIds(){return this.bundleStateManager.getState()?.productIds}async addProductId(e){const t=this.bundleStateManager.getState();if(t){if(!t.productIds)t.productIds=[];else if(t.productIds.some(i=>i===e)){this.fireEvent("bundle-products-added",{productIds:t.productIds,added:[]});return}t.productIds=[...t.productIds,e];const n=JSON.stringify(t);this.bundleStateManager.setState(n),this.fireEvent("bundle-products-added",{productIds:t.productIds,added:[e]}),await ze.getShadowGraphqlClient().mutate({mutation:Sp,variables:{id:this.id,bundleStateData:n},context:{bundleOwnerId:this.ownerId}})}}async removeProductIds(e){const t=this.bundleStateManager.getState();if(t){const n=e.filter(a=>(t.productIds??[]).includes(a));if(n.length===0)return;t.productIds=(t.productIds??[]).filter(a=>!n.includes(a));const i=JSON.stringify(t);this.bundleStateManager.setState(i),this.fireEvent("bundle-products-removed",{productIds:t.productIds,removed:n}),await ze.getShadowGraphqlClient().mutate({mutation:Sp,variables:{id:this.id,bundleStateData:i},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}getTest(){return this.test}async generateQuoteId(){const t=(await ze.getShadowGraphqlClient().mutate({mutation:mV,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=t,t||""}async attachAddress(e,t,n,i,a,s){await ze.getShadowGraphqlClient().mutate({mutation:pV,variables:{bundleId:this.id,streetAddress:e||void 0,apartment:t||void 0,city:n||void 0,country:i||void 0,state:a||void 0,postCode:s||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(e){await ze.getShadowGraphqlClient().mutate({mutation:gV,variables:{bundleId:this.id,organizationName:e},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(e){this.globalPropertyStateManager.setBundleOptions(e)}getInitializationPromise(){return this.initializationPromise}addEventListener(e,t){this.eventEmitter.on(e,t)}removeEventListener(e,t){this.eventEmitter.off(e,t)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(e){return this.name=e,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(e){return this.dispatchDate=e,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(e){return this.purchaseOrder=e,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(e){return this.metadata=new Map(e),this.updateBundle()}setNameAndMetadata(e,t){return this.name=e,this.metadata=new Map(t),this.updateBundle()}hasGlobalProperties(){return!!this.getGlobalPropertyConfiguration()}getGlobalPropertyConfiguration(){return this.activation?.globalPropertyConfiguration??this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(e){this.updatesLocked=!0;const t=await this.globalPropertyHandleService.getHandles();try{for(const n of e.aspects){const i=n?.name;await this.getGlobalPropertyStateManager().setAspect(i,n.value,void 0,void 0,n.hidden)}for(const n of e.aspects){const i=n?.name,a=t.find(s=>s.getName()===i);if(a)switch(n.type){case Hn.FileUpload:{const s=a,o=await ag([n.value]);o.length>0&&await s.selectImage(o[0]);const l=n.storage?.colors;if(l){const u=Object.fromEntries(l.map(c=>[c.key,{browserValue:c.browserValue,pmsValue:c.pmsValue}])??[]);await s.changeColors(u)}break}case Hn.ColorOption:{const s=a,l=(await s.getAllVariants()).find(c=>c.getId()===n.value),u=n.storage?n.storage:void 0;l&&await s.selectVariant(l),u?.customColor&&s.setCustomColor(u.customColor);break}case Hn.Option:{const s=a,l=(await s.getAllVariants()).find(u=>u.getId()===n.value);l&&await s.selectVariant(l);break}case Hn.Text:{await a.setText(n.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(n=>n.getType()===Hn.Option).map(n=>n.getCurrentVariant()?.getPrice()||0).reduce((n,i)=>n+i,0)}getTotalSubunits(){return this.workflowExperiences.map(e=>e.getTotalPriceSubunits()).reduce((e,t)=>e+t,0)}getProductCollection(){return this.productCollection?new _1(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(e){for(const t of e.getStepsByType(Xe.Illustration)){const n=t.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const i of n){const a=this.getGlobalPropertyConfiguration()?.aspects.find(s=>s.name===i);if(a&&a.type===Hn.ColorOption){const s=t.getCurrentVariant()?.getAssetResource(),o=s?.assetConfiguration?.channelNumbers||[],l=s?.assetConfiguration?.defaultColorVariants||[],u=DI(this,i),c=[...new Set(o.map(d=>d.number))];if(c.length>u)for(const d of c){const h=this.getGlobalPropertyStateManager(),g=l.find(v=>v.channelNumber===d);g&&await h.setAspect(i,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(e){await this.initializeAdditionalRequiredColorChannels(e),e.setBundle(this),await this.appendWorkflowExperience(e),await this.injectExperienceIntoPreviewService(e),await e.getWorkflowManager().getInitializationPromise();const t=await this.getGlobalProperties();for(const n of t)await n.applyGlobalState([e]);this.fireEvent("workflow-experience-added",{workflowExperiences:[e]})}async addWorkflowExperiences(e){for(const o of e)await this.initializeAdditionalRequiredColorChannels(o);const t=e.map(o=>o.getTransaction().id),n=t.map(o=>this.workflowExperiences.find(l=>l.getTransaction().id===o));if(n.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+n.filter(o=>!!o).map(o=>o?.getTransaction().id).join(", "));const i=wr.getMap("transactionOwnerIds")||new Map,a=t.map(o=>i.get(o));await ze.getShadowGraphqlClient().mutate({mutation:o9,variables:{id:this.id,transactionIds:t,transactionOwnerIds:a},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...e);const s=async()=>{for(const l of e)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(e.map(l=>l.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const l of o)await l.applyGlobalState(e)};await Promise.all([this.updateTransactionOrder(),s()]),await this.initializeUninitializedHandles(),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(e,t=!0){const n=e.getTransaction().id;if(this.workflowExperiences.find(o=>o.getTransaction().id===n))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(wr.getMap("transactionOwnerIds")||new Map).get(n);await ze.getShadowGraphqlClient().mutate({mutation:s9,variables:{id:this.id,transactionId:n},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),t&&(this.workflowExperiences.push(e),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(e){const t=this.workflowExperiences.indexOf(e);await this.removeTransaction(t,this.workflowExperiences[t].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[e]})}async removeWorkflowExperiences(e){await this.removeTransactions(e.map(t=>t.getTransaction()))}async removeWorkflowExperienceByTransaction(e){const t=this.workflowExperiences.findIndex(n=>n.getTransaction().id===e.id);await this.removeTransaction(t,e)}async removeWorkflowExperiencesByTransactions(e){await this.removeTransactions(e)}async removeTransaction(e,t,n=!0){if(e>-1){const i=this.workflowExperiences.find(a=>a.getTransaction().id===t.id);if(i.setBundle(void 0),this.previewService&&i.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(t.id),await ze.getShadowGraphqlClient().mutate({mutation:l9,variables:{id:this.id,transactionId:t.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,s])=>({key:a,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),n){const a=this.workflowExperiences.splice(e,1);this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),i.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:a})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+t.id)}async removeTransactions(e){const t=e.map(i=>this.workflowExperiences.findIndex(a=>a.getTransaction().id===i.id));if(t.some(i=>i===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+e.filter((i,a)=>t[a]===-1).map(i=>i.id).join(", "));const n=e.map(i=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(a=>a.getTransaction().id===i.id),1)[0]);n.forEach(i=>i.setBundle(void 0)),[...this.workflowExperiences,...n].forEach(i=>i.checkForPriceBreakChanges()),this.previewService&&n.forEach(i=>i.getWorkflowManager().ejectFromPreviewService()),e.forEach(i=>this.bundleStateManager.removeStateForTransaction(i.id)),await ze.getShadowGraphqlClient().mutate({mutation:u9,variables:{id:this.id,transactionIds:e.map(i=>i.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,a])=>({key:i,value:a})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:n}),await this.updateTransactionOrder()}async insertWorkflowExperience(e,t){await this.appendWorkflowExperience(e,!1),this.workflowExperiences.splice(t,0,e),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async replaceWorkflowExperience(e,t){if(e<0||e>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const n=this.workflowExperiences[e];if(n.getTransaction().id===t.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(e,n.getTransaction(),!1),this.appendWorkflowExperience(t,!1)]),this.workflowExperiences[e]=t,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const i=await this.getGlobalProperties();await Promise.all(i.map(a=>a.applyGlobalState([t])))})()])}async swapWorkflowExperiences(e,t){if(e<0||e>=this.workflowExperiences.length||t<0||t>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(e===t)return;const n=this.workflowExperiences[e];this.workflowExperiences[e]=this.workflowExperiences[t],this.workflowExperiences[t]=n,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}getTopLevelWorkflowExperiences(){return this.workflowExperiences.filter(e=>!e.getTransaction().parentTransaction)}getChildWorkflowExperiences(e){return this.workflowExperiences.filter(t=>t.getTransaction().parentTransaction?.id===e)}async sortWorkflowExperiences(e){this.workflowExperiences=this.workflowExperiences.sort(e),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(e,t){const n=await ze.getShadowGraphqlClient().mutate({mutation:c9,variables:{id:this.id,details:e,type:t||GA.Owner},context:{bundleOwnerId:this.ownerId}});if(!n.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const i=n.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(i)}async removeStakeholder(e){if(!(await ze.getShadowGraphqlClient().mutate({mutation:d9,variables:{id:this.id,emailAddress:e},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(e){const t=await ze.getShadowGraphqlClient().mutate({mutation:f9,variables:{id:this.id,input:e},context:{bundleOwnerId:this.ownerId}});if(!t.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const n=t.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async getAllStakeholders(){const e=await ze.getShadowGraphqlClient().query({query:CE,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!e.data.bundles||e.data.bundles.length===0)throw new Error("Bundle not found!");const t=e.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(t),t}async getCurrentStakeholder(){const e=await ze.getShadowGraphqlClient().query({query:CE,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!e.data.bundles||e.data.bundles.length===0)throw new Error("Bundle not found!");return e.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(e){e.forEach(t=>{t.customer&&this.client.storeCustomer(t.customer)})}async finish(e,t){this.completed&&await ze.getShadowGraphqlClient().mutate({mutation:v9,variables:{bundleId:this.id}});const n=this.workflowExperiences.filter(o=>!!o.getWorkflow()),i=this.workflowExperiences.filter(o=>!o.getWorkflow()&&!!o.getTransaction().parentTransaction?.id).map(o=>o.getTransaction()),a=await TI(n.map(o=>{const l=o.getWorkflow();if(!l)throw new Error("Unable to create designs - Workflow not found!");const u=o.getProduct();if(!u)throw new Error("Unable to create designs - Product not found!");return{workflowManager:o.getWorkflowManager(),workflow:l,layouts:o.getWorkflowManager().getLayouts(),getReducerState:()=>o.getCommandContext().getState(),product:u,transaction:o.getTransaction(),workflowSelections:o.getWorkflowManager().getWorkflowSelections(),designName:l.name,workflowMetadata:o.getWorkflowManager().getWorkflowMetadata()}}),t?(o,l)=>{const u=n.find(c=>c.getTransaction().id===l);return u?t(u,o):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+l),Promise.resolve(void 0))}:void 0),s=new Map;return n.forEach((o,l)=>{s.set(o.getTransaction().id,a[l])}),await z9(i),$9(s,i),{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const e=this.workflowExperiences.map(t=>({transactionId:t.getTransaction().id,amountToOrder:t.getTransaction().quantity||1}));return await this.getClient().placeOrder(e)}getPreviewService(){return this.previewService}async setPreviewService(e){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(t=>t.getWorkflowManager().ejectFromPreviewService()),e))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t);e&&e.registerModelLoadEventListener&&e.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==e&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=e}async assignGlobalPropertyConfiguration(e){await ze.getShadowGraphqlClient().mutate({mutation:g9,variables:{bundleId:this.id,globalPropertyConfigurationId:e},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=e}async assignProductCollection(e){const t=await ze.getShadowGraphqlClient().mutate({mutation:p9(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:e??""},context:{bundleOwnerId:this.ownerId}});if(t.data?.bundleAssignProductCollection.productCollection){this.productCollection=t.data.bundleAssignProductCollection.productCollection;const n=this.getGlobalPropertyConfiguration();this.globalPropertyStateManager.setConfiguration(n),await this.globalPropertyHandleService.getHandles(),this.globalConfigurationPropertyId=n?.id,await this.clearOldProducts(this.workflowExperiences)}}onModelLoadEvent(e){e.eventType==="unload"||!e.modelContainer||(e.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(e.modelContainer,!0)),e.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(e.modelContainer,!1)))}onModelSelectedEvent(e,t){if(e&&e.metadata&&e.metadata instanceof Map&&e.metadata.has("workflowManager")){const i=e.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),a=this.workflowExperiences.find(s=>s.getTransaction().id===i.id);a&&this.fireEvent(t?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:a})}}async injectExperienceIntoPreviewService(e){this.previewService&&await e.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingWorkflowExperiences(e,t,n){let i=[];if(e.length>0&&(i=await this.client.getWorkflowExperiences(e.map(a=>({type:"transaction",transactionId:a})),t,void 0,n),i.forEach(a=>a.setBundle(this)),i.forEach(a=>a.checkForPriceBreakChanges()),this.workflowExperiences=i,this.previewService))for(const a of i)await this.injectExperienceIntoPreviewService(a);await this.clearOldProducts(i)}async clearOldProducts(e){if(!this.globalPropertyStateManager.getBundleOptions()?.readonly){const t=this.getProductIds()||[],n=this.getProductCollection();if(n&&t.length>0){await n.fetchProducts();const i=n.getProducts(),a=[],s=[];for(const l of t)if(!i.find(c=>c.getId()===l)){for(const c of e)c.getProduct()?.id===l&&s.push(c);a.push(l)}const o=[];a.length>0&&o.push(this.removeProductIds(a)),s.length>0&&o.push(Promise.all(s.map(l=>l.clearProduct()))),o.length>0&&await Promise.all(o)}}}async updateBundle(){if(!(await ze.getShadowGraphqlClient().mutate({mutation:Sp,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([t,n])=>({key:t,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await ze.getShadowGraphqlClient().mutate({mutation:h9,variables:{id:this.id,transactionIds:this.workflowExperiences.map(e=>e.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(e,t){if(this.updatesLocked)return;const n=await this.globalPropertyHandleService.getHandles(),i=this.globalPropertyHandleService.applyConditionsFromState(n,e),a=this.globalPropertyHandleService.applyConditionsFromState(n,t);this.checkConditionalHandlesChanged(i,a),this.checkMandatoryHandlesChanged(e,a);const s=this.getGlobalPropertyStateManager();let o=[];for(const f of n)a.find(d=>d.getName()==f.getName())||(o=[...o,f.getName()]);await s.clearAspects(o);const l=a.map(f=>{if(f.getType()===Hn.ColorOption||f.getType()===Hn.Option){const d=f;if(!t.aspects.find(g=>g.name===d.getName()))return d.initDefaultVariant()}});await Promise.all(l),await Promise.all(a.map(f=>f.applyGlobalState()));const u=this.globalPropertyStateManager.getGlobalPropertyState(),c=this.globalPropertyHandleService.applyConditionsFromState(n,u);vf(a.sort(),c.sort())||(this.checkConditionalHandlesChanged(a,c),this.checkMandatoryHandlesChanged(u,c),await this.onGlobalPropertiesChanged(t,u))}checkConditionalHandlesChanged(e,t){(()=>{if(e.length!==t.length)return!0;for(let a=0;a<e.length;a++)if(e[a].getName()!==t[a].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:t})}checkMandatoryHandlesChanged(e,t){const n=[],i=[],a=[],s=RI(e);t.forEach(o=>{if(o.isMandatory()){const l=o.isMandatoryFulfilled();l?i.push(o):a.push(o);const u=s.get(o.getName());(u===void 0||u!==l)&&n.push(o)}}),this.fireEvent("global-properties-mandatory-changed",{changed:n,completed:i,remaining:a})}fireEvent(e,t){this.eventEmitter.emit(e,t)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(e,t){await ze.getShadowGraphqlClient().mutate({mutation:y9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:e,stakeholderId:t}})}async reject(e,t){await ze.getShadowGraphqlClient().mutate({mutation:A9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:e,stakeholderId:t}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const vV=Se`
2889
2889
  mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
2890
2890
  processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
2891
2891
  id
2892
2892
  }
2893
2893
  }
2894
- `;class BI{async execute(e,t,n){const a=(await ze.getShadowGraphqlClient().mutate({mutation:gV,variables:{processFlowId:e,inputs:[...t.map(f=>f.getValueForTransmission())]}})).data?.processExecutionCreate?.id;if(!a)throw new Error("Failed to create process execution.");function s(f){return new Promise(d=>{setTimeout(d,f)})}let o=!1,l=0,u,c;for(;!o;){u=await ze.getShadowGraphqlClient().query({query:Se`
2894
+ `;class BI{async execute(e,t,n){const a=(await ze.getShadowGraphqlClient().mutate({mutation:vV,variables:{processFlowId:e,inputs:[...t.map(f=>f.getValueForTransmission())]}})).data?.processExecutionCreate?.id;if(!a)throw new Error("Failed to create process execution.");function s(f){return new Promise(d=>{setTimeout(d,f)})}let o=!1,l=0,u,c;for(;!o;){u=await ze.getShadowGraphqlClient().query({query:Se`
2895
2895
  query getProcessFlowExecution($ids: [String]!) {
2896
2896
  processExecutions(ids: $ids) {
2897
2897
  id
@@ -2904,7 +2904,7 @@ Minimum version required to store current data is: `+q+`.
2904
2904
  }
2905
2905
  }
2906
2906
  }
2907
- `,variables:{ids:[a]}});const f=u.data?.processExecutions[0];if(!u||!f)throw new Error("Failed to retrieve server response for execution.");if(f.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(f.completedAt){o=!0,c=new MI(f);break}l+=1;const d=n?.repeats?n?.repeats:5;if(l>=d)throw new Error("Maximum wait time exceeded for execution result.");await s(n?.sleepTime?Math.max(n.sleepTime,500):2e3)}if(!c)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(c)}}class MI{constructor(e){this.execution=e}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(e=>new Vd(e))}getNodesByType(e){return this.execution.nodes.filter(t=>t.type===e).map(t=>new Vd(t))}getInputs(){return this.execution.nodes.filter(e=>e.type==="StartTerminal").map(e=>new Vd(e))}getOutputs(){return this.execution.nodes.filter(e=>e.type==="EndTerminal").map(e=>new Vd(e))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Vd{constructor(e){this.node=e}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(e){return this.getArtifacts().get(e)}}class N1{constructor(e){this.value=e}getRaw(){return this.value}getValueForTransmission(){const e=this.value;return e.startsWith("[")?JSON.stringify(JSON.parse(e)):e}}var _I=(r=>(r.Transaction="Transaction",r.Bundle="Bundle",r.Product="Product",r.Variant="Variant",r.Option="Option",r.LineItem="LineItem",r.Asset="Asset",r))(_I||{});class mV extends N1{constructor(e){super(`"${e}"`)}}class L1 extends N1{constructor(e,t){if(t!=="Asset"&&!L1.validUUID(e))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${e}", "type": "${t}"}`)}static validUUID(e){return e.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}class vV extends N1{constructor(e){super(`[${e.map(t=>t.getRaw()).join(",")}]`)}}class gA{constructor(e){this.integrationProduct=e}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.basePrice||0,t=this.integrationProduct?.additionalIntegrationProduct;if(!t)return e;if(t&&!t.product)throw new Error("An additional integration product was found, but it does not have a product");return e+(t.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.workflows||[];if(e.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return new oo(e[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.workflows||[];if(e.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return e.sort((t,n)=>(t.index??0)-(n.index??0)).map(t=>new oo(t))}}const Ov=Se`
2907
+ `,variables:{ids:[a]}});const f=u.data?.processExecutions[0];if(!u||!f)throw new Error("Failed to retrieve server response for execution.");if(f.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(f.completedAt){o=!0,c=new MI(f);break}l+=1;const d=n?.repeats?n?.repeats:5;if(l>=d)throw new Error("Maximum wait time exceeded for execution result.");await s(n?.sleepTime?Math.max(n.sleepTime,500):2e3)}if(!c)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(c)}}class MI{constructor(e){this.execution=e}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(e=>new Vd(e))}getNodesByType(e){return this.execution.nodes.filter(t=>t.type===e).map(t=>new Vd(t))}getInputs(){return this.execution.nodes.filter(e=>e.type==="StartTerminal").map(e=>new Vd(e))}getOutputs(){return this.execution.nodes.filter(e=>e.type==="EndTerminal").map(e=>new Vd(e))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Vd{constructor(e){this.node=e}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(e){return this.getArtifacts().get(e)}}class N1{constructor(e){this.value=e}getRaw(){return this.value}getValueForTransmission(){const e=this.value;return e.startsWith("[")?JSON.stringify(JSON.parse(e)):e}}var _I=(r=>(r.Transaction="Transaction",r.Bundle="Bundle",r.Product="Product",r.Variant="Variant",r.Option="Option",r.LineItem="LineItem",r.Asset="Asset",r))(_I||{});class yV extends N1{constructor(e){super(`"${e}"`)}}class L1 extends N1{constructor(e,t){if(t!=="Asset"&&!L1.validUUID(e))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${e}", "type": "${t}"}`)}static validUUID(e){return e.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}class AV extends N1{constructor(e){super(`[${e.map(t=>t.getRaw()).join(",")}]`)}}class gA{constructor(e){this.integrationProduct=e}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.basePrice||0,t=this.integrationProduct?.additionalIntegrationProduct;if(!t)return e;if(t&&!t.product)throw new Error("An additional integration product was found, but it does not have a product");return e+(t.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.workflows||[];if(e.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return new oo(e[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.workflows||[];if(e.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return e.sort((t,n)=>(t.index??0)-(n.index??0)).map(t=>new oo(t))}}const Ov=Se`
2908
2908
  query GetCustomer($emailAddress: String!) {
2909
2909
  customer(emailAddress: $emailAddress) {
2910
2910
  id
@@ -2925,7 +2925,7 @@ Minimum version required to store current data is: `+q+`.
2925
2925
  }
2926
2926
  }
2927
2927
  }
2928
- `,yV=Se`
2928
+ `,bV=Se`
2929
2929
  mutation CustomerCreate($details: CustomerDetailsInput!) {
2930
2930
  customerCreate(details: $details) {
2931
2931
  id
@@ -2974,11 +2974,11 @@ Minimum version required to store current data is: `+q+`.
2974
2974
  }
2975
2975
  }
2976
2976
  }
2977
- `;const AV=Se`
2977
+ `;const wV=Se`
2978
2978
  mutation CustomerGenerateVerificationCode($emailAddress: String!) {
2979
2979
  customerGenerateVerificationCode(emailAddress: $emailAddress)
2980
2980
  }
2981
- `,bV=Se`
2981
+ `,CV=Se`
2982
2982
  mutation CustomerVerifyCode($emailAddress: String!, $verificationCode: String!) {
2983
2983
  customerVerifyCode(emailAddress: $emailAddress, verificationCode: $verificationCode) {
2984
2984
  id
@@ -3018,7 +3018,7 @@ Minimum version required to store current data is: `+q+`.
3018
3018
  }
3019
3019
  }
3020
3020
  }
3021
- `,wV=Se`
3021
+ `,xV=Se`
3022
3022
  query CustomerMetafields($id: String!) {
3023
3023
  metafields(entityId: $id) {
3024
3024
  id
@@ -3036,13 +3036,13 @@ Minimum version required to store current data is: `+q+`.
3036
3036
  }
3037
3037
  }
3038
3038
  }
3039
- `;class CV{constructor(e,t=ze.getShadowGraphqlClient.bind(ze)){this.options=e,this.client=t}query(e){const t=this.options?.onQuery?this.options?.onQuery(e):{};return this.client().query({...t,...e,context:{...t.context??{},...e.context??{}}})}mutate(e){const t=this.options?.onMutate?this.options?.onMutate(e):{};return this.client().mutate({...t,...e,context:{...t.context??{},...e.context??{}}})}}function xV(r,e,t){return r.$source||(r.$source={}),r.$source[e]=t,r}const SV=r=>r?.body instanceof ReadableStream,fl=(r,e)=>{const t=[];if(r&&t.push(r),e)for(const n of e)t.push(n);return t},to=(r,e)=>`${r||"anonymous"}${e&&e.length>0?` (a.k.a. ${e.join(",")})`:""}`,bg=()=>{let r=[],e=[],t=!1;const n=new Set,i=f=>f.sort((d,h)=>RE[h.step]-RE[d.step]||OE[h.priority||"normal"]-OE[d.priority||"normal"]),a=f=>{let d=!1;const h=g=>{const v=fl(g.name,g.aliases);if(v.includes(f)){d=!0;for(const y of v)n.delete(y);return!1}return!0};return r=r.filter(h),e=e.filter(h),d},s=f=>{let d=!1;const h=g=>{if(g.middleware===f){d=!0;for(const v of fl(g.name,g.aliases))n.delete(v);return!1}return!0};return r=r.filter(h),e=e.filter(h),d},o=f=>(r.forEach(d=>{f.add(d.middleware,{...d})}),e.forEach(d=>{f.addRelativeTo(d.middleware,{...d})}),f.identifyOnResolve?.(c.identifyOnResolve()),f),l=f=>{const d=[];return f.before.forEach(h=>{h.before.length===0&&h.after.length===0?d.push(h):d.push(...l(h))}),d.push(f),f.after.reverse().forEach(h=>{h.before.length===0&&h.after.length===0?d.push(h):d.push(...l(h))}),d},u=(f=!1)=>{const d=[],h=[],g={};return r.forEach(y=>{const A={...y,before:[],after:[]};for(const C of fl(A.name,A.aliases))g[C]=A;d.push(A)}),e.forEach(y=>{const A={...y,before:[],after:[]};for(const C of fl(A.name,A.aliases))g[C]=A;h.push(A)}),h.forEach(y=>{if(y.toMiddleware){const A=g[y.toMiddleware];if(A===void 0){if(f)return;throw new Error(`${y.toMiddleware} is not found when adding ${to(y.name,y.aliases)} middleware ${y.relation} ${y.toMiddleware}`)}y.relation==="after"&&A.after.push(y),y.relation==="before"&&A.before.push(y)}}),i(d).map(l).reduce((y,A)=>(y.push(...A),y),[])},c={add:(f,d={})=>{const{name:h,override:g,aliases:v}=d,y={step:"initialize",priority:"normal",middleware:f,...d},A=fl(h,v);if(A.length>0){if(A.some(C=>n.has(C))){if(!g)throw new Error(`Duplicate middleware name '${to(h,v)}'`);for(const C of A){const S=r.findIndex(E=>E.name===C||E.aliases?.some(R=>R===C));if(S===-1)continue;const F=r[S];if(F.step!==y.step||y.priority!==F.priority)throw new Error(`"${to(F.name,F.aliases)}" middleware with ${F.priority} priority in ${F.step} step cannot be overridden by "${to(h,v)}" middleware with ${y.priority} priority in ${y.step} step.`);r.splice(S,1)}}for(const C of A)n.add(C)}r.push(y)},addRelativeTo:(f,d)=>{const{name:h,override:g,aliases:v}=d,y={middleware:f,...d},A=fl(h,v);if(A.length>0){if(A.some(C=>n.has(C))){if(!g)throw new Error(`Duplicate middleware name '${to(h,v)}'`);for(const C of A){const S=e.findIndex(E=>E.name===C||E.aliases?.some(R=>R===C));if(S===-1)continue;const F=e[S];if(F.toMiddleware!==y.toMiddleware||F.relation!==y.relation)throw new Error(`"${to(F.name,F.aliases)}" middleware ${F.relation} "${F.toMiddleware}" middleware cannot be overridden by "${to(h,v)}" middleware ${y.relation} "${y.toMiddleware}" middleware.`);e.splice(S,1)}}for(const C of A)n.add(C)}e.push(y)},clone:()=>o(bg()),use:f=>{f.applyToStack(c)},remove:f=>typeof f=="string"?a(f):s(f),removeByTag:f=>{let d=!1;const h=g=>{const{tags:v,name:y,aliases:A}=g;if(v&&v.includes(f)){const C=fl(y,A);for(const S of C)n.delete(S);return d=!0,!1}return!0};return r=r.filter(h),e=e.filter(h),d},concat:f=>{const d=o(bg());return d.use(f),d.identifyOnResolve(t||d.identifyOnResolve()||(f.identifyOnResolve?.()??!1)),d},applyToStack:o,identify:()=>u(!0).map(f=>{const d=f.step??f.relation+" "+f.toMiddleware;return to(f.name,f.aliases)+" - "+d}),identifyOnResolve(f){return typeof f=="boolean"&&(t=f),t},resolve:(f,d)=>{for(const h of u().map(g=>g.middleware).reverse())f=h(f,d);return t&&console.log(c.identify()),f}};return c},RE={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},OE={high:3,normal:2,low:1};var xf;(function(r){r.HTTP="http",r.HTTPS="https"})(xf||(xf={}));var Sf;(function(r){r.MD5="md5",r.CRC32="crc32",r.CRC32C="crc32c",r.SHA1="sha1",r.SHA256="sha256"})(Sf||(Sf={}));const mA="__smithy_context",vc=r=>r[mA]||(r[mA]={});class na{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){const t=new na({...e,headers:{...e.headers}});return t.query&&(t.query=EV(t.query)),t}static isInstance(e){if(!e)return!1;const t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&typeof t.query=="object"&&typeof t.headers=="object"}clone(){return na.clone(this)}}function EV(r){return Object.keys(r).reduce((e,t)=>{const n=r[t];return{...e,[t]:Array.isArray(n)?[...n]:n}},{})}class sc{statusCode;reason;headers;body;constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;const t=e;return typeof t.statusCode=="number"&&typeof t.headers=="object"}}const kV=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Kg=(r,e=!1)=>{if(!e)return kV.test(r);const t=r.split(".");for(const n of t)if(!Kg(n))return!1;return!0},Bs=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};function TV(r){const e={};if(r=r.replace(/^\?/,""),r)for(const t of r.split("&")){let[n,i=null]=t.split("=");n=decodeURIComponent(n),i&&(i=decodeURIComponent(i)),n in e?Array.isArray(e[n])?e[n].push(i):e[n]=[e[n],i]:e[n]=i}return e}const wg=r=>{if(typeof r=="string")return wg(new URL(r));const{hostname:e,pathname:t,port:n,protocol:i,search:a}=r;let s;return a&&(s=TV(a)),{hostname:e,port:n?parseInt(n):void 0,protocol:i,path:t,query:s}},U1=r=>{if(typeof r=="object"){if("url"in r){const e=wg(r.url);if(r.headers){e.headers={};for(const t in r.headers)e.headers[t.toLowerCase()]=r.headers[t].join(", ")}return e}return r}return wg(r)},FV=r=>()=>Promise.reject(r);class IV{config;middlewareStack=bg();initConfig;handlers;constructor(e){this.config=e;const{protocol:t,protocolSettings:n}=e;n&&typeof t=="function"&&(e.protocol=new t(n))}send(e,t,n){const i=typeof t!="function"?t:void 0,a=typeof t=="function"?t:n,s=i===void 0&&this.config.cacheMiddleware===!0;let o;if(s){this.handlers||(this.handlers=new WeakMap);const l=this.handlers;l.has(e.constructor)?o=l.get(e.constructor):(o=e.resolveMiddleware(this.middlewareStack,this.config,i),l.set(e.constructor,o))}else delete this.handlers,o=e.resolveMiddleware(this.middlewareStack,this.config,i);if(a)o(e).then(l=>a(null,l.output),l=>a(l)).catch(()=>{});else return o(e).then(l=>l.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const Yp=r=>typeof r=="function"?r():r,NI=(r,e,t,n,i)=>({name:e,namespace:r,traits:t,input:n,output:i}),PV=r=>(e,t)=>async n=>{const{response:i}=await e(n),{operationSchema:a}=vc(t),[,s,o,l,u,c]=a??[];try{const f=await r.protocol.deserializeResponse(NI(s,o,l,u,c),{...r,...t},i);return{response:i,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){const d="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{f.message+=`
3040
- `+d}catch{!t.logger||t.logger?.constructor?.name==="NoOpLogger"?console.warn(d):t.logger?.warn?.(d)}typeof f.$responseBodyText<"u"&&f.$response&&(f.$response.body=f.$responseBodyText);try{if(sc.isInstance(i)){const{headers:h={},statusCode:g}=i,v=Object.entries(h);f.$metadata={httpStatusCode:g,requestId:Bv(/^x-[\w-]+-request-?id$/,v),extendedRequestId:Bv(/^x-[\w-]+-id-2$/,v),cfId:Bv(/^x-[\w-]+-cf-id$/,v)}}}catch{}}throw f}},Bv=(r,e)=>(e.find(([t])=>t.match(r))||[void 0,void 0])[1],DV=r=>(e,t)=>async n=>{const{operationSchema:i}=vc(t),[,a,s,o,l,u]=i??[],c=t.endpointV2?async()=>U1(t.endpointV2):r.endpoint,f=await r.protocol.serializeRequest(NI(a,s,o,l,u),n.input,{...r,...t,endpoint:c});return e({...n,request:f})},RV={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},OV={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function BV(r){return{applyToStack:e=>{e.add(DV(r),OV),e.add(PV(r),RV),r.protocol.setSerdeContext(r)}}}const Mv=[];function zd(r){if(typeof r=="object")return r;if(r=r|0,Mv[r])return Mv[r];const e={};let t=0;for(const n of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(r>>t++&1)===1&&(e[n]=1);return Mv[r]=e}const kd={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},_v=[],Nv={};class vi{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=vi.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,t){this.ref=e,this.memberName=t;const n=[];let i=e,a=e;for(this._isMemberSchema=!1;Lv(i);)n.push(i[1]),i=i[0],a=Yp(i),this._isMemberSchema=!0;if(n.length>0){this.memberTraits={};for(let s=n.length-1;s>=0;--s){const o=n[s];Object.assign(this.memberTraits,zd(o))}}else this.memberTraits=0;if(a instanceof vi){const s=this.memberTraits;Object.assign(this,a),this.memberTraits=Object.assign({},s,a.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??a.memberName;return}if(this.schema=Yp(a),MV(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(a),this.traits=0),this._isMemberSchema&&!t)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){const t=this.prototype.isPrototypeOf(e);return!t&&typeof e=="object"&&e!==null?e.symbol===this.symbol:t}static of(e){const t=typeof e=="function"||typeof e=="object"&&e!==null;if(typeof e=="number"){if(_v[e])return _v[e]}else if(typeof e=="string"){if(Nv[e])return Nv[e]}else if(t&&e[kd.ns])return e[kd.ns];const n=Yp(e);if(n instanceof vi)return n;if(Lv(n)){const[a,s]=n;if(a instanceof vi)return Object.assign(a.getMergedTraits(),zd(s)),a;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}const i=new vi(n);return t?e[kd.ns]=i:typeof n=="string"?Nv[n]=i:typeof n=="number"?_v[n]=i:i}getSchema(){const e=this.schema;return Array.isArray(e)&&e[0]===0?e[4]:e}getName(e=!1){const{name:t}=this;return!e&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){const e=this.getSchema();return typeof e=="number"?e>=64&&e<128:e[0]===1}isMapSchema(){const e=this.getSchema();return typeof e=="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){const e=this.getSchema();if(typeof e!="object")return!1;const t=e[0];return t===3||t===-3||t===4}isUnionSchema(){const e=this.getSchema();return typeof e!="object"?!1:e[0]===4}isBlobSchema(){const e=this.getSchema();return e===21||e===42}isTimestampSchema(){const e=this.getSchema();return typeof e=="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){const{streaming:e}=this.getMergedTraits();return!!e||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return zd(this.memberTraits)}getOwnTraits(){return zd(this.traits)}getKeySchema(){const[e,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!t)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);const n=this.getSchema(),i=e?15:n[4]??0;return Td([i,0],"key")}getValueSchema(){const e=this.getSchema(),[t,n,i]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],a=typeof e=="number"?63&e:e&&typeof e=="object"&&(n||i)?e[3+e[0]]:t?15:void 0;if(a!=null)return Td([a,0],n?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(e){const t=this.getSchema();if(this.isStructSchema()&&t[4].includes(e)){const n=t[4].indexOf(e),i=t[5][n];return Td(Lv(i)?i:[i,0],e)}if(this.isDocumentSchema())return Td([15,0],e);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${e}.`)}getMemberSchemas(){const e={};try{for(const[t,n]of this.structIterator())e[t]=n}catch{}return e}getEventStreamMember(){if(this.isStructSchema()){for(const[e,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return e}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");const e=this.getSchema(),t=e[4].length;let n=e[kd.it];if(n&&t===n.length){yield*n;return}n=Array(t);for(let i=0;i<t;++i){const a=e[4][i],s=Td([e[5][i],0],a);yield n[i]=[a,s]}e[kd.it]=n}}function Td(r,e){if(r instanceof vi)return Object.assign(r,{memberName:e,_isMemberSchema:!0});const t=vi;return new t(r,e)}const Lv=r=>Array.isArray(r)&&r.length===2,MV=r=>Array.isArray(r)&&r.length>=5;class Zi{namespace;schemas;exceptions;static registries=new Map;constructor(e,t=new Map,n=new Map){this.namespace=e,this.schemas=t,this.exceptions=n}static for(e){return Zi.registries.has(e)||Zi.registries.set(e,new Zi(e)),Zi.registries.get(e)}copyFrom(e){const{schemas:t,exceptions:n}=this;for(const[i,a]of e.schemas)t.has(i)||t.set(i,a);for(const[i,a]of e.exceptions)n.has(i)||n.set(i,a)}register(e,t){const n=this.normalizeShapeId(e);for(const i of[this,Zi.for(n.split("#")[0])])i.schemas.set(n,t)}getSchema(e){const t=this.normalizeShapeId(e);if(!this.schemas.has(t)){if(!e.includes("#")){const n="#"+e,i=[];for(const[a,s]of this.schemas.entries())a.endsWith(n)&&i.push(s);if(i.length===1)return i[0]}throw new Error(`@smithy/core/schema - schema not found for ${t}`)}return this.schemas.get(t)}registerError(e,t){const n=e,i=n[1];for(const a of[this,Zi.for(i)])a.schemas.set(i+"#"+n[2],n),a.exceptions.set(n,t)}getErrorCtor(e){const t=e;return this.exceptions.has(t)?this.exceptions.get(t):Zi.for(t[1]).exceptions.get(t)}getBaseException(){for(const e of this.exceptions.keys())if(Array.isArray(e)){const[,t,n]=e,i=t+"#"+n;if(i.startsWith("smithy.ts.sdk.synthetic.")&&i.endsWith("ServiceException"))return e}}find(e){for(const t of this.schemas.values())if(e(t))return t}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(e){return e.includes("#")?e:this.namespace+"#"+e}}const Uv="***SensitiveInformation***";function vA(r,e){if(e==null)return e;const t=vi.of(r);if(t.getMergedTraits().sensitive)return Uv;if(t.isListSchema()){if(!!t.getValueSchema().getMergedTraits().sensitive)return Uv}else if(t.isMapSchema()){if(!!t.getKeySchema().getMergedTraits().sensitive||!!t.getValueSchema().getMergedTraits().sensitive)return Uv}else if(t.isStructSchema()&&typeof e=="object"){const n=e,i={};for(const[a,s]of t.structIterator())n[a]!=null&&(i[a]=vA(s,n[a]));return i}return e}class V1{middlewareStack=bg();schema;static classBuilder(){return new _V}resolveMiddlewareWithContext(e,t,n,{middlewareFn:i,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,smithyContext:u,additionalContext:c,CommandCtor:f}){for(const A of i.bind(this)(f,e,t,n))this.middlewareStack.use(A);const d=e.concat(this.middlewareStack),{logger:h}=t,g={logger:h,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,[mA]:{commandInstance:this,...u},...c},{requestHandler:v}=t;let y=n??{};return u.eventStream&&(y={isEventStream:!0,...y}),d.resolve(A=>v.handle(A.request,y),g)}}class _V{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,n={}){return this._smithyContext={service:e,operation:t,...n},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=n=>n,t=n=>n){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){const e=this;let t;return t=class extends V1{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[n]){super(),this.input=n??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(n,i,a){const s=e._operationSchema,o=s?.[4]??s?.input,l=s?.[5]??s?.output;return this.resolveMiddlewareWithContext(n,i,a,{CommandCtor:t,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(s?vA.bind(null,o):u=>u),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?vA.bind(null,l):u=>u),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}class Lu extends Error{$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;const t=e;return Lu.prototype.isPrototypeOf(t)||!!t.$fault&&!!t.$metadata&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;const t=e;return this===Lu?Lu.isInstance(e):Lu.isInstance(e)?t.name&&this.name?this.prototype.isPrototypeOf(e)||t.name===this.name:this.prototype.isPrototypeOf(e):!1}}const BE=(r,e={})=>{Object.entries(e).filter(([,n])=>n!==void 0).forEach(([n,i])=>{(r[n]==null||r[n]==="")&&(r[n]=i)});const t=r.message||r.Message||"UnknownError";return r.message=t,delete r.Message,r},NV=r=>{switch(r){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},LI=Object.values(Sf),LV=r=>{const e=[];for(const t in Sf){const n=Sf[t];r[n]!==void 0&&e.push({algorithmId:()=>n,checksumConstructor:()=>r[n]})}for(const[t,n]of Object.entries(r.checksumAlgorithms??{}))e.push({algorithmId:()=>t,checksumConstructor:()=>n});return{addChecksumAlgorithm(t){r.checksumAlgorithms=r.checksumAlgorithms??{};const n=t.algorithmId(),i=t.checksumConstructor();LI.includes(n)?r.checksumAlgorithms[n.toUpperCase()]=i:r.checksumAlgorithms[n]=i,e.push(t)},checksumAlgorithms(){return e}}},UV=r=>{const e={};return r.checksumAlgorithms().forEach(t=>{const n=t.algorithmId();LI.includes(n)&&(e[n]=t.checksumConstructor())}),e},VV=r=>({setRetryStrategy(e){r.retryStrategy=e},retryStrategy(){return r.retryStrategy}}),zV=r=>{const e={};return e.retryStrategy=r.retryStrategy(),e},$V=r=>Object.assign(LV(r),VV(r)),HV=r=>Object.assign(UV(r),zV(r));class UI{trace(){}debug(){}info(){}warn(){}error(){}}const VI="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ME=Object.entries(VI).reduce((r,[e,t])=>(r[t]=Number(e),r),{}),jV=VI.split(""),Gu=6,Zd=8,GV=63,Zg=r=>{let e=r.length/4*3;r.slice(-2)==="=="?e-=2:r.slice(-1)==="="&&e--;const t=new ArrayBuffer(e),n=new DataView(t);for(let i=0;i<r.length;i+=4){let a=0,s=0;for(let u=i,c=i+3;u<=c;u++)if(r[u]!=="="){if(!(r[u]in ME))throw new TypeError(`Invalid character ${r[u]} in base64 string.`);a|=ME[r[u]]<<(c-u)*Gu,s+=Gu}else a>>=Gu;const o=i/4*3;a>>=s%Zd;const l=Math.floor(s/Zd);for(let u=0;u<l;u++){const c=(l-u-1)*Zd;n.setUint8(o+u,(a&255<<c)>>c)}}return new Uint8Array(t)},kl=r=>new TextEncoder().encode(r);function Cg(r){let e;typeof r=="string"?e=kl(r):e=r;const t=typeof e=="object"&&typeof e.length=="number",n=typeof e=="object"&&typeof e.byteOffset=="number"&&typeof e.byteLength=="number";if(!t&&!n)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let a=0;a<e.length;a+=3){let s=0,o=0;for(let u=a,c=Math.min(a+3,e.length);u<c;u++)s|=e[u]<<(c-u-1)*Zd,o+=Zd;const l=Math.ceil(o/Gu);s<<=l*Gu-o;for(let u=1;u<=l;u++){const c=(l-u)*Gu;i+=jV[(s&GV<<c)>>c]}i+="==".slice(0,4-l)}return i}function qV(r,e,t,n){return class Xp extends Uint8Array{static fromString(a,s="utf-8"){if(typeof a=="string")return s==="base64"?Xp.mutate(n(a)):Xp.mutate(e(a));throw new Error(`Unsupported conversion from ${typeof a} to Uint8ArrayBlobAdapter.`)}static mutate(a){return Object.setPrototypeOf(a,Xp.prototype),a}transformToString(a="utf-8"){return a==="base64"?t(this):r(this)}}}const em=r=>{if(typeof r=="string")return r;if(typeof r!="object"||typeof r.byteOffset!="number"||typeof r.byteLength!="number")throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(r)},Ii=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function WV(r){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?()=>crypto.randomUUID():()=>{const e=new Uint8Array(16);return r(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,Ii[e[0]]+Ii[e[1]]+Ii[e[2]]+Ii[e[3]]+"-"+Ii[e[4]]+Ii[e[5]]+"-"+Ii[e[6]]+Ii[e[7]]+"-"+Ii[e[8]]+Ii[e[9]]+"-"+Ii[e[10]]+Ii[e[11]]+Ii[e[12]]+Ii[e[13]]+Ii[e[14]]+Ii[e[15]]}}const yA=r=>{if(r!=null){if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return String(e)!==String(r)&&rz.warn(tz(`Expected number but observed string: ${r}`)),e}if(typeof r=="number")return r;throw new TypeError(`Expected number, got ${typeof r}: ${r}`)}},QV=Math.ceil(2**127*(2-2**-23)),_E=r=>{const e=yA(r);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>QV)throw new TypeError(`Expected 32-bit float, got ${r}`);return e},YV=r=>{if(r!=null){if(Number.isInteger(r)&&!Number.isNaN(r))return r;throw new TypeError(`Expected integer, got ${typeof r}: ${r}`)}},NE=r=>zI(r,16),LE=r=>zI(r,8),zI=(r,e)=>{const t=YV(r);if(t!==void 0&&XV(t,e)!==t)throw new TypeError(`Expected ${e}-bit integer, got ${r}`);return t},XV=(r,e)=>{switch(e){case 32:return Int32Array.of(r)[0];case 16:return Int16Array.of(r)[0];case 8:return Int8Array.of(r)[0]}},JV=r=>yA(typeof r=="string"?tm(r):r),KV=r=>_E(typeof r=="string"?tm(r):r),ZV=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,tm=r=>{const e=r.match(ZV);if(e===null||e[0].length!==r.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(r)},xg=r=>NE(typeof r=="string"?tm(r):r),ez=r=>LE(typeof r=="string"?tm(r):r),tz=r=>String(new TypeError(r).stack||r).split(`
3039
+ `;class SV{constructor(e,t=ze.getShadowGraphqlClient.bind(ze)){this.options=e,this.client=t}query(e){const t=this.options?.onQuery?this.options?.onQuery(e):{};return this.client().query({...t,...e,context:{...t.context??{},...e.context??{}}})}mutate(e){const t=this.options?.onMutate?this.options?.onMutate(e):{};return this.client().mutate({...t,...e,context:{...t.context??{},...e.context??{}}})}}function EV(r,e,t){return r.$source||(r.$source={}),r.$source[e]=t,r}const kV=r=>r?.body instanceof ReadableStream,fl=(r,e)=>{const t=[];if(r&&t.push(r),e)for(const n of e)t.push(n);return t},to=(r,e)=>`${r||"anonymous"}${e&&e.length>0?` (a.k.a. ${e.join(",")})`:""}`,bg=()=>{let r=[],e=[],t=!1;const n=new Set,i=f=>f.sort((d,h)=>RE[h.step]-RE[d.step]||OE[h.priority||"normal"]-OE[d.priority||"normal"]),a=f=>{let d=!1;const h=g=>{const v=fl(g.name,g.aliases);if(v.includes(f)){d=!0;for(const y of v)n.delete(y);return!1}return!0};return r=r.filter(h),e=e.filter(h),d},s=f=>{let d=!1;const h=g=>{if(g.middleware===f){d=!0;for(const v of fl(g.name,g.aliases))n.delete(v);return!1}return!0};return r=r.filter(h),e=e.filter(h),d},o=f=>(r.forEach(d=>{f.add(d.middleware,{...d})}),e.forEach(d=>{f.addRelativeTo(d.middleware,{...d})}),f.identifyOnResolve?.(c.identifyOnResolve()),f),l=f=>{const d=[];return f.before.forEach(h=>{h.before.length===0&&h.after.length===0?d.push(h):d.push(...l(h))}),d.push(f),f.after.reverse().forEach(h=>{h.before.length===0&&h.after.length===0?d.push(h):d.push(...l(h))}),d},u=(f=!1)=>{const d=[],h=[],g={};return r.forEach(y=>{const A={...y,before:[],after:[]};for(const C of fl(A.name,A.aliases))g[C]=A;d.push(A)}),e.forEach(y=>{const A={...y,before:[],after:[]};for(const C of fl(A.name,A.aliases))g[C]=A;h.push(A)}),h.forEach(y=>{if(y.toMiddleware){const A=g[y.toMiddleware];if(A===void 0){if(f)return;throw new Error(`${y.toMiddleware} is not found when adding ${to(y.name,y.aliases)} middleware ${y.relation} ${y.toMiddleware}`)}y.relation==="after"&&A.after.push(y),y.relation==="before"&&A.before.push(y)}}),i(d).map(l).reduce((y,A)=>(y.push(...A),y),[])},c={add:(f,d={})=>{const{name:h,override:g,aliases:v}=d,y={step:"initialize",priority:"normal",middleware:f,...d},A=fl(h,v);if(A.length>0){if(A.some(C=>n.has(C))){if(!g)throw new Error(`Duplicate middleware name '${to(h,v)}'`);for(const C of A){const S=r.findIndex(E=>E.name===C||E.aliases?.some(R=>R===C));if(S===-1)continue;const F=r[S];if(F.step!==y.step||y.priority!==F.priority)throw new Error(`"${to(F.name,F.aliases)}" middleware with ${F.priority} priority in ${F.step} step cannot be overridden by "${to(h,v)}" middleware with ${y.priority} priority in ${y.step} step.`);r.splice(S,1)}}for(const C of A)n.add(C)}r.push(y)},addRelativeTo:(f,d)=>{const{name:h,override:g,aliases:v}=d,y={middleware:f,...d},A=fl(h,v);if(A.length>0){if(A.some(C=>n.has(C))){if(!g)throw new Error(`Duplicate middleware name '${to(h,v)}'`);for(const C of A){const S=e.findIndex(E=>E.name===C||E.aliases?.some(R=>R===C));if(S===-1)continue;const F=e[S];if(F.toMiddleware!==y.toMiddleware||F.relation!==y.relation)throw new Error(`"${to(F.name,F.aliases)}" middleware ${F.relation} "${F.toMiddleware}" middleware cannot be overridden by "${to(h,v)}" middleware ${y.relation} "${y.toMiddleware}" middleware.`);e.splice(S,1)}}for(const C of A)n.add(C)}e.push(y)},clone:()=>o(bg()),use:f=>{f.applyToStack(c)},remove:f=>typeof f=="string"?a(f):s(f),removeByTag:f=>{let d=!1;const h=g=>{const{tags:v,name:y,aliases:A}=g;if(v&&v.includes(f)){const C=fl(y,A);for(const S of C)n.delete(S);return d=!0,!1}return!0};return r=r.filter(h),e=e.filter(h),d},concat:f=>{const d=o(bg());return d.use(f),d.identifyOnResolve(t||d.identifyOnResolve()||(f.identifyOnResolve?.()??!1)),d},applyToStack:o,identify:()=>u(!0).map(f=>{const d=f.step??f.relation+" "+f.toMiddleware;return to(f.name,f.aliases)+" - "+d}),identifyOnResolve(f){return typeof f=="boolean"&&(t=f),t},resolve:(f,d)=>{for(const h of u().map(g=>g.middleware).reverse())f=h(f,d);return t&&console.log(c.identify()),f}};return c},RE={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},OE={high:3,normal:2,low:1};var xf;(function(r){r.HTTP="http",r.HTTPS="https"})(xf||(xf={}));var Sf;(function(r){r.MD5="md5",r.CRC32="crc32",r.CRC32C="crc32c",r.SHA1="sha1",r.SHA256="sha256"})(Sf||(Sf={}));const mA="__smithy_context",vc=r=>r[mA]||(r[mA]={});class na{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){const t=new na({...e,headers:{...e.headers}});return t.query&&(t.query=TV(t.query)),t}static isInstance(e){if(!e)return!1;const t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&typeof t.query=="object"&&typeof t.headers=="object"}clone(){return na.clone(this)}}function TV(r){return Object.keys(r).reduce((e,t)=>{const n=r[t];return{...e,[t]:Array.isArray(n)?[...n]:n}},{})}class sc{statusCode;reason;headers;body;constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;const t=e;return typeof t.statusCode=="number"&&typeof t.headers=="object"}}const FV=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Kg=(r,e=!1)=>{if(!e)return FV.test(r);const t=r.split(".");for(const n of t)if(!Kg(n))return!1;return!0},Bs=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};function IV(r){const e={};if(r=r.replace(/^\?/,""),r)for(const t of r.split("&")){let[n,i=null]=t.split("=");n=decodeURIComponent(n),i&&(i=decodeURIComponent(i)),n in e?Array.isArray(e[n])?e[n].push(i):e[n]=[e[n],i]:e[n]=i}return e}const wg=r=>{if(typeof r=="string")return wg(new URL(r));const{hostname:e,pathname:t,port:n,protocol:i,search:a}=r;let s;return a&&(s=IV(a)),{hostname:e,port:n?parseInt(n):void 0,protocol:i,path:t,query:s}},U1=r=>{if(typeof r=="object"){if("url"in r){const e=wg(r.url);if(r.headers){e.headers={};for(const t in r.headers)e.headers[t.toLowerCase()]=r.headers[t].join(", ")}return e}return r}return wg(r)},PV=r=>()=>Promise.reject(r);class DV{config;middlewareStack=bg();initConfig;handlers;constructor(e){this.config=e;const{protocol:t,protocolSettings:n}=e;n&&typeof t=="function"&&(e.protocol=new t(n))}send(e,t,n){const i=typeof t!="function"?t:void 0,a=typeof t=="function"?t:n,s=i===void 0&&this.config.cacheMiddleware===!0;let o;if(s){this.handlers||(this.handlers=new WeakMap);const l=this.handlers;l.has(e.constructor)?o=l.get(e.constructor):(o=e.resolveMiddleware(this.middlewareStack,this.config,i),l.set(e.constructor,o))}else delete this.handlers,o=e.resolveMiddleware(this.middlewareStack,this.config,i);if(a)o(e).then(l=>a(null,l.output),l=>a(l)).catch(()=>{});else return o(e).then(l=>l.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const Yp=r=>typeof r=="function"?r():r,NI=(r,e,t,n,i)=>({name:e,namespace:r,traits:t,input:n,output:i}),RV=r=>(e,t)=>async n=>{const{response:i}=await e(n),{operationSchema:a}=vc(t),[,s,o,l,u,c]=a??[];try{const f=await r.protocol.deserializeResponse(NI(s,o,l,u,c),{...r,...t},i);return{response:i,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){const d="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{f.message+=`
3040
+ `+d}catch{!t.logger||t.logger?.constructor?.name==="NoOpLogger"?console.warn(d):t.logger?.warn?.(d)}typeof f.$responseBodyText<"u"&&f.$response&&(f.$response.body=f.$responseBodyText);try{if(sc.isInstance(i)){const{headers:h={},statusCode:g}=i,v=Object.entries(h);f.$metadata={httpStatusCode:g,requestId:Bv(/^x-[\w-]+-request-?id$/,v),extendedRequestId:Bv(/^x-[\w-]+-id-2$/,v),cfId:Bv(/^x-[\w-]+-cf-id$/,v)}}}catch{}}throw f}},Bv=(r,e)=>(e.find(([t])=>t.match(r))||[void 0,void 0])[1],OV=r=>(e,t)=>async n=>{const{operationSchema:i}=vc(t),[,a,s,o,l,u]=i??[],c=t.endpointV2?async()=>U1(t.endpointV2):r.endpoint,f=await r.protocol.serializeRequest(NI(a,s,o,l,u),n.input,{...r,...t,endpoint:c});return e({...n,request:f})},BV={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},MV={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function _V(r){return{applyToStack:e=>{e.add(OV(r),MV),e.add(RV(r),BV),r.protocol.setSerdeContext(r)}}}const Mv=[];function zd(r){if(typeof r=="object")return r;if(r=r|0,Mv[r])return Mv[r];const e={};let t=0;for(const n of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(r>>t++&1)===1&&(e[n]=1);return Mv[r]=e}const kd={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},_v=[],Nv={};class vi{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=vi.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,t){this.ref=e,this.memberName=t;const n=[];let i=e,a=e;for(this._isMemberSchema=!1;Lv(i);)n.push(i[1]),i=i[0],a=Yp(i),this._isMemberSchema=!0;if(n.length>0){this.memberTraits={};for(let s=n.length-1;s>=0;--s){const o=n[s];Object.assign(this.memberTraits,zd(o))}}else this.memberTraits=0;if(a instanceof vi){const s=this.memberTraits;Object.assign(this,a),this.memberTraits=Object.assign({},s,a.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??a.memberName;return}if(this.schema=Yp(a),NV(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(a),this.traits=0),this._isMemberSchema&&!t)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){const t=this.prototype.isPrototypeOf(e);return!t&&typeof e=="object"&&e!==null?e.symbol===this.symbol:t}static of(e){const t=typeof e=="function"||typeof e=="object"&&e!==null;if(typeof e=="number"){if(_v[e])return _v[e]}else if(typeof e=="string"){if(Nv[e])return Nv[e]}else if(t&&e[kd.ns])return e[kd.ns];const n=Yp(e);if(n instanceof vi)return n;if(Lv(n)){const[a,s]=n;if(a instanceof vi)return Object.assign(a.getMergedTraits(),zd(s)),a;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}const i=new vi(n);return t?e[kd.ns]=i:typeof n=="string"?Nv[n]=i:typeof n=="number"?_v[n]=i:i}getSchema(){const e=this.schema;return Array.isArray(e)&&e[0]===0?e[4]:e}getName(e=!1){const{name:t}=this;return!e&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){const e=this.getSchema();return typeof e=="number"?e>=64&&e<128:e[0]===1}isMapSchema(){const e=this.getSchema();return typeof e=="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){const e=this.getSchema();if(typeof e!="object")return!1;const t=e[0];return t===3||t===-3||t===4}isUnionSchema(){const e=this.getSchema();return typeof e!="object"?!1:e[0]===4}isBlobSchema(){const e=this.getSchema();return e===21||e===42}isTimestampSchema(){const e=this.getSchema();return typeof e=="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){const{streaming:e}=this.getMergedTraits();return!!e||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return zd(this.memberTraits)}getOwnTraits(){return zd(this.traits)}getKeySchema(){const[e,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!t)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);const n=this.getSchema(),i=e?15:n[4]??0;return Td([i,0],"key")}getValueSchema(){const e=this.getSchema(),[t,n,i]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],a=typeof e=="number"?63&e:e&&typeof e=="object"&&(n||i)?e[3+e[0]]:t?15:void 0;if(a!=null)return Td([a,0],n?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(e){const t=this.getSchema();if(this.isStructSchema()&&t[4].includes(e)){const n=t[4].indexOf(e),i=t[5][n];return Td(Lv(i)?i:[i,0],e)}if(this.isDocumentSchema())return Td([15,0],e);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${e}.`)}getMemberSchemas(){const e={};try{for(const[t,n]of this.structIterator())e[t]=n}catch{}return e}getEventStreamMember(){if(this.isStructSchema()){for(const[e,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return e}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");const e=this.getSchema(),t=e[4].length;let n=e[kd.it];if(n&&t===n.length){yield*n;return}n=Array(t);for(let i=0;i<t;++i){const a=e[4][i],s=Td([e[5][i],0],a);yield n[i]=[a,s]}e[kd.it]=n}}function Td(r,e){if(r instanceof vi)return Object.assign(r,{memberName:e,_isMemberSchema:!0});const t=vi;return new t(r,e)}const Lv=r=>Array.isArray(r)&&r.length===2,NV=r=>Array.isArray(r)&&r.length>=5;class Zi{namespace;schemas;exceptions;static registries=new Map;constructor(e,t=new Map,n=new Map){this.namespace=e,this.schemas=t,this.exceptions=n}static for(e){return Zi.registries.has(e)||Zi.registries.set(e,new Zi(e)),Zi.registries.get(e)}copyFrom(e){const{schemas:t,exceptions:n}=this;for(const[i,a]of e.schemas)t.has(i)||t.set(i,a);for(const[i,a]of e.exceptions)n.has(i)||n.set(i,a)}register(e,t){const n=this.normalizeShapeId(e);for(const i of[this,Zi.for(n.split("#")[0])])i.schemas.set(n,t)}getSchema(e){const t=this.normalizeShapeId(e);if(!this.schemas.has(t)){if(!e.includes("#")){const n="#"+e,i=[];for(const[a,s]of this.schemas.entries())a.endsWith(n)&&i.push(s);if(i.length===1)return i[0]}throw new Error(`@smithy/core/schema - schema not found for ${t}`)}return this.schemas.get(t)}registerError(e,t){const n=e,i=n[1];for(const a of[this,Zi.for(i)])a.schemas.set(i+"#"+n[2],n),a.exceptions.set(n,t)}getErrorCtor(e){const t=e;return this.exceptions.has(t)?this.exceptions.get(t):Zi.for(t[1]).exceptions.get(t)}getBaseException(){for(const e of this.exceptions.keys())if(Array.isArray(e)){const[,t,n]=e,i=t+"#"+n;if(i.startsWith("smithy.ts.sdk.synthetic.")&&i.endsWith("ServiceException"))return e}}find(e){for(const t of this.schemas.values())if(e(t))return t}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(e){return e.includes("#")?e:this.namespace+"#"+e}}const Uv="***SensitiveInformation***";function vA(r,e){if(e==null)return e;const t=vi.of(r);if(t.getMergedTraits().sensitive)return Uv;if(t.isListSchema()){if(!!t.getValueSchema().getMergedTraits().sensitive)return Uv}else if(t.isMapSchema()){if(!!t.getKeySchema().getMergedTraits().sensitive||!!t.getValueSchema().getMergedTraits().sensitive)return Uv}else if(t.isStructSchema()&&typeof e=="object"){const n=e,i={};for(const[a,s]of t.structIterator())n[a]!=null&&(i[a]=vA(s,n[a]));return i}return e}class V1{middlewareStack=bg();schema;static classBuilder(){return new LV}resolveMiddlewareWithContext(e,t,n,{middlewareFn:i,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,smithyContext:u,additionalContext:c,CommandCtor:f}){for(const A of i.bind(this)(f,e,t,n))this.middlewareStack.use(A);const d=e.concat(this.middlewareStack),{logger:h}=t,g={logger:h,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,[mA]:{commandInstance:this,...u},...c},{requestHandler:v}=t;let y=n??{};return u.eventStream&&(y={isEventStream:!0,...y}),d.resolve(A=>v.handle(A.request,y),g)}}class LV{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,n={}){return this._smithyContext={service:e,operation:t,...n},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=n=>n,t=n=>n){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){const e=this;let t;return t=class extends V1{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[n]){super(),this.input=n??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(n,i,a){const s=e._operationSchema,o=s?.[4]??s?.input,l=s?.[5]??s?.output;return this.resolveMiddlewareWithContext(n,i,a,{CommandCtor:t,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(s?vA.bind(null,o):u=>u),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?vA.bind(null,l):u=>u),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}class Lu extends Error{$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;const t=e;return Lu.prototype.isPrototypeOf(t)||!!t.$fault&&!!t.$metadata&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;const t=e;return this===Lu?Lu.isInstance(e):Lu.isInstance(e)?t.name&&this.name?this.prototype.isPrototypeOf(e)||t.name===this.name:this.prototype.isPrototypeOf(e):!1}}const BE=(r,e={})=>{Object.entries(e).filter(([,n])=>n!==void 0).forEach(([n,i])=>{(r[n]==null||r[n]==="")&&(r[n]=i)});const t=r.message||r.Message||"UnknownError";return r.message=t,delete r.Message,r},UV=r=>{switch(r){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},LI=Object.values(Sf),VV=r=>{const e=[];for(const t in Sf){const n=Sf[t];r[n]!==void 0&&e.push({algorithmId:()=>n,checksumConstructor:()=>r[n]})}for(const[t,n]of Object.entries(r.checksumAlgorithms??{}))e.push({algorithmId:()=>t,checksumConstructor:()=>n});return{addChecksumAlgorithm(t){r.checksumAlgorithms=r.checksumAlgorithms??{};const n=t.algorithmId(),i=t.checksumConstructor();LI.includes(n)?r.checksumAlgorithms[n.toUpperCase()]=i:r.checksumAlgorithms[n]=i,e.push(t)},checksumAlgorithms(){return e}}},zV=r=>{const e={};return r.checksumAlgorithms().forEach(t=>{const n=t.algorithmId();LI.includes(n)&&(e[n]=t.checksumConstructor())}),e},$V=r=>({setRetryStrategy(e){r.retryStrategy=e},retryStrategy(){return r.retryStrategy}}),HV=r=>{const e={};return e.retryStrategy=r.retryStrategy(),e},jV=r=>Object.assign(VV(r),$V(r)),GV=r=>Object.assign(zV(r),HV(r));class UI{trace(){}debug(){}info(){}warn(){}error(){}}const VI="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ME=Object.entries(VI).reduce((r,[e,t])=>(r[t]=Number(e),r),{}),qV=VI.split(""),Gu=6,Zd=8,WV=63,Zg=r=>{let e=r.length/4*3;r.slice(-2)==="=="?e-=2:r.slice(-1)==="="&&e--;const t=new ArrayBuffer(e),n=new DataView(t);for(let i=0;i<r.length;i+=4){let a=0,s=0;for(let u=i,c=i+3;u<=c;u++)if(r[u]!=="="){if(!(r[u]in ME))throw new TypeError(`Invalid character ${r[u]} in base64 string.`);a|=ME[r[u]]<<(c-u)*Gu,s+=Gu}else a>>=Gu;const o=i/4*3;a>>=s%Zd;const l=Math.floor(s/Zd);for(let u=0;u<l;u++){const c=(l-u-1)*Zd;n.setUint8(o+u,(a&255<<c)>>c)}}return new Uint8Array(t)},kl=r=>new TextEncoder().encode(r);function Cg(r){let e;typeof r=="string"?e=kl(r):e=r;const t=typeof e=="object"&&typeof e.length=="number",n=typeof e=="object"&&typeof e.byteOffset=="number"&&typeof e.byteLength=="number";if(!t&&!n)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let a=0;a<e.length;a+=3){let s=0,o=0;for(let u=a,c=Math.min(a+3,e.length);u<c;u++)s|=e[u]<<(c-u-1)*Zd,o+=Zd;const l=Math.ceil(o/Gu);s<<=l*Gu-o;for(let u=1;u<=l;u++){const c=(l-u)*Gu;i+=qV[(s&WV<<c)>>c]}i+="==".slice(0,4-l)}return i}function QV(r,e,t,n){return class Xp extends Uint8Array{static fromString(a,s="utf-8"){if(typeof a=="string")return s==="base64"?Xp.mutate(n(a)):Xp.mutate(e(a));throw new Error(`Unsupported conversion from ${typeof a} to Uint8ArrayBlobAdapter.`)}static mutate(a){return Object.setPrototypeOf(a,Xp.prototype),a}transformToString(a="utf-8"){return a==="base64"?t(this):r(this)}}}const em=r=>{if(typeof r=="string")return r;if(typeof r!="object"||typeof r.byteOffset!="number"||typeof r.byteLength!="number")throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(r)},Ii=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function YV(r){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?()=>crypto.randomUUID():()=>{const e=new Uint8Array(16);return r(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,Ii[e[0]]+Ii[e[1]]+Ii[e[2]]+Ii[e[3]]+"-"+Ii[e[4]]+Ii[e[5]]+"-"+Ii[e[6]]+Ii[e[7]]+"-"+Ii[e[8]]+Ii[e[9]]+"-"+Ii[e[10]]+Ii[e[11]]+Ii[e[12]]+Ii[e[13]]+Ii[e[14]]+Ii[e[15]]}}const yA=r=>{if(r!=null){if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return String(e)!==String(r)&&iz.warn(nz(`Expected number but observed string: ${r}`)),e}if(typeof r=="number")return r;throw new TypeError(`Expected number, got ${typeof r}: ${r}`)}},XV=Math.ceil(2**127*(2-2**-23)),_E=r=>{const e=yA(r);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>XV)throw new TypeError(`Expected 32-bit float, got ${r}`);return e},JV=r=>{if(r!=null){if(Number.isInteger(r)&&!Number.isNaN(r))return r;throw new TypeError(`Expected integer, got ${typeof r}: ${r}`)}},NE=r=>zI(r,16),LE=r=>zI(r,8),zI=(r,e)=>{const t=JV(r);if(t!==void 0&&KV(t,e)!==t)throw new TypeError(`Expected ${e}-bit integer, got ${r}`);return t},KV=(r,e)=>{switch(e){case 32:return Int32Array.of(r)[0];case 16:return Int16Array.of(r)[0];case 8:return Int8Array.of(r)[0]}},ZV=r=>yA(typeof r=="string"?tm(r):r),ez=r=>_E(typeof r=="string"?tm(r):r),tz=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,tm=r=>{const e=r.match(tz);if(e===null||e[0].length!==r.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(r)},xg=r=>NE(typeof r=="string"?tm(r):r),rz=r=>LE(typeof r=="string"?tm(r):r),nz=r=>String(new TypeError(r).stack||r).split(`
3041
3041
  `).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
3042
- `),rz={warn:console.warn},nz=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],z1=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function iz(r){const e=r.getUTCFullYear(),t=r.getUTCMonth(),n=r.getUTCDay(),i=r.getUTCDate(),a=r.getUTCHours(),s=r.getUTCMinutes(),o=r.getUTCSeconds(),l=i<10?`0${i}`:`${i}`,u=a<10?`0${a}`:`${a}`,c=s<10?`0${s}`:`${s}`,f=o<10?`0${o}`:`${o}`;return`${nz[n]}, ${l} ${z1[t]} ${e} ${u}:${c}:${f} GMT`}const az=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),sz=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=az.exec(r);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,n,i,a,s,o,l,u,c]=e,f=xg(Ef(n)),d=yo(i,"month",1,12),h=yo(a,"day",1,31),g=Jp(f,d,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u});return c.toUpperCase()!="Z"&&g.setTime(g.getTime()-yz(c)),g},oz=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),lz=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),uz=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),$I=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=oz.exec(r);if(e){const[t,n,i,a,s,o,l,u]=e;return Jp(xg(Ef(a)),Vv(i),yo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u})}if(e=lz.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return hz(Jp(dz(a),Vv(i),yo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u}))}if(e=uz.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return Jp(xg(Ef(u)),Vv(n),yo(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},cz=r=>{if(r==null)return;let e;if(typeof r=="number")e=r;else if(typeof r=="string")e=JV(r);else if(typeof r=="object"&&r.tag===1)e=r.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},Jp=(r,e,t,n)=>{const i=e-1;return gz(r,i,t),new Date(Date.UTC(r,i,t,yo(n.hours,"hour",0,23),yo(n.minutes,"minute",0,59),yo(n.seconds,"seconds",0,60),vz(n.fractionalMilliseconds)))},dz=r=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+xg(Ef(r));return t<e?t+100:t},fz=50*365*24*60*60*1e3,hz=r=>r.getTime()-new Date().getTime()>fz?new Date(Date.UTC(r.getUTCFullYear()-100,r.getUTCMonth(),r.getUTCDate(),r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds())):r,Vv=r=>{const e=z1.indexOf(r);if(e<0)throw new TypeError(`Invalid month: ${r}`);return e+1},pz=[31,28,31,30,31,30,31,31,30,31,30,31],gz=(r,e,t)=>{let n=pz[e];if(e===1&&mz(r)&&(n=29),t>n)throw new TypeError(`Invalid day for ${z1[e]} in ${r}: ${t}`)},mz=r=>r%4===0&&(r%100!==0||r%400===0),yo=(r,e,t,n)=>{const i=ez(Ef(r));if(i<t||i>n)throw new TypeError(`${e} must be between ${t} and ${n}, inclusive`);return i},vz=r=>r==null?0:KV("0."+r)*1e3,yz=r=>{const e=r[0];let t=1;if(e=="+")t=1;else if(e=="-")t=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);const n=Number(r.substring(1,3)),i=Number(r.substring(4,6));return t*(n*60+i)*60*1e3},Ef=r=>{let e=0;for(;e<r.length-1&&r.charAt(e)==="0";)e++;return e===0?r:r.slice(e)},po=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};po.from=r=>r&&typeof r=="object"&&(r instanceof po||"deserializeJSON"in r)?r:typeof r=="string"||Object.getPrototypeOf(r)===String.prototype?po(String(r)):po(JSON.stringify(r));po.fromObject=po.from;const UE=/^-?\d*(\.\d+)?$/;class ns{string;type;constructor(e,t){if(this.string=e,this.type=t,!UE.test(e))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;const t=e;return ns.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&UE.test(t.string)}}const HI={},AA={};for(let r=0;r<256;r++){let e=r.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),HI[r]=e,AA[e]=r}function jI(r){if(r.length%2!==0)throw new Error("Hex encoded strings must have an even number length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2){const n=r.slice(t,t+2).toLowerCase();if(n in AA)e[t/2]=AA[n];else throw new Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return e}function Ao(r){let e="";for(let t=0;t<r.byteLength;t++)e+=HI[r[t]];return e}const VE=typeof TextEncoder=="function"?new TextEncoder:null,Az=r=>{if(typeof r=="string"){if(VE)return VE.encode(r).byteLength;let e=r.length;for(let t=e-1;t>=0;t--){const n=r.charCodeAt(t);n>127&&n<=2047?e++:n>2047&&n<=65535&&(e+=2),n>=56320&&n<=57343&&t--}return e}else{if(typeof r.byteLength=="number")return r.byteLength;if(typeof r.size=="number")return r.size}throw new Error(`Body Length computation failed for ${r}`)},kf=r=>typeof r=="string"?kl(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r),bz=r=>typeof ArrayBuffer=="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]",GI=async r=>{},wz=async r=>{const e=r?.Bucket||"";if(typeof r.Bucket=="string"&&(r.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),kz(e)){if(r.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!Ez(e)||e.indexOf(".")!==-1&&!String(r.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(r.ForcePathStyle=!0);return r.DisableMultiRegionAccessPoints&&(r.disableMultiRegionAccessPoints=!0,r.DisableMRAP=!0),r},Cz=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,xz=/(\d+\.){3}\d+/,Sz=/\.\./,Ez=r=>Cz.test(r)&&!xz.test(r)&&!Sz.test(r),kz=r=>{const[e,t,n,,,i]=r.split(":"),a=e==="arn"&&r.split(":").length>=6,s=!!(a&&t&&n&&i);if(a&&!s)throw new Error(`Invalid ARN: ${r} was an invalid ARN.`);return s},Tz=(r,e,t,n=!1)=>{const i=async()=>{let a;return n?a=t.clientContextParams?.[r]??t[r]??t[e]:a=t[r]??t[e],typeof a=="function"?a():a};return r==="credentialScope"||e==="CredentialScope"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.credentialScope??a?.CredentialScope}:r==="accountId"||e==="AccountId"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.accountId??a?.AccountId}:r==="endpoint"||e==="endpoint"?async()=>{if(t.isCustomEndpoint===!1)return;const a=await i();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:s,hostname:o,port:l,path:u}=a;return`${s}//${o}${l?":"+l:""}${u}`}}return a}:i};function Fz(r){return async(e,t,n,i)=>{if(!n.isCustomEndpoint){let o;n.serviceConfiguredEndpoint?o=await n.serviceConfiguredEndpoint():o=await r(n.serviceId),o&&(n.endpoint=()=>Promise.resolve(U1(o)),n.isCustomEndpoint=!0)}const a=await Iz(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");const s=n.endpointProvider(a,i);if(n.isCustomEndpoint&&n.endpoint){const o=await n.endpoint();if(o?.headers){s.headers??={};for(const[l,u]of Object.entries(o.headers))s.headers[l]=Array.isArray(u)?u:[u]}}return s}}const Iz=async(r,e,t)=>{const n={},i=e?.getEndpointParameterInstructions?.()||{};for(const[a,s]of Object.entries(i))switch(s.type){case"staticContextParams":n[a]=s.value;break;case"contextParams":n[a]=r[s.name];break;case"clientContextParams":case"builtInParams":n[a]=await Tz(s.name,a,t,s.type!=="builtInParams")();break;case"operationContextParams":n[a]=s.get(r);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(i).length===0&&Object.assign(n,t),String(t.serviceId).toLowerCase()==="s3"&&await wz(n),n};function Pz(r,e,t){r.__smithy_context?r.__smithy_context.features||(r.__smithy_context.features={}):r.__smithy_context={features:{}},r.__smithy_context.features[e]=t}function Dz(r){const e=Fz(r);return({config:t,instructions:n})=>(i,a)=>async s=>{t.isCustomEndpoint&&Pz(a,"ENDPOINT_OVERRIDE","N");const o=await e(s.input,{getEndpointParameterInstructions(){return n}},{...t},a);a.endpointV2=o,a.authSchemes=o.properties?.authSchemes;const l=a.authSchemes?.[0];if(l){a.signing_region=l.signingRegion,a.signing_service=l.signingName;const c=vc(a)?.selectedHttpAuthScheme?.httpAuthOption;c&&(c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:l.signingRegion,signingRegion:l.signingRegion,signing_service:l.signingName,signingName:l.signingName,signingRegionSet:l.signingRegionSet},l.properties))}return i({...s})}}const Rz={name:"serializerMiddleware"},Oz={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Rz.name};function Bz(r){const e=Dz(r);return(t,n)=>({applyToStack:i=>{i.addRelativeTo(e({config:t,instructions:n}),Oz)}})}function Mz(r){return e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:a}=e,s=n!=null?async()=>U1(await Bs(n)()):void 0,l=Object.assign(e,{endpoint:s,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:Bs(i??!1),useFipsEndpoint:Bs(a??!1)});let u;return l.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=r(e.serviceId)),u),l}}class $1{nodes;root;conditions;results;constructor(e,t,n,i){this.nodes=e,this.root=t,this.conditions=n,this.results=i}static from(e,t,n,i){return new $1(e,t,n,i)}}class _z{capacity;data=new Map;parameters=[];constructor({size:e,params:t}){this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const n=this.hash(e);if(n===!1)return t();if(!this.data.has(n)){if(this.data.size>this.capacity+10){const i=this.data.keys();let a=0;for(;;){const{value:s,done:o}=i.next();if(this.data.delete(s),o||++a>10)break}}this.data.set(n,t())}return this.data.get(n)}size(){return this.data.size}hash(e){let t="";const{parameters:n}=this;if(n.length===0)return!1;for(const i of n){const a=String(e[i]??"");if(a.includes("|;"))return!1;t+=a+"|;"}return t}}class Ba extends Error{constructor(e){super(e),this.name="EndpointError"}}const Nz="endpoints";function Sg(r){return typeof r!="object"||r==null?r:"ref"in r?`$${Sg(r.ref)}`:"fn"in r?`${r.fn}(${(r.argv||[]).map(Sg).join(", ")})`:JSON.stringify(r,null,2)}const H1={},Lz=(r,e)=>r===e;function Uz(...r){for(const e of r)if(e!=null)return e}const Vz=r=>{const e=r.split("."),t=[];for(const n of e){const i=n.indexOf("[");if(i!==-1){if(n.indexOf("]")!==n.length-1)throw new Ba(`Path: '${r}' does not end with ']'`);const a=n.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new Ba(`Invalid array index: '${a}' in path: '${r}'`);i!==0&&t.push(n.slice(0,i)),t.push(a)}else t.push(n)}return t},qI=(r,e)=>Vz(e).reduce((t,n)=>{if(typeof t!="object")throw new Ba(`Index '${n}' in '${e}' not found in '${JSON.stringify(r)}'`);if(Array.isArray(t)){const i=parseInt(n);return t[i<0?t.length+i:i]}return t[n]},r),zz=r=>r!=null;function $z(r,e,t){return r?e:t}const Hz=r=>!r,jz=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),WI=r=>jz.test(r)||r.startsWith("[")&&r.endsWith("]"),zv={[xf.HTTP]:80,[xf.HTTPS]:443},Gz=r=>{const e=(()=>{try{if(r instanceof URL)return r;if(typeof r=="object"&&"hostname"in r){const{hostname:d,port:h,protocol:g="",path:v="",query:y={}}=r,A=new URL(`${g}//${d}${h?`:${h}`:""}${v}`);return A.search=Object.entries(y).map(([C,S])=>`${C}=${S}`).join("&"),A}return new URL(r)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(r)} as a whatwg URL.`),null;const t=e.href,{host:n,hostname:i,pathname:a,protocol:s,search:o}=e;if(o)return null;const l=s.slice(0,-1);if(!Object.values(xf).includes(l))return null;const u=WI(i),c=t.includes(`${n}:${zv[l]}`)||typeof r=="string"&&r.includes(`${n}:${zv[l]}`),f=`${n}${c?`:${zv[l]}`:""}`;return{scheme:l,authority:f,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:u}};function qz(r,e,t){if(t===1)return[r];if(r==="")return[""];const n=r.split(e);return t===0?n:n.slice(0,t-1).concat(n.slice(1).join(e))}const Wz=(r,e)=>r===e,Qz=(r,e,t,n)=>r==null||e>=t||r.length<t||/[^\u0000-\u007f]/.test(r)?null:n?r.substring(r.length-t,r.length-e):r.substring(e,t),Yz=r=>encodeURIComponent(r).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Xz={booleanEquals:Lz,coalesce:Uz,getAttr:qI,isSet:zz,isValidHostLabel:Kg,ite:$z,not:Hz,parseURL:Gz,split:qz,stringEquals:Wz,substring:Qz,uriEncode:Yz},QI=(r,e)=>{const t=[],{referenceRecord:n,endpointParams:i}=e;let a=0;for(;a<r.length;){const s=r.indexOf("{",a);if(s===-1){t.push(r.slice(a));break}t.push(r.slice(a,s));const o=r.indexOf("}",s);if(o===-1){t.push(r.slice(s));break}r[s+1]==="{"&&r[o+1]==="}"&&(t.push(r.slice(s+1,o)),a=o+2);const l=r.substring(s+1,o);if(l.includes("#")){const[u,c]=l.split("#");t.push(qI(n[u]??i[u],c))}else t.push(n[l]??i[l]);a=o+1}return t.join("")},Jz=({ref:r},e)=>e.referenceRecord[r]??e.endpointParams[r],rm=(r,e,t)=>{if(typeof r=="string")return QI(r,t);if(r.fn)return XI.callFunction(r,t);if(r.ref)return Jz(r,t);throw new Ba(`'${e}': ${String(r)} is not a string, function or reference.`)},YI=({fn:r,argv:e},t)=>{const n=Array(e.length);for(let s=0;s<n.length;++s){const o=e[s];typeof o=="boolean"||typeof o=="number"?n[s]=o:n[s]=XI.evaluateExpression(o,"arg",t)}const i=r.indexOf(".");if(i!==-1){const o=H1[r.slice(0,i)]?.[r.slice(i+1)];if(typeof o=="function")return o(...n)}const a=Xz[r];if(typeof a=="function")return a(...n);throw new Error(`function ${r} not loaded in endpointFunctions.`)},XI={evaluateExpression:rm,callFunction:YI},Kz=(r,e)=>{const{assign:t}=r;if(t&&t in e.referenceRecord)throw new Ba(`'${t}' is already defined in Reference Record.`);const n=YI(r,e);e.logger?.debug?.(`${Nz} evaluateCondition: ${Sg(r)} = ${Sg(n)}`);const i=n===""?!0:!!n;return t!=null?{result:i,toAssign:{name:t,value:n}}:{result:i}},Zz=(r,e)=>Object.entries(r??{}).reduce((t,[n,i])=>(t[n]=i.map(a=>{const s=rm(a,"Header value entry",e);if(typeof s!="string")throw new Ba(`Header '${n}' value '${s}' is not a string`);return s}),t),{}),JI=(r,e)=>Object.entries(r).reduce((t,[n,i])=>(t[n]=ZI.getEndpointProperty(i,e),t),{}),KI=(r,e)=>{if(Array.isArray(r))return r.map(t=>KI(t,e));switch(typeof r){case"string":return QI(r,e);case"object":if(r===null)throw new Ba(`Unexpected endpoint property: ${r}`);return ZI.getEndpointProperties(r,e);case"boolean":return r;default:throw new Ba(`Unexpected endpoint property type: ${typeof r}`)}},ZI={getEndpointProperty:KI,getEndpointProperties:JI},e$=(r,e)=>{const t=rm(r,"Endpoint URL",e);if(typeof t=="string")try{return new URL(t)}catch(n){throw console.error(`Failed to construct URL with ${t}`,n),n}throw new Ba(`Endpoint URL must be a string, got ${typeof t}`)},$v=1e8,t$=(r,e)=>{const{nodes:t,root:n,results:i,conditions:a}=r;let s=n;const o={},l={referenceRecord:o,endpointParams:e.endpointParams,logger:e.logger};for(;s!==1&&s!==-1&&s<$v;){const u=3*(Math.abs(s)-1),[c,f,d]=[t[u],t[u+1],t[u+2]],[h,g,v]=a[c],y=Kz({fn:h,assign:v,argv:g},l);if(y.toAssign){const{name:A,value:C}=y.toAssign;o[A]=C}s=s>=0===y.result?f:d}if(s>=$v){const u=i[s-$v];if(u[0]===-1){const[,h]=u;throw new Ba(rm(h,"Error",l))}const[c,f,d]=u;return{url:e$(c,l),properties:JI(f,l),headers:Zz(d??{},l)}}throw new Ba("No matching endpoint.")},r$=Mz(GI),eP=Bz(GI);class Hv extends qV(em,kl,Cg,Zg){}const n$=r=>crypto.getRandomValues(r),tP=WV(n$),i$=tP,bA=async(r=new Uint8Array,e)=>{if(r instanceof Uint8Array)return Hv.mutate(r);if(!r)return Hv.mutate(new Uint8Array);const t=e.streamCollector(r);return Hv.mutate(await t)};class a${serdeContext;setSerdeContext(e){this.serdeContext=e}}class s$ extends a${options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=Zi.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return na}getResponseType(){return sc}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,t){if("url"in t){e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,e.query||(e.query={});for(const[n,i]of t.url.searchParams.entries())e.query[n]=i;if(t.headers)for(const n in t.headers)e.headers[n]=t.headers[n].join(", ");return e}else{if(e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},t.headers)for(const n in t.headers)e.headers[n]=t.headers[n];return e}}setHostPrefix(e,t,n){if(this.serdeContext?.disableHostPrefix)return;const i=vi.of(t.input),a=zd(t.traits??{});if(a.endpoint){let s=a.endpoint?.[0];if(typeof s=="string"){for(const[o,l]of i.structIterator()){if(!l.getMergedTraits().hostLabel)continue;const u=n[o];if(typeof u!="string")throw new Error(`@smithy/core/schema - ${o} in input must be a string as hostLabel.`);s=s.replace(`{${o}}`,u)}e.hostname=s+e.hostname}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n})}async loadEventStreamCapability(){const{EventStreamSerde:e,eventStreamSerdeProvider:t}=await Promise.resolve().then(()=>require("./index.browser-BvJ1h7yg.cjs")),n=this.resolveEventStreamMarshaller(t);return new e({marshaller:n,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(e){const t=this.serdeContext;return t.eventStreamMarshaller?t.eventStreamMarshaller:e(this.serdeContext)}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,n,i,a){return[]}getEventStreamMarshaller(){const e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}}class o$ extends s${async serializeRequest(e,t,n){const i=this.serializer,a={},s={},o=await n.endpoint(),l=vi.of(e?.input),u=l.getSchema();let c;const f=t&&typeof t=="object"?t:{},d=new na({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:a,headers:s,body:void 0});if(o&&(this.updateServiceEndpoint(d,o),this.setHostPrefix(d,e,f)),f){const h=l.getEventStreamMember();if(h){if(f[h]){const g={};for(const[v,y]of l.structIterator())v!==h&&f[v]&&(i.write(y,f[v]),g[v]=i.flush());c=await this.serializeEventStream({eventStream:f[h],requestSchema:l,initialRequest:g})}}else i.write(u,f),c=i.flush()}return d.headers=Object.assign(d.headers,s),d.query=a,d.body=c,d.method="POST",d}async deserializeResponse(e,t,n){const i=this.deserializer,a=vi.of(e.output),s={};if(n.statusCode>=300){const l=await bA(n.body,t);throw l.byteLength>0&&Object.assign(s,await i.read(15,l)),await this.handleError(e,t,n,s,this.deserializeMetadata(n)),new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(const l in n.headers){const u=n.headers[l];delete n.headers[l],n.headers[l.toLowerCase()]=u}const o=a.getEventStreamMember();if(o)s[o]=await this.deserializeEventStream({response:n,responseSchema:a,initialResponseContainer:s});else{const l=await bA(n.body,t);l.byteLength>0&&Object.assign(s,await i.read(a,l))}return s.$metadata=this.deserializeMetadata(n),s}}function rP(r,e){if(e.timestampFormat.useTrait&&r.isTimestampSchema()&&(r.getSchema()===5||r.getSchema()===6||r.getSchema()===7))return r.getSchema();const{httpLabel:t,httpPrefixHeaders:n,httpHeader:i,httpQuery:a}=r.getMergedTraits();return(e.httpBindings?typeof n=="string"||i?6:a||t?5:void 0:void 0)??e.timestampFormat.default}const l$=r=>({setHttpHandler(e){r.httpHandler=e},httpHandler(){return r.httpHandler},updateHttpClientConfig(e,t){r.httpHandler?.updateHttpClientConfig(e,t)},httpHandlerConfigs(){return r.httpHandler.httpHandlerConfigs()}}),u$=r=>({httpHandler:r.httpHandler()}),zE="content-length";function c$(r){return e=>async t=>{const n=t.request;if(na.isInstance(n)){const{body:i,headers:a}=n;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf(zE)===-1)try{const s=r(i);n.headers={...n.headers,[zE]:String(s)}}catch{}}return e({...t,request:n})}}const d$={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},f$=r=>({applyToStack:e=>{e.add(c$(r.bodyLengthChecker),d$)}}),Cl=r=>encodeURIComponent(r).replace(/[!'()*]/g,h$),h$=r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`;function p$(r){const e=[];for(let t of Object.keys(r).sort()){const n=r[t];if(t=Cl(t),Array.isArray(n))for(let i=0,a=n.length;i<a;i++)e.push(`${t}=${Cl(n[i])}`);else{let i=t;(n||typeof n=="string")&&(i+=`=${Cl(n)}`),e.push(i)}}return e.join("&")}const g$=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],m$=["TimeoutError","RequestTimeout","RequestTimeoutException"],v$=[500,502,503,504],y$=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],A$=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],b$=r=>r?.$retryable!==void 0,w$=r=>r.$metadata?.clockSkewCorrected,C$=r=>{const e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return r&&r instanceof TypeError?e.has(r.message):!1},nP=r=>r.$metadata?.httpStatusCode===429||g$.includes(r.name)||r.$retryable?.throttling==!0,j1=(r,e=0)=>b$(r)||w$(r)||r.name==="InvalidSignatureException"&&r.message?.includes("Signature expired")||m$.includes(r.name)||y$.includes(r?.code||"")||A$.includes(r?.code||"")||v$.includes(r.$metadata?.httpStatusCode||0)||C$(r)||S$(r)||r.cause!==void 0&&e<=10&&j1(r.cause,e+1),x$=r=>{if(r.$metadata?.httpStatusCode!==void 0){const e=r.$metadata.httpStatusCode;return 500<=e&&e<=599&&!j1(r)}return!1};function S$(r){return r.code==="ERR_HTTP2_STREAM_ERROR"&&r.message.includes("NGHTTP2_REFUSED_STREAM")}const iP=20*1e3,$E=500,E$=1,k$="amz-sdk-invocation-id",T$="amz-sdk-request";function F$(r,e){if(sc.isInstance(r))for(const t of Object.keys(r.headers)){const n=t.toLowerCase();if(n==="retry-after"){const i=r.headers[t];let a=NaN;if(i.endsWith("GMT"))try{a=($I(i).getTime()-Date.now())/1e3}catch(s){e?.trace?.("Failed to parse retry-after header"),e?.trace?.(s)}else i.match(/ GMT, ((\d+)|(\d+\.\d+))$/)?a=Number(i.match(/ GMT, ([\d.]+)$/)?.[1]):i.match(/^((\d+)|(\d+\.\d+))$/)?a=Number(i):Date.parse(i)>=Date.now()&&(a=(Date.parse(i)-Date.now())/1e3);return isNaN(a)?void 0:new Date(Date.now()+a*1e3)}else if(n==="x-amz-retry-after"){const i=r.headers[t],a=Number(i);if(isNaN(a)){e?.trace?.(`Failed to parse x-amz-retry-after=${i}`);return}return new Date(Date.now()+a)}}}const I$=r=>r instanceof Error?r:r instanceof Object?Object.assign(new Error,r):typeof r=="string"?new Error(r):new Error(`AWS SDK error wrapper for ${r}`);function P$(r){return e=>(t,n)=>async i=>{let a=await e.retryStrategy();const s=await e.maxAttempts();if(R$(a)){a=a;let o=await a.acquireInitialRetryToken((n.partition_id??"")+(n.__retryLongPoll?":longpoll":"")),l=new Error,u=0,c=0;const{request:f}=i,d=na.isInstance(f);for(d&&(f.headers[k$]=tP());;)try{d&&(f.headers[T$]=`attempt=${u+1}; max=${s}`);const{response:h,output:g}=await t(i);return a.recordSuccess(o),g.$metadata.attempts=u+1,g.$metadata.totalRetryDelay=c,{response:h,output:g}}catch(h){const g=O$(h,e.logger);if(l=I$(h),d&&r(f))throw(n.logger instanceof UI?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),l;try{o=await a.refreshRetryTokenForRetry(o,g)}catch{throw l.$metadata||(l.$metadata={}),l.$metadata.attempts=u+1,l.$metadata.totalRetryDelay=c,l}u=o.getRetryCount();const v=o.getRetryDelay();c+=(o?.$retryLog?.acquisitionDelay??0)+v,v>0&&await D$(v)}}else return a=a,a?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",a.mode]]),a.retry(t,i)}}const D$=r=>new Promise(e=>setTimeout(e,r)),R$=r=>typeof r.acquireInitialRetryToken<"u"&&typeof r.refreshRetryTokenForRetry<"u"&&typeof r.recordSuccess<"u",O$=(r,e)=>{const t={error:r,errorType:B$(r)},n=F$(r.$response,e);return n&&(t.retryAfterHint=n),t},B$=r=>nP(r)?"THROTTLING":j1(r)?"TRANSIENT":x$(r)?"SERVER_ERROR":"CLIENT_ERROR",M$={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function _$(r){const e=P$(r);return t=>({applyToStack:n=>{n.add(e(t),M$)}})}class G1{static setTimeoutFn=(e,t)=>setTimeout(e,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(e){let t;this.updateMeasuredRate();const n=e;if(n?.errorType==="THROTTLING"||nP(n?.error??e)){const s=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=s,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(s),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const a=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(a)}getCurrentTimeInSeconds(){return Date.now()/1e3}async acquireTokenBucket(e){if(this.enabled){for(this.refillTokenBucket();e>this.availableTokens;){const t=(e-this.availableTokens)/this.fillRate*1e3;await new Promise(n=>G1.setTimeoutFn(n,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}const t=(e-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=e}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(e*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){const n=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(n*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}class Ei{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Ei.v2026?50:100}static throttlingDelay(){return Ei.v2026?1e3:500}static cost(){return Ei.v2026?14:5}static throttlingCost(){return Ei.v2026?5:10}static modifiedCostType(){return Ei.v2026?"THROTTLING":"TRANSIENT"}}class N${x=Ei.delay();computeNextBackoffDelay(e){const i=Math.random()*Math.min(this.x*2**e,iP);return Math.floor(i)}setDelayBase(e){this.x=e}}class HE{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(e,t,n,i){this.delay=e,this.count=t,this.cost=n,this.longPoll=i}getRetryCount(){return this.count}getRetryDelay(){return Math.min(iP,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Po;(function(r){r.STANDARD="standard",r.ADAPTIVE="adaptive"})(Po||(Po={}));const ef=3,L$=Po.STANDARD,kp={incompatible:1,attempts:2,capacity:3};class wA{mode=Po.STANDARD;retryBackoffStrategy;capacity=$E;maxAttemptsProvider;baseDelay;constructor(e){typeof e=="number"?this.maxAttemptsProvider=async()=>e:typeof e=="function"?this.maxAttemptsProvider=e:e&&typeof e=="object"&&(this.maxAttemptsProvider=async()=>e.maxAttempts,this.baseDelay=e.baseDelay,this.retryBackoffStrategy=e.backoff),this.maxAttemptsProvider??=async()=>ef,this.baseDelay??=Ei.delay(),this.retryBackoffStrategy??=new N$}async acquireInitialRetryToken(e){return new HE(Ei.delay(),0,void 0,Ei.v2026&&e.includes(":longpoll"))}async refreshRetryTokenForRetry(e,t){const n=await this.getMaxAttempts(),i=this.retryCode(e,t,n),a=i===0,s=e.isLongPoll?.();if(a||s){const o=t.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?Ei.throttlingDelay():this.baseDelay);const l=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount());let u=l;if(t.retryAfterHint instanceof Date&&(u=Math.max(l,Math.min(t.retryAfterHint.getTime()-Date.now(),l+5e3))),a){const c=this.getCapacityCost(o);this.capacity-=c;const f=new HE(0,e.getRetryCount()+1,c,e.isLongPoll?.()??!1);return await new Promise(d=>setTimeout(d,u)),f.$retryLog.acquisitionDelay=u,f}else{const c=Ei.v2026&&i===kp.capacity&&s?u:0;c>0&&await new Promise(f=>setTimeout(f,c))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min($E,this.capacity+(e.getRetryCost()??E$))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${ef}`),ef}}retryCode(e,t,n){const i=e.getRetryCount()+1,a=this.isRetryableError(t.errorType)?0:kp.incompatible,s=i<n?0:kp.attempts,o=this.capacity>=this.getCapacityCost(t.errorType)?0:kp.capacity;return a||s||o}getCapacityCost(e){return e===Ei.modifiedCostType()?Ei.throttlingCost():Ei.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class U${mode=Po.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,t){const{rateLimiter:n}=t??{};this.rateLimiter=n??new G1,this.standardRetryStrategy=t?new wA({maxAttempts:typeof e=="number"?e:3,...t}):new wA(e)}async acquireInitialRetryToken(e){const t=await this.standardRetryStrategy.acquireInitialRetryToken(e);return await this.rateLimiter.getSendToken(),t}async refreshRetryTokenForRetry(e,t){this.rateLimiter.updateClientSendingRate(t);const n=await this.standardRetryStrategy.refreshRetryTokenForRetry(e,t);return await this.rateLimiter.getSendToken(),n}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}const V$=(r,e)=>{const{retryStrategy:t,retryMode:n}=r,{defaultMaxAttempts:i=ef,defaultBaseDelay:a=Ei.delay()}={},s=Bs(r.maxAttempts??i);let o=t?Promise.resolve(t):void 0;const l=async()=>{const u=await s();return await Bs(n)()===Po.ADAPTIVE?new U$(s,{maxAttempts:u,baseDelay:a}):new wA({maxAttempts:u,baseDelay:a})};return Object.assign(r,{maxAttempts:s,retryStrategy:()=>o??=l()})},z$=_$(SV);Ei.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Is(r,e,t){r.__aws_sdk_context?r.__aws_sdk_context.features||(r.__aws_sdk_context.features={}):r.__aws_sdk_context={features:{}},r.__aws_sdk_context.features[e]=t}const $$=r=>e=>async t=>{if(!na.isInstance(t.request))return e(t);const{request:n}=t,{handlerProtocol:i=""}=r.requestHandler.metadata||{};if(i.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let a=n.hostname;n.port!=null&&(a+=`:${n.port}`),n.headers.host=a}return e(t)},H$={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},j$=r=>({applyToStack:e=>{e.add($$(r),H$)}}),G$=()=>(r,e)=>async t=>{try{const n=await r(t),{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l,overrideOutputFilterSensitiveLog:u}=o,c=l??e.inputFilterSensitiveLog,f=u??e.outputFilterSensitiveLog,{$metadata:d,...h}=n.output;return s?.info?.({clientName:i,commandName:a,input:c(t.input),output:f(h),metadata:d}),n}catch(n){const{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l}=o,u=l??e.inputFilterSensitiveLog;throw s?.error?.({clientName:i,commandName:a,input:u(t.input),error:n,metadata:n.$metadata}),n}},q$={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},W$=r=>({applyToStack:e=>{e.add(G$(),q$)}}),Q$=r=>({applyToStack:e=>{}}),Y$=(r,e)=>{if(!e||e.length===0)return r;const t=[];for(const n of e)for(const i of r)i.schemeId.split("#")[1]===n&&t.push(i);for(const n of r)t.find(({schemeId:i})=>i===n.schemeId)||t.push(n);return t};function X$(r){const e=new Map;for(const t of r)e.set(t.schemeId,t);return e}const J$=(r,e)=>(t,n)=>async i=>{const a=r.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(r,n,i.input)),s=r.authSchemePreference?await r.authSchemePreference():[],o=Y$(a,s),l=X$(r.httpAuthSchemes),u=vc(n),c=[];for(const f of o){const d=l.get(f.schemeId);if(!d){c.push(`HttpAuthScheme \`${f.schemeId}\` was not enabled for this service.`);continue}const h=d.identityProvider(await e.identityProviderConfigProvider(r));if(!h){c.push(`HttpAuthScheme \`${f.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:g={},signingProperties:v={}}=f.propertiesExtractor?.(r,n)||{};f.identityProperties=Object.assign(f.identityProperties||{},g),f.signingProperties=Object.assign(f.signingProperties||{},v),u.selectedHttpAuthScheme={httpAuthOption:f,identity:await h(f.identityProperties),signer:d.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(c.join(`
3043
- `));return t(i)},K$={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},Z$=(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t})=>({applyToStack:n=>{n.addRelativeTo(J$(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t}),K$)}}),eH=r=>e=>{throw e},tH=(r,e)=>{},rH=r=>(e,t)=>async n=>{if(!na.isInstance(n.request))return e(n);const a=vc(t).selectedHttpAuthScheme;if(!a)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties:s={}},identity:o,signer:l}=a,u=await e({...n,request:await l.sign(n.request,o,s)}).catch((l.errorHandler||eH)(s));return(l.successHandler||tH)(u.response,s),u},nH={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},iH=r=>({applyToStack:e=>{e.addRelativeTo(rH(),nH)}}),tf=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};class aH{authSchemes=new Map;constructor(e){for(const t in e){const n=e[t];n!==void 0&&this.authSchemes.set(t,n)}}getIdentityProvider(e){return this.authSchemes.get(e)}}class sH{async sign(e,t,n){return e}}const oH=r=>function(t){return aP(t)&&t.expiration.getTime()-Date.now()<r},lH=3e5,uH=oH(lH),aP=r=>r.expiration!==void 0,cH=(r,e,t)=>{if(r===void 0)return;const n=typeof r!="function"?async()=>Promise.resolve(r):r;let i,a,s,o=!1;const l=async u=>{a||(a=n(u));try{i=await a,s=!0,o=!1}finally{a=void 0}return i};return e===void 0?async u=>((!s||u?.forceRefresh)&&(i=await l(u)),i):async u=>((!s||u?.forceRefresh)&&(i=await l(u)),o?i:t(i)?(e(i)&&await l(u),i):(o=!0,i))},dH=void 0;function fH(r){return r===void 0?!0:typeof r=="string"&&r.length<=50}function hH(r){const e=tf(r.userAgentAppId??dH),{customUserAgent:t}=r;return Object.assign(r,{customUserAgent:typeof t=="string"?[[t]]:t,userAgentAppId:async()=>{const n=await e();if(!fH(n)){const i=r.logger?.constructor?.name==="NoOpLogger"||!r.logger?console:r.logger;typeof n!="string"?i?.warn("userAgentAppId must be a string or undefined."):n.length>50&&i?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return n}})}const pH={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}]};let gH=pH;const mH=r=>{const{partitions:e}=gH;for(const n of e){const{regions:i,outputs:a}=n;for(const[s,o]of Object.entries(i))if(s===r)return{...a,...o}}for(const n of e){const{regionRegex:i,outputs:a}=n;if(new RegExp(i).test(r))return{...a}}const t=e.find(n=>n.id==="aws");if(!t)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...t.outputs}},vH=/\d{12}\.ddb/;async function yH(r,e,t){if(t.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&Is(r,"PROTOCOL_RPC_V2_CBOR","M"),typeof e.retryStrategy=="function"){const a=await e.retryStrategy();if(typeof a.mode=="string")switch(a.mode){case Po.ADAPTIVE:Is(r,"RETRY_MODE_ADAPTIVE","F");break;case Po.STANDARD:Is(r,"RETRY_MODE_STANDARD","E");break}}if(typeof e.accountIdEndpointMode=="function"){const a=r.endpointV2;switch(String(a?.url?.hostname).match(vH)&&Is(r,"ACCOUNT_ID_ENDPOINT","O"),await e.accountIdEndpointMode?.()){case"disabled":Is(r,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Is(r,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Is(r,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const i=r.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const a=i;a.accountId&&Is(r,"RESOLVED_ACCOUNT_ID","T");for(const[s,o]of Object.entries(a.$source??{}))Is(r,s,o)}}const jE="user-agent",jv="x-amz-user-agent",GE=" ",Gv="/",AH=/[^!$%&'*+\-.^_`|~\w]/g,bH=/[^!$%&'*+\-.^_`|~\w#]/g,qE="-",wH=1024;function CH(r){let e="";for(const t in r){const n=r[t];if(e.length+n.length+1<=wH){e.length?e+=","+n:e+=n;continue}break}return e}const xH=r=>(e,t)=>async n=>{const{request:i}=n;if(!na.isInstance(i))return e(n);const{headers:a}=i,s=t?.userAgent?.map(Tp)||[],o=(await r.defaultUserAgentProvider()).map(Tp);await yH(t,r,n);const l=t;o.push(`m/${CH(Object.assign({},t.__smithy_context?.features,l.__aws_sdk_context?.features))}`);const u=r?.customUserAgent?.map(Tp)||[],c=await r.userAgentAppId();c&&o.push(Tp(["app",`${c}`]));const f=[].concat([...o,...s,...u]).join(GE),d=[...o.filter(h=>h.startsWith("aws-sdk-")),...u].join(GE);return r.runtime!=="browser"?(d&&(a[jv]=a[jv]?`${a[jE]} ${d}`:d),a[jE]=f):a[jv]=f,e({...n,request:i})},Tp=r=>{const e=r[0].split(Gv).map(s=>s.replace(AH,qE)).join(Gv),t=r[1]?.replace(bH,qE),n=e.indexOf(Gv),i=e.substring(0,n);let a=e.substring(n+1);return i==="api"&&(a=a.toLowerCase()),[i,a,t].filter(s=>s&&s.length>0).reduce((s,o,l)=>{switch(l){case 0:return o;case 1:return`${s}/${o}`;default:return`${s}#${o}`}},"")},SH={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},EH=r=>({applyToStack:e=>{e.add(xH(r),SH)}}),kH=({serviceId:r,clientVersion:e})=>async t=>{const n=typeof window<"u"?window.navigator:void 0,i=n?.userAgent??"",a=n?.userAgentData?.platform??WE.os(i)??"other",s=void 0,o=n?.userAgentData?.brands??[],l=o[o.length-1],u=l?.brand??WE.browser(i)??"unknown",c=l?.version??"unknown",f=[["aws-sdk-js",e],["ua","2.1"],[`os/${a}`,s],["lang/js"],["md/browser",`${u}_${c}`]];r&&f.push([`api/${r}`,e]);const d=await t?.userAgentAppId?.();return d&&f.push([`app/${d}`]),f},WE={os(r){if(/iPhone|iPad|iPod/.test(r))return"iOS";if(/Macintosh|Mac OS X/.test(r))return"macOS";if(/Windows NT/.test(r))return"Windows";if(/Android/.test(r))return"Android";if(/Linux/.test(r))return"Linux"},browser(r){if(/EdgiOS|EdgA|Edg\//.test(r))return"Microsoft Edge";if(/Firefox\//.test(r))return"Firefox";if(/Chrome\//.test(r))return"Chrome";if(/Safari\//.test(r))return"Safari"}},sP=(r,e=!1)=>{if(e){for(const t of r.split("."))if(!sP(t))return!1;return!0}return!(!Kg(r)||r.length<3||r.length>63||r!==r.toLowerCase()||WI(r))},QE=":",TH="/",FH=r=>{const e=r.split(QE);if(e.length<6)return null;const[t,n,i,a,s,...o]=e;if(t!=="arn"||n===""||i===""||o.join(QE)==="")return null;const l=o.map(u=>u.split(TH)).flat();return{partition:n,service:i,region:a,accountId:s,resourceId:l}},oP={isVirtualHostableS3Bucket:sP,parseArn:FH,partition:mH};H1.aws=oP;const IH=(r,e,t)=>{let n,i,a,s=!1;const o=async()=>{i||(i=r());try{n=await i,a=!0,s=!1}finally{i=void 0}return n};return async l=>((!a||l?.forceRefresh)&&(n=await o()),n)},YE=new Set,PH=(r,e=Kg)=>{if(!YE.has(r)&&!e(r))if(r==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${r}" is not a valid hostname component.`);else YE.add(r)},lP=r=>typeof r=="string"&&(r.startsWith("fips-")||r.endsWith("-fips")),DH=r=>lP(r)?["fips-aws-global","aws-fips"].includes(r)?"us-east-1":r.replace(/fips-(dkr-|prod-)?|-fips/,""):r,RH=r=>{const{region:e,useFipsEndpoint:t}=r;if(!e)throw new Error("Region is missing");return Object.assign(r,{region:async()=>{const n=typeof e=="function"?await e():e,i=DH(n);return PH(i),i},useFipsEndpoint:async()=>{const n=typeof e=="string"?e:await e();return lP(n)?!0:typeof t!="function"?Promise.resolve(!!t):t()}})},OH=["in-region","cross-region","mobile","standard","legacy"],BH=({defaultsMode:r}={})=>IH(async()=>{const e=typeof r=="function"?await r():r;switch(e?.toLowerCase()){case"auto":return Promise.resolve(MH()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(e?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${OH.join(", ")}, got ${e}`)}}),MH=()=>{const r=window?.navigator;if(r?.connection){const{effectiveType:e,rtt:t,downlink:n}=r?.connection;if(typeof e=="string"&&e!=="4g"||Number(t)>100||Number(n)<10)return!0}return r?.userAgentData?.mobile||typeof r?.maxTouchPoints=="number"&&r?.maxTouchPoints>1},_H=!1,NH=!1,LH=r=>({setRegion(e){r.region=e},region(){return r.region}}),UH=r=>({region:r.region()}),XE=r=>sc.isInstance(r)?r.headers?.date??r.headers?.Date:void 0,uP=r=>new Date(Date.now()+r),VH=(r,e)=>Math.abs(uP(e).getTime()-r)>=3e5,JE=(r,e)=>{const t=Date.parse(r);return VH(t,e)?t-Date.now():e},rf=(r,e)=>{if(!e)throw new Error(`Property \`${r}\` is not resolved for AWS SDK SigV4Auth`);return e},zH=async r=>{const e=rf("context",r.context),t=rf("config",r.config),n=e.endpointV2?.properties?.authSchemes?.[0],a=await rf("signer",t.signer)(n),s=r?.signingRegion,o=r?.signingRegionSet,l=r?.signingName;return{config:t,signer:a,signingRegion:s,signingRegionSet:o,signingName:l}};class $H{async sign(e,t,n){if(!na.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const i=await zH(n),{config:a,signer:s}=i;let{signingRegion:o,signingName:l}=i;const u=n.context;if(u?.authSchemes?.length??!1){const[f,d]=u.authSchemes;f?.name==="sigv4a"&&d?.name==="sigv4"&&(o=d?.signingRegion??o,l=d?.signingName??l)}return n._preRequestSystemClockOffset=a.systemClockOffset,await s.sign(e,{signingDate:uP(a.systemClockOffset),signingRegion:o,signingService:l})}errorHandler(e){return t=>{const n=t,i=n.ServerTime??XE(n.$response);if(i){const a=rf("config",e.config),s=e._preRequestSystemClockOffset,o=JE(i,a.systemClockOffset);(o!==a.systemClockOffset||s!==void 0&&s!==o)&&n.$metadata&&(a.systemClockOffset=o,n.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const n=XE(e);if(n){const i=rf("config",t.config);i.systemClockOffset=JE(n,i.systemClockOffset)}}}class HH{format(e){const t=[];for(const a of Object.keys(e)){const s=kl(a);t.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[a]))}const n=new Uint8Array(t.reduce((a,s)=>a+s.byteLength,0));let i=0;for(const a of t)n.set(a,i),i+=a.byteLength;return n}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const n=new DataView(new ArrayBuffer(5));return n.setUint8(0,4),n.setInt32(1,e.value,!1),new Uint8Array(n.buffer);case"long":const i=new Uint8Array(9);return i[0]=5,i.set(e.value.bytes,1),i;case"binary":const a=new DataView(new ArrayBuffer(3+e.value.byteLength));a.setUint8(0,6),a.setUint16(1,e.value.byteLength,!1);const s=new Uint8Array(a.buffer);return s.set(e.value,3),s;case"string":const o=kl(e.value),l=new DataView(new ArrayBuffer(3+o.byteLength));l.setUint8(0,7),l.setUint16(1,o.byteLength,!1);const u=new Uint8Array(l.buffer);return u.set(o,3),u;case"timestamp":const c=new Uint8Array(9);return c[0]=8,c.set(q1.fromNumber(e.value.valueOf()).bytes,1),c;case"uuid":if(!jH.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const f=new Uint8Array(17);return f[0]=9,f.set(jI(e.value.replace(/\-/g,"")),1),f}}}var KE;(function(r){r[r.boolTrue=0]="boolTrue",r[r.boolFalse=1]="boolFalse",r[r.byte=2]="byte",r[r.short=3]="short",r[r.integer=4]="integer",r[r.long=5]="long",r[r.byteArray=6]="byteArray",r[r.string=7]="string",r[r.timestamp=8]="timestamp",r[r.uuid=9]="uuid"})(KE||(KE={}));const jH=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class q1{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let n=7,i=Math.abs(Math.round(e));n>-1&&i>0;n--,i/=256)t[n]=i;return e<0&&ZE(t),new q1(t)}valueOf(){const e=this.bytes.slice(0),t=e[0]&128;return t&&ZE(e),parseInt(Ao(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function ZE(r){for(let e=0;e<8;e++)r[e]^=255;for(let e=7;e>-1&&(r[e]++,r[e]===0);e--);}const GH="X-Amz-Algorithm",qH="X-Amz-Credential",cP="X-Amz-Date",WH="X-Amz-SignedHeaders",QH="X-Amz-Expires",dP="X-Amz-Signature",fP="X-Amz-Security-Token",hP="authorization",pP=cP.toLowerCase(),YH="date",XH=[hP,pP,YH],JH=dP.toLowerCase(),CA="x-amz-content-sha256",KH=fP.toLowerCase(),ZH={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},ej=/^proxy-/,tj=/^sec-/,qv="AWS4-HMAC-SHA256",rj="AWS4-HMAC-SHA256-PAYLOAD",nj="UNSIGNED-PAYLOAD",ij=50,gP="aws4_request",aj=3600*24*7,sj=({query:r={}})=>{const e=[],t={};for(const n of Object.keys(r)){if(n.toLowerCase()===JH)continue;const i=Cl(n);e.push(i);const a=r[n];typeof a=="string"?t[i]=`${i}=${Cl(a)}`:Array.isArray(a)&&(t[i]=a.slice(0).reduce((s,o)=>s.concat([`${i}=${Cl(o)}`]),[]).sort().join("&"))}return e.sort().map(n=>t[n]).filter(n=>n).join("&")},oj=r=>lj(r).toISOString().replace(/\.\d{3}Z$/,"Z"),lj=r=>typeof r=="number"?new Date(r*1e3):typeof r=="string"?Number(r)?new Date(Number(r)*1e3):new Date(r):r;class uj{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s=!0}){this.service=i,this.sha256=a,this.uriEscapePath=s,this.applyChecksum=typeof e=="boolean"?e:!0,this.regionProvider=Bs(n),this.credentialProvider=Bs(t)}createCanonicalRequest(e,t,n){const i=Object.keys(t).sort();return`${e.method}
3042
+ `),iz={warn:console.warn},az=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],z1=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function sz(r){const e=r.getUTCFullYear(),t=r.getUTCMonth(),n=r.getUTCDay(),i=r.getUTCDate(),a=r.getUTCHours(),s=r.getUTCMinutes(),o=r.getUTCSeconds(),l=i<10?`0${i}`:`${i}`,u=a<10?`0${a}`:`${a}`,c=s<10?`0${s}`:`${s}`,f=o<10?`0${o}`:`${o}`;return`${az[n]}, ${l} ${z1[t]} ${e} ${u}:${c}:${f} GMT`}const oz=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),lz=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=oz.exec(r);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,n,i,a,s,o,l,u,c]=e,f=xg(Ef(n)),d=yo(i,"month",1,12),h=yo(a,"day",1,31),g=Jp(f,d,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u});return c.toUpperCase()!="Z"&&g.setTime(g.getTime()-bz(c)),g},uz=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),cz=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),dz=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),$I=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=uz.exec(r);if(e){const[t,n,i,a,s,o,l,u]=e;return Jp(xg(Ef(a)),Vv(i),yo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u})}if(e=cz.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return gz(Jp(hz(a),Vv(i),yo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u}))}if(e=dz.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return Jp(xg(Ef(u)),Vv(n),yo(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},fz=r=>{if(r==null)return;let e;if(typeof r=="number")e=r;else if(typeof r=="string")e=ZV(r);else if(typeof r=="object"&&r.tag===1)e=r.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},Jp=(r,e,t,n)=>{const i=e-1;return vz(r,i,t),new Date(Date.UTC(r,i,t,yo(n.hours,"hour",0,23),yo(n.minutes,"minute",0,59),yo(n.seconds,"seconds",0,60),Az(n.fractionalMilliseconds)))},hz=r=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+xg(Ef(r));return t<e?t+100:t},pz=50*365*24*60*60*1e3,gz=r=>r.getTime()-new Date().getTime()>pz?new Date(Date.UTC(r.getUTCFullYear()-100,r.getUTCMonth(),r.getUTCDate(),r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds())):r,Vv=r=>{const e=z1.indexOf(r);if(e<0)throw new TypeError(`Invalid month: ${r}`);return e+1},mz=[31,28,31,30,31,30,31,31,30,31,30,31],vz=(r,e,t)=>{let n=mz[e];if(e===1&&yz(r)&&(n=29),t>n)throw new TypeError(`Invalid day for ${z1[e]} in ${r}: ${t}`)},yz=r=>r%4===0&&(r%100!==0||r%400===0),yo=(r,e,t,n)=>{const i=rz(Ef(r));if(i<t||i>n)throw new TypeError(`${e} must be between ${t} and ${n}, inclusive`);return i},Az=r=>r==null?0:ez("0."+r)*1e3,bz=r=>{const e=r[0];let t=1;if(e=="+")t=1;else if(e=="-")t=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);const n=Number(r.substring(1,3)),i=Number(r.substring(4,6));return t*(n*60+i)*60*1e3},Ef=r=>{let e=0;for(;e<r.length-1&&r.charAt(e)==="0";)e++;return e===0?r:r.slice(e)},po=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};po.from=r=>r&&typeof r=="object"&&(r instanceof po||"deserializeJSON"in r)?r:typeof r=="string"||Object.getPrototypeOf(r)===String.prototype?po(String(r)):po(JSON.stringify(r));po.fromObject=po.from;const UE=/^-?\d*(\.\d+)?$/;class ns{string;type;constructor(e,t){if(this.string=e,this.type=t,!UE.test(e))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;const t=e;return ns.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&UE.test(t.string)}}const HI={},AA={};for(let r=0;r<256;r++){let e=r.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),HI[r]=e,AA[e]=r}function jI(r){if(r.length%2!==0)throw new Error("Hex encoded strings must have an even number length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2){const n=r.slice(t,t+2).toLowerCase();if(n in AA)e[t/2]=AA[n];else throw new Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return e}function Ao(r){let e="";for(let t=0;t<r.byteLength;t++)e+=HI[r[t]];return e}const VE=typeof TextEncoder=="function"?new TextEncoder:null,wz=r=>{if(typeof r=="string"){if(VE)return VE.encode(r).byteLength;let e=r.length;for(let t=e-1;t>=0;t--){const n=r.charCodeAt(t);n>127&&n<=2047?e++:n>2047&&n<=65535&&(e+=2),n>=56320&&n<=57343&&t--}return e}else{if(typeof r.byteLength=="number")return r.byteLength;if(typeof r.size=="number")return r.size}throw new Error(`Body Length computation failed for ${r}`)},kf=r=>typeof r=="string"?kl(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r),Cz=r=>typeof ArrayBuffer=="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]",GI=async r=>{},xz=async r=>{const e=r?.Bucket||"";if(typeof r.Bucket=="string"&&(r.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),Fz(e)){if(r.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!Tz(e)||e.indexOf(".")!==-1&&!String(r.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(r.ForcePathStyle=!0);return r.DisableMultiRegionAccessPoints&&(r.disableMultiRegionAccessPoints=!0,r.DisableMRAP=!0),r},Sz=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,Ez=/(\d+\.){3}\d+/,kz=/\.\./,Tz=r=>Sz.test(r)&&!Ez.test(r)&&!kz.test(r),Fz=r=>{const[e,t,n,,,i]=r.split(":"),a=e==="arn"&&r.split(":").length>=6,s=!!(a&&t&&n&&i);if(a&&!s)throw new Error(`Invalid ARN: ${r} was an invalid ARN.`);return s},Iz=(r,e,t,n=!1)=>{const i=async()=>{let a;return n?a=t.clientContextParams?.[r]??t[r]??t[e]:a=t[r]??t[e],typeof a=="function"?a():a};return r==="credentialScope"||e==="CredentialScope"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.credentialScope??a?.CredentialScope}:r==="accountId"||e==="AccountId"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.accountId??a?.AccountId}:r==="endpoint"||e==="endpoint"?async()=>{if(t.isCustomEndpoint===!1)return;const a=await i();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:s,hostname:o,port:l,path:u}=a;return`${s}//${o}${l?":"+l:""}${u}`}}return a}:i};function Pz(r){return async(e,t,n,i)=>{if(!n.isCustomEndpoint){let o;n.serviceConfiguredEndpoint?o=await n.serviceConfiguredEndpoint():o=await r(n.serviceId),o&&(n.endpoint=()=>Promise.resolve(U1(o)),n.isCustomEndpoint=!0)}const a=await Dz(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");const s=n.endpointProvider(a,i);if(n.isCustomEndpoint&&n.endpoint){const o=await n.endpoint();if(o?.headers){s.headers??={};for(const[l,u]of Object.entries(o.headers))s.headers[l]=Array.isArray(u)?u:[u]}}return s}}const Dz=async(r,e,t)=>{const n={},i=e?.getEndpointParameterInstructions?.()||{};for(const[a,s]of Object.entries(i))switch(s.type){case"staticContextParams":n[a]=s.value;break;case"contextParams":n[a]=r[s.name];break;case"clientContextParams":case"builtInParams":n[a]=await Iz(s.name,a,t,s.type!=="builtInParams")();break;case"operationContextParams":n[a]=s.get(r);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(i).length===0&&Object.assign(n,t),String(t.serviceId).toLowerCase()==="s3"&&await xz(n),n};function Rz(r,e,t){r.__smithy_context?r.__smithy_context.features||(r.__smithy_context.features={}):r.__smithy_context={features:{}},r.__smithy_context.features[e]=t}function Oz(r){const e=Pz(r);return({config:t,instructions:n})=>(i,a)=>async s=>{t.isCustomEndpoint&&Rz(a,"ENDPOINT_OVERRIDE","N");const o=await e(s.input,{getEndpointParameterInstructions(){return n}},{...t},a);a.endpointV2=o,a.authSchemes=o.properties?.authSchemes;const l=a.authSchemes?.[0];if(l){a.signing_region=l.signingRegion,a.signing_service=l.signingName;const c=vc(a)?.selectedHttpAuthScheme?.httpAuthOption;c&&(c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:l.signingRegion,signingRegion:l.signingRegion,signing_service:l.signingName,signingName:l.signingName,signingRegionSet:l.signingRegionSet},l.properties))}return i({...s})}}const Bz={name:"serializerMiddleware"},Mz={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Bz.name};function _z(r){const e=Oz(r);return(t,n)=>({applyToStack:i=>{i.addRelativeTo(e({config:t,instructions:n}),Mz)}})}function Nz(r){return e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:a}=e,s=n!=null?async()=>U1(await Bs(n)()):void 0,l=Object.assign(e,{endpoint:s,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:Bs(i??!1),useFipsEndpoint:Bs(a??!1)});let u;return l.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=r(e.serviceId)),u),l}}class $1{nodes;root;conditions;results;constructor(e,t,n,i){this.nodes=e,this.root=t,this.conditions=n,this.results=i}static from(e,t,n,i){return new $1(e,t,n,i)}}class Lz{capacity;data=new Map;parameters=[];constructor({size:e,params:t}){this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const n=this.hash(e);if(n===!1)return t();if(!this.data.has(n)){if(this.data.size>this.capacity+10){const i=this.data.keys();let a=0;for(;;){const{value:s,done:o}=i.next();if(this.data.delete(s),o||++a>10)break}}this.data.set(n,t())}return this.data.get(n)}size(){return this.data.size}hash(e){let t="";const{parameters:n}=this;if(n.length===0)return!1;for(const i of n){const a=String(e[i]??"");if(a.includes("|;"))return!1;t+=a+"|;"}return t}}class Ba extends Error{constructor(e){super(e),this.name="EndpointError"}}const Uz="endpoints";function Sg(r){return typeof r!="object"||r==null?r:"ref"in r?`$${Sg(r.ref)}`:"fn"in r?`${r.fn}(${(r.argv||[]).map(Sg).join(", ")})`:JSON.stringify(r,null,2)}const H1={},Vz=(r,e)=>r===e;function zz(...r){for(const e of r)if(e!=null)return e}const $z=r=>{const e=r.split("."),t=[];for(const n of e){const i=n.indexOf("[");if(i!==-1){if(n.indexOf("]")!==n.length-1)throw new Ba(`Path: '${r}' does not end with ']'`);const a=n.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new Ba(`Invalid array index: '${a}' in path: '${r}'`);i!==0&&t.push(n.slice(0,i)),t.push(a)}else t.push(n)}return t},qI=(r,e)=>$z(e).reduce((t,n)=>{if(typeof t!="object")throw new Ba(`Index '${n}' in '${e}' not found in '${JSON.stringify(r)}'`);if(Array.isArray(t)){const i=parseInt(n);return t[i<0?t.length+i:i]}return t[n]},r),Hz=r=>r!=null;function jz(r,e,t){return r?e:t}const Gz=r=>!r,qz=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),WI=r=>qz.test(r)||r.startsWith("[")&&r.endsWith("]"),zv={[xf.HTTP]:80,[xf.HTTPS]:443},Wz=r=>{const e=(()=>{try{if(r instanceof URL)return r;if(typeof r=="object"&&"hostname"in r){const{hostname:d,port:h,protocol:g="",path:v="",query:y={}}=r,A=new URL(`${g}//${d}${h?`:${h}`:""}${v}`);return A.search=Object.entries(y).map(([C,S])=>`${C}=${S}`).join("&"),A}return new URL(r)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(r)} as a whatwg URL.`),null;const t=e.href,{host:n,hostname:i,pathname:a,protocol:s,search:o}=e;if(o)return null;const l=s.slice(0,-1);if(!Object.values(xf).includes(l))return null;const u=WI(i),c=t.includes(`${n}:${zv[l]}`)||typeof r=="string"&&r.includes(`${n}:${zv[l]}`),f=`${n}${c?`:${zv[l]}`:""}`;return{scheme:l,authority:f,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:u}};function Qz(r,e,t){if(t===1)return[r];if(r==="")return[""];const n=r.split(e);return t===0?n:n.slice(0,t-1).concat(n.slice(1).join(e))}const Yz=(r,e)=>r===e,Xz=(r,e,t,n)=>r==null||e>=t||r.length<t||/[^\u0000-\u007f]/.test(r)?null:n?r.substring(r.length-t,r.length-e):r.substring(e,t),Jz=r=>encodeURIComponent(r).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Kz={booleanEquals:Vz,coalesce:zz,getAttr:qI,isSet:Hz,isValidHostLabel:Kg,ite:jz,not:Gz,parseURL:Wz,split:Qz,stringEquals:Yz,substring:Xz,uriEncode:Jz},QI=(r,e)=>{const t=[],{referenceRecord:n,endpointParams:i}=e;let a=0;for(;a<r.length;){const s=r.indexOf("{",a);if(s===-1){t.push(r.slice(a));break}t.push(r.slice(a,s));const o=r.indexOf("}",s);if(o===-1){t.push(r.slice(s));break}r[s+1]==="{"&&r[o+1]==="}"&&(t.push(r.slice(s+1,o)),a=o+2);const l=r.substring(s+1,o);if(l.includes("#")){const[u,c]=l.split("#");t.push(qI(n[u]??i[u],c))}else t.push(n[l]??i[l]);a=o+1}return t.join("")},Zz=({ref:r},e)=>e.referenceRecord[r]??e.endpointParams[r],rm=(r,e,t)=>{if(typeof r=="string")return QI(r,t);if(r.fn)return XI.callFunction(r,t);if(r.ref)return Zz(r,t);throw new Ba(`'${e}': ${String(r)} is not a string, function or reference.`)},YI=({fn:r,argv:e},t)=>{const n=Array(e.length);for(let s=0;s<n.length;++s){const o=e[s];typeof o=="boolean"||typeof o=="number"?n[s]=o:n[s]=XI.evaluateExpression(o,"arg",t)}const i=r.indexOf(".");if(i!==-1){const o=H1[r.slice(0,i)]?.[r.slice(i+1)];if(typeof o=="function")return o(...n)}const a=Kz[r];if(typeof a=="function")return a(...n);throw new Error(`function ${r} not loaded in endpointFunctions.`)},XI={evaluateExpression:rm,callFunction:YI},e$=(r,e)=>{const{assign:t}=r;if(t&&t in e.referenceRecord)throw new Ba(`'${t}' is already defined in Reference Record.`);const n=YI(r,e);e.logger?.debug?.(`${Uz} evaluateCondition: ${Sg(r)} = ${Sg(n)}`);const i=n===""?!0:!!n;return t!=null?{result:i,toAssign:{name:t,value:n}}:{result:i}},t$=(r,e)=>Object.entries(r??{}).reduce((t,[n,i])=>(t[n]=i.map(a=>{const s=rm(a,"Header value entry",e);if(typeof s!="string")throw new Ba(`Header '${n}' value '${s}' is not a string`);return s}),t),{}),JI=(r,e)=>Object.entries(r).reduce((t,[n,i])=>(t[n]=ZI.getEndpointProperty(i,e),t),{}),KI=(r,e)=>{if(Array.isArray(r))return r.map(t=>KI(t,e));switch(typeof r){case"string":return QI(r,e);case"object":if(r===null)throw new Ba(`Unexpected endpoint property: ${r}`);return ZI.getEndpointProperties(r,e);case"boolean":return r;default:throw new Ba(`Unexpected endpoint property type: ${typeof r}`)}},ZI={getEndpointProperty:KI,getEndpointProperties:JI},r$=(r,e)=>{const t=rm(r,"Endpoint URL",e);if(typeof t=="string")try{return new URL(t)}catch(n){throw console.error(`Failed to construct URL with ${t}`,n),n}throw new Ba(`Endpoint URL must be a string, got ${typeof t}`)},$v=1e8,n$=(r,e)=>{const{nodes:t,root:n,results:i,conditions:a}=r;let s=n;const o={},l={referenceRecord:o,endpointParams:e.endpointParams,logger:e.logger};for(;s!==1&&s!==-1&&s<$v;){const u=3*(Math.abs(s)-1),[c,f,d]=[t[u],t[u+1],t[u+2]],[h,g,v]=a[c],y=e$({fn:h,assign:v,argv:g},l);if(y.toAssign){const{name:A,value:C}=y.toAssign;o[A]=C}s=s>=0===y.result?f:d}if(s>=$v){const u=i[s-$v];if(u[0]===-1){const[,h]=u;throw new Ba(rm(h,"Error",l))}const[c,f,d]=u;return{url:r$(c,l),properties:JI(f,l),headers:t$(d??{},l)}}throw new Ba("No matching endpoint.")},i$=Nz(GI),eP=_z(GI);class Hv extends QV(em,kl,Cg,Zg){}const a$=r=>crypto.getRandomValues(r),tP=YV(a$),s$=tP,bA=async(r=new Uint8Array,e)=>{if(r instanceof Uint8Array)return Hv.mutate(r);if(!r)return Hv.mutate(new Uint8Array);const t=e.streamCollector(r);return Hv.mutate(await t)};class o${serdeContext;setSerdeContext(e){this.serdeContext=e}}class l$ extends o${options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=Zi.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return na}getResponseType(){return sc}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,t){if("url"in t){e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,e.query||(e.query={});for(const[n,i]of t.url.searchParams.entries())e.query[n]=i;if(t.headers)for(const n in t.headers)e.headers[n]=t.headers[n].join(", ");return e}else{if(e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},t.headers)for(const n in t.headers)e.headers[n]=t.headers[n];return e}}setHostPrefix(e,t,n){if(this.serdeContext?.disableHostPrefix)return;const i=vi.of(t.input),a=zd(t.traits??{});if(a.endpoint){let s=a.endpoint?.[0];if(typeof s=="string"){for(const[o,l]of i.structIterator()){if(!l.getMergedTraits().hostLabel)continue;const u=n[o];if(typeof u!="string")throw new Error(`@smithy/core/schema - ${o} in input must be a string as hostLabel.`);s=s.replace(`{${o}}`,u)}e.hostname=s+e.hostname}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n})}async loadEventStreamCapability(){const{EventStreamSerde:e,eventStreamSerdeProvider:t}=await Promise.resolve().then(()=>require("./index.browser-BfhBgZKW.cjs")),n=this.resolveEventStreamMarshaller(t);return new e({marshaller:n,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(e){const t=this.serdeContext;return t.eventStreamMarshaller?t.eventStreamMarshaller:e(this.serdeContext)}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,n,i,a){return[]}getEventStreamMarshaller(){const e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}}class u$ extends l${async serializeRequest(e,t,n){const i=this.serializer,a={},s={},o=await n.endpoint(),l=vi.of(e?.input),u=l.getSchema();let c;const f=t&&typeof t=="object"?t:{},d=new na({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:a,headers:s,body:void 0});if(o&&(this.updateServiceEndpoint(d,o),this.setHostPrefix(d,e,f)),f){const h=l.getEventStreamMember();if(h){if(f[h]){const g={};for(const[v,y]of l.structIterator())v!==h&&f[v]&&(i.write(y,f[v]),g[v]=i.flush());c=await this.serializeEventStream({eventStream:f[h],requestSchema:l,initialRequest:g})}}else i.write(u,f),c=i.flush()}return d.headers=Object.assign(d.headers,s),d.query=a,d.body=c,d.method="POST",d}async deserializeResponse(e,t,n){const i=this.deserializer,a=vi.of(e.output),s={};if(n.statusCode>=300){const l=await bA(n.body,t);throw l.byteLength>0&&Object.assign(s,await i.read(15,l)),await this.handleError(e,t,n,s,this.deserializeMetadata(n)),new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(const l in n.headers){const u=n.headers[l];delete n.headers[l],n.headers[l.toLowerCase()]=u}const o=a.getEventStreamMember();if(o)s[o]=await this.deserializeEventStream({response:n,responseSchema:a,initialResponseContainer:s});else{const l=await bA(n.body,t);l.byteLength>0&&Object.assign(s,await i.read(a,l))}return s.$metadata=this.deserializeMetadata(n),s}}function rP(r,e){if(e.timestampFormat.useTrait&&r.isTimestampSchema()&&(r.getSchema()===5||r.getSchema()===6||r.getSchema()===7))return r.getSchema();const{httpLabel:t,httpPrefixHeaders:n,httpHeader:i,httpQuery:a}=r.getMergedTraits();return(e.httpBindings?typeof n=="string"||i?6:a||t?5:void 0:void 0)??e.timestampFormat.default}const c$=r=>({setHttpHandler(e){r.httpHandler=e},httpHandler(){return r.httpHandler},updateHttpClientConfig(e,t){r.httpHandler?.updateHttpClientConfig(e,t)},httpHandlerConfigs(){return r.httpHandler.httpHandlerConfigs()}}),d$=r=>({httpHandler:r.httpHandler()}),zE="content-length";function f$(r){return e=>async t=>{const n=t.request;if(na.isInstance(n)){const{body:i,headers:a}=n;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf(zE)===-1)try{const s=r(i);n.headers={...n.headers,[zE]:String(s)}}catch{}}return e({...t,request:n})}}const h$={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},p$=r=>({applyToStack:e=>{e.add(f$(r.bodyLengthChecker),h$)}}),Cl=r=>encodeURIComponent(r).replace(/[!'()*]/g,g$),g$=r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`;function m$(r){const e=[];for(let t of Object.keys(r).sort()){const n=r[t];if(t=Cl(t),Array.isArray(n))for(let i=0,a=n.length;i<a;i++)e.push(`${t}=${Cl(n[i])}`);else{let i=t;(n||typeof n=="string")&&(i+=`=${Cl(n)}`),e.push(i)}}return e.join("&")}const v$=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],y$=["TimeoutError","RequestTimeout","RequestTimeoutException"],A$=[500,502,503,504],b$=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],w$=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],C$=r=>r?.$retryable!==void 0,x$=r=>r.$metadata?.clockSkewCorrected,S$=r=>{const e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return r&&r instanceof TypeError?e.has(r.message):!1},nP=r=>r.$metadata?.httpStatusCode===429||v$.includes(r.name)||r.$retryable?.throttling==!0,j1=(r,e=0)=>C$(r)||x$(r)||r.name==="InvalidSignatureException"&&r.message?.includes("Signature expired")||y$.includes(r.name)||b$.includes(r?.code||"")||w$.includes(r?.code||"")||A$.includes(r.$metadata?.httpStatusCode||0)||S$(r)||k$(r)||r.cause!==void 0&&e<=10&&j1(r.cause,e+1),E$=r=>{if(r.$metadata?.httpStatusCode!==void 0){const e=r.$metadata.httpStatusCode;return 500<=e&&e<=599&&!j1(r)}return!1};function k$(r){return r.code==="ERR_HTTP2_STREAM_ERROR"&&r.message.includes("NGHTTP2_REFUSED_STREAM")}const iP=20*1e3,$E=500,T$=1,F$="amz-sdk-invocation-id",I$="amz-sdk-request";function P$(r,e){if(sc.isInstance(r))for(const t of Object.keys(r.headers)){const n=t.toLowerCase();if(n==="retry-after"){const i=r.headers[t];let a=NaN;if(i.endsWith("GMT"))try{a=($I(i).getTime()-Date.now())/1e3}catch(s){e?.trace?.("Failed to parse retry-after header"),e?.trace?.(s)}else i.match(/ GMT, ((\d+)|(\d+\.\d+))$/)?a=Number(i.match(/ GMT, ([\d.]+)$/)?.[1]):i.match(/^((\d+)|(\d+\.\d+))$/)?a=Number(i):Date.parse(i)>=Date.now()&&(a=(Date.parse(i)-Date.now())/1e3);return isNaN(a)?void 0:new Date(Date.now()+a*1e3)}else if(n==="x-amz-retry-after"){const i=r.headers[t],a=Number(i);if(isNaN(a)){e?.trace?.(`Failed to parse x-amz-retry-after=${i}`);return}return new Date(Date.now()+a)}}}const D$=r=>r instanceof Error?r:r instanceof Object?Object.assign(new Error,r):typeof r=="string"?new Error(r):new Error(`AWS SDK error wrapper for ${r}`);function R$(r){return e=>(t,n)=>async i=>{let a=await e.retryStrategy();const s=await e.maxAttempts();if(B$(a)){a=a;let o=await a.acquireInitialRetryToken((n.partition_id??"")+(n.__retryLongPoll?":longpoll":"")),l=new Error,u=0,c=0;const{request:f}=i,d=na.isInstance(f);for(d&&(f.headers[F$]=tP());;)try{d&&(f.headers[I$]=`attempt=${u+1}; max=${s}`);const{response:h,output:g}=await t(i);return a.recordSuccess(o),g.$metadata.attempts=u+1,g.$metadata.totalRetryDelay=c,{response:h,output:g}}catch(h){const g=M$(h,e.logger);if(l=D$(h),d&&r(f))throw(n.logger instanceof UI?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),l;try{o=await a.refreshRetryTokenForRetry(o,g)}catch{throw l.$metadata||(l.$metadata={}),l.$metadata.attempts=u+1,l.$metadata.totalRetryDelay=c,l}u=o.getRetryCount();const v=o.getRetryDelay();c+=(o?.$retryLog?.acquisitionDelay??0)+v,v>0&&await O$(v)}}else return a=a,a?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",a.mode]]),a.retry(t,i)}}const O$=r=>new Promise(e=>setTimeout(e,r)),B$=r=>typeof r.acquireInitialRetryToken<"u"&&typeof r.refreshRetryTokenForRetry<"u"&&typeof r.recordSuccess<"u",M$=(r,e)=>{const t={error:r,errorType:_$(r)},n=P$(r.$response,e);return n&&(t.retryAfterHint=n),t},_$=r=>nP(r)?"THROTTLING":j1(r)?"TRANSIENT":E$(r)?"SERVER_ERROR":"CLIENT_ERROR",N$={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function L$(r){const e=R$(r);return t=>({applyToStack:n=>{n.add(e(t),N$)}})}class G1{static setTimeoutFn=(e,t)=>setTimeout(e,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(e){let t;this.updateMeasuredRate();const n=e;if(n?.errorType==="THROTTLING"||nP(n?.error??e)){const s=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=s,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(s),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const a=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(a)}getCurrentTimeInSeconds(){return Date.now()/1e3}async acquireTokenBucket(e){if(this.enabled){for(this.refillTokenBucket();e>this.availableTokens;){const t=(e-this.availableTokens)/this.fillRate*1e3;await new Promise(n=>G1.setTimeoutFn(n,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}const t=(e-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=e}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(e*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){const n=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(n*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}class Ei{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Ei.v2026?50:100}static throttlingDelay(){return Ei.v2026?1e3:500}static cost(){return Ei.v2026?14:5}static throttlingCost(){return Ei.v2026?5:10}static modifiedCostType(){return Ei.v2026?"THROTTLING":"TRANSIENT"}}class U${x=Ei.delay();computeNextBackoffDelay(e){const i=Math.random()*Math.min(this.x*2**e,iP);return Math.floor(i)}setDelayBase(e){this.x=e}}class HE{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(e,t,n,i){this.delay=e,this.count=t,this.cost=n,this.longPoll=i}getRetryCount(){return this.count}getRetryDelay(){return Math.min(iP,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Po;(function(r){r.STANDARD="standard",r.ADAPTIVE="adaptive"})(Po||(Po={}));const ef=3,V$=Po.STANDARD,kp={incompatible:1,attempts:2,capacity:3};class wA{mode=Po.STANDARD;retryBackoffStrategy;capacity=$E;maxAttemptsProvider;baseDelay;constructor(e){typeof e=="number"?this.maxAttemptsProvider=async()=>e:typeof e=="function"?this.maxAttemptsProvider=e:e&&typeof e=="object"&&(this.maxAttemptsProvider=async()=>e.maxAttempts,this.baseDelay=e.baseDelay,this.retryBackoffStrategy=e.backoff),this.maxAttemptsProvider??=async()=>ef,this.baseDelay??=Ei.delay(),this.retryBackoffStrategy??=new U$}async acquireInitialRetryToken(e){return new HE(Ei.delay(),0,void 0,Ei.v2026&&e.includes(":longpoll"))}async refreshRetryTokenForRetry(e,t){const n=await this.getMaxAttempts(),i=this.retryCode(e,t,n),a=i===0,s=e.isLongPoll?.();if(a||s){const o=t.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?Ei.throttlingDelay():this.baseDelay);const l=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount());let u=l;if(t.retryAfterHint instanceof Date&&(u=Math.max(l,Math.min(t.retryAfterHint.getTime()-Date.now(),l+5e3))),a){const c=this.getCapacityCost(o);this.capacity-=c;const f=new HE(0,e.getRetryCount()+1,c,e.isLongPoll?.()??!1);return await new Promise(d=>setTimeout(d,u)),f.$retryLog.acquisitionDelay=u,f}else{const c=Ei.v2026&&i===kp.capacity&&s?u:0;c>0&&await new Promise(f=>setTimeout(f,c))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min($E,this.capacity+(e.getRetryCost()??T$))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${ef}`),ef}}retryCode(e,t,n){const i=e.getRetryCount()+1,a=this.isRetryableError(t.errorType)?0:kp.incompatible,s=i<n?0:kp.attempts,o=this.capacity>=this.getCapacityCost(t.errorType)?0:kp.capacity;return a||s||o}getCapacityCost(e){return e===Ei.modifiedCostType()?Ei.throttlingCost():Ei.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class z${mode=Po.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,t){const{rateLimiter:n}=t??{};this.rateLimiter=n??new G1,this.standardRetryStrategy=t?new wA({maxAttempts:typeof e=="number"?e:3,...t}):new wA(e)}async acquireInitialRetryToken(e){const t=await this.standardRetryStrategy.acquireInitialRetryToken(e);return await this.rateLimiter.getSendToken(),t}async refreshRetryTokenForRetry(e,t){this.rateLimiter.updateClientSendingRate(t);const n=await this.standardRetryStrategy.refreshRetryTokenForRetry(e,t);return await this.rateLimiter.getSendToken(),n}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}const $$=(r,e)=>{const{retryStrategy:t,retryMode:n}=r,{defaultMaxAttempts:i=ef,defaultBaseDelay:a=Ei.delay()}={},s=Bs(r.maxAttempts??i);let o=t?Promise.resolve(t):void 0;const l=async()=>{const u=await s();return await Bs(n)()===Po.ADAPTIVE?new z$(s,{maxAttempts:u,baseDelay:a}):new wA({maxAttempts:u,baseDelay:a})};return Object.assign(r,{maxAttempts:s,retryStrategy:()=>o??=l()})},H$=L$(kV);Ei.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Is(r,e,t){r.__aws_sdk_context?r.__aws_sdk_context.features||(r.__aws_sdk_context.features={}):r.__aws_sdk_context={features:{}},r.__aws_sdk_context.features[e]=t}const j$=r=>e=>async t=>{if(!na.isInstance(t.request))return e(t);const{request:n}=t,{handlerProtocol:i=""}=r.requestHandler.metadata||{};if(i.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let a=n.hostname;n.port!=null&&(a+=`:${n.port}`),n.headers.host=a}return e(t)},G$={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},q$=r=>({applyToStack:e=>{e.add(j$(r),G$)}}),W$=()=>(r,e)=>async t=>{try{const n=await r(t),{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l,overrideOutputFilterSensitiveLog:u}=o,c=l??e.inputFilterSensitiveLog,f=u??e.outputFilterSensitiveLog,{$metadata:d,...h}=n.output;return s?.info?.({clientName:i,commandName:a,input:c(t.input),output:f(h),metadata:d}),n}catch(n){const{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l}=o,u=l??e.inputFilterSensitiveLog;throw s?.error?.({clientName:i,commandName:a,input:u(t.input),error:n,metadata:n.$metadata}),n}},Q$={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},Y$=r=>({applyToStack:e=>{e.add(W$(),Q$)}}),X$=r=>({applyToStack:e=>{}}),J$=(r,e)=>{if(!e||e.length===0)return r;const t=[];for(const n of e)for(const i of r)i.schemeId.split("#")[1]===n&&t.push(i);for(const n of r)t.find(({schemeId:i})=>i===n.schemeId)||t.push(n);return t};function K$(r){const e=new Map;for(const t of r)e.set(t.schemeId,t);return e}const Z$=(r,e)=>(t,n)=>async i=>{const a=r.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(r,n,i.input)),s=r.authSchemePreference?await r.authSchemePreference():[],o=J$(a,s),l=K$(r.httpAuthSchemes),u=vc(n),c=[];for(const f of o){const d=l.get(f.schemeId);if(!d){c.push(`HttpAuthScheme \`${f.schemeId}\` was not enabled for this service.`);continue}const h=d.identityProvider(await e.identityProviderConfigProvider(r));if(!h){c.push(`HttpAuthScheme \`${f.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:g={},signingProperties:v={}}=f.propertiesExtractor?.(r,n)||{};f.identityProperties=Object.assign(f.identityProperties||{},g),f.signingProperties=Object.assign(f.signingProperties||{},v),u.selectedHttpAuthScheme={httpAuthOption:f,identity:await h(f.identityProperties),signer:d.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(c.join(`
3043
+ `));return t(i)},eH={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},tH=(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t})=>({applyToStack:n=>{n.addRelativeTo(Z$(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t}),eH)}}),rH=r=>e=>{throw e},nH=(r,e)=>{},iH=r=>(e,t)=>async n=>{if(!na.isInstance(n.request))return e(n);const a=vc(t).selectedHttpAuthScheme;if(!a)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties:s={}},identity:o,signer:l}=a,u=await e({...n,request:await l.sign(n.request,o,s)}).catch((l.errorHandler||rH)(s));return(l.successHandler||nH)(u.response,s),u},aH={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},sH=r=>({applyToStack:e=>{e.addRelativeTo(iH(),aH)}}),tf=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};class oH{authSchemes=new Map;constructor(e){for(const t in e){const n=e[t];n!==void 0&&this.authSchemes.set(t,n)}}getIdentityProvider(e){return this.authSchemes.get(e)}}class lH{async sign(e,t,n){return e}}const uH=r=>function(t){return aP(t)&&t.expiration.getTime()-Date.now()<r},cH=3e5,dH=uH(cH),aP=r=>r.expiration!==void 0,fH=(r,e,t)=>{if(r===void 0)return;const n=typeof r!="function"?async()=>Promise.resolve(r):r;let i,a,s,o=!1;const l=async u=>{a||(a=n(u));try{i=await a,s=!0,o=!1}finally{a=void 0}return i};return e===void 0?async u=>((!s||u?.forceRefresh)&&(i=await l(u)),i):async u=>((!s||u?.forceRefresh)&&(i=await l(u)),o?i:t(i)?(e(i)&&await l(u),i):(o=!0,i))},hH=void 0;function pH(r){return r===void 0?!0:typeof r=="string"&&r.length<=50}function gH(r){const e=tf(r.userAgentAppId??hH),{customUserAgent:t}=r;return Object.assign(r,{customUserAgent:typeof t=="string"?[[t]]:t,userAgentAppId:async()=>{const n=await e();if(!pH(n)){const i=r.logger?.constructor?.name==="NoOpLogger"||!r.logger?console:r.logger;typeof n!="string"?i?.warn("userAgentAppId must be a string or undefined."):n.length>50&&i?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return n}})}const mH={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}]};let vH=mH;const yH=r=>{const{partitions:e}=vH;for(const n of e){const{regions:i,outputs:a}=n;for(const[s,o]of Object.entries(i))if(s===r)return{...a,...o}}for(const n of e){const{regionRegex:i,outputs:a}=n;if(new RegExp(i).test(r))return{...a}}const t=e.find(n=>n.id==="aws");if(!t)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...t.outputs}},AH=/\d{12}\.ddb/;async function bH(r,e,t){if(t.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&Is(r,"PROTOCOL_RPC_V2_CBOR","M"),typeof e.retryStrategy=="function"){const a=await e.retryStrategy();if(typeof a.mode=="string")switch(a.mode){case Po.ADAPTIVE:Is(r,"RETRY_MODE_ADAPTIVE","F");break;case Po.STANDARD:Is(r,"RETRY_MODE_STANDARD","E");break}}if(typeof e.accountIdEndpointMode=="function"){const a=r.endpointV2;switch(String(a?.url?.hostname).match(AH)&&Is(r,"ACCOUNT_ID_ENDPOINT","O"),await e.accountIdEndpointMode?.()){case"disabled":Is(r,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Is(r,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Is(r,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const i=r.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const a=i;a.accountId&&Is(r,"RESOLVED_ACCOUNT_ID","T");for(const[s,o]of Object.entries(a.$source??{}))Is(r,s,o)}}const jE="user-agent",jv="x-amz-user-agent",GE=" ",Gv="/",wH=/[^!$%&'*+\-.^_`|~\w]/g,CH=/[^!$%&'*+\-.^_`|~\w#]/g,qE="-",xH=1024;function SH(r){let e="";for(const t in r){const n=r[t];if(e.length+n.length+1<=xH){e.length?e+=","+n:e+=n;continue}break}return e}const EH=r=>(e,t)=>async n=>{const{request:i}=n;if(!na.isInstance(i))return e(n);const{headers:a}=i,s=t?.userAgent?.map(Tp)||[],o=(await r.defaultUserAgentProvider()).map(Tp);await bH(t,r,n);const l=t;o.push(`m/${SH(Object.assign({},t.__smithy_context?.features,l.__aws_sdk_context?.features))}`);const u=r?.customUserAgent?.map(Tp)||[],c=await r.userAgentAppId();c&&o.push(Tp(["app",`${c}`]));const f=[].concat([...o,...s,...u]).join(GE),d=[...o.filter(h=>h.startsWith("aws-sdk-")),...u].join(GE);return r.runtime!=="browser"?(d&&(a[jv]=a[jv]?`${a[jE]} ${d}`:d),a[jE]=f):a[jv]=f,e({...n,request:i})},Tp=r=>{const e=r[0].split(Gv).map(s=>s.replace(wH,qE)).join(Gv),t=r[1]?.replace(CH,qE),n=e.indexOf(Gv),i=e.substring(0,n);let a=e.substring(n+1);return i==="api"&&(a=a.toLowerCase()),[i,a,t].filter(s=>s&&s.length>0).reduce((s,o,l)=>{switch(l){case 0:return o;case 1:return`${s}/${o}`;default:return`${s}#${o}`}},"")},kH={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},TH=r=>({applyToStack:e=>{e.add(EH(r),kH)}}),FH=({serviceId:r,clientVersion:e})=>async t=>{const n=typeof window<"u"?window.navigator:void 0,i=n?.userAgent??"",a=n?.userAgentData?.platform??WE.os(i)??"other",s=void 0,o=n?.userAgentData?.brands??[],l=o[o.length-1],u=l?.brand??WE.browser(i)??"unknown",c=l?.version??"unknown",f=[["aws-sdk-js",e],["ua","2.1"],[`os/${a}`,s],["lang/js"],["md/browser",`${u}_${c}`]];r&&f.push([`api/${r}`,e]);const d=await t?.userAgentAppId?.();return d&&f.push([`app/${d}`]),f},WE={os(r){if(/iPhone|iPad|iPod/.test(r))return"iOS";if(/Macintosh|Mac OS X/.test(r))return"macOS";if(/Windows NT/.test(r))return"Windows";if(/Android/.test(r))return"Android";if(/Linux/.test(r))return"Linux"},browser(r){if(/EdgiOS|EdgA|Edg\//.test(r))return"Microsoft Edge";if(/Firefox\//.test(r))return"Firefox";if(/Chrome\//.test(r))return"Chrome";if(/Safari\//.test(r))return"Safari"}},sP=(r,e=!1)=>{if(e){for(const t of r.split("."))if(!sP(t))return!1;return!0}return!(!Kg(r)||r.length<3||r.length>63||r!==r.toLowerCase()||WI(r))},QE=":",IH="/",PH=r=>{const e=r.split(QE);if(e.length<6)return null;const[t,n,i,a,s,...o]=e;if(t!=="arn"||n===""||i===""||o.join(QE)==="")return null;const l=o.map(u=>u.split(IH)).flat();return{partition:n,service:i,region:a,accountId:s,resourceId:l}},oP={isVirtualHostableS3Bucket:sP,parseArn:PH,partition:yH};H1.aws=oP;const DH=(r,e,t)=>{let n,i,a,s=!1;const o=async()=>{i||(i=r());try{n=await i,a=!0,s=!1}finally{i=void 0}return n};return async l=>((!a||l?.forceRefresh)&&(n=await o()),n)},YE=new Set,RH=(r,e=Kg)=>{if(!YE.has(r)&&!e(r))if(r==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${r}" is not a valid hostname component.`);else YE.add(r)},lP=r=>typeof r=="string"&&(r.startsWith("fips-")||r.endsWith("-fips")),OH=r=>lP(r)?["fips-aws-global","aws-fips"].includes(r)?"us-east-1":r.replace(/fips-(dkr-|prod-)?|-fips/,""):r,BH=r=>{const{region:e,useFipsEndpoint:t}=r;if(!e)throw new Error("Region is missing");return Object.assign(r,{region:async()=>{const n=typeof e=="function"?await e():e,i=OH(n);return RH(i),i},useFipsEndpoint:async()=>{const n=typeof e=="string"?e:await e();return lP(n)?!0:typeof t!="function"?Promise.resolve(!!t):t()}})},MH=["in-region","cross-region","mobile","standard","legacy"],_H=({defaultsMode:r}={})=>DH(async()=>{const e=typeof r=="function"?await r():r;switch(e?.toLowerCase()){case"auto":return Promise.resolve(NH()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(e?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${MH.join(", ")}, got ${e}`)}}),NH=()=>{const r=window?.navigator;if(r?.connection){const{effectiveType:e,rtt:t,downlink:n}=r?.connection;if(typeof e=="string"&&e!=="4g"||Number(t)>100||Number(n)<10)return!0}return r?.userAgentData?.mobile||typeof r?.maxTouchPoints=="number"&&r?.maxTouchPoints>1},LH=!1,UH=!1,VH=r=>({setRegion(e){r.region=e},region(){return r.region}}),zH=r=>({region:r.region()}),XE=r=>sc.isInstance(r)?r.headers?.date??r.headers?.Date:void 0,uP=r=>new Date(Date.now()+r),$H=(r,e)=>Math.abs(uP(e).getTime()-r)>=3e5,JE=(r,e)=>{const t=Date.parse(r);return $H(t,e)?t-Date.now():e},rf=(r,e)=>{if(!e)throw new Error(`Property \`${r}\` is not resolved for AWS SDK SigV4Auth`);return e},HH=async r=>{const e=rf("context",r.context),t=rf("config",r.config),n=e.endpointV2?.properties?.authSchemes?.[0],a=await rf("signer",t.signer)(n),s=r?.signingRegion,o=r?.signingRegionSet,l=r?.signingName;return{config:t,signer:a,signingRegion:s,signingRegionSet:o,signingName:l}};class jH{async sign(e,t,n){if(!na.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const i=await HH(n),{config:a,signer:s}=i;let{signingRegion:o,signingName:l}=i;const u=n.context;if(u?.authSchemes?.length??!1){const[f,d]=u.authSchemes;f?.name==="sigv4a"&&d?.name==="sigv4"&&(o=d?.signingRegion??o,l=d?.signingName??l)}return n._preRequestSystemClockOffset=a.systemClockOffset,await s.sign(e,{signingDate:uP(a.systemClockOffset),signingRegion:o,signingService:l})}errorHandler(e){return t=>{const n=t,i=n.ServerTime??XE(n.$response);if(i){const a=rf("config",e.config),s=e._preRequestSystemClockOffset,o=JE(i,a.systemClockOffset);(o!==a.systemClockOffset||s!==void 0&&s!==o)&&n.$metadata&&(a.systemClockOffset=o,n.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const n=XE(e);if(n){const i=rf("config",t.config);i.systemClockOffset=JE(n,i.systemClockOffset)}}}class GH{format(e){const t=[];for(const a of Object.keys(e)){const s=kl(a);t.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[a]))}const n=new Uint8Array(t.reduce((a,s)=>a+s.byteLength,0));let i=0;for(const a of t)n.set(a,i),i+=a.byteLength;return n}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const n=new DataView(new ArrayBuffer(5));return n.setUint8(0,4),n.setInt32(1,e.value,!1),new Uint8Array(n.buffer);case"long":const i=new Uint8Array(9);return i[0]=5,i.set(e.value.bytes,1),i;case"binary":const a=new DataView(new ArrayBuffer(3+e.value.byteLength));a.setUint8(0,6),a.setUint16(1,e.value.byteLength,!1);const s=new Uint8Array(a.buffer);return s.set(e.value,3),s;case"string":const o=kl(e.value),l=new DataView(new ArrayBuffer(3+o.byteLength));l.setUint8(0,7),l.setUint16(1,o.byteLength,!1);const u=new Uint8Array(l.buffer);return u.set(o,3),u;case"timestamp":const c=new Uint8Array(9);return c[0]=8,c.set(q1.fromNumber(e.value.valueOf()).bytes,1),c;case"uuid":if(!qH.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const f=new Uint8Array(17);return f[0]=9,f.set(jI(e.value.replace(/\-/g,"")),1),f}}}var KE;(function(r){r[r.boolTrue=0]="boolTrue",r[r.boolFalse=1]="boolFalse",r[r.byte=2]="byte",r[r.short=3]="short",r[r.integer=4]="integer",r[r.long=5]="long",r[r.byteArray=6]="byteArray",r[r.string=7]="string",r[r.timestamp=8]="timestamp",r[r.uuid=9]="uuid"})(KE||(KE={}));const qH=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class q1{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let n=7,i=Math.abs(Math.round(e));n>-1&&i>0;n--,i/=256)t[n]=i;return e<0&&ZE(t),new q1(t)}valueOf(){const e=this.bytes.slice(0),t=e[0]&128;return t&&ZE(e),parseInt(Ao(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function ZE(r){for(let e=0;e<8;e++)r[e]^=255;for(let e=7;e>-1&&(r[e]++,r[e]===0);e--);}const WH="X-Amz-Algorithm",QH="X-Amz-Credential",cP="X-Amz-Date",YH="X-Amz-SignedHeaders",XH="X-Amz-Expires",dP="X-Amz-Signature",fP="X-Amz-Security-Token",hP="authorization",pP=cP.toLowerCase(),JH="date",KH=[hP,pP,JH],ZH=dP.toLowerCase(),CA="x-amz-content-sha256",ej=fP.toLowerCase(),tj={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},rj=/^proxy-/,nj=/^sec-/,qv="AWS4-HMAC-SHA256",ij="AWS4-HMAC-SHA256-PAYLOAD",aj="UNSIGNED-PAYLOAD",sj=50,gP="aws4_request",oj=3600*24*7,lj=({query:r={}})=>{const e=[],t={};for(const n of Object.keys(r)){if(n.toLowerCase()===ZH)continue;const i=Cl(n);e.push(i);const a=r[n];typeof a=="string"?t[i]=`${i}=${Cl(a)}`:Array.isArray(a)&&(t[i]=a.slice(0).reduce((s,o)=>s.concat([`${i}=${Cl(o)}`]),[]).sort().join("&"))}return e.sort().map(n=>t[n]).filter(n=>n).join("&")},uj=r=>cj(r).toISOString().replace(/\.\d{3}Z$/,"Z"),cj=r=>typeof r=="number"?new Date(r*1e3):typeof r=="string"?Number(r)?new Date(Number(r)*1e3):new Date(r):r;class dj{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s=!0}){this.service=i,this.sha256=a,this.uriEscapePath=s,this.applyChecksum=typeof e=="boolean"?e:!0,this.regionProvider=Bs(n),this.credentialProvider=Bs(t)}createCanonicalRequest(e,t,n){const i=Object.keys(t).sort();return`${e.method}
3044
3044
  ${this.getCanonicalPath(e)}
3045
- ${sj(e)}
3045
+ ${lj(e)}
3046
3046
  ${i.map(a=>`${a}:${t[a]}`).join(`
3047
3047
  `)}
3048
3048
 
@@ -3050,10 +3050,10 @@ ${i.join(";")}
3050
3050
  ${n}`}async createStringToSign(e,t,n,i){const a=new this.sha256;a.update(kf(n));const s=await a.digest();return`${i}
3051
3051
  ${e}
3052
3052
  ${t}
3053
- ${Ao(s)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){const t=[];for(const a of e.split("/"))a?.length!==0&&a!=="."&&(a===".."?t.pop():t.push(a));const n=`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`;return Cl(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){const t=oj(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}const Fp={},Wv=[],Qv=(r,e,t)=>`${r}/${e}/${t}/${gP}`,cj=async(r,e,t,n,i)=>{const a=await e2(r,e.secretAccessKey,e.accessKeyId),s=`${t}:${n}:${i}:${Ao(a)}:${e.sessionToken}`;if(s in Fp)return Fp[s];for(Wv.push(s);Wv.length>ij;)delete Fp[Wv.shift()];let o=`AWS4${e.secretAccessKey}`;for(const l of[t,n,i,gP])o=await e2(r,o,l);return Fp[s]=o},e2=(r,e,t)=>{const n=new r(e);return n.update(kf(t)),n.digest()},t2=({headers:r},e,t)=>{const n={};for(const i of Object.keys(r).sort()){if(r[i]==null)continue;const a=i.toLowerCase();(a in ZH||e?.has(a)||ej.test(a)||tj.test(a))&&(!t||t&&!t.has(a))||(n[a]=r[i].trim().replace(/\s+/g," "))}return n},Yv=async({headers:r,body:e},t)=>{for(const n of Object.keys(r))if(n.toLowerCase()===CA)return r[n];if(e==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof e=="string"||ArrayBuffer.isView(e)||bz(e)){const n=new t;return n.update(kf(e)),Ao(await n.digest())}return nj},dj=(r,e)=>{r=r.toLowerCase();for(const t of Object.keys(e))if(r===t.toLowerCase())return!0;return!1},fj=(r,e={})=>{const{headers:t,query:n={}}=na.clone(r);for(const i of Object.keys(t)){const a=i.toLowerCase();(a.slice(0,6)==="x-amz-"&&!e.unhoistableHeaders?.has(a)||e.hoistableHeaders?.has(a))&&(n[i]=t[i],delete t[i])}return{...r,headers:t,query:n}},r2=r=>{r=na.clone(r);for(const e of Object.keys(r.headers))XH.indexOf(e.toLowerCase())>-1&&delete r.headers[e];return r};class n2 extends uj{headerFormatter=new HH;constructor({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s})}async presign(e,t={}){const{signingDate:n=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:o,hoistableHeaders:l,signingRegion:u,signingService:c}=t,f=await this.credentialProvider();this.validateResolvedCredentials(f);const d=u??await this.regionProvider(),{longDate:h,shortDate:g}=this.formatDate(n);if(i>aj)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const v=Qv(g,d,c??this.service),y=fj(r2(e),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(y.query[fP]=f.sessionToken),y.query[GH]=qv,y.query[qH]=`${f.accessKeyId}/${v}`,y.query[cP]=h,y.query[QH]=i.toString(10);const A=t2(y,a,o);return y.query[WH]=this.getCanonicalHeaderList(A),y.query[dP]=await this.getSignature(h,v,this.getSigningKey(f,d,g,c),this.createCanonicalRequest(y,A,await Yv(e,this.sha256))),y}async sign(e,t){return typeof e=="string"?this.signString(e,t):e.headers&&e.payload?this.signEvent(e,t):e.message?this.signMessage(e,t):this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:n=new Date,priorSignature:i,signingRegion:a,signingService:s,eventStreamCredentials:o}){const l=a??await this.regionProvider(),{shortDate:u,longDate:c}=this.formatDate(n),f=Qv(u,l,s??this.service),d=await Yv({headers:{},body:t},this.sha256),h=new this.sha256;h.update(e);const g=Ao(await h.digest()),v=[rj,c,f,i,g,d].join(`
3054
- `);return this.signString(v,{signingDate:n,signingRegion:l,signingService:s,eventStreamCredentials:o})}async signMessage(e,{signingDate:t=new Date,signingRegion:n,signingService:i,eventStreamCredentials:a}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:n,signingService:i,priorSignature:e.priorSignature,eventStreamCredentials:a}).then(o=>({message:e.message,signature:o}))}async signString(e,{signingDate:t=new Date,signingRegion:n,signingService:i,eventStreamCredentials:a}={}){const s=a??await this.credentialProvider();this.validateResolvedCredentials(s);const o=n??await this.regionProvider(),{shortDate:l}=this.formatDate(t),u=new this.sha256(await this.getSigningKey(s,o,l,i));return u.update(kf(e)),Ao(await u.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:n,unsignableHeaders:i,signingRegion:a,signingService:s}={}){const o=await this.credentialProvider();this.validateResolvedCredentials(o);const l=a??await this.regionProvider(),u=r2(e),{longDate:c,shortDate:f}=this.formatDate(t),d=Qv(f,l,s??this.service);u.headers[pP]=c,o.sessionToken&&(u.headers[KH]=o.sessionToken);const h=await Yv(u,this.sha256);!dj(CA,u.headers)&&this.applyChecksum&&(u.headers[CA]=h);const g=t2(u,i,n),v=await this.getSignature(c,d,this.getSigningKey(o,l,f,s),this.createCanonicalRequest(u,g,h));return u.headers[hP]=`${qv} Credential=${o.accessKeyId}/${d}, SignedHeaders=${this.getCanonicalHeaderList(g)}, Signature=${v}`,u}async getSignature(e,t,n,i){const a=await this.createStringToSign(e,t,i,qv),s=new this.sha256(await n);return s.update(kf(a)),Ao(await s.digest())}getSigningKey(e,t,n,i){return cj(this.sha256,e,n,t,i||this.service)}}const hj=r=>{let e=r.credentials,t=!!r.credentials,n;Object.defineProperty(r,"credentials",{set(u){u&&u!==e&&u!==n&&(t=!0),e=u;const c=pj(r,{credentials:e,credentialDefaultProvider:r.credentialDefaultProvider}),f=gj(r,c);if(t&&!f.attributed){const d=typeof e=="object"&&e!==null;n=async h=>{const v=await f(h);return d&&(!v.$source||Object.keys(v.$source).length===0)?xV(v,"CREDENTIALS_CODE","e"):v},n.memoized=f.memoized,n.configBound=f.configBound,n.attributed=!0}else n=f},get(){return n},enumerable:!0,configurable:!0}),r.credentials=e;const{signingEscapePath:i=!0,systemClockOffset:a=r.systemClockOffset||0,sha256:s}=r;let o;return r.signer?o=tf(r.signer):r.regionInfoProvider?o=()=>tf(r.region)().then(async u=>[await r.regionInfoProvider(u,{useFipsEndpoint:await r.useFipsEndpoint(),useDualstackEndpoint:await r.useDualstackEndpoint()})||{},u]).then(([u,c])=>{const{signingRegion:f,signingService:d}=u;r.signingRegion=r.signingRegion||f||c,r.signingName=r.signingName||d||r.serviceId;const h={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:s,uriEscapePath:i},g=r.signerConstructor||n2;return new g(h)}):o=async u=>{u=Object.assign({},{name:"sigv4",signingName:r.signingName||r.defaultSigningName,signingRegion:await tf(r.region)(),properties:{}},u);const c=u.signingRegion,f=u.signingName;r.signingRegion=r.signingRegion||c,r.signingName=r.signingName||f||r.serviceId;const d={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:s,uriEscapePath:i},h=r.signerConstructor||n2;return new h(d)},Object.assign(r,{systemClockOffset:a,signingEscapePath:i,signer:o})};function pj(r,{credentials:e,credentialDefaultProvider:t}){let n;return e?e?.memoized?n=e:n=cH(e,uH,aP):t?n=tf(t(Object.assign({},r,{parentClientConfig:r}))):n=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},n.memoized=!0,n}function gj(r,e){if(e.configBound)return e;const t=async n=>e({...n,callerClientConfig:r});return t.memoized=e.memoized,t.configBound=!0,t}const mj=async(r,e,t)=>({operation:vc(e).operation,region:await Bs(r.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function vj(r){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-idp",region:r.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function Ur(r){return{schemeId:"smithy.api#noAuth"}}const yj=r=>{const e=[];switch(r.operation){case"AssociateSoftwareToken":{e.push(Ur());break}case"ChangePassword":{e.push(Ur());break}case"CompleteWebAuthnRegistration":{e.push(Ur());break}case"ConfirmDevice":{e.push(Ur());break}case"ConfirmForgotPassword":{e.push(Ur());break}case"ConfirmSignUp":{e.push(Ur());break}case"DeleteUser":{e.push(Ur());break}case"DeleteUserAttributes":{e.push(Ur());break}case"DeleteWebAuthnCredential":{e.push(Ur());break}case"ForgetDevice":{e.push(Ur());break}case"ForgotPassword":{e.push(Ur());break}case"GetDevice":{e.push(Ur());break}case"GetTokensFromRefreshToken":{e.push(Ur());break}case"GetUser":{e.push(Ur());break}case"GetUserAttributeVerificationCode":{e.push(Ur());break}case"GetUserAuthFactors":{e.push(Ur());break}case"GlobalSignOut":{e.push(Ur());break}case"InitiateAuth":{e.push(Ur());break}case"ListDevices":{e.push(Ur());break}case"ListWebAuthnCredentials":{e.push(Ur());break}case"ResendConfirmationCode":{e.push(Ur());break}case"RespondToAuthChallenge":{e.push(Ur());break}case"RevokeToken":{e.push(Ur());break}case"SetUserMFAPreference":{e.push(Ur());break}case"SetUserSettings":{e.push(Ur());break}case"SignUp":{e.push(Ur());break}case"StartWebAuthnRegistration":{e.push(Ur());break}case"UpdateAuthEventFeedback":{e.push(Ur());break}case"UpdateDeviceStatus":{e.push(Ur());break}case"UpdateUserAttributes":{e.push(Ur());break}case"VerifySoftwareToken":{e.push(Ur());break}case"VerifyUserAttribute":{e.push(Ur());break}default:e.push(vj(r))}return e},Aj=r=>{const e=hj(r);return Object.assign(e,{authSchemePreference:Bs(r.authSchemePreference??[])})},bj=r=>Object.assign(r,{useDualstackEndpoint:r.useDualstackEndpoint??!1,useFipsEndpoint:r.useFipsEndpoint??!1,defaultSigningName:"cognito-idp"}),mP={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},wj="3.1075.0",Cj={version:wj},xj=r=>new TextEncoder().encode(r);var Sj=typeof Buffer<"u"&&Buffer.from?function(r){return Buffer.from(r,"utf8")}:xj;function Tf(r){return r instanceof Uint8Array?r:typeof r=="string"?Sj(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r)}function xA(r){return typeof r=="string"?r.length===0:r.byteLength===0}var vP={name:"SHA-256"},i2={name:"HMAC",hash:vP},Ej=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);const kj={};function Kp(){return typeof window<"u"?window:typeof self<"u"?self:kj}var Tj=(function(){function r(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return r.prototype.update=function(e){if(!xA(e)){var t=Tf(e),n=new Uint8Array(this.toHash.byteLength+t.byteLength);n.set(this.toHash,0),n.set(t,this.toHash.byteLength),this.toHash=n}},r.prototype.digest=function(){var e=this;return this.key?this.key.then(function(t){return Kp().crypto.subtle.sign(i2,t,e.toHash).then(function(n){return new Uint8Array(n)})}):xA(this.toHash)?Promise.resolve(Ej):Promise.resolve().then(function(){return Kp().crypto.subtle.digest(vP,e.toHash)}).then(function(t){return Promise.resolve(new Uint8Array(t))})},r.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&this.secret!==void 0&&(this.key=new Promise(function(t,n){Kp().crypto.subtle.importKey("raw",Tf(e.secret),i2,!1,["sign"]).then(t,n)}),this.key.catch(function(){}))},r})(),ha=64,Fj=32,Ij=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pj=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],Dj=Math.pow(2,53)-1,Zp=(function(){function r(){this.state=Int32Array.from(Pj),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return r.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,this.bytesHashed*8>Dj)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===ha&&(this.hashBuffer(),this.bufferLength=0)},r.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%ha>=ha-8){for(var i=this.bufferLength;i<ha;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0}for(var i=this.bufferLength;i<ha-8;i++)t.setUint8(i,0);t.setUint32(ha-8,Math.floor(e/4294967296),!0),t.setUint32(ha-4,e),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(Fj),i=0;i<8;i++)a[i*4]=this.state[i]>>>24&255,a[i*4+1]=this.state[i]>>>16&255,a[i*4+2]=this.state[i]>>>8&255,a[i*4+3]=this.state[i]>>>0&255;return a},r.prototype.hashBuffer=function(){for(var e=this,t=e.buffer,n=e.state,i=n[0],a=n[1],s=n[2],o=n[3],l=n[4],u=n[5],c=n[6],f=n[7],d=0;d<ha;d++){if(d<16)this.temp[d]=(t[d*4]&255)<<24|(t[d*4+1]&255)<<16|(t[d*4+2]&255)<<8|t[d*4+3]&255;else{var h=this.temp[d-2],g=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10;h=this.temp[d-15];var v=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[d]=(g+this.temp[d-7]|0)+(v+this.temp[d-16]|0)}var y=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&u^~l&c)|0)+(f+(Ij[d]+this.temp[d]|0)|0)|0,A=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&a^i&s^a&s)|0;f=c,c=u,u=l,l=o+y|0,o=s,s=a,a=i,i=y+A|0}n[0]+=i,n[1]+=a,n[2]+=s,n[3]+=o,n[4]+=l,n[5]+=u,n[6]+=c,n[7]+=f},r})(),Rj=(function(){function r(e){this.secret=e,this.hash=new Zp,this.reset()}return r.prototype.update=function(e){if(!(xA(e)||this.error))try{this.hash.update(Tf(e))}catch(t){this.error=t}},r.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},r.prototype.digest=function(){return es(this,void 0,void 0,function(){return ts(this,function(e){return[2,this.digestSync()]})})},r.prototype.reset=function(){if(this.hash=new Zp,this.secret){this.outer=new Zp;var e=Oj(this.secret),t=new Uint8Array(ha);t.set(e);for(var n=0;n<ha;n++)e[n]^=54,t[n]^=92;this.hash.update(e),this.outer.update(t);for(var n=0;n<e.byteLength;n++)e[n]=0}},r})();function Oj(r){var e=Tf(r);if(e.byteLength>ha){var t=new Zp;t.update(e),e=t.digest()}var n=new Uint8Array(ha);return n.set(e),n}var Bj=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Mj(r){if(_j(r)&&typeof r.crypto.subtle=="object"){var e=r.crypto.subtle;return Nj(e)}return!1}function _j(r){if(typeof r=="object"&&typeof r.crypto=="object"){var e=r.crypto.getRandomValues;return typeof e=="function"}return!1}function Nj(r){return r&&Bj.every(function(e){return typeof r[e]=="function"})}var Lj=(function(){function r(e){Mj(Kp())?this.hash=new Tj(e):this.hash=new Rj(e)}return r.prototype.update=function(e,t){this.hash.update(Tf(e))},r.prototype.digest=function(){return this.hash.digest()},r.prototype.reset=function(){this.hash.reset()},r})();function a2(r,e){return new Request(r,e)}function Uj(r=0){return new Promise((e,t)=>{r&&setTimeout(()=>{const n=new Error(`Request did not complete within ${r} ms`);n.name="TimeoutError",t(n)},r)})}const Xv={supported:void 0};class W1{config;configProvider;static create(e){return typeof e?.handle=="function"?e:new W1(e)}constructor(e){typeof e=="function"?this.configProvider=e().then(t=>t||{}):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),Xv.supported===void 0&&(Xv.supported=typeof Request<"u"&&"keepalive"in a2("https://[::1]"))}destroy(){}async handle(e,{abortSignal:t,requestTimeout:n}={}){this.config||(this.config=await this.configProvider);const i=n??this.config.requestTimeout,a=this.config.keepAlive===!0,s=this.config.credentials;if(t?.aborted){const C=s2(t);return Promise.reject(C)}let o=e.path;const l=p$(e.query||{});l&&(o+=`?${l}`),e.fragment&&(o+=`#${e.fragment}`);let u="";if(e.username!=null||e.password!=null){const C=e.username??"",S=e.password??"";u=`${C}:${S}@`}const{port:c,method:f}=e,d=`${e.protocol}//${u}${e.hostname}${c?`:${c}`:""}${o}`,h=f==="GET"||f==="HEAD"?void 0:e.body,g={body:h,headers:new Headers(e.headers),method:f,credentials:s};this.config?.cache&&(g.cache=this.config.cache),h&&(g.duplex="half"),typeof AbortController<"u"&&(g.signal=t),Xv.supported&&(g.keepalive=a),typeof this.config.requestInit=="function"&&Object.assign(g,this.config.requestInit(e));let v=()=>{};const y=a2(d,g),A=[fetch(y).then(C=>{const S=C.headers,F={};for(const R of S.entries())F[R[0]]=R[1];return C.body!=null?{response:new sc({headers:F,reason:C.statusText,statusCode:C.status,body:C.body})}:C.blob().then(R=>({response:new sc({headers:F,reason:C.statusText,statusCode:C.status,body:R})}))}),Uj(i)];return t&&A.push(new Promise((C,S)=>{const F=()=>{const E=s2(t);S(E)};if(typeof t.addEventListener=="function"){const E=t;E.addEventListener("abort",F,{once:!0}),v=()=>E.removeEventListener("abort",F)}else t.onabort=F})),Promise.race(A).finally(v)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then(n=>(n[e]=t,n))}httpHandlerConfigs(){return this.config??{}}}function s2(r){const e=r&&typeof r=="object"&&"reason"in r?r.reason:void 0;if(e){if(e instanceof Error){const i=new Error("Request aborted");return i.name="AbortError",i.cause=e,i}const n=new Error(String(e));return n.name="AbortError",n}const t=new Error("Request aborted");return t.name="AbortError",t}const Vj=async r=>typeof Blob=="function"&&r instanceof Blob||r.constructor?.name==="Blob"?Blob.prototype.arrayBuffer!==void 0?new Uint8Array(await r.arrayBuffer()):zj(r):$j(r);async function zj(r){const e=await Hj(r),t=Zg(e);return new Uint8Array(t)}async function $j(r){const e=[],t=r.getReader();let n=!1,i=0;for(;!n;){const{done:o,value:l}=await t.read();l&&(e.push(l),i+=l.length),n=o}const a=new Uint8Array(i);let s=0;for(const o of e)a.set(o,s),s+=o.length;return a}function Hj(r){return new Promise((e,t)=>{const n=new FileReader;n.onloadend=()=>{if(n.readyState!==2)return t(new Error("Reader aborted too early"));const i=n.result??"",a=i.indexOf(","),s=a>-1?a+1:i.length;e(i.substring(s))},n.onabort=()=>t(new Error("Read aborted")),n.onerror=()=>t(n.error),n.readAsDataURL(r)})}class jj{queryCompat;errorRegistry;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,t){const n=t.getMemberSchemas(),i=Object.values(n).find(a=>!!a.getMergedTraits().httpPayload);if(i){const a=i.getMergedTraits().mediaType;return a||(i.isStringSchema()?"text/plain":i.isBlobSchema()?"application/octet-stream":e)}else if(!t.isUnitSchema()&&Object.values(n).find(s=>{const{httpQuery:o,httpQueryParams:l,httpHeader:u,httpLabel:c,httpPrefixHeaders:f}=s.getMergedTraits();return!o&&!l&&!u&&!c&&f===void 0}))return e}async getErrorSchemaOrThrowBaseException(e,t,n,i,a,s){let o=e;e.includes("#")&&([,o]=e.split("#"));const l={$metadata:a,$fault:n.statusCode<500?"client":"server"};if(!this.errorRegistry)throw new Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:s?.(this.errorRegistry,o)??this.errorRegistry.getSchema(e),errorMetadata:l}}catch{i.message=i.message??i.Message??"UnknownError";const c=this.errorRegistry,f=c.getBaseException();if(f){const g=c.getErrorCtor(f)??Error;throw this.decorateServiceException(Object.assign(new g({name:o}),l),i)}const d=i,h=d?.message??d?.Message??d?.Error?.Message??d?.Error?.message;throw this.decorateServiceException(Object.assign(new Error(h),{name:o},l),i)}}compose(e,t,n){let i=n;t.includes("#")&&([i]=t.split("#"));const a=Zi.for(i),s=Zi.for("smithy.ts.sdk.synthetic."+n);e.copyFrom(a),e.copyFrom(s),this.errorRegistry=e}decorateServiceException(e,t={}){if(this.queryCompat){const n=e.Message??t.Message,i=BE(e,t);n&&(i.message=n);const a=i.Error??{};a.Type=i.Error?.Type,a.Code=i.Error?.Code,a.Message=i.Error?.message??i.Error?.Message??n,i.Error=a;const s=i.$metadata.requestId;return s&&(i.RequestId=s),i}return BE(e,t)}setQueryCompatError(e,t){const n=t.headers?.["x-amzn-query-error"];if(e!==void 0&&n!=null){const[i,a]=n.split(";"),s=Object.keys(e),o={Code:i,Type:a};e.Code=i,e.Type=a;for(let l=0;l<s.length;l++){const u=s[l];o[u==="message"?"Message":u]=e[u]}delete o.__type,e.Error=o}}queryCompatOutput(e,t){e.Error&&(t.Error=e.Error),e.Type&&(t.Type=e.Type),e.Code&&(t.Code=e.Code)}findQueryCompatibleError(e,t){try{return e.getSchema(t)}catch{return e.find(i=>vi.of(i).getMergedTraits().awsQueryError?.[0]===t)}}}class Q1{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Gj{from;to;keys;constructor(e,t){this.from=e,this.to=t;const n=Object.keys(this.from),i=new Set(n);i.delete("__type"),this.keys=i}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){const e=this.keys.values().next().value,t=this.from[e];this.to.$unknown=[e,t]}}}function qj(r,e,t){if(t?.source){const n=t.source;if(typeof e=="number"&&(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER||n!==String(e)))return n.includes(".")?new ns(n,"bigDecimal"):BigInt(n)}return e}const Wj=(r,e)=>bA(r,e).then(t=>(e?.utf8Encoder??em)(t)),Qj=(r,e)=>Wj(r,e).then(t=>{if(t.length)try{return JSON.parse(t)}catch(n){throw n?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:t}),n}return{}}),o2=(r,e)=>Object.keys(r).find(t=>t.toLowerCase()===e.toLowerCase()),Jv=r=>{let e=r;return typeof e=="number"&&(e=e.toString()),e.indexOf(",")>=0&&(e=e.split(",")[0]),e.indexOf(":")>=0&&(e=e.split(":")[0]),e.indexOf("#")>=0&&(e=e.split("#")[1]),e},Yj=(r,e,t=!1)=>Xj(r,e,t?["code","header","type"]:["type","code","header"]),Xj=({headers:r},e,t)=>{for(;t.length>0;)switch(t.shift()){case"header":const i=o2(r??{},"x-amzn-errortype");if(i!==void 0)return Jv(r[i]);break;case"code":const a=o2(e??{},"code");if(a&&e[a]!==void 0)return Jv(e[a]);break;case"type":if(e?.__type!==void 0)return Jv(e.__type);break}};class Jj extends Q1{settings;constructor(e){super(),this.settings=e}async read(e,t){return this._read(e,typeof t=="string"?JSON.parse(t,qj):await Qj(t,this.serdeContext))}readObject(e,t){return this._read(e,t)}_read(e,t){const n=t!==null&&typeof t=="object",i=vi.of(e);if(n){if(i.isStructSchema()){const s=t,o=i.isUnionSchema(),l={};let u;const{jsonName:c}=this.settings;c&&(u={});let f;o&&(f=new Gj(s,l));for(const[d,h]of i.structIterator()){let g=d;c&&(g=h.getMergedTraits().jsonName??g,u[g]=d),o&&f.mark(g),s[g]!=null&&(l[d]=this._read(h,s[g]))}if(o)f.writeUnknown();else if(typeof s.__type=="string")for(const d in s){const h=s[d],g=c?u[d]??d:d;g in l||(l[g]=h)}return l}if(Array.isArray(t)&&i.isListSchema()){const s=i.getValueSchema(),o=[];for(const l of t)o.push(this._read(s,l));return o}if(i.isMapSchema()){const s=i.getValueSchema(),o={};for(const l in t)o[l]=this._read(s,t[l]);return o}}if(i.isBlobSchema()&&typeof t=="string")return Zg(t);const a=i.getMergedTraits().mediaType;if(i.isStringSchema()&&typeof t=="string"&&a)return a==="application/json"||a.endsWith("+json")?po.from(t):t;if(i.isTimestampSchema()&&t!=null)switch(rP(i,this.settings)){case 5:return sz(t);case 6:return $I(t);case 7:return cz(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(i.isBigIntegerSchema()&&(typeof t=="number"||typeof t=="string"))return BigInt(t);if(i.isBigDecimalSchema()&&t!=null){if(t instanceof ns)return t;const s=t;return s.type==="bigDecimal"&&"string"in s?new ns(s.string,s.type):new ns(String(t),"bigDecimal")}if(i.isNumericSchema()&&typeof t=="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(i.isDocumentSchema())if(n){const s=Array.isArray(t)?[]:{};for(const o in t){const l=t[o];l instanceof ns?s[o]=l:s[o]=this._read(i,l)}return s}else return structuredClone(t);return t}}const l2="Ν";class Kj{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,t)=>{if(t instanceof ns){const n=`${l2+"nv"+this.counter++}_`+t.string;return this.values.set(`"${n}"`,t.string),n}if(typeof t=="bigint"){const n=t.toString(),i=`${l2+"b"+this.counter++}_`+n;return this.values.set(`"${i}"`,n),i}return t}}replaceInJson(e){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(const[t,n]of this.values)e=e.replace(t,n);return e}}class Zj extends Q1{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super(),this.settings=e}write(e,t){this.rootSchema=vi.of(e),this.buffer=this._write(this.rootSchema,t)}flush(){const{rootSchema:e,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);const n=new Kj;return n.replaceInJson(JSON.stringify(this.buffer,n.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(e,t){this.write(e,t),typeof this.buffer=="object"&&(this.buffer.__type=vi.of(e).getName(!0))}_write(e,t,n){const i=t!==null&&typeof t=="object",a=vi.of(e);if(i){if(a.isStructSchema()){const s=t,o={},{jsonName:l}=this.settings;let u;l&&(u={});let c=0;for(const[f,d]of a.structIterator()){const h=this._write(d,s[f],a);if(h!==void 0){let g=f;l&&(g=d.getMergedTraits().jsonName??f,u[f]=g),o[g]=h,c++}}if(a.isUnionSchema()&&c===0){const{$unknown:f}=s;if(Array.isArray(f)){const[d,h]=f;o[d]=this._write(15,h)}}else if(typeof s.__type=="string")for(const f in s){const d=s[f],h=l?u[f]??f:f;h in o||(o[h]=this._write(15,d))}return o}if(Array.isArray(t)&&a.isListSchema()){const s=a.getValueSchema(),o=[],l=!!a.getMergedTraits().sparse;for(const u of t)(l||u!=null)&&o.push(this._write(s,u));return o}if(a.isMapSchema()){const s=a.getValueSchema(),o={},l=!!a.getMergedTraits().sparse;for(const u in t){const c=t[u];(l||c!=null)&&(o[u]=this._write(s,c))}return o}if(t instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??Cg)(t);if(t instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(rP(a,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return iz(t);case 7:return t.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1e3}t instanceof ns&&(this.useReplacer=!0)}if(!(t===null&&n?.isStructSchema())){if(a.isStringSchema()){if(typeof t>"u"&&a.isIdempotencyToken())return i$();const s=a.getMergedTraits().mediaType;return t!=null&&s&&(s==="application/json"||s.endsWith("+json"))?po.from(t):t}if(typeof t=="number"&&a.isNumericSchema())return Math.abs(t)===1/0||isNaN(t)?String(t):t;if(typeof t=="string"&&a.isBlobSchema())return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??Cg)(t);if(typeof t=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(i){const s=Array.isArray(t)?[]:{};for(const o in t){const l=t[o];l instanceof ns?(this.useReplacer=!0,s[o]=l):s[o]=this._write(a,l)}return s}else return structuredClone(t);return t}}}class eG extends Q1{settings;constructor(e){super(),this.settings=e}createSerializer(){const e=new Zj(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){const e=new Jj(this.settings);return e.setSerdeContext(this.serdeContext),e}}class tG extends o${serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a}){super({defaultNamespace:e,errorTypeRegistries:t}),this.serviceTarget=n,this.codec=a??new eG({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!i,this.mixin=new jj(this.awsQueryCompatible)}async serializeRequest(e,t,n){const i=await super.serializeRequest(e,t,n);return i.path.endsWith("/")||(i.path+="/"),i.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,i.headers["x-amz-target"]=`${this.serviceTarget}.${e.name}`,this.awsQueryCompatible&&(i.headers["x-amzn-query-mode"]="true"),(Yp(e.input)==="unit"||!i.body)&&(i.body="{}"),i}getPayloadCodec(){return this.codec}async handleError(e,t,n,i,a){const{awsQueryCompatible:s}=this;s&&this.mixin.setQueryCompatError(i,n);const o=Yj(n,i,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,o,this.options.defaultNamespace);const{errorSchema:l,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,n,i,a,s?this.mixin.findQueryCompatibleError:void 0),c=vi.of(l),f=i.message??i.Message??"UnknownError",d=this.compositeErrorRegistry.getErrorCtor(l)??Error,h=new d({}),g={},v=this.codec.createDeserializer();for(const[y,A]of c.structIterator())i[y]!=null&&(g[y]=v.readObject(A,i[y]));throw s&&this.mixin.queryCompatOutput(i,g),this.mixin.decorateServiceException(Object.assign(h,u,{$fault:c.getMergedTraits().error,message:f},g),i)}}class rG extends tG{constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a}){super({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}const Ff="ref",hl=-1,Ip=!0,u2="isSet",yP="PartitionResult",Pp="booleanEquals",Kv="getAttr",Fd="stringEquals",c2={[Ff]:"Endpoint"},Zv={[Ff]:yP},$d={[Ff]:"Region"},Ya={},d2=[$d],f2={conditions:[[u2,[c2]],[u2,d2],["aws.partition",d2,yP],[Pp,[{[Ff]:"UseFIPS"},Ip]],[Pp,[{fn:Kv,argv:[Zv,"supportsFIPS"]},Ip]],[Pp,[{[Ff]:"UseDualStack"},Ip]],[Pp,[{fn:Kv,argv:[Zv,"supportsDualStack"]},Ip]],[Fd,[{fn:Kv,argv:[Zv,"name"]},"aws"]],[Fd,[$d,"us-east-1"]],[Fd,[$d,"us-east-2"]],[Fd,[$d,"us-west-1"]],[Fd,[$d,"us-west-2"]]],results:[[hl],[hl,"Invalid Configuration: FIPS and custom endpoint are not supported"],[hl,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[c2,Ya],["https://cognito-idp-fips.us-east-1.amazonaws.com",Ya],["https://cognito-idp-fips.us-east-2.amazonaws.com",Ya],["https://cognito-idp-fips.us-west-1.amazonaws.com",Ya],["https://cognito-idp-fips.us-west-2.amazonaws.com",Ya],["https://cognito-idp-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Ya],[hl,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://cognito-idp-fips.{Region}.{PartitionResult#dnsSuffix}",Ya],[hl,"FIPS is enabled but this partition does not support FIPS"],["https://cognito-idp.{Region}.amazonaws.com",Ya],["https://cognito-idp.{Region}.{PartitionResult#dualStackDnsSuffix}",Ya],[hl,"DualStack is enabled but this partition does not support DualStack"],["https://cognito-idp.{Region}.{PartitionResult#dnsSuffix}",Ya],[hl,"Invalid Configuration: Missing Region"]]},nG=2,pi=1e8,iG=new Int32Array([-1,1,-1,0,17,3,1,4,pi+16,2,5,pi+16,3,9,6,5,7,pi+15,6,8,pi+14,7,pi+12,pi+13,4,11,10,5,pi+9,pi+11,5,12,pi+10,6,13,pi+9,8,pi+4,14,9,pi+5,15,10,pi+6,16,11,pi+7,pi+8,3,pi+1,18,5,pi+2,pi+3]),aG=$1.from(iG,nG,f2.conditions,f2.results),sG=new _z({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),oG=(r,e={})=>sG.get(r,()=>t$(aG,{endpointParams:r,logger:e.logger}));H1.aws=oP;class Ct extends Lu{constructor(e){super(e),Object.setPrototypeOf(this,Ct.prototype)}}class Y1 extends Ct{name="AccessDeniedException";$fault="client";constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,Y1.prototype)}}class X1 extends Ct{name="InternalErrorException";$fault="server";constructor(e){super({name:"InternalErrorException",$fault:"server",...e}),Object.setPrototypeOf(this,X1.prototype)}}class J1 extends Ct{name="InvalidParameterException";$fault="client";reasonCode;constructor(e){super({name:"InvalidParameterException",$fault:"client",...e}),Object.setPrototypeOf(this,J1.prototype),this.reasonCode=e.reasonCode}}class K1 extends Ct{name="NotAuthorizedException";$fault="client";constructor(e){super({name:"NotAuthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,K1.prototype)}}class Z1 extends Ct{name="OperationNotEnabledException";$fault="client";constructor(e){super({name:"OperationNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Z1.prototype)}}class eb extends Ct{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,eb.prototype)}}class tb extends Ct{name="TooManyRequestsException";$fault="client";constructor(e){super({name:"TooManyRequestsException",$fault:"client",...e}),Object.setPrototypeOf(this,tb.prototype)}}class rb extends Ct{name="UserImportInProgressException";$fault="client";constructor(e){super({name:"UserImportInProgressException",$fault:"client",...e}),Object.setPrototypeOf(this,rb.prototype)}}class nb extends Ct{name="InternalServerException";$fault="server";constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,nb.prototype)}}class ib extends Ct{name="LimitExceededException";$fault="client";constructor(e){super({name:"LimitExceededException",$fault:"client",...e}),Object.setPrototypeOf(this,ib.prototype)}}class ab extends Ct{name="UserNotFoundException";$fault="client";constructor(e){super({name:"UserNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,ab.prototype)}}class sb extends Ct{name="InvalidLambdaResponseException";$fault="client";constructor(e){super({name:"InvalidLambdaResponseException",$fault:"client",...e}),Object.setPrototypeOf(this,sb.prototype)}}class ob extends Ct{name="TooManyFailedAttemptsException";$fault="client";constructor(e){super({name:"TooManyFailedAttemptsException",$fault:"client",...e}),Object.setPrototypeOf(this,ob.prototype)}}class lb extends Ct{name="UnexpectedLambdaException";$fault="client";constructor(e){super({name:"UnexpectedLambdaException",$fault:"client",...e}),Object.setPrototypeOf(this,lb.prototype)}}class ub extends Ct{name="UserLambdaValidationException";$fault="client";constructor(e){super({name:"UserLambdaValidationException",$fault:"client",...e}),Object.setPrototypeOf(this,ub.prototype)}}class cb extends Ct{name="CodeDeliveryFailureException";$fault="client";constructor(e){super({name:"CodeDeliveryFailureException",$fault:"client",...e}),Object.setPrototypeOf(this,cb.prototype)}}class db extends Ct{name="InvalidPasswordException";$fault="client";constructor(e){super({name:"InvalidPasswordException",$fault:"client",...e}),Object.setPrototypeOf(this,db.prototype)}}class fb extends Ct{name="InvalidSmsRoleAccessPolicyException";$fault="client";constructor(e){super({name:"InvalidSmsRoleAccessPolicyException",$fault:"client",...e}),Object.setPrototypeOf(this,fb.prototype)}}class hb extends Ct{name="InvalidSmsRoleTrustRelationshipException";$fault="client";constructor(e){super({name:"InvalidSmsRoleTrustRelationshipException",$fault:"client",...e}),Object.setPrototypeOf(this,hb.prototype)}}class pb extends Ct{name="PreconditionNotMetException";$fault="client";constructor(e){super({name:"PreconditionNotMetException",$fault:"client",...e}),Object.setPrototypeOf(this,pb.prototype)}}class gb extends Ct{name="UnsupportedUserStateException";$fault="client";constructor(e){super({name:"UnsupportedUserStateException",$fault:"client",...e}),Object.setPrototypeOf(this,gb.prototype)}}class mb extends Ct{name="UsernameExistsException";$fault="client";constructor(e){super({name:"UsernameExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,mb.prototype)}}class vb extends Ct{name="AliasExistsException";$fault="client";constructor(e){super({name:"AliasExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,vb.prototype)}}class yb extends Ct{name="InvalidUserPoolConfigurationException";$fault="client";constructor(e){super({name:"InvalidUserPoolConfigurationException",$fault:"client",...e}),Object.setPrototypeOf(this,yb.prototype)}}class Ab extends Ct{name="InvalidEmailRoleAccessPolicyException";$fault="client";constructor(e){super({name:"InvalidEmailRoleAccessPolicyException",$fault:"client",...e}),Object.setPrototypeOf(this,Ab.prototype)}}class bb extends Ct{name="MFAMethodNotFoundException";$fault="client";constructor(e){super({name:"MFAMethodNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,bb.prototype)}}class wb extends Ct{name="PasswordResetRequiredException";$fault="client";constructor(e){super({name:"PasswordResetRequiredException",$fault:"client",...e}),Object.setPrototypeOf(this,wb.prototype)}}class Cb extends Ct{name="UnsupportedOperationException";$fault="client";constructor(e){super({name:"UnsupportedOperationException",$fault:"client",...e}),Object.setPrototypeOf(this,Cb.prototype)}}class xb extends Ct{name="UserNotConfirmedException";$fault="client";constructor(e){super({name:"UserNotConfirmedException",$fault:"client",...e}),Object.setPrototypeOf(this,xb.prototype)}}class Sb extends Ct{name="UserPoolAddOnNotEnabledException";$fault="client";constructor(e){super({name:"UserPoolAddOnNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Sb.prototype)}}class Eb extends Ct{name="CodeMismatchException";$fault="client";constructor(e){super({name:"CodeMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,Eb.prototype)}}class kb extends Ct{name="ExpiredCodeException";$fault="client";constructor(e){super({name:"ExpiredCodeException",$fault:"client",...e}),Object.setPrototypeOf(this,kb.prototype)}}class Tb extends Ct{name="PasswordHistoryPolicyViolationException";$fault="client";constructor(e){super({name:"PasswordHistoryPolicyViolationException",$fault:"client",...e}),Object.setPrototypeOf(this,Tb.prototype)}}class Fb extends Ct{name="SoftwareTokenMFANotFoundException";$fault="client";constructor(e){super({name:"SoftwareTokenMFANotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,Fb.prototype)}}class Ib extends Ct{name="ConcurrentModificationException";$fault="client";constructor(e){super({name:"ConcurrentModificationException",$fault:"client",...e}),Object.setPrototypeOf(this,Ib.prototype)}}class Pb extends Ct{name="ForbiddenException";$fault="client";constructor(e){super({name:"ForbiddenException",$fault:"client",...e}),Object.setPrototypeOf(this,Pb.prototype)}}class Db extends Ct{name="WebAuthnChallengeNotFoundException";$fault="client";constructor(e){super({name:"WebAuthnChallengeNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,Db.prototype)}}class Rb extends Ct{name="WebAuthnClientMismatchException";$fault="client";constructor(e){super({name:"WebAuthnClientMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,Rb.prototype)}}class Ob extends Ct{name="WebAuthnCredentialNotSupportedException";$fault="client";constructor(e){super({name:"WebAuthnCredentialNotSupportedException",$fault:"client",...e}),Object.setPrototypeOf(this,Ob.prototype)}}class Bb extends Ct{name="WebAuthnNotEnabledException";$fault="client";constructor(e){super({name:"WebAuthnNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Bb.prototype)}}class Mb extends Ct{name="WebAuthnOriginNotAllowedException";$fault="client";constructor(e){super({name:"WebAuthnOriginNotAllowedException",$fault:"client",...e}),Object.setPrototypeOf(this,Mb.prototype)}}class _b extends Ct{name="WebAuthnRelyingPartyMismatchException";$fault="client";constructor(e){super({name:"WebAuthnRelyingPartyMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,_b.prototype)}}class Nb extends Ct{name="DeviceKeyExistsException";$fault="client";constructor(e){super({name:"DeviceKeyExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Nb.prototype)}}class Lb extends Ct{name="GroupExistsException";$fault="client";constructor(e){super({name:"GroupExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Lb.prototype)}}class Ub extends Ct{name="DuplicateProviderException";$fault="client";constructor(e){super({name:"DuplicateProviderException",$fault:"client",...e}),Object.setPrototypeOf(this,Ub.prototype)}}class Vb extends Ct{name="ManagedLoginBrandingExistsException";$fault="client";constructor(e){super({name:"ManagedLoginBrandingExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Vb.prototype)}}class zb extends Ct{name="TermsExistsException";$fault="client";constructor(e){super({name:"TermsExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,zb.prototype)}}class $b extends Ct{name="FeatureUnavailableInTierException";$fault="client";constructor(e){super({name:"FeatureUnavailableInTierException",$fault:"client",...e}),Object.setPrototypeOf(this,$b.prototype)}}class Hb extends Ct{name="TierChangeNotAllowedException";$fault="client";constructor(e){super({name:"TierChangeNotAllowedException",$fault:"client",...e}),Object.setPrototypeOf(this,Hb.prototype)}}class jb extends Ct{name="UserPoolTaggingException";$fault="client";constructor(e){super({name:"UserPoolTaggingException",$fault:"client",...e}),Object.setPrototypeOf(this,jb.prototype)}}class Gb extends Ct{name="InvalidOAuthFlowException";$fault="client";constructor(e){super({name:"InvalidOAuthFlowException",$fault:"client",...e}),Object.setPrototypeOf(this,Gb.prototype)}}class qb extends Ct{name="ScopeDoesNotExistException";$fault="client";constructor(e){super({name:"ScopeDoesNotExistException",$fault:"client",...e}),Object.setPrototypeOf(this,qb.prototype)}}class Wb extends Ct{name="UnsupportedIdentityProviderException";$fault="client";constructor(e){super({name:"UnsupportedIdentityProviderException",$fault:"client",...e}),Object.setPrototypeOf(this,Wb.prototype)}}class Qb extends Ct{name="RefreshTokenReuseException";$fault="client";constructor(e){super({name:"RefreshTokenReuseException",$fault:"client",...e}),Object.setPrototypeOf(this,Qb.prototype)}}class Yb extends Ct{name="UnauthorizedException";$fault="client";constructor(e){super({name:"UnauthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,Yb.prototype)}}class Xb extends Ct{name="UnsupportedTokenTypeException";$fault="client";constructor(e){super({name:"UnsupportedTokenTypeException",$fault:"client",...e}),Object.setPrototypeOf(this,Xb.prototype)}}class Jb extends Ct{name="WebAuthnConfigurationMissingException";$fault="client";constructor(e){super({name:"WebAuthnConfigurationMissingException",$fault:"client",...e}),Object.setPrototypeOf(this,Jb.prototype)}}class Kb extends Ct{name="EnableSoftwareTokenMFAException";$fault="client";constructor(e){super({name:"EnableSoftwareTokenMFAException",$fault:"client",...e}),Object.setPrototypeOf(this,Kb.prototype)}}const lG="AvailableChallenges",uG="AccessDeniedException",cG="AliasExistsException",dG="AnalyticsEndpointId",fG="AuthFlow",AP="AnalyticsMetadata",hG="AnalyticsMetadataType",pG="AuthParameters",gG="AuthParametersType",bP="AuthenticationResult",mG="AuthenticationResultType",vG="AccessToken",yG="CodeDeliveryFailureException",wP="ClientId",AG="ClientIdType",CP="ClientMetadata",bG="CodeMismatchException",wG="ConcurrentModificationException",Zb="ChallengeName",xP="ChallengeParameters",CG="ChallengeResponses",xG="ChallengeResponsesType",SG="DeviceGroupKey",EG="DeviceKey",kG="DeviceKeyExistsException",TG="DuplicateProviderException",FG="ExpiredCodeException",IG="EncodedData",PG="ExpiresIn",DG="EnableSoftwareTokenMFAException",RG="ForbiddenException",OG="FeatureUnavailableInTierException",BG="GroupExistsException",MG="IpAddress",_G="InitiateAuthRequest",NG="InitiateAuthResponse",LG="InitiateAuth",UG="InternalErrorException",VG="InvalidEmailRoleAccessPolicyException",zG="InvalidLambdaResponseException",$G="InvalidOAuthFlowException",HG="InvalidParameterException",jG="InvalidPasswordException",GG="InternalServerException",qG="InvalidSmsRoleAccessPolicyException",WG="InvalidSmsRoleTrustRelationshipException",QG="IdToken",YG="InvalidUserPoolConfigurationException",XG="LimitExceededException",JG="MFAMethodNotFoundException",KG="ManagedLoginBrandingExistsException",ZG="NotAuthorizedException",eq="NewDeviceMetadata",tq="NewDeviceMetadataType",rq="OperationNotEnabledException",nq="PasswordHistoryPolicyViolationException",iq="PreconditionNotMetException",aq="PasswordResetRequiredException",sq="ResourceNotFoundException",oq="RefreshToken",lq="RespondToAuthChallenge",uq="RespondToAuthChallengeRequest",cq="RespondToAuthChallengeResponse",dq="RefreshTokenReuseException",nm="Session",fq="ScopeDoesNotExistException",hq="SessionType",pq="SoftwareTokenMFANotFoundException",gq="TierChangeNotAllowedException",mq="TermsExistsException",vq="TooManyFailedAttemptsException",yq="TooManyRequestsException",Aq="TokenModelType",bq="TokenType",wq="UserContextDataType",SP="UserContextData",Cq="UnauthorizedException",xq="UsernameExistsException",Sq="UserImportInProgressException",Eq="UnsupportedIdentityProviderException",kq="UnexpectedLambdaException",Tq="UserLambdaValidationException",Fq="UserNotConfirmedException",Iq="UserNotFoundException",Pq="UnsupportedOperationException",Dq="UserPoolAddOnNotEnabledException",Rq="UserPoolTaggingException",Oq="UnsupportedTokenTypeException",Bq="UnsupportedUserStateException",Mq="WebAuthnClientMismatchException",_q="WebAuthnConfigurationMissingException",Nq="WebAuthnChallengeNotFoundException",Lq="WebAuthnCredentialNotSupportedException",Uq="WebAuthnNotEnabledException",Vq="WebAuthnOriginNotAllowedException",zq="WebAuthnRelyingPartyMismatchException",It="client",Tt="error",Pt="httpError",Ft="message",$q="reasonCode",EP="smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentityprovider",kP="server",at="com.amazonaws.cognitoidentityprovider",TP=Zi.for(EP);var Hq=[-3,EP,"CognitoIdentityProviderServiceException",0,[],[]];TP.registerError(Hq,Ct);const kt=Zi.for(at);var jq=[-3,at,uG,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(jq,Y1);var Gq=[-3,at,cG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Gq,vb);var qq=[-3,at,yG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(qq,cb);var Wq=[-3,at,bG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Wq,Eb);var Qq=[-3,at,wG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Qq,Ib);var Yq=[-3,at,kG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Yq,Nb);var Xq=[-3,at,TG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Xq,Ub);var Jq=[-3,at,DG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Jq,Kb);var Kq=[-3,at,FG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Kq,kb);var Zq=[-3,at,OG,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(Zq,$b);var eW=[-3,at,RG,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(eW,Pb);var tW=[-3,at,BG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(tW,Lb);var rW=[-3,at,UG,{[Tt]:kP},[Ft],[0]];kt.registerError(rW,X1);var nW=[-3,at,GG,{[Tt]:kP},[Ft],[0]];kt.registerError(nW,nb);var iW=[-3,at,VG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(iW,Ab);var aW=[-3,at,zG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(aW,sb);var sW=[-3,at,$G,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(sW,Gb);var oW=[-3,at,HG,{[Tt]:It,[Pt]:400},[Ft,$q],[0,0]];kt.registerError(oW,J1);var lW=[-3,at,jG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(lW,db);var uW=[-3,at,qG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(uW,fb);var cW=[-3,at,WG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(cW,hb);var dW=[-3,at,YG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(dW,yb);var fW=[-3,at,XG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(fW,ib);var hW=[-3,at,KG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(hW,Vb);var pW=[-3,at,JG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(pW,bb);var gW=[-3,at,ZG,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(gW,K1);var mW=[-3,at,rq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(mW,Z1);var vW=[-3,at,nq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(vW,Tb);var yW=[-3,at,aq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(yW,wb);var AW=[-3,at,iq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(AW,pb);var bW=[-3,at,dq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(bW,Qb);var wW=[-3,at,sq,{[Tt]:It,[Pt]:404},[Ft],[0]];kt.registerError(wW,eb);var CW=[-3,at,fq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(CW,qb);var xW=[-3,at,pq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(xW,Fb);var SW=[-3,at,mq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(SW,zb);var EW=[-3,at,gq,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(EW,Hb);var kW=[-3,at,vq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(kW,ob);var TW=[-3,at,yq,{[Tt]:It,[Pt]:429},[Ft],[0]];kt.registerError(TW,tb);var FW=[-3,at,Cq,{[Tt]:It,[Pt]:401},[Ft],[0]];kt.registerError(FW,Yb);var IW=[-3,at,kq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(IW,lb);var PW=[-3,at,Eq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(PW,Wb);var DW=[-3,at,Pq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(DW,Cb);var RW=[-3,at,Oq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(RW,Xb);var OW=[-3,at,Bq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(OW,gb);var BW=[-3,at,Sq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(BW,rb);var MW=[-3,at,Tq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(MW,ub);var _W=[-3,at,xq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(_W,mb);var NW=[-3,at,Fq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(NW,xb);var LW=[-3,at,Iq,{[Tt]:It,[Pt]:404},[Ft],[0]];kt.registerError(LW,ab);var UW=[-3,at,Dq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(UW,Sb);var VW=[-3,at,Rq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(VW,jb);var zW=[-3,at,Nq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(zW,Db);var $W=[-3,at,Mq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError($W,Rb);var HW=[-3,at,_q,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(HW,Jb);var jW=[-3,at,Lq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(jW,Ob);var GW=[-3,at,Uq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(GW,Bb);var qW=[-3,at,Vq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(qW,Mb);var WW=[-3,at,zq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(WW,_b);const QW=[TP,kt];var FP=[0,at,AG,8,0],im=[0,at,hq,8,0],ey=[0,at,Aq,8,0],IP=[3,at,hG,0,[dG],[0]],PP=[3,at,mG,0,[vG,PG,bq,oq,QG,eq],[[()=>ey,0],1,0,[()=>ey,0],[()=>ey,0],()=>JW]],YW=[3,at,_G,0,[fG,wP,pG,CP,AP,SP,nm],[0,[()=>FP,0],[()=>eQ,0],128,()=>IP,[()=>DP,0],[()=>im,0]],2],XW=[3,at,NG,0,[Zb,nm,xP,bP,lG],[0,[()=>im,0],128,[()=>PP,0],64]],JW=[3,at,tq,0,[EG,SG],[0,0]],KW=[3,at,uq,0,[wP,Zb,nm,CG,AP,SP,CP],[[()=>FP,0],0,[()=>im,0],[()=>tQ,0],()=>IP,[()=>DP,0],128],2],ZW=[3,at,cq,0,[Zb,nm,xP,bP],[0,[()=>im,0],128,[()=>PP,0]]],DP=[3,at,wq,8,[MG,IG],[0,0]],eQ=[2,at,gG,8,0,0],tQ=[2,at,xG,8,0,0],rQ=[9,at,LG,0,()=>YW,()=>XW],nQ=[9,at,lq,0,()=>KW,()=>ZW];const iQ=r=>({apiVersion:"2016-04-18",base64Decoder:r?.base64Decoder??Zg,base64Encoder:r?.base64Encoder??Cg,disableHostPrefix:r?.disableHostPrefix??!1,endpointProvider:r?.endpointProvider??oG,extensions:r?.extensions??[],httpAuthSchemeProvider:r?.httpAuthSchemeProvider??yj,httpAuthSchemes:r?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new $H},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new sH}],logger:r?.logger??new UI,protocol:r?.protocol??rG,protocolSettings:r?.protocolSettings??{defaultNamespace:"com.amazonaws.cognitoidentityprovider",errorTypeRegistries:QW,xmlNamespace:"http://cognito-idp.amazonaws.com/doc/2016-04-18/",version:"2016-04-18",serviceTarget:"AWSCognitoIdentityProviderService"},serviceId:r?.serviceId??"Cognito Identity Provider",urlParser:r?.urlParser??wg,utf8Decoder:r?.utf8Decoder??kl,utf8Encoder:r?.utf8Encoder??em}),aQ=r=>{const e=BH(r),t=()=>e().then(NV),n=iQ(r);return{...n,...r,runtime:"browser",defaultsMode:e,bodyLengthChecker:r?.bodyLengthChecker??Az,credentialDefaultProvider:r?.credentialDefaultProvider??(i=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:r?.defaultUserAgentProvider??kH({serviceId:n.serviceId,clientVersion:Cj.version}),maxAttempts:r?.maxAttempts??ef,region:r?.region??FV("Region is missing"),requestHandler:W1.create(r?.requestHandler??t),retryMode:r?.retryMode??(async()=>(await t()).retryMode||L$),sha256:r?.sha256??Lj,streamCollector:r?.streamCollector??Vj,useDualstackEndpoint:r?.useDualstackEndpoint??(()=>Promise.resolve(_H)),useFipsEndpoint:r?.useFipsEndpoint??(()=>Promise.resolve(NH))}},sQ=r=>{const e=r.httpAuthSchemes;let t=r.httpAuthSchemeProvider,n=r.credentials;return{setHttpAuthScheme(i){const a=e.findIndex(s=>s.schemeId===i.schemeId);a===-1?e.push(i):e.splice(a,1,i)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(i){t=i},httpAuthSchemeProvider(){return t},setCredentials(i){n=i},credentials(){return n}}},oQ=r=>({httpAuthSchemes:r.httpAuthSchemes(),httpAuthSchemeProvider:r.httpAuthSchemeProvider(),credentials:r.credentials()}),lQ=(r,e)=>{const t=Object.assign(LH(r),$V(r),l$(r),sQ(r));return e.forEach(n=>n.configure(t)),Object.assign(r,UH(t),HV(t),u$(t),oQ(t))};class uQ extends IV{config;constructor(...[e]){const t=aQ(e||{});super(t),this.initConfig=t;const n=bj(t),i=hH(n),a=V$(i),s=RH(a),o=s,l=r$(o),u=Aj(l),c=lQ(u,e?.extensions||[]);this.config=c,this.middlewareStack.use(BV(this.config)),this.middlewareStack.use(EH(this.config)),this.middlewareStack.use(z$(this.config)),this.middlewareStack.use(f$(this.config)),this.middlewareStack.use(j$(this.config)),this.middlewareStack.use(W$(this.config)),this.middlewareStack.use(Q$(this.config)),this.middlewareStack.use(Z$(this.config,{httpAuthSchemeParametersProvider:mj,identityProviderConfigProvider:async f=>new aH({"aws.auth#sigv4":f.credentials})})),this.middlewareStack.use(iH(this.config))}destroy(){super.destroy()}}class h2 extends V1.classBuilder().ep(mP).m(function(e,t,n,i){return[eP(n,e.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityProviderService","InitiateAuth",{}).n("CognitoIdentityProviderClient","InitiateAuthCommand").sc(rQ).build(){}class cQ extends V1.classBuilder().ep(mP).m(function(e,t,n,i){return[eP(n,e.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityProviderService","RespondToAuthChallenge",{}).n("CognitoIdentityProviderClient","RespondToAuthChallengeCommand").sc(nQ).build(){}class dQ{init(e,t,n){this.cognitoClient=new uQ({region:t}),this.spiffRegion=e,this.userPoolClientId=n}async generateCode(e){const t=await this.cognitoClient?.send(new h2({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:e}}));t?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=t.Session)}async verifyCode(e,t,n){const i=await this.cognitoClient?.send(new cQ({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:e,ANSWER:t},ClientMetadata:{partnerId:n,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}async refreshTokens(){const e=localStorage.getItem("cognito-tokens");if(!e)throw new Error("Failed to find existing tokens.");const t=JSON.parse(e);return await this.cognitoClient?.send(new h2({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:t.RefreshToken||""}}))}}const Id=new dQ;var fQ={defaultAmount:0,defaultCurrency:"USD",defaultPrecision:2},hQ={globalLocale:"en-US",globalFormat:"$0,0.00",globalRoundingMode:"HALF_EVEN",globalFormatRoundingMode:"HALF_AWAY_FROM_ZERO",globalExchangeRatesApi:{endpoint:void 0,headers:void 0,propertyPath:void 0}};function nf(r){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?nf=function(e){return typeof e}:nf=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},nf(r)}function p2(r){return pQ(r)||gQ(r)||mQ(r)||vQ()}function pQ(r){if(Array.isArray(r))return r}function gQ(r){if(typeof Symbol<"u"&&Symbol.iterator in Object(r))return Array.from(r)}function mQ(r,e){if(r){if(typeof r=="string")return g2(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return g2(r,e)}}function g2(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function vQ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3055
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var yQ={normalizePrecision:function(e){var t=e.reduce(function(n,i){return Math.max(n.getPrecision(),i.getPrecision())});return e.map(function(n){return n.getPrecision()!==t?n.convertPrecision(t):n})},minimum:function(e){var t=p2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.lessThan(s)?a:s}),a},maximum:function(e){var t=p2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.greaterThan(s)?a:s}),a}};function RP(r){return!isNaN(parseInt(r))&&isFinite(r)}function AQ(r){return RP(r)&&r<=100&&r>=0}function bQ(r){return r.length>0&&r.every(function(e){return e>=0})&&r.some(function(e){return e>0})}function m2(r){return r%2===0}function v2(r){return RP(r)&&!Number.isInteger(r)}function wQ(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=r.toString();if(e.indexOf("e-")>0)return parseInt(e.split("e-")[1]);var t=e.split(".")[1];return t?t.length:0}function Pd(r){return Math.abs(r)%1===.5}function CQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(t,n){var i=Object.assign(new XMLHttpRequest,{onreadystatechange:function(){i.readyState===4&&(i.status>=200&&i.status<400?t(JSON.parse(i.responseText)):n(new Error(i.statusText)))},onerror:function(){n(new Error("Network error"))}});i.open("GET",r,!0),xQ(i,e.headers),i.send()})}function xQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};for(var t in e)r.setRequestHeader(t,e[t]);return r}function Hd(r){return typeof r>"u"}function OP(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:".",t={};return Object.entries(r).forEach(function(n){if(nf(n[1])==="object"){var i=OP(n[1]);Object.entries(i).forEach(function(a){t[n[0]+e+a[0]]=a[1]})}else t[n[0]]=n[1]}),t}function SQ(r){return!!r&&(nf(r)==="object"||typeof r=="function")&&typeof r.then=="function"}function BP(){var r=function(n,i){var a=function(l){return Math.pow(10,wQ(l))},s=Math.max(a(n),a(i));return Math.round(n*s)*Math.round(i*s)/(s*s)},e={HALF_ODD:function(n){var i=Math.round(n);return Pd(n)&&m2(i)?i-1:i},HALF_EVEN:function(n){var i=Math.round(n);return Pd(n)?m2(i)?i:i-1:i},HALF_UP:function(n){return Math.round(n)},HALF_DOWN:function(n){return Pd(n)?Math.floor(n):Math.round(n)},HALF_TOWARDS_ZERO:function(n){return Pd(n)?Math.sign(n)*Math.floor(Math.abs(n)):Math.round(n)},HALF_AWAY_FROM_ZERO:function(n){return Pd(n)?Math.sign(n)*Math.ceil(Math.abs(n)):Math.round(n)},DOWN:function(n){return Math.floor(n)}};return{add:function(n,i){return n+i},subtract:function(n,i){return n-i},multiply:function(n,i){return v2(n)||v2(i)?r(n,i):n*i},divide:function(n,i){return n/i},modulo:function(n,i){return n%i},round:function(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"HALF_EVEN";return e[i](n)}}}var EQ=BP();function kQ(r){var e=/^(?:(\$|USD)?0(?:(,)0)?(\.)?(0+)?|0(?:(,)0)?(\.)?(0+)?\s?(dollar)?)$/gm.exec(r);return{getMatches:function(){return e!==null?e.slice(1).filter(function(n){return!Hd(n)}):[]},getMinimumFractionDigits:function(){var n=function(a){return a==="."};return Hd(this.getMatches().find(n))?0:this.getMatches()[EQ.add(this.getMatches().findIndex(n),1)].split("").length},getCurrencyDisplay:function(){var n={USD:"code",dollar:"name",$:"symbol"};return n[this.getMatches().find(function(i){return i==="USD"||i==="dollar"||i==="$"})]},getStyle:function(){return Hd(this.getCurrencyDisplay(this.getMatches()))?"decimal":"currency"},getUseGrouping:function(){return!Hd(this.getMatches().find(function(n){return n===","}))}}}function TQ(r){var e=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",a=arguments.length>1?arguments[1]:void 0;for(var s in a)i=i.replace("{{".concat(s,"}}"),a[s]);return i},t=function(i,a){return CQ(e(r.endpoint,{from:i,to:a}),{headers:r.headers})};return{getExchangeRate:function(i,a){return(SQ(r.endpoint)?r.endpoint:t(i,a)).then(function(s){return OP(s)[e(r.propertyPath,{from:i,to:a})]})}}}function If(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Error;if(!r)throw new t(e)}function FQ(r){If(AQ(r),"You must provide a numeric value between 0 and 100.",RangeError)}function IQ(r){If(bQ(r),"You must provide a non-empty array of numeric values greater than 0.",TypeError)}function ty(r){If(Number.isInteger(r),"You must provide an integer.",TypeError)}var kn=BP(),PQ=function r(e){var t=Object.assign({},{amount:r.defaultAmount,currency:r.defaultCurrency,precision:r.defaultPrecision},e),n=t.amount,i=t.currency,a=t.precision;ty(n),ty(a);var s=r.globalLocale,o=r.globalFormat,l=r.globalRoundingMode,u=r.globalFormatRoundingMode,c=Object.assign({},r.globalExchangeRatesApi),f=function(g){var v=Object.assign({},Object.assign({},{amount:n,currency:i,precision:a},g),Object.assign({},{locale:this.locale},g));return Object.assign(r({amount:v.amount,currency:v.currency,precision:v.precision}),{locale:v.locale})},d=function(g){If(this.hasSameCurrency(g),"You must provide a Dinero instance with the same currency.",TypeError)};return{getAmount:function(){return n},getCurrency:function(){return i},getLocale:function(){return this.locale||s},setLocale:function(g){return f.call(this,{locale:g})},getPrecision:function(){return a},convertPrecision:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u;ty(g);var y=this.getPrecision(),A=g>y,C=A?kn.multiply:kn.divide,S=A?[g,y]:[y,g],F=Math.pow(10,kn.subtract.apply(kn,S));return f.call(this,{amount:kn.round(C(this.getAmount(),F),v),precision:g})},add:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return f.call(this,{amount:kn.add(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},subtract:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return f.call(this,{amount:kn.subtract(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},multiply:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return f.call(this,{amount:kn.round(kn.multiply(this.getAmount(),g),v)})},divide:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return f.call(this,{amount:kn.round(kn.divide(this.getAmount(),g),v)})},percentage:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return FQ(g),this.multiply(kn.divide(g,100),v)},allocate:function(g){var v=this;IQ(g);for(var y=g.reduce(function(F,E){return kn.add(F,E)}),A=this.getAmount(),C=g.map(function(F){var E=Math.floor(kn.divide(kn.multiply(v.getAmount(),F),y));return A=kn.subtract(A,E),f.call(v,{amount:E})}),S=0;A>0;)g[S]>0&&(C[S]=C[S].add(f.call(this,{amount:1})),A=kn.subtract(A,1)),S+=1;return C},convert:function(g){var v=this,y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=y.endpoint,C=A===void 0?c.endpoint:A,S=y.propertyPath,F=S===void 0?c.propertyPath||"rates.{{to}}":S,E=y.headers,R=E===void 0?c.headers:E,B=y.roundingMode,j=B===void 0?l:B,G=Object.assign({},{endpoint:C,propertyPath:F,headers:R,roundingMode:j});return TQ(G).getExchangeRate(this.getCurrency(),g).then(function(ie){return If(!Hd(ie),'No rate was found for the destination currency "'.concat(g,'".'),TypeError),f.call(v,{amount:kn.round(kn.multiply(v.getAmount(),parseFloat(ie)),G.roundingMode),currency:g})})},equalsTo:function(g){return this.hasSameAmount(g)&&this.hasSameCurrency(g)},lessThan:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<v[1].getAmount()},lessThanOrEqual:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<=v[1].getAmount()},greaterThan:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>v[1].getAmount()},greaterThanOrEqual:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>=v[1].getAmount()},isZero:function(){return this.getAmount()===0},isPositive:function(){return this.getAmount()>=0},isNegative:function(){return this.getAmount()<0},hasSubUnits:function(){return kn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasCents:function(){return kn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasSameCurrency:function(g){return this.getCurrency()===g.getCurrency()},hasSameAmount:function(g){var v=r.normalizePrecision([this,g]);return v[0].getAmount()===v[1].getAmount()},toFormat:function(){var g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:o,v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=kQ(g);return this.toRoundedUnit(y.getMinimumFractionDigits(),v).toLocaleString(this.getLocale(),{currencyDisplay:y.getCurrencyDisplay(),useGrouping:y.getUseGrouping(),minimumFractionDigits:y.getMinimumFractionDigits(),style:y.getStyle(),currency:this.getCurrency()})},toUnit:function(){return kn.divide(this.getAmount(),Math.pow(10,a))},toRoundedUnit:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=Math.pow(10,g);return kn.divide(kn.round(kn.multiply(this.toUnit(),y),v),y)},toObject:function(){return{amount:n,currency:i,precision:a}},toJSON:function(){return this.toObject()}}},DQ=Object.assign(PQ,fQ,hQ,yQ),Xa={},ry,y2;function RQ(){if(y2)return ry;y2=1;function r(t){return t}function e(t,a,s){for(var a=a||r,s=s||t,o=0,l=t.length;o<l;o+=1)if(a.call(s,t[o],o))return t[o]}return ry=e,ry}var ny={exports:{}},A2;function OQ(){if(A2)return ny.exports;A2=1;var r=ny.exports=function(e,t){if(typeof e=="function"||t)return r.by(e,t);for(var n={object:[],function:[],string:{},number:{},boolean:{},undefined:{}},i=[],a=0;a<e.length;a++){var s=e[a],o=s==="__proto__"?n.objects:n[typeof s]||n.objects;Array.isArray(o)?o.indexOf(s)<0&&(o.push(s),i.push(s)):Object.hasOwnProperty.call(o,s)||(o[s]=!0,i.push(s))}return i};return r.by=function(e,t){if(typeof e=="function"){var n=t;t=e,e=n}for(var i=[],a=0;a<e.length;a++){for(var s=e[a],o=!1,l=0;l<i.length;l++){var u=i[l];if(t.call(i,s,u)){o=!0;break}}o||i.push(s)}return i},ny.exports}var iy,b2;function BQ(){return b2||(b2=1,iy=[{code:"AED",number:"784",digits:2,currency:"UAE Dirham",countries:["United Arab Emirates (The)"]},{code:"AFN",number:"971",digits:2,currency:"Afghani",countries:["Afghanistan"]},{code:"ALL",number:"008",digits:2,currency:"Lek",countries:["Albania"]},{code:"AMD",number:"051",digits:2,currency:"Armenian Dram",countries:["Armenia"]},{code:"ANG",number:"532",digits:2,currency:"Netherlands Antillean Guilder",countries:["Curaçao","Sint Maarten (Dutch Part)"]},{code:"AOA",number:"973",digits:2,currency:"Kwanza",countries:["Angola"]},{code:"ARS",number:"032",digits:2,currency:"Argentine Peso",countries:["Argentina"]},{code:"AUD",number:"036",digits:2,currency:"Australian Dollar",countries:["Australia","Christmas Island","Cocos (Keeling) Islands (The)","Heard Island and Mcdonald Islands","Kiribati","Nauru","Norfolk Island","Tuvalu"]},{code:"AWG",number:"533",digits:2,currency:"Aruban Florin",countries:["Aruba"]},{code:"AZN",number:"944",digits:2,currency:"Azerbaijan Manat",countries:["Azerbaijan"]},{code:"BAM",number:"977",digits:2,currency:"Convertible Mark",countries:["Bosnia and Herzegovina"]},{code:"BBD",number:"052",digits:2,currency:"Barbados Dollar",countries:["Barbados"]},{code:"BDT",number:"050",digits:2,currency:"Taka",countries:["Bangladesh"]},{code:"BGN",number:"975",digits:2,currency:"Bulgarian Lev",countries:["Bulgaria"]},{code:"BHD",number:"048",digits:3,currency:"Bahraini Dinar",countries:["Bahrain"]},{code:"BIF",number:"108",digits:0,currency:"Burundi Franc",countries:["Burundi"]},{code:"BMD",number:"060",digits:2,currency:"Bermudian Dollar",countries:["Bermuda"]},{code:"BND",number:"096",digits:2,currency:"Brunei Dollar",countries:["Brunei Darussalam"]},{code:"BOB",number:"068",digits:2,currency:"Boliviano",countries:["Bolivia (Plurinational State Of)"]},{code:"BOV",number:"984",digits:2,currency:"Mvdol",countries:["Bolivia (Plurinational State Of)"]},{code:"BRL",number:"986",digits:2,currency:"Brazilian Real",countries:["Brazil"]},{code:"BSD",number:"044",digits:2,currency:"Bahamian Dollar",countries:["Bahamas (The)"]},{code:"BTN",number:"064",digits:2,currency:"Ngultrum",countries:["Bhutan"]},{code:"BWP",number:"072",digits:2,currency:"Pula",countries:["Botswana"]},{code:"BYN",number:"933",digits:2,currency:"Belarusian Ruble",countries:["Belarus"]},{code:"BZD",number:"084",digits:2,currency:"Belize Dollar",countries:["Belize"]},{code:"CAD",number:"124",digits:2,currency:"Canadian Dollar",countries:["Canada"]},{code:"CDF",number:"976",digits:2,currency:"Congolese Franc",countries:["Congo (The Democratic Republic of The)"]},{code:"CHE",number:"947",digits:2,currency:"WIR Euro",countries:["Switzerland"]},{code:"CHF",number:"756",digits:2,currency:"Swiss Franc",countries:["Liechtenstein","Switzerland"]},{code:"CHW",number:"948",digits:2,currency:"WIR Franc",countries:["Switzerland"]},{code:"CLF",number:"990",digits:4,currency:"Unidad de Fomento",countries:["Chile"]},{code:"CLP",number:"152",digits:0,currency:"Chilean Peso",countries:["Chile"]},{code:"CNY",number:"156",digits:2,currency:"Yuan Renminbi",countries:["China"]},{code:"COP",number:"170",digits:2,currency:"Colombian Peso",countries:["Colombia"]},{code:"COU",number:"970",digits:2,currency:"Unidad de Valor Real",countries:["Colombia"]},{code:"CRC",number:"188",digits:2,currency:"Costa Rican Colon",countries:["Costa Rica"]},{code:"CUC",number:"931",digits:2,currency:"Peso Convertible",countries:["Cuba"]},{code:"CUP",number:"192",digits:2,currency:"Cuban Peso",countries:["Cuba"]},{code:"CVE",number:"132",digits:2,currency:"Cabo Verde Escudo",countries:["Cabo Verde"]},{code:"CZK",number:"203",digits:2,currency:"Czech Koruna",countries:["Czechia"]},{code:"DJF",number:"262",digits:0,currency:"Djibouti Franc",countries:["Djibouti"]},{code:"DKK",number:"208",digits:2,currency:"Danish Krone",countries:["Denmark","Faroe Islands (The)","Greenland"]},{code:"DOP",number:"214",digits:2,currency:"Dominican Peso",countries:["Dominican Republic (The)"]},{code:"DZD",number:"012",digits:2,currency:"Algerian Dinar",countries:["Algeria"]},{code:"EGP",number:"818",digits:2,currency:"Egyptian Pound",countries:["Egypt"]},{code:"ERN",number:"232",digits:2,currency:"Nakfa",countries:["Eritrea"]},{code:"ETB",number:"230",digits:2,currency:"Ethiopian Birr",countries:["Ethiopia"]},{code:"EUR",number:"978",digits:2,currency:"Euro",countries:["Åland Islands","Andorra","Austria","Belgium","Croatia","Cyprus","Estonia","European Union","Finland","France","French Guiana","French Southern Territories (The)","Germany","Greece","Guadeloupe","Holy See (The)","Ireland","Italy","Latvia","Lithuania","Luxembourg","Malta","Martinique","Mayotte","Monaco","Montenegro","Netherlands (The)","Portugal","Réunion","Saint Barthélemy","Saint Martin (French Part)","Saint Pierre and Miquelon","San Marino","Slovakia","Slovenia","Spain"]},{code:"FJD",number:"242",digits:2,currency:"Fiji Dollar",countries:["Fiji"]},{code:"FKP",number:"238",digits:2,currency:"Falkland Islands Pound",countries:["Falkland Islands (The) [Malvinas]"]},{code:"GBP",number:"826",digits:2,currency:"Pound Sterling",countries:["Guernsey","Isle of Man","Jersey","United Kingdom of Great Britain and Northern Ireland (The)"]},{code:"GEL",number:"981",digits:2,currency:"Lari",countries:["Georgia"]},{code:"GHS",number:"936",digits:2,currency:"Ghana Cedi",countries:["Ghana"]},{code:"GIP",number:"292",digits:2,currency:"Gibraltar Pound",countries:["Gibraltar"]},{code:"GMD",number:"270",digits:2,currency:"Dalasi",countries:["Gambia (The)"]},{code:"GNF",number:"324",digits:0,currency:"Guinean Franc",countries:["Guinea"]},{code:"GTQ",number:"320",digits:2,currency:"Quetzal",countries:["Guatemala"]},{code:"GYD",number:"328",digits:2,currency:"Guyana Dollar",countries:["Guyana"]},{code:"HKD",number:"344",digits:2,currency:"Hong Kong Dollar",countries:["Hong Kong"]},{code:"HNL",number:"340",digits:2,currency:"Lempira",countries:["Honduras"]},{code:"HTG",number:"332",digits:2,currency:"Gourde",countries:["Haiti"]},{code:"HUF",number:"348",digits:2,currency:"Forint",countries:["Hungary"]},{code:"IDR",number:"360",digits:2,currency:"Rupiah",countries:["Indonesia"]},{code:"ILS",number:"376",digits:2,currency:"New Israeli Sheqel",countries:["Israel"]},{code:"INR",number:"356",digits:2,currency:"Indian Rupee",countries:["Bhutan","India"]},{code:"IQD",number:"368",digits:3,currency:"Iraqi Dinar",countries:["Iraq"]},{code:"IRR",number:"364",digits:2,currency:"Iranian Rial",countries:["Iran (Islamic Republic Of)"]},{code:"ISK",number:"352",digits:0,currency:"Iceland Krona",countries:["Iceland"]},{code:"JMD",number:"388",digits:2,currency:"Jamaican Dollar",countries:["Jamaica"]},{code:"JOD",number:"400",digits:3,currency:"Jordanian Dinar",countries:["Jordan"]},{code:"JPY",number:"392",digits:0,currency:"Yen",countries:["Japan"]},{code:"KES",number:"404",digits:2,currency:"Kenyan Shilling",countries:["Kenya"]},{code:"KGS",number:"417",digits:2,currency:"Som",countries:["Kyrgyzstan"]},{code:"KHR",number:"116",digits:2,currency:"Riel",countries:["Cambodia"]},{code:"KMF",number:"174",digits:0,currency:"Comorian Franc ",countries:["Comoros (The)"]},{code:"KPW",number:"408",digits:2,currency:"North Korean Won",countries:["Korea (The Democratic People’s Republic Of)"]},{code:"KRW",number:"410",digits:0,currency:"Won",countries:["Korea (The Republic Of)"]},{code:"KWD",number:"414",digits:3,currency:"Kuwaiti Dinar",countries:["Kuwait"]},{code:"KYD",number:"136",digits:2,currency:"Cayman Islands Dollar",countries:["Cayman Islands (The)"]},{code:"KZT",number:"398",digits:2,currency:"Tenge",countries:["Kazakhstan"]},{code:"LAK",number:"418",digits:2,currency:"Lao Kip",countries:["Lao People’s Democratic Republic (The)"]},{code:"LBP",number:"422",digits:2,currency:"Lebanese Pound",countries:["Lebanon"]},{code:"LKR",number:"144",digits:2,currency:"Sri Lanka Rupee",countries:["Sri Lanka"]},{code:"LRD",number:"430",digits:2,currency:"Liberian Dollar",countries:["Liberia"]},{code:"LSL",number:"426",digits:2,currency:"Loti",countries:["Lesotho"]},{code:"LYD",number:"434",digits:3,currency:"Libyan Dinar",countries:["Libya"]},{code:"MAD",number:"504",digits:2,currency:"Moroccan Dirham",countries:["Morocco","Western Sahara"]},{code:"MDL",number:"498",digits:2,currency:"Moldovan Leu",countries:["Moldova (The Republic Of)"]},{code:"MGA",number:"969",digits:2,currency:"Malagasy Ariary",countries:["Madagascar"]},{code:"MKD",number:"807",digits:2,currency:"Denar",countries:["North Macedonia"]},{code:"MMK",number:"104",digits:2,currency:"Kyat",countries:["Myanmar"]},{code:"MNT",number:"496",digits:2,currency:"Tugrik",countries:["Mongolia"]},{code:"MOP",number:"446",digits:2,currency:"Pataca",countries:["Macao"]},{code:"MRU",number:"929",digits:2,currency:"Ouguiya",countries:["Mauritania"]},{code:"MUR",number:"480",digits:2,currency:"Mauritius Rupee",countries:["Mauritius"]},{code:"MVR",number:"462",digits:2,currency:"Rufiyaa",countries:["Maldives"]},{code:"MWK",number:"454",digits:2,currency:"Malawi Kwacha",countries:["Malawi"]},{code:"MXN",number:"484",digits:2,currency:"Mexican Peso",countries:["Mexico"]},{code:"MXV",number:"979",digits:2,currency:"Mexican Unidad de Inversion (UDI)",countries:["Mexico"]},{code:"MYR",number:"458",digits:2,currency:"Malaysian Ringgit",countries:["Malaysia"]},{code:"MZN",number:"943",digits:2,currency:"Mozambique Metical",countries:["Mozambique"]},{code:"NAD",number:"516",digits:2,currency:"Namibia Dollar",countries:["Namibia"]},{code:"NGN",number:"566",digits:2,currency:"Naira",countries:["Nigeria"]},{code:"NIO",number:"558",digits:2,currency:"Cordoba Oro",countries:["Nicaragua"]},{code:"NOK",number:"578",digits:2,currency:"Norwegian Krone",countries:["Bouvet Island","Norway","Svalbard and Jan Mayen"]},{code:"NPR",number:"524",digits:2,currency:"Nepalese Rupee",countries:["Nepal"]},{code:"NZD",number:"554",digits:2,currency:"New Zealand Dollar",countries:["Cook Islands (The)","New Zealand","Niue","Pitcairn","Tokelau"]},{code:"OMR",number:"512",digits:3,currency:"Rial Omani",countries:["Oman"]},{code:"PAB",number:"590",digits:2,currency:"Balboa",countries:["Panama"]},{code:"PEN",number:"604",digits:2,currency:"Sol",countries:["Peru"]},{code:"PGK",number:"598",digits:2,currency:"Kina",countries:["Papua New Guinea"]},{code:"PHP",number:"608",digits:2,currency:"Philippine Peso",countries:["Philippines (The)"]},{code:"PKR",number:"586",digits:2,currency:"Pakistan Rupee",countries:["Pakistan"]},{code:"PLN",number:"985",digits:2,currency:"Zloty",countries:["Poland"]},{code:"PYG",number:"600",digits:0,currency:"Guarani",countries:["Paraguay"]},{code:"QAR",number:"634",digits:2,currency:"Qatari Rial",countries:["Qatar"]},{code:"RON",number:"946",digits:2,currency:"Romanian Leu",countries:["Romania"]},{code:"RSD",number:"941",digits:2,currency:"Serbian Dinar",countries:["Serbia"]},{code:"RUB",number:"643",digits:2,currency:"Russian Ruble",countries:["Russian Federation (The)"]},{code:"RWF",number:"646",digits:0,currency:"Rwanda Franc",countries:["Rwanda"]},{code:"SAR",number:"682",digits:2,currency:"Saudi Riyal",countries:["Saudi Arabia"]},{code:"SBD",number:"090",digits:2,currency:"Solomon Islands Dollar",countries:["Solomon Islands"]},{code:"SCR",number:"690",digits:2,currency:"Seychelles Rupee",countries:["Seychelles"]},{code:"SDG",number:"938",digits:2,currency:"Sudanese Pound",countries:["Sudan (The)"]},{code:"SEK",number:"752",digits:2,currency:"Swedish Krona",countries:["Sweden"]},{code:"SGD",number:"702",digits:2,currency:"Singapore Dollar",countries:["Singapore"]},{code:"SHP",number:"654",digits:2,currency:"Saint Helena Pound",countries:["Saint Helena, Ascension and Tristan Da Cunha"]},{code:"SLE",number:"925",digits:2,currency:"Leone",countries:["Sierra Leone"]},{code:"SOS",number:"706",digits:2,currency:"Somali Shilling",countries:["Somalia"]},{code:"SRD",number:"968",digits:2,currency:"Surinam Dollar",countries:["Suriname"]},{code:"SSP",number:"728",digits:2,currency:"South Sudanese Pound",countries:["South Sudan"]},{code:"STN",number:"930",digits:2,currency:"Dobra",countries:["Sao Tome and Principe"]},{code:"SVC",number:"222",digits:2,currency:"El Salvador Colon",countries:["El Salvador"]},{code:"SYP",number:"760",digits:2,currency:"Syrian Pound",countries:["Syrian Arab Republic"]},{code:"SZL",number:"748",digits:2,currency:"Lilangeni",countries:["Eswatini"]},{code:"THB",number:"764",digits:2,currency:"Baht",countries:["Thailand"]},{code:"TJS",number:"972",digits:2,currency:"Somoni",countries:["Tajikistan"]},{code:"TMT",number:"934",digits:2,currency:"Turkmenistan New Manat",countries:["Turkmenistan"]},{code:"TND",number:"788",digits:3,currency:"Tunisian Dinar",countries:["Tunisia"]},{code:"TOP",number:"776",digits:2,currency:"Pa’anga",countries:["Tonga"]},{code:"TRY",number:"949",digits:2,currency:"Turkish Lira",countries:["Türki̇ye"]},{code:"TTD",number:"780",digits:2,currency:"Trinidad and Tobago Dollar",countries:["Trinidad and Tobago"]},{code:"TWD",number:"901",digits:2,currency:"New Taiwan Dollar",countries:["Taiwan (Province of China)"]},{code:"TZS",number:"834",digits:2,currency:"Tanzanian Shilling",countries:["Tanzania, United Republic Of"]},{code:"UAH",number:"980",digits:2,currency:"Hryvnia",countries:["Ukraine"]},{code:"UGX",number:"800",digits:0,currency:"Uganda Shilling",countries:["Uganda"]},{code:"USD",number:"840",digits:2,currency:"US Dollar",countries:["American Samoa","Bonaire, Sint Eustatius and Saba","British Indian Ocean Territory (The)","Ecuador","El Salvador","Guam","Haiti","Marshall Islands (The)","Micronesia (Federated States Of)","Northern Mariana Islands (The)","Palau","Panama","Puerto Rico","Timor-Leste","Turks and Caicos Islands (The)","United States Minor Outlying Islands (The)","United States of America (The)","Virgin Islands (British)","Virgin Islands (u.s.)"]},{code:"USN",number:"997",digits:2,currency:"US Dollar (Next day)",countries:["United States of America (The)"]},{code:"UYI",number:"940",digits:0,currency:"Uruguay Peso en Unidades Indexadas (UI)",countries:["Uruguay"]},{code:"UYU",number:"858",digits:2,currency:"Peso Uruguayo",countries:["Uruguay"]},{code:"UYW",number:"927",digits:4,currency:"Unidad Previsional",countries:["Uruguay"]},{code:"UZS",number:"860",digits:2,currency:"Uzbekistan Sum",countries:["Uzbekistan"]},{code:"VED",number:"926",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VES",number:"928",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VND",number:"704",digits:0,currency:"Dong",countries:["Viet Nam"]},{code:"VUV",number:"548",digits:0,currency:"Vatu",countries:["Vanuatu"]},{code:"WST",number:"882",digits:2,currency:"Tala",countries:["Samoa"]},{code:"XAF",number:"950",digits:0,currency:"CFA Franc BEAC",countries:["Cameroon","Central African Republic (The)","Chad","Congo (The)","Equatorial Guinea","Gabon"]},{code:"XAG",number:"961",digits:0,currency:"Silver",countries:["Zz11_silver"]},{code:"XAU",number:"959",digits:0,currency:"Gold",countries:["Zz08_gold"]},{code:"XBA",number:"955",digits:0,currency:"Bond Markets Unit European Composite Unit (EURCO)",countries:["Zz01_bond Markets Unit European_eurco"]},{code:"XBB",number:"956",digits:0,currency:"Bond Markets Unit European Monetary Unit (E.M.U.-6)",countries:["Zz02_bond Markets Unit European_emu-6"]},{code:"XBC",number:"957",digits:0,currency:"Bond Markets Unit European Unit of Account 9 (E.U.A.-9)",countries:["Zz03_bond Markets Unit European_eua-9"]},{code:"XBD",number:"958",digits:0,currency:"Bond Markets Unit European Unit of Account 17 (E.U.A.-17)",countries:["Zz04_bond Markets Unit European_eua-17"]},{code:"XCD",number:"951",digits:2,currency:"East Caribbean Dollar",countries:["Anguilla","Antigua and Barbuda","Dominica","Grenada","Montserrat","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines"]},{code:"XDR",number:"960",digits:0,currency:"SDR (Special Drawing Right)",countries:["International Monetary Fund (Imf) "]},{code:"XOF",number:"952",digits:0,currency:"CFA Franc BCEAO",countries:["Benin","Burkina Faso","Côte D'ivoire","Guinea-Bissau","Mali","Niger (The)","Senegal","Togo"]},{code:"XPD",number:"964",digits:0,currency:"Palladium",countries:["Zz09_palladium"]},{code:"XPF",number:"953",digits:0,currency:"CFP Franc",countries:["French Polynesia","New Caledonia","Wallis and Futuna"]},{code:"XPT",number:"962",digits:0,currency:"Platinum",countries:["Zz10_platinum"]},{code:"XSU",number:"994",digits:0,currency:"Sucre",countries:['Sistema Unitario De Compensacion Regional De Pagos "Sucre"']},{code:"XTS",number:"963",digits:0,currency:"Codes specifically reserved for testing purposes",countries:["Zz06_testing_code"]},{code:"XUA",number:"965",digits:0,currency:"ADB Unit of Account",countries:["Member Countries of the African Development Bank Group"]},{code:"XXX",number:"999",digits:0,currency:"The codes assigned for transactions where no currency is involved",countries:["Zz07_no_currency"]},{code:"YER",number:"886",digits:2,currency:"Yemeni Rial",countries:["Yemen"]},{code:"ZAR",number:"710",digits:2,currency:"Rand",countries:["Lesotho","Namibia","South Africa"]},{code:"ZMW",number:"967",digits:2,currency:"Zambian Kwacha",countries:["Zambia"]},{code:"ZWG",number:"924",digits:2,currency:"Zimbabwe Gold",countries:["Zimbabwe"]}]),iy}var ay,w2;function MQ(){return w2||(w2=1,ay="2024-06-25"),ay}var C2;function _Q(){if(C2)return Xa;C2=1;var r=RQ(),e=OQ(),t=BQ(),n=MQ(),i=function(c){return c=c.toUpperCase(),r(t,function(f){return f.code===c})},a=function(c){return c=c.toLowerCase(),t.filter(function(f){return(f.countries.map(function(d){return d.toLowerCase()})||[]).indexOf(c)>-1})},s=function(c){return r(t,function(f){return f.number===String(c)})},o=function(){return t.map(function(c){return c.code})},l=function(){var c=t.map(function(f){return f.number});return c.filter(function(f){if(f)return f})},u=function(){var c=t.filter(function(f){return f.countries}).map(function(f){return f.countries});return e(Array.prototype.concat.apply([],c))};return Xa.code=i,Xa.country=a,Xa.number=s,Xa.codes=o,Xa.numbers=l,Xa.countries=u,Xa.publishDate=n,Xa.data=t,Xa}var x2=_Q();class MP{formatCurrencyForDisplay(e,t){const n={amount:t||0,currency:e,precision:this.getPrecisionForCurrency(e)};return DQ(n).toFormat(this.getSpecialFormat(e))}getPrecisionForCurrency(e){const t=e,n=x2.code(t);return n?n.digits:2}getSpecialFormat(e){const t=e;if(x2.code(t)?.code==="CLP")return"USD0,0"}}const S2=new MP;class _P{constructor(e,t,n,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,this.partnerCurrency=n,this.rateFrom=e,this.rateTo=t}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(e){return this.conversionRequired()?Math.ceil(this.subunits(this.units(e,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):e}units(e,t){return e/Math.pow(10,S2.getPrecisionForCurrency(t))}subunits(e,t){return e*Math.pow(10,S2.getPrecisionForCurrency(t))}}const NQ=async(r,e)=>{const t=q3(e?.assets?.metadata||!1),n={ids:r};console.log("[getWorkflowsInternal] Requesting workflows.",{url:`${ss.getServerUrl()}/graphql`,variables:JSON.stringify(n)}),console.log(`[getWorkflowsInternal] Query:
3056
- ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:"all",variables:n,context:{logRequestHeaders:!0}});if(i.error)throw console.log("[getWorkflowsInternal] Response errored."),i.error;if(i.errors)throw i.errors.forEach(s=>console.error(s)),new Error("Unable to read workflows. Consult GraphQL errors.");if(!i.data.workflows||i.data.workflows.length!==r.length)throw new Error(`Unable to read workflows: ${i.errors??"Length mismatch in response"}`);const a=mo(i.data.workflows);return a.forEach(s=>{s.finalizeStepConfig||(s.finalizeStepConfig={}),s.finalizeStepConfig.termsMarkdown=s.finalizeStepConfig.termsMarkdown||s.partner.termsMarkdown}),a},LQ=async(r,e)=>{const n=(await e).find(i=>i.id===r);if(!n)throw new Error(`Workflow not found: ${r}`);return n},ew=async(r,e)=>{const t=r.map(o=>mf.get({id:o,options:e})),n=r.filter((o,l)=>t[l]===void 0);if(n.length===0)return Promise.all(t);const i=NQ(n,e),a=n.map(o=>mf.set({id:o,options:e},LQ(o,i))),s=t.filter(o=>o!==void 0);return await Promise.all(s.concat(a))},NP=async(r,e)=>(await ew([r],e))[0],LP=async r=>{const e=await ze.getShadowGraphqlClient().query({query:yT,variables:{ids:r},errorPolicy:"all",fetchPolicy:"no-cache"});return e.errors&&console.error(e.errors),e.data.integrationProducts||[]};class UQ{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return ze.getShadowGraphqlClient().mutate({...t,mutation:D3})}catch(n){throw console.error(n),new lo("Critical - Unable to synchronize workflow state with server.")}},this.options=e,this.options.applicationKey&&Yk(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 44.5.5-alpha.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(e){ss.setHubUrl(e.hubUrl),ss.setServerUrl(e.serverUrl),ss.setServicesApiUrl(e.servicesApiUrl),this.marketplaceThemeInstallId=e.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=e.marketplaceThemeInstallConfigurationId,this.userPoolClientId=e.userPoolClientId,this.userPoolRegion=e.userPoolRegion,this.spiffRegion=e.spiffRegion,e.bearerAuthenticationToken&&Jk(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Id.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getVersion(){return"44.5.5-alpha.2"}getAssetManager(){return Ln}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!J4())throw new Error("Application key required to use Flow Service.");return new BI}async getCurrencyContext(e){const n=(await this.getIntegration()).partner.currencyCode,a=await ze.getShadowGraphqlClient().query({query:K3,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:e}}),{rateFrom:s,rateTo:o}=a.data.currencyConversion;return new _P(s,o,n,e)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=UP(this.options.applicationKey),this.activeIntegration}async canUseAddon(e){try{return(await this.getIntegration()).partner.activeAddons?.includes(e)??!1}catch(t){return console.error(t),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(e){const t=wr.getMap("transactionCustomerIds");t?.has(e)&&(t.delete(e),wr.setMap("transactionCustomerIds",t))}async customerHasBundleTemplates(e){const i=(await ze.getShadowGraphqlClient().query({query:Ov,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(e){const t=this.customer?.stakeholders?.find(n=>n.transaction?.id===e);if(t)return t.type}async getOrCreateCustomer(e){this.customer=void 0;const t=ze.getShadowGraphqlClient(),i=(await t.query({query:Ov,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!i.id){const o=(await t.mutate({mutation:yV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:e}}})).data?.customerCreate;if(!o)throw new Error("Unable to create customer.");return this.storeCustomer(o),this.customer=o,{customer:o,isAuthenticated:!1}}this.storeCustomer(i);const a=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:a}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens"),n=localStorage.getItem("cognito-email");if(!e||!t||!n)return!1;const i=JSON.parse(t),a=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<a-parseInt(e)){const u=await Id.refreshTokens();if(u?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=u.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=localStorage.getItem("customer-login-token");s&&p0(s);const l=(await ze.getShadowGraphqlClient().query({query:Ov,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:n}})).data.customer;return l.id?(this.customer=l,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(e){await ze.getShadowGraphqlClient().mutate({mutation:AV,variables:{emailAddress:e}}),await Id.generateCode(e)}async verifyCode(e,t){const n=(await this.getIntegration()).partner.id||"",i=await Id.verifyCode(e,t,n);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",e);const s=(await ze.getShadowGraphqlClient().mutate({mutation:bV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e,verificationCode:t}})).data?.customerVerifyCode;if(!s?.id)throw new Error("Failed to get customer.");return this.customer=s,s.loginToken&&(localStorage.setItem("customer-login-token",s.loginToken),p0(s.loginToken)),!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),localStorage.removeItem("customer-login-token"),p0(""),this.clearCustomer()}async loggedInBearerToken(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens");if(!e||!t)throw new Error("No token data in storage.");const n=JSON.parse(t),i=new Date().getTime()/1e3,a=!n?.AccessToken||vg(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(e)||a){const s=await Id.refreshTokens();if(s?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!n.AccessToken)throw new Error("No bearer token in storage.");return n.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await ze.getShadowGraphqlClient().query({query:wV,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(e,t,n,i){const s=(await ze.getShadowGraphqlClient().mutate({mutation:r9(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((c,f)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,activationId:i,test:n?.test},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!s?.id)throw new Error("Unable to create bundle");const o=wr.getMap("bundlePartnerIds")||new Map;o.set(s.id,s.partner.id),wr.setMap("bundlePartnerIds",o);const l=wr.getMap("bundleOwnerIds")||new Map;l.set(s.id,s.bundleOwnerId),wr.setMap("bundleOwnerIds",l);const u=new DE(this,s,void 0,void 0,s.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts});return await u.getInitializationPromise(),u}async getExistingBundle(e,t,n,i,a){const o=wr.getMap("bundleOwnerIds")?.get(e),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const y=Object.entries(localStorage).find(([C,S])=>C.startsWith("CognitoIdentityServiceProvider")&&C.endsWith("idToken"))?.[0]||"",A=localStorage.getItem(y);A&&!vg(A)&&(l.Authorization=`Bearer ${A}`)}const u={bundleOwnerId:o,...l,...i?.graphql?.additionalHeaders},c=await ze.getShadowGraphqlClient().query({query:KU(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:e},fetchPolicy:"no-cache",context:{headers:u}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${e}`);const f=c.data?.bundles[0],d=wr.getMap("bundlePartnerIds")||new Map;d.set(f.id,f.partner.id),wr.setMap("bundlePartnerIds",d);const h=new DE(this,f,t,n,o,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:i?.readonly},a);return await h.getInitializationPromise(),h}async duplicateBundle(e,t,n,i){const s={...await $P(e),...i?.graphql?.additionalHeaders},l=(await ze.getShadowGraphqlClient().mutate({mutation:n9(),variables:{id:e,template:t,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n,test:i?.test},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const u=wr.getMap("bundlePartnerIds")||new Map;u.set(l.id,l.partner.id),wr.setMap("bundlePartnerIds",u);const c=wr.getMap("bundleOwnerIds")||new Map;return c.set(l.id,l.bundleOwnerId),wr.setMap("bundleOwnerIds",c),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(e){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:t,...n}=e;return(await ze.getShadowGraphqlClient().query({query:p9(t??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const e=await ze.getShadowGraphqlClient().query({query:ZU,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!e.data?.customers||e.data.customers.length===0)throw new Error("Unable to find customer.");const n=e.data.customers[0].bundleStakeholders||[],i=wr.getMap("bundlePartnerIds")||new Map;return n.forEach(a=>{a.bundle?.id&&a.bundle.partner?.id&&i.set(a.bundle.id,a.bundle.partner.id)}),wr.setMap("bundlePartnerIds",i),n}async getWorkflowExperience(e,t){if(!e)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const n=await this.getWorkflowExperiences([e],e.graphql),i=n[0],a=i.getWorkflow();return t&&!a&&console.error("No workflow instantiated when trying to create preview service."),t&&a&&await i.getWorkflowManager().injectIntoPreviewService(t(a)),n[0]}async getWorkflowExperiences(e,t,n,i){if(e.length===0)throw new lo("No options provided!");const a=e.map((q,Y)=>({option:q,index:Y})),s=a.filter(q=>q.option.type==="transaction"),o=a.filter(q=>q.option.type==="integration"||q.option.type==="external"||q.option.type==="blank"),l=50,u=fA(s,l),c=fA(o,l);let f=0;const d=ze.getShadowGraphqlClient(),h=async q=>{if(q.length===0)return[];const Y=q.map(oe=>oe.option.transactionId),J=await d.query({query:P3,variables:{ids:Y},errorPolicy:"all",fetchPolicy:"no-cache"}),ae=J.data.transactions;if(f=f+ae.length,i&&i(f,s.length),ae.length!==q.length){const oe=J.errors?.[0]?.message||"Unknown error";throw new lo(`Not all transactions were found: ${oe}`)}return!this.activeIntegration&&ae[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(ae[0].integrationProduct.integration)),ae.map((oe,he)=>({transaction:oe,workflowId:oe.workflowId,readOnly:q.find(ye=>ye.option.transactionId===oe.id)?.option.readOnly??!1,index:q[he].index}))},g=async q=>{if(q.length===0)return[];const Y=await d.mutate({mutation:I3,variables:{inputs:q.map(ae=>({integrationProductId:ae.option.type==="integration"?ae.option.integrationProductId:void 0,externalIntegrationId:ae.option.type==="external"?ae.option.externalIntegrationId:void 0,externalProductId:ae.option.type==="external"?ae.option.externalProductId:void 0,workflowId:ae.option.workflowId,designName:ae.option.designName,claim:!0,quantity:ae.option.quantity,recipient:ae.option.recipient,parentTransactionId:ae.option.parentTransactionId})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.getCreateTransactionContext(q,t)}),J=Y.data?.transactionCreateMany;if(!J||J.length===0){const ae=Y.errors?.[0]?.message||"Unknown error";throw new lo(`Failed to create transactions: ${ae}`)}return f=f+J.length,i&&i(f,s.length),J.map((ae,oe)=>({transaction:ae,workflowId:ae.workflowId,readOnly:!1,index:q[oe].index}))},v=(await Promise.all([...u.map(h),...c.map(g)])).flat();let y=[...new Set(v.map(q=>q.transaction.integrationProductId))].filter(q=>!!q);y=y.filter(q=>!!q);let A=[...new Set(v.map(q=>q.workflowId))].filter(q=>!!q);A=A.filter(q=>!!q);const[C,S]=await Promise.all([(async()=>y.length>0?await LP(y):[])(),(async()=>A.length>0?await ew(A,t):[])()]),F=new Map(C.map(q=>[q.id,q])),E=new Map(S.map(q=>[q.id,q])),R=v.map(async q=>{const{transaction:Y,workflowId:J,readOnly:ae,index:oe}=q,he=J?E.get(J):void 0,ye=e[oe];if(Y.integrationProductId){const re=F.get(Y.integrationProductId);Y.integrationProduct=re,Y.product=re?.product,Y.integrationProduct||console.error("failed to find transaction's product")}const Ue=wr.getMap("transactionOwnerIds")||new Map;!Ue.get(Y.id)&&Y.transactionOwnerId&&(Ue.set(Y.id,Y.transactionOwnerId),wr.setMap("transactionOwnerIds",Ue));const Re=Ue.get(Y.id)||void 0,Oe=new CV({onMutate:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}})}),ee={workflow:he,transaction:Y,singleVariantsRenderable:ye?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:ae?async()=>{throw new nn("State mutation is forbidden in read only mode!")}:async re=>this.updateTransactionState({...re,context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),graphQlClient:()=>Oe,readOnly:ae,isReloadedTransaction:ye.type==="transaction"};if(ye.type==="transaction"&&Y.workflowState){const re=JSON.parse(Y.workflowState);await sA(re),ee.reloadedState=re}else if(!ae&&ye.workflowState){const re=JSON.parse(ye.workflowState);await sA(re),ee.reloadedState=re}return ee.delayWorkflowStateSync=!0,{experienceOptions:ee,index:oe,options:ye}}),j=(await Promise.all(R)).sort((q,Y)=>q.index-Y.index);let G=[],ie=[];for(const q of j){const{experienceOptions:Y,options:J}=q,ae=new B1(this,Y);await ae.getWorkflowManager().getInitializationPromise(),n&&n(),J.type!=="transaction"&&this.customer&&ie.push(ae),G=[...G,ae],ae.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}if(ie.length>0){const q=this.customer.emailAddress,Y=ie.map(oe=>oe.getTransaction().id),ae=(await d.mutate({mutation:q9,variables:{ids:Y,details:{emailAddress:q},type:"Owner"},errorPolicy:"all"})).data?.transactionsAddStakeholder;if(ae&&ae?.length>0){const oe=ae[0].stakeholders?.find(he=>he.customer?.emailAddress===q);if(oe?.customer)for(const he of ie)he.assignCustomerInternal(oe.customer)}}return G}getCreateTransactionContext(e,t){const n=e.find(s=>s.option.parentTransactionId)?.option.parentTransactionId;if(!n&&!t?.bundleOwnerId)return;const i=wr.getMap("transactionOwnerIds")||new Map,a=n?i.get(n):void 0;return{...a?{transactionOwnerId:a}:{},...t?.bundleOwnerId?{bundleOwnerId:t.bundleOwnerId}:{}}}storeCustomer(e){const t=wr.getMap("partnerCustomerIds")||new Map;t.set(e.partner.id,e.id),wr.setMap("partnerCustomerIds",t)}async getIntegrationProductById(e,t){const a=(await ze.getShadowGraphqlClient().query({query:L3(t),variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!a||a.length===0||!a[0]?.id)throw new Error("Integration product not found.");return new gA(a[0])}async getIntegrationProductFromExternalIds(e,t,n){const s=(await ze.getShadowGraphqlClient().query({query:U3(n),variables:{externalProductId:t,externalIntegrationId:e},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!s?.id)throw new Error("Integration product not found.");return new gA(s)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}async getShareActionsForTransaction(e){const n=(wr.getMap("transactionOwnerIds")||new Map).get(e)||void 0,i=await ze.getShadowGraphqlClient().query({query:_3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e},context:{transactionOwnerId:n}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${e}`);return i.data.transactions[0].transactionShareActions}async placeOrder(e){const t=await ze.getShadowGraphqlClient().mutate({mutation:J3,variables:{orderItems:e}});if(t.errors)throw new Error(t.errors[0].message);if(!t.data)throw new Error("Failed to create order: No order data in response.");return{id:t.data.orderCreate.id,internalId:t.data.orderCreate.internalId}}}const UP=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:Q3,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r},skipIntegrationCheck:!0},variables:{themeConfigurationId:e}})).data.currentIntegration,VQ=async r=>{const t=await ze.getShadowGraphqlClient().query({query:M3,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(t.data.transactions.length!==0)return t.data.transactions[0]},zQ=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:W3,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:e}})).data?.marketplaceThemeInstallConfiguration,$Q=async r=>(await ze.getShadowGraphqlClient().query({query:X3,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,HQ=async r=>(await ze.getShadowGraphqlClient().query({query:Y3,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,VP=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:aM(!!e),errorPolicy:"all",variables:{id:r,productIds:e}})).data?.activation,jQ=async r=>(await VP(r))?.marketplaceThemeInstallConfiguration;async function zP(){const r={};try{const e=await this.loggedInBearerToken();r.Authorization=`Bearer ${e}`}catch{const n=Object.entries(localStorage).find(([a,s])=>a.startsWith("CognitoIdentityServiceProvider")&&a.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(n);i&&!vg(i)&&(r.Authorization=`Bearer ${i}`)}return r}async function $P(r){const t=wr.getMap("bundleOwnerIds")?.get(r),n=await zP();return{bundleOwnerId:t,...n}}async function GQ(r){const t=wr.getMap("transactionOwnerIds")?.get(r),n=await zP();return{transactionOwnerId:t,...n}}const qQ=async r=>{const e=await $P(r),t=await ze.getShadowGraphqlClient().mutate({mutation:x9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r},context:{headers:e}});if(t.data?.bundleDelete!==r)throw new Error(`Failed to delete bundle: ${t.errors}`)},WQ=async r=>{const e=await GQ(r),t=await ze.getShadowGraphqlClient().mutate({mutation:S9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[r]},context:{headers:e}});if(!t.data?.transactions||t.data.transactions.length!==1||t.data.transactions[0].id!==r)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(t.errors)}`);return t.data.transactions[0].bundle?.id};function HP(r,e,t,n){const i=t.width*r.zoom,a=t.height*r.zoom;if(n){const s=Math.max(e.width/t.width,e.height/t.height),o=Math.max(s,r.zoom),l=t.width*o,u=t.height*o;return{...r,x:Dp(r.x,e.width-l,0),y:Dp(r.y,e.height-u,0),zoom:o}}return{...r,x:Dp(r.x,-i,e.width),y:Dp(r.y,-a,e.height)}}function Dp(r,e,t){return Math.min(Math.max(r,e),t)}class jP{constructor(e,t){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=FI(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.onRotationChangeListeners=[],this.forceImageCover=e,this.initialZoom=t,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(e,t){t&&e.addStepSpecificStorageCallback(async n=>{if(n){const i=n;if(i.currentFrameSources){let a=!1;for(let s=0;s<i.currentFrameSources.length;s++){const o=i.currentFrameSources[s],l=await Xf(o),u=this.frameData?this.frameData[s]:void 0;vf(l,u)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[s]=l,a=!0)}a&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},t),this.workflowManager=e,this.stepName=t}setTargetElements(e){this.targetElements=e}getFrameData(){return this.frameData}setFrameData(e){if(!e){this.frameData=void 0;return}e.forEach((t,n)=>{const i=_u.get(t);i&&(this.frameData||(this.frameData=new Array(e.length)),this.frameData[n]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const e=zg(this.imageData.svg,this.imageData.colors||{},!1);return Ug(e)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(e){this.offsets=e}setZoom(e,t,n,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const a=this.frameData.map((s,o)=>{const l=(t[o]-this.offsets[o].x)/this.offsets[o].zoom,u=(n[o]-this.offsets[o].y)/this.offsets[o].zoom,c=t[o]-l*e[o],f=n[o]-u*e[o];return{x:c,y:f,zoom:this.imageData.width*e[o]/this.imageData.width,rotation:this.offsets[o].rotation}});this.updateOffsets(a,i),this.onZoomChangeListeners.forEach(s=>s(e))}}setRotation(e,t){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const n=this.frameData.map((i,a)=>({...this.offsets[a],rotation:e[a]}));this.updateOffsets(n,t),this.onRotationChangeListeners.forEach(i=>i(e))}}setPatternData(e,t=!0){this.imageData=e,e&&this.frameData&&((t||!this.offsets)&&this.recalculateOffsets(e,t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(e,t,n){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==e.length)throw new nn("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(e[o].x===s.x&&e[o].y===s.y&&e[o].zoom===s.zoom&&e[o].rotation===s.rotation))&&!n){t&&t();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=HP(e[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.thresholdSettings,t)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(e){this.thresholdSettings=e,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,e)}onFrameDataChanged(e){e(this.frameData),this.onFrameDataChangeListeners.push(e)}onZoom(e){this.onZoomChangeListeners.push(e)}onRotation(e){this.onRotationChangeListeners.push(e)}updateFrameOffsets(e,t,n,i,a){if(!n||n.length===0||n.some(l=>!l))throw new nn("Frame data not set. This is a bug");if(!this.workflowManager)throw new nn("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getRegionElements(this.stepName||""),o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,u)=>{let c=s.find(f=>f.id===l)?.regionIndex??u;c>=e.length&&(c=u);try{o(new On([new wL(l,t,e[c]),new CL(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}catch{}}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:e}),a&&a()}recalculateZoomLimits(e,t){(this.minZoomScale.length!==t.length||this.maxZoomScale.length!==t.length)&&(this.minZoomScale=new Array(t.length),this.maxZoomScale=new Array(t.length)),t.forEach((n,i)=>{const a=Math.max(n.width/e.width,n.height/e.height);this.forceImageCover?(this.minZoomScale[i]=a,this.maxZoomScale[i]=a*2.5):(this.minZoomScale[i]=a/10,this.maxZoomScale[i]=a*2.5)})}recalculateOffsets(e,t=!0){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((n,i)=>{const a=t?0:this.offsets[i]?.rotation||0;this.offsets[i]={...C1(e,n,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover),rotation:a}}),this._debouncedUpdateFrameOffsets(this.offsets,e,this.frameData,this.thresholdSettings))}}class QQ{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,v,y,A){throw new Error("Method not implemented.")}approveTransaction(e){throw new Error("Method not implemented.")}rejectTransaction(e){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(e){this.client=e}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(e){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,n){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}injectIntoPreviewService(e){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(e){}async updateTransactionShareActions(){}addValidationCallback(e){}setStepError(e,t,n){}getStepErrors(e){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(e){return[]}}var GP=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(GP||{}),qP=(r=>(r.Original="original",r.BackgroundRemoved="backgroundRemoved",r.Optimized="optimized",r))(qP||{});class WP extends Ui{constructor(e,t,n){super(e,t,n);const i=t.data;this.frameService=new jP(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(e,t.stepName)}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return so.selectVariant(this.step,e.getResource(),t,this.manager,n=>this.setUpdateState(n))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}async selectImage(e,t=!0,n=!0){await so.selectImage(this.step,e,this.manager,n),t&&this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,enhancedAssetKey:void 0,useOriginalAsset:void 0}})}async canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Bg.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImageSelection();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const n=await Ln.removeBackgroundFromAsset(t);e&&await so.selectImage(this.step,n,this.manager,!1);const i=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:n.key,useOriginalAsset:!e}}),n}async vectorize(e,t=void 0){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to vectorize the image.");const i=await Ln.vectorizeAsset(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,vectorizedAssetKey:i.key,useOriginalAsset:!1}}),i}async enhanceWithAI(e,t){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to enhance the image with AI.");const i=await Ln.enhanceWithAI(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:a.originalAssetKey,backgroundRemovedAssetKey:a.backgroundRemovedAssetKey,vectorizedAssetKey:a.vectorizedAssetKey,enhancedAssetKey:i.key,useOriginalAsset:!1}}),i}async getBackgroundRemovedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getVectorizedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getEnhancedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}hasOriginalImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}hasEnhancedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey}async changeColors(e){await so.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?so.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e?.svg?(await Pa(e.svg)).colors:void 0}async mergeColors(e,t,n){const i=this.frameService.getImageData();if(!i?.svg||!i.colors)throw new Error("Cannot merge colors on non-SVG image or image without color information");const{svg:a,colors:s}=fT(i.svg,i.colors,e,t,n);this.frameService.setPatternData({...i,svg:a,colors:s},!1),this.manager.updateStorage(this.step.stepName,{colors:s})}async unmergeColors(e,t,n,i){const a=this.frameService.getImageData();if(!a?.svg||!a.colors)throw new Error("Cannot unmerge colors on non-SVG image or image without color information");this.frameService.setPatternData({...a,svg:i,colors:n},!1),this.manager.updateStorage(this.step.stepName,{colors:n})}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMinimumPixelThresholdForOptimization(){return this.step.data.vectorizationMinimumPixelThreshold}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return so.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(e,t,n,i){return i&&i.length>1&&e===void 0?"SelectFrame":t||n||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.originalAssetKey;if(e)return Ln.getLocalOrFromServer(e)}getCurrentImageState(){const e=this.getFrameStepStorage()?.framePatternData;return e?e.vectorizedAssetKey&&!e.useOriginalAsset?"optimized":e.useOriginalAsset!==!1?"original":"backgroundRemoved":"original"}async setImageState(e){const t=this.getFrameStepStorage()?.framePatternData||{};let n,i;switch(e){case"original":if(n=await this.getOriginalImageSelection(),!n)throw new Error("No original image available");i=!0;break;case"backgroundRemoved":if(n=await this.getBackgroundRemovedImageSelection(),!n)throw new Error("No background-removed image available. Call removeBackgroundFromImageSelection first.");i=!1;break;case"optimized":if(n=await this.getVectorizedImageSelection(),!n)throw new Error("No optimized image available. Call vectorize first.");i=!1;break}await this.selectImage(n,!1,!0),this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:i}})}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(e){const t=this.getFrameStepStorage()?.framePatternData||{};if(t.useOriginalAsset===e)return;const n=await this.getOriginalImageSelection();if(!n)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(e)await this.selectImage(n,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:e}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const YQ=Se`
3053
+ ${Ao(s)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){const t=[];for(const a of e.split("/"))a?.length!==0&&a!=="."&&(a===".."?t.pop():t.push(a));const n=`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`;return Cl(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){const t=uj(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}const Fp={},Wv=[],Qv=(r,e,t)=>`${r}/${e}/${t}/${gP}`,fj=async(r,e,t,n,i)=>{const a=await e2(r,e.secretAccessKey,e.accessKeyId),s=`${t}:${n}:${i}:${Ao(a)}:${e.sessionToken}`;if(s in Fp)return Fp[s];for(Wv.push(s);Wv.length>sj;)delete Fp[Wv.shift()];let o=`AWS4${e.secretAccessKey}`;for(const l of[t,n,i,gP])o=await e2(r,o,l);return Fp[s]=o},e2=(r,e,t)=>{const n=new r(e);return n.update(kf(t)),n.digest()},t2=({headers:r},e,t)=>{const n={};for(const i of Object.keys(r).sort()){if(r[i]==null)continue;const a=i.toLowerCase();(a in tj||e?.has(a)||rj.test(a)||nj.test(a))&&(!t||t&&!t.has(a))||(n[a]=r[i].trim().replace(/\s+/g," "))}return n},Yv=async({headers:r,body:e},t)=>{for(const n of Object.keys(r))if(n.toLowerCase()===CA)return r[n];if(e==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof e=="string"||ArrayBuffer.isView(e)||Cz(e)){const n=new t;return n.update(kf(e)),Ao(await n.digest())}return aj},hj=(r,e)=>{r=r.toLowerCase();for(const t of Object.keys(e))if(r===t.toLowerCase())return!0;return!1},pj=(r,e={})=>{const{headers:t,query:n={}}=na.clone(r);for(const i of Object.keys(t)){const a=i.toLowerCase();(a.slice(0,6)==="x-amz-"&&!e.unhoistableHeaders?.has(a)||e.hoistableHeaders?.has(a))&&(n[i]=t[i],delete t[i])}return{...r,headers:t,query:n}},r2=r=>{r=na.clone(r);for(const e of Object.keys(r.headers))KH.indexOf(e.toLowerCase())>-1&&delete r.headers[e];return r};class n2 extends dj{headerFormatter=new GH;constructor({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s})}async presign(e,t={}){const{signingDate:n=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:o,hoistableHeaders:l,signingRegion:u,signingService:c}=t,f=await this.credentialProvider();this.validateResolvedCredentials(f);const d=u??await this.regionProvider(),{longDate:h,shortDate:g}=this.formatDate(n);if(i>oj)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const v=Qv(g,d,c??this.service),y=pj(r2(e),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(y.query[fP]=f.sessionToken),y.query[WH]=qv,y.query[QH]=`${f.accessKeyId}/${v}`,y.query[cP]=h,y.query[XH]=i.toString(10);const A=t2(y,a,o);return y.query[YH]=this.getCanonicalHeaderList(A),y.query[dP]=await this.getSignature(h,v,this.getSigningKey(f,d,g,c),this.createCanonicalRequest(y,A,await Yv(e,this.sha256))),y}async sign(e,t){return typeof e=="string"?this.signString(e,t):e.headers&&e.payload?this.signEvent(e,t):e.message?this.signMessage(e,t):this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:n=new Date,priorSignature:i,signingRegion:a,signingService:s,eventStreamCredentials:o}){const l=a??await this.regionProvider(),{shortDate:u,longDate:c}=this.formatDate(n),f=Qv(u,l,s??this.service),d=await Yv({headers:{},body:t},this.sha256),h=new this.sha256;h.update(e);const g=Ao(await h.digest()),v=[ij,c,f,i,g,d].join(`
3054
+ `);return this.signString(v,{signingDate:n,signingRegion:l,signingService:s,eventStreamCredentials:o})}async signMessage(e,{signingDate:t=new Date,signingRegion:n,signingService:i,eventStreamCredentials:a}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:n,signingService:i,priorSignature:e.priorSignature,eventStreamCredentials:a}).then(o=>({message:e.message,signature:o}))}async signString(e,{signingDate:t=new Date,signingRegion:n,signingService:i,eventStreamCredentials:a}={}){const s=a??await this.credentialProvider();this.validateResolvedCredentials(s);const o=n??await this.regionProvider(),{shortDate:l}=this.formatDate(t),u=new this.sha256(await this.getSigningKey(s,o,l,i));return u.update(kf(e)),Ao(await u.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:n,unsignableHeaders:i,signingRegion:a,signingService:s}={}){const o=await this.credentialProvider();this.validateResolvedCredentials(o);const l=a??await this.regionProvider(),u=r2(e),{longDate:c,shortDate:f}=this.formatDate(t),d=Qv(f,l,s??this.service);u.headers[pP]=c,o.sessionToken&&(u.headers[ej]=o.sessionToken);const h=await Yv(u,this.sha256);!hj(CA,u.headers)&&this.applyChecksum&&(u.headers[CA]=h);const g=t2(u,i,n),v=await this.getSignature(c,d,this.getSigningKey(o,l,f,s),this.createCanonicalRequest(u,g,h));return u.headers[hP]=`${qv} Credential=${o.accessKeyId}/${d}, SignedHeaders=${this.getCanonicalHeaderList(g)}, Signature=${v}`,u}async getSignature(e,t,n,i){const a=await this.createStringToSign(e,t,i,qv),s=new this.sha256(await n);return s.update(kf(a)),Ao(await s.digest())}getSigningKey(e,t,n,i){return fj(this.sha256,e,n,t,i||this.service)}}const gj=r=>{let e=r.credentials,t=!!r.credentials,n;Object.defineProperty(r,"credentials",{set(u){u&&u!==e&&u!==n&&(t=!0),e=u;const c=mj(r,{credentials:e,credentialDefaultProvider:r.credentialDefaultProvider}),f=vj(r,c);if(t&&!f.attributed){const d=typeof e=="object"&&e!==null;n=async h=>{const v=await f(h);return d&&(!v.$source||Object.keys(v.$source).length===0)?EV(v,"CREDENTIALS_CODE","e"):v},n.memoized=f.memoized,n.configBound=f.configBound,n.attributed=!0}else n=f},get(){return n},enumerable:!0,configurable:!0}),r.credentials=e;const{signingEscapePath:i=!0,systemClockOffset:a=r.systemClockOffset||0,sha256:s}=r;let o;return r.signer?o=tf(r.signer):r.regionInfoProvider?o=()=>tf(r.region)().then(async u=>[await r.regionInfoProvider(u,{useFipsEndpoint:await r.useFipsEndpoint(),useDualstackEndpoint:await r.useDualstackEndpoint()})||{},u]).then(([u,c])=>{const{signingRegion:f,signingService:d}=u;r.signingRegion=r.signingRegion||f||c,r.signingName=r.signingName||d||r.serviceId;const h={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:s,uriEscapePath:i},g=r.signerConstructor||n2;return new g(h)}):o=async u=>{u=Object.assign({},{name:"sigv4",signingName:r.signingName||r.defaultSigningName,signingRegion:await tf(r.region)(),properties:{}},u);const c=u.signingRegion,f=u.signingName;r.signingRegion=r.signingRegion||c,r.signingName=r.signingName||f||r.serviceId;const d={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:s,uriEscapePath:i},h=r.signerConstructor||n2;return new h(d)},Object.assign(r,{systemClockOffset:a,signingEscapePath:i,signer:o})};function mj(r,{credentials:e,credentialDefaultProvider:t}){let n;return e?e?.memoized?n=e:n=fH(e,dH,aP):t?n=tf(t(Object.assign({},r,{parentClientConfig:r}))):n=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},n.memoized=!0,n}function vj(r,e){if(e.configBound)return e;const t=async n=>e({...n,callerClientConfig:r});return t.memoized=e.memoized,t.configBound=!0,t}const yj=async(r,e,t)=>({operation:vc(e).operation,region:await Bs(r.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function Aj(r){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-idp",region:r.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function Ur(r){return{schemeId:"smithy.api#noAuth"}}const bj=r=>{const e=[];switch(r.operation){case"AssociateSoftwareToken":{e.push(Ur());break}case"ChangePassword":{e.push(Ur());break}case"CompleteWebAuthnRegistration":{e.push(Ur());break}case"ConfirmDevice":{e.push(Ur());break}case"ConfirmForgotPassword":{e.push(Ur());break}case"ConfirmSignUp":{e.push(Ur());break}case"DeleteUser":{e.push(Ur());break}case"DeleteUserAttributes":{e.push(Ur());break}case"DeleteWebAuthnCredential":{e.push(Ur());break}case"ForgetDevice":{e.push(Ur());break}case"ForgotPassword":{e.push(Ur());break}case"GetDevice":{e.push(Ur());break}case"GetTokensFromRefreshToken":{e.push(Ur());break}case"GetUser":{e.push(Ur());break}case"GetUserAttributeVerificationCode":{e.push(Ur());break}case"GetUserAuthFactors":{e.push(Ur());break}case"GlobalSignOut":{e.push(Ur());break}case"InitiateAuth":{e.push(Ur());break}case"ListDevices":{e.push(Ur());break}case"ListWebAuthnCredentials":{e.push(Ur());break}case"ResendConfirmationCode":{e.push(Ur());break}case"RespondToAuthChallenge":{e.push(Ur());break}case"RevokeToken":{e.push(Ur());break}case"SetUserMFAPreference":{e.push(Ur());break}case"SetUserSettings":{e.push(Ur());break}case"SignUp":{e.push(Ur());break}case"StartWebAuthnRegistration":{e.push(Ur());break}case"UpdateAuthEventFeedback":{e.push(Ur());break}case"UpdateDeviceStatus":{e.push(Ur());break}case"UpdateUserAttributes":{e.push(Ur());break}case"VerifySoftwareToken":{e.push(Ur());break}case"VerifyUserAttribute":{e.push(Ur());break}default:e.push(Aj(r))}return e},wj=r=>{const e=gj(r);return Object.assign(e,{authSchemePreference:Bs(r.authSchemePreference??[])})},Cj=r=>Object.assign(r,{useDualstackEndpoint:r.useDualstackEndpoint??!1,useFipsEndpoint:r.useFipsEndpoint??!1,defaultSigningName:"cognito-idp"}),mP={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},xj="3.1075.0",Sj={version:xj},Ej=r=>new TextEncoder().encode(r);var kj=typeof Buffer<"u"&&Buffer.from?function(r){return Buffer.from(r,"utf8")}:Ej;function Tf(r){return r instanceof Uint8Array?r:typeof r=="string"?kj(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r)}function xA(r){return typeof r=="string"?r.length===0:r.byteLength===0}var vP={name:"SHA-256"},i2={name:"HMAC",hash:vP},Tj=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);const Fj={};function Kp(){return typeof window<"u"?window:typeof self<"u"?self:Fj}var Ij=(function(){function r(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return r.prototype.update=function(e){if(!xA(e)){var t=Tf(e),n=new Uint8Array(this.toHash.byteLength+t.byteLength);n.set(this.toHash,0),n.set(t,this.toHash.byteLength),this.toHash=n}},r.prototype.digest=function(){var e=this;return this.key?this.key.then(function(t){return Kp().crypto.subtle.sign(i2,t,e.toHash).then(function(n){return new Uint8Array(n)})}):xA(this.toHash)?Promise.resolve(Tj):Promise.resolve().then(function(){return Kp().crypto.subtle.digest(vP,e.toHash)}).then(function(t){return Promise.resolve(new Uint8Array(t))})},r.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&this.secret!==void 0&&(this.key=new Promise(function(t,n){Kp().crypto.subtle.importKey("raw",Tf(e.secret),i2,!1,["sign"]).then(t,n)}),this.key.catch(function(){}))},r})(),ha=64,Pj=32,Dj=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Rj=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],Oj=Math.pow(2,53)-1,Zp=(function(){function r(){this.state=Int32Array.from(Rj),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return r.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,this.bytesHashed*8>Oj)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===ha&&(this.hashBuffer(),this.bufferLength=0)},r.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%ha>=ha-8){for(var i=this.bufferLength;i<ha;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0}for(var i=this.bufferLength;i<ha-8;i++)t.setUint8(i,0);t.setUint32(ha-8,Math.floor(e/4294967296),!0),t.setUint32(ha-4,e),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(Pj),i=0;i<8;i++)a[i*4]=this.state[i]>>>24&255,a[i*4+1]=this.state[i]>>>16&255,a[i*4+2]=this.state[i]>>>8&255,a[i*4+3]=this.state[i]>>>0&255;return a},r.prototype.hashBuffer=function(){for(var e=this,t=e.buffer,n=e.state,i=n[0],a=n[1],s=n[2],o=n[3],l=n[4],u=n[5],c=n[6],f=n[7],d=0;d<ha;d++){if(d<16)this.temp[d]=(t[d*4]&255)<<24|(t[d*4+1]&255)<<16|(t[d*4+2]&255)<<8|t[d*4+3]&255;else{var h=this.temp[d-2],g=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10;h=this.temp[d-15];var v=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[d]=(g+this.temp[d-7]|0)+(v+this.temp[d-16]|0)}var y=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&u^~l&c)|0)+(f+(Dj[d]+this.temp[d]|0)|0)|0,A=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&a^i&s^a&s)|0;f=c,c=u,u=l,l=o+y|0,o=s,s=a,a=i,i=y+A|0}n[0]+=i,n[1]+=a,n[2]+=s,n[3]+=o,n[4]+=l,n[5]+=u,n[6]+=c,n[7]+=f},r})(),Bj=(function(){function r(e){this.secret=e,this.hash=new Zp,this.reset()}return r.prototype.update=function(e){if(!(xA(e)||this.error))try{this.hash.update(Tf(e))}catch(t){this.error=t}},r.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},r.prototype.digest=function(){return es(this,void 0,void 0,function(){return ts(this,function(e){return[2,this.digestSync()]})})},r.prototype.reset=function(){if(this.hash=new Zp,this.secret){this.outer=new Zp;var e=Mj(this.secret),t=new Uint8Array(ha);t.set(e);for(var n=0;n<ha;n++)e[n]^=54,t[n]^=92;this.hash.update(e),this.outer.update(t);for(var n=0;n<e.byteLength;n++)e[n]=0}},r})();function Mj(r){var e=Tf(r);if(e.byteLength>ha){var t=new Zp;t.update(e),e=t.digest()}var n=new Uint8Array(ha);return n.set(e),n}var _j=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Nj(r){if(Lj(r)&&typeof r.crypto.subtle=="object"){var e=r.crypto.subtle;return Uj(e)}return!1}function Lj(r){if(typeof r=="object"&&typeof r.crypto=="object"){var e=r.crypto.getRandomValues;return typeof e=="function"}return!1}function Uj(r){return r&&_j.every(function(e){return typeof r[e]=="function"})}var Vj=(function(){function r(e){Nj(Kp())?this.hash=new Ij(e):this.hash=new Bj(e)}return r.prototype.update=function(e,t){this.hash.update(Tf(e))},r.prototype.digest=function(){return this.hash.digest()},r.prototype.reset=function(){this.hash.reset()},r})();function a2(r,e){return new Request(r,e)}function zj(r=0){return new Promise((e,t)=>{r&&setTimeout(()=>{const n=new Error(`Request did not complete within ${r} ms`);n.name="TimeoutError",t(n)},r)})}const Xv={supported:void 0};class W1{config;configProvider;static create(e){return typeof e?.handle=="function"?e:new W1(e)}constructor(e){typeof e=="function"?this.configProvider=e().then(t=>t||{}):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),Xv.supported===void 0&&(Xv.supported=typeof Request<"u"&&"keepalive"in a2("https://[::1]"))}destroy(){}async handle(e,{abortSignal:t,requestTimeout:n}={}){this.config||(this.config=await this.configProvider);const i=n??this.config.requestTimeout,a=this.config.keepAlive===!0,s=this.config.credentials;if(t?.aborted){const C=s2(t);return Promise.reject(C)}let o=e.path;const l=m$(e.query||{});l&&(o+=`?${l}`),e.fragment&&(o+=`#${e.fragment}`);let u="";if(e.username!=null||e.password!=null){const C=e.username??"",S=e.password??"";u=`${C}:${S}@`}const{port:c,method:f}=e,d=`${e.protocol}//${u}${e.hostname}${c?`:${c}`:""}${o}`,h=f==="GET"||f==="HEAD"?void 0:e.body,g={body:h,headers:new Headers(e.headers),method:f,credentials:s};this.config?.cache&&(g.cache=this.config.cache),h&&(g.duplex="half"),typeof AbortController<"u"&&(g.signal=t),Xv.supported&&(g.keepalive=a),typeof this.config.requestInit=="function"&&Object.assign(g,this.config.requestInit(e));let v=()=>{};const y=a2(d,g),A=[fetch(y).then(C=>{const S=C.headers,F={};for(const R of S.entries())F[R[0]]=R[1];return C.body!=null?{response:new sc({headers:F,reason:C.statusText,statusCode:C.status,body:C.body})}:C.blob().then(R=>({response:new sc({headers:F,reason:C.statusText,statusCode:C.status,body:R})}))}),zj(i)];return t&&A.push(new Promise((C,S)=>{const F=()=>{const E=s2(t);S(E)};if(typeof t.addEventListener=="function"){const E=t;E.addEventListener("abort",F,{once:!0}),v=()=>E.removeEventListener("abort",F)}else t.onabort=F})),Promise.race(A).finally(v)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then(n=>(n[e]=t,n))}httpHandlerConfigs(){return this.config??{}}}function s2(r){const e=r&&typeof r=="object"&&"reason"in r?r.reason:void 0;if(e){if(e instanceof Error){const i=new Error("Request aborted");return i.name="AbortError",i.cause=e,i}const n=new Error(String(e));return n.name="AbortError",n}const t=new Error("Request aborted");return t.name="AbortError",t}const $j=async r=>typeof Blob=="function"&&r instanceof Blob||r.constructor?.name==="Blob"?Blob.prototype.arrayBuffer!==void 0?new Uint8Array(await r.arrayBuffer()):Hj(r):jj(r);async function Hj(r){const e=await Gj(r),t=Zg(e);return new Uint8Array(t)}async function jj(r){const e=[],t=r.getReader();let n=!1,i=0;for(;!n;){const{done:o,value:l}=await t.read();l&&(e.push(l),i+=l.length),n=o}const a=new Uint8Array(i);let s=0;for(const o of e)a.set(o,s),s+=o.length;return a}function Gj(r){return new Promise((e,t)=>{const n=new FileReader;n.onloadend=()=>{if(n.readyState!==2)return t(new Error("Reader aborted too early"));const i=n.result??"",a=i.indexOf(","),s=a>-1?a+1:i.length;e(i.substring(s))},n.onabort=()=>t(new Error("Read aborted")),n.onerror=()=>t(n.error),n.readAsDataURL(r)})}class qj{queryCompat;errorRegistry;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,t){const n=t.getMemberSchemas(),i=Object.values(n).find(a=>!!a.getMergedTraits().httpPayload);if(i){const a=i.getMergedTraits().mediaType;return a||(i.isStringSchema()?"text/plain":i.isBlobSchema()?"application/octet-stream":e)}else if(!t.isUnitSchema()&&Object.values(n).find(s=>{const{httpQuery:o,httpQueryParams:l,httpHeader:u,httpLabel:c,httpPrefixHeaders:f}=s.getMergedTraits();return!o&&!l&&!u&&!c&&f===void 0}))return e}async getErrorSchemaOrThrowBaseException(e,t,n,i,a,s){let o=e;e.includes("#")&&([,o]=e.split("#"));const l={$metadata:a,$fault:n.statusCode<500?"client":"server"};if(!this.errorRegistry)throw new Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:s?.(this.errorRegistry,o)??this.errorRegistry.getSchema(e),errorMetadata:l}}catch{i.message=i.message??i.Message??"UnknownError";const c=this.errorRegistry,f=c.getBaseException();if(f){const g=c.getErrorCtor(f)??Error;throw this.decorateServiceException(Object.assign(new g({name:o}),l),i)}const d=i,h=d?.message??d?.Message??d?.Error?.Message??d?.Error?.message;throw this.decorateServiceException(Object.assign(new Error(h),{name:o},l),i)}}compose(e,t,n){let i=n;t.includes("#")&&([i]=t.split("#"));const a=Zi.for(i),s=Zi.for("smithy.ts.sdk.synthetic."+n);e.copyFrom(a),e.copyFrom(s),this.errorRegistry=e}decorateServiceException(e,t={}){if(this.queryCompat){const n=e.Message??t.Message,i=BE(e,t);n&&(i.message=n);const a=i.Error??{};a.Type=i.Error?.Type,a.Code=i.Error?.Code,a.Message=i.Error?.message??i.Error?.Message??n,i.Error=a;const s=i.$metadata.requestId;return s&&(i.RequestId=s),i}return BE(e,t)}setQueryCompatError(e,t){const n=t.headers?.["x-amzn-query-error"];if(e!==void 0&&n!=null){const[i,a]=n.split(";"),s=Object.keys(e),o={Code:i,Type:a};e.Code=i,e.Type=a;for(let l=0;l<s.length;l++){const u=s[l];o[u==="message"?"Message":u]=e[u]}delete o.__type,e.Error=o}}queryCompatOutput(e,t){e.Error&&(t.Error=e.Error),e.Type&&(t.Type=e.Type),e.Code&&(t.Code=e.Code)}findQueryCompatibleError(e,t){try{return e.getSchema(t)}catch{return e.find(i=>vi.of(i).getMergedTraits().awsQueryError?.[0]===t)}}}class Q1{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Wj{from;to;keys;constructor(e,t){this.from=e,this.to=t;const n=Object.keys(this.from),i=new Set(n);i.delete("__type"),this.keys=i}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){const e=this.keys.values().next().value,t=this.from[e];this.to.$unknown=[e,t]}}}function Qj(r,e,t){if(t?.source){const n=t.source;if(typeof e=="number"&&(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER||n!==String(e)))return n.includes(".")?new ns(n,"bigDecimal"):BigInt(n)}return e}const Yj=(r,e)=>bA(r,e).then(t=>(e?.utf8Encoder??em)(t)),Xj=(r,e)=>Yj(r,e).then(t=>{if(t.length)try{return JSON.parse(t)}catch(n){throw n?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:t}),n}return{}}),o2=(r,e)=>Object.keys(r).find(t=>t.toLowerCase()===e.toLowerCase()),Jv=r=>{let e=r;return typeof e=="number"&&(e=e.toString()),e.indexOf(",")>=0&&(e=e.split(",")[0]),e.indexOf(":")>=0&&(e=e.split(":")[0]),e.indexOf("#")>=0&&(e=e.split("#")[1]),e},Jj=(r,e,t=!1)=>Kj(r,e,t?["code","header","type"]:["type","code","header"]),Kj=({headers:r},e,t)=>{for(;t.length>0;)switch(t.shift()){case"header":const i=o2(r??{},"x-amzn-errortype");if(i!==void 0)return Jv(r[i]);break;case"code":const a=o2(e??{},"code");if(a&&e[a]!==void 0)return Jv(e[a]);break;case"type":if(e?.__type!==void 0)return Jv(e.__type);break}};class Zj extends Q1{settings;constructor(e){super(),this.settings=e}async read(e,t){return this._read(e,typeof t=="string"?JSON.parse(t,Qj):await Xj(t,this.serdeContext))}readObject(e,t){return this._read(e,t)}_read(e,t){const n=t!==null&&typeof t=="object",i=vi.of(e);if(n){if(i.isStructSchema()){const s=t,o=i.isUnionSchema(),l={};let u;const{jsonName:c}=this.settings;c&&(u={});let f;o&&(f=new Wj(s,l));for(const[d,h]of i.structIterator()){let g=d;c&&(g=h.getMergedTraits().jsonName??g,u[g]=d),o&&f.mark(g),s[g]!=null&&(l[d]=this._read(h,s[g]))}if(o)f.writeUnknown();else if(typeof s.__type=="string")for(const d in s){const h=s[d],g=c?u[d]??d:d;g in l||(l[g]=h)}return l}if(Array.isArray(t)&&i.isListSchema()){const s=i.getValueSchema(),o=[];for(const l of t)o.push(this._read(s,l));return o}if(i.isMapSchema()){const s=i.getValueSchema(),o={};for(const l in t)o[l]=this._read(s,t[l]);return o}}if(i.isBlobSchema()&&typeof t=="string")return Zg(t);const a=i.getMergedTraits().mediaType;if(i.isStringSchema()&&typeof t=="string"&&a)return a==="application/json"||a.endsWith("+json")?po.from(t):t;if(i.isTimestampSchema()&&t!=null)switch(rP(i,this.settings)){case 5:return lz(t);case 6:return $I(t);case 7:return fz(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(i.isBigIntegerSchema()&&(typeof t=="number"||typeof t=="string"))return BigInt(t);if(i.isBigDecimalSchema()&&t!=null){if(t instanceof ns)return t;const s=t;return s.type==="bigDecimal"&&"string"in s?new ns(s.string,s.type):new ns(String(t),"bigDecimal")}if(i.isNumericSchema()&&typeof t=="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(i.isDocumentSchema())if(n){const s=Array.isArray(t)?[]:{};for(const o in t){const l=t[o];l instanceof ns?s[o]=l:s[o]=this._read(i,l)}return s}else return structuredClone(t);return t}}const l2="Ν";class eG{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,t)=>{if(t instanceof ns){const n=`${l2+"nv"+this.counter++}_`+t.string;return this.values.set(`"${n}"`,t.string),n}if(typeof t=="bigint"){const n=t.toString(),i=`${l2+"b"+this.counter++}_`+n;return this.values.set(`"${i}"`,n),i}return t}}replaceInJson(e){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(const[t,n]of this.values)e=e.replace(t,n);return e}}class tG extends Q1{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super(),this.settings=e}write(e,t){this.rootSchema=vi.of(e),this.buffer=this._write(this.rootSchema,t)}flush(){const{rootSchema:e,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);const n=new eG;return n.replaceInJson(JSON.stringify(this.buffer,n.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(e,t){this.write(e,t),typeof this.buffer=="object"&&(this.buffer.__type=vi.of(e).getName(!0))}_write(e,t,n){const i=t!==null&&typeof t=="object",a=vi.of(e);if(i){if(a.isStructSchema()){const s=t,o={},{jsonName:l}=this.settings;let u;l&&(u={});let c=0;for(const[f,d]of a.structIterator()){const h=this._write(d,s[f],a);if(h!==void 0){let g=f;l&&(g=d.getMergedTraits().jsonName??f,u[f]=g),o[g]=h,c++}}if(a.isUnionSchema()&&c===0){const{$unknown:f}=s;if(Array.isArray(f)){const[d,h]=f;o[d]=this._write(15,h)}}else if(typeof s.__type=="string")for(const f in s){const d=s[f],h=l?u[f]??f:f;h in o||(o[h]=this._write(15,d))}return o}if(Array.isArray(t)&&a.isListSchema()){const s=a.getValueSchema(),o=[],l=!!a.getMergedTraits().sparse;for(const u of t)(l||u!=null)&&o.push(this._write(s,u));return o}if(a.isMapSchema()){const s=a.getValueSchema(),o={},l=!!a.getMergedTraits().sparse;for(const u in t){const c=t[u];(l||c!=null)&&(o[u]=this._write(s,c))}return o}if(t instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??Cg)(t);if(t instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(rP(a,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return sz(t);case 7:return t.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1e3}t instanceof ns&&(this.useReplacer=!0)}if(!(t===null&&n?.isStructSchema())){if(a.isStringSchema()){if(typeof t>"u"&&a.isIdempotencyToken())return s$();const s=a.getMergedTraits().mediaType;return t!=null&&s&&(s==="application/json"||s.endsWith("+json"))?po.from(t):t}if(typeof t=="number"&&a.isNumericSchema())return Math.abs(t)===1/0||isNaN(t)?String(t):t;if(typeof t=="string"&&a.isBlobSchema())return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??Cg)(t);if(typeof t=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(i){const s=Array.isArray(t)?[]:{};for(const o in t){const l=t[o];l instanceof ns?(this.useReplacer=!0,s[o]=l):s[o]=this._write(a,l)}return s}else return structuredClone(t);return t}}}class rG extends Q1{settings;constructor(e){super(),this.settings=e}createSerializer(){const e=new tG(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){const e=new Zj(this.settings);return e.setSerdeContext(this.serdeContext),e}}class nG extends u${serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a}){super({defaultNamespace:e,errorTypeRegistries:t}),this.serviceTarget=n,this.codec=a??new rG({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!i,this.mixin=new qj(this.awsQueryCompatible)}async serializeRequest(e,t,n){const i=await super.serializeRequest(e,t,n);return i.path.endsWith("/")||(i.path+="/"),i.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,i.headers["x-amz-target"]=`${this.serviceTarget}.${e.name}`,this.awsQueryCompatible&&(i.headers["x-amzn-query-mode"]="true"),(Yp(e.input)==="unit"||!i.body)&&(i.body="{}"),i}getPayloadCodec(){return this.codec}async handleError(e,t,n,i,a){const{awsQueryCompatible:s}=this;s&&this.mixin.setQueryCompatError(i,n);const o=Jj(n,i,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,o,this.options.defaultNamespace);const{errorSchema:l,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,n,i,a,s?this.mixin.findQueryCompatibleError:void 0),c=vi.of(l),f=i.message??i.Message??"UnknownError",d=this.compositeErrorRegistry.getErrorCtor(l)??Error,h=new d({}),g={},v=this.codec.createDeserializer();for(const[y,A]of c.structIterator())i[y]!=null&&(g[y]=v.readObject(A,i[y]));throw s&&this.mixin.queryCompatOutput(i,g),this.mixin.decorateServiceException(Object.assign(h,u,{$fault:c.getMergedTraits().error,message:f},g),i)}}class iG extends nG{constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a}){super({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}const Ff="ref",hl=-1,Ip=!0,u2="isSet",yP="PartitionResult",Pp="booleanEquals",Kv="getAttr",Fd="stringEquals",c2={[Ff]:"Endpoint"},Zv={[Ff]:yP},$d={[Ff]:"Region"},Ya={},d2=[$d],f2={conditions:[[u2,[c2]],[u2,d2],["aws.partition",d2,yP],[Pp,[{[Ff]:"UseFIPS"},Ip]],[Pp,[{fn:Kv,argv:[Zv,"supportsFIPS"]},Ip]],[Pp,[{[Ff]:"UseDualStack"},Ip]],[Pp,[{fn:Kv,argv:[Zv,"supportsDualStack"]},Ip]],[Fd,[{fn:Kv,argv:[Zv,"name"]},"aws"]],[Fd,[$d,"us-east-1"]],[Fd,[$d,"us-east-2"]],[Fd,[$d,"us-west-1"]],[Fd,[$d,"us-west-2"]]],results:[[hl],[hl,"Invalid Configuration: FIPS and custom endpoint are not supported"],[hl,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[c2,Ya],["https://cognito-idp-fips.us-east-1.amazonaws.com",Ya],["https://cognito-idp-fips.us-east-2.amazonaws.com",Ya],["https://cognito-idp-fips.us-west-1.amazonaws.com",Ya],["https://cognito-idp-fips.us-west-2.amazonaws.com",Ya],["https://cognito-idp-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Ya],[hl,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://cognito-idp-fips.{Region}.{PartitionResult#dnsSuffix}",Ya],[hl,"FIPS is enabled but this partition does not support FIPS"],["https://cognito-idp.{Region}.amazonaws.com",Ya],["https://cognito-idp.{Region}.{PartitionResult#dualStackDnsSuffix}",Ya],[hl,"DualStack is enabled but this partition does not support DualStack"],["https://cognito-idp.{Region}.{PartitionResult#dnsSuffix}",Ya],[hl,"Invalid Configuration: Missing Region"]]},aG=2,pi=1e8,sG=new Int32Array([-1,1,-1,0,17,3,1,4,pi+16,2,5,pi+16,3,9,6,5,7,pi+15,6,8,pi+14,7,pi+12,pi+13,4,11,10,5,pi+9,pi+11,5,12,pi+10,6,13,pi+9,8,pi+4,14,9,pi+5,15,10,pi+6,16,11,pi+7,pi+8,3,pi+1,18,5,pi+2,pi+3]),oG=$1.from(sG,aG,f2.conditions,f2.results),lG=new Lz({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),uG=(r,e={})=>lG.get(r,()=>n$(oG,{endpointParams:r,logger:e.logger}));H1.aws=oP;class Ct extends Lu{constructor(e){super(e),Object.setPrototypeOf(this,Ct.prototype)}}class Y1 extends Ct{name="AccessDeniedException";$fault="client";constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,Y1.prototype)}}class X1 extends Ct{name="InternalErrorException";$fault="server";constructor(e){super({name:"InternalErrorException",$fault:"server",...e}),Object.setPrototypeOf(this,X1.prototype)}}class J1 extends Ct{name="InvalidParameterException";$fault="client";reasonCode;constructor(e){super({name:"InvalidParameterException",$fault:"client",...e}),Object.setPrototypeOf(this,J1.prototype),this.reasonCode=e.reasonCode}}class K1 extends Ct{name="NotAuthorizedException";$fault="client";constructor(e){super({name:"NotAuthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,K1.prototype)}}class Z1 extends Ct{name="OperationNotEnabledException";$fault="client";constructor(e){super({name:"OperationNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Z1.prototype)}}class eb extends Ct{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,eb.prototype)}}class tb extends Ct{name="TooManyRequestsException";$fault="client";constructor(e){super({name:"TooManyRequestsException",$fault:"client",...e}),Object.setPrototypeOf(this,tb.prototype)}}class rb extends Ct{name="UserImportInProgressException";$fault="client";constructor(e){super({name:"UserImportInProgressException",$fault:"client",...e}),Object.setPrototypeOf(this,rb.prototype)}}class nb extends Ct{name="InternalServerException";$fault="server";constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,nb.prototype)}}class ib extends Ct{name="LimitExceededException";$fault="client";constructor(e){super({name:"LimitExceededException",$fault:"client",...e}),Object.setPrototypeOf(this,ib.prototype)}}class ab extends Ct{name="UserNotFoundException";$fault="client";constructor(e){super({name:"UserNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,ab.prototype)}}class sb extends Ct{name="InvalidLambdaResponseException";$fault="client";constructor(e){super({name:"InvalidLambdaResponseException",$fault:"client",...e}),Object.setPrototypeOf(this,sb.prototype)}}class ob extends Ct{name="TooManyFailedAttemptsException";$fault="client";constructor(e){super({name:"TooManyFailedAttemptsException",$fault:"client",...e}),Object.setPrototypeOf(this,ob.prototype)}}class lb extends Ct{name="UnexpectedLambdaException";$fault="client";constructor(e){super({name:"UnexpectedLambdaException",$fault:"client",...e}),Object.setPrototypeOf(this,lb.prototype)}}class ub extends Ct{name="UserLambdaValidationException";$fault="client";constructor(e){super({name:"UserLambdaValidationException",$fault:"client",...e}),Object.setPrototypeOf(this,ub.prototype)}}class cb extends Ct{name="CodeDeliveryFailureException";$fault="client";constructor(e){super({name:"CodeDeliveryFailureException",$fault:"client",...e}),Object.setPrototypeOf(this,cb.prototype)}}class db extends Ct{name="InvalidPasswordException";$fault="client";constructor(e){super({name:"InvalidPasswordException",$fault:"client",...e}),Object.setPrototypeOf(this,db.prototype)}}class fb extends Ct{name="InvalidSmsRoleAccessPolicyException";$fault="client";constructor(e){super({name:"InvalidSmsRoleAccessPolicyException",$fault:"client",...e}),Object.setPrototypeOf(this,fb.prototype)}}class hb extends Ct{name="InvalidSmsRoleTrustRelationshipException";$fault="client";constructor(e){super({name:"InvalidSmsRoleTrustRelationshipException",$fault:"client",...e}),Object.setPrototypeOf(this,hb.prototype)}}class pb extends Ct{name="PreconditionNotMetException";$fault="client";constructor(e){super({name:"PreconditionNotMetException",$fault:"client",...e}),Object.setPrototypeOf(this,pb.prototype)}}class gb extends Ct{name="UnsupportedUserStateException";$fault="client";constructor(e){super({name:"UnsupportedUserStateException",$fault:"client",...e}),Object.setPrototypeOf(this,gb.prototype)}}class mb extends Ct{name="UsernameExistsException";$fault="client";constructor(e){super({name:"UsernameExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,mb.prototype)}}class vb extends Ct{name="AliasExistsException";$fault="client";constructor(e){super({name:"AliasExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,vb.prototype)}}class yb extends Ct{name="InvalidUserPoolConfigurationException";$fault="client";constructor(e){super({name:"InvalidUserPoolConfigurationException",$fault:"client",...e}),Object.setPrototypeOf(this,yb.prototype)}}class Ab extends Ct{name="InvalidEmailRoleAccessPolicyException";$fault="client";constructor(e){super({name:"InvalidEmailRoleAccessPolicyException",$fault:"client",...e}),Object.setPrototypeOf(this,Ab.prototype)}}class bb extends Ct{name="MFAMethodNotFoundException";$fault="client";constructor(e){super({name:"MFAMethodNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,bb.prototype)}}class wb extends Ct{name="PasswordResetRequiredException";$fault="client";constructor(e){super({name:"PasswordResetRequiredException",$fault:"client",...e}),Object.setPrototypeOf(this,wb.prototype)}}class Cb extends Ct{name="UnsupportedOperationException";$fault="client";constructor(e){super({name:"UnsupportedOperationException",$fault:"client",...e}),Object.setPrototypeOf(this,Cb.prototype)}}class xb extends Ct{name="UserNotConfirmedException";$fault="client";constructor(e){super({name:"UserNotConfirmedException",$fault:"client",...e}),Object.setPrototypeOf(this,xb.prototype)}}class Sb extends Ct{name="UserPoolAddOnNotEnabledException";$fault="client";constructor(e){super({name:"UserPoolAddOnNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Sb.prototype)}}class Eb extends Ct{name="CodeMismatchException";$fault="client";constructor(e){super({name:"CodeMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,Eb.prototype)}}class kb extends Ct{name="ExpiredCodeException";$fault="client";constructor(e){super({name:"ExpiredCodeException",$fault:"client",...e}),Object.setPrototypeOf(this,kb.prototype)}}class Tb extends Ct{name="PasswordHistoryPolicyViolationException";$fault="client";constructor(e){super({name:"PasswordHistoryPolicyViolationException",$fault:"client",...e}),Object.setPrototypeOf(this,Tb.prototype)}}class Fb extends Ct{name="SoftwareTokenMFANotFoundException";$fault="client";constructor(e){super({name:"SoftwareTokenMFANotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,Fb.prototype)}}class Ib extends Ct{name="ConcurrentModificationException";$fault="client";constructor(e){super({name:"ConcurrentModificationException",$fault:"client",...e}),Object.setPrototypeOf(this,Ib.prototype)}}class Pb extends Ct{name="ForbiddenException";$fault="client";constructor(e){super({name:"ForbiddenException",$fault:"client",...e}),Object.setPrototypeOf(this,Pb.prototype)}}class Db extends Ct{name="WebAuthnChallengeNotFoundException";$fault="client";constructor(e){super({name:"WebAuthnChallengeNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,Db.prototype)}}class Rb extends Ct{name="WebAuthnClientMismatchException";$fault="client";constructor(e){super({name:"WebAuthnClientMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,Rb.prototype)}}class Ob extends Ct{name="WebAuthnCredentialNotSupportedException";$fault="client";constructor(e){super({name:"WebAuthnCredentialNotSupportedException",$fault:"client",...e}),Object.setPrototypeOf(this,Ob.prototype)}}class Bb extends Ct{name="WebAuthnNotEnabledException";$fault="client";constructor(e){super({name:"WebAuthnNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Bb.prototype)}}class Mb extends Ct{name="WebAuthnOriginNotAllowedException";$fault="client";constructor(e){super({name:"WebAuthnOriginNotAllowedException",$fault:"client",...e}),Object.setPrototypeOf(this,Mb.prototype)}}class _b extends Ct{name="WebAuthnRelyingPartyMismatchException";$fault="client";constructor(e){super({name:"WebAuthnRelyingPartyMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,_b.prototype)}}class Nb extends Ct{name="DeviceKeyExistsException";$fault="client";constructor(e){super({name:"DeviceKeyExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Nb.prototype)}}class Lb extends Ct{name="GroupExistsException";$fault="client";constructor(e){super({name:"GroupExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Lb.prototype)}}class Ub extends Ct{name="DuplicateProviderException";$fault="client";constructor(e){super({name:"DuplicateProviderException",$fault:"client",...e}),Object.setPrototypeOf(this,Ub.prototype)}}class Vb extends Ct{name="ManagedLoginBrandingExistsException";$fault="client";constructor(e){super({name:"ManagedLoginBrandingExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Vb.prototype)}}class zb extends Ct{name="TermsExistsException";$fault="client";constructor(e){super({name:"TermsExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,zb.prototype)}}class $b extends Ct{name="FeatureUnavailableInTierException";$fault="client";constructor(e){super({name:"FeatureUnavailableInTierException",$fault:"client",...e}),Object.setPrototypeOf(this,$b.prototype)}}class Hb extends Ct{name="TierChangeNotAllowedException";$fault="client";constructor(e){super({name:"TierChangeNotAllowedException",$fault:"client",...e}),Object.setPrototypeOf(this,Hb.prototype)}}class jb extends Ct{name="UserPoolTaggingException";$fault="client";constructor(e){super({name:"UserPoolTaggingException",$fault:"client",...e}),Object.setPrototypeOf(this,jb.prototype)}}class Gb extends Ct{name="InvalidOAuthFlowException";$fault="client";constructor(e){super({name:"InvalidOAuthFlowException",$fault:"client",...e}),Object.setPrototypeOf(this,Gb.prototype)}}class qb extends Ct{name="ScopeDoesNotExistException";$fault="client";constructor(e){super({name:"ScopeDoesNotExistException",$fault:"client",...e}),Object.setPrototypeOf(this,qb.prototype)}}class Wb extends Ct{name="UnsupportedIdentityProviderException";$fault="client";constructor(e){super({name:"UnsupportedIdentityProviderException",$fault:"client",...e}),Object.setPrototypeOf(this,Wb.prototype)}}class Qb extends Ct{name="RefreshTokenReuseException";$fault="client";constructor(e){super({name:"RefreshTokenReuseException",$fault:"client",...e}),Object.setPrototypeOf(this,Qb.prototype)}}class Yb extends Ct{name="UnauthorizedException";$fault="client";constructor(e){super({name:"UnauthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,Yb.prototype)}}class Xb extends Ct{name="UnsupportedTokenTypeException";$fault="client";constructor(e){super({name:"UnsupportedTokenTypeException",$fault:"client",...e}),Object.setPrototypeOf(this,Xb.prototype)}}class Jb extends Ct{name="WebAuthnConfigurationMissingException";$fault="client";constructor(e){super({name:"WebAuthnConfigurationMissingException",$fault:"client",...e}),Object.setPrototypeOf(this,Jb.prototype)}}class Kb extends Ct{name="EnableSoftwareTokenMFAException";$fault="client";constructor(e){super({name:"EnableSoftwareTokenMFAException",$fault:"client",...e}),Object.setPrototypeOf(this,Kb.prototype)}}const cG="AvailableChallenges",dG="AccessDeniedException",fG="AliasExistsException",hG="AnalyticsEndpointId",pG="AuthFlow",AP="AnalyticsMetadata",gG="AnalyticsMetadataType",mG="AuthParameters",vG="AuthParametersType",bP="AuthenticationResult",yG="AuthenticationResultType",AG="AccessToken",bG="CodeDeliveryFailureException",wP="ClientId",wG="ClientIdType",CP="ClientMetadata",CG="CodeMismatchException",xG="ConcurrentModificationException",Zb="ChallengeName",xP="ChallengeParameters",SG="ChallengeResponses",EG="ChallengeResponsesType",kG="DeviceGroupKey",TG="DeviceKey",FG="DeviceKeyExistsException",IG="DuplicateProviderException",PG="ExpiredCodeException",DG="EncodedData",RG="ExpiresIn",OG="EnableSoftwareTokenMFAException",BG="ForbiddenException",MG="FeatureUnavailableInTierException",_G="GroupExistsException",NG="IpAddress",LG="InitiateAuthRequest",UG="InitiateAuthResponse",VG="InitiateAuth",zG="InternalErrorException",$G="InvalidEmailRoleAccessPolicyException",HG="InvalidLambdaResponseException",jG="InvalidOAuthFlowException",GG="InvalidParameterException",qG="InvalidPasswordException",WG="InternalServerException",QG="InvalidSmsRoleAccessPolicyException",YG="InvalidSmsRoleTrustRelationshipException",XG="IdToken",JG="InvalidUserPoolConfigurationException",KG="LimitExceededException",ZG="MFAMethodNotFoundException",eq="ManagedLoginBrandingExistsException",tq="NotAuthorizedException",rq="NewDeviceMetadata",nq="NewDeviceMetadataType",iq="OperationNotEnabledException",aq="PasswordHistoryPolicyViolationException",sq="PreconditionNotMetException",oq="PasswordResetRequiredException",lq="ResourceNotFoundException",uq="RefreshToken",cq="RespondToAuthChallenge",dq="RespondToAuthChallengeRequest",fq="RespondToAuthChallengeResponse",hq="RefreshTokenReuseException",nm="Session",pq="ScopeDoesNotExistException",gq="SessionType",mq="SoftwareTokenMFANotFoundException",vq="TierChangeNotAllowedException",yq="TermsExistsException",Aq="TooManyFailedAttemptsException",bq="TooManyRequestsException",wq="TokenModelType",Cq="TokenType",xq="UserContextDataType",SP="UserContextData",Sq="UnauthorizedException",Eq="UsernameExistsException",kq="UserImportInProgressException",Tq="UnsupportedIdentityProviderException",Fq="UnexpectedLambdaException",Iq="UserLambdaValidationException",Pq="UserNotConfirmedException",Dq="UserNotFoundException",Rq="UnsupportedOperationException",Oq="UserPoolAddOnNotEnabledException",Bq="UserPoolTaggingException",Mq="UnsupportedTokenTypeException",_q="UnsupportedUserStateException",Nq="WebAuthnClientMismatchException",Lq="WebAuthnConfigurationMissingException",Uq="WebAuthnChallengeNotFoundException",Vq="WebAuthnCredentialNotSupportedException",zq="WebAuthnNotEnabledException",$q="WebAuthnOriginNotAllowedException",Hq="WebAuthnRelyingPartyMismatchException",It="client",Tt="error",Pt="httpError",Ft="message",jq="reasonCode",EP="smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentityprovider",kP="server",at="com.amazonaws.cognitoidentityprovider",TP=Zi.for(EP);var Gq=[-3,EP,"CognitoIdentityProviderServiceException",0,[],[]];TP.registerError(Gq,Ct);const kt=Zi.for(at);var qq=[-3,at,dG,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(qq,Y1);var Wq=[-3,at,fG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Wq,vb);var Qq=[-3,at,bG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Qq,cb);var Yq=[-3,at,CG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Yq,Eb);var Xq=[-3,at,xG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Xq,Ib);var Jq=[-3,at,FG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Jq,Nb);var Kq=[-3,at,IG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Kq,Ub);var Zq=[-3,at,OG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Zq,Kb);var eW=[-3,at,PG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(eW,kb);var tW=[-3,at,MG,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(tW,$b);var rW=[-3,at,BG,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(rW,Pb);var nW=[-3,at,_G,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(nW,Lb);var iW=[-3,at,zG,{[Tt]:kP},[Ft],[0]];kt.registerError(iW,X1);var aW=[-3,at,WG,{[Tt]:kP},[Ft],[0]];kt.registerError(aW,nb);var sW=[-3,at,$G,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(sW,Ab);var oW=[-3,at,HG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(oW,sb);var lW=[-3,at,jG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(lW,Gb);var uW=[-3,at,GG,{[Tt]:It,[Pt]:400},[Ft,jq],[0,0]];kt.registerError(uW,J1);var cW=[-3,at,qG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(cW,db);var dW=[-3,at,QG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(dW,fb);var fW=[-3,at,YG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(fW,hb);var hW=[-3,at,JG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(hW,yb);var pW=[-3,at,KG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(pW,ib);var gW=[-3,at,eq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(gW,Vb);var mW=[-3,at,ZG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(mW,bb);var vW=[-3,at,tq,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(vW,K1);var yW=[-3,at,iq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(yW,Z1);var AW=[-3,at,aq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(AW,Tb);var bW=[-3,at,oq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(bW,wb);var wW=[-3,at,sq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(wW,pb);var CW=[-3,at,hq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(CW,Qb);var xW=[-3,at,lq,{[Tt]:It,[Pt]:404},[Ft],[0]];kt.registerError(xW,eb);var SW=[-3,at,pq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(SW,qb);var EW=[-3,at,mq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(EW,Fb);var kW=[-3,at,yq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(kW,zb);var TW=[-3,at,vq,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(TW,Hb);var FW=[-3,at,Aq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(FW,ob);var IW=[-3,at,bq,{[Tt]:It,[Pt]:429},[Ft],[0]];kt.registerError(IW,tb);var PW=[-3,at,Sq,{[Tt]:It,[Pt]:401},[Ft],[0]];kt.registerError(PW,Yb);var DW=[-3,at,Fq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(DW,lb);var RW=[-3,at,Tq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(RW,Wb);var OW=[-3,at,Rq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(OW,Cb);var BW=[-3,at,Mq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(BW,Xb);var MW=[-3,at,_q,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(MW,gb);var _W=[-3,at,kq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(_W,rb);var NW=[-3,at,Iq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(NW,ub);var LW=[-3,at,Eq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(LW,mb);var UW=[-3,at,Pq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(UW,xb);var VW=[-3,at,Dq,{[Tt]:It,[Pt]:404},[Ft],[0]];kt.registerError(VW,ab);var zW=[-3,at,Oq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(zW,Sb);var $W=[-3,at,Bq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError($W,jb);var HW=[-3,at,Uq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(HW,Db);var jW=[-3,at,Nq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(jW,Rb);var GW=[-3,at,Lq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(GW,Jb);var qW=[-3,at,Vq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(qW,Ob);var WW=[-3,at,zq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(WW,Bb);var QW=[-3,at,$q,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(QW,Mb);var YW=[-3,at,Hq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(YW,_b);const XW=[TP,kt];var FP=[0,at,wG,8,0],im=[0,at,gq,8,0],ey=[0,at,wq,8,0],IP=[3,at,gG,0,[hG],[0]],PP=[3,at,yG,0,[AG,RG,Cq,uq,XG,rq],[[()=>ey,0],1,0,[()=>ey,0],[()=>ey,0],()=>ZW]],JW=[3,at,LG,0,[pG,wP,mG,CP,AP,SP,nm],[0,[()=>FP,0],[()=>rQ,0],128,()=>IP,[()=>DP,0],[()=>im,0]],2],KW=[3,at,UG,0,[Zb,nm,xP,bP,cG],[0,[()=>im,0],128,[()=>PP,0],64]],ZW=[3,at,nq,0,[TG,kG],[0,0]],eQ=[3,at,dq,0,[wP,Zb,nm,SG,AP,SP,CP],[[()=>FP,0],0,[()=>im,0],[()=>nQ,0],()=>IP,[()=>DP,0],128],2],tQ=[3,at,fq,0,[Zb,nm,xP,bP],[0,[()=>im,0],128,[()=>PP,0]]],DP=[3,at,xq,8,[NG,DG],[0,0]],rQ=[2,at,vG,8,0,0],nQ=[2,at,EG,8,0,0],iQ=[9,at,VG,0,()=>JW,()=>KW],aQ=[9,at,cq,0,()=>eQ,()=>tQ];const sQ=r=>({apiVersion:"2016-04-18",base64Decoder:r?.base64Decoder??Zg,base64Encoder:r?.base64Encoder??Cg,disableHostPrefix:r?.disableHostPrefix??!1,endpointProvider:r?.endpointProvider??uG,extensions:r?.extensions??[],httpAuthSchemeProvider:r?.httpAuthSchemeProvider??bj,httpAuthSchemes:r?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new jH},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new lH}],logger:r?.logger??new UI,protocol:r?.protocol??iG,protocolSettings:r?.protocolSettings??{defaultNamespace:"com.amazonaws.cognitoidentityprovider",errorTypeRegistries:XW,xmlNamespace:"http://cognito-idp.amazonaws.com/doc/2016-04-18/",version:"2016-04-18",serviceTarget:"AWSCognitoIdentityProviderService"},serviceId:r?.serviceId??"Cognito Identity Provider",urlParser:r?.urlParser??wg,utf8Decoder:r?.utf8Decoder??kl,utf8Encoder:r?.utf8Encoder??em}),oQ=r=>{const e=_H(r),t=()=>e().then(UV),n=sQ(r);return{...n,...r,runtime:"browser",defaultsMode:e,bodyLengthChecker:r?.bodyLengthChecker??wz,credentialDefaultProvider:r?.credentialDefaultProvider??(i=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:r?.defaultUserAgentProvider??FH({serviceId:n.serviceId,clientVersion:Sj.version}),maxAttempts:r?.maxAttempts??ef,region:r?.region??PV("Region is missing"),requestHandler:W1.create(r?.requestHandler??t),retryMode:r?.retryMode??(async()=>(await t()).retryMode||V$),sha256:r?.sha256??Vj,streamCollector:r?.streamCollector??$j,useDualstackEndpoint:r?.useDualstackEndpoint??(()=>Promise.resolve(LH)),useFipsEndpoint:r?.useFipsEndpoint??(()=>Promise.resolve(UH))}},lQ=r=>{const e=r.httpAuthSchemes;let t=r.httpAuthSchemeProvider,n=r.credentials;return{setHttpAuthScheme(i){const a=e.findIndex(s=>s.schemeId===i.schemeId);a===-1?e.push(i):e.splice(a,1,i)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(i){t=i},httpAuthSchemeProvider(){return t},setCredentials(i){n=i},credentials(){return n}}},uQ=r=>({httpAuthSchemes:r.httpAuthSchemes(),httpAuthSchemeProvider:r.httpAuthSchemeProvider(),credentials:r.credentials()}),cQ=(r,e)=>{const t=Object.assign(VH(r),jV(r),c$(r),lQ(r));return e.forEach(n=>n.configure(t)),Object.assign(r,zH(t),GV(t),d$(t),uQ(t))};class dQ extends DV{config;constructor(...[e]){const t=oQ(e||{});super(t),this.initConfig=t;const n=Cj(t),i=gH(n),a=$$(i),s=BH(a),o=s,l=i$(o),u=wj(l),c=cQ(u,e?.extensions||[]);this.config=c,this.middlewareStack.use(_V(this.config)),this.middlewareStack.use(TH(this.config)),this.middlewareStack.use(H$(this.config)),this.middlewareStack.use(p$(this.config)),this.middlewareStack.use(q$(this.config)),this.middlewareStack.use(Y$(this.config)),this.middlewareStack.use(X$(this.config)),this.middlewareStack.use(tH(this.config,{httpAuthSchemeParametersProvider:yj,identityProviderConfigProvider:async f=>new oH({"aws.auth#sigv4":f.credentials})})),this.middlewareStack.use(sH(this.config))}destroy(){super.destroy()}}class h2 extends V1.classBuilder().ep(mP).m(function(e,t,n,i){return[eP(n,e.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityProviderService","InitiateAuth",{}).n("CognitoIdentityProviderClient","InitiateAuthCommand").sc(iQ).build(){}class fQ extends V1.classBuilder().ep(mP).m(function(e,t,n,i){return[eP(n,e.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityProviderService","RespondToAuthChallenge",{}).n("CognitoIdentityProviderClient","RespondToAuthChallengeCommand").sc(aQ).build(){}class hQ{init(e,t,n){this.cognitoClient=new dQ({region:t}),this.spiffRegion=e,this.userPoolClientId=n}async generateCode(e){const t=await this.cognitoClient?.send(new h2({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:e}}));t?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=t.Session)}async verifyCode(e,t,n){const i=await this.cognitoClient?.send(new fQ({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:e,ANSWER:t},ClientMetadata:{partnerId:n,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}async refreshTokens(){const e=localStorage.getItem("cognito-tokens");if(!e)throw new Error("Failed to find existing tokens.");const t=JSON.parse(e);return await this.cognitoClient?.send(new h2({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:t.RefreshToken||""}}))}}const Id=new hQ;var pQ={defaultAmount:0,defaultCurrency:"USD",defaultPrecision:2},gQ={globalLocale:"en-US",globalFormat:"$0,0.00",globalRoundingMode:"HALF_EVEN",globalFormatRoundingMode:"HALF_AWAY_FROM_ZERO",globalExchangeRatesApi:{endpoint:void 0,headers:void 0,propertyPath:void 0}};function nf(r){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?nf=function(e){return typeof e}:nf=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},nf(r)}function p2(r){return mQ(r)||vQ(r)||yQ(r)||AQ()}function mQ(r){if(Array.isArray(r))return r}function vQ(r){if(typeof Symbol<"u"&&Symbol.iterator in Object(r))return Array.from(r)}function yQ(r,e){if(r){if(typeof r=="string")return g2(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return g2(r,e)}}function g2(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function AQ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3055
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var bQ={normalizePrecision:function(e){var t=e.reduce(function(n,i){return Math.max(n.getPrecision(),i.getPrecision())});return e.map(function(n){return n.getPrecision()!==t?n.convertPrecision(t):n})},minimum:function(e){var t=p2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.lessThan(s)?a:s}),a},maximum:function(e){var t=p2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.greaterThan(s)?a:s}),a}};function RP(r){return!isNaN(parseInt(r))&&isFinite(r)}function wQ(r){return RP(r)&&r<=100&&r>=0}function CQ(r){return r.length>0&&r.every(function(e){return e>=0})&&r.some(function(e){return e>0})}function m2(r){return r%2===0}function v2(r){return RP(r)&&!Number.isInteger(r)}function xQ(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=r.toString();if(e.indexOf("e-")>0)return parseInt(e.split("e-")[1]);var t=e.split(".")[1];return t?t.length:0}function Pd(r){return Math.abs(r)%1===.5}function SQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(t,n){var i=Object.assign(new XMLHttpRequest,{onreadystatechange:function(){i.readyState===4&&(i.status>=200&&i.status<400?t(JSON.parse(i.responseText)):n(new Error(i.statusText)))},onerror:function(){n(new Error("Network error"))}});i.open("GET",r,!0),EQ(i,e.headers),i.send()})}function EQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};for(var t in e)r.setRequestHeader(t,e[t]);return r}function Hd(r){return typeof r>"u"}function OP(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:".",t={};return Object.entries(r).forEach(function(n){if(nf(n[1])==="object"){var i=OP(n[1]);Object.entries(i).forEach(function(a){t[n[0]+e+a[0]]=a[1]})}else t[n[0]]=n[1]}),t}function kQ(r){return!!r&&(nf(r)==="object"||typeof r=="function")&&typeof r.then=="function"}function BP(){var r=function(n,i){var a=function(l){return Math.pow(10,xQ(l))},s=Math.max(a(n),a(i));return Math.round(n*s)*Math.round(i*s)/(s*s)},e={HALF_ODD:function(n){var i=Math.round(n);return Pd(n)&&m2(i)?i-1:i},HALF_EVEN:function(n){var i=Math.round(n);return Pd(n)?m2(i)?i:i-1:i},HALF_UP:function(n){return Math.round(n)},HALF_DOWN:function(n){return Pd(n)?Math.floor(n):Math.round(n)},HALF_TOWARDS_ZERO:function(n){return Pd(n)?Math.sign(n)*Math.floor(Math.abs(n)):Math.round(n)},HALF_AWAY_FROM_ZERO:function(n){return Pd(n)?Math.sign(n)*Math.ceil(Math.abs(n)):Math.round(n)},DOWN:function(n){return Math.floor(n)}};return{add:function(n,i){return n+i},subtract:function(n,i){return n-i},multiply:function(n,i){return v2(n)||v2(i)?r(n,i):n*i},divide:function(n,i){return n/i},modulo:function(n,i){return n%i},round:function(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"HALF_EVEN";return e[i](n)}}}var TQ=BP();function FQ(r){var e=/^(?:(\$|USD)?0(?:(,)0)?(\.)?(0+)?|0(?:(,)0)?(\.)?(0+)?\s?(dollar)?)$/gm.exec(r);return{getMatches:function(){return e!==null?e.slice(1).filter(function(n){return!Hd(n)}):[]},getMinimumFractionDigits:function(){var n=function(a){return a==="."};return Hd(this.getMatches().find(n))?0:this.getMatches()[TQ.add(this.getMatches().findIndex(n),1)].split("").length},getCurrencyDisplay:function(){var n={USD:"code",dollar:"name",$:"symbol"};return n[this.getMatches().find(function(i){return i==="USD"||i==="dollar"||i==="$"})]},getStyle:function(){return Hd(this.getCurrencyDisplay(this.getMatches()))?"decimal":"currency"},getUseGrouping:function(){return!Hd(this.getMatches().find(function(n){return n===","}))}}}function IQ(r){var e=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",a=arguments.length>1?arguments[1]:void 0;for(var s in a)i=i.replace("{{".concat(s,"}}"),a[s]);return i},t=function(i,a){return SQ(e(r.endpoint,{from:i,to:a}),{headers:r.headers})};return{getExchangeRate:function(i,a){return(kQ(r.endpoint)?r.endpoint:t(i,a)).then(function(s){return OP(s)[e(r.propertyPath,{from:i,to:a})]})}}}function If(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Error;if(!r)throw new t(e)}function PQ(r){If(wQ(r),"You must provide a numeric value between 0 and 100.",RangeError)}function DQ(r){If(CQ(r),"You must provide a non-empty array of numeric values greater than 0.",TypeError)}function ty(r){If(Number.isInteger(r),"You must provide an integer.",TypeError)}var kn=BP(),RQ=function r(e){var t=Object.assign({},{amount:r.defaultAmount,currency:r.defaultCurrency,precision:r.defaultPrecision},e),n=t.amount,i=t.currency,a=t.precision;ty(n),ty(a);var s=r.globalLocale,o=r.globalFormat,l=r.globalRoundingMode,u=r.globalFormatRoundingMode,c=Object.assign({},r.globalExchangeRatesApi),f=function(g){var v=Object.assign({},Object.assign({},{amount:n,currency:i,precision:a},g),Object.assign({},{locale:this.locale},g));return Object.assign(r({amount:v.amount,currency:v.currency,precision:v.precision}),{locale:v.locale})},d=function(g){If(this.hasSameCurrency(g),"You must provide a Dinero instance with the same currency.",TypeError)};return{getAmount:function(){return n},getCurrency:function(){return i},getLocale:function(){return this.locale||s},setLocale:function(g){return f.call(this,{locale:g})},getPrecision:function(){return a},convertPrecision:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u;ty(g);var y=this.getPrecision(),A=g>y,C=A?kn.multiply:kn.divide,S=A?[g,y]:[y,g],F=Math.pow(10,kn.subtract.apply(kn,S));return f.call(this,{amount:kn.round(C(this.getAmount(),F),v),precision:g})},add:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return f.call(this,{amount:kn.add(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},subtract:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return f.call(this,{amount:kn.subtract(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},multiply:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return f.call(this,{amount:kn.round(kn.multiply(this.getAmount(),g),v)})},divide:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return f.call(this,{amount:kn.round(kn.divide(this.getAmount(),g),v)})},percentage:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return PQ(g),this.multiply(kn.divide(g,100),v)},allocate:function(g){var v=this;DQ(g);for(var y=g.reduce(function(F,E){return kn.add(F,E)}),A=this.getAmount(),C=g.map(function(F){var E=Math.floor(kn.divide(kn.multiply(v.getAmount(),F),y));return A=kn.subtract(A,E),f.call(v,{amount:E})}),S=0;A>0;)g[S]>0&&(C[S]=C[S].add(f.call(this,{amount:1})),A=kn.subtract(A,1)),S+=1;return C},convert:function(g){var v=this,y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=y.endpoint,C=A===void 0?c.endpoint:A,S=y.propertyPath,F=S===void 0?c.propertyPath||"rates.{{to}}":S,E=y.headers,R=E===void 0?c.headers:E,B=y.roundingMode,j=B===void 0?l:B,G=Object.assign({},{endpoint:C,propertyPath:F,headers:R,roundingMode:j});return IQ(G).getExchangeRate(this.getCurrency(),g).then(function(ie){return If(!Hd(ie),'No rate was found for the destination currency "'.concat(g,'".'),TypeError),f.call(v,{amount:kn.round(kn.multiply(v.getAmount(),parseFloat(ie)),G.roundingMode),currency:g})})},equalsTo:function(g){return this.hasSameAmount(g)&&this.hasSameCurrency(g)},lessThan:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<v[1].getAmount()},lessThanOrEqual:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<=v[1].getAmount()},greaterThan:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>v[1].getAmount()},greaterThanOrEqual:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>=v[1].getAmount()},isZero:function(){return this.getAmount()===0},isPositive:function(){return this.getAmount()>=0},isNegative:function(){return this.getAmount()<0},hasSubUnits:function(){return kn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasCents:function(){return kn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasSameCurrency:function(g){return this.getCurrency()===g.getCurrency()},hasSameAmount:function(g){var v=r.normalizePrecision([this,g]);return v[0].getAmount()===v[1].getAmount()},toFormat:function(){var g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:o,v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=FQ(g);return this.toRoundedUnit(y.getMinimumFractionDigits(),v).toLocaleString(this.getLocale(),{currencyDisplay:y.getCurrencyDisplay(),useGrouping:y.getUseGrouping(),minimumFractionDigits:y.getMinimumFractionDigits(),style:y.getStyle(),currency:this.getCurrency()})},toUnit:function(){return kn.divide(this.getAmount(),Math.pow(10,a))},toRoundedUnit:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=Math.pow(10,g);return kn.divide(kn.round(kn.multiply(this.toUnit(),y),v),y)},toObject:function(){return{amount:n,currency:i,precision:a}},toJSON:function(){return this.toObject()}}},OQ=Object.assign(RQ,pQ,gQ,bQ),Xa={},ry,y2;function BQ(){if(y2)return ry;y2=1;function r(t){return t}function e(t,a,s){for(var a=a||r,s=s||t,o=0,l=t.length;o<l;o+=1)if(a.call(s,t[o],o))return t[o]}return ry=e,ry}var ny={exports:{}},A2;function MQ(){if(A2)return ny.exports;A2=1;var r=ny.exports=function(e,t){if(typeof e=="function"||t)return r.by(e,t);for(var n={object:[],function:[],string:{},number:{},boolean:{},undefined:{}},i=[],a=0;a<e.length;a++){var s=e[a],o=s==="__proto__"?n.objects:n[typeof s]||n.objects;Array.isArray(o)?o.indexOf(s)<0&&(o.push(s),i.push(s)):Object.hasOwnProperty.call(o,s)||(o[s]=!0,i.push(s))}return i};return r.by=function(e,t){if(typeof e=="function"){var n=t;t=e,e=n}for(var i=[],a=0;a<e.length;a++){for(var s=e[a],o=!1,l=0;l<i.length;l++){var u=i[l];if(t.call(i,s,u)){o=!0;break}}o||i.push(s)}return i},ny.exports}var iy,b2;function _Q(){return b2||(b2=1,iy=[{code:"AED",number:"784",digits:2,currency:"UAE Dirham",countries:["United Arab Emirates (The)"]},{code:"AFN",number:"971",digits:2,currency:"Afghani",countries:["Afghanistan"]},{code:"ALL",number:"008",digits:2,currency:"Lek",countries:["Albania"]},{code:"AMD",number:"051",digits:2,currency:"Armenian Dram",countries:["Armenia"]},{code:"ANG",number:"532",digits:2,currency:"Netherlands Antillean Guilder",countries:["Curaçao","Sint Maarten (Dutch Part)"]},{code:"AOA",number:"973",digits:2,currency:"Kwanza",countries:["Angola"]},{code:"ARS",number:"032",digits:2,currency:"Argentine Peso",countries:["Argentina"]},{code:"AUD",number:"036",digits:2,currency:"Australian Dollar",countries:["Australia","Christmas Island","Cocos (Keeling) Islands (The)","Heard Island and Mcdonald Islands","Kiribati","Nauru","Norfolk Island","Tuvalu"]},{code:"AWG",number:"533",digits:2,currency:"Aruban Florin",countries:["Aruba"]},{code:"AZN",number:"944",digits:2,currency:"Azerbaijan Manat",countries:["Azerbaijan"]},{code:"BAM",number:"977",digits:2,currency:"Convertible Mark",countries:["Bosnia and Herzegovina"]},{code:"BBD",number:"052",digits:2,currency:"Barbados Dollar",countries:["Barbados"]},{code:"BDT",number:"050",digits:2,currency:"Taka",countries:["Bangladesh"]},{code:"BGN",number:"975",digits:2,currency:"Bulgarian Lev",countries:["Bulgaria"]},{code:"BHD",number:"048",digits:3,currency:"Bahraini Dinar",countries:["Bahrain"]},{code:"BIF",number:"108",digits:0,currency:"Burundi Franc",countries:["Burundi"]},{code:"BMD",number:"060",digits:2,currency:"Bermudian Dollar",countries:["Bermuda"]},{code:"BND",number:"096",digits:2,currency:"Brunei Dollar",countries:["Brunei Darussalam"]},{code:"BOB",number:"068",digits:2,currency:"Boliviano",countries:["Bolivia (Plurinational State Of)"]},{code:"BOV",number:"984",digits:2,currency:"Mvdol",countries:["Bolivia (Plurinational State Of)"]},{code:"BRL",number:"986",digits:2,currency:"Brazilian Real",countries:["Brazil"]},{code:"BSD",number:"044",digits:2,currency:"Bahamian Dollar",countries:["Bahamas (The)"]},{code:"BTN",number:"064",digits:2,currency:"Ngultrum",countries:["Bhutan"]},{code:"BWP",number:"072",digits:2,currency:"Pula",countries:["Botswana"]},{code:"BYN",number:"933",digits:2,currency:"Belarusian Ruble",countries:["Belarus"]},{code:"BZD",number:"084",digits:2,currency:"Belize Dollar",countries:["Belize"]},{code:"CAD",number:"124",digits:2,currency:"Canadian Dollar",countries:["Canada"]},{code:"CDF",number:"976",digits:2,currency:"Congolese Franc",countries:["Congo (The Democratic Republic of The)"]},{code:"CHE",number:"947",digits:2,currency:"WIR Euro",countries:["Switzerland"]},{code:"CHF",number:"756",digits:2,currency:"Swiss Franc",countries:["Liechtenstein","Switzerland"]},{code:"CHW",number:"948",digits:2,currency:"WIR Franc",countries:["Switzerland"]},{code:"CLF",number:"990",digits:4,currency:"Unidad de Fomento",countries:["Chile"]},{code:"CLP",number:"152",digits:0,currency:"Chilean Peso",countries:["Chile"]},{code:"CNY",number:"156",digits:2,currency:"Yuan Renminbi",countries:["China"]},{code:"COP",number:"170",digits:2,currency:"Colombian Peso",countries:["Colombia"]},{code:"COU",number:"970",digits:2,currency:"Unidad de Valor Real",countries:["Colombia"]},{code:"CRC",number:"188",digits:2,currency:"Costa Rican Colon",countries:["Costa Rica"]},{code:"CUC",number:"931",digits:2,currency:"Peso Convertible",countries:["Cuba"]},{code:"CUP",number:"192",digits:2,currency:"Cuban Peso",countries:["Cuba"]},{code:"CVE",number:"132",digits:2,currency:"Cabo Verde Escudo",countries:["Cabo Verde"]},{code:"CZK",number:"203",digits:2,currency:"Czech Koruna",countries:["Czechia"]},{code:"DJF",number:"262",digits:0,currency:"Djibouti Franc",countries:["Djibouti"]},{code:"DKK",number:"208",digits:2,currency:"Danish Krone",countries:["Denmark","Faroe Islands (The)","Greenland"]},{code:"DOP",number:"214",digits:2,currency:"Dominican Peso",countries:["Dominican Republic (The)"]},{code:"DZD",number:"012",digits:2,currency:"Algerian Dinar",countries:["Algeria"]},{code:"EGP",number:"818",digits:2,currency:"Egyptian Pound",countries:["Egypt"]},{code:"ERN",number:"232",digits:2,currency:"Nakfa",countries:["Eritrea"]},{code:"ETB",number:"230",digits:2,currency:"Ethiopian Birr",countries:["Ethiopia"]},{code:"EUR",number:"978",digits:2,currency:"Euro",countries:["Åland Islands","Andorra","Austria","Belgium","Croatia","Cyprus","Estonia","European Union","Finland","France","French Guiana","French Southern Territories (The)","Germany","Greece","Guadeloupe","Holy See (The)","Ireland","Italy","Latvia","Lithuania","Luxembourg","Malta","Martinique","Mayotte","Monaco","Montenegro","Netherlands (The)","Portugal","Réunion","Saint Barthélemy","Saint Martin (French Part)","Saint Pierre and Miquelon","San Marino","Slovakia","Slovenia","Spain"]},{code:"FJD",number:"242",digits:2,currency:"Fiji Dollar",countries:["Fiji"]},{code:"FKP",number:"238",digits:2,currency:"Falkland Islands Pound",countries:["Falkland Islands (The) [Malvinas]"]},{code:"GBP",number:"826",digits:2,currency:"Pound Sterling",countries:["Guernsey","Isle of Man","Jersey","United Kingdom of Great Britain and Northern Ireland (The)"]},{code:"GEL",number:"981",digits:2,currency:"Lari",countries:["Georgia"]},{code:"GHS",number:"936",digits:2,currency:"Ghana Cedi",countries:["Ghana"]},{code:"GIP",number:"292",digits:2,currency:"Gibraltar Pound",countries:["Gibraltar"]},{code:"GMD",number:"270",digits:2,currency:"Dalasi",countries:["Gambia (The)"]},{code:"GNF",number:"324",digits:0,currency:"Guinean Franc",countries:["Guinea"]},{code:"GTQ",number:"320",digits:2,currency:"Quetzal",countries:["Guatemala"]},{code:"GYD",number:"328",digits:2,currency:"Guyana Dollar",countries:["Guyana"]},{code:"HKD",number:"344",digits:2,currency:"Hong Kong Dollar",countries:["Hong Kong"]},{code:"HNL",number:"340",digits:2,currency:"Lempira",countries:["Honduras"]},{code:"HTG",number:"332",digits:2,currency:"Gourde",countries:["Haiti"]},{code:"HUF",number:"348",digits:2,currency:"Forint",countries:["Hungary"]},{code:"IDR",number:"360",digits:2,currency:"Rupiah",countries:["Indonesia"]},{code:"ILS",number:"376",digits:2,currency:"New Israeli Sheqel",countries:["Israel"]},{code:"INR",number:"356",digits:2,currency:"Indian Rupee",countries:["Bhutan","India"]},{code:"IQD",number:"368",digits:3,currency:"Iraqi Dinar",countries:["Iraq"]},{code:"IRR",number:"364",digits:2,currency:"Iranian Rial",countries:["Iran (Islamic Republic Of)"]},{code:"ISK",number:"352",digits:0,currency:"Iceland Krona",countries:["Iceland"]},{code:"JMD",number:"388",digits:2,currency:"Jamaican Dollar",countries:["Jamaica"]},{code:"JOD",number:"400",digits:3,currency:"Jordanian Dinar",countries:["Jordan"]},{code:"JPY",number:"392",digits:0,currency:"Yen",countries:["Japan"]},{code:"KES",number:"404",digits:2,currency:"Kenyan Shilling",countries:["Kenya"]},{code:"KGS",number:"417",digits:2,currency:"Som",countries:["Kyrgyzstan"]},{code:"KHR",number:"116",digits:2,currency:"Riel",countries:["Cambodia"]},{code:"KMF",number:"174",digits:0,currency:"Comorian Franc ",countries:["Comoros (The)"]},{code:"KPW",number:"408",digits:2,currency:"North Korean Won",countries:["Korea (The Democratic People’s Republic Of)"]},{code:"KRW",number:"410",digits:0,currency:"Won",countries:["Korea (The Republic Of)"]},{code:"KWD",number:"414",digits:3,currency:"Kuwaiti Dinar",countries:["Kuwait"]},{code:"KYD",number:"136",digits:2,currency:"Cayman Islands Dollar",countries:["Cayman Islands (The)"]},{code:"KZT",number:"398",digits:2,currency:"Tenge",countries:["Kazakhstan"]},{code:"LAK",number:"418",digits:2,currency:"Lao Kip",countries:["Lao People’s Democratic Republic (The)"]},{code:"LBP",number:"422",digits:2,currency:"Lebanese Pound",countries:["Lebanon"]},{code:"LKR",number:"144",digits:2,currency:"Sri Lanka Rupee",countries:["Sri Lanka"]},{code:"LRD",number:"430",digits:2,currency:"Liberian Dollar",countries:["Liberia"]},{code:"LSL",number:"426",digits:2,currency:"Loti",countries:["Lesotho"]},{code:"LYD",number:"434",digits:3,currency:"Libyan Dinar",countries:["Libya"]},{code:"MAD",number:"504",digits:2,currency:"Moroccan Dirham",countries:["Morocco","Western Sahara"]},{code:"MDL",number:"498",digits:2,currency:"Moldovan Leu",countries:["Moldova (The Republic Of)"]},{code:"MGA",number:"969",digits:2,currency:"Malagasy Ariary",countries:["Madagascar"]},{code:"MKD",number:"807",digits:2,currency:"Denar",countries:["North Macedonia"]},{code:"MMK",number:"104",digits:2,currency:"Kyat",countries:["Myanmar"]},{code:"MNT",number:"496",digits:2,currency:"Tugrik",countries:["Mongolia"]},{code:"MOP",number:"446",digits:2,currency:"Pataca",countries:["Macao"]},{code:"MRU",number:"929",digits:2,currency:"Ouguiya",countries:["Mauritania"]},{code:"MUR",number:"480",digits:2,currency:"Mauritius Rupee",countries:["Mauritius"]},{code:"MVR",number:"462",digits:2,currency:"Rufiyaa",countries:["Maldives"]},{code:"MWK",number:"454",digits:2,currency:"Malawi Kwacha",countries:["Malawi"]},{code:"MXN",number:"484",digits:2,currency:"Mexican Peso",countries:["Mexico"]},{code:"MXV",number:"979",digits:2,currency:"Mexican Unidad de Inversion (UDI)",countries:["Mexico"]},{code:"MYR",number:"458",digits:2,currency:"Malaysian Ringgit",countries:["Malaysia"]},{code:"MZN",number:"943",digits:2,currency:"Mozambique Metical",countries:["Mozambique"]},{code:"NAD",number:"516",digits:2,currency:"Namibia Dollar",countries:["Namibia"]},{code:"NGN",number:"566",digits:2,currency:"Naira",countries:["Nigeria"]},{code:"NIO",number:"558",digits:2,currency:"Cordoba Oro",countries:["Nicaragua"]},{code:"NOK",number:"578",digits:2,currency:"Norwegian Krone",countries:["Bouvet Island","Norway","Svalbard and Jan Mayen"]},{code:"NPR",number:"524",digits:2,currency:"Nepalese Rupee",countries:["Nepal"]},{code:"NZD",number:"554",digits:2,currency:"New Zealand Dollar",countries:["Cook Islands (The)","New Zealand","Niue","Pitcairn","Tokelau"]},{code:"OMR",number:"512",digits:3,currency:"Rial Omani",countries:["Oman"]},{code:"PAB",number:"590",digits:2,currency:"Balboa",countries:["Panama"]},{code:"PEN",number:"604",digits:2,currency:"Sol",countries:["Peru"]},{code:"PGK",number:"598",digits:2,currency:"Kina",countries:["Papua New Guinea"]},{code:"PHP",number:"608",digits:2,currency:"Philippine Peso",countries:["Philippines (The)"]},{code:"PKR",number:"586",digits:2,currency:"Pakistan Rupee",countries:["Pakistan"]},{code:"PLN",number:"985",digits:2,currency:"Zloty",countries:["Poland"]},{code:"PYG",number:"600",digits:0,currency:"Guarani",countries:["Paraguay"]},{code:"QAR",number:"634",digits:2,currency:"Qatari Rial",countries:["Qatar"]},{code:"RON",number:"946",digits:2,currency:"Romanian Leu",countries:["Romania"]},{code:"RSD",number:"941",digits:2,currency:"Serbian Dinar",countries:["Serbia"]},{code:"RUB",number:"643",digits:2,currency:"Russian Ruble",countries:["Russian Federation (The)"]},{code:"RWF",number:"646",digits:0,currency:"Rwanda Franc",countries:["Rwanda"]},{code:"SAR",number:"682",digits:2,currency:"Saudi Riyal",countries:["Saudi Arabia"]},{code:"SBD",number:"090",digits:2,currency:"Solomon Islands Dollar",countries:["Solomon Islands"]},{code:"SCR",number:"690",digits:2,currency:"Seychelles Rupee",countries:["Seychelles"]},{code:"SDG",number:"938",digits:2,currency:"Sudanese Pound",countries:["Sudan (The)"]},{code:"SEK",number:"752",digits:2,currency:"Swedish Krona",countries:["Sweden"]},{code:"SGD",number:"702",digits:2,currency:"Singapore Dollar",countries:["Singapore"]},{code:"SHP",number:"654",digits:2,currency:"Saint Helena Pound",countries:["Saint Helena, Ascension and Tristan Da Cunha"]},{code:"SLE",number:"925",digits:2,currency:"Leone",countries:["Sierra Leone"]},{code:"SOS",number:"706",digits:2,currency:"Somali Shilling",countries:["Somalia"]},{code:"SRD",number:"968",digits:2,currency:"Surinam Dollar",countries:["Suriname"]},{code:"SSP",number:"728",digits:2,currency:"South Sudanese Pound",countries:["South Sudan"]},{code:"STN",number:"930",digits:2,currency:"Dobra",countries:["Sao Tome and Principe"]},{code:"SVC",number:"222",digits:2,currency:"El Salvador Colon",countries:["El Salvador"]},{code:"SYP",number:"760",digits:2,currency:"Syrian Pound",countries:["Syrian Arab Republic"]},{code:"SZL",number:"748",digits:2,currency:"Lilangeni",countries:["Eswatini"]},{code:"THB",number:"764",digits:2,currency:"Baht",countries:["Thailand"]},{code:"TJS",number:"972",digits:2,currency:"Somoni",countries:["Tajikistan"]},{code:"TMT",number:"934",digits:2,currency:"Turkmenistan New Manat",countries:["Turkmenistan"]},{code:"TND",number:"788",digits:3,currency:"Tunisian Dinar",countries:["Tunisia"]},{code:"TOP",number:"776",digits:2,currency:"Pa’anga",countries:["Tonga"]},{code:"TRY",number:"949",digits:2,currency:"Turkish Lira",countries:["Türki̇ye"]},{code:"TTD",number:"780",digits:2,currency:"Trinidad and Tobago Dollar",countries:["Trinidad and Tobago"]},{code:"TWD",number:"901",digits:2,currency:"New Taiwan Dollar",countries:["Taiwan (Province of China)"]},{code:"TZS",number:"834",digits:2,currency:"Tanzanian Shilling",countries:["Tanzania, United Republic Of"]},{code:"UAH",number:"980",digits:2,currency:"Hryvnia",countries:["Ukraine"]},{code:"UGX",number:"800",digits:0,currency:"Uganda Shilling",countries:["Uganda"]},{code:"USD",number:"840",digits:2,currency:"US Dollar",countries:["American Samoa","Bonaire, Sint Eustatius and Saba","British Indian Ocean Territory (The)","Ecuador","El Salvador","Guam","Haiti","Marshall Islands (The)","Micronesia (Federated States Of)","Northern Mariana Islands (The)","Palau","Panama","Puerto Rico","Timor-Leste","Turks and Caicos Islands (The)","United States Minor Outlying Islands (The)","United States of America (The)","Virgin Islands (British)","Virgin Islands (u.s.)"]},{code:"USN",number:"997",digits:2,currency:"US Dollar (Next day)",countries:["United States of America (The)"]},{code:"UYI",number:"940",digits:0,currency:"Uruguay Peso en Unidades Indexadas (UI)",countries:["Uruguay"]},{code:"UYU",number:"858",digits:2,currency:"Peso Uruguayo",countries:["Uruguay"]},{code:"UYW",number:"927",digits:4,currency:"Unidad Previsional",countries:["Uruguay"]},{code:"UZS",number:"860",digits:2,currency:"Uzbekistan Sum",countries:["Uzbekistan"]},{code:"VED",number:"926",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VES",number:"928",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VND",number:"704",digits:0,currency:"Dong",countries:["Viet Nam"]},{code:"VUV",number:"548",digits:0,currency:"Vatu",countries:["Vanuatu"]},{code:"WST",number:"882",digits:2,currency:"Tala",countries:["Samoa"]},{code:"XAF",number:"950",digits:0,currency:"CFA Franc BEAC",countries:["Cameroon","Central African Republic (The)","Chad","Congo (The)","Equatorial Guinea","Gabon"]},{code:"XAG",number:"961",digits:0,currency:"Silver",countries:["Zz11_silver"]},{code:"XAU",number:"959",digits:0,currency:"Gold",countries:["Zz08_gold"]},{code:"XBA",number:"955",digits:0,currency:"Bond Markets Unit European Composite Unit (EURCO)",countries:["Zz01_bond Markets Unit European_eurco"]},{code:"XBB",number:"956",digits:0,currency:"Bond Markets Unit European Monetary Unit (E.M.U.-6)",countries:["Zz02_bond Markets Unit European_emu-6"]},{code:"XBC",number:"957",digits:0,currency:"Bond Markets Unit European Unit of Account 9 (E.U.A.-9)",countries:["Zz03_bond Markets Unit European_eua-9"]},{code:"XBD",number:"958",digits:0,currency:"Bond Markets Unit European Unit of Account 17 (E.U.A.-17)",countries:["Zz04_bond Markets Unit European_eua-17"]},{code:"XCD",number:"951",digits:2,currency:"East Caribbean Dollar",countries:["Anguilla","Antigua and Barbuda","Dominica","Grenada","Montserrat","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines"]},{code:"XDR",number:"960",digits:0,currency:"SDR (Special Drawing Right)",countries:["International Monetary Fund (Imf) "]},{code:"XOF",number:"952",digits:0,currency:"CFA Franc BCEAO",countries:["Benin","Burkina Faso","Côte D'ivoire","Guinea-Bissau","Mali","Niger (The)","Senegal","Togo"]},{code:"XPD",number:"964",digits:0,currency:"Palladium",countries:["Zz09_palladium"]},{code:"XPF",number:"953",digits:0,currency:"CFP Franc",countries:["French Polynesia","New Caledonia","Wallis and Futuna"]},{code:"XPT",number:"962",digits:0,currency:"Platinum",countries:["Zz10_platinum"]},{code:"XSU",number:"994",digits:0,currency:"Sucre",countries:['Sistema Unitario De Compensacion Regional De Pagos "Sucre"']},{code:"XTS",number:"963",digits:0,currency:"Codes specifically reserved for testing purposes",countries:["Zz06_testing_code"]},{code:"XUA",number:"965",digits:0,currency:"ADB Unit of Account",countries:["Member Countries of the African Development Bank Group"]},{code:"XXX",number:"999",digits:0,currency:"The codes assigned for transactions where no currency is involved",countries:["Zz07_no_currency"]},{code:"YER",number:"886",digits:2,currency:"Yemeni Rial",countries:["Yemen"]},{code:"ZAR",number:"710",digits:2,currency:"Rand",countries:["Lesotho","Namibia","South Africa"]},{code:"ZMW",number:"967",digits:2,currency:"Zambian Kwacha",countries:["Zambia"]},{code:"ZWG",number:"924",digits:2,currency:"Zimbabwe Gold",countries:["Zimbabwe"]}]),iy}var ay,w2;function NQ(){return w2||(w2=1,ay="2024-06-25"),ay}var C2;function LQ(){if(C2)return Xa;C2=1;var r=BQ(),e=MQ(),t=_Q(),n=NQ(),i=function(c){return c=c.toUpperCase(),r(t,function(f){return f.code===c})},a=function(c){return c=c.toLowerCase(),t.filter(function(f){return(f.countries.map(function(d){return d.toLowerCase()})||[]).indexOf(c)>-1})},s=function(c){return r(t,function(f){return f.number===String(c)})},o=function(){return t.map(function(c){return c.code})},l=function(){var c=t.map(function(f){return f.number});return c.filter(function(f){if(f)return f})},u=function(){var c=t.filter(function(f){return f.countries}).map(function(f){return f.countries});return e(Array.prototype.concat.apply([],c))};return Xa.code=i,Xa.country=a,Xa.number=s,Xa.codes=o,Xa.numbers=l,Xa.countries=u,Xa.publishDate=n,Xa.data=t,Xa}var x2=LQ();class MP{formatCurrencyForDisplay(e,t){const n={amount:t||0,currency:e,precision:this.getPrecisionForCurrency(e)};return OQ(n).toFormat(this.getSpecialFormat(e))}getPrecisionForCurrency(e){const t=e,n=x2.code(t);return n?n.digits:2}getSpecialFormat(e){const t=e;if(x2.code(t)?.code==="CLP")return"USD0,0"}}const S2=new MP;class _P{constructor(e,t,n,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,this.partnerCurrency=n,this.rateFrom=e,this.rateTo=t}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(e){return this.conversionRequired()?Math.ceil(this.subunits(this.units(e,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):e}units(e,t){return e/Math.pow(10,S2.getPrecisionForCurrency(t))}subunits(e,t){return e*Math.pow(10,S2.getPrecisionForCurrency(t))}}const UQ=async(r,e)=>{const t=q3(e?.assets?.metadata||!1),n={ids:r};console.log("[getWorkflowsInternal] Requesting workflows.",{url:`${ss.getServerUrl()}/graphql`,variables:JSON.stringify(n)}),console.log(`[getWorkflowsInternal] Query:
3056
+ ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:"all",variables:n,context:{logRequestHeaders:!0}});if(i.error)throw console.log("[getWorkflowsInternal] Response errored."),i.error;if(i.errors)throw i.errors.forEach(s=>console.error(s)),new Error("Unable to read workflows. Consult GraphQL errors.");if(!i.data.workflows||i.data.workflows.length!==r.length)throw new Error(`Unable to read workflows: ${i.errors??"Length mismatch in response"}`);const a=mo(i.data.workflows);return a.forEach(s=>{s.finalizeStepConfig||(s.finalizeStepConfig={}),s.finalizeStepConfig.termsMarkdown=s.finalizeStepConfig.termsMarkdown||s.partner.termsMarkdown}),a},VQ=async(r,e)=>{const n=(await e).find(i=>i.id===r);if(!n)throw new Error(`Workflow not found: ${r}`);return n},ew=async(r,e)=>{const t=r.map(o=>mf.get({id:o,options:e})),n=r.filter((o,l)=>t[l]===void 0);if(n.length===0)return Promise.all(t);const i=UQ(n,e),a=n.map(o=>mf.set({id:o,options:e},VQ(o,i))),s=t.filter(o=>o!==void 0);return await Promise.all(s.concat(a))},NP=async(r,e)=>(await ew([r],e))[0],LP=async r=>{const e=await ze.getShadowGraphqlClient().query({query:yT,variables:{ids:r},errorPolicy:"all",fetchPolicy:"no-cache"});return e.errors&&console.error(e.errors),e.data.integrationProducts||[]};class zQ{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return ze.getShadowGraphqlClient().mutate({...t,mutation:D3})}catch(n){throw console.error(n),new lo("Critical - Unable to synchronize workflow state with server.")}},this.options=e,this.options.applicationKey&&Yk(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 44.5.5-alpha.4"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(e){ss.setHubUrl(e.hubUrl),ss.setServerUrl(e.serverUrl),ss.setServicesApiUrl(e.servicesApiUrl),this.marketplaceThemeInstallId=e.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=e.marketplaceThemeInstallConfigurationId,this.userPoolClientId=e.userPoolClientId,this.userPoolRegion=e.userPoolRegion,this.spiffRegion=e.spiffRegion,e.bearerAuthenticationToken&&Jk(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Id.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getVersion(){return"44.5.5-alpha.4"}getAssetManager(){return Ln}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!J4())throw new Error("Application key required to use Flow Service.");return new BI}async getCurrencyContext(e){const n=(await this.getIntegration()).partner.currencyCode,a=await ze.getShadowGraphqlClient().query({query:K3,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:e}}),{rateFrom:s,rateTo:o}=a.data.currencyConversion;return new _P(s,o,n,e)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=UP(this.options.applicationKey),this.activeIntegration}async canUseAddon(e){try{return(await this.getIntegration()).partner.activeAddons?.includes(e)??!1}catch(t){return console.error(t),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(e){const t=wr.getMap("transactionCustomerIds");t?.has(e)&&(t.delete(e),wr.setMap("transactionCustomerIds",t))}async customerHasBundleTemplates(e){const i=(await ze.getShadowGraphqlClient().query({query:Ov,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(e){const t=this.customer?.stakeholders?.find(n=>n.transaction?.id===e);if(t)return t.type}async getOrCreateCustomer(e){this.customer=void 0;const t=ze.getShadowGraphqlClient(),i=(await t.query({query:Ov,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!i.id){const o=(await t.mutate({mutation:bV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:e}}})).data?.customerCreate;if(!o)throw new Error("Unable to create customer.");return this.storeCustomer(o),this.customer=o,{customer:o,isAuthenticated:!1}}this.storeCustomer(i);const a=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:a}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens"),n=localStorage.getItem("cognito-email");if(!e||!t||!n)return!1;const i=JSON.parse(t),a=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<a-parseInt(e)){const u=await Id.refreshTokens();if(u?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=u.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=localStorage.getItem("customer-login-token");s&&p0(s);const l=(await ze.getShadowGraphqlClient().query({query:Ov,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:n}})).data.customer;return l.id?(this.customer=l,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(e){await ze.getShadowGraphqlClient().mutate({mutation:wV,variables:{emailAddress:e}}),await Id.generateCode(e)}async verifyCode(e,t){const n=(await this.getIntegration()).partner.id||"",i=await Id.verifyCode(e,t,n);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",e);const s=(await ze.getShadowGraphqlClient().mutate({mutation:CV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e,verificationCode:t}})).data?.customerVerifyCode;if(!s?.id)throw new Error("Failed to get customer.");return this.customer=s,s.loginToken&&(localStorage.setItem("customer-login-token",s.loginToken),p0(s.loginToken)),!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),localStorage.removeItem("customer-login-token"),p0(""),this.clearCustomer()}async loggedInBearerToken(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens");if(!e||!t)throw new Error("No token data in storage.");const n=JSON.parse(t),i=new Date().getTime()/1e3,a=!n?.AccessToken||vg(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(e)||a){const s=await Id.refreshTokens();if(s?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!n.AccessToken)throw new Error("No bearer token in storage.");return n.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await ze.getShadowGraphqlClient().query({query:xV,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(e,t,n,i){const s=(await ze.getShadowGraphqlClient().mutate({mutation:i9(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((c,f)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,activationId:i,test:n?.test},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!s?.id)throw new Error("Unable to create bundle");const o=wr.getMap("bundlePartnerIds")||new Map;o.set(s.id,s.partner.id),wr.setMap("bundlePartnerIds",o);const l=wr.getMap("bundleOwnerIds")||new Map;l.set(s.id,s.bundleOwnerId),wr.setMap("bundleOwnerIds",l);const u=new DE(this,s,void 0,void 0,s.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts});return await u.getInitializationPromise(),u}async getExistingBundle(e,t,n,i,a){const o=wr.getMap("bundleOwnerIds")?.get(e),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const y=Object.entries(localStorage).find(([C,S])=>C.startsWith("CognitoIdentityServiceProvider")&&C.endsWith("idToken"))?.[0]||"",A=localStorage.getItem(y);A&&!vg(A)&&(l.Authorization=`Bearer ${A}`)}const u={bundleOwnerId:o,...l,...i?.graphql?.additionalHeaders},c=await ze.getShadowGraphqlClient().query({query:e9(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:e},fetchPolicy:"no-cache",context:{headers:u}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${e}`);const f=c.data?.bundles[0],d=wr.getMap("bundlePartnerIds")||new Map;d.set(f.id,f.partner.id),wr.setMap("bundlePartnerIds",d);const h=new DE(this,f,t,n,o,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:i?.readonly},a);return await h.getInitializationPromise(),h}async duplicateBundle(e,t,n,i){const s={...await $P(e),...i?.graphql?.additionalHeaders},l=(await ze.getShadowGraphqlClient().mutate({mutation:a9(),variables:{id:e,template:t,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n,test:i?.test},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const u=wr.getMap("bundlePartnerIds")||new Map;u.set(l.id,l.partner.id),wr.setMap("bundlePartnerIds",u);const c=wr.getMap("bundleOwnerIds")||new Map;return c.set(l.id,l.bundleOwnerId),wr.setMap("bundleOwnerIds",c),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(e){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:t,...n}=e;return(await ze.getShadowGraphqlClient().query({query:m9(t??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const e=await ze.getShadowGraphqlClient().query({query:t9,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!e.data?.customers||e.data.customers.length===0)throw new Error("Unable to find customer.");const n=e.data.customers[0].bundleStakeholders||[],i=wr.getMap("bundlePartnerIds")||new Map;return n.forEach(a=>{a.bundle?.id&&a.bundle.partner?.id&&i.set(a.bundle.id,a.bundle.partner.id)}),wr.setMap("bundlePartnerIds",i),n}async getWorkflowExperience(e,t){if(!e)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const n=await this.getWorkflowExperiences([e],e.graphql),i=n[0],a=i.getWorkflow();return t&&!a&&console.error("No workflow instantiated when trying to create preview service."),t&&a&&await i.getWorkflowManager().injectIntoPreviewService(t(a)),n[0]}async getWorkflowExperiences(e,t,n,i){if(e.length===0)throw new lo("No options provided!");const a=e.map((q,Y)=>({option:q,index:Y})),s=a.filter(q=>q.option.type==="transaction"),o=a.filter(q=>q.option.type==="integration"||q.option.type==="external"||q.option.type==="blank"),l=50,u=fA(s,l),c=fA(o,l);let f=0;const d=ze.getShadowGraphqlClient(),h=async q=>{if(q.length===0)return[];const Y=q.map(oe=>oe.option.transactionId),J=await d.query({query:P3,variables:{ids:Y},errorPolicy:"all",fetchPolicy:"no-cache"}),ae=J.data.transactions;if(f=f+ae.length,i&&i(f,s.length),ae.length!==q.length){const oe=J.errors?.[0]?.message||"Unknown error";throw new lo(`Not all transactions were found: ${oe}`)}return!this.activeIntegration&&ae[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(ae[0].integrationProduct.integration)),ae.map((oe,he)=>({transaction:oe,workflowId:oe.workflowId,readOnly:q.find(ye=>ye.option.transactionId===oe.id)?.option.readOnly??!1,index:q[he].index}))},g=async q=>{if(q.length===0)return[];const Y=await d.mutate({mutation:I3,variables:{inputs:q.map(ae=>({integrationProductId:ae.option.type==="integration"?ae.option.integrationProductId:void 0,externalIntegrationId:ae.option.type==="external"?ae.option.externalIntegrationId:void 0,externalProductId:ae.option.type==="external"?ae.option.externalProductId:void 0,workflowId:ae.option.workflowId,designName:ae.option.designName,claim:!0,quantity:ae.option.quantity,recipient:ae.option.recipient,parentTransactionId:ae.option.parentTransactionId})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.getCreateTransactionContext(q,t)}),J=Y.data?.transactionCreateMany;if(!J||J.length===0){const ae=Y.errors?.[0]?.message||"Unknown error";throw new lo(`Failed to create transactions: ${ae}`)}return f=f+J.length,i&&i(f,s.length),J.map((ae,oe)=>({transaction:ae,workflowId:ae.workflowId,readOnly:!1,index:q[oe].index}))},v=(await Promise.all([...u.map(h),...c.map(g)])).flat();let y=[...new Set(v.map(q=>q.transaction.integrationProductId))].filter(q=>!!q);y=y.filter(q=>!!q);let A=[...new Set(v.map(q=>q.workflowId))].filter(q=>!!q);A=A.filter(q=>!!q);const[C,S]=await Promise.all([(async()=>y.length>0?await LP(y):[])(),(async()=>A.length>0?await ew(A,t):[])()]),F=new Map(C.map(q=>[q.id,q])),E=new Map(S.map(q=>[q.id,q])),R=v.map(async q=>{const{transaction:Y,workflowId:J,readOnly:ae,index:oe}=q,he=J?E.get(J):void 0,ye=e[oe];if(Y.integrationProductId){const re=F.get(Y.integrationProductId);Y.integrationProduct=re,Y.product=re?.product,Y.integrationProduct||console.error("failed to find transaction's product")}const Ue=wr.getMap("transactionOwnerIds")||new Map;!Ue.get(Y.id)&&Y.transactionOwnerId&&(Ue.set(Y.id,Y.transactionOwnerId),wr.setMap("transactionOwnerIds",Ue));const Re=Ue.get(Y.id)||void 0,Oe=new SV({onMutate:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}})}),ee={workflow:he,transaction:Y,singleVariantsRenderable:ye?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:ae?async()=>{throw new nn("State mutation is forbidden in read only mode!")}:async re=>this.updateTransactionState({...re,context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),graphQlClient:()=>Oe,readOnly:ae,isReloadedTransaction:ye.type==="transaction"};if(ye.type==="transaction"&&Y.workflowState){const re=JSON.parse(Y.workflowState);await sA(re),ee.reloadedState=re}else if(!ae&&ye.workflowState){const re=JSON.parse(ye.workflowState);await sA(re),ee.reloadedState=re}return ee.delayWorkflowStateSync=!0,{experienceOptions:ee,index:oe,options:ye}}),j=(await Promise.all(R)).sort((q,Y)=>q.index-Y.index);let G=[],ie=[];for(const q of j){const{experienceOptions:Y,options:J}=q,ae=new B1(this,Y);await ae.getWorkflowManager().getInitializationPromise(),n&&n(),J.type!=="transaction"&&this.customer&&ie.push(ae),G=[...G,ae],ae.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}if(ie.length>0){const q=this.customer.emailAddress,Y=ie.map(oe=>oe.getTransaction().id),ae=(await d.mutate({mutation:Q9,variables:{ids:Y,details:{emailAddress:q},type:"Owner"},errorPolicy:"all"})).data?.transactionsAddStakeholder;if(ae&&ae?.length>0){const oe=ae[0].stakeholders?.find(he=>he.customer?.emailAddress===q);if(oe?.customer)for(const he of ie)he.assignCustomerInternal(oe.customer)}}return G}getCreateTransactionContext(e,t){const n=e.find(s=>s.option.parentTransactionId)?.option.parentTransactionId;if(!n&&!t?.bundleOwnerId)return;const i=wr.getMap("transactionOwnerIds")||new Map,a=n?i.get(n):void 0;return{...a?{transactionOwnerId:a}:{},...t?.bundleOwnerId?{bundleOwnerId:t.bundleOwnerId}:{}}}storeCustomer(e){const t=wr.getMap("partnerCustomerIds")||new Map;t.set(e.partner.id,e.id),wr.setMap("partnerCustomerIds",t)}async getIntegrationProductById(e,t){const a=(await ze.getShadowGraphqlClient().query({query:L3(t),variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!a||a.length===0||!a[0]?.id)throw new Error("Integration product not found.");return new gA(a[0])}async getIntegrationProductFromExternalIds(e,t,n){const s=(await ze.getShadowGraphqlClient().query({query:U3(n),variables:{externalProductId:t,externalIntegrationId:e},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!s?.id)throw new Error("Integration product not found.");return new gA(s)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}async getShareActionsForTransaction(e){const n=(wr.getMap("transactionOwnerIds")||new Map).get(e)||void 0,i=await ze.getShadowGraphqlClient().query({query:_3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e},context:{transactionOwnerId:n}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${e}`);return i.data.transactions[0].transactionShareActions}async placeOrder(e){const t=await ze.getShadowGraphqlClient().mutate({mutation:J3,variables:{orderItems:e}});if(t.errors)throw new Error(t.errors[0].message);if(!t.data)throw new Error("Failed to create order: No order data in response.");return{id:t.data.orderCreate.id,internalId:t.data.orderCreate.internalId}}}const UP=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:Q3,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r},skipIntegrationCheck:!0},variables:{themeConfigurationId:e}})).data.currentIntegration,$Q=async r=>{const t=await ze.getShadowGraphqlClient().query({query:M3,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(t.data.transactions.length!==0)return t.data.transactions[0]},HQ=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:W3,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:e}})).data?.marketplaceThemeInstallConfiguration,jQ=async r=>(await ze.getShadowGraphqlClient().query({query:X3,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,GQ=async r=>(await ze.getShadowGraphqlClient().query({query:Y3,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,VP=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:aM(!!e),errorPolicy:"all",variables:{id:r,productIds:e}})).data?.activation,qQ=async r=>(await VP(r))?.marketplaceThemeInstallConfiguration;async function zP(){const r={};try{const e=await this.loggedInBearerToken();r.Authorization=`Bearer ${e}`}catch{const n=Object.entries(localStorage).find(([a,s])=>a.startsWith("CognitoIdentityServiceProvider")&&a.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(n);i&&!vg(i)&&(r.Authorization=`Bearer ${i}`)}return r}async function $P(r){const t=wr.getMap("bundleOwnerIds")?.get(r),n=await zP();return{bundleOwnerId:t,...n}}async function WQ(r){const t=wr.getMap("transactionOwnerIds")?.get(r),n=await zP();return{transactionOwnerId:t,...n}}const QQ=async r=>{const e=await $P(r),t=await ze.getShadowGraphqlClient().mutate({mutation:E9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r},context:{headers:e}});if(t.data?.bundleDelete!==r)throw new Error(`Failed to delete bundle: ${t.errors}`)},YQ=async r=>{const e=await WQ(r),t=await ze.getShadowGraphqlClient().mutate({mutation:k9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[r]},context:{headers:e}});if(!t.data?.transactions||t.data.transactions.length!==1||t.data.transactions[0].id!==r)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(t.errors)}`);return t.data.transactions[0].bundle?.id};function HP(r,e,t,n){const i=t.width*r.zoom,a=t.height*r.zoom;if(n){const s=Math.max(e.width/t.width,e.height/t.height),o=Math.max(s,r.zoom),l=t.width*o,u=t.height*o;return{...r,x:Dp(r.x,e.width-l,0),y:Dp(r.y,e.height-u,0),zoom:o}}return{...r,x:Dp(r.x,-i,e.width),y:Dp(r.y,-a,e.height)}}function Dp(r,e,t){return Math.min(Math.max(r,e),t)}class jP{constructor(e,t){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=FI(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.onRotationChangeListeners=[],this.forceImageCover=e,this.initialZoom=t,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(e,t){t&&e.addStepSpecificStorageCallback(async n=>{if(n){const i=n;if(i.currentFrameSources){let a=!1;for(let s=0;s<i.currentFrameSources.length;s++){const o=i.currentFrameSources[s],l=await Xf(o),u=this.frameData?this.frameData[s]:void 0;vf(l,u)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[s]=l,a=!0)}a&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},t),this.workflowManager=e,this.stepName=t}setTargetElements(e){this.targetElements=e}getFrameData(){return this.frameData}setFrameData(e){if(!e){this.frameData=void 0;return}e.forEach((t,n)=>{const i=_u.get(t);i&&(this.frameData||(this.frameData=new Array(e.length)),this.frameData[n]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const e=zg(this.imageData.svg,this.imageData.colors||{},!1);return Ug(e)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(e){this.offsets=e}setZoom(e,t,n,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const a=this.frameData.map((s,o)=>{const l=(t[o]-this.offsets[o].x)/this.offsets[o].zoom,u=(n[o]-this.offsets[o].y)/this.offsets[o].zoom,c=t[o]-l*e[o],f=n[o]-u*e[o];return{x:c,y:f,zoom:this.imageData.width*e[o]/this.imageData.width,rotation:this.offsets[o].rotation}});this.updateOffsets(a,i),this.onZoomChangeListeners.forEach(s=>s(e))}}setRotation(e,t){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const n=this.frameData.map((i,a)=>({...this.offsets[a],rotation:e[a]}));this.updateOffsets(n,t),this.onRotationChangeListeners.forEach(i=>i(e))}}setPatternData(e,t=!0){this.imageData=e,e&&this.frameData&&((t||!this.offsets)&&this.recalculateOffsets(e,t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(e,t,n){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==e.length)throw new nn("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(e[o].x===s.x&&e[o].y===s.y&&e[o].zoom===s.zoom&&e[o].rotation===s.rotation))&&!n){t&&t();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=HP(e[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.thresholdSettings,t)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(e){this.thresholdSettings=e,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,e)}onFrameDataChanged(e){e(this.frameData),this.onFrameDataChangeListeners.push(e)}onZoom(e){this.onZoomChangeListeners.push(e)}onRotation(e){this.onRotationChangeListeners.push(e)}updateFrameOffsets(e,t,n,i,a){if(!n||n.length===0||n.some(l=>!l))throw new nn("Frame data not set. This is a bug");if(!this.workflowManager)throw new nn("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getRegionElements(this.stepName||""),o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,u)=>{let c=s.find(f=>f.id===l)?.regionIndex??u;c>=e.length&&(c=u);try{o(new On([new wL(l,t,e[c]),new CL(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}catch{}}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:e}),a&&a()}recalculateZoomLimits(e,t){(this.minZoomScale.length!==t.length||this.maxZoomScale.length!==t.length)&&(this.minZoomScale=new Array(t.length),this.maxZoomScale=new Array(t.length)),t.forEach((n,i)=>{const a=Math.max(n.width/e.width,n.height/e.height);this.forceImageCover?(this.minZoomScale[i]=a,this.maxZoomScale[i]=a*2.5):(this.minZoomScale[i]=a/10,this.maxZoomScale[i]=a*2.5)})}recalculateOffsets(e,t=!0){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((n,i)=>{const a=t?0:this.offsets[i]?.rotation||0;this.offsets[i]={...C1(e,n,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover),rotation:a}}),this._debouncedUpdateFrameOffsets(this.offsets,e,this.frameData,this.thresholdSettings))}}class XQ{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,v,y,A){throw new Error("Method not implemented.")}approveTransaction(e){throw new Error("Method not implemented.")}rejectTransaction(e){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(e){this.client=e}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(e){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,n){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}injectIntoPreviewService(e){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(e){}async updateTransactionShareActions(){}addValidationCallback(e){}setStepError(e,t,n){}getStepErrors(e){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(e){return[]}}var GP=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(GP||{}),qP=(r=>(r.Original="original",r.BackgroundRemoved="backgroundRemoved",r.Optimized="optimized",r))(qP||{});class WP extends Ui{constructor(e,t,n){super(e,t,n);const i=t.data;this.frameService=new jP(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(e,t.stepName)}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return so.selectVariant(this.step,e.getResource(),t,this.manager,n=>this.setUpdateState(n))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}async selectImage(e,t=!0,n=!0){await so.selectImage(this.step,e,this.manager,n),t&&this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,enhancedAssetKey:void 0,useOriginalAsset:void 0}})}async canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Bg.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImageSelection();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const n=await Ln.removeBackgroundFromAsset(t);e&&await so.selectImage(this.step,n,this.manager,!1);const i=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:n.key,useOriginalAsset:!e}}),n}async vectorize(e,t=void 0){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to vectorize the image.");const i=await Ln.vectorizeAsset(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,vectorizedAssetKey:i.key,useOriginalAsset:!1}}),i}async enhanceWithAI(e,t){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to enhance the image with AI.");const i=await Ln.enhanceWithAI(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:a.originalAssetKey,backgroundRemovedAssetKey:a.backgroundRemovedAssetKey,vectorizedAssetKey:a.vectorizedAssetKey,enhancedAssetKey:i.key,useOriginalAsset:!1}}),i}async getBackgroundRemovedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getVectorizedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getEnhancedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}hasOriginalImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}hasEnhancedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey}async changeColors(e){await so.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?so.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e?.svg?(await Pa(e.svg)).colors:void 0}async mergeColors(e,t,n){const i=this.frameService.getImageData();if(!i?.svg||!i.colors)throw new Error("Cannot merge colors on non-SVG image or image without color information");const{svg:a,colors:s}=fT(i.svg,i.colors,e,t,n);this.frameService.setPatternData({...i,svg:a,colors:s},!1),this.manager.updateStorage(this.step.stepName,{colors:s})}async unmergeColors(e,t,n,i){const a=this.frameService.getImageData();if(!a?.svg||!a.colors)throw new Error("Cannot unmerge colors on non-SVG image or image without color information");this.frameService.setPatternData({...a,svg:i,colors:n},!1),this.manager.updateStorage(this.step.stepName,{colors:n})}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMinimumPixelThresholdForOptimization(){return this.step.data.vectorizationMinimumPixelThreshold}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return so.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(e,t,n,i){return i&&i.length>1&&e===void 0?"SelectFrame":t||n||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.originalAssetKey;if(e)return Ln.getLocalOrFromServer(e)}getCurrentImageState(){const e=this.getFrameStepStorage()?.framePatternData;return e?e.vectorizedAssetKey&&!e.useOriginalAsset?"optimized":e.useOriginalAsset!==!1?"original":"backgroundRemoved":"original"}async setImageState(e){const t=this.getFrameStepStorage()?.framePatternData||{};let n,i;switch(e){case"original":if(n=await this.getOriginalImageSelection(),!n)throw new Error("No original image available");i=!0;break;case"backgroundRemoved":if(n=await this.getBackgroundRemovedImageSelection(),!n)throw new Error("No background-removed image available. Call removeBackgroundFromImageSelection first.");i=!1;break;case"optimized":if(n=await this.getVectorizedImageSelection(),!n)throw new Error("No optimized image available. Call vectorize first.");i=!1;break}await this.selectImage(n,!1,!0),this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:i}})}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(e){const t=this.getFrameStepStorage()?.framePatternData||{};if(t.useOriginalAsset===e)return;const n=await this.getOriginalImageSelection();if(!n)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(e)await this.selectImage(n,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:e}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const JQ=Se`
3057
3057
  query GetLoggedInCustomer($email: String!) {
3058
3058
  customer(emailAddress: $email) {
3059
3059
  id
@@ -3097,21 +3097,21 @@ ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:
3097
3097
  total
3098
3098
  }
3099
3099
  }
3100
- `,XQ=Se`
3100
+ `,KQ=Se`
3101
3101
  mutation SetTransactionDesignName($id: String!, $name: String!) {
3102
3102
  transactionUpdate(id: $id, designName: $name) {
3103
3103
  id
3104
3104
  designName
3105
3105
  }
3106
3106
  }
3107
- `,JQ=Se`
3107
+ `,ZQ=Se`
3108
3108
  mutation DuplicateTransaction($id: String!, $template: Boolean!) {
3109
3109
  transactionDuplicate(id: $id, template: $template) {
3110
3110
  id
3111
3111
  workflowViewerLink
3112
3112
  }
3113
3113
  }
3114
- `,KQ=Se`
3114
+ `,eY=Se`
3115
3115
  query GetCustomerBundles($id: String!, $limit: Int!, $offset: Int!) {
3116
3116
  customerBundlesFeed(id: $id, limit: $limit, offset: $offset) {
3117
3117
  items {
@@ -3126,7 +3126,7 @@ ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:
3126
3126
  total
3127
3127
  }
3128
3128
  }
3129
- `,ZQ=Se`
3129
+ `,tY=Se`
3130
3130
  query GetTransactionsForBundle($id: String!) {
3131
3131
  bundles(ids: [$id]) {
3132
3132
  id
@@ -3150,14 +3150,14 @@ ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:
3150
3150
  }
3151
3151
  }
3152
3152
  }
3153
- `,eY=Se`
3153
+ `,rY=Se`
3154
3154
  mutation SetBundleName($id: String!, $name: String!) {
3155
3155
  bundleUpdate(id: $id, name: $name) {
3156
3156
  id
3157
3157
  name
3158
3158
  }
3159
3159
  }
3160
- `,tY=Se`
3160
+ `,nY=Se`
3161
3161
  mutation DuplicateBundle($id: String!, $template: Boolean!, $test: Boolean) {
3162
3162
  bundleDuplicate(id: $id, template: $template, test: $test) {
3163
3163
  id
@@ -3165,7 +3165,7 @@ ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:
3165
3165
  workflowViewerLink
3166
3166
  }
3167
3167
  }
3168
- `,rY=Se`
3168
+ `,iY=Se`
3169
3169
  query GetBundleTemplates($id: String!, $limit: Int!, $offset: Int!) {
3170
3170
  customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: true) {
3171
3171
  items {
@@ -3178,7 +3178,7 @@ ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:
3178
3178
  total
3179
3179
  }
3180
3180
  }
3181
- `,nY=async(r,e,t)=>await ze.getShadowGraphqlClient().mutate({mutation:eY,errorPolicy:"all",variables:{id:r,name:e},context:t}),iY=async(r,e)=>await ze.getShadowGraphqlClient().mutate({mutation:XQ,errorPolicy:"all",variables:{id:r,name:e}}),aY=async(r,e,t)=>await ze.getShadowGraphqlClient().mutate({mutation:tY,errorPolicy:"all",variables:{id:r,template:e,test:t}}),sY=async(r,e)=>await ze.getShadowGraphqlClient().mutate({mutation:JQ,errorPolicy:"all",variables:{id:r,template:e}}),oY=async r=>(await ze.getShadowGraphqlClient().query({query:YQ,errorPolicy:"all",variables:{email:r}})).data.customer,lY=async(r,e,t)=>await ze.getShadowGraphqlClient().query({query:KQ,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,offset:t,limit:e}}),uY=async(r,e)=>await ze.getShadowGraphqlClient().query({query:ZQ,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r},context:e}),cY=async(r,e,t)=>(await ze.getShadowGraphqlClient().query({query:tw,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,quicksearch:"",filters:{link:"and",status:{operator:"isAnyOf",values:["Created","DesignCompleted","ExternallyOrdered"]},template:{value:"false"}},offset:t,limit:e}}))?.data.customerTransactionsFeed?.items||[],dY=async(r,e,t)=>(await ze.getShadowGraphqlClient().query({query:tw,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,quicksearch:"",filters:{link:"and",status:{operator:"equals",value:"Ordered"},template:{value:"false"}},offset:t,limit:e}}))?.data.customerTransactionsFeed?.items||[],fY=async(r,e,t)=>(await ze.getShadowGraphqlClient().query({query:tw,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,quicksearch:"",filters:{link:"and",template:{value:"true"}},offset:t,limit:e}}))?.data.customerTransactionsFeed?.items||[],hY=async(r,e,t)=>(await ze.getShadowGraphqlClient().query({query:rY,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,offset:t,limit:e}}))?.data.customerBundlesFeed?.items||[],QP=Se`
3181
+ `,aY=async(r,e,t)=>await ze.getShadowGraphqlClient().mutate({mutation:rY,errorPolicy:"all",variables:{id:r,name:e},context:t}),sY=async(r,e)=>await ze.getShadowGraphqlClient().mutate({mutation:KQ,errorPolicy:"all",variables:{id:r,name:e}}),oY=async(r,e,t)=>await ze.getShadowGraphqlClient().mutate({mutation:nY,errorPolicy:"all",variables:{id:r,template:e,test:t}}),lY=async(r,e)=>await ze.getShadowGraphqlClient().mutate({mutation:ZQ,errorPolicy:"all",variables:{id:r,template:e}}),uY=async r=>(await ze.getShadowGraphqlClient().query({query:JQ,errorPolicy:"all",variables:{email:r}})).data.customer,cY=async(r,e,t)=>await ze.getShadowGraphqlClient().query({query:eY,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,offset:t,limit:e}}),dY=async(r,e)=>await ze.getShadowGraphqlClient().query({query:tY,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r},context:e}),fY=async(r,e,t)=>(await ze.getShadowGraphqlClient().query({query:tw,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,quicksearch:"",filters:{link:"and",status:{operator:"isAnyOf",values:["Created","DesignCompleted","ExternallyOrdered"]},template:{value:"false"}},offset:t,limit:e}}))?.data.customerTransactionsFeed?.items||[],hY=async(r,e,t)=>(await ze.getShadowGraphqlClient().query({query:tw,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,quicksearch:"",filters:{link:"and",status:{operator:"equals",value:"Ordered"},template:{value:"false"}},offset:t,limit:e}}))?.data.customerTransactionsFeed?.items||[],pY=async(r,e,t)=>(await ze.getShadowGraphqlClient().query({query:tw,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,quicksearch:"",filters:{link:"and",template:{value:"true"}},offset:t,limit:e}}))?.data.customerTransactionsFeed?.items||[],gY=async(r,e,t)=>(await ze.getShadowGraphqlClient().query({query:iY,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,offset:t,limit:e}}))?.data.customerBundlesFeed?.items||[],QP=Se`
3182
3182
  fragment AddressValidationResultFields on AddressValidationResult {
3183
3183
  addressComplete
3184
3184
  address {
@@ -3212,14 +3212,14 @@ ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:
3212
3212
  ...AddressValidationResultFields
3213
3213
  }
3214
3214
  }
3215
- `,pY=Se`
3215
+ `,mY=Se`
3216
3216
  ${rw}
3217
3217
  query GetAddressValidationJobs($ids: [String!]!) {
3218
3218
  addressValidationJobs(ids: $ids) {
3219
3219
  ...AddressValidationJobFields
3220
3220
  }
3221
3221
  }
3222
- `,gY=Se`
3222
+ `,vY=Se`
3223
3223
  ${rw}
3224
3224
  query GetRecipientsWithAddressValidationJobs($ids: [String!]!) {
3225
3225
  recipients(ids: $ids) {
@@ -3229,33 +3229,33 @@ ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:
3229
3229
  }
3230
3230
  }
3231
3231
  }
3232
- `,mY=Se`
3232
+ `,yY=Se`
3233
3233
  ${QP}
3234
3234
  mutation ValidateRecipientAddress($id: String!) {
3235
3235
  recipientValidate(id: $id) {
3236
3236
  ...AddressValidationResultFields
3237
3237
  }
3238
3238
  }
3239
- `,vY=Se`
3239
+ `,AY=Se`
3240
3240
  ${rw}
3241
3241
  mutation BatchValidateRecipientAddress($ids: [String!]!) {
3242
3242
  recipientValidateBatch(ids: $ids) {
3243
3243
  ...AddressValidationJobFields
3244
3244
  }
3245
3245
  }
3246
- `,yY=Se`
3246
+ `,bY=Se`
3247
3247
  mutation OverrideRecipientAddress($id: String!) {
3248
3248
  recipientOverrideAddress(id: $id) {
3249
3249
  id
3250
3250
  }
3251
3251
  }
3252
- `,AY=Se`
3252
+ `,wY=Se`
3253
3253
  mutation SkipRecipientAddress($id: String!) {
3254
3254
  recipientSkipAddress(id: $id) {
3255
3255
  id
3256
3256
  }
3257
3257
  }
3258
- `;var YP=(r=>(r.Confirmed="Confirmed",r.Plausible="Plausible",r.Unlikely="Unlikely",r))(YP||{}),XP=(r=>(r.Created="Created",r.Processing="Processing",r.Completed="Completed",r.Failed="Failed",r.Cancelled="Cancelled",r))(XP||{});const bY=async r=>{const e=r.map(n=>n.getTransaction().recipient?.id).filter(n=>!!n),t=await ze.getShadowGraphqlClient().query({query:gY,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:e}});return r.map(n=>{const i=n.getTransaction().recipient?.id;if(i)return t.data?.recipients?.find(a=>a.id===i)?.addressValidationJob})},wY=async r=>(await ze.getShadowGraphqlClient().query({query:pY,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:r}})).data?.addressValidationJobs,CY=async r=>r.getTransaction().recipient?.id?(await ze.getShadowGraphqlClient().mutate({mutation:mY,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r.getTransaction().recipient.id}})).data?.recipientValidate:void 0,xY=async r=>{const e=r.map(n=>n.getTransaction().recipient?.id).filter(n=>!!n),t=await ze.getShadowGraphqlClient().mutate({mutation:vY,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:e}});return r.map(n=>{const i=n.getTransaction().recipient?.id;if(i)return t.data?.recipientValidateBatch?.find(a=>a.entityId===i)})},SY=async r=>{const e=r.getTransaction().recipient?.id;if(!e)return;(await ze.getShadowGraphqlClient().mutate({mutation:yY,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:e}})).data?.recipientOverrideAddress?.id&&(r.getTransaction().addressValidationStatus=Og.Overridden)},EY=async r=>{const e=r.getTransaction().recipient?.id;if(!e)return;(await ze.getShadowGraphqlClient().mutate({mutation:AY,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:e}})).data?.recipientSkipAddress?.id&&(r.getTransaction().addressValidationStatus=Og.Skipped)},kY=Se`
3258
+ `;var YP=(r=>(r.Confirmed="Confirmed",r.Plausible="Plausible",r.Unlikely="Unlikely",r))(YP||{}),XP=(r=>(r.Created="Created",r.Processing="Processing",r.Completed="Completed",r.Failed="Failed",r.Cancelled="Cancelled",r))(XP||{});const CY=async r=>{const e=r.map(n=>n.getTransaction().recipient?.id).filter(n=>!!n),t=await ze.getShadowGraphqlClient().query({query:vY,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:e}});return r.map(n=>{const i=n.getTransaction().recipient?.id;if(i)return t.data?.recipients?.find(a=>a.id===i)?.addressValidationJob})},xY=async r=>(await ze.getShadowGraphqlClient().query({query:mY,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:r}})).data?.addressValidationJobs,SY=async r=>r.getTransaction().recipient?.id?(await ze.getShadowGraphqlClient().mutate({mutation:yY,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r.getTransaction().recipient.id}})).data?.recipientValidate:void 0,EY=async r=>{const e=r.map(n=>n.getTransaction().recipient?.id).filter(n=>!!n),t=await ze.getShadowGraphqlClient().mutate({mutation:AY,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:e}});return r.map(n=>{const i=n.getTransaction().recipient?.id;if(i)return t.data?.recipientValidateBatch?.find(a=>a.entityId===i)})},kY=async r=>{const e=r.getTransaction().recipient?.id;if(!e)return;(await ze.getShadowGraphqlClient().mutate({mutation:bY,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:e}})).data?.recipientOverrideAddress?.id&&(r.getTransaction().addressValidationStatus=Og.Overridden)},TY=async r=>{const e=r.getTransaction().recipient?.id;if(!e)return;(await ze.getShadowGraphqlClient().mutate({mutation:wY,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:e}})).data?.recipientSkipAddress?.id&&(r.getTransaction().addressValidationStatus=Og.Skipped)},FY=Se`
3259
3259
  query GetIntegrationProductsForIds($ids: [String!]!) {
3260
3260
  integrationProducts(ids: $ids) {
3261
3261
  id
@@ -3265,5 +3265,5 @@ ${L2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:
3265
3265
  }
3266
3266
  }
3267
3267
  }
3268
- `,TY=async r=>(await ze.getShadowGraphqlClient().query({query:kY,variables:{ids:r}})).data.integrationProducts;function FY(r){return new B1({},{stateMutationFunc:(()=>Promise.resolve()),transaction:{id:"local-transaction",product:{modelUrl:r.modelUrl}},graphQlClient:{},workflow:r.workflow,reloadedState:r.reloadedState})}exports.AddonHandle=Bg;exports.AddressValidationJobStatus=XP;exports.AddressValidationResultConfirmationLevel=YP;exports.AddressValidationStatus=Og;exports.ArrayInput=vV;exports.AspectType=Hn;exports.AssetNotFoundError=So;exports.AssetType=ff;exports.BringForwardCommand=TL;exports.BringToBackCommand=kL;exports.BringToFrontCommand=EL;exports.BundleDesignCreationCartAddMode=Nk;exports.CanvasCommand=Fn;exports.CollectionProduct=Pu;exports.ColorOptionGlobalPropertyHandle=hA;exports.CommandContext=GF;exports.ConversionDataType=Qd;exports.CreateElementCommand=ai;exports.CreateLayoutCommand=E1;exports.CurrencyContext=_P;exports.CurrencyService=MP;exports.DeleteElementCommand=Ol;exports.DigitalContentStepHandle=xI;exports.FileUploadGlobalPropertyHandle=II;exports.FlowExecutionNodeResult=Vd;exports.FlowExecutionResult=MI;exports.FlowService=BI;exports.FontAlignmentCommand=XF;exports.FontColorCommand=oA;exports.FontSizeCommand=YF;exports.FontSourceCommand=lA;exports.FrameService=jP;exports.FrameStep=GP;exports.FrameStepHandle=WP;exports.GlobalPropertyHandle=Jg;exports.GroupCommand=On;exports.IllustrationStepHandle=gI;exports.ImageState=qP;exports.InformationMessageType=Jf;exports.InformationStepHandle=CI;exports.IntegrationProduct=gA;exports.IntegrationType=Uk;exports.LayoutElementFactory=vL;exports.LayoutElementType=er;exports.LayoutNotFoundError=Ai;exports.LayoutRenderingPurpose=Ku;exports.MaterialStepHandle=mI;exports.MisconfigurationError=as;exports.MockWorkflowManager=QQ;exports.ModelStepHandle=vI;exports.ModuleStepHandle=SI;exports.MoveCommand=yL;exports.ObjectInput=L1;exports.ObjectInputType=_I;exports.OptionGlobalPropertyHandle=M1;exports.OptionNotFoundError=hf;exports.ParseError=Al;exports.PictureStepHandle=yI;exports.ProductCameraRig=Vk;exports.ProductCollection=_1;exports.ProductCollectionProductSortKey=OI;exports.ProductStepHandle=EI;exports.ProductWorkflow=oo;exports.PromiseQueue=Gg;exports.QuestionStepHandle=AI;exports.QueueablePromise=jg;exports.ResizeCommand=bL;exports.ResourceNotFoundError=Zu;exports.RotateCommand=AL;exports.ScaleAxis=gi;exports.SendBackwardsCommand=FL;exports.ShapeStepHandle=bI;exports.ShareActionType=Lk;exports.SpiffCommerceClient=UQ;exports.StakeholderType=GA;exports.StepAspectType=_k;exports.StepHandle=Ui;exports.StepType=Xe;exports.TextAlgorithm=Fl;exports.TextChangeCommand=JF;exports.TextGlobalPropertyHandle=PI;exports.TextInput=mV;exports.TextStepHandle=wI;exports.UnhandledBehaviorError=nn;exports.UnitOfMeasurement=zk;exports.UpdateImageSourceCommand=xL;exports.Variant=Fa;exports.WorkflowExperienceEventType=yg;exports.WorkflowExperienceImpl=B1;exports.__values=aD;exports.amtChannelsForAspect=DI;exports.assetConfigurationDeleteMutation=tM;exports.assetConfigurationUpdateMutation=eM;exports.assetConfigurationsQuery=Z3;exports.assetService=Ln;exports.browserColorToHex=lT;exports.bundleEmailMutation=E9;exports.cmPerPixel=Y_;exports.createLocalWorkflowExperience=FY;exports.currentDirection=q_;exports.dataUrlFromExternalUrl=U4;exports.deleteBundle=qQ;exports.designService=Qp;exports.determineCorrectFontSizeAndLines=Kd;exports.digitalContentStepService=T1;exports.domParser=us;exports.duplicateBundle=aY;exports.duplicateTransaction=sY;exports.fetchAsString=ra;exports.findAngle=U_;exports.findElement=Un;exports.findPmsColors=n3;exports.frameDataCache=_u;exports.frameStepService=so;exports.fromHex=jI;exports.fromUtf8=kl;exports.generate=Ar;exports.generateCommands=lI;exports.generateSVGWithUnknownColors=Pa;exports.generateStateFromDesignInputSteps=GU;exports.getActivation=VP;exports.getActivationThemeConfiguration=jQ;exports.getAddressValidationJobs=wY;exports.getAssetsForProductImagesQuery=rM;exports.getAttributesFromArrayBuffer=_f;exports.getAxisAlignedBoundingBox=L_;exports.getBoundedOffsets=HP;exports.getBundleIdForTransaction=WQ;exports.getBundleThemeConfiguration=$Q;exports.getCustomer=oY;exports.getCustomerBundles=lY;exports.getElementVertices=W_;exports.getFrameData=Xf;exports.getGlobalPropertyStateForBundle=YU;exports.getIntegration=UP;exports.getIntegrationProducts=TY;exports.getLayoutCanvasSize=cI;exports.getNEPoint=j_;exports.getNWPoint=H_;exports.getOrderedTransactions=dY;exports.getOverrideThemeConfiguration=zQ;exports.getPointOfRotation=$_;exports.getProductCollections=cV;exports.getSEPoint=G_;exports.getSvgElement=Qg;exports.getTemplateBundles=hY;exports.getTemplateTransactions=fY;exports.getTransaction=VQ;exports.getTransactionThemeConfiguration=HQ;exports.getTransactionsForBundle=uY;exports.getTransformedAssetURL=$g;exports.getTrueCoordinates=z_;exports.getUnorderedTransactions=cY;exports.getValidationJobsForWorkflowExperiences=bY;exports.getWorkflow=NP;exports.getWorkflows=ew;exports.graphQlManager=ze;exports.illustrationStepService=Jd;exports.isCloseToValue=V_;exports.loadFont=Rl;exports.matchHexToPms=e3;exports.materialStepService=F1;exports.mergeColorClasses=fT;exports.metafieldManager=Ag;exports.mmPerPixel=Q_;exports.modelStepService=I1;exports.modifySVGColors=zg;exports.moduleStepService=P1;exports.nameBundle=nY;exports.nameTransaction=iY;exports.nonPotTexSupport=uI;exports.optionService=ct;exports.outlineFontsInSvg=k7;exports.overrideWorkflowExperienceRecipientAddress=SY;exports.patternImageDataCache=Ds;exports.persistenceService=wr;exports.pictureStepService=D1;exports.pmsToRgb=ZB;exports.promiseCache=mf;exports.questionStepService=R1;exports.registerFetchImplementation=B4;exports.registerWindowImplementation=O4;exports.rehydrateSerializedLayout=sA;exports.rgbToPms=oT;exports.rotateAroundPoint=Ld;exports.sanitizeSvgTree=Vg;exports.setApplicationKey=Yk;exports.setBearerAuthenticationToken=Jk;exports.setCanvasModule=WA;exports.shapeStepService=Nu;exports.shortenUrl=nI;exports.skipWorkflowExperienceRecipientAddress=EY;exports.spiffCoreConfiguration=ss;exports.stepAspectValuesToDesignInputSteps=jU;exports.svgColorValueToDefinition=$y;exports.svgStringDimensions=S1;exports.svgToDataUrl=Ug;exports.textStepService=ri;exports.toHex=Ao;exports.toUtf8=em;exports.toast=aI;exports.validateWorkflowExperienceRecipient=CY;exports.validateWorkflowExperienceRecipients=xY;exports.xmlSerializer=Do;
3269
- //# sourceMappingURL=index-BIWTdrp-.cjs.map
3268
+ `,IY=async r=>(await ze.getShadowGraphqlClient().query({query:FY,variables:{ids:r}})).data.integrationProducts;function PY(r){return new B1({},{stateMutationFunc:(()=>Promise.resolve()),transaction:{id:"local-transaction",product:{modelUrl:r.modelUrl}},graphQlClient:{},workflow:r.workflow,reloadedState:r.reloadedState})}exports.AddonHandle=Bg;exports.AddressValidationJobStatus=XP;exports.AddressValidationResultConfirmationLevel=YP;exports.AddressValidationStatus=Og;exports.ArrayInput=AV;exports.AspectType=Hn;exports.AssetNotFoundError=So;exports.AssetType=ff;exports.BringForwardCommand=TL;exports.BringToBackCommand=kL;exports.BringToFrontCommand=EL;exports.BundleDesignCreationCartAddMode=Nk;exports.CanvasCommand=Fn;exports.CollectionProduct=Pu;exports.ColorOptionGlobalPropertyHandle=hA;exports.CommandContext=GF;exports.ConversionDataType=Qd;exports.CreateElementCommand=ai;exports.CreateLayoutCommand=E1;exports.CurrencyContext=_P;exports.CurrencyService=MP;exports.DeleteElementCommand=Ol;exports.DigitalContentStepHandle=xI;exports.FileUploadGlobalPropertyHandle=II;exports.FlowExecutionNodeResult=Vd;exports.FlowExecutionResult=MI;exports.FlowService=BI;exports.FontAlignmentCommand=XF;exports.FontColorCommand=oA;exports.FontSizeCommand=YF;exports.FontSourceCommand=lA;exports.FrameService=jP;exports.FrameStep=GP;exports.FrameStepHandle=WP;exports.GlobalPropertyHandle=Jg;exports.GroupCommand=On;exports.IllustrationStepHandle=gI;exports.ImageState=qP;exports.InformationMessageType=Jf;exports.InformationStepHandle=CI;exports.IntegrationProduct=gA;exports.IntegrationType=Uk;exports.LayoutElementFactory=vL;exports.LayoutElementType=er;exports.LayoutNotFoundError=Ai;exports.LayoutRenderingPurpose=Ku;exports.MaterialStepHandle=mI;exports.MisconfigurationError=as;exports.MockWorkflowManager=XQ;exports.ModelStepHandle=vI;exports.ModuleStepHandle=SI;exports.MoveCommand=yL;exports.ObjectInput=L1;exports.ObjectInputType=_I;exports.OptionGlobalPropertyHandle=M1;exports.OptionNotFoundError=hf;exports.ParseError=Al;exports.PictureStepHandle=yI;exports.ProductCameraRig=Vk;exports.ProductCollection=_1;exports.ProductCollectionProductSortKey=OI;exports.ProductStepHandle=EI;exports.ProductWorkflow=oo;exports.PromiseQueue=Gg;exports.QuestionStepHandle=AI;exports.QueueablePromise=jg;exports.ResizeCommand=bL;exports.ResourceNotFoundError=Zu;exports.RotateCommand=AL;exports.ScaleAxis=gi;exports.SendBackwardsCommand=FL;exports.ShapeStepHandle=bI;exports.ShareActionType=Lk;exports.SpiffCommerceClient=zQ;exports.StakeholderType=GA;exports.StepAspectType=_k;exports.StepHandle=Ui;exports.StepType=Xe;exports.TextAlgorithm=Fl;exports.TextChangeCommand=JF;exports.TextGlobalPropertyHandle=PI;exports.TextInput=yV;exports.TextStepHandle=wI;exports.UnhandledBehaviorError=nn;exports.UnitOfMeasurement=zk;exports.UpdateImageSourceCommand=xL;exports.Variant=Fa;exports.WorkflowExperienceEventType=yg;exports.WorkflowExperienceImpl=B1;exports.__values=aD;exports.amtChannelsForAspect=DI;exports.assetConfigurationDeleteMutation=tM;exports.assetConfigurationUpdateMutation=eM;exports.assetConfigurationsQuery=Z3;exports.assetService=Ln;exports.browserColorToHex=lT;exports.bundleEmailMutation=T9;exports.cmPerPixel=Y_;exports.createLocalWorkflowExperience=PY;exports.currentDirection=q_;exports.dataUrlFromExternalUrl=U4;exports.deleteBundle=QQ;exports.designService=Qp;exports.determineCorrectFontSizeAndLines=Kd;exports.digitalContentStepService=T1;exports.domParser=us;exports.duplicateBundle=oY;exports.duplicateTransaction=lY;exports.fetchAsString=ra;exports.findAngle=U_;exports.findElement=Un;exports.findPmsColors=n3;exports.frameDataCache=_u;exports.frameStepService=so;exports.fromHex=jI;exports.fromUtf8=kl;exports.generate=Ar;exports.generateCommands=lI;exports.generateSVGWithUnknownColors=Pa;exports.generateStateFromDesignInputSteps=WU;exports.getActivation=VP;exports.getActivationThemeConfiguration=qQ;exports.getAddressValidationJobs=xY;exports.getAssetsForProductImagesQuery=rM;exports.getAttributesFromArrayBuffer=_f;exports.getAxisAlignedBoundingBox=L_;exports.getBoundedOffsets=HP;exports.getBundleIdForTransaction=YQ;exports.getBundleThemeConfiguration=jQ;exports.getCustomer=uY;exports.getCustomerBundles=cY;exports.getElementVertices=W_;exports.getFrameData=Xf;exports.getGlobalPropertyStateForBundle=JU;exports.getIntegration=UP;exports.getIntegrationProducts=IY;exports.getLayoutCanvasSize=cI;exports.getNEPoint=j_;exports.getNWPoint=H_;exports.getOrderedTransactions=hY;exports.getOverrideThemeConfiguration=HQ;exports.getPointOfRotation=$_;exports.getProductCollections=fV;exports.getSEPoint=G_;exports.getSvgElement=Qg;exports.getTemplateBundles=gY;exports.getTemplateTransactions=pY;exports.getTransaction=$Q;exports.getTransactionThemeConfiguration=GQ;exports.getTransactionsForBundle=dY;exports.getTransformedAssetURL=$g;exports.getTrueCoordinates=z_;exports.getUnorderedTransactions=fY;exports.getValidationJobsForWorkflowExperiences=CY;exports.getWorkflow=NP;exports.getWorkflows=ew;exports.graphQlManager=ze;exports.illustrationStepService=Jd;exports.isCloseToValue=V_;exports.loadFont=Rl;exports.matchHexToPms=e3;exports.materialStepService=F1;exports.mergeColorClasses=fT;exports.metafieldManager=Ag;exports.mmPerPixel=Q_;exports.modelStepService=I1;exports.modifySVGColors=zg;exports.moduleStepService=P1;exports.nameBundle=aY;exports.nameTransaction=sY;exports.nonPotTexSupport=uI;exports.optionService=ct;exports.outlineFontsInSvg=k7;exports.overrideWorkflowExperienceRecipientAddress=kY;exports.patternImageDataCache=Ds;exports.persistenceService=wr;exports.pictureStepService=D1;exports.pmsToRgb=ZB;exports.promiseCache=mf;exports.questionStepService=R1;exports.registerFetchImplementation=B4;exports.registerWindowImplementation=O4;exports.rehydrateSerializedLayout=sA;exports.rgbToPms=oT;exports.rotateAroundPoint=Ld;exports.sanitizeSvgTree=Vg;exports.setApplicationKey=Yk;exports.setBearerAuthenticationToken=Jk;exports.setCanvasModule=WA;exports.shapeStepService=Nu;exports.shortenUrl=nI;exports.skipWorkflowExperienceRecipientAddress=TY;exports.spiffCoreConfiguration=ss;exports.stepAspectValuesToDesignInputSteps=qU;exports.svgColorValueToDefinition=$y;exports.svgStringDimensions=S1;exports.svgToDataUrl=Ug;exports.textStepService=ri;exports.toHex=Ao;exports.toUtf8=em;exports.toast=aI;exports.validateWorkflowExperienceRecipient=SY;exports.validateWorkflowExperienceRecipients=EY;exports.xmlSerializer=Do;
3269
+ //# sourceMappingURL=index-JFF_QSgS.cjs.map