@spiffcommerce/core 32.3.1-beta.0913bb04-4304-5dae-95b3-20ea61cba9ab → 32.3.1-beta.535b64df-4d00-52c9-95fe-209938040cab
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 +5 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
@@ -1819,6 +1819,9 @@ declare class Transform {
|
|
1819
1819
|
}
|
1820
1820
|
declare const getProductCollections: (ids: string[]) => Promise<ProductCollection[] | undefined>;
|
1821
1821
|
|
1822
|
+
interface BundleIntegrationProductsAddedEventData {
|
1823
|
+
integrationProductIds: string[];
|
1824
|
+
}
|
1822
1825
|
interface ConditionalGlobalPropertiesChangedEventData {
|
1823
1826
|
globalProperties: GlobalPropertyHandle[];
|
1824
1827
|
}
|
@@ -1836,6 +1839,7 @@ interface WorkflowExperienceAddedEventData {
|
|
1836
1839
|
interface WorkflowExperienceRemovedEventData extends WorkflowExperienceAddedEventData {
|
1837
1840
|
}
|
1838
1841
|
type BundleEventMap = {
|
1842
|
+
"bundle-integration-products-added": BundleIntegrationProductsAddedEventData;
|
1839
1843
|
"conditional-global-properties-changed": ConditionalGlobalPropertiesChangedEventData;
|
1840
1844
|
"global-properties-mandatory-changed": GlobalPropertiesMandatoryChangedEventData;
|
1841
1845
|
"workflow-experience-hover-enter": WorkflowExperienceHoverEventData;
|
@@ -1844,7 +1848,7 @@ type BundleEventMap = {
|
|
1844
1848
|
"workflow-experience-removed": WorkflowExperienceRemovedEventData;
|
1845
1849
|
};
|
1846
1850
|
type BundleEventType = keyof BundleEventMap;
|
1847
|
-
type BundleEventData = WorkflowExperienceHoverEventData | ConditionalGlobalPropertiesChangedEventData | WorkflowExperienceAddedEventData;
|
1851
|
+
type BundleEventData = BundleIntegrationProductsAddedEventData | WorkflowExperienceHoverEventData | ConditionalGlobalPropertiesChangedEventData | WorkflowExperienceAddedEventData;
|
1848
1852
|
type BundleEvent<K extends BundleEventType = BundleEventType> = BundleEventMap[K];
|
1849
1853
|
|
1850
1854
|
/**
|
package/dist/index.js
CHANGED
@@ -2443,7 +2443,7 @@
|
|
2443
2443
|
/>
|
2444
2444
|
</svg>
|
2445
2445
|
`,h={"spiff-fill-shape":{browserValue:o.color||"#000000"}},m=M();return new z({colors:h,id:m,svg:u,type:F.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(s)}catch(c){return console.error(c),[]}},Yl=async(n,t,e)=>{const a=[],i=t.type===E.ProductOverlay?e||t.data.asset?.fileLink||"":t.data.asset?.fileLink||"",s=i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?F.Image:(i.endsWith(".svg"),F.Illustration),l=t.data.regions;if(s==="image")try{l.forEach(c=>{const d=n.find(A=>A.panelId===c.panelId);if(!d)throw new W(c);const u={id:M(),src:i,type:s,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===E.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new z(u,d))})}catch(c){console.error(c)}else{const c=await tt(i,!0),d=u=>{const A=/<svg.*?<\/svg>/s,h=u.match(A)||[],m=h?.length>0?h[0]:"",f=lt().parseFromString(m,"image/svg+xml").firstElementChild;if(!f)throw new bt("Failed to read SVG.");return Ve(f),St().serializeToString(f)};l.forEach(u=>{const A=n.find(m=>m.panelId===u.panelId);if(!A)throw new W(u);const h={id:M(),src:i,asset_key:i,svg:d(c),colors:{},type:s,y:u.top,x:u.left,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,scaleX:1,scaleY:1,rotation:u.rotation,productOverlay:t.type===E.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new z(h,A))})}return a},Jl=async(n,t,e,a)=>{const r=[],i=e.data,o=30,s=g=>g.vertical?"center":g.textAlign||"center",l=()=>{const g=a.option;if(!g)return;const f=g.variants?.find(I=>I.id===i.fontVariantId)||Ae(g);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const w=f.asset.fileLink;if(w)return w},d=await(async()=>{const g=l();if(!g)return;const f=await xt(g);return{assetUrl:g,name:f.names.fullName.en}})(),u=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",i.text):i.text)||"",A=ke(u,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async g=>{const f=g.colorOption;return f?j.getDefaultVariant(f)?.color:void 0},m=i.color||await h(a.data),p=a.data.regions;for(const g of p){const f=n.find(I=>I.panelId===g.panelId);if(!f)continue;const w={stepName:e.name,id:M(),align:s(a.data),curved:a.data.curved,fill:i.color||m||"#000000",fontData:d,fontSize:a.data.size||o,height:g.height,layer:g.layer,layerIndex:g.layerIndex,paths:a.data.paths,rotation:g.rotation,text:A,type:F.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:g.width,x:g.left,y:g.top};if(d){const[I,x]=Kt(a.data.size||o,d,g,[ke(A,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});r.push(new z({...w,fontSize:I,text:w.curved?w.text:(x||[]).join(`
|
2446
|
-
`)},f))}else r.push(new z(w,f))}return r},Kl=(n,t)=>n.conditions?n.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const r=a.selectedVariants;return e.requiredVariantSelections.some(i=>r.find(o=>o.id===i)!==void 0)}return!1}):!0,Nr=async(n,t,e,a)=>{const r=[],i={};for(const o of n){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case E.DigitalContent:r.push(...await zl(e,o,s));break;case E.Frame:case E.Photo:r.push(...await ql(e,i,o,s));break;case E.Illustration:r.push(...await Gl(e,i,o,s));break;case E.Module:r.push(...await jl(e,o,s));break;case E.Picture:r.push(...await Wl(e,i,o,s));break;case E.Shape:r.push(...await Hl(e,i,o,s));break;case E.Text:r.push(...await Jl(e,i,o,s));break}}for(const o of t.steps)o.type!==E.SilentIllustration&&o.type!==E.ProductOverlay||Kl(o,i)&&r.push(...await Yl(e,o,a));return r};class _l{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new tc(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Xl=()=>new Promise((n,t)=>{try{const a=ft().getContext("webgl2");n(!!a)}catch{n(!1)}}),Zl=Xl();class tc{constructor(t,e,a,r,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Ma(2),this.id=t,this.name=e,this.service=a,this.panelSize=r,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Bt(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new ec(this.getID(),a,await Zl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class ec extends ka{constructor(t,e,a,r,i,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=r,this.layouts=i,this.getWorkflowManager=o}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,r=e/t.height,i=Math.min(a,r);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(m=>m.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,r=t.layoutState.layout.height,i=a===1||r===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=i.width,s=i.height;let l,c;if(this.nonPOTSupport){const m=o/s;a/r<m?(l=o,c=r*(o/a)):(l=a*(s/r),c=s);const g=this.resizeFit({width:l,height:c});l=g.width,c=g.height}else l=i.width,c=i.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),u=je(t.layoutState.layout,e,{renderingConfiguration:{purpose:Nt.ThreeD,templatingContext:d}}),A=Rn(u),h=await ba.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:ft,createImage:le,DOMParser:xa(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const ac=(n,t)=>{const e=[];return n.forEach(a=>{const r=t.steps.find(i=>i.stepName===a.stepName);r?.type===E.Text&&a.stepAspectType==="Text"&&e.push({name:r.stepName,data:{text:a.value}})}),e},nc=async(n,t,e,a)=>{let r={serializableWorkflow:{steps:[]},layouts:{}};r=new R(e.map(l=>new Oa(l))).apply(r);const o=await Nr(n,t,e,a);return new R(o).apply(r)};class rc{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(e=>this.getHandle(e)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const r=e.aspects.find(i=>i.name===a.targetAspectName);return r?a.requiredVariantSelections.some(i=>i===r.value):!1})}async createHandle(t){switch(t.type){case L.FileUpload:return new Qr(this.bundle,t).initialize();case L.ColorOption:return new ya(this.bundle,t,t.entityId?await j.getOption(t.entityId):void 0);case L.Option:{const e=t.entityId?await j.getOption(t.entityId):void 0;return e?.type==="Color"?new ya(this.bundle,t,e):new ja(this.bundle,t,e)}case L.Text:return new Rr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class We{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(r=>r.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Qr extends We{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await j.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await tt(t?.fileLink),a=await Qa(t?.fileLink),r=a.width,i=a.height,o=await ot(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:r,height:i,aspect:r/i,svg:o.svg,colors:o.colors};dt.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Qe.BackgroundRemover)}async removeBackgroundFromImage(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.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),r=await O.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:r.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,r.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(r,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),r}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return O.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Le(ze(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return O.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return O.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),r=a.getAspectStorage(this.property.name);if(r?.useOriginalAsset===t)return;const i={...r,useOriginalAsset:t},o=t?r?.originalAssetKey:r?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",i)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await O.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(r){if(this.updateSharedStepStorage({...r}),r.colors){const i=new Map(r.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(a)});const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...r,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,r=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,r)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(r=>{if(r.getOverrideGlobalPropertyConfiguration(this.property.type))return;r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(r.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Rr extends We{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const r=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(r)}}class ja extends We{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new rt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new rt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new rt(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new rt(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(r=>r.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const r=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(r)}}class ya extends ja{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(i=>i.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;r&&this.setCustomColor(r)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(o=>{switch(o.getType()){case E.Shape:return o.selectVariant(t);case E.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getCurrentVariant()?.getColor()&&this.getCurrentVariant().getColor().toLowerCase()==="#custom"&&this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const ic=(n,t,e,a)=>n.flatMap(r=>r.getSteps()).filter(r=>r.getGlobalPropertyAspects(t).includes(e)&&r.getType()===a),oc=(n,t,e)=>{const r=ic(n,t,e,E.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...r)};function Sa(n,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!lc(a))return a;if(Array.isArray(a))return Sa(a,t);let r={};for(const[i,o]of Object.entries(a))r[i]=sc(o)?o:Sa(o,t);return mi(r,t)}return Array.isArray(n)?n.map(e):e(n)}function sc(n){return n==null}function lc(n){return typeof n=="object"&&!Array.isArray(n)&&n!==null}function Or(n){const t=new Map;return n?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function ve(n){return Sa(n,["__typename"])}class cc{constructor(t,e,a,r,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=ve(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=ve(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=r}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=Or(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Bt(this.globalPropertyState);this.globalPropertyState={...ve(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(r=>r.name===t&&r.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,r){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 i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=Bt(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(r){const l=s.find(c=>c.channel===r);if(l)l.value=e,l.type=i.type,l.channel=r,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(r===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r})}}else{const l=s[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r});xe(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(t,e,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 r=this.configuration.aspects.find(s=>s.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Bt(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=r.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=r.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:r.type,storage:e!==null?e:void 0,channel:a});xe(i,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await v.getShadowGraphqlClient().mutate({mutation:Ys,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case L.FileUpload:{a.fileUpload=e.storage;break}case L.Option:{a.option=e.storage;break}case L.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=ve(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await v.getShadowGraphqlClient().mutate({mutation:Hs,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class dc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const r=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=r.position,i.rotation=r.rotation,i.scale=r.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const r=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===r);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:r,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,r=this.state.transactions.find(l=>l.transactionId===a),i=r?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,r.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const uc=C.gql`
|
2446
|
+
`)},f))}else r.push(new z(w,f))}return r},Kl=(n,t)=>n.conditions?n.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const r=a.selectedVariants;return e.requiredVariantSelections.some(i=>r.find(o=>o.id===i)!==void 0)}return!1}):!0,Nr=async(n,t,e,a)=>{const r=[],i={};for(const o of n){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case E.DigitalContent:r.push(...await zl(e,o,s));break;case E.Frame:case E.Photo:r.push(...await ql(e,i,o,s));break;case E.Illustration:r.push(...await Gl(e,i,o,s));break;case E.Module:r.push(...await jl(e,o,s));break;case E.Picture:r.push(...await Wl(e,i,o,s));break;case E.Shape:r.push(...await Hl(e,i,o,s));break;case E.Text:r.push(...await Jl(e,i,o,s));break}}for(const o of t.steps)o.type!==E.SilentIllustration&&o.type!==E.ProductOverlay||Kl(o,i)&&r.push(...await Yl(e,o,a));return r};class _l{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new tc(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Xl=()=>new Promise((n,t)=>{try{const a=ft().getContext("webgl2");n(!!a)}catch{n(!1)}}),Zl=Xl();class tc{constructor(t,e,a,r,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Ma(2),this.id=t,this.name=e,this.service=a,this.panelSize=r,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Bt(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new ec(this.getID(),a,await Zl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class ec extends ka{constructor(t,e,a,r,i,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=r,this.layouts=i,this.getWorkflowManager=o}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,r=e/t.height,i=Math.min(a,r);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(m=>m.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,r=t.layoutState.layout.height,i=a===1||r===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=i.width,s=i.height;let l,c;if(this.nonPOTSupport){const m=o/s;a/r<m?(l=o,c=r*(o/a)):(l=a*(s/r),c=s);const g=this.resizeFit({width:l,height:c});l=g.width,c=g.height}else l=i.width,c=i.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),u=je(t.layoutState.layout,e,{renderingConfiguration:{purpose:Nt.ThreeD,templatingContext:d}}),A=Rn(u),h=await ba.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:ft,createImage:le,DOMParser:xa(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const ac=(n,t)=>{const e=[];return n.forEach(a=>{const r=t.steps.find(i=>i.stepName===a.stepName);r?.type===E.Text&&a.stepAspectType==="Text"&&e.push({name:r.stepName,data:{text:a.value}})}),e},nc=async(n,t,e,a)=>{let r={serializableWorkflow:{steps:[]},layouts:{}};r=new R(e.map(l=>new Oa(l))).apply(r);const o=await Nr(n,t,e,a);return new R(o).apply(r)};class rc{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(e=>this.getHandle(e)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const r=e.aspects.find(i=>i.name===a.targetAspectName);return r?a.requiredVariantSelections.some(i=>i===r.value):!1})}async createHandle(t){switch(t.type){case L.FileUpload:return new Qr(this.bundle,t).initialize();case L.ColorOption:return new ya(this.bundle,t,t.entityId?await j.getOption(t.entityId):void 0);case L.Option:{const e=t.entityId?await j.getOption(t.entityId):void 0;return e?.type==="Color"?new ya(this.bundle,t,e):new ja(this.bundle,t,e)}case L.Text:return new Rr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class We{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(r=>r.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Qr extends We{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await j.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await tt(t?.fileLink),a=await Qa(t?.fileLink),r=a.width,i=a.height,o=await ot(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:r,height:i,aspect:r/i,svg:o.svg,colors:o.colors};dt.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Qe.BackgroundRemover)}async removeBackgroundFromImage(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.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),r=await O.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:r.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,r.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(r,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),r}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return O.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Le(ze(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return O.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return O.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),r=a.getAspectStorage(this.property.name);if(r?.useOriginalAsset===t)return;const i={...r,useOriginalAsset:t},o=t?r?.originalAssetKey:r?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",i)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await O.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(r){if(this.updateSharedStepStorage({...r}),r.colors){const i=new Map(r.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(a)});const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...r,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,r=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,r)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(r=>{if(r.getOverrideGlobalPropertyConfiguration(this.property.type))return;r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(r.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Rr extends We{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const r=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(r)}}class ja extends We{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new rt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new rt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new rt(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new rt(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(r=>r.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const r=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(r)}}class ya extends ja{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(i=>i.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;r&&this.setCustomColor(r)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(o=>{switch(o.getType()){case E.Shape:return o.selectVariant(t);case E.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getCurrentVariant()?.getColor()&&this.getCurrentVariant().getColor().toLowerCase()==="#custom"&&this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const ic=(n,t,e,a)=>n.flatMap(r=>r.getSteps()).filter(r=>r.getGlobalPropertyAspects(t).includes(e)&&r.getType()===a),oc=(n,t,e)=>{const r=ic(n,t,e,E.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...r)};function Sa(n,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!lc(a))return a;if(Array.isArray(a))return Sa(a,t);let r={};for(const[i,o]of Object.entries(a))r[i]=sc(o)?o:Sa(o,t);return mi(r,t)}return Array.isArray(n)?n.map(e):e(n)}function sc(n){return n==null}function lc(n){return typeof n=="object"&&!Array.isArray(n)&&n!==null}function Or(n){const t=new Map;return n?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function ve(n){return Sa(n,["__typename"])}class cc{constructor(t,e,a,r,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=ve(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=ve(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=r}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=Or(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Bt(this.globalPropertyState);this.globalPropertyState={...ve(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(r=>r.name===t&&r.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,r){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 i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=Bt(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(r){const l=s.find(c=>c.channel===r);if(l)l.value=e,l.type=i.type,l.channel=r,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(r===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r})}}else{const l=s[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r});xe(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(t,e,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 r=this.configuration.aspects.find(s=>s.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Bt(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=r.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=r.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:r.type,storage:e!==null?e:void 0,channel:a});xe(i,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await v.getShadowGraphqlClient().mutate({mutation:Ys,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case L.FileUpload:{a.fileUpload=e.storage;break}case L.Option:{a.option=e.storage;break}case L.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=ve(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await v.getShadowGraphqlClient().mutate({mutation:Hs,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class dc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const r=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=r.position,i.rotation=r.rotation,i.scale=r.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const r=t.getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===r);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:r,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const a=t.getTransaction().id,r=this.state.transactions.find(l=>l.transactionId===a),i=r?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,r.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const uc=C.gql`
|
2447
2447
|
query GetManyMetafields($entityIds: [String!]!) {
|
2448
2448
|
metafieldsMany(entityIds: $entityIds) {
|
2449
2449
|
id
|
@@ -2496,7 +2496,7 @@
|
|
2496
2496
|
quoteId
|
2497
2497
|
}
|
2498
2498
|
}
|
2499
|
-
`;class ra{constructor(t,e,a,r,i,o){this.workflowExperiences=[],this.eventEmitter=new gc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new dc(e.bundleStateData);const s=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=s?.id,this.globalPropertyStateManager=new cc(this.id,this.ownerId,s,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new rc(this),this.setPreviewService(a);const l=new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const u=this.globalPropertyStateManager.getGlobalPropertyState();u?this.globalPropertyHandleService.getHandles().then(A=>{const h=A.map(m=>{if(m.getType()===L.ColorOption||m.getType()===L.Option){const p=m;if(!u.aspects.find(f=>f.name===p.getName()))return p.initDefaultVariant()}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactions?.map(c=>c.id)||[],{...r,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getIntegrationProductIds(){return this.bundleStateManager.getState()?.integrationProductIds}addIntegrationProductId(t){const e=this.bundleStateManager.getState();if(e){e.integrationProductIds||(e.integrationProductIds=[]),e.integrationProductIds=[...e.integrationProductIds,t];const a=JSON.stringify(e);this.bundleStateManager.setState(a)}}getTemplate(){return this.template}async generateQuoteId(){const e=(await v.getShadowGraphqlClient().mutate({mutation:Cc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,r,i,o){await v.getShadowGraphqlClient().mutate({mutation:pc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await v.getShadowGraphqlClient().mutate({mutation:fc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const r=a?.name;this.getGlobalPropertyStateManager().setAspect(r,a.value)}for(const a of t.aspects){const r=a?.name,i=e.find(o=>o.getName()===r);if(i)switch(a.type){case L.FileUpload:{const o=i,s=await De([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case L.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case L.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case L.Text:{await i.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===L.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,r)=>a+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Wa(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(E.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===L.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=oc(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",r),d=[...new Set(s.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),m=l.find(p=>p.channelNumber===A);m&&await h.setAspect(r,m.variant.id||"",void 0,m.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const r=k.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await v.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(k.getMap("transactionOwnerIds")||new Map).get(a);await v.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const r=this.workflowExperiences.find(i=>i.getTransaction().id===e.id);if(r.setBundle(void 0),this.previewService&&r.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await v.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),r.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(r=>this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id));if(e.some(r=>r===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((r,i)=>e[i]===-1).map(r=>r.id).join(", "));const a=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id),1)[0]);a.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&a.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await v.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,transactionIds:t.map(r=>r.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,i])=>({key:r,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(r=>r.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const r=await this.getGlobalProperties();await Promise.all(r.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await v.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,details:t,type:e||ee.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await v.getShadowGraphqlClient().mutate({mutation:ul,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await v.getShadowGraphqlClient().mutate({mutation:Al,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await v.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await v.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await v.getShadowGraphqlClient().mutate({mutation:fl,variables:{bundleId:this.id}});const a=await Tl(this.workflowExperiences.map(r=>{const i=r.getWorkflow();if(!i)throw new Error("Unable to create designs - Workflow not found!");const o=r.getProduct();if(!o)throw new Error("Unable to create designs - Product not found!");return{workflowManager:r.getWorkflowManager(),workflow:i,layouts:r.getWorkflowManager().getLayouts(),getReducerState:()=>r.getCommandContext().getState(),product:o,transaction:r.getTransaction(),workflowSelections:r.getWorkflowManager().getWorkflowSelections(),designName:i.name,workflowMetadata:r.getWorkflowManager().getWorkflowMetadata()}}),t??(()=>{}),e?(r,i)=>{const o=this.workflowExperiences.find(s=>s.getTransaction().id===i);return o?e(o,r):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await v.getShadowGraphqlClient().mutate({mutation:gl,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await v.getShadowGraphqlClient().mutate({mutation:ml(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const r=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),i=this.workflowExperiences.find(o=>o.getTransaction().id===r.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e);if(a.forEach(r=>r.setBundle(this)),a.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const r of a)await this.injectExperienceIntoPreviewService(r)}async updateBundle(){if(!(await v.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await v.getShadowGraphqlClient().mutate({mutation:hl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=a.map(s=>{if(s.getType()===L.ColorOption||s.getType()===L.Option){const l=s;if(!e.aspects.find(d=>d.name===l.getName()))return l.initDefaultVariant()}});await Promise.all(o),await Promise.all(i.map(s=>s.applyGlobalState()))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],r=[],i=[],o=Or(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?r.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:r,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await v.getShadowGraphqlClient().mutate({mutation:Cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await v.getShadowGraphqlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const wc=C.gql`
|
2499
|
+
`;class ra{constructor(t,e,a,r,i,o){this.workflowExperiences=[],this.eventEmitter=new gc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new dc(e.bundleStateData);const s=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=s?.id,this.globalPropertyStateManager=new cc(this.id,this.ownerId,s,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new rc(this),this.setPreviewService(a);const l=new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const u=this.globalPropertyStateManager.getGlobalPropertyState();u?this.globalPropertyHandleService.getHandles().then(A=>{const h=A.map(m=>{if(m.getType()===L.ColorOption||m.getType()===L.Option){const p=m;if(!u.aspects.find(f=>f.name===p.getName()))return p.initDefaultVariant()}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactions?.map(c=>c.id)||[],{...r,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getIntegrationProductIds(){return this.bundleStateManager.getState()?.integrationProductIds}addIntegrationProductId(t){const e=this.bundleStateManager.getState();if(e){e.integrationProductIds||(e.integrationProductIds=[]),e.integrationProductIds=[...e.integrationProductIds,t];const a=JSON.stringify(e);this.bundleStateManager.setState(a),this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await v.getShadowGraphqlClient().mutate({mutation:Cc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,r,i,o){await v.getShadowGraphqlClient().mutate({mutation:pc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await v.getShadowGraphqlClient().mutate({mutation:fc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const r=a?.name;this.getGlobalPropertyStateManager().setAspect(r,a.value)}for(const a of t.aspects){const r=a?.name,i=e.find(o=>o.getName()===r);if(i)switch(a.type){case L.FileUpload:{const o=i,s=await De([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case L.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case L.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case L.Text:{await i.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===L.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,r)=>a+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Wa(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(E.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===L.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=oc(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",r),d=[...new Set(s.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),m=l.find(p=>p.channelNumber===A);m&&await h.setAspect(r,m.variant.id||"",void 0,m.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const r=k.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await v.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(k.getMap("transactionOwnerIds")||new Map).get(a);await v.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const r=this.workflowExperiences.find(i=>i.getTransaction().id===e.id);if(r.setBundle(void 0),this.previewService&&r.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await v.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),r.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(r=>this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id));if(e.some(r=>r===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((r,i)=>e[i]===-1).map(r=>r.id).join(", "));const a=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getTransaction().id===r.id),1)[0]);a.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&a.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await v.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,transactionIds:t.map(r=>r.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,i])=>({key:r,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(r=>r.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const r=await this.getGlobalProperties();await Promise.all(r.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await v.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,details:t,type:e||ee.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await v.getShadowGraphqlClient().mutate({mutation:ul,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await v.getShadowGraphqlClient().mutate({mutation:Al,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await v.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await v.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await v.getShadowGraphqlClient().mutate({mutation:fl,variables:{bundleId:this.id}});const a=await Tl(this.workflowExperiences.map(r=>{const i=r.getWorkflow();if(!i)throw new Error("Unable to create designs - Workflow not found!");const o=r.getProduct();if(!o)throw new Error("Unable to create designs - Product not found!");return{workflowManager:r.getWorkflowManager(),workflow:i,layouts:r.getWorkflowManager().getLayouts(),getReducerState:()=>r.getCommandContext().getState(),product:o,transaction:r.getTransaction(),workflowSelections:r.getWorkflowManager().getWorkflowSelections(),designName:i.name,workflowMetadata:r.getWorkflowManager().getWorkflowMetadata()}}),t??(()=>{}),e?(r,i)=>{const o=this.workflowExperiences.find(s=>s.getTransaction().id===i);return o?e(o,r):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await v.getShadowGraphqlClient().mutate({mutation:gl,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await v.getShadowGraphqlClient().mutate({mutation:ml(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const r=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),i=this.workflowExperiences.find(o=>o.getTransaction().id===r.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e);if(a.forEach(r=>r.setBundle(this)),a.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const r of a)await this.injectExperienceIntoPreviewService(r)}async updateBundle(){if(!(await v.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await v.getShadowGraphqlClient().mutate({mutation:hl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=a.map(s=>{if(s.getType()===L.ColorOption||s.getType()===L.Option){const l=s;if(!e.aspects.find(d=>d.name===l.getName()))return l.initDefaultVariant()}});await Promise.all(o),await Promise.all(i.map(s=>s.applyGlobalState()))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],r=[],i=[],o=Or(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?r.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:r,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await v.getShadowGraphqlClient().mutate({mutation:Cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await v.getShadowGraphqlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const wc=C.gql`
|
2500
2500
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
2501
2501
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
2502
2502
|
id
|
@@ -2625,7 +2625,7 @@
|
|
2625
2625
|
}
|
2626
2626
|
}
|
2627
2627
|
}
|
2628
|
-
`;class Ic{constructor(t,e=v.getShadowGraphqlClient.bind(v)){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 Bc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.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 fe.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 fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Bc;class jr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Ai(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const pn=new jr;class Wr{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 Pc=async(n,t)=>{const e=await v.getShadowGraphqlClient().query({query:Po(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&&O.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&O.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&O.cacheAsset(o.asset),o.thumbnail&&O.cacheAsset(o.thumbnail),o.material&&O.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},xc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=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=Pc(a,t),i=a.map(s=>$t.set({id:s,options:t},xc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Dc=async(n,t)=>(await Ja([n],t))[0],Fc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),kc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):Fc(t.panels)};class Mc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return v.getShadowGraphqlClient().mutate({...e,mutation:mo})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Fi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.3.1"),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&&Un(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return O}getFlowService(){if(!ki())throw new Error("Application key required to use Flow Service.");return new zr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await v.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Wr(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=Hr(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(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.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=v.getShadowGraphqlClient(),a=await e.query({query:xo,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(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(m=>m.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:Do,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=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await v.getShadowGraphqlClient().query({query:Ee,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=v.getShadowGraphqlClient(),r=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:vc,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 v.getShadowGraphqlClient().query({query:Ee,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 v.getShadowGraphqlClient().mutate({mutation:Ec,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 v.getShadowGraphqlClient().query({query:Ee,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||_t(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 v.getShadowGraphqlClient().query({query:bc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await v.getShadowGraphqlClient().mutate({mutation:nl(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=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const p=Object.entries(localStorage).find(([f,w])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",g=localStorage.getItem(p);g&&!_t(g)&&(s.Authorization=`Bearer ${g}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await v.getShadowGraphqlClient().query({query:Xs(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],u=k.getMap("bundlePartnerIds")||new Map;u.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",u);const A=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await A.getInitializationPromise(),A}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const A=await this.loggedInBearerToken();o.Authorization=`Bearer ${A}`}catch{const m=Object.entries(localStorage).find(([g,f])=>g.startsWith("CognitoIdentityServiceProvider")&&g.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(o.Authorization=`Bearer ${p}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await v.getShadowGraphqlClient().mutate({mutation:rl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const u=k.getMap("bundleOwnerIds")||new Map;return u.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",u),async()=>{const A=new ra(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await A.getInitializationPromise(),A}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await v.getShadowGraphqlClient().query({query:pl(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 v.getShadowGraphqlClient().query({query:Zs,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=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.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){if(t.length===0)throw new mt("No options provided!");const a=v.getShadowGraphqlClient(),r=async y=>{if(y.length===0)return[];const S=y.map(D=>D.option.transactionId),P=await a.query({query:ho,variables:{ids:S},errorPolicy:"all",fetchPolicy:"no-cache"}),b=P.data.transactions;if(b.length!==y.length){const D=P.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&b[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(b[0].integrationProduct.integration)),b.map((D,$)=>({transaction:D,workflowId:D.workflowId,readOnly:y.find(N=>N.option.transactionId===D.id)?.option.readOnly??!1,index:y[$].index}))},i=async y=>{if(y.length===0)return[];const S=await a.mutate({mutation:Ao,variables:{inputs:y.map(b=>({integrationProductId:b.option.type==="integration"?b.option.integrationProductId:void 0,externalIntegrationId:b.option.type==="external"?b.option.externalIntegrationId:void 0,externalProductId:b.option.type==="external"?b.option.externalProductId:void 0,workflowId:b.option.workflowId,designName:b.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),P=S.data?.transactionCreateMany;if(!P||P.length===0){const b=S.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${b}`)}return P.map((b,D)=>({transaction:b,workflowId:b.workflowId,readOnly:!1,index:y[D].index}))},o=t.map((y,S)=>({option:y,index:S})),s=o.filter(y=>y.option.type==="transaction"),l=o.filter(y=>y.option.type==="integration"||y.option.type==="external"||y.option.type==="blank"),c=Xa(s,10),d=Xa(l,10),u=(await Promise.all([...c.map(r),...d.map(i)])).flat(),A=[...new Set(u.map(y=>y.workflowId))].filter(y=>y!==void 0),h=A.length>0?await Ja(A,e):[],m=new Map(h.map(y=>[y.id,y])),p=k.getMap("transactionOwnerIds")||new Map,g=u.map(async y=>{const{transaction:S,workflowId:P,readOnly:b,index:D}=y,$=P?m.get(P):void 0,N=t[D];!p.get(S.id)&&S.transactionOwnerId&&p.set(S.id,S.transactionOwnerId);const et=p.get(S.id)||void 0,at=new Ic({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),H={workflow:$,transaction:S,layouts:[],singleVariantsRenderable:N?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:b?async()=>{throw new T("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:b,isReloadedTransaction:N.type==="transaction"};if(N.type==="transaction"&&S.workflowState){const Y=JSON.parse(S.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else if(!b&&N.workflowState){const Y=JSON.parse(N.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else H.layouts=kc(H.transaction,H.workflow);return H.renderableContextService=new _l(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:D,options:N}}),f=await Promise.all(g);k.setMap("transactionOwnerIds",p);const I=f.sort((y,S)=>y.index-S.index).map(async y=>{const{experienceOptions:S,options:P}=y,b=new Tr(this,S);return await b.getWorkflowManager().getInitializationPromise(),P.type!=="transaction"&&this.customer&&await b.attachCustomerDetails({email:this.customer.emailAddress}),b}),x=await Promise.all(I);return x.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),x}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await v.getShadowGraphqlClient().query({query:wo(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 va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await v.getShadowGraphqlClient().query({query:yo(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 va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await v.getShadowGraphqlClient().query({query:Co,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 v.getShadowGraphqlClient().mutate({mutation:No,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 Hr=async(n,t)=>(await v.getShadowGraphqlClient().query({query:ko,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Tc=async n=>{const e=await v.getShadowGraphqlClient().query({query:fo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Nc=async(n,t)=>(await v.getShadowGraphqlClient().query({query:Fo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Qc=async n=>(await v.getShadowGraphqlClient().query({query:To,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Rc=async n=>(await v.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,Oc=async n=>{const t=await v.getShadowGraphqlClient().mutate({mutation:Il,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n}});if(t.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${t.errors}`)};function Yr(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 Jr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Bn(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 he(s),c=this.frameData?this.frameData[o]:void 0;xe(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=Ft.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=ze(this.imageData.svg,this.imageData.colors||{},!1);return Le(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 T("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]=Yr(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(s=>!s))throw new T("Frame data not set. This is a bug");if(!this.workflowManager)throw new T("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new R([new ws(s,e,t[l]),new ys(s,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]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class $c{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,m,p,g,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 Kr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Kr||{});class _r extends X{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Jr(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.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 ht.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(Qe.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 O.removeBackgroundFromAsset(e);t&&await ht.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){ht.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?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.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 O.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return O.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 Uc=C.gql`
|
2628
|
+
`;class Ic{constructor(t,e=v.getShadowGraphqlClient.bind(v)){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 Bc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.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 fe.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 fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Bc;class jr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Ai(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const pn=new jr;class Wr{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 Pc=async(n,t)=>{const e=await v.getShadowGraphqlClient().query({query:Po(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&&O.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&O.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&O.cacheAsset(o.asset),o.thumbnail&&O.cacheAsset(o.thumbnail),o.material&&O.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},xc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=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=Pc(a,t),i=a.map(s=>$t.set({id:s,options:t},xc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Dc=async(n,t)=>(await Ja([n],t))[0],Fc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),kc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):Fc(t.panels)};class Mc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return v.getShadowGraphqlClient().mutate({...e,mutation:mo})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Fi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.3.1-beta.f47441d7-c6fd-544a-8448-b3ed6932599d"),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&&Un(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return O}getFlowService(){if(!ki())throw new Error("Application key required to use Flow Service.");return new zr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await v.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Wr(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=Hr(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(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.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=v.getShadowGraphqlClient(),a=await e.query({query:xo,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(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(m=>m.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:Do,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=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await v.getShadowGraphqlClient().query({query:Ee,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=v.getShadowGraphqlClient(),r=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:vc,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 v.getShadowGraphqlClient().query({query:Ee,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 v.getShadowGraphqlClient().mutate({mutation:Ec,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 v.getShadowGraphqlClient().query({query:Ee,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||_t(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 v.getShadowGraphqlClient().query({query:bc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await v.getShadowGraphqlClient().mutate({mutation:nl(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=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const p=Object.entries(localStorage).find(([f,w])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",g=localStorage.getItem(p);g&&!_t(g)&&(s.Authorization=`Bearer ${g}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await v.getShadowGraphqlClient().query({query:Xs(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],u=k.getMap("bundlePartnerIds")||new Map;u.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",u);const A=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await A.getInitializationPromise(),A}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const A=await this.loggedInBearerToken();o.Authorization=`Bearer ${A}`}catch{const m=Object.entries(localStorage).find(([g,f])=>g.startsWith("CognitoIdentityServiceProvider")&&g.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(o.Authorization=`Bearer ${p}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await v.getShadowGraphqlClient().mutate({mutation:rl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const u=k.getMap("bundleOwnerIds")||new Map;return u.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",u),async()=>{const A=new ra(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await A.getInitializationPromise(),A}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await v.getShadowGraphqlClient().query({query:pl(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 v.getShadowGraphqlClient().query({query:Zs,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=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.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){if(t.length===0)throw new mt("No options provided!");const a=v.getShadowGraphqlClient(),r=async y=>{if(y.length===0)return[];const S=y.map(D=>D.option.transactionId),P=await a.query({query:ho,variables:{ids:S},errorPolicy:"all",fetchPolicy:"no-cache"}),b=P.data.transactions;if(b.length!==y.length){const D=P.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&b[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(b[0].integrationProduct.integration)),b.map((D,$)=>({transaction:D,workflowId:D.workflowId,readOnly:y.find(N=>N.option.transactionId===D.id)?.option.readOnly??!1,index:y[$].index}))},i=async y=>{if(y.length===0)return[];const S=await a.mutate({mutation:Ao,variables:{inputs:y.map(b=>({integrationProductId:b.option.type==="integration"?b.option.integrationProductId:void 0,externalIntegrationId:b.option.type==="external"?b.option.externalIntegrationId:void 0,externalProductId:b.option.type==="external"?b.option.externalProductId:void 0,workflowId:b.option.workflowId,designName:b.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),P=S.data?.transactionCreateMany;if(!P||P.length===0){const b=S.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${b}`)}return P.map((b,D)=>({transaction:b,workflowId:b.workflowId,readOnly:!1,index:y[D].index}))},o=t.map((y,S)=>({option:y,index:S})),s=o.filter(y=>y.option.type==="transaction"),l=o.filter(y=>y.option.type==="integration"||y.option.type==="external"||y.option.type==="blank"),c=Xa(s,10),d=Xa(l,10),u=(await Promise.all([...c.map(r),...d.map(i)])).flat(),A=[...new Set(u.map(y=>y.workflowId))].filter(y=>y!==void 0),h=A.length>0?await Ja(A,e):[],m=new Map(h.map(y=>[y.id,y])),p=k.getMap("transactionOwnerIds")||new Map,g=u.map(async y=>{const{transaction:S,workflowId:P,readOnly:b,index:D}=y,$=P?m.get(P):void 0,N=t[D];!p.get(S.id)&&S.transactionOwnerId&&p.set(S.id,S.transactionOwnerId);const et=p.get(S.id)||void 0,at=new Ic({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),H={workflow:$,transaction:S,layouts:[],singleVariantsRenderable:N?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:b?async()=>{throw new T("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:b,isReloadedTransaction:N.type==="transaction"};if(N.type==="transaction"&&S.workflowState){const Y=JSON.parse(S.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else if(!b&&N.workflowState){const Y=JSON.parse(N.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else H.layouts=kc(H.transaction,H.workflow);return H.renderableContextService=new _l(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:D,options:N}}),f=await Promise.all(g);k.setMap("transactionOwnerIds",p);const I=f.sort((y,S)=>y.index-S.index).map(async y=>{const{experienceOptions:S,options:P}=y,b=new Tr(this,S);return await b.getWorkflowManager().getInitializationPromise(),P.type!=="transaction"&&this.customer&&await b.attachCustomerDetails({email:this.customer.emailAddress}),b}),x=await Promise.all(I);return x.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),x}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await v.getShadowGraphqlClient().query({query:wo(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 va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await v.getShadowGraphqlClient().query({query:yo(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 va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await v.getShadowGraphqlClient().query({query:Co,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 v.getShadowGraphqlClient().mutate({mutation:No,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 Hr=async(n,t)=>(await v.getShadowGraphqlClient().query({query:ko,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Tc=async n=>{const e=await v.getShadowGraphqlClient().query({query:fo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Nc=async(n,t)=>(await v.getShadowGraphqlClient().query({query:Fo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Qc=async n=>(await v.getShadowGraphqlClient().query({query:To,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Rc=async n=>(await v.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,Oc=async n=>{const t=await v.getShadowGraphqlClient().mutate({mutation:Il,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n}});if(t.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${t.errors}`)};function Yr(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 Jr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Bn(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 he(s),c=this.frameData?this.frameData[o]:void 0;xe(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=Ft.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=ze(this.imageData.svg,this.imageData.colors||{},!1);return Le(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 T("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]=Yr(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(s=>!s))throw new T("Frame data not set. This is a bug");if(!this.workflowManager)throw new T("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new R([new ws(s,e,t[l]),new ys(s,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]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class $c{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,m,p,g,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 Kr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Kr||{});class _r extends X{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Jr(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.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 ht.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(Qe.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 O.removeBackgroundFromAsset(e);t&&await ht.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){ht.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?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.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 O.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return O.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 Uc=C.gql`
|
2629
2629
|
query GetLoggedInCustomer($email: String!) {
|
2630
2630
|
customer(emailAddress: $email) {
|
2631
2631
|
id
|