@spiffcommerce/core 21.7.1 → 21.8.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.
@@ -2289,6 +2289,12 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2289
2289
  }
2290
2290
  }
2291
2291
  `,Xn=M.gql`
2292
+ mutation BundleAddStakeholder($id: String!, $emailAddress: String!) {
2293
+ bundleRemoveStakeholder(id: $id, emailAddress: $emailAddress) {
2294
+ id
2295
+ }
2296
+ }
2297
+ `,qn=M.gql`
2292
2298
  mutation BundleUpdateStakeholders($id: String!, $input: [BundleStakeholderInput!]!) {
2293
2299
  bundleUpdateStakeholders(id: $id, input: $input) {
2294
2300
  id
@@ -2308,13 +2314,13 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2308
2314
  }
2309
2315
  }
2310
2316
  }
2311
- `,qn=M.gql`
2317
+ `,Zn=M.gql`
2312
2318
  mutation BundleUpdateTransactionOrder($id: String!, $transactionIds: [String!]!) {
2313
2319
  bundleUpdateTransactionOrder(id: $id, transactionIds: $transactionIds) {
2314
2320
  id
2315
2321
  }
2316
2322
  }
2317
- `;class Zn{constructor(e){this.handleCache={},this.bundle=e}async getHandle(e){if(this.handleCache[e.name])return this.handleCache[e.name];const t=await this.createHandle(e);return this.handleCache[e.name]=t,t}async getHandles(){var t;if(!((t=this.bundle.getProductCollection())!=null&&t.getResource().globalPropertyConfiguration))return[];const e=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(e.aspects.map(A=>this.getHandle(A)))}applyConditionsFromState(e,t){return t?e.filter(A=>this.aspectConditionsSatisfied(A.getRawProperty(),t)):e}aspectConditionsSatisfied(e,t){return!e.conditions||e.conditions.length===0?!0:e.conditions.some(A=>{const n=t.aspects.find(a=>a.name===A.targetAspectName);return n?A.requiredVariantSelections.some(a=>a===n.value):!1})}async createHandle(e){switch(e.type){case g.AspectType.FileUpload:return new qt(this.bundle,e);case g.AspectType.Option:{const t=e.entityId?await L.getOption(e.entityId):void 0;return(t==null?void 0:t.type)==="Color"?new $t(this.bundle,e,t):new Ke(this.bundle,e,t)}case g.AspectType.Text:return new Zt(this.bundle,e)}}}class Se{constructor(e,t){this.bundle=e,this.property=t}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(e){return(e??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getSteps().filter(a=>{var i;return a.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(i=a.getRaw().globalPropertyAspectConfigurations)==null?void 0:i.some(o=>{var s,r;return o.globalPropertyConfigurationId===((r=(s=this.bundle.getProductCollection())==null?void 0:s.getResource().globalPropertyConfiguration)==null?void 0:r.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class qt extends Se{constructor(e,t){super(e,t)}async selectImage(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.key),this.applyImageSelection(e)])}hasImage(){return!!this.getStateValue()}async getImage(){const e=this.getStateValue();if(e)return k.getLocalOrFromServer(e)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return Promise.resolve();const A=await k.getLocalOrFromServer(t);return A?this.applyImageSelection(A,e):Promise.resolve()}async applyImageSelection(e,t){const n=this.getSharedSteps(t).map(a=>a.selectImage(e));await Promise.all(n)}}class Zt extends Se{constructor(e,t){super(e,t)}getText(){const e=this.getStateValue();return e||""}async setText(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e),this.applyTextSelection(e)])}async applyGlobalState(e){const t=this.getStateValue();if(!t)return Promise.resolve();await this.applyTextSelection(t,e)}async applyTextSelection(e,t){const n=this.getSharedSteps(t).map(a=>{a.setText(e)});await Promise.all(n)}}class Ke extends Se{constructor(e,t,A){super(e,t),this.optionResource=A}getCurrentVariant(){var t,A;if(!this.optionResource)return;const e=this.getStateValue();if(e){const n=(A=this.optionResource.variants)==null?void 0:A.find(a=>a.id===e);return n?new K(n):void 0}else{const n=(t=this.optionResource.variants)==null?void 0:t.find(a=>{var i,o;return a.id===((o=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:o.id)});return n?new K(n):void 0}}getAvailableVariants(){var t,A;return(((A=(t=this.optionResource)==null?void 0:t.variants)==null?void 0:A.filter(n=>n.enabled))||[]).map(n=>new K(n))}getAllVariants(){var t;return(((t=this.optionResource)==null?void 0:t.variants)||[]).map(A=>new K(A))}async selectVariant(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.getId()),this.applyVariantSelection(e)])}async applyGlobalState(e){var n,a;const t=this.getStateValue();if(!t)return Promise.resolve();const A=(a=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:a.find(i=>i.id===t);return A?this.applyVariantSelection(new K(A),e):Promise.resolve()}async applyVariantSelection(e,t){const n=this.getSharedSteps(t).map(a=>a.selectVariant(e));await Promise.all(n)}}class $t extends Ke{constructor(e,t,A){super(e,t,A)}setCustomColor(e){this.getSharedSteps().forEach(A=>A.setCustomColor(e))}getCustomColor(){return this.getSharedSteps()[0].getCustomColor()}}const $n=M.gql`
2323
+ `;class $n{constructor(e){this.handleCache={},this.bundle=e}async getHandle(e){if(this.handleCache[e.name])return this.handleCache[e.name];const t=await this.createHandle(e);return this.handleCache[e.name]=t,t}async getHandles(){var t;if(!((t=this.bundle.getProductCollection())!=null&&t.getResource().globalPropertyConfiguration))return[];const e=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(e.aspects.map(A=>this.getHandle(A)))}applyConditionsFromState(e,t){return t?e.filter(A=>this.aspectConditionsSatisfied(A.getRawProperty(),t)):e}aspectConditionsSatisfied(e,t){return!e.conditions||e.conditions.length===0?!0:e.conditions.some(A=>{const n=t.aspects.find(a=>a.name===A.targetAspectName);return n?A.requiredVariantSelections.some(a=>a===n.value):!1})}async createHandle(e){switch(e.type){case g.AspectType.FileUpload:return new qt(this.bundle,e);case g.AspectType.Option:{const t=e.entityId?await L.getOption(e.entityId):void 0;return(t==null?void 0:t.type)==="Color"?new $t(this.bundle,e,t):new Ke(this.bundle,e,t)}case g.AspectType.Text:return new Zt(this.bundle,e)}}}class Se{constructor(e,t){this.bundle=e,this.property=t}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(e){return(e??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getSteps().filter(a=>{var i;return a.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(i=a.getRaw().globalPropertyAspectConfigurations)==null?void 0:i.some(o=>{var s,r;return o.globalPropertyConfigurationId===((r=(s=this.bundle.getProductCollection())==null?void 0:s.getResource().globalPropertyConfiguration)==null?void 0:r.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class qt extends Se{constructor(e,t){super(e,t)}async selectImage(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.key),this.applyImageSelection(e)])}hasImage(){return!!this.getStateValue()}async getImage(){const e=this.getStateValue();if(e)return k.getLocalOrFromServer(e)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return Promise.resolve();const A=await k.getLocalOrFromServer(t);return A?this.applyImageSelection(A,e):Promise.resolve()}async applyImageSelection(e,t){const n=this.getSharedSteps(t).map(a=>a.selectImage(e));await Promise.all(n)}}class Zt extends Se{constructor(e,t){super(e,t)}getText(){const e=this.getStateValue();return e||""}async setText(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e),this.applyTextSelection(e)])}async applyGlobalState(e){const t=this.getStateValue();if(!t)return Promise.resolve();await this.applyTextSelection(t,e)}async applyTextSelection(e,t){const n=this.getSharedSteps(t).map(a=>{a.setText(e)});await Promise.all(n)}}class Ke extends Se{constructor(e,t,A){super(e,t),this.optionResource=A}getCurrentVariant(){var t,A;if(!this.optionResource)return;const e=this.getStateValue();if(e){const n=(A=this.optionResource.variants)==null?void 0:A.find(a=>a.id===e);return n?new K(n):void 0}else{const n=(t=this.optionResource.variants)==null?void 0:t.find(a=>{var i,o;return a.id===((o=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:o.id)});return n?new K(n):void 0}}getAvailableVariants(){var t,A;return(((A=(t=this.optionResource)==null?void 0:t.variants)==null?void 0:A.filter(n=>n.enabled))||[]).map(n=>new K(n))}getAllVariants(){var t;return(((t=this.optionResource)==null?void 0:t.variants)||[]).map(A=>new K(A))}async selectVariant(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.getId()),this.applyVariantSelection(e)])}async applyGlobalState(e){var n,a;const t=this.getStateValue();if(!t)return Promise.resolve();const A=(a=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:a.find(i=>i.id===t);return A?this.applyVariantSelection(new K(A),e):Promise.resolve()}async applyVariantSelection(e,t){const n=this.getSharedSteps(t).map(a=>a.selectVariant(e));await Promise.all(n)}}class $t extends Ke{constructor(e,t,A){super(e,t,A)}setCustomColor(e){this.getSharedSteps().forEach(A=>A.setCustomColor(e))}getCustomColor(){return this.getSharedSteps()[0].getCustomColor()}}const _n=M.gql`
2318
2324
  mutation CreateGlobalPropertyState($bundleId: String!) {
2319
2325
  globalPropertyStateCreate(bundleId: $bundleId) {
2320
2326
  id
@@ -2324,7 +2330,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2324
2330
  }
2325
2331
  }
2326
2332
  }
2327
- `,_n=M.gql`
2333
+ `,ea=M.gql`
2328
2334
  mutation UpdateGlobalPropertyState($id: String!, $aspects: [GlobalPropertyStateAspectInput]!) {
2329
2335
  globalPropertyStateUpdate(id: $id, aspects: $aspects) {
2330
2336
  id
@@ -2334,7 +2340,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2334
2340
  }
2335
2341
  }
2336
2342
  }
2337
- `,ea=M.gql`
2343
+ `,ta=M.gql`
2338
2344
  query GetGlobalPropertyState($bundleId: String!) {
2339
2345
  globalPropertyState(bundleId: $bundleId) {
2340
2346
  id
@@ -2344,13 +2350,13 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2344
2350
  }
2345
2351
  }
2346
2352
  }
