@spiffcommerce/core 37.0.3 → 37.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2654 -183
- package/dist/index.cjs +10 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +20 -1
- package/dist/index.mjs +37 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -166,6 +166,7 @@
|
|
|
166
166
|
material {
|
|
167
167
|
...MaterialFields
|
|
168
168
|
}
|
|
169
|
+
category
|
|
169
170
|
}
|
|
170
171
|
defaultVariant {
|
|
171
172
|
id
|
|
@@ -952,6 +953,7 @@
|
|
|
952
953
|
disablePlaceholder
|
|
953
954
|
displayImageOnFinishStep
|
|
954
955
|
displaySelectionOnFinishStep
|
|
956
|
+
enableVariantCategories
|
|
955
957
|
forceImageCover
|
|
956
958
|
hideImageInCart
|
|
957
959
|
hideSelectionInCart
|
|
@@ -985,6 +987,7 @@
|
|
|
985
987
|
pmsPickerEnabled
|
|
986
988
|
displayColorsOnFinishStep
|
|
987
989
|
displaySelectionOnFinishStep
|
|
990
|
+
enableVariantCategories
|
|
988
991
|
enableVariantSearch
|
|
989
992
|
hideColorsInCart
|
|
990
993
|
hideSelectionInCart
|
|
@@ -1006,6 +1009,7 @@
|
|
|
1006
1009
|
layoutName
|
|
1007
1010
|
}
|
|
1008
1011
|
displaySelectionOnFinishStep
|
|
1012
|
+
enableVariantCategories
|
|
1009
1013
|
hideSelectionInCart
|
|
1010
1014
|
lookAtAnimation {
|
|
1011
1015
|
...LookAtAnimationFields
|
|
@@ -1023,6 +1027,7 @@
|
|
|
1023
1027
|
layoutName
|
|
1024
1028
|
}
|
|
1025
1029
|
displaySelectionOnFinishStep
|
|
1030
|
+
enableVariantCategories
|
|
1026
1031
|
hideSelectionInCart
|
|
1027
1032
|
lookAtAnimation {
|
|
1028
1033
|
...LookAtAnimationFields
|
|
@@ -1061,6 +1066,7 @@
|
|
|
1061
1066
|
layoutName
|
|
1062
1067
|
}
|
|
1063
1068
|
displaySelectionOnFinishStep
|
|
1069
|
+
enableVariantCategories
|
|
1064
1070
|
enableVariantSearch
|
|
1065
1071
|
hideSelectionInCart
|
|
1066
1072
|
lookAtAnimation {
|
|
@@ -1105,6 +1111,7 @@
|
|
|
1105
1111
|
layoutName
|
|
1106
1112
|
}
|
|
1107
1113
|
displaySelectionOnFinishStep
|
|
1114
|
+
enableVariantCategories
|
|
1108
1115
|
excludeFromPrint
|
|
1109
1116
|
hideSelectionInCart
|
|
1110
1117
|
lookAtAnimation {
|
|
@@ -1157,6 +1164,7 @@
|
|
|
1157
1164
|
displayImageFillOnFinishStep
|
|
1158
1165
|
displayStrokeOnFinishStep
|
|
1159
1166
|
displayTextOnFinishStep
|
|
1167
|
+
enableVariantCategories
|
|
1160
1168
|
hideColorInCart
|
|
1161
1169
|
hideImageFillInCart
|
|
1162
1170
|
hideSelectionInCart
|
|
@@ -2112,7 +2120,7 @@
|
|
|
2112
2120
|
}
|
|
2113
2121
|
}
|
|
2114
2122
|
}
|
|
2115
|
-
`,mc=(n,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,a)=>(e[a]=t[a],e),{}):t,pc=n=>{for(const t of Object.values(n.layouts).map(e=>e.elements).flat())t.type==="illustration"&&(delete t.cachedObjectURL,t.src&&delete t.svg),t.type==="frame"&&delete t.pattern?.svg;return Oi(n,"__typename"),n},Oi=(n,t)=>{if(!(typeof n!="object"||n===null))for(const e in n)e===t?delete n[e]:Oi(n[e],t)};var he=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(he||{});const fc=1e3;class In extends Ua{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},fc)})}}const Cc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),wc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(i=>i.layout):Cc(t.panels)},Xt=class Xt{constructor(t,e,a,i,r,o=!1,s,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new Va(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):A?this.layouts=wc(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new Fl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const A=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(A)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=i,this.reloadedState=r,this.readOnly=o,this.singleVariantsRenderable=c,this.commandContext=new vi,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=s,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const i=a.uniqueIdentifier??a.title??"";a.type===_t.FirstName?e[i]=t?.firstName:a.type===_t.LastName?e[i]=t?.lastName:a.type===_t.Custom&&(a.customFieldIndex===1?e[i]=t?.customField1:a.customFieldIndex===2?e[i]=t?.customField2:a.customFieldIndex===3?e[i]=t?.customField3:a.customFieldIndex===4?e[i]=t?.customField4:a.customFieldIndex===5&&(e[i]=t?.customField5),a.option&&(e[i]=a.option.variants?.find(r=>r.id===e[i])?.name))}),e}async updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f,y){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:i??w.recipient.suburb,state:r??w.recipient.state,email:o??w.recipient.email,postalCode:s??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId},this.experience.callEvent(Qe.RecipientChanged),await this.graphQlClient().mutate({mutation:uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:i||w.recipient.suburb,state:r||w.recipient.state,email:o||w.recipient.email,postalCode:s||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId,prevalidated:y}});else{const F=await this.graphQlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:i,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f}});w.recipient={id:F?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:i,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f},this.experience.callEvent(Qe.RecipientChanged),await this.graphQlClient().mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=Xt.configurationPromiseMap.get(t.conversionConfigurationId);if(e)this.recipientConversionConfiguration=await e;else{const i=(async()=>(await this.graphQlClient().query({query:Go,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}})).data.conversionConfiguration)();Xt.configurationPromiseMap.set(t.conversionConfigurationId,i),this.recipientConversionConfiguration=await i}}}async initializeDefaultWorkflowState(t){const e=()=>{const d=t.finalizeStepConfig;if(!d)return;const u=d.lookAtAnimation,A=d.modelAnimation;u&&this.previewService?.executeCameraAnimation(u),A&&this.modelContainer?.executeAnimation(A)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(d=>{this.storage[d.stepName]=d.storage||{}});const a=this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((d,u)=>(u.selectedVariants?.length&&(d[u.stepName]={selectedVariants:u.selectedVariants.map(A=>({id:A.id}))}),d),{})),i=P.getOptions(Array.from(a)),r=this.fetchConversionConfiguration();await Promise.all([i,r]),this.allScenes=fn(t);const s=dt(this.allScenes,this.stepSelections).map(d=>d.silentSteps).flat(),{stepElements:l,commands:c}=await this.stepElementsForIntroducedSilentSteps(s,!!this.reloadedState);this.commandContext.apply(new U(c),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}getInitialOptionIds(t){const e=new Set,a=this.experience.getWorkflow();if(!a)return e;const i=fn(a),r={...t};let o=-1;for(;;){const c=dt(i,r).flatMap(d=>d.renderableSteps);if(c.length===o)break;o=c.length;for(const d of c){if(r[d.stepName])continue;const u=d.option?.defaultVariant?.id;u&&(r[d.stepName]={selectedVariants:[{id:u}]})}}return dt(i,r).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&e.add(l.option.id)}),e}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({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)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.experience.getTransaction().recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==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}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}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&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!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=N();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())}getMandatoryUnfulfilledSteps(){return dt(this.allScenes,this.stepSelections).flatMap(r=>r.renderableSteps).filter(r=>r.mandatory).filter(r=>!this.mandatorySteps[r.stepName]).map(r=>r.stepName)}setStepError(t,e,a){let i=!1;if(!this.validationErrors.steps.has(t)&&a)i=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const r=this.validationErrors.steps.get(t);a&&a!==r.get(e)?(i=!0,r.set(e,a)):a||(i=!0,r.delete(e),r.size===0&&this.validationErrors.steps.delete(t))}i&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const i=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(i),dt(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===E.Model||s.type===E.Material).forEach(s=>{if(!s.option?.id){console.error(`Failed to read option id from step: ${s.stepName}`);return}const l=this.stepSelections[s.stepName]?.selectedVariants||[];if(l.length===0)return;const c=l[0];if(s.type===E.Model){if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${s.stepName}`);return}const u=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,s.option.id,d)})}}),await i.getInitializationPromise(),this.renderLayouts()}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(!te(a,this.storage)){this.storage=a;const i=new Sn(this.constructSerializableWorkflow());this.commandContext.apply(i,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const i={stepName:a.stepName};i.storage=this.storage[a.stepName],i.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(r=>({id:r.id,priceModifier:r.priceModifier})),t.push(i)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new In(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new In(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new O("Attempted to serialize state before it was initialized.");const e=Pt(t.transaction),a=pc(e);return JSON.stringify(a,mc,void 0)}async getStateHash(){const t=this.getCommandContext().getState(),a=Object.values(t?.transaction.layouts||{}).map(o=>o.modificationID??"").sort().join(""),r=new TextEncoder().encode(a);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const o=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(a,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,i)=>Object.keys(a).reduce((r,o)=>{const s=[...a[o]||[]];return i.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),r[o]=s,r},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(Bt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])||[]}getInvalidModelVariants(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(e.type===E.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])||[]}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const i=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new vn(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new vn(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},r=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of r)this.markStepsAsInitialised([c.stepName]),e||s.push(i(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await S.getShadowGraphqlClient().query({query:Ko,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await S.getShadowGraphqlClient().mutate({mutation:lc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await S.getShadowGraphqlClient().mutate({mutation:cc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,i){const r=this.experience.getWorkflow();if(!r)throw new Error("Attempted to set selections when no workflow is set!");const o=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((v,I)=>v+I.selectedVariants.map(M=>M.priceModifier||0).reduce((M,R)=>M+R,0),0),r.steps.forEach(v=>{Bt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1,delete this.stepMetadata[v.stepName],delete this.stepSelections[v.stepName],delete this.storage[v.stepName])});const s=this.allScenes,l=dt(s,o),c=dt(s,this.stepSelections),d=l.map(v=>v.silentSteps).flat(),A=c.map(v=>v.silentSteps).flat().filter(v=>!d.some(I=>I.stepName===v.stepName));d.forEach(v=>{Bt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1)});const h=this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=r.steps.find(v=>v.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(I=>I.id));const f=h.map(v=>new Dt(v.id)),y=new Sn(this.constructSerializableWorkflow()),w=[...p,...f,y];w.length>0&&this.commandContext.apply(new U(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const F=this.getInvalidModelVariants(),b=this.modelContainer;if(b){const v=F.map(I=>b.applyModelVariant(I,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(v)}await this.onSelectionChange(),m?.type!==E.Frame&&m?.type!==E.Text&&this.setMandatoryFulfilled(t,!0),i&&await i()}async ensureStepsAreLoaded(){const e=dt(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],i=e.flat();for(const l of i)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push(Ha.init(l,this,this.reloadedState));break;case E.Frame:a.push(pt.init(l,this,this.reloadedState));break;case E.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case E.Material:a.push(Wa.init(l,this,this.reloadedState));break;case E.Model:a.push(Ya.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await Ti(l.data.module)},a.push(Ja.init(l,this,this.reloadedState));break;case E.Picture:a.push(Ka.init(l,this,this.reloadedState));break;case E.Question:a.push(_a.init(l,this,this.reloadedState));break;case E.Shape:a.push(Tt.init(l,this,this.reloadedState));break;case E.Text:a.push(j.init(l,this,this.reloadedState));break}const r=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=r.flatMap(l=>l?.command?[l.command]:[]),s=r.flatMap(l=>l?.followup?[l.followup]:[]);o&&o.length>0&&this.commandContext.apply(new U(o),!0);for(const l of s)await l();s.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({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))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return us(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}};Xt.configurationPromiseMap=new Map;let Pa=Xt;class nt{constructor(t){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=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const Zt=class Zt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Zt.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new nt(a)}async getAvailableVariants(){return(await this.getAllVariants()).filter(e=>e.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(e=>new nt(e))||[];const t=await P.getOption(this.step.option?.id);if(!t)throw new Error("Option not found, cannot fetch variants.");return(t.variants||[]).map(e=>new nt(e))||[]}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.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),i=this.step.data.modelAnimation,r=this.step.data.lookAtAnimation;e?r&&e.executeCameraAnimation(r):console.warn("No preview service available, cannot execute camera animations."),a?i&&a.executeAnimation(i,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let Z=Zt;class Ri extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=V(t[0].id,this.manager.getAllLayoutData()).colors,r=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=r?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=r.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const i=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?i.set(c,{browserValue:e,pmsValue:a}):i.set(c,e)}}):a?i.set(t,{browserValue:e,pmsValue:a}):i.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,i)}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}}class $i extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Wa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Ui extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ya.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Vi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ka.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}}class Li extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await _a.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class qi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Tt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Tt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Tt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Tt.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}}class zi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){await j.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:he.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?j.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return j.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return j.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);j.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,i=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:i,defaultCleared:!1}),this.setText(i)}setText(t){const e={input:t,helperData:{}},a=j.findLayoutElements(this.manager,this.step),i=j.filterUnsupportedCharacters(t,a[0]?.fontData),r=Nt(i,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&r>this.step.data.maxLength;o||(e.input=i);const s=a.length<=0,l=s?{inputText:i,text:i}:{inputText:i};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=j.getProcessedInput(i,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=j.updateInputText(i,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!o&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=j.findLayoutElements(this.manager,this.step);return j.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?j.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeStrokeColor(this.step,t,e,this.manager)}}class Gi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class ji extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Ha.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Hi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Ja.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:he.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class Se{static get(t,e){switch(e.type){case E.DigitalContent:return new ji(t,e,t.getStepTags(e.stepName));case E.Information:return new Gi(t,e,t.getStepTags(e.stepName));case E.Question:return new Li(t,e,t.getStepTags(e.stepName));case E.Text:return new zi(t,e,t.getStepTags(e.stepName));case E.Illustration:return new Ri(t,e,t.getStepTags(e.stepName));case E.Picture:return new Vi(t,e,t.getStepTags(e.stepName));case E.Shape:return new qi(t,e,t.getStepTags(e.stepName));case E.Material:return new $i(t,e,t.getStepTags(e.stepName));case E.Model:return new Ui(t,e,t.getStepTags(e.stepName));case E.Frame:return new hr(t,e,t.getStepTags(e.stepName));case E.Module:return new Hi(t,e,t.getStepTags(e.stepName));default:throw new O(`Step type ${e.type} not yet supported in Core SDK`)}}}const yc=C.gql`
|
|
2123
|
+
`,mc=(n,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,a)=>(e[a]=t[a],e),{}):t,pc=n=>{for(const t of Object.values(n.layouts).map(e=>e.elements).flat())t.type==="illustration"&&(delete t.cachedObjectURL,t.src&&delete t.svg),t.type==="frame"&&delete t.pattern?.svg;return Oi(n,"__typename"),n},Oi=(n,t)=>{if(!(typeof n!="object"||n===null))for(const e in n)e===t?delete n[e]:Oi(n[e],t)};var he=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(he||{});const fc=1e3;class In extends Ua{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},fc)})}}const Cc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),wc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(i=>i.layout):Cc(t.panels)},Xt=class Xt{constructor(t,e,a,i,r,o=!1,s,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new Va(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):A?this.layouts=wc(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new Fl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const A=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(A)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=i,this.reloadedState=r,this.readOnly=o,this.singleVariantsRenderable=c,this.commandContext=new vi,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=s,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const i=a.uniqueIdentifier??a.title??"";a.type===_t.FirstName?e[i]=t?.firstName:a.type===_t.LastName?e[i]=t?.lastName:a.type===_t.Custom&&(a.customFieldIndex===1?e[i]=t?.customField1:a.customFieldIndex===2?e[i]=t?.customField2:a.customFieldIndex===3?e[i]=t?.customField3:a.customFieldIndex===4?e[i]=t?.customField4:a.customFieldIndex===5&&(e[i]=t?.customField5),a.option&&(e[i]=a.option.variants?.find(r=>r.id===e[i])?.name))}),e}async updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f,y){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:i??w.recipient.suburb,state:r??w.recipient.state,email:o??w.recipient.email,postalCode:s??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId},this.experience.callEvent(Qe.RecipientChanged),await this.graphQlClient().mutate({mutation:uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:i||w.recipient.suburb,state:r||w.recipient.state,email:o||w.recipient.email,postalCode:s||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId,prevalidated:y}});else{const F=await this.graphQlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:i,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f}});w.recipient={id:F?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:i,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f},this.experience.callEvent(Qe.RecipientChanged),await this.graphQlClient().mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=Xt.configurationPromiseMap.get(t.conversionConfigurationId);if(e)this.recipientConversionConfiguration=await e;else{const i=(async()=>(await this.graphQlClient().query({query:Go,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}})).data.conversionConfiguration)();Xt.configurationPromiseMap.set(t.conversionConfigurationId,i),this.recipientConversionConfiguration=await i}}}async initializeDefaultWorkflowState(t){const e=()=>{const d=t.finalizeStepConfig;if(!d)return;const u=d.lookAtAnimation,A=d.modelAnimation;u&&this.previewService?.executeCameraAnimation(u),A&&this.modelContainer?.executeAnimation(A)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(d=>{this.storage[d.stepName]=d.storage||{}});const a=this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((d,u)=>(u.selectedVariants?.length&&(d[u.stepName]={selectedVariants:u.selectedVariants.map(A=>({id:A.id}))}),d),{})),i=P.getOptions(Array.from(a)),r=this.fetchConversionConfiguration();await Promise.all([i,r]),this.allScenes=fn(t);const s=dt(this.allScenes,this.stepSelections).map(d=>d.silentSteps).flat(),{stepElements:l,commands:c}=await this.stepElementsForIntroducedSilentSteps(s,!!this.reloadedState);this.commandContext.apply(new U(c),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}getInitialOptionIds(t){const e=new Set,a=this.experience.getWorkflow();if(!a)return e;const i=fn(a),r={...t};let o=-1;for(;;){const c=dt(i,r).flatMap(d=>d.renderableSteps);if(c.length===o)break;o=c.length;for(const d of c){if(r[d.stepName])continue;const u=d.option?.defaultVariant?.id;u&&(r[d.stepName]={selectedVariants:[{id:u}]})}}return dt(i,r).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&e.add(l.option.id)}),e}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({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)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.experience.getTransaction().recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==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}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}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&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!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=N();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())}getMandatoryUnfulfilledSteps(){return dt(this.allScenes,this.stepSelections).flatMap(r=>r.renderableSteps).filter(r=>r.mandatory).filter(r=>!this.mandatorySteps[r.stepName]).map(r=>r.stepName)}setStepError(t,e,a){let i=!1;if(!this.validationErrors.steps.has(t)&&a)i=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const r=this.validationErrors.steps.get(t);a&&a!==r.get(e)?(i=!0,r.set(e,a)):a||(i=!0,r.delete(e),r.size===0&&this.validationErrors.steps.delete(t))}i&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const i=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(i),dt(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===E.Model||s.type===E.Material).forEach(s=>{if(!s.option?.id){console.error(`Failed to read option id from step: ${s.stepName}`);return}const l=this.stepSelections[s.stepName]?.selectedVariants||[];if(l.length===0)return;const c=l[0];if(s.type===E.Model){if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${s.stepName}`);return}const u=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,s.option.id,d)})}}),await i.getInitializationPromise(),this.renderLayouts()}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(!te(a,this.storage)){this.storage=a;const i=new Sn(this.constructSerializableWorkflow());this.commandContext.apply(i,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const i={stepName:a.stepName};i.storage=this.storage[a.stepName],i.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(r=>({id:r.id,priceModifier:r.priceModifier})),t.push(i)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new In(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new In(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new O("Attempted to serialize state before it was initialized.");const e=Pt(t.transaction),a=pc(e);return JSON.stringify(a,mc,void 0)}async getStateHash(){const t=this.getCommandContext().getState(),a=Object.values(t?.transaction.layouts||{}).map(o=>o.modificationID??"").sort().join(""),r=new TextEncoder().encode(a);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const o=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(a,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,i)=>Object.keys(a).reduce((r,o)=>{const s=[...a[o]||[]];return i.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),r[o]=s,r},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(Bt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])||[]}getInvalidModelVariants(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(e.type===E.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])||[]}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const i=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new vn(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new vn(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},r=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of r)this.markStepsAsInitialised([c.stepName]),e||s.push(i(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await S.getShadowGraphqlClient().query({query:Ko,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await S.getShadowGraphqlClient().mutate({mutation:lc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await S.getShadowGraphqlClient().mutate({mutation:cc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,i){const r=this.experience.getWorkflow();if(!r)throw new Error("Attempted to set selections when no workflow is set!");const o=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((v,I)=>v+I.selectedVariants.map(M=>M.priceModifier||0).reduce((M,R)=>M+R,0),0),r.steps.forEach(v=>{Bt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1,delete this.stepMetadata[v.stepName],delete this.stepSelections[v.stepName],delete this.storage[v.stepName])});const s=this.allScenes,l=dt(s,o),c=dt(s,this.stepSelections),d=l.map(v=>v.silentSteps).flat(),A=c.map(v=>v.silentSteps).flat().filter(v=>!d.some(I=>I.stepName===v.stepName));d.forEach(v=>{Bt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1)});const h=this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=r.steps.find(v=>v.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(I=>I.id));const f=h.map(v=>new Dt(v.id)),y=new Sn(this.constructSerializableWorkflow()),w=[...p,...f,y];w.length>0&&this.commandContext.apply(new U(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const F=this.getInvalidModelVariants(),b=this.modelContainer;if(b){const v=F.map(I=>b.applyModelVariant(I,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(v)}await this.onSelectionChange(),m?.type!==E.Frame&&m?.type!==E.Text&&this.setMandatoryFulfilled(t,!0),i&&await i()}async ensureStepsAreLoaded(){const e=dt(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],i=e.flat();for(const l of i)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push(Ha.init(l,this,this.reloadedState));break;case E.Frame:a.push(pt.init(l,this,this.reloadedState));break;case E.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case E.Material:a.push(Wa.init(l,this,this.reloadedState));break;case E.Model:a.push(Ya.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await Ti(l.data.module)},a.push(Ja.init(l,this,this.reloadedState));break;case E.Picture:a.push(Ka.init(l,this,this.reloadedState));break;case E.Question:a.push(_a.init(l,this,this.reloadedState));break;case E.Shape:a.push(Tt.init(l,this,this.reloadedState));break;case E.Text:a.push(j.init(l,this,this.reloadedState));break}const r=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=r.flatMap(l=>l?.command?[l.command]:[]),s=r.flatMap(l=>l?.followup?[l.followup]:[]);o&&o.length>0&&this.commandContext.apply(new U(o),!0);for(const l of s)await l();s.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({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))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return us(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}};Xt.configurationPromiseMap=new Map;let Pa=Xt;class nt{constructor(t){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=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}getCategory(){return this.variantData.category}}const Zt=class Zt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Zt.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new nt(a)}async getAvailableVariants(){return(await this.getAllVariants()).filter(e=>e.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(e=>new nt(e))||[];const t=await P.getOption(this.step.option?.id);if(!t)throw new Error("Option not found, cannot fetch variants.");return(t.variants||[]).map(e=>new nt(e))||[]}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.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),i=this.step.data.modelAnimation,r=this.step.data.lookAtAnimation;e?r&&e.executeCameraAnimation(r):console.warn("No preview service available, cannot execute camera animations."),a?i&&a.executeAnimation(i,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let Z=Zt;class Ri extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=V(t[0].id,this.manager.getAllLayoutData()).colors,r=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=r?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=r.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const i=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?i.set(c,{browserValue:e,pmsValue:a}):i.set(c,e)}}):a?i.set(t,{browserValue:e,pmsValue:a}):i.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,i)}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class $i extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Wa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Ui extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ya.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Vi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ka.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Li extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await _a.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class qi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Tt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Tt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Tt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Tt.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class zi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){await j.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:he.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?j.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return j.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return j.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);j.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,i=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:i,defaultCleared:!1}),this.setText(i)}setText(t){const e={input:t,helperData:{}},a=j.findLayoutElements(this.manager,this.step),i=j.filterUnsupportedCharacters(t,a[0]?.fontData),r=Nt(i,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&r>this.step.data.maxLength;o||(e.input=i);const s=a.length<=0,l=s?{inputText:i,text:i}:{inputText:i};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=j.getProcessedInput(i,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=j.updateInputText(i,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!o&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=j.findLayoutElements(this.manager,this.step);return j.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?j.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeStrokeColor(this.step,t,e,this.manager)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Gi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class ji extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Ha.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Hi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Ja.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:he.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class Se{static get(t,e){switch(e.type){case E.DigitalContent:return new ji(t,e,t.getStepTags(e.stepName));case E.Information:return new Gi(t,e,t.getStepTags(e.stepName));case E.Question:return new Li(t,e,t.getStepTags(e.stepName));case E.Text:return new zi(t,e,t.getStepTags(e.stepName));case E.Illustration:return new Ri(t,e,t.getStepTags(e.stepName));case E.Picture:return new Vi(t,e,t.getStepTags(e.stepName));case E.Shape:return new qi(t,e,t.getStepTags(e.stepName));case E.Material:return new $i(t,e,t.getStepTags(e.stepName));case E.Model:return new Ui(t,e,t.getStepTags(e.stepName));case E.Frame:return new hr(t,e,t.getStepTags(e.stepName));case E.Module:return new Hi(t,e,t.getStepTags(e.stepName));default:throw new O(`Step type ${e.type} not yet supported in Core SDK`)}}}const yc=C.gql`
|
|
2116
2124
|
fragment CreateDesignTransaction on Transaction {
|
|
2117
2125
|
id
|
|
2118
2126
|
designName
|
|
@@ -2463,7 +2471,7 @@
|
|
|
2463
2471
|
}
|
|
2464
2472
|
}
|
|
2465
2473
|
}
|
|
2466
|
-
`;class Xc{constructor(t,e=S.getShadowGraphqlClient.bind(S)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Zc{init(t,e,a){this.cognitoClient=new pe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const i=await this.cognitoClient?.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Zc;class ir{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Or(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=ln.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(ln.code(e)?.code==="CLP")return"USD0,0"}}const Fn=new ir;class rr{constructor(t,e,a,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Fn.getPrecisionForCurrency(e))}}const td=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:as(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},ed=async(n,t)=>{const a=(await t).find(i=>i.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},nn=async(n,t)=>{const e=n.map(s=>ie.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const i=td(a,t),r=a.map(s=>ie.set({id:s,options:t},ed(s,i))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},or=async(n,t)=>(await nn([n],t))[0],ad=async n=>{const t=await S.getShadowGraphqlClient().query({query:hi,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class nd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:Lo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&eo(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 37.0.3"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ht.setHubUrl(t.hubUrl),ht.setServerUrl(t.serverUrl),ht.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Zn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return W}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!ao())throw new Error("Application key required to use Flow Service.");return new er}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await S.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new rr(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=sr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const i=(await S.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=S.getShadowGraphqlClient(),i=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!i.id){const s=(await e.mutate({mutation:Jc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(i);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const i=JSON.parse(e),r=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<r-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await S.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await S.getShadowGraphqlClient().mutate({mutation:Kc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",i=await jt.verifyCode(t,e,a);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await S.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),i=new Date().getTime()/1e3,r=!a?.AccessToken||Ne(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<i-parseInt(t)||r){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await S.getShadowGraphqlClient().query({query:_c,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await S.getShadowGraphqlClient().mutate({mutation:Hl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new xn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,i,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([y,w])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Ne(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...i?.graphql?.additionalHeaders},d=await S.getShadowGraphqlClient().query({query:Ll(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new xn(this,u,e,a,s,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:i?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,i){const o={...await cr(t),...i?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:Wl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await S.getShadowGraphqlClient().query({query:ic(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await S.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],i=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&i.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",i),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),i=a[0],r=i.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await i.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,i){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=ha(o,l),d=ha(s,l);let u=0;const A=S.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:Vo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,i&&i(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,bt)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(gt=>gt.option.transactionId===X.id)?.option.readOnly??!1,index:x[bt].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Uo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,i&&i(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[y,w]=await Promise.all([(async()=>m.length>0?await ad(m):[])(),(async()=>f.length>0?await nn(f,e):[])()]),F=new Map(y.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,bt=L?b.get(L):void 0,gt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const ge=Q.getMap("transactionOwnerIds")||new Map;!ge.get(T.id)&&T.transactionOwnerId&&(ge.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",ge));const _e=ge.get(T.id)||void 0,wr=new Xc({onMutate:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}})}),me={workflow:bt,transaction:T,singleVariantsRenderable:gt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>wr,readOnly:k,isReloadedTransaction:gt.type==="transaction"};if(gt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await ba(ot),me.reloadedState=ot}else if(!k&>.workflowState){const ot=JSON.parse(gt.workflowState);await ba(ot),me.reloadedState=ot}return me.delayWorkflowStateSync=!0,{experienceOptions:me,index:X,options:gt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Yi(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await S.getShadowGraphqlClient().query({query:Yo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Da(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Jo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Da(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,i=await S.getShadowGraphqlClient().query({query:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return i.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await S.getShadowGraphqlClient().mutate({mutation:ss,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const sr=async(n,t)=>(await S.getShadowGraphqlClient().query({query:is,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,id=async n=>{const e=await S.getShadowGraphqlClient().query({query:jo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},rd=async(n,t)=>(await S.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,od=async n=>(await S.getShadowGraphqlClient().query({query:os,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,sd=async n=>(await S.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function lr(){const n={};try{const t=await this.loggedInBearerToken();n.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(a);i&&!Ne(i)&&(n.Authorization=`Bearer ${i}`)}return n}async function cr(n){const e=Q.getMap("bundleOwnerIds")?.get(n),a=await lr();return{bundleOwnerId:e,...a}}async function ld(n){const e=Q.getMap("transactionOwnerIds")?.get(n),a=await lr();return{transactionOwnerId:e,...a}}const cd=async n=>{const t=await cr(n),e=await S.getShadowGraphqlClient().mutate({mutation:hc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)},dd=async n=>{const t=await ld(n),e=await S.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[n]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==n)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function dr(n,t,e,a){const i=e.width*n.zoom,r=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=be(n.x,t.width-c,0),s.y=be(n.y,t.height-d,0),s}const o=n;return o.x=be(o.x,-i,t.width),o.y=be(o.y,-r,t.height),o}function be(n,t,e){return Math.min(Math.max(n,t),e)}class ur{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=$n(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const i=a;if(i.currentFrameSources){let r=!1;for(let o=0;o<i.currentFrameSources.length;o++){const s=i.currentFrameSources[o],l=await Ae(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const i=Mt.get(e);i&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(this.imageData.svg,this.imageData.colors||{},!1);return Le(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(r,i),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==t.length)throw new O("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=dr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,i,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new U([new js(l,e,t[d]),new Hs(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,i)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[i]=r,this.maxZoomScale[i]=r*2.5):(this.minZoomScale[i]=r/10,this.maxZoomScale[i]=r*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=qa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class ud{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Set}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Ar=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Ar||{});class hr extends Z{constructor(t,e,a){super(t,e,a);const i=e.data;this.frameService=new ur(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return pt.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await pt.selectImage(this.step,t,this.manager,a),e){const i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Oe.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await W.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,i){return i&&i.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return W.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return W.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Ad=C.gql`
|
|
2474
|
+
`;class Xc{constructor(t,e=S.getShadowGraphqlClient.bind(S)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Zc{init(t,e,a){this.cognitoClient=new pe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const i=await this.cognitoClient?.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Zc;class ir{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Or(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=ln.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(ln.code(e)?.code==="CLP")return"USD0,0"}}const Fn=new ir;class rr{constructor(t,e,a,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Fn.getPrecisionForCurrency(e))}}const td=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:as(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},ed=async(n,t)=>{const a=(await t).find(i=>i.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},nn=async(n,t)=>{const e=n.map(s=>ie.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const i=td(a,t),r=a.map(s=>ie.set({id:s,options:t},ed(s,i))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},or=async(n,t)=>(await nn([n],t))[0],ad=async n=>{const t=await S.getShadowGraphqlClient().query({query:hi,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class nd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:Lo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&eo(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 37.1.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ht.setHubUrl(t.hubUrl),ht.setServerUrl(t.serverUrl),ht.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Zn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return W}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!ao())throw new Error("Application key required to use Flow Service.");return new er}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await S.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new rr(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=sr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const i=(await S.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=S.getShadowGraphqlClient(),i=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!i.id){const s=(await e.mutate({mutation:Jc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(i);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const i=JSON.parse(e),r=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<r-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await S.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await S.getShadowGraphqlClient().mutate({mutation:Kc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",i=await jt.verifyCode(t,e,a);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await S.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),i=new Date().getTime()/1e3,r=!a?.AccessToken||Ne(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<i-parseInt(t)||r){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await S.getShadowGraphqlClient().query({query:_c,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await S.getShadowGraphqlClient().mutate({mutation:Hl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new xn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,i,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([y,w])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Ne(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...i?.graphql?.additionalHeaders},d=await S.getShadowGraphqlClient().query({query:Ll(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new xn(this,u,e,a,s,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:i?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,i){const o={...await cr(t),...i?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:Wl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await S.getShadowGraphqlClient().query({query:ic(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await S.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],i=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&i.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",i),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),i=a[0],r=i.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await i.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,i){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=ha(o,l),d=ha(s,l);let u=0;const A=S.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:Vo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,i&&i(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,bt)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(gt=>gt.option.transactionId===X.id)?.option.readOnly??!1,index:x[bt].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Uo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,i&&i(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[y,w]=await Promise.all([(async()=>m.length>0?await ad(m):[])(),(async()=>f.length>0?await nn(f,e):[])()]),F=new Map(y.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,bt=L?b.get(L):void 0,gt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const ge=Q.getMap("transactionOwnerIds")||new Map;!ge.get(T.id)&&T.transactionOwnerId&&(ge.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",ge));const _e=ge.get(T.id)||void 0,wr=new Xc({onMutate:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}})}),me={workflow:bt,transaction:T,singleVariantsRenderable:gt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:_e,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>wr,readOnly:k,isReloadedTransaction:gt.type==="transaction"};if(gt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await ba(ot),me.reloadedState=ot}else if(!k&>.workflowState){const ot=JSON.parse(gt.workflowState);await ba(ot),me.reloadedState=ot}return me.delayWorkflowStateSync=!0,{experienceOptions:me,index:X,options:gt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Yi(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await S.getShadowGraphqlClient().query({query:Yo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Da(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Jo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Da(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,i=await S.getShadowGraphqlClient().query({query:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return i.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await S.getShadowGraphqlClient().mutate({mutation:ss,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const sr=async(n,t)=>(await S.getShadowGraphqlClient().query({query:is,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,id=async n=>{const e=await S.getShadowGraphqlClient().query({query:jo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},rd=async(n,t)=>(await S.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,od=async n=>(await S.getShadowGraphqlClient().query({query:os,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,sd=async n=>(await S.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function lr(){const n={};try{const t=await this.loggedInBearerToken();n.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(a);i&&!Ne(i)&&(n.Authorization=`Bearer ${i}`)}return n}async function cr(n){const e=Q.getMap("bundleOwnerIds")?.get(n),a=await lr();return{bundleOwnerId:e,...a}}async function ld(n){const e=Q.getMap("transactionOwnerIds")?.get(n),a=await lr();return{transactionOwnerId:e,...a}}const cd=async n=>{const t=await cr(n),e=await S.getShadowGraphqlClient().mutate({mutation:hc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)},dd=async n=>{const t=await ld(n),e=await S.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[n]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==n)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function dr(n,t,e,a){const i=e.width*n.zoom,r=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=be(n.x,t.width-c,0),s.y=be(n.y,t.height-d,0),s}const o=n;return o.x=be(o.x,-i,t.width),o.y=be(o.y,-r,t.height),o}function be(n,t,e){return Math.min(Math.max(n,t),e)}class ur{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=$n(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const i=a;if(i.currentFrameSources){let r=!1;for(let o=0;o<i.currentFrameSources.length;o++){const s=i.currentFrameSources[o],l=await Ae(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const i=Mt.get(e);i&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(this.imageData.svg,this.imageData.colors||{},!1);return Le(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(r,i),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==t.length)throw new O("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=dr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,i,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new U([new js(l,e,t[d]),new Hs(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,i)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[i]=r,this.maxZoomScale[i]=r*2.5):(this.minZoomScale[i]=r/10,this.maxZoomScale[i]=r*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=qa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class ud{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Set}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Ar=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Ar||{});class hr extends Z{constructor(t,e,a){super(t,e,a);const i=e.data;this.frameService=new ur(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return pt.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await pt.selectImage(this.step,t,this.manager,a),e){const i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Oe.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await W.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,i){return i&&i.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return W.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return W.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const Ad=C.gql`
|
|
2467
2475
|
query GetLoggedInCustomer($email: String!) {
|
|
2468
2476
|
customer(emailAddress: $email) {
|
|
2469
2477
|
id
|