@spiffcommerce/core 14.1.6 → 14.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/module.js CHANGED
@@ -487,7 +487,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
487
487
  id
488
488
  }
489
489
  }
490
- `;class va extends Ma{constructor(t,e){super(t,e),Fa(this,"transaction",this.manager.getTransaction())}selectVariant(){throw new Error("Bulk step does not support variants.")}async setDesignName(t){await ye.getShadowGraphqlClient().mutate({mutation:Sa,variables:{transactionId:this.manager.getTransaction().id,designName:t}});const e=this.manager.getTransaction();this.manager.setTransaction({...e,designName:t})}addVariationRecord(){const t=this.manager.addVariationRecord({transactionId:this.transaction.id,values:[]});return this.manager.setCurrentVariationRecord(t),t}updateBulkIsConnected(t){this.manager.updateStorage(this.getId(),{bulkIsConnected:t})}openBulkSourceUrl(){window.open(this.transaction.bulkSourceUrl,"_blank")}async sendGoogleSheetLinkToEmail(t){await ye.getShadowGraphqlClient().mutate({mutation:Ya,variables:{id:this.transaction.id,details:{emailAddress:t},type:"Owner"}}),this.openBulkSourceUrl()}deleteVariationRecord(t){this.manager.removeVariationRecord(t)}getAspects(){return this.step.data.aspects}}class xa extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){if(this.getCurrentVariant()!==t)return oa.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],(t=>this.setUpdateState(t)),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(0!==t.length)try{return y(t[0].id,this.manager.getAllLayoutData()).colors}catch(t){console.error(t)}}setColor(t,e){const A=new Map;return A.set(t,e),oa.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,(()=>this.manager.getCommandContext().getAllLayouts()),A)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?oa.availableColors(this.step,this.manager):Promise.resolve([])}hasVaryingSelection(){return this.step.data.varySelection}hasVaryingColors(){return this.step.data.varyColors}isColorPickerEnabled(){return this.step.data.colorPickerEnabled}}class Na extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return ra.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Pa extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return sa.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ra extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return ga.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ha extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await la.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.option?.displayType}}class Ua extends Ma{constructor(t,e){super(t,e)}selectVariant(t){const e=t.getResource();return Ba.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Ba.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Ba.availableColours(this.step)}}class ba extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){Ca.selectVariant(this.step,t.getResource(),this.manager,(t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occured with test",messageType:Qa.Error,stepID:this.step.stepName}]);else{const t=this.manager.getInformationResults().filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}}),(t=>{}))}getAvailableFillColors(){return this.step.data.colorPickerEnabled?Ca.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await Ca.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return Ca.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await Ca.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",A=void 0!==this.step.data.replaceableText?this.step.data.replaceableText.replace("{{}}",e):e,n=t?A:this.step.data.defaultText;this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1});return this.setText(n)}setText(t){const e={input:t},A=Ca.findLayoutElements(this.manager,this.step),n=Ca.filterUnsupportedCharacters(t,A[0]?.fontData);!!this.step.data&&!!this.step.data.maxLength&&n.length>this.step.data.maxLength||(e.input=n);const a=A.length<=0,i=a?{inputText:n,text:n}:{inputText:n};if(this.manager.updateStorage(this.step.stepName,i),this.manager.updateMetadata(this.step.stepName,{text:n}),a)return e;const{command:o,errors:r,helperText:s}=Ca.updateInputText(n,A,this.step,this.manager);o&&this.manager.getCommandDispatcher()(o);const c=this.manager.getInformationResults(),g=r[0]?.localizationKey;if(g)this.manager.setInformationResults([...c,{message:`${g} - ${this.step.stepTitle}`,messageType:Qa.Error,stepID:this.step.stepName}]);else{const t=c.filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}return e.helperText=g||s,e.errorText=g,e}getText(){const t=this.step.data.defaultText;return this.manager.getStepStorage(this.step.stepName)?.text||t||""}isReplaceable(){return this.step.data.userCanReplaceText}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const t=this.setText("");return this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""}),t}}hasVaryingText(){return this.step.data.varyText}hasVaryingColor(){return this.step.data.varyColor}hasVaryingSelection(){return this.step.data.varySelection}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(void 0===t)return;return t-this.getText().length}}class Ga{static get(t,e){switch(e.type){case m.Question:return new Ha(t,e);case m.Text:return new ba(t,e);case m.Illustration:return new xa(t,e);case m.Picture:return new Ra(t,e);case m.Shape:return new Ua(t,e);case m.Material:return new Na(t,e);case m.Model:return new Pa(t,e);case m.Frame:return new Wi(t,e);case m.Bulk:return new va(t,e);default:throw new re(`Step type ${e.type} not yet supported in Core SDK`)}}}function ka(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Ja=ft`
490
+ `;class va extends Ma{constructor(t,e){super(t,e),Fa(this,"transaction",this.manager.getTransaction())}selectVariant(){throw new Error("Bulk step does not support variants.")}async setDesignName(t){await ye.getShadowGraphqlClient().mutate({mutation:Sa,variables:{transactionId:this.manager.getTransaction().id,designName:t}});const e=this.manager.getTransaction();this.manager.setTransaction({...e,designName:t})}addVariationRecord(){const t=this.manager.addVariationRecord({transactionId:this.transaction.id,values:[]});return this.manager.setCurrentVariationRecord(t),t}updateBulkIsConnected(t){this.manager.updateStorage(this.getId(),{bulkIsConnected:t})}openBulkSourceUrl(){window.open(this.transaction.bulkSourceUrl,"_blank")}async sendGoogleSheetLinkToEmail(t){await ye.getShadowGraphqlClient().mutate({mutation:Ya,variables:{id:this.transaction.id,details:{emailAddress:t},type:"Owner"}}),this.openBulkSourceUrl()}deleteVariationRecord(t){this.manager.removeVariationRecord(t)}getAspects(){return this.step.data.aspects}}class xa extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){if(this.getCurrentVariant()!==t)return oa.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],(t=>this.setUpdateState(t)),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(0!==t.length)try{return y(t[0].id,this.manager.getAllLayoutData()).colors}catch(t){console.error(t)}}setColor(t,e){const A=new Map;return A.set(t,e),oa.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,(()=>this.manager.getCommandContext().getAllLayouts()),A)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?oa.availableColors(this.step,this.manager):Promise.resolve([])}hasVaryingSelection(){return this.step.data.varySelection}hasVaryingColors(){return this.step.data.varyColors}isColorPickerEnabled(){return this.step.data.colorPickerEnabled}}class Na extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return ra.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Pa extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return sa.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ra extends Ma{constructor(t,e){super(t,e)}selectVariant(t){return ga.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ha extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await la.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.option?.displayType}}class Ua extends Ma{constructor(t,e){super(t,e)}selectVariant(t){const e=t.getResource();return Ba.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Ba.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Ba.availableColours(this.step)}}class ba extends Ma{constructor(t,e){super(t,e)}async selectVariant(t){Ca.selectVariant(this.step,t.getResource(),this.manager,(t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occured with test",messageType:Qa.Error,stepID:this.step.stepName}]);else{const t=this.manager.getInformationResults().filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}}),(t=>{}))}getAvailableFillColors(){return this.step.data.colorPickerEnabled?Ca.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await Ca.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return Ca.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await Ca.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",A=void 0!==this.step.data.replaceableText?this.step.data.replaceableText.replace("{{}}",e):e,n=t?A:this.step.data.defaultText;this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1});return this.setText(n)}setText(t){const e={input:t},A=Ca.findLayoutElements(this.manager,this.step),n=Ca.filterUnsupportedCharacters(t,A[0]?.fontData);!!this.step.data&&!!this.step.data.maxLength&&n.length>this.step.data.maxLength||(e.input=n);const a=A.length<=0,i=a?{inputText:n,text:n}:{inputText:n};if(this.manager.updateStorage(this.step.stepName,i),this.manager.updateMetadata(this.step.stepName,{text:n}),a)return e;const{command:o,errors:r,helperText:s}=Ca.updateInputText(n,A,this.step,this.manager);o&&this.manager.getCommandDispatcher()(o);const c=this.manager.getInformationResults(),g=r[0]?.localizationKey;if(g)this.manager.setInformationResults([...c,{message:`${g} - ${this.step.stepTitle}`,messageType:Qa.Error,stepID:this.step.stepName}]);else{const t=c.filter((t=>t.stepID!==this.step.stepName));this.manager.setInformationResults(t)}return e.helperText=g||s,e.errorText=g,e}getText(){const t=this.step.data.defaultText;return this.manager.getStepStorage(this.step.stepName)?.text||t||""}isReplaceable(){return this.step.data.userCanReplaceText}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const t=this.setText("");return this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""}),t}}hasVaryingText(){return this.step.data.varyText}hasVaryingColor(){return this.step.data.varyColor}hasVaryingSelection(){return this.step.data.varySelection}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(void 0===t)return;return t-this.getText().length}}class Ga{static get(t,e){switch(e.type){case m.Question:return new Ha(t,e);case m.Text:return new ba(t,e);case m.Illustration:return new xa(t,e);case m.Picture:return new Ra(t,e);case m.Shape:return new Ua(t,e);case m.Material:return new Na(t,e);case m.Model:return new Pa(t,e);case m.Frame:return new Xi(t,e);case m.Bulk:return new va(t,e);default:throw new re(`Step type ${e.type} not yet supported in Core SDK`)}}}function ka(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Ja=ft`
491
491
  mutation CreateDesign(
492
492
  $name: String!
493
493
  $layouts: [LayoutInput]!
@@ -519,7 +519,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
519
519
  }
520
520
  }
521
521
  }