2347
- `;class ta{constructor(e,t,A){this.bundleId=e,this.bundleOwnerId=t,this.initPromise=this.getOrCreateGlobalPropertyState().then(n=>{this.globalPropertyState=n}),this.onGlobalPropertyStateChange=A}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}getAspect(e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=this.globalPropertyState.aspects.find(A=>A.name===e);if(t)return t.value}async setAspect(e,t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=Ee(this.globalPropertyState),n=this.globalPropertyState.aspects.find(a=>a.name===e);n?n.value=t:this.globalPropertyState.aspects.push({name:e,value:t}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){var t;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=await N.getShadowGraphqlClient().mutate({mutation:_n,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects},context:{bundleOwnerId:this.bundleOwnerId}});if((t=e.data)!=null&&t.globalPropertyStateUpdate)this.globalPropertyState=e.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async getOrCreateGlobalPropertyState(){var A;const e=await N.getShadowGraphqlClient().query({query:ea,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId},context:{bundleOwnerId:this.bundleOwnerId}});if(e.data.globalPropertyState&&e.data.globalPropertyState.id)return e.data.globalPropertyState;const t=await N.getShadowGraphqlClient().mutate({mutation:$n,variables:{bundleId:this.bundleId},context:{bundleOwnerId:this.bundleOwnerId}});if((A=t.data)!=null&&A.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class Aa{constructor(e){this.setState(e)}setState(e){e&&(this.state=JSON.parse(e))}applyStateToWorkflowExperience(e){var i;if(!this.state||!((i=e==null?void 0:e.getWorkflowManager())!=null&&i.getModelContainer()))return;const t=this.state.transactions.find(o=>o.transactionId===e.getWorkflowManager().getTransaction().id);if(!t)return;const A=this.getTransformToApply(t);if(!A)return;const n=this.flipTransform(A,e.getWorkflowManager().getPreviewService()),a=e.getWorkflowManager().getModelContainer();a.position=n.position,a.rotation=n.rotation,a.scale=n.scale}getTransformToApply(e){return e.activeTransform&&e.transforms?e.transforms[e.activeTransform]:e.transform}updateWorkflowExperienceTransform(e,t,A){const n=e.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const a=this.state.transactions.find(i=>i.transactionId===n);a?(a.transforms||(a.transforms={}),a.transforms[t]=A):this.state.transactions.push({transactionId:n,activeTransform:t,transforms:{[t]:A}})}activateWorkflowExperienceTransform(e,t){var s,r;if(!((s=e==null?void 0:e.getWorkflowManager())!=null&&s.getModelContainer())||!this.state)return;const A=e.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(l=>l.transactionId===A),a=(r=n==null?void 0:n.transforms)==null?void 0:r[t];if(!a)return;const i=this.flipTransform(a,e.getWorkflowManager().getPreviewService()),o=e.getWorkflowManager().getModelContainer();o.position=i.position,o.rotation=i.rotation,o.scale=i.scale,n.activeTransform=t}removeStateForTransaction(e){if(!this.state||!this.state.transactions)return;const t=this.state.transactions.findIndex(A=>A.transactionId===e);t!==-1&&this.state.transactions.splice(t,1)}getSerializedState(){if(this.state)return JSON.stringify(this.state)}flipTransform(e,t){return t&&t.flipTransform?t.flipTransform(e.position,{x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},e.scale):{position:e.position,rotation:{x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},scale:e.scale}}}class _t{constructor(e){this.collection=e}getId(){return this.collection.id}getName(){return this.collection.name}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.map(e=>new ye(e))}async fetchProducts(){if(this.collection.productCollectionProducts)return this.collection.productCollectionProducts.map(t=>new ye(t));const e=await N.getShadowGraphqlClient().query({query:Tn,variables:{id:this.getId()},errorPolicy:"all",fetchPolicy:"no-cache"});return this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.map(t=>new ye(t))}getTransformCollection(){if(this.collection.transformCollection)return new eA(this.collection.transformCollection)}getResource(){return this.collection}}class ye{constructor(e){this.product=e.product,this.productResource=e}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(e,t){const n=(this.product.integrationProducts||[]).find(a=>{var r,l,d;const i=(r=a.integration)==null?void 0:r.type,o=((l=a.integration)==null?void 0:l.type)===e,s=t?((d=a.integration)==null?void 0:d.externalIntegrationId)===t:!0;return i&&o&&s});if(!n)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return n}getCurrentIntegration(){const t=(this.product.integrationProducts||[]).find(A=>{var n;return(n=A.integration)==null?void 0:n.isCurrent});if(!t)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return t}getDefaultWorkflow(){const e=this.product.workflows||[];if(e.length===0)throw new G("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");const t=this.productResource.workflowId;if(t){const n=e.find(a=>a.workflowName===t);if(n)return new Ae(n)}const A=e[0];return new Ae(A)}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new G("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return this.product.workflows.sort((t,A)=>(t.index??0)-(A.index??0)).map(t=>new Ae(t))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(e){var n,a,i,o;const t=this.product.basePrice||0;if(!e)return t;if(!e.integrationType&&!e.externalId&&!e.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let A;return e.integrationId?A=(n=this.product.integrationProducts)==null?void 0:n.find(s=>{var r;return((r=s.integration)==null?void 0:r.id)===e.integrationId}):e.externalId?A=(a=this.product.integrationProducts)==null?void 0:a.find(s=>{var r;return((r=s.integration)==null?void 0:r.externalIntegrationId)===e.externalId}):A=(i=this.product.integrationProducts)==null?void 0:i.find(s=>{var r;return((r=s.integration)==null?void 0:r.type)===e.integrationType}),(o=A==null?void 0:A.additionalIntegrationProduct)!=null&&o.product?t+(A.additionalIntegrationProduct.product.basePrice||0):t}}class Ae{constructor(e){this.workflow=e}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class eA{constructor(e){this.collection=e}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(e=>new tA(e))}}class tA{constructor(e){this.transform=e}getId(){return this.transform.id}getName(){return this.transform.name}get(){return{position:this.transform.position,rotation:this.transform.rotation,scale:this.transform.scale}}}class AA{constructor(e,t,A,n,a){var i,o;this.eventListeners=new Map,this.workflowExperiences=[],this.client=e,this.id=t.id,this.name=t.name||"",this.ownerId=a,this.metadata=new Map(((i=t.metadata)==null?void 0:i.map(s=>[s.key,s.value]))||[]),this.productCollection=t.productCollection,this.bundleStateManager=new Aa(t.bundleStateData),this.globalPropertyStateManager=new ta(this.id,this.ownerId,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new Zn(this),this.setPreviewService(A),this.initializationPromise=this.loadExistingWorkflowExperiences(((o=t.transactions)==null?void 0:o.map(s=>s.id))||[],n)}getInitializationPromise(){return this.initializationPromise}addEventListener(e,t){this.eventListeners.set(e,[...this.eventListeners.get(e)||[],t])}removeEventListener(e,t){const A=this.eventListeners.get(e)||[],n=A.indexOf(t);n>-1&&A.splice(n,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(e){return this.name=e,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(e){return this.metadata=new Map(e),this.updateBundle()}setNameAndMetadata(e,t){return this.name=e,this.metadata=new Map(t),this.updateBundle()}hasGlobalProperties(){var e;return!!((e=this.productCollection)!=null&&e.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var e;return(e=this.productCollection)==null?void 0:e.globalPropertyConfiguration}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(A=>A.getType()===g.AspectType.Option).map(A=>{var n;return((n=A.getCurrentVariant())==null?void 0:n.getPrice())||0}).reduce((A,n)=>A+n,0)}getTotalSubunits(){return this.workflowExperiences.map(e=>e.getTotalPriceSubunits()).reduce((e,t)=>e+t,0)}getProductCollection(){return this.productCollection?new _t(this.productCollection):void 0}async addWorkflowExperience(e){e.setBundle(this),await this.appendWorkflowExperience(e),await this.injectExperienceIntoPreviewService(e);const t=await this.getGlobalProperties();await Promise.all(t.map(A=>A.applyGlobalState([e])))}async addWorkflowExperiences(e){const t=e.map(i=>i.getWorkflowManager().getTransaction().id),A=t.map(i=>this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i));if(A.some(i=>!!i))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter(i=>!!i).map(i=>i==null?void 0:i.getWorkflowManager().getTransaction().id).join(", "));const n=P.getMap("transactionOwnerIds")||new Map,a=t.map(i=>n.get(i));await N.getShadowGraphqlClient().mutate({mutation:jn,variables:{id:this.id,transactionIds:t,transactionOwnerIds:a},context:{bundleOwnerId:this.ownerId}}).catch(i=>{console.error(i)}),this.workflowExperiences.push(...e),await Promise.all([this.updateTransactionOrder(),(async()=>{for(const o of e)await this.injectExperienceIntoPreviewService(o);const i=await this.getGlobalProperties();await Promise.all(i.map(o=>o.applyGlobalState(e)))})()]),this.workflowExperiences.forEach(i=>i.setBundle(this)),this.workflowExperiences.forEach(i=>i.checkForPriceBreakChanges())}async appendWorkflowExperience(e,t=!0){const A=e.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===A))throw new Error("Unable to add transaction to bundle - Already Exists!");const i=(P.getMap("transactionOwnerIds")||new Map).get(A);await N.getShadowGraphqlClient().mutate({mutation:zn,variables:{id:this.id,transactionId:A},context:{bundleOwnerId:this.ownerId,transactionOwnerId:i}}),t&&(this.workflowExperiences.push(e),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(e){const t=this.workflowExperiences.indexOf(e);await this.removeTransaction(t,this.workflowExperiences[t].getWorkflowManager().getTransaction())}async removeWorkflowExperiences(e){await this.removeTransactions(e.map(t=>t.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(e){const t=this.workflowExperiences.findIndex(A=>A.getWorkflowManager().getTransaction().id===e.id);await this.removeTransaction(t,e)}async removeWorkflowExperiencesByTransactions(e){await this.removeTransactions(e)}async removeTransaction(e,t,A=!0){if(e>-1){const n=this.workflowExperiences.find(a=>a.getWorkflowManager().getTransaction().id===t.id);n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(t.id),await N.getShadowGraphqlClient().mutate({mutation:Kn,variables:{id:this.id,transactionId:t.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,i])=>({key:a,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),A&&(this.workflowExperiences.splice(e,1),this.workflowExperiences.forEach(a=>a.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder())}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+t.id)}async removeTransactions(e){const t=e.map(n=>this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===n.id));if(t.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+e.filter((n,a)=>t[a]===-1).map(n=>n.id).join(", "));const A=e.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===n.id),1)[0]);A.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...A].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&A.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),e.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await N.getShadowGraphqlClient().mutate({mutation:Vn,variables:{id:this.id,transactionIds:e.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,a])=>({key:n,value:a})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),await this.updateTransactionOrder()}async insertWorkflowExperience(e,t){await this.appendWorkflowExperience(e,!1),this.workflowExperiences.splice(t,0,e),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const A=await this.getGlobalProperties();await Promise.all(A.map(n=>n.applyGlobalState([e])))})()])}async replaceWorkflowExperience(e,t){if(e<0||e>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const A=this.workflowExperiences[e];if(A.getWorkflowManager().getTransaction().id===t.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(e,A.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(t,!1)]),this.workflowExperiences[e]=t,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const n=await this.getGlobalProperties();await Promise.all(n.map(a=>a.applyGlobalState([t])))})()])}async swapWorkflowExperiences(e,t){if(e<0||e>=this.workflowExperiences.length||t<0||t>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(e===t)return;const A=this.workflowExperiences[e];this.workflowExperiences[e]=this.workflowExperiences[t],this.workflowExperiences[t]=A,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(e){this.workflowExperiences=this.workflowExperiences.sort(e),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(e,t){var a;const A=await N.getShadowGraphqlClient().mutate({mutation:Wn,variables:{id:this.id,details:e,type:t||re.Owner},context:{bundleOwnerId:this.ownerId}});if(!((a=A.data)!=null&&a.bundleAddStakeholder))throw new Error("Bundle not found!");const n=A.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async updateStakeholders(e){var n;const t=await N.getShadowGraphqlClient().mutate({mutation:Xn,variables:{id:this.id,input:e},context:{bundleOwnerId:this.ownerId}});if(!((n=t.data)!=null&&n.bundleUpdateStakeholders))throw new Error("Bundle not found!");const A=t.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(A)}async getAllStakeholders(){const e=await N.getShadowGraphqlClient().query({query:bn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!e.data.bundles||e.data.bundles.length===0)throw new Error("Bundle not found!");const t=e.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(t),t}storeStakeholderCustomers(e){e.forEach(t=>{t.customer&&this.client.storeCustomer(t.customer)})}async finish(e,t){const A=await un(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),e??(()=>{}),t?(n,a)=>{const i=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===a);return i?t(i):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+a),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:A}}getPreviewService(){return this.previewService}async setPreviewService(e){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(t=>t.getWorkflowManager().ejectFromPreviewService()),e))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t);e&&e.registerModelLoadEventListener&&e.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==e&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=e}updateWorkflowExperienceTransform(e,t,A){return this.bundleStateManager.updateWorkflowExperienceTransform(e,t,A),this.updateBundle()}activateWorkflowExperienceTransform(e,t){return this.bundleStateManager.activateWorkflowExperienceTransform(e,t),this.updateBundle()}onModelLoadEvent(e){e.eventType==="unload"||!e.modelContainer||(e.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(e.modelContainer,!0)),e.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(e.modelContainer,!1)))}onModelSelectedEvent(e,t){if(e&&e.metadata&&e.metadata instanceof Map&&e.metadata.has("workflowManager")){const n=e.metadata.get("workflowManager").getTransaction(),a=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===n.id);a&&this.fireEvent(t?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:a})}}async injectExperienceIntoPreviewService(e){if(this.previewService){const t=e.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(e)}catch(A){console.error(`Unable to apply state to workflow experience: ${A}`)}await t}}async loadExistingWorkflowExperiences(e,t){if(e.length===0)return;const A=await this.client.getWorkflowExperiences(e.map(n=>({type:"transaction",transactionId:n})),t);if(A.forEach(n=>n.setBundle(this)),A.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=A,this.previewService)for(const n of A)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){var t;if(!((t=(await N.getShadowGraphqlClient().mutate({mutation:On,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([A,n])=>({key:A,value:n})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}})).data)!=null&&t.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await N.getShadowGraphqlClient().mutate({mutation:qn,variables:{id:this.id,transactionIds:this.workflowExperiences.map(e=>e.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(e,t){const A=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(A,e),a=this.globalPropertyHandleService.applyConditionsFromState(A,t);(()=>{if(n.length!==a.length)return!0;for(let o=0;o<n.length;o++)if(n[o].getName()!==a[o].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:a})}fireEvent(e,t){(this.eventListeners.get(e)||[]).forEach(n=>n({bundle:this,event:e,data:t}))}}const na=M.gql`
2353
+ `;class Aa{constructor(e,t,A){this.bundleId=e,this.bundleOwnerId=t,this.initPromise=this.getOrCreateGlobalPropertyState().then(n=>{this.globalPropertyState=n}),this.onGlobalPropertyStateChange=A}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}getAspect(e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=this.globalPropertyState.aspects.find(A=>A.name===e);if(t)return t.value}async setAspect(e,t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const A=Ee(this.globalPropertyState),n=this.globalPropertyState.aspects.find(a=>a.name===e);n?n.value=t:this.globalPropertyState.aspects.push({name:e,value:t}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(A,this.globalPropertyState)}async updateGlobalPropertyState(){var t;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=await N.getShadowGraphqlClient().mutate({mutation:ea,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects},context:{bundleOwnerId:this.bundleOwnerId}});if((t=e.data)!=null&&t.globalPropertyStateUpdate)this.globalPropertyState=e.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async getOrCreateGlobalPropertyState(){var A;const e=await N.getShadowGraphqlClient().query({query:ta,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId},context:{bundleOwnerId:this.bundleOwnerId}});if(e.data.globalPropertyState&&e.data.globalPropertyState.id)return e.data.globalPropertyState;const t=await N.getShadowGraphqlClient().mutate({mutation:_n,variables:{bundleId:this.bundleId},context:{bundleOwnerId:this.bundleOwnerId}});if((A=t.data)!=null&&A.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class na{constructor(e){this.setState(e)}setState(e){e&&(this.state=JSON.parse(e))}applyStateToWorkflowExperience(e){var i;if(!this.state||!((i=e==null?void 0:e.getWorkflowManager())!=null&&i.getModelContainer()))return;const t=this.state.transactions.find(o=>o.transactionId===e.getWorkflowManager().getTransaction().id);if(!t)return;const A=this.getTransformToApply(t);if(!A)return;const n=this.flipTransform(A,e.getWorkflowManager().getPreviewService()),a=e.getWorkflowManager().getModelContainer();a.position=n.position,a.rotation=n.rotation,a.scale=n.scale}getTransformToApply(e){return e.activeTransform&&e.transforms?e.transforms[e.activeTransform]:e.transform}updateWorkflowExperienceTransform(e,t,A){const n=e.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const a=this.state.transactions.find(i=>i.transactionId===n);a?(a.transforms||(a.transforms={}),a.transforms[t]=A):this.state.transactions.push({transactionId:n,activeTransform:t,transforms:{[t]:A}})}activateWorkflowExperienceTransform(e,t){var s,r;if(!((s=e==null?void 0:e.getWorkflowManager())!=null&&s.getModelContainer())||!this.state)return;const A=e.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(l=>l.transactionId===A),a=(r=n==null?void 0:n.transforms)==null?void 0:r[t];if(!a)return;const i=this.flipTransform(a,e.getWorkflowManager().getPreviewService()),o=e.getWorkflowManager().getModelContainer();o.position=i.position,o.rotation=i.rotation,o.scale=i.scale,n.activeTransform=t}removeStateForTransaction(e){if(!this.state||!this.state.transactions)return;const t=this.state.transactions.findIndex(A=>A.transactionId===e);t!==-1&&this.state.transactions.splice(t,1)}getSerializedState(){if(this.state)return JSON.stringify(this.state)}flipTransform(e,t){return t&&t.flipTransform?t.flipTransform(e.position,{x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},e.scale):{position:e.position,rotation:{x:e.rotation.x*Math.PI/180,y:e.rotation.y*Math.PI/180,z:e.rotation.z*Math.PI/180},scale:e.scale}}}class _t{constructor(e){this.collection=e}getId(){return this.collection.id}getName(){return this.collection.name}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.map(e=>new ye(e))}async fetchProducts(){if(this.collection.productCollectionProducts)return this.collection.productCollectionProducts.map(t=>new ye(t));const e=await N.getShadowGraphqlClient().query({query:Tn,variables:{id:this.getId()},errorPolicy:"all",fetchPolicy:"no-cache"});return this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.map(t=>new ye(t))}getTransformCollection(){if(this.collection.transformCollection)return new eA(this.collection.transformCollection)}getResource(){return this.collection}}class ye{constructor(e){this.product=e.product,this.productResource=e}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(e,t){const n=(this.product.integrationProducts||[]).find(a=>{var r,l,d;const i=(r=a.integration)==null?void 0:r.type,o=((l=a.integration)==null?void 0:l.type)===e,s=t?((d=a.integration)==null?void 0:d.externalIntegrationId)===t:!0;return i&&o&&s});if(!n)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return n}getCurrentIntegration(){const t=(this.product.integrationProducts||[]).find(A=>{var n;return(n=A.integration)==null?void 0:n.isCurrent});if(!t)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return t}getDefaultWorkflow(){const e=this.product.workflows||[];if(e.length===0)throw new G("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");const t=this.productResource.workflowId;if(t){const n=e.find(a=>a.workflowName===t);if(n)return new Ae(n)}const A=e[0];return new Ae(A)}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new G("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return this.product.workflows.sort((t,A)=>(t.index??0)-(A.index??0)).map(t=>new Ae(t))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(e){var n,a,i,o;const t=this.product.basePrice||0;if(!e)return t;if(!e.integrationType&&!e.externalId&&!e.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let A;return e.integrationId?A=(n=this.product.integrationProducts)==null?void 0:n.find(s=>{var r;return((r=s.integration)==null?void 0:r.id)===e.integrationId}):e.externalId?A=(a=this.product.integrationProducts)==null?void 0:a.find(s=>{var r;return((r=s.integration)==null?void 0:r.externalIntegrationId)===e.externalId}):A=(i=this.product.integrationProducts)==null?void 0:i.find(s=>{var r;return((r=s.integration)==null?void 0:r.type)===e.integrationType}),(o=A==null?void 0:A.additionalIntegrationProduct)!=null&&o.product?t+(A.additionalIntegrationProduct.product.basePrice||0):t}}class Ae{constructor(e){this.workflow=e}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class eA{constructor(e){this.collection=e}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(e=>new tA(e))}}class tA{constructor(e){this.transform=e}getId(){return this.transform.id}getName(){return this.transform.name}get(){return{position:this.transform.position,rotation:this.transform.rotation,scale:this.transform.scale}}}class AA{constructor(e,t,A,n,a){var i,o;this.eventListeners=new Map,this.workflowExperiences=[],this.client=e,this.id=t.id,this.name=t.name||"",this.ownerId=a,this.metadata=new Map(((i=t.metadata)==null?void 0:i.map(s=>[s.key,s.value]))||[]),this.productCollection=t.productCollection,this.bundleStateManager=new na(t.bundleStateData),this.globalPropertyStateManager=new Aa(this.id,this.ownerId,this.checkConditionalHandlesChanged.bind(this)),this.globalPropertyHandleService=new $n(this),this.setPreviewService(A),this.initializationPromise=this.loadExistingWorkflowExperiences(((o=t.transactions)==null?void 0:o.map(s=>s.id))||[],n)}getInitializationPromise(){return this.initializationPromise}addEventListener(e,t){this.eventListeners.set(e,[...this.eventListeners.get(e)||[],t])}removeEventListener(e,t){const A=this.eventListeners.get(e)||[],n=A.indexOf(t);n>-1&&A.splice(n,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(e){return this.name=e,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(e){return this.metadata=new Map(e),this.updateBundle()}setNameAndMetadata(e,t){return this.name=e,this.metadata=new Map(t),this.updateBundle()}hasGlobalProperties(){var e;return!!((e=this.productCollection)!=null&&e.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var e;return(e=this.productCollection)==null?void 0:e.globalPropertyConfiguration}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(A=>A.getType()===g.AspectType.Option).map(A=>{var n;return((n=A.getCurrentVariant())==null?void 0:n.getPrice())||0}).reduce((A,n)=>A+n,0)}getTotalSubunits(){return this.workflowExperiences.map(e=>e.getTotalPriceSubunits()).reduce((e,t)=>e+t,0)}getProductCollection(){return this.productCollection?new _t(this.productCollection):void 0}async addWorkflowExperience(e){e.setBundle(this),await this.appendWorkflowExperience(e),await this.injectExperienceIntoPreviewService(e);const t=await this.getGlobalProperties();await Promise.all(t.map(A=>A.applyGlobalState([e])))}async addWorkflowExperiences(e){const t=e.map(i=>i.getWorkflowManager().getTransaction().id),A=t.map(i=>this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i));if(A.some(i=>!!i))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter(i=>!!i).map(i=>i==null?void 0:i.getWorkflowManager().getTransaction().id).join(", "));const n=P.getMap("transactionOwnerIds")||new Map,a=t.map(i=>n.get(i));await N.getShadowGraphqlClient().mutate({mutation:jn,variables:{id:this.id,transactionIds:t,transactionOwnerIds:a},context:{bundleOwnerId:this.ownerId}}).catch(i=>{console.error(i)}),this.workflowExperiences.push(...e),await Promise.all([this.updateTransactionOrder(),(async()=>{for(const o of e)await this.injectExperienceIntoPreviewService(o);const i=await this.getGlobalProperties();await Promise.all(i.map(o=>o.applyGlobalState(e)))})()]),this.workflowExperiences.forEach(i=>i.setBundle(this)),this.workflowExperiences.forEach(i=>i.checkForPriceBreakChanges())}async appendWorkflowExperience(e,t=!0){const A=e.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===A))throw new Error("Unable to add transaction to bundle - Already Exists!");const i=(P.getMap("transactionOwnerIds")||new Map).get(A);await N.getShadowGraphqlClient().mutate({mutation:zn,variables:{id:this.id,transactionId:A},context:{bundleOwnerId:this.ownerId,transactionOwnerId:i}}),t&&(this.workflowExperiences.push(e),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(e){const t=this.workflowExperiences.indexOf(e);await this.removeTransaction(t,this.workflowExperiences[t].getWorkflowManager().getTransaction())}async removeWorkflowExperiences(e){await this.removeTransactions(e.map(t=>t.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(e){const t=this.workflowExperiences.findIndex(A=>A.getWorkflowManager().getTransaction().id===e.id);await this.removeTransaction(t,e)}async removeWorkflowExperiencesByTransactions(e){await this.removeTransactions(e)}async removeTransaction(e,t,A=!0){if(e>-1){const n=this.workflowExperiences.find(a=>a.getWorkflowManager().getTransaction().id===t.id);n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(t.id),await N.getShadowGraphqlClient().mutate({mutation:Kn,variables:{id:this.id,transactionId:t.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,i])=>({key:a,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),A&&(this.workflowExperiences.splice(e,1),this.workflowExperiences.forEach(a=>a.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder())}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+t.id)}async removeTransactions(e){const t=e.map(n=>this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===n.id));if(t.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+e.filter((n,a)=>t[a]===-1).map(n=>n.id).join(", "));const A=e.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===n.id),1)[0]);A.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...A].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&A.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),e.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await N.getShadowGraphqlClient().mutate({mutation:Vn,variables:{id:this.id,transactionIds:e.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,a])=>({key:n,value:a})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),await this.updateTransactionOrder()}async insertWorkflowExperience(e,t){await this.appendWorkflowExperience(e,!1),this.workflowExperiences.splice(t,0,e),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const A=await this.getGlobalProperties();await Promise.all(A.map(n=>n.applyGlobalState([e])))})()])}async replaceWorkflowExperience(e,t){if(e<0||e>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const A=this.workflowExperiences[e];if(A.getWorkflowManager().getTransaction().id===t.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(e,A.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(t,!1)]),this.workflowExperiences[e]=t,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const n=await this.getGlobalProperties();await Promise.all(n.map(a=>a.applyGlobalState([t])))})()])}async swapWorkflowExperiences(e,t){if(e<0||e>=this.workflowExperiences.length||t<0||t>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(e===t)return;const A=this.workflowExperiences[e];this.workflowExperiences[e]=this.workflowExperiences[t],this.workflowExperiences[t]=A,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(e){this.workflowExperiences=this.workflowExperiences.sort(e),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(e,t){var a;const A=await N.getShadowGraphqlClient().mutate({mutation:Wn,variables:{id:this.id,details:e,type:t||re.Owner},context:{bundleOwnerId:this.ownerId}});if(!((a=A.data)!=null&&a.bundleAddStakeholder))throw new Error("Bundle not found!");const n=A.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(e){var A;if(!((A=(await N.getShadowGraphqlClient().mutate({mutation:Xn,variables:{id:this.id,emailAddress:e},context:{bundleOwnerId:this.ownerId}})).data)!=null&&A.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(e){var n;const t=await N.getShadowGraphqlClient().mutate({mutation:qn,variables:{id:this.id,input:e},context:{bundleOwnerId:this.ownerId}});if(!((n=t.data)!=null&&n.bundleUpdateStakeholders))throw new Error("Bundle not found!");const A=t.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(A)}async getAllStakeholders(){const e=await N.getShadowGraphqlClient().query({query:bn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!e.data.bundles||e.data.bundles.length===0)throw new Error("Bundle not found!");const t=e.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(t),t}storeStakeholderCustomers(e){e.forEach(t=>{t.customer&&this.client.storeCustomer(t.customer)})}async finish(e,t){const A=await un(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),e??(()=>{}),t?(n,a)=>{const i=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===a);return i?t(i):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+a),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:A}}getPreviewService(){return this.previewService}async setPreviewService(e){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(t=>t.getWorkflowManager().ejectFromPreviewService()),e))for(const t of this.workflowExperiences)await this.injectExperienceIntoPreviewService(t);e&&e.registerModelLoadEventListener&&e.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==e&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=e}updateWorkflowExperienceTransform(e,t,A){return this.bundleStateManager.updateWorkflowExperienceTransform(e,t,A),this.updateBundle()}activateWorkflowExperienceTransform(e,t){return this.bundleStateManager.activateWorkflowExperienceTransform(e,t),this.updateBundle()}onModelLoadEvent(e){e.eventType==="unload"||!e.modelContainer||(e.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(e.modelContainer,!0)),e.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(e.modelContainer,!1)))}onModelSelectedEvent(e,t){if(e&&e.metadata&&e.metadata instanceof Map&&e.metadata.has("workflowManager")){const n=e.metadata.get("workflowManager").getTransaction(),a=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===n.id);a&&this.fireEvent(t?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:a})}}async injectExperienceIntoPreviewService(e){if(this.previewService){const t=e.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(e)}catch(A){console.error(`Unable to apply state to workflow experience: ${A}`)}await t}}async loadExistingWorkflowExperiences(e,t){if(e.length===0)return;const A=await this.client.getWorkflowExperiences(e.map(n=>({type:"transaction",transactionId:n})),t);if(A.forEach(n=>n.setBundle(this)),A.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=A,this.previewService)for(const n of A)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){var t;if(!((t=(await N.getShadowGraphqlClient().mutate({mutation:On,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([A,n])=>({key:A,value:n})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}})).data)!=null&&t.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await N.getShadowGraphqlClient().mutate({mutation:Zn,variables:{id:this.id,transactionIds:this.workflowExperiences.map(e=>e.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(e,t){const A=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(A,e),a=this.globalPropertyHandleService.applyConditionsFromState(A,t);(()=>{if(n.length!==a.length)return!0;for(let o=0;o<n.length;o++)if(n[o].getName()!==a[o].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:a})}fireEvent(e,t){(this.eventListeners.get(e)||[]).forEach(n=>n({bundle:this,event:e,data:t}))}}const aa=M.gql`
2348
2354
  mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
