@spiffcommerce/core 37.0.1 → 37.0.2

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
@@ -1379,7 +1379,7 @@
1379
1379
  fill="${e.color}"
1380
1380
  />
1381
1381
  </svg>
1382
- `,i={};i["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Gt(t,D.Illustration),o=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:i,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||zt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Gt(t,D.Illustration,e.src),i=await rt(await Ii(e.src)),r=await re(i.svg),o=N();return{cachedObjectURL:r,stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:i.colors,id:o,src:e.src,svg:i.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||zt(t,a.layer||0),immutable:a.immutable}}}class z extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,z.prototype)}}const V=(n,t)=>_(n,t).elements.find(i=>i.id===n),_=(n,t)=>{const e=Object.values(t).find(a=>a.elements.some(i=>i.id===n));if(!e)throw new z;return e},tt=(n,t)=>{const e=[...t.elements.filter(i=>i.id!==n.id),n],a=La(e);return{layout:t.layout,elements:a,modificationID:N()}},ba=async n=>{const t=[...Object.keys(n.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const i=e[a],r=n.layouts[i];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=$a(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 n.layouts){const i=n.layouts[a].elements.filter(o=>o.type===D.Illustration);for(let o=0;o<i.length;++o){const s=i[o];if(s.src&&s.svg)try{s.cachedObjectURL=await re(s.svg)}catch(l){console.log(l)}}const r=n.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 Sn extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class qs 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 z;const a={...e,x:this.x,y:this.y},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class zs 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 z;const a={...e,rotation:this.angle},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Gs 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 z;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=ue(o,s,e)}const i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.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 G 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 i=e[e.length-1],r=i.productOverlay?i: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(i=>(i.layer||0)===(t.layer||0)).sort((i,r)=>(i.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 i={};return a.forEach(r=>{i[r.layout.id]=r}),{...t,layouts:i}}}class Bi 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 z;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class sa 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 z;const a={...e,textFillImage:this.imageFill},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Pi 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 z;const a={...e,fontSize:this.size},i=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ue(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class Ia 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 z;const a={...e,fontData:this.fontData},i=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ue(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class xi 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 z;const a={...e,align:this.align},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class js 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),i=e.elements[a].pattern,r=[...e.elements];r.splice(a,1,{...e.elements[a],pattern:{...i,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 Hs extends ${constructor(t,e,a,i,r){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=i,this.thresholdSaturation=r}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Ws 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 z;const a={...e,src:this.src},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Fi 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 z;const a=_(e.id,Object.values(t.layouts)),i=tt(ue(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:i}}}}class la 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 z;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Ba 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 z;const a=e.colors||{},i=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:i?.spotColor,pmsValue:i?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:i?.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 Ys 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 z;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Js extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;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 i=a.elements.findIndex(o=>o.id===this.id);a.elements.push(a.elements.splice(i,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 Ks 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 z;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 i=a.elements.findIndex(s=>s.id===this.id);a.elements.splice(i,1),a.elements.unshift(e);const r=[...a.elements],o=r.splice(i,1)[0];return r.splice(i,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 _s extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;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 i=a.elements.findIndex(l=>l.id===this.id),r=i+1,o=[...a.elements],s=o.splice(i,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 Xs extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;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 i=a.elements.findIndex(l=>l.id===this.id),r=i-1,o=[...a.elements],s=o.splice(i,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 vn{constructor(t,e,a){this.processRegion=async i=>{const r=this.layouts.find(l=>l.panelId===i.panelId);if(!r)throw new Y(i);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:i.top,x:i.left,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,rotation:i.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:i},command:new G(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 re(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y:i.top,x:i.left,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,rotation:i.rotation,immutable:i.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:u.id,region:i},command:new G(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 Y(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 Di=async n=>{const t=`${ht.getServicesApiUrl()}/shortener`;try{return(await(await it(t,{method:"POST",body:JSON.stringify({longUrl:n}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new $e("Failed to shorten URL, see console.")}};class ki{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,i=3e3,r=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=i,this.maxAttempts=r,this.poll()}}class Zs{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const i=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=i?.storage?.videoShortUrl,d=i?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,i){const r=async()=>{const h=(await xe([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new ki(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=i.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(s+i.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 $e("Cannot create QR code, URL too long.");const d=await Di(c);if(!i.data||!i.data.regions)throw new lt(i,"Missing regions.");const u=await this.regionElements(i),A=await this.command(d,u,a,i.stepName);return A&&(A.command&&a.getCommandDispatcher()(A.command),A.followup&&await A.followup()),await a.setSelectionsAndElements(i.stepName,[],u,async()=>{a.updateStorage(i.stepName,{videoShortUrl:d,videoUrl:o.href})}),d}async regionElements(t){const e=(a,i)=>({id:N(),region:a,regionIndex:i});return t.data.regions.map(e)}async command(t,e,a,i){const r=a.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await Un.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 Y(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new G({stepRegion:d,stepRegionIndex:c.regionIndex,stepName:i,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 Ha=new Zs;class ke{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return va(e);const a=t.asset;if(!a)throw new wt(t);const i=a.fileLink;if(i)return et(i,!0);throw new Rt(a)}}async init(t,e,a){const i=a?.serializableWorkflow.steps.find(s=>s.stepName===t.stepName);if(i?.storage&&Object.keys(i.storage).length!==0||i?.selectedVariants&&i.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 s=o.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=s.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(r=(await W.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option&&t.option.variants&&t.option.variants.length>0){const s=t.option,l=await P.getDefaultVariant(s,t.overrideDefaultVariantId);return l?this.selectVariantCommand(t,l,[],e,void 0,r||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,r||t.data.placeholderImageUrl)}async reload(t,e,a){const i=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}));if(!t.option||(t.option.variants||[]).length===0){const c=t.data.regions.map(d=>va(d));e.updateStorage(t.stepName,{currentFrameSources:c})}if(i){const c=async()=>{const d=i.storage?.colors,u=i.storage?.framePatternSrc,A=i.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:A,framePatternSrc:u}),u){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,h,!0,d),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(A?.some(h=>h.zoom)){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");h.updateOffsets(A)}e.setMandatoryFulfilled(t.stepName,!0)};if(i.selectedVariants&&i.selectedVariants.length>0){const d=i.selectedVariants[0].id;if(t.option&&d){const u=t.option.variants?.find(A=>A.id===d);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const A=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(u,h)));e.updateStorage(t.stepName,{currentFrameSources:A}),await c()})}}else await e.setSelectionsAndElements(t.stepName,[],l,c)}}async availableColors(t,e){return(await P.ensureFullOption(t.data.colorOption))?.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name}))??[]}selectImage(t,e,a,i=!0){const r=ke.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 ki(async()=>{const d=(await W.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{W.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,i).then(l)})},()=>{throw new $e("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,i)}async selectVariant(t,e,a,i,r){const o=await this.selectVariantCommand(t,e,a,i,r);o&&(o.command&&i.getCommandDispatcher()(o.command),o.followup&&await o.followup())}getCreateElementCommand(t,e,a,i,r){return new G({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},i)}async loadPatternFromString(t,e,a=!0,i=void 0,r){if(t.endsWith("svg")){const o=await za(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:i??d.colors};At.set(t,u),e.setPatternData(u,a)}else{const o=await Ue(t,!0),s=await ce(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};At.set(t,l),e.setPatternData(l,a)}}async changeColors(t,e,a){const i=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!i||!i.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const r=await this.calculateColorMetadata(i,t,a);e.updateMetadata(t.stepName,{colors:r.metadataColors}),e.updateStorage(t.stepName,{colors:r.storageColors}),i.setPatternData({...i.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 i=a.getImageData()?.colors??{},r=[];for(const o in i){const s=i[o];if(s.pmsValue){const l=s.pmsValue.trim().toLocaleLowerCase();r.includes(l)||r.push(l)}else if(s.browserValue){const l=ai(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 i={...t.getImageData().colors??{}},r={};Object.entries(i).forEach(([l,c])=>{const d={browserValue:c.browserValue};r[l]=d});for(const[l,c]of a.entries())i[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},r[l]=c;let o=Array.from(Object.values(i)).map(l=>l.browserValue);const s=await P.ensureFullOption(e.data.colorOption);return s&&s.variants?.forEach(l=>{o=o.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:i,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,i,r,o){const s=i.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 Ae(l[g]),m=s.getImageData(),f=a.map(I=>new Dt(I.id)),y=m?qa(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:y?.x||0,y:y?.y||0,width:m.width,height:m.height,scaleX:y?.zoom||1,scaleY:y?.zoom||1,rotation:0}:void 0,F=N(),v=i.getLayouts().find(I=>I.panelId===h.panelId);if(!v)throw new Y(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:f}})),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 i.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(i.updateStorage(t.stepName,{currentFrameSources:l}),o){const h=i.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(i=>i.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,i){const r=ke.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,i,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 ke;class tl{async getIllustrationBody(t){return new Promise(e=>{et(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,i,r){return new G({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},i)}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 i=await P.getOptionForStep(t);if(!i)throw new lt(t,"No option configured for illustration step.");if(a)return await this.reload(t,e,a);{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantCommand(t,r,[],e)}return null}async reload(t,e,a){const i=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 P.getOptionForStep(t);if(i?.selectedVariants){const c=i.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:i.storage?.colors})})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=await P.ensureFullOption(t.data.colorOption);return a?a?a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})):[]:[]}async changeColorsCommand(t,e,a,i,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=$a(t,e,a,o),l=await re(s),c=[];for(const d of i){for(const[u,A]of r.entries())c.push(new Ba(d,u,A));c.push(new Ys(d,s,l))}return new U(c)}async changeColors(t,e,a,i){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 i.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 P.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,i,r){i(!0);try{const o=await this.selectVariantCommand(t,e,a,r);o&&(o.command&&r.getCommandDispatcher()(o.command),o.followup&&await o.followup())}finally{i(!1)}}async selectVariantCommand(t,e,a,i){if(!t.data||!t.data.regions)throw new lt(t,"Missing regions.");const r=e.asset;if(!r)throw new wt(e);const o=r.fileLink;if(!o)throw new Rt(r);t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const s=a.map(m=>new Dt(m.id)),l=await rt(await this.getIllustrationBody(o)),c=await re(l.svg),d=(m,f)=>{const y=i.getLayouts().find(F=>F.panelId===m.panelId);if(!y)throw new Y(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:f},command:this.getCreateElementCommand(w,m,f,y,{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 P.ensureFullOption(t.data.colorOption);return p&&p.variants?.forEach(m=>{g=g.map(f=>f.toLowerCase()===m.color?.toLowerCase()?m.name:f)}),i.updateMetadata(t.stepName,{colors:g}),{command:new U(h),followup:async()=>{const m=u.map(y=>y.regionElement);await i.setSelectionsAndElements(t.stepName,[e],m);const f=r.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const y={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=f.find(v=>v.channelNumber===F.number);b&&(y[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,i,new Map(Object.entries(y)))}if(t.data.colorPickerEnabled){const y=await this.availableColors(t,i)||[],w=Object.keys(l.colors),F=y.length===1&&w.length===1;if(F){const b=y[0],v=w[0];await this.changeColors(t,m,i,new Map([[v,b.variant.color]]))}!F&&f.length===0&&await this.changeColors(t,m,i,new Map)}}}}}const Jt=new tl;class el{async init(t,e,a){const i=t.option;if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=t.option;if(!l)throw new ae(t);if(i?.selectedVariants){const c=i.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,i){const r=await this.selectVariantLambda(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,i){const r=a.getModelContainer();i(!0);const o=e.material;if(!o)throw i(!1),new wt(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{i(!1)}})}}}}const Wa=new el;class al{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const i=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 P.getOptionForStep(t);if(i?.selectedVariants){const c=i.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 wt(d);await A.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1)}})}}}}async selectVariant(t,e,a,i){const r=await this.selectVariantLambda(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,i){i(!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 o=a.getModelContainer();o&&await o.applyModelVariant(t.stepName,{model:r,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1)}finally{i(!1)}})}}}}const Ya=new al;class nl{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 i=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:i?.storage?.text}),e.setMandatoryFulfilled(t.stepName,i?.storage?.text!=="")})}async changeText(t,e,a,i){const r=await this.changeTextCommand(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,a,i){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,i);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(y=>y.panelId===u.panelId);if(!m)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Dt(g)),f.push(new G({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(f)}};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,i){if(t.data&&t.data.maxLength){const o=t.data.maxLength;if(e.length>o)return i("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return i("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const r=ma.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 i("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return i(""),{input:e,helperData:{}}}}const Ja=new nl;class il{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"Missing option for picture step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,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 i=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 P.getOptionForStep(t);if(i?.selectedVariants){const c=i.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,i){const r=await this.selectVariantCommand(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,a,i){const r=e.asset;if(!r)throw new wt(e);const o=r?.fileLink;if(!o)return console.error("No URL for picture!"),null;i(!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 Y(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new G({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()=>{i(!1)})}}}}const Ka=new il;class rl{async init(t,e,a){const i=t.option;if(!i)throw new lt(t,"Missing option for question step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return this.selectVariantLambda(t,r.id||"",e)}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),r=await P.getOptionForStep(t);if(i?.selectedVariants){const o=i.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 i=await this.selectVariantLambda(t,e,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"Missing option for question step");const r=i.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 ${i.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[o],[])}}}}const _a=new rl;class ol{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=await P.getOptionForStep(t);return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const i=a.getLayouts(),o=(a.getRegionElements(e.stepName)||[]).map(s=>{const l=s.region;if(!i.find(d=>d.panelId===l?.panelId))throw new Y(l);return new Ba(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 i=await P.getOptionForStep(t);if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);return r?this.selectVariantCommand(t,{fill:r.color,stroke:r.color,variant:r},[],e):null}return null}async selectVariant(t,e,a,i){const r=await this.selectVariantCommand(t,e,a,i);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async reload(t,e,a){const i=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 P.getOptionForStep(t);if(i?.selectedVariants){const c=i.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:i?.storage?.colour||""})})}}}}async selectVariantCommand(t,e,a,i){const r=i.getLayouts(),o=i.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 Y(u);const h=s();return new Ba(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new U(c),followup:async()=>{await i.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),i.updateStorage(t.stepName,{colour:s()})}}}else{const l=(A,h)=>{const g=r.find(w=>w.panelId===A.panelId);if(!g)throw new Y(A);const p=s(),m=`
1382
+ `,i={};i["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Gt(t,D.Illustration),o=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:i,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||zt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Gt(t,D.Illustration,e.src),i=await rt(await Ii(e.src)),r=await re(i.svg),o=N();return{cachedObjectURL:r,stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:i.colors,id:o,src:e.src,svg:i.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||zt(t,a.layer||0),immutable:a.immutable}}}class z extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,z.prototype)}}const V=(n,t)=>_(n,t).elements.find(i=>i.id===n),_=(n,t)=>{const e=Object.values(t).find(a=>a.elements.some(i=>i.id===n));if(!e)throw new z;return e},tt=(n,t)=>{const e=[...t.elements.filter(i=>i.id!==n.id),n],a=La(e);return{layout:t.layout,elements:a,modificationID:N()}},ba=async n=>{const t=[...Object.keys(n.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const i=e[a],r=n.layouts[i];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=$a(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 n.layouts){const i=n.layouts[a].elements.filter(o=>o.type===D.Illustration);for(let o=0;o<i.length;++o){const s=i[o];if(s.src&&s.svg)try{s.cachedObjectURL=await re(s.svg)}catch(l){console.log(l)}}const r=n.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 Sn extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class qs 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 z;const a={...e,x:this.x,y:this.y},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class zs 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 z;const a={...e,rotation:this.angle},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Gs 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 z;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=ue(o,s,e)}const i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.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 G 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 i=e[e.length-1],r=i.productOverlay?i: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(i=>(i.layer||0)===(t.layer||0)).sort((i,r)=>(i.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 i={};return a.forEach(r=>{i[r.layout.id]=r}),{...t,layouts:i}}}class Bi 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 z;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class sa 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 z;const a={...e,textFillImage:this.imageFill},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Pi 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 z;const a={...e,fontSize:this.size},i=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ue(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class Ia 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 z;const a={...e,fontData:this.fontData},i=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ue(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class xi 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 z;const a={...e,align:this.align},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class js 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),i=e.elements[a].pattern,r=[...e.elements];r.splice(a,1,{...e.elements[a],pattern:{...i,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 Hs extends ${constructor(t,e,a,i,r){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=i,this.thresholdSaturation=r}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Ws 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 z;const a={...e,src:this.src},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Fi 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 z;const a=_(e.id,Object.values(t.layouts)),i=tt(ue(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:i}}}}class la 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 z;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Ba 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 z;const a=e.colors||{},i=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:i?.spotColor,pmsValue:i?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:i?.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 Ys 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 z;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Js extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;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 i=a.elements.findIndex(o=>o.id===this.id);a.elements.push(a.elements.splice(i,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 Ks 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 z;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 i=a.elements.findIndex(s=>s.id===this.id);a.elements.splice(i,1),a.elements.unshift(e);const r=[...a.elements],o=r.splice(i,1)[0];return r.splice(i,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 _s extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;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 i=a.elements.findIndex(l=>l.id===this.id),r=i+1,o=[...a.elements],s=o.splice(i,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 Xs extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;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 i=a.elements.findIndex(l=>l.id===this.id),r=i-1,o=[...a.elements],s=o.splice(i,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 vn{constructor(t,e,a){this.processRegion=async i=>{const r=this.layouts.find(l=>l.panelId===i.panelId);if(!r)throw new Y(i);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:i.top,x:i.left,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,rotation:i.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:i},command:new G(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 re(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y:i.top,x:i.left,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,rotation:i.rotation,immutable:i.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:u.id,region:i},command:new G(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 Y(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 Di=async n=>{const t=`${ht.getServicesApiUrl()}/shortener`;try{return(await(await it(t,{method:"POST",body:JSON.stringify({longUrl:n}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new $e("Failed to shorten URL, see console.")}};class ki{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,i=3e3,r=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=i,this.maxAttempts=r,this.poll()}}class Zs{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const i=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=i?.storage?.videoShortUrl,d=i?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,i){const r=async()=>{const h=(await xe([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new ki(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=i.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(s+i.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 $e("Cannot create QR code, URL too long.");const d=await Di(c);if(!i.data||!i.data.regions)throw new lt(i,"Missing regions.");const u=await this.regionElements(i),A=await this.command(d,u,a,i.stepName);return A&&(A.command&&a.getCommandDispatcher()(A.command),A.followup&&await A.followup()),await a.setSelectionsAndElements(i.stepName,[],u,async()=>{a.updateStorage(i.stepName,{videoShortUrl:d,videoUrl:o.href})}),d}async regionElements(t){const e=(a,i)=>({id:N(),region:a,regionIndex:i});return t.data.regions.map(e)}async command(t,e,a,i){const r=a.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await Un.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 Y(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new G({stepRegion:d,stepRegionIndex:c.regionIndex,stepName:i,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 Ha=new Zs;class ke{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return va(e);const a=t.asset;if(!a)throw new wt(t);const i=a.fileLink;if(i)return et(i,!0);throw new Rt(a)}}async init(t,e,a){const i=a?.serializableWorkflow.steps.find(s=>s.stepName===t.stepName);if(i?.storage&&Object.keys(i.storage).length!==0||i?.selectedVariants&&i.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 s=o.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=s.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(r=(await W.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option){const s=await P.getDefaultVariant(t.option,t.overrideDefaultVariantId);return s?this.selectVariantCommand(t,s,[],e,void 0,r||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,r||t.data.placeholderImageUrl)}async reload(t,e,a){const i=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}));if(!t.option||(t.option.variants||[]).length===0){const c=t.data.regions.map(d=>va(d));e.updateStorage(t.stepName,{currentFrameSources:c})}if(i){const c=async()=>{const d=i.storage?.colors,u=i.storage?.framePatternSrc,A=i.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:A,framePatternSrc:u}),u){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,h,!0,d),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(A?.some(h=>h.zoom)){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");h.updateOffsets(A)}e.setMandatoryFulfilled(t.stepName,!0)};if(i.selectedVariants&&i.selectedVariants.length>0){const d=i.selectedVariants[0].id;if(t.option&&d){const u=t.option.variants?.find(A=>A.id===d);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const A=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(u,h)));e.updateStorage(t.stepName,{currentFrameSources:A}),await c()})}}else await e.setSelectionsAndElements(t.stepName,[],l,c)}}async availableColors(t,e){return(await P.ensureFullOption(t.data.colorOption))?.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name}))??[]}selectImage(t,e,a,i=!0){const r=ke.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 ki(async()=>{const d=(await W.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{W.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,i).then(l)})},()=>{throw new $e("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,i)}async selectVariant(t,e,a,i,r){const o=await this.selectVariantCommand(t,e,a,i,r);o&&(o.command&&i.getCommandDispatcher()(o.command),o.followup&&await o.followup())}getCreateElementCommand(t,e,a,i,r){return new G({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},i)}async loadPatternFromString(t,e,a=!0,i=void 0,r){if(t.endsWith("svg")){const o=await za(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:i??d.colors};At.set(t,u),e.setPatternData(u,a)}else{const o=await Ue(t,!0),s=await ce(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};At.set(t,l),e.setPatternData(l,a)}}async changeColors(t,e,a){const i=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!i||!i.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const r=await this.calculateColorMetadata(i,t,a);e.updateMetadata(t.stepName,{colors:r.metadataColors}),e.updateStorage(t.stepName,{colors:r.storageColors}),i.setPatternData({...i.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 i=a.getImageData()?.colors??{},r=[];for(const o in i){const s=i[o];if(s.pmsValue){const l=s.pmsValue.trim().toLocaleLowerCase();r.includes(l)||r.push(l)}else if(s.browserValue){const l=ai(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 i={...t.getImageData().colors??{}},r={};Object.entries(i).forEach(([l,c])=>{const d={browserValue:c.browserValue};r[l]=d});for(const[l,c]of a.entries())i[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},r[l]=c;let o=Array.from(Object.values(i)).map(l=>l.browserValue);const s=await P.ensureFullOption(e.data.colorOption);return s&&s.variants?.forEach(l=>{o=o.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:i,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,i,r,o){const s=i.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 Ae(l[g]),m=s.getImageData(),f=a.map(I=>new Dt(I.id)),y=m?qa(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:y?.x||0,y:y?.y||0,width:m.width,height:m.height,scaleX:y?.zoom||1,scaleY:y?.zoom||1,rotation:0}:void 0,F=N(),v=i.getLayouts().find(I=>I.panelId===h.panelId);if(!v)throw new Y(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:f}})),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 i.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(i.updateStorage(t.stepName,{currentFrameSources:l}),o){const h=i.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(i=>i.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,i){const r=ke.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,i,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 ke;class tl{async getIllustrationBody(t){return new Promise(e=>{et(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,i,r){return new G({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},i)}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 i=await P.getOptionForStep(t);if(!i)throw new lt(t,"No option configured for illustration step.");if(a)return await this.reload(t,e,a);{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantCommand(t,r,[],e)}return null}async reload(t,e,a){const i=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 P.getOptionForStep(t);if(i?.selectedVariants){const c=i.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:i.storage?.colors})})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=await P.ensureFullOption(t.data.colorOption);return a?a?a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})):[]:[]}async changeColorsCommand(t,e,a,i,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=$a(t,e,a,o),l=await re(s),c=[];for(const d of i){for(const[u,A]of r.entries())c.push(new Ba(d,u,A));c.push(new Ys(d,s,l))}return new U(c)}async changeColors(t,e,a,i){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 i.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 P.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,i,r){i(!0);try{const o=await this.selectVariantCommand(t,e,a,r);o&&(o.command&&r.getCommandDispatcher()(o.command),o.followup&&await o.followup())}finally{i(!1)}}async selectVariantCommand(t,e,a,i){if(!t.data||!t.data.regions)throw new lt(t,"Missing regions.");const r=e.asset;if(!r)throw new wt(e);const o=r.fileLink;if(!o)throw new Rt(r);t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const s=a.map(m=>new Dt(m.id)),l=await rt(await this.getIllustrationBody(o)),c=await re(l.svg),d=(m,f)=>{const y=i.getLayouts().find(F=>F.panelId===m.panelId);if(!y)throw new Y(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:f},command:this.getCreateElementCommand(w,m,f,y,{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 P.ensureFullOption(t.data.colorOption);return p&&p.variants?.forEach(m=>{g=g.map(f=>f.toLowerCase()===m.color?.toLowerCase()?m.name:f)}),i.updateMetadata(t.stepName,{colors:g}),{command:new U(h),followup:async()=>{const m=u.map(y=>y.regionElement);await i.setSelectionsAndElements(t.stepName,[e],m);const f=r.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const y={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=f.find(v=>v.channelNumber===F.number);b&&(y[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,i,new Map(Object.entries(y)))}if(t.data.colorPickerEnabled){const y=await this.availableColors(t,i)||[],w=Object.keys(l.colors),F=y.length===1&&w.length===1;if(F){const b=y[0],v=w[0];await this.changeColors(t,m,i,new Map([[v,b.variant.color]]))}!F&&f.length===0&&await this.changeColors(t,m,i,new Map)}}}}}const Jt=new tl;class el{async init(t,e,a){const i=t.option;if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=t.option;if(!l)throw new ae(t);if(i?.selectedVariants){const c=i.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,i){const r=await this.selectVariantLambda(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,i){const r=a.getModelContainer();i(!0);const o=e.material;if(!o)throw i(!1),new wt(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{i(!1)}})}}}}const Wa=new el;class al{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const i=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 P.getOptionForStep(t);if(i?.selectedVariants){const c=i.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 wt(d);await A.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1)}})}}}}async selectVariant(t,e,a,i){const r=await this.selectVariantLambda(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,i){i(!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 o=a.getModelContainer();o&&await o.applyModelVariant(t.stepName,{model:r,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1)}finally{i(!1)}})}}}}const Ya=new al;class nl{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 i=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:i?.storage?.text}),e.setMandatoryFulfilled(t.stepName,i?.storage?.text!=="")})}async changeText(t,e,a,i){const r=await this.changeTextCommand(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,a,i){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,i);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(y=>y.panelId===u.panelId);if(!m)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Dt(g)),f.push(new G({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(f)}};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,i){if(t.data&&t.data.maxLength){const o=t.data.maxLength;if(e.length>o)return i("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return i("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const r=ma.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 i("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return i(""),{input:e,helperData:{}}}}const Ja=new nl;class il{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"Missing option for picture step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,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 i=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 P.getOptionForStep(t);if(i?.selectedVariants){const c=i.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,i){const r=await this.selectVariantCommand(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,a,i){const r=e.asset;if(!r)throw new wt(e);const o=r?.fileLink;if(!o)return console.error("No URL for picture!"),null;i(!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 Y(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new G({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()=>{i(!1)})}}}}const Ka=new il;class rl{async init(t,e,a){const i=t.option;if(!i)throw new lt(t,"Missing option for question step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return this.selectVariantLambda(t,r.id||"",e)}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),r=await P.getOptionForStep(t);if(i?.selectedVariants){const o=i.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 i=await this.selectVariantLambda(t,e,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"Missing option for question step");const r=i.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 ${i.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[o],[])}}}}const _a=new rl;class ol{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=await P.getOptionForStep(t);return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const i=a.getLayouts(),o=(a.getRegionElements(e.stepName)||[]).map(s=>{const l=s.region;if(!i.find(d=>d.panelId===l?.panelId))throw new Y(l);return new Ba(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 i=await P.getOptionForStep(t);if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);return r?this.selectVariantCommand(t,{fill:r.color,stroke:r.color,variant:r},[],e):null}return null}async selectVariant(t,e,a,i){const r=await this.selectVariantCommand(t,e,a,i);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async reload(t,e,a){const i=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 P.getOptionForStep(t);if(i?.selectedVariants){const c=i.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:i?.storage?.colour||""})})}}}}async selectVariantCommand(t,e,a,i){const r=i.getLayouts(),o=i.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 Y(u);const h=s();return new Ba(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new U(c),followup:async()=>{await i.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),i.updateStorage(t.stepName,{colour:s()})}}}else{const l=(A,h)=>{const g=r.find(w=>w.panelId===A.panelId);if(!g)throw new Y(A);const p=s(),m=`
1383
1383
  <svg