522
- `,La=(t,e,A)=>{const n={};return e.steps.forEach((e=>{Object.assign(n,(e=>{const n={};if("Frame"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideImageInCart&&A)return n;n[`${e.stepTitle} image`]=a.image}if("Illustration"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideColorsInCart&&A||!a.colors)return n;if(a.colors.length>0){const t=a.colors.join(", ").toUpperCase();n[`${e.stepTitle} colors`]=t}}if("Module"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideTextInCart&&A)return n;n[`${e.stepTitle} text`]=a.text}if("Text"===e.type){const a=t[e.stepName];if(!a)return n;const i=e.data;i.hideTextInCart&&A||(n[`${e.stepTitle} text`]=a.text),!a.color||i.hideColorInCart&&A||(n[`${e.stepTitle} color`]=a.color)}return n})(e))})),n},Ta=(t,e,A,n,a,i,o,r,s,c)=>{const g=(de.getMap("transactionOwnerIds")||new Map).get(t.id),l={baseCost:A,designProductId:t.externalDesignProductId,designProductVariantId:t.externalDesignProductVariantId,event:"onComplete",exportedData:i,externalCartProductId:t.externalCartProductId,externalCartProductVariantId:t.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:n,processExecutionId:c,transactionId:t.id,transactionOwnerId:g,weight:e.weight,workflowViewerLink:t.workflowViewerLink||"",workflowViewerReadOnlyLink:t.workflowViewerReadOnlyLink||""};return a&&(l.metadata=a),r&&(l.selectedVariants=r),s&&(l.sku=s),l},Oa=async(t,e,A,n,a,i,o,r)=>{const s=t.product?.basePrice||0,c=t.priceModifierTotal||0,g=((t,e,A,n)=>{const a={};let i;if(A){i=La(A,e,!1);for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}else if(n){i=n;for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}for(const A of Object.keys(t)){const n=t[A],i=e.steps.find((t=>t.stepTitle===A));if(1===n.length)a[`${i?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let t=0;t<n.length;t++)a[`${i?.stepTitle} selection ${t+1}`]={value:n[t].name,priceModifier:n[t].priceModifier}}return a})(n,A,void 0,i);return Ta(t,e,s,c,i,g,o,n,a,r)},za=async(t,e,A,n,a,i,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts"),await t.outstandingRequestsPromise();const w=ye.getShadowGraphqlClient(),d=await w.query({query:Jn,variables:{id:i.id},fetchPolicy:"no-cache",errorPolicy:"all"}),h=d.data?.transactions[0].workflowState;!d.errors&&h||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),d.errors&&d.errors.forEach((t=>{d.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const E=t.getPreviewService(),C=e?.finalizeStepConfig?.lookAtAnimation,u=E&&100===E.getSceneInitializationProgress()&&e.showModelOnFinishStep&&!!C,Q=B&&La(B,e,!0),p=B&&La(B,e,!1),m=async t=>{const A={};let n=0;if(Object.keys(o).length>0)for(const a of Object.keys(o)){const i=o[a],r=e.steps.find((t=>t.stepName===a));for(let e=0;e<i.selections.length;++e){const a=i.selections[e];if(r&&(!t||r.option&&(r.option.variants||[]).length>1&&!r.data.hideSelectionInCart&&!r.data.hideSelectionsInCart)){const t=r.stepTitle;A[t]?A[t].push({id:a.id||"",name:a.name,priceModifier:a.priceModifier}):A[t]=[{id:a.id||"",name:a.name,priceModifier:a.priceModifier}]}n+=a.priceModifier}}return[A,n]},[D]=await m(!0),I=Object.fromEntries(Object.keys(D).map((t=>[t,D[t].map((t=>t.id))]))),[f]=await m(!1),y=Object.fromEntries(Object.keys(f).map((t=>[t,f[t].map((t=>t.id))]))),M=await l(u);s("workflow.steps.finish.finalize.creatingDesign"),i.bulk&&await c(g);const F=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:Ja,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:t.name,layouts:t.layouts,workflowId:t.workflowId,transactionId:t.transactionId,previewImage:t.previewImage,useThreeDimPreview:t.useThreeDimPreview,metadata:t.metadata,selectedVariants:t.selectedVariants}})).data?.designCreate)((()=>{const t={name:r,layouts:A.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:e.id,transactionId:i.id,useThreeDimPreview:!!u,previewImage:M};if(p){const e=[];for(const[t,A]of Object.entries(p))e.push({key:t,value:A});t.metadata=e}if(I){const e=[];for(const[t,A]of Object.entries(y))e.push({key:t,ids:A});t.selectedVariants=e}return t})()),Y=F?.transaction?.previewImageLink;s("workflow.steps.finish.finalize.updatingTransaction");const S=(await ye.getShadowGraphqlClient().query({query:kn,variables:{id:i.id}})).data.transactions[0];return i.bulk?((t,e,A,n)=>{const a=(t.product?.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,o={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return Ta(t,e,a,i,void 0,o,A,void 0,void 0,n)})(S,a,Y,F?.processExecution?.id):await Oa(S,a,e,D,F?.sku,Q,Y,F?.processExecution?.id)};let ja;var Ka;(Ka=ja||(ja={})).Local="Local",Ka.Remote="Remote";const Va=new class{constructor(){ka(this,"localPersistenceKey","designTransactions"),ka(this,"storageMethod",ja.Local),ka(this,"designSavedListeners",[])}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter((e=>e!==t))}async getSavedDesigns(){if(this.storageMethod===ja.Local){const t=de.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new re("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find((e=>e.transactionId===t))}async addDesign(t){const e=(await this.getSavedDesigns()).filter((e=>e.transactionId!==t.transactionId));e.unshift(t),await this.setDesigns(e),this.designSavedListeners.forEach((e=>e(t)))}async renameDesign(t,e){const A=await this.getSavedDesigns(),n=A.find((e=>e.transactionId===t));if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(A)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter((e=>e.transactionId!==t)))}async setDesigns(t){if(this.storageMethod!==ja.Local)throw new re("Unexpected storage method requested");de.set(this.localPersistenceKey,JSON.stringify(t))}};function Wa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Xa{constructor(e,A){if(Wa(this,"client",void 0),Wa(this,"commandContext",void 0),Wa(this,"workflowManager",void 0),Wa(this,"isReadOnly",void 0),Wa(this,"renderableScenes",[]),Wa(this,"renderableSceneCallbacks",[]),Wa(this,"debouncedSavedDesignUpdate",Xt((async()=>{await Va.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),Wa(this,"getCanvasObjectURLAsync",(async t=>new Promise(((e,A)=>{try{t.toBlob((t=>{if(t){const A=URL.createObjectURL(t);e(A)}}))}catch(t){A(t)}})))),!A.workflow)throw new Error("No Workflow ID provided.");this.client=e;const n=A.layouts;this.commandContext=new t,this.commandContext.initialize(n,A.reloadedState),this.isReadOnly=A.transaction.isOrdered||!!A.readOnly,this.workflowManager=new Da(A.workflow,A.product.profanities?.map((t=>t.word))||[],n,this.commandContext,(t=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return A.stateMutationFunc(t)}),A.transaction,A.product,A.previewService,A.renderableContextService,A.reloadedState,A.readOnly,A.modelContainer,A.isReloadedTransaction),this.workflowManager.addSelectionCallback((t=>{const e=t.traversableScenes.map((t=>{const e=t.renderableSteps.map((t=>t.stepName));return{id:t.name,title:t.title,renderableSteps:e}}));this.renderableScenes=e,this.renderableSceneCallbacks.forEach((t=>t(e)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(t){await ye.getShadowGraphqlClient().mutate({mutation:Gn,variables:{transactionId:this.workflowManager.getTransaction().id,updates:t.map((t=>({recordNumber:t.recordNumber,values:t.values.map((t=>({aspect:t.aspect,stepName:t.stepName,value:t.value})))})))}})}async createPreviewImage(t,e){const A=this.workflowManager.getWorkflow(),n=A?.finalizeStepConfig?.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,n))||""}const a=document.createElement("canvas");let i=2048;e&&e<=2048&&(i=e),a.width=i,a.height=i;const o=this.commandContext.getAllLayouts(),r=A.defaultPreviewPanelIndex||0,s=A.panels[r],c=o.find((t=>t.layoutState?.layout.panelId===s?.name))||o[0],g=c.layoutState.layout.previewRegion?{x:c.layoutState.layout.previewRegion.left,y:c.layoutState.layout.previewRegion.top,width:c.layoutState.layout.previewRegion.width,height:c.layoutState.layout.previewRegion.height}:{x:0,y:0,width:c.layoutState.layout.width,height:c.layoutState.layout.height},l=this.commandContext.getLayoutById(c.layoutState.layout.id),B=a.getContext("2d");if(!B)throw new ge("Failed to obtain 2D context for preview image creation");const w=P(l.layoutState.layout,l.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:g.x,top:g.y,width:g.width,height:g.height}}}),d=Kt.renderToStaticMarkup(w),h=await jt.from(B,d,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await h.render();const E=await this.getCanvasObjectURLAsync(a);return a.toDataURL(E)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t));if(e&&this.stepHasHandle(e))return Ga.get(this.getWorkflowManager(),e)}getSteps(){return this.getScenes().flatMap((t=>this.getStepsByScene(t)))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map((t=>({id:t.id,name:t.name,stepIds:t.stepNames})))}getSelectionPriceSubunits(){const t=this.getWorkflowManager().getWorkflowSelections();let e=0;return Object.values(t).forEach((t=>{e+=t.selections.map((t=>t.priceModifier)).reduce(((t,e)=>t+e))})),e}getBasePriceSubunits(){return this.getWorkflowManager().getProduct().basePrice||0}getTotalPriceSubunits(){return this.getBasePriceSubunits()+this.getSelectionPriceSubunits()}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const t=this.getWorkflowManager().getProduct().bulkConfiguration,e={type:m.Bulk,stepName:"Bulk",stepTitle:t?.stepTitle??"workflow.steps.bulk.title",helpText:t?.helpText,data:{aspects:Ln(this.getWorkflowManager().getWorkflow())},conditions:[]};return Ga.get(this.getWorkflowManager(),e)}}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepTitle===t));if(e&&this.stepHasHandle(e))return Ga.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((e=>e.type===t)).map((t=>Ga.get(this.getWorkflowManager(),t)))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((e=>e.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((t=>this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t)))).filter((t=>this.stepHasHandle(t))).map((t=>Ga.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:Ya,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find((e=>e.customer?.emailAddress===t.emailAddress));if(e?.customer){this.getWorkflowManager().setTransactionCustomer(e.customer);const t=de.getMap("transactionCustomerIds")||new Map;t.set(this.getWorkflowManager().getTransaction().id,e.customer.id),de.setMap("transactionCustomerIds",t)}}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 re("State undefined!");const e={title:await(async()=>{if(t)return t;const e=this.getWorkflowManager().getTransaction().id,A=(await Va.getSavedDesigns()).find((t=>t.transactionId===e))?.title;return A||"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 Va.addDesign(e),e}async copy(){const t=zt(this.getCommandContext().getState());if(!t)throw new re("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),A=this.getWorkflowManager().getWorkflow(),n=new Ti({}),a=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!a)throw new re("Integration product id is undefined!");await n.initFromIntegrationProduct(a);return await n.getWorkflowExperience(A.id,e,void 0)}async onDesignFinished(t){return za(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),this.workflowManager.getProduct(),this.workflowManager.getTransaction(),this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),(t=>this.updateVariationRecords(t)),this.workflowManager.getVariationRecords(),(t=>this.createPreviewImage(t)),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==m.SilentIllustration&&t.type!==m.ProductOverlay}getExportedData(){const t=new Map,e=this.getWorkflowManager().getWorkflowMetadata(),A=this.getWorkflowManager().getWorkflowSelections();return Object.keys(e).forEach((A=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===A));if(!n)return;t.has(n.stepTitle)||t.set(n.stepTitle,{});const a=e[A];Object.keys(a).forEach((e=>{t.get(n.stepTitle)[e]=a[e]}))})),Object.keys(A)?.forEach((e=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===e));n&&(t.has(n.stepTitle)||t.set(n.stepTitle,{}),t.get(n.stepTitle).selection=A[e].selections[0].name)})),t}}const qa=Zt`
522
+ `,La=(t,e,A)=>{const n={};return e.steps.forEach((e=>{Object.assign(n,(e=>{const n={};if("Frame"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideImageInCart&&A)return n;n[`${e.stepTitle} image`]=a.image}if("Illustration"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideColorsInCart&&A||!a.colors)return n;if(a.colors.length>0){const t=a.colors.join(", ").toUpperCase();n[`${e.stepTitle} colors`]=t}}if("Module"===e.type){const a=t[e.stepName],i=e.data;if(!a||i.hideTextInCart&&A)return n;n[`${e.stepTitle} text`]=a.text}if("Text"===e.type){const a=t[e.stepName];if(!a)return n;const i=e.data;i.hideTextInCart&&A||(n[`${e.stepTitle} text`]=a.text),!a.color||i.hideColorInCart&&A||(n[`${e.stepTitle} color`]=a.color)}return n})(e))})),n},Ta=(t,e,A,n,a,i,o,r,s,c)=>{const g=(de.getMap("transactionOwnerIds")||new Map).get(t.id),l={baseCost:A,designProductId:t.externalDesignProductId,designProductVariantId:t.externalDesignProductVariantId,event:"onComplete",exportedData:i,externalCartProductId:t.externalCartProductId,externalCartProductVariantId:t.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:n,processExecutionId:c,transactionId:t.id,transactionOwnerId:g,weight:e.weight,workflowViewerLink:t.workflowViewerLink||"",workflowViewerReadOnlyLink:t.workflowViewerReadOnlyLink||""};return a&&(l.metadata=a),r&&(l.selectedVariants=r),s&&(l.sku=s),l},Oa=async(t,e,A,n,a,i,o,r)=>{const s=t.product?.basePrice||0,c=t.priceModifierTotal||0,g=((t,e,A,n)=>{const a={};let i;if(A){i=La(A,e,!1);for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}else if(n){i=n;for(const t of Object.keys(i))a[t]={value:i[t],priceModifier:0}}for(const A of Object.keys(t)){const n=t[A],i=e.steps.find((t=>t.stepTitle===A));if(1===n.length)a[`${i?.stepTitle} selection`]={value:n[0].name,priceModifier:n[0].priceModifier};else if(n.length>1)for(let t=0;t<n.length;t++)a[`${i?.stepTitle} selection ${t+1}`]={value:n[t].name,priceModifier:n[t].priceModifier}}return a})(n,A,void 0,i);return Ta(t,e,s,c,i,g,o,n,a,r)},za=async(t,e,A,n,a,i,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts"),await t.outstandingRequestsPromise();const w=ye.getShadowGraphqlClient(),d=await w.query({query:Jn,variables:{id:i.id},fetchPolicy:"no-cache",errorPolicy:"all"}),h=d.data?.transactions[0].workflowState;!d.errors&&h||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),d.errors&&d.errors.forEach((t=>{d.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const E=t.getPreviewService(),C=e?.finalizeStepConfig?.lookAtAnimation,u=E&&100===E.getSceneInitializationProgress()&&e.showModelOnFinishStep&&!!C,Q=B&&La(B,e,!0),p=B&&La(B,e,!1),m=async t=>{const A={};let n=0;if(Object.keys(o).length>0)for(const a of Object.keys(o)){const i=o[a],r=e.steps.find((t=>t.stepName===a));for(let e=0;e<i.selections.length;++e){const a=i.selections[e];if(r&&(!t||r.option&&(r.option.variants||[]).length>1&&!r.data.hideSelectionInCart&&!r.data.hideSelectionsInCart)){const t=r.stepTitle;A[t]?A[t].push({id:a.id||"",name:a.name,priceModifier:a.priceModifier}):A[t]=[{id:a.id||"",name:a.name,priceModifier:a.priceModifier}]}n+=a.priceModifier}}return[A,n]},[D]=await m(!0),I=Object.fromEntries(Object.keys(D).map((t=>[t,D[t].map((t=>t.id))]))),[f]=await m(!1),y=Object.fromEntries(Object.keys(f).map((t=>[t,f[t].map((t=>t.id))]))),M=await l(u);s("workflow.steps.finish.finalize.creatingDesign"),i.bulk&&await c(g);const F=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:Ja,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:t.name,layouts:t.layouts,workflowId:t.workflowId,transactionId:t.transactionId,previewImage:t.previewImage,useThreeDimPreview:t.useThreeDimPreview,metadata:t.metadata,selectedVariants:t.selectedVariants}})).data?.designCreate)((()=>{const t={name:r,layouts:A.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:e.id,transactionId:i.id,useThreeDimPreview:!!u,previewImage:M};if(p){const e=[];for(const[t,A]of Object.entries(p))e.push({key:t,value:A});t.metadata=e}if(I){const e=[];for(const[t,A]of Object.entries(y))e.push({key:t,ids:A});t.selectedVariants=e}return t})()),Y=F?.transaction?.previewImageLink;s("workflow.steps.finish.finalize.updatingTransaction");const S=(await ye.getShadowGraphqlClient().query({query:kn,variables:{id:i.id}})).data.transactions[0];return i.bulk?((t,e,A,n)=>{const a=(t.product?.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,o={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return Ta(t,e,a,i,void 0,o,A,void 0,void 0,n)})(S,a,Y,F?.processExecution?.id):await Oa(S,a,e,D,F?.sku,Q,Y,F?.processExecution?.id)};let ja;var Ka;(Ka=ja||(ja={})).Local="Local",Ka.Remote="Remote";const Va=new class{constructor(){ka(this,"localPersistenceKey","designTransactions"),ka(this,"storageMethod",ja.Local),ka(this,"designSavedListeners",[])}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter((e=>e!==t))}async getSavedDesigns(){if(this.storageMethod===ja.Local){const t=de.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new re("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find((e=>e.transactionId===t))}async addDesign(t){const e=(await this.getSavedDesigns()).filter((e=>e.transactionId!==t.transactionId));e.unshift(t),await this.setDesigns(e),this.designSavedListeners.forEach((e=>e(t)))}async renameDesign(t,e){const A=await this.getSavedDesigns(),n=A.find((e=>e.transactionId===t));if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(A)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter((e=>e.transactionId!==t)))}async setDesigns(t){if(this.storageMethod!==ja.Local)throw new re("Unexpected storage method requested");de.set(this.localPersistenceKey,JSON.stringify(t))}};function Wa(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Xa{constructor(e,A){if(Wa(this,"client",void 0),Wa(this,"commandContext",void 0),Wa(this,"workflowManager",void 0),Wa(this,"isReadOnly",void 0),Wa(this,"renderableScenes",[]),Wa(this,"renderableSceneCallbacks",[]),Wa(this,"debouncedSavedDesignUpdate",Xt((async()=>{await Va.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),Wa(this,"getCanvasObjectURLAsync",(async t=>new Promise(((e,A)=>{try{t.toBlob((t=>{if(t){const A=URL.createObjectURL(t);e(A)}}))}catch(t){A(t)}})))),!A.workflow)throw new Error("No Workflow ID provided.");this.client=e;const n=A.layouts;this.commandContext=new t,this.commandContext.initialize(n,A.reloadedState),this.isReadOnly=A.transaction.isOrdered||!!A.readOnly,this.workflowManager=new Da(A.workflow,A.product.profanities?.map((t=>t.word))||[],n,this.commandContext,(t=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return A.stateMutationFunc(t)}),A.transaction,A.product,A.previewService,A.renderableContextService,A.reloadedState,A.readOnly,A.modelContainer,A.isReloadedTransaction),this.workflowManager.addSelectionCallback((t=>{const e=t.traversableScenes.map((t=>{const e=t.renderableSteps.map((t=>t.stepName));return{id:t.name,title:t.title,renderableSteps:e}}));this.renderableScenes=e,this.renderableSceneCallbacks.forEach((t=>t(e)))}))}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async updateVariationRecords(t){await ye.getShadowGraphqlClient().mutate({mutation:Gn,variables:{transactionId:this.workflowManager.getTransaction().id,updates:t.map((t=>({recordNumber:t.recordNumber,values:t.values.map((t=>({aspect:t.aspect,stepName:t.stepName,value:t.value})))})))}})}async createPreviewImage(t,e){const A=this.workflowManager.getWorkflow(),n=A?.finalizeStepConfig?.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await(this.workflowManager.getPreviewService()?.renderSceneScreenshot(512,n))||""}const a=document.createElement("canvas");let i=2048;e&&e<=2048&&(i=e),a.width=i,a.height=i;const o=this.commandContext.getAllLayouts(),r=A.defaultPreviewPanelIndex||0,s=A.panels[r],c=o.find((t=>t.layoutState?.layout.panelId===s?.name))||o[0],g=c.layoutState.layout.previewRegion?{x:c.layoutState.layout.previewRegion.left,y:c.layoutState.layout.previewRegion.top,width:c.layoutState.layout.previewRegion.width,height:c.layoutState.layout.previewRegion.height}:{x:0,y:0,width:c.layoutState.layout.width,height:c.layoutState.layout.height},l=this.commandContext.getLayoutById(c.layoutState.layout.id),B=a.getContext("2d");if(!B)throw new ge("Failed to obtain 2D context for preview image creation");const w=P(l.layoutState.layout,l.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:g.x,top:g.y,width:g.width,height:g.height}}}),d=Kt.renderToStaticMarkup(w),h=await jt.from(B,d,{anonymousCrossOrigin:!0,ignoreDimensions:!1});await h.render();const E=await this.getCanvasObjectURLAsync(a);return a.toDataURL(E)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t));if(e&&this.stepHasHandle(e))return Ga.get(this.getWorkflowManager(),e)}getSteps(){return this.getScenes().flatMap((t=>this.getStepsByScene(t)))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map((t=>({id:t.id,name:t.name,stepIds:t.stepNames})))}getSelectionPriceSubunits(){const t=this.getWorkflowManager().getWorkflowSelections();let e=0;return Object.values(t).forEach((t=>{e+=t.selections.map((t=>t.priceModifier)).reduce(((t,e)=>t+e))})),e}getBasePriceSubunits(){return this.getWorkflowManager().getProduct().basePrice||0}getTotalPriceSubunits(){return this.getBasePriceSubunits()+this.getSelectionPriceSubunits()}getBulkStep(){if(this.getWorkflowManager().getTransaction().bulk){const t=this.getWorkflowManager().getProduct().bulkConfiguration,e={type:m.Bulk,stepName:"Bulk",stepTitle:t?.stepTitle??"workflow.steps.bulk.title",helpText:t?.helpText,data:{aspects:Ln(this.getWorkflowManager().getWorkflow())},conditions:[]};return Ga.get(this.getWorkflowManager(),e)}}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepTitle===t));if(e&&this.stepHasHandle(e))return Ga.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((e=>e.type===t)).map((t=>Ga.get(this.getWorkflowManager(),t)))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find((e=>e.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((t=>this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepName===t)))).filter((t=>this.stepHasHandle(t))).map((t=>Ga.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:Ya,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find((e=>e.customer?.emailAddress===t.emailAddress));if(e?.customer){this.getWorkflowManager().setTransactionCustomer(e.customer);const t=de.getMap("transactionCustomerIds")||new Map;t.set(this.getWorkflowManager().getTransaction().id,e.customer.id),de.setMap("transactionCustomerIds",t)}}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 re("State undefined!");const e={title:await(async()=>{if(t)return t;const e=this.getWorkflowManager().getTransaction().id,A=(await Va.getSavedDesigns()).find((t=>t.transactionId===e))?.title;return A||"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 Va.addDesign(e),e}async copy(){const t=zt(this.getCommandContext().getState());if(!t)throw new re("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),A=this.getWorkflowManager().getWorkflow(),n=new Oi({}),a=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!a)throw new re("Integration product id is undefined!");await n.initFromIntegrationProduct(a);return await n.getWorkflowExperience(A.id,e,void 0)}async onDesignFinished(t){return za(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),(()=>this.commandContext.getState()),this.workflowManager.getProduct(),this.workflowManager.getTransaction(),this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),(t=>this.updateVariationRecords(t)),this.workflowManager.getVariationRecords(),(t=>this.createPreviewImage(t)),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==m.SilentIllustration&&t.type!==m.ProductOverlay}getExportedData(){const t=new Map,e=this.getWorkflowManager().getWorkflowMetadata(),A=this.getWorkflowManager().getWorkflowSelections();return Object.keys(e).forEach((A=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===A));if(!n)return;t.has(n.stepTitle)||t.set(n.stepTitle,{});const a=e[A];Object.keys(a).forEach((e=>{t.get(n.stepTitle)[e]=a[e]}))})),Object.keys(A)?.forEach((e=>{const n=this.workflowManager.getWorkflow().steps.find((t=>t.stepName===e));n&&(t.has(n.stepTitle)||t.set(n.stepTitle,{}),t.get(n.stepTitle).selection=A[e].selections[0].name)})),t}}const qa=Zt`
523
523
  ${Zt`
