@spiffcommerce/core 22.4.0 → 22.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -11593,7 +11593,7 @@ class xA extends pt {
11593
11593
  if (!t)
11594
11594
  return Promise.resolve();
11595
11595
  const A = (n = (a = this.optionResource) == null ? void 0 : a.variants) == null ? void 0 : n.find((i) => i.id === t);
11596
- return A ? this.applyVariantSelection(new Z(A), e) : Promise.resolve();
11596
+ return A ? (console.log("Applying Global Variant: ", A), this.applyVariantSelection(new Z(A), e)) : Promise.resolve();
11597
11597
  }
11598
11598
  async applyVariantSelection(e, t) {
11599
11599
  const a = this.getSharedSteps(t).map((n) => n.selectVariant(e));
@@ -11620,7 +11620,7 @@ class Gt extends xA {
11620
11620
  if (!t)
11621
11621
  return Promise.resolve();
11622
11622
  const A = (n = (a = this.optionResource) == null ? void 0 : a.variants) == null ? void 0 : n.find((i) => i.id === t);
11623
- return A ? this.applyColorVariant(new Z(A), e) : Promise.resolve();
11623
+ return A ? (console.log("Applying Global Variant: ", A), this.applyColorVariant(new Z(A), e)) : Promise.resolve();
11624
11624
  }
11625
11625
  async applyColorVariant(e, t) {
11626
11626
  const a = this.getSharedSteps(t).map((n) => {
@@ -12232,19 +12232,20 @@ class bt {
12232
12232
  return this.productCollection ? new Ni(this.productCollection) : void 0;
12233
12233
  }
12234
12234
  async addWorkflowExperience(e) {
12235
- e.setBundle(this), await this.appendWorkflowExperience(e), await this.injectExperienceIntoPreviewService(e);
12235
+ e.setBundle(this), await this.appendWorkflowExperience(e), await this.injectExperienceIntoPreviewService(e), await e.getWorkflowManager().getInitializationPromise();
12236
12236
  const t = await this.getGlobalProperties();
12237
- await Promise.all(t.map((A) => A.applyGlobalState([e])));
12237
+ for (const A of t)
12238
+ await A.applyGlobalState([e]);
12238
12239
  }
12239
12240
  async addWorkflowExperiences(e) {
12240
- const t = e.map((i) => i.getWorkflowManager().getTransaction().id), A = t.map(
12241
- (i) => this.workflowExperiences.find((s) => s.getWorkflowManager().getTransaction().id === i)
12241
+ const t = e.map((s) => s.getWorkflowManager().getTransaction().id), A = t.map(
12242
+ (s) => this.workflowExperiences.find((o) => o.getWorkflowManager().getTransaction().id === s)
12242
12243
  );
12243
- if (A.some((i) => !!i))
12244
+ if (A.some((s) => !!s))
12244
12245
  throw new Error(
12245
- "Unable to add transaction to bundle - Already Exists: " + A.filter((i) => !!i).map((i) => i == null ? void 0 : i.getWorkflowManager().getTransaction().id).join(", ")
12246
+ "Unable to add transaction to bundle - Already Exists: " + A.filter((s) => !!s).map((s) => s == null ? void 0 : s.getWorkflowManager().getTransaction().id).join(", ")
12246
12247
  );
12247
- const a = Y.getMap("transactionOwnerIds") || /* @__PURE__ */ new Map(), n = t.map((i) => a.get(i));
12248
+ const a = Y.getMap("transactionOwnerIds") || /* @__PURE__ */ new Map(), n = t.map((s) => a.get(s));
12248
12249
  await P.getShadowGraphqlClient().mutate({
12249
12250
  mutation: hi,
12250
12251
  variables: {
@@ -12255,17 +12256,18 @@ class bt {
12255
12256
  context: {
12256
12257
  bundleOwnerId: this.ownerId
12257
12258
  }
12258
- }).catch((i) => {
12259
- console.error(i);
12260
- }), this.workflowExperiences.push(...e), await Promise.all([
12261
- this.updateTransactionOrder(),
12262
- (async () => {
12263
- for (const s of e)
12264
- await this.injectExperienceIntoPreviewService(s);
12265
- const i = await this.getGlobalProperties();
12266
- await Promise.all(i.map((s) => s.applyGlobalState(e)));
12267
- })()
12268
- ]), this.workflowExperiences.forEach((i) => i.setBundle(this)), this.workflowExperiences.forEach((i) => i.checkForPriceBreakChanges());
12259
+ }).catch((s) => {
12260
+ console.error(s);
12261
+ }), this.workflowExperiences.push(...e);
12262
+ const i = async () => {
12263
+ for (const o of e)
12264
+ o.setBundle(this), await this.injectExperienceIntoPreviewService(o);
12265
+ await Promise.all(e.map((o) => o.getWorkflowManager().getInitializationPromise()));
12266
+ const s = await this.getGlobalProperties();
12267
+ for (const o of s)
12268
+ await o.applyGlobalState(e);
12269
+ };
12270
+ await Promise.all([this.updateTransactionOrder(), i()]), this.workflowExperiences.forEach((s) => s.checkForPriceBreakChanges());
12269
12271
  }
12270
12272
  async appendWorkflowExperience(e, t = !0) {
12271
12273
  const A = e.getWorkflowManager().getTransaction().id;
@@ -13538,7 +13540,7 @@ class es {
13538
13540
  } catch (A) {
13539
13541
  throw console.error(A), new H("Critical - Unable to synchronize workflow state with server.");
13540
13542
  }
13541
- }, this.initialized = !1, this.options = e, this.options.applicationKey && ca(this.options.applicationKey), console.debug("------------------------"), console.debug("Spiff Commerce Core SDK"), console.debug("Version: 22.3.0-beta.a2ef5e96-a632-56a0-ac67-08058b0e08df"), console.debug(`Application Key Provided: ${!!this.options.applicationKey}`), console.debug("------------------------");
13543
+ }, this.initialized = !1, this.options = e, this.options.applicationKey && ca(this.options.applicationKey), console.debug("------------------------"), console.debug("Spiff Commerce Core SDK"), console.debug("Version: 22.4.0"), console.debug(`Application Key Provided: ${!!this.options.applicationKey}`), console.debug("------------------------");
13542
13544
  }
13543
13545
  /** @deprecated Use `configure` instead */
13544
13546
  configureUrls(e, t, A) {
@@ -2466,7 +2466,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2466
2466
  id
2467
2467
  }
2468
2468
  }
2469
- `;class Pa{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 l.AspectType.FileUpload:return new mA(this.bundle,e);case l.AspectType.ColorOption:return new at(this.bundle,e,e.entityId?await L.getOption(e.entityId):void 0);case l.AspectType.Option:{const t=e.entityId?await L.getOption(e.entityId):void 0;return(t==null?void 0:t.type)==="Color"?new at(this.bundle,e,t):new nt(this.bundle,e,t)}case l.AspectType.Text:return new QA(this.bundle,e);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Re{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 mA extends Re{constructor(e,t){super(e,t)}async selectImage(e){const t=this.bundle.getGlobalPropertyStateManager();await Promise.all([t.setAspect(this.property.name,e.key,{...t.getAspectStorage(this.property.name)||{},originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}),this.applyImageSelection(e)])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Me.BackgroundRemover)}async removeBackgroundFromImage(e=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const t=await this.getOriginalImage();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const A=this.bundle.getGlobalPropertyStateManager(),n=await k.removeBackgroundFromAsset(t),i={...A.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!e},s=[e?A.setAspect(this.property.name,n.key,i):A.setAspectStorage(this.property.name,i)];return e&&s.push(this.applyImageSelection(n,void 0,!1,!1)),await Promise.all(s),this.updateSharedStepStorage(i),n}hasImage(){return!!this.getStateValue()}async getImage(){const e=this.getStateValue();if(e)return k.getLocalOrFromServer(e)}async getOriginalImage(){const e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(e!=null&&e.originalAssetKey)return k.getLocalOrFromServer(e.originalAssetKey)}async getBackgroundRemovedImage(){const e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(e!=null&&e.backgroundRemovedAssetKey)return k.getLocalOrFromServer(e.backgroundRemovedAssetKey)}getUseOriginalImage(){var e;return((e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImage(e){const t=await this.getOriginalImage();if(!t)throw new Error("You must select an image before calling setUseOriginalImage");const A=this.bundle.getGlobalPropertyStateManager(),n=A.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===e)return;const a={...n,useOriginalAsset:e},i=e?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[A.setAspect(this.property.name,i||"",a)];if(e)o.push(this.applyImageSelection(t,void 0,!1,!1));else{const s=async()=>{const r=await this.getBackgroundRemovedImage();if(!r)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(r,void 0,!1,!1)};o.push(s())}this.updateSharedStepStorage(a)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return;const A=await k.getLocalOrFromServer(t);if(!A)return;const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await this.applyImageSelection(A,e,!1,!0),n?this.updateSharedStepStorage({...n}):(this.updateSharedStepStorage({originalAssetKey:t}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:t}))}async applyImageSelection(e,t,A=!0,n=!0){const i=this.getSharedSteps(t).map(o=>{const s=o;if(s.getFrameService())return s.selectImage(e,A,n)});await Promise.all(i)}updateSharedStepStorage(e){this.bundle.getWorkflowExperiences().forEach(A=>A.getSteps().forEach(n=>{var i;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((i=n.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}))&&A.getWorkflowManager().updateStorage(n.getId(),{framePatternData:e})}))}}class QA extends Re{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 nt extends Re{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 W(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 W(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 W(n))}getAllVariants(){var t;return(((t=this.optionResource)==null?void 0:t.variants)||[]).map(A=>new W(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 W(A),e):Promise.resolve()}async applyVariantSelection(e,t){const n=this.getSharedSteps(t).map(a=>a.selectVariant(e));await Promise.all(n)}}class at extends nt{constructor(e,t,A){super(e,t,A)}async selectVariant(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.getId()),this.applyColorVariant(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.applyColorVariant(new W(A),e):Promise.resolve()}async applyColorVariant(e,t){const n=this.getSharedSteps(t).map(a=>{switch(a.getType()){case l.StepType.Shape:return a.selectVariant(e);case l.StepType.Text:return a.setFillColor({fill:e.getColor(),stroke:e.getColor(),variant:e.getResource()})}});await Promise.all(n)}setCustomColor(e){this.getSharedSteps().forEach(A=>A.setCustomColor(e))}getCustomColor(){return this.getSharedSteps()[0].getCustomColor()}}const it=F.gql`
2469
+ `;class Pa{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 l.AspectType.FileUpload:return new mA(this.bundle,e);case l.AspectType.ColorOption:return new at(this.bundle,e,e.entityId?await L.getOption(e.entityId):void 0);case l.AspectType.Option:{const t=e.entityId?await L.getOption(e.entityId):void 0;return(t==null?void 0:t.type)==="Color"?new at(this.bundle,e,t):new nt(this.bundle,e,t)}case l.AspectType.Text:return new QA(this.bundle,e);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Re{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 mA extends Re{constructor(e,t){super(e,t)}async selectImage(e){const t=this.bundle.getGlobalPropertyStateManager();await Promise.all([t.setAspect(this.property.name,e.key,{...t.getAspectStorage(this.property.name)||{},originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}),this.applyImageSelection(e)])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Me.BackgroundRemover)}async removeBackgroundFromImage(e=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const t=await this.getOriginalImage();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const A=this.bundle.getGlobalPropertyStateManager(),n=await k.removeBackgroundFromAsset(t),i={...A.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!e},s=[e?A.setAspect(this.property.name,n.key,i):A.setAspectStorage(this.property.name,i)];return e&&s.push(this.applyImageSelection(n,void 0,!1,!1)),await Promise.all(s),this.updateSharedStepStorage(i),n}hasImage(){return!!this.getStateValue()}async getImage(){const e=this.getStateValue();if(e)return k.getLocalOrFromServer(e)}async getOriginalImage(){const e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(e!=null&&e.originalAssetKey)return k.getLocalOrFromServer(e.originalAssetKey)}async getBackgroundRemovedImage(){const e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(e!=null&&e.backgroundRemovedAssetKey)return k.getLocalOrFromServer(e.backgroundRemovedAssetKey)}getUseOriginalImage(){var e;return((e=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImage(e){const t=await this.getOriginalImage();if(!t)throw new Error("You must select an image before calling setUseOriginalImage");const A=this.bundle.getGlobalPropertyStateManager(),n=A.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===e)return;const a={...n,useOriginalAsset:e},i=e?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[A.setAspect(this.property.name,i||"",a)];if(e)o.push(this.applyImageSelection(t,void 0,!1,!1));else{const s=async()=>{const r=await this.getBackgroundRemovedImage();if(!r)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(r,void 0,!1,!1)};o.push(s())}this.updateSharedStepStorage(a)}async applyGlobalState(e){const t=this.getStateValue();if(!t)return;const A=await k.getLocalOrFromServer(t);if(!A)return;const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await this.applyImageSelection(A,e,!1,!0),n?this.updateSharedStepStorage({...n}):(this.updateSharedStepStorage({originalAssetKey:t}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:t}))}async applyImageSelection(e,t,A=!0,n=!0){const i=this.getSharedSteps(t).map(o=>{const s=o;if(s.getFrameService())return s.selectImage(e,A,n)});await Promise.all(i)}updateSharedStepStorage(e){this.bundle.getWorkflowExperiences().forEach(A=>A.getSteps().forEach(n=>{var i;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((i=n.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}))&&A.getWorkflowManager().updateStorage(n.getId(),{framePatternData:e})}))}}class QA extends Re{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 nt extends Re{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 W(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 W(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 W(n))}getAllVariants(){var t;return(((t=this.optionResource)==null?void 0:t.variants)||[]).map(A=>new W(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?(console.log("Applying Global Variant: ",A),this.applyVariantSelection(new W(A),e)):Promise.resolve()}async applyVariantSelection(e,t){const n=this.getSharedSteps(t).map(a=>a.selectVariant(e));await Promise.all(n)}}class at extends nt{constructor(e,t,A){super(e,t,A)}async selectVariant(e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,e.getId()),this.applyColorVariant(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?(console.log("Applying Global Variant: ",A),this.applyColorVariant(new W(A),e)):Promise.resolve()}async applyColorVariant(e,t){const n=this.getSharedSteps(t).map(a=>{switch(a.getType()){case l.StepType.Shape:return a.selectVariant(e);case l.StepType.Text:return a.setFillColor({fill:e.getColor(),stroke:e.getColor(),variant:e.getResource()})}});await Promise.all(n)}setCustomColor(e){this.getSharedSteps().forEach(A=>A.setCustomColor(e))}getCustomColor(){return this.getSharedSteps()[0].getCustomColor()}}const it=F.gql`
2470
2470
  fragment GlobalPropertyStateAspectFields on GlobalPropertyStateAspect {
2471
2471
  name
2472
2472
  value
@@ -2509,7 +2509,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2509
2509
  }
2510
2510
  }
2511
2511
  }
