@spiffcommerce/core 28.0.0 → 28.0.1-beta.ac9a049c-ad73-555a-adbf-f7557a7cdbde
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.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +259 -258
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1435,7 +1435,7 @@
|
|
|
1435
1435
|
fill="${e.color}"
|
|
1436
1436
|
/>
|
|
1437
1437
|
</svg>
|
|
1438
|
-
`,n={};n["spiff-fill-shape"]={browserValue:e.color};const i=e.region||await qt(t,M.Illustration),s=Q();return{stepRegion:e.region,colors:n,id:s,svg:a,type:M.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer||0,layerIndex:i.layerIndex||Gt(t,i.layer||0),immutable:i.immutable}}static async getIllustration(t,e){const a=e.region||await qt(t,M.Illustration,e.src),n=await ot(await rr(e.src)),i=await ne(n.svg),s=Q();return{cachedObjectURL:i,stepRegion:e.region,colors:n.colors,id:s,src:e.src,svg:n.svg,type:M.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||Gt(t,a.layer||0),immutable:a.immutable}}}class G extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,G.prototype)}}const L=(r,t)=>_(r,t).elements.find(n=>n.id===r),_=(r,t)=>{const e=Object.values(t).find(a=>a.elements.some(n=>n.id===r));if(!e)throw new G;return e},X=(r,t)=>{const e=[...t.elements.filter(n=>n.id!==r.id),r],a=xa(e);return{layout:t.layout,elements:a,modificationID:Q()}},ir=async r=>{var a;const t=[...Object.keys(r.layouts)],e=[...new Set(t)];for(let n=0;n<e.length;n++){const i=e[n],s=r.layouts[i];await Promise.all(s.elements.map(async o=>{var l,c,d;if(o.type==="illustration"){const A=o;if(A.src&&!A.svg){const u=await tt(A.src),h=await ot(u);A.svg=ba(h.svg,A.width,A.height,A.colors)}}else if(o.type==="frame"){const A=o;if((l=A.pattern)!=null&&l.colors&&((c=A.pattern)!=null&&c.src)){const u=await tt((d=A.pattern)==null?void 0:d.src),h=await ot(u);A.pattern.svg=h.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 n in r.layouts){const i=r.layouts[n].elements.filter(o=>o.type===M.Illustration);for(let o=0;o<i.length;++o){const l=i[o];if(l.src&&l.svg)try{l.cachedObjectURL=await ne(l.svg)}catch(c){console.log(c)}}const s=r.layouts[n].elements.filter(o=>o.type===M.Textbox);for(let o=0;o<s.length;++o){const l=s[o];(a=l.fontData)!=null&&a.assetUrl&&await It(l.fontData.assetUrl)}}};class O{undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class sn extends O{constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Ao extends O{constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,x:this.x,y:this.y},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class uo extends O{constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,rotation:this.angle},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class ho extends O{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=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const s=a;s.scaleX=s.scaleX*this.width/e.width,s.scaleY=s.scaleY*this.height/e.height}else if(e.type==="textbox"){const s=a,o=(!s.algorithm||s.algorithm===Bt.Autosize?s.text:s.input)??"";a=ce(s,o,e)}const n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class $ extends O{constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Ta extends O{constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:Q()}}}}}class q extends O{constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(o=>o.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const o=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,o)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:Q()}}}}const n=e[e.length-1],i=n.productOverlay?n:null;i&&e.pop();let s;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)s=[...e,this.element].sort((o,l)=>o.layerIndex!==void 0&&l.layerIndex!==void 0?o.layerIndex-l.layerIndex:0);else{const o=this.assignIndex(this.element,e);this.element.layerIndex=o!==void 0?o:0,s=[...e,this.element]}return i&&s.push(i),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:Q()}}}}assignIndex(t,e){var n;if(e.length===0)return 0;const a=(n=e.filter(i=>(i.layer||0)===(t.layer||0)).sort((i,s)=>(i.layerIndex||0)-(s.layerIndex||0))[e.length-1])==null?void 0:n.layerIndex;return a!==void 0?a+1:0}}class Ct extends O{constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(i=>(i.elements.filter(o=>o.id!==this.id).length!==i.elements.length&&(e=!0),{...i,elements:i.elements.filter(o=>o.id!==this.id),modificationID:Q()}));e||console.log(`Failed to delete element ${this.id}`);const n={};return a.forEach(i=>{n[i.layout.id]=i}),{...t,layouts:n}}}class sr extends O{constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class Ke extends O{constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,textFillImage:this.imageFill},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class or extends O{constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fontSize:this.size},n=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=X(ce(a,i),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class ha extends O{constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fontData:this.fontData},n=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=X(ce(a,i),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class lr extends O{constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,align:this.align},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class go extends O{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(o=>o.id===this.id),n=e.elements[a].pattern,i=[...e.elements];i.splice(a,1,{...e.elements[a],pattern:{...n,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const s={...e,elements:i,modificationID:Q()};return{...t,layouts:{...t.layouts,[e.layout.id]:s}}}}class mo extends O{constructor(t,e,a,n,i){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=n,this.thresholdSaturation=i}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class po extends O{constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,src:this.src},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class cr extends O{constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=_(e.id,Object.values(t.layouts)),n=X(ce(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:n}}}}class _e extends O{constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class ga extends O{constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=e.colors||{},n=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:n==null?void 0:n.spotColor,pmsValue:n==null?void 0:n.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:n==null?void 0:n.spotColor,pmsValue:this.fill.pmsValue};const i={...e,colors:a},s=_(e.id,Object.values(t.layouts)),o=X(i,s);return{...t,layouts:{...t.layouts,[s.layout.id]:o}}}}class fo extends O{constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class Co extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(s=>s.elements.find(o=>o.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(s=>s.id===this.id);a.elements.push(a.elements.splice(n,1)[0]);const i=[...a.elements];return i.forEach((s,o)=>s.layerIndex=o),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:Q()}}}}}class wo extends O{constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=Object.values(t.layouts).find(o=>o.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(o=>o.id===this.id);a.elements.splice(n,1),a.elements.unshift(e);const i=[...a.elements],s=i.splice(n,1)[0];return i.splice(n,0,s),i.forEach((o,l)=>o.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:Q()}}}}}class yo extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),i=n+1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(i,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:Q()}}}}}class So extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),i=n-1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(i,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:Q()}}}}}class on{constructor(t,e,a){this.processRegion=async n=>{var l,c,d,A;const i=this.layouts.find(u=>u.panelId===n.panelId);if(!i)throw new Y(n);let s="";if(this.configuration.type===P.ProductOverlay){let u="";if((l=this.product)!=null&&l.overlayImageUrl&&(u=this.product.overlayImageUrl),s=u,!u)throw new ee(this.configuration,"Couldn't find an asset for product overlay step")}const o=this.evaluateAssetType();if(o===M.Image){const u=this.configuration.type===P.SilentIllustration?(c=this.configuration.data.asset)==null?void 0:c.fileLink:(d=this.product)==null?void 0:d.overlayImageUrl;if(!u)throw new Error("Undefined raster silent step source");const h={stepName:this.configuration.stepName,id:Q(),src:u,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable,productOverlay:this.configuration.type===P.ProductOverlay?!0:void 0,rotation:n.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:h.id,region:n},command:new q(h,i)}}else{const u=this.configuration.type===P.SilentIllustration?(A=this.configuration.data.asset)==null?void 0:A.fileLink:s,g=await ot(await(async()=>new Promise((p,f)=>{if(!u){f("Undefined vector silent step source");return}tt(u,!0).then(C=>{p(C)}).catch(C=>console.error(C))}))()),m={stepName:this.configuration.stepName,id:Q(),cachedObjectURL:await ne(g.svg),src:u,svg:g.svg,colors:g.colors,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,rotation:n.rotation,immutable:n.immutable,productOverlay:this.configuration.type===P.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:m.id,region:n},command:new q(m,i)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new ee(this.configuration,"Missing regions.");if(this.configuration.type===P.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===P.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new Y(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){var e,a,n;const t=this.configuration.type===P.ProductOverlay&&((e=this.product)!=null&&e.overlayImageUrl)?this.product.overlayImageUrl.toLowerCase():(n=(a=this.configuration.data.asset)==null?void 0:a.fileLink)==null?void 0:n.toLowerCase().split("?")[0];return t!=null&&t.startsWith("data:image/png")||t!=null&&t.endsWith(".jpeg")||t!=null&&t.endsWith(".jpg")||t!=null&&t.endsWith(".png")?M.Image:(t!=null&&t.endsWith(".svg")||t!=null&&t.startsWith("image/svg+xml"),M.Illustration)}}const dr=async r=>{const t=`${At.getServicesApiUrl()}/shortener`;try{return(await(await st(t,{method:"POST",body:JSON.stringify({longUrl:r}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new Te("Failed to shorten URL, see console.")}};class Ar{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,n=3e3,i=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}class vo{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{var A,u;const c=(A=n==null?void 0:n.storage)==null?void 0:A.videoShortUrl,d=(u=n==null?void 0:n.storage)==null?void 0:u.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,n){const i=async()=>{var m,p;const h=(await Be([e]))[0],g=(p=(m=h==null?void 0:h.versions)==null?void 0:m.find(f=>f.name==="mpeg4"))==null?void 0:p.link;return{asset:h,link:g}},s=await new Promise((h,g)=>{new Ar(async()=>!!(await i()).link,async()=>{const m=await i();if(!m.link||!m.link)throw new Nt(m.asset);h({rel:"mpeg4",href:m.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new Ct(h.id)));const o=n.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(o+n.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([s]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new Te("Cannot create QR code, URL too long.");const d=await dr(c);if(!n.data||!n.data.regions)throw new ee(n,"Missing regions.");const A=await this.regionElements(n),u=await this.command(d,A,a,n.stepName);return u&&(u.command&&a.getCommandDispatcher()(u.command),u.followup&&await u.followup()),await a.setSelectionsAndElements(n.stepName,[],A,async()=>{a.updateStorage(n.stepName,{videoShortUrl:d,videoUrl:s.href})}),d}async regionElements(t){const e=a=>({id:Q(),region:a});return t.data.regions.map(e)}async command(t,e,a,n){const i=a.getLayouts(),o=`data:image/svg+xml;base64,${btoa(await yn.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,A=i.find(u=>u.panelId===(d==null?void 0:d.panelId));if(!A&&d)throw new Y(d);if(A&&!d)throw new Error("Region not found");if(!A||!d)throw new Error("Neither a region or layout found!");return new q({stepRegion:d,stepName:n,id:c.id,src:o,type:M.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},A)});return{command:new $(l),followup:async()=>{}}}}const Na=new vo;class De{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return Aa(e);const a=t.asset;if(!a)throw new mt(t);const n=a.fileLink;if(n)return tt(n,!0);throw new Nt(a)}}async init(t,e,a){const n=a==null?void 0:a.serializableWorkflow.steps.find(o=>o.stepName===t.stepName);if(n!=null&&n.storage&&Object.keys(n.storage).length!==0||n!=null&&n.selectedVariants&&n.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let i;const s=e.getWorkflowExperience().getBundle();if(s&&t.globalPropertyAspectConfigurations){const o=s.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=o.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(i=(await U.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option&&t.option.variants&&t.option.variants.length>0){const o=t.option,l=H.getDefaultVariant(o);return l?this.selectVariantCommand(t,l,[],e,void 0,i||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,i||t.data.placeholderImageUrl)}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName).map(d=>({id:d.id,region:d.stepRegion}));if(!t.option||(t.option.variants||[]).length===0){const d=t.data.regions.map(A=>Aa(A));e.updateStorage(t.stepName,{currentFrameSources:d})}if(n){const d=async()=>{var g,m,p,f,C;const A=(g=n.storage)==null?void 0:g.colors,u=(m=n.storage)==null?void 0:m.framePatternSrc,h=(p=n.storage)==null?void 0:p.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:h,framePatternSrc:u}),u){const w=(f=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:f.frameService;if(!w)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,w,!0,A),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(h!=null&&h.some(w=>w.zoom)){const w=(C=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:C.frameService;if(!w)throw new Error("Frame service unavailable, cannot load pattern!");w.updateOffsets(h)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const A=n.selectedVariants[0].id;if(t.option&&A){const u=(c=t.option.variants)==null?void 0:c.find(h=>h.id===A);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const h=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(u,g)));e.updateStorage(t.stepName,{currentFrameSources:h}),await d()})}}else await e.setSelectionsAndElements(t.stepName,[],l,d)}}async availableColors(t,e){var n;const a=t.data.colorOption;return((n=a==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]}selectImage(t,e,a,n=!0){var l;const i=De.patternSource(e),s=(l=a.getStepStorage(t.stepName))==null?void 0:l.framePatternSrc;if(s&&s===i)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const o=e.fileLink||"";return o.endsWith(".pdf")||o.endsWith(".eps")||o.endsWith(".ai")?new Promise(c=>{a.addPoller(new Ar(async()=>{var h;const A=(h=(await U.getFromServer(e.key||"")).versions)==null?void 0:h.find(g=>g.name==="svg");return A?(await st(A.link)).status===200:!1},()=>{U.getLocalOrFromServer(e.key||"").then(d=>{this.loadPatternFromAsset(d,t,a,n).then(c)})},()=>{throw new Te("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,n)}async selectVariant(t,e,a,n,i){const s=await this.selectVariantCommand(t,e,a,n,i);s&&(s.command&&n.getCommandDispatcher()(s.command),s.followup&&await s.followup())}getCreateElementCommand(t,e,a,n){return new q({id:t,type:M.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/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,pattern:n.pattern,immutable:e.immutable},a)}async loadPatternFromString(t,e,a=!0,n=void 0,i){if(t.endsWith("svg")){const s=await ka(t),o=s.width,l=s.height,c=await tt(t);if(i){const u=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(u&&u.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await ot(c),A={src:t,width:o,height:l,aspect:o/l,svg:d.svg,colors:n??d.colors};dt.set(t,A),e.setPatternData(A,a)}else{const s=await Ne(t,!0),o=await oe(s),l={src:t,width:o.width,height:o.height,aspect:o.width/o.height,svg:void 0,colors:void 0};dt.set(t,l),e.setPatternData(l,a)}}changeColors(t,e,a){var s,o;const n=(s=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:s.frameService;if(!n||!((o=n.getImageData())!=null&&o.svg)){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const i=this.calculateColorMetadata(n,t,a);e.updateMetadata(t.stepName,{colors:i.metadataColors}),e.updateStorage(t.stepName,{colors:i.storageColors}),n.setPatternData({...n.getImageData(),colors:i.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){var s,o;const a=(s=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:s.frameService;if(!a)return 0;const n=((o=a.getImageData())==null?void 0:o.colors)??{},i=[];for(const l in n){const c=n[l];if(c.pmsValue){const d=c.pmsValue.trim().toLocaleLowerCase();i.includes(d)||i.push(d)}else if(c.browserValue){const d=$n(c.browserValue);i.includes(d)||i.push(d)}}return i.length}calculateColorMetadata(t,e,a){var l,c;if(!((l=t.getImageData())!=null&&l.svg))return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const n={...t.getImageData().colors??{}},i={};Object.entries(n).forEach(([d,A])=>{const u={browserValue:A.browserValue};i[d]=u});for(const[d,A]of a.entries())n[d]={browserValue:A.browserValue,pmsValue:A.pmsValue},i[d]=A;let s=Array.from(Object.values(n)).map(d=>d.browserValue);const o=e.data.colorOption;return o&&((c=o.variants)==null||c.forEach(d=>{s=s.map(A=>{var u;return A.toLowerCase()===((u=d.color)==null?void 0:u.toLowerCase())?d.name:A})})),{newColors:n,metadataColors:s,storageColors:i}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,n,i,s){var h;const o=(h=n.getWorkflowExperience().getStepById(t.stepName))==null?void 0:h.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(e,g)));i&&i(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(g,m)=>{const p=await Ae(l[m]),f=o.getImageData(),C=a.map(I=>new Ct(I.id)),w=f?Fa(f,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,S=f?{id:Q(),src:f.src,x:(w==null?void 0:w.x)||0,y:(w==null?void 0:w.y)||0,width:f.width,height:f.height,scaleX:(w==null?void 0:w.zoom)||1,scaleY:(w==null?void 0:w.zoom)||1,rotation:0}:void 0,y=Q(),b=n.getLayouts().find(I=>I.panelId===g.panelId);if(!b)throw new Y(g);return{command:this.getCreateElementCommand(y,g,b,{frameData:p,pattern:S,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:y,region:g},removeExistingCommands:C}})),A=d.map(g=>g.command),u=d.map(g=>g.removeExistingCommands).flat();return{command:new $([...A,...u]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(g=>g.regionEl)],async()=>{var g;if(n.updateStorage(t.stepName,{currentFrameSources:l}),s){const m=(g=n.getWorkflowExperience().getStepById(t.stepName))==null?void 0:g.frameService;if(!m)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(s,m,!0)}})}}}static patternSource(t){var n;const e=(n=t.versions)==null?void 0:n.find(i=>i.name==="svg");if(e!=null&&e.link)return e.link;const a=t.fileLink;if(a)return a;throw new Nt(t)}async loadPatternFromAsset(t,e,a,n){var c,d;const i=De.patternSource(t),s=a.markUpdatePending(),o=(c=a.getWorkflowExperience().getStepById(e.stepName))==null?void 0:c.frameService;if(!o)throw a.markUpdateCompleted(s),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(i,o,n,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(A){throw a.markUpdateCompleted(s),A}const l=this.calculateColorMetadata(o,e,new Map(Object.entries(((d=o.getImageData())==null?void 0:d.colors)??{})));a.updateMetadata(e.stepName,{image:i,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:i,colors:l.storageColors}),a.markUpdateCompleted(s),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(A=>A.stepID===e.stepName)),this.validateColorCount(e,a)}}const ut=new De;class Eo{async getIllustrationBody(t){return new Promise(e=>{tt(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,n){return new q({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:M.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},a)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return L(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const n=t.option;if(!n)return null;if(a)return this.reload(t,e,a);{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantCommand(t,i,[],()=>{},e)}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var h;e.updateMetadata(t.stepName,{colors:(h=n.storage)==null?void 0:h.colors}),e.setMandatoryFulfilled(t.stepName,!0)})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){var n;const a=t.data.colorOption;return a?a?(n=a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})):[]:[]}async changeColorsCommand(t,e,a,n,i){const s={};for(const[d,A]of i.entries())typeof A=="string"?s[d]={browserValue:A,spotColor:void 0,pmsValue:void 0}:s[d]={browserValue:A.browserValue,spotColor:A.spotColor,pmsValue:A.pmsValue};const o=ba(t,e,a,s),l=await ne(o),c=[];for(const d of n){for(const[A,u]of i.entries())c.push(new ga(d,A,u));c.push(new fo(d,o,l))}return new $(c)}async changeColors(t,e,a,n,i){var h,g;if(e.length===0)return;const s=L(e[0].id,n().map(m=>m.layoutState)),o={...s.colors},l={};Object.entries(o).forEach(([m,p])=>{const f={browserValue:p.browserValue,pmsValue:p.pmsValue},C=p.spotColor;C&&(f.spotColor={profileName:C.profileName,namedColor:C.namedColor}),l[m]=f});for(const[m,p]of i.entries()){const f=typeof p=="string"?p:p.browserValue,C=typeof p=="string"?void 0:p.pmsValue;o[m]={browserValue:f,spotColor:(h=o[m])==null?void 0:h.spotColor,pmsValue:C},l[m]={browserValue:f}}let c=Array.from(Object.values(o)).map(m=>m.browserValue);const d=t.data.colorOption;d&&((g=d.variants)==null||g.forEach(m=>{c=c.map(p=>{var f;return p.toLowerCase()===((f=m.color)==null?void 0:f.toLowerCase())?m.name:p})})),a.updateMetadata(t.stepName,{colors:c});const A=new Map;if(Object.entries(o).forEach(([m,p])=>{A.set(m,p)}),!s.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(s.svg,s.width,s.height,e.map(m=>m.id),A);a.updateStorage(t.stepName,{colors:l}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,n,i){const s=await this.selectVariantCommand(t,e,a,n,i);s&&(s.command&&i.getCommandDispatcher()(s.command),s.followup&&await s.followup())}async selectVariantCommand(t,e,a,n,i){var f;if(!t.data||!t.data.regions)throw new ee(t,"Missing regions.");n(!0);const s=a.map(C=>new Ct(C.id));t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new mt(e);const l=o.fileLink;if(!l)throw new Nt(o);const c=await ot(await this.getIllustrationBody(l)),d=await ne(c.svg),A=C=>{const w=i.getLayouts().find(y=>y.panelId===C.panelId);if(!w)throw new Y(C);const S=Q();return{regionElement:{id:S,region:C},command:this.getCreateElementCommand(S,C,w,{stepName:t.stepName,src:l,objectURL:d,svg:c})}},u=t.data.regions.map(A),g=[...u.map(C=>C.command),...s];let m=Array.from(Object.values(c.colors)).map(C=>C.browserValue);const p=t.data.colorOption;return p&&((f=p.variants)==null||f.forEach(C=>{m=m.map(w=>{var S;return w.toLowerCase()===((S=C.color)==null?void 0:S.toLowerCase())?C.name:w})})),i.updateMetadata(t.stepName,{colors:m}),{command:new $(g),followup:async()=>{var w,S;await i.setSelectionsAndElements(t.stepName,[e],u.map(y=>y.regionElement),async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)});const C=((w=o.assetConfiguration)==null?void 0:w.defaultColorVariants)||[];if(C.length!==0){const y={};(((S=o.assetConfiguration)==null?void 0:S.channelNumbers)||[]).forEach(b=>{var x;const I=C.find(F=>F.channelNumber===b.number);I&&(y[`${b.id.replace(/\W/g,"")}`]={browserValue:((x=I==null?void 0:I.variant)==null?void 0:x.color)||""})}),await this.changeColors(t,u.map(b=>b.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map(Object.entries(y)))}if(t.data.colorPickerEnabled){const y=await this.availableColors(t,i)||[],E=Object.keys(c.colors),b=y.length===1&&E.length===1;if(b){const I=y[0],x=E[0];await this.changeColors(t,u.map(F=>F.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map([[x,I.variant.color]]))}!b&&C.length===0&&await this.changeColors(t,u.map(I=>I.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map)}}}}}const Jt=new Eo;class bo{async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(!l)throw new te(t);if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=A.material,h=o.map(g=>({id:g.id,region:g.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],h,async()=>{const g=e.getModelContainer();if(g){const m=t.data.targetMaterials.map(p=>g.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(m).then(()=>e.setMandatoryFulfilled(t.stepName,!0))}})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantLambda(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,n){const i=a.getModelContainer();n(!0);const s=e.material;if(!s)throw n(!1),new mt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{i&&t.data.targetMaterials.forEach(o=>{t.option&&i.applyMaterialVariant(o,t.option.id||"",s)}),a.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}})}}}}const Qa=new bo;class Bo{async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var g;const h=e.getModelContainer();if(h&&t.option){const m=(g=A.asset)==null?void 0:g.fileLink;if(!m)throw new mt(A);await h.applyModelVariant(t.stepName||"",{model:m,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantLambda(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,n){var s;n(!0);const i=(s=e.asset)==null?void 0:s.fileLink;if(!i)throw new mt(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:i,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1),a.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}})}}}}const Ra=new Bo;class Io{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{var c,d;e.updateStorage(t.stepName,{text:(c=n==null?void 0:n.storage)==null?void 0:c.text}),e.setMandatoryFulfilled(t.stepName,((d=n==null?void 0:n.storage)==null?void 0:d.text)!=="")})}async changeText(t,e,a,n){const i=await this.changeTextCommand(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,a,n){var d;const i=a.getRegionElements(t.stepName),s=(d=a.getStepSpecificServices(t.stepName))==null?void 0:d.module;if(!s)return console.error("Missing module."),null;const o=a.getProfanities(),l=this.validateInput(t,e,o,n);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(A,u,h)=>{const g=h||Q(),p=a.getLayouts().find(C=>C.panelId===u.panelId);if(!p)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Ct(g)),f.push(new q({stepRegion:u,stepName:t.stepName,colors:{},id:g,svg:A,type:M.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},p)),{id:g,region:u,command:new $(f)}};if(i.length>0){const u=i.map(h=>{if(!h.region)return null;const g=s.svgPrint(e,h.region);return c(g,h.region,h.id)}).filter(h=>!!h).filter(h=>!!h).map(h=>h&&h.command);return{command:new $(u),followup:async()=>{}}}else{const A=t.data.regions.map(h=>c(s.svgPrint(e,h),h)),u=A.filter(h=>!!h).map(h=>h&&h.command);return{command:new $(u),followup:async()=>{const h=A.filter(g=>g).map(g=>g&&{id:g.id,region:g.region});await a.setSelectionsAndElements(t.stepName,[],h)}}}}validateInput(t,e,a,n){if(t.data&&t.data.maxLength){const s=t.data.maxLength;if(e.length>s)return n("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const i=ra.split(e.toLowerCase());for(const s of i)for(const o in a){const l=a[o].toLowerCase().replace(/\s/g,"");if(s===l)return n("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return n(""),{input:e,helperData:{}}}}const Oa=new Io;class Po{async init(t,e,a){const n=t.option;if(!n)return null;if(a)await this.reload(t,e,a);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,()=>{});return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantCommand(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,a,n){const i=e.asset;if(!i)throw new mt(e);const s=i==null?void 0:i.fileLink;if(!s)return console.error("No URL for picture!"),null;n(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(A=>new Ct(A.id)),c=A=>{const h=a.getLayouts().find(m=>m.panelId===A.panelId);if(!h)throw new Y(A);const g=Q();return{regionElement:{id:g,region:A},command:new q({stepName:t.stepName,stepRegion:A,id:g,src:s,type:M.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},h)}},d=t.data.regions.map(c);return{command:new $([...l,...d.map(A=>A.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(A=>A.regionElement),async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)})}}}}const $a=new Po;class Do{async init(t,e,a){const n=t.option;if(!n)return null;if(a)await this.reload(t,e,a);else{const i=n.variants;if(H.getDefaultVariant(n)){const o=i==null?void 0:i.find(l=>{var c;return l.id===((c=n.defaultVariant)==null?void 0:c.id)});return this.selectVariantLambda(t,(o==null?void 0:o.id)||"",e)}}return null}async reload(t,e,a){var s;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),i=t.option;if(n!=null&&n.selectedVariants){const o=n.selectedVariants[0].id;if(i&&o){const l=(s=i.variants)==null?void 0:s.find(c=>c.id===o);l&&await e.setSelectionsAndElements(t.stepName,[l],[])}}}async selectVariant(t,e,a){await a.getInitializationPromise();const n=await this.selectVariantLambda(t,e,a);n&&(n.command&&a.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,a){const n=t.option;if(!n)return null;const i=n.variants;if(!i)return null;const s=i.length>1?i.find(o=>o.id===e):i[0];if(!s)throw new Error(`Failed to find selected variant ${e} in option ${n.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[s],[],async()=>{a.setMandatoryFulfilled(t.stepName,!0)})}}}}const Ua=new Do;class xo{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){var a;const e=t.option;return e?((a=e.variants)==null?void 0:a.map(n=>({fill:n.color,stroke:n.color,variant:n})))||[]:[]}setCustomColor(t,e,a){const n=a.getLayouts(),s=(a.getRegionElements(e.stepName)||[]).map(o=>{const l=o.region;if(!n.find(d=>d.panelId===(l==null?void 0:l.panelId)))throw new Y(l);return new ga(o.id,this.shapeFillId,t)}).filter(o=>!!o);a.getCommandDispatcher()(new $(s)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);return i?this.selectVariantCommand(t,{fill:i.color,stroke:i.color,variant:i},[],e):null}return null}async selectVariant(t,e,a,n){const i=await this.selectVariantCommand(t,e,a,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var h;e.updateStorage(t.stepName,{colour:((h=n==null?void 0:n.storage)==null?void 0:h.colour)||""}),e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariantCommand(t,e,a,n){var l;const i=n.getLayouts(),s=(l=n.getStepStorage(t.stepName))==null?void 0:l.colour,o=()=>{var c,d;if(((c=e.variant)==null?void 0:c.color)==="#custom")return s||"#FFFFFF";if((d=e.variant)!=null&&d.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const c=A=>{const u=A.region;if(!i.find(m=>m.panelId===(u==null?void 0:u.panelId)))throw new Y(u);const g=o();return new ga(A.id,this.shapeFillId,g)},d=a.map(c).filter(A=>!!A);return{command:new $(d),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),n.updateStorage(t.stepName,{colour:o()})}}}else{const c=h=>{const g=i.find(w=>w.panelId===h.panelId);if(!g)throw new Y(h);const m=o(),p=`
|
|
1438
|
+
`,n={};n["spiff-fill-shape"]={browserValue:e.color};const i=e.region||await qt(t,M.Illustration),s=Q();return{stepRegion:e.region,colors:n,id:s,svg:a,type:M.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer||0,layerIndex:i.layerIndex||Gt(t,i.layer||0),immutable:i.immutable}}static async getIllustration(t,e){const a=e.region||await qt(t,M.Illustration,e.src),n=await ot(await rr(e.src)),i=await ne(n.svg),s=Q();return{cachedObjectURL:i,stepRegion:e.region,colors:n.colors,id:s,src:e.src,svg:n.svg,type:M.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||Gt(t,a.layer||0),immutable:a.immutable}}}class G extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,G.prototype)}}const L=(r,t)=>_(r,t).elements.find(n=>n.id===r),_=(r,t)=>{const e=Object.values(t).find(a=>a.elements.some(n=>n.id===r));if(!e)throw new G;return e},Z=(r,t)=>{const e=[...t.elements.filter(n=>n.id!==r.id),r],a=xa(e);return{layout:t.layout,elements:a,modificationID:Q()}},ir=async r=>{var a;const t=[...Object.keys(r.layouts)],e=[...new Set(t)];for(let n=0;n<e.length;n++){const i=e[n],s=r.layouts[i];await Promise.all(s.elements.map(async o=>{var l,c,d;if(o.type==="illustration"){const A=o;if(A.src&&!A.svg){const u=await tt(A.src),h=await ot(u);A.svg=ba(h.svg,A.width,A.height,A.colors)}}else if(o.type==="frame"){const A=o;if((l=A.pattern)!=null&&l.colors&&((c=A.pattern)!=null&&c.src)){const u=await tt((d=A.pattern)==null?void 0:d.src),h=await ot(u);A.pattern.svg=h.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 n in r.layouts){const i=r.layouts[n].elements.filter(o=>o.type===M.Illustration);for(let o=0;o<i.length;++o){const l=i[o];if(l.src&&l.svg)try{l.cachedObjectURL=await ne(l.svg)}catch(c){console.log(c)}}const s=r.layouts[n].elements.filter(o=>o.type===M.Textbox);for(let o=0;o<s.length;++o){const l=s[o];(a=l.fontData)!=null&&a.assetUrl&&await It(l.fontData.assetUrl)}}};class O{undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class sn extends O{constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Ao extends O{constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,x:this.x,y:this.y},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class uo extends O{constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,rotation:this.angle},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class ho extends O{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=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const s=a;s.scaleX=s.scaleX*this.width/e.width,s.scaleY=s.scaleY*this.height/e.height}else if(e.type==="textbox"){const s=a,o=(!s.algorithm||s.algorithm===Bt.Autosize?s.text:s.input)??"";a=ce(s,o,e)}const n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class $ extends O{constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Ta extends O{constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:Q()}}}}}class q extends O{constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(o=>o.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const o=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,o)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:Q()}}}}const n=e[e.length-1],i=n.productOverlay?n:null;i&&e.pop();let s;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)s=[...e,this.element].sort((o,l)=>o.layerIndex!==void 0&&l.layerIndex!==void 0?o.layerIndex-l.layerIndex:0);else{const o=this.assignIndex(this.element,e);this.element.layerIndex=o!==void 0?o:0,s=[...e,this.element]}return i&&s.push(i),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:Q()}}}}assignIndex(t,e){var n;if(e.length===0)return 0;const a=(n=e.filter(i=>(i.layer||0)===(t.layer||0)).sort((i,s)=>(i.layerIndex||0)-(s.layerIndex||0))[e.length-1])==null?void 0:n.layerIndex;return a!==void 0?a+1:0}}class Ct extends O{constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(i=>(i.elements.filter(o=>o.id!==this.id).length!==i.elements.length&&(e=!0),{...i,elements:i.elements.filter(o=>o.id!==this.id),modificationID:Q()}));e||console.log(`Failed to delete element ${this.id}`);const n={};return a.forEach(i=>{n[i.layout.id]=i}),{...t,layouts:n}}}class sr extends O{constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class Ke extends O{constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,textFillImage:this.imageFill},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class or extends O{constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fontSize:this.size},n=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=Z(ce(a,i),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class ha extends O{constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fontData:this.fontData},n=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=Z(ce(a,i),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class lr extends O{constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,align:this.align},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class go extends O{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(o=>o.id===this.id),n=e.elements[a].pattern,i=[...e.elements];i.splice(a,1,{...e.elements[a],pattern:{...n,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const s={...e,elements:i,modificationID:Q()};return{...t,layouts:{...t.layouts,[e.layout.id]:s}}}}class mo extends O{constructor(t,e,a,n,i){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=n,this.thresholdSaturation=i}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class po extends O{constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,src:this.src},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class cr extends O{constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=_(e.id,Object.values(t.layouts)),n=Z(ce(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:n}}}}class _e extends O{constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class ga extends O{constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=e.colors||{},n=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:n==null?void 0:n.spotColor,pmsValue:n==null?void 0:n.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:n==null?void 0:n.spotColor,pmsValue:this.fill.pmsValue};const i={...e,colors:a},s=_(e.id,Object.values(t.layouts)),o=Z(i,s);return{...t,layouts:{...t.layouts,[s.layout.id]:o}}}}class fo extends O{constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class Co extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(s=>s.elements.find(o=>o.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(s=>s.id===this.id);a.elements.push(a.elements.splice(n,1)[0]);const i=[...a.elements];return i.forEach((s,o)=>s.layerIndex=o),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:Q()}}}}}class wo extends O{constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=Object.values(t.layouts).find(o=>o.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(o=>o.id===this.id);a.elements.splice(n,1),a.elements.unshift(e);const i=[...a.elements],s=i.splice(n,1)[0];return i.splice(n,0,s),i.forEach((o,l)=>o.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:Q()}}}}}class yo extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),i=n+1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(i,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:Q()}}}}}class So extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),i=n-1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(i,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:Q()}}}}}class on{constructor(t,e,a){this.processRegion=async n=>{var l,c,d,A;const i=this.layouts.find(u=>u.panelId===n.panelId);if(!i)throw new Y(n);let s="";if(this.configuration.type===P.ProductOverlay){let u="";if((l=this.product)!=null&&l.overlayImageUrl&&(u=this.product.overlayImageUrl),s=u,!u)throw new ee(this.configuration,"Couldn't find an asset for product overlay step")}const o=this.evaluateAssetType();if(o===M.Image){const u=this.configuration.type===P.SilentIllustration?(c=this.configuration.data.asset)==null?void 0:c.fileLink:(d=this.product)==null?void 0:d.overlayImageUrl;if(!u)throw new Error("Undefined raster silent step source");const h={stepName:this.configuration.stepName,id:Q(),src:u,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable,productOverlay:this.configuration.type===P.ProductOverlay?!0:void 0,rotation:n.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:h.id,region:n},command:new q(h,i)}}else{const u=this.configuration.type===P.SilentIllustration?(A=this.configuration.data.asset)==null?void 0:A.fileLink:s,g=await ot(await(async()=>new Promise((p,f)=>{if(!u){f("Undefined vector silent step source");return}tt(u,!0).then(C=>{p(C)}).catch(C=>console.error(C))}))()),m={stepName:this.configuration.stepName,id:Q(),cachedObjectURL:await ne(g.svg),src:u,svg:g.svg,colors:g.colors,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,rotation:n.rotation,immutable:n.immutable,productOverlay:this.configuration.type===P.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:m.id,region:n},command:new q(m,i)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new ee(this.configuration,"Missing regions.");if(this.configuration.type===P.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===P.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new Y(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){var e,a,n;const t=this.configuration.type===P.ProductOverlay&&((e=this.product)!=null&&e.overlayImageUrl)?this.product.overlayImageUrl.toLowerCase():(n=(a=this.configuration.data.asset)==null?void 0:a.fileLink)==null?void 0:n.toLowerCase().split("?")[0];return t!=null&&t.startsWith("data:image/png")||t!=null&&t.endsWith(".jpeg")||t!=null&&t.endsWith(".jpg")||t!=null&&t.endsWith(".png")?M.Image:(t!=null&&t.endsWith(".svg")||t!=null&&t.startsWith("image/svg+xml"),M.Illustration)}}const dr=async r=>{const t=`${At.getServicesApiUrl()}/shortener`;try{return(await(await st(t,{method:"POST",body:JSON.stringify({longUrl:r}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new Te("Failed to shorten URL, see console.")}};class Ar{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,n=3e3,i=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}class vo{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{var A,u;const c=(A=n==null?void 0:n.storage)==null?void 0:A.videoShortUrl,d=(u=n==null?void 0:n.storage)==null?void 0:u.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,n){const i=async()=>{var m,p;const h=(await Be([e]))[0],g=(p=(m=h==null?void 0:h.versions)==null?void 0:m.find(f=>f.name==="mpeg4"))==null?void 0:p.link;return{asset:h,link:g}},s=await new Promise((h,g)=>{new Ar(async()=>!!(await i()).link,async()=>{const m=await i();if(!m.link||!m.link)throw new Nt(m.asset);h({rel:"mpeg4",href:m.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new Ct(h.id)));const o=n.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(o+n.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([s]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new Te("Cannot create QR code, URL too long.");const d=await dr(c);if(!n.data||!n.data.regions)throw new ee(n,"Missing regions.");const A=await this.regionElements(n),u=await this.command(d,A,a,n.stepName);return u&&(u.command&&a.getCommandDispatcher()(u.command),u.followup&&await u.followup()),await a.setSelectionsAndElements(n.stepName,[],A,async()=>{a.updateStorage(n.stepName,{videoShortUrl:d,videoUrl:s.href})}),d}async regionElements(t){const e=a=>({id:Q(),region:a});return t.data.regions.map(e)}async command(t,e,a,n){const i=a.getLayouts(),o=`data:image/svg+xml;base64,${btoa(await yn.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,A=i.find(u=>u.panelId===(d==null?void 0:d.panelId));if(!A&&d)throw new Y(d);if(A&&!d)throw new Error("Region not found");if(!A||!d)throw new Error("Neither a region or layout found!");return new q({stepRegion:d,stepName:n,id:c.id,src:o,type:M.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},A)});return{command:new $(l),followup:async()=>{}}}}const Na=new vo;class De{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return Aa(e);const a=t.asset;if(!a)throw new mt(t);const n=a.fileLink;if(n)return tt(n,!0);throw new Nt(a)}}async init(t,e,a){const n=a==null?void 0:a.serializableWorkflow.steps.find(o=>o.stepName===t.stepName);if(n!=null&&n.storage&&Object.keys(n.storage).length!==0||n!=null&&n.selectedVariants&&n.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let i;const s=e.getWorkflowExperience().getBundle();if(s&&t.globalPropertyAspectConfigurations){const o=s.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=o.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(i=(await U.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option&&t.option.variants&&t.option.variants.length>0){const o=t.option,l=H.getDefaultVariant(o);return l?this.selectVariantCommand(t,l,[],e,void 0,i||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,i||t.data.placeholderImageUrl)}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName).map(d=>({id:d.id,region:d.stepRegion}));if(!t.option||(t.option.variants||[]).length===0){const d=t.data.regions.map(A=>Aa(A));e.updateStorage(t.stepName,{currentFrameSources:d})}if(n){const d=async()=>{var g,m,p,f,C;const A=(g=n.storage)==null?void 0:g.colors,u=(m=n.storage)==null?void 0:m.framePatternSrc,h=(p=n.storage)==null?void 0:p.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:h,framePatternSrc:u}),u){const w=(f=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:f.frameService;if(!w)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,w,!0,A),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(h!=null&&h.some(w=>w.zoom)){const w=(C=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:C.frameService;if(!w)throw new Error("Frame service unavailable, cannot load pattern!");w.updateOffsets(h)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const A=n.selectedVariants[0].id;if(t.option&&A){const u=(c=t.option.variants)==null?void 0:c.find(h=>h.id===A);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const h=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(u,g)));e.updateStorage(t.stepName,{currentFrameSources:h}),await d()})}}else await e.setSelectionsAndElements(t.stepName,[],l,d)}}async availableColors(t,e){var n;const a=t.data.colorOption;return((n=a==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]}selectImage(t,e,a,n=!0){var l;const i=De.patternSource(e),s=(l=a.getStepStorage(t.stepName))==null?void 0:l.framePatternSrc;if(s&&s===i)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const o=e.fileLink||"";return o.endsWith(".pdf")||o.endsWith(".eps")||o.endsWith(".ai")?new Promise(c=>{a.addPoller(new Ar(async()=>{var h;const A=(h=(await U.getFromServer(e.key||"")).versions)==null?void 0:h.find(g=>g.name==="svg");return A?(await st(A.link)).status===200:!1},()=>{U.getLocalOrFromServer(e.key||"").then(d=>{this.loadPatternFromAsset(d,t,a,n).then(c)})},()=>{throw new Te("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,n)}async selectVariant(t,e,a,n,i){const s=await this.selectVariantCommand(t,e,a,n,i);s&&(s.command&&n.getCommandDispatcher()(s.command),s.followup&&await s.followup())}getCreateElementCommand(t,e,a,n){return new q({id:t,type:M.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/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,pattern:n.pattern,immutable:e.immutable},a)}async loadPatternFromString(t,e,a=!0,n=void 0,i){if(t.endsWith("svg")){const s=await ka(t),o=s.width,l=s.height,c=await tt(t);if(i){const u=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(u&&u.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await ot(c),A={src:t,width:o,height:l,aspect:o/l,svg:d.svg,colors:n??d.colors};dt.set(t,A),e.setPatternData(A,a)}else{const s=await Ne(t,!0),o=await oe(s),l={src:t,width:o.width,height:o.height,aspect:o.width/o.height,svg:void 0,colors:void 0};dt.set(t,l),e.setPatternData(l,a)}}changeColors(t,e,a){var s,o;const n=(s=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:s.frameService;if(!n||!((o=n.getImageData())!=null&&o.svg)){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const i=this.calculateColorMetadata(n,t,a);e.updateMetadata(t.stepName,{colors:i.metadataColors}),e.updateStorage(t.stepName,{colors:i.storageColors}),n.setPatternData({...n.getImageData(),colors:i.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){var s,o;const a=(s=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:s.frameService;if(!a)return 0;const n=((o=a.getImageData())==null?void 0:o.colors)??{},i=[];for(const l in n){const c=n[l];if(c.pmsValue){const d=c.pmsValue.trim().toLocaleLowerCase();i.includes(d)||i.push(d)}else if(c.browserValue){const d=$n(c.browserValue);i.includes(d)||i.push(d)}}return i.length}calculateColorMetadata(t,e,a){var l,c;if(!((l=t.getImageData())!=null&&l.svg))return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const n={...t.getImageData().colors??{}},i={};Object.entries(n).forEach(([d,A])=>{const u={browserValue:A.browserValue};i[d]=u});for(const[d,A]of a.entries())n[d]={browserValue:A.browserValue,pmsValue:A.pmsValue},i[d]=A;let s=Array.from(Object.values(n)).map(d=>d.browserValue);const o=e.data.colorOption;return o&&((c=o.variants)==null||c.forEach(d=>{s=s.map(A=>{var u;return A.toLowerCase()===((u=d.color)==null?void 0:u.toLowerCase())?d.name:A})})),{newColors:n,metadataColors:s,storageColors:i}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,n,i,s){var h;const o=(h=n.getWorkflowExperience().getStepById(t.stepName))==null?void 0:h.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(e,g)));i&&i(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(g,m)=>{const p=await Ae(l[m]),f=o.getImageData(),C=a.map(I=>new Ct(I.id)),w=f?Fa(f,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,S=f?{id:Q(),src:f.src,x:(w==null?void 0:w.x)||0,y:(w==null?void 0:w.y)||0,width:f.width,height:f.height,scaleX:(w==null?void 0:w.zoom)||1,scaleY:(w==null?void 0:w.zoom)||1,rotation:0}:void 0,y=Q(),b=n.getLayouts().find(I=>I.panelId===g.panelId);if(!b)throw new Y(g);return{command:this.getCreateElementCommand(y,g,b,{frameData:p,pattern:S,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:y,region:g},removeExistingCommands:C}})),A=d.map(g=>g.command),u=d.map(g=>g.removeExistingCommands).flat();return{command:new $([...A,...u]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(g=>g.regionEl)],async()=>{var g;if(n.updateStorage(t.stepName,{currentFrameSources:l}),s){const m=(g=n.getWorkflowExperience().getStepById(t.stepName))==null?void 0:g.frameService;if(!m)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(s,m,!0)}})}}}static patternSource(t){var n;const e=(n=t.versions)==null?void 0:n.find(i=>i.name==="svg");if(e!=null&&e.link)return e.link;const a=t.fileLink;if(a)return a;throw new Nt(t)}async loadPatternFromAsset(t,e,a,n){var c,d;const i=De.patternSource(t),s=a.markUpdatePending(),o=(c=a.getWorkflowExperience().getStepById(e.stepName))==null?void 0:c.frameService;if(!o)throw a.markUpdateCompleted(s),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(i,o,n,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(A){throw a.markUpdateCompleted(s),A}const l=this.calculateColorMetadata(o,e,new Map(Object.entries(((d=o.getImageData())==null?void 0:d.colors)??{})));a.updateMetadata(e.stepName,{image:i,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:i,colors:l.storageColors}),a.markUpdateCompleted(s),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(A=>A.stepID===e.stepName)),this.validateColorCount(e,a)}}const ut=new De;class Eo{async getIllustrationBody(t){return new Promise(e=>{tt(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,n){return new q({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:M.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},a)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return L(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const n=t.option;if(!n)return null;if(a)return this.reload(t,e,a);{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantCommand(t,i,[],()=>{},e)}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var h;e.updateMetadata(t.stepName,{colors:(h=n.storage)==null?void 0:h.colors}),e.setMandatoryFulfilled(t.stepName,!0)})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){var n;const a=t.data.colorOption;return a?a?(n=a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})):[]:[]}async changeColorsCommand(t,e,a,n,i){const s={};for(const[d,A]of i.entries())typeof A=="string"?s[d]={browserValue:A,spotColor:void 0,pmsValue:void 0}:s[d]={browserValue:A.browserValue,spotColor:A.spotColor,pmsValue:A.pmsValue};const o=ba(t,e,a,s),l=await ne(o),c=[];for(const d of n){for(const[A,u]of i.entries())c.push(new ga(d,A,u));c.push(new fo(d,o,l))}return new $(c)}async changeColors(t,e,a,n,i){var h,g;if(e.length===0)return;const s=L(e[0].id,n().map(m=>m.layoutState)),o={...s.colors},l={};Object.entries(o).forEach(([m,p])=>{const f={browserValue:p.browserValue,pmsValue:p.pmsValue},C=p.spotColor;C&&(f.spotColor={profileName:C.profileName,namedColor:C.namedColor}),l[m]=f});for(const[m,p]of i.entries()){const f=typeof p=="string"?p:p.browserValue,C=typeof p=="string"?void 0:p.pmsValue;o[m]={browserValue:f,spotColor:(h=o[m])==null?void 0:h.spotColor,pmsValue:C},l[m]={browserValue:f}}let c=Array.from(Object.values(o)).map(m=>m.browserValue);const d=t.data.colorOption;d&&((g=d.variants)==null||g.forEach(m=>{c=c.map(p=>{var f;return p.toLowerCase()===((f=m.color)==null?void 0:f.toLowerCase())?m.name:p})})),a.updateMetadata(t.stepName,{colors:c});const A=new Map;if(Object.entries(o).forEach(([m,p])=>{A.set(m,p)}),!s.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(s.svg,s.width,s.height,e.map(m=>m.id),A);a.updateStorage(t.stepName,{colors:l}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,n,i){const s=await this.selectVariantCommand(t,e,a,n,i);s&&(s.command&&i.getCommandDispatcher()(s.command),s.followup&&await s.followup())}async selectVariantCommand(t,e,a,n,i){var f;if(!t.data||!t.data.regions)throw new ee(t,"Missing regions.");n(!0);const s=a.map(C=>new Ct(C.id));t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new mt(e);const l=o.fileLink;if(!l)throw new Nt(o);const c=await ot(await this.getIllustrationBody(l)),d=await ne(c.svg),A=C=>{const w=i.getLayouts().find(y=>y.panelId===C.panelId);if(!w)throw new Y(C);const S=Q();return{regionElement:{id:S,region:C},command:this.getCreateElementCommand(S,C,w,{stepName:t.stepName,src:l,objectURL:d,svg:c})}},u=t.data.regions.map(A),g=[...u.map(C=>C.command),...s];let m=Array.from(Object.values(c.colors)).map(C=>C.browserValue);const p=t.data.colorOption;return p&&((f=p.variants)==null||f.forEach(C=>{m=m.map(w=>{var S;return w.toLowerCase()===((S=C.color)==null?void 0:S.toLowerCase())?C.name:w})})),i.updateMetadata(t.stepName,{colors:m}),{command:new $(g),followup:async()=>{var w,S;await i.setSelectionsAndElements(t.stepName,[e],u.map(y=>y.regionElement),async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)});const C=((w=o.assetConfiguration)==null?void 0:w.defaultColorVariants)||[];if(C.length!==0){const y={};(((S=o.assetConfiguration)==null?void 0:S.channelNumbers)||[]).forEach(b=>{var x;const I=C.find(F=>F.channelNumber===b.number);I&&(y[`${b.id.replace(/\W/g,"")}`]={browserValue:((x=I==null?void 0:I.variant)==null?void 0:x.color)||""})}),await this.changeColors(t,u.map(b=>b.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map(Object.entries(y)))}if(t.data.colorPickerEnabled){const y=await this.availableColors(t,i)||[],E=Object.keys(c.colors),b=y.length===1&&E.length===1;if(b){const I=y[0],x=E[0];await this.changeColors(t,u.map(F=>F.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map([[x,I.variant.color]]))}!b&&C.length===0&&await this.changeColors(t,u.map(I=>I.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map)}}}}}const Jt=new Eo;class bo{async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(!l)throw new te(t);if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=A.material,h=o.map(g=>({id:g.id,region:g.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],h,async()=>{const g=e.getModelContainer();if(g){const m=t.data.targetMaterials.map(p=>g.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(m).then(()=>e.setMandatoryFulfilled(t.stepName,!0))}})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantLambda(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,n){const i=a.getModelContainer();n(!0);const s=e.material;if(!s)throw n(!1),new mt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{i&&t.data.targetMaterials.forEach(o=>{t.option&&i.applyMaterialVariant(o,t.option.id||"",s)}),a.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}})}}}}const Qa=new bo;class Bo{async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var g;const h=e.getModelContainer();if(h&&t.option){const m=(g=A.asset)==null?void 0:g.fileLink;if(!m)throw new mt(A);await h.applyModelVariant(t.stepName||"",{model:m,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantLambda(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,n){var s;n(!0);const i=(s=e.asset)==null?void 0:s.fileLink;if(!i)throw new mt(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:i,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1),a.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}})}}}}const Ra=new Bo;class Io{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{var c,d;e.updateStorage(t.stepName,{text:(c=n==null?void 0:n.storage)==null?void 0:c.text}),e.setMandatoryFulfilled(t.stepName,((d=n==null?void 0:n.storage)==null?void 0:d.text)!=="")})}async changeText(t,e,a,n){const i=await this.changeTextCommand(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,a,n){var d;const i=a.getRegionElements(t.stepName),s=(d=a.getStepSpecificServices(t.stepName))==null?void 0:d.module;if(!s)return console.error("Missing module."),null;const o=a.getProfanities(),l=this.validateInput(t,e,o,n);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(A,u,h)=>{const g=h||Q(),p=a.getLayouts().find(C=>C.panelId===u.panelId);if(!p)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Ct(g)),f.push(new q({stepRegion:u,stepName:t.stepName,colors:{},id:g,svg:A,type:M.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},p)),{id:g,region:u,command:new $(f)}};if(i.length>0){const u=i.map(h=>{if(!h.region)return null;const g=s.svgPrint(e,h.region);return c(g,h.region,h.id)}).filter(h=>!!h).filter(h=>!!h).map(h=>h&&h.command);return{command:new $(u),followup:async()=>{}}}else{const A=t.data.regions.map(h=>c(s.svgPrint(e,h),h)),u=A.filter(h=>!!h).map(h=>h&&h.command);return{command:new $(u),followup:async()=>{const h=A.filter(g=>g).map(g=>g&&{id:g.id,region:g.region});await a.setSelectionsAndElements(t.stepName,[],h)}}}}validateInput(t,e,a,n){if(t.data&&t.data.maxLength){const s=t.data.maxLength;if(e.length>s)return n("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const i=ra.split(e.toLowerCase());for(const s of i)for(const o in a){const l=a[o].toLowerCase().replace(/\s/g,"");if(s===l)return n("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return n(""),{input:e,helperData:{}}}}const Oa=new Io;class Po{async init(t,e,a){const n=t.option;if(!n)return null;if(a)await this.reload(t,e,a);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,()=>{});return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantCommand(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,a,n){const i=e.asset;if(!i)throw new mt(e);const s=i==null?void 0:i.fileLink;if(!s)return console.error("No URL for picture!"),null;n(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(A=>new Ct(A.id)),c=A=>{const h=a.getLayouts().find(m=>m.panelId===A.panelId);if(!h)throw new Y(A);const g=Q();return{regionElement:{id:g,region:A},command:new q({stepName:t.stepName,stepRegion:A,id:g,src:s,type:M.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},h)}},d=t.data.regions.map(c);return{command:new $([...l,...d.map(A=>A.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(A=>A.regionElement),async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)})}}}}const $a=new Po;class Do{async init(t,e,a){const n=t.option;if(!n)return null;if(a)await this.reload(t,e,a);else{const i=n.variants;if(H.getDefaultVariant(n)){const o=i==null?void 0:i.find(l=>{var c;return l.id===((c=n.defaultVariant)==null?void 0:c.id)});return this.selectVariantLambda(t,(o==null?void 0:o.id)||"",e)}}return null}async reload(t,e,a){var s;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),i=t.option;if(n!=null&&n.selectedVariants){const o=n.selectedVariants[0].id;if(i&&o){const l=(s=i.variants)==null?void 0:s.find(c=>c.id===o);l&&await e.setSelectionsAndElements(t.stepName,[l],[])}}}async selectVariant(t,e,a){await a.getInitializationPromise();const n=await this.selectVariantLambda(t,e,a);n&&(n.command&&a.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,a){const n=t.option;if(!n)return null;const i=n.variants;if(!i)return null;const s=i.length>1?i.find(o=>o.id===e):i[0];if(!s)throw new Error(`Failed to find selected variant ${e} in option ${n.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[s],[],async()=>{a.setMandatoryFulfilled(t.stepName,!0)})}}}}const Ua=new Do;class xo{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){var a;const e=t.option;return e?((a=e.variants)==null?void 0:a.map(n=>({fill:n.color,stroke:n.color,variant:n})))||[]:[]}setCustomColor(t,e,a){const n=a.getLayouts(),s=(a.getRegionElements(e.stepName)||[]).map(o=>{const l=o.region;if(!n.find(d=>d.panelId===(l==null?void 0:l.panelId)))throw new Y(l);return new ga(o.id,this.shapeFillId,t)}).filter(o=>!!o);a.getCommandDispatcher()(new $(s)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);return i?this.selectVariantCommand(t,{fill:i.color,stroke:i.color,variant:i},[],e):null}return null}async selectVariant(t,e,a,n){const i=await this.selectVariantCommand(t,e,a,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var h;e.updateStorage(t.stepName,{colour:((h=n==null?void 0:n.storage)==null?void 0:h.colour)||""}),e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariantCommand(t,e,a,n){var l;const i=n.getLayouts(),s=(l=n.getStepStorage(t.stepName))==null?void 0:l.colour,o=()=>{var c,d;if(((c=e.variant)==null?void 0:c.color)==="#custom")return s||"#FFFFFF";if((d=e.variant)!=null&&d.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const c=A=>{const u=A.region;if(!i.find(m=>m.panelId===(u==null?void 0:u.panelId)))throw new Y(u);const g=o();return new ga(A.id,this.shapeFillId,g)},d=a.map(c).filter(A=>!!A);return{command:new $(d),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),n.updateStorage(t.stepName,{colour:o()})}}}else{const c=h=>{const g=i.find(w=>w.panelId===h.panelId);if(!g)throw new Y(h);const m=o(),p=`
|
|
1439
1439
|
<svg
|
|
1440
1440
|
xmlns="http://www.w3.org/2000/svg"
|
|
1441
1441
|
xmlnsXlink="http://www.w3.org/1999/xlink"
|
|
@@ -2196,7 +2196,7 @@
|
|
|
2196
2196
|
}
|
|
2197
2197
|
}
|
|
2198
2198
|
}
|
|
2199
|
-
`;function _t(r){const t=JSON.parse(atob(r.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const bl=async(r,t)=>{var n,i;const e={};try{if(t){const s=await t.loggedInBearerToken();e.Authorization=`Bearer ${s}`}else throw new Error}catch{const l=((n=Object.entries(localStorage).find(([d,A])=>d.startsWith("CognitoIdentityServiceProvider")&&d.endsWith("idToken")))==null?void 0:n[0])||"",c=localStorage.getItem(l);c&&!_t(c)&&(e.Authorization=`Bearer ${c}`)}return(i=(await B.getShadowGraphqlClient().mutate({mutation:vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:r.name,layouts:r.layouts,workflowId:r.workflowId,transactionId:r.transactionId,previewImage:r.previewImage,useThreeDimPreview:r.useThreeDimPreview,metadata:r.metadata,selectedVariants:r.selectedVariants},context:{headers:e}})).data)==null?void 0:i.designCreate},Bl=async(r,t)=>{var n,i;const e={};try{if(t){const s=await t.loggedInBearerToken();e.Authorization=`Bearer ${s}`}else throw new Error}catch{const l=((n=Object.entries(localStorage).find(([d,A])=>d.startsWith("CognitoIdentityServiceProvider")&&d.endsWith("idToken")))==null?void 0:n[0])||"",c=localStorage.getItem(l);c&&!_t(c)&&(e.Authorization=`Bearer ${c}`)}return(i=(await B.getShadowGraphqlClient().mutate({mutation:El,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:r.map(s=>({name:s.name,layouts:s.layouts,workflowId:s.workflowId,transactionId:s.transactionId,previewImage:s.previewImage,useThreeDimPreview:s.useThreeDimPreview,metadata:s.metadata,selectedVariants:s.selectedVariants}))},context:{headers:e}})).data)==null?void 0:i.designCreateMany},pa=(r,t,e)=>{const a=i=>{const s={};if(i.type==="Frame"){const o=r[i.stepName],l=i.data;if(!o||!o.image||l.hideImageInCart&&e)return s;s[`${i.stepTitle} image`]=o.image}if(i.type==="Illustration"){const o=r[i.stepName],l=i.data;if(!o||l.hideColorsInCart&&e||!o.colors)return s;if(o.colors.length>0){const c=o.colors.join(", ").toUpperCase();s[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const o=r[i.stepName],l=i.data;if(!o||o.text===void 0||o.text===null||l.hideTextInCart&&e)return s;s[`${i.stepTitle} text`]=o.text}if(i.type==="Text"){const o=r[i.stepName];if(!o)return s;const l=i.data;(!l.hideTextInCart||!e&&o.text!==void 0&&o.text!==null)&&(s[`${i.stepTitle} text`]=o.text),o.color&&(!l.hideColorInCart||!e)&&(s[`${i.stepTitle} color`]=o.color),o.strokeColor&&(!l.hideStrokeInCart||!e)&&(s[`${i.stepTitle} stroke`]=o.strokeColor)}return s},n={};return t.steps.forEach(i=>{Object.assign(n,a(i))}),n},Il=(r,t,e,a)=>{const n={};let i={};e?i=pa(e,t,!1):a&&(i=a);const o=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of o){if(Object.keys(r).includes(l)){const c=r[l],d=t.steps.find(A=>A.stepTitle===l);n[`${d==null?void 0:d.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(n[c]={value:i[c],priceModifier:0})}return n},Ir=(r,t,e,a,n,i,s,o)=>{var g,m;const l=t.basePrice||0,c=r.priceModifierTotal||0,d=Il(a,e,void 0,i),u=(T.getMap("transactionOwnerIds")||new Map).get(r.id),h={additionalExternalProductId:(g=r.integrationProduct)==null?void 0:g.additionalExternalProductId,additionalExternalVariantId:(m=r.integrationProduct)==null?void 0:m.additionalExternalVariantId,baseCost:l,designExternalVariants:r.designExternalVariants,designProductId:r.externalDesignProductId,designProductVariantId:r.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:r.externalCartProductId,externalCartProductVariantId:r.externalCartProductVariantId,lineItemImageUrl:s||"",optionsCost:c,processExecutionId:o,quantity:r.quantity,transactionId:r.id,transactionOwnerId:u,weight:t.weight,workflowViewerLink:r.workflowViewerLink||"",workflowViewerReadOnlyLink:r.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),n&&(h.sku=n),h},Pr=async(r,t,e,a,n,i,s,o,l,c)=>{var I;await(async()=>{var R;if(c!==void 0)return c;await r.outstandingRequestsPromise();const F=(T.getMap("transactionOwnerIds")||new Map).get(n.id),N=await B.getShadowGraphqlClient().query({query:Yn,variables:{ids:[n.id]},fetchPolicy:"no-cache",errorPolicy:"all",context:{transactionOwnerId:F}}),rt=(R=N.data)==null?void 0:R.transactions[0].workflowState;return N.errors?(N.errors.forEach(et=>{N.errors&&console.log("Server Error:",et.message)}),null):rt??null})()||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await r.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const u=r.getPreviewService(),h=(I=t==null?void 0:t.finalizeStepConfig)==null?void 0:I.lookAtAnimation,g=u&&t.showModelOnFinishStep&&!!h,m=l&&pa(l,t,!0),p=l&&pa(l,t,!1),f=async x=>{const F={};let k=0;if(Object.keys(i).length>0)for(const N of Object.keys(i)){const rt=i[N],R=t.steps.find(et=>et.stepName===N);for(let et=0;et<rt.selections.length;++et){const
|
|
2199
|
+
`;function _t(r){const t=JSON.parse(atob(r.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const bl=async(r,t)=>{var n,i;const e={};try{if(t){const s=await t.loggedInBearerToken();e.Authorization=`Bearer ${s}`}else throw new Error}catch{const l=((n=Object.entries(localStorage).find(([d,A])=>d.startsWith("CognitoIdentityServiceProvider")&&d.endsWith("idToken")))==null?void 0:n[0])||"",c=localStorage.getItem(l);c&&!_t(c)&&(e.Authorization=`Bearer ${c}`)}return(i=(await B.getShadowGraphqlClient().mutate({mutation:vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:r.name,layouts:r.layouts,workflowId:r.workflowId,transactionId:r.transactionId,previewImage:r.previewImage,useThreeDimPreview:r.useThreeDimPreview,metadata:r.metadata,selectedVariants:r.selectedVariants},context:{headers:e}})).data)==null?void 0:i.designCreate},Bl=async(r,t)=>{var n,i;const e={};try{if(t){const s=await t.loggedInBearerToken();e.Authorization=`Bearer ${s}`}else throw new Error}catch{const l=((n=Object.entries(localStorage).find(([d,A])=>d.startsWith("CognitoIdentityServiceProvider")&&d.endsWith("idToken")))==null?void 0:n[0])||"",c=localStorage.getItem(l);c&&!_t(c)&&(e.Authorization=`Bearer ${c}`)}return(i=(await B.getShadowGraphqlClient().mutate({mutation:El,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:r.map(s=>({name:s.name,layouts:s.layouts,workflowId:s.workflowId,transactionId:s.transactionId,previewImage:s.previewImage,useThreeDimPreview:s.useThreeDimPreview,metadata:s.metadata,selectedVariants:s.selectedVariants}))},context:{headers:e}})).data)==null?void 0:i.designCreateMany},pa=(r,t,e)=>{const a=i=>{const s={};if(i.type==="Frame"){const o=r[i.stepName],l=i.data;if(!o||!o.image||l.hideImageInCart&&e)return s;s[`${i.stepTitle} image`]=o.image}if(i.type==="Illustration"){const o=r[i.stepName],l=i.data;if(!o||l.hideColorsInCart&&e||!o.colors)return s;if(o.colors.length>0){const c=o.colors.join(", ").toUpperCase();s[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const o=r[i.stepName],l=i.data;if(!o||o.text===void 0||o.text===null||l.hideTextInCart&&e)return s;s[`${i.stepTitle} text`]=o.text}if(i.type==="Text"){const o=r[i.stepName];if(!o)return s;const l=i.data;(!l.hideTextInCart||!e&&o.text!==void 0&&o.text!==null)&&(s[`${i.stepTitle} text`]=o.text),o.color&&(!l.hideColorInCart||!e)&&(s[`${i.stepTitle} color`]=o.color),o.strokeColor&&(!l.hideStrokeInCart||!e)&&(s[`${i.stepTitle} stroke`]=o.strokeColor)}return s},n={};return t.steps.forEach(i=>{Object.assign(n,a(i))}),n},Il=(r,t,e,a)=>{const n={};let i={};e?i=pa(e,t,!1):a&&(i=a);const o=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of o){if(Object.keys(r).includes(l)){const c=r[l],d=t.steps.find(A=>A.stepTitle===l);n[`${d==null?void 0:d.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(n[c]={value:i[c],priceModifier:0})}return n},Ir=(r,t,e,a,n,i,s,o)=>{var g,m;const l=t.basePrice||0,c=r.priceModifierTotal||0,d=Il(a,e,void 0,i),u=(T.getMap("transactionOwnerIds")||new Map).get(r.id),h={additionalExternalProductId:(g=r.integrationProduct)==null?void 0:g.additionalExternalProductId,additionalExternalVariantId:(m=r.integrationProduct)==null?void 0:m.additionalExternalVariantId,baseCost:l,designExternalVariants:r.designExternalVariants,designProductId:r.externalDesignProductId,designProductVariantId:r.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:r.externalCartProductId,externalCartProductVariantId:r.externalCartProductVariantId,lineItemImageUrl:s||"",optionsCost:c,processExecutionId:o,quantity:r.quantity,transactionId:r.id,transactionOwnerId:u,weight:t.weight,workflowViewerLink:r.workflowViewerLink||"",workflowViewerReadOnlyLink:r.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),n&&(h.sku=n),h},Pr=async(r,t,e,a,n,i,s,o,l,c)=>{var I;await(async()=>{var R;if(c!==void 0)return c;await r.outstandingRequestsPromise();const F=(T.getMap("transactionOwnerIds")||new Map).get(n.id),N=await B.getShadowGraphqlClient().query({query:Yn,variables:{ids:[n.id]},fetchPolicy:"no-cache",errorPolicy:"all",context:{transactionOwnerId:F}}),rt=(R=N.data)==null?void 0:R.transactions[0].workflowState;return N.errors?(N.errors.forEach(et=>{N.errors&&console.log("Server Error:",et.message)}),null):rt??null})()||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await r.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const u=r.getPreviewService(),h=(I=t==null?void 0:t.finalizeStepConfig)==null?void 0:I.lookAtAnimation,g=u&&t.showModelOnFinishStep&&!!h,m=l&&pa(l,t,!0),p=l&&pa(l,t,!1),f=async x=>{const F={};let k=0;if(Object.keys(i).length>0)for(const N of Object.keys(i)){const rt=i[N],R=t.steps.find(et=>et.stepName===N);for(let et=0;et<rt.selections.length;++et){const X=rt.selections[et];if(R&&(!x||R.option&&(R.option.variants||[]).length>1&&!R.data.hideSelectionInCart&&!R.data.hideSelectionsInCart)){const Ut=R.stepTitle;F[Ut]?F[Ut].push({id:X.id||"",name:X.name,priceModifier:X.priceModifier}):F[Ut]=[{id:X.id||"",name:X.name,priceModifier:X.priceModifier}]}k+=X.priceModifier}}return[F,k]},[C]=await f(!0),w=Object.fromEntries(Object.keys(C).map(x=>[x,C[x].map(F=>F.id)])),[S]=await f(!1),y=Object.fromEntries(Object.keys(S).map(x=>[x,S[x].map(F=>F.id)]));let E=await o(g,n.id);if(E){const x=await(await st(E)).blob();E=(await U.uploadAsset({name:`${n.id}-preview-image.png`,blob:x},Xt.Image,!0,!1)).fileLink}return{designDetails:(()=>{const x={name:s,layouts:e.map(F=>({index:F.index,panelId:F.panelId})),workflowId:t.id,transactionId:n.id,useThreeDimPreview:!!g,previewImage:E};if(p){const F=[];for(const[k,N]of Object.entries(p))F.push({key:k,value:N});x.metadata=F}if(w){const F=[];for(const[k,N]of Object.entries(y))F.push({key:k,ids:N});x.selectedVariants=F}return x})(),cartSelectionsWithPrices:C,cartMetadata:m}},Dr=async(r,t,e,a,n,i,s,o,l,c,d)=>{var f,C;l("workflow.steps.finish.finalize.buildingLayouts");const{designDetails:A,cartSelectionsWithPrices:u,cartMetadata:h}=await Pr(r,t,e,a,i,s,o,c,d);l("workflow.steps.finish.finalize.creatingDesign");const g=await bl(A),m=(f=g==null?void 0:g.transaction)==null?void 0:f.previewImageLink;if(!(g!=null&&g.transaction))throw new Error("Failed to create design");l("workflow.steps.finish.finalize.updatingTransaction");const p=g.transaction;return Ir(p,n,t,u,g==null?void 0:g.sku,h,m,(C=g==null?void 0:g.processExecution)==null?void 0:C.id)},Pl=async(r,t,e)=>{t("workflow.steps.finish.finalize.buildingLayouts"),await Promise.all(r.map(async o=>{await o.workflowManager.outstandingRequestsPromise()}));const n=await(async()=>{var c;const l=await B.getShadowGraphqlClient().query({query:Yn,variables:{ids:r.map(d=>d.transaction.id)},fetchPolicy:"no-cache",errorPolicy:"all"});return l.errors?(l.errors.forEach(d=>{l.errors&&console.log("Server Error:",d.message)}),null):(c=l.data)!=null&&c.transactions?l.data.transactions.map(d=>d.workflowState??null):null})(),i=await Promise.all(r.map(async(o,l)=>await Pr(o.workflowManager,o.workflow,o.layouts,o.getReducerState,o.transaction,o.workflowSelections,o.designName,e??(()=>Promise.resolve(void 0)),o.workflowMetadata,n?n[l]:void 0)));t("workflow.steps.finish.finalize.creatingDesign");const s=await Bl(i.map(o=>o.designDetails));if(!s)throw new Error("Failed to create designs");return t("workflow.steps.finish.finalize.updatingTransaction"),s.map((o,l)=>{var u;const c=r[l],d=i[l],A=o.transaction;return Ir(A,c.product,c.workflow,d.cartSelectionsWithPrices,o.sku,d.cartMetadata,A.previewImageLink,(u=o.processExecution)==null?void 0:u.id)})};class Dl{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=T.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new z("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(n=>n.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(n=>n(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),n=a.find(i=>i.transactionId===t);if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){T.set(this.localPersistenceKey,JSON.stringify(t));return}throw new z("Unexpected storage method requested")}}const Ee=new Dl,xl=v.gql`
|
|
2200
2200
|
mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
|
|
2201
2201
|
transactionAddStakeholder(id: $id, details: $details, type: $type) {
|
|
2202
2202
|
id
|
|
@@ -2312,7 +2312,7 @@
|
|
|
2312
2312
|
quoteId
|
|
2313
2313
|
}
|
|
2314
2314
|
}
|
|
2315
|
-
`;class ta{constructor(t,e,a,n,i,s){var c,d,A;this.workflowExperiences=[],this.eventEmitter=new rc,this.client=t,this.id=e.id,this.name=e.name||"",this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((c=e.metadata)==null?void 0:c.map(u=>[u.key,u.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Zl(e.bundleStateData);const o=(d=this.productCollection)==null?void 0:d.globalPropertyConfiguration;this.globalConfigurationPropertyId=o==null?void 0:o.id,this.globalPropertyStateManager=new Xl(this.id,this.ownerId,o,this.checkConditionalHandlesChanged.bind(this),s),this.globalPropertyHandleService=new Jl(this),this.setPreviewService(a);const l=new Promise((u,h)=>{if(s!=null&&s.readonly){u([]);return}console.log("Setting default global variants."),this.globalPropertyHandleService.getHandles().then(g=>{const m=g.map(p=>{if(p.getType()===V.ColorOption||p.getType()===V.Option){const f=p;if(this.globalPropertyStateManager.getGlobalPropertyState())return f.initDefaultVariant();console.log("Attempted to set global default variant before state was initialized.")}});Promise.all(m).then(u).catch(h)})});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((A=e.transactions)==null?void 0:A.map(u=>u.id))||[],{...n,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(u=>{console.error(`Bundle initialization failed: ${u}`)})}getTemplate(){return this.template}async generateQuoteId(){var a,n;const e=(n=(a=(await B.getShadowGraphqlClient().mutate({mutation:oc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data)==null?void 0:a.bundleGenerateQuoteId)==null?void 0:n.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,i,s){await B.getShadowGraphqlClient().mutate({mutation:ic,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await B.getShadowGraphqlClient().mutate({mutation:sc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){var a;const e=await this.globalPropertyHandleService.getHandles();for(const n of t.aspects){const i=n==null?void 0:n.name;this.getGlobalPropertyStateManager().setAspect(i,n.value)}for(const n of t.aspects){const i=n==null?void 0:n.name,s=e.find(o=>o.getName()===i);if(s)switch(n.type){case V.FileUpload:{const o=s,l=await Be([n.value]);l.length>0&&await o.selectImage(l[0]);const c=(a=n.storage)==null?void 0:a.colors;if(c){const d=Object.fromEntries(c.map(A=>[A.key,{browserValue:A.browserValue,pmsValue:A.pmsValue}])??[]);await o.changeColors(d)}break}case V.ColorOption:{const o=s;if(n.type===V.ColorOption){const c=o.getAllVariants().find(d=>d.getId()===n.value);c&&await o.selectVariant(c)}else o.setCustomColor(n.value);break}case V.Option:{const o=s,c=o.getAllVariants().find(d=>d.getId()===n.value);c&&await o.selectVariant(c);break}case V.Text:{await s.setText(n.value);break}}}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===V.Option).map(a=>{var n;return((n=a.getCurrentVariant())==null?void 0:n.getPrice())||0}).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new za(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){var e,a,n,i;for(const s of t.getStepsByType(P.Illustration)){const o=s.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const l of o){const c=(e=this.getGlobalPropertyConfiguration())==null?void 0:e.aspects.find(d=>d.name===l);if(c&&c.type===V.ColorOption){const d=(a=s.getCurrentVariant())==null?void 0:a.getAssetResource(),A=((n=d==null?void 0:d.assetConfiguration)==null?void 0:n.channelNumbers)||[],u=((i=d==null?void 0:d.assetConfiguration)==null?void 0:i.defaultColorVariants)||[],h=_l(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",l),g=[...new Set(A.map(p=>p.number))];if(g.length>h)for(const p of g){const f=this.getGlobalPropertyStateManager(),C=u.find(w=>w.channelNumber===p);C&&await f.setAspect(l,C.variant.id||"",void 0,C.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const o of t)await this.initializeAdditionalRequiredColorChannels(o);const e=t.map(o=>o.getWorkflowManager().getTransaction().id),a=e.map(o=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===o));if(a.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const n=T.getMap("transactionOwnerIds")||new Map,i=e.map(o=>n.get(o));await B.getShadowGraphqlClient().mutate({mutation:al,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const l of o)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(T.getMap("transactionOwnerIds")||new Map).get(a);await B.getShadowGraphqlClient().mutate({mutation:el,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await B.getShadowGraphqlClient().mutate({mutation:nl,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,i)=>e[i]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await B.getShadowGraphqlClient().mutate({mutation:rl,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,i])=>({key:n,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){var i;const a=await B.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,details:t,type:e||Zt.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=a.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){var a;if(!((a=(await B.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&a.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var n;const e=await B.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((n=e.data)!=null&&n.bundleUpdateStakeholders))throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await B.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await B.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await B.getShadowGraphqlClient().mutate({mutation:ul,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const a=await Pl(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(n,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await B.getShadowGraphqlClient().mutate({mutation:dl,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){var a,n;const e=await B.getShadowGraphqlClient().mutate({mutation:cl(((a=this.globalPropertyStateManager.getBundleOptions())==null?void 0:a.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if((n=e.data)!=null&&n.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const i=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(i),this.globalConfigurationPropertyId=i==null?void 0:i.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===n.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(n=>({type:"transaction",transactionId:n})),e);if(a.forEach(n=>n.setBundle(this)),a.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const n of a)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){var e;if(!((e=(await B.getShadowGraphqlClient().mutate({mutation:tl,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,n])=>({key:a,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await B.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(t,e){const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);if((()=>{if(n.length!==i.length)return!0;for(let o=0;o<n.length;o++)if(n[o].getName()!==i[o].getName())return!0;return!1})()){this.fireEvent("conditional-global-properties-changed",{globalProperties:i});const o=i.filter(l=>!n.includes(l));await Promise.all(o.map(l=>l.applyGlobalState()))}}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await B.getShadowGraphqlClient().mutate({mutation:hl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await B.getShadowGraphqlClient().mutate({mutation:gl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const lc=v.gql`
|
|
2315
|
+
`;class ta{constructor(t,e,a,n,i,s){var c,d,A;this.workflowExperiences=[],this.eventEmitter=new rc,this.client=t,this.id=e.id,this.name=e.name||"",this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((c=e.metadata)==null?void 0:c.map(u=>[u.key,u.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Zl(e.bundleStateData);const o=(d=this.productCollection)==null?void 0:d.globalPropertyConfiguration;this.globalConfigurationPropertyId=o==null?void 0:o.id,this.globalPropertyStateManager=new Xl(this.id,this.ownerId,o,this.checkConditionalHandlesChanged.bind(this),s),this.globalPropertyHandleService=new Jl(this),this.setPreviewService(a);const l=new Promise((u,h)=>{if(s!=null&&s.readonly){u([]);return}console.log("Setting default global variants.");const g=this.globalPropertyStateManager.getGlobalPropertyState();g?this.globalPropertyHandleService.getHandles().then(m=>{const p=m.map(f=>{if(f.getType()===V.ColorOption||f.getType()===V.Option){const C=f;if(!g.aspects.find(S=>S.name===C.getName()))return C.initDefaultVariant()}});Promise.all(p).then(u).catch(h)}):(console.log("Attempted to set global default variant before state was initialized."),u([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((A=e.transactions)==null?void 0:A.map(u=>u.id))||[],{...n,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(u=>{console.error(`Bundle initialization failed: ${u}`)})}getTemplate(){return this.template}async generateQuoteId(){var a,n;const e=(n=(a=(await B.getShadowGraphqlClient().mutate({mutation:oc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data)==null?void 0:a.bundleGenerateQuoteId)==null?void 0:n.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,i,s){await B.getShadowGraphqlClient().mutate({mutation:ic,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await B.getShadowGraphqlClient().mutate({mutation:sc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){var a;const e=await this.globalPropertyHandleService.getHandles();for(const n of t.aspects){const i=n==null?void 0:n.name;this.getGlobalPropertyStateManager().setAspect(i,n.value)}for(const n of t.aspects){const i=n==null?void 0:n.name,s=e.find(o=>o.getName()===i);if(s)switch(n.type){case V.FileUpload:{const o=s,l=await Be([n.value]);l.length>0&&await o.selectImage(l[0]);const c=(a=n.storage)==null?void 0:a.colors;if(c){const d=Object.fromEntries(c.map(A=>[A.key,{browserValue:A.browserValue,pmsValue:A.pmsValue}])??[]);await o.changeColors(d)}break}case V.ColorOption:{const o=s;if(n.type===V.ColorOption){const c=o.getAllVariants().find(d=>d.getId()===n.value);c&&await o.selectVariant(c)}else o.setCustomColor(n.value);break}case V.Option:{const o=s,c=o.getAllVariants().find(d=>d.getId()===n.value);c&&await o.selectVariant(c);break}case V.Text:{await s.setText(n.value);break}}}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===V.Option).map(a=>{var n;return((n=a.getCurrentVariant())==null?void 0:n.getPrice())||0}).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new za(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){var e,a,n,i;for(const s of t.getStepsByType(P.Illustration)){const o=s.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const l of o){const c=(e=this.getGlobalPropertyConfiguration())==null?void 0:e.aspects.find(d=>d.name===l);if(c&&c.type===V.ColorOption){const d=(a=s.getCurrentVariant())==null?void 0:a.getAssetResource(),A=((n=d==null?void 0:d.assetConfiguration)==null?void 0:n.channelNumbers)||[],u=((i=d==null?void 0:d.assetConfiguration)==null?void 0:i.defaultColorVariants)||[],h=_l(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",l),g=[...new Set(A.map(p=>p.number))];if(g.length>h)for(const p of g){const f=this.getGlobalPropertyStateManager(),C=u.find(w=>w.channelNumber===p);C&&await f.setAspect(l,C.variant.id||"",void 0,C.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const o of t)await this.initializeAdditionalRequiredColorChannels(o);const e=t.map(o=>o.getWorkflowManager().getTransaction().id),a=e.map(o=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===o));if(a.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const n=T.getMap("transactionOwnerIds")||new Map,i=e.map(o=>n.get(o));await B.getShadowGraphqlClient().mutate({mutation:al,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const l of o)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(T.getMap("transactionOwnerIds")||new Map).get(a);await B.getShadowGraphqlClient().mutate({mutation:el,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await B.getShadowGraphqlClient().mutate({mutation:nl,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,i)=>e[i]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await B.getShadowGraphqlClient().mutate({mutation:rl,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,i])=>({key:n,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){var i;const a=await B.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,details:t,type:e||Zt.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=a.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){var a;if(!((a=(await B.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&a.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var n;const e=await B.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((n=e.data)!=null&&n.bundleUpdateStakeholders))throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await B.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await B.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await B.getShadowGraphqlClient().mutate({mutation:ul,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const a=await Pl(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(n,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await B.getShadowGraphqlClient().mutate({mutation:dl,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){var a,n;const e=await B.getShadowGraphqlClient().mutate({mutation:cl(((a=this.globalPropertyStateManager.getBundleOptions())==null?void 0:a.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if((n=e.data)!=null&&n.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const i=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(i),this.globalConfigurationPropertyId=i==null?void 0:i.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===n.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(n=>({type:"transaction",transactionId:n})),e);if(a.forEach(n=>n.setBundle(this)),a.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const n of a)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){var e;if(!((e=(await B.getShadowGraphqlClient().mutate({mutation:tl,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,n])=>({key:a,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await B.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(t,e){const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);if((()=>{if(n.length!==i.length)return!0;for(let o=0;o<n.length;o++)if(n[o].getName()!==i[o].getName())return!0;return!1})()){this.fireEvent("conditional-global-properties-changed",{globalProperties:i});const o=i.filter(l=>!n.includes(l));await Promise.all(o.map(l=>l.applyGlobalState()))}}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await B.getShadowGraphqlClient().mutate({mutation:hl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await B.getShadowGraphqlClient().mutate({mutation:gl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const lc=v.gql`
|
|
2316
2316
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
2317
2317
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
2318
2318
|
id
|
|
@@ -2435,7 +2435,7 @@
|
|
|
2435
2435
|
}
|
|
2436
2436
|
}
|
|
2437
2437
|
}
|
|
2438
|
-
`;class gc{constructor(t,e=B.getShadowGraphqlClient.bind(B)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class mc{init(t,e,a){this.cognitoClient=new me.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){var a;const e=await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}})));(e==null?void 0:e.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){var n;return await((n=this.cognitoClient)==null?void 0:n.send(new me.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})))}async refreshTokens(){var a;const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new mc;class Vr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return ci(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ja.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ja.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const An=new Vr;class zr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,An.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,An.getPrecisionForCurrency(e))}}const pc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Ss(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});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!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),Ot.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},fc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Wa=async(r,t)=>{const e=r.map(o=>Ot.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=pc(a,t),i=a.map(o=>Ot.set({id:o,options:t},fc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},Cc=async(r,t)=>(await Wa([r],t))[0],wc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:Q(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),yc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):wc(t.panels)};class Sc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:cs})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ii(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 28.0.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!Pi())throw new Error("Application key required to use Flow Service.");return new $r}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new zr(s,o,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Gr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(a){return console.error(a),!1}}async authenticateBundleFromLocalStorage(t){var n,i;const e=T.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const a=T.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t);if((T.getMap("partnerCustomerIds")||new Map).get(s)&&await this.reloadLoggedInCustomer()){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=B.getShadowGraphqlClient(),a=await e.query({query:vs,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=T.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const o=T.getMap("transactionCustomerIds");if(o!=null&&o.has(t)&&o.get(t)&&await this.reloadLoggedInCustomer()){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(w=>{var S,y;return(y=(S=w.bundle)==null?void 0:S.transactions)==null?void 0:y.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(w=>{var S;return((S=w.transaction)==null?void 0:S.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}const c=(await e.query({query:Es,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=T.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),T.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=B.getShadowGraphqlClient(),n=(await e.query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l!=null&&l.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const o=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return o.id?(this.customer=o,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await B.getShadowGraphqlClient().mutate({mutation:uc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n!=null&&n.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const s=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!s.id)throw new Error("Failed to get customer.");return this.customer=s,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!(a!=null&&a.AccessToken)||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const s=await Wt.refreshTokens();if(s!=null&&s.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await B.getShadowGraphqlClient().query({query:hc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await B.getShadowGraphqlClient().mutate({mutation:Xo(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=T.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),T.setMap("bundlePartnerIds",s);const o=T.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),T.setMap("bundleOwnerIds",o);const l=new ta(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var h,g,m,p,f,C,w,S,y,E,b;const i=T.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),o={};try{const I=await this.loggedInBearerToken();o.Authorization=`Bearer ${I}`}catch{const F=((h=Object.entries(localStorage).find(([N,rt])=>N.startsWith("CognitoIdentityServiceProvider")&&N.endsWith("idToken")))==null?void 0:h[0])||"",k=localStorage.getItem(F);k&&!_t(k)&&(o.Authorization=`Bearer ${k}`)}const l={bundleOwnerId:s,...o,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=await B.getShadowGraphqlClient().query({query:Ho(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!((f=c.data)!=null&&f.bundles)||((C=c.data)==null?void 0:C.bundles.length)===0||!((w=c.data)!=null&&w.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const d=(S=c.data)==null?void 0:S.bundles[0],A=T.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),T.setMap("bundlePartnerIds",A);const u=new ta(this,d,e,a,s,{additionalHeaders:(y=n==null?void 0:n.graphql)==null?void 0:y.additionalHeaders,eagerFetchProducts:(b=(E=n==null?void 0:n.graphql)==null?void 0:E.productCollection)==null?void 0:b.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n==null?void 0:n.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,n){var u,h,g,m,p,f;const i=(u=T.getMap("bundleOwnerIds"))==null?void 0:u.get(t),s={};try{const C=await this.loggedInBearerToken();s.Authorization=`Bearer ${C}`}catch{const S=((h=Object.entries(localStorage).find(([E,b])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken")))==null?void 0:h[0])||"",y=localStorage.getItem(S);y&&!_t(y)&&(s.Authorization=`Bearer ${y}`)}const o={bundleOwnerId:i,...s,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=(f=(await B.getShadowGraphqlClient().mutate({mutation:Zo(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data)==null?void 0:f.bundleDuplicate;if(!(c!=null&&c.id))throw new Error("Unable to duplicate bundle");const d=T.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),T.setMap("bundlePartnerIds",d);const A=T.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),T.setMap("bundleOwnerIds",A),async()=>{var w,S;const C=new ta(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:(S=(w=n==null?void 0:n.graphql)==null?void 0:w.productCollection)==null?void 0:S.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await C.getInitializationPromise(),C}}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await B.getShadowGraphqlClient().query({query:Al(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await B.getShadowGraphqlClient().query({query:Yo,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=T.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),T.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=B.getShadowGraphqlClient(),n=async y=>{var x,F,k;if(y.length===0)return[];const E=y.map(N=>N.option.transactionId),b=await a.query({query:ls,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),I=b.data.transactions;if(I.length!==y.length){const N=((F=(x=b.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((k=I[0].integrationProduct)!=null&&k.integration)&&(this.activeIntegration=Promise.resolve(I[0].integrationProduct.integration)),I.map((N,rt)=>{var R;return{transaction:N,workflowId:N.workflowId,readOnly:((R=y.find(et=>et.option.transactionId===N.id))==null?void 0:R.option.readOnly)??!1,index:y[rt].index}})},i=async y=>{var I,x,F;if(y.length===0)return[];const E=await a.mutate({mutation:os,variables:{inputs:y.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})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),b=(I=E.data)==null?void 0:I.transactionCreateMany;if(!b||b.length===0){const k=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${k}`)}return b.map((k,N)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:y[N].index}))},s=t.map((y,E)=>({option:y,index:E})),o=s.filter(y=>y.option.type==="transaction"),l=s.filter(y=>y.option.type==="integration"||y.option.type==="external"),c=Ya(o,10),d=Ya(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await Wa(u,e),g=new Map(h.map(y=>[y.id,y])),m=T.getMap("transactionOwnerIds")||new Map,p=A.map(async y=>{var et;const{transaction:E,workflowId:b,readOnly:I,index:x}=y,F=g.get(b),k=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const N=m.get(E.id)||void 0,rt=new gc({onMutate:()=>({context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(et=k==null?void 0:k.workflowConfiguration)==null?void 0:et.singleVariantsRenderable,stateMutationFunc:I?async()=>{throw new z("State mutation is forbidden in read only mode!")}:async Z=>this.updateTransactionState({...Z,context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>rt,readOnly:I,workflow:F,isReloadedTransaction:k.type==="transaction"};if(!I&&k.workflowState){const Z=JSON.parse(k.workflowState);R.layouts=Object.values(Z.layouts||{}).map(Ut=>Ut.layout),await ir(Z),R.reloadedState=Z}else R.layouts=yc(R.transaction,R.workflow);return R.renderableContextService=new zl(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:k}}),f=await Promise.all(p);T.setMap("transactionOwnerIds",m);const w=f.sort((y,E)=>y.index-E.index).map(async y=>{const{experienceOptions:E,options:b}=y,I=new Fr(this,E);return await I.getWorkflowManager().getInitializationPromise(),b.type!=="transaction"&&this.customer&&await I.attachCustomerDetails({email:this.customer.emailAddress}),I}),S=await Promise.all(w);return S.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),S}storeCustomer(t){const e=T.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),T.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await B.getShadowGraphqlClient().query({query:hs(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new Ca(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:gs(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new Ca(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(T.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await B.getShadowGraphqlClient().query({query:us,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await B.getShadowGraphqlClient().mutate({mutation:Ds,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 Gr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Bs,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,vc=async r=>{const e=await B.getShadowGraphqlClient().query({query:As,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Ec=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:bs,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},bc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},Bc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function qr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=Se(r.x,t.width-c,0),o.y=Se(r.y,t.height-d,0),o}const s=r;return s.x=Se(s.x,-n,t.width),s.y=Se(s.y,-i,t.height),s}function Se(r,t,e){return Math.min(Math.max(r,t),e)}class Wr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=vn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await Ae(o),c=this.frameData?this.frameData[s]:void 0;Sn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=$e(this.imageData.svg,this.imageData.colors||{},!1);return Re(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new z("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=qr(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(o=>!o))throw new z("Frame data not set. This is a bug");if(!this.workflowManager)throw new z("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new go(o,e,t[l]),new mo(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*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]=Fa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ic{updateRecipient(t,e,a,n,i,s,o,l,c,d){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(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}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 jr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(jr||{});class Hr extends nt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Wr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.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){var n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.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(ke.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.svg)}async removeBackgroundFromImageSelection(t=!0){var i;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 U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ut.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ut.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var n;const e=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Pc=v.gql`
|
|
2438
|
+
`;class gc{constructor(t,e=B.getShadowGraphqlClient.bind(B)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class mc{init(t,e,a){this.cognitoClient=new me.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){var a;const e=await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}})));(e==null?void 0:e.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){var n;return await((n=this.cognitoClient)==null?void 0:n.send(new me.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})))}async refreshTokens(){var a;const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new mc;class Vr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return ci(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ja.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ja.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const An=new Vr;class zr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,An.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,An.getPrecisionForCurrency(e))}}const pc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Ss(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});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!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),Ot.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},fc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Wa=async(r,t)=>{const e=r.map(o=>Ot.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=pc(a,t),i=a.map(o=>Ot.set({id:o,options:t},fc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},Cc=async(r,t)=>(await Wa([r],t))[0],wc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:Q(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),yc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):wc(t.panels)};class Sc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:cs})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ii(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 28.0.1-beta.29d7ea3f-e4d3-5c03-bd48-b02b5e782f5a"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!Pi())throw new Error("Application key required to use Flow Service.");return new $r}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new zr(s,o,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Gr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(a){return console.error(a),!1}}async authenticateBundleFromLocalStorage(t){var n,i;const e=T.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const a=T.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t);if((T.getMap("partnerCustomerIds")||new Map).get(s)&&await this.reloadLoggedInCustomer()){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=B.getShadowGraphqlClient(),a=await e.query({query:vs,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=T.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const o=T.getMap("transactionCustomerIds");if(o!=null&&o.has(t)&&o.get(t)&&await this.reloadLoggedInCustomer()){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(w=>{var S,y;return(y=(S=w.bundle)==null?void 0:S.transactions)==null?void 0:y.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(w=>{var S;return((S=w.transaction)==null?void 0:S.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}const c=(await e.query({query:Es,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=T.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),T.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=B.getShadowGraphqlClient(),n=(await e.query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l!=null&&l.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const o=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return o.id?(this.customer=o,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await B.getShadowGraphqlClient().mutate({mutation:uc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n!=null&&n.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const s=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!s.id)throw new Error("Failed to get customer.");return this.customer=s,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!(a!=null&&a.AccessToken)||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const s=await Wt.refreshTokens();if(s!=null&&s.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await B.getShadowGraphqlClient().query({query:hc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await B.getShadowGraphqlClient().mutate({mutation:Xo(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=T.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),T.setMap("bundlePartnerIds",s);const o=T.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),T.setMap("bundleOwnerIds",o);const l=new ta(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var h,g,m,p,f,C,w,S,y,E,b;const i=T.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),o={};try{const I=await this.loggedInBearerToken();o.Authorization=`Bearer ${I}`}catch{const F=((h=Object.entries(localStorage).find(([N,rt])=>N.startsWith("CognitoIdentityServiceProvider")&&N.endsWith("idToken")))==null?void 0:h[0])||"",k=localStorage.getItem(F);k&&!_t(k)&&(o.Authorization=`Bearer ${k}`)}const l={bundleOwnerId:s,...o,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=await B.getShadowGraphqlClient().query({query:Ho(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!((f=c.data)!=null&&f.bundles)||((C=c.data)==null?void 0:C.bundles.length)===0||!((w=c.data)!=null&&w.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const d=(S=c.data)==null?void 0:S.bundles[0],A=T.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),T.setMap("bundlePartnerIds",A);const u=new ta(this,d,e,a,s,{additionalHeaders:(y=n==null?void 0:n.graphql)==null?void 0:y.additionalHeaders,eagerFetchProducts:(b=(E=n==null?void 0:n.graphql)==null?void 0:E.productCollection)==null?void 0:b.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n==null?void 0:n.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,n){var u,h,g,m,p,f;const i=(u=T.getMap("bundleOwnerIds"))==null?void 0:u.get(t),s={};try{const C=await this.loggedInBearerToken();s.Authorization=`Bearer ${C}`}catch{const S=((h=Object.entries(localStorage).find(([E,b])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken")))==null?void 0:h[0])||"",y=localStorage.getItem(S);y&&!_t(y)&&(s.Authorization=`Bearer ${y}`)}const o={bundleOwnerId:i,...s,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=(f=(await B.getShadowGraphqlClient().mutate({mutation:Zo(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data)==null?void 0:f.bundleDuplicate;if(!(c!=null&&c.id))throw new Error("Unable to duplicate bundle");const d=T.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),T.setMap("bundlePartnerIds",d);const A=T.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),T.setMap("bundleOwnerIds",A),async()=>{var w,S;const C=new ta(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:(S=(w=n==null?void 0:n.graphql)==null?void 0:w.productCollection)==null?void 0:S.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await C.getInitializationPromise(),C}}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await B.getShadowGraphqlClient().query({query:Al(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await B.getShadowGraphqlClient().query({query:Yo,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=T.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),T.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=B.getShadowGraphqlClient(),n=async y=>{var x,F,k;if(y.length===0)return[];const E=y.map(N=>N.option.transactionId),b=await a.query({query:ls,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),I=b.data.transactions;if(I.length!==y.length){const N=((F=(x=b.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((k=I[0].integrationProduct)!=null&&k.integration)&&(this.activeIntegration=Promise.resolve(I[0].integrationProduct.integration)),I.map((N,rt)=>{var R;return{transaction:N,workflowId:N.workflowId,readOnly:((R=y.find(et=>et.option.transactionId===N.id))==null?void 0:R.option.readOnly)??!1,index:y[rt].index}})},i=async y=>{var I,x,F;if(y.length===0)return[];const E=await a.mutate({mutation:os,variables:{inputs:y.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})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),b=(I=E.data)==null?void 0:I.transactionCreateMany;if(!b||b.length===0){const k=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${k}`)}return b.map((k,N)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:y[N].index}))},s=t.map((y,E)=>({option:y,index:E})),o=s.filter(y=>y.option.type==="transaction"),l=s.filter(y=>y.option.type==="integration"||y.option.type==="external"),c=Ya(o,10),d=Ya(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await Wa(u,e),g=new Map(h.map(y=>[y.id,y])),m=T.getMap("transactionOwnerIds")||new Map,p=A.map(async y=>{var et;const{transaction:E,workflowId:b,readOnly:I,index:x}=y,F=g.get(b),k=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const N=m.get(E.id)||void 0,rt=new gc({onMutate:()=>({context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(et=k==null?void 0:k.workflowConfiguration)==null?void 0:et.singleVariantsRenderable,stateMutationFunc:I?async()=>{throw new z("State mutation is forbidden in read only mode!")}:async X=>(console.log(`LOG: updating transaction with options ${JSON.stringify(X,null,2)}`),console.trace(),this.updateTransactionState({...X,context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})),graphQlClient:()=>rt,readOnly:I,workflow:F,isReloadedTransaction:k.type==="transaction"};if(!I&&k.workflowState){const X=JSON.parse(k.workflowState);R.layouts=Object.values(X.layouts||{}).map(Ut=>Ut.layout),await ir(X),R.reloadedState=X}else R.layouts=yc(R.transaction,R.workflow);return R.renderableContextService=new zl(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:k}}),f=await Promise.all(p);T.setMap("transactionOwnerIds",m);const w=f.sort((y,E)=>y.index-E.index).map(async y=>{const{experienceOptions:E,options:b}=y,I=new Fr(this,E);return await I.getWorkflowManager().getInitializationPromise(),b.type!=="transaction"&&this.customer&&await I.attachCustomerDetails({email:this.customer.emailAddress}),I}),S=await Promise.all(w);return S.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),S}storeCustomer(t){const e=T.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),T.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await B.getShadowGraphqlClient().query({query:hs(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new Ca(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:gs(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new Ca(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(T.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await B.getShadowGraphqlClient().query({query:us,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await B.getShadowGraphqlClient().mutate({mutation:Ds,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 Gr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Bs,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,vc=async r=>{const e=await B.getShadowGraphqlClient().query({query:As,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Ec=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:bs,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},bc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},Bc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function qr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=Se(r.x,t.width-c,0),o.y=Se(r.y,t.height-d,0),o}const s=r;return s.x=Se(s.x,-n,t.width),s.y=Se(s.y,-i,t.height),s}function Se(r,t,e){return Math.min(Math.max(r,t),e)}class Wr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=vn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await Ae(o),c=this.frameData?this.frameData[s]:void 0;Sn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=$e(this.imageData.svg,this.imageData.colors||{},!1);return Re(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new z("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=qr(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(o=>!o))throw new z("Frame data not set. This is a bug");if(!this.workflowManager)throw new z("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new go(o,e,t[l]),new mo(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*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]=Fa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ic{updateRecipient(t,e,a,n,i,s,o,l,c,d){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(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}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 jr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(jr||{});class Hr extends nt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Wr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.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){var n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.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(ke.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.svg)}async removeBackgroundFromImageSelection(t=!0){var i;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 U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ut.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ut.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var n;const e=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Pc=v.gql`
|
|
2439
2439
|
query GetLoggedInCustomer($email: String!) {
|
|
2440
2440
|
customer(emailAddress: $email) {
|
|
2441
2441
|
id
|