524
524
  fragment ProductCollectionProductFields on Product {
525
525
  id
@@ -616,6 +616,20 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
616
616
  }
617
617
  }
618
618
  `,_a=Zt`
619
+ query GetBundlesForCustomer($id: String!) {
620
+ customers(ids: [$id]) {
621
+ bundleStakeholders {
622
+ id
623
+ type
624
+ bundle {
625
+ id
626
+ name
627
+ createdAt
628
+ }
629
+ }
630
+ }
631
+ }
632
+ `,ti=Zt`
619
633
  ${qa}
620
634
  mutation CreateBundle($collectionId: String) {
621
635
  bundleCreate(collectionId: $collectionId) {
@@ -634,43 +648,43 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
634
648
  }
635
649
  }
636
650
  }
637
- `,ti=Zt`
651
+ `,ei=Zt`
638
652
  mutation UpdateBundle($id: String!, $name: String, $metadata: [MetadataInput!]) {
639
653
  bundleUpdate(id: $id, name: $name, metadata: $metadata) {
640
654
  id
641
655
  }
642
656
  }
643
- `,ei=Zt`
657
+ `,Ai=Zt`
644
658
  mutation BundleAddTransaction($id: String!, $transactionId: String!) {
645
659
  bundleAddTransaction(id: $id, transactionId: $transactionId) {
646
660
  id
647
661
  }
648
662
  }
