@spiffcommerce/core 14.4.0 → 14.5.0

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/main.js CHANGED
@@ -467,7 +467,7 @@ var t=require("@apollo/client"),e=require("lodash.clonedeep"),i=require("react/j
467
467
  workflowState
468
468
  }
469
469
  }
470
- `,Gs=t=>{const e=[];for(const i of t.steps)switch(i.type){case si.DigitalContent:i.data.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Frame:const t=i.data;t.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),t.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Illustration:const A=i.data;A.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),A.varyColors&&A.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Colors});break;case si.Material:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Model:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Picture:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Question:i.data.varySelections&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selections});break;case si.Shape:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Text:const n=i.data;n.varyText&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Text}),n.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),n.varyColor&&n.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Color})}return e},Ts=[si.SilentIllustration,si.ProductOverlay],Os=async(t,e,i)=>{const A=[];t.introduction&&A.push({name:"Introduction",title:t.name,renderableSteps:[{type:si.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const i of t.steps){if(e.bulkScene){let t=!1;switch(i.type){case si.DigitalContent:i.data.varyUpload&&(t=!0);break;case si.Frame:{const e=i.data;!e.varyUpload||!e.varySelection&&i.option||(t=!0)}break;case si.Illustration:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case si.Material:i.data.varySelection&&(t=!0);break;case si.Model:i.data.varySelection&&(t=!0);break;case si.Picture:i.data.varySelection&&(t=!0);break;case si.Question:i.data.varySelections&&(t=!0);break;case si.Shape:i.data.varySelection&&(t=!0);break;case si.Text:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const n=Js(i.stepName,t.stepGroups);if(n){const t=A.find((t=>t.name===n.name));t?Ts.includes(i.type)?t.silentSteps.push(i):t.renderableSteps.push(i):A.push({name:n.name,title:n.name,renderableSteps:Ts.includes(i.type)?[]:[i],silentSteps:Ts.includes(i.type)?[i]:[]})}else A.push({name:i.stepName,title:i.stepTitle,renderableSteps:Ts.includes(i.type)?[]:[i],silentSteps:Ts.includes(i.type)?[i]:[]})}if(e.bulkScene){const n=i?.product?.bulkConfiguration;A.push({name:"Bulk",title:n?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:si.Bulk,stepName:"Bulk",stepTitle:n?.stepTitle??e.bulkSceneTitle,helpText:n?.helpText,data:{aspects:Gs(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&A.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:si.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),A},Js=(t,e)=>e.find((e=>e.stepNames.includes(t))),Ls=(t,e)=>(t.conditions||[]).every((t=>{const i=e[t.targetStepName];if(i&&i.selectedVariants){const e=i.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),zs=(t,e)=>t.map((t=>((t,e)=>{const i={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Ls(t,e))),silentSteps:t.silentSteps.filter((t=>Ls(t,e)))};return 0===i.silentSteps.length&&0===i.renderableSteps.length?null:i})(t,e))).filter((t=>null!==t)),js=async(t,e)=>{const i=zs(t,e),A=[];for(const t of i)for(const e of t.renderableSteps)if(e.type===si.Model||e.type===si.Material||e.type===si.Picture||e.type===si.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&A.push(e.stepName)}else A.push(e.stepName);const n=i.filter((t=>t.renderableSteps.filter((t=>A.includes(t.stepName))).length>0));for(const t of n)t.renderableSteps=t.renderableSteps.filter((t=>A.includes(t.stepName)));return n};function Vs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function Ks(t,e,i,A){const n=i.width*t.zoom,r=i.height*t.zoom;if(A){const A=t,n=Math.max(e.width/i.width,e.height/i.height);A.zoom=Math.max(n,t.zoom);const r=i.width*A.zoom,a=i.height*A.zoom;return A.x=Ws(t.x,e.width-r,0),A.y=Ws(t.y,e.height-a,0),A}const a=t;return a.x=Ws(a.x,-n,e.width),a.y=Ws(a.y,-r,e.height),a}function Ws(t,e,i){return Math.min(Math.max(t,e),i)}class Xs{constructor(t){Vs(this,"offsets",void 0),Vs(this,"forceImageCover",void 0),Vs(this,"targetElements",void 0),Vs(this,"imageData",void 0),Vs(this,"frameData",void 0),Vs(this,"_debouncedUpdateFrameOffsets",void 0),Vs(this,"minZoomScale",[.03]),Vs(this,"maxZoomScale",[20]),Vs(this,"onFrameDataChangeListeners",void 0),Vs(this,"onZoomChangeListeners",void 0),Vs(this,"workflowManager",void 0),Vs(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=F(I)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let i=0;i<e.currentFrameSources.length;i++){const A=e.currentFrameSources[i],n=await kn(A);F(C)(n,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[i]=n,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(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){t?t.forEach(((e,i)=>{const A=Yn.get(e);A&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[i]=A)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,i,A){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const n=this.frameData.map(((A,n)=>{const r=(e[n]-this.offsets[n].x)/this.offsets[n].zoom,a=(i[n]-this.offsets[n].y)/this.offsets[n].zoom;return{x:e[n]-r*t[n],y:i[n]-a*t[n],zoom:this.imageData.width*t[n]/this.imageData.width}}));this.updateOffsets(n,A),this.onZoomChangeListeners.forEach((e=>e(t)))}}setPatternData(t){this.imageData=t,t&&this.frameData&&(this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,i){const A=this.imageData;if(!A||!this.frameData)return;if(this.frameData.length!==t.length)throw new ar("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,i)=>t[i].x!==e.x||t[i].y!==e.y||t[i].zoom!==e.zoom))||i?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Ks(t[i],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,A,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,i,A,n){if(!i||0===i.length||i.some((t=>!t)))throw new ar("Frame data not set. This is a bug");if(!this.workflowManager)throw new ar("No workflow manager set, cannot update offsets.");const r=this.workflowManager.getCommandDispatcher();A.forEach(((i,A)=>{r(new wn(i,e,t[A]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),n&&n()}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(((e,i)=>{const A=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[i]=A,this.maxZoomScale[i]=2.5*A):(this.minZoomScale[i]=A/10,this.maxZoomScale[i]=2.5*A)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Hn(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function qs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Zs{constructor(t,e,i){qs(this,"configuration",void 0),qs(this,"layouts",void 0),qs(this,"product",void 0),qs(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new er(t);let i="";if(this.configuration.type===si.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),i=t,!t)throw new nr(this.configuration,"Couldn't find an asset for product overlay step")}const A=this.evaluateAssetType();if(A===ze.Image){const i=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!i)throw new Error("Undefined raster silent step source");const n={stepName:this.configuration.stepName,id:Te(),src:i,type:A,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===si.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:n.id,region:t},command:new an(n,e)}}{const n=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:i,r=async()=>new Promise(((t,e)=>{n?Wi(n).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),a=await TA(await r()),s={stepName:this.configuration.stepName,id:Te(),cachedObjectURL:await Wn(a.svg),src:n,svg:a.svg,colors:a.colors,type:A,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===si.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new an(s,e)}}})),this.configuration=t,this.layouts=e,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new nr(this.configuration,"Missing regions.");if(this.configuration.type===si.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===si.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new er(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===si.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?ze.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),ze.Illustration)}}const $s=async t=>{const e=`${wr.getServicesApiUrl()}/shortener`;try{const i=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await i.json()).shortUrl}catch(t){throw console.error(t),new cr("Failed to shorten URL, see console.")}};function _s(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class to{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,i,A=3e3,n=10){_s(this,"pollingId",void 0),_s(this,"attempts",void 0),_s(this,"interval",void 0),_s(this,"maxAttempts",void 0),_s(this,"predicate",void 0),_s(this,"onSuccess",void 0),_s(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=i,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=A,this.maxAttempts=n,this.poll()}}const eo=new class{async init(t,e,i){return i&&await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{const i=A?.storage?.videoShortUrl,n=A?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:i,videoUrl:n})}))}async regenerateQRCode(t,e,i,A,n,r,a,s,o){if(e||""===i||""!==A)o(!1);else{const e=async()=>{const t=(await br([i]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},c=await new Promise(((t,i)=>{new to((async()=>!!(await e()).link),(async()=>{const i=await e();if(!i.link||!i.link)throw new Ar(i.asset);t({rel:"mpeg4",href:i.link})}),(()=>{i("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>s(new sn(t.id))));const l="http"===r.data.baseUrl.slice(0,4)?"":"https://",g=new URL(l+r.data.baseUrl);g.searchParams.append("video",btoa(JSON.stringify([c]))),g.pathname=g.pathname+("/"===g.pathname.slice(-1)?"":"/");const h=g.toString();if(h.length>=2e3)throw new cr("Cannot create QR code, URL too long.");const d=await $s(h);if(a(d),!r.data||!r.data.regions)throw new nr(r,"Missing regions.");const u=await this.regionElements(r),w=await this.command(d,u,n,r.stepName);w&&(w.command&&n.getCommandDispatcher()(w.command),w.followup&&await w.followup()),await n.setSelectionsAndElements(r.stepName,[],u,(async()=>{n.updateStorage(r.stepName,{videoShortUrl:d,videoUrl:A}),o(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:Te(),region:t})))}async command(t,e,i,A){const n=i.getLayouts(),r=`data:image/svg+xml;base64,${btoa(await(0,y.toString)(t,{type:"svg"}))}`,a=e.map((t=>{const e=t.region,i=n.find((t=>t.panelId===e?.panelId));if(!i&&e)throw new er(e);if(i&&!e)throw new Error("Region not found");if(!i||!e)throw new Error("Neither a region or layout found!");return new an({stepRegion:e,stepName:A,id:t.id,src:r,type:ze.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},i)}));return{command:new An(a),followup:async()=>{}}}};function io(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const Ao=new class{constructor(){io(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Nn(e);const i=t.asset;if(!i)throw new ir(t);const A=i.fileLink;if(A)return Wi(A);throw new Ar(i)}))}async init(t,e,i){if(i)return await this.reload(t,e,i),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const i=t.option,A=Ur.getDefaultVariant(i);return A?this.selectVariantCommand(t,A,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const i=t.data.regions.map((t=>Nn(t)));e.updateStorage(t.stepName,{currentFrameSources:i})}if(A){const i=async()=>{const i=A.storage?.framePatternSrc,n=A.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:n,framePatternSrc:i}),i){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,A),e.updateMetadata(t.stepName,{image:i}),e.updateStorage(t.stepName,{framePatternSrc:i})}if(n?.some((t=>t.zoom))){const i=e.getStepSpecificServices(t.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");i.updateOffsets(n)}e.setMandatoryFulfilled(t.stepName,!0)};if(A.selectedVariants&&A.selectedVariants.length>0){const r=A.selectedVariants[0].id;if(t.option&&r){const A=t.option.variants?.find((t=>t.id===r));A&&await e.setSelectionsAndElements(t.stepName,[A],n,(async()=>{const n=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(A,t))));e.updateStorage(t.stepName,{currentFrameSources:n}),await i()}))}}else await e.setSelectionsAndElements(t.stepName,[],n,i)}}selectImage(t,e,i){i.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?i.addPoller(new to((async()=>{const t=(await Nr.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Nr.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,i)}))}),(()=>{throw new cr("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,i)}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i,A,n);r&&(r.command&&A.getCommandDispatcher()(r.command),r.followup&&await r.followup())}getCreateElementCommand(t,e,i,A){return new an({id:t,type:ze.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/A.frameData.width,scaleY:e.height/A.frameData.height,path:A.frameData.path,dataWidth:A.frameData.width,dataHeight:A.frameData.height,stepRegion:e,stepName:A.stepName,disablePlaceholder:A.disablePlaceholder,focalBlur:A.focalBlur,focalBlurStrength:A.focalBlurStrength,focalBlurRadius:A.focalBlurRadius,pattern:A.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const i=await Gn(t),A=i.width,n=i.height,r={src:t,width:A,height:n,aspect:A/n};bn.set(t,r),e.setPatternData(r)}else{const i=await Ki(t),A=await Sn(i),n={src:t,width:A.width,height:A.height,aspect:A.width/A.height};bn.set(t,n),e.setPatternData(n)}}async selectVariantCommand(t,e,i,A,n,r){const a=A.getStepSpecificServices(t.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");const s=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));n&&n(!0);const o=await Promise.all(t.data.regions.map((async(e,n)=>{const r=await kn(s[n]),o=a.getImageData(),c=i.map((t=>new sn(t.id))),l=o?Hn(o,r):void 0,g=o?{id:Te(),src:o.src,x:l?.x||0,y:l?.y||0,width:o.width,height:o.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,h=Te(),d=A.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new er(e);return{command:this.getCreateElementCommand(h,e,d,{frameData:r,pattern:g,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:h,region:e},removeExistingCommands:c}}))),c=o.map((t=>t.command)),l=o.map((t=>t.removeExistingCommands)).flat();return{command:new An([...c,...l]),followup:async()=>{n&&n(!1),await A.setSelectionsAndElements(t.stepName,e?[e]:[],[...o.map((t=>t.regionEl))],(async()=>{if(A.updateStorage(t.stepName,{currentFrameSources:s}),r){const e=A.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(r,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const i=t.fileLink;if(i)return i;throw new Ar(t)}async loadPatternFromAsset(t,e,i){const A=this.patternSource(t),n=i.markUpdatePending(),r=i.getStepSpecificServices(e.stepName)?.frameService;if(!r)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,r),i.updateMetadata(e.stepName,{image:A}),i.updateStorage(e.stepName,{framePatternSrc:A}),i.markUpdateCompleted(n)}};const no=new class{async getIllustrationBody(t){return new Promise((e=>{Wi(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,i,A){return new an({stepRegion:e,stepName:A.stepName,colors:A.svg.colors,id:t,src:A.src,svg:A.svg.svg,cachedObjectURL:A.objectURL,type:ze.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},i)}getColors(t,e){const i=e.getRegionElements(t.stepName)||[];if(0===i.length)return[];try{return KA(i[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,i){const A=t.option;if(!A)return null;if(i)return this.reload(t,e,i);{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantCommand(t,i,[],(()=>{}),e)}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(!r||!i)throw new Error("Required illustration variant no longer available");{const a=r.variants?.find((t=>t.id===i));if(a){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[a],i,(async()=>{e.updateMetadata(t.stepName,{colors:A.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const i=t.data.colorOption;return i&&i?i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,i,A,n){const r={};for(const[t,e]of n.entries())r[t]={browserValue:e,spotColor:r[t]?.spotColor};const a=GA(t,e,i,r),s=await Wn(a),o=[];for(const t of A){for(const[e,i]of n.entries())o.push(new pn(t,e,i));o.push(new En(t,a,s))}return new An(o)}async changeColors(t,e,i,A,n){if(0===e.length)return;const r=KA(e[0].id,A().map((t=>t.layoutState))),a={...r.colors},s={};Object.entries(a).forEach((([t,e])=>{const i={browserValue:e.browserValue},A=e.spotColor;A&&(i.spotColor={profileName:A.profileName,namedColor:A.namedColor}),s[t]=i}));for(const[t,e]of n.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor},s[t]={browserValue:e};let o=Array.from(Object.values(a)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{o=o.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:o});const l=new Map;if(Object.entries(a).forEach((([t,e])=>{l.set(t,e.browserValue)})),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const g=await this.changeColorsCommand(r.svg,r.width,r.height,e.map((t=>t.id)),l);i.updateStorage(t.stepName,{colors:s}),i.getCommandDispatcher()(g)}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i,A,n);r&&(r.command&&n.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,i,A,n){if(!t.data||!t.data.regions)throw new nr(t,"Missing regions.");A(!0);const r=i.map((t=>new sn(t.id)));n.setMandatoryFulfilled(t.stepName,!1);const a=e.asset;if(!a)throw new ir(e);const s=a.fileLink;if(!s)throw new Ar(a);const o=await TA(await this.getIllustrationBody(s)),c=await Wn(o.svg),l=t.data.regions.map((e=>{const i=n.getLayouts().find((t=>t.panelId===e.panelId));if(!i)throw new er(e);const A=Te();return{regionElement:{id:A,region:e},command:this.getCreateElementCommand(A,e,i,{stepName:t.stepName,src:s,objectURL:c,svg:o})}})),g=[...l.map((t=>t.command)),...r];let h=Array.from(Object.values(o.colors)).map((t=>t.browserValue));const d=t.data.colorOption;return d&&d.variants?.forEach((t=>{h=h.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),n.updateMetadata(t.stepName,{colors:h}),{command:new An(g),followup:async()=>{await n.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{n.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const ro=new class{async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(i)await this.reload(t,e,i);else{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(!r)throw new tr(t);if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(i){const A=r.variants?.find((t=>t.id===i));if(A){const i=A.material,a=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],a,(async()=>{const A=e.getModelContainer();if(A){const n=t.data.targetMaterials.map((t=>A.applyMaterialVariant(t,r.id||"",i||{})));Promise.all(n).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){const n=i.getModelContainer();A(!0);const r=e.material;if(!r)throw A(!1),new ir(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{n&&t.data.targetMaterials.forEach((e=>{t.option&&n.applyMaterialVariant(e,t.option.id||"",r)})),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const ao=new class{async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(i)await this.reload(t,e,i);else{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{const i=e.getModelContainer();if(i&&t.option){const n=A.asset?.fileLink;if(!n)throw new ir(A);await i.applyModelVariant(t.option.id||"",{model:n,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){A(!0);const n=e.asset?.fileLink;if(!n)throw new ir(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=i.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:n,contextService:i.getLayoutPreviewService()},t.data.replaceProductModel||!1),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const so=new class{async init(t,e,i){return i?(await this.reload(t,e,i),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{e.updateStorage(t.stepName,{text:A?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==A?.storage?.text)}))}async changeText(t,e,i,A,n){const r=await this.changeTextCommand(t,e,i,A,n);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,i,A,n){const r=i.getRegionElements(t.stepName),a=i.getStepSpecificServices(t.stepName)?.module;if(!a)return console.error("Missing module."),null;const s=i.getProfanities();if(!this.validateInput(t,e,s,n))return i.setMandatoryFulfilled(t.stepName,!1),console.error(A),null;if(i.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;i.updateStorage(t.stepName,{text:e});const o=(e,A,n)=>{const r=n||Te(),a=i.getLayouts().find((t=>t.panelId===A.panelId));if(!a)return console.error(`Can not find layout for region: ${A.panelId}`),null;const s=[];return n&&s.push(new sn(r)),s.push(new an({stepRegion:A,stepName:t.stepName,colors:{},id:r,svg:e,type:ze.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},a)),{id:r,region:A,command:new An(s)}};if(r.length>0){const t=r.map((t=>{if(!t.region)return null;const i=a.svgPrint(e,t.region);return o(i,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new An(t),followup:async()=>{}}}{const A=t.data.regions.map((t=>o(a.svgPrint(e,t),t))),n=A.filter((t=>!!t)).map((t=>t&&t.command));return{command:new An(n),followup:async()=>{const e=A.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await i.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,i,A){if(t.data&&t.data.maxLength){const i=t.data.maxLength;if(e.length>i)return A("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return A("Unsupported characters."),!1;const n=(0,x.split)(e.toLowerCase());for(const t of n)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,""))return A("Blocked profanity."),!1}return A(""),!0}};const oo=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else if(A.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,A.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=e.asset;if(!n)throw new ir(e);const r=n?.fileLink;if(!r)return console.error("No URL for picture!"),null;A(!0),i.setMandatoryFulfilled(t.stepName,!1);const a=i.getRegionElements(t.stepName).map((t=>new sn(t.id))),s=t.data.regions.map((e=>{const A=i.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new er(e);const n=Te();return{regionElement:{id:n,region:e},command:new an({stepName:t.stepName,stepRegion:e,id:n,src:r,type:ze.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},A)}}));return{command:new An([...a,...s.map((t=>t.command))]),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],s.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const co=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=A.variants;if(Ur.getDefaultVariant(A)){const n=i?.find((t=>t.id===A.defaultVariant?.id));return this.selectVariantLambda(t,n?.id||"",e)}}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(n&&i){const A=n.variants?.find((t=>t.id===i));A&&await e.setSelectionsAndElements(t.stepName,[A],[])}}}async selectVariant(t,e,i){await i.getInitializationPromise();const A=await this.selectVariantLambda(t,e,i);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i){const A=t.option;if(!A)return null;const n=A.variants;if(!n)return null;const r=n.length>1?n.find((t=>t.id===e)):n[0];if(!r)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[r],[],(async()=>{i.setMandatoryFulfilled(t.stepName,!0)}))}}}};const lo=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(!i){const i=Ur.getDefaultVariant(A);if(!i)return null;const n={fill:i.color,stroke:i.color,variant:i};return this.selectVariantCommand(t,n,[],e)}return await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.updateStorage(t.stepName,{colour:A.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=A.getLayouts();if(i.length>0){const r=t=>{const i=t.region;if(!n.find((t=>t.panelId===i?.panelId)))throw new er(i);const A=e.variant?.color;return A?new pn(t.id,"spiff-fill-shape",A):(console.error("Failed to change color."),null)},a=i.map(r).filter((t=>!!t));return{command:new An(a),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],i),A.updateStorage(t.stepName,{colour:e.fill||""})}}}{const i=i=>{const A=n.find((t=>t.panelId===i.panelId));if(!A)throw new er(i);const r=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${e.variant?.color}"\n />\n </svg>\n `,a={};a["spiff-fill-shape"]={browserValue:e.variant.color};const s=Te();return{id:s,region:i,command:new an({stepRegion:i,stepName:t.stepName,colors:a,id:s,svg:r,type:ze.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,excludeFromExport:t.data.excludeFromPrint},A)}},r=t.data.regions.map(i),a=r.filter((t=>!!t)).map((t=>t?.command)),s=r.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new An(a),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{A.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function go(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class ho extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ho.name}}const uo=["‘","’","“","”","\n"];class wo extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=wo.name}}const Bo=new class{constructor(){go(this,"cachedColors",new Map),go(this,"filterUnsupportedCharacters",((t,e)=>{let i=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const A=[],n=e?cA(e):void 0;if(n){const t=i.split("").filter((t=>!uo.includes(t))).join(""),e=t.split("").map((t=>n.getFont().charToGlyph(t)));for(let i=0;i<e.length;i++){".notdef"===e[i].name&&A.push(String.fromCharCode(t.charCodeAt(i)))}}for(let t=0;t<A.length;t++)i=i.replaceAll(A[t],"");return i})),go(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),go(this,"getErrorsForText",((t,e,i)=>{const A=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&A.push({localizationKey:"workflow.steps.text.characterLimit"});const n=i.getProfanities(),r=(0,x.split)(t.toLowerCase());for(const t of r)for(const e in n){if(t===n[e].toLowerCase().replace(/\s/g,"")){A.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&A.push({localizationKey:"workflow.steps.text.multipleLines"}),A}))}async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=this.getDefaultImageFillVariant(t.data),n=i?.asset?.fileLink,r=n?await Un(n):void 0,a=r?{src:r.src,height:r.height,width:r.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:a}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:i?.name});const s=Ur.getDefaultVariant(A);if(s)return this.selectVariantCommand(t,s,{},[],e,(()=>{}),(()=>{}),a)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>KA(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const i=t.data.colorOption;if(i){const e=i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher();e.variant?A.updateMetadata(t.stepName,{color:e.variant.name}):A.updateMetadata(t.stepName,{color:e.fill});const r=t.data.colorOption,a=r?this.createTextFillSpotColor(r,e.variant):void 0;r?A.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:r.colorProfile?.key}):A.updateStorage(t.stepName,{color:e.fill});for(const t of i){if(!e.fill)throw new Error("Fill not set on new color selection!");n(new cn(t.id,e.fill,a))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const i=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(i.map((async e=>{const i=await Un(e);return{src:e,width:i.width,height:i.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher(),r=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));A.updateMetadata(t.stepName,{fillImage:r?.name}),A.updateStorage(t.stepName,{fillImage:e});for(const t of i){n(new ln(t.id,e))}}getProcessedInput(t,e,i){const A=i?t:this.injectReplaceableText(t,e);return QA(A,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,i,A){const n=A.getStepStorage(i.stepName),r=this.getProcessedInput(t,i.data,!!n.customiseAllText),a={command:void 0,helperText:"",errors:this.getErrorsForText(t,i,A)};if(a.errors.length>0)return a.helperText=a.errors[0].localizationKey,a;const s=(i.data.maxLength-r.length).toString();a.helperText=`${s} characters remaining`;const o=A.getTransaction().bulk&&i.data.varyText||!1,c=[],l=new Map,g=new Map;for(const t of e){if(!t.fontData)throw new ar("Failed to resolve font data for text.");const[e,A]=Ln(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[r],{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});l.set(t.id,e),g.set(t.id,A);const n=i.data.curved?r:(A||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,i.data,t.id,n,o))}if(!i.data.curved&&e.length>0){if(!Array.from(g.values()).every((t=>t)))return a.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),a}return A.updateStorage(i.stepName,{text:t}),A.updateMetadata(i.stepName,{text:r}),n.defaultCleared&&A.setMandatoryFulfilled(i.stepName,!0),a.command=new An(c),a.command.varying=o,a}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i.getStepStorage(t.stepName)||{},i.getRegionElements(t.stepName),i,A,n);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}createTextFillSpotColor(t,e){const i=t.colorProfile;if(i){const t=(i.name||"").replace(/\s/g,"-"),A=t.lastIndexOf("/"),n=t.slice(A+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:n,namedColor:e.namedColor}}}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const a=r.variants?.find((t=>t.id===i));if(a){const i=await this.fontDataFromVariant(a),r=n.map((t=>({id:t.id,region:t.stepRegion}))),s=A.storage?.color,o=A.storage?.text;await e.setSelectionsAndElements(t.stepName,[a],r,(async()=>{e.updateMetadata(t.stepName,{color:s,text:o}),e.updateStorage(t.stepName,{text:o,inputText:o});const A=n.map((t=>new dn(t.id,i))),r=new An(A);e.getCommandDispatcher()(r),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Bo.updateInputText(o||"",n,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Ur.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Ur.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Ur.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ir(t);const i=e.fileLink;if(!i)throw new Ar(e);return{assetUrl:i,name:(await sA(i)).names.fullName.en}}async selectVariantCommand(t,e,i,A,n,r,a,s){const o=n.markUpdatePending(),c=await this.fontDataFromVariant(e);if(A.length>0){const l=A.map((t=>new dn(t.id,c)));if(s){const t=A.map((t=>new ln(t.id,s)));l.push(...t)}const g=await this.changeInputTextWithRegion(t,t.data.size||30,c,i.text||"",i,n,!!i.customiseAllText,r,a);g&&l.push(g);return{command:new An(l),followup:async()=>{n.markUpdateCompleted(o),await n.setSelectionsAndElements(t.stepName,[e],A)}}}{const A=await this.createTextboxRegions(t.stepName,e,t.data,c,i,n),l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A[0]?.newElement.input||i.text||t.data.defaultText||"",i,n,!!i.customiseAllText,r,a),g=A.flatMap((t=>t.commands));if(s){const t=A.map((t=>new ln(t.regionElement.id,s)));g.push(...t)}l&&g.push(l);return{command:new An(g),followup:async()=>{n.markUpdateCompleted(o)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,i,A,n,r){if(!i||!i.regions)throw new Error("Step data not supplied");const a=r.getTransaction().bulk&&i.varyText||!1,s=a?"":n.text||i.defaultText||"",o=this.getProcessedInput(s,i,!1),c=await Promise.all(i.regions.map((async e=>{const c=r.getLayouts().find((t=>t.panelId===e.panelId)),l=Te();try{if(!c)throw new wo("Failed to find layout for region: "+e.panelId);const g=i.colorOption;let h;if(g&&g.variants){const e=g.variants.find((t=>t.id===g.defaultVariant?.id))||g.variants[0];h=this.createTextFillSpotColor(g,e),r.updateStorage(t,{colorProfileAssetKey:g.colorProfile?.key})}const d=await this.getDefaultColor(i),u=d||"#000000",w={stepRegion:e,stepName:t,align:this.textAlign(i),fill:n.color?n.color:u,fontSize:i.size||30,fontData:A,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:o,input:s,type:ze.Textbox,vertical:i.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:i.verticalAlign||"middle",curved:i.curved,paths:i.paths,fillSpotColorDefinition:h},B=[],p=new Map,E=new Map;if(!w.fontData)throw new ar("Failed to resolve font data for text.");const[m,f]=Ln(w.fontSize,w.fontData,{left:w.x,top:w.y,width:w.width,height:w.height,rotation:w.rotation,panelId:""},[o],{size:i.size,minSize:i.minSize,maxSize:i.maxSize});p.set(w.id,m),E.set(w.id,f);const C=i.curved||i.vertical?o:(f||[]).join("\n");B.push(this.generateTextChangeCommandsForRegion(m,i,w.id,C,a));const Q=new an(w,c);return Q.varying=a,{regionElement:{id:l,region:e},commands:[Q,...B],newElement:w,fontData:A}}catch(t){throw console.log(t),new ho("Error adding font to region")}}))).catch((t=>{throw t instanceof ho?(ca.setLatestToast("Failed to load font.",Eo.Error),t):t instanceof wo?t:new Error(t)}));return await r.setSelectionsAndElements(t,[e],c.map((t=>t.regionElement)),(async()=>{r.updateMetadata(t,{text:s}),r.updateStorage(t,{text:s})})),c}generateTextChangeCommandsForRegion(t,e,i,A,n){const r=[],a=new Bn(i,A);if(a.varying=n,r.push(a),!e.size){const e=new gn(i,t);e.varying=n,r.push(e)}const s=new An(r);return s.varying=n,s}async changeInputTextWithRegion(t,e,i,A,n,r,a,s,o,c){const l=(A||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),g=this.getProcessedInput(l,t.data,a),h=r.getRegionElements(t.stepName),d=new Map,u=new Map;for(const A of h)if(A.region){const[n,r]=Ln(e,i,A.region,[g],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(A.id,n),u.set(A.id,r)}const w=(()=>{if(t.data&&t.data.maxLength&&g.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=r.getProfanities(),i=(0,x.split)(g.toLowerCase());for(const t of i)for(const i in e){if(t===e[i].toLowerCase().replace(/\s/g,""))return s(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(g.includes("\n")||g.includes("\r")))return s(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(u.values()).every((t=>t)))return s(!0),{error:"Does not fit."}}return s(!1),{info:(t.data.maxLength-g.length).toString()}})();if(w.error)return void o(w.error);if(o(`${w.info} characters remaining`||""),c)return;r.updateStorage(t.stepName,{text:l}),r.updateMetadata(t.stepName,{text:this.injectReplaceableText(l,t.data)});const B=r.getTransaction().bulk&&t.data.varyText||!1;n.defaultCleared&&r.setMandatoryFulfilled(t.stepName,!0);const p=[];for(const e of h){const i=t.data.curved?g:(u.get(e.id)||[]).join("\n");p.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,i,B))}const E=new An(p);return E.varying=B,E}};function po(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}let Eo;var mo;(mo=Eo||(Eo={})).Error="Error",mo.Warning="Warning",mo.Info="Info";class fo extends Ja{constructor(t){super(),po(this,"update",void 0),po(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Co{constructor(t,e,i,A,n,r,a,s,o,c,l=!1,g,h=!1){po(this,"reloadedState",void 0),po(this,"transaction",void 0),po(this,"ownerCustomer",void 0),po(this,"updateTransaction",void 0),po(this,"confirmedDesign",void 0),po(this,"editedSteps",void 0),po(this,"informationResults",void 0),po(this,"layouts",void 0),po(this,"mandatorySteps",void 0),po(this,"pendingUpdates",void 0),po(this,"selectionCost",void 0),po(this,"workflow",void 0),po(this,"stepSpecificServices",void 0),po(this,"previewService",void 0),po(this,"profanityFilter",void 0),po(this,"pollers",void 0),po(this,"commandContext",void 0),po(this,"stepElements",void 0),po(this,"stepInitialised",void 0),po(this,"stepMetadata",void 0),po(this,"stepSelections",void 0),po(this,"storage",void 0),po(this,"confirmCallbacks",void 0),po(this,"editedCallbacks",void 0),po(this,"elementsCallbacks",void 0),po(this,"informationResultCallbacks",void 0),po(this,"initCallbacks",void 0),po(this,"makingAdjustmentsCallback",void 0),po(this,"mandatoryCallbacks",void 0),po(this,"metadataCallbacks",void 0),po(this,"selectionCallbacks",void 0),po(this,"stepSpecificStorageCallbacks",void 0),po(this,"storageCallbacks",void 0),po(this,"currentVariationRecordCallbacks",void 0),po(this,"variationRecordCallbacks",void 0),po(this,"allScenes",void 0),po(this,"product",void 0),po(this,"invalidModelVariants",void 0),po(this,"currentAdjustingStepId",void 0),po(this,"renderableContextService",void 0),po(this,"workflowStatePromiseQueue",new La(1)),po(this,"variationRecords",[]),po(this,"currentVariationRecord",void 0),po(this,"initializationPromise",void 0),po(this,"initialized",!1),po(this,"readOnly",!1),po(this,"modelContainer",void 0),po(this,"isReloadedTransaction",!1),po(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,i]of e)i.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=n,this.commandContext=A,this.reloadedState=c,this.transaction=r,this.readOnly=l,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=a,this.previewService=s,this.modelContainer=g,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=o,this.currentVariationRecord=null,this.isReloadedTransaction=h,this.initializationPromise=this.initializeDefaultWorkflowState(t,r),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await Os(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const i=zs(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:A,commands:n}=await this.stepElementsForIntroducedSilentSteps(i,!!this.reloadedState);this.commandContext.apply(new An(n),!0),this.stepElements={...this.stepElements,...A},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,i=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),i&&this.modelContainer?.executeAnimation(i)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t)}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((e=>{const i=this.stepSelections[e.stepName];i&&i.selectedVariants&&i.selectedVariants.length>0&&(t[e.stepName]={selections:i.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=Te();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise(),this.render3DScene()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}async updateStorage(t,e){const i={...this.storage,[t]:{...this.storage[t],...e}};if(!F(C)(i,this.storage)){this.storage=i;const e=new $A(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const i={stepName:e.stepName};i.storage=this.storage[e.stepName],i.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(i)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new fo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new fo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new ar("Attempted to serialize state before it was initialized.");const i=JSON.stringify(this.dehydrateState(F(e)(t.transaction))),A=t.variation;if(!A)return{transaction:i};const n={layouts:{},serializableWorkflow:{steps:[]},...F(e)(A)||{}};return{transaction:i,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((i,A)=>{const n=[...t[A]||[]];return e.forEach((t=>{const e=n.findIndex((e=>e.id===t.id));e>-1&&n.splice(e,1)})),i[A]=n,i}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Ls(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!Ls(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const i=this.product;if(!i)return Promise.resolve({stepElements:{},commands:[]});const A=async(t,e,i)=>{if(t.type===si.SilentIllustration){return{step:t,results:await new Zs(t,e).trigger()}}if(t.type===si.ProductOverlay){return{step:t,results:await new Zs(t,e,i).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},n=t.filter((t=>!this.stepInitialised[t.stepName])),r={stepElements:{},commands:[]},a=[];for(const t of n)this.markStepsAsInitialised([t.stepName]),e||a.push(A(t,this.layouts,i));const s=await Promise.all(a);for(const t of s)r.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),r.commands=[...r.commands,...t.results.map((t=>t.command))];return r}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new sn(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,i,A){const n=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{Ls(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const r=this.allScenes,a=zs(r,n),s=zs(r,this.stepSelections),o=a.map((t=>t.silentSteps)).flat(),c=s.map((t=>t.silentSteps)).flat().filter((t=>!o.some((e=>e.stepName===t.stepName))));o.forEach((t=>{Ls(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:g,commands:h}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...g,[t]:i},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===si.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(i.map((t=>t.id)))}const d=[...h,...l.map((t=>new sn(t.id))),new $A(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new An(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),A&&await A()}async ensureStepsAreLoaded(){const t=[],e=zs(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const i of e)if(!this.stepInitialised[i.stepName])switch(this.stepInitialised[i.stepName]=!0,i.type){case si.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case si.DigitalContent:t.push(eo.init(i,this,this.reloadedState));break;case si.Frame:case si.Photo:{const e=new Xs(i.data.forceImageCover);e.connectWorkflowManager(this,i.stepName),this.stepSpecificServices[i.stepName]={frameService:e},t.push(Ao.init(i,this,this.reloadedState))}break;case si.Illustration:t.push(no.init(i,this,this.reloadedState));break;case si.Material:t.push(ro.init(i,this,this.reloadedState));break;case si.Model:t.push(ao.init(i,this,this.reloadedState));break;case si.Module:this.stepSpecificServices[i.stepName]={module:await cs(i.data.module)},t.push(so.init(i,this,this.reloadedState));break;case si.Picture:t.push(oo.init(i,this,this.reloadedState));break;case si.Question:t.push(co.init(i,this,this.reloadedState));break;case si.Shape:t.push(lo.init(i,this,this.reloadedState));break;case si.Text:t.push(Bo.init(i,this,this.reloadedState))}const i=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),A=i.filter((t=>!!t&&!!t.command)).map((t=>t.command)),n=i.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));A&&A.length>0&&this.commandContext.apply(new An(A),!0);for(const t of n)await t();n.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((e=>e(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return js(this.allScenes,this.stepSelections)}}function Qo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class yo{constructor(t){Qo(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function Do(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Io{constructor(t,e){Do(this,"manager",void 0),Do(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Io.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Io.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new yo(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new yo(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new yo(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.step.tags||[]}hasTag(t){return this.step.tags?.includes(t)||!1}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),i=this.step.data.modelAnimation,A=this.step.data.lookAtAnimation;t&&A&&t.executeCameraAnimation(A),e&&i&&e.executeAnimation(i)}}function xo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Do(Io,"updateState",new Map);const vo=t.gql`
470
+ `,Gs=t=>{const e=[];for(const i of t.steps)switch(i.type){case si.DigitalContent:i.data.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Frame:const t=i.data;t.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),t.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Illustration:const A=i.data;A.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),A.varyColors&&A.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Colors});break;case si.Material:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Model:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Picture:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Question:i.data.varySelections&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selections});break;case si.Shape:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Text:const n=i.data;n.varyText&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Text}),n.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),n.varyColor&&n.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Color})}return e},Ts=[si.SilentIllustration,si.ProductOverlay],Os=async(t,e,i)=>{const A=[];t.introduction&&A.push({name:"Introduction",title:t.name,renderableSteps:[{type:si.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const i of t.steps){if(e.bulkScene){let t=!1;switch(i.type){case si.DigitalContent:i.data.varyUpload&&(t=!0);break;case si.Frame:{const e=i.data;!e.varyUpload||!e.varySelection&&i.option||(t=!0)}break;case si.Illustration:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case si.Material:i.data.varySelection&&(t=!0);break;case si.Model:i.data.varySelection&&(t=!0);break;case si.Picture:i.data.varySelection&&(t=!0);break;case si.Question:i.data.varySelections&&(t=!0);break;case si.Shape:i.data.varySelection&&(t=!0);break;case si.Text:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const n=Js(i.stepName,t.stepGroups);if(n){const t=A.find((t=>t.name===n.name));t?Ts.includes(i.type)?t.silentSteps.push(i):t.renderableSteps.push(i):A.push({name:n.name,title:n.name,renderableSteps:Ts.includes(i.type)?[]:[i],silentSteps:Ts.includes(i.type)?[i]:[]})}else A.push({name:i.stepName,title:i.stepTitle,renderableSteps:Ts.includes(i.type)?[]:[i],silentSteps:Ts.includes(i.type)?[i]:[]})}if(e.bulkScene){const n=i?.product?.bulkConfiguration;A.push({name:"Bulk",title:n?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:si.Bulk,stepName:"Bulk",stepTitle:n?.stepTitle??e.bulkSceneTitle,helpText:n?.helpText,data:{aspects:Gs(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&A.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:si.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),A},Js=(t,e)=>e.find((e=>e.stepNames.includes(t))),Ls=(t,e)=>(t.conditions||[]).every((t=>{const i=e[t.targetStepName];if(i&&i.selectedVariants){const e=i.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),zs=(t,e)=>t.map((t=>((t,e)=>{const i={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Ls(t,e))),silentSteps:t.silentSteps.filter((t=>Ls(t,e)))};return 0===i.silentSteps.length&&0===i.renderableSteps.length?null:i})(t,e))).filter((t=>null!==t)),js=async(t,e)=>{const i=zs(t,e),A=[];for(const t of i)for(const e of t.renderableSteps)if(e.type===si.Model||e.type===si.Material||e.type===si.Picture||e.type===si.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&A.push(e.stepName)}else A.push(e.stepName);const n=i.filter((t=>t.renderableSteps.filter((t=>A.includes(t.stepName))).length>0));for(const t of n)t.renderableSteps=t.renderableSteps.filter((t=>A.includes(t.stepName)));return n};function Vs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function Ks(t,e,i,A){const n=i.width*t.zoom,r=i.height*t.zoom;if(A){const A=t,n=Math.max(e.width/i.width,e.height/i.height);A.zoom=Math.max(n,t.zoom);const r=i.width*A.zoom,a=i.height*A.zoom;return A.x=Ws(t.x,e.width-r,0),A.y=Ws(t.y,e.height-a,0),A}const a=t;return a.x=Ws(a.x,-n,e.width),a.y=Ws(a.y,-r,e.height),a}function Ws(t,e,i){return Math.min(Math.max(t,e),i)}class Xs{constructor(t){Vs(this,"offsets",void 0),Vs(this,"forceImageCover",void 0),Vs(this,"targetElements",void 0),Vs(this,"imageData",void 0),Vs(this,"frameData",void 0),Vs(this,"_debouncedUpdateFrameOffsets",void 0),Vs(this,"minZoomScale",[.03]),Vs(this,"maxZoomScale",[20]),Vs(this,"onFrameDataChangeListeners",void 0),Vs(this,"onZoomChangeListeners",void 0),Vs(this,"workflowManager",void 0),Vs(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=F(I)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let i=0;i<e.currentFrameSources.length;i++){const A=e.currentFrameSources[i],n=await kn(A);F(C)(n,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[i]=n,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(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){t?t.forEach(((e,i)=>{const A=Yn.get(e);A&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[i]=A)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,i,A){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const n=this.frameData.map(((A,n)=>{const r=(e[n]-this.offsets[n].x)/this.offsets[n].zoom,a=(i[n]-this.offsets[n].y)/this.offsets[n].zoom;return{x:e[n]-r*t[n],y:i[n]-a*t[n],zoom:this.imageData.width*t[n]/this.imageData.width}}));this.updateOffsets(n,A),this.onZoomChangeListeners.forEach((e=>e(t)))}}setPatternData(t){this.imageData=t,t&&this.frameData&&(this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,i){const A=this.imageData;if(!A||!this.frameData)return;if(this.frameData.length!==t.length)throw new ar("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,i)=>t[i].x!==e.x||t[i].y!==e.y||t[i].zoom!==e.zoom))||i?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Ks(t[i],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,A,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,i,A,n){if(!i||0===i.length||i.some((t=>!t)))throw new ar("Frame data not set. This is a bug");if(!this.workflowManager)throw new ar("No workflow manager set, cannot update offsets.");const r=this.workflowManager.getCommandDispatcher();A.forEach(((i,A)=>{r(new wn(i,e,t[A]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),n&&n()}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(((e,i)=>{const A=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[i]=A,this.maxZoomScale[i]=2.5*A):(this.minZoomScale[i]=A/10,this.maxZoomScale[i]=2.5*A)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Hn(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function qs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Zs{constructor(t,e,i){qs(this,"configuration",void 0),qs(this,"layouts",void 0),qs(this,"product",void 0),qs(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new er(t);let i="";if(this.configuration.type===si.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),i=t,!t)throw new nr(this.configuration,"Couldn't find an asset for product overlay step")}const A=this.evaluateAssetType();if(A===ze.Image){const i=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!i)throw new Error("Undefined raster silent step source");const n={stepName:this.configuration.stepName,id:Te(),src:i,type:A,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===si.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:n.id,region:t},command:new an(n,e)}}{const n=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:i,r=async()=>new Promise(((t,e)=>{n?Wi(n).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),a=await TA(await r()),s={stepName:this.configuration.stepName,id:Te(),cachedObjectURL:await Wn(a.svg),src:n,svg:a.svg,colors:a.colors,type:A,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===si.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new an(s,e)}}})),this.configuration=t,this.layouts=e,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new nr(this.configuration,"Missing regions.");if(this.configuration.type===si.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===si.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new er(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===si.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?ze.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),ze.Illustration)}}const $s=async t=>{const e=`${wr.getServicesApiUrl()}/shortener`;try{const i=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await i.json()).shortUrl}catch(t){throw console.error(t),new cr("Failed to shorten URL, see console.")}};function _s(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class to{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,i,A=3e3,n=10){_s(this,"pollingId",void 0),_s(this,"attempts",void 0),_s(this,"interval",void 0),_s(this,"maxAttempts",void 0),_s(this,"predicate",void 0),_s(this,"onSuccess",void 0),_s(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=i,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=A,this.maxAttempts=n,this.poll()}}const eo=new class{async init(t,e,i){return i&&await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{const i=A?.storage?.videoShortUrl,n=A?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:i,videoUrl:n})}))}async regenerateQRCode(t,e,i,A,n,r,a,s,o){if(e||""===i||""!==A)o(!1);else{const e=async()=>{const t=(await br([i]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},c=await new Promise(((t,i)=>{new to((async()=>!!(await e()).link),(async()=>{const i=await e();if(!i.link||!i.link)throw new Ar(i.asset);t({rel:"mpeg4",href:i.link})}),(()=>{i("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>s(new sn(t.id))));const l="http"===r.data.baseUrl.slice(0,4)?"":"https://",g=new URL(l+r.data.baseUrl);g.searchParams.append("video",btoa(JSON.stringify([c]))),g.pathname=g.pathname+("/"===g.pathname.slice(-1)?"":"/");const h=g.toString();if(h.length>=2e3)throw new cr("Cannot create QR code, URL too long.");const d=await $s(h);if(a(d),!r.data||!r.data.regions)throw new nr(r,"Missing regions.");const u=await this.regionElements(r),w=await this.command(d,u,n,r.stepName);w&&(w.command&&n.getCommandDispatcher()(w.command),w.followup&&await w.followup()),await n.setSelectionsAndElements(r.stepName,[],u,(async()=>{n.updateStorage(r.stepName,{videoShortUrl:d,videoUrl:A}),o(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:Te(),region:t})))}async command(t,e,i,A){const n=i.getLayouts(),r=`data:image/svg+xml;base64,${btoa(await(0,y.toString)(t,{type:"svg"}))}`,a=e.map((t=>{const e=t.region,i=n.find((t=>t.panelId===e?.panelId));if(!i&&e)throw new er(e);if(i&&!e)throw new Error("Region not found");if(!i||!e)throw new Error("Neither a region or layout found!");return new an({stepRegion:e,stepName:A,id:t.id,src:r,type:ze.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},i)}));return{command:new An(a),followup:async()=>{}}}};function io(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const Ao=new class{constructor(){io(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Nn(e);const i=t.asset;if(!i)throw new ir(t);const A=i.fileLink;if(A)return Wi(A);throw new Ar(i)}))}async init(t,e,i){if(i)return await this.reload(t,e,i),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const i=t.option,A=Ur.getDefaultVariant(i);return A?this.selectVariantCommand(t,A,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const i=t.data.regions.map((t=>Nn(t)));e.updateStorage(t.stepName,{currentFrameSources:i})}if(A){const i=async()=>{const i=A.storage?.framePatternSrc,n=A.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:n,framePatternSrc:i}),i){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,A),e.updateMetadata(t.stepName,{image:i}),e.updateStorage(t.stepName,{framePatternSrc:i})}if(n?.some((t=>t.zoom))){const i=e.getStepSpecificServices(t.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");i.updateOffsets(n)}e.setMandatoryFulfilled(t.stepName,!0)};if(A.selectedVariants&&A.selectedVariants.length>0){const r=A.selectedVariants[0].id;if(t.option&&r){const A=t.option.variants?.find((t=>t.id===r));A&&await e.setSelectionsAndElements(t.stepName,[A],n,(async()=>{const n=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(A,t))));e.updateStorage(t.stepName,{currentFrameSources:n}),await i()}))}}else await e.setSelectionsAndElements(t.stepName,[],n,i)}}selectImage(t,e,i){i.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?i.addPoller(new to((async()=>{const t=(await Nr.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Nr.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,i)}))}),(()=>{throw new cr("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,i)}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i,A,n);r&&(r.command&&A.getCommandDispatcher()(r.command),r.followup&&await r.followup())}getCreateElementCommand(t,e,i,A){return new an({id:t,type:ze.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/A.frameData.width,scaleY:e.height/A.frameData.height,path:A.frameData.path,dataWidth:A.frameData.width,dataHeight:A.frameData.height,stepRegion:e,stepName:A.stepName,disablePlaceholder:A.disablePlaceholder,focalBlur:A.focalBlur,focalBlurStrength:A.focalBlurStrength,focalBlurRadius:A.focalBlurRadius,pattern:A.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const i=await Gn(t),A=i.width,n=i.height,r={src:t,width:A,height:n,aspect:A/n};bn.set(t,r),e.setPatternData(r)}else{const i=await Ki(t),A=await Sn(i),n={src:t,width:A.width,height:A.height,aspect:A.width/A.height};bn.set(t,n),e.setPatternData(n)}}async selectVariantCommand(t,e,i,A,n,r){const a=A.getStepSpecificServices(t.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");const s=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));n&&n(!0);const o=await Promise.all(t.data.regions.map((async(e,n)=>{const r=await kn(s[n]),o=a.getImageData(),c=i.map((t=>new sn(t.id))),l=o?Hn(o,r):void 0,g=o?{id:Te(),src:o.src,x:l?.x||0,y:l?.y||0,width:o.width,height:o.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,h=Te(),d=A.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new er(e);return{command:this.getCreateElementCommand(h,e,d,{frameData:r,pattern:g,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:h,region:e},removeExistingCommands:c}}))),c=o.map((t=>t.command)),l=o.map((t=>t.removeExistingCommands)).flat();return{command:new An([...c,...l]),followup:async()=>{n&&n(!1),await A.setSelectionsAndElements(t.stepName,e?[e]:[],[...o.map((t=>t.regionEl))],(async()=>{if(A.updateStorage(t.stepName,{currentFrameSources:s}),r){const e=A.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(r,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const i=t.fileLink;if(i)return i;throw new Ar(t)}async loadPatternFromAsset(t,e,i){const A=this.patternSource(t),n=i.markUpdatePending(),r=i.getStepSpecificServices(e.stepName)?.frameService;if(!r)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,r),i.updateMetadata(e.stepName,{image:A}),i.updateStorage(e.stepName,{framePatternSrc:A}),i.markUpdateCompleted(n)}};const no=new class{async getIllustrationBody(t){return new Promise((e=>{Wi(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,i,A){return new an({stepRegion:e,stepName:A.stepName,colors:A.svg.colors,id:t,src:A.src,svg:A.svg.svg,cachedObjectURL:A.objectURL,type:ze.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},i)}getColors(t,e){const i=e.getRegionElements(t.stepName)||[];if(0===i.length)return[];try{return KA(i[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,i){const A=t.option;if(!A)return null;if(i)return this.reload(t,e,i);{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantCommand(t,i,[],(()=>{}),e)}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(!r||!i)throw new Error("Required illustration variant no longer available");{const a=r.variants?.find((t=>t.id===i));if(a){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[a],i,(async()=>{e.updateMetadata(t.stepName,{colors:A.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const i=t.data.colorOption;return i&&i?i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,i,A,n){const r={};for(const[t,e]of n.entries())r[t]={browserValue:e,spotColor:r[t]?.spotColor};const a=GA(t,e,i,r),s=await Wn(a),o=[];for(const t of A){for(const[e,i]of n.entries())o.push(new pn(t,e,i));o.push(new En(t,a,s))}return new An(o)}async changeColors(t,e,i,A,n){if(0===e.length)return;const r=KA(e[0].id,A().map((t=>t.layoutState))),a={...r.colors},s={};Object.entries(a).forEach((([t,e])=>{const i={browserValue:e.browserValue},A=e.spotColor;A&&(i.spotColor={profileName:A.profileName,namedColor:A.namedColor}),s[t]=i}));for(const[t,e]of n.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor},s[t]={browserValue:e};let o=Array.from(Object.values(a)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{o=o.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:o});const l=new Map;if(Object.entries(a).forEach((([t,e])=>{l.set(t,e.browserValue)})),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const g=await this.changeColorsCommand(r.svg,r.width,r.height,e.map((t=>t.id)),l);i.updateStorage(t.stepName,{colors:s}),i.getCommandDispatcher()(g)}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i,A,n);r&&(r.command&&n.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,i,A,n){if(!t.data||!t.data.regions)throw new nr(t,"Missing regions.");A(!0);const r=i.map((t=>new sn(t.id)));n.setMandatoryFulfilled(t.stepName,!1);const a=e.asset;if(!a)throw new ir(e);const s=a.fileLink;if(!s)throw new Ar(a);const o=await TA(await this.getIllustrationBody(s)),c=await Wn(o.svg),l=t.data.regions.map((e=>{const i=n.getLayouts().find((t=>t.panelId===e.panelId));if(!i)throw new er(e);const A=Te();return{regionElement:{id:A,region:e},command:this.getCreateElementCommand(A,e,i,{stepName:t.stepName,src:s,objectURL:c,svg:o})}})),g=[...l.map((t=>t.command)),...r];let h=Array.from(Object.values(o.colors)).map((t=>t.browserValue));const d=t.data.colorOption;return d&&d.variants?.forEach((t=>{h=h.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),n.updateMetadata(t.stepName,{colors:h}),{command:new An(g),followup:async()=>{await n.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{n.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const ro=new class{async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(i)await this.reload(t,e,i);else{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(!r)throw new tr(t);if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(i){const A=r.variants?.find((t=>t.id===i));if(A){const i=A.material,a=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],a,(async()=>{const A=e.getModelContainer();if(A){const n=t.data.targetMaterials.map((t=>A.applyMaterialVariant(t,r.id||"",i||{})));Promise.all(n).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){const n=i.getModelContainer();A(!0);const r=e.material;if(!r)throw A(!1),new ir(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{n&&t.data.targetMaterials.forEach((e=>{t.option&&n.applyMaterialVariant(e,t.option.id||"",r)})),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const ao=new class{async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(i)await this.reload(t,e,i);else{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{const i=e.getModelContainer();if(i&&t.option){const n=A.asset?.fileLink;if(!n)throw new ir(A);await i.applyModelVariant(t.option.id||"",{model:n,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){A(!0);const n=e.asset?.fileLink;if(!n)throw new ir(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=i.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:n,contextService:i.getLayoutPreviewService()},t.data.replaceProductModel||!1),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const so=new class{async init(t,e,i){return i?(await this.reload(t,e,i),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{e.updateStorage(t.stepName,{text:A?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==A?.storage?.text)}))}async changeText(t,e,i,A,n){const r=await this.changeTextCommand(t,e,i,A,n);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,i,A,n){const r=i.getRegionElements(t.stepName),a=i.getStepSpecificServices(t.stepName)?.module;if(!a)return console.error("Missing module."),null;const s=i.getProfanities();if(!this.validateInput(t,e,s,n))return i.setMandatoryFulfilled(t.stepName,!1),console.error(A),null;if(i.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;i.updateStorage(t.stepName,{text:e});const o=(e,A,n)=>{const r=n||Te(),a=i.getLayouts().find((t=>t.panelId===A.panelId));if(!a)return console.error(`Can not find layout for region: ${A.panelId}`),null;const s=[];return n&&s.push(new sn(r)),s.push(new an({stepRegion:A,stepName:t.stepName,colors:{},id:r,svg:e,type:ze.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},a)),{id:r,region:A,command:new An(s)}};if(r.length>0){const t=r.map((t=>{if(!t.region)return null;const i=a.svgPrint(e,t.region);return o(i,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new An(t),followup:async()=>{}}}{const A=t.data.regions.map((t=>o(a.svgPrint(e,t),t))),n=A.filter((t=>!!t)).map((t=>t&&t.command));return{command:new An(n),followup:async()=>{const e=A.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await i.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,i,A){if(t.data&&t.data.maxLength){const i=t.data.maxLength;if(e.length>i)return A("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return A("Unsupported characters."),!1;const n=(0,x.split)(e.toLowerCase());for(const t of n)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,""))return A("Blocked profanity."),!1}return A(""),!0}};const oo=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else if(A.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,A.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=e.asset;if(!n)throw new ir(e);const r=n?.fileLink;if(!r)return console.error("No URL for picture!"),null;A(!0),i.setMandatoryFulfilled(t.stepName,!1);const a=i.getRegionElements(t.stepName).map((t=>new sn(t.id))),s=t.data.regions.map((e=>{const A=i.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new er(e);const n=Te();return{regionElement:{id:n,region:e},command:new an({stepName:t.stepName,stepRegion:e,id:n,src:r,type:ze.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},A)}}));return{command:new An([...a,...s.map((t=>t.command))]),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],s.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const co=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=A.variants;if(Ur.getDefaultVariant(A)){const n=i?.find((t=>t.id===A.defaultVariant?.id));return this.selectVariantLambda(t,n?.id||"",e)}}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(n&&i){const A=n.variants?.find((t=>t.id===i));A&&await e.setSelectionsAndElements(t.stepName,[A],[])}}}async selectVariant(t,e,i){await i.getInitializationPromise();const A=await this.selectVariantLambda(t,e,i);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i){const A=t.option;if(!A)return null;const n=A.variants;if(!n)return null;const r=n.length>1?n.find((t=>t.id===e)):n[0];if(!r)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[r],[],(async()=>{i.setMandatoryFulfilled(t.stepName,!0)}))}}}};const lo=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(!i){const i=Ur.getDefaultVariant(A);if(!i)return null;const n={fill:i.color,stroke:i.color,variant:i};return this.selectVariantCommand(t,n,[],e)}return await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.updateStorage(t.stepName,{colour:A.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=A.getLayouts();if(i.length>0){const r=t=>{const i=t.region;if(!n.find((t=>t.panelId===i?.panelId)))throw new er(i);const A=e.variant?.color;return A?new pn(t.id,"spiff-fill-shape",A):(console.error("Failed to change color."),null)},a=i.map(r).filter((t=>!!t));return{command:new An(a),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],i),A.updateStorage(t.stepName,{colour:e.fill||""})}}}{const i=i=>{const A=n.find((t=>t.panelId===i.panelId));if(!A)throw new er(i);const r=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${e.variant?.color}"\n />\n </svg>\n `,a={};a["spiff-fill-shape"]={browserValue:e.variant.color};const s=Te();return{id:s,region:i,command:new an({stepRegion:i,stepName:t.stepName,colors:a,id:s,svg:r,type:ze.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,excludeFromExport:t.data.excludeFromPrint},A)}},r=t.data.regions.map(i),a=r.filter((t=>!!t)).map((t=>t?.command)),s=r.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new An(a),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{A.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function go(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class ho extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ho.name}}const uo=["‘","’","“","”","\n"];class wo extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=wo.name}}const Bo=new class{constructor(){go(this,"cachedColors",new Map),go(this,"filterUnsupportedCharacters",((t,e)=>{let i=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const A=[],n=e?cA(e):void 0;if(n){const t=i.split("").filter((t=>!uo.includes(t))).join(""),e=t.split("").map((t=>n.getFont().charToGlyph(t)));for(let i=0;i<e.length;i++){".notdef"===e[i].name&&A.push(String.fromCharCode(t.charCodeAt(i)))}}for(let t=0;t<A.length;t++)i=i.replaceAll(A[t],"");return i})),go(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),go(this,"getErrorsForText",((t,e,i)=>{const A=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&A.push({localizationKey:"workflow.steps.text.characterLimit"});const n=i.getProfanities(),r=(0,x.split)(t.toLowerCase());for(const t of r)for(const e in n){if(t===n[e].toLowerCase().replace(/\s/g,"")){A.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&A.push({localizationKey:"workflow.steps.text.multipleLines"}),A}))}async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=this.getDefaultImageFillVariant(t.data),n=i?.asset?.fileLink,r=n?await Un(n):void 0,a=r?{src:r.src,height:r.height,width:r.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:a}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:i?.name});const s=Ur.getDefaultVariant(A);if(s)return this.selectVariantCommand(t,s,{},[],e,(()=>{}),(()=>{}),a)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>KA(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const i=t.data.colorOption;if(i){const e=i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher();e.variant?A.updateMetadata(t.stepName,{color:e.variant.name}):A.updateMetadata(t.stepName,{color:e.fill});const r=t.data.colorOption,a=r?this.createTextFillSpotColor(r,e.variant):void 0;r?A.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:r.colorProfile?.key}):A.updateStorage(t.stepName,{color:e.fill});for(const t of i){if(!e.fill)throw new Error("Fill not set on new color selection!");n(new cn(t.id,e.fill,a))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const i=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(i.map((async e=>{const i=await Un(e);return{src:e,width:i.width,height:i.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher(),r=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));A.updateMetadata(t.stepName,{fillImage:r?.name}),A.updateStorage(t.stepName,{fillImage:e});for(const t of i){n(new ln(t.id,e))}}getProcessedInput(t,e,i){const A=i?t:this.injectReplaceableText(t,e);return QA(A,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,i,A){const n=A.getStepStorage(i.stepName),r=this.getProcessedInput(t,i.data,!!n.customiseAllText),a={command:void 0,helperText:"",errors:this.getErrorsForText(t,i,A)};if(a.errors.length>0)return a.helperText=a.errors[0].localizationKey,a;const s=(i.data.maxLength-r.length).toString();a.helperText=`${s} characters remaining`;const o=A.getTransaction().bulk&&i.data.varyText||!1,c=[],l=new Map,g=new Map;for(const t of e){if(!t.fontData)throw new ar("Failed to resolve font data for text.");const[e,A]=Ln(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[r],{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});l.set(t.id,e),g.set(t.id,A);const n=i.data.curved?r:(A||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,i.data,t.id,n,o))}if(!i.data.curved&&e.length>0){if(!Array.from(g.values()).every((t=>t)))return a.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),a}return A.updateStorage(i.stepName,{text:t}),A.updateMetadata(i.stepName,{text:r}),n.defaultCleared&&A.setMandatoryFulfilled(i.stepName,!0),a.command=new An(c),a.command.varying=o,a}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i.getStepStorage(t.stepName)||{},i.getRegionElements(t.stepName),i,A,n);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}createTextFillSpotColor(t,e){const i=t.colorProfile;if(i){const t=(i.name||"").replace(/\s/g,"-"),A=t.lastIndexOf("/"),n=t.slice(A+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:n,namedColor:e.namedColor}}}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const a=r.variants?.find((t=>t.id===i));if(a){const i=await this.fontDataFromVariant(a),r=n.map((t=>({id:t.id,region:t.stepRegion}))),s=A.storage?.color,o=A.storage?.text;await e.setSelectionsAndElements(t.stepName,[a],r,(async()=>{e.updateMetadata(t.stepName,{color:s,text:o}),e.updateStorage(t.stepName,{text:o,inputText:o});const A=n.map((t=>new dn(t.id,i))),r=new An(A);e.getCommandDispatcher()(r),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Bo.updateInputText(o||"",n,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Ur.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Ur.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Ur.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ir(t);const i=e.fileLink;if(!i)throw new Ar(e);return{assetUrl:i,name:(await sA(i)).names.fullName.en}}async selectVariantCommand(t,e,i,A,n,r,a,s){const o=n.markUpdatePending(),c=await this.fontDataFromVariant(e);if(A.length>0){const l=A.map((t=>new dn(t.id,c)));if(s){const t=A.map((t=>new ln(t.id,s)));l.push(...t)}const g=await this.changeInputTextWithRegion(t,t.data.size||30,c,i.text||"",i,n,!!i.customiseAllText,r,a);g&&l.push(g);return{command:new An(l),followup:async()=>{n.markUpdateCompleted(o),await n.setSelectionsAndElements(t.stepName,[e],A)}}}{const A=await this.createTextboxRegions(t.stepName,e,t.data,c,i,n),l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A[0]?.newElement.input||i.text||t.data.defaultText||"",i,n,!!i.customiseAllText,r,a),g=A.flatMap((t=>t.commands));if(s){const t=A.map((t=>new ln(t.regionElement.id,s)));g.push(...t)}l&&g.push(l);return{command:new An(g),followup:async()=>{n.markUpdateCompleted(o)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,i,A,n,r){if(!i||!i.regions)throw new Error("Step data not supplied");const a=r.getTransaction().bulk&&i.varyText||!1,s=a?"":n.text||i.defaultText||"",o=this.getProcessedInput(s,i,!1),c=await Promise.all(i.regions.map((async e=>{const c=r.getLayouts().find((t=>t.panelId===e.panelId)),l=Te();try{if(!c)throw new wo("Failed to find layout for region: "+e.panelId);const g=i.colorOption;let h;if(g&&g.variants){const e=g.variants.find((t=>t.id===g.defaultVariant?.id))||g.variants[0];h=this.createTextFillSpotColor(g,e),r.updateStorage(t,{colorProfileAssetKey:g.colorProfile?.key})}const d=await this.getDefaultColor(i),u=d||"#000000",w={stepRegion:e,stepName:t,align:this.textAlign(i),fill:n.color?n.color:u,fontSize:i.size||30,fontData:A,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:o,input:s,type:ze.Textbox,vertical:i.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:i.verticalAlign||"middle",curved:i.curved,paths:i.paths,fillSpotColorDefinition:h},B=[],p=new Map,E=new Map;if(!w.fontData)throw new ar("Failed to resolve font data for text.");const[m,f]=Ln(w.fontSize,w.fontData,{left:w.x,top:w.y,width:w.width,height:w.height,rotation:w.rotation,panelId:""},[o],{size:i.size,minSize:i.minSize,maxSize:i.maxSize});p.set(w.id,m),E.set(w.id,f);const C=i.curved||i.vertical?o:(f||[]).join("\n");B.push(this.generateTextChangeCommandsForRegion(m,i,w.id,C,a));const Q=new an(w,c);return Q.varying=a,{regionElement:{id:l,region:e},commands:[Q,...B],newElement:w,fontData:A}}catch(t){throw console.log(t),new ho("Error adding font to region")}}))).catch((t=>{throw t instanceof ho?(ca.setLatestToast("Failed to load font.",Eo.Error),t):t instanceof wo?t:new Error(t)}));return await r.setSelectionsAndElements(t,[e],c.map((t=>t.regionElement)),(async()=>{r.updateMetadata(t,{text:s}),r.updateStorage(t,{text:s})})),c}generateTextChangeCommandsForRegion(t,e,i,A,n){const r=[],a=new Bn(i,A);if(a.varying=n,r.push(a),!e.size){const e=new gn(i,t);e.varying=n,r.push(e)}const s=new An(r);return s.varying=n,s}async changeInputTextWithRegion(t,e,i,A,n,r,a,s,o,c){const l=(A||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),g=this.getProcessedInput(l,t.data,a),h=r.getRegionElements(t.stepName),d=new Map,u=new Map;for(const A of h)if(A.region){const[n,r]=Ln(e,i,A.region,[g],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(A.id,n),u.set(A.id,r)}const w=(()=>{if(t.data&&t.data.maxLength&&g.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=r.getProfanities(),i=(0,x.split)(g.toLowerCase());for(const t of i)for(const i in e){if(t===e[i].toLowerCase().replace(/\s/g,""))return s(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(g.includes("\n")||g.includes("\r")))return s(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(u.values()).every((t=>t)))return s(!0),{error:"Does not fit."}}return s(!1),{info:(t.data.maxLength-g.length).toString()}})();if(w.error)return void o(w.error);if(o(`${w.info} characters remaining`||""),c)return;r.updateStorage(t.stepName,{text:l}),r.updateMetadata(t.stepName,{text:this.injectReplaceableText(l,t.data)});const B=r.getTransaction().bulk&&t.data.varyText||!1;n.defaultCleared&&r.setMandatoryFulfilled(t.stepName,!0);const p=[];for(const e of h){const i=t.data.curved?g:(u.get(e.id)||[]).join("\n");p.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,i,B))}const E=new An(p);return E.varying=B,E}};function po(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}let Eo;var mo;(mo=Eo||(Eo={})).Error="Error",mo.Warning="Warning",mo.Info="Info";class fo extends Ja{constructor(t){super(),po(this,"update",void 0),po(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Co{constructor(t,e,i,A,n,r,a,s,o,c,l=!1,g,h=!1){po(this,"reloadedState",void 0),po(this,"transaction",void 0),po(this,"ownerCustomer",void 0),po(this,"updateTransaction",void 0),po(this,"confirmedDesign",void 0),po(this,"editedSteps",void 0),po(this,"informationResults",void 0),po(this,"layouts",void 0),po(this,"mandatorySteps",void 0),po(this,"pendingUpdates",void 0),po(this,"selectionCost",void 0),po(this,"workflow",void 0),po(this,"stepSpecificServices",void 0),po(this,"previewService",void 0),po(this,"profanityFilter",void 0),po(this,"pollers",void 0),po(this,"commandContext",void 0),po(this,"stepElements",void 0),po(this,"stepInitialised",void 0),po(this,"stepMetadata",void 0),po(this,"stepSelections",void 0),po(this,"storage",void 0),po(this,"confirmCallbacks",void 0),po(this,"editedCallbacks",void 0),po(this,"elementsCallbacks",void 0),po(this,"informationResultCallbacks",void 0),po(this,"initCallbacks",void 0),po(this,"makingAdjustmentsCallback",void 0),po(this,"mandatoryCallbacks",void 0),po(this,"metadataCallbacks",void 0),po(this,"selectionCallbacks",void 0),po(this,"stepSpecificStorageCallbacks",void 0),po(this,"storageCallbacks",void 0),po(this,"currentVariationRecordCallbacks",void 0),po(this,"variationRecordCallbacks",void 0),po(this,"allScenes",void 0),po(this,"product",void 0),po(this,"invalidModelVariants",void 0),po(this,"currentAdjustingStepId",void 0),po(this,"renderableContextService",void 0),po(this,"workflowStatePromiseQueue",new La(1)),po(this,"variationRecords",[]),po(this,"currentVariationRecord",void 0),po(this,"initializationPromise",void 0),po(this,"initialized",!1),po(this,"readOnly",!1),po(this,"modelContainer",void 0),po(this,"isReloadedTransaction",!1),po(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,i]of e)i.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=n,this.commandContext=A,this.reloadedState=c,this.transaction=r,this.readOnly=l,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=a,this.previewService=s,this.modelContainer=g,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=o,this.currentVariationRecord=null,this.isReloadedTransaction=h,this.initializationPromise=this.initializeDefaultWorkflowState(t,r),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await Os(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const i=zs(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:A,commands:n}=await this.stepElementsForIntroducedSilentSteps(i,!!this.reloadedState);this.commandContext.apply(new An(n),!0),this.stepElements={...this.stepElements,...A},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,i=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),i&&this.modelContainer?.executeAnimation(i)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((e=>{const i=this.stepSelections[e.stepName];i&&i.selectedVariants&&i.selectedVariants.length>0&&(t[e.stepName]={selections:i.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=Te();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise(),this.render3DScene()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}async updateStorage(t,e){const i={...this.storage,[t]:{...this.storage[t],...e}};if(!F(C)(i,this.storage)){this.storage=i;const e=new $A(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const i={stepName:e.stepName};i.storage=this.storage[e.stepName],i.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(i)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new fo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new fo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new ar("Attempted to serialize state before it was initialized.");const i=JSON.stringify(this.dehydrateState(F(e)(t.transaction))),A=t.variation;if(!A)return{transaction:i};const n={layouts:{},serializableWorkflow:{steps:[]},...F(e)(A)||{}};return{transaction:i,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((i,A)=>{const n=[...t[A]||[]];return e.forEach((t=>{const e=n.findIndex((e=>e.id===t.id));e>-1&&n.splice(e,1)})),i[A]=n,i}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Ls(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!Ls(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const i=this.product;if(!i)return Promise.resolve({stepElements:{},commands:[]});const A=async(t,e,i)=>{if(t.type===si.SilentIllustration){return{step:t,results:await new Zs(t,e).trigger()}}if(t.type===si.ProductOverlay){return{step:t,results:await new Zs(t,e,i).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},n=t.filter((t=>!this.stepInitialised[t.stepName])),r={stepElements:{},commands:[]},a=[];for(const t of n)this.markStepsAsInitialised([t.stepName]),e||a.push(A(t,this.layouts,i));const s=await Promise.all(a);for(const t of s)r.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),r.commands=[...r.commands,...t.results.map((t=>t.command))];return r}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new sn(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,i,A){const n=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{Ls(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const r=this.allScenes,a=zs(r,n),s=zs(r,this.stepSelections),o=a.map((t=>t.silentSteps)).flat(),c=s.map((t=>t.silentSteps)).flat().filter((t=>!o.some((e=>e.stepName===t.stepName))));o.forEach((t=>{Ls(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:g,commands:h}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...g,[t]:i},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===si.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(i.map((t=>t.id)))}const d=[...h,...l.map((t=>new sn(t.id))),new $A(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new An(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),A&&await A()}async ensureStepsAreLoaded(){const t=[],e=zs(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const i of e)if(!this.stepInitialised[i.stepName])switch(this.stepInitialised[i.stepName]=!0,i.type){case si.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case si.DigitalContent:t.push(eo.init(i,this,this.reloadedState));break;case si.Frame:case si.Photo:{const e=new Xs(i.data.forceImageCover);e.connectWorkflowManager(this,i.stepName),this.stepSpecificServices[i.stepName]={frameService:e},t.push(Ao.init(i,this,this.reloadedState))}break;case si.Illustration:t.push(no.init(i,this,this.reloadedState));break;case si.Material:t.push(ro.init(i,this,this.reloadedState));break;case si.Model:t.push(ao.init(i,this,this.reloadedState));break;case si.Module:this.stepSpecificServices[i.stepName]={module:await cs(i.data.module)},t.push(so.init(i,this,this.reloadedState));break;case si.Picture:t.push(oo.init(i,this,this.reloadedState));break;case si.Question:t.push(co.init(i,this,this.reloadedState));break;case si.Shape:t.push(lo.init(i,this,this.reloadedState));break;case si.Text:t.push(Bo.init(i,this,this.reloadedState))}const i=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),A=i.filter((t=>!!t&&!!t.command)).map((t=>t.command)),n=i.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));A&&A.length>0&&this.commandContext.apply(new An(A),!0);for(const t of n)await t();n.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((e=>e(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return js(this.allScenes,this.stepSelections)}}function Qo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class yo{constructor(t){Qo(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function Do(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Io{constructor(t,e){Do(this,"manager",void 0),Do(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Io.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Io.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new yo(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new yo(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new yo(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.step.tags||[]}hasTag(t){return this.step.tags?.includes(t)||!1}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),i=this.step.data.modelAnimation,A=this.step.data.lookAtAnimation;t&&A&&t.executeCameraAnimation(A),e&&i&&e.executeAnimation(i)}}function xo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Do(Io,"updateState",new Map);const vo=t.gql`
471
471
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
472
472
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
473
473
  id
@@ -718,7 +718,7 @@ var t=require("@apollo/client"),e=require("lodash.clonedeep"),i=require("react/j
718
718
  }
719
719
  }
720
720
  }
721
- `;function Bc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class pc{constructor(t,e){Bc(this,"bundleId",void 0),Bc(this,"globalPropertyState",void 0),Bc(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,i){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=F(e)(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=i:this.globalPropertyState.aspects.push({name:t,value:i}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await Dr.getShadowGraphqlClient().mutate({mutation:uc,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await Dr.getShadowGraphqlClient().query({query:wc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await Dr.getShadowGraphqlClient().mutate({mutation:dc,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function Ec(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class mc{constructor(t,e,i){Ec(this,"client",void 0),Ec(this,"id",void 0),Ec(this,"name",void 0),Ec(this,"metadata",void 0),Ec(this,"productCollection",void 0),Ec(this,"globalConfiguration",void 0),Ec(this,"globalPropertyStateManager",void 0),Ec(this,"globalPropertyHandleService",void 0),Ec(this,"eventListeners",new Map),Ec(this,"initializationPromise",void 0),Ec(this,"workflowExperiences",[]),Ec(this,"previewService",void 0),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new pc(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new oc(this),this.previewService=i,this.initializationPromise=this.loadExistingBundles(e.transactions?.map((t=>t.id))||[])}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const i=this.eventListeners.get(t)||[],A=i.indexOf(e);A>-1&&i.splice(A,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter((t=>t.getType()===ei.Option)).map((t=>t.getCurrentVariant()?.getPrice()||0)).reduce(((t,e)=>t+e),0)}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");await Dr.getShadowGraphqlClient().mutate({mutation:ic,variables:{id:this.id,transactionId:e}}),this.workflowExperiences.push(t),await this.injectExperienceIntoPreviewService(t);const i=await this.getGlobalProperties();await Promise.all(i.map((e=>e.applyGlobalState([t]))))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found!");{await Dr.getShadowGraphqlClient().mutate({mutation:Ac,variables:{id:this.id,transactionId:e.id}});const[i]=this.workflowExperiences.splice(t,1);this.previewService&&i.getWorkflowManager().ejectFromPreviewService()}}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await Dr.getShadowGraphqlClient().mutate({mutation:ac,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await Dr.getShadowGraphqlClient().mutate({mutation:nc,variables:{id:this.id,details:t,type:e||ra.Owner}})}async updateStakeholders(t){await Dr.getShadowGraphqlClient().mutate({mutation:rc,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await Dr.getShadowGraphqlClient().query({query:$o,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.previewService=t,this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t)}async injectExperienceIntoPreviewService(t){this.previewService&&await t.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingBundles(t){if(0===t.length)return;const e=await Promise.all(t.map((t=>this.client.getWorkflowExperience(void 0,void 0,void 0,{type:"transaction",transactionId:t}))));if(this.workflowExperiences=e,this.previewService)for(const t of e)await this.injectExperienceIntoPreviewService(t)}async updateBundle(){if(!(await Dr.getShadowGraphqlClient().mutate({mutation:ec,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e})))}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async checkConditionalHandlesChanged(t,e){(i=>{const A=this.globalPropertyHandleService.applyConditionsFromState(i,t),n=this.globalPropertyHandleService.applyConditionsFromState(i,e);if(A.length!==n.length)return!0;for(let t=0;t<A.length;t++)if(A[t].getName()!==n[t].getName())return!0;return!1})(await this.globalPropertyHandleService.getHandles())&&this.fireEvent("conditional-global-properties-changed")}fireEvent(t){(this.eventListeners.get(t)||[]).forEach((t=>t()))}}function fc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const Cc=t.gql`
721
+ `;function Bc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class pc{constructor(t,e){Bc(this,"bundleId",void 0),Bc(this,"globalPropertyState",void 0),Bc(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,i){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=F(e)(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=i:this.globalPropertyState.aspects.push({name:t,value:i}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await Dr.getShadowGraphqlClient().mutate({mutation:uc,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await Dr.getShadowGraphqlClient().query({query:wc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await Dr.getShadowGraphqlClient().mutate({mutation:dc,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function Ec(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class mc{constructor(t,e,i){Ec(this,"client",void 0),Ec(this,"id",void 0),Ec(this,"name",void 0),Ec(this,"metadata",void 0),Ec(this,"productCollection",void 0),Ec(this,"globalConfiguration",void 0),Ec(this,"globalPropertyStateManager",void 0),Ec(this,"globalPropertyHandleService",void 0),Ec(this,"eventListeners",new Map),Ec(this,"initializationPromise",void 0),Ec(this,"workflowExperiences",[]),Ec(this,"previewService",void 0),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new pc(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new oc(this),this.setPreviewService(i),this.initializationPromise=this.loadExistingBundles(e.transactions?.map((t=>t.id))||[])}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const i=this.eventListeners.get(t)||[],A=i.indexOf(e);A>-1&&i.splice(A,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter((t=>t.getType()===ei.Option)).map((t=>t.getCurrentVariant()?.getPrice()||0)).reduce(((t,e)=>t+e),0)}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");await Dr.getShadowGraphqlClient().mutate({mutation:ic,variables:{id:this.id,transactionId:e}}),this.workflowExperiences.push(t),await this.injectExperienceIntoPreviewService(t);const i=await this.getGlobalProperties();await Promise.all(i.map((e=>e.applyGlobalState([t]))))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found!");{await Dr.getShadowGraphqlClient().mutate({mutation:Ac,variables:{id:this.id,transactionId:e.id}});const[i]=this.workflowExperiences.splice(t,1);this.previewService&&i.getWorkflowManager().ejectFromPreviewService()}}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await Dr.getShadowGraphqlClient().mutate({mutation:ac,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await Dr.getShadowGraphqlClient().mutate({mutation:nc,variables:{id:this.id,details:t,type:e||ra.Owner}})}async updateStakeholders(t){await Dr.getShadowGraphqlClient().mutate({mutation:rc,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await Dr.getShadowGraphqlClient().query({query:$o,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t);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}onModelLoadEvent(t){"unload"!==t.eventType&&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 i=t.metadata.get("workflowManager").getTransaction(),A=this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===i.id));A&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:A})}}async injectExperienceIntoPreviewService(t){this.previewService&&await t.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingBundles(t){if(0===t.length)return;const e=await Promise.all(t.map((t=>this.client.getWorkflowExperience(void 0,void 0,void 0,{type:"transaction",transactionId:t}))));if(this.workflowExperiences=e,this.previewService)for(const t of e)await this.injectExperienceIntoPreviewService(t)}async updateBundle(){if(!(await Dr.getShadowGraphqlClient().mutate({mutation:ec,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e})))}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async checkConditionalHandlesChanged(t,e){const i=await this.globalPropertyHandleService.getHandles(),A=this.globalPropertyHandleService.applyConditionsFromState(i,t),n=this.globalPropertyHandleService.applyConditionsFromState(i,e);(()=>{if(A.length!==n.length)return!0;for(let t=0;t<A.length;t++)if(A[t].getName()!==n[t].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:n})}fireEvent(t,e){(this.eventListeners.get(t)||[]).forEach((i=>i({bundle:this,event:t,data:e})))}}function fc(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const Cc=t.gql`
722
722
  mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
723
723
  processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
724
724
  id