@spiffcommerce/core 39.1.1 → 39.1.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 +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +146 -146
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1401,7 +1401,7 @@
|
|
|
1401
1401
|
fill="${e.color}"
|
|
1402
1402
|
/>
|
|
1403
1403
|
</svg>
|
|
1404
|
-
`,i={};i["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Ht(t,D.Illustration),o=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors: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||jt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Ht(t,D.Illustration,e.src),i=await rt(await Pi(e.src)),r=await se(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||jt(t,a.layer||0),immutable:a.immutable}}}class j extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,j.prototype)}}const U=(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 j;return e},tt=(n,t)=>{const e=[...t.elements.filter(i=>i.id!==n.id),n],a=Ga(e);return{layout:t.layout,elements:a,modificationID:N()}},Pa=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=La(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 se(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 En extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Gs extends ${constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 js extends ${constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Hs extends ${constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const o=a;o.scaleX=o.scaleX*this.width/e.width,o.scaleY=o.scaleY*this.height/e.height}else if(e.type==="textbox"){const o=a,s=(!o.algorithm||o.algorithm===xt.Autosize?o.text:o.input)??"";a=ge(o,s,e)}const i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class V extends ${constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Ya extends ${constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:N()}}}}}class H extends ${constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(s=>s.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const s=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,s)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:N()}}}}const 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 xi extends ${constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 da extends ${constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Fi extends ${constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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(ge(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class xa extends ${constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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(ge(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class Di extends ${constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Ws extends ${constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=_(this.id,Object.values(t.layouts)),a=e.elements.findIndex(s=>s.id===this.id),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 Ys 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=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},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){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 ki extends ${constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=_(e.id,Object.values(t.layouts)),i=tt(ge(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:i}}}}class ua extends ${constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Fa extends ${constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Ks extends ${constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 _s extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(o=>o.elements.find(s=>s.id===this.id));if(!a)throw new Error("Layout missing from state!");const 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 Xs extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=Object.values(t.layouts).find(s=>s.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const 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 Zs extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const 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 tl extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const 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 bn{constructor(t,e,a){this.processRegion=async i=>{const r=this.layouts.find(l=>l.panelId===i.panelId);if(!r)throw new J(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 H(c,r)}}else{const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:o,d=await rt(await(async()=>new Promise((A,h)=>{if(!l){h("Undefined vector silent step source");return}et(l,!0).then(g=>{A(g)}).catch(g=>console.error(g))}))()),u={stepName:this.configuration.stepName,id:N(),cachedObjectURL:await se(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y: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 H(u,r)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new lt(this.configuration,"Missing regions.");if(this.configuration.type===E.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===E.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new J(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===E.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?D.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),D.Illustration)}}const Mi=async n=>{const t=`${mt.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 ze("Failed to shorten URL, see console.")}};class Ti{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 el{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 ke([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new Ti(async()=>!!(await r()).link,async()=>{const p=await r();if(!p.link||!p.link)throw new Ot(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 ze("Cannot create QR code, URL too long.");const d=await Mi(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 Ln.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,u=r.find(A=>A.panelId===d?.panelId);if(!u&&d)throw new J(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new H({stepRegion:d,stepRegionIndex:c.regionIndex,stepName: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 V(l),followup:async()=>{}}}}const Ja=new el;class Ne{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return Ia(e);const a=t.asset;if(!a)throw new yt(t);const i=a.fileLink;if(i)return et(i,!0);throw new Ot(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 G.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option){const s=await P.getDefaultVariant(t.option,t.overrideDefaultVariantId);if(s)return this.selectVariantCommand(t,s,[],e,void 0,r||t.data.placeholderImageUrl);if(t.option.variants?.length!==0)return 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=>Ia(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=Ne.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 Ti(async()=>{const d=(await G.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{G.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,i).then(l)})},()=>{throw new ze("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 H({id:t,type:D.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/r.frameData.width,scaleY:e.height/r.frameData.height,path:r.frameData.path,dataWidth:r.frameData.width,dataHeight:r.frameData.height,stepRegion:e,stepRegionIndex:a,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e,a=!0,i=void 0,r){if(t.endsWith("svg")){const o=await Ha(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};gt.set(t,u),e.setPatternData(u,a)}else{const o=await qe(t,!0),s=await ue(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};gt.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=ii(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 me(l[g]),m=s.getImageData(),f=a.map(I=>new Dt(I.id)),S=m?ja(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:S?.x||0,y:S?.y||0,width:m.width,height:m.height,scaleX:S?.zoom||1,scaleY:S?.zoom||1,rotation:0}:void 0,F=N(),v=i.getLayouts().find(I=>I.panelId===h.panelId);if(!v)throw new J(h);return{command:this.getCreateElementCommand(F,h,g,v,{frameData:p,pattern:w,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:F,region:h,regionIndex:g},removeExistingCommands:f}})),u=d.map(h=>h.command),A=d.map(h=>h.removeExistingCommands).flat();return{command:new V([...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 Ot(t)}async loadPatternFromAsset(t,e,a,i){const r=Ne.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 At=new Ne;class al{async getIllustrationBody(t){return new Promise(e=>{et(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,i,r){return new H({stepRegion:e,stepRegionIndex:a,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:D.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},i)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return U(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=La(t,e,a,o),l=await se(s),c=[];for(const d of i){for(const[u,A]of r.entries())c.push(new Fa(d,u,A));c.push(new Ks(d,s,l))}return new V(c)}async changeColors(t,e,a,i){if(e.length===0)return;const r=U(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 yt(e);const o=r.fileLink;if(!o)throw new Ot(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 se(l.svg),d=(m,f)=>{const S=i.getLayouts().find(F=>F.panelId===m.panelId);if(!S)throw new J(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:f},command:this.getCreateElementCommand(w,m,f,S,{stepName:t.stepName,src:o,objectURL:c,svg:l})}},u=t.data.regions.map(d),A=u.map(m=>m.command),h=[...s,...A];let g=Array.from(Object.values(l.colors)).map(m=>m.browserValue);const p=await 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 V(h),followup:async()=>{const m=u.map(S=>S.regionElement);await i.setSelectionsAndElements(t.stepName,[e],m);const f=r.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const S={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=f.find(v=>v.channelNumber===F.number);b&&(S[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,i,new Map(Object.entries(S)))}if(t.data.colorPickerEnabled){const S=await this.availableColors(t,i)||[],w=Object.keys(l.colors),F=S.length===1&&w.length===1;if(F){const b=S[0],v=w[0];await this.changeColors(t,m,i,new Map([[v,b.variant.color]]))}!F&&f.length===0&&await this.changeColors(t,m,i,new Map)}}}}}const _t=new al;class nl{async init(t,e,a){const i=t.option;if(!i)throw new ie(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 ie(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 yt(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 Ka=new nl;class il{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ie(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 yt(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 yt(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 _a=new il;class rl{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const 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(S=>S.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 H({stepRegion:u,stepRegionIndex:A,stepName:t.stepName,colors:{},id:g,svg:d,type:D.Illustration,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable},m)),{id:g,region:u,command:new V(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 V(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 V(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=Ca.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 Xa=new rl;class ol{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 yt(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 J(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new H({stepName:t.stepName,stepRegion:u,stepRegionIndex:A,id:p,src:o,type:D.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},g)}},d=t.data.regions.map(c);return{command:new V([...l,...d.map(u=>u.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(u=>u.regionElement),async()=>{i(!1)})}}}}const Za=new ol;class sl{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 tn=new sl;class ll{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 J(l);return new Fa(s.id,this.shapeFillId,t)}).filter(s=>!!s);a.getCommandDispatcher()(new V(o)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ie(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 J(u);const h=s();return new Fa(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new V(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 J(A);const p=s(),m=`
|
|
1404
|
+
`,i={};i["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Ht(t,D.Illustration),o=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors: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||jt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Ht(t,D.Illustration,e.src),i=await rt(await Pi(e.src)),r=await se(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||jt(t,a.layer||0),immutable:a.immutable}}}class j extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,j.prototype)}}const U=(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 j;return e},tt=(n,t)=>{const e=[...t.elements.filter(i=>i.id!==n.id),n],a=Ga(e);return{layout:t.layout,elements:a,modificationID:N()}},Pa=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=La(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 se(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 En extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Gs extends ${constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 js extends ${constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Hs extends ${constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const o=a;o.scaleX=o.scaleX*this.width/e.width,o.scaleY=o.scaleY*this.height/e.height}else if(e.type==="textbox"){const o=a,s=(!o.algorithm||o.algorithm===xt.Autosize?o.text:o.input)??"";a=ge(o,s,e)}const i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class V extends ${constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Ya extends ${constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:N()}}}}}class H extends ${constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(s=>s.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const s=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,s)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:N()}}}}const 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 xi extends ${constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 da extends ${constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Fi extends ${constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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(ge(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class xa extends ${constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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(ge(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class Di extends ${constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Ws extends ${constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=_(this.id,Object.values(t.layouts)),a=e.elements.findIndex(s=>s.id===this.id),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 Ys 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=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},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){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 ki extends ${constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=_(e.id,Object.values(t.layouts)),i=tt(ge(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:i}}}}class ua extends ${constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Fa extends ${constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 Ks extends ${constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;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 _s extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(o=>o.elements.find(s=>s.id===this.id));if(!a)throw new Error("Layout missing from state!");const 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 Xs extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=Object.values(t.layouts).find(s=>s.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const 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 Zs extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const 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 tl extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const 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 bn{constructor(t,e,a){this.processRegion=async i=>{const r=this.layouts.find(l=>l.panelId===i.panelId);if(!r)throw new J(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 H(c,r)}}else{const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:o,d=await rt(await(async()=>new Promise((A,h)=>{if(!l){h("Undefined vector silent step source");return}et(l,!0).then(g=>{A(g)}).catch(g=>console.error(g))}))()),u={stepName:this.configuration.stepName,id:N(),cachedObjectURL:await se(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y: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 H(u,r)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new lt(this.configuration,"Missing regions.");if(this.configuration.type===E.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===E.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new J(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===E.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?D.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),D.Illustration)}}const Mi=async n=>{const t=`${mt.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 ze("Failed to shorten URL, see console.")}};class Ti{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 el{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 ke([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new Ti(async()=>!!(await r()).link,async()=>{const p=await r();if(!p.link||!p.link)throw new Ot(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 ze("Cannot create QR code, URL too long.");const d=await Mi(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 Ln.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,u=r.find(A=>A.panelId===d?.panelId);if(!u&&d)throw new J(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new H({stepRegion:d,stepRegionIndex:c.regionIndex,stepName: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 V(l),followup:async()=>{}}}}const Ja=new el;class Ne{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return Ia(e);const a=t.asset;if(!a)throw new yt(t);const i=a.fileLink;if(i)return et(i,!0);throw new Ot(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 G.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option){const s=await P.getDefaultVariant(t.option,t.overrideDefaultVariantId);if(s)return this.selectVariantCommand(t,s,[],e,void 0,r||t.data.placeholderImageUrl);if(t.option.variants&&t.option.variants?.length!==0)return 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=>Ia(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=Ne.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 Ti(async()=>{const d=(await G.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{G.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,i).then(l)})},()=>{throw new ze("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 H({id:t,type:D.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/r.frameData.width,scaleY:e.height/r.frameData.height,path:r.frameData.path,dataWidth:r.frameData.width,dataHeight:r.frameData.height,stepRegion:e,stepRegionIndex:a,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e,a=!0,i=void 0,r){if(t.endsWith("svg")){const o=await Ha(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};gt.set(t,u),e.setPatternData(u,a)}else{const o=await qe(t,!0),s=await ue(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};gt.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=ii(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 me(l[g]),m=s.getImageData(),f=a.map(I=>new Dt(I.id)),S=m?ja(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:S?.x||0,y:S?.y||0,width:m.width,height:m.height,scaleX:S?.zoom||1,scaleY:S?.zoom||1,rotation:0}:void 0,F=N(),v=i.getLayouts().find(I=>I.panelId===h.panelId);if(!v)throw new J(h);return{command:this.getCreateElementCommand(F,h,g,v,{frameData:p,pattern:w,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:F,region:h,regionIndex:g},removeExistingCommands:f}})),u=d.map(h=>h.command),A=d.map(h=>h.removeExistingCommands).flat();return{command:new V([...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 Ot(t)}async loadPatternFromAsset(t,e,a,i){const r=Ne.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 At=new Ne;class al{async getIllustrationBody(t){return new Promise(e=>{et(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,i,r){return new H({stepRegion:e,stepRegionIndex:a,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:D.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},i)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return U(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=La(t,e,a,o),l=await se(s),c=[];for(const d of i){for(const[u,A]of r.entries())c.push(new Fa(d,u,A));c.push(new Ks(d,s,l))}return new V(c)}async changeColors(t,e,a,i){if(e.length===0)return;const r=U(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 yt(e);const o=r.fileLink;if(!o)throw new Ot(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 se(l.svg),d=(m,f)=>{const S=i.getLayouts().find(F=>F.panelId===m.panelId);if(!S)throw new J(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:f},command:this.getCreateElementCommand(w,m,f,S,{stepName:t.stepName,src:o,objectURL:c,svg:l})}},u=t.data.regions.map(d),A=u.map(m=>m.command),h=[...s,...A];let g=Array.from(Object.values(l.colors)).map(m=>m.browserValue);const p=await 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 V(h),followup:async()=>{const m=u.map(S=>S.regionElement);await i.setSelectionsAndElements(t.stepName,[e],m);const f=r.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const S={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=f.find(v=>v.channelNumber===F.number);b&&(S[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,i,new Map(Object.entries(S)))}if(t.data.colorPickerEnabled){const S=await this.availableColors(t,i)||[],w=Object.keys(l.colors),F=S.length===1&&w.length===1;if(F){const b=S[0],v=w[0];await this.changeColors(t,m,i,new Map([[v,b.variant.color]]))}!F&&f.length===0&&await this.changeColors(t,m,i,new Map)}}}}}const _t=new al;class nl{async init(t,e,a){const i=t.option;if(!i)throw new ie(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 ie(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 yt(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 Ka=new nl;class il{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ie(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 yt(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 yt(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 _a=new il;class rl{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const 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(S=>S.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 H({stepRegion:u,stepRegionIndex:A,stepName:t.stepName,colors:{},id:g,svg:d,type:D.Illustration,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable},m)),{id:g,region:u,command:new V(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 V(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 V(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=Ca.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 Xa=new rl;class ol{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 yt(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 J(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new H({stepName:t.stepName,stepRegion:u,stepRegionIndex:A,id:p,src:o,type:D.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},g)}},d=t.data.regions.map(c);return{command:new V([...l,...d.map(u=>u.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(u=>u.regionElement),async()=>{i(!1)})}}}}const Za=new ol;class sl{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 tn=new sl;class ll{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 J(l);return new Fa(s.id,this.shapeFillId,t)}).filter(s=>!!s);a.getCommandDispatcher()(new V(o)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ie(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 J(u);const h=s();return new Fa(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new V(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 J(A);const p=s(),m=`
|
|
1405
1405
|
<svg
|
|
1406
1406
|
xmlns="http://www.w3.org/2000/svg"
|
|
1407
1407
|
xmlnsXlink="http://www.w3.org/1999/xlink"
|
|
@@ -2487,7 +2487,7 @@
|
|
|
2487
2487
|
}
|
|
2488
2488
|
}
|
|
2489
2489
|
}
|
|
2490
|
-
`;class Zc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class td{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const i=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return 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 we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new td;class rr{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=un.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(un.code(e)?.code==="CLP")return"USD0,0"}}const kn=new rr;class or{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,kn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,kn.getPrecisionForCurrency(e))}}const ed=async(n,t)=>{const e=await y.getShadowGraphqlClient().query({query:is(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},ad=async(n,t)=>{const a=(await t).find(i=>i.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},sn=async(n,t)=>{const e=n.map(s=>oe.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const i=ed(a,t),r=a.map(s=>oe.set({id:s,options:t},ad(s,i))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},sr=async(n,t)=>(await sn([n],t))[0],nd=async n=>{const t=await y.getShadowGraphqlClient().query({query:mi,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class id{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:qo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&ao(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 39.1.1"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){mt.setHubUrl(t.hubUrl),mt.setServerUrl(t.serverUrl),mt.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&&ei(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!no())throw new Error("Application key required to use Flow Service.");return new ar}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:ds,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new or(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=lr(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 y.getShadowGraphqlClient().query({query:Be,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=y.getShadowGraphqlClient(),i=(await e.query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!i.id){const s=(await e.mutate({mutation:Kc,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 Wt.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 y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:_c,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",i=await Wt.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 y.getShadowGraphqlClient().query({query:Be,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||Oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<i-parseInt(t)||r){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Xc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Wl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new Dn(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(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Oe(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...i?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:zl(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 Dn(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 dr(t),...i?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Yl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts: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 y.getShadowGraphqlClient().query({query:rc(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],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=pa(o,l),d=pa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:zo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,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,It)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(pt=>pt.option.transactionId===X.id)?.option.readOnly??!1,index:x[It].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Lo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,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),[S,w]=await Promise.all([(async()=>m.length>0?await nd(m):[])(),(async()=>f.length>0?await sn(f,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,It=L?b.get(L):void 0,pt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=Q.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",fe));const ta=fe.get(T.id)||void 0,yr=new Zc({onMutate:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:It,transaction:T,singleVariantsRenderable:pt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new R("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>yr,readOnly:k,isReloadedTransaction:pt.type==="transaction"};if(pt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Pa(ot),Ce.reloadedState=ot}else if(!k&&pt.workflowState){const ot=JSON.parse(pt.workflowState);await Pa(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:X,options:pt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let O=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Ki(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),O=[...O,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return O}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Ko(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Ta(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:_o(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Ta(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 y.getShadowGraphqlClient().query({query:Yo,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 y.getShadowGraphqlClient().mutate({mutation:cs,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const lr=async(n,t)=>(await y.getShadowGraphqlClient().query({query:os,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,rd=async n=>{const e=await y.getShadowGraphqlClient().query({query:Wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},od=async(n,t)=>(await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,sd=async n=>(await y.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ld=async n=>(await y.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function cr(){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&&!Oe(i)&&(n.Authorization=`Bearer ${i}`)}return n}async function dr(n){const e=Q.getMap("bundleOwnerIds")?.get(n),a=await cr();return{bundleOwnerId:e,...a}}async function cd(n){const e=Q.getMap("transactionOwnerIds")?.get(n),a=await cr();return{transactionOwnerId:e,...a}}const dd=async n=>{const t=await dr(n),e=await y.getShadowGraphqlClient().mutate({mutation:gc,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}`)},ud=async n=>{const t=await cd(n),e=await y.getShadowGraphqlClient().mutate({mutation:mc,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 ur(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=Pe(n.x,t.width-c,0),s.y=Pe(n.y,t.height-d,0),s}const o=n;return o.x=Pe(o.x,-i,t.width),o.y=Pe(o.y,-r,t.height),o}function Pe(n,t,e){return Math.min(Math.max(n,t),e)}class Ar{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Un(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 me(s),c=this.frameData?this.frameData[o]:void 0;ae(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=We(this.imageData.svg,this.imageData.colors||{},!1);return je(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 R("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]=ur(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 R("Frame data not set. This is a bug");if(!this.workflowManager)throw new R("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 V([new Ws(l,e,t[d]),new Ys(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]=ja(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ad{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 Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var hr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(hr||{});class gr extends Z{constructor(t,e,a){super(t,e,a);const i=e.data;this.frameService=new Ar(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return At.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 At.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(Ue.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 G.removeBackgroundFromAsset(e);t&&await At.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 vectorizeImageSelection(t=!0){const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to vectorize the image.");const a=await G.vectorizeAsset(e);t&&await At.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,vectorizedAssetKey:a.key,useOriginalAsset:!t}}),a}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await At.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?At.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return At.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 G.getLocalOrFromServer(t)}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const 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)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const hd=C.gql`
|
|
2490
|
+
`;class Zc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class td{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const i=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return 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 we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new td;class rr{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=un.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(un.code(e)?.code==="CLP")return"USD0,0"}}const kn=new rr;class or{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,kn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,kn.getPrecisionForCurrency(e))}}const ed=async(n,t)=>{const e=await y.getShadowGraphqlClient().query({query:is(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},ad=async(n,t)=>{const a=(await t).find(i=>i.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},sn=async(n,t)=>{const e=n.map(s=>oe.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const i=ed(a,t),r=a.map(s=>oe.set({id:s,options:t},ad(s,i))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},sr=async(n,t)=>(await sn([n],t))[0],nd=async n=>{const t=await y.getShadowGraphqlClient().query({query:mi,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class id{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:qo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&ao(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 39.1.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){mt.setHubUrl(t.hubUrl),mt.setServerUrl(t.serverUrl),mt.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&&ei(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!no())throw new Error("Application key required to use Flow Service.");return new ar}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:ds,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new or(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=lr(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 y.getShadowGraphqlClient().query({query:Be,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=y.getShadowGraphqlClient(),i=(await e.query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!i.id){const s=(await e.mutate({mutation:Kc,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 Wt.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 y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:_c,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",i=await Wt.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 y.getShadowGraphqlClient().query({query:Be,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||Oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<i-parseInt(t)||r){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Xc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Wl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new Dn(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(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Oe(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...i?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:zl(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 Dn(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 dr(t),...i?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Yl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts: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 y.getShadowGraphqlClient().query({query:rc(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],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=pa(o,l),d=pa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:zo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,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,It)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(pt=>pt.option.transactionId===X.id)?.option.readOnly??!1,index:x[It].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Lo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,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),[S,w]=await Promise.all([(async()=>m.length>0?await nd(m):[])(),(async()=>f.length>0?await sn(f,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,It=L?b.get(L):void 0,pt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=Q.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",fe));const ta=fe.get(T.id)||void 0,yr=new Zc({onMutate:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:It,transaction:T,singleVariantsRenderable:pt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new R("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>yr,readOnly:k,isReloadedTransaction:pt.type==="transaction"};if(pt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Pa(ot),Ce.reloadedState=ot}else if(!k&&pt.workflowState){const ot=JSON.parse(pt.workflowState);await Pa(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:X,options:pt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let O=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Ki(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),O=[...O,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return O}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Ko(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Ta(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:_o(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Ta(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 y.getShadowGraphqlClient().query({query:Yo,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 y.getShadowGraphqlClient().mutate({mutation:cs,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const lr=async(n,t)=>(await y.getShadowGraphqlClient().query({query:os,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,rd=async n=>{const e=await y.getShadowGraphqlClient().query({query:Wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},od=async(n,t)=>(await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,sd=async n=>(await y.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ld=async n=>(await y.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function cr(){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&&!Oe(i)&&(n.Authorization=`Bearer ${i}`)}return n}async function dr(n){const e=Q.getMap("bundleOwnerIds")?.get(n),a=await cr();return{bundleOwnerId:e,...a}}async function cd(n){const e=Q.getMap("transactionOwnerIds")?.get(n),a=await cr();return{transactionOwnerId:e,...a}}const dd=async n=>{const t=await dr(n),e=await y.getShadowGraphqlClient().mutate({mutation:gc,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}`)},ud=async n=>{const t=await cd(n),e=await y.getShadowGraphqlClient().mutate({mutation:mc,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 ur(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=Pe(n.x,t.width-c,0),s.y=Pe(n.y,t.height-d,0),s}const o=n;return o.x=Pe(o.x,-i,t.width),o.y=Pe(o.y,-r,t.height),o}function Pe(n,t,e){return Math.min(Math.max(n,t),e)}class Ar{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Un(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 me(s),c=this.frameData?this.frameData[o]:void 0;ae(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=We(this.imageData.svg,this.imageData.colors||{},!1);return je(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 R("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]=ur(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 R("Frame data not set. This is a bug");if(!this.workflowManager)throw new R("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 V([new Ws(l,e,t[d]),new Ys(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]=ja(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ad{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 Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var hr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(hr||{});class gr extends Z{constructor(t,e,a){super(t,e,a);const i=e.data;this.frameService=new Ar(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return At.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 At.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(Ue.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 G.removeBackgroundFromAsset(e);t&&await At.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 vectorizeImageSelection(t=!0){const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to vectorize the image.");const a=await G.vectorizeAsset(e);t&&await At.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,vectorizedAssetKey:a.key,useOriginalAsset:!t}}),a}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await At.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?At.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return At.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 G.getLocalOrFromServer(t)}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const 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)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const hd=C.gql`
|
|
2491
2491
|
query GetLoggedInCustomer($email: String!) {
|
|
2492
2492
|
customer(emailAddress: $email) {
|
|
2493
2493
|
id
|