649
- `,Ai=Zt`
663
+ `,ni=Zt`
650
664
  mutation BundleRemoveTransaction($id: String!, $transactionId: String!) {
651
665
  bundleRemoveTransaction(id: $id, transactionId: $transactionId) {
652
666
  id
653
667
  }
654
668
  }
655
- `,ni=Zt`
669
+ `,ai=Zt`
656
670
  mutation BundleAddStakeholder($id: String!, $details: CustomerDetailsInput!, $type: String!) {
657
671
  bundleAddStakeholder(id: $id, details: $details, type: $type) {
658
672
  id
659
673
  }
660
674
  }
661
- `,ai=Zt`
675
+ `,ii=Zt`
662
676
  mutation BundleUpdateStakeholders($id: String!, $input: [BundleStakeholderInput!]!) {
663
677
  bundleUpdateStakeholders(id: $id, input: $input) {
664
678
  id
665
679
  }
666
680
  }
667
- `,ii=Zt`
681
+ `,oi=Zt`
668
682
  mutation BundleUpdateTransactionOrder($id: String!, $transactionIds: [String!]!) {
669
683
  bundleUpdateTransactionOrder(id: $id, transactionIds: $transactionIds) {
670
684
  id
671
685
  }
672
686
  }
673
- `;function oi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ri{constructor(t){oi(this,"bundle",void 0),oi(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()?.globalPropertyConfiguration)return[];const t=this.bundle.getProductCollection().globalPropertyConfiguration;return Promise.all(t.aspects.map((t=>this.getHandle(t))))}applyConditionsFromState(t,e){return e?t.filter((t=>this.aspectConditionsSatisfied(t.getRawProperty(),e))):t}aspectConditionsSatisfied(t,e){return!t.conditions||0===t.conditions.length||t.conditions.some((t=>{const A=e.aspects.find((e=>e.name===t.targetAspectName));return!!A&&t.requiredVariantSelections.some((t=>t===A.value))}))}async createHandle(t){switch(t.type){case It.FileUpload:return new ci(this.bundle,t);case It.Option:const e=t.entityId?await ke.getOption(t.entityId):void 0;return new li(this.bundle,t,e);case It.Text:return new gi(this.bundle,t)}}}class si{constructor(t,e){oi(this,"bundle",void 0),oi(this,"property",void 0),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}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap((t=>t.getSteps().filter((t=>t.getRaw().globalPropertyAspectConfigurations?.some((t=>t.globalPropertyConfigurationId===this.bundle.getProductCollection()?.globalPropertyConfiguration?.id&&t.aspectName===this.property.name))))))}}class ci extends si{constructor(t,e){super(t,e)}async selectImage(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.key),this.applyImageSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const A=await He.getLocalOrFromServer(e);return A?this.applyImageSelection(A,t):Promise.resolve()}async applyImageSelection(t,e){const A=this.getSharedSteps(e).map((e=>e.selectImage(t)));await Promise.all(A)}}class gi extends si{constructor(t,e){super(t,e)}getText(){const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const A=this.getSharedSteps(e).map((e=>{e.setText(t)}));await Promise.all(A)}}class li extends si{constructor(t,e,A){super(t,e),oi(this,"optionResource",void 0),this.optionResource=A}getCurrentVariant(){if(!this.optionResource)return;const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!t)return;const e=this.optionResource.variants?.find((e=>e.id===t));return e?new fa(e):void 0}getAvailableVariants(){return(this.optionResource?.variants?.filter((t=>t.enabled))||[]).map((t=>new fa(t)))}getAllVariants(){return(this.optionResource?.variants||[]).map((t=>new fa(t)))}async selectVariant(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId()),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const A=this.optionResource?.variants?.find((t=>t.id===e));return A?this.applyVariantSelection(new fa(A),t):Promise.resolve()}async applyVariantSelection(t,e){const A=this.getSharedSteps(e).map((e=>e.selectVariant(t)));await Promise.all(A)}}const Bi=Zt`
687
+ `;function ri(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class si{constructor(t){ri(this,"bundle",void 0),ri(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()?.globalPropertyConfiguration)return[];const t=this.bundle.getProductCollection().globalPropertyConfiguration;return Promise.all(t.aspects.map((t=>this.getHandle(t))))}applyConditionsFromState(t,e){return e?t.filter((t=>this.aspectConditionsSatisfied(t.getRawProperty(),e))):t}aspectConditionsSatisfied(t,e){return!t.conditions||0===t.conditions.length||t.conditions.some((t=>{const A=e.aspects.find((e=>e.name===t.targetAspectName));return!!A&&t.requiredVariantSelections.some((t=>t===A.value))}))}async createHandle(t){switch(t.type){case It.FileUpload:return new gi(this.bundle,t);case It.Option:const e=t.entityId?await ke.getOption(t.entityId):void 0;return new Bi(this.bundle,t,e);case It.Text:return new li(this.bundle,t)}}}class ci{constructor(t,e){ri(this,"bundle",void 0),ri(this,"property",void 0),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}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap((t=>t.getSteps().filter((t=>t.getRaw().globalPropertyAspectConfigurations?.some((t=>t.globalPropertyConfigurationId===this.bundle.getProductCollection()?.globalPropertyConfiguration?.id&&t.aspectName===this.property.name))))))}}class gi extends ci{constructor(t,e){super(t,e)}async selectImage(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.key),this.applyImageSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const A=await He.getLocalOrFromServer(e);return A?this.applyImageSelection(A,t):Promise.resolve()}async applyImageSelection(t,e){const A=this.getSharedSteps(e).map((e=>e.selectImage(t)));await Promise.all(A)}}class li extends ci{constructor(t,e){super(t,e)}getText(){const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const A=this.getSharedSteps(e).map((e=>{e.setText(t)}));await Promise.all(A)}}class Bi extends ci{constructor(t,e,A){super(t,e),ri(this,"optionResource",void 0),this.optionResource=A}getCurrentVariant(){if(!this.optionResource)return;const t=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!t)return;const e=this.optionResource.variants?.find((e=>e.id===t));return e?new fa(e):void 0}getAvailableVariants(){return(this.optionResource?.variants?.filter((t=>t.enabled))||[]).map((t=>new fa(t)))}getAllVariants(){return(this.optionResource?.variants||[]).map((t=>new fa(t)))}async selectVariant(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId()),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name);if(!e)return Promise.resolve();const A=this.optionResource?.variants?.find((t=>t.id===e));return A?this.applyVariantSelection(new fa(A),t):Promise.resolve()}async applyVariantSelection(t,e){const A=this.getSharedSteps(e).map((e=>e.selectVariant(t)));await Promise.all(A)}}const wi=Zt`
674
688
  mutation CreateGlobalPropertyState($bundleId: String!) {
675
689
  globalPropertyStateCreate(bundleId: $bundleId) {
676
690
  id
@@ -680,7 +694,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
680
694
  }
681
695
  }
682
696
  }
683
- `,wi=Zt`
697
+ `,di=Zt`
684
698
  mutation UpdateGlobalPropertyState($id: String!, $aspects: [GlobalPropertyStateAspectInput]!) {
685
699
  globalPropertyStateUpdate(id: $id, aspects: $aspects) {
686
700
  id
@@ -690,7 +704,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
690
704
  }
691
705
  }
692
706
  }
693
- `,di=Zt`
707
+ `,hi=Zt`
694
708
  query GetGlobalPropertyState($bundleId: String!) {
695
709
  globalPropertyState(bundleId: $bundleId) {
696
710
  id
@@ -700,7 +714,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
700
714
  }
701
715
  }
702
716
  }
703
- `;function hi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ei{constructor(t,e){hi(this,"bundleId",void 0),hi(this,"globalPropertyState",void 0),hi(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=zt(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=e:this.globalPropertyState.aspects.push({name:t,value:e}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await ye.getShadowGraphqlClient().mutate({mutation:wi,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await ye.getShadowGraphqlClient().query({query:di,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await ye.getShadowGraphqlClient().mutate({mutation:Bi,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function Ci(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ui{constructor(t,e){Ci(this,"client",void 0),Ci(this,"id",void 0),Ci(this,"name",void 0),Ci(this,"metadata",void 0),Ci(this,"productCollection",void 0),Ci(this,"globalConfiguration",void 0),Ci(this,"globalPropertyStateManager",void 0),Ci(this,"globalPropertyHandleService",void 0),Ci(this,"eventListeners",new Map),Ci(this,"workflowExperiences",[]),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new Ei(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new ri(this)}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],n=A.indexOf(e);n>-1&&A.splice(n,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter((t=>t.getType()===It.Option)).map((t=>t.getCurrentVariant()?.getPrice()||0)).reduce(((t,e)=>t+e),0)}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");await ye.getShadowGraphqlClient().mutate({mutation:ei,variables:{id:this.id,transactionId:e}}),this.workflowExperiences.push(t);const A=await this.getGlobalProperties();await Promise.all(A.map((e=>e.applyGlobalState([t]))))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found!");await ye.getShadowGraphqlClient().mutate({mutation:Ai,variables:{id:this.id,transactionId:e.id}}),this.workflowExperiences.splice(t,1)}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await ye.getShadowGraphqlClient().mutate({mutation:ii,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await ye.getShadowGraphqlClient().mutate({mutation:ni,variables:{id:this.id,details:t,type:e||oA.Owner}})}async updateStakeholders(t){await ye.getShadowGraphqlClient().mutate({mutation:ai,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await ye.getShadowGraphqlClient().query({query:$a,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}_setWorkflowExperiencesInternal(t){this.workflowExperiences=t}async updateBundle(){if(!(await ye.getShadowGraphqlClient().mutate({mutation:ti,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e})))}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async checkConditionalHandlesChanged(t,e){(A=>{const n=this.globalPropertyHandleService.applyConditionsFromState(A,t),a=this.globalPropertyHandleService.applyConditionsFromState(A,e);if(n.length!==a.length)return!0;for(let t=0;t<n.length;t++)if(n[t].getName()!==a[t].getName())return!0;return!1})(await this.globalPropertyHandleService.getHandles())&&this.fireEvent("conditional-global-properties-changed")}fireEvent(t){(this.eventListeners.get(t)||[]).forEach((t=>t()))}}function Qi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const pi=ft`
717
+ `;function Ei(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ci{constructor(t,e){Ei(this,"bundleId",void 0),Ei(this,"globalPropertyState",void 0),Ei(this,"onGlobalPropertyStateChange",void 0),this.bundleId=t,this.getOrCreateGlobalPropertyState().then((t=>this.globalPropertyState=t)),this.onGlobalPropertyStateChange=e}getGlobalPropertyState(){return this.globalPropertyState}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find((e=>e.name===t));if(e)return e.value}async setAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=zt(this.globalPropertyState),n=this.globalPropertyState.aspects.find((e=>e.name===t));n?n.value=e:this.globalPropertyState.aspects.push({name:t,value:e}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await ye.getShadowGraphqlClient().mutate({mutation:di,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects}});if(!t.data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state");this.globalPropertyState=t.data.globalPropertyStateUpdate}async getOrCreateGlobalPropertyState(){const t=await ye.getShadowGraphqlClient().query({query:hi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await ye.getShadowGraphqlClient().mutate({mutation:wi,variables:{bundleId:this.bundleId}});if(e.data?.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}function ui(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Qi{constructor(t,e){ui(this,"client",void 0),ui(this,"id",void 0),ui(this,"name",void 0),ui(this,"metadata",void 0),ui(this,"productCollection",void 0),ui(this,"globalConfiguration",void 0),ui(this,"globalPropertyStateManager",void 0),ui(this,"globalPropertyHandleService",void 0),ui(this,"eventListeners",new Map),ui(this,"workflowExperiences",[]),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new Ci(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new si(this)}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],n=A.indexOf(e);n>-1&&A.splice(n,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.globalConfiguration&&this.globalConfiguration.aspects.length>0}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter((t=>t.getType()===It.Option)).map((t=>t.getCurrentVariant()?.getPrice()||0)).reduce(((t,e)=>t+e),0)}getTotalSubunits(){return this.workflowExperiences.map((t=>t.getTotalPriceSubunits())).reduce(((t,e)=>t+e),0)}getProductCollection(){return this.productCollection}async addWorkflowExperience(t){const e=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e)))throw new Error("Unable to add transaction to bundle - Already Exists!");await ye.getShadowGraphqlClient().mutate({mutation:Ai,variables:{id:this.id,transactionId:e}}),this.workflowExperiences.push(t);const A=await this.getGlobalProperties();await Promise.all(A.map((e=>e.applyGlobalState([t]))))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeTransaction(t,e){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found!");await ye.getShadowGraphqlClient().mutate({mutation:ni,variables:{id:this.id,transactionId:e.id}}),this.workflowExperiences.splice(t,1)}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await ye.getShadowGraphqlClient().mutate({mutation:oi,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){await ye.getShadowGraphqlClient().mutate({mutation:ai,variables:{id:this.id,details:t,type:e||oA.Owner}})}async updateStakeholders(t){await ye.getShadowGraphqlClient().mutate({mutation:ii,variables:{id:this.id,input:t}})}async getAllStakeholders(){const t=await ye.getShadowGraphqlClient().query({query:$a,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");return t.data.bundles[0].bundleStakeholders||[]}async finish(){return Promise.all(this.workflowExperiences.map((t=>t.onDesignFinished())))}_setWorkflowExperiencesInternal(t){this.workflowExperiences=t}async updateBundle(){if(!(await ye.getShadowGraphqlClient().mutate({mutation:ei,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e})))}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async checkConditionalHandlesChanged(t,e){(A=>{const n=this.globalPropertyHandleService.applyConditionsFromState(A,t),a=this.globalPropertyHandleService.applyConditionsFromState(A,e);if(n.length!==a.length)return!0;for(let t=0;t<n.length;t++)if(n[t].getName()!==a[t].getName())return!0;return!1})(await this.globalPropertyHandleService.getHandles())&&this.fireEvent("conditional-global-properties-changed")}fireEvent(t){(this.eventListeners.get(t)||[]).forEach((t=>t()))}}function pi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const mi=ft`
704
718
  mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