1384
1384
  xmlns="http://www.w3.org/2000/svg"
1385
1385
  xmlnsXlink="http://www.w3.org/1999/xlink"
@@ -2463,7 +2463,7 @@
2463
2463
  }
2464
2464
  }
2465
2465
  }
2466
- `;class Xc{constructor(t,e=S.getShadowGraphqlClient.bind(S)){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 Zc{init(t,e,a){this.cognitoClient=new pe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const i=await this.cognitoClient?.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}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 pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Zc;class ir{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Or(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=ln.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(ln.code(e)?.code==="CLP")return"USD0,0"}}const Fn=new ir;class rr{constructor(t,e,a,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,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,Fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Fn.getPrecisionForCurrency(e))}}const td=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:as(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},ed=async(n,t)=>{const a=(await t).find(i=>i.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},nn=async(n,t)=>{const e=n.map(s=>ie.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const i=td(a,t),r=a.map(s=>ie.set({id:s,options:t},ed(s,i))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},or=async(n,t)=>(await nn([n],t))[0],ad=async n=>{const t=await S.getShadowGraphqlClient().query({query:hi,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class nd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:Lo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&eo(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 37.0.1"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ht.setHubUrl(t.hubUrl),ht.setServerUrl(t.serverUrl),ht.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&&Zn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return W}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!ao())throw new Error("Application key required to use Flow Service.");return new er}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await S.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new rr(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=sr(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 i=(await S.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return i.id?i.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=S.getShadowGraphqlClient(),i=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!i.id){const s=(await e.mutate({mutation:Jc,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(i);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||i,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 i=JSON.parse(e),r=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<r-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await S.getShadowGraphqlClient().query({query:Ee,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 S.getShadowGraphqlClient().mutate({mutation:Kc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",i=await jt.verifyCode(t,e,a);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await S.getShadowGraphqlClient().query({query:Ee,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),i=new Date().getTime()/1e3,r=!a?.AccessToken||Ne(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<i-parseInt(t)||r){const o=await jt.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 S.getShadowGraphqlClient().query({query:_c,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await S.getShadowGraphqlClient().mutate({mutation:Hl(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 xn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,i,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(([y,w])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Ne(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...i?.graphql?.additionalHeaders},d=await S.getShadowGraphqlClient().query({query:Ll(i?.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 xn(this,u,e,a,s,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:i?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,i){const o={...await cr(t),...i?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:Wl(),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:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await S.getShadowGraphqlClient().query({query:ic(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 S.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||[],i=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&i.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",i),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),i=a[0],r=i.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await i.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,i){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=ha(o,l),d=ha(s,l);let u=0;const A=S.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:Vo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,i&&i(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(gt=>gt.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:Uo,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,i&&i(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),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[y,w]=await Promise.all([(async()=>m.length>0?await ad(m):[])(),(async()=>f.length>0?await nn(f,e):[])()]),F=new Map(y.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,gt=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 ge=Q.getMap("transactionOwnerIds")||new Map;!ge.get(T.id)&&T.transactionOwnerId&&(ge.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",ge));const _e=ge.get(T.id)||void 0,wr=new Xc({onMutate:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}})}),me={workflow:bt,transaction:T,singleVariantsRenderable:gt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>wr,readOnly:k,isReloadedTransaction:gt.type==="transaction"};if(gt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await ba(ot),me.reloadedState=ot}else if(!k&&gt.workflowState){const ot=JSON.parse(gt.workflowState);await ba(ot),me.reloadedState=ot}return me.delayWorkflowStateSync=!0,{experienceOptions:me,index:X,options:gt}}),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 Yi(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 S.getShadowGraphqlClient().query({query:Yo(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 Da(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Jo(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 Da(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,i=await S.getShadowGraphqlClient().query({query:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return i.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await S.getShadowGraphqlClient().mutate({mutation:ss,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 sr=async(n,t)=>(await S.getShadowGraphqlClient().query({query:is,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,id=async n=>{const e=await S.getShadowGraphqlClient().query({query:jo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},rd=async(n,t)=>(await S.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,od=async n=>(await S.getShadowGraphqlClient().query({query:os,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,sd=async n=>(await S.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function lr(){const n={};try{const t=await this.loggedInBearerToken();n.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(a);i&&!Ne(i)&&(n.Authorization=`Bearer ${i}`)}return n}async function cr(n){const e=Q.getMap("bundleOwnerIds")?.get(n),a=await lr();return{bundleOwnerId:e,...a}}async function ld(n){const e=Q.getMap("transactionOwnerIds")?.get(n),a=await lr();return{transactionOwnerId:e,...a}}const cd=async n=>{const t=await cr(n),e=await S.getShadowGraphqlClient().mutate({mutation:hc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)},dd=async n=>{const t=await ld(n),e=await S.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[n]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==n)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function dr(n,t,e,a){const i=e.width*n.zoom,r=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=be(n.x,t.width-c,0),s.y=be(n.y,t.height-d,0),s}const o=n;return o.x=be(o.x,-i,t.width),o.y=be(o.y,-r,t.height),o}function be(n,t,e){return Math.min(Math.max(n,t),e)}class ur{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=$n(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 i=a;if(i.currentFrameSources){let r=!1;for(let o=0;o<i.currentFrameSources.length;o++){const s=i.currentFrameSources[o],l=await Ae(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(i.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 i=Mt.get(e);i&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(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,i){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,i),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 i=this.imageData;if(!i||!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]=dr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,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,i,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 js(l,e,t[d]),new Hs(l,i.useThreshold,i.invertThreshold,i.threshold,i.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,i)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[i]=r,this.maxZoomScale[i]=r*2.5):(this.minZoomScale[i]=r/10,this.maxZoomScale[i]=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]=qa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class ud{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f){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 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=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Ar||{});class hr extends Z{constructor(t,e,a){super(t,e,a);const i=e.data;this.frameService=new ur(i.forceImageCover,i.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 i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Oe.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover 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 W.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.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}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,i){return i&&i.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 W.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return W.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}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 i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Ad=C.gql`
2466
+ `;class Xc{constructor(t,e=S.getShadowGraphqlClient.bind(S)){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 Zc{init(t,e,a){this.cognitoClient=new pe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const i=await this.cognitoClient?.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}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 pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Zc;class ir{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Or(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=ln.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(ln.code(e)?.code==="CLP")return"USD0,0"}}const Fn=new ir;class rr{constructor(t,e,a,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,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,Fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Fn.getPrecisionForCurrency(e))}}const td=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:as(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},ed=async(n,t)=>{const a=(await t).find(i=>i.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},nn=async(n,t)=>{const e=n.map(s=>ie.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const i=td(a,t),r=a.map(s=>ie.set({id:s,options:t},ed(s,i))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},or=async(n,t)=>(await nn([n],t))[0],ad=async n=>{const t=await S.getShadowGraphqlClient().query({query:hi,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class nd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:Lo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&eo(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 37.0.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ht.setHubUrl(t.hubUrl),ht.setServerUrl(t.serverUrl),ht.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&&Zn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return W}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!ao())throw new Error("Application key required to use Flow Service.");return new er}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await S.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new rr(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=sr(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 i=(await S.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return i.id?i.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=S.getShadowGraphqlClient(),i=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!i.id){const s=(await e.mutate({mutation:Jc,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(i);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||i,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 i=JSON.parse(e),r=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<r-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await S.getShadowGraphqlClient().query({query:Ee,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 S.getShadowGraphqlClient().mutate({mutation:Kc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",i=await jt.verifyCode(t,e,a);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await S.getShadowGraphqlClient().query({query:Ee,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),i=new Date().getTime()/1e3,r=!a?.AccessToken||Ne(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<i-parseInt(t)||r){const o=await jt.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 S.getShadowGraphqlClient().query({query:_c,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await S.getShadowGraphqlClient().mutate({mutation:Hl(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 xn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,i,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(([y,w])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Ne(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...i?.graphql?.additionalHeaders},d=await S.getShadowGraphqlClient().query({query:Ll(i?.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 xn(this,u,e,a,s,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:i?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,i){const o={...await cr(t),...i?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:Wl(),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:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await S.getShadowGraphqlClient().query({query:ic(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 S.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||[],i=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&i.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",i),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),i=a[0],r=i.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await i.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,i){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=ha(o,l),d=ha(s,l);let u=0;const A=S.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:Vo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,i&&i(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(gt=>gt.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:Uo,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,i&&i(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),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[y,w]=await Promise.all([(async()=>m.length>0?await ad(m):[])(),(async()=>f.length>0?await nn(f,e):[])()]),F=new Map(y.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,gt=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 ge=Q.getMap("transactionOwnerIds")||new Map;!ge.get(T.id)&&T.transactionOwnerId&&(ge.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",ge));const _e=ge.get(T.id)||void 0,wr=new Xc({onMutate:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}})}),me={workflow:bt,transaction:T,singleVariantsRenderable:gt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>wr,readOnly:k,isReloadedTransaction:gt.type==="transaction"};if(gt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await ba(ot),me.reloadedState=ot}else if(!k&&gt.workflowState){const ot=JSON.parse(gt.workflowState);await ba(ot),me.reloadedState=ot}return me.delayWorkflowStateSync=!0,{experienceOptions:me,index:X,options:gt}}),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 Yi(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 S.getShadowGraphqlClient().query({query:Yo(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 Da(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Jo(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 Da(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,i=await S.getShadowGraphqlClient().query({query:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return i.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await S.getShadowGraphqlClient().mutate({mutation:ss,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 sr=async(n,t)=>(await S.getShadowGraphqlClient().query({query:is,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,id=async n=>{const e=await S.getShadowGraphqlClient().query({query:jo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},rd=async(n,t)=>(await S.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,od=async n=>(await S.getShadowGraphqlClient().query({query:os,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,sd=async n=>(await S.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function lr(){const n={};try{const t=await this.loggedInBearerToken();n.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(a);i&&!Ne(i)&&(n.Authorization=`Bearer ${i}`)}return n}async function cr(n){const e=Q.getMap("bundleOwnerIds")?.get(n),a=await lr();return{bundleOwnerId:e,...a}}async function ld(n){const e=Q.getMap("transactionOwnerIds")?.get(n),a=await lr();return{transactionOwnerId:e,...a}}const cd=async n=>{const t=await cr(n),e=await S.getShadowGraphqlClient().mutate({mutation:hc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)},dd=async n=>{const t=await ld(n),e=await S.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[n]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==n)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function dr(n,t,e,a){const i=e.width*n.zoom,r=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=be(n.x,t.width-c,0),s.y=be(n.y,t.height-d,0),s}const o=n;return o.x=be(o.x,-i,t.width),o.y=be(o.y,-r,t.height),o}function be(n,t,e){return Math.min(Math.max(n,t),e)}class ur{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=$n(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 i=a;if(i.currentFrameSources){let r=!1;for(let o=0;o<i.currentFrameSources.length;o++){const s=i.currentFrameSources[o],l=await Ae(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(i.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 i=Mt.get(e);i&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(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,i){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,i),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 i=this.imageData;if(!i||!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]=dr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,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,i,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 js(l,e,t[d]),new Hs(l,i.useThreshold,i.invertThreshold,i.threshold,i.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,i)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[i]=r,this.maxZoomScale[i]=r*2.5):(this.minZoomScale[i]=r/10,this.maxZoomScale[i]=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]=qa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class ud{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f){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 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=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Ar||{});class hr extends Z{constructor(t,e,a){super(t,e,a);const i=e.data;this.frameService=new ur(i.forceImageCover,i.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 i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Oe.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover 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 W.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.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}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,i){return i&&i.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 W.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return W.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}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 i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Ad=C.gql`
2467
2467
  query GetLoggedInCustomer($email: String!) {
2468
2468
  customer(emailAddress: $email) {
2469
2469
  id