@spiffcommerce/core 34.0.2 → 34.0.3-beta.3987fca8-b016-56d4-a950-f6baef18904a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -4046,6 +4046,7 @@ interface Partner {
4046
4046
  currencyCode?: string;
4047
4047
  customerDetailsPromptMarkdown?: string;
4048
4048
  activeAddons?: AddonHandle[];
4049
+ beta?: boolean;
4049
4050
  }
4050
4051
  declare enum AddonHandle {
4051
4052
  BackgroundRemover = "BackgroundRemover",
package/dist/index.js CHANGED
@@ -197,6 +197,7 @@
197
197
  name
198
198
  activeAddons
199
199
  currencyCode
200
+ beta
200
201
  }
201
202
  }
202
203
  `,We=C.gql`
@@ -2206,7 +2207,7 @@
2206
2207
  }
2207
2208
  }
2208
2209
  }
2209
- `;function Re(n){const t=JSON.parse(atob(n.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const pc=async(n,t)=>{const e={};try{if(!t)throw new Error}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!Re(s)&&(e.Authorization=`Bearer ${s}`)}return(await y.getShadowGraphqlClient().mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:n.map(r=>({name:r.name,layouts:r.layouts,workflowId:r.workflowId,transactionId:r.transactionId,previewImage:r.previewImage,useThreeDimPreview:r.useThreeDimPreview,metadata:r.metadata,selectedVariants:r.selectedVariants}))},context:{headers:e}})).data?.designCreateMany},bn=(n,t,e)=>{const a=i=>{const o={};if(i.type==="Frame"){const s=n[i.stepName],l=i.data;if(!s||!s.image||l.hideImageInCart&&e)return o;o[`${i.stepTitle} image`]=s.image}if(i.type==="Illustration"){const s=n[i.stepName],l=i.data;if(!s||l.hideColorsInCart&&e||!s.colors)return o;if(s.colors.length>0){const c=s.colors.join(", ").toUpperCase();o[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const s=n[i.stepName],l=i.data;if(!s||s.text===void 0||s.text===null||l.hideTextInCart&&e)return o;o[`${i.stepTitle} text`]=s.text}if(i.type==="Text"){const s=n[i.stepName];if(!s)return o;const l=i.data;(!l.hideTextInCart||!e&&s.text!==void 0&&s.text!==null)&&(o[`${i.stepTitle} text`]=s.text),s.color&&(!l.hideColorInCart||!e)&&(o[`${i.stepTitle} color`]=s.color),s.strokeColor&&(!l.hideStrokeInCart||!e)&&(o[`${i.stepTitle} stroke`]=s.strokeColor)}return o},r={};return t.steps.forEach(i=>{Object.assign(r,a(i))}),r},fc=(n,t,e,a)=>{const r={};let i={};a&&(i=a);const s=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of s){if(Object.keys(n).includes(l)){const c=n[l],d=t.steps.find(u=>u.stepTitle===l);r[`${d?.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(r[c]={value:i[c],priceModifier:0})}return r},Cc=(n,t,e,a,r,i,o,s)=>{const l=t.basePrice||0,c=n.priceModifierTotal||0,d=fc(a,e,void 0,i),A=(D.getMap("transactionOwnerIds")||new Map).get(n.id),h={additionalExternalProductId:n.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:n.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:n.designExternalVariants,designProductId:n.externalDesignProductId,designProductVariantId:n.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:n.externalCartProductId,externalCartProductVariantId:n.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:c,processExecutionId:s,quantity:n.quantity,transactionId:n.id,transactionOwnerId:A,weight:t.weight,workflowViewerLink:n.workflowViewerLink||"",workflowViewerReadOnlyLink:n.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),r&&(h.sku=r),h},wc=async(n,t,e,a,r,i,o,s,l,c)=>{c&&(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await n.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const d=n.getPreviewService(),u=t?.finalizeStepConfig?.lookAtAnimation,A=d&&t.showModelOnFinishStep&&!!u,h=l&&bn(l,t,!0),g=l&&bn(l,t,!1),m=async E=>{const I={};let N=0;if(Object.keys(i).length>0)for(const R of Object.keys(i)){const P=i[R],T=t.steps.find(V=>V.stepName===R);for(let V=0;V<P.selections.length;++V){const k=P.selections[V];if(T&&(!E||T.option&&(T.option.variants||[]).length>1&&!T.data.hideSelectionInCart&&!T.data.hideSelectionsInCart)){const W=T.stepTitle;I[W]?I[W].push({id:k.id||"",name:k.name,priceModifier:k.priceModifier}):I[W]=[{id:k.id||"",name:k.name,priceModifier:k.priceModifier}]}N+=k.priceModifier}}return[I,N]},[p]=await m(!0),f=Object.fromEntries(Object.keys(p).map(E=>[E,p[E].map(I=>I.id)])),[S]=await m(!1),w=Object.fromEntries(Object.keys(S).map(E=>[E,S[E].map(I=>I.id)]));let x=await s(A,r.id);if(x){const E=await(await rt(x)).blob();x=(await U.uploadAsset({name:`${r.id}-preview-image.png`,blob:E},ee.Image,!0,!1)).fileLink}return{designDetails:(()=>{const E={name:o,layouts:e.map(I=>({index:I.index,panelId:I.panelId})),workflowId:t.id,transactionId:r.id,useThreeDimPreview:!!A,previewImage:x};if(g){const I=[];for(const[N,R]of Object.entries(g))I.push({key:N,value:R});E.metadata=I}if(f){const I=[];for(const[N,R]of Object.entries(w))I.push({key:N,ids:R});E.selectedVariants=I}return E})(),cartSelectionsWithPrices:p,cartMetadata:h}},qr=async(n,t)=>{await Promise.all(n.map(async o=>{await o.workflowManager.outstandingRequestsPromise()}));const a=await(async()=>{const o=y.getShadowGraphqlClient(),s=await Promise.all(n.map(async u=>({id:u.transaction.id,hash:await u.workflowManager.getStateHash()}))),c=pa(s,100),d=[];for(const u of c){const A=await o.query({query:Vo,variables:{items:u},fetchPolicy:"no-cache",errorPolicy:"all"});if(A.errors&&A.errors.length>0)return s.map(h=>h.id);d.push(...A.data?.transactionConfirmWorkflowStates??[])}return d})(),r=await Promise.all(n.map(async o=>await wc(o.workflowManager,o.workflow,o.layouts,o.getReducerState,o.transaction,o.workflowSelections,o.designName,t??(()=>Promise.resolve(void 0)),o.workflowMetadata,a.includes(o.transaction.id)))),i=await pc(r.map(o=>o.designDetails));if(!i)throw new Error("Failed to create designs");return i.map((o,s)=>{const l=n[s],c=r[s],d=o.transaction;return Cc(d,l.product,l.workflow,c.cartSelectionsWithPrices,o.sku,c.cartMetadata,d.previewImageLink,o.processExecution?.id)})};class yc{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=D.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new Q("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(r=>r.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(r=>r(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),r=a.find(i=>i.transactionId===t);if(!r)throw new Error(`No saved design for transaction ${t}.`);r.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){D.set(this.localPersistenceKey,JSON.stringify(t));return}throw new Q("Unexpected storage method requested")}}const xe=new yc,Sc=C.gql`
2210
+ `;function Re(n){const t=JSON.parse(atob(n.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const pc=async(n,t)=>{const e={};try{if(t){const i=await t.loggedInBearerToken();e.Authorization=`Bearer ${i}`}else throw new Error}catch{const s=Object.entries(localStorage).find(([c,d])=>c.startsWith("CognitoIdentityServiceProvider")&&c.endsWith("idToken"))?.[0]||"",l=localStorage.getItem(s);l&&!Re(l)&&(e.Authorization=`Bearer ${l}`)}return(await t.getIntegration()).partner.beta&&(e["X-Spiff-Beta"]="true"),(await y.getShadowGraphqlClient().mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:n.map(i=>({name:i.name,layouts:i.layouts,workflowId:i.workflowId,transactionId:i.transactionId,previewImage:i.previewImage,useThreeDimPreview:i.useThreeDimPreview,metadata:i.metadata,selectedVariants:i.selectedVariants}))},context:{headers:e}})).data?.designCreateMany},bn=(n,t,e)=>{const a=i=>{const o={};if(i.type==="Frame"){const s=n[i.stepName],l=i.data;if(!s||!s.image||l.hideImageInCart&&e)return o;o[`${i.stepTitle} image`]=s.image}if(i.type==="Illustration"){const s=n[i.stepName],l=i.data;if(!s||l.hideColorsInCart&&e||!s.colors)return o;if(s.colors.length>0){const c=s.colors.join(", ").toUpperCase();o[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const s=n[i.stepName],l=i.data;if(!s||s.text===void 0||s.text===null||l.hideTextInCart&&e)return o;o[`${i.stepTitle} text`]=s.text}if(i.type==="Text"){const s=n[i.stepName];if(!s)return o;const l=i.data;(!l.hideTextInCart||!e&&s.text!==void 0&&s.text!==null)&&(o[`${i.stepTitle} text`]=s.text),s.color&&(!l.hideColorInCart||!e)&&(o[`${i.stepTitle} color`]=s.color),s.strokeColor&&(!l.hideStrokeInCart||!e)&&(o[`${i.stepTitle} stroke`]=s.strokeColor)}return o},r={};return t.steps.forEach(i=>{Object.assign(r,a(i))}),r},fc=(n,t,e,a)=>{const r={};let i={};a&&(i=a);const s=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of s){if(Object.keys(n).includes(l)){const c=n[l],d=t.steps.find(u=>u.stepTitle===l);r[`${d?.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(r[c]={value:i[c],priceModifier:0})}return r},Cc=(n,t,e,a,r,i,o,s)=>{const l=t.basePrice||0,c=n.priceModifierTotal||0,d=fc(a,e,void 0,i),A=(D.getMap("transactionOwnerIds")||new Map).get(n.id),h={additionalExternalProductId:n.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:n.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:n.designExternalVariants,designProductId:n.externalDesignProductId,designProductVariantId:n.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:n.externalCartProductId,externalCartProductVariantId:n.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:c,processExecutionId:s,quantity:n.quantity,transactionId:n.id,transactionOwnerId:A,weight:t.weight,workflowViewerLink:n.workflowViewerLink||"",workflowViewerReadOnlyLink:n.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),r&&(h.sku=r),h},wc=async(n,t,e,a,r,i,o,s,l,c)=>{c&&(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await n.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const d=n.getPreviewService(),u=t?.finalizeStepConfig?.lookAtAnimation,A=d&&t.showModelOnFinishStep&&!!u,h=l&&bn(l,t,!0),g=l&&bn(l,t,!1),m=async E=>{const I={};let N=0;if(Object.keys(i).length>0)for(const R of Object.keys(i)){const P=i[R],T=t.steps.find(V=>V.stepName===R);for(let V=0;V<P.selections.length;++V){const k=P.selections[V];if(T&&(!E||T.option&&(T.option.variants||[]).length>1&&!T.data.hideSelectionInCart&&!T.data.hideSelectionsInCart)){const W=T.stepTitle;I[W]?I[W].push({id:k.id||"",name:k.name,priceModifier:k.priceModifier}):I[W]=[{id:k.id||"",name:k.name,priceModifier:k.priceModifier}]}N+=k.priceModifier}}return[I,N]},[p]=await m(!0),f=Object.fromEntries(Object.keys(p).map(E=>[E,p[E].map(I=>I.id)])),[S]=await m(!1),w=Object.fromEntries(Object.keys(S).map(E=>[E,S[E].map(I=>I.id)]));let x=await s(A,r.id);if(x){const E=await(await rt(x)).blob();x=(await U.uploadAsset({name:`${r.id}-preview-image.png`,blob:E},ee.Image,!0,!1)).fileLink}return{designDetails:(()=>{const E={name:o,layouts:e.map(I=>({index:I.index,panelId:I.panelId})),workflowId:t.id,transactionId:r.id,useThreeDimPreview:!!A,previewImage:x};if(g){const I=[];for(const[N,R]of Object.entries(g))I.push({key:N,value:R});E.metadata=I}if(f){const I=[];for(const[N,R]of Object.entries(w))I.push({key:N,ids:R});E.selectedVariants=I}return E})(),cartSelectionsWithPrices:p,cartMetadata:h}},qr=async(n,t)=>{await Promise.all(n.map(async s=>{await s.workflowManager.outstandingRequestsPromise()}));const a=await(async()=>{const s=y.getShadowGraphqlClient(),l=await Promise.all(n.map(async A=>({id:A.transaction.id,hash:await A.workflowManager.getStateHash()}))),d=pa(l,100),u=[];for(const A of d){const h=await s.query({query:Vo,variables:{transactions:A},fetchPolicy:"no-cache",errorPolicy:"all"});if(h.errors&&h.errors.length>0)return l.map(g=>g.id);u.push(...h.data?.transactionConfirmWorkflowStates??[])}return u})(),r=await Promise.all(n.map(async s=>await wc(s.workflowManager,s.workflow,s.layouts,s.getReducerState,s.transaction,s.workflowSelections,s.designName,t??(()=>Promise.resolve(void 0)),s.workflowMetadata,a.includes(s.transaction.id)))),i=n[0].workflowManager.getClient(),o=await pc(r.map(s=>s.designDetails),i);if(!o)throw new Error("Failed to create designs");return o.map((s,l)=>{const c=n[l],d=r[l],u=s.transaction;return Cc(u,c.product,c.workflow,d.cartSelectionsWithPrices,s.sku,d.cartMetadata,u.previewImageLink,s.processExecution?.id)})};class yc{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=D.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new Q("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(r=>r.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(r=>r(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),r=a.find(i=>i.transactionId===t);if(!r)throw new Error(`No saved design for transaction ${t}.`);r.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){D.set(this.localPersistenceKey,JSON.stringify(t));return}throw new Q("Unexpected storage method requested")}}const xe=new yc,Sc=C.gql`
2210
2211
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
2211
2212
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
2212
2213
  id
@@ -2518,7 +2519,7 @@
2518
2519
  }
2519
2520
  }
2520
2521
  }
2521
- `;class Hc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Yc{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Yc;class ei{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Mi(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=cn.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(cn.code(e)?.code==="CLP")return"USD0,0"}}const Pn=new ei;class ai{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Pn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Pn.getPrecisionForCurrency(e))}}const Jc=async(n,t)=>{const e=await y.getShadowGraphqlClient().query({query:Ko(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&U.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&U.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&U.cacheAsset(o.asset),o.thumbnail&&U.cacheAsset(o.thumbnail),o.material&&U.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Kc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},rn=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Jc(a,t),i=a.map(s=>$t.set({id:s,options:t},Kc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},ni=async(n,t)=>(await rn([n],t))[0],_c=async n=>{const t=await y.getShadowGraphqlClient().query({query:To,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class Xc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Qo})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ki(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 34.0.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&_n(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!_i())throw new Error("Application key required to use Flow Service.");return new Xr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new ai(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=ri(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(D.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ae.Owner});const a=D.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((D.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:_o,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(D.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ae.Owner});const s=D.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:Xo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=D.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),D.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),r=(await e.query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:jc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||Re(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Wc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:ql(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=D.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),D.setMap("bundlePartnerIds",o);const s=D.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),D.setMap("bundleOwnerIds",s);const l=new Bn(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r,i){const s=D.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const p=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(p);f&&!Re(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...r?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:$l(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=D.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),D.setMap("bundlePartnerIds",A);const h=new Bn(this,u,e,a,s,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:r?.readonly},i);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,r){const o={...await ii(t),...r?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Gl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=D.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),D.setMap("bundlePartnerIds",c);const d=D.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),D.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:ec(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Ul,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],r=D.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),D.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),a[0]}async getWorkflowExperiences(t,e,a,r){if(t.length===0)throw new mt("No options provided!");const i=t.map((P,T)=>({option:P,index:T})),o=i.filter(P=>P.option.type==="transaction"),s=i.filter(P=>P.option.type==="integration"||P.option.type==="external"||P.option.type==="blank"),l=50,c=pa(o,l),d=pa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async P=>{if(P.length===0)return[];const T=P.map(W=>W.option.transactionId),V=await A.query({query:No,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=V.data.transactions;if(u=u+k.length,r&&r(u,o.length),k.length!==P.length){const W=V.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${W}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((W,Xe)=>({transaction:W,workflowId:W.workflowId,readOnly:P.find(At=>At.option.transactionId===W.id)?.option.readOnly??!1,index:P[Xe].index}))},g=async P=>{if(P.length===0)return[];const T=await A.mutate({mutation:Mo,variables:{inputs:P.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),V=T.data?.transactionCreateMany;if(!V||V.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${k}`)}return u=u+V.length,r&&r(u,o.length),V.map((k,W)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:P[W].index}))},m=(await Promise.all([...c.map(h),...d.map(g)])).flat(),p=[...new Set(m.map(P=>P.transaction.integrationProductId))].filter(P=>P!==void 0),f=[...new Set(m.map(P=>P.workflowId))].filter(P=>P!==void 0),[S,w]=await Promise.all([(async()=>p.length>0?await _c(p):[])(),(async()=>f.length>0?await rn(f,e):[])()]),x=new Map(S.map(P=>[P.id,P])),v=new Map(w.map(P=>[P.id,P])),E=m.map(async P=>{const{transaction:T,workflowId:V,readOnly:k,index:W}=P,Xe=V?v.get(V):void 0,At=t[W];if(T.integrationProductId){const ot=x.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=D.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),D.setMap("transactionOwnerIds",fe));const Ze=fe.get(T.id)||void 0,mi=new Hc({onMutate:()=>({context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:Xe,transaction:T,singleVariantsRenderable:At?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new Q("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>mi,readOnly:k,isReloadedTransaction:At.type==="transaction"};if(At.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Ia(ot),Ce.reloadedState=ot}else if(!k&&At.workflowState){const ot=JSON.parse(At.workflowState);await Ia(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:W,options:At}}),N=(await Promise.all(E)).sort((P,T)=>P.index-T.index);let R=[];for(const P of N){const{experienceOptions:T,options:V}=P,k=new Gr(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),V.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=D.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),D.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:zo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new ka(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:qo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new ka(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(D.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:Lo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ns,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const ri=async(n,t)=>(await y.getShadowGraphqlClient().query({query:ts,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Zc=async n=>{const e=await y.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},td=async(n,t)=>(await y.getShadowGraphqlClient().query({query:Zo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,ed=async n=>(await y.getShadowGraphqlClient().query({query:as,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ad=async n=>(await y.getShadowGraphqlClient().query({query:es,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function ii(n){const e=D.getMap("bundleOwnerIds")?.get(n),a={};try{const r=await this.loggedInBearerToken();a.Authorization=`Bearer ${r}`}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!Re(s)&&(a.Authorization=`Bearer ${s}`)}return{bundleOwnerId:e,...a}}const nd=async n=>{const t=await ii(n),e=await y.getShadowGraphqlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)};function oi(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Be(n.x,t.width-c,0),s.y=Be(n.y,t.height-d,0),s}const o=n;return o.x=Be(o.x,-r,t.width),o.y=Be(o.y,-i,t.height),o}function Be(n,t,e){return Math.min(Math.max(n,t),e)}class si{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=On(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=je(this.imageData.svg,this.imageData.colors||{},!1);return qe(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new Q("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=oi(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,r,i){if(!a||a.length===0||a.some(l=>!l))throw new Q("Frame data not set. This is a bug");if(!this.workflowManager)throw new Q("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new $([new zs(l,e,t[d]),new qs(l,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=qa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class rd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var li=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(li||{});class ci extends Z{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new si(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return gt.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await gt.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon($e.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await U.removeBackgroundFromAsset(e);t&&await gt.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){gt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?gt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await it(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return gt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const id=C.gql`
2522
+ `;class Hc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Yc{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Yc;class ei{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Mi(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=cn.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(cn.code(e)?.code==="CLP")return"USD0,0"}}const Pn=new ei;class ai{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Pn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Pn.getPrecisionForCurrency(e))}}const Jc=async(n,t)=>{const e=await y.getShadowGraphqlClient().query({query:Ko(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&U.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&U.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&U.cacheAsset(o.asset),o.thumbnail&&U.cacheAsset(o.thumbnail),o.material&&U.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Kc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},rn=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Jc(a,t),i=a.map(s=>$t.set({id:s,options:t},Kc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},ni=async(n,t)=>(await rn([n],t))[0],_c=async n=>{const t=await y.getShadowGraphqlClient().query({query:To,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class Xc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Qo})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ki(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 34.0.3"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&_n(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!_i())throw new Error("Application key required to use Flow Service.");return new Xr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new ai(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=ri(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(D.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ae.Owner});const a=D.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((D.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:_o,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(D.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ae.Owner});const s=D.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:Xo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=D.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),D.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),r=(await e.query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:jc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||Re(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Wc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:ql(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=D.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),D.setMap("bundlePartnerIds",o);const s=D.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),D.setMap("bundleOwnerIds",s);const l=new Bn(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r,i){const s=D.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const p=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(p);f&&!Re(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...r?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:$l(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=D.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),D.setMap("bundlePartnerIds",A);const h=new Bn(this,u,e,a,s,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:r?.readonly},i);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,r){const o={...await ii(t),...r?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Gl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=D.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),D.setMap("bundlePartnerIds",c);const d=D.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),D.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:ec(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Ul,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],r=D.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),D.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),a[0]}async getWorkflowExperiences(t,e,a,r){if(t.length===0)throw new mt("No options provided!");const i=t.map((P,T)=>({option:P,index:T})),o=i.filter(P=>P.option.type==="transaction"),s=i.filter(P=>P.option.type==="integration"||P.option.type==="external"||P.option.type==="blank"),l=50,c=pa(o,l),d=pa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async P=>{if(P.length===0)return[];const T=P.map(W=>W.option.transactionId),V=await A.query({query:No,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=V.data.transactions;if(u=u+k.length,r&&r(u,o.length),k.length!==P.length){const W=V.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${W}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((W,Xe)=>({transaction:W,workflowId:W.workflowId,readOnly:P.find(At=>At.option.transactionId===W.id)?.option.readOnly??!1,index:P[Xe].index}))},g=async P=>{if(P.length===0)return[];const T=await A.mutate({mutation:Mo,variables:{inputs:P.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),V=T.data?.transactionCreateMany;if(!V||V.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${k}`)}return u=u+V.length,r&&r(u,o.length),V.map((k,W)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:P[W].index}))},m=(await Promise.all([...c.map(h),...d.map(g)])).flat(),p=[...new Set(m.map(P=>P.transaction.integrationProductId))].filter(P=>P!==void 0),f=[...new Set(m.map(P=>P.workflowId))].filter(P=>P!==void 0),[S,w]=await Promise.all([(async()=>p.length>0?await _c(p):[])(),(async()=>f.length>0?await rn(f,e):[])()]),x=new Map(S.map(P=>[P.id,P])),v=new Map(w.map(P=>[P.id,P])),E=m.map(async P=>{const{transaction:T,workflowId:V,readOnly:k,index:W}=P,Xe=V?v.get(V):void 0,At=t[W];if(T.integrationProductId){const ot=x.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=D.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),D.setMap("transactionOwnerIds",fe));const Ze=fe.get(T.id)||void 0,mi=new Hc({onMutate:()=>({context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:Xe,transaction:T,singleVariantsRenderable:At?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new Q("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:Ze,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>mi,readOnly:k,isReloadedTransaction:At.type==="transaction"};if(At.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Ia(ot),Ce.reloadedState=ot}else if(!k&&At.workflowState){const ot=JSON.parse(At.workflowState);await Ia(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:W,options:At}}),N=(await Promise.all(E)).sort((P,T)=>P.index-T.index);let R=[];for(const P of N){const{experienceOptions:T,options:V}=P,k=new Gr(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),V.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=D.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),D.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:zo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new ka(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:qo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new ka(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(D.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:Lo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ns,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const ri=async(n,t)=>(await y.getShadowGraphqlClient().query({query:ts,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Zc=async n=>{const e=await y.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},td=async(n,t)=>(await y.getShadowGraphqlClient().query({query:Zo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,ed=async n=>(await y.getShadowGraphqlClient().query({query:as,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ad=async n=>(await y.getShadowGraphqlClient().query({query:es,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function ii(n){const e=D.getMap("bundleOwnerIds")?.get(n),a={};try{const r=await this.loggedInBearerToken();a.Authorization=`Bearer ${r}`}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!Re(s)&&(a.Authorization=`Bearer ${s}`)}return{bundleOwnerId:e,...a}}const nd=async n=>{const t=await ii(n),e=await y.getShadowGraphqlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)};function oi(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Be(n.x,t.width-c,0),s.y=Be(n.y,t.height-d,0),s}const o=n;return o.x=Be(o.x,-r,t.width),o.y=Be(o.y,-i,t.height),o}function Be(n,t,e){return Math.min(Math.max(n,t),e)}class si{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=On(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=je(this.imageData.svg,this.imageData.colors||{},!1);return qe(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new Q("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=oi(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,r,i){if(!a||a.length===0||a.some(l=>!l))throw new Q("Frame data not set. This is a bug");if(!this.workflowManager)throw new Q("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new $([new zs(l,e,t[d]),new qs(l,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=qa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class rd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var li=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(li||{});class ci extends Z{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new si(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return gt.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await gt.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon($e.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await U.removeBackgroundFromAsset(e);t&&await gt.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){gt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?gt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await it(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return gt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const id=C.gql`
2522
2523
  query GetLoggedInCustomer($email: String!) {
2523
2524
  customer(emailAddress: $email) {
2524
2525
  id