705
719
  processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
706
720
  id
@@ -710,7 +724,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
710
724
  }
711
725
  }
712
726
  }
713
- `;class mi{async execute(t,e,A){if(!(await ye.getShadowGraphqlClient().mutate({mutation:pi,variables:{processFlowId:t,inputs:[...e.map((t=>t.getValueForTransmission()))]}})).data?.processExecutionCreate?.id)throw new Error("Failed to create process execution.");function n(t){return new Promise((e=>{setTimeout(e,t)}))}let a,i=!1,o=0;for(;!i;){if(await n(A?.sleepTime?Math.max(A.sleepTime,500):2e3),a=await ye.getShadowGraphqlClient().query({query:ft`
727
+ `;class Di{async execute(t,e,A){if(!(await ye.getShadowGraphqlClient().mutate({mutation:mi,variables:{processFlowId:t,inputs:[...e.map((t=>t.getValueForTransmission()))]}})).data?.processExecutionCreate?.id)throw new Error("Failed to create process execution.");function n(t){return new Promise((e=>{setTimeout(e,t)}))}let a,i=!1,o=0;for(;!i;){if(await n(A?.sleepTime?Math.max(A.sleepTime,500):2e3),a=await ye.getShadowGraphqlClient().query({query:ft`
714
728
  query getProcessFlowExecution($ids: [String]!) {
715
729
  processExecutions(ids: $ids) {
716
730
  id
@@ -722,7 +736,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
722
736
  }
723
737
  }
724
738
  }
725
- `,variables:{ids:[t]}}),!a||!a.data?.getProcessFlowExecution)throw new Error("Failed to retrieve server response for execution.");const e=a.data?.getProcessFlowExecution?.completedAt;if(e){i=!0;break}if(a.data?.getProcessFlowExecution?.failedAt)throw new Error("Execution has failed to complete. See Executions tab in partner account on SpiffCommerce Hub.");if(o+=1,o>=5)throw new Error("Maximum wait time exceeded for execution result.")}return Promise.resolve(a.data?.getProcessFlowExecution)}}class Di{constructor(t){Qi(this,"value",void 0),this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):JSON.stringify(t)}}let Ii;var fi;(fi=Ii||(Ii={})).Transaction="Transaction",fi.Bundle="Bundle",fi.Product="Product",fi.Variant="Variant",fi.Option="Option",fi.LineItem="LineItem",fi.Asset="Asset";class yi extends Di{constructor(t,e){if("Asset"!==e&&!yi.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 Mi extends Di{constructor(t){super(t)}}function Fi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Yi=ft`
739
+ `,variables:{ids:[t]}}),!a||!a.data?.getProcessFlowExecution)throw new Error("Failed to retrieve server response for execution.");const e=a.data?.getProcessFlowExecution?.completedAt;if(e){i=!0;break}if(a.data?.getProcessFlowExecution?.failedAt)throw new Error("Execution has failed to complete. See Executions tab in partner account on SpiffCommerce Hub.");if(o+=1,o>=5)throw new Error("Maximum wait time exceeded for execution result.")}return Promise.resolve(a.data?.getProcessFlowExecution)}}class Ii{constructor(t){pi(this,"value",void 0),this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):JSON.stringify(t)}}let fi;var yi;(yi=fi||(fi={})).Transaction="Transaction",yi.Bundle="Bundle",yi.Product="Product",yi.Variant="Variant",yi.Option="Option",yi.LineItem="LineItem",yi.Asset="Asset";class Mi extends Ii{constructor(t,e){if("Asset"!==e&&!Mi.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 Fi extends Ii{constructor(t){super(t)}}function Yi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Si=ft`
726
740
  fragment RegionFields on Region {
727
741
  width
728
742
  top
@@ -740,7 +754,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
740
754
  height
741
755
  }
742
756
  }
743
- `,Si=ft`
757
+ `,vi=ft`
744
758
  fragment LookAtAnimationFields on LookAtAnimation {
745
759
  latDeg
746
760
  lonDeg
@@ -751,7 +765,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
751
765
  z
752
766
  }
753
767
  }
754
- `,vi=ft`
768
+ `,xi=ft`
755
769
  fragment RenderingPipelineConfigurationFields on RenderingPipelineConfiguration {
756
770
  antiAliasing {
757
771
  samples
@@ -835,21 +849,21 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
835
849
  weight
836
850
  }
837
851
  }
838
- `,xi=ft`
852
+ `,Ni=ft`
839
853
  fragment ModelAnimationFields on ModelAnimation {
840
854
  from
841
855
  to
842
856
  loop
843
857
  name
844
858
  }
845
- `,Ni=ft`
859
+ `,Pi=ft`
846
860
  ${Fe}
847
861
  ${Se}
848
862
  ${be}
849
- ${Yi}
850
863
  ${Si}
851
864
  ${vi}
852
865
  ${xi}
866
+ ${Ni}
853
867
  query GetWorkflow($id: String!) {
854
868
  workflow(id: $id) {
855
869
  allowProofDownload
@@ -1226,7 +1240,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
1226
1240
  }
1227
1241
  }
1228
1242
  }
1229
- `,Pi=ft`
1243
+ `,Ri=ft`
1230
1244
  query GetTransactionForPartner($id: String!) {
1231
1245
  transactions(ids: [$id]) {
1232
1246
  id
@@ -1243,7 +1257,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
1243
1257
  }
1244
1258
  }
1245
1259
  }
1246
- `,Ri=ft`
1260
+ `,Hi=ft`
1247
1261
  ${Fe}
1248
1262
  query GetWorkflowForTheme($id: String!) {
1249
1263
  workflow(id: $id) {
@@ -1265,21 +1279,21 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
1265
1279
  }
1266
1280
  }
1267
1281
  }
1268
- `,Hi=ft`
1282
+ `,Ui=ft`
1269
1283
  query GetCustomer($emailAddress: String!) {
1270
1284
  customer(emailAddress: $emailAddress) {
1271
1285
  id
1272
1286
  emailAddress
1273
1287
  }
1274
1288
  }
1275
- `,Ui=ft`
1289
+ `,bi=ft`
1276
1290
  mutation CustomerCreate($details: CustomerDetailsInput!) {
1277
1291
  customerCreate(details: $details) {
1278
1292
  id
1279
1293
  emailAddress
1280
1294
  }
1281
1295
  }
1282
- `,bi=ft`
1296
+ `,Gi=ft`
1283
1297
  mutation CustomerAuthenticate($loginToken: String!) {
1284
1298
  customerAuthenticate(loginToken: $loginToken) {
1285
1299
  id
@@ -1303,11 +1317,11 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
1303
1317
  }
1304
1318
  }
1305
1319
  }
1306
- `,Gi=ft`
1320
+ `,ki=ft`
1307
1321
  mutation CustomerGenerateVerificationCode($emailAddress: String!) {
1308
1322
  customerGenerateVerificationCode(emailAddress: $emailAddress)
1309
1323
  }
1310
- `,ki=ft`
1324
+ `,Ji=ft`
1311
1325
  mutation CustomerVerifyCode($emailAddress: String!, $verificationCode: String!) {
1312
1326
  customerVerifyCode(emailAddress: $emailAddress, verificationCode: $verificationCode) {
1313
1327
  id
@@ -1335,5 +1349,5 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
1335
1349
  }
1336
1350
  }
1337
1351
  }