2349
2355
  processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
2350
2356
  id
2351
2357
  }
2352
2358
  }
2353
- `;class nA{async execute(e,t,A){var d,B,w;const a=(B=(d=(await N.getShadowGraphqlClient().mutate({mutation:na,variables:{processFlowId:e,inputs:[...t.map(E=>E.getValueForTransmission())]}})).data)==null?void 0:d.processExecutionCreate)==null?void 0:B.id;if(!a)throw new Error("Failed to create process execution.");function i(E){return new Promise(C=>{setTimeout(C,E)})}let o=!1,s=0,r,l;for(;!o;){r=await N.getShadowGraphqlClient().query({query:M.gql`
2359
+ `;class nA{async execute(e,t,A){var d,B,w;const a=(B=(d=(await N.getShadowGraphqlClient().mutate({mutation:aa,variables:{processFlowId:e,inputs:[...t.map(E=>E.getValueForTransmission())]}})).data)==null?void 0:d.processExecutionCreate)==null?void 0:B.id;if(!a)throw new Error("Failed to create process execution.");function i(E){return new Promise(C=>{setTimeout(C,E)})}let o=!1,s=0,r,l;for(;!o;){r=await N.getShadowGraphqlClient().query({query:M.gql`
2354
2360
  query getProcessFlowExecution($ids: [String]!) {
2355
2361
  processExecutions(ids: $ids) {
2356
2362
  id
@@ -2363,7 +2369,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2363
2369
  }
2364
2370
  }
