@spiffcommerce/core 15.0.4 → 15.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +42 -42
- package/dist/module.js +39 -39
- package/dist/types.d.ts +2 -2
- package/package.json +2 -2
package/dist/module.js
CHANGED
|
@@ -576,7 +576,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
576
576
|
id
|
|
577
577
|
}
|
|
578
578
|
}
|
|
579
|
-
`;class ka extends Na{constructor(t,e){super(t,e),Ra(this,"transaction",this.manager.getTransaction())}selectVariant(){throw new Error("Bulk step does not support variants.")}async setDesignName(t){await ye.getShadowGraphqlClient().mutate({mutation:ba,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:Ha,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 Ua extends Na{constructor(t,e){super(t,e)}async selectVariant(t){if(this.getCurrentVariant()!==t)return Ba.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),Ba.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?Ba.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 Ga extends Na{constructor(t,e){super(t,e)}selectVariant(t){return da.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ja extends Na{constructor(t,e){super(t,e)}selectVariant(t){return wa.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ta extends Na{constructor(t,e){super(t,e)}selectVariant(t){return Ea.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class La extends Na{constructor(t,e){super(t,e)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await ua.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.option?.displayType}}class Oa extends Na{constructor(t,e){super(t,e)}selectVariant(t){const e=t.getResource();return Qa.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Qa.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Qa.availableColours(this.step)}setCustomColor(t){if("#custom"!==this.getCurrentVariant()?.getColor())throw new Error("Custom colors can only be set on a non-custom variant. Please add a custom variant to the step.");return Qa.setCustomColor(t,this.step,this.manager)}getCustomColor(){const t=this.manager.getStepStorage(this.step.stepName)?.colour;if("#custom"!==this.getCurrentVariant()?.getColor())throw new Error("Custom colors can only be set on a non-custom variant. Please add a custom variant to the step.");if(!t)throw new Error("Color not available on step. Set a default on the workflow to fix this.");return t}}class za extends Na{constructor(t,e){super(t,e)}async selectVariant(t){Ia.selectVariant(this.step,t.getResource(),this.manager,(t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occured with test",messageType:Ma.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?Ia.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await Ia.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return Ia.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await Ia.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=Ia.findLayoutElements(this.manager,this.step),n=Ia.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}=Ia.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:Ma.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 ja{static get(t,e){switch(e.type){case m.Question:return new La(t,e);case m.Text:return new za(t,e);case m.Illustration:return new Ua(t,e);case m.Picture:return new Ta(t,e);case m.Shape:return new Oa(t,e);case m.Material:return new Ga(t,e);case m.Model:return new Ja(t,e);case m.Frame:return new
|
|
579
|
+
`;class ka extends Na{constructor(t,e){super(t,e),Ra(this,"transaction",this.manager.getTransaction())}selectVariant(){throw new Error("Bulk step does not support variants.")}async setDesignName(t){await ye.getShadowGraphqlClient().mutate({mutation:ba,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:Ha,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 Ua extends Na{constructor(t,e){super(t,e)}async selectVariant(t){if(this.getCurrentVariant()!==t)return Ba.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),Ba.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?Ba.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 Ga extends Na{constructor(t,e){super(t,e)}selectVariant(t){return da.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ja extends Na{constructor(t,e){super(t,e)}selectVariant(t){return wa.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class Ta extends Na{constructor(t,e){super(t,e)}selectVariant(t){return Ea.selectVariant(this.step,t.getResource(),this.manager,(t=>this.setUpdateState(t)))}}class La extends Na{constructor(t,e){super(t,e)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await ua.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.option?.displayType}}class Oa extends Na{constructor(t,e){super(t,e)}selectVariant(t){const e=t.getResource();return Qa.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Qa.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Qa.availableColours(this.step)}setCustomColor(t){if("#custom"!==this.getCurrentVariant()?.getColor())throw new Error("Custom colors can only be set on a non-custom variant. Please add a custom variant to the step.");return Qa.setCustomColor(t,this.step,this.manager)}getCustomColor(){const t=this.manager.getStepStorage(this.step.stepName)?.colour;if("#custom"!==this.getCurrentVariant()?.getColor())throw new Error("Custom colors can only be set on a non-custom variant. Please add a custom variant to the step.");if(!t)throw new Error("Color not available on step. Set a default on the workflow to fix this.");return t}}class za extends Na{constructor(t,e){super(t,e)}async selectVariant(t){Ia.selectVariant(this.step,t.getResource(),this.manager,(t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occured with test",messageType:Ma.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?Ia.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await Ia.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return Ia.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await Ia.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=Ia.findLayoutElements(this.manager,this.step),n=Ia.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}=Ia.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:Ma.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 ja extends Na{constructor(t,e){super(t,e)}async selectVariant(){}getContent(){return this.step.data.content}}class Ka{static get(t,e){switch(e.type){case m.Information:return new ja(t,e);case m.Question:return new La(t,e);case m.Text:return new za(t,e);case m.Illustration:return new Ua(t,e);case m.Picture:return new Ta(t,e);case m.Shape:return new Oa(t,e);case m.Material:return new Ga(t,e);case m.Model:return new Ja(t,e);case m.Frame:return new Eo(t,e);case m.Bulk:return new ka(t,e);default:throw new re(`Step type ${e.type} not yet supported in Core SDK`)}}}function Va(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const Wa=It`
|
|
580
580
|
fragment CreateDesignTransaction on Transaction {
|
|
581
581
|
id
|
|
582
582
|
designName
|
|
@@ -592,8 +592,8 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
592
592
|
lastSyncedAt
|
|
593
593
|
bulkEmailAddress
|
|
594
594
|
}
|
|
595
|
-
`,
|
|
596
|
-
${
|
|
595
|
+
`,Xa=It`
|
|
596
|
+
${Wa}
|
|
597
597
|
mutation CreateDesign(
|
|
598
598
|
$name: String!
|
|
599
599
|
$layouts: [LayoutInput]!
|
|
@@ -624,8 +624,8 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
624
624
|
}
|
|
625
625
|
}
|
|
626
626
|
}
|
|
627
|
-
`,
|
|
628
|
-
${
|
|
627
|
+
`,qa=It`
|
|
628
|
+
${Wa}
|
|
629
629
|
mutation CreateDesigns($inputs: [DesignCreateInput]!) {
|
|
630
630
|
designCreateMany(inputs: $inputs) {
|
|
631
631
|
id
|
|
@@ -638,7 +638,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
638
638
|
}
|
|
639
639
|
}
|
|
640
640
|
}
|
|
641
|
-
`,qa=(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},Za=(t,e,A,n,a,i,o,r,s,c)=>{const g=(we.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},$a=async(t,e,A,n,a,i,o,r)=>{const s=e.basePrice||0,c=t.priceModifierTotal||0,g=((t,e,A,n)=>{const a={};let i;if(A){i=qa(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 Za(t,e,s,c,i,g,o,n,a,r)},_a=async(t,e,A,n,a,i,o,r,s)=>{await t.outstandingRequestsPromise();const c=ye.getShadowGraphqlClient(),g=await c.query({query:Kn,variables:{id:a.id},fetchPolicy:"no-cache",errorPolicy:"all"}),l=g.data?.transactions[0].workflowState;!g.errors&&l||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),g.errors&&g.errors.forEach((t=>{g.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const B=t.getPreviewService(),d=e?.finalizeStepConfig?.lookAtAnimation,w=B&&100===B.getSceneInitializationProgress()&&e.showModelOnFinishStep&&!!d,h=s&&qa(s,e,!0),E=s&&qa(s,e,!1),u=async t=>{const A={};let n=0;if(Object.keys(i).length>0)for(const a of Object.keys(i)){const o=i[a],r=e.steps.find((t=>t.stepName===a));for(let e=0;e<o.selections.length;++e){const a=o.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]},[C]=await u(!0),Q=Object.fromEntries(Object.keys(C).map((t=>[t,C[t].map((t=>t.id))]))),[p]=await u(!1),m=Object.fromEntries(Object.keys(p).map((t=>[t,p[t].map((t=>t.id))]))),f=await r(w);return{designDetails:(()=>{const t={name:o,layouts:A.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:e.id,transactionId:a.id,useThreeDimPreview:!!w,previewImage:f};if(E){const e=[];for(const[t,A]of Object.entries(E))e.push({key:t,value:A});t.metadata=e}if(Q){const e=[];for(const[t,A]of Object.entries(m))e.push({key:t,ids:A});t.selectedVariants=e}return t})(),cartSelectionsWithPrices:C,cartMetadata:h}},ti=async(t,e,A,n,a,i,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts");const{designDetails:d,cartSelectionsWithPrices:w,cartMetadata:h}=await _a(t,e,A,n,i,o,r,l,B);s("workflow.steps.finish.finalize.creatingDesign"),i.bulk&&await c(g);const E=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:Wa,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)(d),u=E?.transaction?.previewImageLink;if(!E?.transaction)throw new Error("Failed to create design");s("workflow.steps.finish.finalize.updatingTransaction");const C=E.transaction;return i.bulk?((t,e,A,n)=>{const a=(e.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,o={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return Za(t,e,a,i,void 0,o,A,void 0,void 0,n)})(C,a,u,E?.processExecution?.id):await $a(C,a,e,w,E?.sku,h,u,E?.processExecution?.id)},ei=async(t,e)=>{e("workflow.steps.finish.finalize.buildingLayouts");const A=await Promise.all(t.map((async t=>await _a(t.workflowManager,t.workflow,t.layouts,t.getReducerState,t.transaction,t.workflowSelections,t.designName,(()=>Promise.resolve(void 0)),t.workflowMetadata))));e("workflow.steps.finish.finalize.creatingDesign");const n=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:Xa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:t.map((t=>({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?.designCreateMany)(A.map((t=>t.designDetails)));if(!n)throw new Error("Failed to create designs");return e("workflow.steps.finish.finalize.updatingTransaction"),Promise.all(n.map((async(e,n)=>{const a=t[n],i=A[n],o=e.transaction;return await $a(o,a.product,a.workflow,i.cartSelectionsWithPrices,e.sku,i.cartMetadata,void 0,e.processExecution?.id)})))};let Ai;var ni;(ni=Ai||(Ai={})).Local="Local",ni.Remote="Remote";const ai=new class{constructor(){Ka(this,"localPersistenceKey","designTransactions"),Ka(this,"storageMethod",Ai.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===Ai.Local){const t=we.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!==Ai.Local)throw new re("Unexpected storage method requested");we.set(this.localPersistenceKey,JSON.stringify(t))}};function ii(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 oi{constructor(e,A){if(ii(this,"client",void 0),ii(this,"commandContext",void 0),ii(this,"workflowManager",void 0),ii(this,"isReadOnly",void 0),ii(this,"renderableScenes",[]),ii(this,"renderableSceneCallbacks",[]),ii(this,"debouncedSavedDesignUpdate",Xt((async()=>{await ai.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),ii(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 Ya(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:jn,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 d=N(l.layoutState.layout,l.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:g.x,top:g.y,width:g.width,height:g.height}}}),w=Kt.renderToStaticMarkup(d),h=await jt.from(B,w,{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 ja.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:Vn(this.getWorkflowManager().getWorkflow())},conditions:[]};return ja.get(this.getWorkflowManager(),e)}}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepTitle===t));if(e&&this.stepHasHandle(e))return ja.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((e=>e.type===t)).map((t=>ja.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=>ja.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:Ha,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=we.getMap("transactionCustomerIds")||new Map;t.set(this.getWorkflowManager().getTransaction().id,e.customer.id),we.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 ai.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 ai.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 so({}),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,e=!0){return ti(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=>e?this.createPreviewImage(t):Promise.resolve(void 0)),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 ri=Zt`
|
|
641
|
+
`,Za=(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},$a=(t,e,A,n,a,i,o,r,s,c)=>{const g=(we.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},_a=async(t,e,A,n,a,i,o,r)=>{const s=e.basePrice||0,c=t.priceModifierTotal||0,g=((t,e,A,n)=>{const a={};let i;if(A){i=Za(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 $a(t,e,s,c,i,g,o,n,a,r)},ti=async(t,e,A,n,a,i,o,r,s)=>{await t.outstandingRequestsPromise();const c=ye.getShadowGraphqlClient(),g=await c.query({query:Kn,variables:{id:a.id},fetchPolicy:"no-cache",errorPolicy:"all"}),l=g.data?.transactions[0].workflowState;!g.errors&&l||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(n())),g.errors&&g.errors.forEach((t=>{g.errors&&console.log("Server Error:",t.message)})),await t.updateStateWithServerImmediate(n),console.log("Server state is undefined @ Workflow completion"));const B=t.getPreviewService(),d=e?.finalizeStepConfig?.lookAtAnimation,w=B&&100===B.getSceneInitializationProgress()&&e.showModelOnFinishStep&&!!d,h=s&&Za(s,e,!0),E=s&&Za(s,e,!1),u=async t=>{const A={};let n=0;if(Object.keys(i).length>0)for(const a of Object.keys(i)){const o=i[a],r=e.steps.find((t=>t.stepName===a));for(let e=0;e<o.selections.length;++e){const a=o.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]},[C]=await u(!0),Q=Object.fromEntries(Object.keys(C).map((t=>[t,C[t].map((t=>t.id))]))),[p]=await u(!1),m=Object.fromEntries(Object.keys(p).map((t=>[t,p[t].map((t=>t.id))]))),f=await r(w);return{designDetails:(()=>{const t={name:o,layouts:A.map((t=>({index:t.index,panelId:t.panelId}))),workflowId:e.id,transactionId:a.id,useThreeDimPreview:!!w,previewImage:f};if(E){const e=[];for(const[t,A]of Object.entries(E))e.push({key:t,value:A});t.metadata=e}if(Q){const e=[];for(const[t,A]of Object.entries(m))e.push({key:t,ids:A});t.selectedVariants=e}return t})(),cartSelectionsWithPrices:C,cartMetadata:h}},ei=async(t,e,A,n,a,i,o,r,s,c,g,l,B)=>{s("workflow.steps.finish.finalize.buildingLayouts");const{designDetails:d,cartSelectionsWithPrices:w,cartMetadata:h}=await ti(t,e,A,n,i,o,r,l,B);s("workflow.steps.finish.finalize.creatingDesign"),i.bulk&&await c(g);const E=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:Xa,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)(d),u=E?.transaction?.previewImageLink;if(!E?.transaction)throw new Error("Failed to create design");s("workflow.steps.finish.finalize.updatingTransaction");const C=E.transaction;return i.bulk?((t,e,A,n)=>{const a=(e.basePrice||0)*(t.variationsCount||0),i=t.priceModifierTotal||0,o={items:{value:t.variationsCount?`${t.variationsCount}`:"0",priceModifier:0}};return $a(t,e,a,i,void 0,o,A,void 0,void 0,n)})(C,a,u,E?.processExecution?.id):await _a(C,a,e,w,E?.sku,h,u,E?.processExecution?.id)},Ai=async(t,e)=>{e("workflow.steps.finish.finalize.buildingLayouts");const A=await Promise.all(t.map((async t=>await ti(t.workflowManager,t.workflow,t.layouts,t.getReducerState,t.transaction,t.workflowSelections,t.designName,(()=>Promise.resolve(void 0)),t.workflowMetadata))));e("workflow.steps.finish.finalize.creatingDesign");const n=await(async t=>(await ye.getShadowGraphqlClient().mutate({mutation:qa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:t.map((t=>({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?.designCreateMany)(A.map((t=>t.designDetails)));if(!n)throw new Error("Failed to create designs");return e("workflow.steps.finish.finalize.updatingTransaction"),Promise.all(n.map((async(e,n)=>{const a=t[n],i=A[n],o=e.transaction;return await _a(o,a.product,a.workflow,i.cartSelectionsWithPrices,e.sku,i.cartMetadata,void 0,e.processExecution?.id)})))};let ni;var ai;(ai=ni||(ni={})).Local="Local",ai.Remote="Remote";const ii=new class{constructor(){Va(this,"localPersistenceKey","designTransactions"),Va(this,"storageMethod",ni.Local),Va(this,"designSavedListeners",[])}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter((e=>e!==t))}async getSavedDesigns(){if(this.storageMethod===ni.Local){const t=we.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!==ni.Local)throw new re("Unexpected storage method requested");we.set(this.localPersistenceKey,JSON.stringify(t))}};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(e,A){if(oi(this,"client",void 0),oi(this,"commandContext",void 0),oi(this,"workflowManager",void 0),oi(this,"isReadOnly",void 0),oi(this,"renderableScenes",[]),oi(this,"renderableSceneCallbacks",[]),oi(this,"debouncedSavedDesignUpdate",Xt((async()=>{await ii.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()}),2500)),oi(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 Ya(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:jn,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 d=N(l.layoutState.layout,l.layoutState.elements,{renderingConfiguration:{purpose:W.Print,region:{left:g.x,top:g.y,width:g.width,height:g.height}}}),w=Kt.renderToStaticMarkup(d),h=await jt.from(B,w,{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 Ka.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:Vn(this.getWorkflowManager().getWorkflow())},conditions:[]};return Ka.get(this.getWorkflowManager(),e)}}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find((e=>e.stepTitle===t));if(e&&this.stepHasHandle(e))return Ka.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter((e=>e.type===t)).map((t=>Ka.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=>Ka.get(this.getWorkflowManager(),t)))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:Ha,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=we.getMap("transactionCustomerIds")||new Map;t.set(this.getWorkflowManager().getTransaction().id,e.customer.id),we.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 ii.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 ii.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 co({}),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,e=!0){return ei(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=>e?this.createPreviewImage(t):Promise.resolve(void 0)),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 si=Zt`
|
|
642
642
|
${Zt`
|
|
643
643
|
fragment ProductCollectionProductFields on Product {
|
|
644
644
|
id
|
|
@@ -720,8 +720,8 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
720
720
|
}
|
|
721
721
|
}
|
|
722
722
|
}
|
|
723
|
-
`,
|
|
724
|
-
${
|
|
723
|
+
`,ci=Zt`
|
|
724
|
+
${si}
|
|
725
725
|
query GetBundle($id: String!) {
|
|
726
726
|
bundles(ids: [$id]) {
|
|
727
727
|
id
|
|
@@ -742,7 +742,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
742
742
|
}
|
|
743
743
|
}
|
|
744
744
|
}
|
|
745
|
-
`,
|
|
745
|
+
`,gi=Zt`
|
|
746
746
|
query GetBundleStakeholders($id: String!) {
|
|
747
747
|
bundles(ids: [$id]) {
|
|
748
748
|
id
|
|
@@ -762,7 +762,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
762
762
|
}
|
|
763
763
|
}
|
|
764
764
|
}
|
|
765
|
-
`,
|
|
765
|
+
`,li=Zt`
|
|
766
766
|
query GetBundlesForCustomer($id: String!) {
|
|
767
767
|
customers(ids: [$id]) {
|
|
768
768
|
bundleStakeholders {
|
|
@@ -783,8 +783,8 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
783
783
|
}
|
|
784
784
|
}
|
|
785
785
|
}
|
|
786
|
-
`,
|
|
787
|
-
${
|
|
786
|
+
`,Bi=Zt`
|
|
787
|
+
${si}
|
|
788
788
|
mutation CreateBundle($collectionId: String) {
|
|
789
789
|
bundleCreate(collectionId: $collectionId) {
|
|
790
790
|
id
|
|
@@ -802,25 +802,25 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
802
802
|
}
|
|
803
803
|
}
|
|
804
804
|
}
|
|
805
|
-
`,
|
|
805
|
+
`,di=Zt`
|
|
806
806
|
mutation UpdateBundle($id: String!, $name: String, $metadata: [MetadataInput!], $bundleStateData: String) {
|
|
807
807
|
bundleUpdate(id: $id, name: $name, metadata: $metadata, bundleStateData: $bundleStateData) {
|
|
808
808
|
id
|
|
809
809
|
}
|
|
810
810
|
}
|
|
811
|
-
`,
|
|
811
|
+
`,wi=Zt`
|
|
812
812
|
mutation BundleAddTransaction($id: String!, $transactionId: String!) {
|
|
813
813
|
bundleAddTransaction(id: $id, transactionId: $transactionId) {
|
|
814
814
|
id
|
|
815
815
|
}
|
|
816
816
|
}
|
|
817
|
-
`,
|
|
817
|
+
`,hi=Zt`
|
|
818
818
|
mutation BundleAddTransactions($id: String!, $transactionIds: [String!]!, $transactionOwnerIds: [String!]) {
|
|
819
819
|
bundleAddTransactions(id: $id, transactionIds: $transactionIds, transactionOwnerIds: $transactionOwnerIds) {
|
|
820
820
|
id
|
|
821
821
|
}
|
|
822
822
|
}
|
|
823
|
-
`,
|
|
823
|
+
`,Ei=Zt`
|
|
824
824
|
mutation BundleRemoveTransaction(
|
|
825
825
|
$id: String!
|
|
826
826
|
$transactionId: String!
|
|
@@ -835,7 +835,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
835
835
|
id
|
|
836
836
|
}
|
|
837
837
|
}
|
|
838
|
-
`,
|
|
838
|
+
`,ui=Zt`
|
|
839
839
|
mutation BundleRemoveTransactions(
|
|
840
840
|
$id: String!
|
|
841
841
|
$transactionIds: [String!]!
|
|
@@ -850,7 +850,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
850
850
|
id
|
|
851
851
|
}
|
|
852
852
|
}
|
|
853
|
-
`,
|
|
853
|
+
`,Ci=Zt`
|
|
854
854
|
mutation BundleAddStakeholder($id: String!, $details: CustomerDetailsInput!, $type: String!) {
|
|
855
855
|
bundleAddStakeholder(id: $id, details: $details, type: $type) {
|
|
856
856
|
id
|
|
@@ -870,7 +870,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
870
870
|
}
|
|
871
871
|
}
|
|
872
872
|
}
|
|
873
|
-
`,
|
|
873
|
+
`,Qi=Zt`
|
|
874
874
|
mutation BundleUpdateStakeholders($id: String!, $input: [BundleStakeholderInput!]!) {
|
|
875
875
|
bundleUpdateStakeholders(id: $id, input: $input) {
|
|
876
876
|
id
|
|
@@ -890,13 +890,13 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
890
890
|
}
|
|
891
891
|
}
|
|
892
892
|
}
|
|
893
|
-
`,
|
|
893
|
+
`,pi=Zt`
|
|
894
894
|
mutation BundleUpdateTransactionOrder($id: String!, $transactionIds: [String!]!) {
|
|
895
895
|
bundleUpdateTransactionOrder(id: $id, transactionIds: $transactionIds) {
|
|
896
896
|
id
|
|
897
897
|
}
|
|
898
898
|
}
|
|
899
|
-
`;function
|
|
899
|
+
`;function mi(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 fi{constructor(t){mi(this,"bundle",void 0),mi(this,"handleCache",{}),this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];const t=this.bundle.getProductCollection().getResource().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 Dt.FileUpload:return new Ii(this.bundle,t);case Dt.Option:{const e=t.entityId?await Oe.getOption(t.entityId):void 0;return"Color"===e?.type?new Fi(this.bundle,t,e):new Mi(this.bundle,t,e)}case Dt.Text:return new yi(this.bundle,t)}}}class Di{constructor(t,e){mi(this,"bundle",void 0),mi(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()?.getResource().globalPropertyConfiguration?.id&&t.aspectName===this.property.name))))))}}class Ii extends Di{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 be.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 yi extends Di{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 Mi extends Di{constructor(t,e,A){super(t,e),mi(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 xa(e):void 0}getAvailableVariants(){return(this.optionResource?.variants?.filter((t=>t.enabled))||[]).map((t=>new xa(t)))}getAllVariants(){return(this.optionResource?.variants||[]).map((t=>new xa(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 xa(A),t):Promise.resolve()}async applyVariantSelection(t,e){const A=this.getSharedSteps(e).map((e=>e.selectVariant(t)));await Promise.all(A)}}class Fi extends Mi{constructor(t,e,A){super(t,e,A)}setCustomColor(t){this.getSharedSteps().forEach((e=>e.setCustomColor(t)))}getCustomColor(){return this.getSharedSteps()[0].getCustomColor()}}const Si=Zt`
|
|
900
900
|
mutation CreateGlobalPropertyState($bundleId: String!) {
|
|
901
901
|
globalPropertyStateCreate(bundleId: $bundleId) {
|
|
902
902
|
id
|
|
@@ -906,7 +906,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
906
906
|
}
|
|
907
907
|
}
|
|
908
908
|
}
|
|
909
|
-
`,
|
|
909
|
+
`,Yi=Zt`
|
|
910
910
|
mutation UpdateGlobalPropertyState($id: String!, $aspects: [GlobalPropertyStateAspectInput]!) {
|
|
911
911
|
globalPropertyStateUpdate(id: $id, aspects: $aspects) {
|
|
912
912
|
id
|
|
@@ -916,7 +916,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
916
916
|
}
|
|
917
917
|
}
|
|
918
918
|
}
|
|
919
|
-
`,
|
|
919
|
+
`,vi=Zt`
|
|
920
920
|
query GetGlobalPropertyState($bundleId: String!) {
|
|
921
921
|
globalPropertyState(bundleId: $bundleId) {
|
|
922
922
|
id
|
|
@@ -926,7 +926,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
926
926
|
}
|
|
927
927
|
}
|
|
928
928
|
}
|
|
929
|
-
`;function vi(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 xi{constructor(t,e){vi(this,"bundleId",void 0),vi(this,"globalPropertyState",void 0),vi(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:Si,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:Yi,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:Fi,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 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}class Ni{constructor(t){Pi(this,"state",void 0),this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find((e=>e.transactionId===t.getWorkflowManager().getTransaction().id&&e.transform))?.transform;if(!e)return;const A=t.getWorkflowManager().getModelContainer();A.position=e.position,A.rotation={x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},A.scale=e.scale}setWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer())return;const A=t.getWorkflowManager().getModelContainer();A.position=e.position,A.rotation={x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},A.scale=e.scale;const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const a=this.state.transactions.find((t=>t.transactionId===n));a?a.transform=e:this.state.transactions.push({transactionId:n,transform:e})}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex((e=>e.transactionId===t));-1!==e&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return JSON.stringify(this.state)}}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 Hi{constructor(t){Ri(this,"collection",void 0),this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getProducts(){return this.collection.products.map((t=>new bi(t)))}getResource(){return this.collection}}class bi{constructor(t){Ri(this,"product",void 0),this.product=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t){const e=(this.product.integrationProducts||[]).find((e=>!!e.integration?.type&&e.integration?.type===t));if(!e)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return e}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}}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}class Ui{constructor(t,e,A,n){ki(this,"client",void 0),ki(this,"id",void 0),ki(this,"name",void 0),ki(this,"metadata",void 0),ki(this,"productCollection",void 0),ki(this,"bundleStateManager",void 0),ki(this,"globalConfiguration",void 0),ki(this,"globalPropertyStateManager",void 0),ki(this,"globalPropertyHandleService",void 0),ki(this,"eventListeners",new Map),ki(this,"initializationPromise",void 0),ki(this,"workflowExperiences",[]),ki(this,"previewService",void 0),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.bundleStateManager=new Ni(e.bundleStateData),this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new xi(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new mi(this),this.setPreviewService(A),this.initializationPromise=this.loadExistingBundles(e.transactions?.map((t=>t.id))||[],n)}getInitializationPromise(){return this.initializationPromise}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()===Dt.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?new Hi(this.productCollection):void 0}async addWorkflowExperience(t){await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState([t]))))}async addWorkflowExperiences(t){const e=t.map((t=>t.getWorkflowManager().getTransaction().id)),A=e.map((t=>this.workflowExperiences.find((e=>e.getWorkflowManager().getTransaction().id===t))));if(A.some((t=>!!t)))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter((t=>!!t)).map((t=>t?.getWorkflowManager().getTransaction().id)).join(", "));const n=we.getMap("transactionOwnerIds")||new Map,a=e.map((t=>n.get(t)));await ye.getShadowGraphqlClient().mutate({mutation:wi,variables:{id:this.id,transactionIds:e,transactionOwnerIds:a}}).catch((t=>{console.error(t)})),this.workflowExperiences.push(...t),await Promise.all([this.updateTransactionOrder(),(async()=>{for(const e of t)await this.injectExperienceIntoPreviewService(e);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState(t))))})()])}async appendWorkflowExperience(t,e=!0){const A=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===A)))throw new Error("Unable to add transaction to bundle - Already Exists!");const n=(we.getMap("transactionOwnerIds")||new Map).get(A);await ye.getShadowGraphqlClient().mutate({mutation:di,variables:{id:this.id,transactionId:A},context:{transactionOwnerId:n}}),e&&this.workflowExperiences.push(t)}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperiences(t){await this.removeTransactions(t.map((t=>t.getWorkflowManager().getTransaction())))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,A=!0){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id);{const n=this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e.id));this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await ye.getShadowGraphqlClient().mutate({mutation:hi,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}}),A&&(this.workflowExperiences.splice(t,1),await this.updateTransactionOrder())}}async removeTransactions(t){const e=t.map((t=>this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id))));if(e.some((t=>-1===t)))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter(((t,A)=>-1===e[A])).map((t=>t.id)).join(", "));const A=t.map((t=>this.workflowExperiences.splice(this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id)),1)[0]));this.previewService&&A.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t.forEach((t=>this.bundleStateManager.removeStateForTransaction(t.id))),await ye.getShadowGraphqlClient().mutate({mutation:Ei,variables:{id:this.id,transactionIds:t.map((t=>t.id)),name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState([t]))))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const A=this.workflowExperiences[t];if(A.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,A.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const t=await this.getGlobalProperties();await Promise.all(t.map((t=>t.applyGlobalState([e]))))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const A=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=A,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const A=await ye.getShadowGraphqlClient().mutate({mutation:ui,variables:{id:this.id,details:t,type:e||BA.Owner}});if(!A.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const n=A.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async updateStakeholders(t){const e=await ye.getShadowGraphqlClient().mutate({mutation:Ci,variables:{id:this.id,input:t}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const A=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(A)}async getAllStakeholders(){const t=await ye.getShadowGraphqlClient().query({query:ci,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}storeStakeholderCustomers(t){t.forEach((t=>{t.customer&&this.client.storeCustomer(t.customer)}))}async finish(t){return await ei(this.workflowExperiences.map((t=>({workflowManager:t.getWorkflowManager(),workflow:t.getWorkflowManager().getWorkflow(),layouts:t.getWorkflowManager().getLayouts(),getReducerState:()=>t.getCommandContext().getState(),product:t.getWorkflowManager().getProduct(),transaction:t.getWorkflowManager().getTransaction(),workflowSelections:t.getWorkflowManager().getWorkflowSelections(),designName:t.getWorkflowManager().getWorkflow().name,variationRecords:t.getWorkflowManager().getVariationRecords(),updateVariationRecords:e=>t.updateVariationRecords(e),workflowMetadata:t.getWorkflowManager().getWorkflowMetadata()}))),t??(()=>{}))}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}setWorkflowExperienceTransform(t,e){return this.bundleStateManager.setWorkflowExperienceTransform(t,e),this.updateBundle()}onModelLoadEvent(t){"unload"!==t.eventType&&t.modelContainer&&(t.modelContainer.registerMaterialSelectedCallback((()=>this.onModelSelectedEvent(t.modelContainer,!0))),t.modelContainer.registerMaterialDeselectedCallback((()=>this.onModelSelectedEvent(t.modelContainer,!1))))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const A=t.metadata.get("workflowManager").getTransaction(),n=this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===A.id));n&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:n})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(t){console.error(`Unable to apply state to workflow experience: ${t}`)}await e}}async loadExistingBundles(t,e){if(0===t.length)return;const A=await this.client.getWorkflowExperiences(t.map((t=>({type:"transaction",transactionId:t}))),e);if(this.workflowExperiences=A,this.previewService)for(const t of A)await this.injectExperienceIntoPreviewService(t)}async updateBundle(){if(!(await ye.getShadowGraphqlClient().mutate({mutation:Bi,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await ye.getShadowGraphqlClient().mutate({mutation:Qi,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}async checkConditionalHandlesChanged(t,e){const A=await this.globalPropertyHandleService.getHandles(),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})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:a})}fireEvent(t,e){(this.eventListeners.get(t)||[]).forEach((A=>A({bundle:this,event:t,data:e})))}}function Gi(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 Ji=It`
|
|
929
|
+
`;function xi(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 Pi{constructor(t,e){xi(this,"bundleId",void 0),xi(this,"globalPropertyState",void 0),xi(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:Yi,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:vi,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:Si,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 Ni(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){Ni(this,"state",void 0),this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find((e=>e.transactionId===t.getWorkflowManager().getTransaction().id&&e.transform))?.transform;if(!e)return;const A=t.getWorkflowManager().getModelContainer();A.position=e.position,A.rotation={x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},A.scale=e.scale}setWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer())return;const A=t.getWorkflowManager().getModelContainer();A.position=e.position,A.rotation={x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},A.scale=e.scale;const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const a=this.state.transactions.find((t=>t.transactionId===n));a?a.transform=e:this.state.transactions.push({transactionId:n,transform:e})}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex((e=>e.transactionId===t));-1!==e&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return JSON.stringify(this.state)}}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 bi{constructor(t){Hi(this,"collection",void 0),this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getProducts(){return this.collection.products.map((t=>new ki(t)))}getResource(){return this.collection}}class ki{constructor(t){Hi(this,"product",void 0),this.product=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t){const e=(this.product.integrationProducts||[]).find((e=>!!e.integration?.type&&e.integration?.type===t));if(!e)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return e}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}}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 Gi{constructor(t,e,A,n){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,"bundleStateManager",void 0),Ui(this,"globalConfiguration",void 0),Ui(this,"globalPropertyStateManager",void 0),Ui(this,"globalPropertyHandleService",void 0),Ui(this,"eventListeners",new Map),Ui(this,"initializationPromise",void 0),Ui(this,"workflowExperiences",[]),Ui(this,"previewService",void 0),this.client=t,this.id=e.id,this.name=e.name||"",this.metadata=new Map(e.metadata?.map((t=>[t.key,t.value]))||[]),this.productCollection=e.productCollection,this.bundleStateManager=new Ri(e.bundleStateData),this.globalConfiguration=this.productCollection?.globalPropertyConfiguration,this.globalPropertyStateManager=new Pi(this.id,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new fi(this),this.setPreviewService(A),this.initializationPromise=this.loadExistingBundles(e.transactions?.map((t=>t.id))||[],n)}getInitializationPromise(){return this.initializationPromise}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()===Dt.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?new bi(this.productCollection):void 0}async addWorkflowExperience(t){await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState([t]))))}async addWorkflowExperiences(t){const e=t.map((t=>t.getWorkflowManager().getTransaction().id)),A=e.map((t=>this.workflowExperiences.find((e=>e.getWorkflowManager().getTransaction().id===t))));if(A.some((t=>!!t)))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter((t=>!!t)).map((t=>t?.getWorkflowManager().getTransaction().id)).join(", "));const n=we.getMap("transactionOwnerIds")||new Map,a=e.map((t=>n.get(t)));await ye.getShadowGraphqlClient().mutate({mutation:hi,variables:{id:this.id,transactionIds:e,transactionOwnerIds:a}}).catch((t=>{console.error(t)})),this.workflowExperiences.push(...t),await Promise.all([this.updateTransactionOrder(),(async()=>{for(const e of t)await this.injectExperienceIntoPreviewService(e);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState(t))))})()])}async appendWorkflowExperience(t,e=!0){const A=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===A)))throw new Error("Unable to add transaction to bundle - Already Exists!");const n=(we.getMap("transactionOwnerIds")||new Map).get(A);await ye.getShadowGraphqlClient().mutate({mutation:wi,variables:{id:this.id,transactionId:A},context:{transactionOwnerId:n}}),e&&this.workflowExperiences.push(t)}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperiences(t){await this.removeTransactions(t.map((t=>t.getWorkflowManager().getTransaction())))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id));await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,A=!0){if(!(t>-1))throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id);{const n=this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===e.id));this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await ye.getShadowGraphqlClient().mutate({mutation:Ei,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}}),A&&(this.workflowExperiences.splice(t,1),await this.updateTransactionOrder())}}async removeTransactions(t){const e=t.map((t=>this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id))));if(e.some((t=>-1===t)))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter(((t,A)=>-1===e[A])).map((t=>t.id)).join(", "));const A=t.map((t=>this.workflowExperiences.splice(this.workflowExperiences.findIndex((e=>e.getWorkflowManager().getTransaction().id===t.id)),1)[0]));this.previewService&&A.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t.forEach((t=>this.bundleStateManager.removeStateForTransaction(t.id))),await ye.getShadowGraphqlClient().mutate({mutation:ui,variables:{id:this.id,transactionIds:t.map((t=>t.id)),name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const e=await this.getGlobalProperties();await Promise.all(e.map((e=>e.applyGlobalState([t]))))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const A=this.workflowExperiences[t];if(A.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,A.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const t=await this.getGlobalProperties();await Promise.all(t.map((t=>t.applyGlobalState([e]))))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const A=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=A,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const A=await ye.getShadowGraphqlClient().mutate({mutation:Ci,variables:{id:this.id,details:t,type:e||BA.Owner}});if(!A.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const n=A.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async updateStakeholders(t){const e=await ye.getShadowGraphqlClient().mutate({mutation:Qi,variables:{id:this.id,input:t}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const A=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(A)}async getAllStakeholders(){const t=await ye.getShadowGraphqlClient().query({query:gi,errorPolicy:"all",variables:{id:this.id}});if(!t.data.bundles||0===t.data.bundles.length)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}storeStakeholderCustomers(t){t.forEach((t=>{t.customer&&this.client.storeCustomer(t.customer)}))}async finish(t){return await Ai(this.workflowExperiences.map((t=>({workflowManager:t.getWorkflowManager(),workflow:t.getWorkflowManager().getWorkflow(),layouts:t.getWorkflowManager().getLayouts(),getReducerState:()=>t.getCommandContext().getState(),product:t.getWorkflowManager().getProduct(),transaction:t.getWorkflowManager().getTransaction(),workflowSelections:t.getWorkflowManager().getWorkflowSelections(),designName:t.getWorkflowManager().getWorkflow().name,variationRecords:t.getWorkflowManager().getVariationRecords(),updateVariationRecords:e=>t.updateVariationRecords(e),workflowMetadata:t.getWorkflowManager().getWorkflowMetadata()}))),t??(()=>{}))}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach((t=>t.getWorkflowManager().ejectFromPreviewService())),t))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}setWorkflowExperienceTransform(t,e){return this.bundleStateManager.setWorkflowExperienceTransform(t,e),this.updateBundle()}onModelLoadEvent(t){"unload"!==t.eventType&&t.modelContainer&&(t.modelContainer.registerMaterialSelectedCallback((()=>this.onModelSelectedEvent(t.modelContainer,!0))),t.modelContainer.registerMaterialDeselectedCallback((()=>this.onModelSelectedEvent(t.modelContainer,!1))))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const A=t.metadata.get("workflowManager").getTransaction(),n=this.workflowExperiences.find((t=>t.getWorkflowManager().getTransaction().id===A.id));n&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:n})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(t){console.error(`Unable to apply state to workflow experience: ${t}`)}await e}}async loadExistingBundles(t,e){if(0===t.length)return;const A=await this.client.getWorkflowExperiences(t.map((t=>({type:"transaction",transactionId:t}))),e);if(this.workflowExperiences=A,this.previewService)for(const t of A)await this.injectExperienceIntoPreviewService(t)}async updateBundle(){if(!(await ye.getShadowGraphqlClient().mutate({mutation:di,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map((([t,e])=>({key:t,value:e}))),bundleStateData:this.bundleStateManager.getSerializedState()}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await ye.getShadowGraphqlClient().mutate({mutation:pi,variables:{id:this.id,transactionIds:this.workflowExperiences.map((t=>t.getWorkflowManager().getTransaction().id))}})}async checkConditionalHandlesChanged(t,e){const A=await this.globalPropertyHandleService.getHandles(),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})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:a})}fireEvent(t,e){(this.eventListeners.get(t)||[]).forEach((A=>A({bundle:this,event:t,data:e})))}}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}const Ti=It`
|
|
930
930
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
931
931
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
932
932
|
id
|
|
@@ -936,7 +936,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
936
936
|
}
|
|
937
937
|
}
|
|
938
938
|
}
|
|
939
|
-
`;class
|
|
939
|
+
`;class Li{async execute(t,e,A){if(!(await ye.getShadowGraphqlClient().mutate({mutation:Ti,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:It`
|
|
940
940
|
query getProcessFlowExecution($ids: [String]!) {
|
|
941
941
|
processExecutions(ids: $ids) {
|
|
942
942
|
id
|
|
@@ -948,7 +948,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
948
948
|
}
|
|
949
949
|
}
|
|
950
950
|
}
|
|
951
|
-
`,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
|
|
951
|
+
`,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 Oi{constructor(t){Ji(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 zi;var ji;(ji=zi||(zi={})).Transaction="Transaction",ji.Bundle="Bundle",ji.Product="Product",ji.Variant="Variant",ji.Option="Option",ji.LineItem="LineItem",ji.Asset="Asset";class Ki extends Oi{constructor(t,e){if("Asset"!==e&&!Ki.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 Vi extends Oi{constructor(t){super(t)}}function Wi(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 Xi=It`
|
|
952
952
|
fragment RegionFields on Region {
|
|
953
953
|
width
|
|
954
954
|
top
|
|
@@ -966,7 +966,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
966
966
|
height
|
|
967
967
|
}
|
|
968
968
|
}
|
|
969
|
-
`,
|
|
969
|
+
`,qi=It`
|
|
970
970
|
fragment LookAtAnimationFields on LookAtAnimation {
|
|
971
971
|
latDeg
|
|
972
972
|
lonDeg
|
|
@@ -977,7 +977,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
977
977
|
z
|
|
978
978
|
}
|
|
979
979
|
}
|
|
980
|
-
`,
|
|
980
|
+
`,Zi=It`
|
|
981
981
|
fragment RenderingPipelineConfigurationFields on RenderingPipelineConfiguration {
|
|
982
982
|
antiAliasing {
|
|
983
983
|
samples
|
|
@@ -1061,14 +1061,14 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1061
1061
|
weight
|
|
1062
1062
|
}
|
|
1063
1063
|
}
|
|
1064
|
-
|
|
1064
|
+
`,$i=It`
|
|
1065
1065
|
fragment ModelAnimationFields on ModelAnimation {
|
|
1066
1066
|
from
|
|
1067
1067
|
to
|
|
1068
1068
|
loop
|
|
1069
1069
|
name
|
|
1070
1070
|
}
|
|
1071
|
-
|
|
1071
|
+
`,_i=It`
|
|
1072
1072
|
query GetTransactionForPartner($id: String!) {
|
|
1073
1073
|
transactions(ids: [$id]) {
|
|
1074
1074
|
id
|
|
@@ -1085,7 +1085,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1085
1085
|
}
|
|
1086
1086
|
}
|
|
1087
1087
|
}
|
|
1088
|
-
`,
|
|
1088
|
+
`,to=It`
|
|
1089
1089
|
${Se(!1)}
|
|
1090
1090
|
query GetWorkflowForTheme($id: String!) {
|
|
1091
1091
|
workflow(id: $id) {
|
|
@@ -1107,7 +1107,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1107
1107
|
}
|
|
1108
1108
|
}
|
|
1109
1109
|
}
|
|
1110
|
-
`,
|
|
1110
|
+
`,eo=It`
|
|
1111
1111
|
query GetCustomer($emailAddress: String!) {
|
|
1112
1112
|
customer(emailAddress: $emailAddress) {
|
|
1113
1113
|
id
|
|
@@ -1117,7 +1117,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1117
1117
|
}
|
|
1118
1118
|
}
|
|
1119
1119
|
}
|
|
1120
|
-
`,
|
|
1120
|
+
`,Ao=It`
|
|
1121
1121
|
mutation CustomerCreate($details: CustomerDetailsInput!) {
|
|
1122
1122
|
customerCreate(details: $details) {
|
|
1123
1123
|
id
|
|
@@ -1127,7 +1127,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1127
1127
|
}
|
|
1128
1128
|
}
|
|
1129
1129
|
}
|
|
1130
|
-
`,
|
|
1130
|
+
`,no=It`
|
|
1131
1131
|
mutation CustomerAuthenticate($loginToken: String!) {
|
|
1132
1132
|
customerAuthenticate(loginToken: $loginToken) {
|
|
1133
1133
|
id
|
|
@@ -1154,11 +1154,11 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1154
1154
|
}
|
|
1155
1155
|
}
|
|
1156
1156
|
}
|
|
1157
|
-
`,
|
|
1157
|
+
`,ao=It`
|
|
1158
1158
|
mutation CustomerGenerateVerificationCode($emailAddress: String!) {
|
|
1159
1159
|
customerGenerateVerificationCode(emailAddress: $emailAddress)
|
|
1160
1160
|
}
|
|
1161
|
-
`,
|
|
1161
|
+
`,io=It`
|
|
1162
1162
|
mutation CustomerVerifyCode($emailAddress: String!, $verificationCode: String!) {
|
|
1163
1163
|
customerVerifyCode(emailAddress: $emailAddress, verificationCode: $verificationCode) {
|
|
1164
1164
|
id
|
|
@@ -1186,14 +1186,14 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1186
1186
|
}
|
|
1187
1187
|
}
|
|
1188
1188
|
}
|
|
1189
|
-
`,
|
|
1189
|
+
`,oo=async(t,e)=>{const A=t.map((t=>Ue.get({id:t,options:e}))),n=t.filter(((t,e)=>void 0===A[e]));if(0===n.length)return Promise.all(A);const a=(async(t,e)=>{const A=await ye.getShadowGraphqlClient().query({query:(n=e?.assets?.metadata||!1,It`
|
|
1190
1190
|
${Se(n)}
|
|
1191
1191
|
${ve}
|
|
1192
1192
|
${Je}
|
|
1193
|
-
${Wi}
|
|
1194
1193
|
${Xi}
|
|
1195
1194
|
${qi}
|
|
1196
1195
|
${Zi}
|
|
1196
|
+
${$i}
|
|
1197
1197
|
query GetWorkflows($ids: [String!]!) {
|
|
1198
1198
|
workflows(ids: $ids) {
|
|
1199
1199
|
allowProofDownload
|
|
@@ -1571,5 +1571,5 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
|
|
|
1571
1571
|
}
|
|
1572
1572
|
}
|
|
1573
1573
|
}
|
|
1574
|
-
`),errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:t}});var n;const a=A.data.workflows;if(void 0===a||a.length!==t.length)throw new Error(`Unable to read workflows: ${A.errors??"Length mismatch in response"}`);return a.forEach((t=>{t.steps.forEach((t=>{delete t.data.__typename,t.option?.id&&(t.option.defaultVariant?.asset&&be.cacheAsset(t.option.defaultVariant.asset),t.option.colorProfile&&be.cacheAsset(t.option.colorProfile),t.option.variants?.forEach((t=>{t.asset&&be.cacheAsset(t.asset),t.displayImage&&be.cacheAsset(t.displayImage),t.thumbnail&&be.cacheAsset(t.thumbnail),t.material&&be.cacheMaterial(t.material)})),Ue.set({id:t.option.id},Promise.resolve(t.option)))}))})),a})(n,e),i=n.map((t=>Ue.set({id:t,options:e},(async(t,e)=>{const A=(await e).find((e=>e.id===t));if(!A)throw new Error(`Workflow not found: ${t}`);return A})(t,a)))),o=A.filter((t=>void 0!==t));return await Promise.all(o.concat(i))},oo=async(t,e)=>(await io([t],e))[0],ro=(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 so{constructor(t){var e;Vi(this,"options",void 0),Vi(this,"initialized",void 0),Vi(this,"currencyCode",void 0),Vi(this,"customer",void 0),Vi(this,"experienceOptions",void 0),Vi(this,"updateTransactionState",(async t=>{try{return ye.getShadowGraphqlClient().mutate({...t,mutation:On})}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,Ie=e)}getAssetManager(){return be}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 Ti}async authenticateBundleFromLocalStorage(t){const e=we.getMap("bundleOwnerIds");if(e?.has(t)){const A=e.get(t);return me(A),Promise.resolve({success:!0,stakeholderType:BA.Owner})}const A=we.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const e=A.get(t),n=(we.getMap("partnerCustomerIds")||new Map).get(e);if(n){if(await this.authenticateCustomerId(n)){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:$i,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=we.getMap("transactionOwnerIds");if(i?.has(t)){const e=i.get(t);return Qe(e),Promise.resolve({success:!0,stakeholderType:BA.Owner})}const o=we.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:_i,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=we.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),we.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:to,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!A.id){const A=(await e.mutate({mutation:eo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!A)throw new Error("Unable to create customer.");return this.storeCustomer(A),this.customer=A,{customer:A,isAuthenticated:!1}}this.storeCustomer(A);const n=await this.authenticateCustomerId(A.id);return{customer:this.customer||A,isAuthenticated:n}}async authenticateCustomerId(t){const e=ye.getShadowGraphqlClient(),A=we.getMap("customerTokens");if(!A?.has(t))return!1;const n=A.get(t);if(!n)return!1;const a=(await e.mutate({mutation:Ao,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data?.customerAuthenticate;return!!a&&(this.storeCustomer(a),De(n),this.customer=a,!0)}async generateVerificationCode(t){await ye.getShadowGraphqlClient().mutate({mutation:no,variables:{emailAddress:t}})}async verifyCode(t,e){const A=(await ye.getShadowGraphqlClient().mutate({mutation:ao,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=we.getMap("customerTokens")||new Map;return e.set(A.id,A.loginToken),we.setMap("customerTokens",e),this.storeCustomer(A),De(A.loginToken),this.customer={...A,loginToken:void 0},!0}return!1}async getNewBundle(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:li,variables:{collectionId:t},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!e?.id)throw new Error("Unable to create bundle");const A=we.getMap("bundlePartnerIds")||new Map;A.set(e.id,e.partner.id),we.setMap("bundlePartnerIds",A),me(e.bundleOwnerId);const n=we.getMap("bundleOwnerIds")||new Map;return n.set(e.id,e.bundleOwnerId),we.setMap("bundleOwnerIds",n),new Ui(this,e)}async getExistingBundle(t,e,A){const n=we.getMap("bundleOwnerIds")?.get(t);n&&me(n);const a=await ye.getShadowGraphqlClient().query({query:si,variables:{id:t},fetchPolicy:"no-cache"});if(!a.data?.bundles||0===a.data?.bundles.length||!a.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const i=a.data?.bundles[0],o=we.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),we.setMap("bundlePartnerIds",o);const r=new Ui(this,i,e,A);return await r.getInitializationPromise(),r}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await ye.getShadowGraphqlClient().query({query:gi,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 wt(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:Ln,variables:{ids:[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 oo(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:Gn,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=oo(n.workflowId,n?.graphql),[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!")}:async t=>{const e=(we.getMap("transactionOwnerIds")||new Map).get(i.id)||void 0;return this.updateTransactionState({...t,context:{transactionOwnerId:e}})},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=ro(s.transaction,s.workflow);if(s.renderableContextService=new vn(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=we.getMap("transactionOwnerIds")||new Map;t.set(i.id,i.transactionOwnerId),Qe(i.transactionOwnerId||""),we.setMap("transactionOwnerIds",t)}else{const t=(we.getMap("transactionOwnerIds")||new Map).get(i.id);t&&Qe(t),s.isReloadedTransaction=!0}this.initialized=!0,this.experienceOptions=s;const c=new oi(this,s);return await c.getWorkflowManager().getInitializationPromise(),"transaction"!==n.type&&this.customer&&await c.attachCustomerDetails({email:this.customer.emailAddress}),c}async getWorkflowExperiences(t,e){if(0===t.length)throw new ce("No options provided!");const A=ye.getShadowGraphqlClient(),n=t.map(((t,e)=>({option:t,index:e}))),a=n.filter((t=>"transaction"===t.option.type)),i=n.filter((t=>"integration"===t.option.type||"external"===t.option.type)),o=(await Promise.all([(async()=>{if(0===a.length)return[];const t=a.map((t=>t.option.transactionId)),e=await A.query({query:Ln,variables:{ids:t},errorPolicy:"all",fetchPolicy:"no-cache"}),n=e.data.transactions;if(n.length!==a.length){const t=e.errors?.[0]?.message||"Unknown error";throw new ce(`Not all transactions were found: ${t}`)}return n.map(((t,e)=>({transaction:t,workflowId:t.workflowId,readOnly:a.find((e=>e.option.transactionId===t.id))?.option.readOnly??!1,index:a[e].index})))})(),(async()=>{if(0===i.length)return[];const t=await A.mutate({mutation:Jn,variables:{inputs:i.map((t=>({integrationProductId:"integration"===t.option.type?t.option.integrationProductId:void 0,externalIntegrationId:"external"===t.option.type?t.option.externalIntegrationId:void 0,externalProductId:"external"===t.option.type?t.option.externalProductId:void 0,workflowId:t.option.workflowId,bulk:t.option.bulk,claim:!0})))},errorPolicy:"all",fetchPolicy:"no-cache"}),e=t.data?.transactionCreateMany;if(!e||0===e.length){const e=t.errors?.[0]?.message||"Unknown error";throw new ce(`Failed to create transactions: ${e}`)}return e.map(((t,e)=>({transaction:t,workflowId:t.workflowId,readOnly:!1,index:i[e].index})))})()])).flat(),r=[...new Set(o.map((t=>t.workflowId)))],s=await io(r,e),c=new Map(s.map((t=>[t.id,t]))),g=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 wt(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)}}},l=we.getMap("transactionOwnerIds")||new Map,B=o.map((async e=>{const{transaction:A,workflowId:n,readOnly:a,index:i}=e,o=c.get(n),r=t[i];!l.get(A.id)&&A.transactionOwnerId&&l.set(A.id,A.transactionOwnerId);const s=l.get(A.id)||void 0,B={product:A.product,transaction:A,layouts:[],stateMutationFunc:a?async()=>{throw new re("State mutation is forbidden in read only mode!")}:async t=>this.updateTransactionState({...t,context:{transactionOwnerId:s}}),readOnly:a,workflow:o,isReloadedTransaction:"transaction"===r.type};if("transaction"===r.type&&A.workflowState){const t=JSON.parse(A.workflowState);B.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await g(t),B.reloadedState=t}else if(!a&&r.workflowState){const t=JSON.parse(r.workflowState);B.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await g(t),B.reloadedState=t}else B.layouts=ro(B.transaction,B.workflow);return B.renderableContextService=new vn(B.layouts),this.initialized=!0,this.experienceOptions=B,{experienceOptions:B,index:i,options:r}}));we.setMap("transactionOwnerIds",l);const d=(await Promise.all(B)).sort(((t,e)=>t.index-e.index)).map((async t=>{const{experienceOptions:e,options:A}=t,n=new oi(this,e);return await n.getWorkflowManager().getInitializationPromise(),"transaction"!==A.type&&this.customer&&await n.attachCustomerDetails({email:this.customer.emailAddress}),n}));return await Promise.all(d)}async initFromIntegrationProduct(t){if(""===t)throw new ce("No integration product ID provided.");const e=ye.getShadowGraphqlClient(),A=await e.mutate({mutation:Gn,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=we.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),Qe(n.transactionOwnerId||""),we.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:Ln,variables:{ids:[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=we.getMap("transactionOwnerIds")||new Map,a=n.get(t);if(a){Qe(a);const n=(await A.query({query:Ln,variables:{ids:[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:Tn,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),we.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 wt(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 oo(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 vn(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 oi(this,this.experienceOptions);return await e.getWorkflowManager().getInitializationPromise(),e}if(t){const a=ye.getShadowGraphqlClient().mutate({mutation:zn,variables:{workflowId:t,id:this.experienceOptions.transaction.id}}),i=oo(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=ro(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await i),this.experienceOptions.renderableContextService=new vn(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 oi(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}storeCustomer(t){const e=we.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),we.setMap("partnerCustomerIds",e)}}function co(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 go{constructor(){co(this,"getProduct",void 0),co(this,"getCommandContext",void 0),co(this,"getAllLayoutData",void 0),co(this,"getMetadata",void 0),co(this,"getWorkflowMetadata",void 0),co(this,"getStepStorage",void 0),co(this,"setModelContainer",void 0),co(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 lo(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 Bo;var wo;(wo=Bo||(Bo={})).SelectFrame="SelectFrame",wo.SelectImage="SelectImage",wo.Position="Position";class ho extends Na{constructor(t,e){super(t,e),lo(this,"frameService",this.manager.getStepSpecificServices(this.getId())?.frameService)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return la.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 la.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?Bo.SelectFrame:e||A||this.getImageData()?Bo.Position:Bo.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 Eo=t=>{const e=Gt(null),A=Gt(void 0),[n,a]=Nt(void 0),{addEvent:i,removeEvent:o,updateEvent:r,eventCache:s}=je(),[c,g]=Nt(!1),[l,B]=Nt(!1),{state:d,uiDispatcher:w}=eA(),h=Rt((t=>{const e=t;w(new tA({zoom:Math.max(.1,Math.min(e,d.maxZoom))}))}),[w,d.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]),u=Rt((t=>{i(t);"touch"===t.pointerType&&1===s.length&&(w(new tA({selectedElement:void 0})),B(!0),g(!0))}),[i,s.length,w]),C=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(d.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;w(new tA({selectedElement:void 0,xTranslation:d.xTranslation-e/d.zoom,yTranslation:d.yTranslation-n/d.zoom}))}t.isPrimary&&(A.current={x:t.screenX,y:t.screenY})}),[r,s,c,l,n,h,d.zoom,d.xTranslation,d.yTranslation,w]),Q=Rt((t=>{c&&h(d.zoom-.035*Math.sign(t.deltaY))}),[h,d.zoom,c]);bt((()=>{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]),KA([" "],(()=>{B(!0),w(new tA({selectedElement:void 0}))}),(()=>B(!1))),KA(["Control"],(()=>g(!0)),(()=>g(!1)));const p=Ut((()=>({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:u,onPointerUp:E,onPointerCancel:E,onPointerLeave:E,onPointerMove:C,style:p,children:t.children})};export{so as SpiffCommerceClient,t as CommandContext,Ee as spiffCoreConfiguration,qA as PromiseQueue,XA as QueueablePromise,go as MockWorkflowManager,Ma as InformationMessageType,Na as StepHandle,za as TextStepHandle,ho as FrameStepHandle,ka as BulkStepHandle,Oa as ShapeStepHandle,Ua as IllustrationStepHandle,Ga as MaterialStepHandle,Ja as ModelStepHandle,Ta as PictureStepHandle,La as QuestionStepHandle,fi as GlobalPropertyHandle,oA as BulkPriceCalculationStrategy,xa as Variant,oi as WorkflowExperienceImpl,ee as OptionNotFoundError,Ae as LayoutNotFoundError,ne as AssetNotFoundError,ae as ResourceNotFoundError,ie as MisconfigurationError,se as ParseError,re as UnhandledBehaviorError,be as assetService,ai as designService,ti as createDesign,Oe as optionService,we as persistenceService,ye as graphQlManager,EA as toast,na as FrameService,ea as getBoundedOffsets,la as frameStepService,wa as modelStepService,da as materialStepService,Qa as shapeStepService,ua as questionStepService,ca as digitalContentStepService,ha as moduleStepService,Ea as pictureStepService,Ia as textStepService,Ba as illustrationStepService,aA as ProductCameraRig,Bo as FrameStep,sA as ConversionLocation,gA as ConversionDataType,oo as getWorkflow,io as getWorkflows,oa as shortenUrl,ji as ObjectInput,Ki as TextInput,Oi as ObjectInputType,Hi as ProductCollection,bi as CollectionProduct,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,d as GroupCommand,w as LayoutElementFactory,h as LayoutElementType,E as MoveCommand,u as ResizeCommand,C as RotateCommand,Q as SendBackwardsCommand,BA as StakeholderType,p as StepAspectType,m as StepType,f as TextChangeCommand,D as UnitOfMeasurement,I as dataUrlFromExternalUrl,y as findElement,M as frameDataCache,F as generate,S as getAxisAlignedBoundingBox,Y as generateSVGWithUnknownColors,v as getAttributesFromArrayBuffer,x as rehydrateSerializedLayout,P as getFrameData,N as getSvgElement,R as loadFontFromDataUrl,H as loadFontFromExternalUrl,b as determineCorrectFontSizeAndLines,k as patternImageDataCache,Sn as generateCommands,U as registerJSDOM,OA as minZoom,Un as AdvancedEditor,Eo as TransformWrapper,kn as EditorCore,Ke as useLayouts,eA as useEditorState,jA as useEditorInteraction,KA as useShortcutCombination,Ze as commandReducer,qe as getDefaultState,ze as CommandContextContext,_e as AdvancedEditorStateProvider,$e as AdvancedEditorContext,tA as UICommand,We as EditorSubMenu,uA as ElementEventType,QA as KeyEvent,Vn as gatherVaryingStepAspects};
|
|
1574
|
+
`),errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:t}});var n;const a=A.data.workflows;if(void 0===a||a.length!==t.length)throw new Error(`Unable to read workflows: ${A.errors??"Length mismatch in response"}`);return a.forEach((t=>{t.steps.forEach((t=>{delete t.data.__typename,t.option?.id&&(t.option.defaultVariant?.asset&&be.cacheAsset(t.option.defaultVariant.asset),t.option.colorProfile&&be.cacheAsset(t.option.colorProfile),t.option.variants?.forEach((t=>{t.asset&&be.cacheAsset(t.asset),t.displayImage&&be.cacheAsset(t.displayImage),t.thumbnail&&be.cacheAsset(t.thumbnail),t.material&&be.cacheMaterial(t.material)})),Ue.set({id:t.option.id},Promise.resolve(t.option)))}))})),a})(n,e),i=n.map((t=>Ue.set({id:t,options:e},(async(t,e)=>{const A=(await e).find((e=>e.id===t));if(!A)throw new Error(`Workflow not found: ${t}`);return A})(t,a)))),o=A.filter((t=>void 0!==t));return await Promise.all(o.concat(i))},ro=async(t,e)=>(await oo([t],e))[0],so=(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 co{constructor(t){var e;Wi(this,"options",void 0),Wi(this,"initialized",void 0),Wi(this,"currencyCode",void 0),Wi(this,"customer",void 0),Wi(this,"experienceOptions",void 0),Wi(this,"updateTransactionState",(async t=>{try{return ye.getShadowGraphqlClient().mutate({...t,mutation:On})}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,Ie=e)}getAssetManager(){return be}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 Li}async authenticateBundleFromLocalStorage(t){const e=we.getMap("bundleOwnerIds");if(e?.has(t)){const A=e.get(t);return me(A),Promise.resolve({success:!0,stakeholderType:BA.Owner})}const A=we.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const e=A.get(t),n=(we.getMap("partnerCustomerIds")||new Map).get(e);if(n){if(await this.authenticateCustomerId(n)){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:_i,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=we.getMap("transactionOwnerIds");if(i?.has(t)){const e=i.get(t);return Qe(e),Promise.resolve({success:!0,stakeholderType:BA.Owner})}const o=we.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:to,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=we.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),we.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:eo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!A.id){const A=(await e.mutate({mutation:Ao,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!A)throw new Error("Unable to create customer.");return this.storeCustomer(A),this.customer=A,{customer:A,isAuthenticated:!1}}this.storeCustomer(A);const n=await this.authenticateCustomerId(A.id);return{customer:this.customer||A,isAuthenticated:n}}async authenticateCustomerId(t){const e=ye.getShadowGraphqlClient(),A=we.getMap("customerTokens");if(!A?.has(t))return!1;const n=A.get(t);if(!n)return!1;const a=(await e.mutate({mutation:no,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data?.customerAuthenticate;return!!a&&(this.storeCustomer(a),De(n),this.customer=a,!0)}async generateVerificationCode(t){await ye.getShadowGraphqlClient().mutate({mutation:ao,variables:{emailAddress:t}})}async verifyCode(t,e){const A=(await ye.getShadowGraphqlClient().mutate({mutation:io,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=we.getMap("customerTokens")||new Map;return e.set(A.id,A.loginToken),we.setMap("customerTokens",e),this.storeCustomer(A),De(A.loginToken),this.customer={...A,loginToken:void 0},!0}return!1}async getNewBundle(t){const e=(await ye.getShadowGraphqlClient().mutate({mutation:Bi,variables:{collectionId:t},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!e?.id)throw new Error("Unable to create bundle");const A=we.getMap("bundlePartnerIds")||new Map;A.set(e.id,e.partner.id),we.setMap("bundlePartnerIds",A),me(e.bundleOwnerId);const n=we.getMap("bundleOwnerIds")||new Map;return n.set(e.id,e.bundleOwnerId),we.setMap("bundleOwnerIds",n),new Gi(this,e)}async getExistingBundle(t,e,A){const n=we.getMap("bundleOwnerIds")?.get(t);n&&me(n);const a=await ye.getShadowGraphqlClient().query({query:ci,variables:{id:t},fetchPolicy:"no-cache"});if(!a.data?.bundles||0===a.data?.bundles.length||!a.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const i=a.data?.bundles[0],o=we.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),we.setMap("bundlePartnerIds",o);const r=new Gi(this,i,e,A);return await r.getInitializationPromise(),r}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await ye.getShadowGraphqlClient().query({query:li,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 wt(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:Ln,variables:{ids:[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 ro(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:Gn,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=ro(n.workflowId,n?.graphql),[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!")}:async t=>{const e=(we.getMap("transactionOwnerIds")||new Map).get(i.id)||void 0;return this.updateTransactionState({...t,context:{transactionOwnerId:e}})},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=so(s.transaction,s.workflow);if(s.renderableContextService=new vn(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=we.getMap("transactionOwnerIds")||new Map;t.set(i.id,i.transactionOwnerId),Qe(i.transactionOwnerId||""),we.setMap("transactionOwnerIds",t)}else{const t=(we.getMap("transactionOwnerIds")||new Map).get(i.id);t&&Qe(t),s.isReloadedTransaction=!0}this.initialized=!0,this.experienceOptions=s;const c=new ri(this,s);return await c.getWorkflowManager().getInitializationPromise(),"transaction"!==n.type&&this.customer&&await c.attachCustomerDetails({email:this.customer.emailAddress}),c}async getWorkflowExperiences(t,e){if(0===t.length)throw new ce("No options provided!");const A=ye.getShadowGraphqlClient(),n=t.map(((t,e)=>({option:t,index:e}))),a=n.filter((t=>"transaction"===t.option.type)),i=n.filter((t=>"integration"===t.option.type||"external"===t.option.type)),o=(await Promise.all([(async()=>{if(0===a.length)return[];const t=a.map((t=>t.option.transactionId)),e=await A.query({query:Ln,variables:{ids:t},errorPolicy:"all",fetchPolicy:"no-cache"}),n=e.data.transactions;if(n.length!==a.length){const t=e.errors?.[0]?.message||"Unknown error";throw new ce(`Not all transactions were found: ${t}`)}return n.map(((t,e)=>({transaction:t,workflowId:t.workflowId,readOnly:a.find((e=>e.option.transactionId===t.id))?.option.readOnly??!1,index:a[e].index})))})(),(async()=>{if(0===i.length)return[];const t=await A.mutate({mutation:Jn,variables:{inputs:i.map((t=>({integrationProductId:"integration"===t.option.type?t.option.integrationProductId:void 0,externalIntegrationId:"external"===t.option.type?t.option.externalIntegrationId:void 0,externalProductId:"external"===t.option.type?t.option.externalProductId:void 0,workflowId:t.option.workflowId,bulk:t.option.bulk,claim:!0})))},errorPolicy:"all",fetchPolicy:"no-cache"}),e=t.data?.transactionCreateMany;if(!e||0===e.length){const e=t.errors?.[0]?.message||"Unknown error";throw new ce(`Failed to create transactions: ${e}`)}return e.map(((t,e)=>({transaction:t,workflowId:t.workflowId,readOnly:!1,index:i[e].index})))})()])).flat(),r=[...new Set(o.map((t=>t.workflowId)))],s=await oo(r,e),c=new Map(s.map((t=>[t.id,t]))),g=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 wt(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)}}},l=we.getMap("transactionOwnerIds")||new Map,B=o.map((async e=>{const{transaction:A,workflowId:n,readOnly:a,index:i}=e,o=c.get(n),r=t[i];!l.get(A.id)&&A.transactionOwnerId&&l.set(A.id,A.transactionOwnerId);const s=l.get(A.id)||void 0,B={product:A.product,transaction:A,layouts:[],stateMutationFunc:a?async()=>{throw new re("State mutation is forbidden in read only mode!")}:async t=>this.updateTransactionState({...t,context:{transactionOwnerId:s}}),readOnly:a,workflow:o,isReloadedTransaction:"transaction"===r.type};if("transaction"===r.type&&A.workflowState){const t=JSON.parse(A.workflowState);B.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await g(t),B.reloadedState=t}else if(!a&&r.workflowState){const t=JSON.parse(r.workflowState);B.layouts=Object.values(t.layouts).map((t=>t.layout)),await x(t),await g(t),B.reloadedState=t}else B.layouts=so(B.transaction,B.workflow);return B.renderableContextService=new vn(B.layouts),this.initialized=!0,this.experienceOptions=B,{experienceOptions:B,index:i,options:r}}));we.setMap("transactionOwnerIds",l);const d=(await Promise.all(B)).sort(((t,e)=>t.index-e.index)).map((async t=>{const{experienceOptions:e,options:A}=t,n=new ri(this,e);return await n.getWorkflowManager().getInitializationPromise(),"transaction"!==A.type&&this.customer&&await n.attachCustomerDetails({email:this.customer.emailAddress}),n}));return await Promise.all(d)}async initFromIntegrationProduct(t){if(""===t)throw new ce("No integration product ID provided.");const e=ye.getShadowGraphqlClient(),A=await e.mutate({mutation:Gn,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=we.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),Qe(n.transactionOwnerId||""),we.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:Ln,variables:{ids:[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=we.getMap("transactionOwnerIds")||new Map,a=n.get(t);if(a){Qe(a);const n=(await A.query({query:Ln,variables:{ids:[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:Tn,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),we.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 wt(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 ro(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 vn(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 ri(this,this.experienceOptions);return await e.getWorkflowManager().getInitializationPromise(),e}if(t){const a=ye.getShadowGraphqlClient().mutate({mutation:zn,variables:{workflowId:t,id:this.experienceOptions.transaction.id}}),i=ro(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=so(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await i),this.experienceOptions.renderableContextService=new vn(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 ri(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}storeCustomer(t){const e=we.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),we.setMap("partnerCustomerIds",e)}}function go(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 lo{constructor(){go(this,"getProduct",void 0),go(this,"getCommandContext",void 0),go(this,"getAllLayoutData",void 0),go(this,"getMetadata",void 0),go(this,"getWorkflowMetadata",void 0),go(this,"getStepStorage",void 0),go(this,"setModelContainer",void 0),go(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 Bo(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 wo;var ho;(ho=wo||(wo={})).SelectFrame="SelectFrame",ho.SelectImage="SelectImage",ho.Position="Position";class Eo extends Na{constructor(t,e){super(t,e),Bo(this,"frameService",this.manager.getStepSpecificServices(this.getId())?.frameService)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return la.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 la.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?wo.SelectFrame:e||A||this.getImageData()?wo.Position:wo.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 uo=t=>{const e=Gt(null),A=Gt(void 0),[n,a]=Nt(void 0),{addEvent:i,removeEvent:o,updateEvent:r,eventCache:s}=je(),[c,g]=Nt(!1),[l,B]=Nt(!1),{state:d,uiDispatcher:w}=eA(),h=Rt((t=>{const e=t;w(new tA({zoom:Math.max(.1,Math.min(e,d.maxZoom))}))}),[w,d.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]),u=Rt((t=>{i(t);"touch"===t.pointerType&&1===s.length&&(w(new tA({selectedElement:void 0})),B(!0),g(!0))}),[i,s.length,w]),C=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(d.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;w(new tA({selectedElement:void 0,xTranslation:d.xTranslation-e/d.zoom,yTranslation:d.yTranslation-n/d.zoom}))}t.isPrimary&&(A.current={x:t.screenX,y:t.screenY})}),[r,s,c,l,n,h,d.zoom,d.xTranslation,d.yTranslation,w]),Q=Rt((t=>{c&&h(d.zoom-.035*Math.sign(t.deltaY))}),[h,d.zoom,c]);bt((()=>{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]),KA([" "],(()=>{B(!0),w(new tA({selectedElement:void 0}))}),(()=>B(!1))),KA(["Control"],(()=>g(!0)),(()=>g(!1)));const p=Ut((()=>({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:u,onPointerUp:E,onPointerCancel:E,onPointerLeave:E,onPointerMove:C,style:p,children:t.children})};export{co as SpiffCommerceClient,t as CommandContext,Ee as spiffCoreConfiguration,qA as PromiseQueue,XA as QueueablePromise,lo as MockWorkflowManager,Ma as InformationMessageType,Na as StepHandle,za as TextStepHandle,Eo as FrameStepHandle,ka as BulkStepHandle,Oa as ShapeStepHandle,Ua as IllustrationStepHandle,Ga as MaterialStepHandle,Ja as ModelStepHandle,Ta as PictureStepHandle,La as QuestionStepHandle,Di as GlobalPropertyHandle,oA as BulkPriceCalculationStrategy,xa as Variant,ri as WorkflowExperienceImpl,ee as OptionNotFoundError,Ae as LayoutNotFoundError,ne as AssetNotFoundError,ae as ResourceNotFoundError,ie as MisconfigurationError,se as ParseError,re as UnhandledBehaviorError,be as assetService,ii as designService,ei as createDesign,Oe as optionService,we as persistenceService,ye as graphQlManager,EA as toast,na as FrameService,ea as getBoundedOffsets,la as frameStepService,wa as modelStepService,da as materialStepService,Qa as shapeStepService,ua as questionStepService,ca as digitalContentStepService,ha as moduleStepService,Ea as pictureStepService,Ia as textStepService,Ba as illustrationStepService,aA as ProductCameraRig,wo as FrameStep,sA as ConversionLocation,gA as ConversionDataType,ro as getWorkflow,oo as getWorkflows,oa as shortenUrl,Ki as ObjectInput,Vi as TextInput,zi as ObjectInputType,bi as ProductCollection,ki as CollectionProduct,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,d as GroupCommand,w as LayoutElementFactory,h as LayoutElementType,E as MoveCommand,u as ResizeCommand,C as RotateCommand,Q as SendBackwardsCommand,BA as StakeholderType,p as StepAspectType,m as StepType,f as TextChangeCommand,D as UnitOfMeasurement,I as dataUrlFromExternalUrl,y as findElement,M as frameDataCache,F as generate,S as getAxisAlignedBoundingBox,Y as generateSVGWithUnknownColors,v as getAttributesFromArrayBuffer,x as rehydrateSerializedLayout,P as getFrameData,N as getSvgElement,R as loadFontFromDataUrl,H as loadFontFromExternalUrl,b as determineCorrectFontSizeAndLines,k as patternImageDataCache,Sn as generateCommands,U as registerJSDOM,OA as minZoom,Un as AdvancedEditor,uo as TransformWrapper,kn as EditorCore,Ke as useLayouts,eA as useEditorState,jA as useEditorInteraction,KA as useShortcutCombination,Ze as commandReducer,qe as getDefaultState,ze as CommandContextContext,_e as AdvancedEditorStateProvider,$e as AdvancedEditorContext,tA as UICommand,We as EditorSubMenu,uA as ElementEventType,QA as KeyEvent,Vn as gatherVaryingStepAspects};
|
|
1575
1575
|
//# sourceMappingURL=module.js.map
|