2512
- `;class Ra{constructor(e,t,A,n,a){this.bundleId=e,this.bundleOwnerId=t,this.configuration=A,this.bundleOptions=a,this.initPromise=this.getOrCreateGlobalPropertyState().then(i=>{this.globalPropertyState=i}),this.onGlobalPropertyStateChange=n}setBundleOptions(e){this.bundleOptions=e}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}getAspectStorage(e){var t;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(t=this.globalPropertyState.aspects.find(A=>A.name===e))==null?void 0:t.storage}async setAspect(e,t,A){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===e);if(!n)throw new Error(`Failed to find configuration aspect with name: ${e}`);const a=ge(this.globalPropertyState),i=this.globalPropertyState.aspects.find(o=>o.name===e);i?(i.value=t,A!==void 0&&(i.type=n.type,i.storage=A!==null?A:void 0)):this.globalPropertyState.aspects.push({name:e,value:t,...A===void 0?{}:{storage:A!==null?A:void 0,type:n.type}}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(a,this.globalPropertyState)}async setAspectStorage(e,t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const A=this.configuration.aspects.find(i=>i.name===e);if(!A)throw new Error(`Failed to find configuration aspect with name: ${e}`);const n=ge(this.globalPropertyState),a=this.globalPropertyState.aspects.find(i=>i.name===e);a?(a.storage=t!==null?t:void 0,a.type=A.type):this.globalPropertyState.aspects.push({name:e,value:"",type:A.type,storage:t!==null?t:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(n,this.globalPropertyState)}async updateGlobalPropertyState(){var t,A;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=await x.getShadowGraphqlClient().mutate({mutation:Na,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{const a=n.type&&n.storage?{}:void 0;if(a)switch(n.type){case l.AspectType.FileUpload:{a.fileUpload=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:a}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(t=this.bundleOptions)==null?void 0:t.additionalHeaders}}});if((A=e.data)!=null&&A.globalPropertyStateUpdate)this.globalPropertyState=e.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async getOrCreateGlobalPropertyState(){var A,n,a;const e=await x.getShadowGraphqlClient().query({query:va,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(A=this.bundleOptions)==null?void 0:A.additionalHeaders}}});if(e.data.globalPropertyState&&e.data.globalPropertyState.id)return e.data.globalPropertyState;const t=await x.getShadowGraphqlClient().mutate({mutation:xa,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(n=this.bundleOptions)==null?void 0:n.additionalHeaders}}});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 Ha{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(g=>g.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 DA{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 He(e))}async fetchProducts(){if(this.collection.productCollectionProducts)return this.collection.productCollectionProducts.map(t=>new He(t));const e=await x.getShadowGraphqlClient().query({query:ma,variables:{id:this.getId()},errorPolicy:"all",fetchPolicy:"no-cache"});return this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.map(t=>new He(t))}getTransformCollection(){if(this.collection.transformCollection)return new fA(this.collection.transformCollection)}getResource(){return this.collection}}class He{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,g,d;const i=(r=a.integration)==null?void 0:r.type,o=((g=a.integration)==null?void 0:g.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 U("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 re(n)}const A=e[0];return new re(A)}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new U("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 re(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 re{constructor(e){this.workflow=e}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class fA{constructor(e){this.collection=e}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(e=>new IA(e))}}class IA{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 pA{constructor(e,t,A,n,a,i){var o,s,r;this.eventListeners=new Map,this.workflowExperiences=[],this.client=e,this.id=t.id,this.name=t.name||"",this.ownerId=a,this.metadata=new Map(((o=t.metadata)==null?void 0:o.map(g=>[g.key,g.value]))||[]),this.productCollection=t.productCollection,this.bundleStateManager=new Ha(t.bundleStateData),this.globalPropertyStateManager=new Ra(this.id,this.ownerId,(s=this.productCollection)==null?void 0:s.globalPropertyConfiguration,this.checkConditionalHandlesChanged.bind(this),i),this.globalPropertyHandleService=new Pa(this),this.setPreviewService(A),this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((r=t.transactions)==null?void 0:r.map(g=>g.id))||[],n),this.globalPropertyStateManager.getInitializationPromise()]),this.initializationPromise.catch(g=>{console.error(`Bundle initialization failed: ${g}`)})}setBundleOptions(e){this.globalPropertyStateManager.setBundleOptions(e)}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()===l.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 DA(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 x.getShadowGraphqlClient().mutate({mutation:Ia,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 x.getShadowGraphqlClient().mutate({mutation:fa,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 x.getShadowGraphqlClient().mutate({mutation:pa,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 x.getShadowGraphqlClient().mutate({mutation:Fa,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 x.getShadowGraphqlClient().mutate({mutation:Ma,variables:{id:this.id,details:e,type:t||Ee.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 x.getShadowGraphqlClient().mutate({mutation:Sa,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 x.getShadowGraphqlClient().mutate({mutation:ya,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 x.getShadowGraphqlClient().query({query:ha,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 Zn(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 x.getShadowGraphqlClient().mutate({mutation:Da,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 x.getShadowGraphqlClient().mutate({mutation:Ya,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((()=>{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});const o=a.filter(s=>!n.includes(s));await Promise.all(o.map(s=>s.applyGlobalState()))}}fireEvent(e,t){(this.eventListeners.get(e)||[]).forEach(n=>n({bundle:this,event:e,data:t}))}}const Ua=F.gql`
2512
+ `;class Ra{constructor(e,t,A,n,a){this.bundleId=e,this.bundleOwnerId=t,this.configuration=A,this.bundleOptions=a,this.initPromise=this.getOrCreateGlobalPropertyState().then(i=>{this.globalPropertyState=i}),this.onGlobalPropertyStateChange=n}setBundleOptions(e){this.bundleOptions=e}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}getAspectStorage(e){var t;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(t=this.globalPropertyState.aspects.find(A=>A.name===e))==null?void 0:t.storage}async setAspect(e,t,A){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===e);if(!n)throw new Error(`Failed to find configuration aspect with name: ${e}`);const a=ge(this.globalPropertyState),i=this.globalPropertyState.aspects.find(o=>o.name===e);i?(i.value=t,A!==void 0&&(i.type=n.type,i.storage=A!==null?A:void 0)):this.globalPropertyState.aspects.push({name:e,value:t,...A===void 0?{}:{storage:A!==null?A:void 0,type:n.type}}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(a,this.globalPropertyState)}async setAspectStorage(e,t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const A=this.configuration.aspects.find(i=>i.name===e);if(!A)throw new Error(`Failed to find configuration aspect with name: ${e}`);const n=ge(this.globalPropertyState),a=this.globalPropertyState.aspects.find(i=>i.name===e);a?(a.storage=t!==null?t:void 0,a.type=A.type):this.globalPropertyState.aspects.push({name:e,value:"",type:A.type,storage:t!==null?t:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(n,this.globalPropertyState)}async updateGlobalPropertyState(){var t,A;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=await x.getShadowGraphqlClient().mutate({mutation:Na,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{const a=n.type&&n.storage?{}:void 0;if(a)switch(n.type){case l.AspectType.FileUpload:{a.fileUpload=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:a}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(t=this.bundleOptions)==null?void 0:t.additionalHeaders}}});if((A=e.data)!=null&&A.globalPropertyStateUpdate)this.globalPropertyState=e.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async getOrCreateGlobalPropertyState(){var A,n,a;const e=await x.getShadowGraphqlClient().query({query:va,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(A=this.bundleOptions)==null?void 0:A.additionalHeaders}}});if(e.data.globalPropertyState&&e.data.globalPropertyState.id)return e.data.globalPropertyState;const t=await x.getShadowGraphqlClient().mutate({mutation:xa,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(n=this.bundleOptions)==null?void 0:n.additionalHeaders}}});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 Ha{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(g=>g.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 DA{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 He(e))}async fetchProducts(){if(this.collection.productCollectionProducts)return this.collection.productCollectionProducts.map(t=>new He(t));const e=await x.getShadowGraphqlClient().query({query:ma,variables:{id:this.getId()},errorPolicy:"all",fetchPolicy:"no-cache"});return this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.map(t=>new He(t))}getTransformCollection(){if(this.collection.transformCollection)return new fA(this.collection.transformCollection)}getResource(){return this.collection}}class He{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,g,d;const i=(r=a.integration)==null?void 0:r.type,o=((g=a.integration)==null?void 0:g.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 U("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 re(n)}const A=e[0];return new re(A)}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new U("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 re(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 re{constructor(e){this.workflow=e}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class fA{constructor(e){this.collection=e}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(e=>new IA(e))}}class IA{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 pA{constructor(e,t,A,n,a,i){var o,s,r;this.eventListeners=new Map,this.workflowExperiences=[],this.client=e,this.id=t.id,this.name=t.name||"",this.ownerId=a,this.metadata=new Map(((o=t.metadata)==null?void 0:o.map(g=>[g.key,g.value]))||[]),this.productCollection=t.productCollection,this.bundleStateManager=new Ha(t.bundleStateData),this.globalPropertyStateManager=new Ra(this.id,this.ownerId,(s=this.productCollection)==null?void 0:s.globalPropertyConfiguration,this.checkConditionalHandlesChanged.bind(this),i),this.globalPropertyHandleService=new Pa(this),this.setPreviewService(A),this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((r=t.transactions)==null?void 0:r.map(g=>g.id))||[],n),this.globalPropertyStateManager.getInitializationPromise()]),this.initializationPromise.catch(g=>{console.error(`Bundle initialization failed: ${g}`)})}setBundleOptions(e){this.globalPropertyStateManager.setBundleOptions(e)}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()===l.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 DA(this.productCollection):void 0}async addWorkflowExperience(e){e.setBundle(this),await this.appendWorkflowExperience(e),await this.injectExperienceIntoPreviewService(e),await e.getWorkflowManager().getInitializationPromise();const t=await this.getGlobalProperties();for(const A of t)await A.applyGlobalState([e])}async addWorkflowExperiences(e){const t=e.map(o=>o.getWorkflowManager().getTransaction().id),A=t.map(o=>this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===o));if(A.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const n=P.getMap("transactionOwnerIds")||new Map,a=t.map(o=>n.get(o));await x.getShadowGraphqlClient().mutate({mutation:Ia,variables:{id:this.id,transactionIds:t,transactionOwnerIds:a},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...e);const i=async()=>{for(const s of e)s.setBundle(this),await this.injectExperienceIntoPreviewService(s);await Promise.all(e.map(s=>s.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const s of o)await s.applyGlobalState(e)};await Promise.all([this.updateTransactionOrder(),i()]),this.workflowExperiences.forEach(o=>o.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 x.getShadowGraphqlClient().mutate({mutation:fa,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 x.getShadowGraphqlClient().mutate({mutation:pa,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 x.getShadowGraphqlClient().mutate({mutation:Fa,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 x.getShadowGraphqlClient().mutate({mutation:Ma,variables:{id:this.id,details:e,type:t||Ee.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 x.getShadowGraphqlClient().mutate({mutation:Sa,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 x.getShadowGraphqlClient().mutate({mutation:ya,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 x.getShadowGraphqlClient().query({query:ha,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 Zn(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 x.getShadowGraphqlClient().mutate({mutation:Da,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 x.getShadowGraphqlClient().mutate({mutation:Ya,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((()=>{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});const o=a.filter(s=>!n.includes(s));await Promise.all(o.map(s=>s.applyGlobalState()))}}fireEvent(e,t){(this.eventListeners.get(e)||[]).forEach(n=>n({bundle:this,event:e,data:t}))}}const Ua=F.gql`
2513
2513
  mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