1338
- `,Ji=async t=>{const e=(await ye.getShadowGraphqlClient().query({query:Ni,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}})).data.workflow;return e.steps.forEach((t=>{delete t.data.__typename})),e},Li=(t,e)=>{const A=t.workflowState,n=A?JSON.parse(A):void 0;return n?Object.values(n.layouts).map((t=>t.layout)):e.panels.sort(((t,e)=>t.index-e.index)).map((t=>({id:F(),panelId:t.name,name:t.name,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})))};class Ti{constructor(t){var e;Fi(this,"options",void 0),Fi(this,"initialized",void 0),Fi(this,"currencyCode",void 0),Fi(this,"customer",void 0),Fi(this,"experienceOptions",void 0),Fi(this,"updateTransactionState",(async t=>{try{return ye.getShadowGraphqlClient().mutate({...t,mutation:Un})}catch(t){throw console.error(t),new ce("Critical - Unable to synchronize workflow state with server.")}})),this.initialized=!1,this.options=t,this.options.applicationKey&&(e=this.options.applicationKey,fe=e)}getAssetManager(){return He}getCurrencyCode(){if(void 0===this.currencyCode)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!this.options.applicationKey)throw new Error("Application key required to use Flow Service.");return new mi}async authenticateBundleFromLocalStorage(t){const e=de.getMap("bundleOwnerIds");if(e?.has(t)){const A=e.get(t);return me(A),Promise.resolve({success:!0,stakeholderType:oA.Owner})}const A=de.getMap("bundleCustomerIds");if(A?.has(t)){const e=A.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=ye.getShadowGraphqlClient(),A=await e.query({query:Pi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||0===A.data.transactions.length)throw new Error(`Transaction not found: ${t}`);const n=A.data.transactions[0],a=n.product?.partner?.id;if(!a)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const i=de.getMap("transactionOwnerIds");if(i?.has(t)){const e=i.get(t);return Qe(e),Promise.resolve({success:!0,stakeholderType:oA.Owner})}const o=de.getMap("transactionCustomerIds");if(o?.has(t)){const e=o.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.transactions?.some((e=>e.id===t))))||this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}const r=(await e.query({query:Ri,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!r)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:r.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=de.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),de.setMap("transactionCustomerIds",e))}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=ye.getShadowGraphqlClient(),A=(await e.query({query:Hi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!A.id){const A=(await e.mutate({mutation:Ui,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!A)throw new Error("Unable to create customer.");return this.customer=A,{customer:A,isAuthenticated:!1}}const n=await this.authenticateCustomerId(A.id);return{customer:this.customer||A,isAuthenticated:n}}async authenticateCustomerId(t){const e=ye.getShadowGraphqlClient(),A=de.getMap("customerTokens");if(!A?.has(t))return!1;const n=A.get(t);if(!n)return!1;const a=(await e.mutate({mutation:bi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data?.customerAuthenticate;return!!a&&(Ie(n),this.customer=a,!0)}async generateVerificationCode(t){await ye.getShadowGraphqlClient().mutate({mutation:Gi,variables:{emailAddress:t}})}async verifyCode(t,e){const A=(await ye.getShadowGraphqlClient().mutate({mutation:ki,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data?.customerVerifyCode;if(A?.loginToken){if(!A.partner?.id)throw new Error(`Unable to find customer: ${t}`);const e=de.getMap("customerTokens")||new Map;return e.set(A.id,A.loginToken),de.setMap("customerTokens",e),Ie(A.loginToken),this.customer={...A,loginToken:void 0},!0}return!1}async getNewBundle(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:_a,variables:{collectionId:t},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!e)throw new Error("Unable to create bundle");me(e.bundleOwnerId);const A=de.getMap("bundleOwnerIds")||new Map;return A.set(e.id,e.bundleOwnerId),de.setMap("bundleOwnerIds",A),new ui(this,e)}async getExistingBundle(t,e){const A=de.getMap("bundleOwnerIds")?.get(t);A&&me(A);const n=await ye.getShadowGraphqlClient().query({query:Za,variables:{id:t},fetchPolicy:"no-cache"});if(!n.data?.bundles||0===n.data?.bundles.length||!n.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const a=n.data?.bundles[0],i=new ui(this,a);if(a.transactions&&a.transactions.length>0){const t=t=>{const A=e?A=>e(A,t):void 0;return this.getWorkflowExperience(void 0,void 0,A,{type:"transaction",transactionId:t})},A=await Promise.all(a.transactions.map((e=>t(e.id))));i._setWorkflowExperiencesInternal(A)}return i}async getWorkflowExperience(t,e,A,n){if(!n)return await this.getWorkflowExperienceDeprecated(t,e,A);const a=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}},{transaction:i,workflow:o,readOnly:r}=await(async()=>{const t=ye.getShadowGraphqlClient();if("transaction"===n.type){const{transactionId:e,readOnly:A}=n,a=await t.query({query:Hn,variables:{id:e},errorPolicy:"all",fetchPolicy:"no-cache"});if(!a.data?.transactions||0===a.data.transactions.length)throw new ce("Existing transaction not found.");const i=a.data?.transactions[0];if(!i.workflowId)throw new ce("Existing transaction has no workflow ID.");const o=await Ji(i.workflowId);if(!i.product)throw new ce("Failed to load transaction, product not available.");return{transaction:i,workflow:o,readOnly:A}}if("integration"===n.type||"external"===n.type){const e=async()=>{const e="integration"===n.type?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},A=await t.mutate({mutation:Pn,variables:{...e,bulk:n.bulk,workflowId:n.workflowId,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new ce("Failed to create transaction, product not available.");return a},A=Ji(n.workflowId),[a,i]=await Promise.all([e(),A]);return{transaction:a,workflow:i}}throw new ce("No workflow ID provided.")})();this.currencyCode=i.product.partner?.currencyCode;const s={product:i.product,transaction:i,layouts:[],stateMutationFunc:r?async()=>{throw new re("State mutation is forbidden in read only mode!")}:this.updateTransactionState,readOnly:r,workflow:o};if("transaction"===n.type&&i.workflowState){const t=JSON.parse(i.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else if(!r&&n.workflowState){const t=JSON.parse(n.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else s.layouts=Li(s.transaction,s.workflow);if(s.renderableContextService=new fn(s.layouts),n.previewService?(s.previewService=n.previewService,s.product?.modelUrl&&(s.modelContainer=s.previewService.loadModel({model:s.product.modelUrl,contextService:s.renderableContextService}))):(s.previewService=A&&A(o),s.product?.modelUrl&&(s.previewService?.initialize({model:s.product.modelUrl,contextService:s.renderableContextService}),s.modelContainer=s.previewService?.getAllModels()[0])),"transaction"!==n.type){const t=de.getMap("transactionOwnerIds")||new Map;t.set(i.id,i.transactionOwnerId),Qe(i.transactionOwnerId||""),de.setMap("transactionOwnerIds",t)}else{const t=(de.getMap("transactionOwnerIds")||new Map).get(i.id);t&&Qe(t),s.isReloadedTransaction=!0}this.initialized=!0,this.experienceOptions=s;const c=new Xa(this,s);return await c.getWorkflowManager().getInitializationPromise(),"transaction"!==n.type&&this.customer&&await c.attachCustomerDetails({email:this.customer.emailAddress}),c}async initFromIntegrationProduct(t){if(""===t)throw new ce("No integration product ID provided.");const e=ye.getShadowGraphqlClient(),A=await e.mutate({mutation:Pn,variables:{integrationProductId:t,bulk:this.options.bulk||!1,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new ce("Failed to create transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode;const a=de.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),Qe(n.transactionOwnerId||""),de.setMap("transactionOwnerIds",a),this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState},this.initialized=!0}async initFromTransaction(t,e=!1){if(""===t)throw new ce("No transaction ID provided.");const A=ye.getShadowGraphqlClient();if(e)return await(async()=>{const n=(await A.query({query:Hn,variables:{id:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:async()=>{throw new re("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0})();const n=de.getMap("transactionOwnerIds")||new Map,a=n.get(t);if(a){Qe(a);const n=(await A.query({query:Hn,variables:{id:t},errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");return this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},void(this.initialized=!0)}try{const a=(await A.mutate({mutation:Rn,variables:{id:t},errorPolicy:"all"})).data?.transactionClaim;if(!a)throw new ce("Failed to read transaction.");if(!a.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=a.product.partner?.currencyCode,a.transactionOwnerId&&(n.set(a.id,a.transactionOwnerId),Qe(a.transactionOwnerId),de.setMap("transactionOwnerIds",n)),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},this.initialized=!0}catch{throw new ce("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot launch experience: Not initialized.");const n=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}};if(this.experienceOptions.transaction.workflowId){const t=await Ji(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=t,this.experienceOptions.transaction.workflowState){const t=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}this.experienceOptions.previewService=A&&A(t),this.experienceOptions.renderableContextService=new fn(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const e=new Xa(this,this.experienceOptions);return await e.getWorkflowManager().getInitializationPromise(),e}if(t){const a=ye.getShadowGraphqlClient().mutate({mutation:bn,variables:{workflowId:t,id:this.experienceOptions.transaction.id}}),i=Ji(t);if(await Promise.all([a,i]),this.experienceOptions.workflow=await i,e){const t=JSON.parse(e);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}else this.experienceOptions.layouts=Li(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await i),this.experienceOptions.renderableContextService=new fn(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const o=new Xa(this,this.experienceOptions);return await o.getWorkflowManager().getInitializationPromise(),o}throw new ce("No workflow ID provided.")}getPreviewService(){return this.experienceOptions?.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}}function Oi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class zi{constructor(){Oi(this,"getProduct",void 0),Oi(this,"getCommandContext",void 0),Oi(this,"getAllLayoutData",void 0),Oi(this,"getMetadata",void 0),Oi(this,"getWorkflowMetadata",void 0),Oi(this,"getStepStorage",void 0),Oi(this,"setModelContainer",void 0),Oi(this,"getUpdatesPending",void 0)}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}getVariationRecords(){return[]}async reset(){}updateStateWithServer(t){}addVariationRecord(t){return{recordNumber:0,transactionId:"",values:[]}}getCurrentVariationRecord(){}removeVariationRecord(t){return[]}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addCurrentVariationCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}addVariationRecordsCallback(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{}}setCurrentAdjustingStepId(t){}setCurrentVariationRecord(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,A){}setVariationRecords(t){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}}function ji(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Ki;var Vi;(Vi=Ki||(Ki={})).SelectFrame="SelectFrame",Vi.SelectImage="SelectImage",Vi.Position="Position";class Wi extends Ma{constructor(t,e){super(t,e),ji(this,"frameService",this.manager.getStepSpecificServices(this.getId())?.frameService)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ia.selectVariant(this.step,t.getResource(),e,this.manager,(t=>this.setUpdateState(t)))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged((e=>{e&&t(e)}))}selectImage(t){return ia.selectImage(this.step,t,this.manager)}getImageData(){if(this.frameService)return this.frameService.getImageData()}getCurrentFrameStep(t,e,A,n){return n&&n.length>1&&void 0===t?Ki.SelectFrame:e||A||this.getImageData()?Ki.Position:Ki.SelectImage}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}hasVaryingUpload(){return this.step.data.varyUpload}hasVaryingSelection(){return this.step.data.varySelection}}const Xi=t=>{const e=kt(null),A=kt(void 0),[n,a]=Pt(void 0),{addEvent:i,removeEvent:o,updateEvent:r,eventCache:s}=Le(),[c,g]=Pt(!1),[l,B]=Pt(!1),{state:w,uiDispatcher:d}=Ze(),h=Rt((t=>{const e=t;d(new qe({zoom:Math.max(.1,Math.min(e,w.maxZoom))}))}),[d,w.maxZoom]),E=Rt((t=>{o(t),1===s.length&&(A.current=void 0),2===s.length&&a(void 0);"touch"===t.pointerType&&s.length>1&&s.length-1==1&&(B(!1),g(!1))}),[o,s.length]),C=Rt((t=>{i(t);"touch"===t.pointerType&&1===s.length&&(d(new qe({selectedElement:void 0})),B(!0),g(!0))}),[i,s.length,d]),u=Rt((t=>{r(t);const e=1===s.length&&"touch"!==s[0].pointerType,i=2===s.length&&"touch"===s[0].pointerType;if(c&&i){const[t,e]=s,A=Math.abs(t.clientX-e.clientX),i=n;i&&h(w.zoom-.0055*(i-A)),a(A)}if(l&&(e||i)&&t.isPrimary){const e=(A?.current?.x||t.screenX)-t.screenX,n=(A?.current?.y||t.screenY)-t.screenY;d(new qe({selectedElement:void 0,xTranslation:w.xTranslation-e/w.zoom,yTranslation:w.yTranslation-n/w.zoom}))}t.isPrimary&&(A.current={x:t.screenX,y:t.screenY})}),[r,s,c,l,n,h,w.zoom,w.xTranslation,w.yTranslation,d]),Q=Rt((t=>{c&&h(w.zoom-.035*Math.sign(t.deltaY))}),[h,w.zoom,c]);Ut((()=>{if(!e.current||0===s.length)return;const t=s[0].pointerId,A=e.current.hasPointerCapture(t);l&&!A&&e.current.setPointerCapture(t),!l&&A&&e.current.releasePointerCapture(t)}),[e,l,s]),JA([" "],(()=>{B(!0),d(new qe({selectedElement:void 0}))}),(()=>B(!1))),JA(["Control"],(()=>g(!0)),(()=>g(!1)));const p=Gt((()=>({cursor:l&&0===s.length?"grab":l&&1===s.length?"grabbing":c?"zoom-in":void 0,width:"100%",height:"100%",overflow:"clip"})),[l,c,s]);return Jt("div",{ref:e,className:"transform-wrapper",onWheel:Q,onPointerDown:C,onPointerUp:E,onPointerCancel:E,onPointerLeave:E,onPointerMove:u,style:p,children:t.children})};export{Ti as SpiffCommerceClient,t as CommandContext,Ee as spiffCoreConfiguration,zA as PromiseQueue,OA as QueueablePromise,zi as MockWorkflowManager,Qa as InformationMessageType,Ma as StepHandle,ba as TextStepHandle,Wi as FrameStepHandle,va as BulkStepHandle,Ua as ShapeStepHandle,xa as IllustrationStepHandle,Na as MaterialStepHandle,Pa as ModelStepHandle,Ra as PictureStepHandle,Ha as QuestionStepHandle,tA as BulkPriceCalculationStrategy,fa as Variant,ee as OptionNotFoundError,Ae as LayoutNotFoundError,ne as AssetNotFoundError,ae as ResourceNotFoundError,ie as MisconfigurationError,se as ParseError,re as UnhandledBehaviorError,He as assetService,Va as designService,za as createDesign,ke as optionService,de as persistenceService,ye as graphQlManager,gA as toast,Zn as FrameService,Xn as getBoundedOffsets,ia as frameStepService,sa as modelStepService,ra as materialStepService,Ba as shapeStepService,la as questionStepService,na as digitalContentStepService,ca as moduleStepService,ga as pictureStepService,Ca as textStepService,oa as illustrationStepService,$e as ProductCameraRig,Ki as FrameStep,AA as ConversionLocation,aA as ConversionDataType,Ji as getWorkflow,ta as shortenUrl,yi as ObjectInput,Mi as TextInput,Ii as ObjectInputType,e as AssetType,A as BringForwardCommand,n as BringToFrontCommand,a as BringToBackCommand,i as CanvasCommand,o as CreateElementCommand,r as CreateLayoutCommand,s as DeleteElementCommand,c as FontAlignmentCommand,g as FontColorCommand,l as FontSizeCommand,B as FontSourceCommand,w as GroupCommand,d as LayoutElementFactory,h as LayoutElementType,E as MoveCommand,C as ResizeCommand,u as RotateCommand,Q as SendBackwardsCommand,oA as StakeholderType,p as StepAspectType,m as StepType,D as TextChangeCommand,I as UnitOfMeasurement,f as dataUrlFromExternalUrl,y as findElement,M as frameDataCache,F as generate,Y as getAxisAlignedBoundingBox,S as generateSVGWithUnknownColors,v as getAttributesFromArrayBuffer,x as rehydrateSerializedLayout,N as getFrameData,P as getSvgElement,R as loadFontFromDataUrl,H as loadFontFromExternalUrl,U as determineCorrectFontSizeAndLines,b as patternImageDataCache,Dn as generateCommands,G as registerJSDOM,bA as minZoom,Nn as AdvancedEditor,Xi as TransformWrapper,xn as EditorCore,Te as useLayouts,Ze as useEditorState,kA as useEditorInteraction,JA as useShortcutCombination,Ve as commandReducer,Ke as getDefaultState,Je as CommandContextContext,Xe as AdvancedEditorStateProvider,We as AdvancedEditorContext,qe as UICommand,ze as EditorSubMenu,lA as ElementEventType,wA as KeyEvent,Ln as gatherVaryingStepAspects};
1352
+ `,Li=async t=>{const e=(await ye.getShadowGraphqlClient().query({query:Pi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}})).data.workflow;return e.steps.forEach((t=>{delete t.data.__typename})),e},Ti=(t,e)=>{const A=t.workflowState,n=A?JSON.parse(A):void 0;return n?Object.values(n.layouts).map((t=>t.layout)):e.panels.sort(((t,e)=>t.index-e.index)).map((t=>({id:F(),panelId:t.name,name:t.name,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})))};class Oi{constructor(t){var e;Yi(this,"options",void 0),Yi(this,"initialized",void 0),Yi(this,"currencyCode",void 0),Yi(this,"customer",void 0),Yi(this,"experienceOptions",void 0),Yi(this,"updateTransactionState",(async t=>{try{return ye.getShadowGraphqlClient().mutate({...t,mutation:Un})}catch(t){throw console.error(t),new ce("Critical - Unable to synchronize workflow state with server.")}})),this.initialized=!1,this.options=t,this.options.applicationKey&&(e=this.options.applicationKey,fe=e)}getAssetManager(){return He}getCurrencyCode(){if(void 0===this.currencyCode)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!this.options.applicationKey)throw new Error("Application key required to use Flow Service.");return new Di}async authenticateBundleFromLocalStorage(t){const e=de.getMap("bundleOwnerIds");if(e?.has(t)){const A=e.get(t);return me(A),Promise.resolve({success:!0,stakeholderType:oA.Owner})}const A=de.getMap("bundleCustomerIds");if(A?.has(t)){const e=A.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=ye.getShadowGraphqlClient(),A=await e.query({query:Ri,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||0===A.data.transactions.length)throw new Error(`Transaction not found: ${t}`);const n=A.data.transactions[0],a=n.product?.partner?.id;if(!a)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const i=de.getMap("transactionOwnerIds");if(i?.has(t)){const e=i.get(t);return Qe(e),Promise.resolve({success:!0,stakeholderType:oA.Owner})}const o=de.getMap("transactionCustomerIds");if(o?.has(t)){const e=o.get(t);if(e){if(await this.authenticateCustomerId(e)){const e=this.customer?.bundleStakeholders?.find((e=>e.bundle?.transactions?.some((e=>e.id===t))))||this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return Promise.resolve({success:!0,stakeholderType:e.type})}}}const r=(await e.query({query:Hi,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!r)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:r.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=de.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),de.setMap("transactionCustomerIds",e))}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find((e=>e.transaction?.id===t));if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=ye.getShadowGraphqlClient(),A=(await e.query({query:Ui,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!A.id){const A=(await e.mutate({mutation:bi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!A)throw new Error("Unable to create customer.");return this.customer=A,{customer:A,isAuthenticated:!1}}const n=await this.authenticateCustomerId(A.id);return{customer:this.customer||A,isAuthenticated:n}}async authenticateCustomerId(t){const e=ye.getShadowGraphqlClient(),A=de.getMap("customerTokens");if(!A?.has(t))return!1;const n=A.get(t);if(!n)return!1;const a=(await e.mutate({mutation:Gi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data?.customerAuthenticate;return!!a&&(Ie(n),this.customer=a,!0)}async generateVerificationCode(t){await ye.getShadowGraphqlClient().mutate({mutation:ki,variables:{emailAddress:t}})}async verifyCode(t,e){const A=(await ye.getShadowGraphqlClient().mutate({mutation:Ji,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data?.customerVerifyCode;if(A?.loginToken){if(!A.partner?.id)throw new Error(`Unable to find customer: ${t}`);const e=de.getMap("customerTokens")||new Map;return e.set(A.id,A.loginToken),de.setMap("customerTokens",e),Ie(A.loginToken),this.customer={...A,loginToken:void 0},!0}return!1}async getNewBundle(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:ti,variables:{collectionId:t},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!e)throw new Error("Unable to create bundle");me(e.bundleOwnerId);const A=de.getMap("bundleOwnerIds")||new Map;return A.set(e.id,e.bundleOwnerId),de.setMap("bundleOwnerIds",A),new Qi(this,e)}async getExistingBundle(t,e){const A=de.getMap("bundleOwnerIds")?.get(t);A&&me(A);const n=await ye.getShadowGraphqlClient().query({query:Za,variables:{id:t},fetchPolicy:"no-cache"});if(!n.data?.bundles||0===n.data?.bundles.length||!n.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const a=n.data?.bundles[0],i=new Qi(this,a);if(a.transactions&&a.transactions.length>0){const t=t=>{const A=e?A=>e(A,t):void 0;return this.getWorkflowExperience(void 0,void 0,A,{type:"transaction",transactionId:t})},A=await Promise.all(a.transactions.map((e=>t(e.id))));i._setWorkflowExperiencesInternal(A)}return i}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await ye.getShadowGraphqlClient().query({query:_a,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||0===t.data.customers.length)throw new Error("Unable to find customer.");return t.data.customers[0].bundleStakeholders||[]}async getWorkflowExperience(t,e,A,n){if(!n)return await this.getWorkflowExperienceDeprecated(t,e,A);const a=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}},{transaction:i,workflow:o,readOnly:r}=await(async()=>{const t=ye.getShadowGraphqlClient();if("transaction"===n.type){const{transactionId:e,readOnly:A}=n,a=await t.query({query:Hn,variables:{id:e},errorPolicy:"all",fetchPolicy:"no-cache"});if(!a.data?.transactions||0===a.data.transactions.length)throw new ce("Existing transaction not found.");const i=a.data?.transactions[0];if(!i.workflowId)throw new ce("Existing transaction has no workflow ID.");const o=await Li(i.workflowId);if(!i.product)throw new ce("Failed to load transaction, product not available.");return{transaction:i,workflow:o,readOnly:A}}if("integration"===n.type||"external"===n.type){const e=async()=>{const e="integration"===n.type?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},A=await t.mutate({mutation:Pn,variables:{...e,bulk:n.bulk,workflowId:n.workflowId,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new ce("Failed to create transaction, product not available.");return a},A=Li(n.workflowId),[a,i]=await Promise.all([e(),A]);return{transaction:a,workflow:i}}throw new ce("No workflow ID provided.")})();this.currencyCode=i.product.partner?.currencyCode;const s={product:i.product,transaction:i,layouts:[],stateMutationFunc:r?async()=>{throw new re("State mutation is forbidden in read only mode!")}:this.updateTransactionState,readOnly:r,workflow:o};if("transaction"===n.type&&i.workflowState){const t=JSON.parse(i.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else if(!r&&n.workflowState){const t=JSON.parse(n.workflowState);s.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await a(t),s.reloadedState=t}else s.layouts=Ti(s.transaction,s.workflow);if(s.renderableContextService=new fn(s.layouts),n.previewService?(s.previewService=n.previewService,s.product?.modelUrl&&(s.modelContainer=s.previewService.loadModel({model:s.product.modelUrl,contextService:s.renderableContextService}))):(s.previewService=A&&A(o),s.product?.modelUrl&&(s.previewService?.initialize({model:s.product.modelUrl,contextService:s.renderableContextService}),s.modelContainer=s.previewService?.getAllModels()[0])),"transaction"!==n.type){const t=de.getMap("transactionOwnerIds")||new Map;t.set(i.id,i.transactionOwnerId),Qe(i.transactionOwnerId||""),de.setMap("transactionOwnerIds",t)}else{const t=(de.getMap("transactionOwnerIds")||new Map).get(i.id);t&&Qe(t),s.isReloadedTransaction=!0}this.initialized=!0,this.experienceOptions=s;const c=new Xa(this,s);return await c.getWorkflowManager().getInitializationPromise(),"transaction"!==n.type&&this.customer&&await c.attachCustomerDetails({email:this.customer.emailAddress}),c}async initFromIntegrationProduct(t){if(""===t)throw new ce("No integration product ID provided.");const e=ye.getShadowGraphqlClient(),A=await e.mutate({mutation:Pn,variables:{integrationProductId:t,bulk:this.options.bulk||!1,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new ce("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new ce("Failed to create transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode;const a=de.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),Qe(n.transactionOwnerId||""),de.setMap("transactionOwnerIds",a),this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState},this.initialized=!0}async initFromTransaction(t,e=!1){if(""===t)throw new ce("No transaction ID provided.");const A=ye.getShadowGraphqlClient();if(e)return await(async()=>{const n=(await A.query({query:Hn,variables:{id:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:async()=>{throw new re("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0})();const n=de.getMap("transactionOwnerIds")||new Map,a=n.get(t);if(a){Qe(a);const n=(await A.query({query:Hn,variables:{id:t},errorPolicy:"all"})).data?.transactions[0];if(!n)throw new ce("Failed to read transaction.");if(!n.product)throw new ce("Failed to load transaction, product not available.");return this.currencyCode=n.product.partner?.currencyCode,this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},void(this.initialized=!0)}try{const a=(await A.mutate({mutation:Rn,variables:{id:t},errorPolicy:"all"})).data?.transactionClaim;if(!a)throw new ce("Failed to read transaction.");if(!a.product)throw new ce("Failed to load transaction, product not available.");this.currencyCode=a.product.partner?.currencyCode,a.transactionOwnerId&&(n.set(a.id,a.transactionOwnerId),Qe(a.transactionOwnerId),de.setMap("transactionOwnerIds",n)),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:this.updateTransactionState,readOnly:e},this.initialized=!0}catch{throw new ce("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot launch experience: Not initialized.");const n=async t=>{for(const e in t.layouts){const A=t.layouts[e].elements.filter((t=>t.type===h.Illustration));for(let t=0;t<A.length;++t){const e=A[t];e.src&&e.svg&&(e.cachedObjectURL=await dt(e.svg))}const n=t.layouts[e].elements.filter((t=>t.type===h.Textbox));for(let t=0;t<n.length;++t){const e=n[t];e.fontData?.assetUrl&&H(e.fontData.assetUrl)}}};if(this.experienceOptions.transaction.workflowId){const t=await Li(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=t,this.experienceOptions.transaction.workflowState){const t=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}this.experienceOptions.previewService=A&&A(t),this.experienceOptions.renderableContextService=new fn(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const e=new Xa(this,this.experienceOptions);return await e.getWorkflowManager().getInitializationPromise(),e}if(t){const a=ye.getShadowGraphqlClient().mutate({mutation:bn,variables:{workflowId:t,id:this.experienceOptions.transaction.id}}),i=Li(t);if(await Promise.all([a,i]),this.experienceOptions.workflow=await i,e){const t=JSON.parse(e);this.experienceOptions.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await n(t),this.experienceOptions.reloadedState=t}else this.experienceOptions.layouts=Ti(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await i),this.experienceOptions.renderableContextService=new fn(this.experienceOptions.layouts),this.experienceOptions.product?.modelUrl&&(this.experienceOptions.previewService?.initialize({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}),this.experienceOptions.modelContainer=this.experienceOptions.previewService?.getAllModels()[0]);const o=new Xa(this,this.experienceOptions);return await o.getWorkflowManager().getInitializationPromise(),o}throw new ce("No workflow ID provided.")}getPreviewService(){return this.experienceOptions?.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new ce("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}}function zi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class ji{constructor(){zi(this,"getProduct",void 0),zi(this,"getCommandContext",void 0),zi(this,"getAllLayoutData",void 0),zi(this,"getMetadata",void 0),zi(this,"getWorkflowMetadata",void 0),zi(this,"getStepStorage",void 0),zi(this,"setModelContainer",void 0),zi(this,"getUpdatesPending",void 0)}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}getVariationRecords(){return[]}async reset(){}updateStateWithServer(t){}addVariationRecord(t){return{recordNumber:0,transactionId:"",values:[]}}getCurrentVariationRecord(){}removeVariationRecord(t){return[]}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addCurrentVariationCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}addVariationRecordsCallback(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{}}setCurrentAdjustingStepId(t){}setCurrentVariationRecord(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,A){}setVariationRecords(t){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}}function Ki(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Vi;var Wi;(Wi=Vi||(Vi={})).SelectFrame="SelectFrame",Wi.SelectImage="SelectImage",Wi.Position="Position";class Xi extends Ma{constructor(t,e){super(t,e),Ki(this,"frameService",this.manager.getStepSpecificServices(this.getId())?.frameService)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ia.selectVariant(this.step,t.getResource(),e,this.manager,(t=>this.setUpdateState(t)))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged((e=>{e&&t(e)}))}selectImage(t){return ia.selectImage(this.step,t,this.manager)}getImageData(){if(this.frameService)return this.frameService.getImageData()}getCurrentFrameStep(t,e,A,n){return n&&n.length>1&&void 0===t?Vi.SelectFrame:e||A||this.getImageData()?Vi.Position:Vi.SelectImage}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}hasVaryingUpload(){return this.step.data.varyUpload}hasVaryingSelection(){return this.step.data.varySelection}}const qi=t=>{const e=kt(null),A=kt(void 0),[n,a]=Pt(void 0),{addEvent:i,removeEvent:o,updateEvent:r,eventCache:s}=Le(),[c,g]=Pt(!1),[l,B]=Pt(!1),{state:w,uiDispatcher:d}=Ze(),h=Rt((t=>{const e=t;d(new qe({zoom:Math.max(.1,Math.min(e,w.maxZoom))}))}),[d,w.maxZoom]),E=Rt((t=>{o(t),1===s.length&&(A.current=void 0),2===s.length&&a(void 0);"touch"===t.pointerType&&s.length>1&&s.length-1==1&&(B(!1),g(!1))}),[o,s.length]),C=Rt((t=>{i(t);"touch"===t.pointerType&&1===s.length&&(d(new qe({selectedElement:void 0})),B(!0),g(!0))}),[i,s.length,d]),u=Rt((t=>{r(t);const e=1===s.length&&"touch"!==s[0].pointerType,i=2===s.length&&"touch"===s[0].pointerType;if(c&&i){const[t,e]=s,A=Math.abs(t.clientX-e.clientX),i=n;i&&h(w.zoom-.0055*(i-A)),a(A)}if(l&&(e||i)&&t.isPrimary){const e=(A?.current?.x||t.screenX)-t.screenX,n=(A?.current?.y||t.screenY)-t.screenY;d(new qe({selectedElement:void 0,xTranslation:w.xTranslation-e/w.zoom,yTranslation:w.yTranslation-n/w.zoom}))}t.isPrimary&&(A.current={x:t.screenX,y:t.screenY})}),[r,s,c,l,n,h,w.zoom,w.xTranslation,w.yTranslation,d]),Q=Rt((t=>{c&&h(w.zoom-.035*Math.sign(t.deltaY))}),[h,w.zoom,c]);Ut((()=>{if(!e.current||0===s.length)return;const t=s[0].pointerId,A=e.current.hasPointerCapture(t);l&&!A&&e.current.setPointerCapture(t),!l&&A&&e.current.releasePointerCapture(t)}),[e,l,s]),JA([" "],(()=>{B(!0),d(new qe({selectedElement:void 0}))}),(()=>B(!1))),JA(["Control"],(()=>g(!0)),(()=>g(!1)));const p=Gt((()=>({cursor:l&&0===s.length?"grab":l&&1===s.length?"grabbing":c?"zoom-in":void 0,width:"100%",height:"100%",overflow:"clip"})),[l,c,s]);return Jt("div",{ref:e,className:"transform-wrapper",onWheel:Q,onPointerDown:C,onPointerUp:E,onPointerCancel:E,onPointerLeave:E,onPointerMove:u,style:p,children:t.children})};export{Oi as SpiffCommerceClient,t as CommandContext,Ee as spiffCoreConfiguration,zA as PromiseQueue,OA as QueueablePromise,ji as MockWorkflowManager,Qa as InformationMessageType,Ma as StepHandle,ba as TextStepHandle,Xi as FrameStepHandle,va as BulkStepHandle,Ua as ShapeStepHandle,xa as IllustrationStepHandle,Na as MaterialStepHandle,Pa as ModelStepHandle,Ra as PictureStepHandle,Ha as QuestionStepHandle,tA as BulkPriceCalculationStrategy,fa as Variant,ee as OptionNotFoundError,Ae as LayoutNotFoundError,ne as AssetNotFoundError,ae as ResourceNotFoundError,ie as MisconfigurationError,se as ParseError,re as UnhandledBehaviorError,He as assetService,Va as designService,za as createDesign,ke as optionService,de as persistenceService,ye as graphQlManager,gA as toast,Zn as FrameService,Xn as getBoundedOffsets,ia as frameStepService,sa as modelStepService,ra as materialStepService,Ba as shapeStepService,la as questionStepService,na as digitalContentStepService,ca as moduleStepService,ga as pictureStepService,Ca as textStepService,oa as illustrationStepService,$e as ProductCameraRig,Vi as FrameStep,AA as ConversionLocation,aA as ConversionDataType,Li as getWorkflow,ta as shortenUrl,Mi as ObjectInput,Fi as TextInput,fi as ObjectInputType,e as AssetType,A as BringForwardCommand,n as BringToFrontCommand,a as BringToBackCommand,i as CanvasCommand,o as CreateElementCommand,r as CreateLayoutCommand,s as DeleteElementCommand,c as FontAlignmentCommand,g as FontColorCommand,l as FontSizeCommand,B as FontSourceCommand,w as GroupCommand,d as LayoutElementFactory,h as LayoutElementType,E as MoveCommand,C as ResizeCommand,u as RotateCommand,Q as SendBackwardsCommand,oA as StakeholderType,p as StepAspectType,m as StepType,D as TextChangeCommand,I as UnitOfMeasurement,f as dataUrlFromExternalUrl,y as findElement,M as frameDataCache,F as generate,Y as getAxisAlignedBoundingBox,S as generateSVGWithUnknownColors,v as getAttributesFromArrayBuffer,x as rehydrateSerializedLayout,N as getFrameData,P as getSvgElement,R as loadFontFromDataUrl,H as loadFontFromExternalUrl,U as determineCorrectFontSizeAndLines,b as patternImageDataCache,Dn as generateCommands,G as registerJSDOM,bA as minZoom,Nn as AdvancedEditor,qi as TransformWrapper,xn as EditorCore,Te as useLayouts,Ze as useEditorState,kA as useEditorInteraction,JA as useShortcutCombination,Ve as commandReducer,Ke as getDefaultState,Je as CommandContextContext,Xe as AdvancedEditorStateProvider,We as AdvancedEditorContext,qe as UICommand,ze as EditorSubMenu,lA as ElementEventType,wA as KeyEvent,Ln as gatherVaryingStepAspects};
1339
1353
  //# sourceMappingURL=module.js.map
package/dist/types.d.ts CHANGED
@@ -2252,6 +2252,11 @@ export class SpiffCommerceClient {
2252
2252
  * @returns A bundle to be used for grouping and operating on large amounts of workflow experiences.
2253
2253
  */
2254
2254
  getExistingBundle(bundleId: string, previewServiceConstructor?: (workflow: _Workflow1, transactionId: string) => any): Promise<_Bundle1>;
2255
+ /**
2256
+ * Retrieves all existing bundle stakeholders from the API, for the currently authenticated customer.
2257
+ * @returns An array of bundle stakeholders.
2258
+ */
2259
+ getBundleStakeholders(): Promise<BundleStakeholder[]>;
2255
2260
  /**
2256
2261
  * Creates a new instance of WorkflowExperience. A high level wrapper for workflows.
2257
2262
  * @param workflowId The id of the workflow to be run. Deprecated: Provide options instead.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/core",
3
- "version": "14.1.6",
3
+ "version": "14.2.0",
4
4
  "description": "Core client API for interacting with the Spiff Commerce backend.",
5
5
  "source": "src/index.ts",
6
6
  "main": "dist/main.js",