@spiffcommerce/core 32.2.7-beta.8bae3361-3242-5b7e-a75c-ed03cdc03b9c → 32.2.7-beta.fe525a16-f209-5cb8-95bc-b269e8ebcfcc
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +6 -1
- package/dist/index.js +35 -35
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +346 -335
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
@@ -2214,11 +2214,11 @@
|
|
2214
2214
|
id
|
2215
2215
|
}
|
2216
2216
|
}
|
2217
|
-
|
2217
|
+
`,Bl=w.gql`
|
2218
2218
|
mutation DeleteBundle($id: String!) {
|
2219
2219
|
bundleDelete(id: $id)
|
2220
2220
|
}
|
2221
|
-
`;var pe=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(pe||{});const Bl=1e3;class gn extends ka{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Bl)})}}class Il{constructor(t,e,a,r,i,o,s,l,c,d,A,u,h,g=!1,m,p=!1,f=!1,S=!1){this.workflowStatePromiseQueue=new Ma(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{if(!this.previewService)return;const b=this.getCommandContext().getAllLayouts(),P=this.getLayoutPreviewService()?.getAll();if(P)for(const[,C]of P)C.render(b)},this.experience=t,this.client=e,this.updateTransaction=s,this.graphQlClient=l,this.commandContext=o,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=r,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=m,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},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.currentAdjustingStepId="",this.renderableContextService=u,this.renderableContextService?.setWorkflowManager(this),this.isReloadedTransaction=p,this.workflow.steps.forEach(b=>{this.stepTags[b.stepName]=b.tags??[]}),S&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(b=>{throw console.error(b),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}getTemplatingContext(){const t=this.transaction.recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const r=a.uniqueIdentifier??a.title??"";a.type===Xt.FirstName?e[r]=t?.firstName:a.type===Xt.LastName?e[r]=t?.lastName:a.type===Xt.Custom&&(a.customFieldIndex===1?e[r]=t?.customField1:a.customFieldIndex===2?e[r]=t?.customField2:a.customFieldIndex===3?e[r]=t?.customField3:a.customFieldIndex===4?e[r]=t?.customField4:a.customFieldIndex===5&&(e[r]=t?.customField5))}),e}async updateRecipient(t,e,a,r,i,o,s,l,c,d,A,u,h,g,m,p,f){if(this.transaction.recipient?.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t??this.transaction.recipient.firstName,lastName:e??this.transaction.recipient.lastName,address:a??this.transaction.recipient.address,suburb:r??this.transaction.recipient.suburb,state:i??this.transaction.recipient.state,email:o??this.transaction.recipient.email,postalCode:s??this.transaction.recipient.postalCode,country:l??this.transaction.recipient.country,mobile:c??this.transaction.recipient.mobile,company:d??this.transaction.recipient.company,apartment:A??this.transaction.recipient.apartment,customField1:u??this.transaction.recipient.customField1,customField2:h??this.transaction.recipient.customField2,customField3:g??this.transaction.recipient.customField3,customField4:m??this.transaction.recipient.customField4,customField5:p??this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId},await this.graphQlClient().mutate({mutation:El,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:r||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:o||this.transaction.recipient.email,postalCode:s||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company,apartment:A||this.transaction.recipient.apartment,customField1:u||this.transaction.recipient.customField1,customField2:h||this.transaction.recipient.customField2,customField3:g||this.transaction.recipient.customField3,customField4:m||this.transaction.recipient.customField4,customField5:p||this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId}});else{const S=await this.graphQlClient().mutate({mutation:vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f}});this.transaction.recipient={id:S?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f},await this.graphQlClient().mutate({mutation:bl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:S.data?.recipientCreate?.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(S=>S(this.transaction.recipient))}async fetchConversionConfiguration(){const t=this.transaction.recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=await this.graphQlClient().query({query:po,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}});e.data.conversionConfiguration&&(this.recipientConversionConfiguration=e.data.conversionConfiguration)}}async initializeDefaultWorkflowState(t){const e=()=>{const s=this.workflow.finalizeStepConfig;if(!s)return;const l=s.lookAtAnimation,c=s.modelAnimation;l&&this.previewService?.executeCameraAnimation(l),c&&this.modelContainer?.executeAnimation(c)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(s=>{this.storage[s.stepName]=s.storage||{}}),await this.fetchConversionConfiguration(),this.allScenes=await Ro(t);const r=Et(this.allScenes,this.stepSelections).map(s=>s.silentSteps).flat(),{stepElements:i,commands:o}=await this.stepElementsForIntroducedSilentSteps(r,!!this.reloadedState);this.commandContext.apply(new Q(o),!0),this.stepElements={...this.stepElements,...i},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}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}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.transaction.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}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}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=M();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 Et(this.allScenes,this.stepSelections).flatMap(i=>i.renderableSteps).filter(i=>i.mandatory).filter(i=>!this.mandatorySteps[i.stepName]).map(i=>i.stepName)}setStepError(t,e,a){let r=!1;if(!this.validationErrors.steps.has(t)&&a)r=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(r=!0,i.set(e,a)):a||(r=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}r&&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.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),Et(this.allScenes,this.stepSelections).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===v.Model||o.type===v.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const s=this.stepSelections[o.stepName]?.selectedVariants||[];if(s.length===0)return;const l=s[0];if(o.type===v.Model){if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");const c=l.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${l.id} for step: ${o.stepName}`);return}const d=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},d.replaceProductModel||!1)}else{const c=l.material;if(!c){console.error(`Failed to read material from variant: ${l.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,o.option.id,c)})}}),await a.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(!De(a,this.storage)){this.storage=a;const r=new dn(this.constructSerializableWorkflow());this.commandContext.apply(r,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const r={stepName:a.stepName};r.storage=this.storage[a.stepName],r.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(i=>({id:i.id,priceModifier:i.priceModifier})),t.push(r)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new gn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new gn(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new L("Attempted to serialize state before it was initialized.");const e=It(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){for(const e of Object.values(t.layouts).map(a=>a.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}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,r)=>Object.keys(a).reduce((i,o)=>{const s=[...a[o]||[]];return r.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),i[o]=s,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.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.workflow.steps.reduce((t,e)=>(e.type===v.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const r=async(c,d,A)=>{if(c.type===v.SilentIllustration){const u=await new An(c,d).trigger();return{step:c,results:u}}else if(c.type===v.ProductOverlay){const u=await new An(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||s.push(r(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.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:So,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:yl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Sl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new yt(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,r){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((C,E)=>C+E.selectedVariants.map(D=>D.priceModifier||0).reduce((D,B)=>D+B,0),0),this.workflow.steps.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1,delete this.stepMetadata[C.stepName],delete this.stepSelections[C.stepName],delete this.storage[C.stepName])});const o=this.allScenes,s=Et(o,i),l=Et(o,this.stepSelections),c=s.map(C=>C.silentSteps).flat(),A=l.map(C=>C.silentSteps).flat().filter(C=>!c.some(E=>E.stepName===C.stepName));c.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const m=this.workflow.steps.find(C=>C.stepName===t);m?.type===v.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(E=>E.id));const p=u.map(C=>new yt(C.id)),f=new dn(this.constructSerializableWorkflow()),S=[...g,...p,f];S.length>0&&this.commandContext.apply(new Q(S),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const b=this.getInvalidModelVariants(),P=this.modelContainer;if(P){const C=b.map(E=>P.applyModelVariant(E,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(C)}await this.onSelectionChange(),r&&await r()}async ensureStepsAreLoaded(){const e=Et(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],r=e.flat();for(const l of r)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case v.DigitalContent:a.push($a.init(l,this,this.reloadedState));break;case v.Frame:a.push(ht.init(l,this,this.reloadedState));break;case v.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case v.Material:a.push(Ua.init(l,this,this.reloadedState));break;case v.Model:a.push(La.init(l,this,this.reloadedState));break;case v.Module:this.stepSpecificServices[l.stepName]={module:await fr(l.data.module)},a.push(Va.init(l,this,this.reloadedState));break;case v.Picture:a.push(za.init(l,this,this.reloadedState));break;case v.Question:a.push(qa.init(l,this,this.reloadedState));break;case v.Shape:a.push(kt.init(l,this,this.reloadedState));break;case v.Text:a.push(q.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=i.filter(l=>!!l&&!!l.command).map(l=>l.command),s=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);o&&o.length>0&&this.commandContext.apply(new Q(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 Uo(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class rt{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.getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new rt(a)}getAvailableVariants(){return(this.step.option?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.step.option?.variants||[]).map(e=>new rt(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(),r=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?r&&a.executeAnimation(r,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let X=Zt;class Cr extends X{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=$(t[0].id,this.manager.getAllLayoutData()).colors,i=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=i?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=i.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 r=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?r.set(c,{browserValue:e,pmsValue:a}):r.set(c,e)}}):a?r.set(t,{browserValue:e,pmsValue:a}):r.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),r)}async getColorOption(){return 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}}class wr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ua.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class yr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return La.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Sr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return za.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class vr extends X{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 qa.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Er extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return kt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return kt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return kt.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()}`),kt.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 br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){q.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:pe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?q.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return q.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return q.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);q.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,r=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:r,defaultCleared:!1}),this.setText(r)}setText(t){const e={input:t,helperData:{}},a=q.findLayoutElements(this.manager,this.step),r=q.filterUnsupportedCharacters(t,a[0]?.fontData),i=Mt(r,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&i>this.step.data.maxLength;o||(e.input=r);const s=a.length<=0,l=s?{inputText:r,text:r}:{inputText:r};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=q.getProcessedInput(r,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:A,errorData:u,helperData:h}=q.updateInputText(r,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!o&&!u&&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=q.findLayoutElements(this.manager,this.step);return q.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=Mt(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.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?q.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 q.changeStrokeColor(this.step,t,e,this.manager)}}class Br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Ir extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return $a.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Pr extends X{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=Mt(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){Va.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class Se{static get(t,e){switch(e.type){case v.DigitalContent:return new Ir(t,e,t.getStepTags(e.stepName));case v.Information:return new Br(t,e,t.getStepTags(e.stepName));case v.Question:return new vr(t,e,t.getStepTags(e.stepName));case v.Text:return new br(t,e,t.getStepTags(e.stepName));case v.Illustration:return new Cr(t,e,t.getStepTags(e.stepName));case v.Picture:return new Sr(t,e,t.getStepTags(e.stepName));case v.Shape:return new Er(t,e,t.getStepTags(e.stepName));case v.Material:return new wr(t,e,t.getStepTags(e.stepName));case v.Model:return new yr(t,e,t.getStepTags(e.stepName));case v.Frame:return new _r(t,e,t.getStepTags(e.stepName));case v.Module:return new Pr(t,e,t.getStepTags(e.stepName));default:throw new L(`Step type ${e.type} not yet supported in Core SDK`)}}}const Dr=w.gql`
|
2221
|
+
`;var pe=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(pe||{});const Il=1e3;class gn extends ka{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Il)})}}class Pl{constructor(t,e,a,r,i,o,s,l,c,d,A,u,h,g=!1,m,p=!1,f=!1,S=!1){this.workflowStatePromiseQueue=new Ma(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{if(!this.previewService)return;const b=this.getCommandContext().getAllLayouts(),P=this.getLayoutPreviewService()?.getAll();if(P)for(const[,C]of P)C.render(b)},this.experience=t,this.client=e,this.updateTransaction=s,this.graphQlClient=l,this.commandContext=o,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=r,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=m,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},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.currentAdjustingStepId="",this.renderableContextService=u,this.renderableContextService?.setWorkflowManager(this),this.isReloadedTransaction=p,this.workflow.steps.forEach(b=>{this.stepTags[b.stepName]=b.tags??[]}),S&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(b=>{throw console.error(b),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}getTemplatingContext(){const t=this.transaction.recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const r=a.uniqueIdentifier??a.title??"";a.type===Xt.FirstName?e[r]=t?.firstName:a.type===Xt.LastName?e[r]=t?.lastName:a.type===Xt.Custom&&(a.customFieldIndex===1?e[r]=t?.customField1:a.customFieldIndex===2?e[r]=t?.customField2:a.customFieldIndex===3?e[r]=t?.customField3:a.customFieldIndex===4?e[r]=t?.customField4:a.customFieldIndex===5&&(e[r]=t?.customField5))}),e}async updateRecipient(t,e,a,r,i,o,s,l,c,d,A,u,h,g,m,p,f){if(this.transaction.recipient?.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t??this.transaction.recipient.firstName,lastName:e??this.transaction.recipient.lastName,address:a??this.transaction.recipient.address,suburb:r??this.transaction.recipient.suburb,state:i??this.transaction.recipient.state,email:o??this.transaction.recipient.email,postalCode:s??this.transaction.recipient.postalCode,country:l??this.transaction.recipient.country,mobile:c??this.transaction.recipient.mobile,company:d??this.transaction.recipient.company,apartment:A??this.transaction.recipient.apartment,customField1:u??this.transaction.recipient.customField1,customField2:h??this.transaction.recipient.customField2,customField3:g??this.transaction.recipient.customField3,customField4:m??this.transaction.recipient.customField4,customField5:p??this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId},await this.graphQlClient().mutate({mutation:El,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:r||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:o||this.transaction.recipient.email,postalCode:s||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company,apartment:A||this.transaction.recipient.apartment,customField1:u||this.transaction.recipient.customField1,customField2:h||this.transaction.recipient.customField2,customField3:g||this.transaction.recipient.customField3,customField4:m||this.transaction.recipient.customField4,customField5:p||this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId}});else{const S=await this.graphQlClient().mutate({mutation:vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f}});this.transaction.recipient={id:S?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f},await this.graphQlClient().mutate({mutation:bl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:S.data?.recipientCreate?.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(S=>S(this.transaction.recipient))}async fetchConversionConfiguration(){const t=this.transaction.recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=await this.graphQlClient().query({query:po,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}});e.data.conversionConfiguration&&(this.recipientConversionConfiguration=e.data.conversionConfiguration)}}async initializeDefaultWorkflowState(t){const e=()=>{const s=this.workflow.finalizeStepConfig;if(!s)return;const l=s.lookAtAnimation,c=s.modelAnimation;l&&this.previewService?.executeCameraAnimation(l),c&&this.modelContainer?.executeAnimation(c)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(s=>{this.storage[s.stepName]=s.storage||{}}),await this.fetchConversionConfiguration(),this.allScenes=await Ro(t);const r=Et(this.allScenes,this.stepSelections).map(s=>s.silentSteps).flat(),{stepElements:i,commands:o}=await this.stepElementsForIntroducedSilentSteps(r,!!this.reloadedState);this.commandContext.apply(new Q(o),!0),this.stepElements={...this.stepElements,...i},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}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}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.transaction.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}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}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=M();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 Et(this.allScenes,this.stepSelections).flatMap(i=>i.renderableSteps).filter(i=>i.mandatory).filter(i=>!this.mandatorySteps[i.stepName]).map(i=>i.stepName)}setStepError(t,e,a){let r=!1;if(!this.validationErrors.steps.has(t)&&a)r=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(r=!0,i.set(e,a)):a||(r=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}r&&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.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),Et(this.allScenes,this.stepSelections).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===v.Model||o.type===v.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const s=this.stepSelections[o.stepName]?.selectedVariants||[];if(s.length===0)return;const l=s[0];if(o.type===v.Model){if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");const c=l.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${l.id} for step: ${o.stepName}`);return}const d=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},d.replaceProductModel||!1)}else{const c=l.material;if(!c){console.error(`Failed to read material from variant: ${l.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,o.option.id,c)})}}),await a.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(!De(a,this.storage)){this.storage=a;const r=new dn(this.constructSerializableWorkflow());this.commandContext.apply(r,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const r={stepName:a.stepName};r.storage=this.storage[a.stepName],r.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(i=>({id:i.id,priceModifier:i.priceModifier})),t.push(r)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new gn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new gn(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new L("Attempted to serialize state before it was initialized.");const e=It(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){for(const e of Object.values(t.layouts).map(a=>a.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}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,r)=>Object.keys(a).reduce((i,o)=>{const s=[...a[o]||[]];return r.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),i[o]=s,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.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.workflow.steps.reduce((t,e)=>(e.type===v.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const r=async(c,d,A)=>{if(c.type===v.SilentIllustration){const u=await new An(c,d).trigger();return{step:c,results:u}}else if(c.type===v.ProductOverlay){const u=await new An(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||s.push(r(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.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:So,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:yl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Sl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new yt(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,r){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((C,E)=>C+E.selectedVariants.map(D=>D.priceModifier||0).reduce((D,B)=>D+B,0),0),this.workflow.steps.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1,delete this.stepMetadata[C.stepName],delete this.stepSelections[C.stepName],delete this.storage[C.stepName])});const o=this.allScenes,s=Et(o,i),l=Et(o,this.stepSelections),c=s.map(C=>C.silentSteps).flat(),A=l.map(C=>C.silentSteps).flat().filter(C=>!c.some(E=>E.stepName===C.stepName));c.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const m=this.workflow.steps.find(C=>C.stepName===t);m?.type===v.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(E=>E.id));const p=u.map(C=>new yt(C.id)),f=new dn(this.constructSerializableWorkflow()),S=[...g,...p,f];S.length>0&&this.commandContext.apply(new Q(S),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const b=this.getInvalidModelVariants(),P=this.modelContainer;if(P){const C=b.map(E=>P.applyModelVariant(E,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(C)}await this.onSelectionChange(),r&&await r()}async ensureStepsAreLoaded(){const e=Et(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],r=e.flat();for(const l of r)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case v.DigitalContent:a.push($a.init(l,this,this.reloadedState));break;case v.Frame:a.push(ht.init(l,this,this.reloadedState));break;case v.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case v.Material:a.push(Ua.init(l,this,this.reloadedState));break;case v.Model:a.push(La.init(l,this,this.reloadedState));break;case v.Module:this.stepSpecificServices[l.stepName]={module:await fr(l.data.module)},a.push(Va.init(l,this,this.reloadedState));break;case v.Picture:a.push(za.init(l,this,this.reloadedState));break;case v.Question:a.push(qa.init(l,this,this.reloadedState));break;case v.Shape:a.push(kt.init(l,this,this.reloadedState));break;case v.Text:a.push(q.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=i.filter(l=>!!l&&!!l.command).map(l=>l.command),s=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);o&&o.length>0&&this.commandContext.apply(new Q(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 Uo(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class rt{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.getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new rt(a)}getAvailableVariants(){return(this.step.option?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.step.option?.variants||[]).map(e=>new rt(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(),r=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?r&&a.executeAnimation(r,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let X=Zt;class Cr extends X{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=$(t[0].id,this.manager.getAllLayoutData()).colors,i=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=i?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=i.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 r=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?r.set(c,{browserValue:e,pmsValue:a}):r.set(c,e)}}):a?r.set(t,{browserValue:e,pmsValue:a}):r.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),r)}async getColorOption(){return 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}}class wr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ua.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class yr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return La.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Sr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return za.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class vr extends X{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 qa.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Er extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return kt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return kt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return kt.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()}`),kt.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 br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){q.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:pe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?q.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return q.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return q.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);q.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,r=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:r,defaultCleared:!1}),this.setText(r)}setText(t){const e={input:t,helperData:{}},a=q.findLayoutElements(this.manager,this.step),r=q.filterUnsupportedCharacters(t,a[0]?.fontData),i=Mt(r,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&i>this.step.data.maxLength;o||(e.input=r);const s=a.length<=0,l=s?{inputText:r,text:r}:{inputText:r};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=q.getProcessedInput(r,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:A,errorData:u,helperData:h}=q.updateInputText(r,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!o&&!u&&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=q.findLayoutElements(this.manager,this.step);return q.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=Mt(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.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?q.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 q.changeStrokeColor(this.step,t,e,this.manager)}}class Br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Ir extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return $a.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Pr extends X{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=Mt(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){Va.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class Se{static get(t,e){switch(e.type){case v.DigitalContent:return new Ir(t,e,t.getStepTags(e.stepName));case v.Information:return new Br(t,e,t.getStepTags(e.stepName));case v.Question:return new vr(t,e,t.getStepTags(e.stepName));case v.Text:return new br(t,e,t.getStepTags(e.stepName));case v.Illustration:return new Cr(t,e,t.getStepTags(e.stepName));case v.Picture:return new Sr(t,e,t.getStepTags(e.stepName));case v.Shape:return new Er(t,e,t.getStepTags(e.stepName));case v.Material:return new wr(t,e,t.getStepTags(e.stepName));case v.Model:return new yr(t,e,t.getStepTags(e.stepName));case v.Frame:return new _r(t,e,t.getStepTags(e.stepName));case v.Module:return new Pr(t,e,t.getStepTags(e.stepName));default:throw new L(`Step type ${e.type} not yet supported in Core SDK`)}}}const Dr=w.gql`
|
2222
2222
|
fragment CreateDesignTransaction on Transaction {
|
2223
2223
|
id
|
2224
2224
|
designName
|
@@ -2243,7 +2243,7 @@
|
|
2243
2243
|
externalProductVariantId
|
2244
2244
|
}
|
2245
2245
|
}
|
2246
|
-
`,
|
2246
|
+
`,Dl=w.gql`
|
2247
2247
|
${Dr}
|
2248
2248
|
mutation CreateDesign(
|
2249
2249
|
$name: String!
|
@@ -2275,7 +2275,7 @@
|
|
2275
2275
|
}
|
2276
2276
|
}
|
2277
2277
|
}
|
2278
|
-
`,
|
2278
|
+
`,xl=w.gql`
|
2279
2279
|
${Dr}
|
2280
2280
|
mutation CreateDesigns($inputs: [DesignCreateInput]!) {
|
2281
2281
|
designCreateMany(inputs: $inputs) {
|
@@ -2289,7 +2289,7 @@
|
|
2289
2289
|
}
|
2290
2290
|
}
|
2291
2291
|
}
|
2292
|
-
`;function _t(n){const t=JSON.parse(atob(n.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const
|
2292
|
+
`;function _t(n){const t=JSON.parse(atob(n.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const Fl=async(n,t)=>{const e={};try{if(!t)throw new Error}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!_t(s)&&(e.Authorization=`Bearer ${s}`)}return(await y.getShadowGraphqlClient().mutate({mutation:Dl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:n.name,layouts:n.layouts,workflowId:n.workflowId,transactionId:n.transactionId,previewImage:n.previewImage,useThreeDimPreview:n.useThreeDimPreview,metadata:n.metadata,selectedVariants:n.selectedVariants},context:{headers:e}})).data?.designCreate},kl=async(n,t)=>{const e={};try{if(!t)throw new Error}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!_t(s)&&(e.Authorization=`Bearer ${s}`)}return(await y.getShadowGraphqlClient().mutate({mutation:xl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:n.map(r=>({name:r.name,layouts:r.layouts,workflowId:r.workflowId,transactionId:r.transactionId,previewImage:r.previewImage,useThreeDimPreview:r.useThreeDimPreview,metadata:r.metadata,selectedVariants:r.selectedVariants}))},context:{headers:e}})).data?.designCreateMany},mn=(n,t,e)=>{const a=i=>{const o={};if(i.type==="Frame"){const s=n[i.stepName],l=i.data;if(!s||!s.image||l.hideImageInCart&&e)return o;o[`${i.stepTitle} image`]=s.image}if(i.type==="Illustration"){const s=n[i.stepName],l=i.data;if(!s||l.hideColorsInCart&&e||!s.colors)return o;if(s.colors.length>0){const c=s.colors.join(", ").toUpperCase();o[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const s=n[i.stepName],l=i.data;if(!s||s.text===void 0||s.text===null||l.hideTextInCart&&e)return o;o[`${i.stepTitle} text`]=s.text}if(i.type==="Text"){const s=n[i.stepName];if(!s)return o;const l=i.data;(!l.hideTextInCart||!e&&s.text!==void 0&&s.text!==null)&&(o[`${i.stepTitle} text`]=s.text),s.color&&(!l.hideColorInCart||!e)&&(o[`${i.stepTitle} color`]=s.color),s.strokeColor&&(!l.hideStrokeInCart||!e)&&(o[`${i.stepTitle} stroke`]=s.strokeColor)}return o},r={};return t.steps.forEach(i=>{Object.assign(r,a(i))}),r},Ml=(n,t,e,a)=>{const r={};let i={};a&&(i=a);const s=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of s){if(Object.keys(n).includes(l)){const c=n[l],d=t.steps.find(A=>A.stepTitle===l);r[`${d?.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(r[c]={value:i[c],priceModifier:0})}return r},xr=(n,t,e,a,r,i,o,s)=>{const l=t.basePrice||0,c=n.priceModifierTotal||0,d=Ml(a,e,void 0,i),u=(k.getMap("transactionOwnerIds")||new Map).get(n.id),h={additionalExternalProductId:n.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:n.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:n.designExternalVariants,designProductId:n.externalDesignProductId,designProductVariantId:n.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:n.externalCartProductId,externalCartProductVariantId:n.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:c,processExecutionId:s,quantity:n.quantity,transactionId:n.id,transactionOwnerId:u,weight:t.weight,workflowViewerLink:n.workflowViewerLink||"",workflowViewerReadOnlyLink:n.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),r&&(h.sku=r),h},Fr=async(n,t,e,a,r,i,o,s,l,c)=>{await(async()=>{if(c!==void 0)return c;await n.outstandingRequestsPromise();const x=(k.getMap("transactionOwnerIds")||new Map).get(r.id),T=await y.getShadowGraphqlClient().query({query:_n,variables:{ids:[r.id]},fetchPolicy:"no-cache",errorPolicy:"all",context:{transactionOwnerId:x}}),et=T.data?.transactions[0].workflowState;return T.errors?(T.errors.forEach(at=>{T.errors&&console.log("Server Error:",at.message)}),null):et??null})()||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await n.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const u=n.getPreviewService(),h=t?.finalizeStepConfig?.lookAtAnimation,g=u&&t.showModelOnFinishStep&&!!h,m=l&&mn(l,t,!0),p=l&&mn(l,t,!1),f=async B=>{const x={};let O=0;if(Object.keys(i).length>0)for(const T of Object.keys(i)){const et=i[T],at=t.steps.find(H=>H.stepName===T);for(let H=0;H<et.selections.length;++H){const Y=et.selections[H];if(at&&(!B||at.option&&(at.option.variants||[]).length>1&&!at.data.hideSelectionInCart&&!at.data.hideSelectionsInCart)){const vt=at.stepTitle;x[vt]?x[vt].push({id:Y.id||"",name:Y.name,priceModifier:Y.priceModifier}):x[vt]=[{id:Y.id||"",name:Y.name,priceModifier:Y.priceModifier}]}O+=Y.priceModifier}}return[x,O]},[S]=await f(!0),b=Object.fromEntries(Object.keys(S).map(B=>[B,S[B].map(x=>x.id)])),[P]=await f(!1),C=Object.fromEntries(Object.keys(P).map(B=>[B,P[B].map(x=>x.id)]));let E=await s(g,r.id);if(E){const B=await(await it(E)).blob();E=(await R.uploadAsset({name:`${r.id}-preview-image.png`,blob:B},te.Image,!0,!1)).fileLink}return{designDetails:(()=>{const B={name:o,layouts:e.map(x=>({index:x.index,panelId:x.panelId})),workflowId:t.id,transactionId:r.id,useThreeDimPreview:!!g,previewImage:E};if(p){const x=[];for(const[O,T]of Object.entries(p))x.push({key:O,value:T});B.metadata=x}if(b){const x=[];for(const[O,T]of Object.entries(C))x.push({key:O,ids:T});B.selectedVariants=x}return B})(),cartSelectionsWithPrices:S,cartMetadata:m}},kr=async(n,t,e,a,r,i,o,s,l,c,d)=>{l("workflow.steps.finish.finalize.buildingLayouts");const{designDetails:A,cartSelectionsWithPrices:u,cartMetadata:h}=await Fr(n,t,e,a,i,o,s,c,d);l("workflow.steps.finish.finalize.creatingDesign");const g=await Fl(A),m=g?.transaction?.previewImageLink;if(!g?.transaction)throw new Error("Failed to create design");l("workflow.steps.finish.finalize.updatingTransaction");const p=g.transaction;return xr(p,r,t,u,g?.sku,h,m,g?.processExecution?.id)},Tl=async(n,t,e)=>{t("workflow.steps.finish.finalize.buildingLayouts"),await Promise.all(n.map(async s=>{await s.workflowManager.outstandingRequestsPromise()}));const r=await(async()=>{const l=await y.getShadowGraphqlClient().query({query:_n,variables:{ids:n.map(c=>c.transaction.id)},fetchPolicy:"no-cache",errorPolicy:"all"});return l.errors?(l.errors.forEach(c=>{l.errors&&console.log("Server Error:",c.message)}),null):l.data?.transactions?l.data.transactions.map(c=>c.workflowState??null):null})(),i=await Promise.all(n.map(async(s,l)=>await Fr(s.workflowManager,s.workflow,s.layouts,s.getReducerState,s.transaction,s.workflowSelections,s.designName,e??(()=>Promise.resolve(void 0)),s.workflowMetadata,r?r[l]:void 0)));t("workflow.steps.finish.finalize.creatingDesign");const o=await kl(i.map(s=>s.designDetails));if(!o)throw new Error("Failed to create designs");return t("workflow.steps.finish.finalize.updatingTransaction"),o.map((s,l)=>{const c=n[l],d=i[l],A=s.transaction;return xr(A,c.product,c.workflow,d.cartSelectionsWithPrices,s.sku,d.cartMetadata,A.previewImageLink,s.processExecution?.id)})};class Nl{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=k.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new L("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(r=>r.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(r=>r(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),r=a.find(i=>i.transactionId===t);if(!r)throw new Error(`No saved design for transaction ${t}.`);r.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){k.set(this.localPersistenceKey,JSON.stringify(t));return}throw new L("Unexpected storage method requested")}}const Ie=new Nl,Ql=w.gql`
|
2293
2293
|
mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
|
2294
2294
|
transactionAddStakeholder(id: $id, details: $details, type: $type) {
|
2295
2295
|
id
|
@@ -2303,7 +2303,7 @@
|
|
2303
2303
|
}
|
2304
2304
|
}
|
2305
2305
|
}
|
2306
|
-
`,
|
2306
|
+
`,Rl=w.gql`
|
2307
2307
|
mutation AddAddressToTransaction(
|
2308
2308
|
$transactionId: String!
|
2309
2309
|
$streetAddress: String
|
@@ -2325,13 +2325,13 @@
|
|
2325
2325
|
id
|
2326
2326
|
}
|
2327
2327
|
}
|
2328
|
-
`,
|
2328
|
+
`,Ol=w.gql`
|
2329
2329
|
mutation AddOrganizationToTransaction($transactionId: String!, $organizationName: String!) {
|
2330
2330
|
organizationAttachToTransaction(transactionId: $transactionId, organizationName: $organizationName) {
|
2331
2331
|
id
|
2332
2332
|
}
|
2333
2333
|
}
|
2334
|
-
`;var Mr=(n=>(n.QuantityChanged="QuantityChanged",n.PriceBreakChanged="PriceBreakChanged",n))(Mr||{});class Tr{constructor(t,e){if(this.cachedStepHandles=new Map,this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=In(async()=>{await Ie.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async r=>new Promise((i,o)=>{try{r.toBlob(s=>{if(s){const l=URL.createObjectURL(s);i(l)}})}catch(s){o(s)}}),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const a=e.layouts;this.commandContext=new or,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Il(this,t,e.workflow,e.product.profanities?.map(r=>r.word)||[],a,this.commandContext,r=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(r)},e.graphQlClient,e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(r=>{const i=r.traversableScenes.map(o=>{const s=o.renderableSteps.map(l=>l.stepName);return{id:o.name,title:o.title,renderableSteps:s,workflowScene:o}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(o=>o(i))}),this.currentPriceBreak=this.priceBreakToBeApplied()}async attachAddress(t,e,a,r,i,o){await this.graphQlClient().mutate({mutation:Ql,variables:{transactionId:this.getWorkflowManager().getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Rl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.workflowManager.getWorkflow(),r=a?.finalizeStepConfig?.lookAtAnimation;if(t){if(!r)throw new Error("Failed to generate cart preview image!");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,r)||""}let i=2048;e&&e<=2048&&(i=e);const o=ft(i,i),s=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(b=>b.layoutState?.layout.panelId===c?.name)||s[0],A=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},u=this.commandContext.getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Oe("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),m=We(u.layoutState.layout,u.layoutState.elements,{renderingConfiguration:{purpose:Nt.Print,region:{left:A.x,top:A.y,width:A.width,height:A.height},templatingContext:g}}),p=Rn(m);await(await ba.Pith.from(h,p,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:ft,createImage:le,DOMParser:Da(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const r=Se.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,r),r}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>Bt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(r=>{a+=r.selections.reduce((i,o)=>i+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getWorkflowManager().getProduct().basePrice||0,e);if(t){const r=this.getAdditionalProductPriceSubunits(e)||0;return a+r}return a}getAdditionalProductPriceSubunits(t){const e=this.getWorkflowManager().getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),r=t*a;return Math.ceil(r)}priceBreakToBeApplied(){const t=(this.getWorkflowManager().getProduct().priceBreaks||[]).sort((r,i)=>-(r.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((r,i)=>r+i.getQuantity(),0);for(const r of t)if(r.minQty<=a)return r.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>t.getWorkflowManager().getTransaction().id!==this.getWorkflowManager().getTransaction().id&&t.getWorkflowManager().getProduct().id===this.getWorkflowManager().getProduct().id)}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const r=await t.getGlobalProperties(),i=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),s=e.getSteps(),l=c=>r.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,A=c.getRaw().globalPropertyAspectConfigurations;A!==void 0&&(A.forEach(u=>d.add(JSON.stringify(u))),s.forEach(u=>{const h=u.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const m=l(g),p=d.has(JSON.stringify(g));if(p&&m?.getType()==="Option"){const f=u.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(p&&m?.getType()==="Text"){const f=u.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return Se.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter(e=>e.type===t).map(e=>Se.get(this.getWorkflowManager(),e))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find(a=>a.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(a=>this.getWorkflowManager().getWorkflow().steps.find(r=>r.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>Se.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:Nl,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(r=>r.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const r=k.getMap("transactionCustomerIds")||new Map;r.set(this.getWorkflowManager().getTransaction().id,a.customer.id),k.setMap("transactionCustomerIds",r)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){if(!this.getCommandContext().getState())throw new L("State undefined!");const r={title:await(async()=>{if(t)return t;const i=this.getWorkflowManager().getTransaction().id,s=(await Ie.getSavedDesigns()).find(l=>l.transactionId===i)?.title;return s||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Ie.addDesign(r),r}async copy(){const t=It(this.getCommandContext().getState());if(!t)throw new L("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflowManager().getWorkflow(),r=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!r)throw new L("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:r,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.workflowManager.getTransaction();return a.completed?(await this.graphQlClient().mutate({mutation:vo,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):kr(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),()=>this.commandContext.getState(),this.workflowManager.getProduct(),a,this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),r=>e?this.createPreviewImage(r,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==v.SilentIllustration&&t.type!==v.ProductOverlay}getExportedStepData(){const t=this.getWorkflowManager().getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),r=[];return t.steps.forEach(i=>{const o=i.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:i.stepTitle,properties:[]};if(l&&$l(i,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){r.push(c);return}switch(i.type){case v.Frame:{const d=i.data,A=s;A.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:A.image,priceModifier:0})}break;case v.Illustration:{const d=i.data,A=s;if(A&&A.colors&&A.colors.length>0&&d.displayColorsOnFinishStep){const u=A.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:u,priceModifier:0})}}break;case v.Module:{const d=i.data,A=s;A&&A.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:A.text,priceModifier:0})}break;case v.Text:{const d=i.data,A=s;A&&A.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:A.text,priceModifier:0}),A&&A.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:A.color,priceModifier:0})}}r.push(c)}),r.filter(i=>i.properties&&i.properties.length>0)}getQuantity(){return this.getWorkflowManager().getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getWorkflowManager().getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getWorkflowManager().getTransaction();await this.graphQlClient().mutate({mutation:mo,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(r=>r!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const Ol=n=>{if([v.Question,v.Frame,v.Illustration,v.Material,v.Model,v.Picture,v.Shape,v.Text].includes(n.type)){const e=n.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},$l=(n,t)=>{if(!Ol(n))return!1;if(n.option&&(n.option.variants||[]).length>1){const e=t[n.stepName];return!!(e&&e.selections.length>0)}return!1},Ul=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],Ll=async(n,t,e)=>{const a=t.data,r=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),o=r.slice(0,4)==="http"?"":"https://",s=new URL(o+r);s.searchParams.append("video",nn(JSON.stringify([{href:i}]))),s.pathname=s.pathname+(s.pathname.slice(-1)==="/"?"":"/");const l=s.toString(),d=`data:image/svg+xml;base64,${nn(await Bn.toString(l,{type:"svg"}))}`,A=h=>{const g=n.find(p=>p.panelId===h.panelId);if(!g)throw new j(h);const m=M();return new z({id:m,src:d,type:F.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},u=e.data.regions;try{return u.map(A)}catch(h){return console.error(h),[]}},Vl=async(n,t,e,a)=>{const r=e.data,i=r.assetUrl,o=await pa(i);try{const s=gs(r,a.option);s&&(t[a.stepName]={selectedVariants:[s]});const l=async c=>{const d=await lr(c,s?.asset?.fileLink),A=await he(d),u=M(),h=n.find(m=>m.panelId===c.panelId);if(!h)throw new j(c);const g=Na(o,A,{scale:r.scale,left:r.x,top:r.y},a.data.forceImageCover);return[new z({id:u,path:A.path,type:F.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/A.width,scaleY:c.height/A.height,pattern:{id:`${u}-pattern`,src:o.src,x:g.x,y:g.y,width:o.width,height:o.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:o.svg,colors:o.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(s){return console.error(s),[]}},zl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(C=>C.id===r.illustrationVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.illustrationVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.illustrationVariantId}`),[];const l=await tt(s,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],A=d?.length>0?d[0]:"",g=lt().parseFromString(A,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Ve(g);const m={};Ot(g,C=>{Ul.includes(C.tagName)&&!C.attributes.getNamedItem("fill")&&C.setAttribute("fill","#000000");const E=C.attributes.getNamedItem("fill");if(E&&E.value!=="none"){const B=E.value,O=`spiff-fill-${B.replace(/\W/g,"")}`;C.classList.add(O),m[O]={browserValue:B}}const D=C.attributes.getNamedItem("stroke");if(D&&D.value!=="none"){const B=D.value,O=`spiff-stroke-${B.replace(/\W/g,"")}`;C.classList.add(O),m[O]={browserValue:B}}});const f=St().serializeToString(g),S=r.colors;if(S){for(const[C,E]of Object.entries(m))for(const D of Object.keys(S))if(E.browserValue===D){m[C]={browserValue:S[D]};break}}const b=C=>{const E=n.find(B=>B.panelId===C.panelId);if(!E)throw new j(C);const D=M();return new z({colors:m,id:D,svg:f,type:F.Illustration,y:C.top,x:C.left,rotation:C.rotation,width:C.width,height:C.height,layer:C.layer,layerIndex:C.layerIndex,immutable:C.immutable},E)},P=a.data.regions;try{return P.map(b)}catch(C){return console.error(C),[]}},ql=async(n,t,e)=>{const a=await fr(e.data.module),r=t.data,i=(s,l)=>{const c=n.find(A=>A.panelId===l.panelId);if(!c)throw new j(l);const d=M();return new z({colors:{},id:d,svg:s,type:F.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},o=e.data.regions;try{return o.map(s=>i(a.svgPrint(r.text,s),s))}catch(s){return console.error(s),[]}},Gl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(d=>d.id===r.pictureVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.pictureVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.pictureVariantId}`),[];const l=d=>{const A=n.find(h=>h.panelId===d.panelId);if(!A)throw new j(d);const u=M();return new z({id:u,src:s,type:F.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},A)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},Wl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(c=>c.id===r.colorVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.colorVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=c=>{const d=n.find(m=>m.panelId===c.panelId);if(!d)throw new j(c);const A=`
|
2334
|
+
`;var Mr=(n=>(n.QuantityChanged="QuantityChanged",n.PriceBreakChanged="PriceBreakChanged",n))(Mr||{});class Tr{constructor(t,e){if(this.cachedStepHandles=new Map,this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=In(async()=>{await Ie.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async r=>new Promise((i,o)=>{try{r.toBlob(s=>{if(s){const l=URL.createObjectURL(s);i(l)}})}catch(s){o(s)}}),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const a=e.layouts;this.commandContext=new or,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Pl(this,t,e.workflow,e.product.profanities?.map(r=>r.word)||[],a,this.commandContext,r=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(r)},e.graphQlClient,e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(r=>{const i=r.traversableScenes.map(o=>{const s=o.renderableSteps.map(l=>l.stepName);return{id:o.name,title:o.title,renderableSteps:s,workflowScene:o}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(o=>o(i))}),this.currentPriceBreak=this.priceBreakToBeApplied()}async attachAddress(t,e,a,r,i,o){await this.graphQlClient().mutate({mutation:Rl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Ol,variables:{transactionId:this.getWorkflowManager().getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.workflowManager.getWorkflow(),r=a?.finalizeStepConfig?.lookAtAnimation;if(t){if(!r)throw new Error("Failed to generate cart preview image!");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,r)||""}let i=2048;e&&e<=2048&&(i=e);const o=ft(i,i),s=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(b=>b.layoutState?.layout.panelId===c?.name)||s[0],A=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},u=this.commandContext.getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Oe("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),m=We(u.layoutState.layout,u.layoutState.elements,{renderingConfiguration:{purpose:Nt.Print,region:{left:A.x,top:A.y,width:A.width,height:A.height},templatingContext:g}}),p=Rn(m);await(await ba.Pith.from(h,p,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:ft,createImage:le,DOMParser:Da(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const r=Se.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,r),r}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>Bt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(r=>{a+=r.selections.reduce((i,o)=>i+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getWorkflowManager().getProduct().basePrice||0,e);if(t){const r=this.getAdditionalProductPriceSubunits(e)||0;return a+r}return a}getAdditionalProductPriceSubunits(t){const e=this.getWorkflowManager().getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),r=t*a;return Math.ceil(r)}priceBreakToBeApplied(){const t=(this.getWorkflowManager().getProduct().priceBreaks||[]).sort((r,i)=>-(r.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((r,i)=>r+i.getQuantity(),0);for(const r of t)if(r.minQty<=a)return r.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>t.getWorkflowManager().getTransaction().id!==this.getWorkflowManager().getTransaction().id&&t.getWorkflowManager().getProduct().id===this.getWorkflowManager().getProduct().id)}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const r=await t.getGlobalProperties(),i=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),s=e.getSteps(),l=c=>r.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,A=c.getRaw().globalPropertyAspectConfigurations;A!==void 0&&(A.forEach(u=>d.add(JSON.stringify(u))),s.forEach(u=>{const h=u.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const m=l(g),p=d.has(JSON.stringify(g));if(p&&m?.getType()==="Option"){const f=u.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(p&&m?.getType()==="Text"){const f=u.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return Se.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter(e=>e.type===t).map(e=>Se.get(this.getWorkflowManager(),e))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find(a=>a.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(a=>this.getWorkflowManager().getWorkflow().steps.find(r=>r.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>Se.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:Ql,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(r=>r.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const r=k.getMap("transactionCustomerIds")||new Map;r.set(this.getWorkflowManager().getTransaction().id,a.customer.id),k.setMap("transactionCustomerIds",r)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){if(!this.getCommandContext().getState())throw new L("State undefined!");const r={title:await(async()=>{if(t)return t;const i=this.getWorkflowManager().getTransaction().id,s=(await Ie.getSavedDesigns()).find(l=>l.transactionId===i)?.title;return s||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Ie.addDesign(r),r}async copy(){const t=It(this.getCommandContext().getState());if(!t)throw new L("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflowManager().getWorkflow(),r=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!r)throw new L("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:r,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.workflowManager.getTransaction();return a.completed?(await this.graphQlClient().mutate({mutation:vo,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):kr(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),()=>this.commandContext.getState(),this.workflowManager.getProduct(),a,this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),r=>e?this.createPreviewImage(r,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==v.SilentIllustration&&t.type!==v.ProductOverlay}getExportedStepData(){const t=this.getWorkflowManager().getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),r=[];return t.steps.forEach(i=>{const o=i.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:i.stepTitle,properties:[]};if(l&&Ul(i,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){r.push(c);return}switch(i.type){case v.Frame:{const d=i.data,A=s;A.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:A.image,priceModifier:0})}break;case v.Illustration:{const d=i.data,A=s;if(A&&A.colors&&A.colors.length>0&&d.displayColorsOnFinishStep){const u=A.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:u,priceModifier:0})}}break;case v.Module:{const d=i.data,A=s;A&&A.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:A.text,priceModifier:0})}break;case v.Text:{const d=i.data,A=s;A&&A.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:A.text,priceModifier:0}),A&&A.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:A.color,priceModifier:0})}}r.push(c)}),r.filter(i=>i.properties&&i.properties.length>0)}getQuantity(){return this.getWorkflowManager().getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getWorkflowManager().getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getWorkflowManager().getTransaction();await this.graphQlClient().mutate({mutation:mo,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(r=>r!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const $l=n=>{if([v.Question,v.Frame,v.Illustration,v.Material,v.Model,v.Picture,v.Shape,v.Text].includes(n.type)){const e=n.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Ul=(n,t)=>{if(!$l(n))return!1;if(n.option&&(n.option.variants||[]).length>1){const e=t[n.stepName];return!!(e&&e.selections.length>0)}return!1},Ll=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],Vl=async(n,t,e)=>{const a=t.data,r=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),o=r.slice(0,4)==="http"?"":"https://",s=new URL(o+r);s.searchParams.append("video",nn(JSON.stringify([{href:i}]))),s.pathname=s.pathname+(s.pathname.slice(-1)==="/"?"":"/");const l=s.toString(),d=`data:image/svg+xml;base64,${nn(await Bn.toString(l,{type:"svg"}))}`,A=h=>{const g=n.find(p=>p.panelId===h.panelId);if(!g)throw new j(h);const m=M();return new z({id:m,src:d,type:F.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},u=e.data.regions;try{return u.map(A)}catch(h){return console.error(h),[]}},zl=async(n,t,e,a)=>{const r=e.data,i=r.assetUrl,o=await pa(i);try{const s=gs(r,a.option);s&&(t[a.stepName]={selectedVariants:[s]});const l=async c=>{const d=await lr(c,s?.asset?.fileLink),A=await he(d),u=M(),h=n.find(m=>m.panelId===c.panelId);if(!h)throw new j(c);const g=Na(o,A,{scale:r.scale,left:r.x,top:r.y},a.data.forceImageCover);return[new z({id:u,path:A.path,type:F.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/A.width,scaleY:c.height/A.height,pattern:{id:`${u}-pattern`,src:o.src,x:g.x,y:g.y,width:o.width,height:o.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:o.svg,colors:o.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(s){return console.error(s),[]}},ql=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(C=>C.id===r.illustrationVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.illustrationVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.illustrationVariantId}`),[];const l=await tt(s,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],A=d?.length>0?d[0]:"",g=lt().parseFromString(A,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Ve(g);const m={};Ot(g,C=>{Ll.includes(C.tagName)&&!C.attributes.getNamedItem("fill")&&C.setAttribute("fill","#000000");const E=C.attributes.getNamedItem("fill");if(E&&E.value!=="none"){const B=E.value,O=`spiff-fill-${B.replace(/\W/g,"")}`;C.classList.add(O),m[O]={browserValue:B}}const D=C.attributes.getNamedItem("stroke");if(D&&D.value!=="none"){const B=D.value,O=`spiff-stroke-${B.replace(/\W/g,"")}`;C.classList.add(O),m[O]={browserValue:B}}});const f=St().serializeToString(g),S=r.colors;if(S){for(const[C,E]of Object.entries(m))for(const D of Object.keys(S))if(E.browserValue===D){m[C]={browserValue:S[D]};break}}const b=C=>{const E=n.find(B=>B.panelId===C.panelId);if(!E)throw new j(C);const D=M();return new z({colors:m,id:D,svg:f,type:F.Illustration,y:C.top,x:C.left,rotation:C.rotation,width:C.width,height:C.height,layer:C.layer,layerIndex:C.layerIndex,immutable:C.immutable},E)},P=a.data.regions;try{return P.map(b)}catch(C){return console.error(C),[]}},Gl=async(n,t,e)=>{const a=await fr(e.data.module),r=t.data,i=(s,l)=>{const c=n.find(A=>A.panelId===l.panelId);if(!c)throw new j(l);const d=M();return new z({colors:{},id:d,svg:s,type:F.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},o=e.data.regions;try{return o.map(s=>i(a.svgPrint(r.text,s),s))}catch(s){return console.error(s),[]}},Wl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(d=>d.id===r.pictureVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.pictureVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.pictureVariantId}`),[];const l=d=>{const A=n.find(h=>h.panelId===d.panelId);if(!A)throw new j(d);const u=M();return new z({id:u,src:s,type:F.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},A)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},jl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(c=>c.id===r.colorVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.colorVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=c=>{const d=n.find(m=>m.panelId===c.panelId);if(!d)throw new j(c);const A=`
|
2335
2335
|
<svg
|
2336
2336
|
xmlns="http://www.w3.org/2000/svg"
|
2337
2337
|
xmlnsXlink="http://www.w3.org/1999/xlink"
|
@@ -2351,8 +2351,8 @@
|
|
2351
2351
|
fill="${o?.color}"
|
2352
2352
|
/>
|
2353
2353
|
</svg>
|
2354
|
-
`,h={"spiff-fill-shape":{browserValue:o.color||"#000000"}},g=M();return new z({colors:h,id:g,svg:A,type:F.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(s)}catch(c){return console.error(c),[]}},
|
2355
|
-
`)},f))}else r.push(new z(S,f))}return r},Yl=(n,t)=>n.conditions?n.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const r=a.selectedVariants;return e.requiredVariantSelections.some(i=>r.find(o=>o.id===i)!==void 0)}return!1}):!0,Nr=async(n,t,e,a)=>{const r=[],i={};for(const o of n){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case v.DigitalContent:r.push(...await Ll(e,o,s));break;case v.Frame:case v.Photo:r.push(...await Vl(e,i,o,s));break;case v.Illustration:r.push(...await zl(e,i,o,s));break;case v.Module:r.push(...await ql(e,o,s));break;case v.Picture:r.push(...await Gl(e,i,o,s));break;case v.Shape:r.push(...await Wl(e,i,o,s));break;case v.Text:r.push(...await Hl(e,i,o,s));break}}for(const o of t.steps)o.type!==v.SilentIllustration&&o.type!==v.ProductOverlay||Yl(o,i)&&r.push(...await jl(e,o,a));return r};class Jl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Xl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Kl=()=>new Promise((n,t)=>{try{const a=ft().getContext("webgl2");n(!!a)}catch{n(!1)}}),_l=Kl();class Xl{constructor(t,e,a,r,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Ma(2),this.id=t,this.name=e,this.service=a,this.panelSize=r,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=It(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Zl(this.getID(),a,await _l,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Zl extends ka{constructor(t,e,a,r,i,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=r,this.layouts=i,this.getWorkflowManager=o}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,r=e/t.height,i=Math.min(a,r);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(g=>g.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,r=t.layoutState.layout.height,i=a===1||r===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=i.width,s=i.height;let l,c;if(this.nonPOTSupport){const g=o/s;a/r<g?(l=o,c=r*(o/a)):(l=a*(s/r),c=s);const p=this.resizeFit({width:l,height:c});l=p.width,c=p.height}else l=i.width,c=i.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),A=We(t.layoutState.layout,e,{renderingConfiguration:{purpose:Nt.ThreeD,templatingContext:d}}),u=Rn(A),h=await ba.Pith.from(this.ctx,u,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:ft,createImage:le,DOMParser:Da(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const tc=(n,t)=>{const e=[];return n.forEach(a=>{const r=t.steps.find(i=>i.stepName===a.stepName);r?.type===v.Text&&a.stepAspectType==="Text"&&e.push({name:r.stepName,data:{text:a.value}})}),e},ec=async(n,t,e,a)=>{let r={serializableWorkflow:{steps:[]},layouts:{}};r=new Q(e.map(l=>new Oa(l))).apply(r);const o=await Nr(n,t,e,a);return new Q(o).apply(r)};class ac{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(e=>this.getHandle(e)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const r=e.aspects.find(i=>i.name===a.targetAspectName);return r?a.requiredVariantSelections.some(i=>i===r.value):!1})}async createHandle(t){switch(t.type){case U.FileUpload:return new Qr(this.bundle,t).initialize();case U.ColorOption:return new ya(this.bundle,t,t.entityId?await W.getOption(t.entityId):void 0);case U.Option:{const e=t.entityId?await W.getOption(t.entityId):void 0;return e?.type==="Color"?new ya(this.bundle,t,e):new Wa(this.bundle,t,e)}case U.Text:return new Rr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class je{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(r=>r.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Qr extends je{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await W.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await tt(t?.fileLink),a=await Qa(t?.fileLink),r=a.width,i=a.height,o=await ot(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:r,height:i,aspect:r/i,svg:o.svg,colors:o.colors};dt.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Qe.BackgroundRemover)}async removeBackgroundFromImage(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.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),r=await R.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:r.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,r.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(r,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),r}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return R.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Le(ze(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return R.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return R.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),r=a.getAspectStorage(this.property.name);if(r?.useOriginalAsset===t)return;const i={...r,useOriginalAsset:t},o=t?r?.originalAssetKey:r?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",i)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await R.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(r){if(this.updateSharedStepStorage({...r}),r.colors){const i=new Map(r.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(a)});const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...r,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,r=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,r)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(r=>{if(r.getOverrideGlobalPropertyConfiguration(this.property.type))return;r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(r.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Rr extends je{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const r=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(r)}}class Wa extends je{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new rt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new rt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new rt(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new rt(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(r=>r.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const r=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(r)}}class ya extends Wa{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(i=>i.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;r&&this.setCustomColor(r)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(o=>{switch(o.getType()){case v.Shape:return o.selectVariant(t);case v.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case v.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getCurrentVariant()?.getColor()&&this.getCurrentVariant().getColor().toLowerCase()==="#custom"&&this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const nc=(n,t,e,a)=>n.flatMap(r=>r.getSteps()).filter(r=>r.getGlobalPropertyAspects(t).includes(e)&&r.getType()===a),rc=(n,t,e)=>{const r=nc(n,t,e,v.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...r)};function Sa(n,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!oc(a))return a;if(Array.isArray(a))return Sa(a,t);let r={};for(const[i,o]of Object.entries(a))r[i]=ic(o)?o:Sa(o,t);return gi(r,t)}return Array.isArray(n)?n.map(e):e(n)}function ic(n){return n==null}function oc(n){return typeof n=="object"&&!Array.isArray(n)&&n!==null}function Or(n){const t=new Map;return n?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function ve(n){return Sa(n,["__typename"])}class sc{constructor(t,e,a,r,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=ve(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=ve(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=r}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=Or(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=It(this.globalPropertyState);this.globalPropertyState={...ve(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(r=>r.name===t&&r.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,r){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=It(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(r){const l=s.find(c=>c.channel===r);if(l)l.value=e,l.type=i.type,l.channel=r,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(r===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r})}}else{const l=s[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r});De(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const r=this.configuration.aspects.find(s=>s.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=It(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=r.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=r.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:r.type,storage:e!==null?e:void 0,channel:a});De(i,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:Ys,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case U.FileUpload:{a.fileUpload=e.storage;break}case U.Option:{a.option=e.storage;break}case U.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=ve(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Hs,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class lc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const r=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=r.position,i.rotation=r.rotation,i.scale=r.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const r=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===r);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:r,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,r=this.state.transactions.find(l=>l.transactionId===a),i=r?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,r.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const cc=w.gql`
|
2354
|
+
`,h={"spiff-fill-shape":{browserValue:o.color||"#000000"}},g=M();return new z({colors:h,id:g,svg:A,type:F.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(s)}catch(c){return console.error(c),[]}},Hl=async(n,t,e)=>{const a=[],i=t.type===v.ProductOverlay?e||t.data.asset?.fileLink||"":t.data.asset?.fileLink||"",s=i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?F.Image:(i.endsWith(".svg"),F.Illustration),l=t.data.regions;if(s==="image")try{l.forEach(c=>{const d=n.find(u=>u.panelId===c.panelId);if(!d)throw new j(c);const A={id:M(),src:i,type:s,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===v.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new z(A,d))})}catch(c){console.error(c)}else{const c=await tt(i,!0),d=A=>{const u=/<svg.*?<\/svg>/s,h=A.match(u)||[],g=h?.length>0?h[0]:"",f=lt().parseFromString(g,"image/svg+xml").firstElementChild;if(!f)throw new bt("Failed to read SVG.");return Ve(f),St().serializeToString(f)};l.forEach(A=>{const u=n.find(g=>g.panelId===A.panelId);if(!u)throw new j(A);const h={id:M(),src:i,asset_key:i,svg:d(c),colors:{},type:s,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,scaleX:1,scaleY:1,rotation:A.rotation,productOverlay:t.type===v.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new z(h,u))})}return a},Yl=async(n,t,e,a)=>{const r=[],i=e.data,o=30,s=p=>p.vertical?"center":p.textAlign||"center",l=()=>{const p=a.option;if(!p)return;const f=p.variants?.find(b=>b.id===i.fontVariantId)||ue(p);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const S=f.asset.fileLink;if(S)return S},d=await(async()=>{const p=l();if(!p)return;const f=await Dt(p);return{assetUrl:p,name:f.names.fullName.en}})(),A=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",i.text):i.text)||"",u=ke(A,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async p=>{const f=p.colorOption;return f?W.getDefaultVariant(f)?.color:void 0},g=i.color||await h(a.data),m=a.data.regions;for(const p of m){const f=n.find(b=>b.panelId===p.panelId);if(!f)continue;const S={stepName:e.name,id:M(),align:s(a.data),curved:a.data.curved,fill:i.color||g||"#000000",fontData:d,fontSize:a.data.size||o,height:p.height,layer:p.layer,layerIndex:p.layerIndex,paths:a.data.paths,rotation:p.rotation,text:u,type:F.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:p.width,x:p.left,y:p.top};if(d){const[b,P]=Kt(a.data.size||o,d,p,[ke(u,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});r.push(new z({...S,fontSize:b,text:S.curved?S.text:(P||[]).join(`
|
2355
|
+
`)},f))}else r.push(new z(S,f))}return r},Jl=(n,t)=>n.conditions?n.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const r=a.selectedVariants;return e.requiredVariantSelections.some(i=>r.find(o=>o.id===i)!==void 0)}return!1}):!0,Nr=async(n,t,e,a)=>{const r=[],i={};for(const o of n){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case v.DigitalContent:r.push(...await Vl(e,o,s));break;case v.Frame:case v.Photo:r.push(...await zl(e,i,o,s));break;case v.Illustration:r.push(...await ql(e,i,o,s));break;case v.Module:r.push(...await Gl(e,o,s));break;case v.Picture:r.push(...await Wl(e,i,o,s));break;case v.Shape:r.push(...await jl(e,i,o,s));break;case v.Text:r.push(...await Yl(e,i,o,s));break}}for(const o of t.steps)o.type!==v.SilentIllustration&&o.type!==v.ProductOverlay||Jl(o,i)&&r.push(...await Hl(e,o,a));return r};class Kl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Zl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const _l=()=>new Promise((n,t)=>{try{const a=ft().getContext("webgl2");n(!!a)}catch{n(!1)}}),Xl=_l();class Zl{constructor(t,e,a,r,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Ma(2),this.id=t,this.name=e,this.service=a,this.panelSize=r,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=It(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new tc(this.getID(),a,await Xl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class tc extends ka{constructor(t,e,a,r,i,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=r,this.layouts=i,this.getWorkflowManager=o}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,r=e/t.height,i=Math.min(a,r);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(g=>g.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,r=t.layoutState.layout.height,i=a===1||r===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=i.width,s=i.height;let l,c;if(this.nonPOTSupport){const g=o/s;a/r<g?(l=o,c=r*(o/a)):(l=a*(s/r),c=s);const p=this.resizeFit({width:l,height:c});l=p.width,c=p.height}else l=i.width,c=i.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),A=We(t.layoutState.layout,e,{renderingConfiguration:{purpose:Nt.ThreeD,templatingContext:d}}),u=Rn(A),h=await ba.Pith.from(this.ctx,u,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:ft,createImage:le,DOMParser:Da(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const ec=(n,t)=>{const e=[];return n.forEach(a=>{const r=t.steps.find(i=>i.stepName===a.stepName);r?.type===v.Text&&a.stepAspectType==="Text"&&e.push({name:r.stepName,data:{text:a.value}})}),e},ac=async(n,t,e,a)=>{let r={serializableWorkflow:{steps:[]},layouts:{}};r=new Q(e.map(l=>new Oa(l))).apply(r);const o=await Nr(n,t,e,a);return new Q(o).apply(r)};class nc{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(e=>this.getHandle(e)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const r=e.aspects.find(i=>i.name===a.targetAspectName);return r?a.requiredVariantSelections.some(i=>i===r.value):!1})}async createHandle(t){switch(t.type){case U.FileUpload:return new Qr(this.bundle,t).initialize();case U.ColorOption:return new ya(this.bundle,t,t.entityId?await W.getOption(t.entityId):void 0);case U.Option:{const e=t.entityId?await W.getOption(t.entityId):void 0;return e?.type==="Color"?new ya(this.bundle,t,e):new Wa(this.bundle,t,e)}case U.Text:return new Rr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class je{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(r=>r.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Qr extends je{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await W.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await tt(t?.fileLink),a=await Qa(t?.fileLink),r=a.width,i=a.height,o=await ot(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:r,height:i,aspect:r/i,svg:o.svg,colors:o.colors};dt.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Qe.BackgroundRemover)}async removeBackgroundFromImage(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.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),r=await R.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:r.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,r.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(r,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),r}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return R.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Le(ze(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return R.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return R.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),r=a.getAspectStorage(this.property.name);if(r?.useOriginalAsset===t)return;const i={...r,useOriginalAsset:t},o=t?r?.originalAssetKey:r?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",i)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await R.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(r){if(this.updateSharedStepStorage({...r}),r.colors){const i=new Map(r.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(a)});const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...r,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,r=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,r)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(r=>{if(r.getOverrideGlobalPropertyConfiguration(this.property.type))return;r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(r.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Rr extends je{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const r=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(r)}}class Wa extends je{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new rt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new rt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new rt(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new rt(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(r=>r.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const r=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(r)}}class ya extends Wa{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(i=>i.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;r&&this.setCustomColor(r)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(o=>{switch(o.getType()){case v.Shape:return o.selectVariant(t);case v.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case v.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getCurrentVariant()?.getColor()&&this.getCurrentVariant().getColor().toLowerCase()==="#custom"&&this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const rc=(n,t,e,a)=>n.flatMap(r=>r.getSteps()).filter(r=>r.getGlobalPropertyAspects(t).includes(e)&&r.getType()===a),ic=(n,t,e)=>{const r=rc(n,t,e,v.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...r)};function Sa(n,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!sc(a))return a;if(Array.isArray(a))return Sa(a,t);let r={};for(const[i,o]of Object.entries(a))r[i]=oc(o)?o:Sa(o,t);return gi(r,t)}return Array.isArray(n)?n.map(e):e(n)}function oc(n){return n==null}function sc(n){return typeof n=="object"&&!Array.isArray(n)&&n!==null}function Or(n){const t=new Map;return n?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function ve(n){return Sa(n,["__typename"])}class lc{constructor(t,e,a,r,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=ve(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=ve(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=r}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=Or(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=It(this.globalPropertyState);this.globalPropertyState={...ve(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(r=>r.name===t&&r.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,r){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=It(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(r){const l=s.find(c=>c.channel===r);if(l)l.value=e,l.type=i.type,l.channel=r,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(r===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r})}}else{const l=s[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r});De(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const r=this.configuration.aspects.find(s=>s.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=It(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=r.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=r.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:r.type,storage:e!==null?e:void 0,channel:a});De(i,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:Ys,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case U.FileUpload:{a.fileUpload=e.storage;break}case U.Option:{a.option=e.storage;break}case U.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=ve(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Hs,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class cc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const r=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=r.position,i.rotation=r.rotation,i.scale=r.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const r=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===r);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:r,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,r=this.state.transactions.find(l=>l.transactionId===a),i=r?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,r.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const dc=w.gql`
|
2356
2356
|
query GetManyMetafields($entityIds: [String!]!) {
|
2357
2357
|
metafieldsMany(entityIds: $entityIds) {
|
2358
2358
|
id
|
@@ -2363,14 +2363,14 @@
|
|
2363
2363
|
}
|
2364
2364
|
}
|
2365
2365
|
}
|
2366
|
-
`;class
|
2366
|
+
`;class Ac{constructor(){this.internalMap=new Map}async requestKeysForEntity(t,e){const a=new Map;return await this.ensureIdsArePresent([t]),e.forEach(r=>{const i=this.requestKeyForEntityIfAvailable(t,r);i&&a.set(r,i)}),a}async ensureIdsArePresent(t){if(t.every(a=>this.internalMap.has(a)))return;const e=await y.getShadowGraphqlClient().query({query:dc,errorPolicy:"all",variables:{entityIds:t.filter(a=>!this.internalMap.has(a))}});t.forEach((a,r)=>{const i=e.data.metafieldsMany[r];this.internalMap.set(a,i.map(o=>({key:o.metafieldConfiguration.name,value:o.value})))})}async requestKeyForEntity(t,e){if(!this.internalMap.has(t))return;let a=this.internalMap.get(t);const r=a.find(i=>i.key===e);return r||(await this.ensureIdsArePresent([t]),a=this.internalMap.get(t)),r?JSON.parse(r.value):void 0}requestKeyForEntityIfAvailable(t,e){if(!this.internalMap.has(t))return;const r=this.internalMap.get(t).find(i=>i.key===e);if(r)return JSON.parse(r.value)}}const $r=new Ac;var Ur=(n=>(n.Default="Default",n.Name="Name",n.Price="Price",n))(Ur||{});class ja{constructor(t){this.fullFetched=!1,this.collection=t;const e=this.collection.productCollectionProducts;e&&e.length>0&&(this.fullFetched=!0)}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getDispatchStartDate(){if(this.collection.dispatchStartDate)return new Date(this.collection.dispatchStartDate)}getDispatchEndDate(){if(this.collection.dispatchEndDate)return new Date(this.collection.dispatchEndDate)}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.filter(t=>!!t.product).map(t=>new Ht(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new Ht(a));const e=await y.getShadowGraphqlClient().query({query:tl,variables:{id:this.getId(),productIds:t},errorPolicy:"all"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new Ht(a))}async filterProducts(t,e,a,r){const i=await y.getShadowGraphqlClient().query({query:el,errorPolicy:"all",variables:{id:this.getId(),filters:t?{link:"And",metafields:t}:void 0,tags:e?{include:e.include??[],exclude:e.exclude??[]}:void 0,sortKey:a,sortDescending:r}});if(!i.data?.productCollections||i.data?.productCollections.length===0)throw new Error("Failed to filter product collection products.");const o=this.getProducts(),s=i.data.productCollections[0].productCollectionProducts.map(l=>l.product.id);return o.filter(l=>s.includes(l.getId()))}async fetchProductsFeed(t,e,a,r,i,o,s,l){if(this.fullFetched){const u=await(a?this.filterProducts(a):this.fetchProducts());return{total:u.length,items:u.slice(t,t+e)}}const c=new AbortController,{signal:d}=c,A=y.getShadowGraphqlClient().watchQuery({query:al,variables:{id:this.getId(),limit:e,offset:t,productFilters:a?{link:"And",metafields:a}:void 0,productWorkflowFilters:l?{link:"And",metafields:l}:void 0,tags:r?{include:r.include??[],exclude:r.exclude??[]}:void 0,sortKey:i,sortDescending:o,quickSearch:s},errorPolicy:"all",fetchPolicy:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:d}}});return new Promise(u=>{let h=!1;const g=A.subscribe({next(m){if(h||m.partial&&(!m.data.productCollections||m.data.productCollections.length===0||!m.data.productCollections[0].productCollectionProductsFeed?.items||m.data.productCollections[0].productCollectionProductsFeed?.items.length===0))return;c.abort(),h=!0,g.unsubscribe();const p=m.data.productCollections?.[0].productCollectionProductsFeed?.items.filter(f=>!!f.product).map(f=>new Ht(It(f)))||[];u({items:p,total:m.data.productCollections?.[0].productCollectionProductsFeed?.total??0})},error(){h||(h=!0,g.unsubscribe(),u({items:[],total:0}))}})})}getTransformCollection(){if(this.collection.transformCollection)return new Lr(this.collection.transformCollection)}getResource(){return this.collection}}class Ht{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const r=(this.product.integrationProducts||[]).find(i=>{const o=i.integration?.type,s=i.integration?.type===t,l=e?i.integration?.externalIntegrationId===e:!0;return o&&s&&l});if(!r)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return r}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(a=>a.integration?.isCurrent);if(!e)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return e}getDefaultWorkflow(){const t=this.product.workflows;if(t===void 0)throw new gt("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new gt("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const e=this.productResource.workflowId;if(e){const a=t.find(r=>r.workflowName===e);if(a)return new Tt(a)}if(t.length===1)return console.warn("Called getDefaultWorkflow() but no default was configured. There is only one workflow available so we will fall back to using this!"),new Tt(t[0]);throw new gt("Called getDefaultWorkflow() but no default workflow is configured for the requested product. Multiple workflows exist so we can't assume!")}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new gt("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.product.workflows.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){const e=this.product.basePrice||0;if(!t)return e;if(!t.integrationType&&!t.externalId&&!t.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let a;return t.integrationId?a=this.product.integrationProducts?.find(r=>r.integration?.id===t.integrationId):t.externalId?a=this.product.integrationProducts?.find(r=>r.integration?.externalIntegrationId===t.externalId):a=this.product.integrationProducts?.find(r=>r.integration?.type===t.integrationType),a?.additionalIntegrationProduct?.product?e+(a.additionalIntegrationProduct.product.basePrice||0):e}async requestMetafields(t){return $r.requestKeysForEntity(this.product.id,t)}}class Tt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Lr{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new Vr(t))}}class Vr{constructor(t){this.transform=t}getId(){return this.transform.id}getName(){return this.transform.name}get(){return{position:this.transform.position,rotation:this.transform.rotation,scale:this.transform.scale}}}const uc=w.gql`
|
2367
2367
|
${me(!1)}
|
2368
2368
|
query GetProductCollections($ids: [String!]!) {
|
2369
2369
|
productCollections(ids: $ids) {
|
2370
2370
|
...ProductCollectionFields
|
2371
2371
|
}
|
2372
2372
|
}
|
2373
|
-
`,
|
2373
|
+
`,hc=async n=>(await y.getShadowGraphqlClient().query({query:uc,errorPolicy:"all",variables:{ids:n}})).data?.productCollections?.map(e=>new ja(e));class gc{constructor(){this.listeners={}}on(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}off(t,e){this.listeners[t]&&(this.listeners[t]=this.listeners[t].filter(a=>a!==e))}emit(t,e){if(this.listeners[t])for(const a of this.listeners[t])a(e)}clear(t){if(t)delete this.listeners[t];else for(const e in this.listeners)delete this.listeners[e]}}const mc=w.gql`
|
2374
2374
|
mutation AddAddressToBundle(
|
2375
2375
|
$bundleId: String!
|
2376
2376
|
$streetAddress: String
|
@@ -2392,26 +2392,26 @@
|
|
2392
2392
|
id
|
2393
2393
|
}
|
2394
2394
|
}
|
2395
|
-
`,
|
2395
|
+
`,pc=w.gql`
|
2396
2396
|
mutation AddOrganizationToBundle($bundleId: String!, $organizationName: String!) {
|
2397
2397
|
organizationAttachToBundle(bundleId: $bundleId, organizationName: $organizationName) {
|
2398
2398
|
id
|
2399
2399
|
}
|
2400
2400
|
}
|
2401
|
-
`,
|
2401
|
+
`,fc=w.gql`
|
2402
2402
|
mutation GenerateQuoteId($id: String!) {
|
2403
2403
|
bundleGenerateQuoteId(id: $id) {
|
2404
2404
|
id
|
2405
2405
|
quoteId
|
2406
2406
|
}
|
2407
2407
|
}
|
2408
|
-
`;class ra{constructor(t,e,a,r,i,o){this.workflowExperiences=[],this.eventEmitter=new hc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new lc(e.bundleStateData);const s=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=s?.id,this.globalPropertyStateManager=new sc(this.id,this.ownerId,s,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new ac(this),this.setPreviewService(a);const l=new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const A=this.globalPropertyStateManager.getGlobalPropertyState();A?this.globalPropertyHandleService.getHandles().then(u=>{const h=u.map(g=>{if(g.getType()===U.ColorOption||g.getType()===U.Option){const m=g;if(!A.aspects.find(f=>f.name===m.getName()))return m.initDefaultVariant()}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactions?.map(c=>c.id)||[],{...r,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:pc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,r,i,o){await y.getShadowGraphqlClient().mutate({mutation:gc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:mc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const r=a?.name;this.getGlobalPropertyStateManager().setAspect(r,a.value)}for(const a of t.aspects){const r=a?.name,i=e.find(o=>o.getName()===r);if(i)switch(a.type){case U.FileUpload:{const o=i,s=await xe([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case U.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case U.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case U.Text:{await i.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===U.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,r)=>a+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new ja(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(v.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===U.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=rc(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",r),d=[...new Set(s.map(u=>u.number))];if(d.length>c)for(const u of d){const h=this.getGlobalPropertyStateManager(),g=l.find(m=>m.channelNumber===u);g&&await h.setAspect(r,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getWorkflowManager().getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getWorkflowManager().getTransaction().id).join(", "));const r=k.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await y.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(k.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const r=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(r.setBundle(void 0),this.previewService&&r.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),r.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(r=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===r.id));if(e.some(r=>r===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((r,i)=>e[i]===-1).map(r=>r.id).join(", "));const a=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===r.id),1)[0]);a.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&a.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await y.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,transactionIds:t.map(r=>r.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,i])=>({key:r,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(r=>r.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const r=await this.getGlobalProperties();await Promise.all(r.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,details:t,type:e||ee.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:Al,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ul,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:fl,variables:{bundleId:this.id}});const a=await Ml(this.workflowExperiences.map(r=>({workflowManager:r.getWorkflowManager(),workflow:r.getWorkflowManager().getWorkflow(),layouts:r.getWorkflowManager().getLayouts(),getReducerState:()=>r.getCommandContext().getState(),product:r.getWorkflowManager().getProduct(),transaction:r.getWorkflowManager().getTransaction(),workflowSelections:r.getWorkflowManager().getWorkflowSelections(),designName:r.getWorkflowManager().getWorkflow().name,workflowMetadata:r.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(r,i)=>{const o=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===i);return o?e(o,r):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:ml,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:gl(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const r=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===r.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e);if(a.forEach(r=>r.setBundle(this)),a.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const r of a)await this.injectExperienceIntoPreviewService(r)}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:hl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=a.map(s=>{if(s.getType()===U.ColorOption||s.getType()===U.Option){const l=s;if(!e.aspects.find(d=>d.name===l.getName()))return l.initDefaultVariant()}});await Promise.all(o),await Promise.all(i.map(s=>s.applyGlobalState()))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],r=[],i=[],o=Or(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?r.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:r,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:Cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const fc=w.gql`
|
2408
|
+
`;class ra{constructor(t,e,a,r,i,o){this.workflowExperiences=[],this.eventEmitter=new gc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new cc(e.bundleStateData);const s=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=s?.id,this.globalPropertyStateManager=new lc(this.id,this.ownerId,s,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new nc(this),this.setPreviewService(a);const l=new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const A=this.globalPropertyStateManager.getGlobalPropertyState();A?this.globalPropertyHandleService.getHandles().then(u=>{const h=u.map(g=>{if(g.getType()===U.ColorOption||g.getType()===U.Option){const m=g;if(!A.aspects.find(f=>f.name===m.getName()))return m.initDefaultVariant()}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactions?.map(c=>c.id)||[],{...r,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:fc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,r,i,o){await y.getShadowGraphqlClient().mutate({mutation:mc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:pc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const r=a?.name;this.getGlobalPropertyStateManager().setAspect(r,a.value)}for(const a of t.aspects){const r=a?.name,i=e.find(o=>o.getName()===r);if(i)switch(a.type){case U.FileUpload:{const o=i,s=await xe([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case U.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case U.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case U.Text:{await i.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===U.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,r)=>a+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new ja(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(v.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===U.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=ic(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",r),d=[...new Set(s.map(u=>u.number))];if(d.length>c)for(const u of d){const h=this.getGlobalPropertyStateManager(),g=l.find(m=>m.channelNumber===u);g&&await h.setAspect(r,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getWorkflowManager().getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getWorkflowManager().getTransaction().id).join(", "));const r=k.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await y.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(k.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const r=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(r.setBundle(void 0),this.previewService&&r.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),r.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(r=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===r.id));if(e.some(r=>r===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((r,i)=>e[i]===-1).map(r=>r.id).join(", "));const a=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===r.id),1)[0]);a.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&a.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await y.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,transactionIds:t.map(r=>r.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,i])=>({key:r,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(r=>r.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const r=await this.getGlobalProperties();await Promise.all(r.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,details:t,type:e||ee.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:Al,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ul,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:fl,variables:{bundleId:this.id}});const a=await Tl(this.workflowExperiences.map(r=>({workflowManager:r.getWorkflowManager(),workflow:r.getWorkflowManager().getWorkflow(),layouts:r.getWorkflowManager().getLayouts(),getReducerState:()=>r.getCommandContext().getState(),product:r.getWorkflowManager().getProduct(),transaction:r.getWorkflowManager().getTransaction(),workflowSelections:r.getWorkflowManager().getWorkflowSelections(),designName:r.getWorkflowManager().getWorkflow().name,workflowMetadata:r.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(r,i)=>{const o=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===i);return o?e(o,r):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:ml,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:gl(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const r=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===r.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e);if(a.forEach(r=>r.setBundle(this)),a.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const r of a)await this.injectExperienceIntoPreviewService(r)}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:hl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=a.map(s=>{if(s.getType()===U.ColorOption||s.getType()===U.Option){const l=s;if(!e.aspects.find(d=>d.name===l.getName()))return l.initDefaultVariant()}});await Promise.all(o),await Promise.all(i.map(s=>s.applyGlobalState()))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],r=[],i=[],o=Or(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?r.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:r,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:Cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const Cc=w.gql`
|
2409
2409
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
2410
2410
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
2411
2411
|
id
|
2412
2412
|
}
|
2413
2413
|
}
|
2414
|
-
`;class zr{async execute(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:
|
2414
|
+
`;class zr{async execute(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:Cc,variables:{processFlowId:t,inputs:[...e.map(A=>A.getValueForTransmission())]}})).data?.processExecutionCreate?.id;if(!i)throw new Error("Failed to create process execution.");function o(A){return new Promise(u=>{setTimeout(u,A)})}let s=!1,l=0,c,d;for(;!s;){c=await y.getShadowGraphqlClient().query({query:w.gql`
|
2415
2415
|
query getProcessFlowExecution($ids: [String]!) {
|
2416
2416
|
processExecutions(ids: $ids) {
|
2417
2417
|
id
|
@@ -2424,7 +2424,7 @@
|
|
2424
2424
|
}
|
2425
2425
|
}
|
2426
2426
|
}
|
2427
|
-
`,variables:{ids:[i]}});const A=c.data?.processExecutions[0];if(!c||!A)throw new Error("Failed to retrieve server response for execution.");if(A.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(A.completedAt){s=!0,d=new qr(A);break}l+=1;const u=a?.repeats?a?.repeats:5;if(l>=u)throw new Error("Maximum wait time exceeded for execution result.");await o(a?.sleepTime?Math.max(a.sleepTime,500):2e3)}if(!d)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(d)}}class qr{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Yt(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Yt(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Yt(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Yt(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Yt{constructor(t){this.node=t}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(t){return this.getArtifacts().get(t)}}class Ha{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var Gr=(n=>(n.Transaction="Transaction",n.Bundle="Bundle",n.Product="Product",n.Variant="Variant",n.Option="Option",n.LineItem="LineItem",n.Asset="Asset",n))(Gr||{});class
|
2427
|
+
`,variables:{ids:[i]}});const A=c.data?.processExecutions[0];if(!c||!A)throw new Error("Failed to retrieve server response for execution.");if(A.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(A.completedAt){s=!0,d=new qr(A);break}l+=1;const u=a?.repeats?a?.repeats:5;if(l>=u)throw new Error("Maximum wait time exceeded for execution result.");await o(a?.sleepTime?Math.max(a.sleepTime,500):2e3)}if(!d)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(d)}}class qr{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Yt(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Yt(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Yt(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Yt(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Yt{constructor(t){this.node=t}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(t){return this.getArtifacts().get(t)}}class Ha{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var Gr=(n=>(n.Transaction="Transaction",n.Bundle="Bundle",n.Product="Product",n.Variant="Variant",n.Option="Option",n.LineItem="LineItem",n.Asset="Asset",n))(Gr||{});class wc extends Ha{constructor(t){super(`"${t}"`)}}class Ya extends Ha{constructor(t,e){if(e!=="Asset"&&!Ya.validUUID(t))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${t}", "type": "${e}"}`)}static validUUID(t){return t.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}class yc extends Ha{constructor(t){super(`[${t.map(e=>e.getRaw()).join(",")}]`)}}class va{constructor(t){this.integrationProduct=t}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.basePrice||0,e=this.integrationProduct?.additionalIntegrationProduct;if(!e)return t;if(e&&!e.product)throw new Error("An additional integration product was found, but it does not have a product");return t+(e.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return new Tt(t[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return t.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}}const Ee=w.gql`
|
2428
2428
|
query GetCustomer($emailAddress: String!) {
|
2429
2429
|
customer(emailAddress: $emailAddress) {
|
2430
2430
|
id
|
@@ -2441,7 +2441,7 @@
|
|
2441
2441
|
}
|
2442
2442
|
}
|
2443
2443
|
}
|
2444
|
-
`,
|
2444
|
+
`,Sc=w.gql`
|
2445
2445
|
mutation CustomerCreate($details: CustomerDetailsInput!) {
|
2446
2446
|
customerCreate(details: $details) {
|
2447
2447
|
id
|
@@ -2481,7 +2481,7 @@
|
|
2481
2481
|
}
|
2482
2482
|
}
|
2483
2483
|
}
|
2484
|
-
`;const
|
2484
|
+
`;const vc=w.gql`
|
2485
2485
|
mutation CustomerGenerateVerificationCode($emailAddress: String!) {
|
2486
2486
|
customerGenerateVerificationCode(emailAddress: $emailAddress)
|
2487
2487
|
}
|
@@ -2516,7 +2516,7 @@
|
|
2516
2516
|
}
|
2517
2517
|
}
|
2518
2518
|
}
|
2519
|
-
`;const
|
2519
|
+
`;const Ec=w.gql`
|
2520
2520
|
query CustomerMetafields($id: String!) {
|
2521
2521
|
metafields(entityId: $id) {
|
2522
2522
|
id
|
@@ -2534,7 +2534,7 @@
|
|
2534
2534
|
}
|
2535
2535
|
}
|
2536
2536
|
}
|
2537
|
-
`;class Ec{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class bc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new fe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}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 fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new bc;class Wr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return ui(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const pn=new Wr;class jr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,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,pn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,pn.getPrecisionForCurrency(e))}}const Bc=async(n,t)=>{const e=await y.getShadowGraphqlClient().query({query:Po(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),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(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&R.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&R.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&R.cacheAsset(o.asset),o.thumbnail&&R.cacheAsset(o.thumbnail),o.material&&R.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Ic=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Bc(a,t),i=a.map(s=>$t.set({id:s,options:t},Ic(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Pc=async(n,t)=>(await Ja([n],t))[0],Dc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),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})),xc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):Dc(t.panels)};class Fc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:go})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Fi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.2.7-beta.25f931c6-ae18-5ac4-a721-e801a472f301"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Un(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return R}getFlowService(){if(!ki())throw new Error("Application key required to use Flow Service.");return new zr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new jr(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=Hr(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}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:Do,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const u=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}const c=(await e.query({query:xo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),r=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:yc,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(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.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 y.getShadowGraphqlClient().mutate({mutation:Sc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await Wt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.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),r=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:vc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:nl(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(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const m=Object.entries(localStorage).find(([f,S])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(s.Authorization=`Bearer ${p}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await y.getShadowGraphqlClient().query({query:Xs(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],A=k.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",A);const u=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const u=await this.loggedInBearerToken();o.Authorization=`Bearer ${u}`}catch{const g=Object.entries(localStorage).find(([p,f])=>p.startsWith("CognitoIdentityServiceProvider")&&p.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(g);m&&!_t(m)&&(o.Authorization=`Bearer ${m}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await y.getShadowGraphqlClient().mutate({mutation:rl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const A=k.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",A),async()=>{const u=new ra(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:pl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Zs,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||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),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),r=a[0];return e&&await r.getWorkflowManager().injectIntoPreviewService(e(r.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=y.getShadowGraphqlClient(),r=async C=>{if(C.length===0)return[];const E=C.map(x=>x.option.transactionId),D=await a.query({query:ho,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),B=D.data.transactions;if(B.length!==C.length){const x=D.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${x}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((x,O)=>({transaction:x,workflowId:x.workflowId,readOnly:C.find(T=>T.option.transactionId===x.id)?.option.readOnly??!1,index:C[O].index}))},i=async C=>{if(C.length===0)return[];const E=await a.mutate({mutation:uo,variables:{inputs:C.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),D=E.data?.transactionCreateMany;if(!D||D.length===0){const B=E.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return D.map((B,x)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:C[x].index}))},o=t.map((C,E)=>({option:C,index:E})),s=o.filter(C=>C.option.type==="transaction"),l=o.filter(C=>C.option.type==="integration"||C.option.type==="external"),c=Xa(s,10),d=Xa(l,10),A=(await Promise.all([...c.map(r),...d.map(i)])).flat(),u=[...new Set(A.map(C=>C.workflowId))],h=await Ja(u,e),g=new Map(h.map(C=>[C.id,C])),m=k.getMap("transactionOwnerIds")||new Map,p=A.map(async C=>{const{transaction:E,workflowId:D,readOnly:B,index:x}=C,O=g.get(D),T=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const et=m.get(E.id)||void 0,at=new Ec({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),H={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:T?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:B,workflow:O,isReloadedTransaction:T.type==="transaction"};if(T.type==="transaction"&&E.workflowState){const Y=JSON.parse(E.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else if(!B&&T.workflowState){const Y=JSON.parse(T.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else H.layouts=xc(H.transaction,H.workflow);return H.renderableContextService=new Jl(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:x,options:T}}),f=await Promise.all(p);k.setMap("transactionOwnerIds",m);const b=f.sort((C,E)=>C.index-E.index).map(async C=>{const{experienceOptions:E,options:D}=C,B=new Tr(this,E);return await B.getWorkflowManager().getInitializationPromise(),D.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),B}),P=await Promise.all(b);return P.forEach(C=>C.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),P}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:wo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:yo(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 va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:Co,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:No,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 Hr=async(n,t)=>(await y.getShadowGraphqlClient().query({query:ko,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,kc=async n=>{const e=await y.getShadowGraphqlClient().query({query:fo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Mc=async(n,t)=>(await y.getShadowGraphqlClient().query({query:Fo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Tc=async n=>(await y.getShadowGraphqlClient().query({query:To,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Nc=async n=>(await y.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;function Yr(n,t,e,a){const r=e.width*n.zoom,i=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,-r,t.width),o.y=be(o.y,-i,t.height),o}function be(n,t,e){return Math.min(Math.max(n,t),e)}class Jr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=In(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 r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await he(s),c=this.frameData?this.frameData[o]:void 0;De(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(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 r=Ft.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}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,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((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],A=a[s]-c*t[s];return{x:d,y:A,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),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 r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new L("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]=Yr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,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,r,i){if(!a||a.length===0||a.some(s=>!s))throw new L("Frame data not set. This is a bug");if(!this.workflowManager)throw new L("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new Q([new ws(s,e,t[l]),new ys(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Qc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,A,u,h,g,m,p,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(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Kr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Kr||{});class _r extends X{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Jr(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.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 ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Qe.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 R.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.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 R.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return R.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 r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Rc=w.gql`
|
2537
|
+
`;class bc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Bc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new fe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}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 fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new Bc;class Wr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return ui(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const pn=new Wr;class jr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,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,pn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,pn.getPrecisionForCurrency(e))}}const Ic=async(n,t)=>{const e=await y.getShadowGraphqlClient().query({query:Po(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),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(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&R.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&R.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&R.cacheAsset(o.asset),o.thumbnail&&R.cacheAsset(o.thumbnail),o.material&&R.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Pc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Ic(a,t),i=a.map(s=>$t.set({id:s,options:t},Pc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Dc=async(n,t)=>(await Ja([n],t))[0],xc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),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})),Fc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):xc(t.panels)};class kc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:go})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Fi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.2.7-beta.8bae3361-3242-5b7e-a75c-ed03cdc03b9c"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Un(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return R}getFlowService(){if(!ki())throw new Error("Application key required to use Flow Service.");return new zr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new jr(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=Hr(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}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:Do,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const u=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}const c=(await e.query({query:xo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),r=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Sc,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(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.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 y.getShadowGraphqlClient().mutate({mutation:vc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await Wt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.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),r=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Ec,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:nl(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(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const m=Object.entries(localStorage).find(([f,S])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(s.Authorization=`Bearer ${p}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await y.getShadowGraphqlClient().query({query:Xs(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],A=k.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",A);const u=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const u=await this.loggedInBearerToken();o.Authorization=`Bearer ${u}`}catch{const g=Object.entries(localStorage).find(([p,f])=>p.startsWith("CognitoIdentityServiceProvider")&&p.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(g);m&&!_t(m)&&(o.Authorization=`Bearer ${m}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await y.getShadowGraphqlClient().mutate({mutation:rl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const A=k.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",A),async()=>{const u=new ra(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:pl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Zs,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||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),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),r=a[0];return e&&await r.getWorkflowManager().injectIntoPreviewService(e(r.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=y.getShadowGraphqlClient(),r=async C=>{if(C.length===0)return[];const E=C.map(x=>x.option.transactionId),D=await a.query({query:ho,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),B=D.data.transactions;if(B.length!==C.length){const x=D.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${x}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((x,O)=>({transaction:x,workflowId:x.workflowId,readOnly:C.find(T=>T.option.transactionId===x.id)?.option.readOnly??!1,index:C[O].index}))},i=async C=>{if(C.length===0)return[];const E=await a.mutate({mutation:uo,variables:{inputs:C.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),D=E.data?.transactionCreateMany;if(!D||D.length===0){const B=E.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return D.map((B,x)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:C[x].index}))},o=t.map((C,E)=>({option:C,index:E})),s=o.filter(C=>C.option.type==="transaction"),l=o.filter(C=>C.option.type==="integration"||C.option.type==="external"),c=Xa(s,10),d=Xa(l,10),A=(await Promise.all([...c.map(r),...d.map(i)])).flat(),u=[...new Set(A.map(C=>C.workflowId))],h=await Ja(u,e),g=new Map(h.map(C=>[C.id,C])),m=k.getMap("transactionOwnerIds")||new Map,p=A.map(async C=>{const{transaction:E,workflowId:D,readOnly:B,index:x}=C,O=g.get(D),T=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const et=m.get(E.id)||void 0,at=new bc({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),H={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:T?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:B,workflow:O,isReloadedTransaction:T.type==="transaction"};if(T.type==="transaction"&&E.workflowState){const Y=JSON.parse(E.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else if(!B&&T.workflowState){const Y=JSON.parse(T.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else H.layouts=Fc(H.transaction,H.workflow);return H.renderableContextService=new Kl(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:x,options:T}}),f=await Promise.all(p);k.setMap("transactionOwnerIds",m);const b=f.sort((C,E)=>C.index-E.index).map(async C=>{const{experienceOptions:E,options:D}=C,B=new Tr(this,E);return await B.getWorkflowManager().getInitializationPromise(),D.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),B}),P=await Promise.all(b);return P.forEach(C=>C.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),P}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:wo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:yo(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 va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:Co,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:No,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 Hr=async(n,t)=>(await y.getShadowGraphqlClient().query({query:ko,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Mc=async n=>{const e=await y.getShadowGraphqlClient().query({query:fo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Tc=async(n,t)=>(await y.getShadowGraphqlClient().query({query:Fo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Nc=async n=>(await y.getShadowGraphqlClient().query({query:To,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Qc=async n=>(await y.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,Rc=async n=>{const t=await y.getShadowGraphqlClient().mutate({mutation:Bl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n}});if(t.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${t.errors}`)};function Yr(n,t,e,a){const r=e.width*n.zoom,i=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,-r,t.width),o.y=be(o.y,-i,t.height),o}function be(n,t,e){return Math.min(Math.max(n,t),e)}class Jr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=In(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 r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await he(s),c=this.frameData?this.frameData[o]:void 0;De(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(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 r=Ft.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}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,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((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],A=a[s]-c*t[s];return{x:d,y:A,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),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 r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new L("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]=Yr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,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,r,i){if(!a||a.length===0||a.some(s=>!s))throw new L("Frame data not set. This is a bug");if(!this.workflowManager)throw new L("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new Q([new ws(s,e,t[l]),new ys(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Oc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,A,u,h,g,m,p,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(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Kr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Kr||{});class _r extends X{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Jr(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.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 ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Qe.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 R.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.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 R.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return R.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 r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const $c=w.gql`
|
2538
2538
|
query GetLoggedInCustomer($email: String!) {
|
2539
2539
|
customer(emailAddress: $email) {
|
2540
2540
|
id
|
@@ -2577,21 +2577,21 @@
|
|
2577
2577
|
total
|
2578
2578
|
}
|
2579
2579
|
}
|
2580
|
-
`,
|
2580
|
+
`,Uc=w.gql`
|
2581
2581
|
mutation SetTransactionDesignName($id: String!, $name: String!) {
|
2582
2582
|
transactionUpdate(id: $id, designName: $name) {
|
2583
2583
|
id
|
2584
2584
|
designName
|
2585
2585
|
}
|
2586
2586
|
}
|
2587
|
-
|
2587
|
+
`,Lc=w.gql`
|
2588
2588
|
mutation DuplicateTransaction($id: String!, $template: Boolean!) {
|
2589
2589
|
transactionDuplicate(id: $id, template: $template) {
|
2590
2590
|
id
|
2591
2591
|
workflowViewerLink
|
2592
2592
|
}
|
2593
2593
|
}
|
2594
|
-
`,
|
2594
|
+
`,Vc=w.gql`
|
2595
2595
|
query GetCustomerBundles($id: String!, $limit: Int!, $offset: Int!) {
|
2596
2596
|
customerBundlesFeed(id: $id, limit: $limit, offset: $offset) {
|
2597
2597
|
items {
|
@@ -2606,7 +2606,7 @@
|
|
2606
2606
|
total
|
2607
2607
|
}
|
2608
2608
|
}
|
2609
|
-
`,
|
2609
|
+
`,zc=w.gql`
|
2610
2610
|
query GetTransactionsForBundle($id: String!) {
|
2611
2611
|
bundles(ids: [$id]) {
|
2612
2612
|
id
|
@@ -2627,21 +2627,21 @@
|
|
2627
2627
|
}
|
2628
2628
|
}
|
2629
2629
|
}
|
2630
|
-
`,
|
2630
|
+
`,qc=w.gql`
|
2631
2631
|
mutation SetBundleName($id: String!, $name: String!) {
|
2632
2632
|
bundleUpdate(id: $id, name: $name) {
|
2633
2633
|
id
|
2634
2634
|
name
|
2635
2635
|
}
|
2636
2636
|
}
|
2637
|
-
`,
|
2637
|
+
`,Gc=w.gql`
|
2638
2638
|
mutation DuplicateBundle($id: String!, $template: Boolean!) {
|
2639
2639
|
bundleDuplicate(id: $id, template: $template) {
|
2640
2640
|
id
|
2641
2641
|
workflowViewerLink
|
2642
2642
|
}
|
2643
2643
|
}
|
2644
|
-
`,
|
2644
|
+
`,Wc=w.gql`
|
2645
2645
|
query GetBundleTemplates($id: String!, $limit: Int!, $offset: Int!) {
|
2646
2646
|
customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: true) {
|
2647
2647
|
items {
|
@@ -2654,7 +2654,7 @@
|
|
2654
2654
|
total
|
2655
2655
|
}
|
2656
2656
|
}
|
2657
|
-
`,
|
2657
|
+
`,jc=async(n,t,e)=>await y.getShadowGraphqlClient().mutate({mutation:qc,errorPolicy:"all",variables:{id:n,name:t},context:e}),Hc=async(n,t)=>await y.getShadowGraphqlClient().mutate({mutation:Uc,errorPolicy:"all",variables:{id:n,name:t}}),Yc=async(n,t)=>await y.getShadowGraphqlClient().mutate({mutation:Gc,errorPolicy:"all",variables:{id:n,template:t}}),Jc=async(n,t)=>await y.getShadowGraphqlClient().mutate({mutation:Lc,errorPolicy:"all",variables:{id:n,template:t}}),Kc=async n=>(await y.getShadowGraphqlClient().query({query:$c,errorPolicy:"all",variables:{email:n}})).data.customer,_c=async(n,t,e)=>await y.getShadowGraphqlClient().query({query:Vc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,offset:e,limit:t}}),Xc=async(n,t)=>await y.getShadowGraphqlClient().query({query:zc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:t}),Zc=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:Ka,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",status:{operator:"isAnyOf",values:["Created","DesignCompleted","ExternallyOrdered"]},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],td=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:Ka,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",status:{operator:"equals",value:"Ordered"},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],ed=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:Ka,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",template:{value:"true"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],ad=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:Wc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,offset:e,limit:t}}))?.data.customerBundlesFeed?.items||[];(function(){try{if(typeof document<"u"){var n=document.createElement("style");n.appendChild(document.createTextNode("#spiffThemeWrapper{width:100%;height:100%}")),document.head.appendChild(n)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();var Xr=(n=>(n.Manual="Manual",n.OnStart="OnStart",n.OnQuit="OnQuit",n.OnEnd="OnEnd",n))(Xr||{}),Xt=(n=>(n.Email="Email",n.FirstName="FirstName",n.LastName="LastName",n.Phone="Phone",n.Apartment="Apartment",n.City="City",n.Country="Country",n.OrganizationName="OrganizationName",n.PostCode="PostCode",n.State="State",n.StreetAddress="StreetAddress",n.Custom="Custom",n))(Xt||{}),K;K={__e:function(n,t,e,a){for(var r,i,o;t=t.__;)if((r=t.__c)&&!r.__)try{if((i=r.constructor)&&i.getDerivedStateFromError!=null&&(r.setState(i.getDerivedStateFromError(n)),o=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(n,a||{}),o=r.__d),o)return r.__E=r}catch(s){n=s}throw n}},typeof Promise=="function"&&Promise.prototype.then.bind(Promise.resolve());var st,ia,fn,Zr=[],oa=[],Cn=K.__b,wn=K.__r,yn=K.diffed,Sn=K.__c,vn=K.unmount;function nd(){for(var n;n=Zr.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(Pe),n.__H.__h.forEach(Ea),n.__H.__h=[]}catch(t){n.__H.__h=[],K.__e(t,n.__v)}}K.__b=function(n){st=null,Cn&&Cn(n)},K.__r=function(n){wn&&wn(n);var t=(st=n.__c).__H;t&&(ia===st?(t.__h=[],st.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.__V=oa,e.__N=e.i=void 0})):(t.__h.forEach(Pe),t.__h.forEach(Ea),t.__h=[])),ia=st},K.diffed=function(n){yn&&yn(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(Zr.push(t)!==1&&fn===K.requestAnimationFrame||((fn=K.requestAnimationFrame)||rd)(nd)),t.__H.__.forEach(function(e){e.i&&(e.__H=e.i),e.__V!==oa&&(e.__=e.__V),e.i=void 0,e.__V=oa})),ia=st=null},K.__c=function(n,t){t.some(function(e){try{e.__h.forEach(Pe),e.__h=e.__h.filter(function(a){return!a.__||Ea(a)})}catch(a){t.some(function(r){r.__h&&(r.__h=[])}),t=[],K.__e(a,e.__v)}}),Sn&&Sn(n,t)},K.unmount=function(n){vn&&vn(n);var t,e=n.__c;e&&e.__H&&(e.__H.__.forEach(function(a){try{Pe(a)}catch(r){t=r}}),e.__H=void 0,t&&K.__e(t,e.__v))};var En=typeof requestAnimationFrame=="function";function rd(n){var t,e=function(){clearTimeout(a),En&&cancelAnimationFrame(t),setTimeout(n)},a=setTimeout(e,100);En&&(t=requestAnimationFrame(e))}function Pe(n){var t=st,e=n.__c;typeof e=="function"&&(n.__c=void 0,e()),st=t}function Ea(n){var t=st;n.__c=n.__(),st=t}const ti=w.gql`
|
2658
2658
|
fragment AddressValidationResultFields on AddressValidationResult {
|
2659
2659
|
addressComplete
|
2660
2660
|
address {
|
@@ -2688,14 +2688,14 @@
|
|
2688
2688
|
...AddressValidationResultFields
|
2689
2689
|
}
|
2690
2690
|
}
|
2691
|
-
`,
|
2691
|
+
`,id=w.gql`
|
2692
2692
|
${_a}
|
2693
2693
|
query GetAddressValidationJobs($ids: [String!]!) {
|
2694
2694
|
addressValidationJobs(ids: $ids) {
|
2695
2695
|
...AddressValidationJobFields
|
2696
2696
|
}
|
2697
2697
|
}
|
2698
|
-
`,
|
2698
|
+
`,od=w.gql`
|
2699
2699
|
${_a}
|
2700
2700
|
query GetRecipientsWithAddressValidationJobs($ids: [String!]!) {
|
2701
2701
|
recipients(ids: $ids) {
|
@@ -2705,25 +2705,25 @@
|
|
2705
2705
|
}
|
2706
2706
|
}
|
2707
2707
|
}
|
2708
|
-
`,
|
2708
|
+
`,sd=w.gql`
|
2709
2709
|
${ti}
|
2710
2710
|
mutation ValidateRecipientAddress($id: String!) {
|
2711
2711
|
recipientValidate(id: $id) {
|
2712
2712
|
...AddressValidationResultFields
|
2713
2713
|
}
|
2714
2714
|
}
|
2715
|
-
`,
|
2715
|
+
`,ld=w.gql`
|
2716
2716
|
${_a}
|
2717
2717
|
mutation BatchValidateRecipientAddress($ids: [String!]!) {
|
2718
2718
|
recipientValidateBatch(ids: $ids) {
|
2719
2719
|
...AddressValidationJobFields
|
2720
2720
|
}
|
2721
2721
|
}
|
2722
|
-
`,
|
2722
|
+
`,cd=w.gql`
|
2723
2723
|
mutation OverrideRecipientAddress($id: String!) {
|
2724
2724
|
recipientOverrideAddress(id: $id) {
|
2725
2725
|
id
|
2726
2726
|
}
|
2727
2727
|
}
|
2728
|
-
`;var ei=(n=>(n.Confirmed="Confirmed",n.Plausible="Plausible",n.Unlikely="Unlikely",n))(ei||{}),ai=(n=>(n.Created="Created",n.Processing="Processing",n.Completed="Completed",n.Failed="Failed",n.Cancelled="Cancelled",n))(ai||{});const
|
2728
|
+
`;var ei=(n=>(n.Confirmed="Confirmed",n.Plausible="Plausible",n.Unlikely="Unlikely",n))(ei||{}),ai=(n=>(n.Created="Created",n.Processing="Processing",n.Completed="Completed",n.Failed="Failed",n.Cancelled="Cancelled",n))(ai||{});const dd=async n=>{const t=n.map(a=>a.getWorkflowManager().getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().query({query:od,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getWorkflowManager().getTransaction().recipient?.id;if(r)return e.data?.recipients?.find(i=>i.id===r)?.addressValidationJob})},Ad=async n=>(await y.getShadowGraphqlClient().query({query:id,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:n}})).data?.addressValidationJobs,ud=async n=>n.getWorkflowManager().getTransaction().recipient?.id?(await y.getShadowGraphqlClient().mutate({mutation:sd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n.getWorkflowManager().getTransaction().recipient.id}})).data?.recipientValidate:void 0,hd=async n=>{const t=n.map(a=>a.getWorkflowManager().getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().mutate({mutation:ld,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getWorkflowManager().getTransaction().recipient?.id;if(r)return e.data?.recipientValidateBatch?.find(i=>i.entityId===r)})},gd=async n=>{const t=n.getWorkflowManager().getTransaction().recipient?.id;if(!t)return;(await y.getShadowGraphqlClient().mutate({mutation:cd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:t}})).data?.recipientOverrideAddress?.id&&(n.getWorkflowManager().getTransaction().addressValidationStatus=Ba.Overridden)};exports.AddonHandle=Qe;exports.AddressValidationJobStatus=ai;exports.AddressValidationResultConfirmationLevel=ei;exports.AddressValidationStatus=Ba;exports.ArrayInput=yc;exports.AspectType=U;exports.AssetNotFoundError=pt;exports.AssetType=te;exports.BringForwardCommand=Bs;exports.BringToBackCommand=bs;exports.BringToFrontCommand=Es;exports.BundleDesignCreationCartAddMode=Dn;exports.CanvasCommand=N;exports.CollectionProduct=Ht;exports.ColorOptionGlobalPropertyHandle=ya;exports.CommandContext=or;exports.ConversionDataType=Xt;exports.ConversionLocation=Xr;exports.CreateElementCommand=z;exports.CreateLayoutCommand=Oa;exports.CurrencyContext=jr;exports.CurrencyService=Wr;exports.DeleteElementCommand=yt;exports.DigitalContentStepHandle=Ir;exports.FileUploadGlobalPropertyHandle=Qr;exports.FlowExecutionNodeResult=Yt;exports.FlowExecutionResult=qr;exports.FlowService=zr;exports.FontAlignmentCommand=ur;exports.FontColorCommand=dr;exports.FontSizeCommand=Ar;exports.FontSourceCommand=Ca;exports.FrameService=Jr;exports.FrameStep=Kr;exports.FrameStepHandle=_r;exports.GlobalPropertyHandle=je;exports.GroupCommand=Q;exports.IllustrationStepHandle=Cr;exports.InformationMessageType=pe;exports.InformationStepHandle=Br;exports.IntegrationProduct=va;exports.IntegrationType=Fn;exports.LayoutElementFactory=ms;exports.LayoutElementType=F;exports.LayoutNotFoundError=j;exports.LayoutRenderingPurpose=Nt;exports.MaterialStepHandle=wr;exports.MisconfigurationError=ne;exports.MockWorkflowManager=Oc;exports.ModelStepHandle=yr;exports.ModuleStepHandle=Pr;exports.MoveCommand=ps;exports.ObjectInput=Ya;exports.ObjectInputType=Gr;exports.OptionGlobalPropertyHandle=Wa;exports.OptionNotFoundError=ae;exports.ParseError=bt;exports.PictureStepHandle=Sr;exports.ProductCameraRig=kn;exports.ProductCollection=ja;exports.ProductCollectionProductSortKey=Ur;exports.ProductWorkflow=Tt;exports.PromiseCache=$t;exports.PromiseQueue=Ma;exports.QuestionStepHandle=vr;exports.QueueablePromise=ka;exports.ResizeCommand=Cs;exports.ResourceNotFoundError=Qt;exports.RotateCommand=fs;exports.ScaleAxis=G;exports.SendBackwardsCommand=Is;exports.ShapeStepHandle=Er;exports.ShareActionType=xn;exports.SpiffCommerceClient=kc;exports.StakeholderType=ee;exports.StepAspectType=Pn;exports.StepHandle=X;exports.StepType=v;exports.TextAlgorithm=Pt;exports.TextChangeCommand=hr;exports.TextGlobalPropertyHandle=Rr;exports.TextInput=wc;exports.TextStepHandle=br;exports.Transform=Vr;exports.TransformCollection=Lr;exports.UnhandledBehaviorError=L;exports.UnitOfMeasurement=Mn;exports.UpdateImageSourceCommand=Ss;exports.Variant=rt;exports.WorkflowExperienceEventType=Mr;exports.WorkflowExperienceImpl=Tr;exports.assetService=R;exports.browserColorToHex=zn;exports.cmPerPixel=Xo;exports.createDesign=kr;exports.currentDirection=Jo;exports.dataUrlFromExternalUrl=Bi;exports.deleteBundle=Rc;exports.designService=Ie;exports.determineCorrectFontSizeAndLines=Kt;exports.digitalContentStepService=$a;exports.domParser=lt;exports.duplicateBundle=Yc;exports.duplicateTransaction=Jc;exports.fetchAsString=tt;exports.findAngle=zo;exports.findElement=$;exports.findPmsColors=Gi;exports.frameDataCache=Ft;exports.frameStepService=ht;exports.generate=M;exports.generateCommands=Nr;exports.generateSVGWithUnknownColors=ot;exports.generateStateFromDesignInputSteps=ac;exports.getAddressValidationJobs=Ad;exports.getAttributesFromArrayBuffer=ce;exports.getAxisAlignedBoundingBox=Vo;exports.getBoundedOffsets=Yr;exports.getBundleThemeConfiguration=Nc;exports.getCustomer=Kc;exports.getCustomerBundles=_c;exports.getElementVertices=Ko;exports.getFrameData=he;exports.getGlobalPropertyStateForBundle=Ks;exports.getIntegration=Hr;exports.getNEPoint=Ho;exports.getNWPoint=jo;exports.getOrderedTransactions=td;exports.getOverrideThemeConfiguration=Tc;exports.getPointOfRotation=Wo;exports.getProductCollections=hc;exports.getSEPoint=Yo;exports.getSvgElement=We;exports.getTemplateBundles=ad;exports.getTemplateTransactions=ed;exports.getTransaction=Mc;exports.getTransactionThemeConfiguration=Qc;exports.getTransactionsForBundle=Xc;exports.getTrueCoordinates=Go;exports.getUnorderedTransactions=Zc;exports.getValidationJobsForWorkflowExperiences=dd;exports.getWorkflow=Dc;exports.getWorkflows=Ja;exports.graphQlManager=y;exports.illustrationStepService=Jt;exports.isCloseToValue=qo;exports.loadFont=Dt;exports.matchHexToPms=Vi;exports.materialStepService=Ua;exports.metafieldManager=$r;exports.mmPerPixel=_o;exports.modelStepService=La;exports.modifySVGColors=ze;exports.moduleStepService=Va;exports.nameBundle=jc;exports.nameTransaction=Hc;exports.optionService=W;exports.outlineFontsInSvg=ns;exports.overrideWorkflowExperienceRecipientAddress=gd;exports.patternImageDataCache=dt;exports.persistenceService=k;exports.pictureStepService=za;exports.pmsToRgb=Li;exports.questionStepService=qa;exports.registerFetchImplementation=yi;exports.registerWindowImplementation=wi;exports.rehydrateSerializedLayout=fa;exports.rgbToPms=Vn;exports.rotateAroundPoint=jt;exports.sanitizeSvgTree=Ve;exports.setBearerAuthenticationToken=Un;exports.setCanvasModule=Pa;exports.shapeStepService=kt;exports.shortenUrl=gr;exports.spiffCoreConfiguration=At;exports.stepAspectValuesToDesignInputSteps=ec;exports.svgColorValueToDefinition=ha;exports.svgStringDimensions=Ra;exports.svgToDataUrl=Le;exports.textStepService=q;exports.toast=pr;exports.validateWorkflowExperienceRecipient=ud;exports.validateWorkflowExperienceRecipients=hd;exports.xmlSerializer=St;
|
2729
2729
|
//# sourceMappingURL=index.js.map
|