2514
2514
  processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
2515
2515
  id
@@ -3161,4 +3161,4 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
3161
3161
  }
3162
3162
  }
3163
3163
  }
3164
- `,ce=async c=>{var e;for(const t in c.layouts){const A=c.layouts[t].elements.filter(a=>a.type===l.LayoutElementType.Illustration);for(let a=0;a<A.length;++a){const i=A[a];i.src&&i.svg&&(i.cachedObjectURL=await l.svgObjectURL(i.svg))}const n=c.layouts[t].elements.filter(a=>a.type===l.LayoutElementType.Textbox);for(let a=0;a<n.length;++a){const i=n[a];(e=i.fontData)!=null&&e.assetUrl&&await l.loadFont(i.fontData.assetUrl)}}},Za=async(c,e)=>{var n;const t=await x.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(g=>{g.asset&&k.cacheAsset(g.asset),g.displayImage&&k.cacheAsset(g.displayImage),g.thumbnail&&k.cacheAsset(g.thumbnail),g.material&&k.cacheMaterial(g.material)}),te.set({id:i.option.id},Promise.resolve(i.option)))}),a.finalizeStepConfig||(a.finalizeStepConfig={}),a.finalizeStepConfig.termsMarkdown=a.partner.termsMarkdown}),A},$a=async(c,e)=>{const A=(await e).find(n=>n.id===c);if(!A)throw new Error(`Workflow not found: ${c}`);return A},ct=async(c,e)=>{const t=c.map(o=>te.get({id:o,options:e})),A=c.filter((o,s)=>t[s]===void 0);if(A.length===0)return Promise.all(t);const n=Za(A,e),a=A.map(o=>te.set({id:o,options:e},$a(o,n))),i=t.filter(o=>o!==void 0);return await Promise.all(i.concat(a))},Ie=async(c,e)=>(await ct([c],e))[0],_a=c=>c.sort((e,t)=>e.index-t.index).map(e=>({id:l.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})),gt=(c,e)=>{const t=c.workflowState,A=t?JSON.parse(t):void 0;return A?Object.values(A.layouts).map(n=>n.layout):_a(e.panels)};class yA{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return x.getShadowGraphqlClient().mutate({...t,mutation:an})}catch(A){throw console.error(A),new U("Critical - Unable to synchronize workflow state with server.")}},this.initialized=!1,this.options=e,this.options.applicationKey&&UA(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 22.3.0-beta.a2ef5e96-a632-56a0-ac67-08058b0e08df"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configureUrls(e,t,A){j.setHubUrl(e),j.setServerUrl(t),j.setServicesApiUrl(A),this.options.applicationKey&&this.getIntegration()}configure(e){j.setHubUrl(e.hubUrl),j.setServerUrl(e.serverUrl),j.setServicesApiUrl(e.servicesApiUrl),this.marketplaceThemeInstallId=e.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=e.marketplaceThemeInstallConfigurationId,e.bearerAuthenticationToken&&It(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return k}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!kA())throw new Error("Application key required to use Flow Service.");return new FA}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");const e=async()=>(await x.getShadowGraphqlClient().query({query:tn,errorPolicy:"all",fetchPolicy:"no-cache"})).data.currentIntegration;return this.activeIntegration=e(),this.activeIntegration}async canUseAddon(e){var t;try{return((t=(await this.getIntegration()).partner.activeAddons)==null?void 0:t.includes(e))??!1}catch(A){return console.error(A),!1}}async authenticateBundleFromLocalStorage(e){var n,a;const t=P.getMap("bundleOwnerIds");if(t!=null&&t.has(e))return Promise.resolve({success:!0,stakeholderType:Ee.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 g=(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(g)return Promise.resolve({success:!0,stakeholderType:g.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(e){var g,d,B,C,w,u;const t=x.getShadowGraphqlClient(),A=await t.query({query:za,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=(g=n.product)==null?void 0:g.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:Ee.Owner});const o=P.getMap("transactionCustomerIds");if(o!=null&&o.has(e)){const h=o.get(e);if(h&&await this.authenticateCustomerId(h)){const m=((C=(B=this.customer)==null?void 0:B.bundleStakeholders)==null?void 0:C.find(M=>{var p,f;return(f=(p=M.bundle)==null?void 0:p.transactions)==null?void 0:f.some(D=>D.id===e)}))||((u=(w=this.customer)==null?void 0:w.stakeholders)==null?void 0:u.find(M=>{var p;return((p=M.transaction)==null?void 0:p.id)===e}));if(m)return Promise.resolve({success:!0,stakeholderType:m.type})}}const r=(await t.query({query:Ka,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=x.getShadowGraphqlClient(),n=(await t.query({query:ja,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!n.id){const s=(i=(await t.mutate({mutation:Va,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=x.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:Wa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data)==null?void 0:o.customerAuthenticate;return i?(this.storeCustomer(i),Dt(n),this.customer=i,!0):!1}async generateVerificationCode(e){await x.getShadowGraphqlClient().mutate({mutation:Xa,variables:{emailAddress:e}})}async verifyCode(e,t){var a,i;const n=(a=(await x.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),Dt(n.loginToken),this.customer={...n,loginToken:void 0},!0}return!1}async getNewBundle(e,t,A){var r,g,d;const a=(d=(await x.getShadowGraphqlClient().mutate({mutation:Qa(((g=(r=A==null?void 0:A.graphql)==null?void 0:r.productCollection)==null?void 0:g.eagerFetchProducts)||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((B,C)=>({key:B[0],value:B[1]})):void 0},fetchPolicy:"no-cache"})).data)==null?void 0:d.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;o.set(a.id,a.bundleOwnerId),P.setMap("bundleOwnerIds",o);const s=new pA(this,a,void 0,void 0,a.bundleOwnerId);return await s.getInitializationPromise(),s}async getExistingBundle(e,t,A,n){var h,Q,m,M,p,f,D,I,S;const a=P.getMap("bundleOwnerIds"),i=a==null?void 0:a.get(e),s=((h=Object.entries(localStorage).find(([y,Y])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken")))==null?void 0:h[0])||"",r=localStorage.getItem(s),g={};r&&!tt(r)&&(g.Authorization=`Bearer ${r}`);const d={bundleOwnerId:i,...g,...(Q=n==null?void 0:n.graphql)==null?void 0:Q.additionalHeaders},B=await x.getShadowGraphqlClient().query({query:Ea(((M=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:M.eagerFetchProducts)||!1),variables:{id:e},fetchPolicy:"no-cache",context:{headers:d}});if(!((p=B.data)!=null&&p.bundles)||((f=B.data)==null?void 0:f.bundles.length)===0||!((D=B.data)!=null&&D.bundles[0]))throw new Error(`Unable to find bundle: ${e}`);const C=(I=B.data)==null?void 0:I.bundles[0],w=P.getMap("bundlePartnerIds")||new Map;w.set(C.id,C.partner.id),P.setMap("bundlePartnerIds",w);const u=new pA(this,C,t,A,i,{additionalHeaders:(S=n==null?void 0:n.graphql)==null?void 0:S.additionalHeaders});return await u.getInitializationPromise(),u}async getBundleStakeholders(){var a;if(!this.customer)throw new Error("Customer not authenticated.");const e=await x.getShadowGraphqlClient().query({query:ua,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,C,w,u;if(!n)return await this.getWorkflowExperienceDeprecated(e,t,A);const a=async()=>{var Q,m,M;const h=x.getShadowGraphqlClient();if(n.type==="transaction"){const{transactionId:p,readOnly:f}=n,D=await h.query({query:Se,variables:{ids:[p]},errorPolicy:"all",fetchPolicy:"no-cache"});if(!((Q=D.data)!=null&&Q.transactions)||D.data.transactions.length===0)throw new U("Existing transaction not found.");const I=(m=D.data)==null?void 0:m.transactions[0];if(!I.workflowId)throw new U("Existing transaction has no workflow ID.");const S=await Ie(I.workflowId);if(!I.product)throw new U("Failed to load transaction, product not available.");return!this.activeIntegration&&((M=I.integrationProduct)!=null&&M.integration)&&(this.activeIntegration=Promise.resolve(I.integrationProduct.integration)),{transaction:I,workflow:S,readOnly:f}}if(n.type==="integration"||n.type==="external"){const p=async()=>{const S=n.type==="integration"?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},y=await h.mutate({mutation:vt,variables:{...S,workflowId:n.workflowId,designName:n.designName,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!y.data||!y.data.transactionCreate)throw new U("Failed to create transaction!");const Y=y.data.transactionCreate;if(!Y.product)throw new U("Failed to create transaction, product not available.");return Y},f=Ie(n.workflowId,n==null?void 0:n.graphql),[D,I]=await Promise.all([p(),f]);return{transaction:D,workflow:I}}throw new U("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 G("State mutation is forbidden in read only mode!")}:async h=>{const m=(P.getMap("transactionOwnerIds")||new Map).get(i.id)||void 0;return this.updateTransactionState({...h,context:{transactionOwnerId:m}})},readOnly:s,workflow:o};if(n.type==="transaction"&&i.workflowState){const h=JSON.parse(i.workflowState);r.layouts=Object.values(h.layouts).map(Q=>Q.layout),await l.rehydrateSerializedLayout(h),await ce(h),r.reloadedState=h}else if(!s&&n.workflowState){const h=JSON.parse(n.workflowState);r.layouts=Object.values(h.layouts).map(Q=>Q.layout),await l.rehydrateSerializedLayout(h),await ce(h),r.reloadedState=h}else r.layouts=gt(r.transaction,r.workflow);if(r.renderableContextService=new ve(r.layouts),n.previewService?(r.previewService=n.previewService,(C=r.product)!=null&&C.modelUrl&&(r.modelContainer=r.previewService.loadModel({model:r.product.modelUrl,contextService:r.renderableContextService}))):(r.previewService=A&&A(o),(w=r.product)!=null&&w.modelUrl&&(r.modelContainer=(u=r.previewService)==null?void 0:u.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 g=new De(this,r);return await g.getWorkflowManager().getInitializationPromise(),n.type!=="transaction"&&this.customer&&await g.attachCustomerDetails({email:this.customer.emailAddress}),g}async getWorkflowExperiences(e,t){if(e.length===0)throw new U("No options provided!");const A=x.getShadowGraphqlClient(),n=async f=>{var y,Y,v;if(f.length===0)return[];const D=f.map(N=>N.option.transactionId),I=await A.query({query:Se,variables:{ids:D},errorPolicy:"all",fetchPolicy:"no-cache"}),S=I.data.transactions;if(S.length!==f.length){const N=((Y=(y=I.errors)==null?void 0:y[0])==null?void 0:Y.message)||"Unknown error";throw new U(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((v=S[0].integrationProduct)!=null&&v.integration)&&(this.activeIntegration=Promise.resolve(S[0].integrationProduct.integration)),S.map((N,H)=>{var J;return{transaction:N,workflowId:N.workflowId,readOnly:((J=f.find(b=>b.option.transactionId===N.id))==null?void 0:J.option.readOnly)??!1,index:f[H].index}})},a=async f=>{var S,y,Y;if(f.length===0)return[];const D=await A.mutate({mutation:An,variables:{inputs:f.map(v=>({integrationProductId:v.option.type==="integration"?v.option.integrationProductId:void 0,externalIntegrationId:v.option.type==="external"?v.option.externalIntegrationId:void 0,externalProductId:v.option.type==="external"?v.option.externalProductId:void 0,workflowId:v.option.workflowId,designName:v.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),I=(S=D.data)==null?void 0:S.transactionCreateMany;if(!I||I.length===0){const v=((Y=(y=D.errors)==null?void 0:y[0])==null?void 0:Y.message)||"Unknown error";throw new U(`Failed to create transactions: ${v}`)}return I.map((v,N)=>({transaction:v,workflowId:v.workflowId,readOnly:!1,index:f[N].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=ht(o,10),g=ht(s,10),d=(await Promise.all([...r.map(n),...g.map(a)])).flat(),B=[...new Set(d.map(f=>f.workflowId))],C=await ct(B,t),w=new Map(C.map(f=>[f.id,f])),u=P.getMap("transactionOwnerIds")||new Map,h=d.map(async f=>{var J;const{transaction:D,workflowId:I,readOnly:S,index:y}=f,Y=w.get(I),v=e[y];!u.get(D.id)&&D.transactionOwnerId&&u.set(D.id,D.transactionOwnerId);const N=u.get(D.id)||void 0,H={product:D.product,transaction:D,layouts:[],singleVariantsRenderable:(J=v==null?void 0:v.workflowConfiguration)==null?void 0:J.singleVariantsRenderable,stateMutationFunc:S?async()=>{throw new G("State mutation is forbidden in read only mode!")}:async b=>this.updateTransactionState({...b,context:{transactionOwnerId:N}}),readOnly:S,workflow:Y,isReloadedTransaction:v.type==="transaction"};if(v.type==="transaction"&&D.workflowState){const b=JSON.parse(D.workflowState);H.layouts=Object.values(b.layouts||{}).map(V=>V.layout),await l.rehydrateSerializedLayout(b),await ce(b),H.reloadedState=b}else if(!S&&v.workflowState){const b=JSON.parse(v.workflowState);H.layouts=Object.values(b.layouts||{}).map(V=>V.layout),await l.rehydrateSerializedLayout(b),await ce(b),H.reloadedState=b}else H.layouts=gt(H.transaction,H.workflow);return H.renderableContextService=new ve(H.layouts),H.delayWorkflowStateSync=!0,this.initialized=!0,this.experienceOptions=H,{experienceOptions:H,index:y,options:v}});P.setMap("transactionOwnerIds",u);const M=(await Promise.all(h)).sort((f,D)=>f.index-D.index).map(async f=>{const{experienceOptions:D,options:I}=f,S=new De(this,D);return await S.getWorkflowManager().getInitializationPromise(),I.type!=="transaction"&&this.customer&&await S.attachCustomerDetails({email:this.customer.emailAddress}),S}),p=await Promise.all(M);return p.forEach(f=>f.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),p}async initFromIntegrationProduct(e){var i;if(e==="")throw new U("No integration product ID provided.");const A=await x.getShadowGraphqlClient().mutate({mutation:vt,variables:{integrationProductId:e,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},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 U("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new U("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,g;if(e==="")throw new U("No transaction ID provided.");const A=x.getShadowGraphqlClient(),n=async()=>{var C,w;const B=(C=(await A.query({query:Se,variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:C.transactions[0];if(!B)throw new U("Failed to read transaction.");if(!B.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(w=B.product.partner)==null?void 0:w.currencyCode,this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async()=>{throw new G("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:Se,variables:{ids:[e]},errorPolicy:"all"})).data)==null?void 0:o.transactions[0];if(!B)throw new U("Failed to read transaction.");if(!B.product)throw new U("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 C=>this.updateTransactionState({...C,context:{transactionOwnerId:i}}),readOnly:t},this.initialized=!0;return}try{const B=(r=(await A.mutate({mutation:nn,variables:{id:e},errorPolicy:"all"})).data)==null?void 0:r.transactionClaim;if(!B)throw new U("Failed to read transaction.");if(!B.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(g=B.product.partner)==null?void 0:g.currencyCode,B.transactionOwnerId&&(a.set(B.id,B.transactionOwnerId),P.setMap("transactionOwnerIds",a)),this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async C=>this.updateTransactionState({...C,context:{transactionOwnerId:B.transactionOwnerId}}),readOnly:t},this.initialized=!0}catch{throw new U("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 U("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const s=await Ie(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=s,this.experienceOptions.transaction.workflowState){const g=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(g.layouts).map(d=>d.layout),await l.rehydrateSerializedLayout(g),await ce(g),this.experienceOptions.reloadedState=g}this.experienceOptions.previewService=A&&A(s),this.experienceOptions.renderableContextService=new ve(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 De(this,this.experienceOptions);return await r.getWorkflowManager().getInitializationPromise(),r}if(e){const r=(P.getMap("transactionOwnerIds")||new Map).get(this.experienceOptions.transaction.id),g=x.getShadowGraphqlClient().mutate({mutation:on,variables:{workflowId:e,id:this.experienceOptions.transaction.id},context:{transactionOwnerId:r}}),d=Ie(e);if(await Promise.all([g,d]),this.experienceOptions.workflow=await d,t){const C=JSON.parse(t);this.experienceOptions.layouts=Object.values(C.layouts).map(w=>w.layout),await l.rehydrateSerializedLayout(C),await ce(C),this.experienceOptions.reloadedState=C}else this.experienceOptions.layouts=gt(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await d),this.experienceOptions.renderableContextService=new ve(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 De(this,this.experienceOptions);return await B.getWorkflowManager().getInitializationPromise(),B}throw new U("No workflow ID provided.")}getPreviewService(){var e;return(e=this.experienceOptions)==null?void 0:e.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}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 x.getShadowGraphqlClient().query({query:cn,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 rt(n[0])}async getIntegrationProductFromExternalIds(e,t){var i;const a=(i=(await x.getShadowGraphqlClient().query({query:gn,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 rt(a)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}async getShareActionsForTransaction(e){const A=(P.getMap("transactionOwnerIds")||new Map).get(e)||void 0,n=await x.getShadowGraphqlClient().query({query:rn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e},context:{transactionOwnerId:A}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${e}`);return n.data.transactions[0].transactionShareActions}}class ei{getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(e){this.client=e}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){}async updateTransactionShareActions(){}addValidationCallback(e){}setStepError(e,t,A){}getStepErrors(e){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}}var YA=(c=>(c.SelectFrame="SelectFrame",c.SelectImage="SelectImage",c.Position="Position",c))(YA||{});class PA extends K{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 q.selectVariant(this.step,e.getResource(),t,this.manager,A=>this.setUpdateState(A))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}async selectImage(e,t=!0,A=!0){var n;if(await q.selectImage(this.step,e,this.manager,A),t){const a=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Me.BackgroundRemover)}async canRemoveBackground(){var e,t,A,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((t=(e=this.frameService)==null?void 0:e.getImageData())!=null&&t.src)&&!((n=(A=this.frameService)==null?void 0:A.getImageData())!=null&&n.svg)}async removeBackgroundFromImageSelection(e=!0){var a;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const t=await this.getOriginalImageSelection();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const A=await k.removeBackgroundFromAsset(t);e&&await q.selectImage(this.step,A,this.manager,!1);const n=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:A.key,useOriginalAsset:!e}}),A}changeColors(e){q.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?q.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e!=null&&e.svg?(await l.generateSVGWithUnknownColors(e.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return q.getUniqueColorCount(this.step,this.manager)}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}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var t,A;const e=(A=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)==null?void 0:A.originalAssetKey;if(e)return k.getLocalOrFromServer(e)}async getBackgroundRemovedImageSelection(){var t,A;const e=(A=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)==null?void 0:A.backgroundRemovedAssetKey;if(e)return k.getLocalOrFromServer(e)}hasOriginalImageSelection(){var e,t;return!!((t=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)!=null&&t.originalAssetKey)}hasBackgroundRemovedImageSelection(){var e,t;return!!((t=(e=this.getFrameStepStorage())==null?void 0:e.framePatternData)!=null&&t.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var e,t;return((t=(e=this.getFrameStepStorage())==null?void 0:e.framePatternData)==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImageSelection(e){var n;const t=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(t.useOriginalAsset===e)return;const A=await this.getOriginalImageSelection();if(!A)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(e)await this.selectImage(A,!1,!1);else{const a=await this.getBackgroundRemovedImageSelection();if(!a)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(a,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:e}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}Object.defineProperty(E,"AspectType",{enumerable:!0,get:()=>l.AspectType}),Object.defineProperty(E,"AssetType",{enumerable:!0,get:()=>l.AssetType}),Object.defineProperty(E,"BringForwardCommand",{enumerable:!0,get:()=>l.BringForwardCommand}),Object.defineProperty(E,"BringToBackCommand",{enumerable:!0,get:()=>l.BringToBackCommand}),Object.defineProperty(E,"BringToFrontCommand",{enumerable:!0,get:()=>l.BringToFrontCommand}),Object.defineProperty(E,"CanvasCommand",{enumerable:!0,get:()=>l.CanvasCommand}),Object.defineProperty(E,"CommandContext",{enumerable:!0,get:()=>l.CommandContext}),Object.defineProperty(E,"CreateElementCommand",{enumerable:!0,get:()=>l.CreateElementCommand}),Object.defineProperty(E,"CreateLayoutCommand",{enumerable:!0,get:()=>l.CreateLayoutCommand}),Object.defineProperty(E,"DeleteElementCommand",{enumerable:!0,get:()=>l.DeleteElementCommand}),Object.defineProperty(E,"FontAlignmentCommand",{enumerable:!0,get:()=>l.FontAlignmentCommand}),Object.defineProperty(E,"FontColorCommand",{enumerable:!0,get:()=>l.FontColorCommand}),Object.defineProperty(E,"FontSizeCommand",{enumerable:!0,get:()=>l.FontSizeCommand}),Object.defineProperty(E,"FontSourceCommand",{enumerable:!0,get:()=>l.FontSourceCommand}),Object.defineProperty(E,"GroupCommand",{enumerable:!0,get:()=>l.GroupCommand}),Object.defineProperty(E,"LayoutElementFactory",{enumerable:!0,get:()=>l.LayoutElementFactory}),Object.defineProperty(E,"LayoutElementType",{enumerable:!0,get:()=>l.LayoutElementType}),Object.defineProperty(E,"MoveCommand",{enumerable:!0,get:()=>l.MoveCommand}),Object.defineProperty(E,"ResizeCommand",{enumerable:!0,get:()=>l.ResizeCommand}),Object.defineProperty(E,"RotateCommand",{enumerable:!0,get:()=>l.RotateCommand}),Object.defineProperty(E,"SendBackwardsCommand",{enumerable:!0,get:()=>l.SendBackwardsCommand}),Object.defineProperty(E,"StepAspectType",{enumerable:!0,get:()=>l.StepAspectType}),Object.defineProperty(E,"StepType",{enumerable:!0,get:()=>l.StepType}),Object.defineProperty(E,"TextChangeCommand",{enumerable:!0,get:()=>l.TextChangeCommand}),Object.defineProperty(E,"UnitOfMeasurement",{enumerable:!0,get:()=>l.UnitOfMeasurement}),Object.defineProperty(E,"UpdateImageSourceCommand",{enumerable:!0,get:()=>l.UpdateImageSourceCommand}),Object.defineProperty(E,"dataUrlFromExternalUrl",{enumerable:!0,get:()=>l.dataUrlFromExternalUrl}),Object.defineProperty(E,"determineCorrectFontSizeAndLines",{enumerable:!0,get:()=>l.determineCorrectFontSizeAndLines}),Object.defineProperty(E,"findElement",{enumerable:!0,get:()=>l.findElement}),Object.defineProperty(E,"frameDataCache",{enumerable:!0,get:()=>l.frameDataCache}),Object.defineProperty(E,"generate",{enumerable:!0,get:()=>l.generate}),Object.defineProperty(E,"generateSVGWithUnknownColors",{enumerable:!0,get:()=>l.generateSVGWithUnknownColors}),Object.defineProperty(E,"getAttributesFromArrayBuffer",{enumerable:!0,get:()=>l.getAttributesFromArrayBuffer}),Object.defineProperty(E,"getAxisAlignedBoundingBox",{enumerable:!0,get:()=>l.getAxisAlignedBoundingBox}),Object.defineProperty(E,"getFrameData",{enumerable:!0,get:()=>l.getFrameData}),Object.defineProperty(E,"getSvgElement",{enumerable:!0,get:()=>l.getSvgElement}),Object.defineProperty(E,"loadFont",{enumerable:!0,get:()=>l.loadFont}),Object.defineProperty(E,"patternImageDataCache",{enumerable:!0,get:()=>l.patternImageDataCache}),Object.defineProperty(E,"registerFetchImplementation",{enumerable:!0,get:()=>l.registerFetchImplementation}),Object.defineProperty(E,"registerWindowImplementation",{enumerable:!0,get:()=>l.registerWindowImplementation}),Object.defineProperty(E,"rehydrateSerializedLayout",{enumerable:!0,get:()=>l.rehydrateSerializedLayout}),Object.defineProperty(E,"setCanvasModule",{enumerable:!0,get:()=>l.setCanvasModule}),Object.defineProperty(E,"svgToDataUrl",{enumerable:!0,get:()=>l.svgToDataUrl}),E.AddonHandle=Me,E.ArrayInput=Ga,E.AssetNotFoundError=X,E.CollectionProduct=He,E.ColorOptionGlobalPropertyHandle=at,E.ConversionDataType=xt,E.ConversionLocation=Pt,E.DigitalContentStepHandle=cA,E.FileUploadGlobalPropertyHandle=mA,E.FlowExecutionNodeResult=fe,E.FlowExecutionResult=MA,E.FlowService=FA,E.FrameService=bt,E.FrameStep=YA,E.FrameStepHandle=PA,E.GlobalPropertyHandle=Re,E.IllustrationStepHandle=tA,E.InformationMessageType=se,E.InformationStepHandle=rA,E.IntegrationProduct=rt,E.IntegrationType=yt,E.LayoutNotFoundError=T,E.MaterialStepHandle=AA,E.MisconfigurationError=de,E.MockWorkflowManager=ei,E.ModelStepHandle=nA,E.ModuleStepHandle=gA,E.ObjectInput=st,E.ObjectInputType=SA,E.OptionGlobalPropertyHandle=nt,E.OptionNotFoundError=Be,E.ParseError=_,E.PictureStepHandle=aA,E.ProductCameraRig=Yt,E.ProductCollection=DA,E.ProductWorkflow=re,E.PromiseCache=te,E.PromiseQueue=Oe,E.QuestionStepHandle=iA,E.QueueablePromise=Je,E.ResourceNotFoundError=$,E.ShapeStepHandle=oA,E.SpiffCommerceClient=yA,E.StakeholderType=Ee,E.StepHandle=K,E.TextGlobalPropertyHandle=QA,E.TextInput=ka,E.TextStepHandle=sA,E.TransactionShareActionType=St,E.Transform=IA,E.TransformCollection=fA,E.UnhandledBehaviorError=G,E.Variant=W,E.WorkflowExperienceEventType=wA,E.WorkflowExperienceImpl=De,E.assetService=k,E.browserColorToHex=zt,E.createDesign=CA,E.designService=Ne,E.digitalContentStepService=Le,E.findPmsColors=Dn,E.frameStepService=q,E.generateCommands=EA,E.generateStateFromDesignInputSteps=Ca,E.getBoundedOffsets=Gt,E.getWorkflow=Ie,E.getWorkflows=ct,E.graphQlManager=x,E.illustrationStepService=Qe,E.matchHexToPms=un,E.materialStepService=Ke,E.modelStepService=je,E.moduleStepService=Ve,E.optionService=L,E.persistenceService=P,E.pictureStepService=We,E.pmsToRgb=hn,E.questionStepService=Xe,E.rgbToPms=Lt,E.setBearerAuthenticationToken=It,E.shapeStepService=oe,E.shortenUrl=Jt,E.spiffCoreConfiguration=j,E.stepAspectValuesToDesignInputSteps=da,E.textStepService=z,E.toast=jt,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
3164
+ `,ce=async c=>{var e;for(const t in c.layouts){const A=c.layouts[t].elements.filter(a=>a.type===l.LayoutElementType.Illustration);for(let a=0;a<A.length;++a){const i=A[a];i.src&&i.svg&&(i.cachedObjectURL=await l.svgObjectURL(i.svg))}const n=c.layouts[t].elements.filter(a=>a.type===l.LayoutElementType.Textbox);for(let a=0;a<n.length;++a){const i=n[a];(e=i.fontData)!=null&&e.assetUrl&&await l.loadFont(i.fontData.assetUrl)}}},Za=async(c,e)=>{var n;const t=await x.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(g=>{g.asset&&k.cacheAsset(g.asset),g.displayImage&&k.cacheAsset(g.displayImage),g.thumbnail&&k.cacheAsset(g.thumbnail),g.material&&k.cacheMaterial(g.material)}),te.set({id:i.option.id},Promise.resolve(i.option)))}),a.finalizeStepConfig||(a.finalizeStepConfig={}),a.finalizeStepConfig.termsMarkdown=a.partner.termsMarkdown}),A},$a=async(c,e)=>{const A=(await e).find(n=>n.id===c);if(!A)throw new Error(`Workflow not found: ${c}`);return A},ct=async(c,e)=>{const t=c.map(o=>te.get({id:o,options:e})),A=c.filter((o,s)=>t[s]===void 0);if(A.length===0)return Promise.all(t);const n=Za(A,e),a=A.map(o=>te.set({id:o,options:e},$a(o,n))),i=t.filter(o=>o!==void 0);return await Promise.all(i.concat(a))},Ie=async(c,e)=>(await ct([c],e))[0],_a=c=>c.sort((e,t)=>e.index-t.index).map(e=>({id:l.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})),gt=(c,e)=>{const t=c.workflowState,A=t?JSON.parse(t):void 0;return A?Object.values(A.layouts).map(n=>n.layout):_a(e.panels)};class yA{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return x.getShadowGraphqlClient().mutate({...t,mutation:an})}catch(A){throw console.error(A),new U("Critical - Unable to synchronize workflow state with server.")}},this.initialized=!1,this.options=e,this.options.applicationKey&&UA(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 22.4.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configureUrls(e,t,A){j.setHubUrl(e),j.setServerUrl(t),j.setServicesApiUrl(A),this.options.applicationKey&&this.getIntegration()}configure(e){j.setHubUrl(e.hubUrl),j.setServerUrl(e.serverUrl),j.setServicesApiUrl(e.servicesApiUrl),this.marketplaceThemeInstallId=e.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=e.marketplaceThemeInstallConfigurationId,e.bearerAuthenticationToken&&It(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return k}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!kA())throw new Error("Application key required to use Flow Service.");return new FA}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");const e=async()=>(await x.getShadowGraphqlClient().query({query:tn,errorPolicy:"all",fetchPolicy:"no-cache"})).data.currentIntegration;return this.activeIntegration=e(),this.activeIntegration}async canUseAddon(e){var t;try{return((t=(await this.getIntegration()).partner.activeAddons)==null?void 0:t.includes(e))??!1}catch(A){return console.error(A),!1}}async authenticateBundleFromLocalStorage(e){var n,a;const t=P.getMap("bundleOwnerIds");if(t!=null&&t.has(e))return Promise.resolve({success:!0,stakeholderType:Ee.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 g=(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(g)return Promise.resolve({success:!0,stakeholderType:g.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(e){var g,d,B,C,w,u;const t=x.getShadowGraphqlClient(),A=await t.query({query:za,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=(g=n.product)==null?void 0:g.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:Ee.Owner});const o=P.getMap("transactionCustomerIds");if(o!=null&&o.has(e)){const h=o.get(e);if(h&&await this.authenticateCustomerId(h)){const m=((C=(B=this.customer)==null?void 0:B.bundleStakeholders)==null?void 0:C.find(M=>{var p,f;return(f=(p=M.bundle)==null?void 0:p.transactions)==null?void 0:f.some(D=>D.id===e)}))||((u=(w=this.customer)==null?void 0:w.stakeholders)==null?void 0:u.find(M=>{var p;return((p=M.transaction)==null?void 0:p.id)===e}));if(m)return Promise.resolve({success:!0,stakeholderType:m.type})}}const r=(await t.query({query:Ka,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=x.getShadowGraphqlClient(),n=(await t.query({query:ja,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!n.id){const s=(i=(await t.mutate({mutation:Va,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=x.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:Wa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data)==null?void 0:o.customerAuthenticate;return i?(this.storeCustomer(i),Dt(n),this.customer=i,!0):!1}async generateVerificationCode(e){await x.getShadowGraphqlClient().mutate({mutation:Xa,variables:{emailAddress:e}})}async verifyCode(e,t){var a,i;const n=(a=(await x.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),Dt(n.loginToken),this.customer={...n,loginToken:void 0},!0}return!1}async getNewBundle(e,t,A){var r,g,d;const a=(d=(await x.getShadowGraphqlClient().mutate({mutation:Qa(((g=(r=A==null?void 0:A.graphql)==null?void 0:r.productCollection)==null?void 0:g.eagerFetchProducts)||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((B,C)=>({key:B[0],value:B[1]})):void 0},fetchPolicy:"no-cache"})).data)==null?void 0:d.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;o.set(a.id,a.bundleOwnerId),P.setMap("bundleOwnerIds",o);const s=new pA(this,a,void 0,void 0,a.bundleOwnerId);return await s.getInitializationPromise(),s}async getExistingBundle(e,t,A,n){var h,Q,m,M,p,f,D,I,S;const a=P.getMap("bundleOwnerIds"),i=a==null?void 0:a.get(e),s=((h=Object.entries(localStorage).find(([y,Y])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken")))==null?void 0:h[0])||"",r=localStorage.getItem(s),g={};r&&!tt(r)&&(g.Authorization=`Bearer ${r}`);const d={bundleOwnerId:i,...g,...(Q=n==null?void 0:n.graphql)==null?void 0:Q.additionalHeaders},B=await x.getShadowGraphqlClient().query({query:Ea(((M=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:M.eagerFetchProducts)||!1),variables:{id:e},fetchPolicy:"no-cache",context:{headers:d}});if(!((p=B.data)!=null&&p.bundles)||((f=B.data)==null?void 0:f.bundles.length)===0||!((D=B.data)!=null&&D.bundles[0]))throw new Error(`Unable to find bundle: ${e}`);const C=(I=B.data)==null?void 0:I.bundles[0],w=P.getMap("bundlePartnerIds")||new Map;w.set(C.id,C.partner.id),P.setMap("bundlePartnerIds",w);const u=new pA(this,C,t,A,i,{additionalHeaders:(S=n==null?void 0:n.graphql)==null?void 0:S.additionalHeaders});return await u.getInitializationPromise(),u}async getBundleStakeholders(){var a;if(!this.customer)throw new Error("Customer not authenticated.");const e=await x.getShadowGraphqlClient().query({query:ua,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,C,w,u;if(!n)return await this.getWorkflowExperienceDeprecated(e,t,A);const a=async()=>{var Q,m,M;const h=x.getShadowGraphqlClient();if(n.type==="transaction"){const{transactionId:p,readOnly:f}=n,D=await h.query({query:Se,variables:{ids:[p]},errorPolicy:"all",fetchPolicy:"no-cache"});if(!((Q=D.data)!=null&&Q.transactions)||D.data.transactions.length===0)throw new U("Existing transaction not found.");const I=(m=D.data)==null?void 0:m.transactions[0];if(!I.workflowId)throw new U("Existing transaction has no workflow ID.");const S=await Ie(I.workflowId);if(!I.product)throw new U("Failed to load transaction, product not available.");return!this.activeIntegration&&((M=I.integrationProduct)!=null&&M.integration)&&(this.activeIntegration=Promise.resolve(I.integrationProduct.integration)),{transaction:I,workflow:S,readOnly:f}}if(n.type==="integration"||n.type==="external"){const p=async()=>{const S=n.type==="integration"?{integrationProductId:n.integrationProductId}:{externalIntegrationId:n.externalIntegrationId,externalProductId:n.externalProductId},y=await h.mutate({mutation:vt,variables:{...S,workflowId:n.workflowId,designName:n.designName,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!y.data||!y.data.transactionCreate)throw new U("Failed to create transaction!");const Y=y.data.transactionCreate;if(!Y.product)throw new U("Failed to create transaction, product not available.");return Y},f=Ie(n.workflowId,n==null?void 0:n.graphql),[D,I]=await Promise.all([p(),f]);return{transaction:D,workflow:I}}throw new U("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 G("State mutation is forbidden in read only mode!")}:async h=>{const m=(P.getMap("transactionOwnerIds")||new Map).get(i.id)||void 0;return this.updateTransactionState({...h,context:{transactionOwnerId:m}})},readOnly:s,workflow:o};if(n.type==="transaction"&&i.workflowState){const h=JSON.parse(i.workflowState);r.layouts=Object.values(h.layouts).map(Q=>Q.layout),await l.rehydrateSerializedLayout(h),await ce(h),r.reloadedState=h}else if(!s&&n.workflowState){const h=JSON.parse(n.workflowState);r.layouts=Object.values(h.layouts).map(Q=>Q.layout),await l.rehydrateSerializedLayout(h),await ce(h),r.reloadedState=h}else r.layouts=gt(r.transaction,r.workflow);if(r.renderableContextService=new ve(r.layouts),n.previewService?(r.previewService=n.previewService,(C=r.product)!=null&&C.modelUrl&&(r.modelContainer=r.previewService.loadModel({model:r.product.modelUrl,contextService:r.renderableContextService}))):(r.previewService=A&&A(o),(w=r.product)!=null&&w.modelUrl&&(r.modelContainer=(u=r.previewService)==null?void 0:u.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 g=new De(this,r);return await g.getWorkflowManager().getInitializationPromise(),n.type!=="transaction"&&this.customer&&await g.attachCustomerDetails({email:this.customer.emailAddress}),g}async getWorkflowExperiences(e,t){if(e.length===0)throw new U("No options provided!");const A=x.getShadowGraphqlClient(),n=async f=>{var y,Y,v;if(f.length===0)return[];const D=f.map(N=>N.option.transactionId),I=await A.query({query:Se,variables:{ids:D},errorPolicy:"all",fetchPolicy:"no-cache"}),S=I.data.transactions;if(S.length!==f.length){const N=((Y=(y=I.errors)==null?void 0:y[0])==null?void 0:Y.message)||"Unknown error";throw new U(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((v=S[0].integrationProduct)!=null&&v.integration)&&(this.activeIntegration=Promise.resolve(S[0].integrationProduct.integration)),S.map((N,H)=>{var J;return{transaction:N,workflowId:N.workflowId,readOnly:((J=f.find(b=>b.option.transactionId===N.id))==null?void 0:J.option.readOnly)??!1,index:f[H].index}})},a=async f=>{var S,y,Y;if(f.length===0)return[];const D=await A.mutate({mutation:An,variables:{inputs:f.map(v=>({integrationProductId:v.option.type==="integration"?v.option.integrationProductId:void 0,externalIntegrationId:v.option.type==="external"?v.option.externalIntegrationId:void 0,externalProductId:v.option.type==="external"?v.option.externalProductId:void 0,workflowId:v.option.workflowId,designName:v.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),I=(S=D.data)==null?void 0:S.transactionCreateMany;if(!I||I.length===0){const v=((Y=(y=D.errors)==null?void 0:y[0])==null?void 0:Y.message)||"Unknown error";throw new U(`Failed to create transactions: ${v}`)}return I.map((v,N)=>({transaction:v,workflowId:v.workflowId,readOnly:!1,index:f[N].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=ht(o,10),g=ht(s,10),d=(await Promise.all([...r.map(n),...g.map(a)])).flat(),B=[...new Set(d.map(f=>f.workflowId))],C=await ct(B,t),w=new Map(C.map(f=>[f.id,f])),u=P.getMap("transactionOwnerIds")||new Map,h=d.map(async f=>{var J;const{transaction:D,workflowId:I,readOnly:S,index:y}=f,Y=w.get(I),v=e[y];!u.get(D.id)&&D.transactionOwnerId&&u.set(D.id,D.transactionOwnerId);const N=u.get(D.id)||void 0,H={product:D.product,transaction:D,layouts:[],singleVariantsRenderable:(J=v==null?void 0:v.workflowConfiguration)==null?void 0:J.singleVariantsRenderable,stateMutationFunc:S?async()=>{throw new G("State mutation is forbidden in read only mode!")}:async b=>this.updateTransactionState({...b,context:{transactionOwnerId:N}}),readOnly:S,workflow:Y,isReloadedTransaction:v.type==="transaction"};if(v.type==="transaction"&&D.workflowState){const b=JSON.parse(D.workflowState);H.layouts=Object.values(b.layouts||{}).map(V=>V.layout),await l.rehydrateSerializedLayout(b),await ce(b),H.reloadedState=b}else if(!S&&v.workflowState){const b=JSON.parse(v.workflowState);H.layouts=Object.values(b.layouts||{}).map(V=>V.layout),await l.rehydrateSerializedLayout(b),await ce(b),H.reloadedState=b}else H.layouts=gt(H.transaction,H.workflow);return H.renderableContextService=new ve(H.layouts),H.delayWorkflowStateSync=!0,this.initialized=!0,this.experienceOptions=H,{experienceOptions:H,index:y,options:v}});P.setMap("transactionOwnerIds",u);const M=(await Promise.all(h)).sort((f,D)=>f.index-D.index).map(async f=>{const{experienceOptions:D,options:I}=f,S=new De(this,D);return await S.getWorkflowManager().getInitializationPromise(),I.type!=="transaction"&&this.customer&&await S.attachCustomerDetails({email:this.customer.emailAddress}),S}),p=await Promise.all(M);return p.forEach(f=>f.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),p}async initFromIntegrationProduct(e){var i;if(e==="")throw new U("No integration product ID provided.");const A=await x.getShadowGraphqlClient().mutate({mutation:vt,variables:{integrationProductId:e,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},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 U("Failed to create transaction!");const n=A.data.transactionCreate;if(!n.product)throw new U("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,g;if(e==="")throw new U("No transaction ID provided.");const A=x.getShadowGraphqlClient(),n=async()=>{var C,w;const B=(C=(await A.query({query:Se,variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:C.transactions[0];if(!B)throw new U("Failed to read transaction.");if(!B.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(w=B.product.partner)==null?void 0:w.currencyCode,this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async()=>{throw new G("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:Se,variables:{ids:[e]},errorPolicy:"all"})).data)==null?void 0:o.transactions[0];if(!B)throw new U("Failed to read transaction.");if(!B.product)throw new U("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 C=>this.updateTransactionState({...C,context:{transactionOwnerId:i}}),readOnly:t},this.initialized=!0;return}try{const B=(r=(await A.mutate({mutation:nn,variables:{id:e},errorPolicy:"all"})).data)==null?void 0:r.transactionClaim;if(!B)throw new U("Failed to read transaction.");if(!B.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(g=B.product.partner)==null?void 0:g.currencyCode,B.transactionOwnerId&&(a.set(B.id,B.transactionOwnerId),P.setMap("transactionOwnerIds",a)),this.experienceOptions={product:B.product,transaction:B,layouts:[],stateMutationFunc:async C=>this.updateTransactionState({...C,context:{transactionOwnerId:B.transactionOwnerId}}),readOnly:t},this.initialized=!0}catch{throw new U("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 U("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const s=await Ie(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=s,this.experienceOptions.transaction.workflowState){const g=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(g.layouts).map(d=>d.layout),await l.rehydrateSerializedLayout(g),await ce(g),this.experienceOptions.reloadedState=g}this.experienceOptions.previewService=A&&A(s),this.experienceOptions.renderableContextService=new ve(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 De(this,this.experienceOptions);return await r.getWorkflowManager().getInitializationPromise(),r}if(e){const r=(P.getMap("transactionOwnerIds")||new Map).get(this.experienceOptions.transaction.id),g=x.getShadowGraphqlClient().mutate({mutation:on,variables:{workflowId:e,id:this.experienceOptions.transaction.id},context:{transactionOwnerId:r}}),d=Ie(e);if(await Promise.all([g,d]),this.experienceOptions.workflow=await d,t){const C=JSON.parse(t);this.experienceOptions.layouts=Object.values(C.layouts).map(w=>w.layout),await l.rehydrateSerializedLayout(C),await ce(C),this.experienceOptions.reloadedState=C}else this.experienceOptions.layouts=gt(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await d),this.experienceOptions.renderableContextService=new ve(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 De(this,this.experienceOptions);return await B.getWorkflowManager().getInitializationPromise(),B}throw new U("No workflow ID provided.")}getPreviewService(){var e;return(e=this.experienceOptions)==null?void 0:e.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}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 x.getShadowGraphqlClient().query({query:cn,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 rt(n[0])}async getIntegrationProductFromExternalIds(e,t){var i;const a=(i=(await x.getShadowGraphqlClient().query({query:gn,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 rt(a)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}async getShareActionsForTransaction(e){const A=(P.getMap("transactionOwnerIds")||new Map).get(e)||void 0,n=await x.getShadowGraphqlClient().query({query:rn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e},context:{transactionOwnerId:A}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${e}`);return n.data.transactions[0].transactionShareActions}}class ei{getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(e){this.client=e}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){}async updateTransactionShareActions(){}addValidationCallback(e){}setStepError(e,t,A){}getStepErrors(e){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}}var YA=(c=>(c.SelectFrame="SelectFrame",c.SelectImage="SelectImage",c.Position="Position",c))(YA||{});class PA extends K{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 q.selectVariant(this.step,e.getResource(),t,this.manager,A=>this.setUpdateState(A))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}async selectImage(e,t=!0,A=!0){var n;if(await q.selectImage(this.step,e,this.manager,A),t){const a=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Me.BackgroundRemover)}async canRemoveBackground(){var e,t,A,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((t=(e=this.frameService)==null?void 0:e.getImageData())!=null&&t.src)&&!((n=(A=this.frameService)==null?void 0:A.getImageData())!=null&&n.svg)}async removeBackgroundFromImageSelection(e=!0){var a;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const t=await this.getOriginalImageSelection();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const A=await k.removeBackgroundFromAsset(t);e&&await q.selectImage(this.step,A,this.manager,!1);const n=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:A.key,useOriginalAsset:!e}}),A}changeColors(e){q.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?q.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e!=null&&e.svg?(await l.generateSVGWithUnknownColors(e.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return q.getUniqueColorCount(this.step,this.manager)}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}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var t,A;const e=(A=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)==null?void 0:A.originalAssetKey;if(e)return k.getLocalOrFromServer(e)}async getBackgroundRemovedImageSelection(){var t,A;const e=(A=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)==null?void 0:A.backgroundRemovedAssetKey;if(e)return k.getLocalOrFromServer(e)}hasOriginalImageSelection(){var e,t;return!!((t=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)!=null&&t.originalAssetKey)}hasBackgroundRemovedImageSelection(){var e,t;return!!((t=(e=this.getFrameStepStorage())==null?void 0:e.framePatternData)!=null&&t.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var e,t;return((t=(e=this.getFrameStepStorage())==null?void 0:e.framePatternData)==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImageSelection(e){var n;const t=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(t.useOriginalAsset===e)return;const A=await this.getOriginalImageSelection();if(!A)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(e)await this.selectImage(A,!1,!1);else{const a=await this.getBackgroundRemovedImageSelection();if(!a)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(a,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:e}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}Object.defineProperty(E,"AspectType",{enumerable:!0,get:()=>l.AspectType}),Object.defineProperty(E,"AssetType",{enumerable:!0,get:()=>l.AssetType}),Object.defineProperty(E,"BringForwardCommand",{enumerable:!0,get:()=>l.BringForwardCommand}),Object.defineProperty(E,"BringToBackCommand",{enumerable:!0,get:()=>l.BringToBackCommand}),Object.defineProperty(E,"BringToFrontCommand",{enumerable:!0,get:()=>l.BringToFrontCommand}),Object.defineProperty(E,"CanvasCommand",{enumerable:!0,get:()=>l.CanvasCommand}),Object.defineProperty(E,"CommandContext",{enumerable:!0,get:()=>l.CommandContext}),Object.defineProperty(E,"CreateElementCommand",{enumerable:!0,get:()=>l.CreateElementCommand}),Object.defineProperty(E,"CreateLayoutCommand",{enumerable:!0,get:()=>l.CreateLayoutCommand}),Object.defineProperty(E,"DeleteElementCommand",{enumerable:!0,get:()=>l.DeleteElementCommand}),Object.defineProperty(E,"FontAlignmentCommand",{enumerable:!0,get:()=>l.FontAlignmentCommand}),Object.defineProperty(E,"FontColorCommand",{enumerable:!0,get:()=>l.FontColorCommand}),Object.defineProperty(E,"FontSizeCommand",{enumerable:!0,get:()=>l.FontSizeCommand}),Object.defineProperty(E,"FontSourceCommand",{enumerable:!0,get:()=>l.FontSourceCommand}),Object.defineProperty(E,"GroupCommand",{enumerable:!0,get:()=>l.GroupCommand}),Object.defineProperty(E,"LayoutElementFactory",{enumerable:!0,get:()=>l.LayoutElementFactory}),Object.defineProperty(E,"LayoutElementType",{enumerable:!0,get:()=>l.LayoutElementType}),Object.defineProperty(E,"MoveCommand",{enumerable:!0,get:()=>l.MoveCommand}),Object.defineProperty(E,"ResizeCommand",{enumerable:!0,get:()=>l.ResizeCommand}),Object.defineProperty(E,"RotateCommand",{enumerable:!0,get:()=>l.RotateCommand}),Object.defineProperty(E,"SendBackwardsCommand",{enumerable:!0,get:()=>l.SendBackwardsCommand}),Object.defineProperty(E,"StepAspectType",{enumerable:!0,get:()=>l.StepAspectType}),Object.defineProperty(E,"StepType",{enumerable:!0,get:()=>l.StepType}),Object.defineProperty(E,"TextChangeCommand",{enumerable:!0,get:()=>l.TextChangeCommand}),Object.defineProperty(E,"UnitOfMeasurement",{enumerable:!0,get:()=>l.UnitOfMeasurement}),Object.defineProperty(E,"UpdateImageSourceCommand",{enumerable:!0,get:()=>l.UpdateImageSourceCommand}),Object.defineProperty(E,"dataUrlFromExternalUrl",{enumerable:!0,get:()=>l.dataUrlFromExternalUrl}),Object.defineProperty(E,"determineCorrectFontSizeAndLines",{enumerable:!0,get:()=>l.determineCorrectFontSizeAndLines}),Object.defineProperty(E,"findElement",{enumerable:!0,get:()=>l.findElement}),Object.defineProperty(E,"frameDataCache",{enumerable:!0,get:()=>l.frameDataCache}),Object.defineProperty(E,"generate",{enumerable:!0,get:()=>l.generate}),Object.defineProperty(E,"generateSVGWithUnknownColors",{enumerable:!0,get:()=>l.generateSVGWithUnknownColors}),Object.defineProperty(E,"getAttributesFromArrayBuffer",{enumerable:!0,get:()=>l.getAttributesFromArrayBuffer}),Object.defineProperty(E,"getAxisAlignedBoundingBox",{enumerable:!0,get:()=>l.getAxisAlignedBoundingBox}),Object.defineProperty(E,"getFrameData",{enumerable:!0,get:()=>l.getFrameData}),Object.defineProperty(E,"getSvgElement",{enumerable:!0,get:()=>l.getSvgElement}),Object.defineProperty(E,"loadFont",{enumerable:!0,get:()=>l.loadFont}),Object.defineProperty(E,"patternImageDataCache",{enumerable:!0,get:()=>l.patternImageDataCache}),Object.defineProperty(E,"registerFetchImplementation",{enumerable:!0,get:()=>l.registerFetchImplementation}),Object.defineProperty(E,"registerWindowImplementation",{enumerable:!0,get:()=>l.registerWindowImplementation}),Object.defineProperty(E,"rehydrateSerializedLayout",{enumerable:!0,get:()=>l.rehydrateSerializedLayout}),Object.defineProperty(E,"setCanvasModule",{enumerable:!0,get:()=>l.setCanvasModule}),Object.defineProperty(E,"svgToDataUrl",{enumerable:!0,get:()=>l.svgToDataUrl}),E.AddonHandle=Me,E.ArrayInput=Ga,E.AssetNotFoundError=X,E.CollectionProduct=He,E.ColorOptionGlobalPropertyHandle=at,E.ConversionDataType=xt,E.ConversionLocation=Pt,E.DigitalContentStepHandle=cA,E.FileUploadGlobalPropertyHandle=mA,E.FlowExecutionNodeResult=fe,E.FlowExecutionResult=MA,E.FlowService=FA,E.FrameService=bt,E.FrameStep=YA,E.FrameStepHandle=PA,E.GlobalPropertyHandle=Re,E.IllustrationStepHandle=tA,E.InformationMessageType=se,E.InformationStepHandle=rA,E.IntegrationProduct=rt,E.IntegrationType=yt,E.LayoutNotFoundError=T,E.MaterialStepHandle=AA,E.MisconfigurationError=de,E.MockWorkflowManager=ei,E.ModelStepHandle=nA,E.ModuleStepHandle=gA,E.ObjectInput=st,E.ObjectInputType=SA,E.OptionGlobalPropertyHandle=nt,E.OptionNotFoundError=Be,E.ParseError=_,E.PictureStepHandle=aA,E.ProductCameraRig=Yt,E.ProductCollection=DA,E.ProductWorkflow=re,E.PromiseCache=te,E.PromiseQueue=Oe,E.QuestionStepHandle=iA,E.QueueablePromise=Je,E.ResourceNotFoundError=$,E.ShapeStepHandle=oA,E.SpiffCommerceClient=yA,E.StakeholderType=Ee,E.StepHandle=K,E.TextGlobalPropertyHandle=QA,E.TextInput=ka,E.TextStepHandle=sA,E.TransactionShareActionType=St,E.Transform=IA,E.TransformCollection=fA,E.UnhandledBehaviorError=G,E.Variant=W,E.WorkflowExperienceEventType=wA,E.WorkflowExperienceImpl=De,E.assetService=k,E.browserColorToHex=zt,E.createDesign=CA,E.designService=Ne,E.digitalContentStepService=Le,E.findPmsColors=Dn,E.frameStepService=q,E.generateCommands=EA,E.generateStateFromDesignInputSteps=Ca,E.getBoundedOffsets=Gt,E.getWorkflow=Ie,E.getWorkflows=ct,E.graphQlManager=x,E.illustrationStepService=Qe,E.matchHexToPms=un,E.materialStepService=Ke,E.modelStepService=je,E.moduleStepService=Ve,E.optionService=L,E.persistenceService=P,E.pictureStepService=We,E.pmsToRgb=hn,E.questionStepService=Xe,E.rgbToPms=Lt,E.setBearerAuthenticationToken=It,E.shapeStepService=oe,E.shortenUrl=Jt,E.spiffCoreConfiguration=j,E.stepAspectValuesToDesignInputSteps=da,E.textStepService=z,E.toast=jt,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/core",
3
- "version": "22.4.0",
3
+ "version": "22.4.1",
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",