2365
2371
  }
2366
- `,variables:{ids:[a]}});const E=(w=r.data)==null?void 0:w.processExecutions[0];if(!r||!E)throw new Error("Failed to retrieve server response for execution.");if(E.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(E.completedAt){o=!0,l=new aA(E);break}s+=1;const C=A!=null&&A.repeats?A==null?void 0:A.repeats:5;if(s>=C)throw new Error("Maximum wait time exceeded for execution result.");await i(A!=null&&A.sleepTime?Math.max(A.sleepTime,500):2e3)}if(!l)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(l)}}class aA{constructor(e){this.execution=e}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(e=>new de(e))}getNodesByType(e){return this.execution.nodes.filter(t=>t.type===e).map(t=>new de(t))}getInputs(){return this.execution.nodes.filter(e=>e.type==="StartTerminal").map(e=>new de(e))}getOutputs(){return this.execution.nodes.filter(e=>e.type==="EndTerminal").map(e=>new de(e))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class de{constructor(e){this.node=e}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(e){return this.getArtifacts().get(e)}}class Ve{constructor(e){this.value=e}getRaw(){return this.value}getValueForTransmission(){const e=this.value;return e.startsWith("[")?JSON.stringify(JSON.parse(e)):e}}var iA=(c=>(c.Transaction="Transaction",c.Bundle="Bundle",c.Product="Product",c.Variant="Variant",c.Option="Option",c.LineItem="LineItem",c.Asset="Asset",c))(iA||{});class aa extends Ve{constructor(e){super(`"${e}"`)}}class We extends Ve{constructor(e,t){if(t!=="Asset"&&!We.validUUID(e))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${e}", "type": "${t}"}`)}static validUUID(e){return e.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 ia extends Ve{constructor(e){super(`[${e.map(t=>t.getRaw()).join(",")}]`)}}class Xe{constructor(e){this.integrationProduct=e}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){var A;if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.basePrice||0,t=(A=this.integrationProduct)==null?void 0:A.additionalIntegrationProduct;if(!t)return e;if(t&&!t.product)throw new Error("An additional integration product was found, but it does not have a product");return e+(t.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.workflows||[];if(e.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return new Ae(e[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.workflows||[];if(e.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return e.sort((t,A)=>(t.index??0)-(A.index??0)).map(t=>new Ae(t))}}const oa=M.gql`
2372
+ `,variables:{ids:[a]}});const E=(w=r.data)==null?void 0:w.processExecutions[0];if(!r||!E)throw new Error("Failed to retrieve server response for execution.");if(E.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(E.completedAt){o=!0,l=new aA(E);break}s+=1;const C=A!=null&&A.repeats?A==null?void 0:A.repeats:5;if(s>=C)throw new Error("Maximum wait time exceeded for execution result.");await i(A!=null&&A.sleepTime?Math.max(A.sleepTime,500):2e3)}if(!l)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(l)}}class aA{constructor(e){this.execution=e}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(e=>new de(e))}getNodesByType(e){return this.execution.nodes.filter(t=>t.type===e).map(t=>new de(t))}getInputs(){return this.execution.nodes.filter(e=>e.type==="StartTerminal").map(e=>new de(e))}getOutputs(){return this.execution.nodes.filter(e=>e.type==="EndTerminal").map(e=>new de(e))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class de{constructor(e){this.node=e}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(e){return this.getArtifacts().get(e)}}class Ve{constructor(e){this.value=e}getRaw(){return this.value}getValueForTransmission(){const e=this.value;return e.startsWith("[")?JSON.stringify(JSON.parse(e)):e}}var iA=(c=>(c.Transaction="Transaction",c.Bundle="Bundle",c.Product="Product",c.Variant="Variant",c.Option="Option",c.LineItem="LineItem",c.Asset="Asset",c))(iA||{});class ia extends Ve{constructor(e){super(`"${e}"`)}}class We extends Ve{constructor(e,t){if(t!=="Asset"&&!We.validUUID(e))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${e}", "type": "${t}"}`)}static validUUID(e){return e.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 oa extends Ve{constructor(e){super(`[${e.map(t=>t.getRaw()).join(",")}]`)}}class Xe{constructor(e){this.integrationProduct=e}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){var A;if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.basePrice||0,t=(A=this.integrationProduct)==null?void 0:A.additionalIntegrationProduct;if(!t)return e;if(t&&!t.product)throw new Error("An additional integration product was found, but it does not have a product");return e+(t.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.workflows||[];if(e.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return new Ae(e[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const e=this.integrationProduct.product.workflows||[];if(e.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return e.sort((t,A)=>(t.index??0)-(A.index??0)).map(t=>new Ae(t))}}const sa=M.gql`
2367
2373
  fragment RegionFields on Region {
2368
2374
  width
2369
2375
  top
@@ -2381,7 +2387,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2381
2387
  height
2382
2388
  }
2383
2389
  }
2384
- `,sa=M.gql`
2390
+ `,ra=M.gql`
2385
2391
  fragment LookAtAnimationFields on LookAtAnimation {
2386
2392
  latDeg
2387
2393
  lonDeg
@@ -2392,7 +2398,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2392
2398
  z
2393
2399
  }
2394
2400
  }
2395
- `,ra=M.gql`
2401
+ `,ca=M.gql`
2396
2402
  fragment RenderingPipelineConfigurationFields on RenderingPipelineConfiguration {
2397
2403
  antiAliasing {
2398
2404
  samples
@@ -2476,21 +2482,21 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2476
2482
  weight
2477
2483
  }
2478
2484
  }
2479
- `,ca=M.gql`
2485
+ `,ga=M.gql`
2480
2486
  fragment ModelAnimationFields on ModelAnimation {
2481
2487
  from
2482
2488
  to
2483
2489
  loop
2484
2490
  name
2485
2491
  }
2486
- `,ga=c=>M.gql`
2492
+ `,la=c=>M.gql`
2487
2493
  ${Qe(c)}
2488
2494
  ${Ne}
2489
2495
  ${gt}
2490
- ${oa}
2491
2496
  ${sa}
2492
2497
  ${ra}
2493
2498
  ${ca}
2499
+ ${ga}
2494
2500
  query GetWorkflows($ids: [String!]!) {
2495
2501
  workflows(ids: $ids) {
2496
2502
  allowProofDownload
@@ -2868,7 +2874,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2868
2874
  }
2869
2875
  }
2870
2876
  }
2871
- `,la=M.gql`
2877
+ `,Ba=M.gql`
2872
2878
  query GetTransactionForPartner($id: String!) {
2873
2879
  transactions(ids: [$id]) {
2874
2880
  id
@@ -2885,7 +2891,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2885
2891
  }
2886
2892
  }
2887
2893
  }
2888
- `,Ba=M.gql`
2894
+ `,da=M.gql`
2889
2895
  query GetIntegrationWithPartnerAndLogo {
2890
2896
  currentIntegration {
2891
2897
  id
@@ -2903,7 +2909,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2903
2909
  }
2904
2910
  }
2905
2911
  }
2906
- `,da=M.gql`
2912
+ `,wa=M.gql`
2907
2913
  ${Qe(!1)}
2908
2914
  query GetWorkflowForTheme($id: String!) {
2909
2915
  workflow(id: $id) {
@@ -2925,7 +2931,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2925
2931
  }
2926
2932
  }
2927
2933
  }
2928
- `,wa=M.gql`
2934
+ `,Ea=M.gql`
2929
2935
  query GetCustomer($emailAddress: String!) {
2930
2936
  customer(emailAddress: $emailAddress) {
2931
2937
  id
@@ -2935,7 +2941,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2935
2941
  }
2936
2942
  }
2937
2943
  }
2938
- `,Ea=M.gql`
2944
+ `,ha=M.gql`
2939
2945
  mutation CustomerCreate($details: CustomerDetailsInput!) {
2940
2946
  customerCreate(details: $details) {
2941
2947
  id
@@ -2945,7 +2951,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2945
2951
  }
2946
2952
  }
2947
2953
  }
2948
- `,ha=M.gql`
2954
+ `,Ca=M.gql`
2949
2955
  mutation CustomerAuthenticate($loginToken: String!) {
2950
2956
  customerAuthenticate(loginToken: $loginToken) {
2951
2957
  id
@@ -2972,11 +2978,11 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2972
2978
  }
2973
2979
  }
2974
2980
  }
2975
- `,Ca=M.gql`
2981
+ `,Qa=M.gql`
2976
2982
  mutation CustomerGenerateVerificationCode($emailAddress: String!) {
2977
2983
  customerGenerateVerificationCode(emailAddress: $emailAddress)
2978
2984
  }
2979
- `,Qa=M.gql`
2985
+ `,ua=M.gql`
2980
2986
  mutation CustomerVerifyCode($emailAddress: String!, $verificationCode: String!) {
2981
2987
  customerVerifyCode(emailAddress: $emailAddress, verificationCode: $verificationCode) {
2982
2988
  id
@@ -3004,4 +3010,4 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
3004
3010
  }
3005
3011
  }
3006
3012
  }
