@spiffcommerce/core 15.1.4 → 15.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -556,7 +556,7 @@ var t=require("@apollo/client"),e=require("lodash.clonedeep"),i=require("react/j
556
556
  workflowState
557
557
  }
558
558
  }
559
- `),Vo=t=>{const e=[];for(const i of t.steps)switch(i.type){case oi.DigitalContent:i.data.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case oi.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 oi.Illustration:const n=i.data;n.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Colors});break;case oi.Material:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case oi.Model:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case oi.Picture:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case oi.Question:i.data.varySelections&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selections});break;case oi.Shape:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case oi.Text:const A=i.data;A.varyText&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Text}),A.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),A.varyColor&&A.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Color})}return e},Ko=[oi.SilentIllustration,oi.ProductOverlay],Wo=async(t,e,i)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:oi.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 oi.DigitalContent:i.data.varyUpload&&(t=!0);break;case oi.Frame:{const e=i.data;!e.varyUpload||!e.varySelection&&i.option||(t=!0)}break;case oi.Illustration:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case oi.Material:i.data.varySelection&&(t=!0);break;case oi.Model:i.data.varySelection&&(t=!0);break;case oi.Picture:i.data.varySelection&&(t=!0);break;case oi.Question:i.data.varySelections&&(t=!0);break;case oi.Shape:i.data.varySelection&&(t=!0);break;case oi.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 A=Xo(i.stepName,t.stepGroups);if(A){const t=n.find((t=>t.name===A.name));t?Ko.includes(i.type)?t.silentSteps.push(i):t.renderableSteps.push(i):n.push({name:A.name,title:A.name,renderableSteps:Ko.includes(i.type)?[]:[i],silentSteps:Ko.includes(i.type)?[i]:[]})}else n.push({name:i.stepName,title:i.stepTitle,renderableSteps:Ko.includes(i.type)?[]:[i],silentSteps:Ko.includes(i.type)?[i]:[]})}if(e.bulkScene){const A=i?.product?.bulkConfiguration;n.push({name:"Bulk",title:A?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:oi.Bulk,stepName:"Bulk",stepTitle:A?.stepTitle??e.bulkSceneTitle,helpText:A?.helpText,data:{aspects:Vo(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:oi.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:[]}),n},Xo=(t,e)=>e.find((e=>e.stepNames.includes(t))),qo=(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})),Zo=(t,e)=>t.map((t=>((t,e)=>{const i={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>qo(t,e))),silentSteps:t.silentSteps.filter((t=>qo(t,e)))};return 0===i.silentSteps.length&&0===i.renderableSteps.length?null:i})(t,e))).filter((t=>null!==t)),$o=async(t,e)=>{const i=Zo(t,e),n=[];for(const t of i)for(const e of t.renderableSteps)if(e.type===oi.Model||e.type===oi.Material||e.type===oi.Picture||e.type===oi.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const A=i.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of A)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return A};function _o(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 ts(t,e,i,n){const A=i.width*t.zoom,a=i.height*t.zoom;if(n){const n=t,A=Math.max(e.width/i.width,e.height/i.height);n.zoom=Math.max(A,t.zoom);const a=i.width*n.zoom,r=i.height*n.zoom;return n.x=es(t.x,e.width-a,0),n.y=es(t.y,e.height-r,0),n}const r=t;return r.x=es(r.x,-A,e.width),r.y=es(r.y,-a,e.height),r}function es(t,e,i){return Math.min(Math.max(t,e),i)}class is{constructor(t){_o(this,"offsets",void 0),_o(this,"forceImageCover",void 0),_o(this,"targetElements",void 0),_o(this,"imageData",void 0),_o(this,"frameData",void 0),_o(this,"_debouncedUpdateFrameOffsets",void 0),_o(this,"minZoomScale",[.03]),_o(this,"maxZoomScale",[20]),_o(this,"onFrameDataChangeListeners",void 0),_o(this,"onZoomChangeListeners",void 0),_o(this,"workflowManager",void 0),_o(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=b(D)(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 n=e.currentFrameSources[i],A=await RA(n);b(C)(A,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[i]=A,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 n=PA.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[i]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,i,n){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const A=this.frameData.map(((n,A)=>{const a=(e[A]-this.offsets[A].x)/this.offsets[A].zoom,r=(i[A]-this.offsets[A].y)/this.offsets[A].zoom;return{x:e[A]-a*t[A],y:i[A]-r*t[A],zoom:this.imageData.width*t[A]/this.imageData.width}}));this.updateOffsets(A,n),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 n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new ra("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]=ts(t[i],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,n,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,n,A){if(!i||0===i.length||i.some((t=>!t)))throw new ra("Frame data not set. This is a bug");if(!this.workflowManager)throw new ra("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach(((i,n)=>{a(new wA(i,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),A&&A()}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 n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[i]=n,this.maxZoomScale[i]=2.5*n):(this.minZoomScale[i]=n/10,this.maxZoomScale[i]=2.5*n)}))}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]=HA(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function ns(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 As{constructor(t,e,i){ns(this,"configuration",void 0),ns(this,"layouts",void 0),ns(this,"product",void 0),ns(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new ea(t);let i="";if(this.configuration.type===oi.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),i=t,!t)throw new Aa(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===ze.Image){const i=this.configuration.type===oi.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!i)throw new Error("Undefined raster silent step source");const A={stepName:this.configuration.stepName,id:Te(),src:i,type:n,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===oi.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:A.id,region:t},command:new rA(A,e)}}{const A=this.configuration.type===oi.SilentIllustration?this.configuration.data.asset?.fileLink:i,a=async()=>new Promise(((t,e)=>{A?Xi(A).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await On(await a()),o={stepName:this.configuration.stepName,id:Te(),cachedObjectURL:await WA(r.svg),src:A,svg:r.svg,colors:r.colors,type:n,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===oi.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:o.id,region:t},command:new rA(o,e)}}})),this.configuration=t,this.layouts=e,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new Aa(this.configuration,"Missing regions.");if(this.configuration.type===oi.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===oi.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new ea(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===oi.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 as=async t=>{const e=`${wa.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 ca("Failed to shorten URL, see console.")}};function rs(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 os{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,n=3e3,A=10){rs(this,"pollingId",void 0),rs(this,"attempts",void 0),rs(this,"interval",void 0),rs(this,"maxAttempts",void 0),rs(this,"predicate",void 0),rs(this,"onSuccess",void 0),rs(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=i,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=A,this.poll()}}const ss=new class{async init(t,e,i){return i&&await this.reload(t,e,i),null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=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,[],A,(async()=>{const i=n?.storage?.videoShortUrl,A=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:i,videoUrl:A})}))}async regenerateQRCode(t,e,i,n,A,a,r,o,s){if(e||""===i||""!==n)s(!1);else{const e=async()=>{const t=(await Pa([i]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},c=await new Promise(((t,i)=>{new os((async()=>!!(await e()).link),(async()=>{const i=await e();if(!i.link||!i.link)throw new na(i.asset);t({rel:"mpeg4",href:i.link})}),(()=>{i("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>o(new oA(t.id))));const l="http"===a.data.baseUrl.slice(0,4)?"":"https://",g=new URL(l+a.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 ca("Cannot create QR code, URL too long.");const d=await as(h);if(r(d),!a.data||!a.data.regions)throw new Aa(a,"Missing regions.");const u=await this.regionElements(a),w=await this.command(d,u,A,a.stepName);w&&(w.command&&A.getCommandDispatcher()(w.command),w.followup&&await w.followup()),await A.setSelectionsAndElements(a.stepName,[],u,(async()=>{A.updateStorage(a.stepName,{videoShortUrl:d,videoUrl:n}),s(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:Te(),region:t})))}async command(t,e,i,n){const A=i.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await(0,y.toString)(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,i=A.find((t=>t.panelId===e?.panelId));if(!i&&e)throw new ea(e);if(i&&!e)throw new Error("Region not found");if(!i||!e)throw new Error("Neither a region or layout found!");return new rA({stepRegion:e,stepName:n,id:t.id,src:a,type:ze.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},i)}));return{command:new nA(r),followup:async()=>{}}}};function cs(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 ls=new class{constructor(){cs(this,"frameSourceSvg",(async(t,e)=>{if(!t)return NA(e);const i=t.asset;if(!i)throw new ia(t);const n=i.fileLink;if(n)return Xi(n);throw new na(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,n=Ja.getDefaultVariant(i);return n?this.selectVariantCommand(t,n,[],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 n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=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=>NA(t)));e.updateStorage(t.stepName,{currentFrameSources:i})}if(n){const i=async()=>{const i=n.storage?.framePatternSrc,A=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:A,framePatternSrc:i}),i){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,n),e.updateMetadata(t.stepName,{image:i}),e.updateStorage(t.stepName,{framePatternSrc:i})}if(A?.some((t=>t.zoom))){const i=e.getStepSpecificServices(t.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");i.updateOffsets(A)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(t.option&&a){const n=t.option.variants?.find((t=>t.id===a));n&&await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:A}),await i()}))}}else await e.setSelectionsAndElements(t.stepName,[],A,i)}}selectImage(t,e,i){i.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?i.addPoller(new os((async()=>{const t=(await ka.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{ka.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,i)}))}),(()=>{throw new ca("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,i)}async selectVariant(t,e,i,n,A){const a=await this.selectVariantCommand(t,e,i,n,A);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,e,i,n){return new rA({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/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const i=await GA(t),n=i.width,A=i.height,a={src:t,width:n,height:A,aspect:n/A};FA.set(t,a),e.setPatternData(a)}else{const i=await Wi(t),n=await SA(i),A={src:t,width:n.width,height:n.height,aspect:n.width/n.height};FA.set(t,A),e.setPatternData(A)}}async selectVariantCommand(t,e,i,n,A,a){const r=n.getStepSpecificServices(t.stepName)?.frameService;if(!r)throw new Error("Frame service unavailable, cannot load pattern!");const o=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));A&&A(!0);const s=await Promise.all(t.data.regions.map((async(e,A)=>{const a=await RA(o[A]),s=r.getImageData(),c=i.map((t=>new oA(t.id))),l=s?HA(s,a):void 0,g=s?{id:Te(),src:s.src,x:l?.x||0,y:l?.y||0,width:s.width,height:s.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,h=Te(),d=n.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new ea(e);return{command:this.getCreateElementCommand(h,e,d,{frameData:a,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=s.map((t=>t.command)),l=s.map((t=>t.removeExistingCommands)).flat();return{command:new nA([...c,...l]),followup:async()=>{A&&A(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...s.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:o}),a){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(a,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 na(t)}async loadPatternFromAsset(t,e,i){const n=this.patternSource(t),A=i.markUpdatePending(),a=i.getStepSpecificServices(e.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,a),i.updateMetadata(e.stepName,{image:n}),i.updateStorage(e.stepName,{framePatternSrc:n}),i.markUpdateCompleted(A)}};const gs=new class{async getIllustrationBody(t){return new Promise((e=>{Xi(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,i,n){return new rA({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.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 Wn(i[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,i){const n=t.option;if(!n)return null;if(i)return this.reload(t,e,i);{const i=Ja.getDefaultVariant(n);if(i)return await this.selectVariantCommand(t,i,[],(()=>{}),e)}return null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(!a||!i)throw new Error("Required illustration variant no longer available");{const r=a.variants?.find((t=>t.id===i));if(r){const i=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[r],i,(async()=>{e.updateMetadata(t.stepName,{colors:n.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,n,A){const a={};for(const[t,e]of A.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor};const r=Tn(t,e,i,a),o=await WA(r),s=[];for(const t of n){for(const[e,i]of A.entries())s.push(new pA(t,e,i));s.push(new mA(t,r,o))}return new nA(s)}async changeColors(t,e,i,n,A){if(0===e.length)return;const a=Wn(e[0].id,n().map((t=>t.layoutState))),r={...a.colors},o={};Object.entries(r).forEach((([t,e])=>{const i={browserValue:e.browserValue},n=e.spotColor;n&&(i.spotColor={profileName:n.profileName,namedColor:n.namedColor}),o[t]=i}));for(const[t,e]of A.entries())r[t]={browserValue:e,spotColor:r[t]?.spotColor},o[t]={browserValue:e};let s=Array.from(Object.values(r)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:s});const l=new Map;if(Object.entries(r).forEach((([t,e])=>{l.set(t,e.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const g=await this.changeColorsCommand(a.svg,a.width,a.height,e.map((t=>t.id)),l);i.updateStorage(t.stepName,{colors:o}),i.getCommandDispatcher()(g)}async selectVariant(t,e,i,n,A){const a=await this.selectVariantCommand(t,e,i,n,A);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,i,n,A){if(!t.data||!t.data.regions)throw new Aa(t,"Missing regions.");n(!0);const a=i.map((t=>new oA(t.id)));A.setMandatoryFulfilled(t.stepName,!1);const r=e.asset;if(!r)throw new ia(e);const o=r.fileLink;if(!o)throw new na(r);const s=await On(await this.getIllustrationBody(o)),c=await WA(s.svg),l=t.data.regions.map((e=>{const i=A.getLayouts().find((t=>t.panelId===e.panelId));if(!i)throw new ea(e);const n=Te();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,i,{stepName:t.stepName,src:o,objectURL:c,svg:s})}})),g=[...l.map((t=>t.command)),...a];let h=Array.from(Object.values(s.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))})),A.updateMetadata(t.stepName,{colors:h}),{command:new nA(g),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const hs=new class{async init(t,e,i){const n=t.option;if(!n)throw new ta(t);if(i)await this.reload(t,e,i);else{const i=Ja.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(!a)throw new ta(t);if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(i){const n=a.variants?.find((t=>t.id===i));if(n){const i=n.material,r=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],r,(async()=>{const n=e.getModelContainer();if(n){const A=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,a.id||"",i||{})));Promise.all(A).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,i,n){const A=await this.selectVariantLambda(t,e,i,n);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i,n){const A=i.getModelContainer();n(!0);const a=e.material;if(!a)throw n(!1),new ia(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{A&&t.data.targetMaterials.forEach((e=>{t.option&&A.applyMaterialVariant(e,t.option.id||"",a)})),i.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const ds=new class{async init(t,e,i){const n=t.option;if(!n)throw new ta(t);if(i)await this.reload(t,e,i);else{const i=Ja.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(a&&i){const n=a.variants?.find((t=>t.id===i));if(n){const i=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],i,(async()=>{const i=e.getModelContainer();if(i&&t.option){const A=n.asset?.fileLink;if(!A)throw new ia(n);await i.applyModelVariant(t.option.id||"",{model:A,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,i,n){const A=await this.selectVariantLambda(t,e,i,n);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i,n){n(!0);const A=e.asset?.fileLink;if(!A)throw new ia(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:A,contextService:i.getLayoutPreviewService()},t.data.replaceProductModel||!1),i.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const us=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 n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=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,[],A,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,i,n,A){const a=await this.changeTextCommand(t,e,i,n,A);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,e,i,n,A){const a=i.getRegionElements(t.stepName),r=i.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const o=i.getProfanities();if(!this.validateInput(t,e,o,A))return i.setMandatoryFulfilled(t.stepName,!1),console.error(n),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 s=(e,n,A)=>{const a=A||Te(),r=i.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const o=[];return A&&o.push(new oA(a)),o.push(new rA({stepRegion:n,stepName:t.stepName,colors:{},id:a,svg:e,type:ze.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},r)),{id:a,region:n,command:new nA(o)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const i=r.svgPrint(e,t.region);return s(i,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new nA(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>s(r.svgPrint(e,t),t))),A=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new nA(A),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await i.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,i,n){if(t.data&&t.data.maxLength){const i=t.data.maxLength;if(e.length>i)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const A=(0,x.split)(e.toLowerCase());for(const t of A)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const ws=new class{async init(t,e,i){const n=t.option;if(!n)return null;if(i)await this.reload(t,e,i);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(a&&i){const n=a.variants?.find((t=>t.id===i));if(n){const i=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],i,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,n){const A=await this.selectVariantCommand(t,e,i,n);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantCommand(t,e,i,n){const A=e.asset;if(!A)throw new ia(e);const a=A?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),i.setMandatoryFulfilled(t.stepName,!1);const r=i.getRegionElements(t.stepName).map((t=>new oA(t.id))),o=t.data.regions.map((e=>{const n=i.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new ea(e);const A=Te();return{regionElement:{id:A,region:e},command:new rA({stepName:t.stepName,stepRegion:e,id:A,src:a,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"},n)}}));return{command:new nA([...r,...o.map((t=>t.command))]),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],o.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const Bs=new class{async init(t,e,i){const n=t.option;if(!n)return null;if(i)await this.reload(t,e,i);else{const i=n.variants;if(Ja.getDefaultVariant(n)){const A=i?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,A?.id||"",e)}}return null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(A&&i){const n=A.variants?.find((t=>t.id===i));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,i){await i.getInitializationPromise();const n=await this.selectVariantLambda(t,e,i);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i){const n=t.option;if(!n)return null;const A=n.variants;if(!A)return null;const a=A.length>1?A.find((t=>t.id===e)):A[0];if(!a)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,[a],[],(async()=>{i.setMandatoryFulfilled(t.stepName,!0)}))}}}};function ps(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 ms=new class{constructor(){ps(this,"shapeFillId","spiff-fill-shape")}async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}setCustomColor(t,e,i){const n=i.getLayouts(),A=(i.getRegionElements(e.stepName)||[]).map((e=>{const i=e.region;if(!n.find((t=>t.panelId===i?.panelId)))throw new ea(i);return new pA(e.id,this.shapeFillId,t)})).filter((t=>!!t));i.getCommandDispatcher()(new nA(A)),i.updateStorage(e.stepName,{colour:t})}async init(t,e,i){const n=t.option;if(!n)throw new ta(t);if(!i){const i=Ja.getDefaultVariant(n);return i?this.selectVariantCommand(t,{fill:i.color,stroke:i.color,variant:i},[],e):null}return await this.reload(t,e,i),null}async selectVariant(t,e,i,n){const A=await this.selectVariantCommand(t,e,i,n);A&&(A.command&&n.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(a&&i){const r=a.variants?.find((t=>t.id===i));if(r){const i=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[r],i,(async()=>{e.updateStorage(t.stepName,{colour:n?.storage?.colour||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariantCommand(t,e,i,n){const A=n.getLayouts(),a=n.getStepStorage(t.stepName)?.colour,r=()=>{if("#custom"===e.variant?.color)return a||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(i.length>0){const a=t=>{const e=t.region;if(!A.find((t=>t.panelId===e?.panelId)))throw new ea(e);const i=r();return new pA(t.id,this.shapeFillId,i)},o=i.map(a).filter((t=>!!t));return{command:new nA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],i),n.updateStorage(t.stepName,{colour:r()})}}}{const i=e=>{const i=A.find((t=>t.panelId===e.panelId));if(!i)throw new ea(e);const n=r(),a=`\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="${this.shapeFillId}"\n fill="${n}"\n />\n </svg>\n `,o={};o[this.shapeFillId]={browserValue:n};const s=Te();return{id:s,region:e,command:new rA({stepRegion:e,stepName:t.stepName,colors:o,id:s,svg:a,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,excludeFromExport:t.data.excludeFromPrint},i)}},a=t.data.regions.map(i),o=a.filter((t=>!!t)).map((t=>t?.command)),s=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new nA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{n.updateStorage(t.stepName,{colour:r()})}))}}}}};function Es(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 fs extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=fs.name}}const Cs=["‘","’","“","”","\n"];class Qs extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Qs.name}}const ys=new class{constructor(){Es(this,"cachedColors",new Map),Es(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 n=[],A=e?ln(e.assetUrl):void 0;if(A){const t=i.split("").filter((t=>!Cs.includes(t))).join(""),e=t.split("").map((t=>A.getFont().charToGlyph(t)));for(let i=0;i<e.length;i++){".notdef"===e[i].name&&n.push(String.fromCharCode(t.charCodeAt(i)))}}for(let t=0;t<n.length;t++)i=i.replaceAll(n[t],"");return i})),Es(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),Es(this,"getErrorsForText",((t,e,i)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const A=i.getProfanities(),a=(0,x.split)(t.toLowerCase());for(const t of a)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,i){const n=t.option;if(!n)return null;if(i)await this.reload(t,e,i);else{const i=this.getDefaultImageFillVariant(t.data),A=i?.asset?.fileLink,a=A?await UA(A):void 0,r=a?{src:a.src,height:a.height,width:a.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:r}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:i?.name});const o=Ja.getDefaultVariant(n);if(o)return this.selectVariantCommand(t,o,{},[],e,(()=>{}),(()=>{}),r)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>Wn(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,n){if(!t.data||!t.data.regions)return;const A=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const a=t.data.colorOption,r=a?this.createTextFillSpotColor(a,e.variant):void 0;a?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of i){if(!e.fill)throw new Error("Fill not set on new color selection!");A(new cA(t.id,e.fill,r))}}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 UA(e);return{src:e,width:i.width,height:i.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,i,n){if(!t.data||!t.data.regions)return;const A=n.getCommandDispatcher(),a=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:a?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of i){A(new lA(t.id,e))}}getProcessedInput(t,e,i){const n=i?t:this.injectReplaceableText(t,e);return yn(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,i,n){const A=n.getStepStorage(i.stepName),a=this.getProcessedInput(t,i.data,!!A.customiseAllText),r={command:void 0,helperText:"",errors:this.getErrorsForText(t,i,n)};if(r.errors.length>0)return r.helperText=r.errors[0].localizationKey,r;const o=(i.data.maxLength-a.length).toString();r.helperText=`${o} characters remaining`;const s=n.getTransaction().bulk&&i.data.varyText||!1,c=[],l=new Map,g=new Map;for(const t of e){if(!t.fontData)throw new ra("Failed to resolve font data for text.");const[e,n]=LA(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});l.set(t.id,e),g.set(t.id,n);const A=i.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,i.data,t.id,A,s))}if(!i.data.curved&&e.length>0){if(!Array.from(g.values()).every((t=>t)))return r.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),r}return n.updateStorage(i.stepName,{text:t}),n.updateMetadata(i.stepName,{text:a}),A.defaultCleared&&n.setMandatoryFulfilled(i.stepName,!0),r.command=new nA(c),r.command.varying=s,r}async selectVariant(t,e,i,n,A){const a=await this.selectVariantCommand(t,e,i.getStepStorage(t.stepName)||{},i.getRegionElements(t.stepName),i,n,A);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,e){const i=t.colorProfile;if(i){const t=(i.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),A=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:A,namedColor:e.namedColor}}}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(a&&i){const r=a.variants?.find((t=>t.id===i));if(r){const i=await this.fontDataFromVariant(r),a=A.map((t=>({id:t.id,region:t.stepRegion}))),o=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[r],a,(async()=>{e.updateMetadata(t.stepName,{color:o,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=A.map((t=>new dA(t.id,i))),a=new nA(n);e.getCommandDispatcher()(a),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=ys.updateInputText(s||"",A,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Ja.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Ja.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Ja.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ia(t);const i=e.fileLink;if(!i)throw new na(e);return{assetUrl:i,name:(await sn(i)).names.fullName.en}}async selectVariantCommand(t,e,i,n,A,a,r,o){const s=A.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const l=n.map((t=>new dA(t.id,c)));if(o){const t=n.map((t=>new lA(t.id,o)));l.push(...t)}const g=await this.changeInputTextWithRegion(t,t.data.size||30,c,i.text||"",i,A,!!i.customiseAllText,a,r);g&&l.push(g);return{command:new nA(l),followup:async()=>{A.markUpdateCompleted(s),await A.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,i,A),l=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||i.text||t.data.defaultText||"",i,A,!!i.customiseAllText,a,r),g=n.flatMap((t=>t.commands));if(o){const t=n.map((t=>new lA(t.regionElement.id,o)));g.push(...t)}l&&g.push(l);return{command:new nA(g),followup:async()=>{A.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,i,n,A,a){if(!i||!i.regions)throw new Error("Step data not supplied");const r=a.getTransaction().bulk&&i.varyText||!1,o=r?"":A.text||i.defaultText||"",s=this.getProcessedInput(o,i,!1),c=await Promise.all(i.regions.map((async e=>{const c=a.getLayouts().find((t=>t.panelId===e.panelId)),l=Te();try{if(!c)throw new Qs("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),a.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:A.color?A.color:u,fontSize:i.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:s,input:o,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,m=new Map;if(!w.fontData)throw new ra("Failed to resolve font data for text.");const[E,f]=LA(w.fontSize,w.fontData,{left:w.x,top:w.y,width:w.width,height:w.height,rotation:w.rotation,panelId:""},[s],{size:i.size,minSize:i.minSize,maxSize:i.maxSize});p.set(w.id,E),m.set(w.id,f);const C=i.curved||i.vertical?s:(f||[]).join("\n");B.push(this.generateTextChangeCommandsForRegion(E,i,w.id,C,r));const Q=new rA(w,c);return Q.varying=r,{regionElement:{id:l,region:e},commands:[Q,...B],newElement:w,fontData:n}}catch(t){throw console.log(t),new fs("Error adding font to region")}}))).catch((t=>{throw t instanceof fs?(wr.setLatestToast("Failed to load font.",Ds.Error),t):t instanceof Qs?t:new Error(t)}));return await a.setSelectionsAndElements(t,[e],c.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:o}),a.updateStorage(t,{text:o})})),c}generateTextChangeCommandsForRegion(t,e,i,n,A){const a=[],r=new BA(i,n);if(r.varying=A,a.push(r),!e.size){const e=new gA(i,t);e.varying=A,a.push(e)}const o=new nA(a);return o.varying=A,o}async changeInputTextWithRegion(t,e,i,n,A,a,r,o,s,c){const l=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),g=this.getProcessedInput(l,t.data,r),h=a.getRegionElements(t.stepName),d=new Map,u=new Map;for(const n of h)if(n.region){const[A,a]=LA(e,i,n.region,[g],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(n.id,A),u.set(n.id,a)}const w=(()=>{if(t.data&&t.data.maxLength&&g.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=a.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 o(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(g.includes("\n")||g.includes("\r")))return o(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(u.values()).every((t=>t)))return o(!0),{error:"Does not fit."}}return o(!1),{info:(t.data.maxLength-g.length).toString()}})();if(w.error)return void s(w.error);if(s(`${w.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:l}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(l,t.data)});const B=a.getTransaction().bulk&&t.data.varyText||!1;A.defaultCleared&&a.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 m=new nA(p);return m.varying=B,m}};function Is(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 Ds;var xs;(xs=Ds||(Ds={})).Error="Error",xs.Warning="Warning",xs.Info="Info";class vs extends Wr{constructor(t){super(),Is(this,"update",void 0),Is(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Ms{constructor(t,e,i,n,A,a,r,o,s,c,l=!1,g,h=!1){Is(this,"reloadedState",void 0),Is(this,"transaction",void 0),Is(this,"ownerCustomer",void 0),Is(this,"updateTransaction",void 0),Is(this,"confirmedDesign",void 0),Is(this,"editedSteps",void 0),Is(this,"informationResults",void 0),Is(this,"layouts",void 0),Is(this,"mandatorySteps",void 0),Is(this,"pendingUpdates",void 0),Is(this,"selectionCost",void 0),Is(this,"workflow",void 0),Is(this,"stepSpecificServices",void 0),Is(this,"previewService",void 0),Is(this,"profanityFilter",void 0),Is(this,"pollers",void 0),Is(this,"commandContext",void 0),Is(this,"stepElements",void 0),Is(this,"stepInitialised",void 0),Is(this,"stepMetadata",void 0),Is(this,"stepSelections",void 0),Is(this,"storage",void 0),Is(this,"confirmCallbacks",void 0),Is(this,"editedCallbacks",void 0),Is(this,"elementsCallbacks",void 0),Is(this,"informationResultCallbacks",void 0),Is(this,"initCallbacks",void 0),Is(this,"makingAdjustmentsCallback",void 0),Is(this,"mandatoryCallbacks",void 0),Is(this,"metadataCallbacks",void 0),Is(this,"selectionCallbacks",void 0),Is(this,"stepSpecificStorageCallbacks",void 0),Is(this,"storageCallbacks",void 0),Is(this,"currentVariationRecordCallbacks",void 0),Is(this,"variationRecordCallbacks",void 0),Is(this,"allScenes",void 0),Is(this,"product",void 0),Is(this,"invalidModelVariants",void 0),Is(this,"currentAdjustingStepId",void 0),Is(this,"renderableContextService",void 0),Is(this,"workflowStatePromiseQueue",new Xr(1)),Is(this,"variationRecords",[]),Is(this,"currentVariationRecord",void 0),Is(this,"initializationPromise",void 0),Is(this,"initialized",!1),Is(this,"readOnly",!1),Is(this,"modelContainer",void 0),Is(this,"isReloadedTransaction",!1),Is(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=A,this.commandContext=n,this.reloadedState=c,this.transaction=a,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=r,this.previewService=o,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=s,this.currentVariationRecord=null,this.isReloadedTransaction=h,this.initializationPromise=this.initializeDefaultWorkflowState(t,a),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 Wo(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const i=Zo(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:A}=await this.stepElementsForIntroducedSilentSteps(i,!!this.reloadedState);this.commandContext.apply(new nA(A),!0),this.stepElements={...this.stepElements,...n},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}updateStorage(t,e){const i={...this.storage,[t]:{...this.storage[t],...e}};if(!b(C)(i,this.storage)){this.storage=i;const e=new _n(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 vs((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new vs((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new ra("Attempted to serialize state before it was initialized.");const i=JSON.stringify(this.dehydrateState(b(e)(t.transaction))),n=t.variation;if(!n)return{transaction:i};const A={layouts:{},serializableWorkflow:{steps:[]},...b(e)(n)||{}};return{transaction:i,variation:JSON.stringify(this.dehydrateState(A))}}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,n)=>{const A=[...t[n]||[]];return e.forEach((t=>{const e=A.findIndex((e=>e.id===t.id));e>-1&&A.splice(e,1)})),i[n]=A,i}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(qo(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&&!qo(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 n=async(t,e,i)=>{if(t.type===oi.SilentIllustration){return{step:t,results:await new As(t,e).trigger()}}if(t.type===oi.ProductOverlay){return{step:t,results:await new As(t,e,i).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},A=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},r=[];for(const t of A)this.markStepsAsInitialised([t.stepName]),e||r.push(n(t,this.layouts,i));const o=await Promise.all(r);for(const t of o)a.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),a.commands=[...a.commands,...t.results.map((t=>t.command))];return a}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 oA(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,i,n){const A=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=>{qo(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const a=this.allScenes,r=Zo(a,A),o=Zo(a,this.stepSelections),s=r.map((t=>t.silentSteps)).flat(),c=o.map((t=>t.silentSteps)).flat().filter((t=>!s.some((e=>e.stepName===t.stepName))));s.forEach((t=>{qo(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===oi.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(i.map((t=>t.id)))}const d=[...h,...l.map((t=>new oA(t.id))),new _n(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new nA(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=Zo(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 oi.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case oi.DigitalContent:t.push(ss.init(i,this,this.reloadedState));break;case oi.Frame:case oi.Photo:{const e=new is(i.data.forceImageCover);e.connectWorkflowManager(this,i.stepName),this.stepSpecificServices[i.stepName]={frameService:e},t.push(ls.init(i,this,this.reloadedState))}break;case oi.Illustration:t.push(gs.init(i,this,this.reloadedState));break;case oi.Material:t.push(hs.init(i,this,this.reloadedState));break;case oi.Model:t.push(ds.init(i,this,this.reloadedState));break;case oi.Module:this.stepSpecificServices[i.stepName]={module:await Bo(i.data.module)},t.push(us.init(i,this,this.reloadedState));break;case oi.Picture:t.push(ws.init(i,this,this.reloadedState));break;case oi.Question:t.push(Bs.init(i,this,this.reloadedState));break;case oi.Shape:t.push(ms.init(i,this,this.reloadedState));break;case oi.Text:t.push(ys.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})),n=i.filter((t=>!!t&&!!t.command)).map((t=>t.command)),A=i.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new nA(n),!0);for(const t of A)await t();A.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 $o(this.allScenes,this.stepSelections)}}function Ss(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 bs{constructor(t){Ss(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.asset?.versions?.find((t=>"cdn"===t.name))?.link}getAssetResource(){return this.variantData.asset}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 Fs(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 Ps{constructor(t,e){Fs(this,"manager",void 0),Fs(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Ps.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Ps.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new bs(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new bs(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new bs(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,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&i&&e.executeAnimation(i)}}function Ys(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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}Fs(Ps,"updateState",new Map);const Ns=t.gql`
559
+ `),Vo=t=>{const e=[];for(const i of t.steps)switch(i.type){case oi.DigitalContent:i.data.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case oi.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 oi.Illustration:const n=i.data;n.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Colors});break;case oi.Material:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case oi.Model:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case oi.Picture:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case oi.Question:i.data.varySelections&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selections});break;case oi.Shape:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case oi.Text:const A=i.data;A.varyText&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Text}),A.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),A.varyColor&&A.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Color})}return e},Ko=[oi.SilentIllustration,oi.ProductOverlay],Wo=async(t,e,i)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:oi.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 oi.DigitalContent:i.data.varyUpload&&(t=!0);break;case oi.Frame:{const e=i.data;!e.varyUpload||!e.varySelection&&i.option||(t=!0)}break;case oi.Illustration:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case oi.Material:i.data.varySelection&&(t=!0);break;case oi.Model:i.data.varySelection&&(t=!0);break;case oi.Picture:i.data.varySelection&&(t=!0);break;case oi.Question:i.data.varySelections&&(t=!0);break;case oi.Shape:i.data.varySelection&&(t=!0);break;case oi.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 A=Xo(i.stepName,t.stepGroups);if(A){const t=n.find((t=>t.name===A.name));t?Ko.includes(i.type)?t.silentSteps.push(i):t.renderableSteps.push(i):n.push({name:A.name,title:A.name,renderableSteps:Ko.includes(i.type)?[]:[i],silentSteps:Ko.includes(i.type)?[i]:[]})}else n.push({name:i.stepName,title:i.stepTitle,renderableSteps:Ko.includes(i.type)?[]:[i],silentSteps:Ko.includes(i.type)?[i]:[]})}if(e.bulkScene){const A=i?.product?.bulkConfiguration;n.push({name:"Bulk",title:A?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:oi.Bulk,stepName:"Bulk",stepTitle:A?.stepTitle??e.bulkSceneTitle,helpText:A?.helpText,data:{aspects:Vo(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:oi.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:[]}),n},Xo=(t,e)=>e.find((e=>e.stepNames.includes(t))),qo=(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})),Zo=(t,e)=>t.map((t=>((t,e)=>{const i={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>qo(t,e))),silentSteps:t.silentSteps.filter((t=>qo(t,e)))};return 0===i.silentSteps.length&&0===i.renderableSteps.length?null:i})(t,e))).filter((t=>null!==t)),$o=async(t,e)=>{const i=Zo(t,e),n=[];for(const t of i)for(const e of t.renderableSteps)if(e.type===oi.Model||e.type===oi.Material||e.type===oi.Picture||e.type===oi.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const A=i.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of A)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return A};function _o(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 ts(t,e,i,n){const A=i.width*t.zoom,a=i.height*t.zoom;if(n){const n=t,A=Math.max(e.width/i.width,e.height/i.height);n.zoom=Math.max(A,t.zoom);const a=i.width*n.zoom,r=i.height*n.zoom;return n.x=es(t.x,e.width-a,0),n.y=es(t.y,e.height-r,0),n}const r=t;return r.x=es(r.x,-A,e.width),r.y=es(r.y,-a,e.height),r}function es(t,e,i){return Math.min(Math.max(t,e),i)}class is{constructor(t){_o(this,"offsets",void 0),_o(this,"forceImageCover",void 0),_o(this,"targetElements",void 0),_o(this,"imageData",void 0),_o(this,"frameData",void 0),_o(this,"_debouncedUpdateFrameOffsets",void 0),_o(this,"minZoomScale",[.03]),_o(this,"maxZoomScale",[20]),_o(this,"onFrameDataChangeListeners",void 0),_o(this,"onZoomChangeListeners",void 0),_o(this,"workflowManager",void 0),_o(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=b(D)(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 n=e.currentFrameSources[i],A=await RA(n);b(C)(A,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[i]=A,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 n=PA.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[i]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,i,n){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const A=this.frameData.map(((n,A)=>{const a=(e[A]-this.offsets[A].x)/this.offsets[A].zoom,r=(i[A]-this.offsets[A].y)/this.offsets[A].zoom;return{x:e[A]-a*t[A],y:i[A]-r*t[A],zoom:this.imageData.width*t[A]/this.imageData.width}}));this.updateOffsets(A,n),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 n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new ra("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]=ts(t[i],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,n,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,n,A){if(!i||0===i.length||i.some((t=>!t)))throw new ra("Frame data not set. This is a bug");if(!this.workflowManager)throw new ra("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach(((i,n)=>{a(new wA(i,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),A&&A()}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 n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[i]=n,this.maxZoomScale[i]=2.5*n):(this.minZoomScale[i]=n/10,this.maxZoomScale[i]=2.5*n)}))}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]=HA(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function ns(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 As{constructor(t,e,i){ns(this,"configuration",void 0),ns(this,"layouts",void 0),ns(this,"product",void 0),ns(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new ea(t);let i="";if(this.configuration.type===oi.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),i=t,!t)throw new Aa(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===ze.Image){const i=this.configuration.type===oi.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!i)throw new Error("Undefined raster silent step source");const A={stepName:this.configuration.stepName,id:Te(),src:i,type:n,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===oi.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:A.id,region:t},command:new rA(A,e)}}{const A=this.configuration.type===oi.SilentIllustration?this.configuration.data.asset?.fileLink:i,a=async()=>new Promise(((t,e)=>{A?Xi(A).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await On(await a()),o={stepName:this.configuration.stepName,id:Te(),cachedObjectURL:await WA(r.svg),src:A,svg:r.svg,colors:r.colors,type:n,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===oi.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:o.id,region:t},command:new rA(o,e)}}})),this.configuration=t,this.layouts=e,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new Aa(this.configuration,"Missing regions.");if(this.configuration.type===oi.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===oi.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new ea(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===oi.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 as=async t=>{const e=`${wa.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 ca("Failed to shorten URL, see console.")}};function rs(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 os{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,n=3e3,A=10){rs(this,"pollingId",void 0),rs(this,"attempts",void 0),rs(this,"interval",void 0),rs(this,"maxAttempts",void 0),rs(this,"predicate",void 0),rs(this,"onSuccess",void 0),rs(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=i,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=A,this.poll()}}const ss=new class{async init(t,e,i){return i&&await this.reload(t,e,i),null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=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,[],A,(async()=>{const i=n?.storage?.videoShortUrl,A=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:i,videoUrl:A})}))}async regenerateQRCode(t,e,i,n,A,a,r,o,s){if(e||""===i||""!==n)s(!1);else{const e=async()=>{const t=(await Pa([i]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},c=await new Promise(((t,i)=>{new os((async()=>!!(await e()).link),(async()=>{const i=await e();if(!i.link||!i.link)throw new na(i.asset);t({rel:"mpeg4",href:i.link})}),(()=>{i("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>o(new oA(t.id))));const l="http"===a.data.baseUrl.slice(0,4)?"":"https://",g=new URL(l+a.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 ca("Cannot create QR code, URL too long.");const d=await as(h);if(r(d),!a.data||!a.data.regions)throw new Aa(a,"Missing regions.");const u=await this.regionElements(a),w=await this.command(d,u,A,a.stepName);w&&(w.command&&A.getCommandDispatcher()(w.command),w.followup&&await w.followup()),await A.setSelectionsAndElements(a.stepName,[],u,(async()=>{A.updateStorage(a.stepName,{videoShortUrl:d,videoUrl:n}),s(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:Te(),region:t})))}async command(t,e,i,n){const A=i.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await(0,y.toString)(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,i=A.find((t=>t.panelId===e?.panelId));if(!i&&e)throw new ea(e);if(i&&!e)throw new Error("Region not found");if(!i||!e)throw new Error("Neither a region or layout found!");return new rA({stepRegion:e,stepName:n,id:t.id,src:a,type:ze.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},i)}));return{command:new nA(r),followup:async()=>{}}}};function cs(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 ls=new class{constructor(){cs(this,"frameSourceSvg",(async(t,e)=>{if(!t)return NA(e);const i=t.asset;if(!i)throw new ia(t);const n=i.fileLink;if(n)return Xi(n);throw new na(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,n=Ja.getDefaultVariant(i);return n?this.selectVariantCommand(t,n,[],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 n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=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=>NA(t)));e.updateStorage(t.stepName,{currentFrameSources:i})}if(n){const i=async()=>{const i=n.storage?.framePatternSrc,A=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:A,framePatternSrc:i}),i){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,n),e.updateMetadata(t.stepName,{image:i}),e.updateStorage(t.stepName,{framePatternSrc:i})}if(A?.some((t=>t.zoom))){const i=e.getStepSpecificServices(t.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");i.updateOffsets(A)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(t.option&&a){const n=t.option.variants?.find((t=>t.id===a));n&&await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:A}),await i()}))}}else await e.setSelectionsAndElements(t.stepName,[],A,i)}}selectImage(t,e,i){i.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?i.addPoller(new os((async()=>{const t=(await ka.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{ka.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,i)}))}),(()=>{throw new ca("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,i)}async selectVariant(t,e,i,n,A){const a=await this.selectVariantCommand(t,e,i,n,A);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,e,i,n){return new rA({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/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const i=await GA(t),n=i.width,A=i.height,a={src:t,width:n,height:A,aspect:n/A};FA.set(t,a),e.setPatternData(a)}else{const i=await Wi(t),n=await SA(i),A={src:t,width:n.width,height:n.height,aspect:n.width/n.height};FA.set(t,A),e.setPatternData(A)}}async selectVariantCommand(t,e,i,n,A,a){const r=n.getStepSpecificServices(t.stepName)?.frameService;if(!r)throw new Error("Frame service unavailable, cannot load pattern!");const o=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));A&&A(!0);const s=await Promise.all(t.data.regions.map((async(e,A)=>{const a=await RA(o[A]),s=r.getImageData(),c=i.map((t=>new oA(t.id))),l=s?HA(s,a):void 0,g=s?{id:Te(),src:s.src,x:l?.x||0,y:l?.y||0,width:s.width,height:s.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,h=Te(),d=n.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new ea(e);return{command:this.getCreateElementCommand(h,e,d,{frameData:a,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=s.map((t=>t.command)),l=s.map((t=>t.removeExistingCommands)).flat();return{command:new nA([...c,...l]),followup:async()=>{A&&A(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...s.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:o}),a){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(a,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 na(t)}async loadPatternFromAsset(t,e,i){const n=this.patternSource(t),A=i.markUpdatePending(),a=i.getStepSpecificServices(e.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,a),i.updateMetadata(e.stepName,{image:n}),i.updateStorage(e.stepName,{framePatternSrc:n}),i.markUpdateCompleted(A)}};const gs=new class{async getIllustrationBody(t){return new Promise((e=>{Xi(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,i,n){return new rA({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.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 Wn(i[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,i){const n=t.option;if(!n)return null;if(i)return this.reload(t,e,i);{const i=Ja.getDefaultVariant(n);if(i)return await this.selectVariantCommand(t,i,[],(()=>{}),e)}return null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(!a||!i)throw new Error("Required illustration variant no longer available");{const r=a.variants?.find((t=>t.id===i));if(r){const i=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[r],i,(async()=>{e.updateMetadata(t.stepName,{colors:n.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,n,A){const a={};for(const[t,e]of A.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor};const r=Tn(t,e,i,a),o=await WA(r),s=[];for(const t of n){for(const[e,i]of A.entries())s.push(new pA(t,e,i));s.push(new mA(t,r,o))}return new nA(s)}async changeColors(t,e,i,n,A){if(0===e.length)return;const a=Wn(e[0].id,n().map((t=>t.layoutState))),r={...a.colors},o={};Object.entries(r).forEach((([t,e])=>{const i={browserValue:e.browserValue},n=e.spotColor;n&&(i.spotColor={profileName:n.profileName,namedColor:n.namedColor}),o[t]=i}));for(const[t,e]of A.entries())r[t]={browserValue:e,spotColor:r[t]?.spotColor},o[t]={browserValue:e};let s=Array.from(Object.values(r)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:s});const l=new Map;if(Object.entries(r).forEach((([t,e])=>{l.set(t,e.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const g=await this.changeColorsCommand(a.svg,a.width,a.height,e.map((t=>t.id)),l);i.updateStorage(t.stepName,{colors:o}),i.getCommandDispatcher()(g)}async selectVariant(t,e,i,n,A){const a=await this.selectVariantCommand(t,e,i,n,A);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,i,n,A){if(!t.data||!t.data.regions)throw new Aa(t,"Missing regions.");n(!0);const a=i.map((t=>new oA(t.id)));A.setMandatoryFulfilled(t.stepName,!1);const r=e.asset;if(!r)throw new ia(e);const o=r.fileLink;if(!o)throw new na(r);const s=await On(await this.getIllustrationBody(o)),c=await WA(s.svg),l=t.data.regions.map((e=>{const i=A.getLayouts().find((t=>t.panelId===e.panelId));if(!i)throw new ea(e);const n=Te();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,i,{stepName:t.stepName,src:o,objectURL:c,svg:s})}})),g=[...l.map((t=>t.command)),...a];let h=Array.from(Object.values(s.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))})),A.updateMetadata(t.stepName,{colors:h}),{command:new nA(g),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const hs=new class{async init(t,e,i){const n=t.option;if(!n)throw new ta(t);if(i)await this.reload(t,e,i);else{const i=Ja.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(!a)throw new ta(t);if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(i){const n=a.variants?.find((t=>t.id===i));if(n){const i=n.material,r=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],r,(async()=>{const n=e.getModelContainer();if(n){const A=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,a.id||"",i||{})));Promise.all(A).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,i,n){const A=await this.selectVariantLambda(t,e,i,n);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i,n){const A=i.getModelContainer();n(!0);const a=e.material;if(!a)throw n(!1),new ia(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{A&&t.data.targetMaterials.forEach((e=>{t.option&&A.applyMaterialVariant(e,t.option.id||"",a)})),i.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const ds=new class{async init(t,e,i){const n=t.option;if(!n)throw new ta(t);if(i)await this.reload(t,e,i);else{const i=Ja.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(a&&i){const n=a.variants?.find((t=>t.id===i));if(n){const i=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],i,(async()=>{const i=e.getModelContainer();if(i&&t.option){const A=n.asset?.fileLink;if(!A)throw new ia(n);await i.applyModelVariant(t.option.id||"",{model:A,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,i,n){const A=await this.selectVariantLambda(t,e,i,n);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i,n){n(!0);const A=e.asset?.fileLink;if(!A)throw new ia(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:A,contextService:i.getLayoutPreviewService()},t.data.replaceProductModel||!1),i.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const us=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 n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=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,[],A,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,i,n,A){const a=await this.changeTextCommand(t,e,i,n,A);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,e,i,n,A){const a=i.getRegionElements(t.stepName),r=i.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const o=i.getProfanities();if(!this.validateInput(t,e,o,A))return i.setMandatoryFulfilled(t.stepName,!1),console.error(n),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 s=(e,n,A)=>{const a=A||Te(),r=i.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const o=[];return A&&o.push(new oA(a)),o.push(new rA({stepRegion:n,stepName:t.stepName,colors:{},id:a,svg:e,type:ze.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},r)),{id:a,region:n,command:new nA(o)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const i=r.svgPrint(e,t.region);return s(i,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new nA(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>s(r.svgPrint(e,t),t))),A=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new nA(A),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await i.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,i,n){if(t.data&&t.data.maxLength){const i=t.data.maxLength;if(e.length>i)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const A=(0,x.split)(e.toLowerCase());for(const t of A)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const ws=new class{async init(t,e,i){const n=t.option;if(!n)return null;if(i)await this.reload(t,e,i);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(a&&i){const n=a.variants?.find((t=>t.id===i));if(n){const i=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],i,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,n){const A=await this.selectVariantCommand(t,e,i,n);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantCommand(t,e,i,n){const A=e.asset;if(!A)throw new ia(e);const a=A?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),i.setMandatoryFulfilled(t.stepName,!1);const r=i.getRegionElements(t.stepName).map((t=>new oA(t.id))),o=t.data.regions.map((e=>{const n=i.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new ea(e);const A=Te();return{regionElement:{id:A,region:e},command:new rA({stepName:t.stepName,stepRegion:e,id:A,src:a,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"},n)}}));return{command:new nA([...r,...o.map((t=>t.command))]),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],o.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const Bs=new class{async init(t,e,i){const n=t.option;if(!n)return null;if(i)await this.reload(t,e,i);else{const i=n.variants;if(Ja.getDefaultVariant(n)){const A=i?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,A?.id||"",e)}}return null}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(A&&i){const n=A.variants?.find((t=>t.id===i));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,i){await i.getInitializationPromise();const n=await this.selectVariantLambda(t,e,i);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i){const n=t.option;if(!n)return null;const A=n.variants;if(!A)return null;const a=A.length>1?A.find((t=>t.id===e)):A[0];if(!a)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,[a],[],(async()=>{i.setMandatoryFulfilled(t.stepName,!0)}))}}}};function ps(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 ms=new class{constructor(){ps(this,"shapeFillId","spiff-fill-shape")}async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}setCustomColor(t,e,i){const n=i.getLayouts(),A=(i.getRegionElements(e.stepName)||[]).map((e=>{const i=e.region;if(!n.find((t=>t.panelId===i?.panelId)))throw new ea(i);return new pA(e.id,this.shapeFillId,t)})).filter((t=>!!t));i.getCommandDispatcher()(new nA(A)),i.updateStorage(e.stepName,{colour:t})}async init(t,e,i){const n=t.option;if(!n)throw new ta(t);if(!i){const i=Ja.getDefaultVariant(n);return i?this.selectVariantCommand(t,{fill:i.color,stroke:i.color,variant:i},[],e):null}return await this.reload(t,e,i),null}async selectVariant(t,e,i,n){const A=await this.selectVariantCommand(t,e,i,n);A&&(A.command&&n.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(a&&i){const r=a.variants?.find((t=>t.id===i));if(r){const i=A.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[r],i,(async()=>{e.updateStorage(t.stepName,{colour:n?.storage?.colour||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariantCommand(t,e,i,n){const A=n.getLayouts(),a=n.getStepStorage(t.stepName)?.colour,r=()=>{if("#custom"===e.variant?.color)return a||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(i.length>0){const a=t=>{const e=t.region;if(!A.find((t=>t.panelId===e?.panelId)))throw new ea(e);const i=r();return new pA(t.id,this.shapeFillId,i)},o=i.map(a).filter((t=>!!t));return{command:new nA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],i),n.updateStorage(t.stepName,{colour:r()})}}}{const i=e=>{const i=A.find((t=>t.panelId===e.panelId));if(!i)throw new ea(e);const n=r(),a=`\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="${this.shapeFillId}"\n fill="${n}"\n />\n </svg>\n `,o={};o[this.shapeFillId]={browserValue:n};const s=Te();return{id:s,region:e,command:new rA({stepRegion:e,stepName:t.stepName,colors:o,id:s,svg:a,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,excludeFromExport:t.data.excludeFromPrint},i)}},a=t.data.regions.map(i),o=a.filter((t=>!!t)).map((t=>t?.command)),s=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new nA(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{n.updateStorage(t.stepName,{colour:r()})}))}}}}};function Es(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 fs extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=fs.name}}const Cs=["‘","’","“","”","\n"];class Qs extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Qs.name}}const ys=new class{constructor(){Es(this,"cachedColors",new Map),Es(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 n=[],A=e?ln(e.assetUrl):void 0;if(A){const t=i.split("").filter((t=>!Cs.includes(t))).join(""),e=t.split("").map((t=>A.getFont().charToGlyph(t)));for(let i=0;i<e.length;i++){".notdef"===e[i].name&&n.push(String.fromCharCode(t.charCodeAt(i)))}}for(let t=0;t<n.length;t++)i=i.replaceAll(n[t],"");return i})),Es(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),Es(this,"getErrorsForText",((t,e,i)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const A=i.getProfanities(),a=(0,x.split)(t.toLowerCase());for(const t of a)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,i){const n=t.option;if(!n)return null;if(i)await this.reload(t,e,i);else{const i=this.getDefaultImageFillVariant(t.data),A=i?.asset?.fileLink,a=A?await UA(A):void 0,r=a?{src:a.src,height:a.height,width:a.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:r}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:i?.name});const o=Ja.getDefaultVariant(n);if(o)return this.selectVariantCommand(t,o,{},[],e,(()=>{}),(()=>{}),r)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>Wn(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,n){if(!t.data||!t.data.regions)return;const A=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const a=t.data.colorOption,r=a?this.createTextFillSpotColor(a,e.variant):void 0;a?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of i){if(!e.fill)throw new Error("Fill not set on new color selection!");A(new cA(t.id,e.fill,r))}}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 UA(e);return{src:e,width:i.width,height:i.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,i,n){if(!t.data||!t.data.regions)return;const A=n.getCommandDispatcher(),a=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:a?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of i){A(new lA(t.id,e))}}getProcessedInput(t,e,i){const n=i?t:this.injectReplaceableText(t,e);return yn(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,i,n){const A=n.getStepStorage(i.stepName),a=this.getProcessedInput(t,i.data,!!A.customiseAllText),r={command:void 0,helperText:"",errors:this.getErrorsForText(t,i,n)};if(r.errors.length>0)return r.helperText=r.errors[0].localizationKey,r;const o=(i.data.maxLength-a.length).toString();r.helperText=`${o} characters remaining`;const s=n.getTransaction().bulk&&i.data.varyText||!1,c=[],l=new Map,g=new Map;for(const t of e){if(!t.fontData)throw new ra("Failed to resolve font data for text.");const[e,n]=LA(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});l.set(t.id,e),g.set(t.id,n);const A=i.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,i.data,t.id,A,s))}if(!i.data.curved&&e.length>0){if(!Array.from(g.values()).every((t=>t)))return r.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),r}return n.updateStorage(i.stepName,{text:t}),n.updateMetadata(i.stepName,{text:a}),A.defaultCleared&&n.setMandatoryFulfilled(i.stepName,!0),r.command=new nA(c),r.command.varying=s,r}async selectVariant(t,e,i,n,A){const a=await this.selectVariantCommand(t,e,i.getStepStorage(t.stepName)||{},i.getRegionElements(t.stepName),i,n,A);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,e){const i=t.colorProfile;if(i){const t=(i.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),A=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:A,namedColor:e.namedColor}}}async reload(t,e,i){const n=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),A=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const i=n.selectedVariants[0].id;if(a&&i){const r=a.variants?.find((t=>t.id===i));if(r){const i=await this.fontDataFromVariant(r),a=A.map((t=>({id:t.id,region:t.stepRegion}))),o=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[r],a,(async()=>{e.updateMetadata(t.stepName,{color:o,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=A.map((t=>new dA(t.id,i))),a=new nA(n);e.getCommandDispatcher()(a),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=ys.updateInputText(s||"",A,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Ja.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Ja.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Ja.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ia(t);const i=e.fileLink;if(!i)throw new na(e);return{assetUrl:i,name:(await sn(i)).names.fullName.en}}async selectVariantCommand(t,e,i,n,A,a,r,o){const s=A.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const l=n.map((t=>new dA(t.id,c)));if(o){const t=n.map((t=>new lA(t.id,o)));l.push(...t)}const g=await this.changeInputTextWithRegion(t,t.data.size||30,c,i.text||"",i,A,!!i.customiseAllText,a,r);g&&l.push(g);return{command:new nA(l),followup:async()=>{A.markUpdateCompleted(s),await A.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,i,A),l=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||i.text||t.data.defaultText||"",i,A,!!i.customiseAllText,a,r),g=n.flatMap((t=>t.commands));if(o){const t=n.map((t=>new lA(t.regionElement.id,o)));g.push(...t)}l&&g.push(l);return{command:new nA(g),followup:async()=>{A.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,i,n,A,a){if(!i||!i.regions)throw new Error("Step data not supplied");const r=a.getTransaction().bulk&&i.varyText||!1,o=r?"":A.text||i.defaultText||"",s=this.getProcessedInput(o,i,!1),c=await Promise.all(i.regions.map((async e=>{const c=a.getLayouts().find((t=>t.panelId===e.panelId)),l=Te();try{if(!c)throw new Qs("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),a.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:A.color?A.color:u,fontSize:i.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:s,input:o,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,m=new Map;if(!w.fontData)throw new ra("Failed to resolve font data for text.");const[E,f]=LA(w.fontSize,w.fontData,{left:w.x,top:w.y,width:w.width,height:w.height,rotation:w.rotation,panelId:""},[s],{size:i.size,minSize:i.minSize,maxSize:i.maxSize});p.set(w.id,E),m.set(w.id,f);const C=i.curved||i.vertical?s:(f||[]).join("\n");B.push(this.generateTextChangeCommandsForRegion(E,i,w.id,C,r));const Q=new rA(w,c);return Q.varying=r,{regionElement:{id:l,region:e},commands:[Q,...B],newElement:w,fontData:n}}catch(t){throw console.log(t),new fs("Error adding font to region")}}))).catch((t=>{throw t instanceof fs?(wr.setLatestToast("Failed to load font.",Ds.Error),t):t instanceof Qs?t:new Error(t)}));return await a.setSelectionsAndElements(t,[e],c.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:o}),a.updateStorage(t,{text:o})})),c}generateTextChangeCommandsForRegion(t,e,i,n,A){const a=[],r=new BA(i,n);if(r.varying=A,a.push(r),!e.size){const e=new gA(i,t);e.varying=A,a.push(e)}const o=new nA(a);return o.varying=A,o}async changeInputTextWithRegion(t,e,i,n,A,a,r,o,s,c){const l=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),g=this.getProcessedInput(l,t.data,r),h=a.getRegionElements(t.stepName),d=new Map,u=new Map;for(const n of h)if(n.region){const[A,a]=LA(e,i,n.region,[g],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(n.id,A),u.set(n.id,a)}const w=(()=>{if(t.data&&t.data.maxLength&&g.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=a.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 o(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(g.includes("\n")||g.includes("\r")))return o(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(u.values()).every((t=>t)))return o(!0),{error:"Does not fit."}}return o(!1),{info:(t.data.maxLength-g.length).toString()}})();if(w.error)return void s(w.error);if(s(`${w.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:l}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(l,t.data)});const B=a.getTransaction().bulk&&t.data.varyText||!1;A.defaultCleared&&a.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 m=new nA(p);return m.varying=B,m}};function Is(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 Ds;var xs;(xs=Ds||(Ds={})).Error="Error",xs.Warning="Warning",xs.Info="Info";class vs extends Wr{constructor(t){super(),Is(this,"update",void 0),Is(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Ms{constructor(t,e,i,n,A,a,r,o,s,c,l=!1,g,h=!1){Is(this,"reloadedState",void 0),Is(this,"transaction",void 0),Is(this,"ownerCustomer",void 0),Is(this,"updateTransaction",void 0),Is(this,"confirmedDesign",void 0),Is(this,"editedSteps",void 0),Is(this,"informationResults",void 0),Is(this,"layouts",void 0),Is(this,"mandatorySteps",void 0),Is(this,"pendingUpdates",void 0),Is(this,"selectionCost",void 0),Is(this,"workflow",void 0),Is(this,"stepSpecificServices",void 0),Is(this,"previewService",void 0),Is(this,"profanityFilter",void 0),Is(this,"pollers",void 0),Is(this,"commandContext",void 0),Is(this,"stepElements",void 0),Is(this,"stepInitialised",void 0),Is(this,"stepMetadata",void 0),Is(this,"stepSelections",void 0),Is(this,"storage",void 0),Is(this,"confirmCallbacks",void 0),Is(this,"editedCallbacks",void 0),Is(this,"elementsCallbacks",void 0),Is(this,"informationResultCallbacks",void 0),Is(this,"initCallbacks",void 0),Is(this,"makingAdjustmentsCallback",void 0),Is(this,"mandatoryCallbacks",void 0),Is(this,"metadataCallbacks",void 0),Is(this,"selectionCallbacks",void 0),Is(this,"stepSpecificStorageCallbacks",void 0),Is(this,"storageCallbacks",void 0),Is(this,"currentVariationRecordCallbacks",void 0),Is(this,"variationRecordCallbacks",void 0),Is(this,"allScenes",void 0),Is(this,"product",void 0),Is(this,"invalidModelVariants",void 0),Is(this,"currentAdjustingStepId",void 0),Is(this,"renderableContextService",void 0),Is(this,"workflowStatePromiseQueue",new Xr(1)),Is(this,"variationRecords",[]),Is(this,"currentVariationRecord",void 0),Is(this,"initializationPromise",void 0),Is(this,"initialized",!1),Is(this,"readOnly",!1),Is(this,"modelContainer",void 0),Is(this,"isReloadedTransaction",!1),Is(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=A,this.commandContext=n,this.reloadedState=c,this.transaction=a,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=r,this.previewService=o,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=s,this.currentVariationRecord=null,this.isReloadedTransaction=h,this.initializationPromise=this.initializeDefaultWorkflowState(t,a),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 Wo(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const i=Zo(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:A}=await this.stepElementsForIntroducedSilentSteps(i,!!this.reloadedState);this.commandContext.apply(new nA(A),!0),this.stepElements={...this.stepElements,...n},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}updateStorage(t,e){const i={...this.storage,[t]:{...this.storage[t],...e}};if(!b(C)(i,this.storage)){this.storage=i;const e=new _n(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 vs((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new vs((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new ra("Attempted to serialize state before it was initialized.");const i=JSON.stringify(this.dehydrateState(b(e)(t.transaction))),n=t.variation;if(!n)return{transaction:i};const A={layouts:{},serializableWorkflow:{steps:[]},...b(e)(n)||{}};return{transaction:i,variation:JSON.stringify(this.dehydrateState(A))}}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,n)=>{const A=[...t[n]||[]];return e.forEach((t=>{const e=A.findIndex((e=>e.id===t.id));e>-1&&A.splice(e,1)})),i[n]=A,i}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(qo(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&&!qo(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 n=async(t,e,i)=>{if(t.type===oi.SilentIllustration){return{step:t,results:await new As(t,e).trigger()}}if(t.type===oi.ProductOverlay){return{step:t,results:await new As(t,e,i).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},A=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},r=[];for(const t of A)this.markStepsAsInitialised([t.stepName]),e||r.push(n(t,this.layouts,i));const o=await Promise.all(r);for(const t of o)a.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),a.commands=[...a.commands,...t.results.map((t=>t.command))];return a}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 oA(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,i,n){const A=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=>{qo(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const a=this.allScenes,r=Zo(a,A),o=Zo(a,this.stepSelections),s=r.map((t=>t.silentSteps)).flat(),c=o.map((t=>t.silentSteps)).flat().filter((t=>!s.some((e=>e.stepName===t.stepName))));s.forEach((t=>{qo(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===oi.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(i.map((t=>t.id)))}const d=[...h,...l.map((t=>new oA(t.id))),new _n(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new nA(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=Zo(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 oi.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case oi.DigitalContent:t.push(ss.init(i,this,this.reloadedState));break;case oi.Frame:case oi.Photo:{const e=new is(i.data.forceImageCover);e.connectWorkflowManager(this,i.stepName),this.stepSpecificServices[i.stepName]={frameService:e},t.push(ls.init(i,this,this.reloadedState))}break;case oi.Illustration:t.push(gs.init(i,this,this.reloadedState));break;case oi.Material:t.push(hs.init(i,this,this.reloadedState));break;case oi.Model:t.push(ds.init(i,this,this.reloadedState));break;case oi.Module:this.stepSpecificServices[i.stepName]={module:await Bo(i.data.module)},t.push(us.init(i,this,this.reloadedState));break;case oi.Picture:t.push(ws.init(i,this,this.reloadedState));break;case oi.Question:t.push(Bs.init(i,this,this.reloadedState));break;case oi.Shape:t.push(ms.init(i,this,this.reloadedState));break;case oi.Text:t.push(ys.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})),n=i.filter((t=>!!t&&!!t.command)).map((t=>t.command)),A=i.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new nA(n),!0);for(const t of A)await t();A.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 $o(this.allScenes,this.stepSelections)}}function Ss(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 bs{constructor(t){Ss(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.asset?.versions?.find((t=>"cdn"===t.name))?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){return this.variantData.thumbnail?.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 Fs(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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 Ps{constructor(t,e){Fs(this,"manager",void 0),Fs(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Ps.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Ps.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new bs(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new bs(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new bs(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,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&i&&e.executeAnimation(i)}}function Ys(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 n=i.call(t,e||"default");if("object"!=typeof n)return n;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}Fs(Ps,"updateState",new Map);const Ns=t.gql`
560
560
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
561
561
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
562
562
  id
package/dist/module.js CHANGED
@@ -556,7 +556,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
556
556
  workflowState
557
557
  }
558
558
  }
559
- `),Vn=t=>{const e=[];for(const A of t.steps)switch(A.type){case m.DigitalContent:A.data.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Frame:const t=A.data;t.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),t.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Illustration:const n=A.data;n.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Colors});break;case m.Material:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Model:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Picture:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Question:A.data.varySelections&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selections});break;case m.Shape:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Text:const a=A.data;a.varyText&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Text}),a.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),a.varyColor&&a.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Color})}return e},Wn=[m.SilentIllustration,m.ProductOverlay],Xn=async(t,e,A)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const A of t.steps){if(e.bulkScene){let t=!1;switch(A.type){case m.DigitalContent:A.data.varyUpload&&(t=!0);break;case m.Frame:{const e=A.data;!e.varyUpload||!e.varySelection&&A.option||(t=!0)}break;case m.Illustration:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case m.Material:A.data.varySelection&&(t=!0);break;case m.Model:A.data.varySelection&&(t=!0);break;case m.Picture:A.data.varySelection&&(t=!0);break;case m.Question:A.data.varySelections&&(t=!0);break;case m.Shape:A.data.varySelection&&(t=!0);break;case m.Text:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const a=qn(A.stepName,t.stepGroups);if(a){const t=n.find((t=>t.name===a.name));t?Wn.includes(A.type)?t.silentSteps.push(A):t.renderableSteps.push(A):n.push({name:a.name,title:a.name,renderableSteps:Wn.includes(A.type)?[]:[A],silentSteps:Wn.includes(A.type)?[A]:[]})}else n.push({name:A.stepName,title:A.stepTitle,renderableSteps:Wn.includes(A.type)?[]:[A],silentSteps:Wn.includes(A.type)?[A]:[]})}if(e.bulkScene){const a=A?.product?.bulkConfiguration;n.push({name:"Bulk",title:a?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:a?.stepTitle??e.bulkSceneTitle,helpText:a?.helpText,data:{aspects:Vn(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:m.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:[]}),n},qn=(t,e)=>e.find((e=>e.stepNames.includes(t))),Zn=(t,e)=>(t.conditions||[]).every((t=>{const A=e[t.targetStepName];if(A&&A.selectedVariants){const e=A.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),$n=(t,e)=>t.map((t=>((t,e)=>{const A={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Zn(t,e))),silentSteps:t.silentSteps.filter((t=>Zn(t,e)))};return 0===A.silentSteps.length&&0===A.renderableSteps.length?null:A})(t,e))).filter((t=>null!==t)),_n=async(t,e)=>{const A=$n(t,e),n=[];for(const t of A)for(const e of t.renderableSteps)if(e.type===m.Model||e.type===m.Material||e.type===m.Picture||e.type===m.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const a=A.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of a)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return a};function ta(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}function ea(t,e,A,n){const a=A.width*t.zoom,i=A.height*t.zoom;if(n){const n=t,a=Math.max(e.width/A.width,e.height/A.height);n.zoom=Math.max(a,t.zoom);const i=A.width*n.zoom,o=A.height*n.zoom;return n.x=Aa(t.x,e.width-i,0),n.y=Aa(t.y,e.height-o,0),n}const o=t;return o.x=Aa(o.x,-a,e.width),o.y=Aa(o.y,-i,e.height),o}function Aa(t,e,A){return Math.min(Math.max(t,e),A)}class na{constructor(t){ta(this,"offsets",void 0),ta(this,"forceImageCover",void 0),ta(this,"targetElements",void 0),ta(this,"imageData",void 0),ta(this,"frameData",void 0),ta(this,"_debouncedUpdateFrameOffsets",void 0),ta(this,"minZoomScale",[.03]),ta(this,"maxZoomScale",[20]),ta(this,"onFrameDataChangeListeners",void 0),ta(this,"onZoomChangeListeners",void 0),ta(this,"workflowManager",void 0),ta(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=Xt(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 A=0;A<e.currentFrameSources.length;A++){const n=e.currentFrameSources[A],a=await P(n);Ot(a,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[A]=a,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,A)=>{const n=M.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,n){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const a=this.frameData.map(((n,a)=>{const i=(e[a]-this.offsets[a].x)/this.offsets[a].zoom,o=(A[a]-this.offsets[a].y)/this.offsets[a].zoom;return{x:e[a]-i*t[a],y:A[a]-o*t[a],zoom:this.imageData.width*t[a]/this.imageData.width}}));this.updateOffsets(a,n),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,A){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new re("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,A)=>t[A].x!==e.x||t[A].y!==e.y||t[A].zoom!==e.zoom))||A?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=ea(t[A],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,n,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,A,n,a){if(!A||0===A.length||A.some((t=>!t)))throw new re("Frame data not set. This is a bug");if(!this.workflowManager)throw new re("No workflow manager set, cannot update offsets.");const i=this.workflowManager.getCommandDispatcher();n.forEach(((A,n)=>{i(new et(A,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),a&&a()}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,A)=>{const n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[A]=n,this.maxZoomScale[A]=2.5*n):(this.minZoomScale[A]=n/10,this.maxZoomScale[A]=2.5*n)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=tt(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function aa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ia{constructor(t,e,A){aa(this,"configuration",void 0),aa(this,"layouts",void 0),aa(this,"product",void 0),aa(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new Ae(t);let A="";if(this.configuration.type===m.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),A=t,!t)throw new ie(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===h.Image){const A=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!A)throw new Error("Undefined raster silent step source");const a={stepName:this.configuration.stepName,id:F(),src:A,type:n,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===m.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:a.id,region:t},command:new o(a,e)}}{const a=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:A,i=async()=>new Promise(((t,e)=>{a?nt(a).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await Y(await i()),s={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await wt(r.svg),src:a,svg:r.svg,colors:r.colors,type:n,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===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new o(s,e)}}})),this.configuration=t,this.layouts=e,this.product=A||void 0}async trigger(){if(!this.configuration.data.regions)throw new ie(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new Ae(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===m.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")?h.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),h.Illustration)}}const oa=async t=>{const e=`${Ee.getServicesApiUrl()}/shortener`;try{const A=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await A.json()).shortUrl}catch(t){throw console.error(t),new ge("Failed to shorten URL, see console.")}};function ra(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class sa{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,A,n=3e3,a=10){ra(this,"pollingId",void 0),ra(this,"attempts",void 0),ra(this,"interval",void 0),ra(this,"maxAttempts",void 0),ra(this,"predicate",void 0),ra(this,"onSuccess",void 0),ra(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=A,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=a,this.poll()}}const ca=new class{async init(t,e,A){return A&&await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.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,[],a,(async()=>{const A=n?.storage?.videoShortUrl,a=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:A,videoUrl:a})}))}async regenerateQRCode(t,e,A,n,a,i,o,r,c){if(e||""===A||""!==n)c(!1);else{const e=async()=>{const t=(await Ne([A]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},g=await new Promise(((t,A)=>{new sa((async()=>!!(await e()).link),(async()=>{const A=await e();if(!A.link||!A.link)throw new ae(A.asset);t({rel:"mpeg4",href:A.link})}),(()=>{A("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new s(t.id))));const l="http"===i.data.baseUrl.slice(0,4)?"":"https://",B=new URL(l+i.data.baseUrl);B.searchParams.append("video",btoa(JSON.stringify([g]))),B.pathname=B.pathname+("/"===B.pathname.slice(-1)?"":"/");const d=B.toString();if(d.length>=2e3)throw new ge("Cannot create QR code, URL too long.");const w=await oa(d);if(o(w),!i.data||!i.data.regions)throw new ie(i,"Missing regions.");const h=await this.regionElements(i),E=await this.command(w,h,a,i.stepName);E&&(E.command&&a.getCommandDispatcher()(E.command),E.followup&&await E.followup()),await a.setSelectionsAndElements(i.stepName,[],h,(async()=>{a.updateStorage(i.stepName,{videoShortUrl:w,videoUrl:n}),c(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,e,A,n){const a=A.getLayouts(),i=`data:image/svg+xml;base64,${btoa(await Vt(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,A=a.find((t=>t.panelId===e?.panelId));if(!A&&e)throw new Ae(e);if(A&&!e)throw new Error("Region not found");if(!A||!e)throw new Error("Neither a region or layout found!");return new o({stepRegion:e,stepName:n,id:t.id,src:i,type:h.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},A)}));return{command:new d(r),followup:async()=>{}}}};function ga(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const la=new class{constructor(){ga(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Et(e);const A=t.asset;if(!A)throw new ne(t);const n=A.fileLink;if(n)return nt(n);throw new ae(A)}))}async init(t,e,A){if(A)return await this.reload(t,e,A),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const A=t.option,n=Oe.getDefaultVariant(A);return n?this.selectVariantCommand(t,n,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.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 A=t.data.regions.map((t=>Et(t)));e.updateStorage(t.stepName,{currentFrameSources:A})}if(n){const A=async()=>{const A=n.storage?.framePatternSrc,a=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:a,framePatternSrc:A}),A){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,n),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A})}if(a?.some((t=>t.zoom))){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");A.updateOffsets(a)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const i=n.selectedVariants[0].id;if(t.option&&i){const n=t.option.variants?.find((t=>t.id===i));n&&await e.setSelectionsAndElements(t.stepName,[n],a,(async()=>{const a=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:a}),await A()}))}}else await e.setSelectionsAndElements(t.stepName,[],a,A)}}selectImage(t,e,A){A.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?A.addPoller(new sa((async()=>{const t=(await be.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{be.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,A)}))}),(()=>{throw new ge("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,A)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}getCreateElementCommand(t,e,A,n){return new o({id:t,type:h.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},A)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const A=await ut(t),n=A.width,a=A.height,i={src:t,width:n,height:a,aspect:n/a};k.set(t,i),e.setPatternData(i)}else{const A=await st(t),n=await v(A),a={src:t,width:n.width,height:n.height,aspect:n.width/n.height};k.set(t,a),e.setPatternData(a)}}async selectVariantCommand(t,e,A,n,a,i){const o=n.getStepSpecificServices(t.stepName)?.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const r=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));a&&a(!0);const c=await Promise.all(t.data.regions.map((async(e,a)=>{const i=await P(r[a]),c=o.getImageData(),g=A.map((t=>new s(t.id))),l=c?tt(c,i):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,d=F(),w=n.getLayouts().find((t=>t.panelId===e.panelId));if(!w)throw new Ae(e);return{command:this.getCreateElementCommand(d,e,w,{frameData:i,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:d,region:e},removeExistingCommands:g}}))),g=c.map((t=>t.command)),l=c.map((t=>t.removeExistingCommands)).flat();return{command:new d([...g,...l]),followup:async()=>{a&&a(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...c.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:r}),i){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const A=t.fileLink;if(A)return A;throw new ae(t)}async loadPatternFromAsset(t,e,A){const n=this.patternSource(t),a=A.markUpdatePending(),i=A.getStepSpecificServices(e.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,i),A.updateMetadata(e.stepName,{image:n}),A.updateStorage(e.stepName,{framePatternSrc:n}),A.markUpdateCompleted(a)}};const Ba=new class{async getIllustrationBody(t){return new Promise((e=>{nt(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,A,n){return new o({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:h.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},A)}getColors(t,e){const A=e.getRegionElements(t.stepName)||[];if(0===A.length)return[];try{return y(A[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,A){const n=t.option;if(!n)return null;if(A)return this.reload(t,e,A);{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantCommand(t,A,[],(()=>{}),e)}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(!i||!A)throw new Error("Required illustration variant no longer available");{const o=i.variants?.find((t=>t.id===A));if(o){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const A=t.data.colorOption;return A&&A?A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,A,n,a){const i={};for(const[t,e]of a.entries())i[t]={browserValue:e,spotColor:i[t]?.spotColor};const o=Ct(t,e,A,i),r=await wt(o),s=[];for(const t of n){for(const[e,A]of a.entries())s.push(new Qt(t,e,A));s.push(new pt(t,o,r))}return new d(s)}async changeColors(t,e,A,n,a){if(0===e.length)return;const i=y(e[0].id,n().map((t=>t.layoutState))),o={...i.colors},r={};Object.entries(o).forEach((([t,e])=>{const A={browserValue:e.browserValue},n=e.spotColor;n&&(A.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=A}));for(const[t,e]of a.entries())o[t]={browserValue:e,spotColor:o[t]?.spotColor},r[t]={browserValue:e};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),A.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,e])=>{g.set(t,e.browserValue)})),!i.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(i.svg,i.width,i.height,e.map((t=>t.id)),g);A.updateStorage(t.stepName,{colors:r}),A.getCommandDispatcher()(l)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n,a){if(!t.data||!t.data.regions)throw new ie(t,"Missing regions.");n(!0);const i=A.map((t=>new s(t.id)));a.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new ne(e);const r=o.fileLink;if(!r)throw new ae(o);const c=await Y(await this.getIllustrationBody(r)),g=await wt(c.svg),l=t.data.regions.map((e=>{const A=a.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=F();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,A,{stepName:t.stepName,src:r,objectURL:g,svg:c})}})),B=[...l.map((t=>t.command)),...i];let w=Array.from(Object.values(c.colors)).map((t=>t.browserValue));const h=t.data.colorOption;return h&&h.variants?.forEach((t=>{w=w.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),a.updateMetadata(t.stepName,{colors:w}),{command:new d(B),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const da=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(!i)throw new ee(t);if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(A){const n=i.variants?.find((t=>t.id===A));if(n){const A=n.material,o=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=e.getModelContainer();if(n){const a=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,i.id||"",A||{})));Promise.all(a).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){const a=A.getModelContainer();n(!0);const i=e.material;if(!i)throw n(!1),new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{a&&t.data.targetMaterials.forEach((e=>{t.option&&a.applyMaterialVariant(e,t.option.id||"",i)})),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const wa=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=e.getModelContainer();if(A&&t.option){const a=n.asset?.fileLink;if(!a)throw new ne(n);await A.applyModelVariant(t.option.id||"",{model:a,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){n(!0);const a=e.asset?.fileLink;if(!a)throw new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=A.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:a,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const ha=new class{async init(t,e,A){return A?(await this.reload(t,e,A),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.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,[],a,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,A,n,a){const i=await this.changeTextCommand(t,e,A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,A,n,a){const i=A.getRegionElements(t.stepName),r=A.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const c=A.getProfanities();if(!this.validateInput(t,e,c,a))return A.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(A.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;A.updateStorage(t.stepName,{text:e});const g=(e,n,a)=>{const i=a||F(),r=A.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return a&&c.push(new s(i)),c.push(new o({stepRegion:n,stepName:t.stepName,colors:{},id:i,svg:e,type:h.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},r)),{id:i,region:n,command:new d(c)}};if(i.length>0){const t=i.map((t=>{if(!t.region)return null;const A=r.svgPrint(e,t.region);return g(A,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new d(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>g(r.svgPrint(e,t),t))),a=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new d(a),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await A.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,A,n){if(t.data&&t.data.maxLength){const A=t.data.maxLength;if(e.length>A)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const a=qt(e.toLowerCase());for(const t of a)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const Ea=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n){const a=e.asset;if(!a)throw new ne(e);const i=a?.fileLink;if(!i)return console.error("No URL for picture!"),null;n(!0),A.setMandatoryFulfilled(t.stepName,!1);const r=A.getRegionElements(t.stepName).map((t=>new s(t.id))),c=t.data.regions.map((e=>{const n=A.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new Ae(e);const a=F();return{regionElement:{id:a,region:e},command:new o({stepName:t.stepName,stepRegion:e,id:a,src:i,type:h.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"},n)}}));return{command:new d([...r,...c.map((t=>t.command))]),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],c.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ua=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=n.variants;if(Oe.getDefaultVariant(n)){const a=A?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,a?.id||"",e)}}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,A){await A.getInitializationPromise();const n=await this.selectVariantLambda(t,e,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,A){const n=t.option;if(!n)return null;const a=n.variants;if(!a)return null;const i=a.length>1?a.find((t=>t.id===e)):a[0];if(!i)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[i],[],(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}};function Ca(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Qa=new class{constructor(){Ca(this,"shapeFillId","spiff-fill-shape")}async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}setCustomColor(t,e,A){const n=A.getLayouts(),a=(A.getRegionElements(e.stepName)||[]).map((e=>{const A=e.region;if(!n.find((t=>t.panelId===A?.panelId)))throw new Ae(A);return new Qt(e.id,this.shapeFillId,t)})).filter((t=>!!t));A.getCommandDispatcher()(new d(a)),A.updateStorage(e.stepName,{colour:t})}async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(!A){const A=Oe.getDefaultVariant(n);return A?this.selectVariantCommand(t,{fill:A.color,stroke:A.color,variant:A},[],e):null}return await this.reload(t,e,A),null}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const o=i.variants?.find((t=>t.id===A));if(o){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateStorage(t.stepName,{colour:n?.storage?.colour||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariantCommand(t,e,A,n){const a=n.getLayouts(),i=n.getStepStorage(t.stepName)?.colour,r=()=>{if("#custom"===e.variant?.color)return i||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(A.length>0){const i=t=>{const e=t.region;if(!a.find((t=>t.panelId===e?.panelId)))throw new Ae(e);const A=r();return new Qt(t.id,this.shapeFillId,A)},o=A.map(i).filter((t=>!!t));return{command:new d(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A),n.updateStorage(t.stepName,{colour:r()})}}}{const A=e=>{const A=a.find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=r(),i=`\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="${this.shapeFillId}"\n fill="${n}"\n />\n </svg>\n `,s={};s[this.shapeFillId]={browserValue:n};const c=F();return{id:c,region:e,command:new o({stepRegion:e,stepName:t.stepName,colors:s,id:c,svg:i,type:h.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,excludeFromExport:t.data.excludeFromPrint},A)}},i=t.data.regions.map(A),s=i.filter((t=>!!t)).map((t=>t?.command)),c=i.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new d(s),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],c,(async()=>{n.updateStorage(t.stepName,{colour:r()})}))}}}}};function pa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ma extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ma.name}}const fa=["‘","’","“","”","\n"];class Da extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Da.name}}const Ia=new class{constructor(){pa(this,"cachedColors",new Map),pa(this,"filterUnsupportedCharacters",((t,e)=>{let A=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],a=e?mt(e.assetUrl):void 0;if(a){const t=A.split("").filter((t=>!fa.includes(t))).join(""),e=t.split("").map((t=>a.getFont().charToGlyph(t)));for(let A=0;A<e.length;A++){".notdef"===e[A].name&&n.push(String.fromCharCode(t.charCodeAt(A)))}}for(let t=0;t<n.length;t++)A=A.replaceAll(n[t],"");return A})),pa(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),pa(this,"getErrorsForText",((t,e,A)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const a=A.getProfanities(),i=qt(t.toLowerCase());for(const t of i)for(const e in a){if(t===a[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=this.getDefaultImageFillVariant(t.data),a=A?.asset?.fileLink,i=a?await Z(a):void 0,o=i?{src:i.src,height:i.height,width:i.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:o}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:A?.name});const r=Oe.getDefaultVariant(n);if(r)return this.selectVariantCommand(t,r,{},[],e,(()=>{}),(()=>{}),o)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>y(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const A=t.data.colorOption;if(A){const e=A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const i=t.data.colorOption,o=i?this.createTextFillSpotColor(i,e.variant):void 0;i?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:i.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of A){if(!e.fill)throw new Error("Fill not set on new color selection!");a(new g(t.id,e.fill,o))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const A=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(A.map((async e=>{const A=await Z(e);return{src:e,width:A.width,height:A.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher(),i=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:i?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of A){a(new ft(t.id,e))}}getProcessedInput(t,e,A){const n=A?t:this.injectReplaceableText(t,e);return lt(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,A,n){const a=n.getStepStorage(A.stepName),i=this.getProcessedInput(t,A.data,!!a.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,A,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(A.data.maxLength-i.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&A.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of e){if(!t.fontData)throw new re("Failed to resolve font data for text.");const[e,n]=b(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[i],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});g.set(t.id,e),l.set(t.id,n);const a=A.data.curved?i:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,A.data,t.id,a,s))}if(!A.data.curved&&e.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(A.stepName,{text:t}),n.updateMetadata(A.stepName,{text:i}),a.defaultCleared&&n.setMandatoryFulfilled(A.stepName,!0),o.command=new d(c),o.command.varying=s,o}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A.getStepStorage(t.stepName)||{},A.getRegionElements(t.stepName),A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}createTextFillSpotColor(t,e){const A=t.colorProfile;if(A){const t=(A.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),a=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:a,namedColor:e.namedColor}}}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const o=i.variants?.find((t=>t.id===A));if(o){const A=await this.fontDataFromVariant(o),i=a.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[o],i,(async()=>{e.updateMetadata(t.stepName,{color:r,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=a.map((t=>new B(t.id,A))),i=new d(n);e.getCommandDispatcher()(i),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Ia.updateInputText(s||"",a,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Oe.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Oe.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Oe.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ne(t);const A=e.fileLink;if(!A)throw new ae(e);return{assetUrl:A,name:(await H(A)).names.fullName.en}}async selectVariantCommand(t,e,A,n,a,i,o,r){const s=a.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const g=n.map((t=>new B(t.id,c)));if(r){const t=n.map((t=>new ft(t.id,r)));g.push(...t)}const l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A.text||"",A,a,!!A.customiseAllText,i,o);l&&g.push(l);return{command:new d(g),followup:async()=>{a.markUpdateCompleted(s),await a.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,A,a),g=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||A.text||t.data.defaultText||"",A,a,!!A.customiseAllText,i,o),l=n.flatMap((t=>t.commands));if(r){const t=n.map((t=>new ft(t.regionElement.id,r)));l.push(...t)}g&&l.push(g);return{command:new d(l),followup:async()=>{a.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,A,n,a,i){if(!A||!A.regions)throw new Error("Step data not supplied");const r=i.getTransaction().bulk&&A.varyText||!1,s=r?"":a.text||A.defaultText||"",c=this.getProcessedInput(s,A,!1),g=await Promise.all(A.regions.map((async e=>{const g=i.getLayouts().find((t=>t.panelId===e.panelId)),l=F();try{if(!g)throw new Da("Failed to find layout for region: "+e.panelId);const B=A.colorOption;let d;if(B&&B.variants){const e=B.variants.find((t=>t.id===B.defaultVariant?.id))||B.variants[0];d=this.createTextFillSpotColor(B,e),i.updateStorage(t,{colorProfileAssetKey:B.colorProfile?.key})}const w=await this.getDefaultColor(A),E=w||"#000000",u={stepRegion:e,stepName:t,align:this.textAlign(A),fill:a.color?a.color:E,fontSize:A.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:c,input:s,type:h.Textbox,vertical:A.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:A.verticalAlign||"middle",curved:A.curved,paths:A.paths,fillSpotColorDefinition:d},C=[],Q=new Map,p=new Map;if(!u.fontData)throw new re("Failed to resolve font data for text.");const[m,f]=b(u.fontSize,u.fontData,{left:u.x,top:u.y,width:u.width,height:u.height,rotation:u.rotation,panelId:""},[c],{size:A.size,minSize:A.minSize,maxSize:A.maxSize});Q.set(u.id,m),p.set(u.id,f);const D=A.curved||A.vertical?c:(f||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(m,A,u.id,D,r));const I=new o(u,g);return I.varying=r,{regionElement:{id:l,region:e},commands:[I,...C],newElement:u,fontData:n}}catch(t){throw console.log(t),new ma("Error adding font to region")}}))).catch((t=>{throw t instanceof ma?(EA.setLatestToast("Failed to load font.",Ma.Error),t):t instanceof Da?t:new Error(t)}));return await i.setSelectionsAndElements(t,[e],g.map((t=>t.regionElement)),(async()=>{i.updateMetadata(t,{text:s}),i.updateStorage(t,{text:s})})),g}generateTextChangeCommandsForRegion(t,e,A,n,a){const i=[],o=new f(A,n);if(o.varying=a,i.push(o),!e.size){const e=new l(A,t);e.varying=a,i.push(e)}const r=new d(i);return r.varying=a,r}async changeInputTextWithRegion(t,e,A,n,a,i,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=i.getRegionElements(t.stepName),w=new Map,h=new Map;for(const n of B)if(n.region){const[a,i]=b(e,A,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});w.set(n.id,a),h.set(n.id,i)}const E=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=i.getProfanities(),A=qt(l.toLowerCase());for(const t of A)for(const A in e){if(t===e[A].toLowerCase().replace(/\s/g,""))return r(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(E.error)return void s(E.error);if(s(`${E.info} characters remaining`||""),c)return;i.updateStorage(t.stepName,{text:g}),i.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const u=i.getTransaction().bulk&&t.data.varyText||!1;a.defaultCleared&&i.setMandatoryFulfilled(t.stepName,!0);const C=[];for(const e of B){const A=t.data.curved?l:(h.get(e.id)||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(w.get(e.id)||1,t.data,e.id,A,u))}const Q=new d(C);return Q.varying=u,Q}};function ya(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Ma;var Fa;(Fa=Ma||(Ma={})).Error="Error",Fa.Warning="Warning",Fa.Info="Info";class Sa extends XA{constructor(t){super(),ya(this,"update",void 0),ya(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Ya{constructor(t,e,A,n,a,i,o,r,s,c,g=!1,l,B=!1){ya(this,"reloadedState",void 0),ya(this,"transaction",void 0),ya(this,"ownerCustomer",void 0),ya(this,"updateTransaction",void 0),ya(this,"confirmedDesign",void 0),ya(this,"editedSteps",void 0),ya(this,"informationResults",void 0),ya(this,"layouts",void 0),ya(this,"mandatorySteps",void 0),ya(this,"pendingUpdates",void 0),ya(this,"selectionCost",void 0),ya(this,"workflow",void 0),ya(this,"stepSpecificServices",void 0),ya(this,"previewService",void 0),ya(this,"profanityFilter",void 0),ya(this,"pollers",void 0),ya(this,"commandContext",void 0),ya(this,"stepElements",void 0),ya(this,"stepInitialised",void 0),ya(this,"stepMetadata",void 0),ya(this,"stepSelections",void 0),ya(this,"storage",void 0),ya(this,"confirmCallbacks",void 0),ya(this,"editedCallbacks",void 0),ya(this,"elementsCallbacks",void 0),ya(this,"informationResultCallbacks",void 0),ya(this,"initCallbacks",void 0),ya(this,"makingAdjustmentsCallback",void 0),ya(this,"mandatoryCallbacks",void 0),ya(this,"metadataCallbacks",void 0),ya(this,"selectionCallbacks",void 0),ya(this,"stepSpecificStorageCallbacks",void 0),ya(this,"storageCallbacks",void 0),ya(this,"currentVariationRecordCallbacks",void 0),ya(this,"variationRecordCallbacks",void 0),ya(this,"allScenes",void 0),ya(this,"product",void 0),ya(this,"invalidModelVariants",void 0),ya(this,"currentAdjustingStepId",void 0),ya(this,"renderableContextService",void 0),ya(this,"workflowStatePromiseQueue",new qA(1)),ya(this,"variationRecords",[]),ya(this,"currentVariationRecord",void 0),ya(this,"initializationPromise",void 0),ya(this,"initialized",!1),ya(this,"readOnly",!1),ya(this,"modelContainer",void 0),ya(this,"isReloadedTransaction",!1),ya(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,A]of e)A.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=a,this.commandContext=n,this.reloadedState=c,this.transaction=i,this.readOnly=g,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=A,this.product=o,this.previewService=r,this.modelContainer=l,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=s,this.currentVariationRecord=null,this.isReloadedTransaction=B,this.initializationPromise=this.initializeDefaultWorkflowState(t,i),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 Xn(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const A=$n(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:a}=await this.stepElementsForIntroducedSilentSteps(A,!!this.reloadedState);this.commandContext.apply(new d(a),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,A=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),A&&this.modelContainer?.executeAnimation(A)})()}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 A=this.stepSelections[e.stepName];A&&A.selectedVariants&&A.selectedVariants.length>0&&(t[e.stepName]={selections:A.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=F();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}updateStorage(t,e){const A={...this.storage,[t]:{...this.storage[t],...e}};if(!Ot(A,this.storage)){this.storage=A;const e=new ht(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 A={stepName:e.stepName};A.storage=this.storage[e.stepName],A.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(A)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Sa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new Sa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new re("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(zt(t.transaction))),A=t.variation;if(!A)return{transaction:e};const n={layouts:{},serializableWorkflow:{steps:[]},...zt(A)||{}};return{transaction:e,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(((A,n)=>{const a=[...t[n]||[]];return e.forEach((t=>{const e=a.findIndex((e=>e.id===t.id));e>-1&&a.splice(e,1)})),A[n]=a,A}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Zn(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&&!Zn(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,e,A)=>{if(t.type===m.SilentIllustration){return{step:t,results:await new ia(t,e).trigger()}}if(t.type===m.ProductOverlay){return{step:t,results:await new ia(t,e,A).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},a=t.filter((t=>!this.stepInitialised[t.stepName])),i={stepElements:{},commands:[]},o=[];for(const t of a)this.markStepsAsInitialised([t.stepName]),e||o.push(n(t,this.layouts,A));const r=await Promise.all(o);for(const t of r)i.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),i.commands=[...i.commands,...t.results.map((t=>t.command))];return i}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 s(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,n){const a=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=>{Zn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const i=this.allScenes,o=$n(i,a),r=$n(i,this.stepSelections),c=o.map((t=>t.silentSteps)).flat(),g=r.map((t=>t.silentSteps)).flat().filter((t=>!c.some((e=>e.stepName===t.stepName))));c.forEach((t=>{Zn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:B,commands:w}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===m.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(A.map((t=>t.id)))}const h=[...w,...l.map((t=>new s(t.id))),new ht(this.constructSerializableWorkflow())];h.length>0&&this.commandContext.apply(new d(h),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=$n(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const A of e)if(!this.stepInitialised[A.stepName])switch(this.stepInitialised[A.stepName]=!0,A.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case m.DigitalContent:t.push(ca.init(A,this,this.reloadedState));break;case m.Frame:case m.Photo:{const e=new na(A.data.forceImageCover);e.connectWorkflowManager(this,A.stepName),this.stepSpecificServices[A.stepName]={frameService:e},t.push(la.init(A,this,this.reloadedState))}break;case m.Illustration:t.push(Ba.init(A,this,this.reloadedState));break;case m.Material:t.push(da.init(A,this,this.reloadedState));break;case m.Model:t.push(wa.init(A,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[A.stepName]={module:await un(A.data.module)},t.push(ha.init(A,this,this.reloadedState));break;case m.Picture:t.push(Ea.init(A,this,this.reloadedState));break;case m.Question:t.push(ua.init(A,this,this.reloadedState));break;case m.Shape:t.push(Qa.init(A,this,this.reloadedState));break;case m.Text:t.push(Ia.init(A,this,this.reloadedState))}const A=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=A.filter((t=>!!t&&!!t.command)).map((t=>t.command)),a=A.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new d(n),!0);for(const t of a)await t();a.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 _n(this.allScenes,this.stepSelections)}}function va(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class xa{constructor(t){va(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.asset?.versions?.find((t=>"cdn"===t.name))?.link}getAssetResource(){return this.variantData.asset}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 Pa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Na{constructor(t,e){Pa(this,"manager",void 0),Pa(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Na.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Na.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new xa(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new xa(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new xa(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(),A=this.step.data.modelAnimation,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&A&&e.executeAnimation(A)}}function Ra(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}Pa(Na,"updateState",new Map);const Ha=It`
559
+ `),Vn=t=>{const e=[];for(const A of t.steps)switch(A.type){case m.DigitalContent:A.data.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Frame:const t=A.data;t.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),t.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Illustration:const n=A.data;n.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Colors});break;case m.Material:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Model:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Picture:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Question:A.data.varySelections&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selections});break;case m.Shape:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Text:const a=A.data;a.varyText&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Text}),a.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),a.varyColor&&a.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Color})}return e},Wn=[m.SilentIllustration,m.ProductOverlay],Xn=async(t,e,A)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const A of t.steps){if(e.bulkScene){let t=!1;switch(A.type){case m.DigitalContent:A.data.varyUpload&&(t=!0);break;case m.Frame:{const e=A.data;!e.varyUpload||!e.varySelection&&A.option||(t=!0)}break;case m.Illustration:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case m.Material:A.data.varySelection&&(t=!0);break;case m.Model:A.data.varySelection&&(t=!0);break;case m.Picture:A.data.varySelection&&(t=!0);break;case m.Question:A.data.varySelections&&(t=!0);break;case m.Shape:A.data.varySelection&&(t=!0);break;case m.Text:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const a=qn(A.stepName,t.stepGroups);if(a){const t=n.find((t=>t.name===a.name));t?Wn.includes(A.type)?t.silentSteps.push(A):t.renderableSteps.push(A):n.push({name:a.name,title:a.name,renderableSteps:Wn.includes(A.type)?[]:[A],silentSteps:Wn.includes(A.type)?[A]:[]})}else n.push({name:A.stepName,title:A.stepTitle,renderableSteps:Wn.includes(A.type)?[]:[A],silentSteps:Wn.includes(A.type)?[A]:[]})}if(e.bulkScene){const a=A?.product?.bulkConfiguration;n.push({name:"Bulk",title:a?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:a?.stepTitle??e.bulkSceneTitle,helpText:a?.helpText,data:{aspects:Vn(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:m.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:[]}),n},qn=(t,e)=>e.find((e=>e.stepNames.includes(t))),Zn=(t,e)=>(t.conditions||[]).every((t=>{const A=e[t.targetStepName];if(A&&A.selectedVariants){const e=A.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),$n=(t,e)=>t.map((t=>((t,e)=>{const A={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Zn(t,e))),silentSteps:t.silentSteps.filter((t=>Zn(t,e)))};return 0===A.silentSteps.length&&0===A.renderableSteps.length?null:A})(t,e))).filter((t=>null!==t)),_n=async(t,e)=>{const A=$n(t,e),n=[];for(const t of A)for(const e of t.renderableSteps)if(e.type===m.Model||e.type===m.Material||e.type===m.Picture||e.type===m.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const a=A.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of a)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return a};function ta(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}function ea(t,e,A,n){const a=A.width*t.zoom,i=A.height*t.zoom;if(n){const n=t,a=Math.max(e.width/A.width,e.height/A.height);n.zoom=Math.max(a,t.zoom);const i=A.width*n.zoom,o=A.height*n.zoom;return n.x=Aa(t.x,e.width-i,0),n.y=Aa(t.y,e.height-o,0),n}const o=t;return o.x=Aa(o.x,-a,e.width),o.y=Aa(o.y,-i,e.height),o}function Aa(t,e,A){return Math.min(Math.max(t,e),A)}class na{constructor(t){ta(this,"offsets",void 0),ta(this,"forceImageCover",void 0),ta(this,"targetElements",void 0),ta(this,"imageData",void 0),ta(this,"frameData",void 0),ta(this,"_debouncedUpdateFrameOffsets",void 0),ta(this,"minZoomScale",[.03]),ta(this,"maxZoomScale",[20]),ta(this,"onFrameDataChangeListeners",void 0),ta(this,"onZoomChangeListeners",void 0),ta(this,"workflowManager",void 0),ta(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=Xt(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 A=0;A<e.currentFrameSources.length;A++){const n=e.currentFrameSources[A],a=await P(n);Ot(a,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[A]=a,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,A)=>{const n=M.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,n){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const a=this.frameData.map(((n,a)=>{const i=(e[a]-this.offsets[a].x)/this.offsets[a].zoom,o=(A[a]-this.offsets[a].y)/this.offsets[a].zoom;return{x:e[a]-i*t[a],y:A[a]-o*t[a],zoom:this.imageData.width*t[a]/this.imageData.width}}));this.updateOffsets(a,n),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,A){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new re("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,A)=>t[A].x!==e.x||t[A].y!==e.y||t[A].zoom!==e.zoom))||A?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=ea(t[A],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,n,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,A,n,a){if(!A||0===A.length||A.some((t=>!t)))throw new re("Frame data not set. This is a bug");if(!this.workflowManager)throw new re("No workflow manager set, cannot update offsets.");const i=this.workflowManager.getCommandDispatcher();n.forEach(((A,n)=>{i(new et(A,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),a&&a()}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,A)=>{const n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[A]=n,this.maxZoomScale[A]=2.5*n):(this.minZoomScale[A]=n/10,this.maxZoomScale[A]=2.5*n)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=tt(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function aa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ia{constructor(t,e,A){aa(this,"configuration",void 0),aa(this,"layouts",void 0),aa(this,"product",void 0),aa(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new Ae(t);let A="";if(this.configuration.type===m.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),A=t,!t)throw new ie(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===h.Image){const A=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!A)throw new Error("Undefined raster silent step source");const a={stepName:this.configuration.stepName,id:F(),src:A,type:n,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===m.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:a.id,region:t},command:new o(a,e)}}{const a=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:A,i=async()=>new Promise(((t,e)=>{a?nt(a).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await Y(await i()),s={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await wt(r.svg),src:a,svg:r.svg,colors:r.colors,type:n,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===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new o(s,e)}}})),this.configuration=t,this.layouts=e,this.product=A||void 0}async trigger(){if(!this.configuration.data.regions)throw new ie(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new Ae(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===m.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")?h.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),h.Illustration)}}const oa=async t=>{const e=`${Ee.getServicesApiUrl()}/shortener`;try{const A=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await A.json()).shortUrl}catch(t){throw console.error(t),new ge("Failed to shorten URL, see console.")}};function ra(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class sa{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,A,n=3e3,a=10){ra(this,"pollingId",void 0),ra(this,"attempts",void 0),ra(this,"interval",void 0),ra(this,"maxAttempts",void 0),ra(this,"predicate",void 0),ra(this,"onSuccess",void 0),ra(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=A,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=a,this.poll()}}const ca=new class{async init(t,e,A){return A&&await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.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,[],a,(async()=>{const A=n?.storage?.videoShortUrl,a=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:A,videoUrl:a})}))}async regenerateQRCode(t,e,A,n,a,i,o,r,c){if(e||""===A||""!==n)c(!1);else{const e=async()=>{const t=(await Ne([A]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},g=await new Promise(((t,A)=>{new sa((async()=>!!(await e()).link),(async()=>{const A=await e();if(!A.link||!A.link)throw new ae(A.asset);t({rel:"mpeg4",href:A.link})}),(()=>{A("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new s(t.id))));const l="http"===i.data.baseUrl.slice(0,4)?"":"https://",B=new URL(l+i.data.baseUrl);B.searchParams.append("video",btoa(JSON.stringify([g]))),B.pathname=B.pathname+("/"===B.pathname.slice(-1)?"":"/");const d=B.toString();if(d.length>=2e3)throw new ge("Cannot create QR code, URL too long.");const w=await oa(d);if(o(w),!i.data||!i.data.regions)throw new ie(i,"Missing regions.");const h=await this.regionElements(i),E=await this.command(w,h,a,i.stepName);E&&(E.command&&a.getCommandDispatcher()(E.command),E.followup&&await E.followup()),await a.setSelectionsAndElements(i.stepName,[],h,(async()=>{a.updateStorage(i.stepName,{videoShortUrl:w,videoUrl:n}),c(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,e,A,n){const a=A.getLayouts(),i=`data:image/svg+xml;base64,${btoa(await Vt(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,A=a.find((t=>t.panelId===e?.panelId));if(!A&&e)throw new Ae(e);if(A&&!e)throw new Error("Region not found");if(!A||!e)throw new Error("Neither a region or layout found!");return new o({stepRegion:e,stepName:n,id:t.id,src:i,type:h.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},A)}));return{command:new d(r),followup:async()=>{}}}};function ga(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const la=new class{constructor(){ga(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Et(e);const A=t.asset;if(!A)throw new ne(t);const n=A.fileLink;if(n)return nt(n);throw new ae(A)}))}async init(t,e,A){if(A)return await this.reload(t,e,A),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const A=t.option,n=Oe.getDefaultVariant(A);return n?this.selectVariantCommand(t,n,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.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 A=t.data.regions.map((t=>Et(t)));e.updateStorage(t.stepName,{currentFrameSources:A})}if(n){const A=async()=>{const A=n.storage?.framePatternSrc,a=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:a,framePatternSrc:A}),A){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,n),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A})}if(a?.some((t=>t.zoom))){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");A.updateOffsets(a)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const i=n.selectedVariants[0].id;if(t.option&&i){const n=t.option.variants?.find((t=>t.id===i));n&&await e.setSelectionsAndElements(t.stepName,[n],a,(async()=>{const a=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:a}),await A()}))}}else await e.setSelectionsAndElements(t.stepName,[],a,A)}}selectImage(t,e,A){A.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?A.addPoller(new sa((async()=>{const t=(await be.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{be.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,A)}))}),(()=>{throw new ge("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,A)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}getCreateElementCommand(t,e,A,n){return new o({id:t,type:h.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},A)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const A=await ut(t),n=A.width,a=A.height,i={src:t,width:n,height:a,aspect:n/a};k.set(t,i),e.setPatternData(i)}else{const A=await st(t),n=await v(A),a={src:t,width:n.width,height:n.height,aspect:n.width/n.height};k.set(t,a),e.setPatternData(a)}}async selectVariantCommand(t,e,A,n,a,i){const o=n.getStepSpecificServices(t.stepName)?.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const r=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));a&&a(!0);const c=await Promise.all(t.data.regions.map((async(e,a)=>{const i=await P(r[a]),c=o.getImageData(),g=A.map((t=>new s(t.id))),l=c?tt(c,i):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,d=F(),w=n.getLayouts().find((t=>t.panelId===e.panelId));if(!w)throw new Ae(e);return{command:this.getCreateElementCommand(d,e,w,{frameData:i,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:d,region:e},removeExistingCommands:g}}))),g=c.map((t=>t.command)),l=c.map((t=>t.removeExistingCommands)).flat();return{command:new d([...g,...l]),followup:async()=>{a&&a(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...c.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:r}),i){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const A=t.fileLink;if(A)return A;throw new ae(t)}async loadPatternFromAsset(t,e,A){const n=this.patternSource(t),a=A.markUpdatePending(),i=A.getStepSpecificServices(e.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,i),A.updateMetadata(e.stepName,{image:n}),A.updateStorage(e.stepName,{framePatternSrc:n}),A.markUpdateCompleted(a)}};const Ba=new class{async getIllustrationBody(t){return new Promise((e=>{nt(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,A,n){return new o({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:h.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},A)}getColors(t,e){const A=e.getRegionElements(t.stepName)||[];if(0===A.length)return[];try{return y(A[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,A){const n=t.option;if(!n)return null;if(A)return this.reload(t,e,A);{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantCommand(t,A,[],(()=>{}),e)}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(!i||!A)throw new Error("Required illustration variant no longer available");{const o=i.variants?.find((t=>t.id===A));if(o){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const A=t.data.colorOption;return A&&A?A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,A,n,a){const i={};for(const[t,e]of a.entries())i[t]={browserValue:e,spotColor:i[t]?.spotColor};const o=Ct(t,e,A,i),r=await wt(o),s=[];for(const t of n){for(const[e,A]of a.entries())s.push(new Qt(t,e,A));s.push(new pt(t,o,r))}return new d(s)}async changeColors(t,e,A,n,a){if(0===e.length)return;const i=y(e[0].id,n().map((t=>t.layoutState))),o={...i.colors},r={};Object.entries(o).forEach((([t,e])=>{const A={browserValue:e.browserValue},n=e.spotColor;n&&(A.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=A}));for(const[t,e]of a.entries())o[t]={browserValue:e,spotColor:o[t]?.spotColor},r[t]={browserValue:e};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),A.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,e])=>{g.set(t,e.browserValue)})),!i.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(i.svg,i.width,i.height,e.map((t=>t.id)),g);A.updateStorage(t.stepName,{colors:r}),A.getCommandDispatcher()(l)}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A,n,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n,a){if(!t.data||!t.data.regions)throw new ie(t,"Missing regions.");n(!0);const i=A.map((t=>new s(t.id)));a.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new ne(e);const r=o.fileLink;if(!r)throw new ae(o);const c=await Y(await this.getIllustrationBody(r)),g=await wt(c.svg),l=t.data.regions.map((e=>{const A=a.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=F();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,A,{stepName:t.stepName,src:r,objectURL:g,svg:c})}})),B=[...l.map((t=>t.command)),...i];let w=Array.from(Object.values(c.colors)).map((t=>t.browserValue));const h=t.data.colorOption;return h&&h.variants?.forEach((t=>{w=w.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),a.updateMetadata(t.stepName,{colors:w}),{command:new d(B),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const da=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(!i)throw new ee(t);if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(A){const n=i.variants?.find((t=>t.id===A));if(n){const A=n.material,o=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=e.getModelContainer();if(n){const a=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,i.id||"",A||{})));Promise.all(a).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){const a=A.getModelContainer();n(!0);const i=e.material;if(!i)throw n(!1),new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{a&&t.data.targetMaterials.forEach((e=>{t.option&&a.applyMaterialVariant(e,t.option.id||"",i)})),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const wa=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=Oe.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=e.getModelContainer();if(A&&t.option){const a=n.asset?.fileLink;if(!a)throw new ne(n);await A.applyModelVariant(t.option.id||"",{model:a,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantLambda(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantLambda(t,e,A,n){n(!0);const a=e.asset?.fileLink;if(!a)throw new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=A.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:a,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const ha=new class{async init(t,e,A){return A?(await this.reload(t,e,A),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.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,[],a,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,A,n,a){const i=await this.changeTextCommand(t,e,A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,A,n,a){const i=A.getRegionElements(t.stepName),r=A.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const c=A.getProfanities();if(!this.validateInput(t,e,c,a))return A.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(A.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;A.updateStorage(t.stepName,{text:e});const g=(e,n,a)=>{const i=a||F(),r=A.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return a&&c.push(new s(i)),c.push(new o({stepRegion:n,stepName:t.stepName,colors:{},id:i,svg:e,type:h.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},r)),{id:i,region:n,command:new d(c)}};if(i.length>0){const t=i.map((t=>{if(!t.region)return null;const A=r.svgPrint(e,t.region);return g(A,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new d(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>g(r.svgPrint(e,t),t))),a=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new d(a),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await A.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,A,n){if(t.data&&t.data.maxLength){const A=t.data.maxLength;if(e.length>A)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const a=qt(e.toLowerCase());for(const t of a)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const Ea=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));if(n){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n){const a=e.asset;if(!a)throw new ne(e);const i=a?.fileLink;if(!i)return console.error("No URL for picture!"),null;n(!0),A.setMandatoryFulfilled(t.stepName,!1);const r=A.getRegionElements(t.stepName).map((t=>new s(t.id))),c=t.data.regions.map((e=>{const n=A.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new Ae(e);const a=F();return{regionElement:{id:a,region:e},command:new o({stepName:t.stepName,stepRegion:e,id:a,src:i,type:h.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"},n)}}));return{command:new d([...r,...c.map((t=>t.command))]),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],c.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ua=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=n.variants;if(Oe.getDefaultVariant(n)){const a=A?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,a?.id||"",e)}}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,A){await A.getInitializationPromise();const n=await this.selectVariantLambda(t,e,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,A){const n=t.option;if(!n)return null;const a=n.variants;if(!a)return null;const i=a.length>1?a.find((t=>t.id===e)):a[0];if(!i)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[i],[],(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}};function Ca(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Qa=new class{constructor(){Ca(this,"shapeFillId","spiff-fill-shape")}async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}setCustomColor(t,e,A){const n=A.getLayouts(),a=(A.getRegionElements(e.stepName)||[]).map((e=>{const A=e.region;if(!n.find((t=>t.panelId===A?.panelId)))throw new Ae(A);return new Qt(e.id,this.shapeFillId,t)})).filter((t=>!!t));A.getCommandDispatcher()(new d(a)),A.updateStorage(e.stepName,{colour:t})}async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(!A){const A=Oe.getDefaultVariant(n);return A?this.selectVariantCommand(t,{fill:A.color,stroke:A.color,variant:A},[],e):null}return await this.reload(t,e,A),null}async selectVariant(t,e,A,n){const a=await this.selectVariantCommand(t,e,A,n);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const o=i.variants?.find((t=>t.id===A));if(o){const A=a.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateStorage(t.stepName,{colour:n?.storage?.colour||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariantCommand(t,e,A,n){const a=n.getLayouts(),i=n.getStepStorage(t.stepName)?.colour,r=()=>{if("#custom"===e.variant?.color)return i||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(A.length>0){const i=t=>{const e=t.region;if(!a.find((t=>t.panelId===e?.panelId)))throw new Ae(e);const A=r();return new Qt(t.id,this.shapeFillId,A)},o=A.map(i).filter((t=>!!t));return{command:new d(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A),n.updateStorage(t.stepName,{colour:r()})}}}{const A=e=>{const A=a.find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=r(),i=`\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="${this.shapeFillId}"\n fill="${n}"\n />\n </svg>\n `,s={};s[this.shapeFillId]={browserValue:n};const c=F();return{id:c,region:e,command:new o({stepRegion:e,stepName:t.stepName,colors:s,id:c,svg:i,type:h.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,excludeFromExport:t.data.excludeFromPrint},A)}},i=t.data.regions.map(A),s=i.filter((t=>!!t)).map((t=>t?.command)),c=i.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new d(s),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],c,(async()=>{n.updateStorage(t.stepName,{colour:r()})}))}}}}};function pa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ma extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ma.name}}const fa=["‘","’","“","”","\n"];class Da extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Da.name}}const Ia=new class{constructor(){pa(this,"cachedColors",new Map),pa(this,"filterUnsupportedCharacters",((t,e)=>{let A=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],a=e?mt(e.assetUrl):void 0;if(a){const t=A.split("").filter((t=>!fa.includes(t))).join(""),e=t.split("").map((t=>a.getFont().charToGlyph(t)));for(let A=0;A<e.length;A++){".notdef"===e[A].name&&n.push(String.fromCharCode(t.charCodeAt(A)))}}for(let t=0;t<n.length;t++)A=A.replaceAll(n[t],"");return A})),pa(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),pa(this,"getErrorsForText",((t,e,A)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const a=A.getProfanities(),i=qt(t.toLowerCase());for(const t of i)for(const e in a){if(t===a[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=this.getDefaultImageFillVariant(t.data),a=A?.asset?.fileLink,i=a?await Z(a):void 0,o=i?{src:i.src,height:i.height,width:i.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:o}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:A?.name});const r=Oe.getDefaultVariant(n);if(r)return this.selectVariantCommand(t,r,{},[],e,(()=>{}),(()=>{}),o)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>y(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const A=t.data.colorOption;if(A){const e=A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const i=t.data.colorOption,o=i?this.createTextFillSpotColor(i,e.variant):void 0;i?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:i.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of A){if(!e.fill)throw new Error("Fill not set on new color selection!");a(new g(t.id,e.fill,o))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const A=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(A.map((async e=>{const A=await Z(e);return{src:e,width:A.width,height:A.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,A,n){if(!t.data||!t.data.regions)return;const a=n.getCommandDispatcher(),i=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:i?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of A){a(new ft(t.id,e))}}getProcessedInput(t,e,A){const n=A?t:this.injectReplaceableText(t,e);return lt(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,A,n){const a=n.getStepStorage(A.stepName),i=this.getProcessedInput(t,A.data,!!a.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,A,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(A.data.maxLength-i.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&A.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of e){if(!t.fontData)throw new re("Failed to resolve font data for text.");const[e,n]=b(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[i],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});g.set(t.id,e),l.set(t.id,n);const a=A.data.curved?i:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,A.data,t.id,a,s))}if(!A.data.curved&&e.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(A.stepName,{text:t}),n.updateMetadata(A.stepName,{text:i}),a.defaultCleared&&n.setMandatoryFulfilled(A.stepName,!0),o.command=new d(c),o.command.varying=s,o}async selectVariant(t,e,A,n,a){const i=await this.selectVariantCommand(t,e,A.getStepStorage(t.stepName)||{},A.getRegionElements(t.stepName),A,n,a);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}createTextFillSpotColor(t,e){const A=t.colorProfile;if(A){const t=(A.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),a=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:a,namedColor:e.namedColor}}}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),a=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const o=i.variants?.find((t=>t.id===A));if(o){const A=await this.fontDataFromVariant(o),i=a.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[o],i,(async()=>{e.updateMetadata(t.stepName,{color:r,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=a.map((t=>new B(t.id,A))),i=new d(n);e.getCommandDispatcher()(i),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Ia.updateInputText(s||"",a,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Oe.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Oe.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Oe.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ne(t);const A=e.fileLink;if(!A)throw new ae(e);return{assetUrl:A,name:(await H(A)).names.fullName.en}}async selectVariantCommand(t,e,A,n,a,i,o,r){const s=a.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const g=n.map((t=>new B(t.id,c)));if(r){const t=n.map((t=>new ft(t.id,r)));g.push(...t)}const l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A.text||"",A,a,!!A.customiseAllText,i,o);l&&g.push(l);return{command:new d(g),followup:async()=>{a.markUpdateCompleted(s),await a.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,A,a),g=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||A.text||t.data.defaultText||"",A,a,!!A.customiseAllText,i,o),l=n.flatMap((t=>t.commands));if(r){const t=n.map((t=>new ft(t.regionElement.id,r)));l.push(...t)}g&&l.push(g);return{command:new d(l),followup:async()=>{a.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,A,n,a,i){if(!A||!A.regions)throw new Error("Step data not supplied");const r=i.getTransaction().bulk&&A.varyText||!1,s=r?"":a.text||A.defaultText||"",c=this.getProcessedInput(s,A,!1),g=await Promise.all(A.regions.map((async e=>{const g=i.getLayouts().find((t=>t.panelId===e.panelId)),l=F();try{if(!g)throw new Da("Failed to find layout for region: "+e.panelId);const B=A.colorOption;let d;if(B&&B.variants){const e=B.variants.find((t=>t.id===B.defaultVariant?.id))||B.variants[0];d=this.createTextFillSpotColor(B,e),i.updateStorage(t,{colorProfileAssetKey:B.colorProfile?.key})}const w=await this.getDefaultColor(A),E=w||"#000000",u={stepRegion:e,stepName:t,align:this.textAlign(A),fill:a.color?a.color:E,fontSize:A.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:c,input:s,type:h.Textbox,vertical:A.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:A.verticalAlign||"middle",curved:A.curved,paths:A.paths,fillSpotColorDefinition:d},C=[],Q=new Map,p=new Map;if(!u.fontData)throw new re("Failed to resolve font data for text.");const[m,f]=b(u.fontSize,u.fontData,{left:u.x,top:u.y,width:u.width,height:u.height,rotation:u.rotation,panelId:""},[c],{size:A.size,minSize:A.minSize,maxSize:A.maxSize});Q.set(u.id,m),p.set(u.id,f);const D=A.curved||A.vertical?c:(f||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(m,A,u.id,D,r));const I=new o(u,g);return I.varying=r,{regionElement:{id:l,region:e},commands:[I,...C],newElement:u,fontData:n}}catch(t){throw console.log(t),new ma("Error adding font to region")}}))).catch((t=>{throw t instanceof ma?(EA.setLatestToast("Failed to load font.",Ma.Error),t):t instanceof Da?t:new Error(t)}));return await i.setSelectionsAndElements(t,[e],g.map((t=>t.regionElement)),(async()=>{i.updateMetadata(t,{text:s}),i.updateStorage(t,{text:s})})),g}generateTextChangeCommandsForRegion(t,e,A,n,a){const i=[],o=new f(A,n);if(o.varying=a,i.push(o),!e.size){const e=new l(A,t);e.varying=a,i.push(e)}const r=new d(i);return r.varying=a,r}async changeInputTextWithRegion(t,e,A,n,a,i,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=i.getRegionElements(t.stepName),w=new Map,h=new Map;for(const n of B)if(n.region){const[a,i]=b(e,A,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});w.set(n.id,a),h.set(n.id,i)}const E=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=i.getProfanities(),A=qt(l.toLowerCase());for(const t of A)for(const A in e){if(t===e[A].toLowerCase().replace(/\s/g,""))return r(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(E.error)return void s(E.error);if(s(`${E.info} characters remaining`||""),c)return;i.updateStorage(t.stepName,{text:g}),i.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const u=i.getTransaction().bulk&&t.data.varyText||!1;a.defaultCleared&&i.setMandatoryFulfilled(t.stepName,!0);const C=[];for(const e of B){const A=t.data.curved?l:(h.get(e.id)||[]).join("\n");C.push(this.generateTextChangeCommandsForRegion(w.get(e.id)||1,t.data,e.id,A,u))}const Q=new d(C);return Q.varying=u,Q}};function ya(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Ma;var Fa;(Fa=Ma||(Ma={})).Error="Error",Fa.Warning="Warning",Fa.Info="Info";class Sa extends XA{constructor(t){super(),ya(this,"update",void 0),ya(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Ya{constructor(t,e,A,n,a,i,o,r,s,c,g=!1,l,B=!1){ya(this,"reloadedState",void 0),ya(this,"transaction",void 0),ya(this,"ownerCustomer",void 0),ya(this,"updateTransaction",void 0),ya(this,"confirmedDesign",void 0),ya(this,"editedSteps",void 0),ya(this,"informationResults",void 0),ya(this,"layouts",void 0),ya(this,"mandatorySteps",void 0),ya(this,"pendingUpdates",void 0),ya(this,"selectionCost",void 0),ya(this,"workflow",void 0),ya(this,"stepSpecificServices",void 0),ya(this,"previewService",void 0),ya(this,"profanityFilter",void 0),ya(this,"pollers",void 0),ya(this,"commandContext",void 0),ya(this,"stepElements",void 0),ya(this,"stepInitialised",void 0),ya(this,"stepMetadata",void 0),ya(this,"stepSelections",void 0),ya(this,"storage",void 0),ya(this,"confirmCallbacks",void 0),ya(this,"editedCallbacks",void 0),ya(this,"elementsCallbacks",void 0),ya(this,"informationResultCallbacks",void 0),ya(this,"initCallbacks",void 0),ya(this,"makingAdjustmentsCallback",void 0),ya(this,"mandatoryCallbacks",void 0),ya(this,"metadataCallbacks",void 0),ya(this,"selectionCallbacks",void 0),ya(this,"stepSpecificStorageCallbacks",void 0),ya(this,"storageCallbacks",void 0),ya(this,"currentVariationRecordCallbacks",void 0),ya(this,"variationRecordCallbacks",void 0),ya(this,"allScenes",void 0),ya(this,"product",void 0),ya(this,"invalidModelVariants",void 0),ya(this,"currentAdjustingStepId",void 0),ya(this,"renderableContextService",void 0),ya(this,"workflowStatePromiseQueue",new qA(1)),ya(this,"variationRecords",[]),ya(this,"currentVariationRecord",void 0),ya(this,"initializationPromise",void 0),ya(this,"initialized",!1),ya(this,"readOnly",!1),ya(this,"modelContainer",void 0),ya(this,"isReloadedTransaction",!1),ya(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,A]of e)A.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=a,this.commandContext=n,this.reloadedState=c,this.transaction=i,this.readOnly=g,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=A,this.product=o,this.previewService=r,this.modelContainer=l,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=s,this.currentVariationRecord=null,this.isReloadedTransaction=B,this.initializationPromise=this.initializeDefaultWorkflowState(t,i),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 Xn(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const A=$n(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:a}=await this.stepElementsForIntroducedSilentSteps(A,!!this.reloadedState);this.commandContext.apply(new d(a),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,A=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),A&&this.modelContainer?.executeAnimation(A)})()}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 A=this.stepSelections[e.stepName];A&&A.selectedVariants&&A.selectedVariants.length>0&&(t[e.stepName]={selections:A.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=F();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}updateStorage(t,e){const A={...this.storage,[t]:{...this.storage[t],...e}};if(!Ot(A,this.storage)){this.storage=A;const e=new ht(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 A={stepName:e.stepName};A.storage=this.storage[e.stepName],A.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(A)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Sa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new Sa((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new re("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(zt(t.transaction))),A=t.variation;if(!A)return{transaction:e};const n={layouts:{},serializableWorkflow:{steps:[]},...zt(A)||{}};return{transaction:e,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(((A,n)=>{const a=[...t[n]||[]];return e.forEach((t=>{const e=a.findIndex((e=>e.id===t.id));e>-1&&a.splice(e,1)})),A[n]=a,A}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Zn(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&&!Zn(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,e,A)=>{if(t.type===m.SilentIllustration){return{step:t,results:await new ia(t,e).trigger()}}if(t.type===m.ProductOverlay){return{step:t,results:await new ia(t,e,A).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},a=t.filter((t=>!this.stepInitialised[t.stepName])),i={stepElements:{},commands:[]},o=[];for(const t of a)this.markStepsAsInitialised([t.stepName]),e||o.push(n(t,this.layouts,A));const r=await Promise.all(o);for(const t of r)i.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),i.commands=[...i.commands,...t.results.map((t=>t.command))];return i}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 s(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,n){const a=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=>{Zn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const i=this.allScenes,o=$n(i,a),r=$n(i,this.stepSelections),c=o.map((t=>t.silentSteps)).flat(),g=r.map((t=>t.silentSteps)).flat().filter((t=>!c.some((e=>e.stepName===t.stepName))));c.forEach((t=>{Zn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:B,commands:w}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===m.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(A.map((t=>t.id)))}const h=[...w,...l.map((t=>new s(t.id))),new ht(this.constructSerializableWorkflow())];h.length>0&&this.commandContext.apply(new d(h),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=$n(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const A of e)if(!this.stepInitialised[A.stepName])switch(this.stepInitialised[A.stepName]=!0,A.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case m.DigitalContent:t.push(ca.init(A,this,this.reloadedState));break;case m.Frame:case m.Photo:{const e=new na(A.data.forceImageCover);e.connectWorkflowManager(this,A.stepName),this.stepSpecificServices[A.stepName]={frameService:e},t.push(la.init(A,this,this.reloadedState))}break;case m.Illustration:t.push(Ba.init(A,this,this.reloadedState));break;case m.Material:t.push(da.init(A,this,this.reloadedState));break;case m.Model:t.push(wa.init(A,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[A.stepName]={module:await un(A.data.module)},t.push(ha.init(A,this,this.reloadedState));break;case m.Picture:t.push(Ea.init(A,this,this.reloadedState));break;case m.Question:t.push(ua.init(A,this,this.reloadedState));break;case m.Shape:t.push(Qa.init(A,this,this.reloadedState));break;case m.Text:t.push(Ia.init(A,this,this.reloadedState))}const A=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=A.filter((t=>!!t&&!!t.command)).map((t=>t.command)),a=A.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new d(n),!0);for(const t of a)await t();a.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 _n(this.allScenes,this.stepSelections)}}function va(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class xa{constructor(t){va(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.asset?.versions?.find((t=>"cdn"===t.name))?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){return this.variantData.thumbnail?.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 Pa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Na{constructor(t,e){Pa(this,"manager",void 0),Pa(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Na.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Na.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new xa(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new xa(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new xa(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(),A=this.step.data.modelAnimation,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&A&&e.executeAnimation(A)}}function Ra(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;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:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}Pa(Na,"updateState",new Map);const Ha=It`
560
560
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
561
561
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
562
562
  id
package/dist/types.d.ts CHANGED
@@ -1485,7 +1485,7 @@ export class Variant {
1485
1485
  */
1486
1486
  getAssetResource(): _Asset1 | undefined;
1487
1487
  /**
1488
- * @returns The URL for a thumbnail resource configured on this variant. When no thumbnail is configured explicitly we fall back to the base asset and see if a thumbnail is genererated for that.
1488
+ * @returns The URL for a thumbnail resource configured on this variant.
1489
1489
  */
1490
1490
  getThumbnail(): string | undefined;
1491
1491
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/core",
3
- "version": "15.1.4",
3
+ "version": "15.1.5",
4
4
  "description": "Core client API for interacting with the Spiff Commerce backend.",
5
5
  "source": "src/index.ts",
6
6
  "main": "dist/main.js",