@spiffcommerce/core 40.3.2 → 40.3.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.
package/dist/index.cjs CHANGED
@@ -1,20 +1,20 @@
1
- "use strict";var vr=Object.create;var un=Object.defineProperty;var Er=Object.getOwnPropertyDescriptor;var br=Object.getOwnPropertyNames;var Ir=Object.getPrototypeOf,Br=Object.prototype.hasOwnProperty;var Pr=(i,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of br(t))!Br.call(i,n)&&n!==e&&un(i,n,{get:()=>t[n],enumerable:!(a=Er(t,n))||a.enumerable});return i};var xr=(i,t,e)=>(e=i!=null?vr(Ir(i)):{},Pr(t||!i||!i.__esModule?un(e,"default",{value:i,enumerable:!0}):e,i));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("@apollo/client/core"),Fr=require("@apollo/client/link/context"),Dr=require("@apollo/client/link/error"),kr=require("preact-render-to-string"),Mr=require("@apollo/client/link/remove-typename"),Tr=require("exifr/dist/mini.umd.cjs"),Vn=require("css"),Nr=require("fuse.js"),$a=require("pith"),wa=require("lodash.chunk"),yt=require("lodash.clonedeep"),P=require("preact/jsx-runtime"),ya=require("opentype.js"),Qr=require("html-entities"),Or=require("handlebars"),Rr=require("data-uri-to-buffer"),we=require("@aws-sdk/client-cognito-identity-provider"),$r=require("dinero.js"),Ur=require("currency-codes"),Ln=require("lodash.debounce"),ae=require("lodash.isequal"),Sa=require("unicode-default-word-boundary"),zn=require("qrcode"),Vr=require("svg-path-bbox");require("fs");require("path");const Lr=require("lodash.omit");function zr(i){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const a=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,a.get?a:{enumerable:!0,get:()=>i[e]})}}return t.default=i,Object.freeze(t)}const An=zr(Ur);var ne=(i=>(i.Data="Data",i.Font="Font",i.Frame="Frame",i.Illustration="Illustration",i.Image="Image",i.Model="Model",i.Material="Material",i.Color="Color",i.QuestionnaireCollateral="QuestionnaireCollateral",i.RequestCollateral="RequestCollateral",i.SignupCollateral="SignupCollateral",i.Video="Video",i.ColorProfile="ColorProfile",i.Environment="Environment",i))(ne||{}),qn=(i=>(i.AND="AND",i.OR="OR",i))(qn||{}),z=(i=>(i.FileUpload="FileUpload",i.Option="Option",i.ColorOption="ColorOption",i.Text="Text",i))(z||{}),E=(i=>(i.Information="Information",i.Bulk="Bulk",i.DigitalContent="DigitalContent",i.Finish="Finish",i.Frame="Frame",i.Illustration="Illustration",i.Introduction="Introduction",i.Material="Material",i.Model="Model",i.Module="Module",i.Picture="Picture",i.Photo="Photo",i.ProductOverlay="ProductOverlay",i.Question="Question",i.Shape="Shape",i.SilentIllustration="SilentIllustration",i.Text="Text",i))(E||{}),Gn=(i=>(i.Color="Color",i.Colors="Colors",i.Selection="Selection",i.Selections="Selections",i.Text="Text",i.Upload="Upload",i))(Gn||{}),Ot=(i=>(i.ThreeD="ThreeD",i.FreeDesign="FreeDesign",i.Print="Print",i))(Ot||{}),D=(i=>(i.Frame="frame",i.Group="group",i.Image="image",i.Pattern="pattern",i.Illustration="illustration",i.Textbox="textbox",i))(D||{}),jn=(i=>(i.Default="Default",i.FirstTransaction="FirstTransaction",i.OneToOne="OneToOne",i))(jn||{}),Ua=(i=>(i.Pending="Pending",i.Failed="Failed",i.Validated="Validated",i.Overridden="Overridden",i))(Ua||{}),Hn=(i=>(i.Hyperlink="Hyperlink",i.Edit="Edit",i.Approve="Approve",i))(Hn||{}),Wn=(i=>(i.Hub="Hub",i.Shopify="Shopify",i))(Wn||{}),Ue=(i=>(i.AdvancedImageManipulation="BackgroundRemover",i.ConversionAccelerator="Conversion Accelerator",i.ProcessBuilder="ProcessBuilder",i))(Ue||{}),Yn=(i=>(i[i.Orbit=0]="Orbit",i[i.Pan=1]="Pan",i))(Yn||{}),Va=(i=>(i.Owner="Owner",i.Approver="Approver",i.Editor="Editor",i.Viewer="Viewer",i))(Va||{}),xt=(i=>(i.Autosize="Autosize",i.Traditional="Traditional",i))(xt||{}),Y=(i=>(i[i.North=0]="North",i[i.Northeast=1]="Northeast",i[i.East=2]="East",i[i.Southeast=3]="Southeast",i[i.South=4]="South",i[i.Southwest=5]="Southwest",i[i.West=6]="West",i[i.Northwest=7]="Northwest",i))(Y||{}),Jn=(i=>(i.Pixel="px",i.Millimeter="mm",i.Centimeter="cm",i))(Jn||{});class Kn extends Error{constructor(t){super(t),this.name=this.constructor.name}}class le extends Kn{constructor(t){super(`ConfigurationError - ${t}`)}}class ie extends le{constructor(t){super(`Option not Configured: ${t.stepTitle}`),this.optionId=t?.optionId||"N/A"}}class J extends le{constructor(t){super(`Panel not Found: ${t.panelId}`),this.panelId=t?.panelId||"N/A"}}class St extends le{constructor(t){super(`Asset not found for variant: ${t.name}`),this.variant=t}}class Rt extends le{constructor(t){super(`Resource not found for asset: ${t.name}`),this.asset=t}}class lt extends le{constructor(t,e){super(`Workflow Misconfiguration: ${t.stepName} - ${e}`),this.step=t}}class Ve extends Kn{constructor(t){super(`ImplementationError - ${t}`)}}class O extends Ve{constructor(t){super(`Unhandled Behavior Encountered: ${t}`)}}class Pt extends Ve{constructor(t){super(`Parsing Error: ${t}`)}}class ft extends Ve{constructor(t){super(`Client Error: ${t}`)}}class Le extends Ve{constructor(t){super(`Resource Generation Failed: ${t}`)}}class qr{get(t){return localStorage.getItem(t)||void 0}set(t,e){localStorage.setItem(t,e)}remove(t){localStorage.removeItem(t)}getMap(t){const e=this.get(t);if(e)return new Map(JSON.parse(e))}setMap(t,e){const a=JSON.stringify([...e.entries()]);this.set(t,a)}}class hn{constructor(){this.storage=new Map}get(t){return this.storage.get(t)||void 0}set(t,e){this.storage.set(t,e)}remove(t){this.storage.delete(t)}getMap(t){const e=this.get(t);if(e)return new Map(JSON.parse(e))}setMap(t,e){const a=JSON.stringify([...e.entries()]);this.set(t,a)}}const Gr=()=>{try{return localStorage?new qr:new hn}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new hn}},Q=Gr();class jr{constructor(){this.defaultServerUrl="https://api.au.spiffcommerce.com",this.defaultServicesApiUrl="https://services.au.spiffcommerce.com",this.defaultHubUrl="https://hub.au.spiffcommerce.com",this.serverUrl=this.defaultServerUrl,this.servicesApiUrl=this.defaultServicesApiUrl,this.hubUrl=this.defaultHubUrl,this.serverUrlCallbacks=[]}getServerUrl(){return this.serverUrl}getServicesApiUrl(){return this.servicesApiUrl}getHubUrl(){return this.hubUrl}setServerUrl(t){this.serverUrl=t,this.serverUrlCallbacks.forEach(e=>e())}setServicesApiUrl(t){this.servicesApiUrl=t}setHubUrl(t){this.hubUrl=t}addServerUrlCallback(t){this.serverUrlCallbacks.push(t)}}const gt=new jr;let va,Ea;function Hr(i){va=i}function Wr(i){Ea=i}function ce(){return va?new va().window:(console.log("DOM constructor is not registered. Assuming browser environment. If not, please register DOM constructor before calling this function."),window)}function it(i,t){if(!Ea){if(typeof window<"u"&&window.fetch)return window.fetch(i,t);if(typeof global<"u"&&global.fetch)return global.fetch(i,t);throw new Error("Fetch implementation is not registered. Please register it before calling this function.")}return Ea(i,t)}const _n=new Map,gn=new Map,mn=new Map,Xn=async i=>{const t=gn.get(i);if(t)return t;const a=(async()=>{const n=await it(i);return _n.set(i,n.headers?.get("content-type")||""),await n.arrayBuffer()})();return gn.set(i,a),a},Yr=async i=>{const t=mn.get(i);if(t)return t;const a=(async()=>await(await it(i)).text())();return mn.set(i,a),a},Vt=i=>i.every(t=>t!=="undefined"),ye=i=>Vt([typeof document])?document.createElement(i):ce().document.createElement(i),Jr=(i,t)=>{if(Vt([typeof document]))return document.createElementNS(i,t);const a=ce().document.createElement(t);return a.setAttribute("xmlns",i),a},ct=()=>{if(Vt([typeof DOMParser]))return new DOMParser;const i=ce();return new i.DOMParser},Kr=()=>Vt([typeof DOMParser])?DOMParser:ce().DOMParser,ze=(i,t)=>new Promise((e,a)=>{t?Xn(i).then(e).catch(a):it(i).then(n=>{n.arrayBuffer().then(e).catch(a)}).catch(n=>{a(n)})}),et=(i,t)=>new Promise((e,a)=>{t?Yr(i).then(e).catch(a):it(i).then(n=>{n.text().then(e).catch(a)}).catch(a)}),Zn=i=>kr.renderToStaticMarkup(i),na=new Map,_r=async(i,t)=>{if(Vt([typeof FontFace])){if(na.has(t))return na.get(t);const e=i.names.fullName.en,a=new FontFace(e,`url(${t})`);document.fonts.add(a);const n=a.load();return na.set(t,n),n}},It=()=>{if(Vt([typeof XMLSerializer]))return new XMLSerializer;const i=ce();return new i.XMLSerializer},pn=i=>btoa(i),qe=i=>{function t(){const a=new Uint8Array(i),n=4;if(a.length>=n){const r=new Array(n);for(let l=0;l<n;l++)r[l]=new Uint8Array(i)[l].toString(16);const o=r.join("").toUpperCase();switch(o){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"504B0304":return"application/zip"}switch(o.slice(0,4)){case"FFD8":return"image/jpeg"}}return null}const e=t();return e||"image/svg+xml"},Xr=async i=>{const t=await Xn(i),e=_n.get(i)||qe(t);return await eo(new Blob([t],{type:e}))},Zr=i=>{let t="";const e=i.byteLength;for(let a=0;a<e;a++)t+=String.fromCharCode(i[a]);return t},to=async i=>{const t=qe(i),e=new Uint8Array(i),a=Zr(e),n=btoa(a);return`data:${t};base64,${n}`},Ge=i=>`data:image/svg+xml;base64,${btoa(i)}`,ti=i=>{const t=i.replace(/\r?\n/g,""),e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");const a=t.substring(5,e).split(";");let n=!1;for(let o=1;o<a.length;o++)a[o]==="base64"&&(n=!0);const r=decodeURI(t.substring(e+1));return n?new Uint8Array(atob(r).split("").map(s=>s.charCodeAt(0))).buffer:new Uint8Array(r.split("").map(s=>s.charCodeAt(0))).buffer},eo=i=>new Promise((t,e)=>{const a=new FileReader;a.onload=function(n){const r=n.target;!r||!r.result?e():t(r.result.toString())},a.readAsDataURL(i)});let ao,La;const no=i=>{La=i},io=()=>La;let ei;const ai=i=>{ei=i},ro=()=>new Promise(i=>{const t=gt.getHubUrl(),e=a=>{a.origin===t&&(window.removeEventListener("message",e),i(a.data))};window.parent!==window&&(window.addEventListener("message",e,!1),window.parent.postMessage("ready",t))}),oo=async()=>{const i={applicationKey:La,customerToken:ao,bearer:ei};return typeof window<"u"&&(window.location.href.includes("/workflows/product/")||window.location.href.includes("hub=true"))?{...await ro(),...i}:i};async function so(i,t){const e=gt.getServerUrl(),a=e.includes(".aumelbdev.spiffcommerce.com")?"https://moonlight.aumelbdev.spiffcommerce.com":e.includes(".us.spiffcommerce.com")?"https://moonlight.us.spiffcommerce.com":"https://moonlight.au.spiffcommerce.com";let n=await it(i,{...t,redirect:"manual"});return(n.type==="opaqueredirect"||n.status===307)&&(typeof i!="string"&&"url"in i?n=await it({...i,url:`${a}/graphql`},t):n=await it(`${a}/graphql`,t)),n}class lo{constructor(){this.shadowGraphqlClient=this.constructShadowGraphqlClient(),gt.addServerUrlCallback(()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()})}setSpiffCommerceClient(t){this.spiffClient=t,this.shadowGraphqlClient=this.constructShadowGraphqlClient()}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const t=f.createHttpLink({uri:`${gt.getServerUrl()}/graphql`,fetch:so}),e=Fr.setContext(async(r,o)=>{const{headers:s}=o,l=s||{},c=await oo();let d=o.bearer??c.bearer,u=!1;if(this.spiffClient){try{d=await this.spiffClient.loggedInBearerToken()}catch{}try{o.skipIntegrationCheck||(u=await this.spiffClient.getBetaEnabled())}catch{}}const A=o.partnerId??c.partnerId,h=o.activeIntegration??c.activeIntegration,g=o.transactionOwnerId,p=o.customerToken??c.customerToken,m=o.applicationKey??c.applicationKey,C=o.bundleOwnerId;try{if(window&&window.__SENTRY__){const S=window.__SENTRY__.hub;if(S){const w=S.traceHeaders();Object.entries(w).forEach(([F,b])=>{l[F]=b})}}}catch{}return d&&(l.Authorization=`Bearer ${d}`),A&&(l.partnerId=A),h&&(l.activeIntegration=h),g&&(l.transactionOwnerId=g),p&&(l.customerToken=p),m&&(l["X-Application-Key"]=m),C&&(l.bundleOwnerId=C),u&&(l["X-Spiff-Beta"]="true"),l["Allow-Moonlight-Redirect"]="true",{headers:l}}),a=Dr.onError(({operation:r,graphQLErrors:o,networkError:s})=>{const l=o||[],c=r.getContext();s&&!c?.fetchOptions?.signal?.aborted&&console.log("GraphQL Network error"),l.forEach(()=>console.log("GraphQL Error: "+r.operationName))}),n=Mr.removeTypenameFromVariables();return new f.ApolloClient({link:f.from([n,a,e,t]),cache:new f.InMemoryCache,name:"Core"})}}const y=new lo;let ba,Ia;const vt=(i,t,e)=>{if(ba!==void 0)return ba(i,t,e);try{const a=ni(!0);return za(a),a.createCanvas(i,t,e)}catch{throw new Error("Canvas module not set")}},de=(i,t)=>{if(Ia!==void 0)return Ia(i,t);try{const e=ni(!0);return za(e),e.loadImage(i,t)}catch{throw new Error("Canvas module not set")}};function za(i){ba=i?.createCanvas,Ia=i?.loadImage}function ni(i){try{if(document.createElement("canvas").getContext("2d"))return{createCanvas:(e,a,n)=>{const r=document.createElement("canvas");return e!=null&&(r.width=e),a!=null&&(r.height=a),r},loadImage:(e,a)=>new Promise((n,r)=>{const o=document.createElement("img");a!==!1&&(o.crossOrigin="Anonymous"),o.onload=()=>{n(o)},o.onerror=r,o.src=e})}}catch(t){throw t}}let ia;function qa(){return ia===void 0&&(ia=Kr()),ia}let Se=null;const co=i=>new Promise(t=>{if(qe(i)!=="image/jpeg")return t(1);Tr.orientation(i).then(a=>t(a||1)).catch(()=>t(1))}),uo=async()=>{if(Se!==null)return!Se;const t=await de("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/xABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQvoP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXwH/9k=");return Se=t.width===2&&t.height===3,!Se},Ao=i=>{const e=i.naturalWidth/i.naturalHeight;return i.naturalHeight<=8192&&i.naturalWidth<=8192?[i.naturalWidth,i.naturalHeight]:i.naturalHeight>i.naturalWidth?[e*8192,8192]:[8192,8192/e]},ho=async i=>{const t=await to(i),e=await de(t),[a,n]=Ao(e);if(!await uo()){const u=vt(a,n);return u.getContext("2d")?.drawImage(e,0,0,a,n),u}const o=await co(i),[s,l]=o>4?[n,a]:[a,n],c=vt(s,l),d=c.getContext("2d");switch(o){case 2:d.translate(s,0),d.scale(-1,1);break;case 3:d.translate(s,l),d.rotate(Math.PI);break;case 4:d.translate(0,l),d.scale(1,-1);break;case 5:d.rotate(-.5*Math.PI),d.scale(-1,1);break;case 6:d.rotate(-.5*Math.PI),d.translate(-s,0);break;case 7:d.rotate(-.5*Math.PI),d.translate(-s,l),d.scale(1,-1);break;case 8:d.rotate(.5*Math.PI),d.translate(0,-l);break}return d.drawImage(e,0,0,s,l),c},ue=async i=>{const t=await ho(i);return qe(i)==="image/jpeg"?{dataUrl:t.toDataURL("image/jpeg",1),height:t.height,width:t.width}:{dataUrl:t.toDataURL(),height:t.height,width:t.width}},re=["Yellow C","Yellow 012 C","Orange 021 C","Warm Red C","Red 032 C","Rubine Red C","Rhodamine Red C","Purple C","Violet C","Blue 072 C","Reflex Blue C","Process Blue C","Green C","Black C","Yellow 0131 C","Red 0331 C","Magenta 0521 C","Violet 0631 C","Blue 0821 C","Green 0921 C","Black 0961 C","801 C","802 C","803 C","804 C","805 C","806 C","807 C","871 C","872 C","873 C","874 C","875 C","876 C","877 C","Medium Yellow C","Bright Orange C","Bright Red C","Strong Red C","Pink C","Medium Purple C","Dark Blue C","Medium Blue C","Bright Green C","Neutral Black C","100 C","101 C","102 C","103 C","104 C","105 C","7401 C","7402 C","7403 C","7404 C","7405 C","7406 C","7407 C","106 C","107 C","108 C","109 C","110 C","111 C","112 C","113 C","114 C","115 C","116 C","117 C","118 C","119 C","127 C","128 C","129 C","130 C","131 C","132 C","133 C","1205 C","1215 C","1225 C","1235 C","1245 C","1255 C","1265 C","120 C","121 C","122 C","123 C","124 C","125 C","126 C","7548 C","7549 C","7550 C","7551 C","7552 C","7553 C","7554 C","7555 C","7556 C","7557 C","7558 C","7559 C","7560 C","7561 C","134 C","135 C","136 C","137 C","138 C","139 C","140 C","1345 C","1355 C","1365 C","1375 C","1385 C","1395 C","1405 C","141 C","142 C","143 C","144 C","145 C","146 C","147 C","7408 C","7409 C","7410 C","7411 C","7412 C","7413 C","7414 C","7562 C","7563 C","7564 C","7565 C","7566 C","7567 C","7568 C","7569 C","7570 C","7571 C","7572 C","7573 C","7574 C","7575 C","712 C","713 C","714 C","715 C","716 C","717 C","718 C","148 C","149 C","150 C","151 C","152 C","153 C","154 C","155 C","156 C","157 C","158 C","159 C","160 C","161 C","1485 C","1495 C","1505 C","1525 C","1535 C","1545 C","1555 C","1565 C","1575 C","1585 C","1595 C","1605 C","1615 C","162 C","163 C","164 C","165 C","166 C","167 C","168 C","7576 C","7577 C","7578 C","7579 C","7580 C","7581 C","7582 C","1625 C","1635 C","1645 C","1655 C","1665 C","1675 C","1685 C","169 C","170 C","171 C","172 C","173 C","174 C","175 C","7583 C","7584 C","7585 C","7586 C","7587 C","7588 C","7589 C","7590 C","7591 C","7592 C","7593 C","7594 C","7595 C","7596 C","7597 C","7598 C","7599 C","7600 C","7601 C","7602 C","7603 C","7604 C","7605 C","7606 C","7607 C","7608 C","7609 C","7610 C","7611 C","7612 C","7613 C","7614 C","7615 C","7616 C","7617 C","7520 C","7521 C","7522 C","7523 C","7524 C","7525 C","7526 C","489 C","488 C","487 C","486 C","485 C","484 C","483 C","176 C","177 C","178 C","179 C","180 C","181 C","1765 C","1775 C","1785 C","1788 C","1795 C","1805 C","1815 C","1767 C","1777 C","1787 C","1797 C","1807 C","1817 C","7618 C","7619 C","7620 C","7621 C","7622 C","7623 C","7624 C","7625 C","7626 C","7627 C","7628 C","7629 C","7630 C","7631 C","7415 C","7416 C","7417 C","7418 C","7419 C","7420 C","7421 C","182 C","183 C","184 C","185 C","186 C","187 C","188 C","196 C","197 C","198 C","199 C","200 C","201 C","202 C","189 C","190 C","191 C","192 C","193 C","194 C","195 C","1895 C","1905 C","1915 C","1925 C","1935 C","1945 C","1955 C","705 C","706 C","707 C","708 C","709 C","710 C","711 C","698 C","699 C","700 C","701 C","702 C","703 C","704 C","203 C","204 C","205 C","206 C","207 C","208 C","209 C","210 C","211 C","212 C","213 C","214 C","215 C","216 C","7422 C","7423 C","7424 C","7425 C","7426 C","7427 C","7428 C","7632 C","7633 C","7634 C","7635 C","7636 C","7637 C","7638 C","217 C","218 C","219 C","220 C","221 C","222 C","7639 C","7640 C","7641 C","7642 C","7643 C","7644 C","7645 C","223 C","224 C","225 C","226 C","227 C","228 C","229 C","230 C","231 C","232 C","233 C","234 C","235 C","670 C","671 C","672 C","673 C","674 C","675 C","676 C","677 C","678 C","679 C","680 C","681 C","682 C","683 C","684 C","685 C","686 C","687 C","688 C","689 C","690 C","510 C","509 C","508 C","507 C","506 C","505 C","504 C","7429 C","7430 C","7431 C","7432 C","7433 C","7434 C","7435 C","691 C","692 C","693 C","694 C","695 C","696 C","697 C","496 C","495 C","494 C","493 C","492 C","491 C","490 C","503 C","502 C","501 C","500 C","499 C","498 C","497 C","5035 C","5025 C","5015 C","5005 C","4995 C","4985 C","4975 C","236 C","237 C","238 C","239 C","240 C","241 C","242 C","2365 C","2375 C","2385 C","2395 C","2405 C","2415 C","2425 C","243 C","244 C","245 C","246 C","247 C","248 C","249 C","7646 C","7647 C","7648 C","7649 C","7650 C","7651 C","7652 C","250 C","251 C","252 C","253 C","254 C","255 C","517 C","516 C","515 C","514 C","513 C","512 C","511 C","7436 C","7437 C","7438 C","7439 C","7440 C","7441 C","7442 C","2562 C","2572 C","2582 C","2592 C","2602 C","2612 C","2622 C","7653 C","7654 C","7655 C","7656 C","7657 C","7658 C","7659 C","524 C","523 C","522 C","521 C","520 C","519 C","518 C","5245 C","5235 C","5225 C","5215 C","5205 C","5195 C","5185 C","5175 C","5165 C","5155 C","5145 C","5135 C","5125 C","5115 C","531 C","530 C","529 C","528 C","527 C","526 C","525 C","256 C","257 C","258 C","259 C","260 C","261 C","262 C","2563 C","2573 C","2583 C","2593 C","2603 C","2613 C","2623 C","7660 C","7661 C","7662 C","7663 C","7664 C","7665 C","7666 C","2567 C","2577 C","2587 C","2597 C","2607 C","2617 C","2627 C","263 C","264 C","265 C","266 C","267 C","268 C","269 C","2635 C","2645 C","2655 C","2665 C","2685 C","2695 C","270 C","271 C","272 C","273 C","274 C","275 C","276 C","2705 C","2715 C","2725 C","2735 C","2745 C","2755 C","2765 C","7667 C","7668 C","7669 C","7670 C","7671 C","7672 C","7673 C","7443 C","7444 C","7445 C","7446 C","7447 C","7448 C","7449 C","7674 C","7675 C","7676 C","7677 C","7678 C","7679 C","7680 C","663 C","664 C","665 C","666 C","667 C","668 C","669 C","5315 C","5305 C","5295 C","5285 C","5275 C","5265 C","5255 C","538 C","537 C","536 C","535 C","534 C","533 C","532 C","7541 C","7542 C","7543 C","7544 C","7545 C","7546 C","7547 C","552 C","551 C","550 C","549 C","548 C","547 C","546 C","5455 C","5445 C","5435 C","5425 C","5415 C","5405 C","5395 C","642 C","643 C","644 C","645 C","646 C","647 C","648 C","649 C","650 C","651 C","652 C","653 C","654 C","655 C","656 C","657 C","658 C","659 C","660 C","661 C","662 C","7450 C","7451 C","7452 C","7453 C","7454 C","7455 C","7456 C","2706 C","2716 C","2726 C","2736 C","2746 C","2756 C","2766 C","2708 C","2718 C","2728 C","2738 C","2748 C","2758 C","2768 C","2707 C","2717 C","2727 C","2747 C","2757 C","2767 C","277 C","278 C","279 C","280 C","281 C","282 C","283 C","284 C","285 C","286 C","287 C","288 C","289 C","7681 C","7682 C","7683 C","7684 C","7685 C","7686 C","7687 C","545 C","544 C","543 C","542 C","541 C","540 C","539 C","290 C","291 C","292 C","293 C","294 C","295 C","296 C","2905 C","2915 C","2925 C","2935 C","2945 C","2955 C","2965 C","297 C","298 C","299 C","300 C","301 C","302 C","303 C","7688 C","7689 C","7690 C","7691 C","7692 C","7693 C","7694 C","2975 C","2985 C","2995 C","3005 C","3015 C","3025 C","3035 C","7695 C","7696 C","7697 C","7698 C","7699 C","7700 C","7701 C","7457 C","7458 C","7459 C","7460 C","7461 C","7462 C","7463 C","304 C","305 C","306 C","307 C","308 C","309 C","635 C","636 C","637 C","638 C","639 C","640 C","641 C","7702 C","7703 C","7704 C","7705 C","7706 C","7707 C","7708 C","628 C","629 C","630 C","631 C","632 C","633 C","634 C","310 C","311 C","312 C","313 C","314 C","315 C","316 C","3105 C","3115 C","3125 C","3135 C","3145 C","3155 C","3165 C","7709 C","7710 C","7711 C","7712 C","7713 C","7714 C","7715 C","317 C","318 C","319 C","320 C","321 C","322 C","323 C","7464 C","7465 C","7466 C","7467 C","7468 C","7469 C","7470 C","7471 C","7472 C","7473 C","7474 C","7475 C","7476 C","7477 C","5523 C","5513 C","5503 C","5493 C","5483 C","5473 C","5463 C","7716 C","7717 C","7718 C","7719 C","7720 C","7721 C","7722 C","324 C","325 C","326 C","327 C","328 C","329 C","330 C","3242 C","3252 C","3262 C","3272 C","3282 C","3292 C","3302 C","3245 C","3255 C","3265 C","3275 C","3285 C","3295 C","3305 C","3248 C","3258 C","3268 C","3278 C","3288 C","3298 C","3308 C","566 C","565 C","564 C","563 C","562 C","561 C","560 C","573 C","572 C","571 C","570 C","569 C","568 C","567 C","559 C","558 C","557 C","556 C","555 C","554 C","553 C","5595 C","5585 C","5575 C","5565 C","5555 C","5545 C","5535 C","5665 C","5655 C","5645 C","5635 C","5625 C","5615 C","5605 C","5527 C","5517 C","5507 C","5497 C","5487 C","5477 C","5467 C","621 C","622 C","623 C","624 C","625 C","626 C","627 C","331 C","332 C","333 C","334 C","335 C","336 C","337 C","338 C","339 C","340 C","341 C","342 C","343 C","7723 C","7724 C","7725 C","7726 C","7727 C","7728 C","7729 C","3375 C","3385 C","3395 C","3405 C","3415 C","3425 C","3435 C","344 C","345 C","346 C","347 C","348 C","349 C","350 C","351 C","352 C","353 C","354 C","355 C","356 C","357 C","7478 C","7479 C","7480 C","7481 C","7482 C","7483 C","7484 C","7730 C","7731 C","7732 C","7733 C","7734 C","7735 C","7736 C","7737 C","7738 C","7739 C","7740 C","7741 C","7742 C","7743 C","358 C","359 C","360 C","361 C","362 C","363 C","364 C","7485 C","7486 C","7487 C","7488 C","7489 C","7490 C","7491 C","365 C","366 C","367 C","368 C","369 C","370 C","371 C","372 C","373 C","374 C","375 C","376 C","377 C","378 C","580 C","579 C","578 C","577 C","576 C","575 C","574 C","5807 C","5797 C","5787 C","5777 C","5767 C","5757 C","5747 C","5875 C","5865 C","5855 C","5845 C","5835 C","5825 C","5815 C","5803 C","5793 C","5783 C","5773 C","5763 C","5753 C","5743 C","7492 C","7493 C","7494 C","7495 C","7496 C","7497 C","7498 C","7744 C","7745 C","7746 C","7747 C","7748 C","7749 C","7750 C","379 C","380 C","381 C","382 C","383 C","384 C","385 C","386 C","387 C","388 C","389 C","390 C","391 C","392 C","587 C","586 C","585 C","584 C","583 C","582 C","581 C","393 C","394 C","395 C","396 C","397 C","398 C","399 C","3935 C","3945 C","3955 C","3965 C","3975 C","3985 C","3995 C","600 C","601 C","602 C","603 C","604 C","605 C","606 C","607 C","608 C","609 C","610 C","611 C","612 C","613 C","461 C","460 C","459 C","458 C","457 C","456 C","455 C","614 C","615 C","616 C","617 C","618 C","619 C","620 C","7751 C","7752 C","7753 C","7754 C","7755 C","7756 C","7757 C","7758 C","7759 C","7760 C","7761 C","7762 C","7763 C","7764 C","7765 C","7766 C","7767 C","7768 C","7769 C","7770 C","7771 C","4545 C","4535 C","4525 C","4515 C","4505 C","4495 C","4485 C","454 C","453 C","452 C","451 C","450 C","449 C","448 C","7499 C","7500 C","7501 C","7502 C","7503 C","7504 C","7505 C","468 C","467 C","466 C","465 C","464 C","463 C","462 C","7506 C","7507 C","7508 C","7509 C","7510 C","7511 C","7512 C","719 C","720 C","721 C","722 C","723 C","724 C","725 C","475 C","474 C","473 C","472 C","471 C","470 C","469 C","726 C","727 C","728 C","729 C","730 C","731 C","732 C","4685 C","4675 C","4665 C","4655 C","4645 C","4635 C","4625 C","7513 C","7514 C","7515 C","7516 C","7517 C","7518 C","7519 C","4755 C","4745 C","4735 C","4725 C","4715 C","4705 C","4695 C","482 C","481 C","480 C","479 C","478 C","477 C","476 C","7527 C","7528 C","7529 C","7530 C","7531 C","7532 C","7533 C","7534 C","7535 C","7536 C","7537 C","7538 C","7539 C","7540 C","427 C","428 C","429 C","430 C","431 C","432 C","433 C","420 C","421 C","422 C","423 C","424 C","425 C","426 C","441 C","442 C","443 C","444 C","445 C","446 C","447 C","413 C","414 C","415 C","416 C","417 C","418 C","419 C","400 C","401 C","402 C","403 C","404 C","405 C","406 C","407 C","408 C","409 C","410 C","411 C","412 C","434 C","435 C","436 C","437 C","438 C","439 C","440 C","Warm Gray 1 C","Warm Gray 2 C","Warm Gray 3 C","Warm Gray 4 C","Warm Gray 5 C","Warm Gray 6 C","Warm Gray 7 C","Warm Gray 8 C","Warm Gray 9 C","Warm Gray 10 C","Warm Gray 11 C","Cool Gray 1 C","Cool Gray 2 C","Cool Gray 3 C","Cool Gray 4 C","Cool Gray 5 C","Cool Gray 6 C","Cool Gray 7 C","Cool Gray 8 C","Cool Gray 9 C","Cool Gray 10 C","Cool Gray 11 C","Black 2 C","Black 3 C","Black 4 C","Black 5 C","Black 6 C","Black 7 C"],$t=["FEDD00","FFD700","FE5000","F9423A","EF3340","CE0058","E10098","BB29BB","440099","10069F","001489","0085CA","00AB84","2D2926","F2F0A1","FCAEBB","F1B2DC","BF9BDE","74D1EA","9DE7D7","9E978E","009ACE","44D62C","FFE900","FFAA4D","FF7276","FF3EB5","EA27C2","84754E","85714D","866D4B","8B6F4E","87674F","8B634B","8A8D8F","FFD900","FF5E00","F93822","CE0056","D62598","4E008E","00239C","0084CA","00B08B","222223","F6EB61","F7EA48","FCE300","C5A900","AF9800","897A27","F5E1A4","ECD898","EED484","F4DA40","F2CD00","F1C400","CBA052","F9E547","FBE122","FEDB00","FFD100","DAAA00","AA8A00","9C8412","FAE053","FBDD40","FDDA24","FFCD00","C99700","AC8400","897322","F3DD6D","F3D54E","F3D03E","F2A900","CC8A00","A07400","6C571B","F8E08E","FBD872","FFC845","FFB81C","C69214","AD841F","886B25","FBDB65","FDD757","FED141","FFC72C","EAAA00","B58500","9A7611","FFC600","FFB500","D19000","B47E00","73531D","5A4522","4B3D2A","D29F13","B78B20","9F7D23","967126","8F6A2A","7D622E","6C5D34","FDD26E","FFC658","FFBF3F","FFA300","DE7C00","AF6D04","74531C","FDD086","FFC56E","FFB549","FF9E1B","D57800","996017","6E4C1E","F2C75C","F1BE48","F1B434","ED8B00","CF7F00","A76D11","715C2A","F6BE00","F0B323","FEAD77","E6A65D","D38235","DC8633","C16C18","BD9B60","D69A2D","DB8A06","CD7925","AD6433","89532F","775135","D78825","D3832B","C67D30","B67233","A7662B","9E6A38","835D32","FCC89B","FDBE87","FDAA63","F68D2E","EA7600","D45D00","BE4D00","FECB8B","FFC27B","FFB25B","FF8200","E57200","BE6A14","9B5A1A","EFD19F","EFBE7D","ECA154","E87722","CB6015","A1561C","603D20","FFAE62","FF8F1C","FF6900","B94700","94450B","653819","FFB990","FFA06A","FF7F32","FF6A13","D86018","A65523","8B4720","FFBE9F","FF9D6E","FF7F41","FF671F","E35205","BE531C","73381D","DB864E","E07E3C","DC6B2F","DC582A","C05131","864A33","674736","FFA38B","FF8D6D","FF6A39","FC4C02","DC4405","A9431E","833921","FFB3AB","FF8674","FF5C39","FA4616","CF4520","963821","6B3529","C4622D","BA5826","AF5C37","9E5330","924C2E","7B4D35","5C4738","D4B59E","C07D59","B15533","9D432C","7C3A2D","6B3D2E","5C3D31","D14124","BD472A","B33D26","8D3F2B","83412C","7B4931","674230","E4D5D3","E1BBB4","D6938A","C26E60","A4493D","823B34","683431","DDBCB0","CA9A8E","BC8A7E","A37F74","866761","6B4C4C","583D3E","EABEB0","C09C83","B46A55","AB5C57","A45248","9A6A4F","8A391B","ECC3B2","ECBAA8","EAA794","E8927C","DA291C","9A3324","653024","FFB1BB","FF808B","FF585D","E03C31","BE3A34","81312F","FFA3B5","FF8DA1","F8485E","EE2737","D22630","AF272F","7C2529","FCAFC0","FB637E","F4364C","CB333B","A4343A","643335","C66E4E","C04C36","B7312C","AB2328","93272C","8A2A2B","802F2D","E1523D","C63527","A72B2A","9E2A2B","6D3332","633231","572D2D","E6BAA8","E56A54","E04E39","CD545B","B04A5A","9B2242","651D32","FABBCB","FC9BB3","F65275","E4002B","C8102E","A6192E","76232F","ECC7CD","E89CAE","DF4661","D50032","BA0C2F","9D2235","862633","F8A3BC","F67599","EF426F","E40046","BF0D3E","9B2743","782F40","F5B6CD","F59BBB","EF4A81","E0004D","C5003E","A6093D","8A1538","F5DADF","F7CED7","F9B5C4","F890A5","EF6079","E03E52","CB2C30","F2D4D7","F4C3CC","F2ACB9","E68699","D25B73","B83A4B","9E2A2F","ECB3CB","E782A9","E0457B","CE0037","A50034","861F41","6F263D","F99FC9","F57EB6","F04E98","E31C79","CE0F69","AC145A","7D2248","F4CDD4","E06287","E24585","B52555","A4123F","971B2F","6A2C3E","D6C9CA","C4A4A7","C16784","C63663","BC204B","912F46","7E2D40","EABEDB","E56DB1","DA1884","A50050","910048","6C1D45","936D73","934054","8E2C48","732E4A","672E45","582D40","502B3A","EF95CF","EB6FBD","DF1995","D0006F","AA0061","890C58","672146","F4A6D7","F277C6","E93CAC","C6007E","A20067","840B55","EAD3E2","E6BCD8","DFA0C9","D986BA","C6579A","AE2573","960051","E5CEDB","E3C8D8","DEBED2","C996B6","B06C96","994878","7C2855","E4C6D4","DCB6C9","D0A1BA","BE84A3","A76389","893B67","612141","EBBECB","E8B3C3","E4A9BB","D592AA","84344E","6F2C3F","572932","E2BCCB","DCA9BF","C9809E","B55C80","A73A64","9B3259","872651","E9CDD0","E4BEC3","D7A3AB","C48490","B46B7A","984856","893C47","F2C6CF","F1BDC8","E9A2B2","DC8699","8F3237","7F3035","5D2A2C","E9C4C7","E5BAC1","DAA5AD","C6858F","7A3E3A","6A3735","512F2E","DFC2C3","DBB7BB","CCA1A6","B07C83","9C6169","874B52","3F2021","F1A7DC","EC86D0","E45DBF","DB3EB1","C5299B","AF1685","80225F","EFBAE1","E277CD","D539B5","C800A1","B0008E","9E007E","830065","EAB8E4","E59BDC","DD7FD3","C724B1","BB16A3","A51890","80276C","A56E87","A83D72","991E66","8A1B61","722257","6A2A5B","5E2751","E7BAE4","DD9CDF","C964CF","AD1AAC","981D97","72246C","EBC6DF","E6BEDD","E2ACD7","D48BC8","93328E","833177","612C51","EEDAEA","CCAED0","D59ED7","B288B9","A277A6","9F5CC0","963CBD","D7A9E3","C98BDB","AC4FC6","9B26B6","87189D","772583","653165","948794","A2789C","A15A95","8E3A80","6E2B62","6A3460","5D3754","D5C2D8","C9B1D0","BA9CC5","A57FB2","642F6C","59315F","4B3048","DBCDD3","D0BEC7","C6B0BC","AF95A6","86647A","66435A","4A3041","D8C8D1","D3C0CD","BFA5B8","9B7793","7E5475","693C5E","512A44","DFC8E7","D7B9E4","CAA2DD","B580D1","8031A7","702F8A","572C5F","D6BFDD","C6A1CF","8C4799","6D2077","642667","5D285F","51284F","CBA3D8","B884CB","A05EB5","84329B","702082","671E75","5F2167","9991A4","8D6E97","7A4183","6B3077","653279","5E366E","5C4E63","C1A0DA","A77BCA","8246AF","5C068C","500778","470A68","3C1053","D7C6E6","C1A7E2","9063CD","753BBD","5F259F","582C83","512D6D","C5B4E3","AD96DC","9678D3","7D55C7","330072","2E1A47","B4B5DF","9595D2","7474C1","24135F","211551","201747","221C35","A7A4E0","8B84D7","685BC7","2E008B","280071","250E62","201547","6E7CA0","686E9F","615E9B","565294","514689","4C4184","535486","DDDAE8","B6B8DC","A7A2C3","8986CA","5D4777","4B384C","41273B","878CB4","7C7FAB","7566A0","6F5091","68478D","563D82","523178","E5E1E6","E0DBE3","C6BCD0","A192B2","7C6992","614B79","3F2A56","D8D7DF","C6C4D2","B3B0C4","8D89A5","595478","403A60","1E1A34","C5CFDA","BBC7D6","A2B2C8","8E9FBC","1B365D","1F2A44","1C1F2A","D9E1E2","A4BCC2","98A4AE","768692","425563","253746","131E29","B9D3DC","A3C7D2","8DB9CA","6BA4B8","003D4C","00313C","072B31","BFCED6","B7C9D3","A6BBC8","7A99AC","5B7F95","4F758B","081F2C","D1DDE6","C6D6E3","9BB8D3","7DA1C4","5E8AB4","236192","002E5D","DBE2E9","CED9E5","A7BCD6","7D9BC1","326295","003A70","002554","DDE5ED","C8D8EB","B1C9E8","7BA4DB","407EC9","003594","001A70","BDC5DB","89ABE3","8094DD","7BA6DE","5F8FB4","3A5DAE","606EB2","CBD3EB","9FAEE5","485CC7","1E22AA","171C8F","151F6D","141B4D","B8CCEA","5C88DA","0047BB","06038D","001871","001E62","071D49","C3D7EE","A7C6ED","307FE2","001A72","001E60","13294B","ABCAE9","8BB8E8","418FDE","012169","00205B","041E42","92C1E9","6CACE4","0072CE","0033A0","003087","002D72","0C2340","94A9CB","6787B7","426DA9","385E9D","2C5697","1D4F91","1D428A","C6DAE7","BDD6E6","A4C8E1","7BAFD4","003C71","003057","00263A","B9D9EB","9BCBEB","69B3E7","003DA5","002F6C","002855","041C2C","8DC8E8","62B5E5","009CDE","0057B8","004C97","003865","00263E","71C5E8","41B6E6","00A3E0","005EB8","004B87","003B5C","002A3A","4698CB","298FC2","0076A8","006298","005587","004976","01426A","99D6EA","5BC2E7","00A9E0","0077C8","00629B","004F71","003E51","7BA7BC","6399AE","4E87A0","41748D","34657F","165C7D","005776","BBDDE6","71B2C9","4298B5","0086BF","007DBA","00558C","002B49","9ADBE8","59CBE8","00B5E2","006BA6","00587C","003B49","A4DBE8","8BD3E6","4EC3E0","00AFD7","0095C8","0082BA","0067A0","48A9C5","009CBD","0085AD","007096","006A8E","00617F","005670","B8DDE1","9BD3DD","77C5D5","3EB1C8","0093B2","007396","005F83","6AD1E3","05C3DE","00A9CE","0092BC","007FA3","00677F","004851","68D2DF","00C1D5","00AEC7","008EAA","00778B","006272","004F59","63B1BC","00A7B5","0097A9","00859B","007D8A","007680","006269","B1E4E3","88DBDF","2DCCD3","009CA6","008C95","007377","005F61","A0D1CA","40C1AC","00B0B9","00A3AD","007398","005F86","005A70","7EDDD3","5CB8B2","279989","007681","487A7B","0D5257","244C5A","B6CFD0","ABC7CA","94B7BB","7FA9AE","4F868E","115E67","07272D","00968F","00857D","007672","006D68","00635B","005E5D","005151","9CDBD9","64CCC9","00B2A9","008675","007367","00685E","00534C","71DBD4","2AD2C9","00BFB3","00A499","008578","00594F","004C45","7CE0D3","2CD5C4","00C7B1","00B398","009681","007864","004E42","6DCDB8","49C5B1","00AB8E","009B77","008264","006A52","034638","B9DCD2","A1D6CA","86C8BC","6BBBAE","006F62","00594C","1D3C34","B5E3D8","A5DFD3","98DBCE","6BCABA","00816D","006C5B","173F35","ADCAB8","9ABEAA","85B09A","6FA287","28724F","205C40","284734","BFCEC2","A7BDB1","92ACA0","7F9C90","5C7F71","43695B","183028","BAC5B9","B0BDB0","A3B2A4","94A596","708573","5E7461","22372B","BCC9C5","B1C0BC","9DB0AC","829995","5D7975","3E5D58","18332F","D1E0D7","B7CDC2","9AB9AD","789F90","507F70","285C4D","13322B","A7E6D7","8CE2D0","3CDBC0","009775","007B5F","00664F","8FD6BD","6ECEB2","00B388","00965E","007A53","006747","115740","50A684","00966C","008755","007B4B","006F44","006845","005844","7AE1BF","47D7AC","00C389","00AF66","007749","006341","154734","A0DAB3","91D6AC","71CC98","009A44","00843D","046A38","2C5234","A2E4B8","8FE2B0","80E0A7","00B140","009639","007A33","215732","9BE3BF","26D07C","00BF6F","00B74F","009F4D","275D38","00573F","4B9560","228848","007A3E","007041","286140","36573B","395542","6BA539","48A23F","319B42","3A913F","44883E","4A773C","44693D","ADDC91","A1D884","6CC24A","43B02A","509E2F","4C8C2B","4A7729","D0DEBB","BCE194","8EDD65","78D64B","74AA50","719949","79863C","C2E189","B7DD79","A4D65E","78BE20","64A70B","658D1B","546223","D4EB8E","CDEA80","C5E86C","97D700","84BD00","7A9A01","59621D","C4D6A4","BCD19B","B7CE95","A9C47F","789D4A","67823A","4E5B31","D0D1AB","C6C89B","BABD8B","A2A569","8A8D4A","6D712E","3D441E","D2CE9E","CBC793","C0BB87","AFA96E","A09958","89813D","555025","C3C6A8","B3B995","A3AA83","899064","737B4C","5E6738","3E4827","BFCC80","BBC592","9CAF88","8F993E","76881D","7A7256","5B6236","BABC16","ABAD23","999B30","888D30","7C8034","727337","656635","E2E868","DBE442","CEDC00","C4D600","A8AD00","949300","787121","E9EC6B","E3E935","E0E721","D0DF00","B5BD00","9A9500","827A04","E3E48D","E0E27C","DBDE70","D2D755","B7BF10","8E8C13","625D20","F0EC74","EDE939","ECE81A","E1E000","BFB800","ADA400","A09200","F3EA5D","F3E500","EFDF00","EEDC00","BBA600","9A8700","685C20","F1EB9C","F0E991","F0E87B","EDE04B","EADA24","E1CD00","CFB500","EBE49A","E9E186","E6DE77","E1D555","D7C826","C4B000","B39B00","E9DF97","E4D77E","DECD63","D9C756","B89D18","A28E2A","695B24","DCD59A","D6CF8D","D0C883","C0B561","AC9F3C","9F912A","8A7B19","CAB64B","CFB023","C1A01E","A08629","897630","736635","675E33","D4C304","C4B200","91852C","747136","5D6439","585C3B","535435","BBB323","B4A91F","AA9D2E","8F7E35","716135","635939","4E4934","D5CB9F","CFC493","C5B783","B3A369","998542","8C7732","614F25","CAC7A7","BFBB98","B0AA7E","9B945F","594A25","524727","4A412A","F1E6B2","DFD1A7","D9C89E","CEB888","A89968","94795D","816040","DDCBA4","D3BC8D","C6AA76","B9975B","8B5B29","744F28","5C462B","EFDBB2","FCD299","E1B87F","D6A461","C6893F","B77729","A6631B","EDC8A3","E7B78A","DDA46F","C88242","B36924","934D11","7D3F16","F3CFB3","F1C6A7","F0BF9B","E59E6D","B86125","A45A2A","693F23","E0C09F","D9B48F","CDA077","B58150","9E652E","774212","623412","E0C6AD","DCBFA6","CDA788","BF9474","AD7C59","946037","4F2C1D","E1B7A7","D5A286","C58B68","99552B","85431E","6D4F47","5E4B3C","D7C4B7","CDB5A7","C0A392","AE8A79","956C58","7C4D3A","5B3427","DBC8B6","D3BBA8","C6A992","AA8066","703F2A","623B2A","4E3629","D6D2C4","C5B9AC","B7A99A","A39382","7A6855","63513D","473729","D1CCBD","B7B09C","A69F88","A7ACA2","949A90","8E9089","4B4F54","D0D3D4","C1C6C8","A2AAAD","7C878E","5B6770","333F48","1D252D","C7C9C7","B2B4B2","9EA2A2","898D8D","707372","54585A","25282A","BEC6C4","A2ACAB","919D9D","717C7D","505759","3F4444","373A36","BABBB1","A8A99E","919388","7E7F74","65665C","51534A","212322","C4BFB6","AFA9A0","9D968D","8C857B","776E64","696158","C4BCB7","B2A8A2","978C87","857874","746661","5E514D","382F2D","D0C4C5","C1B2B6","AB989D","7B6469","584446","453536","382E2C","D7D2CB","CBC4BC","BFB8AF","B6ADA5","ACA39A","A59C94","968C83","8C8279","83786F","796E65","6E6259","D9D9D6","D0D0CE","C8C9C7","BBBCBC","B1B3B3","A7A8AA","97999B","888B8D","75787B","63666A","53565A","332F21","212721","31261D","3E2B2E","101820","3D3935"],ra=$t.map(i=>[parseInt(i.substring(0,2),16),parseInt(i.substring(2,4),16),parseInt(i.substring(4,6),16)]);function go(i){const t=re.indexOf(i);return t>=0?$t[t]:""}function ii(i){const t=$t.indexOf(i);return t>=0?re[t]:""}function mo(i,t=64){const e=[],a=[],n=ii(i);n&&e.push({pms:n,hex:i,distance:0});const r=parseInt(i.substring(0,2),16),o=parseInt(i.substring(2,4),16),s=parseInt(i.substring(4,6),16);let l,c,d;for(let u=0;u<$t.length;u++){l=ra[u][0],c=ra[u][1],d=ra[u][2];const A=Math.sqrt(Math.pow(r-l,2)+Math.pow(o-c,2)+Math.pow(s-d,2));a.push(A)}for(let u=0;u<a.length;u++)a[u]<=t&&!e.some(A=>A.pms===re[u])&&e.push({pms:re[u],hex:$t[u],distance:a[u]});return e.sort((u,A)=>u.distance-A.distance)}const po=re.map((i,t)=>({pms:i,hex:$t[t]})),fo=new Nr(po,{keys:["pms"]});function Co(i,t){return fo.search(i,t?{limit:t}:void 0)}let Lt=null;function ri(i){if(i.startsWith("#"))return fn(i);if(!document)throw new Error("browserColorToHex is only supported on browsers");if(Lt||(Lt=document.createElement("canvas").getContext("2d")),!Lt)throw new Error("Failed to create canvas context required to convert colors");Lt.fillStyle=i;const t=fn(Lt.fillStyle);return t||console.error(`Unknown browser color ${i}`),t}function fn(i){const t=i.substring(1).toUpperCase();return t.length===6?t:t.length===3?`${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:""}const ve=i=>{const t=oi(i.spotColor);return t?`${i.browserValue} ${t}`:i.browserValue},oi=i=>{if(!i)return"";if(i.profileName.includes("/")&&i.profileName.includes(".icc")){const t=i.profileName.replace(/\s/g,"-"),e=t.lastIndexOf("/");return`icc-named-color(${t.slice(e+1).slice(0,-4)}, ${i.namedColor})`}return`icc-named-color(${i.profileName}, ${i.namedColor})`},Ba=i=>{const t=i.split(/[ ](?=[^)]*?(?:\(|$))/);if(t.length===0)return{browserValue:"#000000"};if(t.length===1)return{browserValue:t[0]};const e=t[1].match(/\(([^)]+)\)/gm);if(!e)throw new Error("Unhandled state of color value in SVG");const a=e[0].replace(/[() ]/g,"").split(",");return{browserValue:t[0],spotColor:{profileName:a[0],namedColor:a[1]}}},wo=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],yo=["fill","stroke"],Ut=(i,t)=>{t(i),i.children.length>0&&Array.from(i.children).forEach(e=>Ut(e,t))},si=(i,t)=>{const e=t(i);if(e)return e;const a=i.parentElement;if(a)return si(a,t)},So=(i,t)=>{try{return i.matches(t)}catch{return i.classList.contains(t.substring(1))}},je=(i,t=!1)=>{!t&&i.setAttribute("preserveAspectRatio","none");const e=[];Ut(i,a=>{if(a.tagName==="script"){a.remove();return}if(a.tagName==="style"){try{Vn.parse(a.innerHTML).stylesheet?.rules.forEach(o=>{e.push(o)}),a.remove()}catch(r){console.error(r)}return}const n=a.attributes.getNamedItem("style")?.value?.trim();if(n){const r=[];n.split(";").forEach(s=>{const l=s.trim();if(l){const[c,d]=l.split(":"),u=c.toLowerCase();yo.indexOf(u)>-1?a.setAttribute(u,d.trim()):r.push(l)}}),r.length>0?a.setAttribute("style",r.join(";")):a.removeAttribute("style")}}),Ut(i,a=>{e.forEach(n=>{n.selectors?.forEach(r=>{So(a,r)&&n.declarations?.forEach(o=>{o.property&&o.value&&a.setAttribute(o.property,o.value)})})})})},vo=i=>{const t=/pt|pc|mm|cm|in/gm,e=i.getAttribute("viewBox"),a=i.getAttribute("width"),n=i.getAttribute("height");if(!e)throw new Error("viewBox not specified on SVG!");a&&i.setAttribute("width",a.replace(t,"")),n&&i.setAttribute("height",n.replace(t,""))},li=i=>ct().parseFromString(i,"image/svg+xml").firstElementChild,Eo=(i,t,e)=>{i.setAttribute("height",`${e}px`),i.setAttribute("width",`${t}px`)},ci=(i,t,e)=>{Ut(i,a=>{const n=a.attributes.getNamedItem("fill");n&&n.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-fill")){const s=t[o.replace("spiff-fill-","")];if(s)a.setAttribute("fill",e?ve(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ve(l):l.browserValue)}}});const r=a.attributes.getNamedItem("stroke");r&&r.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-stroke")){const s=t[o.replace("spiff-stroke-","")];if(s)a.setAttribute("stroke",e?ve(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ve(l):l.browserValue)}}})})},di=i=>It().serializeToString(i),Ga=(i,t,e,a,n)=>{const r=li(i);if(!r)throw new Error("Failed to read SVG.");return Eo(r,t,e),ci(r,a,n),di(r)},He=(i,t,e)=>{const a=li(i);if(!a)throw new Error("Failed to read SVG.");return ci(a,t,e),di(a)},bo=i=>{const t=/<svg.*<\/svg>/s,e=i.match(t)||[],a=e?.length>0?e[0]:"";return ct().parseFromString(a,"image/svg+xml")},rt=async i=>{const e=bo(i).firstElementChild;if(!e)throw new Error("Failed to read SVG.");je(e);const a={};Ut(e,o=>{if(wo.includes(o.tagName)&&!o.attributes.getNamedItem("fill")){let c="black";const d=o.parentElement;if(d){const u=si(d,A=>{const g=A.style.fill;if(g)return g;const p=A.getAttribute("fill");if(p)return p});u&&(c=u)}o.setAttribute("fill",c)}const s=o.attributes.getNamedItem("fill");if(s&&s.value!=="none"&&!s.value.startsWith("url(")){const c=Ba(s.value),d=c.browserValue.replace(/\W/g,""),u=`spiff-fill-${d}`;o.setAttribute("fill",c.browserValue),o.classList.add(u),a[d]=c}const l=o.attributes.getNamedItem("stroke");if(l&&l.value!=="none"&&!l.value.startsWith("url(")){const c=Ba(l.value),d=c.browserValue.replace(/\W/g,""),u=`spiff-stroke-${d}`;o.classList.add(u),o.setAttribute("stroke",c.browserValue),a[d]=c}});const r=It().serializeToString(e);return{colors:a,svg:r}},Io=f.gql`
1
+ "use strict";var lr=Object.create;var rn=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var dr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,Ar=Object.prototype.hasOwnProperty;var hr=(i,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of dr(t))!Ar.call(i,n)&&n!==e&&rn(i,n,{get:()=>t[n],enumerable:!(a=cr(t,n))||a.enumerable});return i};var gr=(i,t,e)=>(e=i!=null?lr(ur(i)):{},hr(t||!i||!i.__esModule?rn(e,"default",{value:i,enumerable:!0}):e,i));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("@apollo/client/core/index.js"),mr=require("@apollo/client/link/context/index.js"),pr=require("@apollo/client/link/error/index.js"),fr=require("react-dom/server"),Cr=require("@apollo/client/link/remove-typename/index.js"),wr=require("exifr/dist/mini.esm.mjs"),Pn=require("css"),yr=require("fuse.js"),Ma=require("pith"),ga=require("lodash.chunk"),Ct=require("lodash.clonedeep"),P=require("react/jsx-runtime"),ma=require("opentype.js"),Sr=require("html-entities"),vr=require("react"),Er=require("handlebars"),br=require("data-uri-to-buffer"),fe=require("@aws-sdk/client-cognito-identity-provider"),Ir=require("dinero.js"),Br=require("currency-codes"),xn=require("lodash.debounce"),te=require("lodash.isequal"),pa=require("unicode-default-word-boundary"),Fn=require("qrcode"),Pr=require("svg-path-bbox"),xr=require("lodash.omit");function Fr(i){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const a=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,a.get?a:{enumerable:!0,get:()=>i[e]})}}return t.default=i,Object.freeze(t)}const sn=Fr(Br);var ee=(i=>(i.Data="Data",i.Font="Font",i.Frame="Frame",i.Illustration="Illustration",i.Image="Image",i.Model="Model",i.Material="Material",i.Color="Color",i.QuestionnaireCollateral="QuestionnaireCollateral",i.RequestCollateral="RequestCollateral",i.SignupCollateral="SignupCollateral",i.Video="Video",i.ColorProfile="ColorProfile",i.Environment="Environment",i))(ee||{}),Dn=(i=>(i.AND="AND",i.OR="OR",i))(Dn||{}),z=(i=>(i.FileUpload="FileUpload",i.Option="Option",i.ColorOption="ColorOption",i.Text="Text",i))(z||{}),E=(i=>(i.Information="Information",i.Bulk="Bulk",i.DigitalContent="DigitalContent",i.Finish="Finish",i.Frame="Frame",i.Illustration="Illustration",i.Introduction="Introduction",i.Material="Material",i.Model="Model",i.Module="Module",i.Picture="Picture",i.Photo="Photo",i.ProductOverlay="ProductOverlay",i.Question="Question",i.Shape="Shape",i.SilentIllustration="SilentIllustration",i.Text="Text",i))(E||{}),kn=(i=>(i.Color="Color",i.Colors="Colors",i.Selection="Selection",i.Selections="Selections",i.Text="Text",i.Upload="Upload",i))(kn||{}),Nt=(i=>(i.ThreeD="ThreeD",i.FreeDesign="FreeDesign",i.Print="Print",i))(Nt||{}),D=(i=>(i.Frame="frame",i.Group="group",i.Image="image",i.Pattern="pattern",i.Illustration="illustration",i.Textbox="textbox",i))(D||{}),Mn=(i=>(i.Default="Default",i.FirstTransaction="FirstTransaction",i.OneToOne="OneToOne",i))(Mn||{}),Ta=(i=>(i.Pending="Pending",i.Failed="Failed",i.Validated="Validated",i.Overridden="Overridden",i))(Ta||{}),Tn=(i=>(i.Hyperlink="Hyperlink",i.Edit="Edit",i.Approve="Approve",i))(Tn||{}),Nn=(i=>(i.Hub="Hub",i.Shopify="Shopify",i))(Nn||{}),Oe=(i=>(i.AdvancedImageManipulation="BackgroundRemover",i.ConversionAccelerator="Conversion Accelerator",i.ProcessBuilder="ProcessBuilder",i))(Oe||{}),Qn=(i=>(i[i.Orbit=0]="Orbit",i[i.Pan=1]="Pan",i))(Qn||{}),Na=(i=>(i.Owner="Owner",i.Approver="Approver",i.Editor="Editor",i.Viewer="Viewer",i))(Na||{}),Bt=(i=>(i.Autosize="Autosize",i.Traditional="Traditional",i))(Bt||{}),Y=(i=>(i[i.North=0]="North",i[i.Northeast=1]="Northeast",i[i.East=2]="East",i[i.Southeast=3]="Southeast",i[i.South=4]="South",i[i.Southwest=5]="Southwest",i[i.West=6]="West",i[i.Northwest=7]="Northwest",i))(Y||{}),On=(i=>(i.Pixel="px",i.Millimeter="mm",i.Centimeter="cm",i))(On||{}),Jt=(i=>(i.Email="Email",i.FirstName="FirstName",i.LastName="LastName",i.Phone="Phone",i.Apartment="Apartment",i.City="City",i.Country="Country",i.OrganizationName="OrganizationName",i.PostCode="PostCode",i.State="State",i.StreetAddress="StreetAddress",i.Custom="Custom",i))(Jt||{});class Rn extends Error{constructor(t){super(t),this.name=this.constructor.name}}class se extends Rn{constructor(t){super(`ConfigurationError - ${t}`)}}class ae extends se{constructor(t){super(`Option not Configured: ${t.stepTitle}`),this.optionId=t?.optionId||"N/A"}}class J extends se{constructor(t){super(`Panel not Found: ${t.panelId}`),this.panelId=t?.panelId||"N/A"}}class wt extends se{constructor(t){super(`Asset not found for variant: ${t.name}`),this.variant=t}}class Qt extends se{constructor(t){super(`Resource not found for asset: ${t.name}`),this.asset=t}}class st extends se{constructor(t,e){super(`Workflow Misconfiguration: ${t.stepName} - ${e}`),this.step=t}}class Re extends Rn{constructor(t){super(`ImplementationError - ${t}`)}}class O extends Re{constructor(t){super(`Unhandled Behavior Encountered: ${t}`)}}class It extends Re{constructor(t){super(`Parsing Error: ${t}`)}}class mt extends Re{constructor(t){super(`Client Error: ${t}`)}}class $e extends Re{constructor(t){super(`Resource Generation Failed: ${t}`)}}class Dr{get(t){return localStorage.getItem(t)||void 0}set(t,e){localStorage.setItem(t,e)}remove(t){localStorage.removeItem(t)}getMap(t){const e=this.get(t);if(e)return new Map(JSON.parse(e))}setMap(t,e){const a=JSON.stringify([...e.entries()]);this.set(t,a)}}class on{constructor(){this.storage=new Map}get(t){return this.storage.get(t)||void 0}set(t,e){this.storage.set(t,e)}remove(t){this.storage.delete(t)}getMap(t){const e=this.get(t);if(e)return new Map(JSON.parse(e))}setMap(t,e){const a=JSON.stringify([...e.entries()]);this.set(t,a)}}const kr=()=>{try{return localStorage?new Dr:new on}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new on}},Q=kr();class Mr{constructor(){this.defaultServerUrl="https://api.au.spiffcommerce.com",this.defaultServicesApiUrl="https://services.au.spiffcommerce.com",this.defaultHubUrl="https://hub.au.spiffcommerce.com",this.serverUrl=this.defaultServerUrl,this.servicesApiUrl=this.defaultServicesApiUrl,this.hubUrl=this.defaultHubUrl,this.serverUrlCallbacks=[]}getServerUrl(){return this.serverUrl}getServicesApiUrl(){return this.servicesApiUrl}getHubUrl(){return this.hubUrl}setServerUrl(t){this.serverUrl=t,this.serverUrlCallbacks.forEach(e=>e())}setServicesApiUrl(t){this.servicesApiUrl=t}setHubUrl(t){this.hubUrl=t}addServerUrlCallback(t){this.serverUrlCallbacks.push(t)}}const At=new Mr;let fa,Ca;function Tr(i){fa=i}function Nr(i){Ca=i}function oe(){return fa?new fa().window:(console.log("DOM constructor is not registered. Assuming browser environment. If not, please register DOM constructor before calling this function."),window)}function nt(i,t){if(!Ca){if(typeof window<"u"&&window.fetch)return window.fetch(i,t);if(typeof global<"u"&&global.fetch)return global.fetch(i,t);throw new Error("Fetch implementation is not registered. Please register it before calling this function.")}return Ca(i,t)}const $n=new Map,ln=new Map,cn=new Map,Un=async i=>{const t=ln.get(i);if(t)return t;const a=(async()=>{const n=await nt(i);return $n.set(i,n.headers?.get("content-type")||""),await n.arrayBuffer()})();return ln.set(i,a),a},Qr=async i=>{const t=cn.get(i);if(t)return t;const a=(async()=>await(await nt(i)).text())();return cn.set(i,a),a},$t=i=>i.every(t=>t!=="undefined"),Ce=i=>$t([typeof document])?document.createElement(i):oe().document.createElement(i),Or=(i,t)=>{if($t([typeof document]))return document.createElementNS(i,t);const a=oe().document.createElement(t);return a.setAttribute("xmlns",i),a},ot=()=>{if($t([typeof DOMParser]))return new DOMParser;const i=oe();return new i.DOMParser},Rr=()=>$t([typeof DOMParser])?DOMParser:oe().DOMParser,Ue=(i,t)=>new Promise((e,a)=>{t?Un(i).then(e).catch(a):nt(i).then(n=>{n.arrayBuffer().then(e).catch(a)}).catch(n=>{a(n)})}),tt=(i,t)=>new Promise((e,a)=>{t?Qr(i).then(e).catch(a):nt(i).then(n=>{n.text().then(e).catch(a)}).catch(a)}),Vn=i=>fr.renderToStaticMarkup(i),ta=new Map,$r=async(i,t)=>{if($t([typeof FontFace])){if(ta.has(t))return ta.get(t);const e=i.names.fullName.en,a=new FontFace(e,`url(${t})`);document.fonts.add(a);const n=a.load();return ta.set(t,n),n}},Et=()=>{if($t([typeof XMLSerializer]))return new XMLSerializer;const i=oe();return new i.XMLSerializer},dn=i=>btoa(i),Ve=i=>{function t(){const a=new Uint8Array(i),n=4;if(a.length>=n){const r=new Array(n);for(let l=0;l<n;l++)r[l]=new Uint8Array(i)[l].toString(16);const s=r.join("").toUpperCase();switch(s){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"504B0304":return"application/zip"}if(s.slice(0,4)==="FFD8")return"image/jpeg"}return null}const e=t();return e||"image/svg+xml"},Ur=async i=>{const t=await Un(i),e=$n.get(i)||Ve(t);return await zr(new Blob([t],{type:e}))},Vr=i=>{let t="";const e=i.byteLength;for(let a=0;a<e;a++)t+=String.fromCharCode(i[a]);return t},Lr=async i=>{const t=Ve(i),e=new Uint8Array(i),a=Vr(e),n=btoa(a);return`data:${t};base64,${n}`},Le=i=>`data:image/svg+xml;base64,${btoa(i)}`,Ln=i=>{const t=i.replace(/\r?\n/g,""),e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");const a=t.substring(5,e).split(";");let n=!1;for(let s=1;s<a.length;s++)a[s]==="base64"&&(n=!0);const r=decodeURI(t.substring(e+1));return n?new Uint8Array(atob(r).split("").map(o=>o.charCodeAt(0))).buffer:new Uint8Array(r.split("").map(o=>o.charCodeAt(0))).buffer},zr=i=>new Promise((t,e)=>{const a=new FileReader;a.onload=function(n){const r=n.target;!r||!r.result?e():t(r.result.toString())},a.readAsDataURL(i)});let qr,Qa;const Gr=i=>{Qa=i},jr=()=>Qa;let zn;const qn=i=>{zn=i},Wr=()=>new Promise(i=>{const t=At.getHubUrl(),e=a=>{a.origin===t&&(window.removeEventListener("message",e),i(a.data))};window.parent!==window&&(window.addEventListener("message",e,!1),window.parent.postMessage("ready",t))}),Hr=async()=>{const i={applicationKey:Qa,customerToken:qr,bearer:zn};return typeof window<"u"&&(window.location.href.includes("/workflows/product/")||window.location.href.includes("hub=true"))?{...await Wr(),...i}:i};async function Yr(i,t){const e=At.getServerUrl(),a=e.includes(".aumelbdev.spiffcommerce.com")?"https://moonlight.aumelbdev.spiffcommerce.com":e.includes(".us.spiffcommerce.com")?"https://moonlight.us.spiffcommerce.com":"https://moonlight.au.spiffcommerce.com";let n=await nt(i,{...t,redirect:"manual"});return(n.type==="opaqueredirect"||n.status===307)&&(typeof i!="string"&&"url"in i?n=await nt({...i,url:`${a}/graphql`},t):n=await nt(`${a}/graphql`,t)),n}class Jr{constructor(){this.shadowGraphqlClient=this.constructShadowGraphqlClient(),At.addServerUrlCallback(()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()})}setSpiffCommerceClient(t){this.spiffClient=t,this.shadowGraphqlClient=this.constructShadowGraphqlClient()}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const t=f.createHttpLink({uri:`${At.getServerUrl()}/graphql`,fetch:Yr}),e=mr.setContext(async(r,s)=>{const{headers:o}=s,l=o||{},c=await Hr();let d=s.bearer??c.bearer,u=!1;if(this.spiffClient){try{d=await this.spiffClient.loggedInBearerToken()}catch{}try{s.skipIntegrationCheck||(u=await this.spiffClient.getBetaEnabled())}catch{}}const A=s.partnerId??c.partnerId,h=s.activeIntegration??c.activeIntegration,g=s.transactionOwnerId,p=s.customerToken??c.customerToken,m=s.applicationKey??c.applicationKey,C=s.bundleOwnerId;try{if(window&&window.__SENTRY__){const S=window.__SENTRY__.hub;if(S){const w=S.traceHeaders();Object.entries(w).forEach(([F,b])=>{l[F]=b})}}}catch{}return d&&(l.Authorization=`Bearer ${d}`),A&&(l.partnerId=A),h&&(l.activeIntegration=h),g&&(l.transactionOwnerId=g),p&&(l.customerToken=p),m&&(l["X-Application-Key"]=m),C&&(l.bundleOwnerId=C),u&&(l["X-Spiff-Beta"]="true"),l["Allow-Moonlight-Redirect"]="true",{headers:l}}),a=pr.onError(({operation:r,graphQLErrors:s,networkError:o})=>{const l=s||[],c=r.getContext();o&&!c?.fetchOptions?.signal?.aborted&&console.log("GraphQL Network error"),l.forEach(()=>console.log("GraphQL Error: "+r.operationName))}),n=Cr.removeTypenameFromVariables();return new f.ApolloClient({link:f.from([n,a,e,t]),cache:new f.InMemoryCache,name:"Core"})}}const y=new Jr;let wa,ya;const yt=(i,t,e)=>{if(wa!==void 0)return wa(i,t,e);try{const a=Gn(!0);return Oa(a),a.createCanvas(i,t,e)}catch{throw new Error("Canvas module not set")}},le=(i,t)=>{if(ya!==void 0)return ya(i,t);try{const e=Gn(!0);return Oa(e),e.loadImage(i,t)}catch{throw new Error("Canvas module not set")}};function Oa(i){wa=i?.createCanvas,ya=i?.loadImage}function Gn(i){try{if(document.createElement("canvas").getContext("2d"))return{createCanvas:(e,a,n)=>{const r=document.createElement("canvas");return e!=null&&(r.width=e),a!=null&&(r.height=a),r},loadImage:(e,a)=>new Promise((n,r)=>{const s=document.createElement("img");a!==!1&&(s.crossOrigin="Anonymous"),s.onload=()=>{n(s)},s.onerror=r,s.src=e})}}catch(t){throw t}}let ea;function Ra(){return ea===void 0&&(ea=Rr()),ea}let we=null;const Kr=i=>new Promise(t=>{if(Ve(i)!=="image/jpeg")return t(1);wr.orientation(i).then(a=>t(a||1)).catch(()=>t(1))}),Xr=async()=>{if(we!==null)return!we;const t=await le("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/xABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQvoP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXwH/9k=");return we=t.width===2&&t.height===3,!we},Zr=i=>{const e=i.naturalWidth/i.naturalHeight;return i.naturalHeight<=8192&&i.naturalWidth<=8192?[i.naturalWidth,i.naturalHeight]:i.naturalHeight>i.naturalWidth?[e*8192,8192]:[8192,8192/e]},_r=async i=>{const t=await Lr(i),e=await le(t),[a,n]=Zr(e);if(!await Xr()){const u=yt(a,n);return u.getContext("2d")?.drawImage(e,0,0,a,n),u}const s=await Kr(i),[o,l]=s>4?[n,a]:[a,n],c=yt(o,l),d=c.getContext("2d");switch(s){case 2:d.translate(o,0),d.scale(-1,1);break;case 3:d.translate(o,l),d.rotate(Math.PI);break;case 4:d.translate(0,l),d.scale(1,-1);break;case 5:d.rotate(-.5*Math.PI),d.scale(-1,1);break;case 6:d.rotate(-.5*Math.PI),d.translate(-o,0);break;case 7:d.rotate(-.5*Math.PI),d.translate(-o,l),d.scale(1,-1);break;case 8:d.rotate(.5*Math.PI),d.translate(0,-l);break}return d.drawImage(e,0,0,o,l),c},ce=async i=>{const t=await _r(i);return Ve(i)==="image/jpeg"?{dataUrl:t.toDataURL("image/jpeg",1),height:t.height,width:t.width}:{dataUrl:t.toDataURL(),height:t.height,width:t.width}},ne=["Yellow C","Yellow 012 C","Orange 021 C","Warm Red C","Red 032 C","Rubine Red C","Rhodamine Red C","Purple C","Violet C","Blue 072 C","Reflex Blue C","Process Blue C","Green C","Black C","Yellow 0131 C","Red 0331 C","Magenta 0521 C","Violet 0631 C","Blue 0821 C","Green 0921 C","Black 0961 C","801 C","802 C","803 C","804 C","805 C","806 C","807 C","871 C","872 C","873 C","874 C","875 C","876 C","877 C","Medium Yellow C","Bright Orange C","Bright Red C","Strong Red C","Pink C","Medium Purple C","Dark Blue C","Medium Blue C","Bright Green C","Neutral Black C","100 C","101 C","102 C","103 C","104 C","105 C","7401 C","7402 C","7403 C","7404 C","7405 C","7406 C","7407 C","106 C","107 C","108 C","109 C","110 C","111 C","112 C","113 C","114 C","115 C","116 C","117 C","118 C","119 C","127 C","128 C","129 C","130 C","131 C","132 C","133 C","1205 C","1215 C","1225 C","1235 C","1245 C","1255 C","1265 C","120 C","121 C","122 C","123 C","124 C","125 C","126 C","7548 C","7549 C","7550 C","7551 C","7552 C","7553 C","7554 C","7555 C","7556 C","7557 C","7558 C","7559 C","7560 C","7561 C","134 C","135 C","136 C","137 C","138 C","139 C","140 C","1345 C","1355 C","1365 C","1375 C","1385 C","1395 C","1405 C","141 C","142 C","143 C","144 C","145 C","146 C","147 C","7408 C","7409 C","7410 C","7411 C","7412 C","7413 C","7414 C","7562 C","7563 C","7564 C","7565 C","7566 C","7567 C","7568 C","7569 C","7570 C","7571 C","7572 C","7573 C","7574 C","7575 C","712 C","713 C","714 C","715 C","716 C","717 C","718 C","148 C","149 C","150 C","151 C","152 C","153 C","154 C","155 C","156 C","157 C","158 C","159 C","160 C","161 C","1485 C","1495 C","1505 C","1525 C","1535 C","1545 C","1555 C","1565 C","1575 C","1585 C","1595 C","1605 C","1615 C","162 C","163 C","164 C","165 C","166 C","167 C","168 C","7576 C","7577 C","7578 C","7579 C","7580 C","7581 C","7582 C","1625 C","1635 C","1645 C","1655 C","1665 C","1675 C","1685 C","169 C","170 C","171 C","172 C","173 C","174 C","175 C","7583 C","7584 C","7585 C","7586 C","7587 C","7588 C","7589 C","7590 C","7591 C","7592 C","7593 C","7594 C","7595 C","7596 C","7597 C","7598 C","7599 C","7600 C","7601 C","7602 C","7603 C","7604 C","7605 C","7606 C","7607 C","7608 C","7609 C","7610 C","7611 C","7612 C","7613 C","7614 C","7615 C","7616 C","7617 C","7520 C","7521 C","7522 C","7523 C","7524 C","7525 C","7526 C","489 C","488 C","487 C","486 C","485 C","484 C","483 C","176 C","177 C","178 C","179 C","180 C","181 C","1765 C","1775 C","1785 C","1788 C","1795 C","1805 C","1815 C","1767 C","1777 C","1787 C","1797 C","1807 C","1817 C","7618 C","7619 C","7620 C","7621 C","7622 C","7623 C","7624 C","7625 C","7626 C","7627 C","7628 C","7629 C","7630 C","7631 C","7415 C","7416 C","7417 C","7418 C","7419 C","7420 C","7421 C","182 C","183 C","184 C","185 C","186 C","187 C","188 C","196 C","197 C","198 C","199 C","200 C","201 C","202 C","189 C","190 C","191 C","192 C","193 C","194 C","195 C","1895 C","1905 C","1915 C","1925 C","1935 C","1945 C","1955 C","705 C","706 C","707 C","708 C","709 C","710 C","711 C","698 C","699 C","700 C","701 C","702 C","703 C","704 C","203 C","204 C","205 C","206 C","207 C","208 C","209 C","210 C","211 C","212 C","213 C","214 C","215 C","216 C","7422 C","7423 C","7424 C","7425 C","7426 C","7427 C","7428 C","7632 C","7633 C","7634 C","7635 C","7636 C","7637 C","7638 C","217 C","218 C","219 C","220 C","221 C","222 C","7639 C","7640 C","7641 C","7642 C","7643 C","7644 C","7645 C","223 C","224 C","225 C","226 C","227 C","228 C","229 C","230 C","231 C","232 C","233 C","234 C","235 C","670 C","671 C","672 C","673 C","674 C","675 C","676 C","677 C","678 C","679 C","680 C","681 C","682 C","683 C","684 C","685 C","686 C","687 C","688 C","689 C","690 C","510 C","509 C","508 C","507 C","506 C","505 C","504 C","7429 C","7430 C","7431 C","7432 C","7433 C","7434 C","7435 C","691 C","692 C","693 C","694 C","695 C","696 C","697 C","496 C","495 C","494 C","493 C","492 C","491 C","490 C","503 C","502 C","501 C","500 C","499 C","498 C","497 C","5035 C","5025 C","5015 C","5005 C","4995 C","4985 C","4975 C","236 C","237 C","238 C","239 C","240 C","241 C","242 C","2365 C","2375 C","2385 C","2395 C","2405 C","2415 C","2425 C","243 C","244 C","245 C","246 C","247 C","248 C","249 C","7646 C","7647 C","7648 C","7649 C","7650 C","7651 C","7652 C","250 C","251 C","252 C","253 C","254 C","255 C","517 C","516 C","515 C","514 C","513 C","512 C","511 C","7436 C","7437 C","7438 C","7439 C","7440 C","7441 C","7442 C","2562 C","2572 C","2582 C","2592 C","2602 C","2612 C","2622 C","7653 C","7654 C","7655 C","7656 C","7657 C","7658 C","7659 C","524 C","523 C","522 C","521 C","520 C","519 C","518 C","5245 C","5235 C","5225 C","5215 C","5205 C","5195 C","5185 C","5175 C","5165 C","5155 C","5145 C","5135 C","5125 C","5115 C","531 C","530 C","529 C","528 C","527 C","526 C","525 C","256 C","257 C","258 C","259 C","260 C","261 C","262 C","2563 C","2573 C","2583 C","2593 C","2603 C","2613 C","2623 C","7660 C","7661 C","7662 C","7663 C","7664 C","7665 C","7666 C","2567 C","2577 C","2587 C","2597 C","2607 C","2617 C","2627 C","263 C","264 C","265 C","266 C","267 C","268 C","269 C","2635 C","2645 C","2655 C","2665 C","2685 C","2695 C","270 C","271 C","272 C","273 C","274 C","275 C","276 C","2705 C","2715 C","2725 C","2735 C","2745 C","2755 C","2765 C","7667 C","7668 C","7669 C","7670 C","7671 C","7672 C","7673 C","7443 C","7444 C","7445 C","7446 C","7447 C","7448 C","7449 C","7674 C","7675 C","7676 C","7677 C","7678 C","7679 C","7680 C","663 C","664 C","665 C","666 C","667 C","668 C","669 C","5315 C","5305 C","5295 C","5285 C","5275 C","5265 C","5255 C","538 C","537 C","536 C","535 C","534 C","533 C","532 C","7541 C","7542 C","7543 C","7544 C","7545 C","7546 C","7547 C","552 C","551 C","550 C","549 C","548 C","547 C","546 C","5455 C","5445 C","5435 C","5425 C","5415 C","5405 C","5395 C","642 C","643 C","644 C","645 C","646 C","647 C","648 C","649 C","650 C","651 C","652 C","653 C","654 C","655 C","656 C","657 C","658 C","659 C","660 C","661 C","662 C","7450 C","7451 C","7452 C","7453 C","7454 C","7455 C","7456 C","2706 C","2716 C","2726 C","2736 C","2746 C","2756 C","2766 C","2708 C","2718 C","2728 C","2738 C","2748 C","2758 C","2768 C","2707 C","2717 C","2727 C","2747 C","2757 C","2767 C","277 C","278 C","279 C","280 C","281 C","282 C","283 C","284 C","285 C","286 C","287 C","288 C","289 C","7681 C","7682 C","7683 C","7684 C","7685 C","7686 C","7687 C","545 C","544 C","543 C","542 C","541 C","540 C","539 C","290 C","291 C","292 C","293 C","294 C","295 C","296 C","2905 C","2915 C","2925 C","2935 C","2945 C","2955 C","2965 C","297 C","298 C","299 C","300 C","301 C","302 C","303 C","7688 C","7689 C","7690 C","7691 C","7692 C","7693 C","7694 C","2975 C","2985 C","2995 C","3005 C","3015 C","3025 C","3035 C","7695 C","7696 C","7697 C","7698 C","7699 C","7700 C","7701 C","7457 C","7458 C","7459 C","7460 C","7461 C","7462 C","7463 C","304 C","305 C","306 C","307 C","308 C","309 C","635 C","636 C","637 C","638 C","639 C","640 C","641 C","7702 C","7703 C","7704 C","7705 C","7706 C","7707 C","7708 C","628 C","629 C","630 C","631 C","632 C","633 C","634 C","310 C","311 C","312 C","313 C","314 C","315 C","316 C","3105 C","3115 C","3125 C","3135 C","3145 C","3155 C","3165 C","7709 C","7710 C","7711 C","7712 C","7713 C","7714 C","7715 C","317 C","318 C","319 C","320 C","321 C","322 C","323 C","7464 C","7465 C","7466 C","7467 C","7468 C","7469 C","7470 C","7471 C","7472 C","7473 C","7474 C","7475 C","7476 C","7477 C","5523 C","5513 C","5503 C","5493 C","5483 C","5473 C","5463 C","7716 C","7717 C","7718 C","7719 C","7720 C","7721 C","7722 C","324 C","325 C","326 C","327 C","328 C","329 C","330 C","3242 C","3252 C","3262 C","3272 C","3282 C","3292 C","3302 C","3245 C","3255 C","3265 C","3275 C","3285 C","3295 C","3305 C","3248 C","3258 C","3268 C","3278 C","3288 C","3298 C","3308 C","566 C","565 C","564 C","563 C","562 C","561 C","560 C","573 C","572 C","571 C","570 C","569 C","568 C","567 C","559 C","558 C","557 C","556 C","555 C","554 C","553 C","5595 C","5585 C","5575 C","5565 C","5555 C","5545 C","5535 C","5665 C","5655 C","5645 C","5635 C","5625 C","5615 C","5605 C","5527 C","5517 C","5507 C","5497 C","5487 C","5477 C","5467 C","621 C","622 C","623 C","624 C","625 C","626 C","627 C","331 C","332 C","333 C","334 C","335 C","336 C","337 C","338 C","339 C","340 C","341 C","342 C","343 C","7723 C","7724 C","7725 C","7726 C","7727 C","7728 C","7729 C","3375 C","3385 C","3395 C","3405 C","3415 C","3425 C","3435 C","344 C","345 C","346 C","347 C","348 C","349 C","350 C","351 C","352 C","353 C","354 C","355 C","356 C","357 C","7478 C","7479 C","7480 C","7481 C","7482 C","7483 C","7484 C","7730 C","7731 C","7732 C","7733 C","7734 C","7735 C","7736 C","7737 C","7738 C","7739 C","7740 C","7741 C","7742 C","7743 C","358 C","359 C","360 C","361 C","362 C","363 C","364 C","7485 C","7486 C","7487 C","7488 C","7489 C","7490 C","7491 C","365 C","366 C","367 C","368 C","369 C","370 C","371 C","372 C","373 C","374 C","375 C","376 C","377 C","378 C","580 C","579 C","578 C","577 C","576 C","575 C","574 C","5807 C","5797 C","5787 C","5777 C","5767 C","5757 C","5747 C","5875 C","5865 C","5855 C","5845 C","5835 C","5825 C","5815 C","5803 C","5793 C","5783 C","5773 C","5763 C","5753 C","5743 C","7492 C","7493 C","7494 C","7495 C","7496 C","7497 C","7498 C","7744 C","7745 C","7746 C","7747 C","7748 C","7749 C","7750 C","379 C","380 C","381 C","382 C","383 C","384 C","385 C","386 C","387 C","388 C","389 C","390 C","391 C","392 C","587 C","586 C","585 C","584 C","583 C","582 C","581 C","393 C","394 C","395 C","396 C","397 C","398 C","399 C","3935 C","3945 C","3955 C","3965 C","3975 C","3985 C","3995 C","600 C","601 C","602 C","603 C","604 C","605 C","606 C","607 C","608 C","609 C","610 C","611 C","612 C","613 C","461 C","460 C","459 C","458 C","457 C","456 C","455 C","614 C","615 C","616 C","617 C","618 C","619 C","620 C","7751 C","7752 C","7753 C","7754 C","7755 C","7756 C","7757 C","7758 C","7759 C","7760 C","7761 C","7762 C","7763 C","7764 C","7765 C","7766 C","7767 C","7768 C","7769 C","7770 C","7771 C","4545 C","4535 C","4525 C","4515 C","4505 C","4495 C","4485 C","454 C","453 C","452 C","451 C","450 C","449 C","448 C","7499 C","7500 C","7501 C","7502 C","7503 C","7504 C","7505 C","468 C","467 C","466 C","465 C","464 C","463 C","462 C","7506 C","7507 C","7508 C","7509 C","7510 C","7511 C","7512 C","719 C","720 C","721 C","722 C","723 C","724 C","725 C","475 C","474 C","473 C","472 C","471 C","470 C","469 C","726 C","727 C","728 C","729 C","730 C","731 C","732 C","4685 C","4675 C","4665 C","4655 C","4645 C","4635 C","4625 C","7513 C","7514 C","7515 C","7516 C","7517 C","7518 C","7519 C","4755 C","4745 C","4735 C","4725 C","4715 C","4705 C","4695 C","482 C","481 C","480 C","479 C","478 C","477 C","476 C","7527 C","7528 C","7529 C","7530 C","7531 C","7532 C","7533 C","7534 C","7535 C","7536 C","7537 C","7538 C","7539 C","7540 C","427 C","428 C","429 C","430 C","431 C","432 C","433 C","420 C","421 C","422 C","423 C","424 C","425 C","426 C","441 C","442 C","443 C","444 C","445 C","446 C","447 C","413 C","414 C","415 C","416 C","417 C","418 C","419 C","400 C","401 C","402 C","403 C","404 C","405 C","406 C","407 C","408 C","409 C","410 C","411 C","412 C","434 C","435 C","436 C","437 C","438 C","439 C","440 C","Warm Gray 1 C","Warm Gray 2 C","Warm Gray 3 C","Warm Gray 4 C","Warm Gray 5 C","Warm Gray 6 C","Warm Gray 7 C","Warm Gray 8 C","Warm Gray 9 C","Warm Gray 10 C","Warm Gray 11 C","Cool Gray 1 C","Cool Gray 2 C","Cool Gray 3 C","Cool Gray 4 C","Cool Gray 5 C","Cool Gray 6 C","Cool Gray 7 C","Cool Gray 8 C","Cool Gray 9 C","Cool Gray 10 C","Cool Gray 11 C","Black 2 C","Black 3 C","Black 4 C","Black 5 C","Black 6 C","Black 7 C"],Ot=["FEDD00","FFD700","FE5000","F9423A","EF3340","CE0058","E10098","BB29BB","440099","10069F","001489","0085CA","00AB84","2D2926","F2F0A1","FCAEBB","F1B2DC","BF9BDE","74D1EA","9DE7D7","9E978E","009ACE","44D62C","FFE900","FFAA4D","FF7276","FF3EB5","EA27C2","84754E","85714D","866D4B","8B6F4E","87674F","8B634B","8A8D8F","FFD900","FF5E00","F93822","CE0056","D62598","4E008E","00239C","0084CA","00B08B","222223","F6EB61","F7EA48","FCE300","C5A900","AF9800","897A27","F5E1A4","ECD898","EED484","F4DA40","F2CD00","F1C400","CBA052","F9E547","FBE122","FEDB00","FFD100","DAAA00","AA8A00","9C8412","FAE053","FBDD40","FDDA24","FFCD00","C99700","AC8400","897322","F3DD6D","F3D54E","F3D03E","F2A900","CC8A00","A07400","6C571B","F8E08E","FBD872","FFC845","FFB81C","C69214","AD841F","886B25","FBDB65","FDD757","FED141","FFC72C","EAAA00","B58500","9A7611","FFC600","FFB500","D19000","B47E00","73531D","5A4522","4B3D2A","D29F13","B78B20","9F7D23","967126","8F6A2A","7D622E","6C5D34","FDD26E","FFC658","FFBF3F","FFA300","DE7C00","AF6D04","74531C","FDD086","FFC56E","FFB549","FF9E1B","D57800","996017","6E4C1E","F2C75C","F1BE48","F1B434","ED8B00","CF7F00","A76D11","715C2A","F6BE00","F0B323","FEAD77","E6A65D","D38235","DC8633","C16C18","BD9B60","D69A2D","DB8A06","CD7925","AD6433","89532F","775135","D78825","D3832B","C67D30","B67233","A7662B","9E6A38","835D32","FCC89B","FDBE87","FDAA63","F68D2E","EA7600","D45D00","BE4D00","FECB8B","FFC27B","FFB25B","FF8200","E57200","BE6A14","9B5A1A","EFD19F","EFBE7D","ECA154","E87722","CB6015","A1561C","603D20","FFAE62","FF8F1C","FF6900","B94700","94450B","653819","FFB990","FFA06A","FF7F32","FF6A13","D86018","A65523","8B4720","FFBE9F","FF9D6E","FF7F41","FF671F","E35205","BE531C","73381D","DB864E","E07E3C","DC6B2F","DC582A","C05131","864A33","674736","FFA38B","FF8D6D","FF6A39","FC4C02","DC4405","A9431E","833921","FFB3AB","FF8674","FF5C39","FA4616","CF4520","963821","6B3529","C4622D","BA5826","AF5C37","9E5330","924C2E","7B4D35","5C4738","D4B59E","C07D59","B15533","9D432C","7C3A2D","6B3D2E","5C3D31","D14124","BD472A","B33D26","8D3F2B","83412C","7B4931","674230","E4D5D3","E1BBB4","D6938A","C26E60","A4493D","823B34","683431","DDBCB0","CA9A8E","BC8A7E","A37F74","866761","6B4C4C","583D3E","EABEB0","C09C83","B46A55","AB5C57","A45248","9A6A4F","8A391B","ECC3B2","ECBAA8","EAA794","E8927C","DA291C","9A3324","653024","FFB1BB","FF808B","FF585D","E03C31","BE3A34","81312F","FFA3B5","FF8DA1","F8485E","EE2737","D22630","AF272F","7C2529","FCAFC0","FB637E","F4364C","CB333B","A4343A","643335","C66E4E","C04C36","B7312C","AB2328","93272C","8A2A2B","802F2D","E1523D","C63527","A72B2A","9E2A2B","6D3332","633231","572D2D","E6BAA8","E56A54","E04E39","CD545B","B04A5A","9B2242","651D32","FABBCB","FC9BB3","F65275","E4002B","C8102E","A6192E","76232F","ECC7CD","E89CAE","DF4661","D50032","BA0C2F","9D2235","862633","F8A3BC","F67599","EF426F","E40046","BF0D3E","9B2743","782F40","F5B6CD","F59BBB","EF4A81","E0004D","C5003E","A6093D","8A1538","F5DADF","F7CED7","F9B5C4","F890A5","EF6079","E03E52","CB2C30","F2D4D7","F4C3CC","F2ACB9","E68699","D25B73","B83A4B","9E2A2F","ECB3CB","E782A9","E0457B","CE0037","A50034","861F41","6F263D","F99FC9","F57EB6","F04E98","E31C79","CE0F69","AC145A","7D2248","F4CDD4","E06287","E24585","B52555","A4123F","971B2F","6A2C3E","D6C9CA","C4A4A7","C16784","C63663","BC204B","912F46","7E2D40","EABEDB","E56DB1","DA1884","A50050","910048","6C1D45","936D73","934054","8E2C48","732E4A","672E45","582D40","502B3A","EF95CF","EB6FBD","DF1995","D0006F","AA0061","890C58","672146","F4A6D7","F277C6","E93CAC","C6007E","A20067","840B55","EAD3E2","E6BCD8","DFA0C9","D986BA","C6579A","AE2573","960051","E5CEDB","E3C8D8","DEBED2","C996B6","B06C96","994878","7C2855","E4C6D4","DCB6C9","D0A1BA","BE84A3","A76389","893B67","612141","EBBECB","E8B3C3","E4A9BB","D592AA","84344E","6F2C3F","572932","E2BCCB","DCA9BF","C9809E","B55C80","A73A64","9B3259","872651","E9CDD0","E4BEC3","D7A3AB","C48490","B46B7A","984856","893C47","F2C6CF","F1BDC8","E9A2B2","DC8699","8F3237","7F3035","5D2A2C","E9C4C7","E5BAC1","DAA5AD","C6858F","7A3E3A","6A3735","512F2E","DFC2C3","DBB7BB","CCA1A6","B07C83","9C6169","874B52","3F2021","F1A7DC","EC86D0","E45DBF","DB3EB1","C5299B","AF1685","80225F","EFBAE1","E277CD","D539B5","C800A1","B0008E","9E007E","830065","EAB8E4","E59BDC","DD7FD3","C724B1","BB16A3","A51890","80276C","A56E87","A83D72","991E66","8A1B61","722257","6A2A5B","5E2751","E7BAE4","DD9CDF","C964CF","AD1AAC","981D97","72246C","EBC6DF","E6BEDD","E2ACD7","D48BC8","93328E","833177","612C51","EEDAEA","CCAED0","D59ED7","B288B9","A277A6","9F5CC0","963CBD","D7A9E3","C98BDB","AC4FC6","9B26B6","87189D","772583","653165","948794","A2789C","A15A95","8E3A80","6E2B62","6A3460","5D3754","D5C2D8","C9B1D0","BA9CC5","A57FB2","642F6C","59315F","4B3048","DBCDD3","D0BEC7","C6B0BC","AF95A6","86647A","66435A","4A3041","D8C8D1","D3C0CD","BFA5B8","9B7793","7E5475","693C5E","512A44","DFC8E7","D7B9E4","CAA2DD","B580D1","8031A7","702F8A","572C5F","D6BFDD","C6A1CF","8C4799","6D2077","642667","5D285F","51284F","CBA3D8","B884CB","A05EB5","84329B","702082","671E75","5F2167","9991A4","8D6E97","7A4183","6B3077","653279","5E366E","5C4E63","C1A0DA","A77BCA","8246AF","5C068C","500778","470A68","3C1053","D7C6E6","C1A7E2","9063CD","753BBD","5F259F","582C83","512D6D","C5B4E3","AD96DC","9678D3","7D55C7","330072","2E1A47","B4B5DF","9595D2","7474C1","24135F","211551","201747","221C35","A7A4E0","8B84D7","685BC7","2E008B","280071","250E62","201547","6E7CA0","686E9F","615E9B","565294","514689","4C4184","535486","DDDAE8","B6B8DC","A7A2C3","8986CA","5D4777","4B384C","41273B","878CB4","7C7FAB","7566A0","6F5091","68478D","563D82","523178","E5E1E6","E0DBE3","C6BCD0","A192B2","7C6992","614B79","3F2A56","D8D7DF","C6C4D2","B3B0C4","8D89A5","595478","403A60","1E1A34","C5CFDA","BBC7D6","A2B2C8","8E9FBC","1B365D","1F2A44","1C1F2A","D9E1E2","A4BCC2","98A4AE","768692","425563","253746","131E29","B9D3DC","A3C7D2","8DB9CA","6BA4B8","003D4C","00313C","072B31","BFCED6","B7C9D3","A6BBC8","7A99AC","5B7F95","4F758B","081F2C","D1DDE6","C6D6E3","9BB8D3","7DA1C4","5E8AB4","236192","002E5D","DBE2E9","CED9E5","A7BCD6","7D9BC1","326295","003A70","002554","DDE5ED","C8D8EB","B1C9E8","7BA4DB","407EC9","003594","001A70","BDC5DB","89ABE3","8094DD","7BA6DE","5F8FB4","3A5DAE","606EB2","CBD3EB","9FAEE5","485CC7","1E22AA","171C8F","151F6D","141B4D","B8CCEA","5C88DA","0047BB","06038D","001871","001E62","071D49","C3D7EE","A7C6ED","307FE2","001A72","001E60","13294B","ABCAE9","8BB8E8","418FDE","012169","00205B","041E42","92C1E9","6CACE4","0072CE","0033A0","003087","002D72","0C2340","94A9CB","6787B7","426DA9","385E9D","2C5697","1D4F91","1D428A","C6DAE7","BDD6E6","A4C8E1","7BAFD4","003C71","003057","00263A","B9D9EB","9BCBEB","69B3E7","003DA5","002F6C","002855","041C2C","8DC8E8","62B5E5","009CDE","0057B8","004C97","003865","00263E","71C5E8","41B6E6","00A3E0","005EB8","004B87","003B5C","002A3A","4698CB","298FC2","0076A8","006298","005587","004976","01426A","99D6EA","5BC2E7","00A9E0","0077C8","00629B","004F71","003E51","7BA7BC","6399AE","4E87A0","41748D","34657F","165C7D","005776","BBDDE6","71B2C9","4298B5","0086BF","007DBA","00558C","002B49","9ADBE8","59CBE8","00B5E2","006BA6","00587C","003B49","A4DBE8","8BD3E6","4EC3E0","00AFD7","0095C8","0082BA","0067A0","48A9C5","009CBD","0085AD","007096","006A8E","00617F","005670","B8DDE1","9BD3DD","77C5D5","3EB1C8","0093B2","007396","005F83","6AD1E3","05C3DE","00A9CE","0092BC","007FA3","00677F","004851","68D2DF","00C1D5","00AEC7","008EAA","00778B","006272","004F59","63B1BC","00A7B5","0097A9","00859B","007D8A","007680","006269","B1E4E3","88DBDF","2DCCD3","009CA6","008C95","007377","005F61","A0D1CA","40C1AC","00B0B9","00A3AD","007398","005F86","005A70","7EDDD3","5CB8B2","279989","007681","487A7B","0D5257","244C5A","B6CFD0","ABC7CA","94B7BB","7FA9AE","4F868E","115E67","07272D","00968F","00857D","007672","006D68","00635B","005E5D","005151","9CDBD9","64CCC9","00B2A9","008675","007367","00685E","00534C","71DBD4","2AD2C9","00BFB3","00A499","008578","00594F","004C45","7CE0D3","2CD5C4","00C7B1","00B398","009681","007864","004E42","6DCDB8","49C5B1","00AB8E","009B77","008264","006A52","034638","B9DCD2","A1D6CA","86C8BC","6BBBAE","006F62","00594C","1D3C34","B5E3D8","A5DFD3","98DBCE","6BCABA","00816D","006C5B","173F35","ADCAB8","9ABEAA","85B09A","6FA287","28724F","205C40","284734","BFCEC2","A7BDB1","92ACA0","7F9C90","5C7F71","43695B","183028","BAC5B9","B0BDB0","A3B2A4","94A596","708573","5E7461","22372B","BCC9C5","B1C0BC","9DB0AC","829995","5D7975","3E5D58","18332F","D1E0D7","B7CDC2","9AB9AD","789F90","507F70","285C4D","13322B","A7E6D7","8CE2D0","3CDBC0","009775","007B5F","00664F","8FD6BD","6ECEB2","00B388","00965E","007A53","006747","115740","50A684","00966C","008755","007B4B","006F44","006845","005844","7AE1BF","47D7AC","00C389","00AF66","007749","006341","154734","A0DAB3","91D6AC","71CC98","009A44","00843D","046A38","2C5234","A2E4B8","8FE2B0","80E0A7","00B140","009639","007A33","215732","9BE3BF","26D07C","00BF6F","00B74F","009F4D","275D38","00573F","4B9560","228848","007A3E","007041","286140","36573B","395542","6BA539","48A23F","319B42","3A913F","44883E","4A773C","44693D","ADDC91","A1D884","6CC24A","43B02A","509E2F","4C8C2B","4A7729","D0DEBB","BCE194","8EDD65","78D64B","74AA50","719949","79863C","C2E189","B7DD79","A4D65E","78BE20","64A70B","658D1B","546223","D4EB8E","CDEA80","C5E86C","97D700","84BD00","7A9A01","59621D","C4D6A4","BCD19B","B7CE95","A9C47F","789D4A","67823A","4E5B31","D0D1AB","C6C89B","BABD8B","A2A569","8A8D4A","6D712E","3D441E","D2CE9E","CBC793","C0BB87","AFA96E","A09958","89813D","555025","C3C6A8","B3B995","A3AA83","899064","737B4C","5E6738","3E4827","BFCC80","BBC592","9CAF88","8F993E","76881D","7A7256","5B6236","BABC16","ABAD23","999B30","888D30","7C8034","727337","656635","E2E868","DBE442","CEDC00","C4D600","A8AD00","949300","787121","E9EC6B","E3E935","E0E721","D0DF00","B5BD00","9A9500","827A04","E3E48D","E0E27C","DBDE70","D2D755","B7BF10","8E8C13","625D20","F0EC74","EDE939","ECE81A","E1E000","BFB800","ADA400","A09200","F3EA5D","F3E500","EFDF00","EEDC00","BBA600","9A8700","685C20","F1EB9C","F0E991","F0E87B","EDE04B","EADA24","E1CD00","CFB500","EBE49A","E9E186","E6DE77","E1D555","D7C826","C4B000","B39B00","E9DF97","E4D77E","DECD63","D9C756","B89D18","A28E2A","695B24","DCD59A","D6CF8D","D0C883","C0B561","AC9F3C","9F912A","8A7B19","CAB64B","CFB023","C1A01E","A08629","897630","736635","675E33","D4C304","C4B200","91852C","747136","5D6439","585C3B","535435","BBB323","B4A91F","AA9D2E","8F7E35","716135","635939","4E4934","D5CB9F","CFC493","C5B783","B3A369","998542","8C7732","614F25","CAC7A7","BFBB98","B0AA7E","9B945F","594A25","524727","4A412A","F1E6B2","DFD1A7","D9C89E","CEB888","A89968","94795D","816040","DDCBA4","D3BC8D","C6AA76","B9975B","8B5B29","744F28","5C462B","EFDBB2","FCD299","E1B87F","D6A461","C6893F","B77729","A6631B","EDC8A3","E7B78A","DDA46F","C88242","B36924","934D11","7D3F16","F3CFB3","F1C6A7","F0BF9B","E59E6D","B86125","A45A2A","693F23","E0C09F","D9B48F","CDA077","B58150","9E652E","774212","623412","E0C6AD","DCBFA6","CDA788","BF9474","AD7C59","946037","4F2C1D","E1B7A7","D5A286","C58B68","99552B","85431E","6D4F47","5E4B3C","D7C4B7","CDB5A7","C0A392","AE8A79","956C58","7C4D3A","5B3427","DBC8B6","D3BBA8","C6A992","AA8066","703F2A","623B2A","4E3629","D6D2C4","C5B9AC","B7A99A","A39382","7A6855","63513D","473729","D1CCBD","B7B09C","A69F88","A7ACA2","949A90","8E9089","4B4F54","D0D3D4","C1C6C8","A2AAAD","7C878E","5B6770","333F48","1D252D","C7C9C7","B2B4B2","9EA2A2","898D8D","707372","54585A","25282A","BEC6C4","A2ACAB","919D9D","717C7D","505759","3F4444","373A36","BABBB1","A8A99E","919388","7E7F74","65665C","51534A","212322","C4BFB6","AFA9A0","9D968D","8C857B","776E64","696158","C4BCB7","B2A8A2","978C87","857874","746661","5E514D","382F2D","D0C4C5","C1B2B6","AB989D","7B6469","584446","453536","382E2C","D7D2CB","CBC4BC","BFB8AF","B6ADA5","ACA39A","A59C94","968C83","8C8279","83786F","796E65","6E6259","D9D9D6","D0D0CE","C8C9C7","BBBCBC","B1B3B3","A7A8AA","97999B","888B8D","75787B","63666A","53565A","332F21","212721","31261D","3E2B2E","101820","3D3935"],aa=Ot.map(i=>[parseInt(i.substring(0,2),16),parseInt(i.substring(2,4),16),parseInt(i.substring(4,6),16)]);function ts(i){const t=ne.indexOf(i);return t>=0?Ot[t]:""}function jn(i){const t=Ot.indexOf(i);return t>=0?ne[t]:""}function es(i,t=64){const e=[],a=[],n=jn(i);n&&e.push({pms:n,hex:i,distance:0});const r=parseInt(i.substring(0,2),16),s=parseInt(i.substring(2,4),16),o=parseInt(i.substring(4,6),16);let l,c,d;for(let u=0;u<Ot.length;u++){l=aa[u][0],c=aa[u][1],d=aa[u][2];const A=Math.sqrt(Math.pow(r-l,2)+Math.pow(s-c,2)+Math.pow(o-d,2));a.push(A)}for(let u=0;u<a.length;u++)a[u]<=t&&!e.some(A=>A.pms===ne[u])&&e.push({pms:ne[u],hex:Ot[u],distance:a[u]});return e.sort((u,A)=>u.distance-A.distance)}const as=ne.map((i,t)=>({pms:i,hex:Ot[t]})),ns=new yr(as,{keys:["pms"]});function is(i,t){return ns.search(i,t?{limit:t}:void 0)}let Ut=null;function Wn(i){if(i.startsWith("#"))return un(i);if(!document)throw new Error("browserColorToHex is only supported on browsers");if(Ut||(Ut=document.createElement("canvas").getContext("2d")),!Ut)throw new Error("Failed to create canvas context required to convert colors");Ut.fillStyle=i;const t=un(Ut.fillStyle);return t||console.error(`Unknown browser color ${i}`),t}function un(i){const t=i.substring(1).toUpperCase();return t.length===6?t:t.length===3?`${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:""}const ye=i=>{const t=Hn(i.spotColor);return t?`${i.browserValue} ${t}`:i.browserValue},Hn=i=>{if(!i)return"";if(i.profileName.includes("/")&&i.profileName.includes(".icc")){const t=i.profileName.replace(/\s/g,"-"),e=t.lastIndexOf("/");return`icc-named-color(${t.slice(e+1).slice(0,-4)}, ${i.namedColor})`}return`icc-named-color(${i.profileName}, ${i.namedColor})`},Sa=i=>{const t=i.split(/[ ](?=[^)]*?(?:\(|$))/);if(t.length===0)return{browserValue:"#000000"};if(t.length===1)return{browserValue:t[0]};const e=t[1].match(/\(([^)]+)\)/gm);if(!e)throw new Error("Unhandled state of color value in SVG");const a=e[0].replace(/[() ]/g,"").split(",");return{browserValue:t[0],spotColor:{profileName:a[0],namedColor:a[1]}}},rs=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],ss=["fill","stroke"],Rt=(i,t)=>{t(i),i.children.length>0&&Array.from(i.children).forEach(e=>Rt(e,t))},Yn=(i,t)=>{const e=t(i);if(e)return e;const a=i.parentElement;if(a)return Yn(a,t)},os=(i,t)=>{try{return i.matches(t)}catch{return i.classList.contains(t.substring(1))}},ze=(i,t=!1)=>{!t&&i.setAttribute("preserveAspectRatio","none");const e=[];Rt(i,a=>{if(a.tagName==="script"){a.remove();return}if(a.tagName==="style"){try{Pn.parse(a.innerHTML).stylesheet?.rules.forEach(s=>{e.push(s)}),a.remove()}catch(r){console.error(r)}return}const n=a.attributes.getNamedItem("style")?.value?.trim();if(n){const r=[];n.split(";").forEach(o=>{const l=o.trim();if(l){const[c,d]=l.split(":"),u=c.toLowerCase();ss.indexOf(u)>-1?a.setAttribute(u,d.trim()):r.push(l)}}),r.length>0?a.setAttribute("style",r.join(";")):a.removeAttribute("style")}}),Rt(i,a=>{e.forEach(n=>{n.selectors?.forEach(r=>{os(a,r)&&n.declarations?.forEach(s=>{s.property&&s.value&&a.setAttribute(s.property,s.value)})})})})},ls=i=>{const t=/pt|pc|mm|cm|in/gm,e=i.getAttribute("viewBox"),a=i.getAttribute("width"),n=i.getAttribute("height");if(!e)throw new Error("viewBox not specified on SVG!");a&&i.setAttribute("width",a.replace(t,"")),n&&i.setAttribute("height",n.replace(t,""))},Jn=i=>ot().parseFromString(i,"image/svg+xml").firstElementChild,cs=(i,t,e)=>{i.setAttribute("height",`${e}px`),i.setAttribute("width",`${t}px`)},Kn=(i,t,e)=>{Rt(i,a=>{const n=a.attributes.getNamedItem("fill");n&&n.value!=="none"&&a.classList.forEach(s=>{if(s.startsWith("spiff-fill")){const o=t[s.replace("spiff-fill-","")];if(o)a.setAttribute("fill",e?ye(o):o.browserValue);else{const l=t[s];l&&a.setAttribute("fill",e?ye(l):l.browserValue)}}});const r=a.attributes.getNamedItem("stroke");r&&r.value!=="none"&&a.classList.forEach(s=>{if(s.startsWith("spiff-stroke")){const o=t[s.replace("spiff-stroke-","")];if(o)a.setAttribute("stroke",e?ye(o):o.browserValue);else{const l=t[s];l&&a.setAttribute("fill",e?ye(l):l.browserValue)}}})})},Xn=i=>Et().serializeToString(i),$a=(i,t,e,a,n)=>{const r=Jn(i);if(!r)throw new Error("Failed to read SVG.");return cs(r,t,e),Kn(r,a,n),Xn(r)},qe=(i,t,e)=>{const a=Jn(i);if(!a)throw new Error("Failed to read SVG.");return Kn(a,t,e),Xn(a)},ds=i=>{const t=/<svg.*<\/svg>/s,e=i.match(t)||[],a=e?.length>0?e[0]:"";return ot().parseFromString(a,"image/svg+xml")},it=async i=>{const e=ds(i).firstElementChild;if(!e)throw new Error("Failed to read SVG.");ze(e);const a={};Rt(e,s=>{if(rs.includes(s.tagName)&&!s.attributes.getNamedItem("fill")){let c="black";const d=s.parentElement;if(d){const u=Yn(d,A=>{const g=A.style.fill;if(g)return g;const p=A.getAttribute("fill");if(p)return p});u&&(c=u)}s.setAttribute("fill",c)}const o=s.attributes.getNamedItem("fill");if(o&&o.value!=="none"&&!o.value.startsWith("url(")){const c=Sa(o.value),d=c.browserValue.replace(/\W/g,""),u=`spiff-fill-${d}`;s.setAttribute("fill",c.browserValue),s.classList.add(u),a[d]=c}const l=s.attributes.getNamedItem("stroke");if(l&&l.value!=="none"&&!l.value.startsWith("url(")){const c=Sa(l.value),d=c.browserValue.replace(/\W/g,""),u=`spiff-stroke-${d}`;s.classList.add(u),s.setAttribute("stroke",c.browserValue),a[d]=c}});const r=Et().serializeToString(e);return{colors:a,svg:r}},us=f.gql`
2
2
  fragment AssetMetadataFields on Asset {
3
3
  metadata {
4
4
  key
5
5
  value
6
6
  }
7
7
  }
8
- `,Bo=f.gql`
8
+ `,As=f.gql`
9
9
  fragment AssetVersionsFields on Asset {
10
10
  versions {
11
11
  name
12
12
  link
13
13
  }
14
14
  }
15
- `,Ae=(i,t)=>f.gql`
16
- ${i&&Io||""}
17
- ${t&&Bo||""}
15
+ `,de=(i,t)=>f.gql`
16
+ ${i&&us||""}
17
+ ${t&&As||""}
18
18
  fragment AssetFields on Asset {
19
19
  name
20
20
  key
@@ -54,7 +54,7 @@
54
54
  ${i&&"...AssetMetadataFields"||""}
55
55
 
56
56
  }
57
- `,ui=f.gql`
57
+ `,Zn=f.gql`
58
58
  fragment MaterialFields on Material {
59
59
  id
60
60
  name
@@ -101,14 +101,14 @@
101
101
  fileLink
102
102
  }
103
103
  }
104
- `,Po=f.gql`
105
- ${ui}
104
+ `,hs=f.gql`
105
+ ${Zn}
106
106
  query GetMaterials($ids: [String]) {
107
107
  materials(id: $ids) {
108
108
  ...MaterialFields
109
109
  }
110
110
  }
111
- `,xo=f.gql`
111
+ `,gs=f.gql`
112
112
  mutation CreateAsset($name: String!, $type: String!, $mimeType: String!, $anonymous: Boolean, $temporary: Boolean) {
113
113
  assetCreate(name: $name, type: $type, mimeType: $mimeType, anonymous: $anonymous, temporary: $temporary) {
114
114
  uploadUrl
@@ -122,35 +122,35 @@
122
122
  }
123
123
  }
124
124
  }
125
- `,Fo=f.gql`
126
- ${Ae(!1,!1)}
125
+ `,ms=f.gql`
126
+ ${de(!1,!1)}
127
127
  mutation RemoveBackgroundFromAsset($key: String!) {
128
128
  assetRemoveBackground(key: $key) {
129
129
  ...AssetFields
130
130
  }
131
131
  }
132
- `,Do=f.gql`
133
- ${Ae(!1,!1)}
132
+ `,ps=f.gql`
133
+ ${de(!1,!1)}
134
134
  mutation VectorizeAsset($key: String!, $options: AssetVectorizeOptions) {
135
135
  assetVectorize(key: $key, options: $options) {
136
136
  ...AssetFields
137
137
  }
138
138
  }
139
- `,De=async(i,t=!0)=>(await y.getShadowGraphqlClient().query({query:f.gql`
140
- ${Ae(!1,t)}
139
+ `,Pe=async(i,t=!0)=>(await y.getShadowGraphqlClient().query({query:f.gql`
140
+ ${de(!1,t)}
141
141
  query GetAssets($keys: [String]!) {
142
142
  assets(keys: $keys) {
143
143
  ...AssetFields
144
144
  }
145
145
  }
146
- `,errorPolicy:"all",fetchPolicy:"no-cache",variables:{keys:i}})).data.assets,ko=async i=>(await y.getShadowGraphqlClient().query({query:Po,errorPolicy:"all",variables:{ids:i}})).data.materials,Mo=async(i,t,e,a,n)=>(await y.getShadowGraphqlClient().mutate({mutation:xo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:i,type:t,mimeType:e,anonymous:a,temporary:n}})).data?.assetCreate;class To{constructor(){this.cache=new Map,this.bgrmProcessCache=new Map,this.materialCache=new Map,this.loadImageAsFileInfo=async t=>{const e=await t.arrayBuffer(),a=await ue(e),n=(r,o)=>{const s=atob(r.split(",")[1]),l=[];for(let c=0;c<s.length;c++)l.push(s.charCodeAt(c));return new Blob([new Uint8Array(l)],{type:o})};return{name:t.name.substring(t.name.lastIndexOf("/")+1),blob:n(a.dataUrl,t.type)}}}async getLocalOrFromServer(t){if(this.cache.has(t)){const n=this.cache.get(t);if(!n)throw new O("Failed to get asset from cache!");return n}const a=(async()=>(await De([t]))[0])();return this.cache.set(t,a),a}async getFromServer(t){const a=(async()=>(await De([t]))[0])();return this.cache.set(t,a),a}keyFromURL(t){let e;try{e=new URL(t).pathname}catch{e=void 0}return e!==void 0&&e.startsWith("/")&&(e=e.replace("/","")),e?.split("?")[0]}cacheAsset(t){if(!t.key)throw new O("Asset has no key!");this.cache.has(t.key)||this.cache.set(t.key,Promise.resolve(t))}cacheMaterial(t){if(!t.id)throw new O("Material has no id!");this.materialCache.has(t.id)||this.materialCache.set(t.id,Promise.resolve(t))}async getMaterialLocalOrFromServer(t){if(this.materialCache.has(t))return this.materialCache.get(t);const a=(async()=>(await ko([t]))[0])();return this.materialCache.set(t,a),a}async uploadAssetWithProgress(t,e,a,n,r){const o=await this.dispatchCreateAssetRequest(t,e,n,r);if(!o)throw new Error("Failed to create asset.");return await new Promise((s,l)=>{const c=new XMLHttpRequest;c.open("PUT",o.assetResponse.uploadUrl,!0),c.setRequestHeader("Content-Type",o.mimeType),c.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),c.upload.onprogress=d=>{d.lengthComputable&&a(d.loaded*100/d.total)},c.onload=()=>{const d=o.assetResponse.asset;ut.add(o.assetResponse.asset),s(d)},c.onerror=l,this.postProcessFileUpload(t,o.mimeType).then(d=>c.send(d.blob)).catch(l)}),this.cacheAsset(o.assetResponse.asset),o.assetResponse.asset}async uploadAsset(t,e,a,n){return this.uploadAssetWithProgress(t,e,()=>{},a,n)}async uploadFile(t,e){const n=this.isRaster(t)?ne.Image:ne.Illustration,r=await this.loadImageAsFileInfo(t);return await this.uploadAssetWithProgress(r,n,e,!0)}async removeBackgroundFromAsset(t){const e=t.key;if(this.bgrmProcessCache.has(e))return this.bgrmProcessCache.get(e);if(q.has(qt,e)){const r=this.getLocalOrFromServer(q.get(qt,e));return this.bgrmProcessCache.set(e,r),r}const n=(async()=>{const r=await y.getShadowGraphqlClient().mutate({mutation:Fo,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:e}});if(this.bgrmProcessCache.delete(e),!r.data?.assetRemoveBackground?.key)throw new Error("Failed to remove background from image");return ut.add(r.data.assetRemoveBackground),q.add(qt,e,r.data.assetRemoveBackground.key),this.cache.set(r.data.assetRemoveBackground.key,Promise.resolve(r.data.assetRemoveBackground)),r.data.assetRemoveBackground})();return this.bgrmProcessCache.set(e,n),n}async vectorizeAsset(t,e=void 0){const a=t.key;if(this.bgrmProcessCache.has(a))return this.bgrmProcessCache.get(a);if(q.has(Gt,a)){const o=this.getLocalOrFromServer(q.get(Gt,a));return this.bgrmProcessCache.set(a,o),o}const r=(async()=>{const o=await y.getShadowGraphqlClient().mutate({mutation:Do,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:a,options:{maxColorCount:e}}});if(this.bgrmProcessCache.delete(a),!o.data?.assetVectorize?.key)throw new Error("Failed to vectorize image");return ut.add(o.data.assetVectorize),q.add(Gt,a,o.data.assetVectorize.key),this.cache.set(o.data.assetVectorize.key,Promise.resolve(o.data.assetVectorize)),o.data.assetVectorize})();return this.bgrmProcessCache.set(a,r),r}removePersistedAsset(t){ut.remove(t),q.delete(qt,t),q.delete(Gt,t),q.deleteForTransformedKey(qt,t),q.deleteForTransformedKey(Gt,t)}getPersistedAssets(){return ut.list()}registerPersistedAssetListener(t){ut.addCallback(t)}unRegisterPersistedAssetListener(t){ut.removeCallback(t)}isRaster(t){return!(t.type==="image/svg+xml"||t.type==="application/pdf"||t.type==="application/postscript")}async postProcessFileUpload(t,e){if(e==="image/svg+xml"){const a=await t.blob.text(),o=new window.DOMParser().parseFromString(a,"image/svg+xml").documentElement;if(!o)throw new Pt("Failed to read SVG.");vo(o);const l=It().serializeToString(o);return{name:t.name,blob:new Blob([l],{type:"image/svg+xml"})}}return t}async dispatchCreateAssetRequest(t,e,a,n){const r=t.blob.type?t.blob.type:this.guessMIME(t.name),o=await Mo(t.name,e,r,a,n);if(o)return{assetResponse:o,mimeType:r}}guessMIME(t){const e=t.split(".").pop();switch(e){case"glb":return"model/gltf-binary";case"ttf":return"font/ttf";case"mkv":return"video/x-matroska";default:throw new O("Unexpected mimetype: "+e)}}}const zt="persistentAssets",At=class At{static add(t){if(!t.fileLink){console.error("Failed to find cdn link on asset, cannot persist!");return}const e=new Map;e.set(t.key||"",t.fileLink);const a=Q.getMap(zt);a&&a.forEach((n,r)=>{e.set(r,n)}),Q.setMap(zt,e),At.executeCallbacks()}static remove(t){const e=Q.getMap(zt);if(!e)return;const a=Array.from(e.entries()).find(n=>n[0]===t);a&&(e.delete(a[0]),Q.setMap(zt,e),At.executeCallbacks())}static list(){const t=Q.getMap(zt);return t?Array.from(t.entries()).map(e=>({assetKey:e[0],src:e[1]})):[]}static addCallback(t){At.callbacks.push(t)}static removeCallback(t){At.callbacks=At.callbacks.filter(e=>e!==t)}static executeCallbacks(){At.callbacks.forEach(t=>t())}};At.callbacks=[];let ut=At;const qt="bgrmPersistentAssets",Gt="vectorizePersistentAssets";class q{static has(t,e){return q.getMap(t).has(e)}static get(t,e){return q.getMap(t).get(e)}static keys(t){return q.getMap(t).keys()}static values(t){return q.getMap(t).values()}static add(t,e,a){const n=q.getMap(t);n.set(e,a),q.setMap(t,n)}static delete(t,e){const a=q.getMap(t);a.delete(e),q.setMap(t,a)}static deleteForTransformedKey(t,e){const a=q.getMap(t),n=Array.from(a.keys()).find(r=>a.get(r)===e);n&&(a.delete(n),q.setMap(t,a))}static getMap(t){return Q.getMap(t)||new Map}static setMap(t,e){Q.setMap(t,e)}}const G=new To;class No{constructor(){this.cache={},this.disabled=!1}get(t){if(this.disabled)return;const e=JSON.stringify(t);return this.cache[e]}set(t,e){if(this.disabled)return e;const a=JSON.stringify(t);return this.cache[a]=e,e}disable(t){this.disabled=t}}const oe=new No,We=(i,t=512,e,a)=>{const n=typeof i=="string"?i:i.fileLink;if(!n)return;const r=n.includes("?")?"&":"?",o=[`w=${t}`,`h=${t}`];return a!==void 0&&o.push(`q=${a}`),e&&o.push(`format=${e}`),`${n}${r}${o.join("&")}`},Qo=f.gql`
146
+ `,errorPolicy:"all",fetchPolicy:"no-cache",variables:{keys:i}})).data.assets,fs=async i=>(await y.getShadowGraphqlClient().query({query:hs,errorPolicy:"all",variables:{ids:i}})).data.materials,Cs=async(i,t,e,a,n)=>(await y.getShadowGraphqlClient().mutate({mutation:gs,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:i,type:t,mimeType:e,anonymous:a,temporary:n}})).data?.assetCreate;class ws{constructor(){this.cache=new Map,this.bgrmProcessCache=new Map,this.materialCache=new Map,this.loadImageAsFileInfo=async t=>{const e=await t.arrayBuffer(),a=await ce(e),n=(r,s)=>{const o=atob(r.split(",")[1]),l=[];for(let c=0;c<o.length;c++)l.push(o.charCodeAt(c));return new Blob([new Uint8Array(l)],{type:s})};return{name:t.name.substring(t.name.lastIndexOf("/")+1),blob:n(a.dataUrl,t.type)}}}async getLocalOrFromServer(t){if(this.cache.has(t)){const n=this.cache.get(t);if(!n)throw new O("Failed to get asset from cache!");return n}const a=(async()=>(await Pe([t]))[0])();return this.cache.set(t,a),a}async getFromServer(t){const a=(async()=>(await Pe([t]))[0])();return this.cache.set(t,a),a}keyFromURL(t){let e;try{e=new URL(t).pathname}catch{e=void 0}return e!==void 0&&e.startsWith("/")&&(e=e.replace("/","")),e?.split("?")[0]}cacheAsset(t){if(!t.key)throw new O("Asset has no key!");this.cache.has(t.key)||this.cache.set(t.key,Promise.resolve(t))}cacheMaterial(t){if(!t.id)throw new O("Material has no id!");this.materialCache.has(t.id)||this.materialCache.set(t.id,Promise.resolve(t))}async getMaterialLocalOrFromServer(t){if(this.materialCache.has(t))return this.materialCache.get(t);const a=(async()=>(await fs([t]))[0])();return this.materialCache.set(t,a),a}async uploadAssetWithProgress(t,e,a,n,r){const s=await this.dispatchCreateAssetRequest(t,e,n,r);if(!s)throw new Error("Failed to create asset.");return await new Promise((o,l)=>{const c=new XMLHttpRequest;c.open("PUT",s.assetResponse.uploadUrl,!0),c.setRequestHeader("Content-Type",s.mimeType),c.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),c.upload.onprogress=d=>{d.lengthComputable&&a(d.loaded*100/d.total)},c.onload=()=>{const d=s.assetResponse.asset;ct.add(s.assetResponse.asset),o(d)},c.onerror=l,this.postProcessFileUpload(t,s.mimeType).then(d=>c.send(d.blob)).catch(l)}),this.cacheAsset(s.assetResponse.asset),s.assetResponse.asset}async uploadAsset(t,e,a,n){return this.uploadAssetWithProgress(t,e,()=>{},a,n)}async uploadFile(t,e){const n=this.isRaster(t)?ee.Image:ee.Illustration,r=await this.loadImageAsFileInfo(t);return await this.uploadAssetWithProgress(r,n,e,!0)}async removeBackgroundFromAsset(t){const e=t.key;if(this.bgrmProcessCache.has(e))return this.bgrmProcessCache.get(e);if(q.has(Lt,e)){const r=this.getLocalOrFromServer(q.get(Lt,e));return this.bgrmProcessCache.set(e,r),r}const n=(async()=>{const r=await y.getShadowGraphqlClient().mutate({mutation:ms,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:e}});if(this.bgrmProcessCache.delete(e),!r.data?.assetRemoveBackground?.key)throw new Error("Failed to remove background from image");return ct.add(r.data.assetRemoveBackground),q.add(Lt,e,r.data.assetRemoveBackground.key),this.cache.set(r.data.assetRemoveBackground.key,Promise.resolve(r.data.assetRemoveBackground)),r.data.assetRemoveBackground})();return this.bgrmProcessCache.set(e,n),n}async vectorizeAsset(t,e=void 0){const a=t.key;if(this.bgrmProcessCache.has(a))return this.bgrmProcessCache.get(a);if(q.has(zt,a)){const s=this.getLocalOrFromServer(q.get(zt,a));return this.bgrmProcessCache.set(a,s),s}const r=(async()=>{const s=await y.getShadowGraphqlClient().mutate({mutation:ps,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:a,options:{maxColorCount:e}}});if(this.bgrmProcessCache.delete(a),!s.data?.assetVectorize?.key)throw new Error("Failed to vectorize image");return ct.add(s.data.assetVectorize),q.add(zt,a,s.data.assetVectorize.key),this.cache.set(s.data.assetVectorize.key,Promise.resolve(s.data.assetVectorize)),s.data.assetVectorize})();return this.bgrmProcessCache.set(a,r),r}removePersistedAsset(t){ct.remove(t),q.delete(Lt,t),q.delete(zt,t),q.deleteForTransformedKey(Lt,t),q.deleteForTransformedKey(zt,t)}getPersistedAssets(){return ct.list()}registerPersistedAssetListener(t){ct.addCallback(t)}unRegisterPersistedAssetListener(t){ct.removeCallback(t)}isRaster(t){return!(t.type==="image/svg+xml"||t.type==="application/pdf"||t.type==="application/postscript")}async postProcessFileUpload(t,e){if(e==="image/svg+xml"){const a=await t.blob.text(),s=new window.DOMParser().parseFromString(a,"image/svg+xml").documentElement;if(!s)throw new It("Failed to read SVG.");ls(s);const l=Et().serializeToString(s);return{name:t.name,blob:new Blob([l],{type:"image/svg+xml"})}}return t}async dispatchCreateAssetRequest(t,e,a,n){const r=t.blob.type?t.blob.type:this.guessMIME(t.name),s=await Cs(t.name,e,r,a,n);if(s)return{assetResponse:s,mimeType:r}}guessMIME(t){const e=t.split(".").pop();switch(e){case"glb":return"model/gltf-binary";case"ttf":return"font/ttf";case"mkv":return"video/x-matroska";default:throw new O("Unexpected mimetype: "+e)}}}const Vt="persistentAssets",dt=class dt{static add(t){if(!t.fileLink){console.error("Failed to find cdn link on asset, cannot persist!");return}const e=new Map;e.set(t.key||"",t.fileLink);const a=Q.getMap(Vt);a&&a.forEach((n,r)=>{e.set(r,n)}),Q.setMap(Vt,e),dt.executeCallbacks()}static remove(t){const e=Q.getMap(Vt);if(!e)return;const a=Array.from(e.entries()).find(n=>n[0]===t);a&&(e.delete(a[0]),Q.setMap(Vt,e),dt.executeCallbacks())}static list(){const t=Q.getMap(Vt);return t?Array.from(t.entries()).map(e=>({assetKey:e[0],src:e[1]})):[]}static addCallback(t){dt.callbacks.push(t)}static removeCallback(t){dt.callbacks=dt.callbacks.filter(e=>e!==t)}static executeCallbacks(){dt.callbacks.forEach(t=>t())}};dt.callbacks=[];let ct=dt;const Lt="bgrmPersistentAssets",zt="vectorizePersistentAssets";class q{static has(t,e){return q.getMap(t).has(e)}static get(t,e){return q.getMap(t).get(e)}static keys(t){return q.getMap(t).keys()}static values(t){return q.getMap(t).values()}static add(t,e,a){const n=q.getMap(t);n.set(e,a),q.setMap(t,n)}static delete(t,e){const a=q.getMap(t);a.delete(e),q.setMap(t,a)}static deleteForTransformedKey(t,e){const a=q.getMap(t),n=Array.from(a.keys()).find(r=>a.get(r)===e);n&&(a.delete(n),q.setMap(t,a))}static getMap(t){return Q.getMap(t)||new Map}static setMap(t,e){Q.setMap(t,e)}}const G=new ws;class ys{constructor(){this.cache={},this.disabled=!1}get(t){if(this.disabled)return;const e=JSON.stringify(t);return this.cache[e]}set(t,e){if(this.disabled)return e;const a=JSON.stringify(t);return this.cache[a]=e,e}disable(t){this.disabled=t}}const ie=new ys,Ge=(i,t=512,e,a)=>{const n=typeof i=="string"?i:i.fileLink;if(!n)return;const r=n.includes("?")?"&":"?",s=[`w=${t}`,`h=${t}`];return a!==void 0&&s.push(`q=${a}`),e&&s.push(`format=${e}`),`${n}${r}${s.join("&")}`},Ss=f.gql`
147
147
  fragment OptionMinimalFields on Option {
148
148
  id
149
149
  defaultVariant {
150
150
  id
151
151
  }
152
152
  }
153
- `,Oo=f.gql`
153
+ `,vs=f.gql`
154
154
  fragment OptionFields on Option {
155
155
  id
156
156
  name
@@ -188,7 +188,7 @@
188
188
  ...AssetFields
189
189
  }
190
190
  }
191
- `,Ro=f.gql`
191
+ `,Es=f.gql`
192
192
  query GetTagsMany($ids: [String!]!) {
193
193
  tagsMany(entityIds: $ids) {
194
194
  id
@@ -196,16 +196,16 @@
196
196
  name
197
197
  }
198
198
  }
199
- `,$o=async i=>{const t=await y.getShadowGraphqlClient().query({query:f.gql`
200
- ${Ae(!1,!1)}
201
- ${ui}
202
- ${Oo}
199
+ `,bs=async i=>{const t=await y.getShadowGraphqlClient().query({query:f.gql`
200
+ ${de(!1,!1)}
201
+ ${Zn}
202
+ ${vs}
203
203
  query GetOptions($ids: [String]!) {
204
204
  options(ids: $ids) {
205
205
  ...OptionFields
206
206
  }
207
207
  }
208
- `,errorPolicy:"all",variables:{ids:i}});return t.data.options.forEach(e=>{e.colorProfile&&G.cacheAsset(e.colorProfile),e.variants?.forEach(a=>{a.asset&&G.cacheAsset(a.asset),a.thumbnail&&G.cacheAsset(a.thumbnail),a.material&&G.cacheMaterial(a.material)})}),t.data.options},Uo=async(i,t)=>(await t).find(a=>a.id===i),oa=async i=>{const t=new Map(i.map(n=>[n,oe.get({id:n})])),e=i.filter(n=>t.get(n)===void 0);if(e.length>0){const n=$o(e);e.forEach(r=>t.set(r,oe.set({id:r},Uo(r,n))))}return(await Promise.all(i.map(n=>t.get(n)))).filter(n=>n!==void 0)},Cn=i=>{if(!(!i||!i.fileLink))return We(i,512,"webp")},wn=(i,t,e)=>{if(i.length===1)return i[0];if(e){const a=i.find(n=>n.id===e);if(a)return a}if(t.defaultVariant!==void 0)return i.find(a=>a.id===t.defaultVariant?.id)};class Vo{constructor(){this.getDefaultVariant=async(t,e)=>{const a=t?.variants;if(a)return wn(a,t,e);const r=(await this.getOption(t.id))?.variants;if(r)return wn(r,t,e)},this.getTagsForAssets=async t=>{const e=t?.map(o=>o.asset?.key)||[],a=t?.map(o=>o.material?.id)||[],n=[...e,...a].filter(o=>!!o);return n.length===0?[]:(await y.getShadowGraphqlClient().query({query:Ro,errorPolicy:"all",variables:{ids:n}})).data.tagsMany}}async getOption(t){return t?(await oa([t]))[0]:void 0}async getOptions(t){return oa(t)}async getOptionForStep(t){return this.ensureFullOption(t.option)}async ensureFullOption(t){return t?.variants?t:t?.id?(await oa([t.id]))[0]:void 0}async getAssetTileImageForVariant(t){const e=Cn(t.thumbnail)??Cn(t.asset);return e||(t.material?t.material.id:"")}}const I=new Vo,Ai=f.gql`
208
+ `,errorPolicy:"all",variables:{ids:i}});return t.data.options.forEach(e=>{e.colorProfile&&G.cacheAsset(e.colorProfile),e.variants?.forEach(a=>{a.asset&&G.cacheAsset(a.asset),a.thumbnail&&G.cacheAsset(a.thumbnail),a.material&&G.cacheMaterial(a.material)})}),t.data.options},Is=async(i,t)=>(await t).find(a=>a.id===i),na=async i=>{const t=new Map(i.map(n=>[n,ie.get({id:n})])),e=i.filter(n=>t.get(n)===void 0);if(e.length>0){const n=bs(e);e.forEach(r=>t.set(r,ie.set({id:r},Is(r,n))))}return(await Promise.all(i.map(n=>t.get(n)))).filter(n=>n!==void 0)},An=i=>{if(!(!i||!i.fileLink))return Ge(i,512,"webp")},hn=(i,t,e)=>{if(i.length===1)return i[0];if(e){const a=i.find(n=>n.id===e);if(a)return a}if(t.defaultVariant!==void 0)return i.find(a=>a.id===t.defaultVariant?.id)};class Bs{constructor(){this.getDefaultVariant=async(t,e)=>{const a=t?.variants;if(a)return hn(a,t,e);const r=(await this.getOption(t.id))?.variants;if(r)return hn(r,t,e)},this.getTagsForAssets=async t=>{const e=t?.map(s=>s.asset?.key)||[],a=t?.map(s=>s.material?.id)||[],n=[...e,...a].filter(s=>!!s);return n.length===0?[]:(await y.getShadowGraphqlClient().query({query:Es,errorPolicy:"all",variables:{ids:n}})).data.tagsMany}}async getOption(t){return t?(await na([t]))[0]:void 0}async getOptions(t){return na(t)}async getOptionForStep(t){return this.ensureFullOption(t.option)}async ensureFullOption(t){return t?.variants?t:t?.id?(await na([t.id]))[0]:void 0}async getAssetTileImageForVariant(t){const e=An(t.thumbnail)??An(t.asset);return e||(t.material?t.material.id:"")}}const I=new Bs,_n=f.gql`
209
209
  fragment ActiveIntegrationFields on Integration {
210
210
  id
211
211
  logo
@@ -225,7 +225,7 @@
225
225
  beta
226
226
  }
227
227
  }
228
- `,Ye=f.gql`
228
+ `,je=f.gql`
229
229
  fragment AdditionalIntegrationProductFields on IntegrationProduct {
230
230
  id
231
231
  product {
@@ -243,7 +243,7 @@
243
243
  preloadImageUrl
244
244
  }
245
245
  }
246
- `,hi=f.gql`
246
+ `,ti=f.gql`
247
247
  fragment RecipientFields on Recipient {
248
248
  id
249
249
  firstName
@@ -264,7 +264,7 @@
264
264
  customField5
265
265
  conversionConfigurationId
266
266
  }
267
- `,he=f.gql`
267
+ `,ue=f.gql`
268
268
  fragment ConversionConfigurationFields on ConversionConfiguration {
269
269
  id
270
270
  partnerId
@@ -293,8 +293,8 @@
293
293
  }
294
294
  }
295
295
  }
296
- `,Lo=f.gql`
297
- ${hi}
296
+ `,Ps=f.gql`
297
+ ${ti}
298
298
  mutation CreateTransactions(
299
299
  $inputs: [TransactionCreateInput]!
300
300
  $marketplaceThemeInstallId: String
@@ -322,7 +322,7 @@
322
322
  integrationProductId
323
323
  }
324
324
  }
325
- `,gi=f.gql`
325
+ `,ei=f.gql`
326
326
  fragment StakeholderFields on Stakeholder {
327
327
  id
328
328
  type
@@ -330,7 +330,7 @@
330
330
  authorizationNote
331
331
  authorizationStatus
332
332
  }
333
- `,mi=f.gql`
333
+ `,ai=f.gql`
334
334
  fragment TransactionShareActionFields on TransactionShareAction {
335
335
  id
336
336
  title
@@ -339,10 +339,10 @@
339
339
  precedence
340
340
  url
341
341
  }
342
- `,pi=f.gql`
343
- ${Ye}
344
- ${he}
345
- ${Ai}
342
+ `,ni=f.gql`
343
+ ${je}
344
+ ${ue}
345
+ ${_n}
346
346
  query ReadIntegrationProducts($ids: [String!]!) {
347
347
  integrationProducts(ids: $ids) {
348
348
  id
@@ -427,10 +427,10 @@
427
427
  }
428
428
  }
429
429
  }
430
- `,zo=f.gql`
431
- ${gi}
432
- ${mi}
433
- ${hi}
430
+ `,xs=f.gql`
431
+ ${ei}
432
+ ${ai}
433
+ ${ti}
434
434
  query ReadTransactions($ids: [String]!) {
435
435
  transactions(ids: $ids) {
436
436
  customLogoLink
@@ -479,33 +479,33 @@
479
479
  integrationProductId
480
480
  }
481
481
  }
482
- `,qo=f.gql`
482
+ `,Fs=f.gql`
483
483
  mutation UpdateTransactionWorkflowState($id: String!, $workflowState: String!) {
484
484
  transactionUpdate(id: $id, workflowState: $workflowState) {
485
485
  id
486
486
  }
487
487
  }
488
- `,Go=f.gql`
488
+ `,Ds=f.gql`
489
489
  mutation UpdateTransactionQuantity($id: String!, $quantity: Int) {
490
490
  transactionUpdate(id: $id, quantity: $quantity) {
491
491
  id
492
492
  }
493
493
  }
494
- `,jo=f.gql`
494
+ `,ks=f.gql`
495
495
  mutation UpdateTransactionWorkflow($id: String!, $workflowId: String!) {
496
496
  transactionUpdate(id: $id, workflowId: $workflowId) {
497
497
  id
498
498
  }
499
499
  }
500
- `,Ho=f.gql`
501
- ${he}
500
+ `,Ms=f.gql`
501
+ ${ue}
502
502
  query ReadConversionConfigurationQuery($id: String!) {
503
503
  conversionConfiguration(id: $id) {
504
504
  ...ConversionConfigurationFields
505
505
  }
506
506
  }
507
- `,Wo=f.gql`
508
- ${he}
507
+ `,Ts=f.gql`
508
+ ${ue}
509
509
  query ReadTransactionForDesignCreation($id: String!) {
510
510
  transactions(ids: [$id]) {
511
511
  id
@@ -563,8 +563,8 @@
563
563
  workflowViewerReadOnlyLink
564
564
  }
565
565
  }
566
- `,Yo=f.gql`
567
- ${mi}
566
+ `,Ns=f.gql`
567
+ ${ai}
568
568
  query ReadTransactionForShareActions($id: String!) {
569
569
  transactions(ids: [$id]) {
570
570
  id
@@ -574,12 +574,12 @@
574
574
  }
575
575
  }
576
576
  }
577
- `,Jo=f.gql`
577
+ `,Qs=f.gql`
578
578
  query ConfirmWorkflowStates($transactions: [TransactionConfirmInput!]!) {
579
579
  transactionConfirmWorkflowStates(transactions: $transactions)
580
580
  }
581
- `,fi=i=>f.gql`
582
- ${Ye}
581
+ `,ii=i=>f.gql`
582
+ ${je}
583
583
  fragment IntegrationProductFields on IntegrationProduct {
584
584
  id
585
585
  externalProductId
@@ -657,15 +657,15 @@
657
657
  `:""}
658
658
  }
659
659
  }
660
- `,Ko=i=>f.gql`
661
- ${fi(i)}
660
+ `,Os=i=>f.gql`
661
+ ${ii(i)}
662
662
  query GetIntegrationProducts($ids: [String!]!) {
663
663
  integrationProducts(ids: $ids) {
664
664
  ...IntegrationProductFields
665
665
  }
666
666
  }
667
- `,_o=i=>f.gql`
668
- ${fi(i)}
667
+ `,Rs=i=>f.gql`
668
+ ${ii(i)}
669
669
  query GetIntegrationProductFromExternalIds($externalIntegrationId: String!, $externalProductId: String!) {
670
670
  integrationProductFromExternalIds(
671
671
  externalIntegrationId: $externalIntegrationId
@@ -674,8 +674,8 @@
674
674
  ...IntegrationProductFields
675
675
  }
676
676
  }
677
- `,Xo=f.gql`
678
- ${gi}
677
+ `,$s=f.gql`
678
+ ${ei}
679
679
  query ReadTransactionForStakeholders($id: String!) {
680
680
  transactions(ids: [$id]) {
681
681
  stakeholders {
@@ -686,11 +686,11 @@
686
686
  }
687
687
  }
688
688
  }
689
- `,Zo=f.gql`
689
+ `,Us=f.gql`
690
690
  mutation FinalizeUpdateTransaction($transactionId: String!) {
691
691
  transactionFinalizeUpdate(transactionId: $transactionId)
692
692
  }
693
- `,ts=f.gql`
693
+ `,Vs=f.gql`
694
694
  fragment RegionFields on Region {
695
695
  width
696
696
  top
@@ -708,7 +708,7 @@
708
708
  height
709
709
  }
710
710
  }
711
- `,es=f.gql`
711
+ `,Ls=f.gql`
712
712
  fragment LookAtAnimationFields on LookAtAnimation {
713
713
  latDeg
714
714
  lonDeg
@@ -719,7 +719,7 @@
719
719
  z
720
720
  }
721
721
  }
722
- `,as=f.gql`
722
+ `,zs=f.gql`
723
723
  fragment RenderingPipelineConfigurationFields on RenderingPipelineConfiguration {
724
724
  antiAliasing {
725
725
  samples
@@ -803,20 +803,20 @@
803
803
  weight
804
804
  }
805
805
  }
806
- `,ns=f.gql`
806
+ `,qs=f.gql`
807
807
  fragment ModelAnimationFields on ModelAnimation {
808
808
  from
809
809
  to
810
810
  loop
811
811
  name
812
812
  }
813
- `,is=i=>f.gql`
814
- ${Ae(i,!1)}
815
- ${Qo}
816
- ${ts}
817
- ${es}
818
- ${as}
819
- ${ns}
813
+ `,Gs=i=>f.gql`
814
+ ${de(i,!1)}
815
+ ${Ss}
816
+ ${Vs}
817
+ ${Ls}
818
+ ${zs}
819
+ ${qs}
820
820
  query GetWorkflows($ids: [String!]!) {
821
821
  workflows(ids: $ids) {
822
822
  partner {
@@ -1216,8 +1216,8 @@
1216
1216
  }
1217
1217
  }
1218
1218
  }
1219
- `,Je=f.gql`
1220
- ${he}
1219
+ `,We=f.gql`
1220
+ ${ue}
1221
1221
  fragment MarketplaceThemeInstallConfigurationFields on MarketplaceThemeInstallConfiguration {
1222
1222
  id
1223
1223
  themeInstallId
@@ -1284,16 +1284,16 @@
1284
1284
  }
1285
1285
  }
1286
1286
  }
1287
- `,rs=f.gql`
1288
- ${Je}
1287
+ `,js=f.gql`
1288
+ ${We}
1289
1289
  query GetMarketplaceThemeInstallConfiguration($themeConfigurationId: String!, $themeInstallId: String!) {
1290
1290
  marketplaceThemeInstallConfiguration(id: $themeConfigurationId, themeInstallId: $themeInstallId, raw: false) {
1291
1291
  ...MarketplaceThemeInstallConfigurationFields
1292
1292
  }
1293
1293
  }
1294
- `,os=f.gql`
1295
- ${Ai}
1296
- ${Je}
1294
+ `,Ws=f.gql`
1295
+ ${_n}
1296
+ ${We}
1297
1297
  query GetCurrentIntegration($themeConfigurationId: String) {
1298
1298
  currentIntegration {
1299
1299
  id
@@ -1304,8 +1304,8 @@
1304
1304
  ...ActiveIntegrationFields
1305
1305
  }
1306
1306
  }
1307
- `,ss=f.gql`
1308
- ${Je}
1307
+ `,Hs=f.gql`
1308
+ ${We}
1309
1309
  query ReadTransactionForMarketplaceTheme($id: String!) {
1310
1310
  transactions(ids: [$id]) {
1311
1311
  marketplaceThemeInstallConfiguration(raw: false) {
@@ -1313,8 +1313,8 @@
1313
1313
  }
1314
1314
  }
1315
1315
  }
1316
- `,ls=f.gql`
1317
- ${Je}
1316
+ `,Ys=f.gql`
1317
+ ${We}
1318
1318
  query ReadBundleForMarketplaceTheme($id: String!) {
1319
1319
  bundles(ids: [$id]) {
1320
1320
  marketplaceThemeInstallConfiguration(raw: false) {
@@ -1322,14 +1322,14 @@
1322
1322
  }
1323
1323
  }
1324
1324
  }
1325
- `,cs=f.gql`
1325
+ `,Js=f.gql`
1326
1326
  mutation CreateOrder($orderItems: [OrderItemInput]!) {
1327
1327
  orderCreate(orderItems: $orderItems, paid: false, generateInternalId: true) {
1328
1328
  id
1329
1329
  internalId
1330
1330
  }
1331
1331
  }
1332
- `,ds=f.gql`
1332
+ `,Ks=f.gql`
1333
1333
  query CurrencyConversion($from: String!, $to: String!) {
1334
1334
  currencyConversion(from: $from, to: $to) {
1335
1335
  rateFrom
@@ -1337,48 +1337,48 @@
1337
1337
  timestamp
1338
1338
  }
1339
1339
  }
1340
- `,sa=[E.SilentIllustration,E.ProductOverlay],yn=i=>{const t=[];for(const a of i.steps){const n=us(a.stepName,i.stepGroups);if(!n)throw new Error("Workflow step does not belong to a group, all steps must belong to a group. Step: "+a.stepName);const r=t.find(o=>o.name===n.name);r?sa.includes(a.type)?r.silentSteps.push(a):r.renderableSteps.push(a):t.push({name:n.name,title:n.name,renderableSteps:sa.includes(a.type)?[]:[a],silentSteps:sa.includes(a.type)?[a]:[]})}const e="workflow.steps.finish.confirmDesign";return t.push({name:"Finish",title:e,renderableSteps:[{type:E.Finish,stepName:"Finish",stepTitle:e,helpText:"",data:{modelAnimation:i.finalizeStepConfig?i.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:i.finalizeStepConfig?i.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),t},us=(i,t)=>t.find(e=>e.stepNames.includes(i)),Ct=async(i,t)=>(await Promise.all((i.conditions||[]).map(async a=>{const n=t[a.targetStepName];if(n&&n.selectedVariants){const r=n.selectedVariants;return a.type==="VariantMetafield"?(await $e.ensureIdsArePresent(r.map(s=>s.id)),a.requiredVariantMetafields?.some(s=>r.find(l=>$e.requestIfAvailable(l.id,s.variantMetafieldConfigurationId||"")?.value===s.variantMetafieldValue))):a.requiredVariantSelections.some(o=>r.find(s=>s.id===o)!==void 0)}return!1}))).every(a=>a),As=async(i,t)=>{const e=await Promise.all(i.renderableSteps.map(s=>Ct(s,t))),a=i.renderableSteps.filter((s,l)=>e[l]),n=await Promise.all(i.silentSteps.map(s=>Ct(s,t))),r=i.silentSteps.filter((s,l)=>n[l]),o={name:i.name,title:i.title,renderableSteps:a,silentSteps:r};return o.silentSteps.length===0&&o.renderableSteps.length===0?null:o},dt=async(i,t)=>(await Promise.all(i.map(a=>As(a,t)))).filter(a=>a!==null),hs=async(i,t,e=!1)=>{const a=await dt(i,t),n=[];for(const o of a)for(const s of o.renderableSteps){let l=0;if(s.type!=="Finish"&&s.type!=="Module"){let c;s.option?.variants?(c=s.option,l=c?.variants?.length||0):(c=await I.getOption(s.option?.id),l=c?.variants?.length||0)}s.silent||(s.type===E.Model||s.type===E.Material||s.type===E.Picture||s.type===E.Shape?(l>1||e)&&n.push(s.stepName):n.push(s.stepName))}const r=a.filter(o=>o.renderableSteps.filter(l=>n.includes(l.stepName)).length>0);for(const o of r)o.renderableSteps=o.renderableSteps.filter(s=>n.includes(s.stepName));return r};class Ke{constructor(){this.timestamp=Date.now()}}class _e{constructor(t,e=!0){this.queue=[],this.activePromise=void 0,this.queueMaxSize=void 0,this.queueMaxSize=t,this.isEnabled=e}enqueue(t){if(this.queue.push(t),this.queueMaxSize!==void 0&&this.queue.length>this.queueMaxSize){const e=this.queue.length-1;for(let a=0;a<e;++a)this.queue.shift()}this.isEnabled&&(this.activePromise||(this.activePromise=this.dequeue()))}get enabled(){return this.isEnabled}set enabled(t){!this.isEnabled&&t&&!this.activePromise&&this.getRemainingQueueSize()>0&&(this.activePromise=this.dequeue()),this.isEnabled=t}hasActivePromise(){return!!this.activePromise}getRemainingQueueSize(){return this.queue.length}async finalize(){return this.activePromise?this.activePromise:Promise.resolve()}async dequeue(){const t=this.queue.shift();if(!t){this.activePromise=void 0;return}try{await t.execute()}catch(e){console.log(e)}finally{await this.dequeue()}}}const N=()=>{const i=()=>Math.floor((1+Math.random())*65536).toString(16).substring(1);return i()+i()+"-"+i()+"-"+i()+"-"+i()+"-"+i()+i()+i()},gs=({backgroundColor:i,outlineColor:t,borderRadius:e,configuration:a,elements:n,height:r,maxHeight:o,maxWidth:s,outlineArea:l,position:c,preserveAspectRatio:d,viewBox:u,width:A})=>{const h=e||0,g=2*(l?.scale||1),p=u||{x:0,y:0,width:A,height:r},m=`${p.x} ${p.y} ${p.width} ${p.height}`,C=N(),S=a.purpose===Ot.FreeDesign&&P.jsx("defs",{children:P.jsx("clipPath",{id:"viewboxClip",children:P.jsx("rect",{width:p.width,height:p.height,rx:h})})}),w=a.colorProfiles?.map((v,B)=>P.jsx("color-profile",{name:v.name,xlinkHref:v.key,children:" "},B)),F=n.map(v=>({...v,_renderingConfiguration:a,mask:l?`url(#viewmask-${C})`:void 0})),b=ja(F);return P.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",xmlSpace:"preserve",version:"1.1",preserveAspectRatio:d,width:A,height:r,style:{gridColumn:1,gridRow:1,maxWidth:s,maxHeight:o,position:c},viewBox:m,children:[w,S,!!i&&P.jsx("rect",{id:"layout-background",width:p.width,height:p.height,fill:i,rx:h}),P.jsx("g",{id:"element-group",clipPath:a.purpose===Ot.FreeDesign?"url(#viewboxClip)":void 0,children:b.map(v=>Bi(v)).filter(v=>!!v)}),l&&P.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"none",stroke:l.hidden?"none":t||"#aaaaaa",strokeWidth:g/2,strokeDasharray:`${g*2} ${g}`}),l&&P.jsxs("mask",{id:`viewmask-${C}`,children:[P.jsx("rect",{x:p.x,y:p.y,width:p.width,height:p.height,fill:"black"}),P.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"white"})]})]})},ms=(i,t,e,a,n)=>{const r=Et(n),o=e/2,s=a/2,l=i+o,c=t+s,d=Math.sin(r),u=Math.cos(r),A=o,h=o,g=-s,p=s,m=A*u-g*d,C=h*u-p*d,S=A*d+g*u,w=h*d+p*u,F=Math.max(Math.abs(m),Math.abs(C)),b=Math.max(Math.abs(S),Math.abs(w));return{minX:l-F,maxX:l+F,minY:c-b,maxY:c+b}},ps=(i,t,e)=>{const a=Math.sqrt(Math.pow(t.x-i.x,2)+Math.pow(t.y-i.y,2)),n=Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2)),r=Math.sqrt(Math.pow(e.x-i.x,2)+Math.pow(e.y-i.y,2));return Math.acos((n*n+a*a-r*r)/(2*n*a))*(180/Math.PI)},Et=i=>i*(Math.PI/180),fs=(i,t,e)=>Math.abs(i-t)<e,Cs=(i,t,e)=>{const a=Math.sin(Et(e)),n=Math.cos(Et(e));return{x:(i.x-t.x)*n-(i.y-t.y)*a+t.x,y:(i.x-t.x)*a+(i.y-t.y)*n+t.y}},ws=(i,t)=>({x:(i.x+t.x)/2,y:(i.y+t.y)/2}),ys=(i,t,e,a)=>({x:i.x+t?.x*e,y:i.y+t?.y*a}),Ss=(i,t,e,a)=>({x:i.x+(t?.x+t?.width)*e,y:i.y+t?.y*a}),vs=(i,t,e,a)=>({x:i.x+(t?.x+t?.width)*e,y:i.y+(t?.y+t?.height)*a}),kt=i=>{switch(i){case Y.North:return Y.East;case Y.East:return Y.South;case Y.South:return Y.West;case Y.West:return Y.North;case Y.Northwest:return Y.Northeast;case Y.Northeast:return Y.Southeast;case Y.Southeast:return Y.Southwest;case Y.Southwest:return Y.Northwest}},Es=(i,t)=>t>45&&t<=135?kt(i):t>135&&t<=225?kt(kt(i)):t>225&&t<=315?kt(kt(kt(i))):i,bs=(i,t={x:0,y:0},e={x:1,y:1})=>{const a=Et(i.rotation),n={x:t.x+i.x*e.x,y:t.x+i.y*e.y},r={x:i.x+i.width,y:i.y},o={x:t.x+(i.x+i.width)*e.x,y:t.y+(i.height+i.y)*e.y},s={x:t.x+i.x*e.x,y:t.y+(i.height+i.y)*e.y},l={x:(s.x+o.x)/2,y:s.y-i.height*e.y/2};return{a:Yt(n,l,a),b:Yt(r,l,a),c:Yt(o,l,a),d:Yt(s,l,a),center:l}},Yt=(i,t,e)=>{const a=Math.sin(e),n=Math.cos(e);return{x:(i.x-t.x)*n-(i.y-t.y)*a+t.x,y:(i.x-t.x)*a+(i.y-t.y)*n+t.y}},Is=.352778,Bs=.035277,Ci=i=>{const t=i.rotation||0,e=Et(t),a=Math.cos(e),n=-Math.sin(e);return P.jsx("g",{mask:i.stepName||i.productOverlay?void 0:i.mask,children:P.jsx("g",{transform:`
1340
+ `,ia=[E.SilentIllustration,E.ProductOverlay],gn=i=>{const t=[];for(const a of i.steps){const n=Xs(a.stepName,i.stepGroups);if(!n)throw new Error("Workflow step does not belong to a group, all steps must belong to a group. Step: "+a.stepName);const r=t.find(s=>s.name===n.name);r?ia.includes(a.type)?r.silentSteps.push(a):r.renderableSteps.push(a):t.push({name:n.name,title:n.name,renderableSteps:ia.includes(a.type)?[]:[a],silentSteps:ia.includes(a.type)?[a]:[]})}const e="workflow.steps.finish.confirmDesign";return t.push({name:"Finish",title:e,renderableSteps:[{type:E.Finish,stepName:"Finish",stepTitle:e,helpText:"",data:{modelAnimation:i.finalizeStepConfig?i.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:i.finalizeStepConfig?i.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),t},Xs=(i,t)=>t.find(e=>e.stepNames.includes(i)),pt=async(i,t)=>(await Promise.all((i.conditions||[]).map(async a=>{const n=t[a.targetStepName];if(n&&n.selectedVariants){const r=n.selectedVariants;return a.type==="VariantMetafield"?(await Qe.ensureIdsArePresent(r.map(o=>o.id)),a.requiredVariantMetafields?.some(o=>r.find(l=>Qe.requestIfAvailable(l.id,o.variantMetafieldConfigurationId||"")?.value===o.variantMetafieldValue))):a.requiredVariantSelections.some(s=>r.find(o=>o.id===s)!==void 0)}return!1}))).every(a=>a),Zs=async(i,t)=>{const e=await Promise.all(i.renderableSteps.map(o=>pt(o,t))),a=i.renderableSteps.filter((o,l)=>e[l]),n=await Promise.all(i.silentSteps.map(o=>pt(o,t))),r=i.silentSteps.filter((o,l)=>n[l]),s={name:i.name,title:i.title,renderableSteps:a,silentSteps:r};return s.silentSteps.length===0&&s.renderableSteps.length===0?null:s},lt=async(i,t)=>(await Promise.all(i.map(a=>Zs(a,t)))).filter(a=>a!==null),_s=async(i,t,e=!1)=>{const a=await lt(i,t),n=[];for(const s of a)for(const o of s.renderableSteps){let l=0;if(o.type!=="Finish"&&o.type!=="Module"){let c;o.option?.variants?(c=o.option,l=c?.variants?.length||0):(c=await I.getOption(o.option?.id),l=c?.variants?.length||0)}o.silent||(o.type===E.Model||o.type===E.Material||o.type===E.Picture||o.type===E.Shape?(l>1||e)&&n.push(o.stepName):n.push(o.stepName))}const r=a.filter(s=>s.renderableSteps.filter(l=>n.includes(l.stepName)).length>0);for(const s of r)s.renderableSteps=s.renderableSteps.filter(o=>n.includes(o.stepName));return r};class He{constructor(){this.timestamp=Date.now()}}class Ye{constructor(t,e=!0){this.queue=[],this.activePromise=void 0,this.queueMaxSize=void 0,this.queueMaxSize=t,this.isEnabled=e}enqueue(t){if(this.queue.push(t),this.queueMaxSize!==void 0&&this.queue.length>this.queueMaxSize){const e=this.queue.length-1;for(let a=0;a<e;++a)this.queue.shift()}this.isEnabled&&(this.activePromise||(this.activePromise=this.dequeue()))}get enabled(){return this.isEnabled}set enabled(t){!this.isEnabled&&t&&!this.activePromise&&this.getRemainingQueueSize()>0&&(this.activePromise=this.dequeue()),this.isEnabled=t}hasActivePromise(){return!!this.activePromise}getRemainingQueueSize(){return this.queue.length}async finalize(){return this.activePromise?this.activePromise:Promise.resolve()}async dequeue(){const t=this.queue.shift();if(!t){this.activePromise=void 0;return}try{await t.execute()}catch(e){console.log(e)}finally{await this.dequeue()}}}const N=()=>{const i=()=>Math.floor((1+Math.random())*65536).toString(16).substring(1);return i()+i()+"-"+i()+"-"+i()+"-"+i()+"-"+i()+i()+i()},ri=({backgroundColor:i,outlineColor:t,borderRadius:e,configuration:a,elements:n,height:r,maxHeight:s,maxWidth:o,outlineArea:l,position:c,preserveAspectRatio:d,viewBox:u,width:A})=>{const h=e||0,g=2*(l?.scale||1),p=u||{x:0,y:0,width:A,height:r},m=`${p.x} ${p.y} ${p.width} ${p.height}`,C=N(),S=a.purpose===Nt.FreeDesign&&P.jsx("defs",{children:P.jsx("clipPath",{id:"viewboxClip",children:P.jsx("rect",{width:p.width,height:p.height,rx:h})})}),w=a.colorProfiles?.map((v,B)=>P.jsx("color-profile",{name:v.name,xlinkHref:v.key,children:" "},B)),F=n.map(v=>({...v,_renderingConfiguration:a,mask:l?`url(#viewmask-${C})`:void 0})),b=Ua(F);return P.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",xmlSpace:"preserve",version:"1.1",preserveAspectRatio:d,width:A,height:r,style:{gridColumn:1,gridRow:1,maxWidth:o,maxHeight:s,position:c},viewBox:m,children:[w,S,!!i&&P.jsx("rect",{id:"layout-background",width:p.width,height:p.height,fill:i,rx:h}),P.jsx("g",{id:"element-group",clipPath:a.purpose===Nt.FreeDesign?"url(#viewboxClip)":void 0,children:b.map(v=>gi(v)).filter(v=>!!v)}),l&&P.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"none",stroke:l.hidden?"none":t||"#aaaaaa",strokeWidth:g/2,strokeDasharray:`${g*2} ${g}`}),l&&P.jsxs("mask",{id:`viewmask-${C}`,children:[P.jsx("rect",{x:p.x,y:p.y,width:p.width,height:p.height,fill:"black"}),P.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"white"})]})]})},to=(i,t,e,a,n)=>{const r=St(n),s=e/2,o=a/2,l=i+s,c=t+o,d=Math.sin(r),u=Math.cos(r),A=s,h=s,g=-o,p=o,m=A*u-g*d,C=h*u-p*d,S=A*d+g*u,w=h*d+p*u,F=Math.max(Math.abs(m),Math.abs(C)),b=Math.max(Math.abs(S),Math.abs(w));return{minX:l-F,maxX:l+F,minY:c-b,maxY:c+b}},eo=(i,t,e)=>{const a=Math.sqrt(Math.pow(t.x-i.x,2)+Math.pow(t.y-i.y,2)),n=Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2)),r=Math.sqrt(Math.pow(e.x-i.x,2)+Math.pow(e.y-i.y,2));return Math.acos((n*n+a*a-r*r)/(2*n*a))*(180/Math.PI)},St=i=>i*(Math.PI/180),ao=(i,t,e)=>Math.abs(i-t)<e,no=(i,t,e)=>{const a=Math.sin(St(e)),n=Math.cos(St(e));return{x:(i.x-t.x)*n-(i.y-t.y)*a+t.x,y:(i.x-t.x)*a+(i.y-t.y)*n+t.y}},io=(i,t)=>({x:(i.x+t.x)/2,y:(i.y+t.y)/2}),ro=(i,t,e,a)=>({x:i.x+t?.x*e,y:i.y+t?.y*a}),so=(i,t,e,a)=>({x:i.x+(t?.x+t?.width)*e,y:i.y+t?.y*a}),oo=(i,t,e,a)=>({x:i.x+(t?.x+t?.width)*e,y:i.y+(t?.y+t?.height)*a}),Ft=i=>{switch(i){case Y.North:return Y.East;case Y.East:return Y.South;case Y.South:return Y.West;case Y.West:return Y.North;case Y.Northwest:return Y.Northeast;case Y.Northeast:return Y.Southeast;case Y.Southeast:return Y.Southwest;case Y.Southwest:return Y.Northwest}},lo=(i,t)=>t>45&&t<=135?Ft(i):t>135&&t<=225?Ft(Ft(i)):t>225&&t<=315?Ft(Ft(Ft(i))):i,co=(i,t={x:0,y:0},e={x:1,y:1})=>{const a=St(i.rotation),n={x:t.x+i.x*e.x,y:t.x+i.y*e.y},r={x:i.x+i.width,y:i.y},s={x:t.x+(i.x+i.width)*e.x,y:t.y+(i.height+i.y)*e.y},o={x:t.x+i.x*e.x,y:t.y+(i.height+i.y)*e.y},l={x:(o.x+s.x)/2,y:o.y-i.height*e.y/2};return{a:Wt(n,l,a),b:Wt(r,l,a),c:Wt(s,l,a),d:Wt(o,l,a),center:l}},Wt=(i,t,e)=>{const a=Math.sin(e),n=Math.cos(e);return{x:(i.x-t.x)*n-(i.y-t.y)*a+t.x,y:(i.x-t.x)*a+(i.y-t.y)*n+t.y}},uo=.352778,Ao=.035277,si=i=>{const t=i.rotation||0,e=St(t),a=Math.cos(e),n=-Math.sin(e);return P.jsx("g",{mask:i.stepName||i.productOverlay?void 0:i.mask,children:P.jsx("g",{transform:`
1341
1341
  matrix(1, 0, 0, 1, ${i.x}, ${i.y})
1342
1342
  matrix(1, 0, 0, 1, ${i.width/2}, ${i.height/2})
1343
1343
  matrix(${a}, ${-n}, ${n}, ${a}, 0, 0)
1344
1344
  matrix(1, 0, 0, 1, ${-i.width/2}, ${-i.height/2})
1345
- `,children:P.jsx("image",{xlinkHref:i.src,preserveAspectRatio:i.preserveAspectRatio,width:i.width,height:i.height})})})},wi=i=>{const t=`spiff-group-clip-${i.id}`,e=i.rotation||0,a=Et(e),n=Math.cos(a),r=-Math.sin(a),o=ja(i.children),s=()=>P.jsx("clipPath",{id:t,preserveAspectRatio:"none",children:i.clipPath?P.jsx("path",{d:i.clipPath}):P.jsx("rect",{x:0,y:0,width:i.width,height:i.height})});return P.jsxs(P.Fragment,{children:[P.jsx("defs",{children:s()}),P.jsxs("g",{transform:`
1345
+ `,children:P.jsx("image",{xlinkHref:i.src,preserveAspectRatio:i.preserveAspectRatio,width:i.width,height:i.height})})})},oi=i=>{const t=`spiff-group-clip-${i.id}`,e=i.rotation||0,a=St(e),n=Math.cos(a),r=-Math.sin(a),s=Ua(i.children),o=()=>P.jsx("clipPath",{id:t,preserveAspectRatio:"none",children:i.clipPath?P.jsx("path",{d:i.clipPath}):P.jsx("rect",{x:0,y:0,width:i.width,height:i.height})});return P.jsxs(P.Fragment,{children:[P.jsx("defs",{children:o()}),P.jsxs("g",{transform:`
1346
1346
  matrix(1, 0, 0, 1, ${i.x}, ${i.y})
1347
1347
  matrix(1, 0, 0, 1, ${i.width/2}, ${i.height/2})
1348
1348
  matrix(${n}, ${-r}, ${r}, ${n}, 0, 0)
1349
1349
  matrix(1, 0, 0, 1, ${-i.width/2}, ${-i.height/2})
1350
- `,children:[i._renderingConfiguration?.debug?P.jsx("rect",{stroke:"red",opacity:.3,fill:"none",x:0,y:0,width:i.width,height:i.height}):void 0,o.map(l=>Bi(l)).filter(l=>!!l).map(l=>P.jsx("g",{clipPath:`url(#${t})`,children:l}))]})]})},Ps=i=>{const t=`spiff-frame-${i.id}`,e=`spiff-frame-threshold-${i.id}`,a=()=>{if(!i.pattern)return"";if(i.pattern.svg){const u=He(i.pattern.svg,i.pattern.colors||{},!1);return Ge(u)}return i.pattern.src};if(!a())return P.jsx(P.Fragment,{});const n=()=>i.threshold?i.invertThreshold?"1 ".repeat(i.threshold)+"0 ".repeat(256-i.threshold):"0 ".repeat(i.threshold)+"1 ".repeat(256-i.threshold):"",r=()=>P.jsx(P.Fragment,{children:i.useThreshold&&P.jsx("defs",{children:P.jsxs("filter",{id:e,"color-interpolation-filters":"sRGB",children:[P.jsx("feColorMatrix",{type:"matrix",values:`
1350
+ `,children:[i._renderingConfiguration?.debug?P.jsx("rect",{stroke:"red",opacity:.3,fill:"none",x:0,y:0,width:i.width,height:i.height}):void 0,s.map(l=>gi(l)).filter(l=>!!l).map(l=>P.jsx("g",{clipPath:`url(#${t})`,children:l}))]})]})},ho=i=>{const t=`spiff-frame-${i.id}`,e=`spiff-frame-threshold-${i.id}`,a=()=>{if(!i.pattern)return"";if(i.pattern.svg){const u=qe(i.pattern.svg,i.pattern.colors||{},!1);return Le(u)}return i.pattern.src};if(!a())return P.jsx(vr.Fragment,{});const n=()=>i.threshold?i.invertThreshold?"1 ".repeat(i.threshold)+"0 ".repeat(256-i.threshold):"0 ".repeat(i.threshold)+"1 ".repeat(256-i.threshold):"",r=()=>P.jsx(P.Fragment,{children:i.useThreshold&&P.jsx("defs",{children:P.jsxs("filter",{id:e,"color-interpolation-filters":"sRGB",children:[P.jsx("feColorMatrix",{type:"matrix",values:`
1351
1351
  ${i.thresholdSaturation} ${i.thresholdSaturation} ${i.thresholdSaturation} 0 0
1352
1352
  ${i.thresholdSaturation} ${i.thresholdSaturation} ${i.thresholdSaturation} 0 0
1353
1353
  ${i.thresholdSaturation} ${i.thresholdSaturation} ${i.thresholdSaturation} 0 0
1354
1354
  0 0 0 1 0
1355
- `,result:"greyscale"}),P.jsxs("feComponentTransfer",{in:"greyscale",children:[P.jsx("feFuncR",{type:"discrete",tableValues:n()}),P.jsx("feFuncG",{type:"discrete",tableValues:n()}),P.jsx("feFuncB",{type:"discrete",tableValues:n()})]})]})})}),o=i.rotation||0,s=Et(o),l=Math.cos(s),c=-Math.sin(s),d=()=>{const u=i.pattern?.x||0,A=i.pattern?.y||0,h=i.pattern?.width||0,g=i.pattern?.height||0,p=i.pattern?.scaleX||1,m=i.pattern?.scaleY||1,C=i.pattern?.rotation||0;return[i.pattern?.svg?{id:`${t}-contents`,type:D.Illustration,x:u,y:A,rotation:C,width:h*p,height:g*m,src:a(),svg:i.pattern?.svg,colors:i.pattern?.colors}:{id:`${t}-contents`,type:D.Image,x:u,y:A,rotation:C,width:h*p,height:g*m,src:a()}]};return P.jsxs(P.Fragment,{children:[r(),P.jsx("g",{opacity:i.opacity,mask:i.stepName?void 0:i.mask,filter:i.useThreshold?`url(#${e})`:void 0,children:P.jsx("g",{transform:`
1355
+ `,result:"greyscale"}),P.jsxs("feComponentTransfer",{in:"greyscale",children:[P.jsx("feFuncR",{type:"discrete",tableValues:n()}),P.jsx("feFuncG",{type:"discrete",tableValues:n()}),P.jsx("feFuncB",{type:"discrete",tableValues:n()})]})]})})}),s=i.rotation||0,o=St(s),l=Math.cos(o),c=-Math.sin(o),d=()=>{const u=i.pattern?.x||0,A=i.pattern?.y||0,h=i.pattern?.width||0,g=i.pattern?.height||0,p=i.pattern?.scaleX||1,m=i.pattern?.scaleY||1,C=i.pattern?.rotation||0;return[i.pattern?.svg?{id:`${t}-contents`,type:D.Illustration,x:u,y:A,rotation:C,width:h*p,height:g*m,src:a(),svg:i.pattern?.svg,colors:i.pattern?.colors}:{id:`${t}-contents`,type:D.Image,x:u,y:A,rotation:C,width:h*p,height:g*m,src:a()}]};return P.jsxs(P.Fragment,{children:[r(),P.jsx("g",{opacity:i.opacity,mask:i.stepName?void 0:i.mask,filter:i.useThreshold?`url(#${e})`:void 0,children:P.jsx("g",{transform:`
1356
1356
  matrix(1, 0, 0, 1, ${i.x}, ${i.y})
1357
1357
  matrix(1, 0, 0, 1, ${i.width/2}, ${i.height/2})
1358
1358
  matrix(${l}, ${-c}, ${c}, ${l}, 0, 0)
1359
1359
  matrix(1, 0, 0, 1, ${-i.width/2}, ${-i.height/2})
1360
1360
  matrix(${i.scaleX}, 0, 0, ${i.scaleY}, 0, 0)
1361
- `,children:P.jsx(wi,{id:t,x:0,y:0,rotation:0,width:i.width,height:i.height,clipPath:i.path,children:d()})})})]})},yi=new Map;class xs{constructor(t){this.font=t,this.glyphsFromText=new Map,this.kerningValues=new Map,this.height=this.calculateApproximateHeight()}getFont(){return this.font}getGlyphs(t){const e=this.glyphsFromText.get(t);if(e)return e;const a=this.font.stringToGlyphs(t);return this.glyphsFromText.set(t,a),a}getApproximateHeight(){return this.height}getExactHeight(t){const e=this.font.stringToGlyphs(t);let a=0,n=0;return e.forEach(r=>{const o=r.getMetrics();a=Math.max(a,o.yMax),n=Math.min(n,o.yMin)}),a-n}getKerningValue(t,e){if(!t.name||!e.name)return;let a=this.kerningValues.get(t.name);a||(a=new Map,this.kerningValues.set(t.name,a));let n=a.get(e.name);return n||(n=this.font.getKerningValue(t,e),a.set(e.name,n)),n}calculateApproximateHeight(){const e=this.font.stringToGlyphs("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");let a=0,n=0;return e.forEach(r=>{const o=r.getMetrics();a=Math.max(a,o.yMax),n=Math.min(n,o.yMin)}),a-n}}const Fs=i=>i.substring(0,5).toLowerCase().trim()==="data:",la=new Map,Ft=async i=>{if(la.has(i))return la.get(i);const e=(async()=>{try{return bt(i).getFont()}catch{if(Fs(i)){const a=ti(i),n=ya.parse(a);return Pa(i,n),n}else{const a=await ze(i,!0),n=ya.parse(a);return Pa(i,n),await _r(n,i),n}}})();return la.set(i,e),e},Ds=i=>{const t=ti(i),e=ya.parse(t);return Pa(i,e),e},bt=i=>{const t=yi.get(i);if(t)return t;throw new Error("Font metrics unavailable for font")},Pa=(i,t)=>{const e=new xs(t);return yi.set(i,e),e},ks=async i=>{const t=ct(),e=t.parseFromString(i,"image/svg+xml"),a=e.firstElementChild,n=new Map;a.querySelectorAll("style").forEach(d=>{Vn.parse(d.innerHTML).stylesheet?.rules.forEach(A=>{if(A.type==="font-face"&&A.declarations){const h=A.declarations.find(m=>m.property==="font-family")?.value,p=A.declarations.find(m=>m.property==="src")?.value?.match(/'(https.*?)'/)?.[1];h&&p&&n.set(h,p)}})});const o=e.querySelectorAll("tspan");for(let d=0;d<o.length;d++){const u=o.item(d),A=u.closest("text"),h=u.closest("g"),g=A.getAttribute("font-family"),p=await Ft(n.get(g)),m=Qr.decode(u.innerHTML),C=A.getAttribute("fill"),S=A.getAttribute("stroke"),w=A.getAttribute("stroke-width"),F=p.getPath(m,0,0,parseInt(A.getAttribute("font-size")??"72")),b=F.getBoundingBox().x2-F.getBoundingBox().x1;let v=0;const B=u.getAttribute("text-anchor");B==="middle"?v=b/2:B==="end"&&(v=b);const M=p.getPath(m,parseFloat(u.getAttribute("x")??"0")-v,parseFloat(u.getAttribute("y")??"0"),parseInt(A.getAttribute("font-size")??"72"));M.fill=C,M.stroke=S,M.strokeWidth=parseFloat(w??"0");const R=M.toSVG(2),T=t.parseFromString(R,"image/svg+xml").firstElementChild;h.appendChild(T)}return e.querySelectorAll("text").forEach(d=>d.remove()),It().serializeToString(a)},ke=(i,t,e,a)=>Math.max(Qs(i.join(`
1362
- `),e,a),t),Sn=(i,t,e,a,n,r)=>{const o=(r||Ei)*n.getApproximateHeight(),s=t.split(`
1363
- `);try{const l=s.flatMap(d=>Pe(d,i.width,a,n)),c=l.flatMap(d=>d.lines);return{lines:c,requiredHeight:l.flatMap(d=>d.lines).length*(a*o),fontSize:e,requiredWidth:ke(c,i.width,a,n)}}catch{const c=t.split("");return{lines:c,requiredHeight:c.length*(a*o),fontSize:e,requiredWidth:ke(c,i.width,a,n)}}},Pe=(i,t,e,a)=>{const n=wt(i,e,a);if(n<=t)return{lines:[i],width:n};if(!(i.indexOf(" ")>-1)){if(i.length<=1)throw new Error(`Character ${i} is wider than region`);const d=Math.floor(i.length/2),u=Pe(i.slice(0,d),t,e,a),A=Pe(i.slice(d),t,e,a);return{lines:[...u.lines,...A.lines],width:Math.max(u.width,A.width)}}const o=i.split(" "),s=[];let l=-1/0,c=0;for(;c<o.length;){const d=o[c];if(wt(d,e,a)>t){const u=Pe(d,t,e,a);s.push(...u.lines),l=Math.max(l,u.width),c++}else{const u=[d];l=Math.max(l,wt(d,e,a));let A=c+1,h=!0;for(;A<o.length&&h;){const g=o[A],p=wt(`${u.join(" ")} ${g}`,e,a);p<=t?(u.push(g),l=Math.max(l,p),A++):h=!1}s.push(u.join(" ")),c=A}}if(l<0)throw new Error(`No max width calculated for text: ${s}.`);return{lines:s,width:l}},Ms=(i,t,e,a,n,r)=>{const o=(r??Ei)*t.getApproximateHeight(),s=1/e.unitsPerEm,l=Si(i,s,t),c=i.length*o*s,d=a/l,u=n/c;return Math.min(u,d)},Ts=(i,t,e,a)=>{const n=bt(t.fontData.assetUrl),r=n.getFont(),o=t.fontSize/r.unitsPerEm;if(!e)return Sn(t,i,t.fontSize,o,n,a);let s;if(t.text?s=t.text.split(`
1364
- `):s=t.input?.split(`
1365
- `)??[""],e.input===i&&t.width===e.width&&t.height===e.height&&t.lineHeight===e.lineHeight)return{lines:s,requiredHeight:t.height,requiredWidth:ke(s,t.width,o,n),fontSize:t.fontSize};const l=t.width!==e.width!=(t.height!==e.height);return t.lineHeight===e.lineHeight&&!l&&e.input===i?{lines:s,requiredHeight:t.height,requiredWidth:ke(s,t.width,o,n),fontSize:Ms(s,n,r,t.width,t.height,a)}:Sn(t,i,t.fontSize,o,n,a)},Ns=(i,t,e,a,n)=>{const o=bt(t.assetUrl).getFont();let s={...i};const l={...i},c=Si(a,e/o.unitsPerEm,bt(t.assetUrl));return c&&c<s.width&&(l.width=c,n==="left"?(l.left+=Math.sin(s.rotation*Math.PI/360)*(s.width-c),l.top+=Math.sin(s.rotation*Math.PI/180)*(c-s.width)/2):n==="right"?l.left+=s.width-c:l.left+=(s.width-c)/2,a&&Os(a,a).every(([d,u])=>d===u)&&(s=l)),s},ca=1,wt=(i,t,e)=>{let a=0;const n=e.getGlyphs(i);return n.forEach((r,o)=>{if(r.advanceWidth&&(a+=r.advanceWidth),o<n.length-1){const s=e.getKerningValue(r,n[o+1]);a+=s||0}}),a*=t,a},Qs=(i,t,e)=>{let a=0;const n=e.getGlyphs(i);return n.forEach((r,o)=>{if(r.advanceWidth&&(a=Math.max(a,r.advanceWidth)),o<n.length-1){const s=e.getKerningValue(r,n[o+1]);a=Math.max(a,s||0)}}),a*=t,a},Si=(i,t,e)=>{let a=0;return i.forEach(n=>{a=Math.max(a,wt(n,t,e))}),a},vn={stripControlCharacters:!0,vertical:!1,uppercase:!1},Me=(i,t=vn)=>{const e={...vn,...t};let a=i||"";return e.stripControlCharacters&&(a=a.replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,"")),e.uppercase&&(a=a.toUpperCase()),e.vertical&&(a=a.split("").join(`
1366
- `)),a},Os=(i,t)=>i.map((e,a)=>[e,t[a]]),Rs=(i="center",t=!1)=>t?"center":i,vi=i=>i==="left"?"start":i==="right"?"end":"middle",ge=(i,t,e)=>i.fontData?{...i,...(()=>{if(i.algorithm===xt.Traditional){const n=Ts(t,i,e,i.lineHeight);return{text:n.lines.join(`
1367
- `),height:n.requiredHeight,width:n.requiredWidth,fontSize:n.fontSize,input:t}}else return{text:t}})()}:i,Ei=1.1;function Nt(i,t){return bi(i,t.getTemplatingContext())}function bi(i,t){try{i=Or.compile(i)(t)}catch(e){console.error("failed to render templated text",e)}return i}const $s=i=>{const e=(i.rotation||0)*Math.PI/180,a=Math.cos(e),n=-Math.sin(e),r=`text-path-${i.id}`,o=`text-fill-${i.id}`,s=i.x+(i.curved?0:i.width/2),l=i.y+(i.curved?0:i.height/2),c=bi(i.text||"",i._renderingConfiguration?.templatingContext),d=c.split(`
1368
- `),u=i.strokeColor?.browserValue&&i.strokeThickness?i.strokeColor?.browserValue:void 0,A=i.strokeColor?.browserValue&&i.strokeThickness?i.strokeThickness:void 0;if(i.curved&&!i.paths||!i.fontData)return null;const h=()=>i.textFillImage?`url("#${o}")`:i._renderingConfiguration?.spotColors&&i.fillSpotColorDefinition?`${i.fill} ${oi(i.fillSpotColorDefinition)}`:i.fill;return P.jsxs(P.Fragment,{children:[P.jsxs("defs",{children:[i.textFillImage&&P.jsx("pattern",{id:o,patternUnits:"userSpaceOnUse",width:i.textFillImage.scale*i.textFillImage.width,height:i.textFillImage.scale*i.textFillImage.height,x:0,y:0,children:P.jsx("image",{href:i.textFillImage.src,xlinkHref:i.textFillImage.src,width:i.textFillImage.scale*i.textFillImage.width,height:i.textFillImage.scale*i.textFillImage.height})}),P.jsx("style",{type:"text/css",dangerouslySetInnerHTML:{__html:`
1361
+ `,children:P.jsx(oi,{id:t,x:0,y:0,rotation:0,width:i.width,height:i.height,clipPath:i.path,children:d()})})})]})},li=new Map;class go{constructor(t){this.font=t,this.glyphsFromText=new Map,this.kerningValues=new Map,this.height=this.calculateApproximateHeight()}getFont(){return this.font}getGlyphs(t){const e=this.glyphsFromText.get(t);if(e)return e;const a=this.font.stringToGlyphs(t);return this.glyphsFromText.set(t,a),a}getApproximateHeight(){return this.height}getExactHeight(t){const e=this.font.stringToGlyphs(t);let a=0,n=0;return e.forEach(r=>{const s=r.getMetrics();a=Math.max(a,s.yMax),n=Math.min(n,s.yMin)}),a-n}getKerningValue(t,e){if(!t.name||!e.name)return;let a=this.kerningValues.get(t.name);a||(a=new Map,this.kerningValues.set(t.name,a));let n=a.get(e.name);return n||(n=this.font.getKerningValue(t,e),a.set(e.name,n)),n}calculateApproximateHeight(){const e=this.font.stringToGlyphs("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");let a=0,n=0;return e.forEach(r=>{const s=r.getMetrics();a=Math.max(a,s.yMax),n=Math.min(n,s.yMin)}),a-n}}const mo=i=>i.substring(0,5).toLowerCase().trim()==="data:",ra=new Map,Pt=async i=>{if(ra.has(i))return ra.get(i);const e=(async()=>{try{return vt(i).getFont()}catch{if(mo(i)){const a=Ln(i),n=ma.parse(a);return va(i,n),n}else{const a=await Ue(i,!0),n=ma.parse(a);return va(i,n),await $r(n,i),n}}})();return ra.set(i,e),e},po=i=>{const t=Ln(i),e=ma.parse(t);return va(i,e),e},vt=i=>{const t=li.get(i);if(t)return t;throw new Error("Font metrics unavailable for font")},va=(i,t)=>{const e=new go(t);return li.set(i,e),e},fo=async i=>{const t=ot(),e=t.parseFromString(i,"image/svg+xml"),a=e.firstElementChild,n=new Map;a.querySelectorAll("style").forEach(d=>{Pn.parse(d.innerHTML).stylesheet?.rules.forEach(A=>{if(A.type==="font-face"&&A.declarations){const h=A.declarations.find(m=>m.property==="font-family")?.value,p=A.declarations.find(m=>m.property==="src")?.value?.match(/'(https.*?)'/)?.[1];h&&p&&n.set(h,p)}})});const s=e.querySelectorAll("tspan");for(let d=0;d<s.length;d++){const u=s.item(d),A=u.closest("text"),h=u.closest("g"),g=A.getAttribute("font-family"),p=await Pt(n.get(g)),m=Sr.decode(u.innerHTML),C=A.getAttribute("fill"),S=A.getAttribute("stroke"),w=A.getAttribute("stroke-width"),F=p.getPath(m,0,0,parseInt(A.getAttribute("font-size")??"72")),b=F.getBoundingBox().x2-F.getBoundingBox().x1;let v=0;const B=u.getAttribute("text-anchor");B==="middle"?v=b/2:B==="end"&&(v=b);const M=p.getPath(m,parseFloat(u.getAttribute("x")??"0")-v,parseFloat(u.getAttribute("y")??"0"),parseInt(A.getAttribute("font-size")??"72"));M.fill=C,M.stroke=S,M.strokeWidth=parseFloat(w??"0");const R=M.toSVG(2),T=t.parseFromString(R,"image/svg+xml").firstElementChild;h.appendChild(T)}return e.querySelectorAll("text").forEach(d=>d.remove()),Et().serializeToString(a)},xe=(i,t,e,a)=>Math.max(So(i.join(`
1362
+ `),e,a),t),mn=(i,t,e,a,n,r)=>{const s=(r||ui)*n.getApproximateHeight(),o=t.split(`
1363
+ `);try{const l=o.flatMap(d=>Ie(d,i.width,a,n)),c=l.flatMap(d=>d.lines);return{lines:c,requiredHeight:l.flatMap(d=>d.lines).length*(a*s),fontSize:e,requiredWidth:xe(c,i.width,a,n)}}catch{const c=t.split("");return{lines:c,requiredHeight:c.length*(a*s),fontSize:e,requiredWidth:xe(c,i.width,a,n)}}},Ie=(i,t,e,a)=>{const n=ft(i,e,a);if(n<=t)return{lines:[i],width:n};if(!(i.indexOf(" ")>-1)){if(i.length<=1)throw new Error(`Character ${i} is wider than region`);const d=Math.floor(i.length/2),u=Ie(i.slice(0,d),t,e,a),A=Ie(i.slice(d),t,e,a);return{lines:[...u.lines,...A.lines],width:Math.max(u.width,A.width)}}const s=i.split(" "),o=[];let l=-1/0,c=0;for(;c<s.length;){const d=s[c];if(ft(d,e,a)>t){const u=Ie(d,t,e,a);o.push(...u.lines),l=Math.max(l,u.width),c++}else{const u=[d];l=Math.max(l,ft(d,e,a));let A=c+1,h=!0;for(;A<s.length&&h;){const g=s[A],p=ft(`${u.join(" ")} ${g}`,e,a);p<=t?(u.push(g),l=Math.max(l,p),A++):h=!1}o.push(u.join(" ")),c=A}}if(l<0)throw new Error(`No max width calculated for text: ${o}.`);return{lines:o,width:l}},Co=(i,t,e,a,n,r)=>{const s=(r??ui)*t.getApproximateHeight(),o=1/e.unitsPerEm,l=ci(i,o,t),c=i.length*s*o,d=a/l,u=n/c;return Math.min(u,d)},wo=(i,t,e,a)=>{const n=vt(t.fontData.assetUrl),r=n.getFont(),s=t.fontSize/r.unitsPerEm;if(!e)return mn(t,i,t.fontSize,s,n,a);let o;if(t.text?o=t.text.split(`
1364
+ `):o=t.input?.split(`
1365
+ `)??[""],e.input===i&&t.width===e.width&&t.height===e.height&&t.lineHeight===e.lineHeight)return{lines:o,requiredHeight:t.height,requiredWidth:xe(o,t.width,s,n),fontSize:t.fontSize};const l=t.width!==e.width!=(t.height!==e.height);return t.lineHeight===e.lineHeight&&!l&&e.input===i?{lines:o,requiredHeight:t.height,requiredWidth:xe(o,t.width,s,n),fontSize:Co(o,n,r,t.width,t.height,a)}:mn(t,i,t.fontSize,s,n,a)},yo=(i,t,e,a,n)=>{const s=vt(t.assetUrl).getFont();let o={...i};const l={...i},c=ci(a,e/s.unitsPerEm,vt(t.assetUrl));return c&&c<o.width&&(l.width=c,n==="left"?(l.left+=Math.sin(o.rotation*Math.PI/360)*(o.width-c),l.top+=Math.sin(o.rotation*Math.PI/180)*(c-o.width)/2):n==="right"?l.left+=o.width-c:l.left+=(o.width-c)/2,a&&vo(a,a).every(([d,u])=>d===u)&&(o=l)),o},sa=1,ft=(i,t,e)=>{let a=0;const n=e.getGlyphs(i);return n.forEach((r,s)=>{if(r.advanceWidth&&(a+=r.advanceWidth),s<n.length-1){const o=e.getKerningValue(r,n[s+1]);a+=o||0}}),a*=t,a},So=(i,t,e)=>{let a=0;const n=e.getGlyphs(i);return n.forEach((r,s)=>{if(r.advanceWidth&&(a=Math.max(a,r.advanceWidth)),s<n.length-1){const o=e.getKerningValue(r,n[s+1]);a=Math.max(a,o||0)}}),a*=t,a},ci=(i,t,e)=>{let a=0;return i.forEach(n=>{a=Math.max(a,ft(n,t,e))}),a},pn={stripControlCharacters:!0,vertical:!1,uppercase:!1},Fe=(i,t=pn)=>{const e={...pn,...t};let a=i||"";return e.stripControlCharacters&&(a=a.replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,"")),e.uppercase&&(a=a.toUpperCase()),e.vertical&&(a=a.split("").join(`
1366
+ `)),a},vo=(i,t)=>i.map((e,a)=>[e,t[a]]),Eo=(i="center",t=!1)=>t?"center":i,di=i=>i==="left"?"start":i==="right"?"end":"middle",Ae=(i,t,e)=>i.fontData?{...i,...(()=>{if(i.algorithm===Bt.Traditional){const n=wo(t,i,e,i.lineHeight);return{text:n.lines.join(`
1367
+ `),height:n.requiredHeight,width:n.requiredWidth,fontSize:n.fontSize,input:t}}else return{text:t}})()}:i,ui=1.1;function Mt(i,t){return Ai(i,t.getTemplatingContext())}function Ai(i,t){try{i=Er.compile(i)(t)}catch(e){console.error("failed to render templated text",e)}return i}const bo=i=>{const e=(i.rotation||0)*Math.PI/180,a=Math.cos(e),n=-Math.sin(e),r=`text-path-${i.id}`,s=`text-fill-${i.id}`,o=i.x+(i.curved?0:i.width/2),l=i.y+(i.curved?0:i.height/2),c=Ai(i.text||"",i._renderingConfiguration?.templatingContext),d=c.split(`
1368
+ `),u=i.strokeColor?.browserValue&&i.strokeThickness?i.strokeColor?.browserValue:void 0,A=i.strokeColor?.browserValue&&i.strokeThickness?i.strokeThickness:void 0;if(i.curved&&!i.paths||!i.fontData)return null;const h=()=>i.textFillImage?`url("#${s}")`:i._renderingConfiguration?.spotColors&&i.fillSpotColorDefinition?`${i.fill} ${Hn(i.fillSpotColorDefinition)}`:i.fill;return P.jsxs(P.Fragment,{children:[P.jsxs("defs",{children:[i.textFillImage&&P.jsx("pattern",{id:s,patternUnits:"userSpaceOnUse",width:i.textFillImage.scale*i.textFillImage.width,height:i.textFillImage.scale*i.textFillImage.height,x:0,y:0,children:P.jsx("image",{href:i.textFillImage.src,xlinkHref:i.textFillImage.src,width:i.textFillImage.scale*i.textFillImage.width,height:i.textFillImage.scale*i.textFillImage.height})}),P.jsx("style",{type:"text/css",dangerouslySetInnerHTML:{__html:`
1369
1369
  @font-face {
1370
1370
  font-family: '${i.fontData.name}';
1371
1371
  src: url('${i.fontData.assetUrl}') format('truetype');
1372
1372
  }
1373
- `}}),i.curved&&i.paths?P.jsx("path",{id:r,d:i.paths[0]}):void 0]}),i._renderingConfiguration?.debug?P.jsx("rect",{stroke:"blue",fill:"none",x:i.x,y:i.y,width:i.width,height:i.height}):void 0,P.jsx("g",{mask:i.stepName?void 0:i.mask,children:P.jsx("g",{transform:`matrix(${a}, ${-n}, ${n}, ${a}, ${s}, ${l})`,children:P.jsx("text",{xmlSpace:"preserve",fontFamily:`'${i.fontData.name}'`,fontSize:i.fontSize,fontStyle:"normal",fontWeight:"normal",fill:h(),style:{whiteSpace:"pre",userSelect:"none"},stroke:u,strokeWidth:A,children:i.curved?P.jsx(Vs,{text:c,curvedPathId:r,align:i.align}):d.map((g,p)=>P.jsx(Us,{align:i.vertical?"center":i.align,fontSize:i.fontSize,thisLineIdx:p,amountLines:d.length,text:g,textboxHeight:i.height,textboxWidth:i.width,lineHeight:i.lineHeight,vertical:i.vertical,verticalAlign:i.verticalAlign,fontData:i.fontData},p))})})})]})},Us=i=>{const t=()=>{if(i.lineHeight!==void 0)return i.lineHeight*i.fontSize;const n=bt(i.fontData.assetUrl),r=n.getFont(),o=i.fontSize/r.unitsPerEm;return n.getApproximateHeight()*o},e=()=>i.align==="left"?-i.textboxWidth/2:i.align==="right"?i.textboxWidth/2:0,a=()=>{const n=t(),r=i.textboxHeight/2;if(i.verticalAlign==="top")return-r+i.fontSize*3/4+i.thisLineIdx*n;if(i.verticalAlign==="bottom"){const s=i.amountLines-1-i.thisLineIdx;return r-i.fontSize/4-s*n}const o=(i.amountLines-1)/2;return(i.thisLineIdx-o)*n+i.fontSize/4};return P.jsx("tspan",{textAnchor:vi(i.align),x:e(),y:`${a()}px`,children:i.text})},Vs=i=>{const t=`#${i.curvedPathId}`,e=()=>i.align==="left"?"0%":i.align==="right"?"100%":"50%";return P.jsx("textPath",{startOffset:e(),textAnchor:vi(i.align),href:t,xlinkHref:t,children:i.text})},Ls=i=>{if(i.cachedObjectURL&&!i._renderingConfiguration?.omitCachedFields)return P.jsx(Ci,{id:i.id,src:i.cachedObjectURL,x:i.x,y:i.y,width:i.width,height:i.height,rotation:i.rotation,preserveAspectRatio:"none",immutable:i.immutable,mask:i.stepName?void 0:i.mask});const t=i.rotation||0,e=Et(t),a=Math.cos(e),n=-Math.sin(e),r=`
1373
+ `}}),i.curved&&i.paths?P.jsx("path",{id:r,d:i.paths[0]}):void 0]}),i._renderingConfiguration?.debug?P.jsx("rect",{stroke:"blue",fill:"none",x:i.x,y:i.y,width:i.width,height:i.height}):void 0,P.jsx("g",{mask:i.stepName?void 0:i.mask,children:P.jsx("g",{transform:`matrix(${a}, ${-n}, ${n}, ${a}, ${o}, ${l})`,children:P.jsx("text",{xmlSpace:"preserve",fontFamily:`'${i.fontData.name}'`,fontSize:i.fontSize,fontStyle:"normal",fontWeight:"normal",fill:h(),style:{whiteSpace:"pre",userSelect:"none"},stroke:u,strokeWidth:A,children:i.curved?P.jsx(Bo,{text:c,curvedPathId:r,align:i.align}):d.map((g,p)=>P.jsx(Io,{align:i.vertical?"center":i.align,fontSize:i.fontSize,thisLineIdx:p,amountLines:d.length,text:g,textboxHeight:i.height,textboxWidth:i.width,lineHeight:i.lineHeight,vertical:i.vertical,verticalAlign:i.verticalAlign,fontData:i.fontData},p))})})})]})},Io=i=>{const t=()=>{if(i.lineHeight!==void 0)return i.lineHeight*i.fontSize;const n=vt(i.fontData.assetUrl),r=n.getFont(),s=i.fontSize/r.unitsPerEm;return n.getApproximateHeight()*s},e=()=>i.align==="left"?-i.textboxWidth/2:i.align==="right"?i.textboxWidth/2:0,a=()=>{const n=t(),r=i.textboxHeight/2;if(i.verticalAlign==="top")return-r+i.fontSize*3/4+i.thisLineIdx*n;if(i.verticalAlign==="bottom"){const o=i.amountLines-1-i.thisLineIdx;return r-i.fontSize/4-o*n}const s=(i.amountLines-1)/2;return(i.thisLineIdx-s)*n+i.fontSize/4};return P.jsx("tspan",{textAnchor:di(i.align),x:e(),y:`${a()}px`,children:i.text})},Bo=i=>{const t=`#${i.curvedPathId}`,e=()=>i.align==="left"?"0%":i.align==="right"?"100%":"50%";return P.jsx("textPath",{startOffset:e(),textAnchor:di(i.align),href:t,xlinkHref:t,children:i.text})},Po=i=>{if(i.cachedObjectURL&&!i._renderingConfiguration?.omitCachedFields)return P.jsx(si,{id:i.id,src:i.cachedObjectURL,x:i.x,y:i.y,width:i.width,height:i.height,rotation:i.rotation,preserveAspectRatio:"none",immutable:i.immutable,mask:i.stepName?void 0:i.mask});const t=i.rotation||0,e=St(t),a=Math.cos(e),n=-Math.sin(e),r=`
1374
1374
  matrix(1, 0, 0, 1, ${i.x}, ${i.y})
1375
1375
  matrix(1, 0, 0, 1, ${i.width/2}, ${i.height/2})
1376
1376
  matrix(${a}, ${-n}, ${n}, ${a}, 0, 0)
1377
1377
  matrix(1, 0, 0, 1, ${-i.width/2}, ${-i.height/2})
1378
- `;if(!i.svg)throw new Error(`Illustration element ${i.id} (stepName ${i.stepName}) lacked svg from src ${i.src} at render time.`);return P.jsx("g",{mask:i.stepName?void 0:i.mask,children:P.jsx("g",{transform:r,dangerouslySetInnerHTML:{__html:Ga(i.svg,i.width,i.height,i.colors,i._renderingConfiguration?.spotColors)}})})};class Ii{constructor(){this.id=N(),this.stateCallbacks=[],this.prevCommands=[],this.nextCommands=[]}registerStateCallback(t){this.stateCallbacks.push(t)}unregisterStateCallback(t){this.stateCallbacks.filter(e=>e!==t)}getState(){return this.state}runStateCallbacks(){this.stateCallbacks.forEach(t=>t())}apply(t,e){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.nextCommands=[],e||this.prevCommands.push(t)}undo(){if(!this.state)return;const t=this.prevCommands.pop();if(!t)return;const e=t.undo();this.state={...this.state,transaction:e},this.nextCommands.push(t),this.runStateCallbacks()}redo(){if(!this.state)return;const t=this.nextCommands.pop();t&&(this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.prevCommands.push(t))}flattenSequence(t,e){const n=this.prevCommands.filter(r=>r.sequenceId===t).pop();n&&(this.prevCommands=this.prevCommands.filter(r=>r.sequenceId!==t),n?.overrideOldState(e),this.prevCommands.push(n))}getLayoutById(t){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const e=this.state.transaction?.layouts?.[t],a=e?.layout;if(!a)throw new Error(`No layout: ${t}`);const n=[...e?.elements||[]];return this.getLayoutDataWithState(a,n)}getAllLayouts(){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const t=[...Object.keys(this.state.transaction?.layouts)];return[...new Set(t)].map(a=>this.getLayoutById(a))}getLayoutDataWithState(t,e){return{layoutState:{layout:t,elements:e},getComponentWithProps:a=>Xe(t,e,a)}}initialize(t,e){if(e){this.state={transaction:e};return}let a={serializableWorkflow:{steps:[]},layouts:{}};t.forEach(n=>{a=new Ja(n).apply(a)}),this.runStateCallbacks(),this.state={transaction:a}}commandReducer(t,e){const a=t.transaction||{layouts:{},serializableWorkflow:{steps:[]}};return{...t,transaction:e.apply(a)}}}const Bi=i=>i.type===D.Image?P.jsx(Ci,{...i},i.id):i.type===D.Frame?P.jsx(Ps,{...i},i.id):i.type===D.Illustration?P.jsx(Ls,{...i},i.id):i.type===D.Textbox?P.jsx($s,{...i},i.id):i.type===D.Group?P.jsx(wi,{...i},i.id):null,Xe=(i,t,e)=>{const a=e.renderingConfiguration,n=a?.removeExcludedElements?t.filter(r=>!r.excludeFromExport):t;return P.jsx(gs,{preserveAspectRatio:void 0,elements:n,backgroundColor:i.transparentBackground?void 0:e.backgroundColor?e.backgroundColor:"white",width:e.width||i.width,height:e.height||i.height,viewBox:a?.region?{x:a.region.left,y:a.region.top,width:a.region.width,height:a.region.height}:{x:0,y:0,width:i.width,height:i.height},configuration:a,outlineArea:e.outlineArea,maxHeight:e.maxHeight,maxWidth:e.maxWidth,position:e.position,borderRadius:e.borderRadius,outlineColor:e.outlineColor})};function ja(i){return i.sort((t,e)=>{const a=t.layer||0,n=e.layer||0;if(a<n)return-1;if(a>n)return 1;const r=t.layerIndex||0,o=e.layerIndex||0;return r<o?-1:r>o?1:0})}const ht=new Map,Mt=new Map,da=new Map,Pi=async(i,t)=>{if(!t){if(!i)throw new Error("No region or src supplied. Cannot construct frame!");return xa(i)}return et(t)},xa=i=>{const t=i.width,e=i.height;return`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${t} ${e}'>
1378
+ `;if(!i.svg)throw new Error(`Illustration element ${i.id} (stepName ${i.stepName}) lacked svg from src ${i.src} at render time.`);return P.jsx("g",{mask:i.stepName?void 0:i.mask,children:P.jsx("g",{transform:r,dangerouslySetInnerHTML:{__html:$a(i.svg,i.width,i.height,i.colors,i._renderingConfiguration?.spotColors)}})})};class hi{constructor(){this.id=N(),this.stateCallbacks=[],this.prevCommands=[],this.nextCommands=[]}registerStateCallback(t){this.stateCallbacks.push(t)}unregisterStateCallback(t){this.stateCallbacks.filter(e=>e!==t)}getState(){return this.state}runStateCallbacks(){this.stateCallbacks.forEach(t=>t())}apply(t,e){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.nextCommands=[],e||this.prevCommands.push(t)}undo(){if(!this.state)return;const t=this.prevCommands.pop();if(!t)return;const e=t.undo();this.state={...this.state,transaction:e},this.nextCommands.push(t),this.runStateCallbacks()}redo(){if(!this.state)return;const t=this.nextCommands.pop();t&&(this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.prevCommands.push(t))}flattenSequence(t,e){const n=this.prevCommands.filter(r=>r.sequenceId===t).pop();n&&(this.prevCommands=this.prevCommands.filter(r=>r.sequenceId!==t),n?.overrideOldState(e),this.prevCommands.push(n))}getLayoutById(t){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const e=this.state.transaction?.layouts?.[t],a=e?.layout;if(!a)throw new Error(`No layout: ${t}`);const n=[...e?.elements||[]];return this.getLayoutDataWithState(a,n)}getAllLayouts(){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const t=[...Object.keys(this.state.transaction?.layouts)];return[...new Set(t)].map(a=>this.getLayoutById(a))}getLayoutDataWithState(t,e){return{layoutState:{layout:t,elements:e},Component:ri,getComponentWithProps:a=>Je(t,e,a)}}initialize(t,e){if(e){this.state={transaction:e};return}let a={serializableWorkflow:{steps:[]},layouts:{}};t.forEach(n=>{a=new qa(n).apply(a)}),this.runStateCallbacks(),this.state={transaction:a}}commandReducer(t,e){const a=t.transaction||{layouts:{},serializableWorkflow:{steps:[]}};return{...t,transaction:e.apply(a)}}}const gi=i=>i.type===D.Image?P.jsx(si,{...i},i.id):i.type===D.Frame?P.jsx(ho,{...i},i.id):i.type===D.Illustration?P.jsx(Po,{...i},i.id):i.type===D.Textbox?P.jsx(bo,{...i},i.id):i.type===D.Group?P.jsx(oi,{...i},i.id):null,Je=(i,t,e)=>{const a=e.renderingConfiguration,n=a?.removeExcludedElements?t.filter(r=>!r.excludeFromExport):t;return P.jsx(ri,{preserveAspectRatio:void 0,elements:n,backgroundColor:i.transparentBackground?void 0:e.backgroundColor?e.backgroundColor:"white",width:e.width||i.width,height:e.height||i.height,viewBox:a?.region?{x:a.region.left,y:a.region.top,width:a.region.width,height:a.region.height}:{x:0,y:0,width:i.width,height:i.height},configuration:a,outlineArea:e.outlineArea,maxHeight:e.maxHeight,maxWidth:e.maxWidth,position:e.position,borderRadius:e.borderRadius,outlineColor:e.outlineColor})};function Ua(i){return i.sort((t,e)=>{const a=t.layer||0,n=e.layer||0;if(a<n)return-1;if(a>n)return 1;const r=t.layerIndex||0,s=e.layerIndex||0;return r<s?-1:r>s?1:0})}const ut=new Map,Dt=new Map,oa=new Map,mi=async(i,t)=>{if(!t){if(!i)throw new Error("No region or src supplied. Cannot construct frame!");return Ea(i)}return tt(t)},Ea=i=>{const t=i.width,e=i.height;return`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${t} ${e}'>
1379
1379
  <path id="target-path" d='M0 0 h ${t} v ${e} h ${-t} Z' />
1380
1380
  </svg>
1381
- `},zs=async(i,t)=>{if(!t)return;const e=await I.getDefaultVariant(t,i.frameVariantId);if(!e)throw new Error(`No variant with ID: ${i.frameVariantId}`);if(!e.asset)throw new Error(`No asset for variant with ID: ${i.frameVariantId}`);return e},me=async i=>{if(da.has(i))return da.get(i);const e=(async()=>{if(Mt.has(i))return Mt.get(i);await new Promise(A=>setTimeout(A,0));const n=ct().parseFromString(i,"image/svg+xml"),r=n.querySelector("svg");if(!r)throw new Error("Malformed frame SVG: <svg> tag not found");const o=r.getAttribute("viewBox");if(!o)throw new Error("SVG missing viewBox.");const s=o.split(" "),l=parseFloat(s[3])||1,c=parseFloat(s[2])||1,d=n.getElementById("target-path"),u=n.getElementsByClassName("st0").item(0);if(d){const A=d.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Mt.set(A,h),h}if(u){const A=u.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Mt.set(A,h),h}throw new Error("Malformed frame SVG")})();return da.set(i,e),e},Ha=(i,t,e,a)=>{const n=t.width/t.height,r=i.width/i.height;let o;a?r>n?o=t.height/i.height:o=t.width/i.width:r>n?o=t.width/i.width:o=t.height/i.height,e?.scale!==void 0&&(o*=e?.scale);const s=t.width/2,l=t.height/2,c=s-i.width/2*o,d=e?.left||c,u=l-i.height/2*o,A=e?.top||u;return{x:d,y:A,zoom:o}},Fa=async i=>{if(ht.has(i))return ht.get(i);if(i.startsWith("data:image/svg+xml")){const e=Rr.dataUriToBuffer(i),a=new TextDecoder().decode(e.buffer),n=Ya(a),r={src:i,width:n.width,height:n.height,aspect:n.width/n.height};return ht.set(i,r),r}if((i.split(".").pop()?.toLowerCase()??"")==="svg"){const e=await Wa(i),a=e.width,n=e.height,r={src:i,width:a,height:n,aspect:a/n};return ht.set(i,r),r}else{const e=await ze(i,!0),a=await ue(e),n={src:i,width:a.width,height:a.height,aspect:a.width/a.height};return ht.set(i,n),n}},Wa=async i=>{const t=await et(i);return Ya(t)},En=i=>i.endsWith("mm")?Number(i.replace("mm",""))*3.7795275591:i.endsWith("px")?Number(i.replace("px","")):Number(i),Ya=i=>{const a=ct().parseFromString(i,"image/svg+xml").querySelector("svg");if(!a)throw new Error("No svg tag found, this svg must be malformed!");const n=a.getAttribute("viewBox"),r=a.getAttribute("width"),o=a.getAttribute("height"),s=o&&r?[0,0,En(r),En(o)]:n?.split(" ").map(l=>Number(l));if(!s)throw new Error("No viewbox or width/height values detected on SVG file!");return{width:s[2],height:s[3]}},jt=(i,t)=>{const e=i.layoutState.elements.filter(n=>n.layer===t),a=Math.max(...e.map(n=>n.layerIndex).filter(n=>n!==void 0));return Math.max(a,0)+1},xi=async i=>new Promise(t=>{et(i).then(e=>{t(e)}).catch(e=>console.error(e))}),ua=new Map,se=async i=>{if(ua.has(i))return ua.get(i);const t=async n=>new Promise((r,o)=>{try{if(!(!!URL&&!!URL.createObjectURL))throw new Error("Environment incapable of generating ObjectURL");n.toBlob(l=>{if(!l)throw n.width===0||n.height===0?new Error(`Canvas dimensions are invalid (${n.width},${n.height})`):n.width*n.height>=268435456?new Error(`Canvas dimensions exceed device limit (${n.width},${n.height})`):new Error("Couldn't generate object URL for Illustration, the blob was undefined!");r(URL.createObjectURL(l))})}catch(s){o(s)}}),a=(async()=>{const o=ct().parseFromString(i,"image/svg+xml").firstElementChild;if(!o)throw new Error("Failed to read SVG");const l=It().serializeToString(o),c=vt(),d=c.getContext("2d"),u=await $a.Pith.from(d,l,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:vt,createImage:de,DOMParser:qa(),fetch:it}),A=o.getAttribute("width"),h=o.getAttribute("height"),g=2048;if(h&&A){const p=parseFloat(h),C=parseFloat(A)/p;C>1?u.resize(g,g/C):u.resize(g*C,g)}else u.resize(g,g);return await u.render(),await t(c)})();return ua.set(i,a),a},Ht=async(i,t,e,a)=>{const n=i.layoutState.layout.useEditableArea&&i.layoutState.layout.editableArea||{width:i.layoutState.layout.width,height:i.layoutState.layout.height,x:0,y:0},r=n.width<n.height?n.width:n.height,o=i.layoutState.layout.useEditableArea?r/1.3:r/2,s={top:n.y+n.height/2-o/2,left:n.x+n.width/2-o/2,width:o,height:o,rotation:0,panelId:i.layoutState.layout.panelId};if(e&&t===D.Illustration){const l=await rt(await xi(e)),A=ct().parseFromString(l.svg,"image/svg+xml").firstElementChild.getAttribute("viewBox");if(!A)throw new Error("SVG missing viewBox.");const h=s.height,g=A.split(" "),p=parseFloat(g[2])||1,m=parseFloat(g[3])||1,C=p/m;s.height=s.width/C,s.top+=(h-s.height)/2}if(e&&t===D.Image){const l=s.height,c=await ze(e),d=await ue(c),u=d.width/d.height;s.height=s.width/u,s.top+=(l-s.height)/2}if(e&&t===D.Textbox&&a?.text&&a?.fontScale){await Ft(e);const l=bt(e),c=wt(a.text,a?.fontScale,l);s.width=Math.min(c,n.width*.85),s.left=n.x+n.width/2-s.width/2}return s};class qs{static async getFrame(t,e){const a=await Pi(e.region,e.src),n=await me(a),r=e.region||await Ht(t,D.Frame);return{id:N(),x:r.left,y:r.top,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||jt(t,r.layer||0),rotation:r.rotation,scaleX:r.width/n.width,scaleY:r.height/n.height,path:n.path,dataWidth:n.width,dataHeight:n.height,type:D.Frame,disablePlaceholder:e.configuration.disablePlaceholder,focalBlur:e.configuration.focalBlur,focalBlurStrength:e.configuration.focalBlurStrength,focalBlurRadius:e.configuration.focalBlurRadius,forceImageCover:e.configuration.forceImageCover,pattern:void 0,immutable:r.immutable}}static async getImage(t,e){const a=e.region||await Ht(t,D.Image,e.src);return{id:N(),src:e.src,type:D.Image,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||jt(t,a.layer||0),immutable:a.immutable,preserveAspectRatio:"none"}}static async getTextbox(t,e){const{configuration:a,fontSrc:n,designInputStep:r}=e,o=await Ft(n),s={assetUrl:n,name:o.names.fullName.en},l=r?.text||a.defaultText||"",c=a.replaceableText?a.replaceableText.replace("{{}}",l):l,d=Me(c,{vertical:a.vertical,uppercase:a.uppercase}),u=e.region||await Ht(t,D.Textbox,n,{text:d,fontScale:a.size?a.size/o.unitsPerEm:void 0}),A=ge({id:N(),type:D.Textbox,x:u.left,y:u.top,width:u.width,height:u.height,align:Rs(a.textAlign,a.vertical),curved:a.curved,fill:r?.color||a.colour||"#000000",fontData:s,layer:u.layer||0,layerIndex:u.layerIndex||jt(t,u.layer||0),paths:a.paths,rotation:u.rotation,vertical:a.vertical,verticalAlign:a.verticalAlign||"middle",algorithm:xt.Traditional,fontSize:a.size||Math.max(Math.round(u.height*.025),1),text:d,input:l},d),h=Ns({...u,height:A.height},s,A.fontSize,A?.text?.split(`
1381
+ `},xo=async(i,t)=>{if(!t)return;const e=await I.getDefaultVariant(t,i.frameVariantId);if(!e)throw new Error(`No variant with ID: ${i.frameVariantId}`);if(!e.asset)throw new Error(`No asset for variant with ID: ${i.frameVariantId}`);return e},he=async i=>{if(oa.has(i))return oa.get(i);const e=(async()=>{if(Dt.has(i))return Dt.get(i);await new Promise(A=>setTimeout(A,0));const n=ot().parseFromString(i,"image/svg+xml"),r=n.querySelector("svg");if(!r)throw new Error("Malformed frame SVG: <svg> tag not found");const s=r.getAttribute("viewBox");if(!s)throw new Error("SVG missing viewBox.");const o=s.split(" "),l=parseFloat(o[3])||1,c=parseFloat(o[2])||1,d=n.getElementById("target-path"),u=n.getElementsByClassName("st0").item(0);if(d){const A=d.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Dt.set(A,h),h}if(u){const A=u.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Dt.set(A,h),h}throw new Error("Malformed frame SVG")})();return oa.set(i,e),e},Va=(i,t,e,a)=>{const n=t.width/t.height,r=i.width/i.height;let s;a?r>n?s=t.height/i.height:s=t.width/i.width:r>n?s=t.width/i.width:s=t.height/i.height,e?.scale!==void 0&&(s*=e?.scale);const o=t.width/2,l=t.height/2,c=o-i.width/2*s,d=e?.left||c,u=l-i.height/2*s,A=e?.top||u;return{x:d,y:A,zoom:s}},ba=async i=>{if(ut.has(i))return ut.get(i);if(i.startsWith("data:image/svg+xml")){const e=br.dataUriToBuffer(i),a=new TextDecoder().decode(e.buffer),n=za(a),r={src:i,width:n.width,height:n.height,aspect:n.width/n.height};return ut.set(i,r),r}if((i.split(".").pop()?.toLowerCase()??"")==="svg"){const e=await La(i),a=e.width,n=e.height,r={src:i,width:a,height:n,aspect:a/n};return ut.set(i,r),r}else{const e=await Ue(i,!0),a=await ce(e),n={src:i,width:a.width,height:a.height,aspect:a.width/a.height};return ut.set(i,n),n}},La=async i=>{const t=await tt(i);return za(t)},fn=i=>i.endsWith("mm")?Number(i.replace("mm",""))*3.7795275591:i.endsWith("px")?Number(i.replace("px","")):Number(i),za=i=>{const a=ot().parseFromString(i,"image/svg+xml").querySelector("svg");if(!a)throw new Error("No svg tag found, this svg must be malformed!");const n=a.getAttribute("viewBox"),r=a.getAttribute("width"),s=a.getAttribute("height"),o=s&&r?[0,0,fn(r),fn(s)]:n?.split(" ").map(l=>Number(l));if(!o)throw new Error("No viewbox or width/height values detected on SVG file!");return{width:o[2],height:o[3]}},qt=(i,t)=>{const e=i.layoutState.elements.filter(n=>n.layer===t),a=Math.max(...e.map(n=>n.layerIndex).filter(n=>n!==void 0));return Math.max(a,0)+1},pi=async i=>new Promise(t=>{tt(i).then(e=>{t(e)}).catch(e=>console.error(e))}),la=new Map,re=async i=>{if(la.has(i))return la.get(i);const t=async n=>new Promise((r,s)=>{try{if(!(!!URL&&!!URL.createObjectURL))throw new Error("Environment incapable of generating ObjectURL");n.toBlob(l=>{if(!l)throw n.width===0||n.height===0?new Error(`Canvas dimensions are invalid (${n.width},${n.height})`):n.width*n.height>=268435456?new Error(`Canvas dimensions exceed device limit (${n.width},${n.height})`):new Error("Couldn't generate object URL for Illustration, the blob was undefined!");r(URL.createObjectURL(l))})}catch(o){s(o)}}),a=(async()=>{const s=ot().parseFromString(i,"image/svg+xml").firstElementChild;if(!s)throw new Error("Failed to read SVG");const l=Et().serializeToString(s),c=yt(),d=c.getContext("2d"),u=await Ma.Pith.from(d,l,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:yt,createImage:le,DOMParser:Ra(),fetch:nt}),A=s.getAttribute("width"),h=s.getAttribute("height"),g=2048;if(h&&A){const p=parseFloat(h),C=parseFloat(A)/p;C>1?u.resize(g,g/C):u.resize(g*C,g)}else u.resize(g,g);return await u.render(),await t(c)})();return la.set(i,a),a},Gt=async(i,t,e,a)=>{const n=i.layoutState.layout.useEditableArea&&i.layoutState.layout.editableArea||{width:i.layoutState.layout.width,height:i.layoutState.layout.height,x:0,y:0},r=n.width<n.height?n.width:n.height,s=i.layoutState.layout.useEditableArea?r/1.3:r/2,o={top:n.y+n.height/2-s/2,left:n.x+n.width/2-s/2,width:s,height:s,rotation:0,panelId:i.layoutState.layout.panelId};if(e&&t===D.Illustration){const l=await it(await pi(e)),A=ot().parseFromString(l.svg,"image/svg+xml").firstElementChild.getAttribute("viewBox");if(!A)throw new Error("SVG missing viewBox.");const h=o.height,g=A.split(" "),p=parseFloat(g[2])||1,m=parseFloat(g[3])||1,C=p/m;o.height=o.width/C,o.top+=(h-o.height)/2}if(e&&t===D.Image){const l=o.height,c=await Ue(e),d=await ce(c),u=d.width/d.height;o.height=o.width/u,o.top+=(l-o.height)/2}if(e&&t===D.Textbox&&a?.text&&a?.fontScale){await Pt(e);const l=vt(e),c=ft(a.text,a?.fontScale,l);o.width=Math.min(c,n.width*.85),o.left=n.x+n.width/2-o.width/2}return o};class Fo{static async getFrame(t,e){const a=await mi(e.region,e.src),n=await he(a),r=e.region||await Gt(t,D.Frame);return{id:N(),x:r.left,y:r.top,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||qt(t,r.layer||0),rotation:r.rotation,scaleX:r.width/n.width,scaleY:r.height/n.height,path:n.path,dataWidth:n.width,dataHeight:n.height,type:D.Frame,disablePlaceholder:e.configuration.disablePlaceholder,focalBlur:e.configuration.focalBlur,focalBlurStrength:e.configuration.focalBlurStrength,focalBlurRadius:e.configuration.focalBlurRadius,forceImageCover:e.configuration.forceImageCover,pattern:void 0,immutable:r.immutable}}static async getImage(t,e){const a=e.region||await Gt(t,D.Image,e.src);return{id:N(),src:e.src,type:D.Image,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||qt(t,a.layer||0),immutable:a.immutable,preserveAspectRatio:"none"}}static async getTextbox(t,e){const{configuration:a,fontSrc:n,designInputStep:r}=e,s=await Pt(n),o={assetUrl:n,name:s.names.fullName.en},l=r?.text||a.defaultText||"",c=a.replaceableText?a.replaceableText.replace("{{}}",l):l,d=Fe(c,{vertical:a.vertical,uppercase:a.uppercase}),u=e.region||await Gt(t,D.Textbox,n,{text:d,fontScale:a.size?a.size/s.unitsPerEm:void 0}),A=Ae({id:N(),type:D.Textbox,x:u.left,y:u.top,width:u.width,height:u.height,align:Eo(a.textAlign,a.vertical),curved:a.curved,fill:r?.color||a.colour||"#000000",fontData:o,layer:u.layer||0,layerIndex:u.layerIndex||qt(t,u.layer||0),paths:a.paths,rotation:u.rotation,vertical:a.vertical,verticalAlign:a.verticalAlign||"middle",algorithm:Bt.Traditional,fontSize:a.size||Math.max(Math.round(u.height*.025),1),text:d,input:l},d),h=yo({...u,height:A.height},o,A.fontSize,A?.text?.split(`
1382
1382
  `)||[],A.align);return{...A,x:h.left,y:h.top+(u.height-h.height)/2,width:h.width,height:h.height}}static async getShape(t,e){const a=`
1383
1383
  <svg
1384
1384
  xmlns="http://www.w3.org/2000/svg"
@@ -1399,7 +1399,7 @@
1399
1399
  fill="${e.color}"
1400
1400
  />
1401
1401
  </svg>
1402
- `,n={};n["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Ht(t,D.Illustration),o=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:n,id:o,svg:a,type:D.Illustration,y:r.top,x:r.left,rotation:r.rotation,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||jt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Ht(t,D.Illustration,e.src),n=await rt(await xi(e.src)),r=await se(n.svg),o=N();return{cachedObjectURL:r,stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:n.colors,id:o,src:e.src,svg:n.svg,type:D.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||jt(t,a.layer||0),immutable:a.immutable}}}class j extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,j.prototype)}}const V=(i,t)=>_(i,t).elements.find(n=>n.id===i),_=(i,t)=>{const e=Object.values(t).find(a=>a.elements.some(n=>n.id===i));if(!e)throw new j;return e},tt=(i,t)=>{const e=[...t.elements.filter(n=>n.id!==i.id),i],a=ja(e);return{layout:t.layout,elements:a,modificationID:N()}},Da=async i=>{const t=[...Object.keys(i.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const n=e[a],r=i.layouts[n];await Promise.all(r.elements.map(async o=>{if(o.type==="illustration"){const s=o;if(s.src&&!s.svg){const l=await et(s.src),c=await rt(l);s.svg=Ga(c.svg,s.width,s.height,s.colors)}}else if(o.type==="frame"){const s=o;if(s.pattern?.colors&&s.pattern?.src){const l=await et(s.pattern?.src),c=await rt(l);s.pattern.svg=c.svg}}isNaN(o.x)&&(o.x=0),isNaN(o.y)&&(o.y=0),isNaN(o.width)&&(o.width=0),isNaN(o.height)&&(o.height=0),isNaN(o.rotation)&&(o.rotation=0)}))}for(const a in i.layouts){const n=i.layouts[a].elements.filter(o=>o.type===D.Illustration);for(let o=0;o<n.length;++o){const s=n[o];if(s.src&&s.svg)try{s.cachedObjectURL=await se(s.svg)}catch(l){console.log(l)}}const r=i.layouts[a].elements.filter(o=>o.type===D.Textbox);for(let o=0;o<r.length;++o){const s=r[o];s.fontData?.assetUrl&&await Ft(s.fontData.assetUrl)}}};class ${undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class bn extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Gs extends ${constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,x:this.x,y:this.y},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class js extends ${constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,rotation:this.angle},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Hs extends ${constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const o=a;o.scaleX=o.scaleX*this.width/e.width,o.scaleY=o.scaleY*this.height/e.height}else if(e.type==="textbox"){const o=a,s=(!o.algorithm||o.algorithm===xt.Autosize?o.text:o.input)??"";a=ge(o,s,e)}const n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class U extends ${constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Ja extends ${constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:N()}}}}}class H extends ${constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(s=>s.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const s=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,s)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:N()}}}}const n=e[e.length-1],r=n.productOverlay?n:null;r&&e.pop();let o;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)o=[...e,this.element].sort((s,l)=>s.layerIndex!==void 0&&l.layerIndex!==void 0?s.layerIndex-l.layerIndex:0);else{const s=this.assignIndex(this.element,e);this.element.layerIndex=s!==void 0?s:0,o=[...e,this.element]}return r&&o.push(r),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:N()}}}}assignIndex(t,e){if(e.length===0)return 0;const a=e.filter(n=>(n.layer||0)===(t.layer||0)).sort((n,r)=>(n.layerIndex||0)-(r.layerIndex||0))[e.length-1]?.layerIndex;return a!==void 0?a+1:0}}class Dt extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(r=>(r.elements.filter(s=>s.id!==this.id).length!==r.elements.length&&(e=!0),{...r,elements:r.elements.filter(s=>s.id!==this.id),modificationID:N()}));e||console.log(`Failed to delete element ${this.id}`);const n={};return a.forEach(r=>{n[r.layout.id]=r}),{...t,layouts:n}}}class Fi extends ${constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Aa extends ${constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,textFillImage:this.imageFill},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Di extends ${constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fontSize:this.size},n=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ge(a,r),n);return{...t,layouts:{...t.layouts,[n.layout.id]:o}}}}class ka extends ${constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fontData:this.fontData},n=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ge(a,r),n);return{...t,layouts:{...t.layouts,[n.layout.id]:o}}}}class ki extends ${constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,align:this.align},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Ws extends ${constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=_(this.id,Object.values(t.layouts)),a=e.elements.findIndex(s=>s.id===this.id),n=e.elements[a].pattern,r=[...e.elements];r.splice(a,1,{...e.elements[a],pattern:{...n,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const o={...e,elements:r,modificationID:N()};return{...t,layouts:{...t.layouts,[e.layout.id]:o}}}}class Ys extends ${constructor(t,e,a,n,r){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=n,this.thresholdSaturation=r}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Js extends ${constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,src:this.src},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Mi extends ${constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=_(e.id,Object.values(t.layouts)),n=tt(ge(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:n}}}}class ha extends ${constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Ma extends ${constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=e.colors||{},n=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:n?.spotColor,pmsValue:n?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:n?.spotColor,pmsValue:this.fill.pmsValue};const r={...e,colors:a},o=_(e.id,Object.values(t.layouts)),s=tt(r,o);return{...t,layouts:{...t.layouts,[o.layout.id]:s}}}}class Ks extends ${constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class _s extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(o=>o.elements.find(s=>s.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(o=>o.id===this.id);a.elements.push(a.elements.splice(n,1)[0]);const r=[...a.elements];return r.forEach((o,s)=>o.layerIndex=s),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Xs extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=Object.values(t.layouts).find(s=>s.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(s=>s.id===this.id);a.elements.splice(n,1),a.elements.unshift(e);const r=[...a.elements],o=r.splice(n,1)[0];return r.splice(n,0,o),r.forEach((s,l)=>s.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Zs extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),r=n+1,o=[...a.elements],s=o.splice(n,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class tl extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),r=n-1,o=[...a.elements],s=o.splice(n,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class In{constructor(t,e,a){this.processRegion=async n=>{const r=this.layouts.find(l=>l.panelId===n.panelId);if(!r)throw new J(n);let o="";if(this.configuration.type===E.ProductOverlay){let l="";if(this.product?.overlayImageUrl&&(l=this.product.overlayImageUrl),o=l,!l)throw new lt(this.configuration,"Couldn't find an asset for product overlay step")}const s=this.evaluateAssetType();if(s===D.Image){const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!l)throw new Error("Undefined raster silent step source");const c={stepName:this.configuration.stepName,id:N(),src:l,type:s,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,rotation:n.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:n},command:new H(c,r)}}else{const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:o,d=await rt(await(async()=>new Promise((A,h)=>{if(!l){h("Undefined vector silent step source");return}et(l,!0).then(g=>{A(g)}).catch(g=>console.error(g))}))()),u={stepName:this.configuration.stepName,id:N(),cachedObjectURL:await se(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,rotation:n.rotation,immutable:n.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:u.id,region:n},command:new H(u,r)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new lt(this.configuration,"Missing regions.");if(this.configuration.type===E.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===E.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new J(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===E.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?D.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),D.Illustration)}}const Ti=async i=>{const t=`${gt.getServicesApiUrl()}/shortener`;try{return(await(await it(t,{method:"POST",body:JSON.stringify({longUrl:i}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new Le("Failed to shorten URL, see console.")}};class Ni{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,n=3e3,r=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=r,this.poll()}}class el{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{const c=n?.storage?.videoShortUrl,d=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,n){const r=async()=>{const h=(await De([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new Ni(async()=>!!(await r()).link,async()=>{const p=await r();if(!p.link||!p.link)throw new Rt(p.asset);h({rel:"mpeg4",href:p.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new Dt(h.id)));const s=n.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(s+n.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([o]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new Le("Cannot create QR code, URL too long.");const d=await Ti(c);if(!n.data||!n.data.regions)throw new lt(n,"Missing regions.");const u=await this.regionElements(n),A=await this.command(d,u,a,n.stepName);return A&&(A.command&&a.getCommandDispatcher()(A.command),A.followup&&await A.followup()),await a.setSelectionsAndElements(n.stepName,[],u,async()=>{a.updateStorage(n.stepName,{videoShortUrl:d,videoUrl:o.href})}),d}async regionElements(t){const e=(a,n)=>({id:N(),region:a,regionIndex:n});return t.data.regions.map(e)}async command(t,e,a,n){const r=a.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await zn.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,u=r.find(A=>A.panelId===d?.panelId);if(!u&&d)throw new J(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new H({stepRegion:d,stepRegionIndex:c.regionIndex,stepName:n,id:c.id,src:s,type:D.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},u)});return{command:new U(l),followup:async()=>{}}}}const Ka=new el;class Te{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return xa(e);const a=t.asset;if(!a)throw new St(t);const n=a.fileLink;if(n)return et(n,!0);throw new Rt(a)}}async init(t,e,a){const n=a?.serializableWorkflow.steps.find(l=>l.stepName===t.stepName);if(n?.storage&&Object.keys(n.storage).length!==0||n?.selectedVariants&&n.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let r;const o=e.getWorkflowExperience().getBundle();if(o&&t.globalPropertyAspectConfigurations){const l=o.getGlobalPropertyStateManager(),c=t.globalPropertyAspectConfigurations[0],d=l.getAspectStorage(c.aspectName);d&&d.originalAssetKey&&(r=(await G.getLocalOrFromServer(d.originalAssetKey)).fileLink)}const s=await I.getOptionForStep(t);if(s){const l=await I.getDefaultVariant(s,t.overrideDefaultVariantId);if(l)return this.selectVariantCommand(t,l,[],e,void 0,r||t.data.placeholderImageUrl);if(s.variants&&s.variants?.length!==0)return null}return this.selectVariantCommand(t,void 0,[],e,void 0,r||t.data.placeholderImageUrl)}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName).map(d=>({id:d.id,region:d.stepRegion,regionIndex:d.stepRegionIndex})),c=await I.getOptionForStep(t);if(!c||(c.variants||[]).length===0){const d=t.data.regions.map(u=>xa(u));e.updateStorage(t.stepName,{currentFrameSources:d})}if(n){const d=async()=>{const u=n.storage?.colors,A=n.storage?.framePatternSrc,h=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:h,framePatternSrc:A}),A){const g=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!g)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,g,!0,u),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A}),this.validateColorCount(t,e)}if(h?.some(g=>g.zoom)){const g=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!g)throw new Error("Frame service unavailable, cannot load pattern!");g.updateOffsets(h)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const u=n.selectedVariants[0].id;if(c&&u){const A=c.variants?.find(h=>h.id===u);A&&await e.setSelectionsAndElements(t.stepName,[A],l,async()=>{const h=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(A,g)));e.updateStorage(t.stepName,{currentFrameSources:h}),await d()})}}else await e.setSelectionsAndElements(t.stepName,[],l,d)}}async availableColors(t,e){return(await I.ensureFullOption(t.data.colorOption))?.variants?.map(n=>({fill:n.color,stroke:n.color,variant:n,pmsValue:n.name}))??[]}selectImage(t,e,a,n=!0){const r=Te.patternSource(e),o=a.getStepStorage(t.stepName)?.framePatternSrc;if(o&&o===r)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const s=e.fileLink||"";return s.endsWith(".pdf")||s.endsWith(".eps")||s.endsWith(".ai")?new Promise(l=>{a.addPoller(new Ni(async()=>{const d=(await G.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{G.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,n).then(l)})},()=>{throw new Le("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,n)}async selectVariant(t,e,a,n,r){const o=await this.selectVariantCommand(t,e,a,n,r);o&&(o.command&&n.getCommandDispatcher()(o.command),o.followup&&await o.followup())}getCreateElementCommand(t,e,a,n,r){return new H({id:t,type:D.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/r.frameData.width,scaleY:e.height/r.frameData.height,path:r.frameData.path,dataWidth:r.frameData.width,dataHeight:r.frameData.height,stepRegion:e,stepRegionIndex:a,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},n)}async loadPatternFromString(t,e,a=!0,n=void 0,r){if(t.endsWith("svg")){const o=await Wa(t),s=o.width,l=o.height,c=await et(t);if(r){const A=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(A&&A.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await rt(c),u={src:t,width:s,height:l,aspect:s/l,svg:d.svg,colors:n??d.colors};ht.set(t,u),e.setPatternData(u,a)}else{const o=await ze(t,!0),s=await ue(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};ht.set(t,l),e.setPatternData(l,a)}}async changeColors(t,e,a){const n=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!n||!n.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const r=await this.calculateColorMetadata(n,t,a);e.updateMetadata(t.stepName,{colors:r.metadataColors}),e.updateStorage(t.stepName,{colors:r.storageColors}),n.setPatternData({...n.getImageData(),colors:r.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){const a=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!a)return 0;const n=a.getImageData()?.colors??{},r=[];for(const o in n){const s=n[o];if(s.pmsValue){const l=s.pmsValue.trim().toLocaleLowerCase();r.includes(l)||r.push(l)}else if(s.browserValue){const l=ri(s.browserValue);r.includes(l)||r.push(l)}}return r.length}async calculateColorMetadata(t,e,a){if(!t.getImageData()?.svg)return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const n={...t.getImageData().colors??{}},r={};Object.entries(n).forEach(([l,c])=>{const d={browserValue:c.browserValue};r[l]=d});for(const[l,c]of a.entries())n[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},r[l]=c;let o=Array.from(Object.values(n)).map(l=>l.browserValue);const s=await I.ensureFullOption(e.data.colorOption);return s&&s.variants?.forEach(l=>{o=o.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:n,metadataColors:o,storageColors:r}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,n,r,o){const s=n.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!s)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(e,h)));r&&r(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(h,g)=>{const p=await me(l[g]),m=s.getImageData(),C=a.map(B=>new Dt(B.id)),S=m?Ha(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:S?.x||0,y:S?.y||0,width:m.width,height:m.height,scaleX:S?.zoom||1,scaleY:S?.zoom||1,rotation:0}:void 0,F=N(),v=n.getLayouts().find(B=>B.panelId===h.panelId);if(!v)throw new J(h);return{command:this.getCreateElementCommand(F,h,g,v,{frameData:p,pattern:w,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:F,region:h,regionIndex:g},removeExistingCommands:C}})),u=d.map(h=>h.command),A=d.map(h=>h.removeExistingCommands).flat();return{command:new U([...u,...A]),followup:async()=>{r&&r(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:l}),o){const h=n.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(o,h,!0)}})}}}static patternSource(t){const e=t.versions?.find(n=>n.name==="svg");if(e?.link)return e.link;const a=t.fileLink;if(a)return a;throw new Rt(t)}async loadPatternFromAsset(t,e,a,n){const r=Te.patternSource(t),o=a.markUpdatePending(),s=a.getWorkflowExperience().getStepById(e.stepName)?.frameService;if(!s)throw a.markUpdateCompleted(o),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(r,s,n,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(c){throw a.markUpdateCompleted(o),c}const l=await this.calculateColorMetadata(s,e,new Map(Object.entries(s.getImageData()?.colors??{})));a.updateMetadata(e.stepName,{image:r,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:r,colors:l.storageColors}),a.markUpdateCompleted(o),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(c=>c.stepID===e.stepName)),this.validateColorCount(e,a)}}const pt=new Te;class al{async getIllustrationBody(t){return new Promise(e=>{et(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,n,r){return new H({stepRegion:e,stepRegionIndex:a,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:D.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},n)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return V(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new lt(t,"No option configured for illustration step.");if(a)return await this.reload(t,e,a);{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantCommand(t,r,[],e)}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors})})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=await I.ensureFullOption(t.data.colorOption);return a?a?a.variants?.map(n=>({fill:n.color,stroke:n.color,variant:n,pmsValue:n.name})):[]:[]}async changeColorsCommand(t,e,a,n,r){const o={};for(const[d,u]of r.entries())typeof u=="string"?o[d]={browserValue:u,spotColor:void 0,pmsValue:void 0}:o[d]={browserValue:u.browserValue,spotColor:u.spotColor,pmsValue:u.pmsValue};const s=Ga(t,e,a,o),l=await se(s),c=[];for(const d of n){for(const[u,A]of r.entries())c.push(new Ma(d,u,A));c.push(new Ks(d,s,l))}return new U(c)}async changeColors(t,e,a,n){if(e.length===0)return;const r=V(e[0].id,a.getCommandContext().getAllLayouts().map(A=>A.layoutState)),o={...r.colors},s={};Object.entries(o).forEach(([A,h])=>{const g={browserValue:h.browserValue,pmsValue:h.pmsValue},p=h.spotColor;p&&(g.spotColor={profileName:p.profileName,namedColor:p.namedColor}),s[A]=g});for(const[A,h]of n.entries()){const g=typeof h=="string"?h:h.browserValue,p=typeof h=="string"?void 0:h.pmsValue;A===""?Object.keys(o).forEach(m=>{o[m]={browserValue:g,spotColor:o[m]?.spotColor,pmsValue:p},s[m]={browserValue:g}}):(o[A]={browserValue:g,spotColor:o[A]?.spotColor,pmsValue:p},s[A]={browserValue:g})}let l=Array.from(Object.values(o)).map(A=>A.browserValue);const c=await I.ensureFullOption(t.data.colorOption);c&&c.variants?.forEach(A=>{l=l.map(h=>h.toLowerCase()===A.color?.toLowerCase()?A.name:h)}),a.updateMetadata(t.stepName,{colors:l});const d=new Map;if(Object.entries(o).forEach(([A,h])=>{d.set(A,h)}),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(r.svg,r.width,r.height,e.map(A=>A.id),d);a.updateStorage(t.stepName,{colors:s}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,n,r){n(!0);try{const o=await this.selectVariantCommand(t,e,a,r);o&&(o.command&&r.getCommandDispatcher()(o.command),o.followup&&await o.followup())}finally{n(!1)}}async selectVariantCommand(t,e,a,n){if(!t.data||!t.data.regions)throw new lt(t,"Missing regions.");const r=e.asset;if(!r)throw new St(e);const o=r.fileLink;if(!o)throw new Rt(r);t.mandatory&&n.setMandatoryFulfilled(t.stepName,!1);const s=a.map(m=>new Dt(m.id)),l=await rt(await this.getIllustrationBody(o)),c=await se(l.svg),d=(m,C)=>{const S=n.getLayouts().find(F=>F.panelId===m.panelId);if(!S)throw new J(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:C},command:this.getCreateElementCommand(w,m,C,S,{stepName:t.stepName,src:o,objectURL:c,svg:l})}},u=t.data.regions.map(d),A=u.map(m=>m.command),h=[...s,...A];let g=Array.from(Object.values(l.colors)).map(m=>m.browserValue);const p=await I.ensureFullOption(t.data.colorOption);return p&&p.variants?.forEach(m=>{g=g.map(C=>C.toLowerCase()===m.color?.toLowerCase()?m.name:C)}),n.updateMetadata(t.stepName,{colors:g}),{command:new U(h),followup:async()=>{const m=u.map(S=>S.regionElement);await n.setSelectionsAndElements(t.stepName,[e],m);const C=r.assetConfiguration?.defaultColorVariants||[];if(C.length!==0){const S={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=C.find(v=>v.channelNumber===F.number);b&&(S[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,n,new Map(Object.entries(S)))}if(t.data.colorPickerEnabled){const S=await this.availableColors(t,n)||[],w=Object.keys(l.colors),F=S.length===1&&w.length===1;if(F){const b=S[0],v=w[0];await this.changeColors(t,m,n,new Map([[v,b.variant.color]]))}!F&&C.length===0&&await this.changeColors(t,m,n,new Map)}}}}}const _t=new al;class nl{async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new ie(t);if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(!l)throw new ie(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(c){const d=l.variants?.find(u=>u.id===c);if(d){const u=d.material,A=s.map(h=>({id:h.id,region:h.stepRegion,regionIndex:h.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{const h=e.getModelContainer();if(h){const g=t.data.targetMaterials.map(p=>h.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(g)}})}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantLambda(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,n){const r=a.getModelContainer();n(!0);const o=e.material;if(!o)throw n(!1),new St(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{r&&t.data.targetMaterials.forEach(s=>{t.option&&r.applyMaterialVariant(s,t.option.id||"",o)})}finally{n(!1)}})}}}}const _a=new nl;class il{async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new ie(t);if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{const A=e.getModelContainer();if(A&&t.option){const h=d.asset?.fileLink;if(!h)throw new St(d);await A.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1)}})}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantLambda(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,n){n(!0);const r=e.asset?.fileLink;if(!r)throw new St(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{const o=a.getModelContainer();o&&await o.applyModelVariant(t.stepName,{model:r,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1)}finally{n(!1)}})}}}}const Xa=new il;class rl{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,n?.storage?.text!=="")})}async changeText(t,e,a,n){const r=await this.changeTextCommand(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,a,n){const r=a.getRegionElements(t.stepName),o=a.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const s=a.getWorkflowExperience().getProfanityList(),l=this.validateInput(t,e,s,n);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(d,u,A,h)=>{const g=h||N(),m=a.getLayouts().find(S=>S.panelId===u.panelId);if(!m)return console.error(`Can not find layout for region: ${u.panelId}`),null;const C=[];return h&&C.push(new Dt(g)),C.push(new H({stepRegion:u,stepRegionIndex:A,stepName:t.stepName,colors:{},id:g,svg:d,type:D.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},m)),{id:g,region:u,command:new U(C)}};if(r.length>0){const u=r.map(A=>{if(!A.region)return null;const h=o.svgPrint(e,A.region);return c(h,A.region,A.regionIndex,A.id)}).filter(A=>!!A).filter(A=>!!A).map(A=>A&&A.command);return{command:new U(u),followup:async()=>{}}}else{const d=t.data.regions.map((A,h)=>c(o.svgPrint(e,A),A,h)),u=d.filter(A=>!!A).map(A=>A&&A.command);return{command:new U(u),followup:async()=>{const A=d.filter(h=>h).map(h=>h&&{id:h.id,region:h.region});await a.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,e,a,n){if(t.data&&t.data.maxLength){const o=t.data.maxLength;if(e.length>o)return n("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const r=Sa.split(e.toLowerCase());for(const o of r)for(const s in a){const l=a[s].toLowerCase().replace(/\s/g,"");if(o===l)return n("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return n(""),{input:e,helperData:{}}}}const Za=new rl;class ol{async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new lt(t,"Missing option for picture step");if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,r,e,()=>{})}return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u)}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantCommand(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,a,n){const r=e.asset;if(!r)throw new St(e);const o=r?.fileLink;if(!o)return console.error("No URL for picture!"),null;n(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(u=>new Dt(u.id)),c=(u,A)=>{const g=a.getLayouts().find(m=>m.panelId===u.panelId);if(!g)throw new J(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new H({stepName:t.stepName,stepRegion:u,stepRegionIndex:A,id:p,src:o,type:D.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},g)}},d=t.data.regions.map(c);return{command:new U([...l,...d.map(u=>u.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(u=>u.regionElement),async()=>{n(!1)})}}}}const tn=new ol;class sl{async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new lt(t,"Missing option for question step");if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return this.selectVariantLambda(t,r.id||"",e)}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),r=await I.getOptionForStep(t);if(n?.selectedVariants){const o=n.selectedVariants[0].id;if(r&&o){const s=r.variants?.find(l=>l.id===o);s&&await e.setSelectionsAndElements(t.stepName,[s],[])}}}async selectVariant(t,e,a){const n=await this.selectVariantLambda(t,e,a);n&&(n.command&&a.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new lt(t,"Missing option for question step");const r=n.variants;if(!r)throw new lt(t,"Option for question step is missing variants");const o=r.length>1?r.find(s=>s.id===e):r[0];if(!o)throw new Error(`Failed to find selected variant ${e} in option ${n.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[o],[])}}}}const en=new sl;class ll{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=await I.getOptionForStep(t);return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const n=a.getLayouts(),o=(a.getRegionElements(e.stepName)||[]).map(s=>{const l=s.region;if(!n.find(d=>d.panelId===l?.panelId))throw new J(l);return new Ma(s.id,this.shapeFillId,t)}).filter(s=>!!s);a.getCommandDispatcher()(new U(o)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new ie(t);if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);return r?this.selectVariantCommand(t,{fill:r.color,stroke:r.color,variant:r},[],e):null}return null}async selectVariant(t,e,a,n){const r=await this.selectVariantCommand(t,e,a,n);r&&(r.command&&n.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateStorage(t.stepName,{colour:n?.storage?.colour||""})})}}}}async selectVariantCommand(t,e,a,n){const r=n.getLayouts(),o=n.getStepStorage(t.stepName)?.colour,s=()=>{if(e.variant?.color==="#custom")return o||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const l=d=>{const u=d.region;if(!r.find(g=>g.panelId===u?.panelId))throw new J(u);const h=s();return new Ma(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new U(c),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),n.updateStorage(t.stepName,{colour:s()})}}}else{const l=(A,h)=>{const g=r.find(w=>w.panelId===A.panelId);if(!g)throw new J(A);const p=s(),m=`
1402
+ `,n={};n["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Gt(t,D.Illustration),s=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:n,id:s,svg:a,type:D.Illustration,y:r.top,x:r.left,rotation:r.rotation,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||qt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Gt(t,D.Illustration,e.src),n=await it(await pi(e.src)),r=await re(n.svg),s=N();return{cachedObjectURL:r,stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:n.colors,id:s,src:e.src,svg:n.svg,type:D.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||qt(t,a.layer||0),immutable:a.immutable}}}class j extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,j.prototype)}}const V=(i,t)=>K(i,t).elements.find(n=>n.id===i),K=(i,t)=>{const e=Object.values(t).find(a=>a.elements.some(n=>n.id===i));if(!e)throw new j;return e},_=(i,t)=>{const e=[...t.elements.filter(n=>n.id!==i.id),i],a=Ua(e);return{layout:t.layout,elements:a,modificationID:N()}},Ia=async i=>{const t=[...Object.keys(i.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const n=e[a],r=i.layouts[n];await Promise.all(r.elements.map(async s=>{if(s.type==="illustration"){const o=s;if(o.src&&!o.svg){const l=await tt(o.src),c=await it(l);o.svg=$a(c.svg,o.width,o.height,o.colors)}}else if(s.type==="frame"){const o=s;if(o.pattern?.colors&&o.pattern?.src){const l=await tt(o.pattern?.src),c=await it(l);o.pattern.svg=c.svg}}isNaN(s.x)&&(s.x=0),isNaN(s.y)&&(s.y=0),isNaN(s.width)&&(s.width=0),isNaN(s.height)&&(s.height=0),isNaN(s.rotation)&&(s.rotation=0)}))}for(const a in i.layouts){const n=i.layouts[a].elements.filter(s=>s.type===D.Illustration);for(let s=0;s<n.length;++s){const o=n[s];if(o.src&&o.svg)try{o.cachedObjectURL=await re(o.svg)}catch(l){console.log(l)}}const r=i.layouts[a].elements.filter(s=>s.type===D.Textbox);for(let s=0;s<r.length;++s){const o=r[s];o.fontData?.assetUrl&&await Pt(o.fontData.assetUrl)}}};class ${undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class Cn extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Do extends ${constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,x:this.x,y:this.y},n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class ko extends ${constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,rotation:this.angle},n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Mo extends ${constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const s=a;s.scaleX=s.scaleX*this.width/e.width,s.scaleY=s.scaleY*this.height/e.height}else if(e.type==="textbox"){const s=a,o=(!s.algorithm||s.algorithm===Bt.Autosize?s.text:s.input)??"";a=Ae(s,o,e)}const n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class U extends ${constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class qa extends ${constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:N()}}}}}class W extends ${constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(o=>o.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const o=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,o)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:N()}}}}const n=e[e.length-1],r=n.productOverlay?n:null;r&&e.pop();let s;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)s=[...e,this.element].sort((o,l)=>o.layerIndex!==void 0&&l.layerIndex!==void 0?o.layerIndex-l.layerIndex:0);else{const o=this.assignIndex(this.element,e);this.element.layerIndex=o!==void 0?o:0,s=[...e,this.element]}return r&&s.push(r),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:N()}}}}assignIndex(t,e){if(e.length===0)return 0;const a=e.filter(n=>(n.layer||0)===(t.layer||0)).sort((n,r)=>(n.layerIndex||0)-(r.layerIndex||0))[e.length-1]?.layerIndex;return a!==void 0?a+1:0}}class xt extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(r=>(r.elements.filter(o=>o.id!==this.id).length!==r.elements.length&&(e=!0),{...r,elements:r.elements.filter(o=>o.id!==this.id),modificationID:N()}));e||console.log(`Failed to delete element ${this.id}`);const n={};return a.forEach(r=>{n[r.layout.id]=r}),{...t,layouts:n}}}class fi extends ${constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class ca extends ${constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,textFillImage:this.imageFill},n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Ci extends ${constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fontSize:this.size},n=K(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=_(Ae(a,r),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class Ba extends ${constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fontData:this.fontData},n=K(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=_(Ae(a,r),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class wi extends ${constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,align:this.align},n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class To extends ${constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=K(this.id,Object.values(t.layouts)),a=e.elements.findIndex(o=>o.id===this.id),n=e.elements[a].pattern,r=[...e.elements];r.splice(a,1,{...e.elements[a],pattern:{...n,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const s={...e,elements:r,modificationID:N()};return{...t,layouts:{...t.layouts,[e.layout.id]:s}}}}class No extends ${constructor(t,e,a,n,r){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=n,this.thresholdSaturation=r}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Qo extends ${constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,src:this.src},n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class yi extends ${constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=K(e.id,Object.values(t.layouts)),n=_(Ae(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:n}}}}class da extends ${constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Pa extends ${constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=e.colors||{},n=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:n?.spotColor,pmsValue:n?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:n?.spotColor,pmsValue:this.fill.pmsValue};const r={...e,colors:a},s=K(e.id,Object.values(t.layouts)),o=_(r,s);return{...t,layouts:{...t.layouts,[s.layout.id]:o}}}}class Oo extends ${constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},n=K(e.id,Object.values(t.layouts)),r=_(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Ro extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(s=>s.elements.find(o=>o.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(s=>s.id===this.id);a.elements.push(a.elements.splice(n,1)[0]);const r=[...a.elements];return r.forEach((s,o)=>s.layerIndex=o),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class $o extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=Object.values(t.layouts).find(o=>o.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(o=>o.id===this.id);a.elements.splice(n,1),a.elements.unshift(e);const r=[...a.elements],s=r.splice(n,1)[0];return r.splice(n,0,s),r.forEach((o,l)=>o.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Uo extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),r=n+1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(r,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:N()}}}}}class Vo extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),r=n-1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(r,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:N()}}}}}class wn{constructor(t,e,a){this.processRegion=async n=>{const r=this.layouts.find(l=>l.panelId===n.panelId);if(!r)throw new J(n);let s="";if(this.configuration.type===E.ProductOverlay){let l="";if(this.product?.overlayImageUrl&&(l=this.product.overlayImageUrl),s=l,!l)throw new st(this.configuration,"Couldn't find an asset for product overlay step")}const o=this.evaluateAssetType();if(o===D.Image){const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!l)throw new Error("Undefined raster silent step source");const c={stepName:this.configuration.stepName,id:N(),src:l,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,rotation:n.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:n},command:new W(c,r)}}else{const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:s,d=await it(await(async()=>new Promise((A,h)=>{if(!l){h("Undefined vector silent step source");return}tt(l,!0).then(g=>{A(g)}).catch(g=>console.error(g))}))()),u={stepName:this.configuration.stepName,id:N(),cachedObjectURL:await re(d.svg),src:l,svg:d.svg,colors:d.colors,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,rotation:n.rotation,immutable:n.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:u.id,region:n},command:new W(u,r)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new st(this.configuration,"Missing regions.");if(this.configuration.type===E.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===E.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new J(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===E.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?D.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),D.Illustration)}}const Si=async i=>{const t=`${At.getServicesApiUrl()}/shortener`;try{return(await(await nt(t,{method:"POST",body:JSON.stringify({longUrl:i}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new $e("Failed to shorten URL, see console.")}};class vi{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,n=3e3,r=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=r,this.poll()}}class Lo{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{const c=n?.storage?.videoShortUrl,d=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,n){const r=async()=>{const h=(await Pe([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},s=await new Promise((h,g)=>{new vi(async()=>!!(await r()).link,async()=>{const p=await r();if(!p.link||!p.link)throw new Qt(p.asset);h({rel:"mpeg4",href:p.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new xt(h.id)));const o=n.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(o+n.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([s]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new $e("Cannot create QR code, URL too long.");const d=await Si(c);if(!n.data||!n.data.regions)throw new st(n,"Missing regions.");const u=await this.regionElements(n),A=await this.command(d,u,a,n.stepName);return A&&(A.command&&a.getCommandDispatcher()(A.command),A.followup&&await A.followup()),await a.setSelectionsAndElements(n.stepName,[],u,async()=>{a.updateStorage(n.stepName,{videoShortUrl:d,videoUrl:s.href})}),d}async regionElements(t){const e=(a,n)=>({id:N(),region:a,regionIndex:n});return t.data.regions.map(e)}async command(t,e,a,n){const r=a.getLayouts(),o=`data:image/svg+xml;base64,${btoa(await Fn.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,u=r.find(A=>A.panelId===d?.panelId);if(!u&&d)throw new J(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new W({stepRegion:d,stepRegionIndex:c.regionIndex,stepName:n,id:c.id,src:o,type:D.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},u)});return{command:new U(l),followup:async()=>{}}}}const Ga=new Lo;class De{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return Ea(e);const a=t.asset;if(!a)throw new wt(t);const n=a.fileLink;if(n)return tt(n,!0);throw new Qt(a)}}async init(t,e,a){const n=a?.serializableWorkflow.steps.find(l=>l.stepName===t.stepName);if(n?.storage&&Object.keys(n.storage).length!==0||n?.selectedVariants&&n.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let r;const s=e.getWorkflowExperience().getBundle();if(s&&t.globalPropertyAspectConfigurations){const l=s.getGlobalPropertyStateManager(),c=t.globalPropertyAspectConfigurations[0],d=l.getAspectStorage(c.aspectName);d&&d.originalAssetKey&&(r=(await G.getLocalOrFromServer(d.originalAssetKey)).fileLink)}const o=await I.getOptionForStep(t);if(o){const l=await I.getDefaultVariant(o,t.overrideDefaultVariantId);if(l)return this.selectVariantCommand(t,l,[],e,void 0,r||t.data.placeholderImageUrl);if(o.variants&&o.variants?.length!==0)return null}return this.selectVariantCommand(t,void 0,[],e,void 0,r||t.data.placeholderImageUrl)}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName).map(d=>({id:d.id,region:d.stepRegion,regionIndex:d.stepRegionIndex})),c=await I.getOptionForStep(t);if(!c||(c.variants||[]).length===0){const d=t.data.regions.map(u=>Ea(u));e.updateStorage(t.stepName,{currentFrameSources:d})}if(n){const d=async()=>{const u=n.storage?.colors,A=n.storage?.framePatternSrc,h=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:h,framePatternSrc:A}),A){const g=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!g)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,g,!0,u),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A}),this.validateColorCount(t,e)}if(h?.some(g=>g.zoom)){const g=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!g)throw new Error("Frame service unavailable, cannot load pattern!");g.updateOffsets(h)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const u=n.selectedVariants[0].id;if(c&&u){const A=c.variants?.find(h=>h.id===u);A&&await e.setSelectionsAndElements(t.stepName,[A],l,async()=>{const h=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(A,g)));e.updateStorage(t.stepName,{currentFrameSources:h}),await d()})}}else await e.setSelectionsAndElements(t.stepName,[],l,d)}}async availableColors(t,e){return(await I.ensureFullOption(t.data.colorOption))?.variants?.map(n=>({fill:n.color,stroke:n.color,variant:n,pmsValue:n.name}))??[]}selectImage(t,e,a,n=!0){const r=De.patternSource(e),s=a.getStepStorage(t.stepName)?.framePatternSrc;if(s&&s===r)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const o=e.fileLink||"";return o.endsWith(".pdf")||o.endsWith(".eps")||o.endsWith(".ai")?new Promise(l=>{a.addPoller(new vi(async()=>{const d=(await G.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await nt(d.link)).status===200:!1},()=>{G.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,n).then(l)})},()=>{throw new $e("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,n)}async selectVariant(t,e,a,n,r){const s=await this.selectVariantCommand(t,e,a,n,r);s&&(s.command&&n.getCommandDispatcher()(s.command),s.followup&&await s.followup())}getCreateElementCommand(t,e,a,n,r){return new W({id:t,type:D.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/r.frameData.width,scaleY:e.height/r.frameData.height,path:r.frameData.path,dataWidth:r.frameData.width,dataHeight:r.frameData.height,stepRegion:e,stepRegionIndex:a,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},n)}async loadPatternFromString(t,e,a=!0,n=void 0,r){if(t.endsWith("svg")){const s=await La(t),o=s.width,l=s.height,c=await tt(t);if(r){const A=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(A&&A.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await it(c),u={src:t,width:o,height:l,aspect:o/l,svg:d.svg,colors:n??d.colors};ut.set(t,u),e.setPatternData(u,a)}else{const s=await Ue(t,!0),o=await ce(s),l={src:t,width:o.width,height:o.height,aspect:o.width/o.height,svg:void 0,colors:void 0};ut.set(t,l),e.setPatternData(l,a)}}async changeColors(t,e,a){const n=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!n||!n.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const r=await this.calculateColorMetadata(n,t,a);e.updateMetadata(t.stepName,{colors:r.metadataColors}),e.updateStorage(t.stepName,{colors:r.storageColors}),n.setPatternData({...n.getImageData(),colors:r.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){const a=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!a)return 0;const n=a.getImageData()?.colors??{},r=[];for(const s in n){const o=n[s];if(o.pmsValue){const l=o.pmsValue.trim().toLocaleLowerCase();r.includes(l)||r.push(l)}else if(o.browserValue){const l=Wn(o.browserValue);r.includes(l)||r.push(l)}}return r.length}async calculateColorMetadata(t,e,a){if(!t.getImageData()?.svg)return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const n={...t.getImageData().colors??{}},r={};Object.entries(n).forEach(([l,c])=>{const d={browserValue:c.browserValue};r[l]=d});for(const[l,c]of a.entries())n[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},r[l]=c;let s=Array.from(Object.values(n)).map(l=>l.browserValue);const o=await I.ensureFullOption(e.data.colorOption);return o&&o.variants?.forEach(l=>{s=s.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:n,metadataColors:s,storageColors:r}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,n,r,s){const o=n.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(e,h)));r&&r(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(h,g)=>{const p=await he(l[g]),m=o.getImageData(),C=a.map(B=>new xt(B.id)),S=m?Va(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:S?.x||0,y:S?.y||0,width:m.width,height:m.height,scaleX:S?.zoom||1,scaleY:S?.zoom||1,rotation:0}:void 0,F=N(),v=n.getLayouts().find(B=>B.panelId===h.panelId);if(!v)throw new J(h);return{command:this.getCreateElementCommand(F,h,g,v,{frameData:p,pattern:w,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:F,region:h,regionIndex:g},removeExistingCommands:C}})),u=d.map(h=>h.command),A=d.map(h=>h.removeExistingCommands).flat();return{command:new U([...u,...A]),followup:async()=>{r&&r(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:l}),s){const h=n.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(s,h,!0)}})}}}static patternSource(t){const e=t.versions?.find(n=>n.name==="svg");if(e?.link)return e.link;const a=t.fileLink;if(a)return a;throw new Qt(t)}async loadPatternFromAsset(t,e,a,n){const r=De.patternSource(t),s=a.markUpdatePending(),o=a.getWorkflowExperience().getStepById(e.stepName)?.frameService;if(!o)throw a.markUpdateCompleted(s),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(r,o,n,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(c){throw a.markUpdateCompleted(s),c}const l=await this.calculateColorMetadata(o,e,new Map(Object.entries(o.getImageData()?.colors??{})));a.updateMetadata(e.stepName,{image:r,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:r,colors:l.storageColors}),a.markUpdateCompleted(s),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(c=>c.stepID===e.stepName)),this.validateColorCount(e,a)}}const gt=new De;class zo{async getIllustrationBody(t){return new Promise(e=>{tt(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,n,r){return new W({stepRegion:e,stepRegionIndex:a,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:D.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},n)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return V(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new st(t,"No option configured for illustration step.");if(a)return await this.reload(t,e,a);{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantCommand(t,r,[],e)}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=o.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors})})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=await I.ensureFullOption(t.data.colorOption);return a?a?a.variants?.map(n=>({fill:n.color,stroke:n.color,variant:n,pmsValue:n.name})):[]:[]}async changeColorsCommand(t,e,a,n,r){const s={};for(const[d,u]of r.entries())typeof u=="string"?s[d]={browserValue:u,spotColor:void 0,pmsValue:void 0}:s[d]={browserValue:u.browserValue,spotColor:u.spotColor,pmsValue:u.pmsValue};const o=$a(t,e,a,s),l=await re(o),c=[];for(const d of n){for(const[u,A]of r.entries())c.push(new Pa(d,u,A));c.push(new Oo(d,o,l))}return new U(c)}async changeColors(t,e,a,n){if(e.length===0)return;const r=V(e[0].id,a.getCommandContext().getAllLayouts().map(A=>A.layoutState)),s={...r.colors},o={};Object.entries(s).forEach(([A,h])=>{const g={browserValue:h.browserValue,pmsValue:h.pmsValue},p=h.spotColor;p&&(g.spotColor={profileName:p.profileName,namedColor:p.namedColor}),o[A]=g});for(const[A,h]of n.entries()){const g=typeof h=="string"?h:h.browserValue,p=typeof h=="string"?void 0:h.pmsValue;A===""?Object.keys(s).forEach(m=>{s[m]={browserValue:g,spotColor:s[m]?.spotColor,pmsValue:p},o[m]={browserValue:g}}):(s[A]={browserValue:g,spotColor:s[A]?.spotColor,pmsValue:p},o[A]={browserValue:g})}let l=Array.from(Object.values(s)).map(A=>A.browserValue);const c=await I.ensureFullOption(t.data.colorOption);c&&c.variants?.forEach(A=>{l=l.map(h=>h.toLowerCase()===A.color?.toLowerCase()?A.name:h)}),a.updateMetadata(t.stepName,{colors:l});const d=new Map;if(Object.entries(s).forEach(([A,h])=>{d.set(A,h)}),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(r.svg,r.width,r.height,e.map(A=>A.id),d);a.updateStorage(t.stepName,{colors:o}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,n,r){n(!0);try{const s=await this.selectVariantCommand(t,e,a,r);s&&(s.command&&r.getCommandDispatcher()(s.command),s.followup&&await s.followup())}finally{n(!1)}}async selectVariantCommand(t,e,a,n){if(!t.data||!t.data.regions)throw new st(t,"Missing regions.");const r=e.asset;if(!r)throw new wt(e);const s=r.fileLink;if(!s)throw new Qt(r);t.mandatory&&n.setMandatoryFulfilled(t.stepName,!1);const o=a.map(m=>new xt(m.id)),l=await it(await this.getIllustrationBody(s)),c=await re(l.svg),d=(m,C)=>{const S=n.getLayouts().find(F=>F.panelId===m.panelId);if(!S)throw new J(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:C},command:this.getCreateElementCommand(w,m,C,S,{stepName:t.stepName,src:s,objectURL:c,svg:l})}},u=t.data.regions.map(d),A=u.map(m=>m.command),h=[...o,...A];let g=Array.from(Object.values(l.colors)).map(m=>m.browserValue);const p=await I.ensureFullOption(t.data.colorOption);return p&&p.variants?.forEach(m=>{g=g.map(C=>C.toLowerCase()===m.color?.toLowerCase()?m.name:C)}),n.updateMetadata(t.stepName,{colors:g}),{command:new U(h),followup:async()=>{const m=u.map(S=>S.regionElement);await n.setSelectionsAndElements(t.stepName,[e],m);const C=r.assetConfiguration?.defaultColorVariants||[];if(C.length!==0){const S={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=C.find(v=>v.channelNumber===F.number);b&&(S[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,n,new Map(Object.entries(S)))}if(t.data.colorPickerEnabled){const S=await this.availableColors(t,n)||[],w=Object.keys(l.colors),F=S.length===1&&w.length===1;if(F){const b=S[0],v=w[0];await this.changeColors(t,m,n,new Map([[v,b.variant.color]]))}!F&&C.length===0&&await this.changeColors(t,m,n,new Map)}}}}}const Kt=new zo;class qo{async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(!l)throw new ae(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(c){const d=l.variants?.find(u=>u.id===c);if(d){const u=d.material,A=o.map(h=>({id:h.id,region:h.stepRegion,regionIndex:h.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{const h=e.getModelContainer();if(h){const g=t.data.targetMaterials.map(p=>h.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(g)}})}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantLambda(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,n){const r=a.getModelContainer();n(!0);const s=e.material;if(!s)throw n(!1),new wt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{r&&t.data.targetMaterials.forEach(o=>{t.option&&r.applyMaterialVariant(o,t.option.id||"",s)})}finally{n(!1)}})}}}}const ja=new qo;class Go{async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=o.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{const A=e.getModelContainer();if(A&&t.option){const h=d.asset?.fileLink;if(!h)throw new wt(d);await A.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1)}})}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantLambda(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,n){n(!0);const r=e.asset?.fileLink;if(!r)throw new wt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{const s=a.getModelContainer();s&&await s.applyModelVariant(t.stepName,{model:r,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1)}finally{n(!1)}})}}}}const Wa=new Go;class jo{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,n?.storage?.text!=="")})}async changeText(t,e,a,n){const r=await this.changeTextCommand(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,a,n){const r=a.getRegionElements(t.stepName),s=a.getStepSpecificServices(t.stepName)?.module;if(!s)return console.error("Missing module."),null;const o=a.getWorkflowExperience().getProfanityList(),l=this.validateInput(t,e,o,n);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(d,u,A,h)=>{const g=h||N(),m=a.getLayouts().find(S=>S.panelId===u.panelId);if(!m)return console.error(`Can not find layout for region: ${u.panelId}`),null;const C=[];return h&&C.push(new xt(g)),C.push(new W({stepRegion:u,stepRegionIndex:A,stepName:t.stepName,colors:{},id:g,svg:d,type:D.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},m)),{id:g,region:u,command:new U(C)}};if(r.length>0){const u=r.map(A=>{if(!A.region)return null;const h=s.svgPrint(e,A.region);return c(h,A.region,A.regionIndex,A.id)}).filter(A=>!!A).filter(A=>!!A).map(A=>A&&A.command);return{command:new U(u),followup:async()=>{}}}else{const d=t.data.regions.map((A,h)=>c(s.svgPrint(e,A),A,h)),u=d.filter(A=>!!A).map(A=>A&&A.command);return{command:new U(u),followup:async()=>{const A=d.filter(h=>h).map(h=>h&&{id:h.id,region:h.region});await a.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,e,a,n){if(t.data&&t.data.maxLength){const s=t.data.maxLength;if(e.length>s)return n("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const r=pa.split(e.toLowerCase());for(const s of r)for(const o in a){const l=a[o].toLowerCase().replace(/\s/g,"");if(s===l)return n("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return n(""),{input:e,helperData:{}}}}const Ha=new jo;class Wo{async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new st(t,"Missing option for picture step");if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,r,e,()=>{})}return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=o.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u)}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantCommand(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,a,n){const r=e.asset;if(!r)throw new wt(e);const s=r?.fileLink;if(!s)return console.error("No URL for picture!"),null;n(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(u=>new xt(u.id)),c=(u,A)=>{const g=a.getLayouts().find(m=>m.panelId===u.panelId);if(!g)throw new J(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new W({stepName:t.stepName,stepRegion:u,stepRegionIndex:A,id:p,src:s,type:D.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},g)}},d=t.data.regions.map(c);return{command:new U([...l,...d.map(u=>u.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(u=>u.regionElement),async()=>{n(!1)})}}}}const Ya=new Wo;class Ho{async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new st(t,"Missing option for question step");if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return this.selectVariantLambda(t,r.id||"",e)}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),r=await I.getOptionForStep(t);if(n?.selectedVariants){const s=n.selectedVariants[0].id;if(r&&s){const o=r.variants?.find(l=>l.id===s);o&&await e.setSelectionsAndElements(t.stepName,[o],[])}}}async selectVariant(t,e,a){const n=await this.selectVariantLambda(t,e,a);n&&(n.command&&a.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new st(t,"Missing option for question step");const r=n.variants;if(!r)throw new st(t,"Option for question step is missing variants");const s=r.length>1?r.find(o=>o.id===e):r[0];if(!s)throw new Error(`Failed to find selected variant ${e} in option ${n.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[s],[])}}}}const Ja=new Ho;class Yo{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=await I.getOptionForStep(t);return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const n=a.getLayouts(),s=(a.getRegionElements(e.stepName)||[]).map(o=>{const l=o.region;if(!n.find(d=>d.panelId===l?.panelId))throw new J(l);return new Pa(o.id,this.shapeFillId,t)}).filter(o=>!!o);a.getCommandDispatcher()(new U(s)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await I.getDefaultVariant(n,t.overrideDefaultVariantId);return r?this.selectVariantCommand(t,{fill:r.color,stroke:r.color,variant:r},[],e):null}return null}async selectVariant(t,e,a,n){const r=await this.selectVariantCommand(t,e,a,n);r&&(r.command&&n.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=o.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateStorage(t.stepName,{colour:n?.storage?.colour||""})})}}}}async selectVariantCommand(t,e,a,n){const r=n.getLayouts(),s=n.getStepStorage(t.stepName)?.colour,o=()=>{if(e.variant?.color==="#custom")return s||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const l=d=>{const u=d.region;if(!r.find(g=>g.panelId===u?.panelId))throw new J(u);const h=o();return new Pa(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new U(c),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),n.updateStorage(t.stepName,{colour:o()})}}}else{const l=(A,h)=>{const g=r.find(w=>w.panelId===A.panelId);if(!g)throw new J(A);const p=o(),m=`
1403
1403
  <svg
1404
1404
  xmlns="http://www.w3.org/2000/svg"
1405
1405
  xmlnsXlink="http://www.w3.org/1999/xlink"
@@ -1419,14 +1419,14 @@
1419
1419
  fill="${p}"
1420
1420
  />
1421
1421
  </svg>
1422
- `,C={};C[this.shapeFillId]={browserValue:p};const S=N();return{id:S,region:A,command:new H({stepRegion:A,stepRegionIndex:h,stepName:t.stepName,colors:C,id:S,svg:m,type:D.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,excludeFromExport:t.data.excludeFromPrint},g)}},c=t.data.regions.map(l),d=c.filter(A=>!!A).map(A=>A?.command),u=c.filter(A=>!!A).map((A,h)=>({id:A.id,region:A.region,regionIndex:h}));return{command:new U(d),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],u,async()=>{n.updateStorage(t.stepName,{colour:s()})})}}}}}const Tt=new ll;class cl{constructor(){this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}removeToastCallback(t){this.toastCallbacks=this.toastCallbacks.filter(e=>e!==t)}setLatestToast(t,e){this.latestToast=t,this.toastType=e,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach(t=>t({toastMessage:this.latestToast,toastType:this.toastType}))}}const Qi=new cl,ga=(i,t,e,a,n)=>{if(t.some(d=>d==null))throw new Error(`Failed to autosize lines: ${t.join(", ")}`);let r=t.map(d=>d.split(`
1423
- `)).flat(),o=r.length,s=r.map(d=>wt(d,a,n));const l=n.getApproximateHeight()*a;let c=!0;for(;c;){if(l+(o-1)*e>i.height)return[null,null];const u=Math.max(...s);if(u<=i.width)return[r,u];const A=s.reduce((m,C,S,w)=>C>w[m]?S:m,0),h=r[A];let g=!1,p=h.length;for(;!g&&p>-1;){p=h.lastIndexOf(" ",p-1);const m=[h.slice(0,p),h.slice(p+1)],C=m.map(w=>wt(w,a,n));C[0]<=i.width&&(r=[...r.slice(0,A),...m,...r.slice(A+1)],s=[...s.slice(0,A),...C,...s.slice(A+1)],o+=1,g=!0)}g||(c=!1)}return[null,null]},Xt=(i,t,e,a,n)=>{let r,o;const s=bt(t.assetUrl),l=s.getFont();if(n.size){const A=i/l.unitsPerEm;return[r,o]=ga(e,a,i,A,s),[n.size,r,o]}const c=6;let d=c-ca;if(a.length>0){let A=a,h=0;for(;(!n.maxSize||d<=n.maxSize)&&A;)d+=ca,h=d/l.unitsPerEm,[A,o]=ga(e,a,d,h,s)}d>c&&(d-=ca),n.minSize&&d<n.minSize&&(d=n.minSize);const u=d/l.unitsPerEm;return[r,o]=ga(e,a,d,u,s),[d,r,o]},ma=30;class Ne extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ne.name}}const dl=["‘","’","“","”",`
1424
- `];class Qe extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Qe.name}}class ul{constructor(){this.cachedColors=new Map,this.cachedStrokeColors=new Map,this.filterUnsupportedCharacters=(t,e)=>{let a=t.replace(/(\r\n|\r|(\u2665|\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],r=e?bt(e.assetUrl):void 0;if(r){const o=a.split("").filter(l=>!dl.includes(l)).join(""),s=o.split("").map(l=>r.getFont().charToGlyph(l));for(let l=0;l<s.length;l++)s[l].name===".notdef"&&n.push(String.fromCharCode(o.charCodeAt(l)))}for(let o=0;o<n.length;o++)a=a.replaceAll(n[o],"");return a},this.textAlign=t=>t.vertical?"center":t.textAlign||"center",this.getErrorsForText=(t,e,a,n)=>{let r;a.data&&a.data.maxLength&&e.length>a.data.maxLength&&(r||(r={}),r.hitCharacterLimit=!0);const o=n.getWorkflowExperience().getProfanityList(),s=Sa.split(t.toLowerCase());for(const c of s)for(const d in o){const u=o[d].toLowerCase().replace(/\s/g,"");if(c===u){r||(r={}),r.blockedProfanity=!0;break}}return!a.data.allowNewlines&&(t.includes(`
1425
- `)||t.includes("\r"))&&(r||(r={}),r.illegalMultipleLines=!0),r}}async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)return null;if(a)await this.reload(t,e,a);else{const r=await this.getDefaultImageFillVariant(t.data),o=r?.asset?.fileLink,s=o?await Fa(o):void 0,l=s?{src:s.src,height:s.height,width:s.width,scale:t.data.imageFillScale||1}:void 0,c=await this.getDefaultStrokeColorVariant(t.data),d=t.data.strokeEnabled&&c?.color?{browserValue:c.color,pmsValue:c.name}:void 0;let u=t.data.defaultText||"";const A=e.getWorkflowExperience().getBundle();if(A&&t.globalPropertyAspectConfigurations){const p=A.getGlobalPropertyConfiguration()?.aspects?.find(m=>m.type===z.Text&&t.globalPropertyAspectConfigurations?.map(C=>C.aspectName).includes(m.name));if(p){const C=A.getGlobalPropertyStateManager().getAspect(p.name);C&&(u=C)}}e.updateStorage(t.stepName,{text:u,inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:l,strokeColor:d}),e.updateMetadata(t.stepName,{text:u,color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:r?.name,strokeColor:t.data.strokeEnabled?c?.color:void 0});const h=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(h)return this.selectVariantCommand(t,h,{text:u},[],e,()=>{},()=>{},l,d)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map(r=>V(r.id,t.getAllLayoutData()))}async availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const a=await I.ensureFullOption(t.data.colorOption);if(a){const n=a.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r}))||[];return this.cachedColors.set(t.stepName,n),n}return[]}changeAlignment(t,e,a,n){if(!t.data||!t.data.regions)return;const r=n.getCommandDispatcher();for(const o of a){const s=new ki(o.id,e);r(s)}}async changeFillColor(t,e,a,n){if(!t.data||!t.data.regions)return;const r=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const o=await I.ensureFullOption(t.data.colorOption),s=o?this.createTextFillSpotColor(o,e.variant):void 0;o?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:o.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const l of a){if(!e.fill)throw new Error("Fill not set on new color selection!");const c=new Fi(l.id,e.fill,s);r(c)}}async availableFillImages(t){const e=await I.ensureFullOption(t.data.imageFillOption);if(e){const a=e.variants?.map(n=>n.asset?.fileLink)?.filter(n=>!!n)||[];return Promise.all(a.map(async n=>{const r=await Fa(n);return{src:n,width:r.width,height:r.height,scale:t.data.imageFillScale||1}}))}return Promise.resolve([])}async changeFillImage(t,e,a,n){if(!t.data||!t.data.regions)return;const r=n.getCommandDispatcher(),s=(await I.getOptionForStep(t))?.variants?.find(l=>l.asset?.fileLink===e.src);n.updateMetadata(t.stepName,{fillImage:s?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const l of a){const c=new Aa(l.id,e);r(c)}}async availableStrokeColors(t){const e=this.cachedStrokeColors.get(t.stepName);if(e)return e;const a=await I.ensureFullOption(t.data.strokeOption);if(a){const n=a.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r}))||[];return this.cachedStrokeColors.set(t.stepName,n),n}return[]}async changeStrokeColor(t,e,a,n){if(!t.data||!t.data.regions)return;const r=n.getCommandDispatcher();e?.variant?n.updateMetadata(t.stepName,{strokeColor:e.variant.name}):n.updateMetadata(t.stepName,{strokeColor:e?.fill});const o=e?{browserValue:e.fill,pmsValue:e.pmsValue}:void 0;n.updateStorage(t.stepName,{strokeColor:o});for(const s of a){const l=new ha(s.id,o,t.data?.strokeThickness);r(l)}}getProcessedInput(t,e,a){const n=a?t:this.injectReplaceableText(t,e);return Me(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,a,n){const r=n.getStepStorage(a.stepName),o=Nt(t,n),s=this.getProcessedInput(o,a.data,r?.customiseAllText??!1),l={command:void 0,helperData:{},errorData:this.getErrorsForText(t,s,a,n)};if(l.errorData)return l;l.helperData.charactersRemaining=a.data.maxLength-s.length;const c=[],d=new Map,u=new Map;for(const A of e){if(!A.fontData)throw new O("Failed to resolve font data for text.");const[h,g]=Xt(A.fontSize,A.fontData,{left:A.x,top:A.y,width:A.width,height:A.height,rotation:A.rotation},[s],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});d.set(A.id,h),u.set(A.id,g);const p=a.data.curved?s:(g||[]).join(`
1426
- `);c.push(this.generateTextChangeCommandsForRegion(h,a.data,A.id,p))}return!a.data.curved&&e.length>0&&!Array.from(u.values()).every(h=>h)?(l.errorData||(l.errorData={}),l.errorData.doesNotFit=!0,l):(n.updateStorage(a.stepName,{text:t}),n.updateMetadata(a.stepName,{text:s}),(r?.defaultCleared||!a.data.deleteDefaultOnFocus)&&s.trim()!==""&&n.setMandatoryFulfilled(a.stepName,!0),l.command=new U(c),l)}async selectVariant(t,e,a,n,r){const o=await this.selectVariantCommand(t,e,a.getStepStorage(t.stepName)||{},a.getRegionElements(t.stepName),a,n,r);o&&(o.command&&a.getCommandDispatcher()(o.command),o.followup&&await o.followup())}createTextFillSpotColor(t,e){const a=t.colorProfile;if(a){const n=(a.name||"").replace(/\s/g,"-"),r=n.lastIndexOf("/"),s=n.slice(r+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:s,namedColor:e.namedColor}}}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=await this.fontDataFromVariant(d),A=s.map(m=>({id:m.id,region:m.stepRegion,regionIndex:m.stepRegionIndex})),h=n.storage?.color;let g=n.storage?.text;const p=e.getWorkflowExperience().getBundle();if(p&&t.globalPropertyAspectConfigurations){const C=p.getGlobalPropertyConfiguration()?.aspects?.find(S=>S.type===z.Text&&t.globalPropertyAspectConfigurations?.map(w=>w.aspectName).includes(S.name));if(C){const w=p.getGlobalPropertyStateManager().getAspect(C.name);w&&(g=w)}}if(await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.updateMetadata(t.stepName,{color:h,text:g}),e.updateStorage(t.stepName,{text:g,inputText:g});const m=s.map(S=>new ka(S.id,u)),C=new U(m);e.getCommandDispatcher()(C)}),s.length===0&&l){const m=await I.getDefaultVariant(l,t.overrideDefaultVariantId);if(m){const C=await this.selectVariantCommand(t,m,{text:g},[],e,()=>{},()=>{});C?.command&&e.getCommandDispatcher()(C.command)}}else{const{command:m}=W.updateInputText(g||"",s,t,e);m&&e.getCommandDispatcher()(m)}}}}else{const c=e.getWorkflowExperience().getBundle();if(c&&t.globalPropertyAspectConfigurations){const u=c.getGlobalPropertyConfiguration()?.aspects?.find(A=>A.type===z.Text&&t.globalPropertyAspectConfigurations?.map(h=>h.aspectName).includes(A.name));if(u){const h=c.getGlobalPropertyStateManager().getAspect(u.name);if(h)if(s.length===0&&l){const g=await I.getDefaultVariant(l,t.overrideDefaultVariantId);if(g){const p=await this.selectVariantCommand(t,g,{text:h},[],e,()=>{},()=>{});p?.command&&e.getCommandDispatcher()(p.command)}}else{const{command:g}=W.updateInputText(h,s,t,e);g&&e.getCommandDispatcher()(g)}}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return I.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;return e?(await I.getDefaultVariant(e))?.color:void 0}async getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return I.getDefaultVariant(e)}async getDefaultStrokeColorVariant(t){const e=t.strokeOption;if(e)return I.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new St(t);const a=e.fileLink;if(!a)throw new Rt(e);const n=await Ft(a);return{assetUrl:a,name:n.names.fullName.en}}async selectVariantCommand(t,e,a,n,r,o,s,l,c){const d=r.markUpdatePending(),u=await this.fontDataFromVariant(e);let A=!0;const h=g=>{o(g),g&&(A=!1)};if(n.length>0){const g=n.map(C=>new ka(C.id,u));if(l){const C=n.map(S=>new Aa(S.id,l));g.push(...C)}if(c){const C=n.map(S=>new ha(S.id,c,t.data.strokeThickness));g.push(...C)}const p=await this.changeInputTextWithRegion(t,t.data.size||ma,u,a.text||"",a,r,a?.customiseAllText??!1,h,s);p&&g.push(p);const m=new U(g);return A?{command:m,followup:async()=>{r.markUpdateCompleted(d),await r.setSelectionsAndElements(t.stepName,[e],n)}}:null}else{const g=await this.createTextboxRegions(t.stepName,e,t.data,u,a,r),p=await this.changeInputTextWithRegion(t,t.data.size||ma,u,g[0]?.newElement.input||a.text||t.data.defaultText||"",a,r,a?.customiseAllText??!1,h,s),m=g.flatMap(S=>S.commands);if(l){const S=g.map(w=>new Aa(w.regionElement.id,l));m.push(...S)}if(c){const S=g.map(w=>new ha(w.newElement.id,c,t.data.strokeThickness));m.push(...S)}p&&m.push(p);const C=new U(m);return A?{command:C,followup:async()=>{r.markUpdateCompleted(d)}}:null}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,a,n,r,o){if(!a||!a.regions)throw new Error("Step data not supplied");const s=r.text||a.defaultText||"",l=Nt(s,o),c=this.getProcessedInput(l,a,!1),d=async(A,h)=>{const p=o.getLayouts().find(C=>C.panelId===A.panelId),m=N();try{if(!p)throw new Qe("Failed to find layout for region: "+A.panelId);const C=await I.ensureFullOption(a.colorOption);let S;if(C&&C.variants){const k=await I.getDefaultVariant(C);k&&(S=this.createTextFillSpotColor(C,k),o.updateStorage(t,{colorProfileAssetKey:C.colorProfile?.key}))}const w=await this.getDefaultColor(a),F=w||"#000000",b={stepRegion:A,stepRegionIndex:h,stepName:t,align:this.textAlign(a),fill:r.color?r.color:F,fontSize:a.size||ma,fontData:n,id:m,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,text:c,input:s,type:D.Textbox,vertical:a.vertical,x:A.left,y:A.top,height:A.height,width:A.width,immutable:A.immutable,verticalAlign:a.verticalAlign||"middle",curved:a.curved,paths:a.paths,fillSpotColorDefinition:S},v=[],B=new Map,M=new Map;if(!b.fontData)throw new O("Failed to resolve font data for text.");const[R,x]=Xt(b.fontSize,b.fontData,{left:b.x,top:b.y,width:b.width,height:b.height,rotation:b.rotation,panelId:""},[c],{size:a.size,minSize:a.minSize,maxSize:a.maxSize});B.set(b.id,R),M.set(b.id,x);const T=a.curved||a.vertical?c:(x||[]).join(`
1427
- `);v.push(this.generateTextChangeCommandsForRegion(R,a,b.id,T));const L=new H(b,p);return{regionElement:{id:m,region:A,regionIndex:h},commands:[L,...v],newElement:b,fontData:n}}catch(C){throw console.log(C),new Ne("Error adding font to region")}},u=await Promise.all(a.regions.map(d)).catch(A=>{throw A instanceof Ne?(Qi.setLatestToast("Failed to load font.",pe.Error),A):A instanceof Qe?A:new Error(A)});return await o.setSelectionsAndElements(t,[e],u.map(A=>A.regionElement),async()=>{o.updateMetadata(t,{text:s}),o.updateStorage(t,{text:s})}),u}generateTextChangeCommandsForRegion(t,e,a,n){const r=[],o=new Mi(a,n);if(r.push(o),!e.size){const l=new Di(a,t);r.push(l)}return new U(r)}async changeInputTextWithRegion(t,e,a,n,r,o,s,l,c,d){const u=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),A=Nt(u,o),h=this.getProcessedInput(A,t.data,s),g=o.getRegionElements(t.stepName),p=new Map,m=new Map;for(const b of g)if(b.region){const[v,B]=Xt(e,a,b.region,[h],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});p.set(b.id,v),m.set(b.id,B)}const S=(()=>{if(t.data&&t.data.maxLength&&h.length>t.data.maxLength)return d&&d(!0),{info:"0"};const b=o.getWorkflowExperience().getProfanityList(),v=Sa.split(h.toLowerCase());for(const B of v)for(const M in b){const R=b[M].toLowerCase().replace(/\s/g,"");if(B===R){const T="Blocked profanity.";return l(T),{error:T}}}if(!t.data.vertical&&!t.data.allowNewlines&&(h.includes(`
1428
- `)||h.includes("\r"))){const B="Text may not span multiple lines.";return l(B),{error:B}}if(!t.data.curved&&!Array.from(m.values()).every(M=>M)){const M="Text does not fit.";return l(M),{error:M}}return l(void 0),{info:(t.data.maxLength-h.length).toString()}})();if(S.error){c(S.error);return}if(c(`${S.info} characters remaining`||""),d)return;o.updateStorage(t.stepName,{text:u}),o.updateMetadata(t.stepName,{text:this.injectReplaceableText(u,t.data)}),(r.defaultCleared||!t.data.deleteDefaultOnFocus)&&u.trim()!==""&&o.setMandatoryFulfilled(t.stepName,!0);const w=[];for(const b of g){const v=t.data.curved?h:(m.get(b.id)||[]).join(`
1429
- `);w.push(this.generateTextChangeCommandsForRegion(p.get(b.id)||1,t.data,b.id,v))}return new U(w)}}const W=new ul;class Al{}const hl="data:application/octet-stream;base64,AAEAAAAPAIAAAwBwRkZUTYdHeHoAAElcAAAAHEdERUYAJwBUAAAe2AAAAB5HUE9TkNtcVAAAHygAACoyR1NVQrj/uP4AAB74AAAAME9TLzJoWmUcAAABeAAAAGBjbWFwtkIacAAAAxAAAAJWZ2FzcP//AAMAAB7QAAAACGdseWY27KOUAAAGCAAAFcRoZWFkFPal0gAAAPwAAAA2aGhlYQU0Ar0AAAE0AAAAJGhtdHiADw6qAAAB2AAAAThsb2Nh5CzfJAAABWgAAACebWF4cACVAEwAAAFYAAAAIG5hbWXeIPPyAAAbzAAAAiJwb3N0ABeZTwAAHfAAAADdAAEAAAABAAAZ9vREXw889QALA+gAAAAA2ZexNAAAAADZl7E0ADL/yQJ2ArwAAAAIAAIAAAAAAAAAAQAAArz/wwAAAqsAAAAAAnYAAQAAAAAAAAAAAAAAAAAAAE4AAQAAAE4ASQAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAAEAbsBkAAFAAACigK7AAAAjAKKArsAAAHfADEBAgAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABYWFhYAEAACgCtArz/wwAAAqkANgAAAAMAAAAAAmQCZAAAACAAAgIPADIAAAAAAU0AAAAAAAAAAAAAALQAAAD3ADUCfQA1AcoANQKrADUCDQA1AX4ANQHYADUBNQA1AcgANQHUADUB8AA1AeEANQHpADUBqQA1AdAANQHpADUCqgA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUB3AA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUAtAAAAAAAAAAAAAMAAAADAAAAHAABAAAAAAFQAAMAAQAAABwABAE0AAAALgAgAAQADgAAAAoADQAhACYAKgA5AFoAXgB6AKAArQDFAM8A1gDdAOUA7wD2AP0A/wF4//8AAAAAAAoADQAgACMAKgAwAEAAXgBhAKAArQDAAMcA0QDYAOAA5wDxAPgA/wF4//8AAf/5//f/5f/k/+H/3P/W/9P/0f+s/6AAAAAAAAAAAAAAAAAAAAAA/0v+twABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYAIAAwADoARABOAF4AaAAAAAAAAAAXABcAFwAXABcAFwAZABsAGwAbABsAHwAfAB8AHwAkACUAJQAlACUAJQAlACsAKwArACsALwAyADIAMgAyADIAMgA0ADYANgA2ADYAOgA6ADoAOgA/AEAAQABAAEAAQABAAEYARgBGAEYASgAAAQYAAAEAAAAAAAAAAQIDAAAEAAAAAAAAAAAAAAAAAAAAAQAABQYABwgJCgAAAAsAAAAAAAwNDg8QERITFBUAAAAAAAAWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAAAAAxAAAyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKSwAAAAAAFxcZGyQlKzIyMjIyMjQ2NjY2Ojo6Oj9AQEBAQEZGRkYAAAAAAAAAAAAAAAAAAAAlAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAABMFxclAAAAAAAAAAAAAEovAAAAAAAAAAAAAAAXGxcbGx8fHx8lJQAlKysrAAAAAAAAAAAAAAAAAAAAACgAKAAoACgAKAAoADwAbgC0AQgBbgGQAcYB1AIGAkYCYAKSAtAC4gMoA2ADyAPgBBoEUAR4BI4EogTWBOoE9gUiBToFSAViBXoFqgXWBjAGWgaaBqwG2AbqBwYHIAc2B0wHXgd2B7AH5ggOCCQIOAhsCIAIjAi4CNAI3gj4CRAJQAlsCcYJ8AowCkIKbgqACpwKtgrMCuIK4griAAAABQAyAAAB3QK8AAMABgAJAAwADwAAEyERIRsCCwEREwMhAxMRMgGr/lUcubrGtMG5AXKttQK8/UQCqP7LATX+tgEs/acBGP7MAUn+0QJdAAACADUABQDCAmoAAwAHAAATESMRExUjNcGLi4sCaf5mAZr+KY2NAAAAAgA1AAACSAJkABsAHwAAJQcjNyMHIzcjNzM3IzczNzMHMzczBzMHIwczByc3IwcBthdrFkoXbBdeDl8KYA9fFWwVShVtFWoPagpqDscJSgqqqqqqqmxHbJqamppsR2xsR0cAAAEANf/JAZUCqgAwAAABFR4BByM0LgEjIgYVFBYXHgMVFA4BBxUjNS4BNTMUFjMyNjU0LgInJjU0Njc1ARwwPAF3CBQOExcsPCEwFgkZNyhnPkGDGRQTGBElHBprRzQCqkQNV0INGBIdFB8hGw4tMCkUJkU7EENDCmk8GiUgFBIeGA4LKXpKVxBEAAAABQA1/+8CdgJrAAwAGAAcACkAOAAAEzQ2MzIeARUUBiMiJjcVFBYzMjY1NCYiBiUDIxMDNTQ+ATMyFhQGIyImNxUUHgEzMjY1NC4BIyIGNk02JD0jTTc2TVEeFBUeHiodAWjhVeEtIz0kN01ONjZOUQ4YDRUeDhcOFR4B1j5XKEUoPldXPgEXISEYGCEhcf2dAmP+JgEoRChXfFdWPwEPGhAiGBAbDyIAAwA1AAAB2AJnACQAOQBIAAAlFwcnDgEjIiY1ND4CNyY1NDYzMhYVFA4IBxc3MyciBhUUHgQXPgU1NCYjAxY+ATcnDgUVFBYBmT8qQgdUMk1cDyETFDVTNzdPAwUJBw0HDgUMATUabPULGQQFCgUKAQENBAsEBBYNAQ8bEQRRAQ4ECwUEIbFNZEERMGJKHzMqEhFDQD9ZVjsLFxITDRAJDgULAUFBtRgSBw4LDwcOAQEQBg8LDwcPGf58AQsOB2IBDQUOCg8IGyQAAAAAAQA1ATwBSQJtABEAABMHNxcHFwcnFyM3Byc3JzcXJ+YXVSVnZyhTGE0WUShnZyVWGAJselJLJSVOVXp7Vk4nI0tReQACADUAAAGjAmQAFwAmAAA3NTQ+AzMyHgMdARQOAiMiLgI3FRQeATMyPQE0IyIOAjYZJzIvFxQtMicaIjc9Hh09OiR8CBsXOTkSGAsF4KQxTzEhDQwhMFAypDtaMhkYMlvjrBUkH1isVxEeGgABADUAAAEAAmEABQAAMxEjNTMRhE7KAd6D/Z8AAQA1AAMBkwJmACEAADc1Njc+AzU0JiMiByM+Ajc+AzMyFhUUBgcGBzMVOi5WFxkaCx0XMQJ2AQINDQ4qLCIQTlkjLkAargN3L1kYHCcoFyIhXhsgNxccJxIHbU04WDRHHYEAAAEANQAAAZ8CZAAtAAATNjc2MzIWFRQOAwcWFRQGIyImJyYnMxYXMjY1NC4DKwE1MzI1NCYjIgdDAjktP0RVCw0VCwlca0otVRYVBn4KLhobCg8UDQcsFT0RESQCAaxgMCdfQRcoGBcIBiVpTWwrKCRENgElHRAYCwcCbzsVHjMAAgA1//8BuwJjAAoADQAAITUjNRMzETMVIxUnMzUBDdfadDY20WJrcgGF/oN6a+XAAAAAAAEANf//AawCYwAgAAABFSMHNjMyHgIVFA4CIyIuASczFjMyNjU0JiMiBycTAX+uCxsnKUIlExYrSy8zUS8HfRYjGygkHy4SZSoCYoBSEic+QyEkSkIqL00xJi8hHy80HwFTAAACADUAAAG0AmIAFgAoAAABMhYVFAYjIiYnJjU0PwEzBw4BBzAyNgMyPgE1NC4EIyIGFRQeAQEaO19vTy9QGCksepBYAw4CCA0kEx8TBAgLDxQLHSUVHQGvbF9kgConOV1LVdqUBRYFAv7XFCYXChMSEAwHLyEaJxIAAAAAAQA1//8BdAJjAAYAABMhFQMjEyM2AT6sibS9AmJ3/hUB3wAAAwA1AAABmwJkABkAJAAuAAATNTQ2MhYVFA4BBxYVFA4BIi4BNTQ3LgMXFRQWMjY1NCYiBjcVFBYyNjQmIgZCVqBWFBAMPC1RaFEtPAkLEgpwHjAdHTAeCRskGxskGwG/AUJhYkIeMxINJGU5WjMzWjllJAkNHSbhARgqKhkaKirTARcfHy8fHwAAAAACADUAAAG0AmQAFgAkAAA/AT4BNyYOASMiJjU0NjMyFhcWFRQPARM1NC4BIyIGFRQWMzI2fVgDDQQBCA0EO15uTy9QGCoteSsVHhAcKCUfHiUBlAQWBgEBAWxfZIAqJzldTFXaAYkBGiYSLiIgMi4AAgA1/8wCdQJtADgASAAAAQcGBwYzMjY1NCYjIgYHBh4DFxY3FQYnLgQ3ND4CMzIWFRQGIyInBicuATU0NjMyFhc3BzY1NC4CJyYGHQEUFjc2AfscBAIBFhYmbFVhdgcBBhwtVThNX01cQGlGMBUBLExzQniZWjs3FB07NT1PQBwoBwgqCQIHEg0gKCAUIQG2ux0NGVo8Wm2Laxg2RTcpBAUfWxsCASlBVlsvQHpfOqF8XZBBNwEBWkRIcyAWKMkaIgcQGBEBAz8rAyYjAQIAAAIANQAAAcgCZQAHAAoAADcHIxMzEyMvAge8GG6bYJdvGhknK3JyAmT9nHJz1tYAAAMANQABAWQCaAAPABoAJQAANxEzMhcWFRQHFhUUBw4BIwMzMjc2NTQnJisBFxUzMjc2NTQnJiM2lEAiJC9DJhszNx0mEgkQEAgUJQExFAsVFAoWAgJlKShQUygka1cuIhMBfAYLIB4LBuNwCA4mIgwGAAAAAQA1AAABqQJnACUAACUzDgEjIi4CNTQ+AjMyHgMXIy4DIyIOARUUFjMyPgIBSWAQX0cxSiwWFStLMSM7KB4QA2AFDhQfER4pEi8qFCEUCulrfjNXbD47alk0HzJAPR0SISATNEwsSWcXJxkAAgA1AAABgwJlAA8AGAAAMxEzMh4DFxYVFA4CIwMRMzI1NCcmIzZ/EhcsICYOJBUtTzUiKF4TFzMCZAEMFi4hT29BbFcwAdr+r6dDLjkAAAABADUAAAE3AmUACwAAEyEVIxUzFSMVMxUhNgEBlpGSlv8AAmR4cHmKeQAAAAEANQAAATcCZQAJAAAzESEVIxUzFSMRNgEBmJOTAmR5b3r+/gAAAAABADUAAAG3AmYAIQAAARUmBw4CFRQeAjMyNzY3IzUzFgcGIyIuATU0NjMyFhcBQBQ3FygbEBkgESEWGQVr0wUTMH89WCpiX0haEAGbAUgCASNPOC1FKhUaHDlpZkOyVYlXiaZvWwAAAAEANQAAAYYCZQALAAAzIxEzFTM1MxEjNSOcZmaDZ2eDAmTm5v2c9QABADUAAACgAmUAAwAAMxEzETZpAmT9nAABADUAAAFRAmUAGgAAAREUBwYHBiMiLgMnJjUzFBYVFjMyNzY1EQFQDQ8fJi4IESsgIAUCcQEEGxUHBAJk/pZkLCscIwIRHkEsFxcCDAQzGxAhAZEAAAAAAQA1//8BiwJmAAoAABcRMxETMwMTIwMRNmdzbISTfnABAmb+7AEU/s/+zAEJ/vYAAQA1AAABGgJlAAUAADMRMxEzFTZpewJk/iaKAAEANQAAAeUCZQAMAAAzIxEzGwEzESMTAyMDlmCLTEuMYARZRVgCZP52AYr9nAHK/jYBygABADUAAAGMAmUACQAAGwEDMxEjAxMjEZ2NAWNikwJjAmT+lAFs/ZwBaf6XAmQAAAACADUAAAGsAmUADAAfAAATNDYzMhYVFA4BIyImNxQWMzI+BDU0LgIjIg4BNmRWUWs0VDRWZGgqKg8aEQ0IAwgSIhceJw4BLKGXmJpfjUaelUtjDxohKCcUHzo1IDVKAAACADUAAAFgAmYAEAAbAAATMzIeARcWFRQGBw4BKwEVIxMVMzI3NjU0JyYjNoEjMRoMLhcSFjEtKGRkJRoNGBkOHAJlCxMPO2cvWRkdGMAB3ZMJEi8uEQoAAwA1//8BvwJmABsALgA8AAAlFwYiLgInDgIjIi4BNTQ+ATMyFhUUBx4CAyIOBAc2MzIXFhc2NTQuAQMeAzsBMjcmJyYjIgG9AQINGRgcChMsFBM+VycmWD1Uah0GDQzAERwSDQcCARgVKCIbHQkbLGgGFRUTBgYWDhEOGSAPenkBAggSDRMTAlaGU1GIXK5/ZUkIBwEBZxIgHScLCBEoHzQeLTJOKP7/HCgQCQwiFSMAAAAAAgA1//8BjwJmAA0AGgAAJRcjJxUjETMXFhcWFRQnNjU0LgInKwEVMzIBDYF+cGpqOi4UW4QYCxARBQY1Lhb7++vqAmQBBQosgohEFyoVHg4IAZkAAQAyAAABjwJnACsAADczFBY3NjU0JicuAycmPgEzMhYXIy4DIyIGFRQWFx4BFRQOAiMiJjZ2JBIyJjwRICobAQE0TSs5WQp0AQMJEg0RHCdBQTEUJkQsXFbFKx8BBDgWIB4JFyg7ITlVKFRbCwwTCh0UFSIkJEc2JUE3IGkAAAABADUAAAFTAmUABwAAMxEjNSEVIxGLVQEdVQHseHj+FAAAAAABADUAAAGNAmUAGgAAEzMRFBceATI2NzY1ETMRFA4BBwYjIiYnLgE1NmsIBR8qHgUIagcQDjBUIk0ZGQwCZP6WLhsSGBYQFzUBa/6WM0MvFEEcJCZISwAAAQA1AAABpwJlAAYAADMDMxsBMwO2gGdQUWmAAmT+UwGt/ZwAAQA1AAACQAJkAAwAADMDMxsBMxsBMwMjCwGfaWk4PFA8OGhrWz4+AmP+cwGN/nEBj/2dAYz+dAABADUAAAHBAmUACwAAMxMDMxc3MwMTIycHNop6c0NCcnmJc1VRAUYBHq6u/t/+vdnZAAAAAQA1AAABlAJlAAkAADczAzMXNzMDFSOsAXdvQUFtd3HrAXn29v6H6wAAAAABADUAAAFDAmYACQAAAQMzFSE1EyM1IQFDiIj+85OTAQ0B5v6kimcBdYkAAAEANQFFAaYCagAGAAAbATMTIycHNnx3fYE4NwFFAST+3LOzAAIANQAAAcgCZQAHAAoAADcHIxMzEyMvAge8GG6bYJdvGhknK3JyAmT9nHJz1tYAAAMANQABAWQCaAAPABoAJQAANxEzMhcWFRQHFhUUBw4BIwMzMjc2NTQnJisBFxUzMjc2NTQnJiM2lEAiJC9DJhszNx0mEgkQEAgUJQExFAsVFAoWAgJlKShQUygka1cuIhMBfAYLIB4LBuNwCA4mIgwGAAAAAQA1AAABqQJnACUAACUzDgEjIi4CNTQ+AjMyHgMXIy4DIyIOARUUFjMyPgIBSWAQX0cxSiwWFStLMSM7KB4QA2AFDhQfER4pEi8qFCEUCulrfjNXbD47alk0HzJAPR0SISATNEwsSWcXJxkAAgA1AAABgwJlAA8AGAAAMxEzMh4DFxYVFA4CIwMRMzI1NCcmIzZ/EhcsICYOJBUtTzUiKF4TFzMCZAEMFi4hT29BbFcwAdr+r6dDLjkAAAABADUAAAE3AmUACwAAEyEVIxUzFSMVMxUhNgEBlpGSlv8AAmR4cHmKeQAAAAEANQAAATcCZQAJAAAzESEVIxUzFSMRNgEBmJOTAmR5b3r+/gAAAAABADUAAAG3AmYAIQAAARUmBw4CFRQeAjMyNzY3IzUzFgcGIyIuATU0NjMyFhcBQBQ3FygbEBkgESEWGQVr0wUTMH89WCpiX0haEAGbAUgCASNPOC1FKhUaHDlpZkOyVYlXiaZvWwAAAAEANQAAAYYCZQALAAAzIxEzFTM1MxEjNSOcZmaDZ2eDAmTm5v2c9QABADUAAACgAmUAAwAAMxEzETZpAmT9nAABADUAAAFRAmUAGgAAAREUBwYHBiMiLgMnJjUzFBYVFjMyNzY1EQFQDQ8fJi4IESsgIAUCcQEEGxUHBAJk/pZkLCscIwIRHkEsFxcCDAQzGxAhAZEAAAAAAQA1//8BiwJmAAoAABcRMxETMwMTIwMRNmdzbISTfnABAmb+7AEU/s/+zAEJ/vYAAQA1AAABGgJlAAUAADMRMxEzFTZpewJk/iaKAAEANQAAAeUCZQAMAAAzIxEzGwEzESMTAyMDlmCLTEuMYARZRVgCZP52AYr9nAHK/jYBygABADUAAAGMAmUACQAAGwEDMxEjAxMjEZ2NAWNikwJjAmT+lAFs/ZwBaf6XAmQAAAACADUAAAGsAmUADAAfAAATNDYzMhYVFA4BIyImNxQWMzI+BDU0LgIjIg4BNmRWUWs0VDRWZGgqKg8aEQ0IAwgSIhceJw4BLKGXmJpfjUaelUtjDxohKCcUHzo1IDVKAAACADUAAAFgAmYAEAAbAAATMzIeARcWFRQGBw4BKwEVIxMVMzI3NjU0JyYjNoEjMRoMLhcSFjEtKGRkJRoNGBkOHAJlCxMPO2cvWRkdGMAB3ZMJEi8uEQoAAwA1//8BvwJmABsALgA8AAAlFwYiLgInDgIjIi4BNTQ+ATMyFhUUBx4CAyIOBAc2MzIXFhc2NTQuAQMeAzsBMjcmJyYjIgG9AQINGRgcChMsFBM+VycmWD1Uah0GDQzAERwSDQcCARgVKCIbHQkbLGgGFRUTBgYWDhEOGSAPenkBAggSDRMTAlaGU1GIXK5/ZUkIBwEBZxIgHScLCBEoHzQeLTJOKP7/HCgQCQwiFSMAAAAAAgA1//8BjwJmAA0AGgAAJRcjJxUjETMXFhcWFRQnNjU0LgInKwEVMzIBDYF+cGpqOi4UW4QYCxARBQY1Lhb7++vqAmQBBQosgohEFyoVHg4IAZkAAQAyAAABjwJnACsAADczFBY3NjU0JicuAycmPgEzMhYXIy4DIyIGFRQWFx4BFRQOAiMiJjZ2JBIyJjwRICobAQE0TSs5WQp0AQMJEg0RHCdBQTEUJkQsXFbFKx8BBDgWIB4JFyg7ITlVKFRbCwwTCh0UFSIkJEc2JUE3IGkAAAABADUAAAFTAmUABwAAMxEjNSEVIxGLVQEdVQHseHj+FAAAAAABADUAAAGNAmUAGgAAEzMRFBceATI2NzY1ETMRFA4BBwYjIiYnLgE1NmsIBR8qHgUIagcQDjBUIk0ZGQwCZP6WLhsSGBYQFzUBa/6WM0MvFEEcJCZISwAAAQA1AAABpwJlAAYAADMDMxsBMwO2gGdQUWmAAmT+UwGt/ZwAAQA1AAACQAJkAAwAADMDMxsBMxsBMwMjCwGfaWk4PFA8OGhrWz4+AmP+cwGN/nEBj/2dAYz+dAABADUAAAHBAmUACwAAMxMDMxc3MwMTIycHNop6c0NCcnmJc1VRAUYBHq6u/t/+vdnZAAAAAQA1AAABlAJlAAkAADczAzMXNzMDFSOsAXdvQUFtd3HrAXn29v6H6wAAAAABADUAAAFDAmYACQAAAQMzFSE1EyM1IQFDiIj+85OTAQ0B5v6kimcBdYkAAAAAEADGAAEAAAAAAAEACAASAAEAAAAAAAIABwArAAEAAAAAAAMAFQBfAAEAAAAAAAQACACHAAEAAAAAAAUAIgDWAAEAAAAAAAYADwEZAAEAAAAAABAACAE7AAEAAAAAABEABwFUAAMAAQQJAAEAEAAAAAMAAQQJAAIADgAbAAMAAQQJAAMAKgAzAAMAAQQJAAQAEAB1AAMAAQQJAAUARACQAAMAAQQJAAYAHgD5AAMAAQQJABAAEAEpAAMAAQQJABEADgFEAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAADEALgAwADAAMgA7AFYAZQBnAGUAbQBpAHQAZQBSAGUAZwB1AGwAYQByAAAxLjAwMjtWZWdlbWl0ZVJlZ3VsYXIAAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFYAZQByAHMAaQBvAG4AIAAxAC4AMAAwADIAOwBGAG8AbgB0AHMAZQBsAGYAIABNAGEAawBlAHIAIAAzAC4AMwAuADAAAFZlcnNpb24gMS4wMDI7Rm9udHNlbGYgTWFrZXIgMy4zLjAAAFYAZQBnAGUAbQBpAHQAZQBSAGUAZwB1AGwAYQByAABWZWdlbWl0ZVJlZ3VsYXIAAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAAAAAAgAAAAAAAP+DADIAAAAAAAAAAAAAAAAAAAAAAAAAAABOAAAAAQACAQIBAwADAAQABgAHAAgACQANABMAFAAVABYAFwAYABkAGgAbABwAIwAkACUAJgAnACgAKQAqACsALAAtAC4ALwAwADEAMgAzADQANQA2ADcAOAA5ADoAOwA8AD0AQQBEAEUARgBHAEgASQBKAEsATABNAE4ATwBQAFEAUgBTAFQAVQBWAFcAWABZAFoAWwBcAF0ArAEECWNvbnRyb2xMRgljb250cm9sQ1IKc29mdGh5cGhlbgAAAAAAAAH//wACAAEAAAAMAAAAFgAAAAIAAQABAE0AAQAEAAAAAgAAAAAAAQAAAAoALAAuAAJERkxUAA5sYXRuABgABAAAAAD//wAAAAQAAAAA//8AAAAAAAAAAQAAAAoAMAA+AAJERkxUAA5sYXRuABoABAAAAAD//wABAAAABAAAAAD//wABAAAAAWtlcm4ACAAAAAEAAAABAAQAAgAAAAEACAABKd4ABAAAAEYAlgEwAd4CjAM2A+AEegUsBWYGDAa+B3AIHgjQCYIKNAriC4gMAgx0DOYNZA3mDlQOyg88D54QEBCGEQARchHsEmIS1BOWFAwUghTwFWIV1BaiFxQXkhgEGMYZdBomGtQbfhwYHL4dYB3+HpgfPh/oIJYhPCHmIpQjRiPsJJolSCXuJpQnQifoKJIpRAAmAAn/8QAK//sADP/7AA3/+wAO//sAD//7ABD/+wAR//sAEv/7ABP/+wAU//sAFf/xABb/8QAZ//sAHf/2AB7/+wAf//sAIP/xACH/+wAi//sAI//7ACT/+wAl//EAJv/2ACf/8QAo//sAKf/2ACr/+wAr//sALP/sAC3/7AAu/+IAL//dADD/9gAx/+wAMv/7ADP/+wA0//YAKwAG//EACP/nAAn/4gAK/9MAC//iAAz/9gAN/+IADv/sAA//4gAQ/9gAEf/iABL/1QAT//EAFP/nABX/8QAW/9gAMf/TADL/pgAz//MANP/nADX/8QA2//EAN//7ADj/7gA5//YAOv/7ADv/2AA8//EAPf/2AD7/9gA///EAQP/sAEH/+wBC/+wAQ//xAET/7ABF/+wARv/2AEf/3QBI/90ASf/EAEr/zgBL//YAKwAG//YAB//2AAn/3QAL/+wADP/sAA3/8QAO//YAD//sABD/8QAR/+wAEv/iABP/5wAU/+wAFf/dABb/7AAX/78AMf/YADL/sAAz/+IANP/iADX/8QA2/+cAN//xADj/3QA5/+wAOv/2ADv/4gA8//EAPf/xAD7/8QA///YAQP/YAEH/9gBC/+cAQ//sAET/7ABF/+wARv/xAEf/zgBI/9MASf/OAEr/zgBL/+wAKgAG//YAB//iAAj/4gAK/+IADP/dAA3/ugAO/+IAD//iABD/5wAR/+IAEv/dABP/yQAU/90AFf+mABb/0wAx/5gAMv/YADP/4gA0/9MANf/xADb/7AA3/+wAOP/iADn/7AA6//EAO//dADz/5wA9/+wAPv/sAD//5wBA/9gAQf/sAEL/zgBD/+wARP/YAEX/tQBG/90AR/+hAEj/oQBJ/8QASv+DAEv/7AAqAAb/8QAH/90ACP/YAAn/oQAL/8kADP/iAA3/sAAO/+cAD//YABD/4gAR/90AEv/bABP/4gAU/+IAFf/TABb/5wAg/+QAMf/nADL/3AAz//QANP/rADX/9AA2//IAN//4ADj/8AA5//QAOv/1ADv/7AA8/+oAPf/7AD7/9wA///IAQP/tAEH/+wBC/+IAQ//2AET/4wBF/7YARv/vAEf/pgBK/6MAS//yACYAB//TAAj/8QAK/84ADP/dAA3/9gAO//EAD//dABD/pgAR/8kAEv+6ABP/7AAU/90AFf/OADH/xAAy/5IAM//sADT/3QA1/+cANv/xADf/9gA4/90AO/9WADz/5wA9//EAPv/sAD//5wBA/84AQf/dAEL/0wBD/+cARP/nAEX/5wBG/+cAR//dAEj/2ABJ/7oASv/JAEv/4gAsAAb/+wAH//sACP/xAAn/zgAK/+cAC//dAAz/9gAN/9gADv/tAA//7AAQ/+kAEf/rABL/3QAT/90AFP/hABX/3QAW/90AMf/nADL/vwAz/+cANP/nADX/8QA2//EAN//sADj/5wA5//YAOv/2ADv/4gA8//EAPf/2AD7/+wA///sAQP/2AEH/+wBC/+wAQ//7AET/7ABF/9MARv/7AEf/yQBI/84ASf+wAEr/xABL/+cADgAG//sACf/xAAv/7AAN//sADv/7AA8AAAAR//EAEv/0ABP/9gAU//EAFf/xABb/7AAx//YAQP/2ACkABv/7AAf/9gAI//sACf/iAAr/5wAL/+wADP/vAA3/3QAO//sAD//qABD/8QAR/+wAEv/nABP/8QAU/+cAFf/iABb/7AAx/+cAMv/vADP//AA0/+cANf/7ADb//gA4//EAOf/8ADr//AA7/+kAPP/6AD3//QA+//4AP//7AEL/6gBD//0ARP/2AEX/7ABG//EAR//YAEj/4gBJ/+wASv/LAEv//AAsAAb/+wAH//EACP/2AAn/0wAK/+IAC//JAAz/5wAN/90ADv/iAA//7AAQ/+cAEf/sABL/3QAT/9MAFP/iABX/zgAW/+cAMf/YADL/xAAz/+wANP/dADX/6AA2//EAN//xADj/4wA5//EAOv/2ADv/7AA8/+wAPf/sAD7/9gA//+wAQP/iAEH/8QBC/90AQ//nAET/5wBF/8QARv/mAEf/xABI/8kASf+1AEr/rQBL/+IALAAG//sAB//7AAj/9gAJ/9MACv/2AAv/ugAM/+kADf/dAA7/9gAP/+wAEP/2ABH/8AAS//EAE//2ABT/5wAV/9gAFv/sADH/vwAy/9UAM//eADT/3wA1//EANv/xADf/9gA4/+IAOf/xADr/9gA7/+wAPP/xAD3/9gA+//EAP//2AED/2ABB//EAQv/nAEP/9gBE/+cARf/TAEb/8QBH/9gASP/YAEn/xgBK/78AS//xACsABv/7AAf/9gAI/+wACf/TAAr/5wAL/90ADP/lAA3/zgAO/90AD//dABD/7AAR/+IAEv/iABP/2AAU/+IAFf/JABb/5wAx/90AMv/EADP/6wA0/+EANf/wADb/8AA4/9wAOf/dADr/7AA7/9gAPP/sAD3/5wA+/+wAP//iAED/0wBB/+IAQv/YAEP/4gBE/84ARf/JAEb/4gBH/8kASP/OAEn/vwBK/8kAS//TACwABv/7AAf/3wAI/+cACf+wAAr/4wAL/8kADP/dAA3/xwAO/+cAD//dABD/7AAR/+cAEv/iABP/yQAU/9cAFf+/ABb/4gAa/+kAMf/YADL/uwAz/+EANP/dADb/6wA3//MAOP/lADn/8QA6//IAO//eADz/5wA9/+4APv/zAD//8ABA/+IAQf/2AEL/6gBD//YARP/kAEX/zABG/+8AR/+0AEj/uwBJ/64ASv+vAEv/5QAsAAb/+wAH/90ACP/nAAn/4gAK/9MAC//nAAz/3QAN//YADv/eAA//3QAQ/7AAEf/OABL/sAAT//sAFP/dABX/0wAW/9MAMf/iADL/iAAz//YANP/OADX/9gA2//EAN//xADj/0wA5//YAOv/zADv/gAA8//EAPf/7AD7/+wA///YAQP/OAEH/7gBC/84AQ//2AET/2ABF//sARv/2AEf/5wBI/+cASf/TAEr/4gBL/+wALAAG//sAB//2AAj/8QAJ/9gACv/nAAv/3QAM/+IADf/dAA7/4gAP/+IAEP/nABH/5wAS/9gAE//YABT/3QAV/84AFv/sADH/5wAy/78AM//nADT/2AA1/+cANv/nADf/7AA4/90AOf/sADr/7AA7/+cAPP/sAD3/8QA+/+wAP//xAED/4gBB//EAQv/dAEP/5wBE/+IARf/YAEb/5wBH/78ASP/HAEn/sABK/7UAS//dACsABv/xAAf/8QAI/+IACf/dAAr/0wAL/+IADP/iAA3/3QAO/+cAD//dABD/zgAR/9MAEv/EABP/0wAU/84AFv/dADH/4gAy/6EAM//jADT/3QA1/+wANv/sADf/5wA4/90AOf/nADr/8QA7/78APP/xAD3/9gA+/+wAP//nAED/3QBB/+cAQv/nAEP/5wBE/+IARf/OAEb/3QBH/8QASP/JAEn/lwBK/7oAS//YACkABv/sAAf/0wAI/90ACf/OAAr/3QAM/90ADf/EAA7/5wAP/9gAEP/YABH/3QAS/9MAE//YABT/4gAV/90AMf/sADL/wAAz/+8ANP/kADX/6wA2//AAN//2ADj/5AA5//EAOv/uADv/1gA8//QAPf/2AD7/8QA///AAQP/dAEH/7ABD/+gARP/YAEX/1QBG/+wAR/+3AEj/wwBJ/7UASv+wAEv/5gAeAAf/zgAi/+4AI//5ACT/7wAy/9AAM//pADT/sQA1/+sANv/nADf/5gA4/7oAOf/vADr/9wA7/9AAPP/sAD3/6wA+/+YAP//sAED/uwBB/+kAQv+7AEP/5ABE/9QARf+6AEb/0ABH/34ASP+SAEn/zQBK/5sAS//nABwAF//RACT//wAy/9EAM//uADT/5wA1/+8ANv/3ADf/7gA4/+gAOf/3ADr/+wA7/9oAPP/vAD3/9wA+/+4AP//vAED/4QBB//cAQv/nAEP/7wBE/+4ARf/QAEb/9wBH/8EASP/MAEn/wwBK/7sAS//nABwAF//QABv/+QAy/8EAM//zADT/6wA1//sANv/zADf/+wA4/+8AOf/zADr//gA7/+EAPP/vAD3/9wA+//kAP//3AED/4gBB//kAQv/jAEP/8wBE/+YARf/VAEb/+QBH/84ASP/JAEn/twBK/8EAS//rAB8ABv/7ABL/3wAX/8kAJf/5ACv/7wAy/7oAM//zADT/6wA1/+8ANv/uADf/8wA4/+oAOf/vADr/7wA7/9QAPP/5AD3//gA+//EAP//vAED/4wBB//MAQv/mAEP/7gBE/+cARf/XAEb/6wBH/8kASP/JAEn/twBK/7cAS//nACAABv/7ACQAAgAl/+8AJ//5AC3//gAv//4AMv/oADP//QA0/+sANf/7ADb/+gA3//sAOP/jADn/9wA6//oAO//kADz//wA9//0APv/+AD8AAABA/+gAQf/7AEL/6ABD//sARP/sAEX/8QBG//sAR//qAEj/6wBJ/+cASv/qAEv/+QAbAAb/+wAl/+8AMv+5ADP/+wA0/+8ANf/7ADb/+wA3//0AOP/vADn/+wA6AAAAO/+7ADz//gA9//4APv/7AED/7ABB//4AQv/nAEP/+QBE//kARf/7AEb/+QBH//MASP/rAEn/4gBK/+8AS//7AB0ABv/2ABf/zgAl/+8AMv+3ADP/9wA0/+sANf/3ADb/8QA3//kAOP/uADn/8wA6//sAO//YADz/8wA9/+4APv/3AD//8wBA/+MAQf/3AEL/6QBD/+8ARP/nAEX/1ABG/+8AR//JAEj/zABJ/6YASv/JAEv/3AAcAAb/+wAX//MAJf/7ADL/6wAz//4ANP/uADX/+wA2//4AN//+ADj/8wA5//0AOv/+ADv/7gA8//4APf/+AD7/+wA///4AQP/uAEL/9wBD//4ARP/+AEX/+QBG//4AR//uAEj/9wBJ/+4ASv/zAEv//gAYAAb/+wAx//YAMv/rADP//wA0//MANf//ADYAAQA3//8AOP/zADv/6AA8//4APf/+AD4AAQBA/+4AQf//AEL/8wBD//4ARP/4AEX//QBH/+wASP/3AEn/7ABK//EASwABABwABv/2ABf/4QAy/8oAM//9ADT/+QA1//4ANv/7ADf//gA4//MAOf/+ADr//wA7/+EAPP/7AD3//gA+//4AP//+AED/7wBB//4AQv/zAEP//gBE//sARf/7AEb//gBH/+8ASP/5AEn/2gBK//oAS//+AB0ABv/nABf/5wAx/7AAMv/hADP/7gA0/7QANf/rADb/5wA3/+4AOP+sADn/6wA6//kAO/+3ADz/6gA9/+8APv/nAD//5wBA/6wAQf/uAEL/rgBD/+cARP+8AEX/3ABG/9oAR//cAEj/0QBJ/9oASv/RAEv/7wAeAAb/9gAX//cAI//9ADH/vwAy/+4AM//5ADT/2gA1//4ANv/3ADf/+wA4/9oAOf/3ADr/+wA7/+cAPP/7AD3/+QA+//cAP//5AED/1ABB//sAQv/cAEP/9wBE/+8ARf/JAEb/6wBH/8QASP++AEn/5wBK/8EAS//+ABwAF//7ADH/7AAy/+QAM//+ADT/7gA1//4ANgAAADf//QA4//cAOf/7ADr//gA7/+4APP/+AD3//gA+//0AP//7AED/7wBB//4AQv/uAEP//gBE//cARf/7AEb/+QBH/+gASP/vAEn/6wBK/+gAS//+AB4ABv/7ABf/8wAa//4AHf/3ACX/9wAq//4AMf/2ADL/5AAz//0ANP/zADX/+wA2//4AN//+ADj/+QA7/+4APf/+AD7/+wA///4AQP/2AEH/+gBC/+4AQ//7AET/+QBF//sARv/+AEf/8wBI/+8ASf/zAEr/6wBL//4AHQAG//EAJP/3ADH/7AAy/7sAM//sADT/4wA1/+8ANv/vADf/9wA4/+QAOf/qADr/9wA7/98APP/vAD3/9wA+/+sAP//uAED/4wBB/+4AQv/mAEP/7wBE/+IARf/VAEb/7gBH/8MASP/GAEn/uwBK/7oAS//fABwABv/sACT//gAy/54AM//rADT/6gA1//EANv/rADf/9wA4/+MAOf/oADr/9wA7/64APP/sAD3/8QA+/+wAP//sAED/4QBB//MAQv/oAEP/5ABE/9gARf/kAEb/7gBH/9EASP/QAEn/uwBK/8QAS//zADAAF//3ABj//wAZ/+kAGv//ABv//QAc//4AHf/pAB7/+wAf//8AIP/iACH//gAi//8AI//+ACT//wAl/+IAJ//uACj//gAp/+cAKv/hACv/+QAs/8MALf/QAC7/5AAv/8wAMP//ADL/4QAz//4ANP/jADX/9wA3//kAOP/fADn/9wA7/+IAPP/5AD3/+gA+//EAP//6AED/2gBB/+8AQv/aAET/7wBF/9cARv/qAEf/xgBI/7sASf/qAEr/tABL//sAHQAG/+cAF//oACT/+gAy/+IAM//xADT/zAA1/+8ANv/sADf/+gA4/8wAOf/3ADr/8wA7/8kAPP/uAD3/7wA+/+wAP//rAED/yQBB//cAQv/MAEP/+ABE/9QARf/KAEb/2gBH/8EASP/EAEn/4gBK/7cAS//vAB0ABv/xABv/+QAl/+4AMv+8ADP/7wA0/9wANf/zADb/6AA3//cAOP/hADn/5gA6//MAO//aADz/6QA9//MAPv/pAD//6wBA/+MAQf/3AEL/2gBD/+kARP/rAEX/1ABG/+kAR//JAEj/zABJ/7QASv+7AEv/5wAbAAb/9gAy/6YAM//9ADT/0wA1//oANv/+ADf//QA4/9UAOf/3ADr//wA7/7kAPP/6AD3//gA+//sAP//7AED/0ABB//oAQv/XAEP/+QBE/+IARf/zAEb/9wBH/+8ASP/vAEn/6gBK/+cAS//6ABwABv/7ACQAAgAy/9UAM//7ADT/7wA1//cANv/9ADf//wA4/+4AOf/7ADr//wA7/+sAPP/+AD3//gA+//0AP//6AED/7gBB//sAQv/sAEP/+wBE/+8ARf/7AEb//QBH/+8ASP/qAEn/3wBK//gAS//+ABwABv/nABf/lQAy/4IAM//3ADT/wQA1/+kANv/nADf/+gA4/8QAOf/oADr/6wA7/5UAPP/uAD3/+wA+//cAP//vAED/wQBB/+8AQv/DAEP/5wBE/84ARf/uAEb/7gBH/+kASP/pAEn/zgBK/+4AS//7ADMABv/sABf/owAY//kAGf/XABr//gAb//4AHP/5AB3/0AAe//gAIP+tACH/8wAi//4AJP/+ACX/0AAm//kAJ//MACj//gAp/9oAKv/+ACv//gAs/+MALf/zAC7/3AAv//cAMP/7ADL/jwAz/+oANP/CADX/7wA2/+oAN//3ADj/xgA5/+sAOv/6ADv/qgA8/+sAPf/7AD7/7wA//+8AQP++AEH/7gBC/8MAQ//qAET/1QBF/+sARv/pAEf/6ABI/+cASf/iAEr/2gBL/+4AHAAG/+cAF//hADL/1AAz/+sANP+wADX/6wA2/+QAN//jADj/qgA5/+cAOv/jADv/ugA8/+cAPf/vAD7/2gA//+kAQP+uAEH/7wBC/64AQ//kAET/uwBF/9oARv/aAEf/zABI/84ASf/TAEr/zQBL/+sAHwAG/+IAF/+lACP//gAk//sAL//uADL/hwAz/+8ANP+sADX/+AA2/9wAN//6ADj/uQA5/+4AOv/vADv/hAA8/+gAPf/pAD7/5wA//+YAQP+wAEH/6QBC/7oAQ//vAET/zgBF/+gARv/oAEf/2gBI/+YASf/QAEr/4gBL/+kAHAAG//sAF//+ADL/5wAz//sANP/kADX/+wA2//8AN//7ADj/4QA5//4AOv//ADv/6wA8//sAPf/+AD7//gA///sAQP/hAEH/+wBC/9oAQ//+AET/7wBF//sARv/6AEf/6QBI//kASf/rAEr/6QBL//sAMAAG/+wAB//YAAj/3QAJ/9MACv+/AAv/yQAM/+IADf/YAA7/7AAP/9MAEP/JABH/5wAS/+IAE//OABT/4gAV/+wAFv/nACD/WwAh/+wAIv/xACP/8QAk//YAJf/xADL/oQAz/+wANP/nADX/7AA2//sAN//2ADj/9gA5//sAO/+PADz/7AA9//YAPv/sAD//8QBA/+IAQf/nAEL/7ABD/+IARP/JAEX/zgBG/+cAR/+/AEj/xABJ/5IASv+/AEv/4gArAAb/9gAI/8QACf+cAAr/zAAL/5QADP+6AA3/xAAO/+oAD//BABD/zgAR/78AEv+7ABP/2AAU/78AFf+mABcAAgAk/+cAMf+mADL/2AAz/+cANP+7ADX/5gA2//MAN//zADj/sQA5/+oAOv/rADz/6AA9/+gAPv/mAD//5wBA/7oAQf/4AEL/twBD/+gARP/OAEX/sQBG/88AR/+EAEj/lwBJ/9AASv+NAEv/9wAsAAb/9gAH/+oACP/nAAn/xAAK/+gAC//TAAz/3QAN/9gADv/lAA//5wAQ/+IAEf/aABL/3AAT/9MAFP/bABX/xAAk//EAMf/YADL/zQAz/+wANP/kADX/9wA2//MAN//9ADj/4wA5//cAOv/3ADv/5gA8//4APf/9AD7/7gA//+4AQP/kAEH/+QBC/+YAQ//vAET/6QBF/9oARv/vAEf/zgBI/88ASf/QAEr/uQBL//kAKwAG//YAB//qAAj/7AAJ/9gACv/uAAv/4gAM/+IADf/dAA7/9AAP/+IAEP/eABH/5gAS/+IAE//TABT/3QAV/90AJP/2ADH/7AAy/74AM//uADT/3wA1//oANv/xADj/5wA5/+8AOv/5ADv/2AA8/+0APf/9AD7/8wA///EAQP/rAEH/+ABC/+QAQ//3AET/5gBF/9AARv/zAEf/xgBI/80ASf++AEr/twBL/+gAKgAH//EACP/xAAn/0wAK/+YAC//YAAz/5wAN/9gADv/oAA//5wAQ/+IAEf/iABP/2AAU/90AFf/dACT/+wAx/+wAMv+7ADP/9wA0/+QANf/rADb/5wA3//EAOP/kADn/+QA6//YAO//aADz/9wA9//4APv/uAD//8QBA/+cAQf/vAEL/4wBD/+sARP/cAEX/0ABG/+sAR//CAEj/xABJ/7QASv+6AEv/6AAmAAf/9gAI//EACf/sAAr/9gAM/+cADv/6AA//8QAQ//EAEf/vABL/4QAT//EAFP/iABX/5wAy/+kAM//9ADT/5wA1//sANv/9ADf//gA4/+sAOf/+ADoAAQA7/+gAPP/9AD3/9wA+//0AP//9AED/6wBBAAEAQv/pAEP/+QBE/+wARgACAEf/6QBI/+8ASf/nAEr/6wBL//sAKQAH//sACP/xAAn/5wAK/+4AC//2AAz/4gAN//sADv/1AA//8QAQ/90AEf/kABL/4gAT/+wAFP/YABX/3QAx//YAMv+5ADP/+AA0/+MANf/3ADb/+AA3//kAOP/iADn/+gA6//0AO//OADz//QA9//4APv/5AD///ABA/+YAQv/jAEP/9wBE/+YARf/vAEb//gBH/+cASP/vAEn/0QBK/+YAS//9ACgAB//2AAj/4gAJ/90ACv/sAAv/4gAM/+gADf/iAA7/9QAP/+gAEP/dABH/4AAS/+YAE//OABT/4gAV/90AJP/7ADH/9gAy/8EAM//vADT/3wA2//QAN//4ADj/4wA5/+kAOv/6ADv/0QA8/+YAPf/zAD7/6QA///EAQP/qAEL/3ABD/+gARP/fAEb/+ABH/7sASP+7AEn/rwBK/68AS//jACcACP/xAAn/7AAK//gADP/2AA7/9wAP//YAEP/xABH/5wAS/+cAE//xABT/7AAV/+UAMf/2ADL/6AAz//kANP/qADX/+wA2//oAN//7ADj/6wA5//cAOv//ADv/4wA8//sAPf/+AD7/+wA///oAQP/sAEH/+gBC/+MAQ//5AET/7wBF/+oARv/7AEf/4wBI/+wASf/jAEr/6gBL//4AJgAH//sACP/7AAn/5wAK//oADP/2AA7/9gAP//YAEP/xABH/8QAS//IAE//xABT/5wAV//EAMv/nADP/+wA0//EANf/9ADb//gA3//4AOP/uADn/+wA6//4AO//oAD0AAAA+//sAP//+AED/7wBB//4AQv/qAEP//wBE//EARf/3AEb/+wBH/+YASP/3AEn/2gBK/+QAS//7ACkAB//2AAj/9gAJ/90ACv/yAAz/8QAO//EAD//wABD/6gAR/+wAEv/mABP/9AAU/+wAFf/rABf/zgAx//YAMv/OADP/7wA0/+oANf/5ADb//gA3//0AOP/oADn/+QA6//0AO//YADz//gA9//8APv/6AD//+QBA/+4AQf/5AEL/4wBD//gARP/qAEX/+QBG//oAR//pAEj/6QBJ/9UASv/rAEv/+gAqAAf/sgAI/8kACf+wAAr/ugAL/7UADP+1AA3/3QAO/+QAD/+6ABD/sgAR/7UAEv+xABP/4gAU/6sAFf+mADH/lwAy/9oAM//jADT/qwA1/+IANv/iADf/4wA4/5oAOf/XADr/7gA7/7QAPP/kAD3/6wA+/+4AP//mAED/rQBB/+8AQv+qAEP/6gBE/74ARf/XAEb/2gBH/9AASP/SAEn/1QBK/80AS//qACsAB//nAAj/8QAJ/6YACv/sAAv/nAAM/90ADf+6AA7/9gAP/+IAEP/sABH/3QAS/9oAE//sABT/3QAV/8QAJP/+ADH/pgAy/+sAM//vADT/ygA1//0ANv/zADf/+wA4/9MAOf/vADr/+wA7/9gAPP/3AD3/9wA+//EAP//7AED/1QBB//cAQv/PAEP/8wBE/+YARf+7AEb/5wBH/7UASP/JAEn/2gBK/6UAS//zACkAB//2AAn/7AAK//kAC//sAAz/9gAO//oAD//2ABD/7AAR/+cAEv/vABP/9gAU//EAFf/sABcAAQAx/+YAMv/pADP/+QA0/+oANf/zADb/+wA3//oAOP/nADn/9wA6//4AO//uADz/+QA9//oAPv/7AD//+QBA/+8AQf/3AEL/6QBD//oARP/sAEX/8wBG//gAR//pAEj/6QBJ/+MASv/nAEv//QAqAAf/9gAI//sACf/sAAr/9wAL/+wADP/7AA7/+gAP//EAEP/2ABH/7AAS//EAE//2ABT/9gAV/+QAFwABADH/8QAy/+kAM//3ADT/6QA1//kANv/5ADf/+QA4/+8AOf/6ADr//gA7/+8APP/7AD3/+gA+//oAP//4AED/7wBB//sAQv/rAEP//QBE/+8ARf/3AEb/+gBH/+4ASP/rAEn/4QBK/+wAS//5ACsAB//xAAj/4gAJ/9gACv/sAAv/2AAM//YADf/iAA7/8QAP/90AEP/iABH/0wAS/+IAE//JABT/4gAV/94AJP/7ADH/3QAy/7QAM//pADT/4QA1/+wANv/vADf/6gA4/+IAOf/qADr/+gA7/9oAPP/pAD3/6wA+/+wAP//pAED/4QBB/+sAQv/cAEP/6wBE/+IARf/JAEb/7gBH/7wASP/BAEn/pgBK/7UAS//kACwAB//iAAj/5wAJ/+IACv/OAAv/2AAM/+cADf/nAA7/8AAP/90AEP+6ABH/xAAS/9cAE//XABT/2AAV/9gAG//3ACT/+wAx/+IAMv+gADP/6QA0/+MANf/mADb/7wA3/+sAOP/aADn/6AA6//YAO/+xADz/6wA9/+4APv/oAD//7wBA/9oAQf/oAEL/1wBD/+MARP/aAEX/2ABG/+cAR//PAEj/yQBJ/7kASv/BAEv/6AApAAf/8QAI/+wACf/OAAr/6gAL/84ADP/nAA3/2AAO//YAD//fABD/4gAR/9gAEv/lABP/5wAU/+IAFf/YADH/4gAy/+cAM//3ADT/2gA1//gANv/5ADf/+wA4/9wAOf/3ADr//gA7/+MAPP/3AD3//QA+//cAP//3AED/1QBC/9UAQ//9AET/6QBF/+EARv/pAEf/ugBI/8QASf/aAEr/wgBL//sAKwAH/8kACP/YAAn/xAAK/9MAC/+/AAz/yQAN/9gADv/nAA//xAAQ/7oAEf+1ABL/wQAT/9gAFP+6ABX/vwAk//sAMf+/ADL/2gAz/+gANP/KADX/6QA2/+kAN//oADj/xgA5/+QAOv/nADv/uQA8/+wAPf/uAD7/6QA//+cAQP/GAEH/7ABC/8kAQ//mAET/2ABF/84ARv/VAEf/wQBI/7wASf/GAEr/tABL/+8AKwAH//EACP/2AAn/yQAK/+oAC//TAAz/3QAN/+cADv/sAA//4gAQ/+IAEf/YABL/3wAT/90AFP/dABX/2AAk//sAMf/nADL/xgAz//MANP/iADX/7wA2/+4AN//3ADj/4wA5/+kAOv/vADv/1wA8/+4APf/zAD7/6gA//+0AQP/kAEH/9wBC/98AQ//qAET/5wBF/9AARv/vAEf/yQBI/9AASf/PAEr/xABL/+8AKQAH/+cACP/sAAn/5wAK/+kAC//dAAz/2AAO/+wAD//XABD/qwAR/8kAEv/AABP/9gAU/9MAFf/OADH/2AAy/7AAM//5ADT/2gA1//0ANv/6ADf//gA4/98AOf/3ADr//QA7/8YAPP/7AD3//gA+//gAP//4AED/1QBB//0AQv/VAEP/+ABE/+MARf/zAEb/+QBH/+4ASP/zAEn/4gBK/+cAS//zACkACP/2AAn/5wAK//QAC//sAAz/+wAN//4ADv/2AA//5QAQ/+wAEf/nABL/8wAT//EAFP/nABX/3QAx/+QAMv/KADP/+QA0/+wANf/6ADb/+gA3//sAOP/vADn/+gA6AAAAO//hADz//wA9//0APv/5AD///gBA/+wAQf/7AEL/7ABD//sARP/vAEX/9wBG//sAR//zAEj/6gBJ/+EASv/jAEv/+wArAAf/zgAI/84ACf/YAAr/ygAL/9gADP/JAA3/+wAO/9kAD//JABD/ogAR/7oAEv+5ABP/5wAU/8QAFf+9ACT/+wAx/7oAMv+FADP/+wA0/7sANf/qADb/6wA3/+wAOP++ADn/5gA6/+8AO/+iADz/6AA9/+oAPv/sAD//7wBA/8MAQf/mAEL/uwBD/+YARP/KAEX/6QBG/+8AR//jAEj/3wBJ/9MASv/hAEv/6wApAAf/zgAI/84ACf/TAAv/2AAM/84ADv/eAA//xAAQ/7AAEf/TABL/sQAT/+wAFP/FABX/yQAk//sAMf/JADL/lQAz//MANP/BADX/+QA2//MAN//3ADj/xgA5//sAOv/3ADv/pQA8/+8APf/+AD7/7gA//+oAQP/DAEH/7gBC/8QAQ//vAET/0ABF/+4ARv/uAEf/6QBI/+QASf/aAEr/5gBL//cAKgAH/8QACP/OAAn/pgAL/7oADP+rAA3/3QAO/+cAD/+5ABD/twAR/8QAEv+zABP/0wAU/7AAFf+cACT/+wAx/6EAMv/aADP/4wA0/7cANf/4ADb/4wA3//0AOP+3ADn/7gA6/+8AO/+7ADz/7gA9//EAPv/jAD//6ABA/7oAQf/zAEL/uQBD/+sARP/OAEX/3wBG/+EAR//aAEj/2ABJ/9gASv/MAEv/7gAsAAf/yQAI/84ACf/JAAr/wgAL/8kADP/JAA3//gAO/8kAD/+6ABD/jQAR/7oAEv+gABP/4gAU/7UAFf+6AB7/8QAk//sAMf+1ADL/lwAz/+8ANP+7ADX/5gA2/+4AN//uADj/uQA5/+gAOv/3ADv/hAA8/+8APf/sAD7/7AA//+oAQP+6AEH/7ABC/7kAQ//pAET/ygBF/+8ARv/vAEf/6ABI/+kASf/fAEr/5ABL//EAJgAH//YACf/iAAr/7AAL/+cADP/iAA3//wAO//UAD//nABD/7AAR/+IAEv/gABP/7AAU/90AFf/TADH/4gAy/+sAM//+ADT/6AA1//4ANgAEADf//wA4/9wAOf/6ADv/5gA8//8APf//AD///QBA/+MAQf//AEMAAABE/+8ARf/4AEb/+wBH//cASP/rAEn/6QBK/+kAS//9AAIAAQAGAEsAAAAAAAAAAQAAAADUGBYRAAAAANmXsTQAAAAA2ZexNA==",at=i=>Jr("http://www.w3.org/2000/svg",i),gl=(i,t)=>{const e=at("rect");return e.setAttribute("height",`${i}`),e.setAttribute("width",`${t}`),e},ml=(i,t,e,a)=>{const n=ye("filter");n.setAttribute("id",a),n.setAttribute("height","200%"),n.setAttribute("width","200%"),n.setAttribute("x","-50%"),n.setAttribute("y","-50%");const r=ye("feOffset");n.appendChild(r),r.setAttribute("result","offOut"),r.setAttribute("in","SourceAlpha"),r.setAttribute("dx",`${i}`),r.setAttribute("dy",`${t}`);const o=ye("feGaussianBlur");n.appendChild(o),o.setAttribute("result","blurOut"),o.setAttribute("in","offOut"),o.setAttribute("stdDeviation",`${e}`);const s=ye("feBlend");return n.appendChild(s),s.setAttribute("in","SourceGraphic"),s.setAttribute("in2","blurOut"),s.setAttribute("mode","normal"),n},pl=i=>{let t=i;return t=t.replace(/feoffset/gi,"feOffset"),t=t.replace(/fegaussianblur/gi,"feGaussianBlur"),t=t.replace(/feblend/gi,"feBlend"),t=t.replace(/lineargradient/gi,"linearGradient"),t=t.replace(/stddeviation/gi,"stdDeviation"),t};function fl(i,t,e,a,n,r){const o=n,s=r,l={x:t[0],y:t[1],width:t[2]-t[0],height:t[3]-t[1]};if(l.width<=0)return;const c=Cl(l.height,l.width,e*o,a*s),d=(a-c*l.width)/2-c*l.x,u=(e-c*l.height)/2-c*l.y;i.setAttribute("transform",`translate(${d} ${u}) scale(${c} ${c})`)}function Cl(i,t,e,a){const n=e/i,r=a/t;return n>1&&r>1?Math.min(n,r):n>1&&r<1?r:n<1&&r>1?n:Math.min(n,r)}const Bn={m:["x","y"],z:[],l:["x","y"],h:["x"],v:["y"],c:["x1","y1","x2","y2","x","y"],s:["x2","y2","x","y"],q:["x1","y1","x","y"],t:["x","y"],a:["rx","ry","xRotation","largeArc","sweep","x","y"]};class wl{constructor(t){const e=Array.from(t.querySelectorAll("path"));this.paths=e.map(a=>{const n=a.getAttribute("d")||"",r=this.parsePath(n);return{pathElement:a,pathData:r}})}transform(t){for(const e of this.paths)e.pathData=this.runTransformer(e.pathData,t);this.update()}encodePath(t){let e="";const n=r=>{const o=[],s=r.relative?r.type:r.type.toUpperCase();let l=e!==s;const c=Bn[r.type];l&&(o.push(s),e=s);for(const d of c){const u=r[d];let A;switch(typeof u){case"boolean":A=u|0;break;case"number":A=(u*100|0)/100;break;default:throw new Pt("Failed to encode path.")}l||o.push(" "),o.push(A),l=!1}return o.join("")};return t.map(n).join("")}parsePath(t){const e=/([mzlhvcsqta])([^mzlhvcsqta]*)/gi,a=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi,n=[];let r;for(e.lastIndex=0;r=e.exec(t);){const o=r[1].toLowerCase(),s=(r[2].match(a)||[]).map(parseFloat),l=o===r[1],c=Bn[o];if(s.length<c.length)throw new Pt(`Path type "${o}" given ${s.length} arguments, expected ${c.length}.`);if(c.length>0){if(s.length%c.length!==0)throw new Pt(`Path type "${o}" given ${s.length} arguments, not divisible by ${c.length}`);for(let d=0;d<s.length/c.length;d++){const u={type:o,relative:l};for(let A=0;A<c.length;A++)u[c[A]]=s[d*c.length+A];n.push(u)}}else n.push({type:o,relative:l})}return n}runTransformer(t,e){const a=[["x1","y1"],["x2","y2"],["x","y"]],n=r=>{for(let o=0;o<a.length;o++){const[s,l]=a[o];if(s in r&&l in r){const c=[r[s],r[l]],d=e(c);if(d.length<2)throw new Pt("Transformer must return at least 2 points.");r[s]=d[0],r[l]=d[1]}}return r};return this.transformPath(t,n)}transformPath(t,e){const a=[];for(let n=0;n<t.length;n++){const r=JSON.parse(JSON.stringify(t[n])),o=e(r);Array.isArray(o)?a.push(...o):o&&a.push(o)}return a}update(){for(const{pathElement:t,pathData:e}of this.paths){const a=this.encodePath(e);t.setAttribute("d",a)}}}class yl extends Al{constructor(){super(...arguments),this.moduleName="Vegemite"}svgPreview(t,e){return this.svgElement(t,e)}svgPrint(t,e){return this.svgElement(t,e)}svgElement(t,e){const a=Ds(hl),r=t!==""?(w=>w.charAt(0).toUpperCase()+w.substr(1).toLowerCase())(t):"",o=a.getPath(r,0,72,72),s=o.toSVG(2),l=o.getBoundingBox(),c=l.x2-l.x1,d=o.toPathData(3),u=()=>{const w=at("g");w.classList.add("module-text-group");const F=at("defs");w.appendChild(F),F.appendChild(ml(0,2,2,"shadow"));const b=at("path");b.setAttribute("d",d),b.setAttribute("stroke","black"),b.setAttribute("stroke-width","3"),F.appendChild(b);const v=at("g");v.classList.add("module-layer0"),w.appendChild(v),v.setAttribute("filter","url(#shadow)"),v.innerHTML=b.outerHTML;const B=at("g");B.classList.add("module-layer1"),w.appendChild(B),B.setAttribute("stroke-width","3"),B.setAttribute("stroke","rgb(45,41,38)"),B.setAttribute("fill","rgb(45,41,38)"),B.setAttribute("transform","translate(0.5,0)"),B.innerHTML=s;const M=at("g");M.classList.add("module-layer2"),w.appendChild(M),M.setAttribute("fill","rgb(255,209,0)"),M.setAttribute("transform","translate(1,-0.1)"),M.innerHTML=s;const R=at("g");return R.classList.add("module-layer3"),w.appendChild(R),R.setAttribute("fill","white"),R.innerHTML=s,new wl(w).transform(([T,L])=>[T,L+(c/2-T)**2/(c*6)]),w},A=at("g");A.classList.add("module-root");const h=at("defs");A.appendChild(h);const g=at("g");g.classList.add("module-bounds"),A.appendChild(g);const p=gl(e.height,e.width);p.setAttribute("opacity","0"),g.appendChild(p);const m=at("g");m.classList.add("module-text-enclosure"),A.appendChild(m);const C=u();m.appendChild(C);const S=Vr(d);return fl(m,S,e.height,e.width,.35,.65),pl(A.outerHTML)}}async function Oi(i){if(i==="Vegemite")return new yl;throw new O(`Failed to resolve Module, Module ${i} not found`)}const Sl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],vl=async(i,t,e)=>{const a=t.data,n=e.data.baseUrl,r=a.assetUrl.replace("localhost","localstack"),o=n.slice(0,4)==="http"?"":"https://",s=new URL(o+n);s.searchParams.append("video",pn(JSON.stringify([{href:r}]))),s.pathname=s.pathname+(s.pathname.slice(-1)==="/"?"":"/");const l=s.toString(),d=`data:image/svg+xml;base64,${pn(await zn.toString(l,{type:"svg"}))}`,u=h=>{const g=i.find(m=>m.panelId===h.panelId);if(!g)throw new J(h);const p=N();return new H({id:p,src:d,type:D.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},A=e.data.regions;try{return A.map(u)}catch(h){return console.error(h),[]}},El=async(i,t,e,a)=>{const n=e.data,r=n.assetUrl,o=await Fa(r);try{const s=await zs(n,a.option);s&&(t[a.stepName]={selectedVariants:[s]});const l=async c=>{const d=await Pi(c,s?.asset?.fileLink),u=await me(d),A=N(),h=i.find(p=>p.panelId===c.panelId);if(!h)throw new J(c);const g=Ha(o,u,{scale:n.scale,left:n.x,top:n.y},a.data.forceImageCover);return[new H({id:A,path:u.path,type:D.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/u.width,scaleY:c.height/u.height,pattern:{id:`${A}-pattern`,src:o.src,x:g.x,y:g.y,width:o.width,height:o.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:o.svg,colors:o.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(s){return console.error(s),[]}},bl=async(i,t,e,a)=>{const n=e.data,r=await I.getOptionForStep(a);if(!r)return console.error(`No option for step ${a.stepName}.`),[];const o=r.variants?.find(b=>b.id===n.illustrationVariantId)||await I.getDefaultVariant(r,a.overrideDefaultVariantId);if(!o)return console.error(`No variant with ID: ${n.illustrationVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${n.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${n.illustrationVariantId}`),[];const l=await et(s,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],u=d?.length>0?d[0]:"",g=ct().parseFromString(u,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];je(g);const p={};Ut(g,b=>{Sl.includes(b.tagName)&&!b.attributes.getNamedItem("fill")&&b.setAttribute("fill","#000000");const v=b.attributes.getNamedItem("fill");if(v&&v.value!=="none"){const M=v.value,x=`spiff-fill-${M.replace(/\W/g,"")}`;b.classList.add(x),p[x]={browserValue:M}}const B=b.attributes.getNamedItem("stroke");if(B&&B.value!=="none"){const M=B.value,x=`spiff-stroke-${M.replace(/\W/g,"")}`;b.classList.add(x),p[x]={browserValue:M}}});const C=It().serializeToString(g),S=n.colors;if(S){for(const[b,v]of Object.entries(p))for(const B of Object.keys(S))if(v.browserValue===B){p[b]={browserValue:S[B]};break}}const w=b=>{const v=i.find(M=>M.panelId===b.panelId);if(!v)throw new J(b);const B=N();return new H({colors:p,id:B,svg:C,type:D.Illustration,y:b.top,x:b.left,rotation:b.rotation,width:b.width,height:b.height,layer:b.layer,layerIndex:b.layerIndex,immutable:b.immutable},v)},F=a.data.regions;try{return F.map(w)}catch(b){return console.error(b),[]}},Il=async(i,t,e)=>{const a=await Oi(e.data.module),n=t.data,r=(s,l)=>{const c=i.find(u=>u.panelId===l.panelId);if(!c)throw new J(l);const d=N();return new H({colors:{},id:d,svg:s,type:D.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},o=e.data.regions;try{return o.map(s=>r(a.svgPrint(n.text,s),s))}catch(s){return console.error(s),[]}},Bl=async(i,t,e,a)=>{const n=e.data,r=await I.getOptionForStep(a);if(!r)return console.error(`No option for step ${a.stepName}.`),[];const o=r.variants?.find(d=>d.id===n.pictureVariantId)||await I.getDefaultVariant(r,a.overrideDefaultVariantId);if(!o)return console.error(`No variant with ID: ${n.pictureVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${n.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${n.pictureVariantId}`),[];const l=d=>{const u=i.find(h=>h.panelId===d.panelId);if(!u)throw new J(d);const A=N();return new H({id:A,src:s,type:D.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},u)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},Pl=async(i,t,e,a)=>{const n=e.data,r=await I.getOptionForStep(a);if(!r)return console.error(`No option for step ${a.stepName}.`),[];const o=r.variants?.find(c=>c.id===n.colorVariantId)||await I.getDefaultVariant(r,a.overrideDefaultVariantId);if(!o)return console.error(`No variant with ID: ${n.colorVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=c=>{const d=i.find(p=>p.panelId===c.panelId);if(!d)throw new J(c);const u=`
1422
+ `,C={};C[this.shapeFillId]={browserValue:p};const S=N();return{id:S,region:A,command:new W({stepRegion:A,stepRegionIndex:h,stepName:t.stepName,colors:C,id:S,svg:m,type:D.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,excludeFromExport:t.data.excludeFromPrint},g)}},c=t.data.regions.map(l),d=c.filter(A=>!!A).map(A=>A?.command),u=c.filter(A=>!!A).map((A,h)=>({id:A.id,region:A.region,regionIndex:h}));return{command:new U(d),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],u,async()=>{n.updateStorage(t.stepName,{colour:o()})})}}}}}const kt=new Yo;class Jo{constructor(){this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}removeToastCallback(t){this.toastCallbacks=this.toastCallbacks.filter(e=>e!==t)}setLatestToast(t,e){this.latestToast=t,this.toastType=e,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach(t=>t({toastMessage:this.latestToast,toastType:this.toastType}))}}const Ei=new Jo,ua=(i,t,e,a,n)=>{if(t.some(d=>d==null))throw new Error(`Failed to autosize lines: ${t.join(", ")}`);let r=t.map(d=>d.split(`
1423
+ `)).flat(),s=r.length,o=r.map(d=>ft(d,a,n));const l=n.getApproximateHeight()*a;let c=!0;for(;c;){if(l+(s-1)*e>i.height)return[null,null];const u=Math.max(...o);if(u<=i.width)return[r,u];const A=o.reduce((m,C,S,w)=>C>w[m]?S:m,0),h=r[A];let g=!1,p=h.length;for(;!g&&p>-1;){p=h.lastIndexOf(" ",p-1);const m=[h.slice(0,p),h.slice(p+1)],C=m.map(w=>ft(w,a,n));C[0]<=i.width&&(r=[...r.slice(0,A),...m,...r.slice(A+1)],o=[...o.slice(0,A),...C,...o.slice(A+1)],s+=1,g=!0)}g||(c=!1)}return[null,null]},Xt=(i,t,e,a,n)=>{let r,s;const o=vt(t.assetUrl),l=o.getFont();if(n.size){const A=i/l.unitsPerEm;return[r,s]=ua(e,a,i,A,o),[n.size,r,s]}const c=6;let d=c-sa;if(a.length>0){let A=a,h=0;for(;(!n.maxSize||d<=n.maxSize)&&A;)d+=sa,h=d/l.unitsPerEm,[A,s]=ua(e,a,d,h,o)}d>c&&(d-=sa),n.minSize&&d<n.minSize&&(d=n.minSize);const u=d/l.unitsPerEm;return[r,s]=ua(e,a,d,u,o),[d,r,s]},Aa=30;class ke extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ke.name}}const Ko=["‘","’","“","”",`
1424
+ `];class Me extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Me.name}}class Xo{constructor(){this.cachedColors=new Map,this.cachedStrokeColors=new Map,this.filterUnsupportedCharacters=(t,e)=>{let a=t.replace(/(\r\n|\r|(\u2665|\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],r=e?vt(e.assetUrl):void 0;if(r){const s=a.split("").filter(l=>!Ko.includes(l)).join(""),o=s.split("").map(l=>r.getFont().charToGlyph(l));for(let l=0;l<o.length;l++)o[l].name===".notdef"&&n.push(String.fromCharCode(s.charCodeAt(l)))}for(let s=0;s<n.length;s++)a=a.replaceAll(n[s],"");return a},this.textAlign=t=>t.vertical?"center":t.textAlign||"center",this.getErrorsForText=(t,e,a,n)=>{let r;a.data&&a.data.maxLength&&e.length>a.data.maxLength&&(r||(r={}),r.hitCharacterLimit=!0);const s=n.getWorkflowExperience().getProfanityList(),o=pa.split(t.toLowerCase());for(const c of o)for(const d in s){const u=s[d].toLowerCase().replace(/\s/g,"");if(c===u){r||(r={}),r.blockedProfanity=!0;break}}return!a.data.allowNewlines&&(t.includes(`
1425
+ `)||t.includes("\r"))&&(r||(r={}),r.illegalMultipleLines=!0),r}}async init(t,e,a){const n=await I.getOptionForStep(t);if(!n)return null;if(a)await this.reload(t,e,a);else{const r=await this.getDefaultImageFillVariant(t.data),s=r?.asset?.fileLink,o=s?await ba(s):void 0,l=o?{src:o.src,height:o.height,width:o.width,scale:t.data.imageFillScale||1}:void 0,c=await this.getDefaultStrokeColorVariant(t.data),d=t.data.strokeEnabled&&c?.color?{browserValue:c.color,pmsValue:c.name}:void 0;let u=t.data.defaultText||"";const A=e.getWorkflowExperience().getBundle();if(A&&t.globalPropertyAspectConfigurations){const p=A.getGlobalPropertyConfiguration()?.aspects?.find(m=>m.type===z.Text&&t.globalPropertyAspectConfigurations?.map(C=>C.aspectName).includes(m.name));if(p){const C=A.getGlobalPropertyStateManager().getAspect(p.name);C&&(u=C)}}e.updateStorage(t.stepName,{text:u,inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:l,strokeColor:d}),e.updateMetadata(t.stepName,{text:u,color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:r?.name,strokeColor:t.data.strokeEnabled?c?.color:void 0});const h=await I.getDefaultVariant(n,t.overrideDefaultVariantId);if(h)return this.selectVariantCommand(t,h,{text:u},[],e,()=>{},()=>{},l,d)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map(r=>V(r.id,t.getAllLayoutData()))}async availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const a=await I.ensureFullOption(t.data.colorOption);if(a){const n=a.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r}))||[];return this.cachedColors.set(t.stepName,n),n}return[]}changeAlignment(t,e,a,n){if(!t.data||!t.data.regions)return;const r=n.getCommandDispatcher();for(const s of a){const o=new wi(s.id,e);r(o)}}async changeFillColor(t,e,a,n){if(!t.data||!t.data.regions)return;const r=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const s=await I.ensureFullOption(t.data.colorOption),o=s?this.createTextFillSpotColor(s,e.variant):void 0;s?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:s.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const l of a){if(!e.fill)throw new Error("Fill not set on new color selection!");const c=new fi(l.id,e.fill,o);r(c)}}async availableFillImages(t){const e=await I.ensureFullOption(t.data.imageFillOption);if(e){const a=e.variants?.map(n=>n.asset?.fileLink)?.filter(n=>!!n)||[];return Promise.all(a.map(async n=>{const r=await ba(n);return{src:n,width:r.width,height:r.height,scale:t.data.imageFillScale||1}}))}return Promise.resolve([])}async changeFillImage(t,e,a,n){if(!t.data||!t.data.regions)return;const r=n.getCommandDispatcher(),o=(await I.getOptionForStep(t))?.variants?.find(l=>l.asset?.fileLink===e.src);n.updateMetadata(t.stepName,{fillImage:o?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const l of a){const c=new ca(l.id,e);r(c)}}async availableStrokeColors(t){const e=this.cachedStrokeColors.get(t.stepName);if(e)return e;const a=await I.ensureFullOption(t.data.strokeOption);if(a){const n=a.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r}))||[];return this.cachedStrokeColors.set(t.stepName,n),n}return[]}async changeStrokeColor(t,e,a,n){if(!t.data||!t.data.regions)return;const r=n.getCommandDispatcher();e?.variant?n.updateMetadata(t.stepName,{strokeColor:e.variant.name}):n.updateMetadata(t.stepName,{strokeColor:e?.fill});const s=e?{browserValue:e.fill,pmsValue:e.pmsValue}:void 0;n.updateStorage(t.stepName,{strokeColor:s});for(const o of a){const l=new da(o.id,s,t.data?.strokeThickness);r(l)}}getProcessedInput(t,e,a){const n=a?t:this.injectReplaceableText(t,e);return Fe(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,a,n){const r=n.getStepStorage(a.stepName),s=Mt(t,n),o=this.getProcessedInput(s,a.data,r?.customiseAllText??!1),l={command:void 0,helperData:{},errorData:this.getErrorsForText(t,o,a,n)};if(l.errorData)return l;l.helperData.charactersRemaining=a.data.maxLength-o.length;const c=[],d=new Map,u=new Map;for(const A of e){if(!A.fontData)throw new O("Failed to resolve font data for text.");const[h,g]=Xt(A.fontSize,A.fontData,{left:A.x,top:A.y,width:A.width,height:A.height,rotation:A.rotation},[o],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});d.set(A.id,h),u.set(A.id,g);const p=a.data.curved?o:(g||[]).join(`
1426
+ `);c.push(this.generateTextChangeCommandsForRegion(h,a.data,A.id,p))}return!a.data.curved&&e.length>0&&!Array.from(u.values()).every(h=>h)?(l.errorData||(l.errorData={}),l.errorData.doesNotFit=!0,l):(n.updateStorage(a.stepName,{text:t}),n.updateMetadata(a.stepName,{text:o}),(r?.defaultCleared||!a.data.deleteDefaultOnFocus)&&o.trim()!==""&&n.setMandatoryFulfilled(a.stepName,!0),l.command=new U(c),l)}async selectVariant(t,e,a,n,r){const s=await this.selectVariantCommand(t,e,a.getStepStorage(t.stepName)||{},a.getRegionElements(t.stepName),a,n,r);s&&(s.command&&a.getCommandDispatcher()(s.command),s.followup&&await s.followup())}createTextFillSpotColor(t,e){const a=t.colorProfile;if(a){const n=(a.name||"").replace(/\s/g,"-"),r=n.lastIndexOf("/"),o=n.slice(r+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:o,namedColor:e.namedColor}}}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await I.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=await this.fontDataFromVariant(d),A=o.map(m=>({id:m.id,region:m.stepRegion,regionIndex:m.stepRegionIndex})),h=n.storage?.color;let g=n.storage?.text;const p=e.getWorkflowExperience().getBundle();if(p&&t.globalPropertyAspectConfigurations){const C=p.getGlobalPropertyConfiguration()?.aspects?.find(S=>S.type===z.Text&&t.globalPropertyAspectConfigurations?.map(w=>w.aspectName).includes(S.name));if(C){const w=p.getGlobalPropertyStateManager().getAspect(C.name);w&&(g=w)}}if(await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.updateMetadata(t.stepName,{color:h,text:g}),e.updateStorage(t.stepName,{text:g,inputText:g});const m=o.map(S=>new Ba(S.id,u)),C=new U(m);e.getCommandDispatcher()(C)}),o.length===0&&l){const m=await I.getDefaultVariant(l,t.overrideDefaultVariantId);if(m){const C=await this.selectVariantCommand(t,m,{text:g},[],e,()=>{},()=>{});C?.command&&e.getCommandDispatcher()(C.command)}}else{const{command:m}=H.updateInputText(g||"",o,t,e);m&&e.getCommandDispatcher()(m)}}}}else{const c=e.getWorkflowExperience().getBundle();if(c&&t.globalPropertyAspectConfigurations){const u=c.getGlobalPropertyConfiguration()?.aspects?.find(A=>A.type===z.Text&&t.globalPropertyAspectConfigurations?.map(h=>h.aspectName).includes(A.name));if(u){const h=c.getGlobalPropertyStateManager().getAspect(u.name);if(h)if(o.length===0&&l){const g=await I.getDefaultVariant(l,t.overrideDefaultVariantId);if(g){const p=await this.selectVariantCommand(t,g,{text:h},[],e,()=>{},()=>{});p?.command&&e.getCommandDispatcher()(p.command)}}else{const{command:g}=H.updateInputText(h,o,t,e);g&&e.getCommandDispatcher()(g)}}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return I.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;return e?(await I.getDefaultVariant(e))?.color:void 0}async getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return I.getDefaultVariant(e)}async getDefaultStrokeColorVariant(t){const e=t.strokeOption;if(e)return I.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new wt(t);const a=e.fileLink;if(!a)throw new Qt(e);const n=await Pt(a);return{assetUrl:a,name:n.names.fullName.en}}async selectVariantCommand(t,e,a,n,r,s,o,l,c){const d=r.markUpdatePending(),u=await this.fontDataFromVariant(e);let A=!0;const h=g=>{s(g),g&&(A=!1)};if(n.length>0){const g=n.map(C=>new Ba(C.id,u));if(l){const C=n.map(S=>new ca(S.id,l));g.push(...C)}if(c){const C=n.map(S=>new da(S.id,c,t.data.strokeThickness));g.push(...C)}const p=await this.changeInputTextWithRegion(t,t.data.size||Aa,u,a.text||"",a,r,a?.customiseAllText??!1,h,o);p&&g.push(p);const m=new U(g);return A?{command:m,followup:async()=>{r.markUpdateCompleted(d),await r.setSelectionsAndElements(t.stepName,[e],n)}}:null}else{const g=await this.createTextboxRegions(t.stepName,e,t.data,u,a,r),p=await this.changeInputTextWithRegion(t,t.data.size||Aa,u,g[0]?.newElement.input||a.text||t.data.defaultText||"",a,r,a?.customiseAllText??!1,h,o),m=g.flatMap(S=>S.commands);if(l){const S=g.map(w=>new ca(w.regionElement.id,l));m.push(...S)}if(c){const S=g.map(w=>new da(w.newElement.id,c,t.data.strokeThickness));m.push(...S)}p&&m.push(p);const C=new U(m);return A?{command:C,followup:async()=>{r.markUpdateCompleted(d)}}:null}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,a,n,r,s){if(!a||!a.regions)throw new Error("Step data not supplied");const o=r.text||a.defaultText||"",l=Mt(o,s),c=this.getProcessedInput(l,a,!1),d=async(A,h)=>{const p=s.getLayouts().find(C=>C.panelId===A.panelId),m=N();try{if(!p)throw new Me("Failed to find layout for region: "+A.panelId);const C=await I.ensureFullOption(a.colorOption);let S;if(C&&C.variants){const k=await I.getDefaultVariant(C);k&&(S=this.createTextFillSpotColor(C,k),s.updateStorage(t,{colorProfileAssetKey:C.colorProfile?.key}))}const w=await this.getDefaultColor(a),F=w||"#000000",b={stepRegion:A,stepRegionIndex:h,stepName:t,align:this.textAlign(a),fill:r.color?r.color:F,fontSize:a.size||Aa,fontData:n,id:m,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,text:c,input:o,type:D.Textbox,vertical:a.vertical,x:A.left,y:A.top,height:A.height,width:A.width,immutable:A.immutable,verticalAlign:a.verticalAlign||"middle",curved:a.curved,paths:a.paths,fillSpotColorDefinition:S},v=[],B=new Map,M=new Map;if(!b.fontData)throw new O("Failed to resolve font data for text.");const[R,x]=Xt(b.fontSize,b.fontData,{left:b.x,top:b.y,width:b.width,height:b.height,rotation:b.rotation,panelId:""},[c],{size:a.size,minSize:a.minSize,maxSize:a.maxSize});B.set(b.id,R),M.set(b.id,x);const T=a.curved||a.vertical?c:(x||[]).join(`
1427
+ `);v.push(this.generateTextChangeCommandsForRegion(R,a,b.id,T));const L=new W(b,p);return{regionElement:{id:m,region:A,regionIndex:h},commands:[L,...v],newElement:b,fontData:n}}catch(C){throw console.log(C),new ke("Error adding font to region")}},u=await Promise.all(a.regions.map(d)).catch(A=>{throw A instanceof ke?(Ei.setLatestToast("Failed to load font.",ge.Error),A):A instanceof Me?A:new Error(A)});return await s.setSelectionsAndElements(t,[e],u.map(A=>A.regionElement),async()=>{s.updateMetadata(t,{text:o}),s.updateStorage(t,{text:o})}),u}generateTextChangeCommandsForRegion(t,e,a,n){const r=[],s=new yi(a,n);if(r.push(s),!e.size){const l=new Ci(a,t);r.push(l)}return new U(r)}async changeInputTextWithRegion(t,e,a,n,r,s,o,l,c,d){const u=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),A=Mt(u,s),h=this.getProcessedInput(A,t.data,o),g=s.getRegionElements(t.stepName),p=new Map,m=new Map;for(const b of g)if(b.region){const[v,B]=Xt(e,a,b.region,[h],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});p.set(b.id,v),m.set(b.id,B)}const S=(()=>{if(t.data&&t.data.maxLength&&h.length>t.data.maxLength)return d&&d(!0),{info:"0"};const b=s.getWorkflowExperience().getProfanityList(),v=pa.split(h.toLowerCase());for(const B of v)for(const M in b){const R=b[M].toLowerCase().replace(/\s/g,"");if(B===R){const T="Blocked profanity.";return l(T),{error:T}}}if(!t.data.vertical&&!t.data.allowNewlines&&(h.includes(`
1428
+ `)||h.includes("\r"))){const B="Text may not span multiple lines.";return l(B),{error:B}}if(!t.data.curved&&!Array.from(m.values()).every(M=>M)){const M="Text does not fit.";return l(M),{error:M}}return l(void 0),{info:(t.data.maxLength-h.length).toString()}})();if(S.error){c(S.error);return}if(c(`${S.info} characters remaining`||""),d)return;s.updateStorage(t.stepName,{text:u}),s.updateMetadata(t.stepName,{text:this.injectReplaceableText(u,t.data)}),(r.defaultCleared||!t.data.deleteDefaultOnFocus)&&u.trim()!==""&&s.setMandatoryFulfilled(t.stepName,!0);const w=[];for(const b of g){const v=t.data.curved?h:(m.get(b.id)||[]).join(`
1429
+ `);w.push(this.generateTextChangeCommandsForRegion(p.get(b.id)||1,t.data,b.id,v))}return new U(w)}}const H=new Xo;class Zo{}const _o="data:application/octet-stream;base64,AAEAAAAPAIAAAwBwRkZUTYdHeHoAAElcAAAAHEdERUYAJwBUAAAe2AAAAB5HUE9TkNtcVAAAHygAACoyR1NVQrj/uP4AAB74AAAAME9TLzJoWmUcAAABeAAAAGBjbWFwtkIacAAAAxAAAAJWZ2FzcP//AAMAAB7QAAAACGdseWY27KOUAAAGCAAAFcRoZWFkFPal0gAAAPwAAAA2aGhlYQU0Ar0AAAE0AAAAJGhtdHiADw6qAAAB2AAAAThsb2Nh5CzfJAAABWgAAACebWF4cACVAEwAAAFYAAAAIG5hbWXeIPPyAAAbzAAAAiJwb3N0ABeZTwAAHfAAAADdAAEAAAABAAAZ9vREXw889QALA+gAAAAA2ZexNAAAAADZl7E0ADL/yQJ2ArwAAAAIAAIAAAAAAAAAAQAAArz/wwAAAqsAAAAAAnYAAQAAAAAAAAAAAAAAAAAAAE4AAQAAAE4ASQAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAAEAbsBkAAFAAACigK7AAAAjAKKArsAAAHfADEBAgAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABYWFhYAEAACgCtArz/wwAAAqkANgAAAAMAAAAAAmQCZAAAACAAAgIPADIAAAAAAU0AAAAAAAAAAAAAALQAAAD3ADUCfQA1AcoANQKrADUCDQA1AX4ANQHYADUBNQA1AcgANQHUADUB8AA1AeEANQHpADUBqQA1AdAANQHpADUCqgA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUB3AA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUAtAAAAAAAAAAAAAMAAAADAAAAHAABAAAAAAFQAAMAAQAAABwABAE0AAAALgAgAAQADgAAAAoADQAhACYAKgA5AFoAXgB6AKAArQDFAM8A1gDdAOUA7wD2AP0A/wF4//8AAAAAAAoADQAgACMAKgAwAEAAXgBhAKAArQDAAMcA0QDYAOAA5wDxAPgA/wF4//8AAf/5//f/5f/k/+H/3P/W/9P/0f+s/6AAAAAAAAAAAAAAAAAAAAAA/0v+twABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYAIAAwADoARABOAF4AaAAAAAAAAAAXABcAFwAXABcAFwAZABsAGwAbABsAHwAfAB8AHwAkACUAJQAlACUAJQAlACsAKwArACsALwAyADIAMgAyADIAMgA0ADYANgA2ADYAOgA6ADoAOgA/AEAAQABAAEAAQABAAEYARgBGAEYASgAAAQYAAAEAAAAAAAAAAQIDAAAEAAAAAAAAAAAAAAAAAAAAAQAABQYABwgJCgAAAAsAAAAAAAwNDg8QERITFBUAAAAAAAAWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAAAAAxAAAyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKSwAAAAAAFxcZGyQlKzIyMjIyMjQ2NjY2Ojo6Oj9AQEBAQEZGRkYAAAAAAAAAAAAAAAAAAAAlAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAABMFxclAAAAAAAAAAAAAEovAAAAAAAAAAAAAAAXGxcbGx8fHx8lJQAlKysrAAAAAAAAAAAAAAAAAAAAACgAKAAoACgAKAAoADwAbgC0AQgBbgGQAcYB1AIGAkYCYAKSAtAC4gMoA2ADyAPgBBoEUAR4BI4EogTWBOoE9gUiBToFSAViBXoFqgXWBjAGWgaaBqwG2AbqBwYHIAc2B0wHXgd2B7AH5ggOCCQIOAhsCIAIjAi4CNAI3gj4CRAJQAlsCcYJ8AowCkIKbgqACpwKtgrMCuIK4griAAAABQAyAAAB3QK8AAMABgAJAAwADwAAEyERIRsCCwEREwMhAxMRMgGr/lUcubrGtMG5AXKttQK8/UQCqP7LATX+tgEs/acBGP7MAUn+0QJdAAACADUABQDCAmoAAwAHAAATESMRExUjNcGLi4sCaf5mAZr+KY2NAAAAAgA1AAACSAJkABsAHwAAJQcjNyMHIzcjNzM3IzczNzMHMzczBzMHIwczByc3IwcBthdrFkoXbBdeDl8KYA9fFWwVShVtFWoPagpqDscJSgqqqqqqqmxHbJqamppsR2xsR0cAAAEANf/JAZUCqgAwAAABFR4BByM0LgEjIgYVFBYXHgMVFA4BBxUjNS4BNTMUFjMyNjU0LgInJjU0Njc1ARwwPAF3CBQOExcsPCEwFgkZNyhnPkGDGRQTGBElHBprRzQCqkQNV0INGBIdFB8hGw4tMCkUJkU7EENDCmk8GiUgFBIeGA4LKXpKVxBEAAAABQA1/+8CdgJrAAwAGAAcACkAOAAAEzQ2MzIeARUUBiMiJjcVFBYzMjY1NCYiBiUDIxMDNTQ+ATMyFhQGIyImNxUUHgEzMjY1NC4BIyIGNk02JD0jTTc2TVEeFBUeHiodAWjhVeEtIz0kN01ONjZOUQ4YDRUeDhcOFR4B1j5XKEUoPldXPgEXISEYGCEhcf2dAmP+JgEoRChXfFdWPwEPGhAiGBAbDyIAAwA1AAAB2AJnACQAOQBIAAAlFwcnDgEjIiY1ND4CNyY1NDYzMhYVFA4IBxc3MyciBhUUHgQXPgU1NCYjAxY+ATcnDgUVFBYBmT8qQgdUMk1cDyETFDVTNzdPAwUJBw0HDgUMATUabPULGQQFCgUKAQENBAsEBBYNAQ8bEQRRAQ4ECwUEIbFNZEERMGJKHzMqEhFDQD9ZVjsLFxITDRAJDgULAUFBtRgSBw4LDwcOAQEQBg8LDwcPGf58AQsOB2IBDQUOCg8IGyQAAAAAAQA1ATwBSQJtABEAABMHNxcHFwcnFyM3Byc3JzcXJ+YXVSVnZyhTGE0WUShnZyVWGAJselJLJSVOVXp7Vk4nI0tReQACADUAAAGjAmQAFwAmAAA3NTQ+AzMyHgMdARQOAiMiLgI3FRQeATMyPQE0IyIOAjYZJzIvFxQtMicaIjc9Hh09OiR8CBsXOTkSGAsF4KQxTzEhDQwhMFAypDtaMhkYMlvjrBUkH1isVxEeGgABADUAAAEAAmEABQAAMxEjNTMRhE7KAd6D/Z8AAQA1AAMBkwJmACEAADc1Njc+AzU0JiMiByM+Ajc+AzMyFhUUBgcGBzMVOi5WFxkaCx0XMQJ2AQINDQ4qLCIQTlkjLkAargN3L1kYHCcoFyIhXhsgNxccJxIHbU04WDRHHYEAAAEANQAAAZ8CZAAtAAATNjc2MzIWFRQOAwcWFRQGIyImJyYnMxYXMjY1NC4DKwE1MzI1NCYjIgdDAjktP0RVCw0VCwlca0otVRYVBn4KLhobCg8UDQcsFT0RESQCAaxgMCdfQRcoGBcIBiVpTWwrKCRENgElHRAYCwcCbzsVHjMAAgA1//8BuwJjAAoADQAAITUjNRMzETMVIxUnMzUBDdfadDY20WJrcgGF/oN6a+XAAAAAAAEANf//AawCYwAgAAABFSMHNjMyHgIVFA4CIyIuASczFjMyNjU0JiMiBycTAX+uCxsnKUIlExYrSy8zUS8HfRYjGygkHy4SZSoCYoBSEic+QyEkSkIqL00xJi8hHy80HwFTAAACADUAAAG0AmIAFgAoAAABMhYVFAYjIiYnJjU0PwEzBw4BBzAyNgMyPgE1NC4EIyIGFRQeAQEaO19vTy9QGCksepBYAw4CCA0kEx8TBAgLDxQLHSUVHQGvbF9kgConOV1LVdqUBRYFAv7XFCYXChMSEAwHLyEaJxIAAAAAAQA1//8BdAJjAAYAABMhFQMjEyM2AT6sibS9AmJ3/hUB3wAAAwA1AAABmwJkABkAJAAuAAATNTQ2MhYVFA4BBxYVFA4BIi4BNTQ3LgMXFRQWMjY1NCYiBjcVFBYyNjQmIgZCVqBWFBAMPC1RaFEtPAkLEgpwHjAdHTAeCRskGxskGwG/AUJhYkIeMxINJGU5WjMzWjllJAkNHSbhARgqKhkaKirTARcfHy8fHwAAAAACADUAAAG0AmQAFgAkAAA/AT4BNyYOASMiJjU0NjMyFhcWFRQPARM1NC4BIyIGFRQWMzI2fVgDDQQBCA0EO15uTy9QGCoteSsVHhAcKCUfHiUBlAQWBgEBAWxfZIAqJzldTFXaAYkBGiYSLiIgMi4AAgA1/8wCdQJtADgASAAAAQcGBwYzMjY1NCYjIgYHBh4DFxY3FQYnLgQ3ND4CMzIWFRQGIyInBicuATU0NjMyFhc3BzY1NC4CJyYGHQEUFjc2AfscBAIBFhYmbFVhdgcBBhwtVThNX01cQGlGMBUBLExzQniZWjs3FB07NT1PQBwoBwgqCQIHEg0gKCAUIQG2ux0NGVo8Wm2Laxg2RTcpBAUfWxsCASlBVlsvQHpfOqF8XZBBNwEBWkRIcyAWKMkaIgcQGBEBAz8rAyYjAQIAAAIANQAAAcgCZQAHAAoAADcHIxMzEyMvAge8GG6bYJdvGhknK3JyAmT9nHJz1tYAAAMANQABAWQCaAAPABoAJQAANxEzMhcWFRQHFhUUBw4BIwMzMjc2NTQnJisBFxUzMjc2NTQnJiM2lEAiJC9DJhszNx0mEgkQEAgUJQExFAsVFAoWAgJlKShQUygka1cuIhMBfAYLIB4LBuNwCA4mIgwGAAAAAQA1AAABqQJnACUAACUzDgEjIi4CNTQ+AjMyHgMXIy4DIyIOARUUFjMyPgIBSWAQX0cxSiwWFStLMSM7KB4QA2AFDhQfER4pEi8qFCEUCulrfjNXbD47alk0HzJAPR0SISATNEwsSWcXJxkAAgA1AAABgwJlAA8AGAAAMxEzMh4DFxYVFA4CIwMRMzI1NCcmIzZ/EhcsICYOJBUtTzUiKF4TFzMCZAEMFi4hT29BbFcwAdr+r6dDLjkAAAABADUAAAE3AmUACwAAEyEVIxUzFSMVMxUhNgEBlpGSlv8AAmR4cHmKeQAAAAEANQAAATcCZQAJAAAzESEVIxUzFSMRNgEBmJOTAmR5b3r+/gAAAAABADUAAAG3AmYAIQAAARUmBw4CFRQeAjMyNzY3IzUzFgcGIyIuATU0NjMyFhcBQBQ3FygbEBkgESEWGQVr0wUTMH89WCpiX0haEAGbAUgCASNPOC1FKhUaHDlpZkOyVYlXiaZvWwAAAAEANQAAAYYCZQALAAAzIxEzFTM1MxEjNSOcZmaDZ2eDAmTm5v2c9QABADUAAACgAmUAAwAAMxEzETZpAmT9nAABADUAAAFRAmUAGgAAAREUBwYHBiMiLgMnJjUzFBYVFjMyNzY1EQFQDQ8fJi4IESsgIAUCcQEEGxUHBAJk/pZkLCscIwIRHkEsFxcCDAQzGxAhAZEAAAAAAQA1//8BiwJmAAoAABcRMxETMwMTIwMRNmdzbISTfnABAmb+7AEU/s/+zAEJ/vYAAQA1AAABGgJlAAUAADMRMxEzFTZpewJk/iaKAAEANQAAAeUCZQAMAAAzIxEzGwEzESMTAyMDlmCLTEuMYARZRVgCZP52AYr9nAHK/jYBygABADUAAAGMAmUACQAAGwEDMxEjAxMjEZ2NAWNikwJjAmT+lAFs/ZwBaf6XAmQAAAACADUAAAGsAmUADAAfAAATNDYzMhYVFA4BIyImNxQWMzI+BDU0LgIjIg4BNmRWUWs0VDRWZGgqKg8aEQ0IAwgSIhceJw4BLKGXmJpfjUaelUtjDxohKCcUHzo1IDVKAAACADUAAAFgAmYAEAAbAAATMzIeARcWFRQGBw4BKwEVIxMVMzI3NjU0JyYjNoEjMRoMLhcSFjEtKGRkJRoNGBkOHAJlCxMPO2cvWRkdGMAB3ZMJEi8uEQoAAwA1//8BvwJmABsALgA8AAAlFwYiLgInDgIjIi4BNTQ+ATMyFhUUBx4CAyIOBAc2MzIXFhc2NTQuAQMeAzsBMjcmJyYjIgG9AQINGRgcChMsFBM+VycmWD1Uah0GDQzAERwSDQcCARgVKCIbHQkbLGgGFRUTBgYWDhEOGSAPenkBAggSDRMTAlaGU1GIXK5/ZUkIBwEBZxIgHScLCBEoHzQeLTJOKP7/HCgQCQwiFSMAAAAAAgA1//8BjwJmAA0AGgAAJRcjJxUjETMXFhcWFRQnNjU0LgInKwEVMzIBDYF+cGpqOi4UW4QYCxARBQY1Lhb7++vqAmQBBQosgohEFyoVHg4IAZkAAQAyAAABjwJnACsAADczFBY3NjU0JicuAycmPgEzMhYXIy4DIyIGFRQWFx4BFRQOAiMiJjZ2JBIyJjwRICobAQE0TSs5WQp0AQMJEg0RHCdBQTEUJkQsXFbFKx8BBDgWIB4JFyg7ITlVKFRbCwwTCh0UFSIkJEc2JUE3IGkAAAABADUAAAFTAmUABwAAMxEjNSEVIxGLVQEdVQHseHj+FAAAAAABADUAAAGNAmUAGgAAEzMRFBceATI2NzY1ETMRFA4BBwYjIiYnLgE1NmsIBR8qHgUIagcQDjBUIk0ZGQwCZP6WLhsSGBYQFzUBa/6WM0MvFEEcJCZISwAAAQA1AAABpwJlAAYAADMDMxsBMwO2gGdQUWmAAmT+UwGt/ZwAAQA1AAACQAJkAAwAADMDMxsBMxsBMwMjCwGfaWk4PFA8OGhrWz4+AmP+cwGN/nEBj/2dAYz+dAABADUAAAHBAmUACwAAMxMDMxc3MwMTIycHNop6c0NCcnmJc1VRAUYBHq6u/t/+vdnZAAAAAQA1AAABlAJlAAkAADczAzMXNzMDFSOsAXdvQUFtd3HrAXn29v6H6wAAAAABADUAAAFDAmYACQAAAQMzFSE1EyM1IQFDiIj+85OTAQ0B5v6kimcBdYkAAAEANQFFAaYCagAGAAAbATMTIycHNnx3fYE4NwFFAST+3LOzAAIANQAAAcgCZQAHAAoAADcHIxMzEyMvAge8GG6bYJdvGhknK3JyAmT9nHJz1tYAAAMANQABAWQCaAAPABoAJQAANxEzMhcWFRQHFhUUBw4BIwMzMjc2NTQnJisBFxUzMjc2NTQnJiM2lEAiJC9DJhszNx0mEgkQEAgUJQExFAsVFAoWAgJlKShQUygka1cuIhMBfAYLIB4LBuNwCA4mIgwGAAAAAQA1AAABqQJnACUAACUzDgEjIi4CNTQ+AjMyHgMXIy4DIyIOARUUFjMyPgIBSWAQX0cxSiwWFStLMSM7KB4QA2AFDhQfER4pEi8qFCEUCulrfjNXbD47alk0HzJAPR0SISATNEwsSWcXJxkAAgA1AAABgwJlAA8AGAAAMxEzMh4DFxYVFA4CIwMRMzI1NCcmIzZ/EhcsICYOJBUtTzUiKF4TFzMCZAEMFi4hT29BbFcwAdr+r6dDLjkAAAABADUAAAE3AmUACwAAEyEVIxUzFSMVMxUhNgEBlpGSlv8AAmR4cHmKeQAAAAEANQAAATcCZQAJAAAzESEVIxUzFSMRNgEBmJOTAmR5b3r+/gAAAAABADUAAAG3AmYAIQAAARUmBw4CFRQeAjMyNzY3IzUzFgcGIyIuATU0NjMyFhcBQBQ3FygbEBkgESEWGQVr0wUTMH89WCpiX0haEAGbAUgCASNPOC1FKhUaHDlpZkOyVYlXiaZvWwAAAAEANQAAAYYCZQALAAAzIxEzFTM1MxEjNSOcZmaDZ2eDAmTm5v2c9QABADUAAACgAmUAAwAAMxEzETZpAmT9nAABADUAAAFRAmUAGgAAAREUBwYHBiMiLgMnJjUzFBYVFjMyNzY1EQFQDQ8fJi4IESsgIAUCcQEEGxUHBAJk/pZkLCscIwIRHkEsFxcCDAQzGxAhAZEAAAAAAQA1//8BiwJmAAoAABcRMxETMwMTIwMRNmdzbISTfnABAmb+7AEU/s/+zAEJ/vYAAQA1AAABGgJlAAUAADMRMxEzFTZpewJk/iaKAAEANQAAAeUCZQAMAAAzIxEzGwEzESMTAyMDlmCLTEuMYARZRVgCZP52AYr9nAHK/jYBygABADUAAAGMAmUACQAAGwEDMxEjAxMjEZ2NAWNikwJjAmT+lAFs/ZwBaf6XAmQAAAACADUAAAGsAmUADAAfAAATNDYzMhYVFA4BIyImNxQWMzI+BDU0LgIjIg4BNmRWUWs0VDRWZGgqKg8aEQ0IAwgSIhceJw4BLKGXmJpfjUaelUtjDxohKCcUHzo1IDVKAAACADUAAAFgAmYAEAAbAAATMzIeARcWFRQGBw4BKwEVIxMVMzI3NjU0JyYjNoEjMRoMLhcSFjEtKGRkJRoNGBkOHAJlCxMPO2cvWRkdGMAB3ZMJEi8uEQoAAwA1//8BvwJmABsALgA8AAAlFwYiLgInDgIjIi4BNTQ+ATMyFhUUBx4CAyIOBAc2MzIXFhc2NTQuAQMeAzsBMjcmJyYjIgG9AQINGRgcChMsFBM+VycmWD1Uah0GDQzAERwSDQcCARgVKCIbHQkbLGgGFRUTBgYWDhEOGSAPenkBAggSDRMTAlaGU1GIXK5/ZUkIBwEBZxIgHScLCBEoHzQeLTJOKP7/HCgQCQwiFSMAAAAAAgA1//8BjwJmAA0AGgAAJRcjJxUjETMXFhcWFRQnNjU0LgInKwEVMzIBDYF+cGpqOi4UW4QYCxARBQY1Lhb7++vqAmQBBQosgohEFyoVHg4IAZkAAQAyAAABjwJnACsAADczFBY3NjU0JicuAycmPgEzMhYXIy4DIyIGFRQWFx4BFRQOAiMiJjZ2JBIyJjwRICobAQE0TSs5WQp0AQMJEg0RHCdBQTEUJkQsXFbFKx8BBDgWIB4JFyg7ITlVKFRbCwwTCh0UFSIkJEc2JUE3IGkAAAABADUAAAFTAmUABwAAMxEjNSEVIxGLVQEdVQHseHj+FAAAAAABADUAAAGNAmUAGgAAEzMRFBceATI2NzY1ETMRFA4BBwYjIiYnLgE1NmsIBR8qHgUIagcQDjBUIk0ZGQwCZP6WLhsSGBYQFzUBa/6WM0MvFEEcJCZISwAAAQA1AAABpwJlAAYAADMDMxsBMwO2gGdQUWmAAmT+UwGt/ZwAAQA1AAACQAJkAAwAADMDMxsBMxsBMwMjCwGfaWk4PFA8OGhrWz4+AmP+cwGN/nEBj/2dAYz+dAABADUAAAHBAmUACwAAMxMDMxc3MwMTIycHNop6c0NCcnmJc1VRAUYBHq6u/t/+vdnZAAAAAQA1AAABlAJlAAkAADczAzMXNzMDFSOsAXdvQUFtd3HrAXn29v6H6wAAAAABADUAAAFDAmYACQAAAQMzFSE1EyM1IQFDiIj+85OTAQ0B5v6kimcBdYkAAAAAEADGAAEAAAAAAAEACAASAAEAAAAAAAIABwArAAEAAAAAAAMAFQBfAAEAAAAAAAQACACHAAEAAAAAAAUAIgDWAAEAAAAAAAYADwEZAAEAAAAAABAACAE7AAEAAAAAABEABwFUAAMAAQQJAAEAEAAAAAMAAQQJAAIADgAbAAMAAQQJAAMAKgAzAAMAAQQJAAQAEAB1AAMAAQQJAAUARACQAAMAAQQJAAYAHgD5AAMAAQQJABAAEAEpAAMAAQQJABEADgFEAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAADEALgAwADAAMgA7AFYAZQBnAGUAbQBpAHQAZQBSAGUAZwB1AGwAYQByAAAxLjAwMjtWZWdlbWl0ZVJlZ3VsYXIAAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFYAZQByAHMAaQBvAG4AIAAxAC4AMAAwADIAOwBGAG8AbgB0AHMAZQBsAGYAIABNAGEAawBlAHIAIAAzAC4AMwAuADAAAFZlcnNpb24gMS4wMDI7Rm9udHNlbGYgTWFrZXIgMy4zLjAAAFYAZQBnAGUAbQBpAHQAZQBSAGUAZwB1AGwAYQByAABWZWdlbWl0ZVJlZ3VsYXIAAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAAAAAAgAAAAAAAP+DADIAAAAAAAAAAAAAAAAAAAAAAAAAAABOAAAAAQACAQIBAwADAAQABgAHAAgACQANABMAFAAVABYAFwAYABkAGgAbABwAIwAkACUAJgAnACgAKQAqACsALAAtAC4ALwAwADEAMgAzADQANQA2ADcAOAA5ADoAOwA8AD0AQQBEAEUARgBHAEgASQBKAEsATABNAE4ATwBQAFEAUgBTAFQAVQBWAFcAWABZAFoAWwBcAF0ArAEECWNvbnRyb2xMRgljb250cm9sQ1IKc29mdGh5cGhlbgAAAAAAAAH//wACAAEAAAAMAAAAFgAAAAIAAQABAE0AAQAEAAAAAgAAAAAAAQAAAAoALAAuAAJERkxUAA5sYXRuABgABAAAAAD//wAAAAQAAAAA//8AAAAAAAAAAQAAAAoAMAA+AAJERkxUAA5sYXRuABoABAAAAAD//wABAAAABAAAAAD//wABAAAAAWtlcm4ACAAAAAEAAAABAAQAAgAAAAEACAABKd4ABAAAAEYAlgEwAd4CjAM2A+AEegUsBWYGDAa+B3AIHgjQCYIKNAriC4gMAgx0DOYNZA3mDlQOyg88D54QEBCGEQARchHsEmIS1BOWFAwUghTwFWIV1BaiFxQXkhgEGMYZdBomGtQbfhwYHL4dYB3+HpgfPh/oIJYhPCHmIpQjRiPsJJolSCXuJpQnQifoKJIpRAAmAAn/8QAK//sADP/7AA3/+wAO//sAD//7ABD/+wAR//sAEv/7ABP/+wAU//sAFf/xABb/8QAZ//sAHf/2AB7/+wAf//sAIP/xACH/+wAi//sAI//7ACT/+wAl//EAJv/2ACf/8QAo//sAKf/2ACr/+wAr//sALP/sAC3/7AAu/+IAL//dADD/9gAx/+wAMv/7ADP/+wA0//YAKwAG//EACP/nAAn/4gAK/9MAC//iAAz/9gAN/+IADv/sAA//4gAQ/9gAEf/iABL/1QAT//EAFP/nABX/8QAW/9gAMf/TADL/pgAz//MANP/nADX/8QA2//EAN//7ADj/7gA5//YAOv/7ADv/2AA8//EAPf/2AD7/9gA///EAQP/sAEH/+wBC/+wAQ//xAET/7ABF/+wARv/2AEf/3QBI/90ASf/EAEr/zgBL//YAKwAG//YAB//2AAn/3QAL/+wADP/sAA3/8QAO//YAD//sABD/8QAR/+wAEv/iABP/5wAU/+wAFf/dABb/7AAX/78AMf/YADL/sAAz/+IANP/iADX/8QA2/+cAN//xADj/3QA5/+wAOv/2ADv/4gA8//EAPf/xAD7/8QA///YAQP/YAEH/9gBC/+cAQ//sAET/7ABF/+wARv/xAEf/zgBI/9MASf/OAEr/zgBL/+wAKgAG//YAB//iAAj/4gAK/+IADP/dAA3/ugAO/+IAD//iABD/5wAR/+IAEv/dABP/yQAU/90AFf+mABb/0wAx/5gAMv/YADP/4gA0/9MANf/xADb/7AA3/+wAOP/iADn/7AA6//EAO//dADz/5wA9/+wAPv/sAD//5wBA/9gAQf/sAEL/zgBD/+wARP/YAEX/tQBG/90AR/+hAEj/oQBJ/8QASv+DAEv/7AAqAAb/8QAH/90ACP/YAAn/oQAL/8kADP/iAA3/sAAO/+cAD//YABD/4gAR/90AEv/bABP/4gAU/+IAFf/TABb/5wAg/+QAMf/nADL/3AAz//QANP/rADX/9AA2//IAN//4ADj/8AA5//QAOv/1ADv/7AA8/+oAPf/7AD7/9wA///IAQP/tAEH/+wBC/+IAQ//2AET/4wBF/7YARv/vAEf/pgBK/6MAS//yACYAB//TAAj/8QAK/84ADP/dAA3/9gAO//EAD//dABD/pgAR/8kAEv+6ABP/7AAU/90AFf/OADH/xAAy/5IAM//sADT/3QA1/+cANv/xADf/9gA4/90AO/9WADz/5wA9//EAPv/sAD//5wBA/84AQf/dAEL/0wBD/+cARP/nAEX/5wBG/+cAR//dAEj/2ABJ/7oASv/JAEv/4gAsAAb/+wAH//sACP/xAAn/zgAK/+cAC//dAAz/9gAN/9gADv/tAA//7AAQ/+kAEf/rABL/3QAT/90AFP/hABX/3QAW/90AMf/nADL/vwAz/+cANP/nADX/8QA2//EAN//sADj/5wA5//YAOv/2ADv/4gA8//EAPf/2AD7/+wA///sAQP/2AEH/+wBC/+wAQ//7AET/7ABF/9MARv/7AEf/yQBI/84ASf+wAEr/xABL/+cADgAG//sACf/xAAv/7AAN//sADv/7AA8AAAAR//EAEv/0ABP/9gAU//EAFf/xABb/7AAx//YAQP/2ACkABv/7AAf/9gAI//sACf/iAAr/5wAL/+wADP/vAA3/3QAO//sAD//qABD/8QAR/+wAEv/nABP/8QAU/+cAFf/iABb/7AAx/+cAMv/vADP//AA0/+cANf/7ADb//gA4//EAOf/8ADr//AA7/+kAPP/6AD3//QA+//4AP//7AEL/6gBD//0ARP/2AEX/7ABG//EAR//YAEj/4gBJ/+wASv/LAEv//AAsAAb/+wAH//EACP/2AAn/0wAK/+IAC//JAAz/5wAN/90ADv/iAA//7AAQ/+cAEf/sABL/3QAT/9MAFP/iABX/zgAW/+cAMf/YADL/xAAz/+wANP/dADX/6AA2//EAN//xADj/4wA5//EAOv/2ADv/7AA8/+wAPf/sAD7/9gA//+wAQP/iAEH/8QBC/90AQ//nAET/5wBF/8QARv/mAEf/xABI/8kASf+1AEr/rQBL/+IALAAG//sAB//7AAj/9gAJ/9MACv/2AAv/ugAM/+kADf/dAA7/9gAP/+wAEP/2ABH/8AAS//EAE//2ABT/5wAV/9gAFv/sADH/vwAy/9UAM//eADT/3wA1//EANv/xADf/9gA4/+IAOf/xADr/9gA7/+wAPP/xAD3/9gA+//EAP//2AED/2ABB//EAQv/nAEP/9gBE/+cARf/TAEb/8QBH/9gASP/YAEn/xgBK/78AS//xACsABv/7AAf/9gAI/+wACf/TAAr/5wAL/90ADP/lAA3/zgAO/90AD//dABD/7AAR/+IAEv/iABP/2AAU/+IAFf/JABb/5wAx/90AMv/EADP/6wA0/+EANf/wADb/8AA4/9wAOf/dADr/7AA7/9gAPP/sAD3/5wA+/+wAP//iAED/0wBB/+IAQv/YAEP/4gBE/84ARf/JAEb/4gBH/8kASP/OAEn/vwBK/8kAS//TACwABv/7AAf/3wAI/+cACf+wAAr/4wAL/8kADP/dAA3/xwAO/+cAD//dABD/7AAR/+cAEv/iABP/yQAU/9cAFf+/ABb/4gAa/+kAMf/YADL/uwAz/+EANP/dADb/6wA3//MAOP/lADn/8QA6//IAO//eADz/5wA9/+4APv/zAD//8ABA/+IAQf/2AEL/6gBD//YARP/kAEX/zABG/+8AR/+0AEj/uwBJ/64ASv+vAEv/5QAsAAb/+wAH/90ACP/nAAn/4gAK/9MAC//nAAz/3QAN//YADv/eAA//3QAQ/7AAEf/OABL/sAAT//sAFP/dABX/0wAW/9MAMf/iADL/iAAz//YANP/OADX/9gA2//EAN//xADj/0wA5//YAOv/zADv/gAA8//EAPf/7AD7/+wA///YAQP/OAEH/7gBC/84AQ//2AET/2ABF//sARv/2AEf/5wBI/+cASf/TAEr/4gBL/+wALAAG//sAB//2AAj/8QAJ/9gACv/nAAv/3QAM/+IADf/dAA7/4gAP/+IAEP/nABH/5wAS/9gAE//YABT/3QAV/84AFv/sADH/5wAy/78AM//nADT/2AA1/+cANv/nADf/7AA4/90AOf/sADr/7AA7/+cAPP/sAD3/8QA+/+wAP//xAED/4gBB//EAQv/dAEP/5wBE/+IARf/YAEb/5wBH/78ASP/HAEn/sABK/7UAS//dACsABv/xAAf/8QAI/+IACf/dAAr/0wAL/+IADP/iAA3/3QAO/+cAD//dABD/zgAR/9MAEv/EABP/0wAU/84AFv/dADH/4gAy/6EAM//jADT/3QA1/+wANv/sADf/5wA4/90AOf/nADr/8QA7/78APP/xAD3/9gA+/+wAP//nAED/3QBB/+cAQv/nAEP/5wBE/+IARf/OAEb/3QBH/8QASP/JAEn/lwBK/7oAS//YACkABv/sAAf/0wAI/90ACf/OAAr/3QAM/90ADf/EAA7/5wAP/9gAEP/YABH/3QAS/9MAE//YABT/4gAV/90AMf/sADL/wAAz/+8ANP/kADX/6wA2//AAN//2ADj/5AA5//EAOv/uADv/1gA8//QAPf/2AD7/8QA///AAQP/dAEH/7ABD/+gARP/YAEX/1QBG/+wAR/+3AEj/wwBJ/7UASv+wAEv/5gAeAAf/zgAi/+4AI//5ACT/7wAy/9AAM//pADT/sQA1/+sANv/nADf/5gA4/7oAOf/vADr/9wA7/9AAPP/sAD3/6wA+/+YAP//sAED/uwBB/+kAQv+7AEP/5ABE/9QARf+6AEb/0ABH/34ASP+SAEn/zQBK/5sAS//nABwAF//RACT//wAy/9EAM//uADT/5wA1/+8ANv/3ADf/7gA4/+gAOf/3ADr/+wA7/9oAPP/vAD3/9wA+/+4AP//vAED/4QBB//cAQv/nAEP/7wBE/+4ARf/QAEb/9wBH/8EASP/MAEn/wwBK/7sAS//nABwAF//QABv/+QAy/8EAM//zADT/6wA1//sANv/zADf/+wA4/+8AOf/zADr//gA7/+EAPP/vAD3/9wA+//kAP//3AED/4gBB//kAQv/jAEP/8wBE/+YARf/VAEb/+QBH/84ASP/JAEn/twBK/8EAS//rAB8ABv/7ABL/3wAX/8kAJf/5ACv/7wAy/7oAM//zADT/6wA1/+8ANv/uADf/8wA4/+oAOf/vADr/7wA7/9QAPP/5AD3//gA+//EAP//vAED/4wBB//MAQv/mAEP/7gBE/+cARf/XAEb/6wBH/8kASP/JAEn/twBK/7cAS//nACAABv/7ACQAAgAl/+8AJ//5AC3//gAv//4AMv/oADP//QA0/+sANf/7ADb/+gA3//sAOP/jADn/9wA6//oAO//kADz//wA9//0APv/+AD8AAABA/+gAQf/7AEL/6ABD//sARP/sAEX/8QBG//sAR//qAEj/6wBJ/+cASv/qAEv/+QAbAAb/+wAl/+8AMv+5ADP/+wA0/+8ANf/7ADb/+wA3//0AOP/vADn/+wA6AAAAO/+7ADz//gA9//4APv/7AED/7ABB//4AQv/nAEP/+QBE//kARf/7AEb/+QBH//MASP/rAEn/4gBK/+8AS//7AB0ABv/2ABf/zgAl/+8AMv+3ADP/9wA0/+sANf/3ADb/8QA3//kAOP/uADn/8wA6//sAO//YADz/8wA9/+4APv/3AD//8wBA/+MAQf/3AEL/6QBD/+8ARP/nAEX/1ABG/+8AR//JAEj/zABJ/6YASv/JAEv/3AAcAAb/+wAX//MAJf/7ADL/6wAz//4ANP/uADX/+wA2//4AN//+ADj/8wA5//0AOv/+ADv/7gA8//4APf/+AD7/+wA///4AQP/uAEL/9wBD//4ARP/+AEX/+QBG//4AR//uAEj/9wBJ/+4ASv/zAEv//gAYAAb/+wAx//YAMv/rADP//wA0//MANf//ADYAAQA3//8AOP/zADv/6AA8//4APf/+AD4AAQBA/+4AQf//AEL/8wBD//4ARP/4AEX//QBH/+wASP/3AEn/7ABK//EASwABABwABv/2ABf/4QAy/8oAM//9ADT/+QA1//4ANv/7ADf//gA4//MAOf/+ADr//wA7/+EAPP/7AD3//gA+//4AP//+AED/7wBB//4AQv/zAEP//gBE//sARf/7AEb//gBH/+8ASP/5AEn/2gBK//oAS//+AB0ABv/nABf/5wAx/7AAMv/hADP/7gA0/7QANf/rADb/5wA3/+4AOP+sADn/6wA6//kAO/+3ADz/6gA9/+8APv/nAD//5wBA/6wAQf/uAEL/rgBD/+cARP+8AEX/3ABG/9oAR//cAEj/0QBJ/9oASv/RAEv/7wAeAAb/9gAX//cAI//9ADH/vwAy/+4AM//5ADT/2gA1//4ANv/3ADf/+wA4/9oAOf/3ADr/+wA7/+cAPP/7AD3/+QA+//cAP//5AED/1ABB//sAQv/cAEP/9wBE/+8ARf/JAEb/6wBH/8QASP++AEn/5wBK/8EAS//+ABwAF//7ADH/7AAy/+QAM//+ADT/7gA1//4ANgAAADf//QA4//cAOf/7ADr//gA7/+4APP/+AD3//gA+//0AP//7AED/7wBB//4AQv/uAEP//gBE//cARf/7AEb/+QBH/+gASP/vAEn/6wBK/+gAS//+AB4ABv/7ABf/8wAa//4AHf/3ACX/9wAq//4AMf/2ADL/5AAz//0ANP/zADX/+wA2//4AN//+ADj/+QA7/+4APf/+AD7/+wA///4AQP/2AEH/+gBC/+4AQ//7AET/+QBF//sARv/+AEf/8wBI/+8ASf/zAEr/6wBL//4AHQAG//EAJP/3ADH/7AAy/7sAM//sADT/4wA1/+8ANv/vADf/9wA4/+QAOf/qADr/9wA7/98APP/vAD3/9wA+/+sAP//uAED/4wBB/+4AQv/mAEP/7wBE/+IARf/VAEb/7gBH/8MASP/GAEn/uwBK/7oAS//fABwABv/sACT//gAy/54AM//rADT/6gA1//EANv/rADf/9wA4/+MAOf/oADr/9wA7/64APP/sAD3/8QA+/+wAP//sAED/4QBB//MAQv/oAEP/5ABE/9gARf/kAEb/7gBH/9EASP/QAEn/uwBK/8QAS//zADAAF//3ABj//wAZ/+kAGv//ABv//QAc//4AHf/pAB7/+wAf//8AIP/iACH//gAi//8AI//+ACT//wAl/+IAJ//uACj//gAp/+cAKv/hACv/+QAs/8MALf/QAC7/5AAv/8wAMP//ADL/4QAz//4ANP/jADX/9wA3//kAOP/fADn/9wA7/+IAPP/5AD3/+gA+//EAP//6AED/2gBB/+8AQv/aAET/7wBF/9cARv/qAEf/xgBI/7sASf/qAEr/tABL//sAHQAG/+cAF//oACT/+gAy/+IAM//xADT/zAA1/+8ANv/sADf/+gA4/8wAOf/3ADr/8wA7/8kAPP/uAD3/7wA+/+wAP//rAED/yQBB//cAQv/MAEP/+ABE/9QARf/KAEb/2gBH/8EASP/EAEn/4gBK/7cAS//vAB0ABv/xABv/+QAl/+4AMv+8ADP/7wA0/9wANf/zADb/6AA3//cAOP/hADn/5gA6//MAO//aADz/6QA9//MAPv/pAD//6wBA/+MAQf/3AEL/2gBD/+kARP/rAEX/1ABG/+kAR//JAEj/zABJ/7QASv+7AEv/5wAbAAb/9gAy/6YAM//9ADT/0wA1//oANv/+ADf//QA4/9UAOf/3ADr//wA7/7kAPP/6AD3//gA+//sAP//7AED/0ABB//oAQv/XAEP/+QBE/+IARf/zAEb/9wBH/+8ASP/vAEn/6gBK/+cAS//6ABwABv/7ACQAAgAy/9UAM//7ADT/7wA1//cANv/9ADf//wA4/+4AOf/7ADr//wA7/+sAPP/+AD3//gA+//0AP//6AED/7gBB//sAQv/sAEP/+wBE/+8ARf/7AEb//QBH/+8ASP/qAEn/3wBK//gAS//+ABwABv/nABf/lQAy/4IAM//3ADT/wQA1/+kANv/nADf/+gA4/8QAOf/oADr/6wA7/5UAPP/uAD3/+wA+//cAP//vAED/wQBB/+8AQv/DAEP/5wBE/84ARf/uAEb/7gBH/+kASP/pAEn/zgBK/+4AS//7ADMABv/sABf/owAY//kAGf/XABr//gAb//4AHP/5AB3/0AAe//gAIP+tACH/8wAi//4AJP/+ACX/0AAm//kAJ//MACj//gAp/9oAKv/+ACv//gAs/+MALf/zAC7/3AAv//cAMP/7ADL/jwAz/+oANP/CADX/7wA2/+oAN//3ADj/xgA5/+sAOv/6ADv/qgA8/+sAPf/7AD7/7wA//+8AQP++AEH/7gBC/8MAQ//qAET/1QBF/+sARv/pAEf/6ABI/+cASf/iAEr/2gBL/+4AHAAG/+cAF//hADL/1AAz/+sANP+wADX/6wA2/+QAN//jADj/qgA5/+cAOv/jADv/ugA8/+cAPf/vAD7/2gA//+kAQP+uAEH/7wBC/64AQ//kAET/uwBF/9oARv/aAEf/zABI/84ASf/TAEr/zQBL/+sAHwAG/+IAF/+lACP//gAk//sAL//uADL/hwAz/+8ANP+sADX/+AA2/9wAN//6ADj/uQA5/+4AOv/vADv/hAA8/+gAPf/pAD7/5wA//+YAQP+wAEH/6QBC/7oAQ//vAET/zgBF/+gARv/oAEf/2gBI/+YASf/QAEr/4gBL/+kAHAAG//sAF//+ADL/5wAz//sANP/kADX/+wA2//8AN//7ADj/4QA5//4AOv//ADv/6wA8//sAPf/+AD7//gA///sAQP/hAEH/+wBC/9oAQ//+AET/7wBF//sARv/6AEf/6QBI//kASf/rAEr/6QBL//sAMAAG/+wAB//YAAj/3QAJ/9MACv+/AAv/yQAM/+IADf/YAA7/7AAP/9MAEP/JABH/5wAS/+IAE//OABT/4gAV/+wAFv/nACD/WwAh/+wAIv/xACP/8QAk//YAJf/xADL/oQAz/+wANP/nADX/7AA2//sAN//2ADj/9gA5//sAO/+PADz/7AA9//YAPv/sAD//8QBA/+IAQf/nAEL/7ABD/+IARP/JAEX/zgBG/+cAR/+/AEj/xABJ/5IASv+/AEv/4gArAAb/9gAI/8QACf+cAAr/zAAL/5QADP+6AA3/xAAO/+oAD//BABD/zgAR/78AEv+7ABP/2AAU/78AFf+mABcAAgAk/+cAMf+mADL/2AAz/+cANP+7ADX/5gA2//MAN//zADj/sQA5/+oAOv/rADz/6AA9/+gAPv/mAD//5wBA/7oAQf/4AEL/twBD/+gARP/OAEX/sQBG/88AR/+EAEj/lwBJ/9AASv+NAEv/9wAsAAb/9gAH/+oACP/nAAn/xAAK/+gAC//TAAz/3QAN/9gADv/lAA//5wAQ/+IAEf/aABL/3AAT/9MAFP/bABX/xAAk//EAMf/YADL/zQAz/+wANP/kADX/9wA2//MAN//9ADj/4wA5//cAOv/3ADv/5gA8//4APf/9AD7/7gA//+4AQP/kAEH/+QBC/+YAQ//vAET/6QBF/9oARv/vAEf/zgBI/88ASf/QAEr/uQBL//kAKwAG//YAB//qAAj/7AAJ/9gACv/uAAv/4gAM/+IADf/dAA7/9AAP/+IAEP/eABH/5gAS/+IAE//TABT/3QAV/90AJP/2ADH/7AAy/74AM//uADT/3wA1//oANv/xADj/5wA5/+8AOv/5ADv/2AA8/+0APf/9AD7/8wA///EAQP/rAEH/+ABC/+QAQ//3AET/5gBF/9AARv/zAEf/xgBI/80ASf++AEr/twBL/+gAKgAH//EACP/xAAn/0wAK/+YAC//YAAz/5wAN/9gADv/oAA//5wAQ/+IAEf/iABP/2AAU/90AFf/dACT/+wAx/+wAMv+7ADP/9wA0/+QANf/rADb/5wA3//EAOP/kADn/+QA6//YAO//aADz/9wA9//4APv/uAD//8QBA/+cAQf/vAEL/4wBD/+sARP/cAEX/0ABG/+sAR//CAEj/xABJ/7QASv+6AEv/6AAmAAf/9gAI//EACf/sAAr/9gAM/+cADv/6AA//8QAQ//EAEf/vABL/4QAT//EAFP/iABX/5wAy/+kAM//9ADT/5wA1//sANv/9ADf//gA4/+sAOf/+ADoAAQA7/+gAPP/9AD3/9wA+//0AP//9AED/6wBBAAEAQv/pAEP/+QBE/+wARgACAEf/6QBI/+8ASf/nAEr/6wBL//sAKQAH//sACP/xAAn/5wAK/+4AC//2AAz/4gAN//sADv/1AA//8QAQ/90AEf/kABL/4gAT/+wAFP/YABX/3QAx//YAMv+5ADP/+AA0/+MANf/3ADb/+AA3//kAOP/iADn/+gA6//0AO//OADz//QA9//4APv/5AD///ABA/+YAQv/jAEP/9wBE/+YARf/vAEb//gBH/+cASP/vAEn/0QBK/+YAS//9ACgAB//2AAj/4gAJ/90ACv/sAAv/4gAM/+gADf/iAA7/9QAP/+gAEP/dABH/4AAS/+YAE//OABT/4gAV/90AJP/7ADH/9gAy/8EAM//vADT/3wA2//QAN//4ADj/4wA5/+kAOv/6ADv/0QA8/+YAPf/zAD7/6QA///EAQP/qAEL/3ABD/+gARP/fAEb/+ABH/7sASP+7AEn/rwBK/68AS//jACcACP/xAAn/7AAK//gADP/2AA7/9wAP//YAEP/xABH/5wAS/+cAE//xABT/7AAV/+UAMf/2ADL/6AAz//kANP/qADX/+wA2//oAN//7ADj/6wA5//cAOv//ADv/4wA8//sAPf/+AD7/+wA///oAQP/sAEH/+gBC/+MAQ//5AET/7wBF/+oARv/7AEf/4wBI/+wASf/jAEr/6gBL//4AJgAH//sACP/7AAn/5wAK//oADP/2AA7/9gAP//YAEP/xABH/8QAS//IAE//xABT/5wAV//EAMv/nADP/+wA0//EANf/9ADb//gA3//4AOP/uADn/+wA6//4AO//oAD0AAAA+//sAP//+AED/7wBB//4AQv/qAEP//wBE//EARf/3AEb/+wBH/+YASP/3AEn/2gBK/+QAS//7ACkAB//2AAj/9gAJ/90ACv/yAAz/8QAO//EAD//wABD/6gAR/+wAEv/mABP/9AAU/+wAFf/rABf/zgAx//YAMv/OADP/7wA0/+oANf/5ADb//gA3//0AOP/oADn/+QA6//0AO//YADz//gA9//8APv/6AD//+QBA/+4AQf/5AEL/4wBD//gARP/qAEX/+QBG//oAR//pAEj/6QBJ/9UASv/rAEv/+gAqAAf/sgAI/8kACf+wAAr/ugAL/7UADP+1AA3/3QAO/+QAD/+6ABD/sgAR/7UAEv+xABP/4gAU/6sAFf+mADH/lwAy/9oAM//jADT/qwA1/+IANv/iADf/4wA4/5oAOf/XADr/7gA7/7QAPP/kAD3/6wA+/+4AP//mAED/rQBB/+8AQv+qAEP/6gBE/74ARf/XAEb/2gBH/9AASP/SAEn/1QBK/80AS//qACsAB//nAAj/8QAJ/6YACv/sAAv/nAAM/90ADf+6AA7/9gAP/+IAEP/sABH/3QAS/9oAE//sABT/3QAV/8QAJP/+ADH/pgAy/+sAM//vADT/ygA1//0ANv/zADf/+wA4/9MAOf/vADr/+wA7/9gAPP/3AD3/9wA+//EAP//7AED/1QBB//cAQv/PAEP/8wBE/+YARf+7AEb/5wBH/7UASP/JAEn/2gBK/6UAS//zACkAB//2AAn/7AAK//kAC//sAAz/9gAO//oAD//2ABD/7AAR/+cAEv/vABP/9gAU//EAFf/sABcAAQAx/+YAMv/pADP/+QA0/+oANf/zADb/+wA3//oAOP/nADn/9wA6//4AO//uADz/+QA9//oAPv/7AD//+QBA/+8AQf/3AEL/6QBD//oARP/sAEX/8wBG//gAR//pAEj/6QBJ/+MASv/nAEv//QAqAAf/9gAI//sACf/sAAr/9wAL/+wADP/7AA7/+gAP//EAEP/2ABH/7AAS//EAE//2ABT/9gAV/+QAFwABADH/8QAy/+kAM//3ADT/6QA1//kANv/5ADf/+QA4/+8AOf/6ADr//gA7/+8APP/7AD3/+gA+//oAP//4AED/7wBB//sAQv/rAEP//QBE/+8ARf/3AEb/+gBH/+4ASP/rAEn/4QBK/+wAS//5ACsAB//xAAj/4gAJ/9gACv/sAAv/2AAM//YADf/iAA7/8QAP/90AEP/iABH/0wAS/+IAE//JABT/4gAV/94AJP/7ADH/3QAy/7QAM//pADT/4QA1/+wANv/vADf/6gA4/+IAOf/qADr/+gA7/9oAPP/pAD3/6wA+/+wAP//pAED/4QBB/+sAQv/cAEP/6wBE/+IARf/JAEb/7gBH/7wASP/BAEn/pgBK/7UAS//kACwAB//iAAj/5wAJ/+IACv/OAAv/2AAM/+cADf/nAA7/8AAP/90AEP+6ABH/xAAS/9cAE//XABT/2AAV/9gAG//3ACT/+wAx/+IAMv+gADP/6QA0/+MANf/mADb/7wA3/+sAOP/aADn/6AA6//YAO/+xADz/6wA9/+4APv/oAD//7wBA/9oAQf/oAEL/1wBD/+MARP/aAEX/2ABG/+cAR//PAEj/yQBJ/7kASv/BAEv/6AApAAf/8QAI/+wACf/OAAr/6gAL/84ADP/nAA3/2AAO//YAD//fABD/4gAR/9gAEv/lABP/5wAU/+IAFf/YADH/4gAy/+cAM//3ADT/2gA1//gANv/5ADf/+wA4/9wAOf/3ADr//gA7/+MAPP/3AD3//QA+//cAP//3AED/1QBC/9UAQ//9AET/6QBF/+EARv/pAEf/ugBI/8QASf/aAEr/wgBL//sAKwAH/8kACP/YAAn/xAAK/9MAC/+/AAz/yQAN/9gADv/nAA//xAAQ/7oAEf+1ABL/wQAT/9gAFP+6ABX/vwAk//sAMf+/ADL/2gAz/+gANP/KADX/6QA2/+kAN//oADj/xgA5/+QAOv/nADv/uQA8/+wAPf/uAD7/6QA//+cAQP/GAEH/7ABC/8kAQ//mAET/2ABF/84ARv/VAEf/wQBI/7wASf/GAEr/tABL/+8AKwAH//EACP/2AAn/yQAK/+oAC//TAAz/3QAN/+cADv/sAA//4gAQ/+IAEf/YABL/3wAT/90AFP/dABX/2AAk//sAMf/nADL/xgAz//MANP/iADX/7wA2/+4AN//3ADj/4wA5/+kAOv/vADv/1wA8/+4APf/zAD7/6gA//+0AQP/kAEH/9wBC/98AQ//qAET/5wBF/9AARv/vAEf/yQBI/9AASf/PAEr/xABL/+8AKQAH/+cACP/sAAn/5wAK/+kAC//dAAz/2AAO/+wAD//XABD/qwAR/8kAEv/AABP/9gAU/9MAFf/OADH/2AAy/7AAM//5ADT/2gA1//0ANv/6ADf//gA4/98AOf/3ADr//QA7/8YAPP/7AD3//gA+//gAP//4AED/1QBB//0AQv/VAEP/+ABE/+MARf/zAEb/+QBH/+4ASP/zAEn/4gBK/+cAS//zACkACP/2AAn/5wAK//QAC//sAAz/+wAN//4ADv/2AA//5QAQ/+wAEf/nABL/8wAT//EAFP/nABX/3QAx/+QAMv/KADP/+QA0/+wANf/6ADb/+gA3//sAOP/vADn/+gA6AAAAO//hADz//wA9//0APv/5AD///gBA/+wAQf/7AEL/7ABD//sARP/vAEX/9wBG//sAR//zAEj/6gBJ/+EASv/jAEv/+wArAAf/zgAI/84ACf/YAAr/ygAL/9gADP/JAA3/+wAO/9kAD//JABD/ogAR/7oAEv+5ABP/5wAU/8QAFf+9ACT/+wAx/7oAMv+FADP/+wA0/7sANf/qADb/6wA3/+wAOP++ADn/5gA6/+8AO/+iADz/6AA9/+oAPv/sAD//7wBA/8MAQf/mAEL/uwBD/+YARP/KAEX/6QBG/+8AR//jAEj/3wBJ/9MASv/hAEv/6wApAAf/zgAI/84ACf/TAAv/2AAM/84ADv/eAA//xAAQ/7AAEf/TABL/sQAT/+wAFP/FABX/yQAk//sAMf/JADL/lQAz//MANP/BADX/+QA2//MAN//3ADj/xgA5//sAOv/3ADv/pQA8/+8APf/+AD7/7gA//+oAQP/DAEH/7gBC/8QAQ//vAET/0ABF/+4ARv/uAEf/6QBI/+QASf/aAEr/5gBL//cAKgAH/8QACP/OAAn/pgAL/7oADP+rAA3/3QAO/+cAD/+5ABD/twAR/8QAEv+zABP/0wAU/7AAFf+cACT/+wAx/6EAMv/aADP/4wA0/7cANf/4ADb/4wA3//0AOP+3ADn/7gA6/+8AO/+7ADz/7gA9//EAPv/jAD//6ABA/7oAQf/zAEL/uQBD/+sARP/OAEX/3wBG/+EAR//aAEj/2ABJ/9gASv/MAEv/7gAsAAf/yQAI/84ACf/JAAr/wgAL/8kADP/JAA3//gAO/8kAD/+6ABD/jQAR/7oAEv+gABP/4gAU/7UAFf+6AB7/8QAk//sAMf+1ADL/lwAz/+8ANP+7ADX/5gA2/+4AN//uADj/uQA5/+gAOv/3ADv/hAA8/+8APf/sAD7/7AA//+oAQP+6AEH/7ABC/7kAQ//pAET/ygBF/+8ARv/vAEf/6ABI/+kASf/fAEr/5ABL//EAJgAH//YACf/iAAr/7AAL/+cADP/iAA3//wAO//UAD//nABD/7AAR/+IAEv/gABP/7AAU/90AFf/TADH/4gAy/+sAM//+ADT/6AA1//4ANgAEADf//wA4/9wAOf/6ADv/5gA8//8APf//AD///QBA/+MAQf//AEMAAABE/+8ARf/4AEb/+wBH//cASP/rAEn/6QBK/+kAS//9AAIAAQAGAEsAAAAAAAAAAQAAAADUGBYRAAAAANmXsTQAAAAA2ZexNA==",et=i=>Or("http://www.w3.org/2000/svg",i),tl=(i,t)=>{const e=et("rect");return e.setAttribute("height",`${i}`),e.setAttribute("width",`${t}`),e},el=(i,t,e,a)=>{const n=Ce("filter");n.setAttribute("id",a),n.setAttribute("height","200%"),n.setAttribute("width","200%"),n.setAttribute("x","-50%"),n.setAttribute("y","-50%");const r=Ce("feOffset");n.appendChild(r),r.setAttribute("result","offOut"),r.setAttribute("in","SourceAlpha"),r.setAttribute("dx",`${i}`),r.setAttribute("dy",`${t}`);const s=Ce("feGaussianBlur");n.appendChild(s),s.setAttribute("result","blurOut"),s.setAttribute("in","offOut"),s.setAttribute("stdDeviation",`${e}`);const o=Ce("feBlend");return n.appendChild(o),o.setAttribute("in","SourceGraphic"),o.setAttribute("in2","blurOut"),o.setAttribute("mode","normal"),n},al=i=>{let t=i;return t=t.replace(/feoffset/gi,"feOffset"),t=t.replace(/fegaussianblur/gi,"feGaussianBlur"),t=t.replace(/feblend/gi,"feBlend"),t=t.replace(/lineargradient/gi,"linearGradient"),t=t.replace(/stddeviation/gi,"stdDeviation"),t};function nl(i,t,e,a,n,r){const s=n,o=r,l={x:t[0],y:t[1],width:t[2]-t[0],height:t[3]-t[1]};if(l.width<=0)return;const c=il(l.height,l.width,e*s,a*o),d=(a-c*l.width)/2-c*l.x,u=(e-c*l.height)/2-c*l.y;i.setAttribute("transform",`translate(${d} ${u}) scale(${c} ${c})`)}function il(i,t,e,a){const n=e/i,r=a/t;return n>1&&r>1?Math.min(n,r):n>1&&r<1?r:n<1&&r>1?n:Math.min(n,r)}const yn={m:["x","y"],z:[],l:["x","y"],h:["x"],v:["y"],c:["x1","y1","x2","y2","x","y"],s:["x2","y2","x","y"],q:["x1","y1","x","y"],t:["x","y"],a:["rx","ry","xRotation","largeArc","sweep","x","y"]};class rl{constructor(t){const e=Array.from(t.querySelectorAll("path"));this.paths=e.map(a=>{const n=a.getAttribute("d")||"",r=this.parsePath(n);return{pathElement:a,pathData:r}})}transform(t){for(const e of this.paths)e.pathData=this.runTransformer(e.pathData,t);this.update()}encodePath(t){let e="";const n=r=>{const s=[],o=r.relative?r.type:r.type.toUpperCase();let l=e!==o;const c=yn[r.type];l&&(s.push(o),e=o);for(const d of c){const u=r[d];let A;switch(typeof u){case"boolean":A=u|0;break;case"number":A=(u*100|0)/100;break;default:throw new It("Failed to encode path.")}l||s.push(" "),s.push(A),l=!1}return s.join("")};return t.map(n).join("")}parsePath(t){const e=/([mzlhvcsqta])([^mzlhvcsqta]*)/gi,a=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi,n=[];let r;for(e.lastIndex=0;r=e.exec(t);){const s=r[1].toLowerCase(),o=(r[2].match(a)||[]).map(parseFloat),l=s===r[1],c=yn[s];if(o.length<c.length)throw new It(`Path type "${s}" given ${o.length} arguments, expected ${c.length}.`);if(c.length>0){if(o.length%c.length!==0)throw new It(`Path type "${s}" given ${o.length} arguments, not divisible by ${c.length}`);for(let d=0;d<o.length/c.length;d++){const u={type:s,relative:l};for(let A=0;A<c.length;A++)u[c[A]]=o[d*c.length+A];n.push(u)}}else n.push({type:s,relative:l})}return n}runTransformer(t,e){const a=[["x1","y1"],["x2","y2"],["x","y"]],n=r=>{for(let s=0;s<a.length;s++){const[o,l]=a[s];if(o in r&&l in r){const c=[r[o],r[l]],d=e(c);if(d.length<2)throw new It("Transformer must return at least 2 points.");r[o]=d[0],r[l]=d[1]}}return r};return this.transformPath(t,n)}transformPath(t,e){const a=[];for(let n=0;n<t.length;n++){const r=JSON.parse(JSON.stringify(t[n])),s=e(r);Array.isArray(s)?a.push(...s):s&&a.push(s)}return a}update(){for(const{pathElement:t,pathData:e}of this.paths){const a=this.encodePath(e);t.setAttribute("d",a)}}}class sl extends Zo{constructor(){super(...arguments),this.moduleName="Vegemite"}svgPreview(t,e){return this.svgElement(t,e)}svgPrint(t,e){return this.svgElement(t,e)}svgElement(t,e){const a=po(_o),r=t!==""?(w=>w.charAt(0).toUpperCase()+w.substr(1).toLowerCase())(t):"",s=a.getPath(r,0,72,72),o=s.toSVG(2),l=s.getBoundingBox(),c=l.x2-l.x1,d=s.toPathData(3),u=()=>{const w=et("g");w.classList.add("module-text-group");const F=et("defs");w.appendChild(F),F.appendChild(el(0,2,2,"shadow"));const b=et("path");b.setAttribute("d",d),b.setAttribute("stroke","black"),b.setAttribute("stroke-width","3"),F.appendChild(b);const v=et("g");v.classList.add("module-layer0"),w.appendChild(v),v.setAttribute("filter","url(#shadow)"),v.innerHTML=b.outerHTML;const B=et("g");B.classList.add("module-layer1"),w.appendChild(B),B.setAttribute("stroke-width","3"),B.setAttribute("stroke","rgb(45,41,38)"),B.setAttribute("fill","rgb(45,41,38)"),B.setAttribute("transform","translate(0.5,0)"),B.innerHTML=o;const M=et("g");M.classList.add("module-layer2"),w.appendChild(M),M.setAttribute("fill","rgb(255,209,0)"),M.setAttribute("transform","translate(1,-0.1)"),M.innerHTML=o;const R=et("g");return R.classList.add("module-layer3"),w.appendChild(R),R.setAttribute("fill","white"),R.innerHTML=o,new rl(w).transform(([T,L])=>[T,L+(c/2-T)**2/(c*6)]),w},A=et("g");A.classList.add("module-root");const h=et("defs");A.appendChild(h);const g=et("g");g.classList.add("module-bounds"),A.appendChild(g);const p=tl(e.height,e.width);p.setAttribute("opacity","0"),g.appendChild(p);const m=et("g");m.classList.add("module-text-enclosure"),A.appendChild(m);const C=u();m.appendChild(C);const S=Pr(d);return nl(m,S,e.height,e.width,.35,.65),al(A.outerHTML)}}async function bi(i){if(i==="Vegemite")return new sl;throw new O(`Failed to resolve Module, Module ${i} not found`)}const ol=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],ll=async(i,t,e)=>{const a=t.data,n=e.data.baseUrl,r=a.assetUrl.replace("localhost","localstack"),s=n.slice(0,4)==="http"?"":"https://",o=new URL(s+n);o.searchParams.append("video",dn(JSON.stringify([{href:r}]))),o.pathname=o.pathname+(o.pathname.slice(-1)==="/"?"":"/");const l=o.toString(),d=`data:image/svg+xml;base64,${dn(await Fn.toString(l,{type:"svg"}))}`,u=h=>{const g=i.find(m=>m.panelId===h.panelId);if(!g)throw new J(h);const p=N();return new W({id:p,src:d,type:D.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},A=e.data.regions;try{return A.map(u)}catch(h){return console.error(h),[]}},cl=async(i,t,e,a)=>{const n=e.data,r=n.assetUrl,s=await ba(r);try{const o=await xo(n,a.option);o&&(t[a.stepName]={selectedVariants:[o]});const l=async c=>{const d=await mi(c,o?.asset?.fileLink),u=await he(d),A=N(),h=i.find(p=>p.panelId===c.panelId);if(!h)throw new J(c);const g=Va(s,u,{scale:n.scale,left:n.x,top:n.y},a.data.forceImageCover);return[new W({id:A,path:u.path,type:D.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/u.width,scaleY:c.height/u.height,pattern:{id:`${A}-pattern`,src:s.src,x:g.x,y:g.y,width:s.width,height:s.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:s.svg,colors:s.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(o){return console.error(o),[]}},dl=async(i,t,e,a)=>{const n=e.data,r=await I.getOptionForStep(a);if(!r)return console.error(`No option for step ${a.stepName}.`),[];const s=r.variants?.find(b=>b.id===n.illustrationVariantId)||await I.getDefaultVariant(r,a.overrideDefaultVariantId);if(!s)return console.error(`No variant with ID: ${n.illustrationVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=s.asset?.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.illustrationVariantId}`),[];const l=await tt(o,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],u=d?.length>0?d[0]:"",g=ot().parseFromString(u,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];ze(g);const p={};Rt(g,b=>{ol.includes(b.tagName)&&!b.attributes.getNamedItem("fill")&&b.setAttribute("fill","#000000");const v=b.attributes.getNamedItem("fill");if(v&&v.value!=="none"){const M=v.value,x=`spiff-fill-${M.replace(/\W/g,"")}`;b.classList.add(x),p[x]={browserValue:M}}const B=b.attributes.getNamedItem("stroke");if(B&&B.value!=="none"){const M=B.value,x=`spiff-stroke-${M.replace(/\W/g,"")}`;b.classList.add(x),p[x]={browserValue:M}}});const C=Et().serializeToString(g),S=n.colors;if(S){for(const[b,v]of Object.entries(p))for(const B of Object.keys(S))if(v.browserValue===B){p[b]={browserValue:S[B]};break}}const w=b=>{const v=i.find(M=>M.panelId===b.panelId);if(!v)throw new J(b);const B=N();return new W({colors:p,id:B,svg:C,type:D.Illustration,y:b.top,x:b.left,rotation:b.rotation,width:b.width,height:b.height,layer:b.layer,layerIndex:b.layerIndex,immutable:b.immutable},v)},F=a.data.regions;try{return F.map(w)}catch(b){return console.error(b),[]}},ul=async(i,t,e)=>{const a=await bi(e.data.module),n=t.data,r=(o,l)=>{const c=i.find(u=>u.panelId===l.panelId);if(!c)throw new J(l);const d=N();return new W({colors:{},id:d,svg:o,type:D.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},s=e.data.regions;try{return s.map(o=>r(a.svgPrint(n.text,o),o))}catch(o){return console.error(o),[]}},Al=async(i,t,e,a)=>{const n=e.data,r=await I.getOptionForStep(a);if(!r)return console.error(`No option for step ${a.stepName}.`),[];const s=r.variants?.find(d=>d.id===n.pictureVariantId)||await I.getDefaultVariant(r,a.overrideDefaultVariantId);if(!s)return console.error(`No variant with ID: ${n.pictureVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=s.asset?.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.pictureVariantId}`),[];const l=d=>{const u=i.find(h=>h.panelId===d.panelId);if(!u)throw new J(d);const A=N();return new W({id:A,src:o,type:D.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},u)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},hl=async(i,t,e,a)=>{const n=e.data,r=await I.getOptionForStep(a);if(!r)return console.error(`No option for step ${a.stepName}.`),[];const s=r.variants?.find(c=>c.id===n.colorVariantId)||await I.getDefaultVariant(r,a.overrideDefaultVariantId);if(!s)return console.error(`No variant with ID: ${n.colorVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=c=>{const d=i.find(p=>p.panelId===c.panelId);if(!d)throw new J(c);const u=`
1430
1430
  <svg
1431
1431
  xmlns="http://www.w3.org/2000/svg"
1432
1432
  xmlnsXlink="http://www.w3.org/1999/xlink"
@@ -1443,11 +1443,11 @@
1443
1443
  width="1"
1444
1444
  height="1"
1445
1445
  class="spiff-fill-shape"
1446
- fill="${o?.color}"
1446
+ fill="${s?.color}"
1447
1447
  />
1448
1448
  </svg>
1449
- `,h={"spiff-fill-shape":{browserValue:o.color||"#000000"}},g=N();return new H({colors:h,id:g,svg:u,type:D.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(s)}catch(c){return console.error(c),[]}},xl=async(i,t,e)=>{const a=[],r=t.type===E.ProductOverlay?e||t.data.asset?.fileLink||"":t.data.asset?.fileLink||"",s=r.endsWith(".jpeg")||r.endsWith(".jpg")||r.endsWith(".png")?D.Image:(r.endsWith(".svg"),D.Illustration),l=t.data.regions;if(s==="image")try{l.forEach(c=>{const d=i.find(A=>A.panelId===c.panelId);if(!d)throw new J(c);const u={id:N(),src:r,type:s,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===E.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new H(u,d))})}catch(c){console.error(c)}else{const c=await et(r,!0),d=u=>{const A=/<svg.*?<\/svg>/s,h=u.match(A)||[],g=h?.length>0?h[0]:"",C=ct().parseFromString(g,"image/svg+xml").firstElementChild;if(!C)throw new Pt("Failed to read SVG.");return je(C),It().serializeToString(C)};l.forEach(u=>{const A=i.find(g=>g.panelId===u.panelId);if(!A)throw new J(u);const h={id:N(),src:r,asset_key:r,svg:d(c),colors:{},type:s,y:u.top,x:u.left,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,scaleX:1,scaleY:1,rotation:u.rotation,productOverlay:t.type===E.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new H(h,A))})}return a},Fl=async(i,t,e,a)=>{const n=[],r=e.data,o=30,s=m=>m.vertical?"center":m.textAlign||"center",l=async()=>{const m=await I.getOptionForStep(a);if(!m)return;const C=m.variants?.find(w=>w.id===r.fontVariantId)||await I.getDefaultVariant(m,a.overrideDefaultVariantId);if(!C||!C.asset)return;t[a.stepName]={selectedVariants:[C]};const S=C.asset.fileLink;if(S)return S},d=await(async()=>{const m=await l();if(!m)return;const C=await Ft(m);return{assetUrl:m,name:C.names.fullName.en}})(),u=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",r.text):r.text)||"",A=Me(u,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async m=>{const C=m.colorOption;return C?(await I.getDefaultVariant(C))?.color:void 0},g=r.color||await h(a.data),p=a.data.regions;for(const m of p){const C=i.find(w=>w.panelId===m.panelId);if(!C)continue;const S={stepName:e.name,id:N(),align:s(a.data),curved:a.data.curved,fill:r.color||g||"#000000",fontData:d,fontSize:a.data.size||o,height:m.height,layer:m.layer,layerIndex:m.layerIndex,paths:a.data.paths,rotation:m.rotation,text:A,type:D.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:m.width,x:m.left,y:m.top};if(d){const[w,F]=Xt(a.data.size||o,d,m,[Me(A,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});n.push(new H({...S,fontSize:w,text:S.curved?S.text:(F||[]).join(`
1450
- `)},C))}else n.push(new H(S,C))}return n},Ri=async(i,t,e,a)=>{const n=[],r={};for(const o of i){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case E.DigitalContent:n.push(...await vl(e,o,s));break;case E.Frame:case E.Photo:n.push(...await El(e,r,o,s));break;case E.Illustration:n.push(...await bl(e,r,o,s));break;case E.Module:n.push(...await Il(e,o,s));break;case E.Picture:n.push(...await Bl(e,r,o,s));break;case E.Shape:n.push(...await Pl(e,r,o,s));break;case E.Text:n.push(...await Fl(e,r,o,s));break}}for(const o of t.steps)o.type!==E.SilentIllustration&&o.type!==E.ProductOverlay||await Ct(o,r)&&n.push(...await xl(e,o,a));return n};class Dl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Tl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const kl=()=>new Promise((i,t)=>{try{const a=vt().getContext("webgl2");i(!!a)}catch{i(!1)}}),Ml=kl();class Tl{constructor(t,e,a,n,r){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new _e(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=r}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=yt(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Nl(this.getID(),a,await Ml,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Nl extends Ke{constructor(t,e,a,n,r,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=r,this.getWorkflowManager=o}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,r=Math.min(a,n);return r>1?t:{width:t.width*r,height:t.height*r}}async execute(){const t=this.layouts.find(g=>g.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,r=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=r.width,s=r.height;let l,c;if(this.nonPOTSupport){const g=o/s;a/n<g?(l=o,c=n*(o/a)):(l=a*(s/n),c=s);const m=this.resizeFit({width:l,height:c});l=m.width,c=m.height}else l=r.width,c=r.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),u=Xe(t.layoutState.layout,e,{renderingConfiguration:{purpose:Ot.ThreeD,templatingContext:d}}),A=Zn(u),h=await $a.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:vt,createImage:de,DOMParser:qa(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const Ql=(i,t)=>{const e=[];return i.forEach(a=>{const n=t.steps.find(r=>r.stepName===a.stepName);n?.type===E.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Ol=async(i,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new U(e.map(l=>new Ja(l))).apply(n);const o=await Ri(i,t,e,a);return new U(o).apply(n)},Ze=f.gql`
1449
+ `,h={"spiff-fill-shape":{browserValue:s.color||"#000000"}},g=N();return new W({colors:h,id:g,svg:u,type:D.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(o)}catch(c){return console.error(c),[]}},gl=async(i,t,e)=>{const a=[],r=t.type===E.ProductOverlay?e||t.data.asset?.fileLink||"":t.data.asset?.fileLink||"",o=r.endsWith(".jpeg")||r.endsWith(".jpg")||r.endsWith(".png")?D.Image:(r.endsWith(".svg"),D.Illustration),l=t.data.regions;if(o==="image")try{l.forEach(c=>{const d=i.find(A=>A.panelId===c.panelId);if(!d)throw new J(c);const u={id:N(),src:r,type:o,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===E.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new W(u,d))})}catch(c){console.error(c)}else{const c=await tt(r,!0),d=u=>{const A=/<svg.*?<\/svg>/s,h=u.match(A)||[],g=h?.length>0?h[0]:"",C=ot().parseFromString(g,"image/svg+xml").firstElementChild;if(!C)throw new It("Failed to read SVG.");return ze(C),Et().serializeToString(C)};l.forEach(u=>{const A=i.find(g=>g.panelId===u.panelId);if(!A)throw new J(u);const h={id:N(),src:r,asset_key:r,svg:d(c),colors:{},type:o,y:u.top,x:u.left,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,scaleX:1,scaleY:1,rotation:u.rotation,productOverlay:t.type===E.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new W(h,A))})}return a},ml=async(i,t,e,a)=>{const n=[],r=e.data,s=30,o=m=>m.vertical?"center":m.textAlign||"center",l=async()=>{const m=await I.getOptionForStep(a);if(!m)return;const C=m.variants?.find(w=>w.id===r.fontVariantId)||await I.getDefaultVariant(m,a.overrideDefaultVariantId);if(!C||!C.asset)return;t[a.stepName]={selectedVariants:[C]};const S=C.asset.fileLink;if(S)return S},d=await(async()=>{const m=await l();if(!m)return;const C=await Pt(m);return{assetUrl:m,name:C.names.fullName.en}})(),u=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",r.text):r.text)||"",A=Fe(u,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async m=>{const C=m.colorOption;return C?(await I.getDefaultVariant(C))?.color:void 0},g=r.color||await h(a.data),p=a.data.regions;for(const m of p){const C=i.find(w=>w.panelId===m.panelId);if(!C)continue;const S={stepName:e.name,id:N(),align:o(a.data),curved:a.data.curved,fill:r.color||g||"#000000",fontData:d,fontSize:a.data.size||s,height:m.height,layer:m.layer,layerIndex:m.layerIndex,paths:a.data.paths,rotation:m.rotation,text:A,type:D.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:m.width,x:m.left,y:m.top};if(d){const[w,F]=Xt(a.data.size||s,d,m,[Fe(A,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});n.push(new W({...S,fontSize:w,text:S.curved?S.text:(F||[]).join(`
1450
+ `)},C))}else n.push(new W(S,C))}return n},Ii=async(i,t,e,a)=>{const n=[],r={};for(const s of i){const o=t.steps.find(l=>l.stepName===s.name);if(o)switch(o.type){case E.DigitalContent:n.push(...await ll(e,s,o));break;case E.Frame:case E.Photo:n.push(...await cl(e,r,s,o));break;case E.Illustration:n.push(...await dl(e,r,s,o));break;case E.Module:n.push(...await ul(e,s,o));break;case E.Picture:n.push(...await Al(e,r,s,o));break;case E.Shape:n.push(...await hl(e,r,s,o));break;case E.Text:n.push(...await ml(e,r,s,o));break}}for(const s of t.steps)s.type!==E.SilentIllustration&&s.type!==E.ProductOverlay||await pt(s,r)&&n.push(...await gl(e,s,a));return n};class pl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new wl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const fl=()=>new Promise((i,t)=>{try{const a=yt().getContext("webgl2");i(!!a)}catch{i(!1)}}),Cl=fl();class wl{constructor(t,e,a,n,r){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Ye(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=r}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Ct(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new yl(this.getID(),a,await Cl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class yl extends He{constructor(t,e,a,n,r,s){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=r,this.getWorkflowManager=s}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,r=Math.min(a,n);return r>1?t:{width:t.width*r,height:t.height*r}}async execute(){const t=this.layouts.find(g=>g.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,r=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=r.width,o=r.height;let l,c;if(this.nonPOTSupport){const g=s/o;a/n<g?(l=s,c=n*(s/a)):(l=a*(o/n),c=o);const m=this.resizeFit({width:l,height:c});l=m.width,c=m.height}else l=r.width,c=r.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),u=Je(t.layoutState.layout,e,{renderingConfiguration:{purpose:Nt.ThreeD,templatingContext:d}}),A=Vn(u),h=await Ma.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:yt,createImage:le,DOMParser:Ra(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const Sl=(i,t)=>{const e=[];return i.forEach(a=>{const n=t.steps.find(r=>r.stepName===a.stepName);n?.type===E.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},vl=async(i,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new U(e.map(l=>new qa(l))).apply(n);const s=await Ii(i,t,e,a);return new U(s).apply(n)},Ke=f.gql`
1451
1451
  fragment GlobalPropertyStateAspectFields on GlobalPropertyStateAspect {
1452
1452
  name
1453
1453
  value
@@ -1470,8 +1470,8 @@
1470
1470
  }
1471
1471
  }
1472
1472
  }
1473
- `,Rl=f.gql`
1474
- ${Ze}
1473
+ `,El=f.gql`
1474
+ ${Ke}
1475
1475
  mutation CreateGlobalPropertyState($bundleId: String!) {
1476
1476
  globalPropertyStateCreate(bundleId: $bundleId) {
1477
1477
  id
@@ -1480,8 +1480,8 @@
1480
1480
  }
1481
1481
  }
1482
1482
  }
1483
- `,$l=f.gql`
1484
- ${Ze}
1483
+ `,bl=f.gql`
1484
+ ${Ke}
1485
1485
  mutation UpdateGlobalPropertyState($id: String!, $aspects: [GlobalPropertyStateAspectInput]!) {
1486
1486
  globalPropertyStateUpdate(id: $id, aspects: $aspects) {
1487
1487
  id
@@ -1490,8 +1490,8 @@
1490
1490
  }
1491
1491
  }
1492
1492
  }
1493
- `,Ul=f.gql`
1494
- ${Ze}
1493
+ `,Il=f.gql`
1494
+ ${Ke}
1495
1495
  query GetGlobalPropertyState($bundleId: String!) {
1496
1496
  globalPropertyState(bundleId: $bundleId) {
1497
1497
  id
@@ -1500,8 +1500,8 @@
1500
1500
  }
1501
1501
  }
1502
1502
  }
1503
- `,Vl=async i=>(await y.getShadowGraphqlClient().query({query:Ul,fetchPolicy:"cache-first",errorPolicy:"all",variables:{bundleId:i}})).data.globalPropertyState,Ll=i=>f.gql`
1504
- ${Ye}
1503
+ `,Bl=async i=>(await y.getShadowGraphqlClient().query({query:Il,fetchPolicy:"cache-first",errorPolicy:"all",variables:{bundleId:i}})).data.globalPropertyState,Pl=i=>f.gql`
1504
+ ${je}
1505
1505
  fragment ProductFields on Product {
1506
1506
  id
1507
1507
  basePrice
@@ -1545,8 +1545,8 @@
1545
1545
  name
1546
1546
  }
1547
1547
  }
1548
- `,an=i=>f.gql`
1549
- ${Ll(i)}
1548
+ `,Ka=i=>f.gql`
1549
+ ${Pl(i)}
1550
1550
  fragment ProductCollectionProductFields on ProductCollectionProduct {
1551
1551
  id
1552
1552
  productId
@@ -1555,8 +1555,8 @@
1555
1555
  ...ProductFields
1556
1556
  }
1557
1557
  }
1558
- `,ta=(i,t=!1)=>f.gql`
1559
- ${i?an(t):""}
1558
+ `,Xe=(i,t=!1)=>f.gql`
1559
+ ${i?Ka(t):""}
1560
1560
  fragment ProductCollectionFields on ProductCollection {
1561
1561
  id
1562
1562
  name
@@ -1605,7 +1605,7 @@
1605
1605
  }
1606
1606
  ${i?"productCollectionProducts { ...ProductCollectionProductFields }":""}
1607
1607
  }
1608
- `,$i=f.gql`
1608
+ `,Bi=f.gql`
1609
1609
  fragment BundleBaseFields on Bundle {
1610
1610
  id
1611
1611
  dispatchDate
@@ -1627,10 +1627,10 @@
1627
1627
  workflowViewerLink
1628
1628
  workflowViewerAmendLink
1629
1629
  }
1630
- `,zl=i=>f.gql`
1631
- ${Ze}
1632
- ${ta(i)}
1633
- ${$i}
1630
+ `,xl=i=>f.gql`
1631
+ ${Ke}
1632
+ ${Xe(i)}
1633
+ ${Bi}
1634
1634
  query GetBundle($id: String!) {
1635
1635
  globalPropertyState(bundleId: $id) {
1636
1636
  id
@@ -1662,7 +1662,7 @@
1662
1662
  }
1663
1663
  }
1664
1664
  }
1665
- `,Pn=f.gql`
1665
+ `,Sn=f.gql`
1666
1666
  query GetBundleStakeholders($id: String!) {
1667
1667
  bundles(ids: [$id]) {
1668
1668
  id
@@ -1707,7 +1707,7 @@
1707
1707
  }
1708
1708
  }
1709
1709
  }
1710
- `,ql=f.gql`
1710
+ `,Fl=f.gql`
1711
1711
  query GetBundlesForCustomer($id: String!) {
1712
1712
  customers(ids: [$id]) {
1713
1713
  bundleStakeholders {
@@ -1736,8 +1736,8 @@
1736
1736
  }
1737
1737
  }
1738
1738
  }
1739
- `,Gl=f.gql`
1740
- ${an(!1)}
1739
+ `,Dl=f.gql`
1740
+ ${Ka(!1)}
1741
1741
  query GetProductCollectionProducts($id: String!, $productIds: [String!]) {
1742
1742
  productCollections(ids: [$id], productIds: $productIds) {
1743
1743
  id
@@ -1746,7 +1746,7 @@
1746
1746
  }
1747
1747
  }
1748
1748
  }
1749
- `,jl=f.gql`
1749
+ `,kl=f.gql`
1750
1750
  query GetProductCollectionForFilteredProducts(
1751
1751
  $id: String!
1752
1752
  $filters: ProductCollectionProductFilterInput
@@ -1769,8 +1769,8 @@
1769
1769
  }
1770
1770
  }
1771
1771
  }
1772
- `,Hl=f.gql`
1773
- ${an(!0)}
1772
+ `,Ml=f.gql`
1773
+ ${Ka(!0)}
1774
1774
  query GetProductCollectionForProductsFeed(
1775
1775
  $id: String!
1776
1776
  $limit: Int
@@ -1801,8 +1801,8 @@
1801
1801
  }
1802
1802
  }
1803
1803
  }
1804
- `,Wl=i=>f.gql`
1805
- ${ta(i)}
1804
+ `,Tl=i=>f.gql`
1805
+ ${Xe(i)}
1806
1806
  mutation CreateBundle(
1807
1807
  $collectionId: String
1808
1808
  $initialMetadata: [MetadataInput!]
@@ -1830,7 +1830,7 @@
1830
1830
  }
1831
1831
  }
1832
1832
  }
1833
- `,Yl=()=>f.gql`
1833
+ `,Nl=()=>f.gql`
1834
1834
  mutation DuplicateBundle(
1835
1835
  $id: String!
1836
1836
  $template: Boolean
@@ -1852,7 +1852,7 @@
1852
1852
  }
1853
1853
  }
1854
1854
  }
1855
- `,Ee=f.gql`
1855
+ `,Se=f.gql`
1856
1856
  mutation UpdateBundle(
1857
1857
  $id: String!
1858
1858
  $name: String
@@ -1872,19 +1872,19 @@
1872
1872
  id
1873
1873
  }
1874
1874
  }
1875
- `,Jl=f.gql`
1875
+ `,Ql=f.gql`
1876
1876
  mutation BundleAddTransaction($id: String!, $transactionId: String!) {
1877
1877
  bundleAddTransaction(id: $id, transactionId: $transactionId) {
1878
1878
  id
1879
1879
  }
1880
1880
  }
1881
- `,Kl=f.gql`
1881
+ `,Ol=f.gql`
1882
1882
  mutation BundleAddTransactions($id: String!, $transactionIds: [String!]!, $transactionOwnerIds: [String!]) {
1883
1883
  bundleAddTransactions(id: $id, transactionIds: $transactionIds, transactionOwnerIds: $transactionOwnerIds) {
1884
1884
  id
1885
1885
  }
1886
1886
  }
1887
- `,_l=f.gql`
1887
+ `,Rl=f.gql`
1888
1888
  mutation BundleRemoveTransaction(
1889
1889
  $id: String!
1890
1890
  $transactionId: String!
@@ -1899,7 +1899,7 @@
1899
1899
  id
1900
1900
  }
1901
1901
  }
1902
- `,Xl=f.gql`
1902
+ `,$l=f.gql`
1903
1903
  mutation BundleRemoveTransactions(
1904
1904
  $id: String!
1905
1905
  $transactionIds: [String!]!
@@ -1914,7 +1914,7 @@
1914
1914
  id
1915
1915
  }
1916
1916
  }
1917
- `,Zl=f.gql`
1917
+ `,Ul=f.gql`
1918
1918
  mutation BundleAddStakeholder($id: String!, $details: CustomerDetailsInput!, $type: String!) {
1919
1919
  bundleAddStakeholder(id: $id, details: $details, type: $type) {
1920
1920
  id
@@ -1934,13 +1934,13 @@
1934
1934
  }
1935
1935
  }
1936
1936
  }
1937
- `,tc=f.gql`
1937
+ `,Vl=f.gql`
1938
1938
  mutation BundleAddStakeholder($id: String!, $emailAddress: String!) {
1939
1939
  bundleRemoveStakeholder(id: $id, emailAddress: $emailAddress) {
1940
1940
  id
1941
1941
  }
1942
1942
  }
1943
- `,ec=f.gql`
1943
+ `,Ll=f.gql`
1944
1944
  mutation BundleUpdateStakeholders($id: String!, $input: [BundleStakeholderInput!]!) {
1945
1945
  bundleUpdateStakeholders(id: $id, input: $input) {
1946
1946
  id
@@ -1960,14 +1960,14 @@
1960
1960
  }
1961
1961
  }
1962
1962
  }
1963
- `,ac=f.gql`
1963
+ `,zl=f.gql`
1964
1964
  mutation BundleUpdateTransactionOrder($id: String!, $transactionIds: [String!]!) {
1965
1965
  bundleUpdateTransactionOrder(id: $id, transactionIds: $transactionIds) {
1966
1966
  id
1967
1967
  }
1968
1968
  }
1969
- `,nc=i=>f.gql`
1970
- ${ta(i)}
1969
+ `,ql=i=>f.gql`
1970
+ ${Xe(i)}
1971
1971
  mutation BundleAssignProductCollection($id: String!, $productCollectionId: String!) {
1972
1972
  bundleAssignProductCollection(id: $id, collectionId: $productCollectionId) {
1973
1973
  id
@@ -1976,14 +1976,14 @@
1976
1976
  }
1977
1977
  }
1978
1978
  }
1979
- `,ic=f.gql`
1979
+ `,Gl=f.gql`
1980
1980
  mutation AssignGlobalPropertyConfiguration($bundleId: String!, $globalPropertyConfigurationId: String!) {
1981
1981
  bundleUpdate(id: $bundleId, globalPropertyConfigurationId: $globalPropertyConfigurationId) {
1982
1982
  id
1983
1983
  }
1984
1984
  }
1985
- `,rc=i=>f.gql`
1986
- ${$i}
1985
+ `,jl=i=>f.gql`
1986
+ ${Bi}
1987
1987
  query CustomerBundlesFeed($id: String!, $limit: Int!, $offset: Int!, $template: Boolean, $templateStatus: BundleTemplateStatus, $ordered: Boolean) {
1988
1988
  customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: $template, templateStatus: $templateStatus, ordered: $ordered) {
1989
1989
  items {
@@ -2008,27 +2008,27 @@
2008
2008
  total
2009
2009
  }
2010
2010
  }
2011
- `,oc=f.gql`
2011
+ `,Wl=f.gql`
2012
2012
  mutation FinalizeUpdateBundle($bundleId: String!) {
2013
2013
  bundleFinalizeUpdate(bundleId: $bundleId)
2014
2014
  }
2015
- `,sc=f.gql`
2015
+ `,Hl=f.gql`
2016
2016
  mutation ApproveBundle($id: String!, $note: String, $stakeholderId: String) {
2017
2017
  bundleApprove(id: $id, note: $note, stakeholderId: $stakeholderId)
2018
2018
  }
2019
- `,lc=f.gql`
2019
+ `,Yl=f.gql`
2020
2020
  mutation RejectBundle($id: String!, $note: String, $stakeholderId: String) {
2021
2021
  bundleReject(id: $id, note: $note, stakeholderId: $stakeholderId)
2022
2022
  }
2023
- `,cc=f.gql`
2023
+ `,Jl=f.gql`
2024
2024
  mutation ApproveTransaction($id: String!, $note: String) {
2025
2025
  transactionApprove(id: $id, note: $note)
2026
2026
  }
2027
- `,dc=f.gql`
2027
+ `,Kl=f.gql`
2028
2028
  mutation RejectTransaction($id: String!, $note: String) {
2029
2029
  transactionReject(id: $id, note: $note)
2030
2030
  }
2031
- `,uc=f.gql`
2031
+ `,Xl=f.gql`
2032
2032
  mutation CreateRecipient(
2033
2033
  $firstName: String
2034
2034
  $lastName: String
@@ -2070,7 +2070,7 @@
2070
2070
  id
2071
2071
  }
2072
2072
  }
2073
- `,Ac=f.gql`
2073
+ `,Zl=f.gql`
2074
2074
  mutation UpdateRecipient(
2075
2075
  $id: String!
2076
2076
  $firstName: String
@@ -2116,17 +2116,17 @@
2116
2116
  id
2117
2117
  }
2118
2118
  }
2119
- `,hc=f.gql`
2119
+ `,_l=f.gql`
2120
2120
  mutation AtttachRecipient($id: String!, $recipientId: String!) {
2121
2121
  transactionAttachRecipient(id: $id, recipientId: $recipientId) {
2122
2122
  id
2123
2123
  }
2124
2124
  }
2125
- `,gc=f.gql`
2125
+ `,tc=f.gql`
2126
2126
  mutation DeleteBundle($id: String!) {
2127
2127
  bundleDelete(id: $id)
2128
2128
  }
2129
- `,mc=f.gql`
2129
+ `,ec=f.gql`
2130
2130
  query FindBundleForTransactions($ids: [String!]!) {
2131
2131
  transactions(ids: $ids) {
2132
2132
  id
@@ -2135,7 +2135,7 @@
2135
2135
  }
2136
2136
  }
2137
2137
  }
2138
- `,pc=(i,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,a)=>(e[a]=t[a],e),{}):t,fc=i=>{for(const t of Object.values(i.layouts).map(e=>e.elements).flat())t.type==="illustration"&&(delete t.cachedObjectURL,t.src&&delete t.svg),t.type==="frame"&&delete t.pattern?.svg;return Ui(i,"__typename"),i},Ui=(i,t)=>{if(!(typeof i!="object"||i===null))for(const e in i)e===t?delete i[e]:Ui(i[e],t)};var pe=(i=>(i.Error="Error",i.Warning="Warning",i.Info="Info",i))(pe||{});const Cc=1e3;class xn extends Ke{constructor(t){super(),this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Cc)})}}const wc=i=>i.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),yc=(i,t)=>{const e=i.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):wc(t.panels)},te=class te{constructor(t,e,a,n,r,o=!1,s,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new _e(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{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):A?this.layouts=yc(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new Dl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),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 A=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(A)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=n,this.reloadedState=r,this.readOnly=o,this.singleVariantsRenderable=c,this.commandContext=new Ii,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=s,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,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const n=a.uniqueIdentifier??a.title??"";a.type===Zt.FirstName?e[n]=t?.firstName:a.type===Zt.LastName?e[n]=t?.lastName:a.type===Zt.Custom&&(a.customFieldIndex===1?e[n]=t?.customField1:a.customFieldIndex===2?e[n]=t?.customField2:a.customFieldIndex===3?e[n]=t?.customField3:a.customFieldIndex===4?e[n]=t?.customField4:a.customFieldIndex===5&&(e[n]=t?.customField5),a.option&&(e[n]=a.option.variants?.find(r=>r.id===e[n])?.name))}),e}async updateRecipient(t,e,a,n,r,o,s,l,c,d,u,A,h,g,p,m,C,S){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:n??w.recipient.suburb,state:r??w.recipient.state,email:o??w.recipient.email,postalCode:s??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:C||w.recipient.conversionConfigurationId},this.experience.callEvent(Re.RecipientChanged),await this.graphQlClient().mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:n||w.recipient.suburb,state:r||w.recipient.state,email:o||w.recipient.email,postalCode:s||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:C||w.recipient.conversionConfigurationId,prevalidated:S}});else{const F=await this.graphQlClient().mutate({mutation:uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:C}});w.recipient={id:F?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:n,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:C},this.experience.callEvent(Re.RecipientChanged),await this.graphQlClient().mutate({mutation:hc,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 t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=te.configurationPromiseMap.get(t.conversionConfigurationId);if(e)this.recipientConversionConfiguration=await e;else{const n=(async()=>(await this.graphQlClient().query({query:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}})).data.conversionConfiguration)();te.configurationPromiseMap.set(t.conversionConfigurationId,n),this.recipientConversionConfiguration=await n}}}async initializeDefaultWorkflowState(t){const e=()=>{const d=t.finalizeStepConfig;if(!d)return;const u=d.lookAtAnimation,A=d.modelAnimation;u&&this.previewService?.executeCameraAnimation(u),A&&this.modelContainer?.executeAnimation(A)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(d=>{this.storage[d.stepName]=d.storage||{}});const a=await this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((d,u)=>(u.selectedVariants?.length&&(d[u.stepName]={selectedVariants:u.selectedVariants.map(A=>({id:A.id}))}),d),{})),n=I.getOptions(Array.from(a)),r=this.fetchConversionConfiguration();await Promise.all([n,r]),this.allScenes=yn(t);const s=(await dt(this.allScenes,this.stepSelections)).map(d=>d.silentSteps).flat(),{stepElements:l,commands:c}=await this.stepElementsForIntroducedSilentSteps(s,!!this.reloadedState);this.commandContext.apply(new U(c),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}async getInitialOptionIds(t){const e=new Set,a=this.experience.getWorkflow();if(!a)return e;const n=yn(a),r={...t};let o=-1;for(;;){const c=(await dt(n,r)).flatMap(d=>d.renderableSteps);if(c.length===o)break;o=c.length;for(const d of c){if(r[d.stepName])continue;const u=d.option?.defaultVariant?.id;u&&(r[d.stepName]={selectedVariants:[{id:u}]})}}return(await dt(n,r)).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&e.add(l.option.id)}),e}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.experience.getTransaction().recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=N();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}async getMandatoryUnfulfilledSteps(){return(await dt(this.allScenes,this.stepSelections)).flatMap(r=>r.renderableSteps).filter(r=>r.mandatory).filter(r=>!this.mandatorySteps[r.stepName]).map(r=>r.stepName)}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const r=this.validationErrors.steps.get(t);a&&a!==r.get(e)?(n=!0,r.set(e,a)):a||(n=!0,r.delete(e),r.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const n=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(n),(await dt(this.allScenes,this.stepSelections)).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===E.Model||s.type===E.Material).forEach(s=>{if(!s.option?.id){console.error(`Failed to read option id from step: ${s.stepName}`);return}const l=this.stepSelections[s.stepName]?.selectedVariants||[];if(l.length===0)return;const c=l[0];if(s.type===E.Model){if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${s.stepName}`);return}const u=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,s.option.id,d)})}}),await n.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(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!ae(a,this.storage)){this.storage=a;const n=new bn(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(r=>({id:r.id,priceModifier:r.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new xn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new xn(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new O("Attempted to serialize state before it was initialized.");const e=yt(t.transaction),a=fc(e);return JSON.stringify(a,pc,void 0)}async getStateHash(){const t=this.getCommandContext().getState(),a=Object.values(t?.transaction.layouts||{}).map(o=>o.modificationID??"").sort().join(""),r=new TextEncoder().encode(a);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const o=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(a,"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(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((r,o)=>{const s=[...a[o]||[]];return n.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),r[o]=s,r},{});this.stepElements=e(this.stepElements,t)}async getInvalidCanvasRegions(){let t=[];for(const e of this.experience.getWorkflow()?.steps||[])if(!await Ct(e,this.stepSelections)&&this.stepElements[e.stepName])for(const a of this.stepElements[e.stepName])t.push(a);return t}async getInvalidModelVariants(){let t=[];for(const e of this.experience.getWorkflow()?.steps||[])e.type===E.Model&&!await Ct(e,this.stepSelections)&&t.push(e.stepName);return t}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new In(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new In(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},r=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of r)this.markStepsAsInitialised([c.stepName]),e||s.push(n(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:Xo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:cc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){const r=this.experience.getWorkflow();if(!r)throw new Error("Attempted to set selections when no workflow is set!");const o=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((v,B)=>v+B.selectedVariants.map(M=>M.priceModifier||0).reduce((M,R)=>M+R,0),0);for(const v of r.steps)await Ct(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1,delete this.stepMetadata[v.stepName],delete this.stepSelections[v.stepName],delete this.storage[v.stepName]);const s=this.allScenes,l=await dt(s,o),c=await dt(s,this.stepSelections),d=l.map(v=>v.silentSteps).flat(),A=c.map(v=>v.silentSteps).flat().filter(v=>!d.some(B=>B.stepName===v.stepName));for(const v of d)await Ct(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1);const h=await this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=r.steps.find(v=>v.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(B=>B.id));const C=h.map(v=>new Dt(v.id)),S=new bn(this.constructSerializableWorkflow()),w=[...p,...C,S];w.length>0&&this.commandContext.apply(new U(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const F=await this.getInvalidModelVariants(),b=this.modelContainer;if(b){const v=F.map(B=>b.applyModelVariant(B,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(v)}await this.onSelectionChange(),m?.type!==E.Frame&&m?.type!==E.Text&&this.setMandatoryFulfilled(t,!0),n&&await n()}async ensureStepsAreLoaded(){const e=(await dt(this.allScenes,this.stepSelections)).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push(Ka.init(l,this,this.reloadedState));break;case E.Frame:a.push(pt.init(l,this,this.reloadedState));break;case E.Illustration:a.push(_t.init(l,this,this.reloadedState));break;case E.Material:a.push(_a.init(l,this,this.reloadedState));break;case E.Model:a.push(Xa.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await Oi(l.data.module)},a.push(Za.init(l,this,this.reloadedState));break;case E.Picture:a.push(tn.init(l,this,this.reloadedState));break;case E.Question:a.push(en.init(l,this,this.reloadedState));break;case E.Shape:a.push(Tt.init(l,this,this.reloadedState));break;case E.Text:a.push(W.init(l,this,this.reloadedState));break}const r=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=r.flatMap(l=>l?.command?[l.command]:[]),s=r.flatMap(l=>l?.followup?[l.followup]:[]);o&&o.length>0&&this.commandContext.apply(new U(o),!0);for(const l of s)await l();s.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return hs(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}};te.configurationPromiseMap=new Map;let Ta=te;class nt{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.fileLink}getAssetResource(){return this.variantData.asset}getThumbnail(t=256,e){const a=this.variantData.thumbnail;if(!(!a||!a.fileLink))return We(a,t,"webp",e)}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}getCategory(){return this.variantData.category}}const ee=class ee{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){ee.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!ee.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new nt(a)}async getAvailableVariants(){return(await this.getAllVariants()).filter(e=>e.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(e=>new nt(e))||[];const t=await I.getOption(this.step.option?.id);if(!t)throw new Error("Option not found, cannot fetch variants.");return(t.variants||[]).map(e=>new nt(e))||[]}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(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,r=this.step.data.lookAtAnimation;e?r&&e.executeCameraAnimation(r):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};ee.updateState=new Map;let Z=ee;class Vi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return _t.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=V(t[0].id,this.manager.getAllLayoutData()).colors,r=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=r?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=r.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const n=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?n.set(c,{browserValue:e,pmsValue:a}):n.set(c,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),_t.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,n)}async getColorOption(){return await I.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?_t.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 Li extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return _a.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class zi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Xa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class qi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return tn.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Gi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await en.selectVariant(this.step,t.getId(),this.manager)}async getDisplayType(){return this.step.data.displayType?this.step.data.displayType:(await I.getOptionForStep(this.step))?.displayType}}class ji extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Tt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Tt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Tt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Tt.setCustomColor(t,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 t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Hi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){await W.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?W.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return W.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return W.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);W.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){const e={input:t,helperData:{}},a=W.findLayoutElements(this.manager,this.step),n=W.filterUnsupportedCharacters(t,a[0]?.fontData),r=Nt(n,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&r>this.step.data.maxLength;o||(e.input=n);const s=a.length<=0,l=s?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=W.getProcessedInput(n,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=W.updateInputText(n,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!o&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t: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 e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=W.findLayoutElements(this.manager,this.step);return W.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?W.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeStrokeColor(this.step,t,e,this.manager)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Wi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Yi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Ka.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Ji extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Za.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class be{static get(t,e){switch(e.type){case E.DigitalContent:return new Yi(t,e,t.getStepTags(e.stepName));case E.Information:return new Wi(t,e,t.getStepTags(e.stepName));case E.Question:return new Gi(t,e,t.getStepTags(e.stepName));case E.Text:return new Hi(t,e,t.getStepTags(e.stepName));case E.Illustration:return new Vi(t,e,t.getStepTags(e.stepName));case E.Picture:return new qi(t,e,t.getStepTags(e.stepName));case E.Shape:return new ji(t,e,t.getStepTags(e.stepName));case E.Material:return new Li(t,e,t.getStepTags(e.stepName));case E.Model:return new zi(t,e,t.getStepTags(e.stepName));case E.Frame:return new mr(t,e,t.getStepTags(e.stepName));case E.Module:return new Ji(t,e,t.getStepTags(e.stepName));default:throw new O(`Step type ${e.type} not yet supported in Core SDK`)}}}const Sc=f.gql`
2138
+ `,ac=(i,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,a)=>(e[a]=t[a],e),{}):t,nc=i=>{for(const t of Object.values(i.layouts).map(e=>e.elements).flat())t.type==="illustration"&&(delete t.cachedObjectURL,t.src&&delete t.svg),t.type==="frame"&&delete t.pattern?.svg;return Pi(i,"__typename"),i},Pi=(i,t)=>{if(!(typeof i!="object"||i===null))for(const e in i)e===t?delete i[e]:Pi(i[e],t)};var ge=(i=>(i.Error="Error",i.Warning="Warning",i.Info="Info",i))(ge||{});const ic=1e3;class vn extends He{constructor(t){super(),this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},ic)})}}const rc=i=>i.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),sc=(i,t)=>{const e=i.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):rc(t.panels)},Zt=class Zt{constructor(t,e,a,n,r,s=!1,o,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new Ye(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{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):A?this.layouts=sc(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new pl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),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 A=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(A)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=n,this.reloadedState=r,this.readOnly=s,this.singleVariantsRenderable=c,this.commandContext=new hi,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,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const n=a.uniqueIdentifier??a.title??"";a.type===Jt.FirstName?e[n]=t?.firstName:a.type===Jt.LastName?e[n]=t?.lastName:a.type===Jt.Custom&&(a.customFieldIndex===1?e[n]=t?.customField1:a.customFieldIndex===2?e[n]=t?.customField2:a.customFieldIndex===3?e[n]=t?.customField3:a.customFieldIndex===4?e[n]=t?.customField4:a.customFieldIndex===5&&(e[n]=t?.customField5),a.option&&(e[n]=a.option.variants?.find(r=>r.id===e[n])?.name))}),e}async updateRecipient(t,e,a,n,r,s,o,l,c,d,u,A,h,g,p,m,C,S){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:n??w.recipient.suburb,state:r??w.recipient.state,email:s??w.recipient.email,postalCode:o??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:C||w.recipient.conversionConfigurationId},this.experience.callEvent(Ne.RecipientChanged),await this.graphQlClient().mutate({mutation:Zl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:n||w.recipient.suburb,state:r||w.recipient.state,email:s||w.recipient.email,postalCode:o||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:C||w.recipient.conversionConfigurationId,prevalidated:S}});else{const F=await this.graphQlClient().mutate({mutation:Xl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:r,email:s,postalCode:o,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:C}});w.recipient={id:F?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:n,state:r,email:s,postalCode:o,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:C},this.experience.callEvent(Ne.RecipientChanged),await this.graphQlClient().mutate({mutation:_l,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 t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=Zt.configurationPromiseMap.get(t.conversionConfigurationId);if(e)this.recipientConversionConfiguration=await e;else{const n=(async()=>(await this.graphQlClient().query({query:Ms,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}})).data.conversionConfiguration)();Zt.configurationPromiseMap.set(t.conversionConfigurationId,n),this.recipientConversionConfiguration=await n}}}async initializeDefaultWorkflowState(t){const e=()=>{const d=t.finalizeStepConfig;if(!d)return;const u=d.lookAtAnimation,A=d.modelAnimation;u&&this.previewService?.executeCameraAnimation(u),A&&this.modelContainer?.executeAnimation(A)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(d=>{this.storage[d.stepName]=d.storage||{}});const a=await this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((d,u)=>(u.selectedVariants?.length&&(d[u.stepName]={selectedVariants:u.selectedVariants.map(A=>({id:A.id}))}),d),{})),n=I.getOptions(Array.from(a)),r=this.fetchConversionConfiguration();await Promise.all([n,r]),this.allScenes=gn(t);const o=(await lt(this.allScenes,this.stepSelections)).map(d=>d.silentSteps).flat(),{stepElements:l,commands:c}=await this.stepElementsForIntroducedSilentSteps(o,!!this.reloadedState);this.commandContext.apply(new U(c),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}async getInitialOptionIds(t){const e=new Set,a=this.experience.getWorkflow();if(!a)return e;const n=gn(a),r={...t};let s=-1;for(;;){const c=(await lt(n,r)).flatMap(d=>d.renderableSteps);if(c.length===s)break;s=c.length;for(const d of c){if(r[d.stepName])continue;const u=d.option?.defaultVariant?.id;u&&(r[d.stepName]={selectedVariants:[{id:u}]})}}return(await lt(n,r)).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&e.add(l.option.id)}),e}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.experience.getTransaction().recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=N();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}async getMandatoryUnfulfilledSteps(){return(await lt(this.allScenes,this.stepSelections)).flatMap(r=>r.renderableSteps).filter(r=>r.mandatory).filter(r=>!this.mandatorySteps[r.stepName]).map(r=>r.stepName)}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const r=this.validationErrors.steps.get(t);a&&a!==r.get(e)?(n=!0,r.set(e,a)):a||(n=!0,r.delete(e),r.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const n=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(n),(await lt(this.allScenes,this.stepSelections)).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===E.Model||o.type===E.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 c=l[0];if(o.type===E.Model){if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${o.stepName}`);return}const u=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,o.option.id,d)})}}),await n.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(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!te(a,this.storage)){this.storage=a;const n=new Cn(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(r=>({id:r.id,priceModifier:r.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new vn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new vn(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new O("Attempted to serialize state before it was initialized.");const e=Ct(t.transaction),a=nc(e);return JSON.stringify(a,ac,void 0)}async getStateHash(){const t=this.getCommandContext().getState(),a=Object.values(t?.transaction.layouts||{}).map(s=>s.modificationID??"").sort().join(""),r=new TextEncoder().encode(a);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const s=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(a,"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(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((r,s)=>{const o=[...a[s]||[]];return n.forEach(l=>{const c=o.findIndex(d=>d.id===l.id);c>-1&&o.splice(c,1)}),r[s]=o,r},{});this.stepElements=e(this.stepElements,t)}async getInvalidCanvasRegions(){let t=[];for(const e of this.experience.getWorkflow()?.steps||[])if(!await pt(e,this.stepSelections)&&this.stepElements[e.stepName])for(const a of this.stepElements[e.stepName])t.push(a);return t}async getInvalidModelVariants(){let t=[];for(const e of this.experience.getWorkflow()?.steps||[])e.type===E.Model&&!await pt(e,this.stepSelections)&&t.push(e.stepName);return t}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new wn(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new wn(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},r=t.filter(c=>!this.stepInitialised[c.stepName]),s={stepElements:{},commands:[]},o=[];for(const c of r)this.markStepsAsInitialised([c.stepName]),e||o.push(n(c,this.layouts,a));const l=await Promise.all(o);for(const c of l)s.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),s.commands=[...s.commands,...c.results.map(d=>d.command)];return s}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:$s,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Jl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Kl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){const r=this.experience.getWorkflow();if(!r)throw new Error("Attempted to set selections when no workflow is set!");const s=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((v,B)=>v+B.selectedVariants.map(M=>M.priceModifier||0).reduce((M,R)=>M+R,0),0);for(const v of r.steps)await pt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1,delete this.stepMetadata[v.stepName],delete this.stepSelections[v.stepName],delete this.storage[v.stepName]);const o=this.allScenes,l=await lt(o,s),c=await lt(o,this.stepSelections),d=l.map(v=>v.silentSteps).flat(),A=c.map(v=>v.silentSteps).flat().filter(v=>!d.some(B=>B.stepName===v.stepName));for(const v of d)await pt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1);const h=await this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=r.steps.find(v=>v.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(B=>B.id));const C=h.map(v=>new xt(v.id)),S=new Cn(this.constructSerializableWorkflow()),w=[...p,...C,S];w.length>0&&this.commandContext.apply(new U(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const F=await this.getInvalidModelVariants(),b=this.modelContainer;if(b){const v=F.map(B=>b.applyModelVariant(B,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(v)}await this.onSelectionChange(),m?.type!==E.Frame&&m?.type!==E.Text&&this.setMandatoryFulfilled(t,!0),n&&await n()}async ensureStepsAreLoaded(){const e=(await lt(this.allScenes,this.stepSelections)).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push(Ga.init(l,this,this.reloadedState));break;case E.Frame:a.push(gt.init(l,this,this.reloadedState));break;case E.Illustration:a.push(Kt.init(l,this,this.reloadedState));break;case E.Material:a.push(ja.init(l,this,this.reloadedState));break;case E.Model:a.push(Wa.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await bi(l.data.module)},a.push(Ha.init(l,this,this.reloadedState));break;case E.Picture:a.push(Ya.init(l,this,this.reloadedState));break;case E.Question:a.push(Ja.init(l,this,this.reloadedState));break;case E.Shape:a.push(kt.init(l,this,this.reloadedState));break;case E.Text:a.push(H.init(l,this,this.reloadedState));break}const r=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),s=r.flatMap(l=>l?.command?[l.command]:[]),o=r.flatMap(l=>l?.followup?[l.followup]:[]);s&&s.length>0&&this.commandContext.apply(new U(s),!0);for(const l of o)await l();o.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return _s(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}};Zt.configurationPromiseMap=new Map;let xa=Zt;class at{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.fileLink}getAssetResource(){return this.variantData.asset}getThumbnail(t=256,e){const a=this.variantData.thumbnail;if(!(!a||!a.fileLink))return Ge(a,t,"webp",e)}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}getCategory(){return this.variantData.category}}const _t=class _t{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){_t.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!_t.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new at(a)}async getAvailableVariants(){return(await this.getAllVariants()).filter(e=>e.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(e=>new at(e))||[];const t=await I.getOption(this.step.option?.id);if(!t)throw new Error("Option not found, cannot fetch variants.");return(t.variants||[]).map(e=>new at(e))||[]}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(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,r=this.step.data.lookAtAnimation;e?r&&e.executeCameraAnimation(r):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};_t.updateState=new Map;let Z=_t;class xi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Kt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=V(t[0].id,this.manager.getAllLayoutData()).colors,r=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,s=r?.defaultColorVariants||[];if(s.length!==0){const o={};return s.forEach(l=>{const c=r.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");o[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),o}try{return a}catch(o){console.error(o)}}setColor(t,e,a){const n=new Map,s=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(s?.defaultColorVariants||[]).length!==0?s.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?n.set(c,{browserValue:e,pmsValue:a}):n.set(c,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),Kt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,n)}async getColorOption(){return await I.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?Kt.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 Fi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return ja.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Di extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Wa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class ki extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ya.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Mi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await Ja.selectVariant(this.step,t.getId(),this.manager)}async getDisplayType(){return this.step.data.displayType?this.step.data.displayType:(await I.getOptionForStep(this.step))?.displayType}}class Ti extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return kt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return kt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return kt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),kt.setCustomColor(t,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 t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Ni extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){await H.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:ge.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?H.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await H.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return H.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await H.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return H.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);H.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){const e={input:t,helperData:{}},a=H.findLayoutElements(this.manager,this.step),n=H.filterUnsupportedCharacters(t,a[0]?.fontData),r=Mt(n,this.manager).length,s=!!this.step.data&&!!this.step.data.maxLength&&r>this.step.data.maxLength;s||(e.input=n);const o=a.length<=0,l=o?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=H.getProcessedInput(n,this.step.data,c?.customiseAllText??!1);if(o)s||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=H.updateInputText(n,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!s&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t: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 e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=H.findLayoutElements(this.manager,this.step);return H.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Mt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?H.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await H.changeStrokeColor(this.step,t,e,this.manager)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Qi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Oi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Ga.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Ri extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Mt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Ha.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:ge.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class ve{static get(t,e){switch(e.type){case E.DigitalContent:return new Oi(t,e,t.getStepTags(e.stepName));case E.Information:return new Qi(t,e,t.getStepTags(e.stepName));case E.Question:return new Mi(t,e,t.getStepTags(e.stepName));case E.Text:return new Ni(t,e,t.getStepTags(e.stepName));case E.Illustration:return new xi(t,e,t.getStepTags(e.stepName));case E.Picture:return new ki(t,e,t.getStepTags(e.stepName));case E.Shape:return new Ti(t,e,t.getStepTags(e.stepName));case E.Material:return new Fi(t,e,t.getStepTags(e.stepName));case E.Model:return new Di(t,e,t.getStepTags(e.stepName));case E.Frame:return new nr(t,e,t.getStepTags(e.stepName));case E.Module:return new Ri(t,e,t.getStepTags(e.stepName));default:throw new O(`Step type ${e.type} not yet supported in Core SDK`)}}}const oc=f.gql`
2139
2139
  fragment CreateDesignTransaction on Transaction {
2140
2140
  id
2141
2141
  designName
@@ -2160,8 +2160,8 @@
2160
2160
  externalProductVariantId
2161
2161
  }
2162
2162
  }
2163
- `,vc=f.gql`
2164
- ${Sc}
2163
+ `,lc=f.gql`
2164
+ ${oc}
2165
2165
  mutation CreateDesigns($inputs: [DesignCreateInput]!) {
2166
2166
  designCreateMany(inputs: $inputs) {
2167
2167
  id
@@ -2174,7 +2174,7 @@
2174
2174
  }
2175
2175
  }
2176
2176
  }
2177
- `;function Oe(i){const t=JSON.parse(atob(i.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const Ec=async(i,t)=>{const e={};try{if(t){const n=await t.loggedInBearerToken();e.Authorization=`Bearer ${n}`}else throw new Error}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!Oe(s)&&(e.Authorization=`Bearer ${s}`)}return await t.getBetaEnabled()&&(e["X-Spiff-Beta"]="true"),(await y.getShadowGraphqlClient().mutate({mutation:vc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:i.map(n=>({name:n.name,layouts:n.layouts,workflowId:n.workflowId,transactionId:n.transactionId,previewImage:n.previewImage,useThreeDimPreview:n.useThreeDimPreview,metadata:n.metadata,selectedVariants:n.selectedVariants}))},context:{headers:e}})).data?.designCreateMany},Fn=(i,t,e)=>{const a=r=>{const o={};if(r.type==="Frame"){const s=i[r.stepName],l=r.data;if(!s||!s.image||l.hideImageInCart&&e)return o;o[`${r.stepTitle} image`]=s.image}if(r.type==="Illustration"){const s=i[r.stepName],l=r.data;if(!s||l.hideColorsInCart&&e||!s.colors)return o;if(s.colors.length>0){const c=s.colors.join(", ").toUpperCase();o[`${r.stepTitle} colors`]=c}}if(r.type==="Module"){const s=i[r.stepName],l=r.data;if(!s||s.text===void 0||s.text===null||l.hideTextInCart&&e)return o;o[`${r.stepTitle} text`]=s.text}if(r.type==="Text"){const s=i[r.stepName];if(!s)return o;const l=r.data;(!l.hideTextInCart||!e&&s.text!==void 0&&s.text!==null)&&(o[`${r.stepTitle} text`]=s.text),s.color&&(!l.hideColorInCart||!e)&&(o[`${r.stepTitle} color`]=s.color),s.strokeColor&&(!l.hideStrokeInCart||!e)&&(o[`${r.stepTitle} stroke`]=s.strokeColor)}return o},n={};return t.steps.forEach(r=>{Object.assign(n,a(r))}),n},bc=(i,t,e,a)=>{const n={};let r={};a&&(r=a);const s=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of s){if(Object.keys(i).includes(l)){const c=i[l],d=t.steps.find(u=>u.stepTitle===l);n[`${d?.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(r))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(n[c]={value:r[c],priceModifier:0})}return n},Ic=(i,t,e,a,n,r,o,s)=>{const l=t.basePrice||0,c=i.priceModifierTotal||0,d=bc(a,e,void 0,r),A=(Q.getMap("transactionOwnerIds")||new Map).get(i.id),h={additionalExternalProductId:i.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:i.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:i.designExternalVariants,designProductId:i.externalDesignProductId,designProductVariantId:i.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:i.externalCartProductId,externalCartProductVariantId:i.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:c,processExecutionId:s,quantity:i.quantity,transactionId:i.id,transactionOwnerId:A,weight:t.weight,workflowViewerLink:i.workflowViewerLink||"",workflowViewerReadOnlyLink:i.workflowViewerReadOnlyLink||""};return r&&(h.metadata=r),a&&(h.selectedVariants=a),n&&(h.sku=n),h},Bc=async(i,t,e,a,n,r,o,s,l,c)=>{c&&(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await i.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const d=i.getPreviewService(),u=t?.finalizeStepConfig?.lookAtAnimation,A=d&&t.showModelOnFinishStep&&!!u,h=l&&Fn(l,t,!0),g=l&&Fn(l,t,!1),p=async v=>{const B={};let M=0;if(Object.keys(r).length>0)for(const R of Object.keys(r)){const x=r[R],T=t.steps.find(L=>L.stepName===R);for(let L=0;L<x.selections.length;++L){const k=x.selections[L];if(T){const X=await I.getOptionForStep(T);if(!v||X&&(X.variants||[]).length>1&&!T.data.hideSelectionInCart&&!T.data.hideSelectionsInCart){const Bt=T.stepTitle;B[Bt]?B[Bt].push({id:k.id||"",name:k.name,priceModifier:k.priceModifier}):B[Bt]=[{id:k.id||"",name:k.name,priceModifier:k.priceModifier}]}}M+=k.priceModifier}}return[B,M]},[m]=await p(!0),C=Object.fromEntries(Object.keys(m).map(v=>[v,m[v].map(B=>B.id)])),[S]=await p(!1),w=Object.fromEntries(Object.keys(S).map(v=>[v,S[v].map(B=>B.id)]));let F=await s(A,n.id);if(F){const v=await(await it(F)).blob();F=(await G.uploadAsset({name:`${n.id}-preview-image.png`,blob:v},ne.Image,!0,!1)).fileLink}return{designDetails:(()=>{const v={name:o,layouts:e.map(B=>({index:B.index,panelId:B.panelId})),workflowId:t.id,transactionId:n.id,useThreeDimPreview:!!A,previewImage:F};if(g){const B=[];for(const[M,R]of Object.entries(g))B.push({key:M,value:R});v.metadata=B}if(C){const B=[];for(const[M,R]of Object.entries(w))B.push({key:M,ids:R});v.selectedVariants=B}return v})(),cartSelectionsWithPrices:m,cartMetadata:h}},Ki=async(i,t)=>{await Promise.all(i.map(async s=>{await s.workflowManager.outstandingRequestsPromise()}));const a=await(async()=>{const s=y.getShadowGraphqlClient(),l=await Promise.all(i.map(async A=>({id:A.transaction.id,hash:await A.workflowManager.getStateHash()}))),d=wa(l,100),u=[];for(const A of d){const h=await s.query({query:Jo,variables:{transactions:A},fetchPolicy:"no-cache",errorPolicy:"all"});if(h.errors&&h.errors.length>0)return l.map(g=>g.id);u.push(...h.data?.transactionConfirmWorkflowStates??[])}return u})(),n=await Promise.all(i.map(async s=>await Bc(s.workflowManager,s.workflow,s.layouts,s.getReducerState,s.transaction,s.workflowSelections,s.designName,t??(()=>Promise.resolve(void 0)),s.workflowMetadata,a.includes(s.transaction.id)))),r=i[0].workflowManager.getClient(),o=await Ec(n.map(s=>s.designDetails),r);if(!o)throw new Error("Failed to create designs");return o.map((s,l)=>{const c=i[l],d=n[l],u=s.transaction;return Ic(u,c.product,c.workflow,d.cartSelectionsWithPrices,s.sku,d.cartMetadata,u.previewImageLink,s.processExecution?.id)})};class Pc{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=Q.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new O("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(n=>n.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(n=>n(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),n=a.find(r=>r.transactionId===t);if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){Q.set(this.localPersistenceKey,JSON.stringify(t));return}throw new O("Unexpected storage method requested")}}const xe=new Pc,xc=f.gql`
2177
+ `;function Te(i){const t=JSON.parse(atob(i.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const cc=async(i,t)=>{const e={};try{if(t){const n=await t.loggedInBearerToken();e.Authorization=`Bearer ${n}`}else throw new Error}catch{const s=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",o=localStorage.getItem(s);o&&!Te(o)&&(e.Authorization=`Bearer ${o}`)}return await t.getBetaEnabled()&&(e["X-Spiff-Beta"]="true"),(await y.getShadowGraphqlClient().mutate({mutation:lc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:i.map(n=>({name:n.name,layouts:n.layouts,workflowId:n.workflowId,transactionId:n.transactionId,previewImage:n.previewImage,useThreeDimPreview:n.useThreeDimPreview,metadata:n.metadata,selectedVariants:n.selectedVariants}))},context:{headers:e}})).data?.designCreateMany},En=(i,t,e)=>{const a=r=>{const s={};if(r.type==="Frame"){const o=i[r.stepName],l=r.data;if(!o||!o.image||l.hideImageInCart&&e)return s;s[`${r.stepTitle} image`]=o.image}if(r.type==="Illustration"){const o=i[r.stepName],l=r.data;if(!o||l.hideColorsInCart&&e||!o.colors)return s;if(o.colors.length>0){const c=o.colors.join(", ").toUpperCase();s[`${r.stepTitle} colors`]=c}}if(r.type==="Module"){const o=i[r.stepName],l=r.data;if(!o||o.text===void 0||o.text===null||l.hideTextInCart&&e)return s;s[`${r.stepTitle} text`]=o.text}if(r.type==="Text"){const o=i[r.stepName];if(!o)return s;const l=r.data;(!l.hideTextInCart||!e&&o.text!==void 0&&o.text!==null)&&(s[`${r.stepTitle} text`]=o.text),o.color&&(!l.hideColorInCart||!e)&&(s[`${r.stepTitle} color`]=o.color),o.strokeColor&&(!l.hideStrokeInCart||!e)&&(s[`${r.stepTitle} stroke`]=o.strokeColor)}return s},n={};return t.steps.forEach(r=>{Object.assign(n,a(r))}),n},dc=(i,t,e,a)=>{const n={};let r={};a&&(r=a);const o=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of o){if(Object.keys(i).includes(l)){const c=i[l],d=t.steps.find(u=>u.stepTitle===l);n[`${d?.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(r))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(n[c]={value:r[c],priceModifier:0})}return n},uc=(i,t,e,a,n,r,s,o)=>{const l=t.basePrice||0,c=i.priceModifierTotal||0,d=dc(a,e,void 0,r),A=(Q.getMap("transactionOwnerIds")||new Map).get(i.id),h={additionalExternalProductId:i.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:i.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:i.designExternalVariants,designProductId:i.externalDesignProductId,designProductVariantId:i.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:i.externalCartProductId,externalCartProductVariantId:i.externalCartProductVariantId,lineItemImageUrl:s||"",optionsCost:c,processExecutionId:o,quantity:i.quantity,transactionId:i.id,transactionOwnerId:A,weight:t.weight,workflowViewerLink:i.workflowViewerLink||"",workflowViewerReadOnlyLink:i.workflowViewerReadOnlyLink||""};return r&&(h.metadata=r),a&&(h.selectedVariants=a),n&&(h.sku=n),h},Ac=async(i,t,e,a,n,r,s,o,l,c)=>{c&&(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await i.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const d=i.getPreviewService(),u=t?.finalizeStepConfig?.lookAtAnimation,A=d&&t.showModelOnFinishStep&&!!u,h=l&&En(l,t,!0),g=l&&En(l,t,!1),p=async v=>{const B={};let M=0;if(Object.keys(r).length>0)for(const R of Object.keys(r)){const x=r[R],T=t.steps.find(L=>L.stepName===R);for(let L=0;L<x.selections.length;++L){const k=x.selections[L];if(T){const X=await I.getOptionForStep(T);if(!v||X&&(X.variants||[]).length>1&&!T.data.hideSelectionInCart&&!T.data.hideSelectionsInCart){const bt=T.stepTitle;B[bt]?B[bt].push({id:k.id||"",name:k.name,priceModifier:k.priceModifier}):B[bt]=[{id:k.id||"",name:k.name,priceModifier:k.priceModifier}]}}M+=k.priceModifier}}return[B,M]},[m]=await p(!0),C=Object.fromEntries(Object.keys(m).map(v=>[v,m[v].map(B=>B.id)])),[S]=await p(!1),w=Object.fromEntries(Object.keys(S).map(v=>[v,S[v].map(B=>B.id)]));let F=await o(A,n.id);if(F){const v=await(await nt(F)).blob();F=(await G.uploadAsset({name:`${n.id}-preview-image.png`,blob:v},ee.Image,!0,!1)).fileLink}return{designDetails:(()=>{const v={name:s,layouts:e.map(B=>({index:B.index,panelId:B.panelId})),workflowId:t.id,transactionId:n.id,useThreeDimPreview:!!A,previewImage:F};if(g){const B=[];for(const[M,R]of Object.entries(g))B.push({key:M,value:R});v.metadata=B}if(C){const B=[];for(const[M,R]of Object.entries(w))B.push({key:M,ids:R});v.selectedVariants=B}return v})(),cartSelectionsWithPrices:m,cartMetadata:h}},$i=async(i,t)=>{await Promise.all(i.map(async o=>{await o.workflowManager.outstandingRequestsPromise()}));const a=await(async()=>{const o=y.getShadowGraphqlClient(),l=await Promise.all(i.map(async A=>({id:A.transaction.id,hash:await A.workflowManager.getStateHash()}))),d=ga(l,100),u=[];for(const A of d){const h=await o.query({query:Qs,variables:{transactions:A},fetchPolicy:"no-cache",errorPolicy:"all"});if(h.errors&&h.errors.length>0)return l.map(g=>g.id);u.push(...h.data?.transactionConfirmWorkflowStates??[])}return u})(),n=await Promise.all(i.map(async o=>await Ac(o.workflowManager,o.workflow,o.layouts,o.getReducerState,o.transaction,o.workflowSelections,o.designName,t??(()=>Promise.resolve(void 0)),o.workflowMetadata,a.includes(o.transaction.id)))),r=i[0].workflowManager.getClient(),s=await cc(n.map(o=>o.designDetails),r);if(!s)throw new Error("Failed to create designs");return s.map((o,l)=>{const c=i[l],d=n[l],u=o.transaction;return uc(u,c.product,c.workflow,d.cartSelectionsWithPrices,o.sku,d.cartMetadata,u.previewImageLink,o.processExecution?.id)})};class hc{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=Q.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new O("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(n=>n.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(n=>n(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),n=a.find(r=>r.transactionId===t);if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){Q.set(this.localPersistenceKey,JSON.stringify(t));return}throw new O("Unexpected storage method requested")}}const Be=new hc,gc=f.gql`
2178
2178
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
2179
2179
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
2180
2180
  id
@@ -2188,7 +2188,7 @@
2188
2188
  }
2189
2189
  }
2190
2190
  }
2191
- `,Fc=f.gql`
2191
+ `,mc=f.gql`
2192
2192
  mutation AddAddressToTransaction(
2193
2193
  $transactionId: String!
2194
2194
  $streetAddress: String
@@ -2210,15 +2210,15 @@
2210
2210
  id
2211
2211
  }
2212
2212
  }
2213
- `,Dc=f.gql`
2213
+ `,pc=f.gql`
2214
2214
  mutation AddOrganizationToTransaction($transactionId: String!, $organizationName: String!) {
2215
2215
  organizationAttachToTransaction(transactionId: $transactionId, organizationName: $organizationName) {
2216
2216
  id
2217
2217
  }
2218
2218
  }
2219
- `,Dn=f.gql`
2220
- ${Ye}
2221
- ${he}
2219
+ `,bn=f.gql`
2220
+ ${je}
2221
+ ${ue}
2222
2222
  mutation TransactionUpdateIntegrationProduct($id: String!, $integrationProductId: String) {
2223
2223
  transactionUpdateIntegrationProduct(id: $id, integrationProductId: $integrationProductId) {
2224
2224
  id
@@ -2300,7 +2300,7 @@
2300
2300
  }
2301
2301
  }
2302
2302
  }
2303
- `;var Re=(i=>(i.PriceBreakChanged="PriceBreakChanged",i.ProductChanged="ProductChanged",i.QuantityChanged="QuantityChanged",i.RecipientChanged="RecipientChanged",i.SelectionChanged="SelectionChanged",i))(Re||{});class _i{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Ln(async()=>{await xe.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async a=>new Promise((n,r)=>{try{a.toBlob(o=>{if(o){const s=URL.createObjectURL(o);n(s)}})}catch(o){r(o)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(a=>a.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Ta(this,t,a=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(a)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(a=>{const n=a.traversableScenes.map(r=>{const o=r.renderableSteps.map(s=>s.stepName);return{id:r.name,title:r.title,renderableSteps:o,workflowScene:r}});this.renderableScenes=n,this.renderableSceneCallbacks.forEach(r=>r(n)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:Dn,variables:{id:this.getTransaction().id,integrationProductId:t}}),a=e.data?.transactionUpdateIntegrationProduct.product;if(!a)throw new O("Failed to set product. No product returned from server.");if(!this.bundle)throw new O("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const n=(await this.bundle.getProductCollection().fetchProducts()).find(r=>r.getId()===a.id);try{const r=n?.getDefaultWorkflow();if(r){const o=await lr(r.getId());await this.setWorkflow(o),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 O("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:Dn,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:jo,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,n,r,o){await this.graphQlClient().mutate({mutation:Fc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Dc,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),n=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!n)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,n)||""}let r=2048;e&&e<=2048&&(r=e);const o=vt(r,r),s=this.workflowManager.getCommandContext().getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(w=>w.layoutState?.layout.panelId===c?.name)||s[0],u=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Le("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),p=Xe(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Ot.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),m=Zn(p);await(await $a.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:vt,createImage:de,DOMParser:qa(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflow()?.steps.find(r=>r.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=be.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}async getStepsConditionallyActive(){const t=this.getScenes();return(await Promise.all(t.map(async a=>{const n=this.getStepsByScene(a),r=await Promise.all(n.map(o=>Ct(o.getRaw(),this.getWorkflowManager().getStepSelections())));return n.filter((o,s)=>r[s])}))).flat()}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((r,o)=>r+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((n,r)=>-(n.minQty-r.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,r)=>n+r.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,a=this.getTransaction().id,n=t.getProduct()?.id,r=this.getProduct()?.id;return e!==a&&n===r})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),r=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>r===void 0||r.includes(c.getId())),s=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),s.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const p=l(g),m=d.has(JSON.stringify(g));if(m&&p?.getType()==="Option"){const C=A.getCurrentVariant();if(!C)return;c.selectVariant(C),d.delete(JSON.stringify(g))}else if(m&&p?.getType()==="Text"){const C=A.getText();c.setText(C),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return be.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>be.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){const e=this.getWorkflow();if(!e?.stepGroups.find(n=>n.name===t.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 t.stepIds.map(n=>e.steps.find(r=>r.stepName===n)).filter(n=>!!n&&this.stepHasHandle(n)).map(n=>be.get(this.getWorkflowManager(),n))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:xc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(n=>n.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const n=Q.getMap("transactionCustomerIds")||new Map;n.set(this.getTransaction().id,a.customer.id),Q.setMap("transactionCustomerIds",n)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),a=this.getWorkflow(),n=this.getCommandContext().getState();if(!e)throw new O("Product undefined!");if(!a)throw new O("Workflow undefined!");if(!n)throw new O("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await xe.getSavedDesigns()).find(d=>d.transactionId===s)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:a.name,workflowId:a.id,lastEdited:new Date};return await xe.addDesign(o),o}async copy(){const t=yt(this.getCommandContext().getState());if(!t)throw new O("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new O("Workflow is undefined! Cannot copy experience!");const n=this.getTransaction().integrationProduct?.id;if(!n)throw new O("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),a=this.getProduct(),n=this.getWorkflow();if(!a)throw new O("Product undefined! Cannot finish an experience without a product.");if(!n)throw new O("Workflow undefined! Cannot finish an experience without a workflow.");if(e.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const r=await Ki([{workflowManager:this.workflowManager,workflow:n,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:a,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:n.name}],o=>t?this.createPreviewImage(o,1024):Promise.resolve(void 0));return e.completed&&await this.graphQlClient().mutate({mutation:Zo,variables:{transactionId:e.id}}),r[0]}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}async getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),n=[];for(const r of t?.steps||[]){const o=r.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:r.stepTitle,properties:[]};if(l&&await Mc(r,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){n.push(c);continue}switch(r.type){case E.Frame:{const d=r.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=r.data,u=s;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case E.Module:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}n.push(c)}return n.filter(r=>r.properties&&r.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(t){if(t<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=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:Go,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const kc=i=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(i.type)){const e=i.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Mc=async(i,t)=>{if(!kc(i))return!1;const e=await I.getOptionForStep(i);if(e&&(e.variants||[]).length>1){const a=t[i.stepName];return!!(a&&a.selections.length>0)}return!1};class Tc{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration;return t?Promise.all(t.aspects.map(e=>this.getHandle(e))):[]}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:(t.conditionMode===qn.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(n=>{const r=e.aspects.find(o=>o.name===n.targetAspectName);return r?n.requiredVariantSelections.some(o=>o===r.value):!1})}async createHandle(t){switch(t.type){case z.FileUpload:return new Xi(this.bundle,t).initialize();case z.ColorOption:return new Na(this.bundle,t,t.entityId?await I.getOption(t.entityId):void 0);case z.Option:{const e=t.entityId?await I.getOption(t.entityId):void 0;return e?.type==="Color"?new Na(this.bundle,t,e):new nn(this.bundle,t,e)}case z.Text:return new Zi(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class ea{constructor(t,e){this.bundle=t,this.property=e}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(t){const e=t??this.bundle.getWorkflowExperiences();return(await Promise.all(e.map(r=>r.getStepsConditionallyActive()))).map(r=>r.filter(o=>o.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:o.getRaw().globalPropertyAspectConfigurations?.some(s=>s.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&s.aspectName===this.property.name))).flat()}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Xi extends ea{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await I.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await et(t?.fileLink),a=await Wa(t?.fileLink),n=a.width,r=a.height,o=await rt(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:n,height:r,aspect:n/r,svg:o.svg,colors:o.colors};ht.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseAdvancedImageManipulation(){return this.bundle.getClient().canUseAddon(Ue.AdvancedImageManipulation)}async removeBackgroundFromImage(t=!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 e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),n}async vectorizeImage(t=!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 e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to vectorize the image.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.vectorizeAsset(e),o={...a.getAspectStorage(this.property.name),vectorizedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return G.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Ge(He(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return G.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return G.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if(n?.useOriginalAsset===t)return;const r={...n,useOriginalAsset:t},o=t?n?.originalAssetKey:n?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",r)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(r)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await G.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const r=new Map(n.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);await Promise.all((await this.getSharedSteps(t)).map(async o=>{await o.changeColors(r)}))}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.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 rt(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));await Promise.all((await e).map(async r=>{await r.changeColors(a)}));const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([r,o])=>({key:r,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const o=(await this.getSharedSteps(e)).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;n.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Zi extends ea{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>{r.setText(t)});await Promise.all(n)}}class nn extends ea{constructor(t,e,a){super(t,e),this.optionResource=a}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const t=await I.getOption(this.property.entityId);return t&&(this.optionResource=t),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new nt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new nt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new nt(e):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new nt(e))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(e=>new nt(e))}async selectVariant(t,e){await this.applyVariantSelection(t),await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(n=>n.id===e);if(a)return this.applyVariantSelection(new nt(a),t)}async applyVariantSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>r.selectVariant(t));await Promise.all(n)}}class Na extends nn{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(r=>r.id===e);if(!a)return;await this.applyColorVariant(new nt(a),t);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;n&&await this.setCustomColor(n)}async applyColorVariant(t,e,a){const r=(await this.getSharedSteps(e)).map(o=>{switch(o.getType()){case E.Shape:return o.selectVariant(t);case E.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(r)}async setCustomColor(t){const e=this.getCurrentVariant()?.getColor();e&&e.toLowerCase()==="#custom"&&(await this.getSharedSteps()).forEach(n=>n.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const Nc=(i,t,e)=>{const a=i.getWorkflowExperiences(),n=i.getGlobalPropertyConfiguration();return n?a.flatMap(o=>o.getSteps()).filter(o=>o.getGlobalPropertyAspects(n.id).includes(t)&&o.getType()===e):[]},tr=(i,t)=>{const a=Nc(i,t,E.Illustration).map(n=>{if(!n.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const o=n.getColors();return o?Object.getOwnPropertyNames(o).length:0});return Math.max(...a)};function Qa(i,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!Oc(a))return a;if(Array.isArray(a))return Qa(a,t);let n={};for(const[r,o]of Object.entries(a))n[r]=Qc(o)?o:Qa(o,t);return Lr(n,t)}return Array.isArray(i)?i.map(e):e(i)}function Qc(i){return i==null}function Oc(i){return typeof i=="object"&&!Array.isArray(i)&&i!==null}function er(i){const t=new Map;return i?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}class Rc extends Ke{constructor(t){super(),this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},1e3)})}}function pa(i){return Qa(i,["__typename"])}class $c{constructor(t,e,a,n,r){this.stateUpdateQueue=new _e(1),this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=r;const o=r?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=pa(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=pa(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=n}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(a=>!t.includes(a.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=er(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=yt(this.globalPropertyState);this.globalPropertyState={...pa(t),id:e.id},this.recalculateMandatoryStates(),this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspectHidden(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return!!this.globalPropertyState.aspects.find(e=>e.name===t)?.hidden}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,n,r){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 o=this.configuration.aspects.find(c=>c.name===t);if(!o)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const s=yt(this.globalPropertyState),l=this.globalPropertyState.aspects.filter(c=>c.name===t);if(l.length>0)if(n){const c=l.find(d=>d.channel===n);if(c)c.value=e,c.type=o.type,c.channel=n,c.hidden=r??c.hidden,a!==void 0&&(c.storage=a!==null?a:void 0);else{let d;if(n===1){const u=this.globalPropertyState.aspects.findIndex(A=>!A.channel&&A.name===t);u&&u>0&&(d=this.globalPropertyState.aspects.splice(u,1)[0].hidden)}this.globalPropertyState.aspects.push({name:t,value:e,type:o.type,storage:a!==null?a:void 0,channel:n,hidden:r??d})}}else{const c=l[0];c.value=e,c.type=o.type,c.hidden=r??c.hidden,a!==void 0&&(c.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:o.type,storage:a!==null?a:void 0,channel:n,hidden:r});ae(s,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState))}async setAspectStorage(t,e,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 n=this.configuration.aspects.find(s=>s.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const r=yt(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=n.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});ae(r,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(r,this.globalPropertyState))}queueGlobalPropertyStateUpdate(){this.stateUpdateQueue.enqueue(new Rc(async()=>{await this.updateGlobalPropertyState()}))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!(await y.getShadowGraphqlClient().mutate({mutation:$l,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case z.FileUpload:{a.fileUpload=e.storage;break}case z.ColorOption:case z.Option:{a.option=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel,hidden:e.hidden}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}})).data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Rl,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class Uc{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}}const Vc=f.gql`
2303
+ `;var Ne=(i=>(i.PriceBreakChanged="PriceBreakChanged",i.ProductChanged="ProductChanged",i.QuantityChanged="QuantityChanged",i.RecipientChanged="RecipientChanged",i.SelectionChanged="SelectionChanged",i))(Ne||{});class Ui{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=xn(async()=>{await Be.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async a=>new Promise((n,r)=>{try{a.toBlob(s=>{if(s){const o=URL.createObjectURL(s);n(o)}})}catch(s){r(s)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(a=>a.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new xa(this,t,a=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(a)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(a=>{const n=a.traversableScenes.map(r=>{const s=r.renderableSteps.map(o=>o.stepName);return{id:r.name,title:r.title,renderableSteps:s,workflowScene:r}});this.renderableScenes=n,this.renderableSceneCallbacks.forEach(r=>r(n)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:bn,variables:{id:this.getTransaction().id,integrationProductId:t}}),a=e.data?.transactionUpdateIntegrationProduct.product;if(!a)throw new O("Failed to set product. No product returned from server.");if(!this.bundle)throw new O("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const n=(await this.bundle.getProductCollection().fetchProducts()).find(r=>r.getId()===a.id);try{const r=n?.getDefaultWorkflow();if(r){const s=await Ki(r.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 O("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:bn,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:ks,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,n,r,s){await this.graphQlClient().mutate({mutation:mc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:s||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:pc,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),n=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!n)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,n)||""}let r=2048;e&&e<=2048&&(r=e);const s=yt(r,r),o=this.workflowManager.getCommandContext().getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=o.find(w=>w.layoutState?.layout.panelId===c?.name)||o[0],u=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=s.getContext("2d");if(!h)throw new $e("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),p=Je(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Nt.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),m=Vn(p);await(await Ma.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:yt,createImage:le,DOMParser:Ra(),fetch})).render();const S=await this.getCanvasObjectURLAsync(s);return s.toDataURL(S)}getStepById(t){const e=this.getWorkflow()?.steps.find(r=>r.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=ve.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}async getStepsConditionallyActive(){const t=this.getScenes();return(await Promise.all(t.map(async a=>{const n=this.getStepsByScene(a),r=await Promise.all(n.map(s=>pt(s.getRaw(),this.getWorkflowManager().getStepSelections())));return n.filter((s,o)=>r[o])}))).flat()}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((r,s)=>r+(s.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((n,r)=>-(n.minQty-r.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,r)=>n+r.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,a=this.getTransaction().id,n=t.getProduct()?.id,r=this.getProduct()?.id;return e!==a&&n===r})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),r=a?.map(c=>c.getId()),s=this.getSteps().filter(c=>r===void 0||r.includes(c.getId())),o=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);s.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),o.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const p=l(g),m=d.has(JSON.stringify(g));if(m&&p?.getType()==="Option"){const C=A.getCurrentVariant();if(!C)return;c.selectVariant(C),d.delete(JSON.stringify(g))}else if(m&&p?.getType()==="Text"){const C=A.getText();c.setText(C),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return ve.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>ve.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){const e=this.getWorkflow();if(!e?.stepGroups.find(n=>n.name===t.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 t.stepIds.map(n=>e.steps.find(r=>r.stepName===n)).filter(n=>!!n&&this.stepHasHandle(n)).map(n=>ve.get(this.getWorkflowManager(),n))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:gc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(n=>n.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const n=Q.getMap("transactionCustomerIds")||new Map;n.set(this.getTransaction().id,a.customer.id),Q.setMap("transactionCustomerIds",n)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),a=this.getWorkflow(),n=this.getCommandContext().getState();if(!e)throw new O("Product undefined!");if(!a)throw new O("Workflow undefined!");if(!n)throw new O("State undefined!");const s={title:await(async()=>{if(t)return t;const o=this.getTransaction().id,c=(await Be.getSavedDesigns()).find(d=>d.transactionId===o)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:a.name,workflowId:a.id,lastEdited:new Date};return await Be.addDesign(s),s}async copy(){const t=Ct(this.getCommandContext().getState());if(!t)throw new O("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new O("Workflow is undefined! Cannot copy experience!");const n=this.getTransaction().integrationProduct?.id;if(!n)throw new O("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),a=this.getProduct(),n=this.getWorkflow();if(!a)throw new O("Product undefined! Cannot finish an experience without a product.");if(!n)throw new O("Workflow undefined! Cannot finish an experience without a workflow.");if(e.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const r=await $i([{workflowManager:this.workflowManager,workflow:n,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:a,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:n.name}],s=>t?this.createPreviewImage(s,1024):Promise.resolve(void 0));return e.completed&&await this.graphQlClient().mutate({mutation:Us,variables:{transactionId:e.id}}),r[0]}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}async getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),n=[];for(const r of t?.steps||[]){const s=r.stepName,o=e[s],l=a[s]?.selections[0],c={stepId:s,title:r.stepTitle,properties:[]};if(l&&await Cc(r,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!o){n.push(c);continue}switch(r.type){case E.Frame:{const d=r.data,u=o;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=r.data,u=o;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case E.Module:{const d=r.data,u=o;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=r.data,u=o;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}n.push(c)}return n.filter(r=>r.properties&&r.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(t){if(t<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=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:Ds,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const fc=i=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(i.type)){const e=i.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Cc=async(i,t)=>{if(!fc(i))return!1;const e=await I.getOptionForStep(i);if(e&&(e.variants||[]).length>1){const a=t[i.stepName];return!!(a&&a.selections.length>0)}return!1};class wc{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration;return t?Promise.all(t.aspects.map(e=>this.getHandle(e))):[]}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:(t.conditionMode===Dn.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(n=>{const r=e.aspects.find(s=>s.name===n.targetAspectName);return r?n.requiredVariantSelections.some(s=>s===r.value):!1})}async createHandle(t){switch(t.type){case z.FileUpload:return new Vi(this.bundle,t).initialize();case z.ColorOption:return new Fa(this.bundle,t,t.entityId?await I.getOption(t.entityId):void 0);case z.Option:{const e=t.entityId?await I.getOption(t.entityId):void 0;return e?.type==="Color"?new Fa(this.bundle,t,e):new Xa(this.bundle,t,e)}case z.Text:return new Li(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Ze{constructor(t,e){this.bundle=t,this.property=e}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(t){const e=t??this.bundle.getWorkflowExperiences();return(await Promise.all(e.map(r=>r.getStepsConditionallyActive()))).map(r=>r.filter(s=>s.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:s.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name))).flat()}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Vi extends Ze{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await I.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await tt(t?.fileLink),a=await La(t?.fileLink),n=a.width,r=a.height,s=await it(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{s.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:n,height:r,aspect:n/r,svg:s.svg,colors:s.colors};ut.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseAdvancedImageManipulation(){return this.bundle.getClient().canUseAddon(Oe.AdvancedImageManipulation)}async removeBackgroundFromImage(t=!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 e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.removeBackgroundFromAsset(e),s={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}async vectorizeImage(t=!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 e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to vectorize the image.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.vectorizeAsset(e),s={...a.getAspectStorage(this.property.name),vectorizedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return G.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Le(qe(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return G.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return G.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if(n?.useOriginalAsset===t)return;const r={...n,useOriginalAsset:t},s=t?n?.originalAssetKey:n?.backgroundRemovedAssetKey,o=[a.setAspect(this.property.name,s||"",r)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(r)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await G.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const r=new Map(n.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);await Promise.all((await this.getSharedSteps(t)).map(async s=>{await s.changeColors(r)}))}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.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 it(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));await Promise.all((await e).map(async r=>{await r.changeColors(a)}));const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([r,s])=>({key:r,browserValue:s.browserValue,pmsValue:s.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const s=(await this.getSharedSteps(e)).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;n.getRaw().globalPropertyAspectConfigurations?.some(s=>s.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&s.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Li extends Ze{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>{r.setText(t)});await Promise.all(n)}}class Xa extends Ze{constructor(t,e,a){super(t,e),this.optionResource=a}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const t=await I.getOption(this.property.entityId);return t&&(this.optionResource=t),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new at(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new at(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new at(e):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new at(e))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(e=>new at(e))}async selectVariant(t,e){await this.applyVariantSelection(t),await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(n=>n.id===e);if(a)return this.applyVariantSelection(new at(a),t)}async applyVariantSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>r.selectVariant(t));await Promise.all(n)}}class Fa extends Xa{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(r=>r.id===e);if(!a)return;await this.applyColorVariant(new at(a),t);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;n&&await this.setCustomColor(n)}async applyColorVariant(t,e,a){const r=(await this.getSharedSteps(e)).map(s=>{switch(s.getType()){case E.Shape:return s.selectVariant(t);case E.Text:return s.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return s.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(r)}async setCustomColor(t){const e=this.getCurrentVariant()?.getColor();e&&e.toLowerCase()==="#custom"&&(await this.getSharedSteps()).forEach(n=>n.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const yc=(i,t,e)=>{const a=i.getWorkflowExperiences(),n=i.getGlobalPropertyConfiguration();return n?a.flatMap(s=>s.getSteps()).filter(s=>s.getGlobalPropertyAspects(n.id).includes(t)&&s.getType()===e):[]},zi=(i,t)=>{const a=yc(i,t,E.Illustration).map(n=>{if(!n.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const s=n.getColors();return s?Object.getOwnPropertyNames(s).length:0});return Math.max(...a)};function Da(i,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!vc(a))return a;if(Array.isArray(a))return Da(a,t);let n={};for(const[r,s]of Object.entries(a))n[r]=Sc(s)?s:Da(s,t);return xr(n,t)}return Array.isArray(i)?i.map(e):e(i)}function Sc(i){return i==null}function vc(i){return typeof i=="object"&&!Array.isArray(i)&&i!==null}function qi(i){const t=new Map;return i?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}class Ec extends He{constructor(t){super(),this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},1e3)})}}function ha(i){return Da(i,["__typename"])}class bc{constructor(t,e,a,n,r){this.stateUpdateQueue=new Ye(1),this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=r;const s=r?.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=ha(s),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=ha(o),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=n}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(a=>!t.includes(a.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=qi(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Ct(this.globalPropertyState);this.globalPropertyState={...ha(t),id:e.id},this.recalculateMandatoryStates(),this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspectHidden(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return!!this.globalPropertyState.aspects.find(e=>e.name===t)?.hidden}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,n,r){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(c=>c.name===t);if(!s)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=Ct(this.globalPropertyState),l=this.globalPropertyState.aspects.filter(c=>c.name===t);if(l.length>0)if(n){const c=l.find(d=>d.channel===n);if(c)c.value=e,c.type=s.type,c.channel=n,c.hidden=r??c.hidden,a!==void 0&&(c.storage=a!==null?a:void 0);else{let d;if(n===1){const u=this.globalPropertyState.aspects.findIndex(A=>!A.channel&&A.name===t);u&&u>0&&(d=this.globalPropertyState.aspects.splice(u,1)[0].hidden)}this.globalPropertyState.aspects.push({name:t,value:e,type:s.type,storage:a!==null?a:void 0,channel:n,hidden:r??d})}}else{const c=l[0];c.value=e,c.type=s.type,c.hidden=r??c.hidden,a!==void 0&&(c.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:s.type,storage:a!==null?a:void 0,channel:n,hidden:r});te(o,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(t,e,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 n=this.configuration.aspects.find(o=>o.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const r=Ct(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===t);if(s.length>0)if(a){const o=s.find(l=>l.channel===a);o&&(o.storage=e!==null?e:void 0,o.type=n.type)}else{const o=s[0];o.storage=e!==null?e:void 0,o.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});te(r,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(r,this.globalPropertyState))}queueGlobalPropertyStateUpdate(){this.stateUpdateQueue.enqueue(new Ec(async()=>{await this.updateGlobalPropertyState()}))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!(await y.getShadowGraphqlClient().mutate({mutation:bl,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case z.FileUpload:{a.fileUpload=e.storage;break}case z.ColorOption:case z.Option:{a.option=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel,hidden:e.hidden}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}})).data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:El,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class Ic{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}}const Bc=f.gql`
2304
2304
  query GetManyMetafields($entityIds: [String!]!) {
2305
2305
  metafieldsMany(entityIds: $entityIds) {
2306
2306
  id
@@ -2312,14 +2312,14 @@
2312
2312
  }
2313
2313
  }
2314
2314
  }
2315
- `;class Lc{constructor(){this.internalMap=new Map}async requestKeysForEntity(t,e){const a=new Map;return await this.ensureIdsArePresent([t]),e.forEach(n=>{const r=this.requestKeyForEntityIfAvailable(t,n);r&&a.set(n,r)}),a}async ensureIdsArePresent(t){if(t.every(a=>this.internalMap.has(a)))return;const e=await y.getShadowGraphqlClient().query({query:Vc,errorPolicy:"all",variables:{entityIds:t.filter(a=>!this.internalMap.has(a))}});t.forEach((a,n)=>{const r=e.data.metafieldsMany[n];this.internalMap.set(a,r.map(o=>({key:o.metafieldConfiguration.name,value:o.value,metafieldConfigurationId:o.metafieldConfiguration.id,metafieldType:o.metafieldConfiguration.metafieldType})))})}async requestKeyForEntity(t,e){if(!this.internalMap.has(t))return;let a=this.internalMap.get(t);const n=a.find(r=>r.key===e);return n||(await this.ensureIdsArePresent([t]),a=this.internalMap.get(t)),n?JSON.parse(n.value):void 0}requestKeyForEntityIfAvailable(t,e){if(!this.internalMap.has(t))return;const n=this.internalMap.get(t).find(r=>r.key===e);if(n)return JSON.parse(n.value)}requestIfAvailable(t,e){return this.internalMap.has(t)?this.internalMap.get(t).find(r=>r.metafieldConfigurationId===e):void 0}}const $e=new Lc;var ar=(i=>(i.Default="Default",i.Name="Name",i.Price="Price",i))(ar||{});class rn{constructor(t){this.fullFetched=!1,this.collection=t;const e=this.collection.productCollectionProducts;e&&e.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(t=>!!t.product).map(t=>new Jt(t))}async fetchProducts(t){if(this.fullFetched)return(this.collection.productCollectionProducts??[]).filter(n=>!!n.product).map(n=>new Jt(n));const e=await y.getShadowGraphqlClient().query({query:Gl,variables:{id:this.getId(),productIds:t},errorPolicy:"all"}),a=this.collection.productCollectionProducts||[];return this.collection.productCollectionProducts=[...a,...e.data.productCollections[0].productCollectionProducts?.filter(n=>!a.some(r=>n.id===r.id))||[]],this.collection.productCollectionProducts.length>=this.collection.total&&(this.fullFetched=!0),this.collection.productCollectionProducts.filter(n=>!!n.product&&(!t||t.includes(n.product.id))).map(n=>new Jt(n))}async filterProducts(t,e,a,n){const r=await y.getShadowGraphqlClient().query({query:jl,errorPolicy:"all",variables:{id:this.getId(),filters:t?{link:"And",metafields:t}:void 0,tags:e?{include:e.include??[],exclude:e.exclude??[]}:void 0,sortKey:a,sortDescending:n}});if(!r.data?.productCollections||r.data?.productCollections.length===0)throw new Error("Failed to filter product collection products.");const o=this.getProducts(),s=r.data.productCollections[0].productCollectionProducts.map(l=>l.product.id);return o.filter(l=>s.includes(l.getId()))}async fetchProductsFeed(t,e,a,n,r,o,s,l){if(this.fullFetched){const A=await(a?this.filterProducts(a):this.fetchProducts());return{total:A.length,items:A.slice(t,t+e)}}const c=new AbortController,{signal:d}=c,u=y.getShadowGraphqlClient().watchQuery({query:Hl,variables:{id:this.getId(),limit:e,offset:t,productFilters:a?{link:"And",metafields:a}:void 0,productWorkflowFilters:l?{link:"And",metafields:l}:void 0,tags:n?{include:n.include??[],exclude:n.exclude??[]}:void 0,sortKey:r,sortDescending:o,quickSearch:s},errorPolicy:"all",fetchPolicy:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:d}}});return new Promise(A=>{let h=!1;const g=u.subscribe({next(p){if(h||p.partial&&(!p.data.productCollections||p.data.productCollections.length===0||!p.data.productCollections[0].productCollectionProductsFeed?.items||p.data.productCollections[0].productCollectionProductsFeed?.items.length===0))return;c.abort(),h=!0,g.unsubscribe();const m=p.data.productCollections?.[0].productCollectionProductsFeed?.items.filter(C=>!!C.product).map(C=>new Jt(yt(C)))||[];A({items:m,total:p.data.productCollections?.[0].productCollectionProductsFeed?.total??0})},error(){h||(h=!0,g.unsubscribe(),A({items:[],total:0}))}})})}getResource(){return this.collection}}class Jt{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const n=(this.product.integrationProducts||[]).find(r=>{const o=r.integration?.type,s=r.integration?.type===t,l=e?r.integration?.externalIntegrationId===e:!0;return o&&s&&l});if(!n)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return n}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(a=>a.integration?.isCurrent);if(!e)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return e}getDefaultWorkflow(){const t=this.product.workflows;if(t===void 0)throw new ft("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new ft("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const e=this.productResource.workflowId;if(e){const a=t.find(n=>n.workflowName===e);if(a)return new Qt(a)}if(t.length===1)return new Qt(t[0]);throw new ft("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 ft("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.product.workflows.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Qt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){const e=this.product.basePrice||0;if(!t)return e;if(!t.integrationType&&!t.externalId&&!t.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let a;return t.integrationId?a=this.product.integrationProducts?.find(n=>n.integration?.id===t.integrationId):t.externalId?a=this.product.integrationProducts?.find(n=>n.integration?.externalIntegrationId===t.externalId):a=this.product.integrationProducts?.find(n=>n.integration?.type===t.integrationType),a?.additionalIntegrationProduct?.product?e+(a.additionalIntegrationProduct.product.basePrice||0):e}async requestMetafields(t){return $e.requestKeysForEntity(this.product.id,t)}}class Qt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(t=128,e){const a=this.workflow?.imageUrl,n=window?.devicePixelRatio||1;if(a)return We(a,t*n,"webp",e)}}const zc=f.gql`
2316
- ${ta(!1)}
2315
+ `;class Pc{constructor(){this.internalMap=new Map}async requestKeysForEntity(t,e){const a=new Map;return await this.ensureIdsArePresent([t]),e.forEach(n=>{const r=this.requestKeyForEntityIfAvailable(t,n);r&&a.set(n,r)}),a}async ensureIdsArePresent(t){if(t.every(a=>this.internalMap.has(a)))return;const e=await y.getShadowGraphqlClient().query({query:Bc,errorPolicy:"all",variables:{entityIds:t.filter(a=>!this.internalMap.has(a))}});t.forEach((a,n)=>{const r=e.data.metafieldsMany[n];this.internalMap.set(a,r.map(s=>({key:s.metafieldConfiguration.name,value:s.value,metafieldConfigurationId:s.metafieldConfiguration.id,metafieldType:s.metafieldConfiguration.metafieldType})))})}async requestKeyForEntity(t,e){if(!this.internalMap.has(t))return;let a=this.internalMap.get(t);const n=a.find(r=>r.key===e);return n||(await this.ensureIdsArePresent([t]),a=this.internalMap.get(t)),n?JSON.parse(n.value):void 0}requestKeyForEntityIfAvailable(t,e){if(!this.internalMap.has(t))return;const n=this.internalMap.get(t).find(r=>r.key===e);if(n)return JSON.parse(n.value)}requestIfAvailable(t,e){return this.internalMap.has(t)?this.internalMap.get(t).find(r=>r.metafieldConfigurationId===e):void 0}}const Qe=new Pc;var Gi=(i=>(i.Default="Default",i.Name="Name",i.Price="Price",i))(Gi||{});class Za{constructor(t){this.fullFetched=!1,this.collection=t;const e=this.collection.productCollectionProducts;e&&e.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(t=>!!t.product).map(t=>new Ht(t))}async fetchProducts(t){if(this.fullFetched)return(this.collection.productCollectionProducts??[]).filter(n=>!!n.product).map(n=>new Ht(n));const e=await y.getShadowGraphqlClient().query({query:Dl,variables:{id:this.getId(),productIds:t},errorPolicy:"all"}),a=this.collection.productCollectionProducts||[];return this.collection.productCollectionProducts=[...a,...e.data.productCollections[0].productCollectionProducts?.filter(n=>!a.some(r=>n.id===r.id))||[]],this.collection.productCollectionProducts.length>=this.collection.total&&(this.fullFetched=!0),this.collection.productCollectionProducts.filter(n=>!!n.product&&(!t||t.includes(n.product.id))).map(n=>new Ht(n))}async filterProducts(t,e,a,n){const r=await y.getShadowGraphqlClient().query({query:kl,errorPolicy:"all",variables:{id:this.getId(),filters:t?{link:"And",metafields:t}:void 0,tags:e?{include:e.include??[],exclude:e.exclude??[]}:void 0,sortKey:a,sortDescending:n}});if(!r.data?.productCollections||r.data?.productCollections.length===0)throw new Error("Failed to filter product collection products.");const s=this.getProducts(),o=r.data.productCollections[0].productCollectionProducts.map(l=>l.product.id);return s.filter(l=>o.includes(l.getId()))}async fetchProductsFeed(t,e,a,n,r,s,o,l){if(this.fullFetched){const A=await(a?this.filterProducts(a):this.fetchProducts());return{total:A.length,items:A.slice(t,t+e)}}const c=new AbortController,{signal:d}=c,u=y.getShadowGraphqlClient().watchQuery({query:Ml,variables:{id:this.getId(),limit:e,offset:t,productFilters:a?{link:"And",metafields:a}:void 0,productWorkflowFilters:l?{link:"And",metafields:l}:void 0,tags:n?{include:n.include??[],exclude:n.exclude??[]}:void 0,sortKey:r,sortDescending:s,quickSearch:o},errorPolicy:"all",fetchPolicy:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:d}}});return new Promise(A=>{let h=!1;const g=u.subscribe({next(p){if(h||p.partial&&(!p.data.productCollections||p.data.productCollections.length===0||!p.data.productCollections[0].productCollectionProductsFeed?.items||p.data.productCollections[0].productCollectionProductsFeed?.items.length===0))return;c.abort(),h=!0,g.unsubscribe();const m=p.data.productCollections?.[0].productCollectionProductsFeed?.items.filter(C=>!!C.product).map(C=>new Ht(Ct(C)))||[];A({items:m,total:p.data.productCollections?.[0].productCollectionProductsFeed?.total??0})},error(){h||(h=!0,g.unsubscribe(),A({items:[],total:0}))}})})}getResource(){return this.collection}}class Ht{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const n=(this.product.integrationProducts||[]).find(r=>{const s=r.integration?.type,o=r.integration?.type===t,l=e?r.integration?.externalIntegrationId===e:!0;return s&&o&&l});if(!n)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return n}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(a=>a.integration?.isCurrent);if(!e)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return e}getDefaultWorkflow(){const t=this.product.workflows;if(t===void 0)throw new mt("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new mt("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const e=this.productResource.workflowId;if(e){const a=t.find(n=>n.workflowName===e);if(a)return new Tt(a)}if(t.length===1)return new Tt(t[0]);throw new mt("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 mt("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.product.workflows.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){const e=this.product.basePrice||0;if(!t)return e;if(!t.integrationType&&!t.externalId&&!t.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let a;return t.integrationId?a=this.product.integrationProducts?.find(n=>n.integration?.id===t.integrationId):t.externalId?a=this.product.integrationProducts?.find(n=>n.integration?.externalIntegrationId===t.externalId):a=this.product.integrationProducts?.find(n=>n.integration?.type===t.integrationType),a?.additionalIntegrationProduct?.product?e+(a.additionalIntegrationProduct.product.basePrice||0):e}async requestMetafields(t){return Qe.requestKeysForEntity(this.product.id,t)}}class Tt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(t=128,e){const a=this.workflow?.imageUrl,n=window?.devicePixelRatio||1;if(a)return Ge(a,t*n,"webp",e)}}const xc=f.gql`
2316
+ ${Xe(!1)}
2317
2317
  query GetProductCollections($ids: [String!]!) {
2318
2318
  productCollections(ids: $ids) {
2319
2319
  ...ProductCollectionFields
2320
2320
  }
2321
2321
  }
2322
- `,qc=async i=>(await y.getShadowGraphqlClient().query({query:zc,errorPolicy:"all",variables:{ids:i}})).data?.productCollections?.map(e=>new rn(e));class Gc{constructor(){this.listeners={}}on(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}off(t,e){this.listeners[t]&&(this.listeners[t]=this.listeners[t].filter(a=>a!==e))}emit(t,e){if(this.listeners[t])for(const a of this.listeners[t])a(e)}clear(t){if(t)delete this.listeners[t];else for(const e in this.listeners)delete this.listeners[e]}}const jc=f.gql`
2322
+ `,Fc=async i=>(await y.getShadowGraphqlClient().query({query:xc,errorPolicy:"all",variables:{ids:i}})).data?.productCollections?.map(e=>new Za(e));class Dc{constructor(){this.listeners={}}on(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}off(t,e){this.listeners[t]&&(this.listeners[t]=this.listeners[t].filter(a=>a!==e))}emit(t,e){if(this.listeners[t])for(const a of this.listeners[t])a(e)}clear(t){if(t)delete this.listeners[t];else for(const e in this.listeners)delete this.listeners[e]}}const kc=f.gql`
2323
2323
  mutation AddAddressToBundle(
2324
2324
  $bundleId: String!
2325
2325
  $streetAddress: String
@@ -2341,26 +2341,26 @@
2341
2341
  id
2342
2342
  }
2343
2343
  }
2344
- `,Hc=f.gql`
2344
+ `,Mc=f.gql`
2345
2345
  mutation AddOrganizationToBundle($bundleId: String!, $organizationName: String!) {
2346
2346
  organizationAttachToBundle(bundleId: $bundleId, organizationName: $organizationName) {
2347
2347
  id
2348
2348
  }
2349
2349
  }
2350
- `,Wc=f.gql`
2350
+ `,Tc=f.gql`
2351
2351
  mutation GenerateQuoteId($id: String!) {
2352
2352
  bundleGenerateQuoteId(id: $id) {
2353
2353
  id
2354
2354
  quoteId
2355
2355
  }
2356
2356
  }
2357
- `;class kn{constructor(t,e,a,n,r,o,s){this.workflowExperiences=[],this.eventEmitter=new Gc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=r,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Uc(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new $c(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Tc(this),this.setPreviewService(a),this.initializationPromise=(async()=>{if(!o?.readonly){const c=this.bundleStateManager.getState();if(c.integrationProductIds&&c.integrationProductIds.length>0){const d=await y.getShadowGraphqlClient().query({query:pi,variables:{ids:c.integrationProductIds},errorPolicy:"all",fetchPolicy:"no-cache"});if(d.errors)throw new Error(`Failed to fetch integration products for Bundle ${e.id}`);const u=d.data.integrationProducts?.filter(h=>!!h.product?.id&&c.integrationProductIds.includes(h.id)).map(h=>h.product.id);c.integrationProductIds=[],c.productIds=Array.from(new Set([...c.productIds||[],...u||[]]));const A=JSON.stringify(c);this.bundleStateManager.setState(A),await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,bundleStateData:A},context:{bundleOwnerId:r}})}}return Promise.all([this.loadExistingWorkflowExperiences(e.transactionIds||[],{...n,bundleOwnerId:r},s),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants."),this.initializeUninitializedHandles().then(c).catch(d)}))})(),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}async initializeUninitializedHandles(){const t=this.globalPropertyStateManager.getGlobalPropertyState();if(!t)return console.log("Attempted to set global default variant before state was initialized."),[];const a=(await this.globalPropertyHandleService.getHandles()).map(async n=>{if(n.getType()===z.ColorOption||n.getType()===z.Option){const r=n;if(!t.aspects.find(s=>s.name===r.getName()))try{return await r.initDefaultVariant()}catch(s){console.error(`Failed to initialize default global variant - ${s}`)}}});return Promise.all(a)}getProductIds(){return this.bundleStateManager.getState()?.productIds}async addProductId(t){const e=this.bundleStateManager.getState();if(e){if(!e.productIds)e.productIds=[];else if(e.productIds.some(n=>n===t)){this.fireEvent("bundle-products-added",{productIds:e.productIds,added:[]});return}e.productIds=[...e.productIds,t];const a=JSON.stringify(e);this.bundleStateManager.setState(a),this.fireEvent("bundle-products-added",{productIds:e.productIds,added:[t]}),await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,bundleStateData:a},context:{bundleOwnerId:this.ownerId}})}}async removeProductIds(t){const e=this.bundleStateManager.getState();if(e){const a=t.filter(r=>(e.productIds??[]).includes(r));if(a.length===0)return;e.productIds=(e.productIds??[]).filter(r=>!a.includes(r));const n=JSON.stringify(e);this.bundleStateManager.setState(n),this.fireEvent("bundle-products-removed",{productIds:e.productIds,removed:a}),await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,bundleStateData:n},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:Wc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,r,o){await y.getShadowGraphqlClient().mutate({mutation:jc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:Hc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const n=a?.name;await this.getGlobalPropertyStateManager().setAspect(n,a.value,void 0,void 0,a.hidden)}for(const a of t.aspects){const n=a?.name,r=e.find(o=>o.getName()===n);if(r)switch(a.type){case z.FileUpload:{const o=r,s=await De([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case z.ColorOption:{const o=r,l=(await o.getAllVariants()).find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case z.Option:{const o=r,l=(await o.getAllVariants()).find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case z.Text:{await r.setText(a.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(a=>a.getType()===z.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new rn(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(E.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const n of a){const r=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===n);if(r&&r.type===z.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=tr(this,n),d=[...new Set(s.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),g=l.find(p=>p.channelNumber===A);g&&await h.setAspect(n,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const n=Q.getMap("transactionOwnerIds")||new Map,r=e.map(s=>n.get(s));await y.getShadowGraphqlClient().mutate({mutation:Kl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:r},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),await this.initializeUninitializedHandles(),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(Q.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:Jl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(r=>r.getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:_l,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,o])=>({key:r,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const r=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:r})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(r=>r.getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,r)=>e[r]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(r=>r.getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await y.getShadowGraphqlClient().mutate({mutation:Xl,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,r])=>({key:n,value:r})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(r=>r.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:Zl,variables:{id:this.id,details:t,type:e||Va.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:tc,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ec,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:Pn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:Pn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:oc,variables:{bundleId:this.id}});const a=await Ki(this.workflowExperiences.map(n=>{const r=n.getWorkflow();if(!r)throw new Error("Unable to create designs - Workflow not found!");const o=n.getProduct();if(!o)throw new Error("Unable to create designs - Product not found!");return{workflowManager:n.getWorkflowManager(),workflow:r,layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:o,transaction:n.getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:r.name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()}}),e?(n,r)=>{const o=this.workflowExperiences.find(s=>s.getTransaction().id===r);return o?e(o,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+r),Promise.resolve(void 0))}:void 0);return{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 t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:ic,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:nc(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),await this.globalPropertyHandleService.getHandles(),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),r=this.workflowExperiences.find(o=>o.getTransaction().id===n.id);r&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:r})}}async injectExperienceIntoPreviewService(t){this.previewService&&await t.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingWorkflowExperiences(t,e,a){if(t.length===0)return;const n=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e,void 0,a);if(n.forEach(r=>r.setBundle(this)),n.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=n,this.previewService)for(const r of n)await this.injectExperienceIntoPreviewService(r);if(!this.globalPropertyStateManager.getBundleOptions()?.readonly){const r=this.getProductIds()||[],o=this.getProductCollection();if(o&&r.length>0){await o.fetchProducts();const s=o.getProducts(),l=[],c=[];for(const u of r)if(!s.find(h=>h.getId()===u)){for(const h of n)h.getProduct()?.id===u&&c.push(h);l.push(u)}const d=[];l.length>0&&d.push(this.removeProductIds(l)),c.length>0&&d.push(Promise.all(c.map(u=>u.clearProduct()))),d.length>0&&await Promise.all(d)}}}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),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 y.getShadowGraphqlClient().mutate({mutation:ac,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),r=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(n,r),this.checkMandatoryHandlesChanged(t,r);const o=this.getGlobalPropertyStateManager();let s=[];for(const u of a)r.find(A=>A.getName()==u.getName())||(s=[...s,u.getName()]);await o.clearAspects(s);const l=r.map(u=>{if(u.getType()===z.ColorOption||u.getType()===z.Option){const A=u;if(!e.aspects.find(g=>g.name===A.getName()))return A.initDefaultVariant()}});await Promise.all(l),await Promise.all(r.map(u=>u.applyGlobalState()));const c=this.globalPropertyStateManager.getGlobalPropertyState(),d=this.globalPropertyHandleService.applyConditionsFromState(a,c);ae(r.sort(),d.sort())||(this.checkConditionalHandlesChanged(r,d),this.checkMandatoryHandlesChanged(c,d),await this.onGlobalPropertiesChanged(e,c))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],n=[],r=[],o=er(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?n.push(s):r.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:n,remaining:r})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:sc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:lc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const Yc=f.gql`
2357
+ `;class In{constructor(t,e,a,n,r,s,o){this.workflowExperiences=[],this.eventEmitter=new Dc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=r,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Ic(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new bc(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),s),this.globalPropertyHandleService=new wc(this),this.setPreviewService(a),this.initializationPromise=(async()=>{if(!s?.readonly){const c=this.bundleStateManager.getState();if(c.integrationProductIds&&c.integrationProductIds.length>0){const d=await y.getShadowGraphqlClient().query({query:ni,variables:{ids:c.integrationProductIds},errorPolicy:"all",fetchPolicy:"no-cache"});if(d.errors)throw new Error(`Failed to fetch integration products for Bundle ${e.id}`);const u=d.data.integrationProducts?.filter(h=>!!h.product?.id&&c.integrationProductIds.includes(h.id)).map(h=>h.product.id);c.integrationProductIds=[],c.productIds=Array.from(new Set([...c.productIds||[],...u||[]]));const A=JSON.stringify(c);this.bundleStateManager.setState(A),await y.getShadowGraphqlClient().mutate({mutation:Se,variables:{id:this.id,bundleStateData:A},context:{bundleOwnerId:r}})}}return Promise.all([this.loadExistingWorkflowExperiences(e.transactionIds||[],{...n,bundleOwnerId:r},o),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>new Promise((c,d)=>{if(s?.readonly){c([]);return}console.log("Setting default global variants."),this.initializeUninitializedHandles().then(c).catch(d)}))})(),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}async initializeUninitializedHandles(){const t=this.globalPropertyStateManager.getGlobalPropertyState();if(!t)return console.log("Attempted to set global default variant before state was initialized."),[];const a=(await this.globalPropertyHandleService.getHandles()).map(async n=>{if(n.getType()===z.ColorOption||n.getType()===z.Option){const r=n;if(!t.aspects.find(o=>o.name===r.getName()))try{return await r.initDefaultVariant()}catch(o){console.error(`Failed to initialize default global variant - ${o}`)}}});return Promise.all(a)}getProductIds(){return this.bundleStateManager.getState()?.productIds}async addProductId(t){const e=this.bundleStateManager.getState();if(e){if(!e.productIds)e.productIds=[];else if(e.productIds.some(n=>n===t)){this.fireEvent("bundle-products-added",{productIds:e.productIds,added:[]});return}e.productIds=[...e.productIds,t];const a=JSON.stringify(e);this.bundleStateManager.setState(a),this.fireEvent("bundle-products-added",{productIds:e.productIds,added:[t]}),await y.getShadowGraphqlClient().mutate({mutation:Se,variables:{id:this.id,bundleStateData:a},context:{bundleOwnerId:this.ownerId}})}}async removeProductIds(t){const e=this.bundleStateManager.getState();if(e){const a=t.filter(r=>(e.productIds??[]).includes(r));if(a.length===0)return;e.productIds=(e.productIds??[]).filter(r=>!a.includes(r));const n=JSON.stringify(e);this.bundleStateManager.setState(n),this.fireEvent("bundle-products-removed",{productIds:e.productIds,removed:a}),await y.getShadowGraphqlClient().mutate({mutation:Se,variables:{id:this.id,bundleStateData:n},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:Tc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,r,s){await y.getShadowGraphqlClient().mutate({mutation:kc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:s||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:Mc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const n=a?.name;await this.getGlobalPropertyStateManager().setAspect(n,a.value,void 0,void 0,a.hidden)}for(const a of t.aspects){const n=a?.name,r=e.find(s=>s.getName()===n);if(r)switch(a.type){case z.FileUpload:{const s=r,o=await Pe([a.value]);o.length>0&&await s.selectImage(o[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await s.changeColors(c)}break}case z.ColorOption:{const s=r,l=(await s.getAllVariants()).find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await s.selectVariant(l),c?.customColor&&s.setCustomColor(c.customColor);break}case z.Option:{const s=r,l=(await s.getAllVariants()).find(c=>c.getId()===a.value);l&&await s.selectVariant(l);break}case z.Text:{await r.setText(a.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(a=>a.getType()===z.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Za(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(E.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const n of a){const r=this.getGlobalPropertyConfiguration()?.aspects.find(s=>s.name===n);if(r&&r.type===z.ColorOption){const s=e.getCurrentVariant()?.getAssetResource(),o=s?.assetConfiguration?.channelNumbers||[],l=s?.assetConfiguration?.defaultColorVariants||[],c=zi(this,n),d=[...new Set(o.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),g=l.find(p=>p.channelNumber===A);g&&await h.setAspect(n,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const o of t)await this.initializeAdditionalRequiredColorChannels(o);const e=t.map(o=>o.getTransaction().id),a=e.map(o=>this.workflowExperiences.find(l=>l.getTransaction().id===o));if(a.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(o=>!!o).map(o=>o?.getTransaction().id).join(", "));const n=Q.getMap("transactionOwnerIds")||new Map,r=e.map(o=>n.get(o));await y.getShadowGraphqlClient().mutate({mutation:Ol,variables:{id:this.id,transactionIds:e,transactionOwnerIds:r},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const l of o)await l.applyGlobalState(t)};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(t,e=!0){const a=t.getTransaction().id;if(this.workflowExperiences.find(o=>o.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(Q.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:Ql,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(r=>r.getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:Rl,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,s])=>({key:r,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const r=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:r})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(r=>r.getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,r)=>e[r]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(r=>r.getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await y.getShadowGraphqlClient().mutate({mutation:$l,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,r])=>({key:n,value:r})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(r=>r.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:Ul,variables:{id:this.id,details:t,type:e||Na.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:Vl,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:Ll,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:Sn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:Sn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:Wl,variables:{bundleId:this.id}});const a=await $i(this.workflowExperiences.map(n=>{const r=n.getWorkflow();if(!r)throw new Error("Unable to create designs - Workflow not found!");const s=n.getProduct();if(!s)throw new Error("Unable to create designs - Product not found!");return{workflowManager:n.getWorkflowManager(),workflow:r,layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:s,transaction:n.getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:r.name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()}}),e?(n,r)=>{const s=this.workflowExperiences.find(o=>o.getTransaction().id===r);return s?e(s,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+r),Promise.resolve(void 0))}:void 0);return{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 t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:Gl,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ql(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),await this.globalPropertyHandleService.getHandles(),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),r=this.workflowExperiences.find(s=>s.getTransaction().id===n.id);r&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:r})}}async injectExperienceIntoPreviewService(t){this.previewService&&await t.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingWorkflowExperiences(t,e,a){if(t.length===0)return;const n=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e,void 0,a);if(n.forEach(r=>r.setBundle(this)),n.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=n,this.previewService)for(const r of n)await this.injectExperienceIntoPreviewService(r);if(!this.globalPropertyStateManager.getBundleOptions()?.readonly){const r=this.getProductIds()||[],s=this.getProductCollection();if(s&&r.length>0){await s.fetchProducts();const o=s.getProducts(),l=[],c=[];for(const u of r)if(!o.find(h=>h.getId()===u)){for(const h of n)h.getProduct()?.id===u&&c.push(h);l.push(u)}const d=[];l.length>0&&d.push(this.removeProductIds(l)),c.length>0&&d.push(Promise.all(c.map(u=>u.clearProduct()))),d.length>0&&await Promise.all(d)}}}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:Se,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),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 y.getShadowGraphqlClient().mutate({mutation:zl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),r=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(n,r),this.checkMandatoryHandlesChanged(t,r);const s=this.getGlobalPropertyStateManager();let o=[];for(const u of a)r.find(A=>A.getName()==u.getName())||(o=[...o,u.getName()]);await s.clearAspects(o);const l=r.map(u=>{if(u.getType()===z.ColorOption||u.getType()===z.Option){const A=u;if(!e.aspects.find(g=>g.name===A.getName()))return A.initDefaultVariant()}});await Promise.all(l),await Promise.all(r.map(u=>u.applyGlobalState()));const c=this.globalPropertyStateManager.getGlobalPropertyState(),d=this.globalPropertyHandleService.applyConditionsFromState(a,c);te(r.sort(),d.sort())||(this.checkConditionalHandlesChanged(r,d),this.checkMandatoryHandlesChanged(c,d),await this.onGlobalPropertiesChanged(e,c))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],n=[],r=[],s=qi(t);e.forEach(o=>{if(o.isMandatory()){const l=o.isMandatoryFulfilled();l?n.push(o):r.push(o);const c=s.get(o.getName());(c===void 0||c!==l)&&a.push(o)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:n,remaining:r})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:Hl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:Yl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const Nc=f.gql`
2358
2358
  mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
2359
2359
  processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
2360
2360
  id
2361
2361
  }
2362
2362
  }
2363
- `;class nr{async execute(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Yc,variables:{processFlowId:t,inputs:[...e.map(u=>u.getValueForTransmission())]}})).data?.processExecutionCreate?.id;if(!r)throw new Error("Failed to create process execution.");function o(u){return new Promise(A=>{setTimeout(A,u)})}let s=!1,l=0,c,d;for(;!s;){c=await y.getShadowGraphqlClient().query({query:f.gql`
2363
+ `;class ji{async execute(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Nc,variables:{processFlowId:t,inputs:[...e.map(u=>u.getValueForTransmission())]}})).data?.processExecutionCreate?.id;if(!r)throw new Error("Failed to create process execution.");function s(u){return new Promise(A=>{setTimeout(A,u)})}let o=!1,l=0,c,d;for(;!o;){c=await y.getShadowGraphqlClient().query({query:f.gql`
2364
2364
  query getProcessFlowExecution($ids: [String]!) {
2365
2365
  processExecutions(ids: $ids) {
2366
2366
  id
@@ -2373,7 +2373,7 @@
2373
2373
  }
2374
2374
  }
2375
2375
  }
2376
- `,variables:{ids:[r]}});const u=c.data?.processExecutions[0];if(!c||!u)throw new Error("Failed to retrieve server response for execution.");if(u.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(u.completedAt){s=!0,d=new ir(u);break}l+=1;const A=a?.repeats?a?.repeats:5;if(l>=A)throw new Error("Maximum wait time exceeded for execution result.");await o(a?.sleepTime?Math.max(a.sleepTime,500):2e3)}if(!d)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(d)}}class ir{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Kt(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Kt(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Kt(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Kt(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Kt{constructor(t){this.node=t}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(t){return this.getArtifacts().get(t)}}class on{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var rr=(i=>(i.Transaction="Transaction",i.Bundle="Bundle",i.Product="Product",i.Variant="Variant",i.Option="Option",i.LineItem="LineItem",i.Asset="Asset",i))(rr||{});class Jc extends on{constructor(t){super(`"${t}"`)}}class sn extends on{constructor(t,e){if(e!=="Asset"&&!sn.validUUID(t))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${t}", "type": "${e}"}`)}static validUUID(t){return t.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 Kc extends on{constructor(t){super(`[${t.map(e=>e.getRaw()).join(",")}]`)}}class Oa{constructor(t){this.integrationProduct=t}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.basePrice||0,e=this.integrationProduct?.additionalIntegrationProduct;if(!e)return t;if(e&&!e.product)throw new Error("An additional integration product was found, but it does not have a product");return t+(e.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.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 Qt(t[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.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 t.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Qt(e))}}const Ie=f.gql`
2376
+ `,variables:{ids:[r]}});const u=c.data?.processExecutions[0];if(!c||!u)throw new Error("Failed to retrieve server response for execution.");if(u.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(u.completedAt){o=!0,d=new Wi(u);break}l+=1;const A=a?.repeats?a?.repeats:5;if(l>=A)throw new Error("Maximum wait time exceeded for execution result.");await s(a?.sleepTime?Math.max(a.sleepTime,500):2e3)}if(!d)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(d)}}class Wi{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Yt(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Yt(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Yt(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Yt(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Yt{constructor(t){this.node=t}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(t){return this.getArtifacts().get(t)}}class _a{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var Hi=(i=>(i.Transaction="Transaction",i.Bundle="Bundle",i.Product="Product",i.Variant="Variant",i.Option="Option",i.LineItem="LineItem",i.Asset="Asset",i))(Hi||{});class Qc extends _a{constructor(t){super(`"${t}"`)}}class tn extends _a{constructor(t,e){if(e!=="Asset"&&!tn.validUUID(t))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${t}", "type": "${e}"}`)}static validUUID(t){return t.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 Oc extends _a{constructor(t){super(`[${t.map(e=>e.getRaw()).join(",")}]`)}}class ka{constructor(t){this.integrationProduct=t}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.basePrice||0,e=this.integrationProduct?.additionalIntegrationProduct;if(!e)return t;if(e&&!e.product)throw new Error("An additional integration product was found, but it does not have a product");return t+(e.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.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 Tt(t[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.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 t.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}}const Ee=f.gql`
2377
2377
  query GetCustomer($emailAddress: String!) {
2378
2378
  customer(emailAddress: $emailAddress) {
2379
2379
  id
@@ -2391,7 +2391,7 @@
2391
2391
  }
2392
2392
  }
2393
2393
  }
2394
- `,_c=f.gql`
2394
+ `,Rc=f.gql`
2395
2395
  mutation CustomerCreate($details: CustomerDetailsInput!) {
2396
2396
  customerCreate(details: $details) {
2397
2397
  id
@@ -2431,7 +2431,7 @@
2431
2431
  }
2432
2432
  }
2433
2433
  }
2434
- `;const Xc=f.gql`
2434
+ `;const $c=f.gql`
2435
2435
  mutation CustomerGenerateVerificationCode($emailAddress: String!) {
2436
2436
  customerGenerateVerificationCode(emailAddress: $emailAddress)
2437
2437
  }
@@ -2466,7 +2466,7 @@
2466
2466
  }
2467
2467
  }
2468
2468
  }
2469
- `;const Zc=f.gql`
2469
+ `;const Uc=f.gql`
2470
2470
  query CustomerMetafields($id: String!) {
2471
2471
  metafields(entityId: $id) {
2472
2472
  id
@@ -2484,14 +2484,14 @@
2484
2484
  }
2485
2485
  }
2486
2486
  }
2487
- `;class td{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class ed{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const n=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new ed;class or{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return $r(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=An.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(An.code(e)?.code==="CLP")return"USD0,0"}}const Mn=new or;class sr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Mn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Mn.getPrecisionForCurrency(e))}}const ad=async(i,t)=>{const e=await y.getShadowGraphqlClient().query({query:is(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:i}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");if(e.data.workflows===void 0||e.data.workflows.length!==i.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);const a=yt(e.data.workflows);return a.forEach(n=>{n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},nd=async(i,t)=>{const a=(await t).find(n=>n.id===i);if(!a)throw new Error(`Workflow not found: ${i}`);return a},ln=async(i,t)=>{const e=i.map(s=>oe.get({id:s,options:t})),a=i.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=ad(a,t),r=a.map(s=>oe.set({id:s,options:t},nd(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},lr=async(i,t)=>(await ln([i],t))[0],id=async i=>{const t=await y.getShadowGraphqlClient().query({query:pi,variables:{ids:i},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class rd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:qo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&no(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 40.3.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){gt.setHubUrl(t.hubUrl),gt.setServerUrl(t.serverUrl),gt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&ai(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!io())throw new Error("Application key required to use Flow Service.");return new nr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:ds,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new sr(o,s,a,t)}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=cr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),n=(await e.query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:_c,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(n);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),r=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<r-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:Xc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,r=!a?.AccessToken||Oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||r){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Zc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Wl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new kn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",C=localStorage.getItem(m);C&&!Oe(C)&&(l.Authorization=`Bearer ${C}`)}const c={bundleOwnerId:s,...l,...n?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:zl(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new kn(this,u,e,a,s,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:n?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,n){const o={...await ur(t),...n?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Yl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:rc(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&n.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0],r=n.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await n.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,n){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=wa(o,l),d=wa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:zo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,n&&n(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,Bt)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(mt=>mt.option.transactionId===X.id)?.option.readOnly??!1,index:x[Bt].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Lo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,n&&n(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),C=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[S,w]=await Promise.all([(async()=>m.length>0?await id(m):[])(),(async()=>C.length>0?await ln(C,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,Bt=L?b.get(L):void 0,mt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=Q.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",fe));const aa=fe.get(T.id)||void 0,Sr=new td({onMutate:()=>({context:{transactionOwnerId:aa,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:aa,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:Bt,transaction:T,singleVariantsRenderable:mt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:aa,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>Sr,readOnly:k,isReloadedTransaction:mt.type==="transaction"};if(mt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Da(ot),Ce.reloadedState=ot}else if(!k&&mt.workflowState){const ot=JSON.parse(mt.workflowState);await Da(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:X,options:mt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new _i(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Ko(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Oa(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:_o(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Oa(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:Yo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:cs,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const cr=async(i,t)=>(await y.getShadowGraphqlClient().query({query:os,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":i},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,od=async i=>{const e=await y.getShadowGraphqlClient().query({query:Wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i}});if(e.data.transactions.length!==0)return e.data.transactions[0]},sd=async(i,t)=>(await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:i,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,ld=async i=>(await y.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",variables:{id:i}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,cd=async i=>(await y.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:i}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function dr(){const i={};try{const t=await this.loggedInBearerToken();i.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",n=localStorage.getItem(a);n&&!Oe(n)&&(i.Authorization=`Bearer ${n}`)}return i}async function ur(i){const e=Q.getMap("bundleOwnerIds")?.get(i),a=await dr();return{bundleOwnerId:e,...a}}async function dd(i){const e=Q.getMap("transactionOwnerIds")?.get(i),a=await dr();return{transactionOwnerId:e,...a}}const ud=async i=>{const t=await ur(i),e=await y.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:{headers:t}});if(e.data?.bundleDelete!==i)throw new Error(`Failed to delete bundle: ${e.errors}`)},Ad=async i=>{const t=await dd(i),e=await y.getShadowGraphqlClient().mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[i]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==i)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function Ar(i,t,e,a){const n=e.width*i.zoom,r=e.height*i.zoom;if(a){const s=i,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,i.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Be(i.x,t.width-c,0),s.y=Be(i.y,t.height-d,0),s}const o=i;return o.x=Be(o.x,-n,t.width),o.y=Be(o.y,-r,t.height),o}function Be(i,t,e){return Math.min(Math.max(i,t),e)}class hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Ln(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let r=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;ae(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Mt.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=He(this.imageData.svg,this.imageData.colors||{},!1);return Ge(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(r,n),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new O("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=Ar(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new U([new Ws(l,e,t[d]),new Ys(l,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=r,this.maxZoomScale[n]=r*2.5):(this.minZoomScale[n]=r/10,this.maxZoomScale[n]=r*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Ha(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class hd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,r,o,s,l,c,d,u,A,h,g,p,m,C){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}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(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var gr=(i=>(i.SelectFrame="SelectFrame",i.SelectImage="SelectImage",i.Position="Position",i))(gr||{});class mr extends Z{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new hr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return pt.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await pt.selectImage(this.step,t,this.manager,a),e){const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Ue.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!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 e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await G.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async vectorize(t,e=void 0){const a=t??await this.getOriginalImageSelection();if(!a)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=await G.vectorizeAsset(a,e);await this.selectImage(n,t!==void 0);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,vectorizedAssetKey:n.key,useOriginalAsset:!1}}),n}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await I.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||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 t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return G.getLocalOrFromServer(t)}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const gd=f.gql`
2487
+ `;class Vc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Lc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const n=await this.cognitoClient?.send(new fe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Lc;class Yi{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Ir(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=sn.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(sn.code(e)?.code==="CLP")return"USD0,0"}}const Bn=new Yi;class Ji{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Bn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Bn.getPrecisionForCurrency(e))}}const zc=async(i,t)=>{const e=await y.getShadowGraphqlClient().query({query:Gs(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:i}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");if(e.data.workflows===void 0||e.data.workflows.length!==i.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);const a=Ct(e.data.workflows);return a.forEach(n=>{n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},qc=async(i,t)=>{const a=(await t).find(n=>n.id===i);if(!a)throw new Error(`Workflow not found: ${i}`);return a},en=async(i,t)=>{const e=i.map(o=>ie.get({id:o,options:t})),a=i.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=zc(a,t),r=a.map(o=>ie.set({id:o,options:t},qc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(r))},Ki=async(i,t)=>(await en([i],t))[0],Gc=async i=>{const t=await y.getShadowGraphqlClient().query({query:ni,variables:{ids:i},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class jc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Fs})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Gr(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 40.3.4"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!jr())throw new Error("Application key required to use Flow Service.");return new ji}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:Ks,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=r.data.currencyConversion;return new Ji(s,o,a,t)}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=Xi(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),n=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const o=(await e.mutate({mutation:Rc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!o)throw new Error("Unable to create customer.");return this.storeCustomer(o),this.customer=o,{customer:o,isAuthenticated:!1}}this.storeCustomer(n);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),r=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<r-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const o=(await y.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return o.id?(this.customer=o,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:$c,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await jt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const s=(await y.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!s.id)throw new Error("Failed to get customer.");return this.customer=s,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,r=!a?.AccessToken||Te(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||r){const s=await jt.refreshTokens();if(s?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Uc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Tl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const s=Q.getMap("bundlePartnerIds")||new Map;s.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",s);const o=Q.getMap("bundleOwnerIds")||new Map;o.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",o);const l=new In(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n,r){const o=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",C=localStorage.getItem(m);C&&!Te(C)&&(l.Authorization=`Bearer ${C}`)}const c={bundleOwnerId:o,...l,...n?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:xl(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new In(this,u,e,a,o,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:n?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,n){const s={...await _i(t),...n?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Nl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:jl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Fl,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&n.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0],r=n.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await n.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,n){if(t.length===0)throw new mt("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),s=r.filter(x=>x.option.type==="transaction"),o=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=ga(s,l),d=ga(o,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:xs,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,n&&n(u,s.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,bt)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(ht=>ht.option.transactionId===X.id)?.option.readOnly??!1,index:x[bt].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Ps,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${k}`)}return u=u+L.length,n&&n(u,s.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),C=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[S,w]=await Promise.all([(async()=>m.length>0?await Gc(m):[])(),(async()=>C.length>0?await en(C,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,bt=L?b.get(L):void 0,ht=t[X];if(T.integrationProductId){const rt=F.get(T.integrationProductId);T.integrationProduct=rt,T.product=rt?.product,T.integrationProduct||console.error("failed to find transaction's product")}const me=Q.getMap("transactionOwnerIds")||new Map;!me.get(T.id)&&T.transactionOwnerId&&(me.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",me));const _e=me.get(T.id)||void 0,or=new Vc({onMutate:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}})}),pe={workflow:bt,transaction:T,singleVariantsRenderable:ht?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async rt=>this.updateTransactionState({...rt,context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>or,readOnly:k,isReloadedTransaction:ht.type==="transaction"};if(ht.type==="transaction"&&T.workflowState){const rt=JSON.parse(T.workflowState);await Ia(rt),pe.reloadedState=rt}else if(!k&&ht.workflowState){const rt=JSON.parse(ht.workflowState);await Ia(rt),pe.reloadedState=rt}return pe.delayWorkflowStateSync=!0,{experienceOptions:pe,index:X,options:ht}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Ui(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Os(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new ka(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const s=(await y.getShadowGraphqlClient().query({query:Rs(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!s?.id)throw new Error("Integration product not found.");return new ka(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:Ns,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:Js,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Xi=async(i,t)=>(await y.getShadowGraphqlClient().query({query:Ws,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":i},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,Wc=async i=>{const e=await y.getShadowGraphqlClient().query({query:Ts,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Hc=async(i,t)=>(await y.getShadowGraphqlClient().query({query:js,errorPolicy:"all",variables:{themeConfigurationId:i,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Yc=async i=>(await y.getShadowGraphqlClient().query({query:Ys,errorPolicy:"all",variables:{id:i}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Jc=async i=>(await y.getShadowGraphqlClient().query({query:Hs,errorPolicy:"all",variables:{id:i}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function Zi(){const i={};try{const t=await this.loggedInBearerToken();i.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,s])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",n=localStorage.getItem(a);n&&!Te(n)&&(i.Authorization=`Bearer ${n}`)}return i}async function _i(i){const e=Q.getMap("bundleOwnerIds")?.get(i),a=await Zi();return{bundleOwnerId:e,...a}}async function Kc(i){const e=Q.getMap("transactionOwnerIds")?.get(i),a=await Zi();return{transactionOwnerId:e,...a}}const Xc=async i=>{const t=await _i(i),e=await y.getShadowGraphqlClient().mutate({mutation:tc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:{headers:t}});if(e.data?.bundleDelete!==i)throw new Error(`Failed to delete bundle: ${e.errors}`)},Zc=async i=>{const t=await Kc(i),e=await y.getShadowGraphqlClient().mutate({mutation:ec,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[i]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==i)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function tr(i,t,e,a){const n=e.width*i.zoom,r=e.height*i.zoom;if(a){const o=i,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,i.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=be(i.x,t.width-c,0),o.y=be(i.y,t.height-d,0),o}const s=i;return s.x=be(s.x,-n,t.width),s.y=be(s.y,-r,t.height),s}function be(i,t,e){return Math.min(Math.max(i,t),e)}class er{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=xn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let r=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await he(o),c=this.frameData?this.frameData[s]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,r=!0)}r&&(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)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Dt.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=qe(this.imageData.svg,this.imageData.colors||{},!1);return Le(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],u=a[o]-c*t[o];return{x:d,y:u,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(r,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new O("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=tr(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getRegionElements(this.stepName||""),o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=s.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),o(new U([new To(l,e,t[d]),new No(l,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=r,this.maxZoomScale[n]=r*2.5):(this.minZoomScale[n]=r/10,this.maxZoomScale[n]=r*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Va(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class _c{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,r,s,o,l,c,d,u,A,h,g,p,m,C){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}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(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var ar=(i=>(i.SelectFrame="SelectFrame",i.SelectImage="SelectImage",i.Position="Position",i))(ar||{});class nr extends Z{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new er(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return gt.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await gt.selectImage(this.step,t,this.manager,a),e){const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Oe.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!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 e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await G.removeBackgroundFromAsset(e);t&&await gt.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async vectorize(t,e=void 0){const a=t??await this.getOriginalImageSelection();if(!a)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=await G.vectorizeAsset(a,e);await this.selectImage(n,t!==void 0);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,vectorizedAssetKey:n.key,useOriginalAsset:!1}}),n}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await gt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await I.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?gt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await it(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return gt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||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 t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return G.getLocalOrFromServer(t)}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const td=f.gql`
2488
2488
  query GetLoggedInCustomer($email: String!) {
2489
2489
  customer(emailAddress: $email) {
2490
2490
  id
2491
2491
  defaultTemplateBundleId
2492
2492
  }
2493
2493
  }
2494
- `,cn=f.gql`
2494
+ `,an=f.gql`
2495
2495
  query GetCustomerTransactions(
2496
2496
  $id: String!
2497
2497
  $limit: Int!
@@ -2528,21 +2528,21 @@
2528
2528
  total
2529
2529
  }
2530
2530
  }
2531
- `,md=f.gql`
2531
+ `,ed=f.gql`
2532
2532
  mutation SetTransactionDesignName($id: String!, $name: String!) {
2533
2533
  transactionUpdate(id: $id, designName: $name) {
2534
2534
  id
2535
2535
  designName
2536
2536
  }
2537
2537
  }
2538
- `,pd=f.gql`
2538
+ `,ad=f.gql`
2539
2539
  mutation DuplicateTransaction($id: String!, $template: Boolean!) {
2540
2540
  transactionDuplicate(id: $id, template: $template) {
2541
2541
  id
2542
2542
  workflowViewerLink
2543
2543
  }
2544
2544
  }
2545
- `,fd=f.gql`
2545
+ `,nd=f.gql`
2546
2546
  query GetCustomerBundles($id: String!, $limit: Int!, $offset: Int!) {
2547
2547
  customerBundlesFeed(id: $id, limit: $limit, offset: $offset) {
2548
2548
  items {
@@ -2557,7 +2557,7 @@
2557
2557
  total
2558
2558
  }
2559
2559
  }
2560
- `,Cd=f.gql`
2560
+ `,id=f.gql`
2561
2561
  query GetTransactionsForBundle($id: String!) {
2562
2562
  bundles(ids: [$id]) {
2563
2563
  id
@@ -2578,21 +2578,21 @@
2578
2578
  }
2579
2579
  }
2580
2580
  }
2581
- `,wd=f.gql`
2581
+ `,rd=f.gql`
2582
2582
  mutation SetBundleName($id: String!, $name: String!) {
2583
2583
  bundleUpdate(id: $id, name: $name) {
2584
2584
  id
2585
2585
  name
2586
2586
  }
2587
2587
  }
2588
- `,yd=f.gql`
2588
+ `,sd=f.gql`
2589
2589
  mutation DuplicateBundle($id: String!, $template: Boolean!) {
2590
2590
  bundleDuplicate(id: $id, template: $template) {
2591
2591
  id
2592
2592
  workflowViewerLink
2593
2593
  }
2594
2594
  }
2595
- `,Sd=f.gql`
2595
+ `,od=f.gql`
2596
2596
  query GetBundleTemplates($id: String!, $limit: Int!, $offset: Int!) {
2597
2597
  customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: true) {
2598
2598
  items {
@@ -2605,7 +2605,7 @@
2605
2605
  total
2606
2606
  }
2607
2607
  }
2608
- `,vd=async(i,t,e)=>await y.getShadowGraphqlClient().mutate({mutation:wd,errorPolicy:"all",variables:{id:i,name:t},context:e}),Ed=async(i,t)=>await y.getShadowGraphqlClient().mutate({mutation:md,errorPolicy:"all",variables:{id:i,name:t}}),bd=async(i,t)=>await y.getShadowGraphqlClient().mutate({mutation:yd,errorPolicy:"all",variables:{id:i,template:t}}),Id=async(i,t)=>await y.getShadowGraphqlClient().mutate({mutation:pd,errorPolicy:"all",variables:{id:i,template:t}}),Bd=async i=>(await y.getShadowGraphqlClient().query({query:gd,errorPolicy:"all",variables:{email:i}})).data.customer,Pd=async(i,t,e)=>await y.getShadowGraphqlClient().query({query:fd,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,offset:e,limit:t}}),xd=async(i,t)=>await y.getShadowGraphqlClient().query({query:Cd,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:t}),Fd=async(i,t,e)=>(await y.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,quicksearch:"",filters:{link:"and",status:{operator:"isAnyOf",values:["Created","DesignCompleted","ExternallyOrdered"]},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],Dd=async(i,t,e)=>(await y.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,quicksearch:"",filters:{link:"and",status:{operator:"equals",value:"Ordered"},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],kd=async(i,t,e)=>(await y.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,quicksearch:"",filters:{link:"and",template:{value:"true"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],Md=async(i,t,e)=>(await y.getShadowGraphqlClient().query({query:Sd,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,offset:e,limit:t}}))?.data.customerBundlesFeed?.items||[];(function(){try{if(typeof document<"u"){var i=document.createElement("style");i.appendChild(document.createTextNode("#spiffThemeWrapper{width:100%;height:100%}")),document.head.appendChild(i)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();var pr=(i=>(i.Manual="Manual",i.OnStart="OnStart",i.OnQuit="OnQuit",i.OnEnd="OnEnd",i))(pr||{}),Zt=(i=>(i.Email="Email",i.FirstName="FirstName",i.LastName="LastName",i.Phone="Phone",i.Apartment="Apartment",i.City="City",i.Country="Country",i.OrganizationName="OrganizationName",i.PostCode="PostCode",i.State="State",i.StreetAddress="StreetAddress",i.Custom="Custom",i))(Zt||{}),K;K={__e:function(i,t,e,a){for(var n,r,o;t=t.__;)if((n=t.__c)&&!n.__)try{if((r=n.constructor)&&r.getDerivedStateFromError!=null&&(n.setState(r.getDerivedStateFromError(i)),o=n.__d),n.componentDidCatch!=null&&(n.componentDidCatch(i,a||{}),o=n.__d),o)return n.__E=n}catch(s){i=s}throw i}},typeof Promise=="function"&&Promise.prototype.then.bind(Promise.resolve());var st,fa,Tn,fr=[],Ca=[],Nn=K.__b,Qn=K.__r,On=K.diffed,Rn=K.__c,$n=K.unmount;function Td(){for(var i;i=fr.shift();)if(i.__P&&i.__H)try{i.__H.__h.forEach(Fe),i.__H.__h.forEach(Ra),i.__H.__h=[]}catch(t){i.__H.__h=[],K.__e(t,i.__v)}}K.__b=function(i){st=null,Nn&&Nn(i)},K.__r=function(i){Qn&&Qn(i);var t=(st=i.__c).__H;t&&(fa===st?(t.__h=[],st.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.__V=Ca,e.__N=e.i=void 0})):(t.__h.forEach(Fe),t.__h.forEach(Ra),t.__h=[])),fa=st},K.diffed=function(i){On&&On(i);var t=i.__c;t&&t.__H&&(t.__H.__h.length&&(fr.push(t)!==1&&Tn===K.requestAnimationFrame||((Tn=K.requestAnimationFrame)||Nd)(Td)),t.__H.__.forEach(function(e){e.i&&(e.__H=e.i),e.__V!==Ca&&(e.__=e.__V),e.i=void 0,e.__V=Ca})),fa=st=null},K.__c=function(i,t){t.some(function(e){try{e.__h.forEach(Fe),e.__h=e.__h.filter(function(a){return!a.__||Ra(a)})}catch(a){t.some(function(n){n.__h&&(n.__h=[])}),t=[],K.__e(a,e.__v)}}),Rn&&Rn(i,t)},K.unmount=function(i){$n&&$n(i);var t,e=i.__c;e&&e.__H&&(e.__H.__.forEach(function(a){try{Fe(a)}catch(n){t=n}}),e.__H=void 0,t&&K.__e(t,e.__v))};var Un=typeof requestAnimationFrame=="function";function Nd(i){var t,e=function(){clearTimeout(a),Un&&cancelAnimationFrame(t),setTimeout(i)},a=setTimeout(e,100);Un&&(t=requestAnimationFrame(e))}function Fe(i){var t=st,e=i.__c;typeof e=="function"&&(i.__c=void 0,e()),st=t}function Ra(i){var t=st;i.__c=i.__(),st=t}const Cr=f.gql`
2608
+ `,ld=async(i,t,e)=>await y.getShadowGraphqlClient().mutate({mutation:rd,errorPolicy:"all",variables:{id:i,name:t},context:e}),cd=async(i,t)=>await y.getShadowGraphqlClient().mutate({mutation:ed,errorPolicy:"all",variables:{id:i,name:t}}),dd=async(i,t)=>await y.getShadowGraphqlClient().mutate({mutation:sd,errorPolicy:"all",variables:{id:i,template:t}}),ud=async(i,t)=>await y.getShadowGraphqlClient().mutate({mutation:ad,errorPolicy:"all",variables:{id:i,template:t}}),Ad=async i=>(await y.getShadowGraphqlClient().query({query:td,errorPolicy:"all",variables:{email:i}})).data.customer,hd=async(i,t,e)=>await y.getShadowGraphqlClient().query({query:nd,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,offset:e,limit:t}}),gd=async(i,t)=>await y.getShadowGraphqlClient().query({query:id,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:t}),md=async(i,t,e)=>(await y.getShadowGraphqlClient().query({query:an,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,quicksearch:"",filters:{link:"and",status:{operator:"isAnyOf",values:["Created","DesignCompleted","ExternallyOrdered"]},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],pd=async(i,t,e)=>(await y.getShadowGraphqlClient().query({query:an,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,quicksearch:"",filters:{link:"and",status:{operator:"equals",value:"Ordered"},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],fd=async(i,t,e)=>(await y.getShadowGraphqlClient().query({query:an,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,quicksearch:"",filters:{link:"and",template:{value:"true"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],Cd=async(i,t,e)=>(await y.getShadowGraphqlClient().query({query:od,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i,offset:e,limit:t}}))?.data.customerBundlesFeed?.items||[],ir=f.gql`
2609
2609
  fragment AddressValidationResultFields on AddressValidationResult {
2610
2610
  addressComplete
2611
2611
  address {
@@ -2627,8 +2627,8 @@
2627
2627
  }
2628
2628
  missingComponentTypes
2629
2629
  }
2630
- `,dn=f.gql`
2631
- ${Cr}
2630
+ `,nn=f.gql`
2631
+ ${ir}
2632
2632
  fragment AddressValidationJobFields on AddressValidationJob {
2633
2633
  id
2634
2634
  entityId
@@ -2639,15 +2639,15 @@
2639
2639
  ...AddressValidationResultFields
2640
2640
  }
2641
2641
  }
2642
- `,Qd=f.gql`
2643
- ${dn}
2642
+ `,wd=f.gql`
2643
+ ${nn}
2644
2644
  query GetAddressValidationJobs($ids: [String!]!) {
2645
2645
  addressValidationJobs(ids: $ids) {
2646
2646
  ...AddressValidationJobFields
2647
2647
  }
2648
2648
  }
2649
- `,Od=f.gql`
2650
- ${dn}
2649
+ `,yd=f.gql`
2650
+ ${nn}
2651
2651
  query GetRecipientsWithAddressValidationJobs($ids: [String!]!) {
2652
2652
  recipients(ids: $ids) {
2653
2653
  id
@@ -2656,27 +2656,27 @@
2656
2656
  }
2657
2657
  }
2658
2658
  }
2659
- `,Rd=f.gql`
2660
- ${Cr}
2659
+ `,Sd=f.gql`
2660
+ ${ir}
2661
2661
  mutation ValidateRecipientAddress($id: String!) {
2662
2662
  recipientValidate(id: $id) {
2663
2663
  ...AddressValidationResultFields
2664
2664
  }
2665
2665
  }
2666
- `,$d=f.gql`
2667
- ${dn}
2666
+ `,vd=f.gql`
2667
+ ${nn}
2668
2668
  mutation BatchValidateRecipientAddress($ids: [String!]!) {
2669
2669
  recipientValidateBatch(ids: $ids) {
2670
2670
  ...AddressValidationJobFields
2671
2671
  }
2672
2672
  }
2673
- `,Ud=f.gql`
2673
+ `,Ed=f.gql`
2674
2674
  mutation OverrideRecipientAddress($id: String!) {
2675
2675
  recipientOverrideAddress(id: $id) {
2676
2676
  id
2677
2677
  }
2678
2678
  }
2679
- `;var wr=(i=>(i.Confirmed="Confirmed",i.Plausible="Plausible",i.Unlikely="Unlikely",i))(wr||{}),yr=(i=>(i.Created="Created",i.Processing="Processing",i.Completed="Completed",i.Failed="Failed",i.Cancelled="Cancelled",i))(yr||{});const Vd=async i=>{const t=i.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().query({query:Od,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return i.map(a=>{const n=a.getTransaction().recipient?.id;if(n)return e.data?.recipients?.find(r=>r.id===n)?.addressValidationJob})},Ld=async i=>(await y.getShadowGraphqlClient().query({query:Qd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:i}})).data?.addressValidationJobs,zd=async i=>i.getTransaction().recipient?.id?(await y.getShadowGraphqlClient().mutate({mutation:Rd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i.getTransaction().recipient.id}})).data?.recipientValidate:void 0,qd=async i=>{const t=i.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().mutate({mutation:$d,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return i.map(a=>{const n=a.getTransaction().recipient?.id;if(n)return e.data?.recipientValidateBatch?.find(r=>r.entityId===n)})},Gd=async i=>{const t=i.getTransaction().recipient?.id;if(!t)return;(await y.getShadowGraphqlClient().mutate({mutation:Ud,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:t}})).data?.recipientOverrideAddress?.id&&(i.getTransaction().addressValidationStatus=Ua.Overridden)},jd=f.gql`
2679
+ `;var rr=(i=>(i.Confirmed="Confirmed",i.Plausible="Plausible",i.Unlikely="Unlikely",i))(rr||{}),sr=(i=>(i.Created="Created",i.Processing="Processing",i.Completed="Completed",i.Failed="Failed",i.Cancelled="Cancelled",i))(sr||{});const bd=async i=>{const t=i.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().query({query:yd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return i.map(a=>{const n=a.getTransaction().recipient?.id;if(n)return e.data?.recipients?.find(r=>r.id===n)?.addressValidationJob})},Id=async i=>(await y.getShadowGraphqlClient().query({query:wd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:i}})).data?.addressValidationJobs,Bd=async i=>i.getTransaction().recipient?.id?(await y.getShadowGraphqlClient().mutate({mutation:Sd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i.getTransaction().recipient.id}})).data?.recipientValidate:void 0,Pd=async i=>{const t=i.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().mutate({mutation:vd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return i.map(a=>{const n=a.getTransaction().recipient?.id;if(n)return e.data?.recipientValidateBatch?.find(r=>r.entityId===n)})},xd=async i=>{const t=i.getTransaction().recipient?.id;if(!t)return;(await y.getShadowGraphqlClient().mutate({mutation:Ed,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:t}})).data?.recipientOverrideAddress?.id&&(i.getTransaction().addressValidationStatus=Ta.Overridden)},Fd=f.gql`
2680
2680
  query GetIntegrationProductsForIds($ids: [String!]!) {
2681
2681
  integrationProducts(ids: $ids) {
2682
2682
  id
@@ -2686,5 +2686,5 @@
2686
2686
  }
2687
2687
  }
2688
2688
  }
2689
- `,Hd=async i=>(await y.getShadowGraphqlClient().query({query:jd,variables:{ids:i}})).data.integrationProducts;exports.AddonHandle=Ue;exports.AddressValidationJobStatus=yr;exports.AddressValidationResultConfirmationLevel=wr;exports.AddressValidationStatus=Ua;exports.ArrayInput=Kc;exports.AspectType=z;exports.AssetNotFoundError=St;exports.AssetType=ne;exports.BringForwardCommand=Zs;exports.BringToBackCommand=Xs;exports.BringToFrontCommand=_s;exports.BundleDesignCreationCartAddMode=jn;exports.CanvasCommand=$;exports.CollectionProduct=Jt;exports.ColorOptionGlobalPropertyHandle=Na;exports.CommandContext=Ii;exports.ConversionDataType=Zt;exports.ConversionLocation=pr;exports.CreateElementCommand=H;exports.CreateLayoutCommand=Ja;exports.CurrencyContext=sr;exports.CurrencyService=or;exports.DeleteElementCommand=Dt;exports.DigitalContentStepHandle=Yi;exports.FileUploadGlobalPropertyHandle=Xi;exports.FlowExecutionNodeResult=Kt;exports.FlowExecutionResult=ir;exports.FlowService=nr;exports.FontAlignmentCommand=ki;exports.FontColorCommand=Fi;exports.FontSizeCommand=Di;exports.FontSourceCommand=ka;exports.FrameService=hr;exports.FrameStep=gr;exports.FrameStepHandle=mr;exports.GlobalPropertyHandle=ea;exports.GroupCommand=U;exports.IllustrationStepHandle=Vi;exports.InformationMessageType=pe;exports.InformationStepHandle=Wi;exports.IntegrationProduct=Oa;exports.IntegrationType=Wn;exports.LayoutElementFactory=qs;exports.LayoutElementType=D;exports.LayoutNotFoundError=J;exports.LayoutRenderingPurpose=Ot;exports.MaterialStepHandle=Li;exports.MisconfigurationError=lt;exports.MockWorkflowManager=hd;exports.ModelStepHandle=zi;exports.ModuleStepHandle=Ji;exports.MoveCommand=Gs;exports.ObjectInput=sn;exports.ObjectInputType=rr;exports.OptionGlobalPropertyHandle=nn;exports.OptionNotFoundError=ie;exports.ParseError=Pt;exports.PictureStepHandle=qi;exports.ProductCameraRig=Yn;exports.ProductCollection=rn;exports.ProductCollectionProductSortKey=ar;exports.ProductWorkflow=Qt;exports.PromiseCache=oe;exports.PromiseQueue=_e;exports.QuestionStepHandle=Gi;exports.QueueablePromise=Ke;exports.ResizeCommand=Hs;exports.ResourceNotFoundError=Rt;exports.RotateCommand=js;exports.ScaleAxis=Y;exports.SendBackwardsCommand=tl;exports.ShapeStepHandle=ji;exports.ShareActionType=Hn;exports.SpiffCommerceClient=rd;exports.StakeholderType=Va;exports.StepAspectType=Gn;exports.StepHandle=Z;exports.StepType=E;exports.TextAlgorithm=xt;exports.TextChangeCommand=Mi;exports.TextGlobalPropertyHandle=Zi;exports.TextInput=Jc;exports.TextStepHandle=Hi;exports.UnhandledBehaviorError=O;exports.UnitOfMeasurement=Jn;exports.UpdateImageSourceCommand=Js;exports.Variant=nt;exports.WorkflowExperienceEventType=Re;exports.WorkflowExperienceImpl=_i;exports.amtChannelsForAspect=tr;exports.assetService=G;exports.browserColorToHex=ri;exports.cmPerPixel=Bs;exports.currentDirection=Es;exports.dataUrlFromExternalUrl=Xr;exports.deleteBundle=ud;exports.designService=xe;exports.determineCorrectFontSizeAndLines=Xt;exports.digitalContentStepService=Ka;exports.domParser=ct;exports.duplicateBundle=bd;exports.duplicateTransaction=Id;exports.fetchAsString=et;exports.findAngle=ps;exports.findElement=V;exports.findPmsColors=Co;exports.frameDataCache=Mt;exports.frameStepService=pt;exports.generate=N;exports.generateCommands=Ri;exports.generateSVGWithUnknownColors=rt;exports.generateStateFromDesignInputSteps=Ol;exports.getAddressValidationJobs=Ld;exports.getAttributesFromArrayBuffer=ue;exports.getAxisAlignedBoundingBox=ms;exports.getBoundedOffsets=Ar;exports.getBundleIdForTransaction=Ad;exports.getBundleThemeConfiguration=ld;exports.getCustomer=Bd;exports.getCustomerBundles=Pd;exports.getElementVertices=bs;exports.getFrameData=me;exports.getGlobalPropertyStateForBundle=Vl;exports.getIntegration=cr;exports.getIntegrationProducts=Hd;exports.getNEPoint=Ss;exports.getNWPoint=ys;exports.getOrderedTransactions=Dd;exports.getOverrideThemeConfiguration=sd;exports.getPointOfRotation=ws;exports.getProductCollections=qc;exports.getSEPoint=vs;exports.getSvgElement=Xe;exports.getTemplateBundles=Md;exports.getTemplateTransactions=kd;exports.getTransaction=od;exports.getTransactionThemeConfiguration=cd;exports.getTransactionsForBundle=xd;exports.getTransformedAssetURL=We;exports.getTrueCoordinates=Cs;exports.getUnorderedTransactions=Fd;exports.getValidationJobsForWorkflowExperiences=Vd;exports.getWorkflow=lr;exports.getWorkflows=ln;exports.graphQlManager=y;exports.illustrationStepService=_t;exports.isCloseToValue=fs;exports.loadFont=Ft;exports.matchHexToPms=mo;exports.materialStepService=_a;exports.metafieldManager=$e;exports.mmPerPixel=Is;exports.modelStepService=Xa;exports.modifySVGColors=He;exports.moduleStepService=Za;exports.nameBundle=vd;exports.nameTransaction=Ed;exports.optionService=I;exports.outlineFontsInSvg=ks;exports.overrideWorkflowExperienceRecipientAddress=Gd;exports.patternImageDataCache=ht;exports.persistenceService=Q;exports.pictureStepService=tn;exports.pmsToRgb=go;exports.questionStepService=en;exports.registerFetchImplementation=Wr;exports.registerWindowImplementation=Hr;exports.rehydrateSerializedLayout=Da;exports.rgbToPms=ii;exports.rotateAroundPoint=Yt;exports.sanitizeSvgTree=je;exports.setBearerAuthenticationToken=ai;exports.setCanvasModule=za;exports.shapeStepService=Tt;exports.shortenUrl=Ti;exports.spiffCoreConfiguration=gt;exports.stepAspectValuesToDesignInputSteps=Ql;exports.svgColorValueToDefinition=Ba;exports.svgStringDimensions=Ya;exports.svgToDataUrl=Ge;exports.textStepService=W;exports.toast=Qi;exports.validateWorkflowExperienceRecipient=zd;exports.validateWorkflowExperienceRecipients=qd;exports.xmlSerializer=It;
2689
+ `,Dd=async i=>(await y.getShadowGraphqlClient().query({query:Fd,variables:{ids:i}})).data.integrationProducts;exports.AddonHandle=Oe;exports.AddressValidationJobStatus=sr;exports.AddressValidationResultConfirmationLevel=rr;exports.AddressValidationStatus=Ta;exports.ArrayInput=Oc;exports.AspectType=z;exports.AssetNotFoundError=wt;exports.AssetType=ee;exports.BringForwardCommand=Uo;exports.BringToBackCommand=$o;exports.BringToFrontCommand=Ro;exports.BundleDesignCreationCartAddMode=Mn;exports.CanvasCommand=$;exports.CollectionProduct=Ht;exports.ColorOptionGlobalPropertyHandle=Fa;exports.CommandContext=hi;exports.ConversionDataType=Jt;exports.CreateElementCommand=W;exports.CreateLayoutCommand=qa;exports.CurrencyContext=Ji;exports.CurrencyService=Yi;exports.DeleteElementCommand=xt;exports.DigitalContentStepHandle=Oi;exports.FileUploadGlobalPropertyHandle=Vi;exports.FlowExecutionNodeResult=Yt;exports.FlowExecutionResult=Wi;exports.FlowService=ji;exports.FontAlignmentCommand=wi;exports.FontColorCommand=fi;exports.FontSizeCommand=Ci;exports.FontSourceCommand=Ba;exports.FrameService=er;exports.FrameStep=ar;exports.FrameStepHandle=nr;exports.GlobalPropertyHandle=Ze;exports.GroupCommand=U;exports.IllustrationStepHandle=xi;exports.InformationMessageType=ge;exports.InformationStepHandle=Qi;exports.IntegrationProduct=ka;exports.IntegrationType=Nn;exports.LayoutElementFactory=Fo;exports.LayoutElementType=D;exports.LayoutNotFoundError=J;exports.LayoutRenderingPurpose=Nt;exports.MaterialStepHandle=Fi;exports.MisconfigurationError=st;exports.MockWorkflowManager=_c;exports.ModelStepHandle=Di;exports.ModuleStepHandle=Ri;exports.MoveCommand=Do;exports.ObjectInput=tn;exports.ObjectInputType=Hi;exports.OptionGlobalPropertyHandle=Xa;exports.OptionNotFoundError=ae;exports.ParseError=It;exports.PictureStepHandle=ki;exports.ProductCameraRig=Qn;exports.ProductCollection=Za;exports.ProductCollectionProductSortKey=Gi;exports.ProductWorkflow=Tt;exports.PromiseCache=ie;exports.PromiseQueue=Ye;exports.QuestionStepHandle=Mi;exports.QueueablePromise=He;exports.ResizeCommand=Mo;exports.ResourceNotFoundError=Qt;exports.RotateCommand=ko;exports.ScaleAxis=Y;exports.SendBackwardsCommand=Vo;exports.ShapeStepHandle=Ti;exports.ShareActionType=Tn;exports.SpiffCommerceClient=jc;exports.StakeholderType=Na;exports.StepAspectType=kn;exports.StepHandle=Z;exports.StepType=E;exports.TextAlgorithm=Bt;exports.TextChangeCommand=yi;exports.TextGlobalPropertyHandle=Li;exports.TextInput=Qc;exports.TextStepHandle=Ni;exports.UnhandledBehaviorError=O;exports.UnitOfMeasurement=On;exports.UpdateImageSourceCommand=Qo;exports.Variant=at;exports.WorkflowExperienceEventType=Ne;exports.WorkflowExperienceImpl=Ui;exports.amtChannelsForAspect=zi;exports.assetService=G;exports.browserColorToHex=Wn;exports.cmPerPixel=Ao;exports.currentDirection=lo;exports.dataUrlFromExternalUrl=Ur;exports.deleteBundle=Xc;exports.designService=Be;exports.determineCorrectFontSizeAndLines=Xt;exports.digitalContentStepService=Ga;exports.domParser=ot;exports.duplicateBundle=dd;exports.duplicateTransaction=ud;exports.fetchAsString=tt;exports.findAngle=eo;exports.findElement=V;exports.findPmsColors=is;exports.frameDataCache=Dt;exports.frameStepService=gt;exports.generate=N;exports.generateCommands=Ii;exports.generateSVGWithUnknownColors=it;exports.generateStateFromDesignInputSteps=vl;exports.getAddressValidationJobs=Id;exports.getAttributesFromArrayBuffer=ce;exports.getAxisAlignedBoundingBox=to;exports.getBoundedOffsets=tr;exports.getBundleIdForTransaction=Zc;exports.getBundleThemeConfiguration=Yc;exports.getCustomer=Ad;exports.getCustomerBundles=hd;exports.getElementVertices=co;exports.getFrameData=he;exports.getGlobalPropertyStateForBundle=Bl;exports.getIntegration=Xi;exports.getIntegrationProducts=Dd;exports.getNEPoint=so;exports.getNWPoint=ro;exports.getOrderedTransactions=pd;exports.getOverrideThemeConfiguration=Hc;exports.getPointOfRotation=io;exports.getProductCollections=Fc;exports.getSEPoint=oo;exports.getSvgElement=Je;exports.getTemplateBundles=Cd;exports.getTemplateTransactions=fd;exports.getTransaction=Wc;exports.getTransactionThemeConfiguration=Jc;exports.getTransactionsForBundle=gd;exports.getTransformedAssetURL=Ge;exports.getTrueCoordinates=no;exports.getUnorderedTransactions=md;exports.getValidationJobsForWorkflowExperiences=bd;exports.getWorkflow=Ki;exports.getWorkflows=en;exports.graphQlManager=y;exports.illustrationStepService=Kt;exports.isCloseToValue=ao;exports.loadFont=Pt;exports.matchHexToPms=es;exports.materialStepService=ja;exports.metafieldManager=Qe;exports.mmPerPixel=uo;exports.modelStepService=Wa;exports.modifySVGColors=qe;exports.moduleStepService=Ha;exports.nameBundle=ld;exports.nameTransaction=cd;exports.optionService=I;exports.outlineFontsInSvg=fo;exports.overrideWorkflowExperienceRecipientAddress=xd;exports.patternImageDataCache=ut;exports.persistenceService=Q;exports.pictureStepService=Ya;exports.pmsToRgb=ts;exports.questionStepService=Ja;exports.registerFetchImplementation=Nr;exports.registerWindowImplementation=Tr;exports.rehydrateSerializedLayout=Ia;exports.rgbToPms=jn;exports.rotateAroundPoint=Wt;exports.sanitizeSvgTree=ze;exports.setBearerAuthenticationToken=qn;exports.setCanvasModule=Oa;exports.shapeStepService=kt;exports.shortenUrl=Si;exports.spiffCoreConfiguration=At;exports.stepAspectValuesToDesignInputSteps=Sl;exports.svgColorValueToDefinition=Sa;exports.svgStringDimensions=za;exports.svgToDataUrl=Le;exports.textStepService=H;exports.toast=Ei;exports.validateWorkflowExperienceRecipient=Bd;exports.validateWorkflowExperienceRecipients=Pd;exports.xmlSerializer=Et;
2690
2690
  //# sourceMappingURL=index.cjs.map