3007
- `,ne=async c=>{var e;for(const t in c.layouts){const A=c.layouts[t].elements.filter(a=>a.type===g.LayoutElementType.Illustration);for(let a=0;a<A.length;++a){const i=A[a];i.src&&i.svg&&(i.cachedObjectURL=await g.svgObjectURL(i.svg))}const n=c.layouts[t].elements.filter(a=>a.type===g.LayoutElementType.Textbox);for(let a=0;a<n.length;++a){const i=n[a];(e=i.fontData)!=null&&e.assetUrl&&await g.loadFont(i.fontData.assetUrl)}}},ua=async(c,e)=>{var n;const t=await N.getShadowGraphqlClient().query({query:ga(((n=e==null?void 0:e.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:c}}),A=t.data.workflows;if(A===void 0||A.length!==c.length)throw new Error(`Unable to read workflows: ${t.errors??"Length mismatch in response"}`);return A.forEach(a=>{a.steps.forEach(i=>{var o,s,r;delete i.data.__typename,(o=i.option)!=null&&o.id&&((s=i.option.defaultVariant)!=null&&s.asset&&k.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&k.cacheAsset(i.option.colorProfile),(r=i.option.variants)==null||r.forEach(l=>{l.asset&&k.cacheAsset(l.asset),l.displayImage&&k.cacheAsset(l.displayImage),l.thumbnail&&k.cacheAsset(l.thumbnail),l.material&&k.cacheMaterial(l.material)}),Z.set({id:i.option.id},Promise.resolve(i.option)))})}),A},ma=async(c,e)=>{const A=(await e).find(n=>n.id===c);if(!A)throw new Error(`Workflow not found: ${c}`);return A},qe=async(c,e)=>{const t=c.map(o=>Z.get({id:o,options:e})),A=c.filter((o,s)=>t[s]===void 0);if(A.length===0)return Promise.all(t);const n=ua(A,e),a=A.map(o=>Z.set({id:o,options:e},ma(o,n))),i=t.filter(o=>o!==void 0);return await Promise.all(i.concat(a))},we=async(c,e)=>(await qe([c],e))[0],Ia=c=>c.sort((e,t)=>e.index-t.index).map(e=>({id:g.generate(),panelId:e.name,name:e.name,index:e.index,createdAt:new Date,updatedAt:new Date,transparentBackground:e.transparentBackground,height:e.height,width:e.width,previewRegion:e.previewRegion,useEditableArea:e.useEditableArea,editableArea:e.editableArea})),Ze=(c,e)=>{const t=c.workflowState,A=t?JSON.parse(t):void 0;return A?Object.values(A.layouts).map(n=>n.layout):Ia(e.panels)};class oA{constructor(e){this.updateTransactionState=async t=>{try{return N.getShadowGraphqlClient().mutate({...t,mutation:HA})}catch(A){throw console.error(A),new G("Critical - Unable to synchronize workflow state with server.")}},this.initialized=!1,this.options=e,this.options.applicationKey&&dA(this.options.applicationKey)}getAssetManager(){return k}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!wA())throw new Error("Application key required to use Flow Service.");return new nA}async getIntegration(){return(await N.getShadowGraphqlClient().query({query:Ba,errorPolicy:"all"})).data.currentIntegration}async authenticateBundleFromLocalStorage(e){var n,a;const t=P.getMap("bundleOwnerIds");if(t!=null&&t.has(e))return Promise.resolve({success:!0,stakeholderType:re.Owner});const A=P.getMap("bundlePartnerIds")||new Map;if(A.has(e)){const i=A.get(e),s=(P.getMap("partnerCustomerIds")||new Map).get(i);if(s&&await this.authenticateCustomerId(s)){const l=(a=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:a.find(d=>{var B;return((B=d.bundle)==null?void 0:B.id)===e});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(e){var l,d,B,w,E,C;const t=N.getShadowGraphqlClient(),A=await t.query({query:la,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e}});if(!A.data.transactions||A.data.transactions.length===0)throw new Error(`Transaction not found: ${e}`);const n=A.data.transactions[0];if(!((d=(l=n.product)==null?void 0:l.partner)==null?void 0:d.id))throw new Error(`Unable to read transaction: ${e}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const i=P.getMap("transactionOwnerIds");if(i!=null&&i.has(e))return Promise.resolve({success:!0,stakeholderType:re.Owner});const o=P.getMap("transactionCustomerIds");if(o!=null&&o.has(e)){const h=o.get(e);if(h&&await this.authenticateCustomerId(h)){const u=((w=(B=this.customer)==null?void 0:B.bundleStakeholders)==null?void 0:w.find(F=>{var I,f;return(f=(I=F.bundle)==null?void 0:I.transactions)==null?void 0:f.some(D=>D.id===e)}))||((C=(E=this.customer)==null?void 0:E.stakeholders)==null?void 0:C.find(F=>{var I;return((I=F.transaction)==null?void 0:I.id)===e}));if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}}const r=(await t.query({query:da,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(e){const t=P.getMap("transactionCustomerIds");t!=null&&t.has(e)&&(t.delete(e),P.setMap("transactionCustomerIds",t))}getStakeholderTypeForTransaction(e){var A,n;const t=(n=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:n.find(a=>{var i;return((i=a.transaction)==null?void 0:i.id)===e});if(t)return t.type}async getOrCreateCustomer(e){var i;this.customer=void 0;const t=N.getShadowGraphqlClient(),n=(await t.query({query:wa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!n.id){const s=(i=(await t.mutate({mutation:Ea,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:e}}})).data)==null?void 0:i.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(n);const a=await this.authenticateCustomerId(n.id);return{customer:this.customer||n,isAuthenticated:a}}async authenticateCustomerId(e){var o;const t=N.getShadowGraphqlClient(),A=P.getMap("customerTokens");if(!(A!=null&&A.has(e)))return!1;const n=A.get(e);if(!n)return!1;const i=(o=(await t.mutate({mutation:ha,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data)==null?void 0:o.customerAuthenticate;return i?(this.storeCustomer(i),rt(n),this.customer=i,!0):!1}async generateVerificationCode(e){await N.getShadowGraphqlClient().mutate({mutation:Ca,variables:{emailAddress:e}})}async verifyCode(e,t){var a,i;const n=(a=(await N.getShadowGraphqlClient().mutate({mutation:Qa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e,verificationCode:t}})).data)==null?void 0:a.customerVerifyCode;if(n!=null&&n.loginToken){if(!((i=n.partner)!=null&&i.id))throw new Error(`Unable to find customer: ${e}`);const o=P.getMap("customerTokens")||new Map;return o.set(n.id,n.loginToken),P.setMap("customerTokens",o),this.storeCustomer(n),rt(n.loginToken),this.customer={...n,loginToken:void 0},!0}return!1}async getNewBundle(e,t,A){var s,r,l;const a=(l=(await N.getShadowGraphqlClient().mutate({mutation:Ln(((r=(s=A==null?void 0:A.graphql)==null?void 0:s.productCollection)==null?void 0:r.eagerFetchProducts)||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((d,B)=>({key:d[0],value:d[1]})):void 0},fetchPolicy:"no-cache"})).data)==null?void 0:l.bundleCreate;if(!(a!=null&&a.id))throw new Error("Unable to create bundle");const i=P.getMap("bundlePartnerIds")||new Map;i.set(a.id,a.partner.id),P.setMap("bundlePartnerIds",i);const o=P.getMap("bundleOwnerIds")||new Map;return o.set(a.id,a.bundleOwnerId),P.setMap("bundleOwnerIds",o),new AA(this,a,void 0,void 0,a.bundleOwnerId)}async getExistingBundle(e,t,A,n){var d,B,w,E,C,h;const a=P.getMap("bundleOwnerIds"),i=a==null?void 0:a.get(e),o=await N.getShadowGraphqlClient().query({query:kn(((B=(d=n==null?void 0:n.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts)||!1),variables:{id:e},fetchPolicy:"no-cache",context:{bundleOwnerId:i}});if(!((w=o.data)!=null&&w.bundles)||((E=o.data)==null?void 0:E.bundles.length)===0||!((C=o.data)!=null&&C.bundles[0]))throw new Error(`Unable to find bundle: ${e}`);const s=(h=o.data)==null?void 0:h.bundles[0],r=P.getMap("bundlePartnerIds")||new Map;r.set(s.id,s.partner.id),P.setMap("bundlePartnerIds",r);const l=new AA(this,s,t,A,i);return await l.getInitializationPromise(),l}async getBundleStakeholders(){var a;if(!this.customer)throw new Error("Customer not authenticated.");const e=await N.getShadowGraphqlClient().query({query:Jn,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((a=e.data)!=null&&a.customers)||e.data.customers.length===0)throw new Error("Unable to find customer.");const A=e.data.customers[0].bundleStakeholders||[],n=P.getMap("bundlePartnerIds")||new Map;return A.forEach(i=>{var o,s;(o=i.bundle)!=null&&o.id&&((s=i.bundle.partner)!=null&&s.id)&&n.set(i.bundle.id,i.bundle.partner.id)}),P.setMap("bundlePartnerIds",n),A}async getWorkflowExperience(e,t,A,n){var d,B,w,E,C;if(!n)return await this.getWorkflowExperienceDeprecated(e,t,A);const a=async()=>{var m,u;const h=N.getShadowGraphqlClient();if(n.type==="transaction"){const{transactionId:F,readOnly:I}=n,f=await h.query({query:ue,variables:{ids:[F]},errorPolicy:"all",fetchPolicy:"no-cache"});if(!((m=f.data)!=null&&m.transactions)||f.data.transactions.length===0)throw new G("Existing transaction not found.");const D=(u=f.data)==null?void 0:u.transactions[0];if(!D.workflowId)throw new G("Existing transaction has no workflow ID.");const p=await we(D.workflowId);if(!D.product)throw new G("Failed to load transaction, product not available.");return{transaction:D,workflow:p,readOnly:I}}if(n.type==="integration"||n.type==="external"){const F=async()=>{const p=n.type==="integration"?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},S=await h.mutate({mutation:Et,variables:{...p,workflowId:n.workflowId,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!S.data||!S.data.transactionCreate)throw new G("Failed to create transaction!");const y=S.data.transactionCreate;if(!y.product)throw new G("Failed to create transaction, product not available.");return y},I=we(n.workflowId,n==null?void 0:n.graphql),[f,D]=await Promise.all([F(),I]);return{transaction:f,workflow:D}}throw new G("No workflow ID provided.")},{transaction:i,workflow:o,readOnly:s}=await a();this.currencyCode=(d=i.product.partner)==null?void 0:d.currencyCode;const r={product:i.product,transaction:i,layouts:[],singleVariantsRenderable:(B=n==null?void 0:n.workflowConfiguration)==null?void 0:B.singleVariantsRenderable,stateMutationFunc:s?async()=>{throw new v("State mutation is forbidden in read only mode!")}:async h=>{const u=(P.getMap("transactionOwnerIds")||new Map).get(i.id)||void 0;return this.updateTransactionState({...h,context:{transactionOwnerId:u}})},readOnly:s,workflow:o};if(n.type==="transaction"&&i.workflowState){const h=JSON.parse(i.workflowState);r.layouts=Object.values(h.layouts).map(m=>m.layout),await g.rehydrateSerializedLayout(h),await ne(h),r.reloadedState=h}else if(!s&&n.workflowState){const h=JSON.parse(n.workflowState);r.layouts=Object.values(h.layouts).map(m=>m.layout),await g.rehydrateSerializedLayout(h),await ne(h),r.reloadedState=h}else r.layouts=Ze(r.transaction,r.workflow);if(r.renderableContextService=new Me(r.layouts),n.previewService?(r.previewService=n.previewService,(w=r.product)!=null&&w.modelUrl&&(r.modelContainer=r.previewService.loadModel({model:r.product.modelUrl,contextService:r.renderableContextService}))):(r.previewService=A&&A(o),(E=r.product)!=null&&E.modelUrl&&(r.modelContainer=(C=r.previewService)==null?void 0:C.loadModel({model:r.product.modelUrl,contextService:r.renderableContextService}))),n.type!=="transaction"){const h=P.getMap("transactionOwnerIds")||new Map;h.set(i.id,i.transactionOwnerId),P.setMap("transactionOwnerIds",h)}else r.isReloadedTransaction=!0;this.initialized=!0,this.experienceOptions=r;const l=new Be(this,r);return await l.getWorkflowManager().getInitializationPromise(),n.type!=="transaction"&&this.customer&&await l.attachCustomerDetails({email:this.customer.emailAddress}),l}async getWorkflowExperiences(e,t){if(e.length===0)throw new G("No options provided!");const A=N.getShadowGraphqlClient(),n=async f=>{var y,x;if(f.length===0)return[];const D=f.map(Y=>Y.option.transactionId),p=await A.query({query:ue,variables:{ids:D},errorPolicy:"all",fetchPolicy:"no-cache"}),S=p.data.transactions;if(S.length!==f.length){const Y=((x=(y=p.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new G(`Not all transactions were found: ${Y}`)}return S.map((Y,H)=>{var R;return{transaction:Y,workflowId:Y.workflowId,readOnly:((R=f.find(T=>T.option.transactionId===Y.id))==null?void 0:R.option.readOnly)??!1,index:f[H].index}})},a=async f=>{var S,y,x;if(f.length===0)return[];const D=await A.mutate({mutation:xA,variables:{inputs:f.map(Y=>({integrationProductId:Y.option.type==="integration"?Y.option.integrationProductId:void 0,externalIntegrationId:Y.option.type==="external"?Y.option.externalIntegrationId:void 0,externalProductId:Y.option.type==="external"?Y.option.externalProductId:void 0,workflowId:Y.option.workflowId,claim:!0}))},errorPolicy:"all",fetchPolicy:"no-cache"}),p=(S=D.data)==null?void 0:S.transactionCreateMany;if(!p||p.length===0){const Y=((x=(y=D.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new G(`Failed to create transactions: ${Y}`)}return p.map((Y,H)=>({transaction:Y,workflowId:Y.workflowId,readOnly:!1,index:f[H].index}))},i=e.map((f,D)=>({option:f,index:D})),o=i.filter(f=>f.option.type==="transaction"),s=i.filter(f=>f.option.type==="integration"||f.option.type==="external"),r=at(o,10),l=at(s,10),d=(await Promise.all([...r.map(n),...l.map(a)])).flat(),B=[...new Set(d.map(f=>f.workflowId))],w=await qe(B,t),E=new Map(w.map(f=>[f.id,f])),C=P.getMap("transactionOwnerIds")||new Map,h=d.map(async f=>{var T;const{transaction:D,workflowId:p,readOnly:S,index:y}=f,x=E.get(p),Y=e[y];!C.get(D.id)&&D.transactionOwnerId&&C.set(D.id,D.transactionOwnerId);const H=C.get(D.id)||void 0,R={product:D.product,transaction:D,layouts:[],singleVariantsRenderable:(T=Y==null?void 0:Y.workflowConfiguration)==null?void 0:T.singleVariantsRenderable,stateMutationFunc:S?async()=>{throw new v("State mutation is forbidden in read only mode!")}:async b=>this.updateTransactionState({...b,context:{transactionOwnerId:H}}),readOnly:S,workflow:x,isReloadedTransaction:Y.type==="transaction"};if(Y.type==="transaction"&&D.workflowState){const b=JSON.parse(D.workflowState);R.layouts=Object.values(b.layouts).map(z=>z.layout),await g.rehydrateSerializedLayout(b),await ne(b),R.reloadedState=b}else if(!S&&Y.workflowState){const b=JSON.parse(Y.workflowState);R.layouts=Object.values(b.layouts).map(z=>z.layout),await g.rehydrateSerializedLayout(b),await ne(b),R.reloadedState=b}else R.layouts=Ze(R.transaction,R.workflow);return R.renderableContextService=new Me(R.layouts),R.delayWorkflowStateSync=!0,this.initialized=!0,this.experienceOptions=R,{experienceOptions:R,index:y,options:Y}});P.setMap("transactionOwnerIds",C);const F=(await Promise.all(h)).sort((f,D)=>f.index-D.index).map(async f=>{const{experienceOptions:D,options:p}=f,S=new Be(this,D);return await S.getWorkflowManager().getInitializationPromise(),p.type!=="transaction"&&this.customer&&await S.attachCustomerDetails({email:this.customer.emailAddress}),S}),I=await Promise.all(F);return I.forEach(f=>f.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),I}async initFromIntegrationProduct(e){var i;if(e==="")throw new G("No integration product ID provided.");const A=await N.getShadowGraphqlClient().mutate({mutation:Et,variables:{integrationProductId:e,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 G("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new G("Failed to create transaction, product not available.");this.currencyCode=(i=n.product.partner)==null?void 0:i.currencyCode;const a=P.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),P.setMap("transactionOwnerIds",a),this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:async o=>this.updateTransactionState({...o,context:{transactionOwnerId:n.transactionOwnerId}})},this.initialized=!0}async initFromTransaction(e,t=!1){var o,s,r,l;if(e==="")throw new G("No transaction ID provided.");const A=N.getShadowGraphqlClient(),n=async()=>{var w,E;const B=(w=(await A.query({query:ue,variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:w.transactions[0];if(!B)throw new G("Failed to read transaction.");if(!B.product)throw new G("Failed to load transaction, product not available.");this.currencyCode=(E=B.product.partner)==null?void 0:E.currencyCode,this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async()=>{throw new v("State mutation is forbidden in read only mode!")},readOnly:t},this.initialized=!0};if(t)return await n();const a=P.getMap("transactionOwnerIds")||new Map,i=a.get(e);if(i){const B=(o=(await A.query({query:ue,variables:{ids:[e]},errorPolicy:"all"})).data)==null?void 0:o.transactions[0];if(!B)throw new G("Failed to read transaction.");if(!B.product)throw new G("Failed to load transaction, product not available.");this.currencyCode=(s=B.product.partner)==null?void 0:s.currencyCode,this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async w=>this.updateTransactionState({...w,context:{transactionOwnerId:i}}),readOnly:t},this.initialized=!0;return}try{const B=(r=(await A.mutate({mutation:NA,variables:{id:e},errorPolicy:"all"})).data)==null?void 0:r.transactionClaim;if(!B)throw new G("Failed to read transaction.");if(!B.product)throw new G("Failed to load transaction, product not available.");this.currencyCode=(l=B.product.partner)==null?void 0:l.currencyCode,B.transactionOwnerId&&(a.set(B.id,B.transactionOwnerId),P.setMap("transactionOwnerIds",a)),this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async w=>this.updateTransactionState({...w,context:{transactionOwnerId:B.transactionOwnerId}}),readOnly:t},this.initialized=!0}catch{throw new G("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(e,t,A){var n,a,i,o;if(!this.initialized||!this.experienceOptions)throw new G("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const s=await we(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=s,this.experienceOptions.transaction.workflowState){const l=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(l.layouts).map(d=>d.layout),await g.rehydrateSerializedLayout(l),await ne(l),this.experienceOptions.reloadedState=l}this.experienceOptions.previewService=A&&A(s),this.experienceOptions.renderableContextService=new Me(this.experienceOptions.layouts),(n=this.experienceOptions.product)!=null&&n.modelUrl&&(this.experienceOptions.modelContainer=(a=this.experienceOptions.previewService)==null?void 0:a.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const r=new Be(this,this.experienceOptions);return await r.getWorkflowManager().getInitializationPromise(),r}if(e){const r=(P.getMap("transactionOwnerIds")||new Map).get(this.experienceOptions.transaction.id),l=N.getShadowGraphqlClient().mutate({mutation:RA,variables:{workflowId:e,id:this.experienceOptions.transaction.id},context:{transactionOwnerId:r}}),d=we(e);if(await Promise.all([l,d]),this.experienceOptions.workflow=await d,t){const w=JSON.parse(t);this.experienceOptions.layouts=Object.values(w.layouts).map(E=>E.layout),await g.rehydrateSerializedLayout(w),await ne(w),this.experienceOptions.reloadedState=w}else this.experienceOptions.layouts=Ze(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await d),this.experienceOptions.renderableContextService=new Me(this.experienceOptions.layouts),(i=this.experienceOptions.product)!=null&&i.modelUrl&&(this.experienceOptions.modelContainer=(o=this.experienceOptions.previewService)==null?void 0:o.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const B=new Be(this,this.experienceOptions);return await B.getWorkflowManager().getInitializationPromise(),B}throw new G("No workflow ID provided.")}getPreviewService(){var e;return(e=this.experienceOptions)==null?void 0:e.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new G("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new G("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}configureUrls(e,t,A){W.setHubUrl(e),W.setServerUrl(t),W.setServicesApiUrl(A)}storeCustomer(e){const t=P.getMap("partnerCustomerIds")||new Map;t.set(e.partner.id,e.id),P.setMap("partnerCustomerIds",t)}async getIntegrationProductById(e){var a,i;const n=(a=(await N.getShadowGraphqlClient().query({query:GA,variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:a.integrationProducts;if(!n||n.length===0||!((i=n[0])!=null&&i.id))throw new Error("Integration product not found.");return new Xe(n[0])}async getIntegrationProductFromExternalIds(e,t){var i;const a=(i=(await N.getShadowGraphqlClient().query({query:vA,variables:{externalProductId:t,externalIntegrationId:e},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProductFromExternalIds;if(!(a!=null&&a.id))throw new Error("Integration product not found.");return new Xe(a)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}}class fa{getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(e){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}setCurrentAdjustingStepId(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,A){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}injectIntoPreviewService(e){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(e){}}var sA=(c=>(c.SelectFrame="SelectFrame",c.SelectImage="SelectImage",c.Position="Position",c))(sA||{});class rA extends j{constructor(e,t){var A;super(e,t),this.frameService=(A=this.manager.getStepSpecificServices(this.getId()))==null?void 0:A.frameService}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return Ie.selectVariant(this.step,e.getResource(),t,this.manager,A=>this.setUpdateState(A))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}selectImage(e){return Ie.selectImage(this.step,e,this.manager)}getImageData(){if(this.frameService)return this.frameService.getImageData()}getCurrentFrameStep(e,t,A,n){return n&&n.length>1&&e===void 0?"SelectFrame":t||A||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}}Object.defineProperty(Q,"AspectType",{enumerable:!0,get:()=>g.AspectType}),Object.defineProperty(Q,"AssetType",{enumerable:!0,get:()=>g.AssetType}),Object.defineProperty(Q,"BringForwardCommand",{enumerable:!0,get:()=>g.BringForwardCommand}),Object.defineProperty(Q,"BringToBackCommand",{enumerable:!0,get:()=>g.BringToBackCommand}),Object.defineProperty(Q,"BringToFrontCommand",{enumerable:!0,get:()=>g.BringToFrontCommand}),Object.defineProperty(Q,"CanvasCommand",{enumerable:!0,get:()=>g.CanvasCommand}),Object.defineProperty(Q,"CommandContext",{enumerable:!0,get:()=>g.CommandContext}),Object.defineProperty(Q,"CreateElementCommand",{enumerable:!0,get:()=>g.CreateElementCommand}),Object.defineProperty(Q,"CreateLayoutCommand",{enumerable:!0,get:()=>g.CreateLayoutCommand}),Object.defineProperty(Q,"DeleteElementCommand",{enumerable:!0,get:()=>g.DeleteElementCommand}),Object.defineProperty(Q,"FontAlignmentCommand",{enumerable:!0,get:()=>g.FontAlignmentCommand}),Object.defineProperty(Q,"FontColorCommand",{enumerable:!0,get:()=>g.FontColorCommand}),Object.defineProperty(Q,"FontSizeCommand",{enumerable:!0,get:()=>g.FontSizeCommand}),Object.defineProperty(Q,"FontSourceCommand",{enumerable:!0,get:()=>g.FontSourceCommand}),Object.defineProperty(Q,"GroupCommand",{enumerable:!0,get:()=>g.GroupCommand}),Object.defineProperty(Q,"LayoutElementFactory",{enumerable:!0,get:()=>g.LayoutElementFactory}),Object.defineProperty(Q,"LayoutElementType",{enumerable:!0,get:()=>g.LayoutElementType}),Object.defineProperty(Q,"MoveCommand",{enumerable:!0,get:()=>g.MoveCommand}),Object.defineProperty(Q,"ResizeCommand",{enumerable:!0,get:()=>g.ResizeCommand}),Object.defineProperty(Q,"RotateCommand",{enumerable:!0,get:()=>g.RotateCommand}),Object.defineProperty(Q,"SendBackwardsCommand",{enumerable:!0,get:()=>g.SendBackwardsCommand}),Object.defineProperty(Q,"StepAspectType",{enumerable:!0,get:()=>g.StepAspectType}),Object.defineProperty(Q,"StepType",{enumerable:!0,get:()=>g.StepType}),Object.defineProperty(Q,"TextChangeCommand",{enumerable:!0,get:()=>g.TextChangeCommand}),Object.defineProperty(Q,"UnitOfMeasurement",{enumerable:!0,get:()=>g.UnitOfMeasurement}),Object.defineProperty(Q,"dataUrlFromExternalUrl",{enumerable:!0,get:()=>g.dataUrlFromExternalUrl}),Object.defineProperty(Q,"determineCorrectFontSizeAndLines",{enumerable:!0,get:()=>g.determineCorrectFontSizeAndLines}),Object.defineProperty(Q,"findElement",{enumerable:!0,get:()=>g.findElement}),Object.defineProperty(Q,"frameDataCache",{enumerable:!0,get:()=>g.frameDataCache}),Object.defineProperty(Q,"generate",{enumerable:!0,get:()=>g.generate}),Object.defineProperty(Q,"generateSVGWithUnknownColors",{enumerable:!0,get:()=>g.generateSVGWithUnknownColors}),Object.defineProperty(Q,"getAttributesFromArrayBuffer",{enumerable:!0,get:()=>g.getAttributesFromArrayBuffer}),Object.defineProperty(Q,"getAxisAlignedBoundingBox",{enumerable:!0,get:()=>g.getAxisAlignedBoundingBox}),Object.defineProperty(Q,"getFrameData",{enumerable:!0,get:()=>g.getFrameData}),Object.defineProperty(Q,"getSvgElement",{enumerable:!0,get:()=>g.getSvgElement}),Object.defineProperty(Q,"loadFont",{enumerable:!0,get:()=>g.loadFont}),Object.defineProperty(Q,"patternImageDataCache",{enumerable:!0,get:()=>g.patternImageDataCache}),Object.defineProperty(Q,"registerFetchImplementation",{enumerable:!0,get:()=>g.registerFetchImplementation}),Object.defineProperty(Q,"registerWindowImplementation",{enumerable:!0,get:()=>g.registerWindowImplementation}),Object.defineProperty(Q,"rehydrateSerializedLayout",{enumerable:!0,get:()=>g.rehydrateSerializedLayout}),Object.defineProperty(Q,"setCanvasModule",{enumerable:!0,get:()=>g.setCanvasModule}),Q.ArrayInput=ia,Q.AssetNotFoundError=V,Q.CollectionProduct=ye,Q.ColorOptionGlobalPropertyHandle=$t,Q.ConversionDataType=wt,Q.ConversionLocation=dt,Q.FileUploadGlobalPropertyHandle=qt,Q.FlowExecutionNodeResult=de,Q.FlowExecutionResult=aA,Q.FlowService=nA,Q.FrameService=ut,Q.FrameStep=sA,Q.FrameStepHandle=rA,Q.GlobalPropertyHandle=Se,Q.IllustrationStepHandle=Rt,Q.InformationMessageType=le,Q.InformationStepHandle=Tt,Q.IntegrationProduct=Xe,Q.IntegrationType=lt,Q.LayoutNotFoundError=J,Q.MaterialStepHandle=Ut,Q.MisconfigurationError=oe,Q.MockWorkflowManager=fa,Q.ModelStepHandle=Gt,Q.ObjectInput=We,Q.ObjectInputType=iA,Q.OptionGlobalPropertyHandle=Ke,Q.OptionNotFoundError=ie,Q.ParseError=q,Q.PictureStepHandle=vt,Q.ProductCameraRig=Bt,Q.ProductCollection=_t,Q.ProductWorkflow=Ae,Q.PromiseCache=Z,Q.PromiseQueue=Ue,Q.QuestionStepHandle=kt,Q.QueueablePromise=Re,Q.ResourceNotFoundError=X,Q.ShapeStepHandle=bt,Q.SpiffCommerceClient=oA,Q.StakeholderType=re,Q.StepHandle=j,Q.TextGlobalPropertyHandle=Zt,Q.TextInput=aa,Q.TextStepHandle=Jt,Q.Transform=tA,Q.TransformCollection=eA,Q.UnhandledBehaviorError=v,Q.Variant=K,Q.WorkflowExperienceEventType=Kt,Q.WorkflowExperienceImpl=Be,Q.assetService=k,Q.createDesign=jt,Q.designService=Fe,Q.digitalContentStepService=Dt,Q.frameStepService=Ie,Q.generateCommands=Vt,Q.generateStateFromDesignInputSteps=Gn,Q.getBoundedOffsets=Qt,Q.getWorkflow=we,Q.getWorkflows=qe,Q.graphQlManager=N,Q.illustrationStepService=ge,Q.materialStepService=Ge,Q.modelStepService=ve,Q.moduleStepService=pt,Q.optionService=L,Q.persistenceService=P,Q.pictureStepService=ke,Q.questionStepService=be,Q.shapeStepService=te,Q.shortenUrl=It,Q.spiffCoreConfiguration=W,Q.stepAspectValuesToDesignInputSteps=Un,Q.textStepService=O,Q.toast=Ft,Object.defineProperty(Q,Symbol.toStringTag,{value:"Module"})});
3013
+ `,ne=async c=>{var e;for(const t in c.layouts){const A=c.layouts[t].elements.filter(a=>a.type===g.LayoutElementType.Illustration);for(let a=0;a<A.length;++a){const i=A[a];i.src&&i.svg&&(i.cachedObjectURL=await g.svgObjectURL(i.svg))}const n=c.layouts[t].elements.filter(a=>a.type===g.LayoutElementType.Textbox);for(let a=0;a<n.length;++a){const i=n[a];(e=i.fontData)!=null&&e.assetUrl&&await g.loadFont(i.fontData.assetUrl)}}},ma=async(c,e)=>{var n;const t=await N.getShadowGraphqlClient().query({query:la(((n=e==null?void 0:e.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:c}}),A=t.data.workflows;if(A===void 0||A.length!==c.length)throw new Error(`Unable to read workflows: ${t.errors??"Length mismatch in response"}`);return A.forEach(a=>{a.steps.forEach(i=>{var o,s,r;delete i.data.__typename,(o=i.option)!=null&&o.id&&((s=i.option.defaultVariant)!=null&&s.asset&&k.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&k.cacheAsset(i.option.colorProfile),(r=i.option.variants)==null||r.forEach(l=>{l.asset&&k.cacheAsset(l.asset),l.displayImage&&k.cacheAsset(l.displayImage),l.thumbnail&&k.cacheAsset(l.thumbnail),l.material&&k.cacheMaterial(l.material)}),Z.set({id:i.option.id},Promise.resolve(i.option)))})}),A},Ia=async(c,e)=>{const A=(await e).find(n=>n.id===c);if(!A)throw new Error(`Workflow not found: ${c}`);return A},qe=async(c,e)=>{const t=c.map(o=>Z.get({id:o,options:e})),A=c.filter((o,s)=>t[s]===void 0);if(A.length===0)return Promise.all(t);const n=ma(A,e),a=A.map(o=>Z.set({id:o,options:e},Ia(o,n))),i=t.filter(o=>o!==void 0);return await Promise.all(i.concat(a))},we=async(c,e)=>(await qe([c],e))[0],fa=c=>c.sort((e,t)=>e.index-t.index).map(e=>({id:g.generate(),panelId:e.name,name:e.name,index:e.index,createdAt:new Date,updatedAt:new Date,transparentBackground:e.transparentBackground,height:e.height,width:e.width,previewRegion:e.previewRegion,useEditableArea:e.useEditableArea,editableArea:e.editableArea})),Ze=(c,e)=>{const t=c.workflowState,A=t?JSON.parse(t):void 0;return A?Object.values(A.layouts).map(n=>n.layout):fa(e.panels)};class oA{constructor(e){this.updateTransactionState=async t=>{try{return N.getShadowGraphqlClient().mutate({...t,mutation:HA})}catch(A){throw console.error(A),new G("Critical - Unable to synchronize workflow state with server.")}},this.initialized=!1,this.options=e,this.options.applicationKey&&dA(this.options.applicationKey)}getAssetManager(){return k}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!wA())throw new Error("Application key required to use Flow Service.");return new nA}async getIntegration(){return(await N.getShadowGraphqlClient().query({query:da,errorPolicy:"all"})).data.currentIntegration}async authenticateBundleFromLocalStorage(e){var n,a;const t=P.getMap("bundleOwnerIds");if(t!=null&&t.has(e))return Promise.resolve({success:!0,stakeholderType:re.Owner});const A=P.getMap("bundlePartnerIds")||new Map;if(A.has(e)){const i=A.get(e),s=(P.getMap("partnerCustomerIds")||new Map).get(i);if(s&&await this.authenticateCustomerId(s)){const l=(a=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:a.find(d=>{var B;return((B=d.bundle)==null?void 0:B.id)===e});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(e){var l,d,B,w,E,C;const t=N.getShadowGraphqlClient(),A=await t.query({query:Ba,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e}});if(!A.data.transactions||A.data.transactions.length===0)throw new Error(`Transaction not found: ${e}`);const n=A.data.transactions[0];if(!((d=(l=n.product)==null?void 0:l.partner)==null?void 0:d.id))throw new Error(`Unable to read transaction: ${e}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const i=P.getMap("transactionOwnerIds");if(i!=null&&i.has(e))return Promise.resolve({success:!0,stakeholderType:re.Owner});const o=P.getMap("transactionCustomerIds");if(o!=null&&o.has(e)){const h=o.get(e);if(h&&await this.authenticateCustomerId(h)){const u=((w=(B=this.customer)==null?void 0:B.bundleStakeholders)==null?void 0:w.find(F=>{var I,f;return(f=(I=F.bundle)==null?void 0:I.transactions)==null?void 0:f.some(D=>D.id===e)}))||((C=(E=this.customer)==null?void 0:E.stakeholders)==null?void 0:C.find(F=>{var I;return((I=F.transaction)==null?void 0:I.id)===e}));if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}}const r=(await t.query({query:wa,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(e){const t=P.getMap("transactionCustomerIds");t!=null&&t.has(e)&&(t.delete(e),P.setMap("transactionCustomerIds",t))}getStakeholderTypeForTransaction(e){var A,n;const t=(n=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:n.find(a=>{var i;return((i=a.transaction)==null?void 0:i.id)===e});if(t)return t.type}async getOrCreateCustomer(e){var i;this.customer=void 0;const t=N.getShadowGraphqlClient(),n=(await t.query({query:Ea,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!n.id){const s=(i=(await t.mutate({mutation:ha,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:e}}})).data)==null?void 0:i.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(n);const a=await this.authenticateCustomerId(n.id);return{customer:this.customer||n,isAuthenticated:a}}async authenticateCustomerId(e){var o;const t=N.getShadowGraphqlClient(),A=P.getMap("customerTokens");if(!(A!=null&&A.has(e)))return!1;const n=A.get(e);if(!n)return!1;const i=(o=(await t.mutate({mutation:Ca,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data)==null?void 0:o.customerAuthenticate;return i?(this.storeCustomer(i),rt(n),this.customer=i,!0):!1}async generateVerificationCode(e){await N.getShadowGraphqlClient().mutate({mutation:Qa,variables:{emailAddress:e}})}async verifyCode(e,t){var a,i;const n=(a=(await N.getShadowGraphqlClient().mutate({mutation:ua,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e,verificationCode:t}})).data)==null?void 0:a.customerVerifyCode;if(n!=null&&n.loginToken){if(!((i=n.partner)!=null&&i.id))throw new Error(`Unable to find customer: ${e}`);const o=P.getMap("customerTokens")||new Map;return o.set(n.id,n.loginToken),P.setMap("customerTokens",o),this.storeCustomer(n),rt(n.loginToken),this.customer={...n,loginToken:void 0},!0}return!1}async getNewBundle(e,t,A){var s,r,l;const a=(l=(await N.getShadowGraphqlClient().mutate({mutation:Ln(((r=(s=A==null?void 0:A.graphql)==null?void 0:s.productCollection)==null?void 0:r.eagerFetchProducts)||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((d,B)=>({key:d[0],value:d[1]})):void 0},fetchPolicy:"no-cache"})).data)==null?void 0:l.bundleCreate;if(!(a!=null&&a.id))throw new Error("Unable to create bundle");const i=P.getMap("bundlePartnerIds")||new Map;i.set(a.id,a.partner.id),P.setMap("bundlePartnerIds",i);const o=P.getMap("bundleOwnerIds")||new Map;return o.set(a.id,a.bundleOwnerId),P.setMap("bundleOwnerIds",o),new AA(this,a,void 0,void 0,a.bundleOwnerId)}async getExistingBundle(e,t,A,n){var d,B,w,E,C,h;const a=P.getMap("bundleOwnerIds"),i=a==null?void 0:a.get(e),o=await N.getShadowGraphqlClient().query({query:kn(((B=(d=n==null?void 0:n.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts)||!1),variables:{id:e},fetchPolicy:"no-cache",context:{bundleOwnerId:i}});if(!((w=o.data)!=null&&w.bundles)||((E=o.data)==null?void 0:E.bundles.length)===0||!((C=o.data)!=null&&C.bundles[0]))throw new Error(`Unable to find bundle: ${e}`);const s=(h=o.data)==null?void 0:h.bundles[0],r=P.getMap("bundlePartnerIds")||new Map;r.set(s.id,s.partner.id),P.setMap("bundlePartnerIds",r);const l=new AA(this,s,t,A,i);return await l.getInitializationPromise(),l}async getBundleStakeholders(){var a;if(!this.customer)throw new Error("Customer not authenticated.");const e=await N.getShadowGraphqlClient().query({query:Jn,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((a=e.data)!=null&&a.customers)||e.data.customers.length===0)throw new Error("Unable to find customer.");const A=e.data.customers[0].bundleStakeholders||[],n=P.getMap("bundlePartnerIds")||new Map;return A.forEach(i=>{var o,s;(o=i.bundle)!=null&&o.id&&((s=i.bundle.partner)!=null&&s.id)&&n.set(i.bundle.id,i.bundle.partner.id)}),P.setMap("bundlePartnerIds",n),A}async getWorkflowExperience(e,t,A,n){var d,B,w,E,C;if(!n)return await this.getWorkflowExperienceDeprecated(e,t,A);const a=async()=>{var m,u;const h=N.getShadowGraphqlClient();if(n.type==="transaction"){const{transactionId:F,readOnly:I}=n,f=await h.query({query:ue,variables:{ids:[F]},errorPolicy:"all",fetchPolicy:"no-cache"});if(!((m=f.data)!=null&&m.transactions)||f.data.transactions.length===0)throw new G("Existing transaction not found.");const D=(u=f.data)==null?void 0:u.transactions[0];if(!D.workflowId)throw new G("Existing transaction has no workflow ID.");const p=await we(D.workflowId);if(!D.product)throw new G("Failed to load transaction, product not available.");return{transaction:D,workflow:p,readOnly:I}}if(n.type==="integration"||n.type==="external"){const F=async()=>{const p=n.type==="integration"?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},S=await h.mutate({mutation:Et,variables:{...p,workflowId:n.workflowId,claim:!0},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!S.data||!S.data.transactionCreate)throw new G("Failed to create transaction!");const y=S.data.transactionCreate;if(!y.product)throw new G("Failed to create transaction, product not available.");return y},I=we(n.workflowId,n==null?void 0:n.graphql),[f,D]=await Promise.all([F(),I]);return{transaction:f,workflow:D}}throw new G("No workflow ID provided.")},{transaction:i,workflow:o,readOnly:s}=await a();this.currencyCode=(d=i.product.partner)==null?void 0:d.currencyCode;const r={product:i.product,transaction:i,layouts:[],singleVariantsRenderable:(B=n==null?void 0:n.workflowConfiguration)==null?void 0:B.singleVariantsRenderable,stateMutationFunc:s?async()=>{throw new v("State mutation is forbidden in read only mode!")}:async h=>{const u=(P.getMap("transactionOwnerIds")||new Map).get(i.id)||void 0;return this.updateTransactionState({...h,context:{transactionOwnerId:u}})},readOnly:s,workflow:o};if(n.type==="transaction"&&i.workflowState){const h=JSON.parse(i.workflowState);r.layouts=Object.values(h.layouts).map(m=>m.layout),await g.rehydrateSerializedLayout(h),await ne(h),r.reloadedState=h}else if(!s&&n.workflowState){const h=JSON.parse(n.workflowState);r.layouts=Object.values(h.layouts).map(m=>m.layout),await g.rehydrateSerializedLayout(h),await ne(h),r.reloadedState=h}else r.layouts=Ze(r.transaction,r.workflow);if(r.renderableContextService=new Me(r.layouts),n.previewService?(r.previewService=n.previewService,(w=r.product)!=null&&w.modelUrl&&(r.modelContainer=r.previewService.loadModel({model:r.product.modelUrl,contextService:r.renderableContextService}))):(r.previewService=A&&A(o),(E=r.product)!=null&&E.modelUrl&&(r.modelContainer=(C=r.previewService)==null?void 0:C.loadModel({model:r.product.modelUrl,contextService:r.renderableContextService}))),n.type!=="transaction"){const h=P.getMap("transactionOwnerIds")||new Map;h.set(i.id,i.transactionOwnerId),P.setMap("transactionOwnerIds",h)}else r.isReloadedTransaction=!0;this.initialized=!0,this.experienceOptions=r;const l=new Be(this,r);return await l.getWorkflowManager().getInitializationPromise(),n.type!=="transaction"&&this.customer&&await l.attachCustomerDetails({email:this.customer.emailAddress}),l}async getWorkflowExperiences(e,t){if(e.length===0)throw new G("No options provided!");const A=N.getShadowGraphqlClient(),n=async f=>{var y,x;if(f.length===0)return[];const D=f.map(Y=>Y.option.transactionId),p=await A.query({query:ue,variables:{ids:D},errorPolicy:"all",fetchPolicy:"no-cache"}),S=p.data.transactions;if(S.length!==f.length){const Y=((x=(y=p.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new G(`Not all transactions were found: ${Y}`)}return S.map((Y,H)=>{var R;return{transaction:Y,workflowId:Y.workflowId,readOnly:((R=f.find(T=>T.option.transactionId===Y.id))==null?void 0:R.option.readOnly)??!1,index:f[H].index}})},a=async f=>{var S,y,x;if(f.length===0)return[];const D=await A.mutate({mutation:xA,variables:{inputs:f.map(Y=>({integrationProductId:Y.option.type==="integration"?Y.option.integrationProductId:void 0,externalIntegrationId:Y.option.type==="external"?Y.option.externalIntegrationId:void 0,externalProductId:Y.option.type==="external"?Y.option.externalProductId:void 0,workflowId:Y.option.workflowId,claim:!0}))},errorPolicy:"all",fetchPolicy:"no-cache"}),p=(S=D.data)==null?void 0:S.transactionCreateMany;if(!p||p.length===0){const Y=((x=(y=D.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new G(`Failed to create transactions: ${Y}`)}return p.map((Y,H)=>({transaction:Y,workflowId:Y.workflowId,readOnly:!1,index:f[H].index}))},i=e.map((f,D)=>({option:f,index:D})),o=i.filter(f=>f.option.type==="transaction"),s=i.filter(f=>f.option.type==="integration"||f.option.type==="external"),r=at(o,10),l=at(s,10),d=(await Promise.all([...r.map(n),...l.map(a)])).flat(),B=[...new Set(d.map(f=>f.workflowId))],w=await qe(B,t),E=new Map(w.map(f=>[f.id,f])),C=P.getMap("transactionOwnerIds")||new Map,h=d.map(async f=>{var T;const{transaction:D,workflowId:p,readOnly:S,index:y}=f,x=E.get(p),Y=e[y];!C.get(D.id)&&D.transactionOwnerId&&C.set(D.id,D.transactionOwnerId);const H=C.get(D.id)||void 0,R={product:D.product,transaction:D,layouts:[],singleVariantsRenderable:(T=Y==null?void 0:Y.workflowConfiguration)==null?void 0:T.singleVariantsRenderable,stateMutationFunc:S?async()=>{throw new v("State mutation is forbidden in read only mode!")}:async b=>this.updateTransactionState({...b,context:{transactionOwnerId:H}}),readOnly:S,workflow:x,isReloadedTransaction:Y.type==="transaction"};if(Y.type==="transaction"&&D.workflowState){const b=JSON.parse(D.workflowState);R.layouts=Object.values(b.layouts).map(z=>z.layout),await g.rehydrateSerializedLayout(b),await ne(b),R.reloadedState=b}else if(!S&&Y.workflowState){const b=JSON.parse(Y.workflowState);R.layouts=Object.values(b.layouts).map(z=>z.layout),await g.rehydrateSerializedLayout(b),await ne(b),R.reloadedState=b}else R.layouts=Ze(R.transaction,R.workflow);return R.renderableContextService=new Me(R.layouts),R.delayWorkflowStateSync=!0,this.initialized=!0,this.experienceOptions=R,{experienceOptions:R,index:y,options:Y}});P.setMap("transactionOwnerIds",C);const F=(await Promise.all(h)).sort((f,D)=>f.index-D.index).map(async f=>{const{experienceOptions:D,options:p}=f,S=new Be(this,D);return await S.getWorkflowManager().getInitializationPromise(),p.type!=="transaction"&&this.customer&&await S.attachCustomerDetails({email:this.customer.emailAddress}),S}),I=await Promise.all(F);return I.forEach(f=>f.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),I}async initFromIntegrationProduct(e){var i;if(e==="")throw new G("No integration product ID provided.");const A=await N.getShadowGraphqlClient().mutate({mutation:Et,variables:{integrationProductId:e,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 G("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new G("Failed to create transaction, product not available.");this.currencyCode=(i=n.product.partner)==null?void 0:i.currencyCode;const a=P.getMap("transactionOwnerIds")||new Map;a.set(n.id,n.transactionOwnerId),P.setMap("transactionOwnerIds",a),this.experienceOptions={product:n.product,transaction:n,layouts:[],stateMutationFunc:async o=>this.updateTransactionState({...o,context:{transactionOwnerId:n.transactionOwnerId}})},this.initialized=!0}async initFromTransaction(e,t=!1){var o,s,r,l;if(e==="")throw new G("No transaction ID provided.");const A=N.getShadowGraphqlClient(),n=async()=>{var w,E;const B=(w=(await A.query({query:ue,variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:w.transactions[0];if(!B)throw new G("Failed to read transaction.");if(!B.product)throw new G("Failed to load transaction, product not available.");this.currencyCode=(E=B.product.partner)==null?void 0:E.currencyCode,this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async()=>{throw new v("State mutation is forbidden in read only mode!")},readOnly:t},this.initialized=!0};if(t)return await n();const a=P.getMap("transactionOwnerIds")||new Map,i=a.get(e);if(i){const B=(o=(await A.query({query:ue,variables:{ids:[e]},errorPolicy:"all"})).data)==null?void 0:o.transactions[0];if(!B)throw new G("Failed to read transaction.");if(!B.product)throw new G("Failed to load transaction, product not available.");this.currencyCode=(s=B.product.partner)==null?void 0:s.currencyCode,this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async w=>this.updateTransactionState({...w,context:{transactionOwnerId:i}}),readOnly:t},this.initialized=!0;return}try{const B=(r=(await A.mutate({mutation:NA,variables:{id:e},errorPolicy:"all"})).data)==null?void 0:r.transactionClaim;if(!B)throw new G("Failed to read transaction.");if(!B.product)throw new G("Failed to load transaction, product not available.");this.currencyCode=(l=B.product.partner)==null?void 0:l.currencyCode,B.transactionOwnerId&&(a.set(B.id,B.transactionOwnerId),P.setMap("transactionOwnerIds",a)),this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async w=>this.updateTransactionState({...w,context:{transactionOwnerId:B.transactionOwnerId}}),readOnly:t},this.initialized=!0}catch{throw new G("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(e,t,A){var n,a,i,o;if(!this.initialized||!this.experienceOptions)throw new G("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const s=await we(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=s,this.experienceOptions.transaction.workflowState){const l=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(l.layouts).map(d=>d.layout),await g.rehydrateSerializedLayout(l),await ne(l),this.experienceOptions.reloadedState=l}this.experienceOptions.previewService=A&&A(s),this.experienceOptions.renderableContextService=new Me(this.experienceOptions.layouts),(n=this.experienceOptions.product)!=null&&n.modelUrl&&(this.experienceOptions.modelContainer=(a=this.experienceOptions.previewService)==null?void 0:a.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const r=new Be(this,this.experienceOptions);return await r.getWorkflowManager().getInitializationPromise(),r}if(e){const r=(P.getMap("transactionOwnerIds")||new Map).get(this.experienceOptions.transaction.id),l=N.getShadowGraphqlClient().mutate({mutation:RA,variables:{workflowId:e,id:this.experienceOptions.transaction.id},context:{transactionOwnerId:r}}),d=we(e);if(await Promise.all([l,d]),this.experienceOptions.workflow=await d,t){const w=JSON.parse(t);this.experienceOptions.layouts=Object.values(w.layouts).map(E=>E.layout),await g.rehydrateSerializedLayout(w),await ne(w),this.experienceOptions.reloadedState=w}else this.experienceOptions.layouts=Ze(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await d),this.experienceOptions.renderableContextService=new Me(this.experienceOptions.layouts),(i=this.experienceOptions.product)!=null&&i.modelUrl&&(this.experienceOptions.modelContainer=(o=this.experienceOptions.previewService)==null?void 0:o.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const B=new Be(this,this.experienceOptions);return await B.getWorkflowManager().getInitializationPromise(),B}throw new G("No workflow ID provided.")}getPreviewService(){var e;return(e=this.experienceOptions)==null?void 0:e.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new G("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new G("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}configureUrls(e,t,A){W.setHubUrl(e),W.setServerUrl(t),W.setServicesApiUrl(A)}storeCustomer(e){const t=P.getMap("partnerCustomerIds")||new Map;t.set(e.partner.id,e.id),P.setMap("partnerCustomerIds",t)}async getIntegrationProductById(e){var a,i;const n=(a=(await N.getShadowGraphqlClient().query({query:GA,variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:a.integrationProducts;if(!n||n.length===0||!((i=n[0])!=null&&i.id))throw new Error("Integration product not found.");return new Xe(n[0])}async getIntegrationProductFromExternalIds(e,t){var i;const a=(i=(await N.getShadowGraphqlClient().query({query:vA,variables:{externalProductId:t,externalIntegrationId:e},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProductFromExternalIds;if(!(a!=null&&a.id))throw new Error("Integration product not found.");return new Xe(a)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}}class Da{getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(e){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}setCurrentAdjustingStepId(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,A){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}injectIntoPreviewService(e){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(e){}}var sA=(c=>(c.SelectFrame="SelectFrame",c.SelectImage="SelectImage",c.Position="Position",c))(sA||{});class rA extends j{constructor(e,t){var A;super(e,t),this.frameService=(A=this.manager.getStepSpecificServices(this.getId()))==null?void 0:A.frameService}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return Ie.selectVariant(this.step,e.getResource(),t,this.manager,A=>this.setUpdateState(A))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}selectImage(e){return Ie.selectImage(this.step,e,this.manager)}getImageData(){if(this.frameService)return this.frameService.getImageData()}getCurrentFrameStep(e,t,A,n){return n&&n.length>1&&e===void 0?"SelectFrame":t||A||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}}Object.defineProperty(Q,"AspectType",{enumerable:!0,get:()=>g.AspectType}),Object.defineProperty(Q,"AssetType",{enumerable:!0,get:()=>g.AssetType}),Object.defineProperty(Q,"BringForwardCommand",{enumerable:!0,get:()=>g.BringForwardCommand}),Object.defineProperty(Q,"BringToBackCommand",{enumerable:!0,get:()=>g.BringToBackCommand}),Object.defineProperty(Q,"BringToFrontCommand",{enumerable:!0,get:()=>g.BringToFrontCommand}),Object.defineProperty(Q,"CanvasCommand",{enumerable:!0,get:()=>g.CanvasCommand}),Object.defineProperty(Q,"CommandContext",{enumerable:!0,get:()=>g.CommandContext}),Object.defineProperty(Q,"CreateElementCommand",{enumerable:!0,get:()=>g.CreateElementCommand}),Object.defineProperty(Q,"CreateLayoutCommand",{enumerable:!0,get:()=>g.CreateLayoutCommand}),Object.defineProperty(Q,"DeleteElementCommand",{enumerable:!0,get:()=>g.DeleteElementCommand}),Object.defineProperty(Q,"FontAlignmentCommand",{enumerable:!0,get:()=>g.FontAlignmentCommand}),Object.defineProperty(Q,"FontColorCommand",{enumerable:!0,get:()=>g.FontColorCommand}),Object.defineProperty(Q,"FontSizeCommand",{enumerable:!0,get:()=>g.FontSizeCommand}),Object.defineProperty(Q,"FontSourceCommand",{enumerable:!0,get:()=>g.FontSourceCommand}),Object.defineProperty(Q,"GroupCommand",{enumerable:!0,get:()=>g.GroupCommand}),Object.defineProperty(Q,"LayoutElementFactory",{enumerable:!0,get:()=>g.LayoutElementFactory}),Object.defineProperty(Q,"LayoutElementType",{enumerable:!0,get:()=>g.LayoutElementType}),Object.defineProperty(Q,"MoveCommand",{enumerable:!0,get:()=>g.MoveCommand}),Object.defineProperty(Q,"ResizeCommand",{enumerable:!0,get:()=>g.ResizeCommand}),Object.defineProperty(Q,"RotateCommand",{enumerable:!0,get:()=>g.RotateCommand}),Object.defineProperty(Q,"SendBackwardsCommand",{enumerable:!0,get:()=>g.SendBackwardsCommand}),Object.defineProperty(Q,"StepAspectType",{enumerable:!0,get:()=>g.StepAspectType}),Object.defineProperty(Q,"StepType",{enumerable:!0,get:()=>g.StepType}),Object.defineProperty(Q,"TextChangeCommand",{enumerable:!0,get:()=>g.TextChangeCommand}),Object.defineProperty(Q,"UnitOfMeasurement",{enumerable:!0,get:()=>g.UnitOfMeasurement}),Object.defineProperty(Q,"dataUrlFromExternalUrl",{enumerable:!0,get:()=>g.dataUrlFromExternalUrl}),Object.defineProperty(Q,"determineCorrectFontSizeAndLines",{enumerable:!0,get:()=>g.determineCorrectFontSizeAndLines}),Object.defineProperty(Q,"findElement",{enumerable:!0,get:()=>g.findElement}),Object.defineProperty(Q,"frameDataCache",{enumerable:!0,get:()=>g.frameDataCache}),Object.defineProperty(Q,"generate",{enumerable:!0,get:()=>g.generate}),Object.defineProperty(Q,"generateSVGWithUnknownColors",{enumerable:!0,get:()=>g.generateSVGWithUnknownColors}),Object.defineProperty(Q,"getAttributesFromArrayBuffer",{enumerable:!0,get:()=>g.getAttributesFromArrayBuffer}),Object.defineProperty(Q,"getAxisAlignedBoundingBox",{enumerable:!0,get:()=>g.getAxisAlignedBoundingBox}),Object.defineProperty(Q,"getFrameData",{enumerable:!0,get:()=>g.getFrameData}),Object.defineProperty(Q,"getSvgElement",{enumerable:!0,get:()=>g.getSvgElement}),Object.defineProperty(Q,"loadFont",{enumerable:!0,get:()=>g.loadFont}),Object.defineProperty(Q,"patternImageDataCache",{enumerable:!0,get:()=>g.patternImageDataCache}),Object.defineProperty(Q,"registerFetchImplementation",{enumerable:!0,get:()=>g.registerFetchImplementation}),Object.defineProperty(Q,"registerWindowImplementation",{enumerable:!0,get:()=>g.registerWindowImplementation}),Object.defineProperty(Q,"rehydrateSerializedLayout",{enumerable:!0,get:()=>g.rehydrateSerializedLayout}),Object.defineProperty(Q,"setCanvasModule",{enumerable:!0,get:()=>g.setCanvasModule}),Q.ArrayInput=oa,Q.AssetNotFoundError=V,Q.CollectionProduct=ye,Q.ColorOptionGlobalPropertyHandle=$t,Q.ConversionDataType=wt,Q.ConversionLocation=dt,Q.FileUploadGlobalPropertyHandle=qt,Q.FlowExecutionNodeResult=de,Q.FlowExecutionResult=aA,Q.FlowService=nA,Q.FrameService=ut,Q.FrameStep=sA,Q.FrameStepHandle=rA,Q.GlobalPropertyHandle=Se,Q.IllustrationStepHandle=Rt,Q.InformationMessageType=le,Q.InformationStepHandle=Tt,Q.IntegrationProduct=Xe,Q.IntegrationType=lt,Q.LayoutNotFoundError=J,Q.MaterialStepHandle=Ut,Q.MisconfigurationError=oe,Q.MockWorkflowManager=Da,Q.ModelStepHandle=Gt,Q.ObjectInput=We,Q.ObjectInputType=iA,Q.OptionGlobalPropertyHandle=Ke,Q.OptionNotFoundError=ie,Q.ParseError=q,Q.PictureStepHandle=vt,Q.ProductCameraRig=Bt,Q.ProductCollection=_t,Q.ProductWorkflow=Ae,Q.PromiseCache=Z,Q.PromiseQueue=Ue,Q.QuestionStepHandle=kt,Q.QueueablePromise=Re,Q.ResourceNotFoundError=X,Q.ShapeStepHandle=bt,Q.SpiffCommerceClient=oA,Q.StakeholderType=re,Q.StepHandle=j,Q.TextGlobalPropertyHandle=Zt,Q.TextInput=ia,Q.TextStepHandle=Jt,Q.Transform=tA,Q.TransformCollection=eA,Q.UnhandledBehaviorError=v,Q.Variant=K,Q.WorkflowExperienceEventType=Kt,Q.WorkflowExperienceImpl=Be,Q.assetService=k,Q.createDesign=jt,Q.designService=Fe,Q.digitalContentStepService=Dt,Q.frameStepService=Ie,Q.generateCommands=Vt,Q.generateStateFromDesignInputSteps=Gn,Q.getBoundedOffsets=Qt,Q.getWorkflow=we,Q.getWorkflows=qe,Q.graphQlManager=N,Q.illustrationStepService=ge,Q.materialStepService=Ge,Q.modelStepService=ve,Q.moduleStepService=pt,Q.optionService=L,Q.persistenceService=P,Q.pictureStepService=ke,Q.questionStepService=be,Q.shapeStepService=te,Q.shortenUrl=It,Q.spiffCoreConfiguration=W,Q.stepAspectValuesToDesignInputSteps=Un,Q.textStepService=O,Q.toast=Ft,Object.defineProperty(Q,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/core",
3
- "version": "21.7.1",
3
+ "version": "21.8.0",
4
4
  "description": "Core client API for interacting with the Spiff Commerce backend.",
5
5
  "source": "src/index.ts",
6
6
  "main": "dist/index.umd.cjs",