@saasquatch/squatch-js 2.8.3 → 2.8.4

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/squatch.js CHANGED
@@ -48,7 +48,7 @@
48
48
  </style>`:""}
49
49
  ${await this._getSkeletonPreloadHTML(i,(O=e==null?void 0:e.color)==null?void 0:O.backgroundColor)}
50
50
  ${await this._getContent()}
51
- `),h.close(),S("Popup template loaded into iframe"),await this._setupResizeHandler(s)}async _setupResizeHandler(e){const{contentWindow:n}=e;if(!n)throw new Error("Frame needs a content window");const i=n.document;M(i,async()=>{i.body.style.overflowY="hidden";let s=!0;new n.ResizeObserver(a=>{for(const d of a){const{top:c,bottom:h}=d.contentRect,u=h+c;u<=0||(s?(s=!1,e.style.height="0",e.height=i.body.scrollHeight+"",e.style.height=""):e.height=u+"",d.target.style="")}}).observe(await this._findInnerContainer(e))})}open(){const e=this.container?this._findElement():document.body,i=(e.shadowRoot||e).querySelector(`#${this.id}`);if(!i)throw new Error("Could not determine container div");i.showModal();const s=this._findFrame();if(!s)throw new Error("Could not find iframe");const{contentWindow:r}=s;if(!r)throw new Error("Squatch.js has an empty iframe");const a=r.document;M(a,()=>{var c;const d=r.squatch||r.widgetIdent;(c=s.contentDocument)==null||c.dispatchEvent(new CustomEvent("sq:refresh")),this.context.user?(this._loadEvent(d),S("Popup opened")):this._attachLoadEventListener(a,d)})}close(){const e=this._findFrame();e!=null&&e.contentDocument&&this._detachLoadEventListener(e.contentDocument);const n=this.container?this._findElement():document.body,s=(n.shadowRoot||n).querySelector(`#${this.id}`);if(!s)throw new Error("Could not determine container div");s.close(),S("Popup closed")}_getErrorStyle(){return"body { margin: 0; } .modal { box-shadow: none; border: 0; }"}}const k=v("squatch-js:widgets");class R{constructor(t){l(this,"api");l(this,"tenantAlias");l(this,"domain");l(this,"npmCdn");const e=$(t);this.tenantAlias=e.tenantAlias,this.domain=e.domain,this.npmCdn=e.npmCdn,this.api=new F(e)}async upsertUser(t){const n=ae(t);try{const i=await this.api.upsertUser(n);return{widget:this._renderWidget(i,n,{type:"upsert",user:n.user,engagementMedium:t.engagementMedium,container:t.container,trigger:t.trigger,widgetConfig:{values:{brandingConfig:i==null?void 0:i.brandingConfig}}}),user:i.user}}catch(i){throw k(i),i.apiErrorCode&&this._renderErrorWidget(i,t.engagementMedium),new Error(i)}}async render(t){const n=de(t);try{const i=await this.api.render(n);return{widget:this._renderWidget(i,n,{type:"passwordless",engagementMedium:n.engagementMedium,container:n.container,trigger:n.trigger,widgetConfig:i==null?void 0:i.widgetConfig}),user:i.user}}catch(i){throw i.apiErrorCode&&this._renderErrorWidget(i,n.engagementMedium),new Error(i)}}async autofill(t){const e=t;if(typeof e=="function"){try{const s=await this.api.squatchReferralCookie();e(s)}catch(s){throw k("Autofill error",s),new Error(s)}return}if(typeof e!="string")throw new Error("Autofill accepts a string or function");let n=document.querySelectorAll(e),i;if(n.length>0)i=n[0];else throw k("Element id/class or function missing"),new Error("Element id/class or function missing");try{const s=await this.api.squatchReferralCookie();i.value=s.codes[0]}catch(s){throw new Error(s)}}_renderWidget(t,e,n){var d;if(k("Rendering Widget..."),!t)throw new Error("Unable to get a response");let i,s=!!e.displayOnLoad;const r=t.jsOptions||{},a={content:t.template,type:e.widgetType||((d=r.widget)==null?void 0:d.defaultWidgetType),api:this.api,domain:this.domain,npmCdn:this.npmCdn,context:n};return r.widgetUrlMappings&&r.widgetUrlMappings.forEach(c=>{var h,u;R._matchesUrl(c.url)&&(c.widgetType!=="CONVERSION_WIDGET"||(u=(h=t.user)==null?void 0:h.referredBy)!=null&&u.code?(s=c.displayOnLoad,k(`Display ${c.widgetType} on ${c.url}`)):k(`Don't display ${c.widgetType} when no referral on widget rule match ${c.url}`))}),r.fuelTankAutofillUrls&&(k("We found a fuel tank autofill!"),r.fuelTankAutofillUrls.forEach(({url:c,formSelector:h})=>{var u,m,w;if(R._matchesUrl(c)&&(k("Fuel Tank URL matches"),(m=(u=t.user)==null?void 0:u.referredBy)!=null&&m.code)){const f=document.querySelector(h);f?f.value=((w=t.user.referredBy.referredReward)==null?void 0:w.fuelTankCode)||"":k(new Error(`Element with id/class ${h} was not found.`))}})),e.engagementMedium==="EMBED"?i=this._renderEmbedWidget(a):(i=this._renderPopupWidget(a),s&&i.open()),i}_renderPopupWidget(t){const e=new P(t,t.context.trigger);return e.load(),e}_renderEmbedWidget(t){const e=new q(t,t.context.container);return e.load(),e}_renderErrorWidget(t,e="POPUP"){const{apiErrorCode:n,rsCode:i,statusCode:s,message:r}=t;k(new Error(`${n} (${i}) ${r}`));const a={content:"error",rsCode:i,apiErrorCode:n,statusCode:s,errorMessage:r,api:this.api,domain:this.domain,npmCdn:this.npmCdn,type:"ERROR_WIDGET",context:{type:"error"}};let d;e==="EMBED"?(d=new q(a),d.load()):e==="POPUP"&&(d=new P(a),d.load())}static _matchesUrl(t){return!!window.location.href.match(new RegExp(t))}}class Pe{constructor(t){l(this,"tenantAlias");l(this,"domain");const n=$(t);this.tenantAlias=n.tenantAlias,this.domain=n.domain}track(t,e){const n=t,i=e,s=Re(n),{jwt:r}=Ue(i),a=encodeURIComponent(this.tenantAlias),d=encodeURIComponent(s.userId),c=encodeURIComponent(s.accountId),h=`/api/v1/${a}/open/account/${c}/user/${d}/events`,u=this.domain+h;return te(u,JSON.stringify(s),r)}}function Re(o){if(!_(o))throw new Error("tracking parameter must be an object");if(!(o!=null&&o.accountId))throw new Error("accountId field is required");if(!(o!=null&&o.events))throw new Error("events field is required");if(!(o!=null&&o.userId))throw new Error("userId field is required");const t=o;if(!Array.isArray(t.events))throw new Error("'events' should be an array");return t}function Ue(o){if(!_(o))throw new Error("'options' should be an object");return o}function Le(){var i;const o=window[K]?K:D,t=((i=window["_"+o])==null?void 0:i.ready)||[],e=window.impactOnReady||window.squatchOnReady,n=[...t,e].filter(s=>!!s);setTimeout(()=>{window[D]&&(window[K]=window[D],n.forEach(s=>s()),window[D]._auto(),window["_"+o]=void 0,delete window["_"+o])},0)}const B=v("squatch-js");function Oe(){var u;const o=window.location.search,e=new URLSearchParams(o).get("_saasquatchExtra")||"";if(!e){B("No _saasquatchExtra param");return}const n=$({tenantAlias:"UNKNOWN"});if(!n.domain){B("domain must be provided in config to use _saasquatchExtra");return}let i;try{i=JSON.parse(j(e))}catch{B("Unable to decode _saasquatchExtra config");return}function s(m){return m.replace(/^https?:\/\//,"")}const r=s(n.domain),a=Object.keys((i==null?void 0:i[r])||{})[0],d=(u=i==null?void 0:i[r])==null?void 0:u[a];if(!d){B("_saasquatchExtra did not have an expected structure");return}const{autoPopupWidgetType:c,...h}=d;return{widgetConfig:{widgetType:c,displayOnLoad:!0,...h},squatchConfig:{...n,tenantAlias:a}}}const je=v("squatch-js:decodeUserJwt");function De(o){var t;try{const e=o.split(".")[1];if(e===void 0)return null;const n=j(e);return(t=JSON.parse(n))==null?void 0:t.user}catch(e){return je(e),null}}const z=v("squatch-js:DeclarativeWidget");class ue extends HTMLElement{constructor(){super();l(this,"config");l(this,"token");l(this,"tenant");l(this,"widgetType");l(this,"locale");l(this,"widgetApi");l(this,"analyticsApi");l(this,"widgetInstance");l(this,"type");l(this,"container");l(this,"element");l(this,"loaded");l(this,"_setWidget",(e,n)=>{var s;const i={api:this.widgetApi,content:e.template,context:{type:n.type,user:n.user,container:this.container||void 0,engagementMedium:this.type,widgetConfig:e.widgetConfig},type:this.widgetType,domain:((s=this.config)==null?void 0:s.domain)||A,npmCdn:Z,container:this};if(this.type==="EMBED")return new q(i);{const r=this.firstChild?null:void 0;return new P(i,r)}});l(this,"setErrorWidget",e=>{var d;const n=e instanceof Error?e.message:e==null?void 0:e.message,i=e==null?void 0:e.apiErrorCode,s=e==null?void 0:e.rsCode,r=e==null?void 0:e.statusCode,a={api:this.widgetApi,content:"error",context:{type:"error",container:this.container||void 0},type:"ERROR_WIDGET",domain:((d=this.config)==null?void 0:d.domain)||A,npmCdn:Z,container:this,apiErrorCode:i,rsCode:s,statusCode:r,errorMessage:n};if(this.type==="EMBED")return new q(a);{const c=this.firstChild?null:void 0;return new P(a,c)}});l(this,"reload",this.renderWidget);l(this,"show",this.open);l(this,"hide",this.close);this.attachShadow({mode:"open"}).innerHTML="<style>:host { display: block; }</style><slot></slot>",this.config=ee(),this.token=W(),this.tenant=window.squatchTenant,this.container=this}_setupApis(e){var n,i;if(!this.tenant)throw new Error("tenantAlias not provided");this.widgetApi=new F({tenantAlias:(e==null?void 0:e.tenantAlias)||this.tenant,domain:(e==null?void 0:e.domain)||((n=this.config)==null?void 0:n.domain)||A}),this.analyticsApi=new le({domain:(e==null?void 0:e.domain)||((i=this.config)==null?void 0:i.domain)||A})}getWidgetType(e){return e&&e.includes("friendWidget")?"instant-access":"verified-access"}async renderPasswordlessVariant(){return this._setupApis(),z("Rendering as an Instant Access widget"),await this.widgetApi.render({engagementMedium:this.type,widgetType:this.widgetType,locale:this.locale}).then(e=>this._setWidget(e,{type:"passwordless"})).catch(this.setErrorWidget)}async renderUserUpsertVariant(){this._setupApis();const e=De(this.token);if(!e)return this.setErrorWidget(Error("No user object in token."));!this.locale&&e.locale&&(this.locale=e.locale),z("Rendering as a Verified widget");try{await this.widgetApi.upsertUser({user:e,locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType,jwt:this.token})}catch(i){return this.setErrorWidget(i)}return await this.widgetApi.render({locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType}).then(i=>this._setWidget(i,{type:"upsert",user:e})).catch(this.setErrorWidget)}async getWidgetInstance(){let e;this.widgetType=this.getAttribute("widget")||void 0,this.locale=this.getAttribute("locale")||this.locale;const n=this.getWidgetType(this.widgetType);if(!this.widgetType)throw new Error("No widget has been specified");return!this.token&&n==="verified-access"&&z("[SquatchJS] Authentication token is required for this widget type."),this.token?e=await this.renderUserUpsertVariant():e=await this.renderPasswordlessVariant(),this.widgetInstance=e,this.widgetInstance&&this.dispatchEvent(new CustomEvent("sq:widget-loaded")),e}async renderWidget(){await this.getWidgetInstance(),await this.widgetInstance.load()}open(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.open()}close(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.close()}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(e,n,i){if(!(n===i||!this.loaded))switch(e){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){this.loaded=!0,this.container=this.getAttribute("container"),this.widgetType=this.getAttribute("widget")||void 0;const e=this.getWidgetType(this.widgetType),{getSkeleton:n}=await Promise.resolve().then(()=>pe),i=n({type:e}),s=document.createElement("div");s.id="loading-skeleton",s.innerHTML=i;const r=this.shadowRoot||this.attachShadow({mode:"open"});if(this.type==="POPUP"){const a=r.getElementById("squatchModal");a?(a.innerHTML="",a.appendChild(s)):r.appendChild(s)}else r.innerHTML="",r.appendChild(s);try{await this.renderWidget()}catch(a){z("Failed to render widget",a)}finally{const a=r.getElementById("loading-skeleton");a&&a.remove()}this.getAttribute("open")!==null&&this.open()}}class ne extends ue{constructor(){super(),this.type="EMBED",this.loaded=!1}}class ie extends ue{constructor(){super(),this.type="POPUP",this.loaded=!1,this.addEventListener("click",t=>{t.stopPropagation(),this.open()})}}class Ne extends ne{}class Fe extends ie{}class He extends ne{}class Je extends ie{}window.customElements.get("squatch-embed")||window.customElements.define("squatch-embed",Ne),window.customElements.get("impact-embed")||window.customElements.define("impact-embed",He),window.customElements.get("squatch-popup")||window.customElements.define("squatch-popup",Fe),window.customElements.get("impact-popup")||window.customElements.define("impact-popup",Je);function Be(){console.log("Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.")}const U=v("squatch-js");let G=null,V=null,X=null;function ze(){return G||L({}),G}function Q(){return V||L({}),V}function Ge(){return X||L({}),X}function Ve(o){var t;return(t=Q())==null?void 0:t.render(o)}function Xe(){var t;const o=Oe();if(o){const{squatchConfig:e,widgetConfig:n}=o;return L(e),(t=Q())==null?void 0:t.render(n)}}function L(o){const e=$(o);e.tenantAlias.match("^test")||e.debug?I("squatch-js*"):ke(),U("initializing ..."),G=new F(e),V=new R(e),X=new Pe(e),U("Widget API instance",G),U("Widgets instance",V),U("Events API instance",X)}function Qe(o){o()}function Ye(o){Q().autofill(o)}function ge(){Ce()}typeof document<"u"&&!window.SaaSquatchDoNotAutoDrop&&ge(),(me=window.squatch)!=null&&me.init&&U("Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics."),typeof document<"u"&&Le();function Ze(o={}){const{rsCode:t,apiErrorCode:e,statusCode:n,message:i,mode:s="modal",style:r=""}=o,a=document.createElement("span"),d=u=>(a.textContent=u,a.innerHTML),c=[];n!==void 0&&c.push(`<dt>Status Code</dt><dd>${d(String(n))}</dd>`),e&&c.push(`<dt>API Error Code</dt><dd>${d(e)}</dd>`),t&&c.push(`<dt>RS Code</dt><dd>${d(t)}</dd>`),i&&c.push(`<dt>Message</dt><dd>${d(i)}</dd>`);const h=c.length>0?`<dl class="error-details">${c.join(`
51
+ `),h.close(),S("Popup template loaded into iframe"),await this._setupResizeHandler(s)}async _setupResizeHandler(e){const{contentWindow:n}=e;if(!n)throw new Error("Frame needs a content window");const i=n.document;M(i,async()=>{i.body.style.overflowY="hidden";let s=!0;new n.ResizeObserver(a=>{for(const d of a){const{top:c,bottom:h}=d.contentRect,u=h+c;u<=0||(s?(s=!1,e.style.height="0",e.height=i.body.scrollHeight+"",e.style.height=""):e.height=u+"",d.target.style="")}}).observe(await this._findInnerContainer(e))})}open(){const e=this.container?this._findElement():document.body,i=(e.shadowRoot||e).querySelector(`#${this.id}`);if(!i)throw new Error("Could not determine container div");i.showModal();const s=this._findFrame();if(!s)throw new Error("Could not find iframe");const{contentWindow:r}=s;if(!r)throw new Error("Squatch.js has an empty iframe");const a=r.document;M(a,()=>{var c;const d=r.squatch||r.widgetIdent;(c=s.contentDocument)==null||c.dispatchEvent(new CustomEvent("sq:refresh")),this.context.user?(this._loadEvent(d),S("Popup opened")):this._attachLoadEventListener(a,d)})}close(){const e=this._findFrame();e!=null&&e.contentDocument&&this._detachLoadEventListener(e.contentDocument);const n=this.container?this._findElement():document.body,s=(n.shadowRoot||n).querySelector(`#${this.id}`);if(!s)throw new Error("Could not determine container div");s.close(),S("Popup closed")}_getErrorStyle(){return"body { margin: 0; } .modal { box-shadow: none; border: 0; }"}}const k=v("squatch-js:widgets");class R{constructor(t){l(this,"api");l(this,"tenantAlias");l(this,"domain");l(this,"npmCdn");const e=$(t);this.tenantAlias=e.tenantAlias,this.domain=e.domain,this.npmCdn=e.npmCdn,this.api=new F(e)}async upsertUser(t){const n=ae(t);try{const i=await this.api.upsertUser(n);return{widget:this._renderWidget(i,n,{type:"upsert",user:n.user,engagementMedium:t.engagementMedium,container:t.container,trigger:t.trigger,widgetConfig:{values:{brandingConfig:i==null?void 0:i.brandingConfig}}}),user:i.user}}catch(i){throw k(i),i.apiErrorCode&&this._renderErrorWidget(i,t.engagementMedium),new Error(i)}}async render(t){const n=de(t);try{const i=await this.api.render(n);return{widget:this._renderWidget(i,n,{type:"passwordless",engagementMedium:n.engagementMedium,container:n.container,trigger:n.trigger,widgetConfig:i==null?void 0:i.widgetConfig}),user:i.user}}catch(i){throw i.apiErrorCode&&this._renderErrorWidget(i,n.engagementMedium),new Error(i)}}async autofill(t){const e=t;if(typeof e=="function"){try{const s=await this.api.squatchReferralCookie();e(s)}catch(s){throw k("Autofill error",s),new Error(s)}return}if(typeof e!="string")throw new Error("Autofill accepts a string or function");let n=document.querySelectorAll(e),i;if(n.length>0)i=n[0];else throw k("Element id/class or function missing"),new Error("Element id/class or function missing");try{const s=await this.api.squatchReferralCookie();i.value=s.codes[0]}catch(s){throw new Error(s)}}_renderWidget(t,e,n){var d;if(k("Rendering Widget..."),!t)throw new Error("Unable to get a response");let i,s=!!e.displayOnLoad;const r=t.jsOptions||{},a={content:t.template,type:e.widgetType||((d=r.widget)==null?void 0:d.defaultWidgetType),api:this.api,domain:this.domain,npmCdn:this.npmCdn,context:n};return r.widgetUrlMappings&&r.widgetUrlMappings.forEach(c=>{var h,u;R._matchesUrl(c.url)&&(c.widgetType!=="CONVERSION_WIDGET"||(u=(h=t.user)==null?void 0:h.referredBy)!=null&&u.code?(s=c.displayOnLoad,k(`Display ${c.widgetType} on ${c.url}`)):k(`Don't display ${c.widgetType} when no referral on widget rule match ${c.url}`))}),r.fuelTankAutofillUrls&&(k("We found a fuel tank autofill!"),r.fuelTankAutofillUrls.forEach(({url:c,formSelector:h})=>{var u,m,w;if(R._matchesUrl(c)&&(k("Fuel Tank URL matches"),(m=(u=t.user)==null?void 0:u.referredBy)!=null&&m.code)){const f=document.querySelector(h);f?f.value=((w=t.user.referredBy.referredReward)==null?void 0:w.fuelTankCode)||"":k(new Error(`Element with id/class ${h} was not found.`))}})),e.engagementMedium==="EMBED"?i=this._renderEmbedWidget(a):(i=this._renderPopupWidget(a),s&&i.open()),i}_renderPopupWidget(t){const e=new P(t,t.context.trigger);return e.load(),e}_renderEmbedWidget(t){const e=new q(t,t.context.container);return e.load(),e}_renderErrorWidget(t,e="POPUP"){const{apiErrorCode:n,rsCode:i,statusCode:s,message:r}=t;k(new Error(`${n} (${i}) ${r}`));const a={content:"error",rsCode:i,apiErrorCode:n,statusCode:s,errorMessage:r,api:this.api,domain:this.domain,npmCdn:this.npmCdn,type:"ERROR_WIDGET",context:{type:"error"}};let d;e==="EMBED"?(d=new q(a),d.load()):e==="POPUP"&&(d=new P(a),d.load())}static _matchesUrl(t){return!!window.location.href.match(new RegExp(t))}}class Pe{constructor(t){l(this,"tenantAlias");l(this,"domain");const n=$(t);this.tenantAlias=n.tenantAlias,this.domain=n.domain}track(t,e){const n=t,i=e,s=Re(n),{jwt:r}=Ue(i),a=encodeURIComponent(this.tenantAlias),d=encodeURIComponent(s.userId),c=encodeURIComponent(s.accountId),h=`/api/v1/${a}/open/account/${c}/user/${d}/events`,u=this.domain+h;return te(u,JSON.stringify(s),r)}}function Re(o){if(!_(o))throw new Error("tracking parameter must be an object");if(!(o!=null&&o.accountId))throw new Error("accountId field is required");if(!(o!=null&&o.events))throw new Error("events field is required");if(!(o!=null&&o.userId))throw new Error("userId field is required");const t=o;if(!Array.isArray(t.events))throw new Error("'events' should be an array");return t}function Ue(o){if(!_(o))throw new Error("'options' should be an object");return o}function Le(){var i;const o=window[K]?K:D,t=((i=window["_"+o])==null?void 0:i.ready)||[],e=window.impactOnReady||window.squatchOnReady,n=[...t,e].filter(s=>!!s);setTimeout(()=>{window[D]&&(window[K]=window[D],n.forEach(s=>s()),window[D]._auto(),window["_"+o]=void 0,delete window["_"+o])},0)}const B=v("squatch-js");function Oe(){var u;const o=window.location.search,e=new URLSearchParams(o).get("_saasquatchExtra")||"";if(!e){B("No _saasquatchExtra param");return}const n=$({tenantAlias:"UNKNOWN"});if(!n.domain){B("domain must be provided in config to use _saasquatchExtra");return}let i;try{i=JSON.parse(j(e))}catch{B("Unable to decode _saasquatchExtra config");return}function s(m){return m.replace(/^https?:\/\//,"")}const r=s(n.domain),a=Object.keys((i==null?void 0:i[r])||{})[0],d=(u=i==null?void 0:i[r])==null?void 0:u[a];if(!d){B("_saasquatchExtra did not have an expected structure");return}const{autoPopupWidgetType:c,...h}=d;return{widgetConfig:{widgetType:c,displayOnLoad:!0,...h},squatchConfig:{...n,tenantAlias:a}}}const je=v("squatch-js:decodeUserJwt");function De(o){var t;try{const e=o.split(".")[1];if(e===void 0)return null;const n=j(e);return(t=JSON.parse(n))==null?void 0:t.user}catch(e){return je(e),null}}const z=v("squatch-js:DeclarativeWidget");class ue extends HTMLElement{constructor(){super();l(this,"config");l(this,"token");l(this,"tenant");l(this,"widgetType");l(this,"locale");l(this,"widgetApi");l(this,"analyticsApi");l(this,"widgetInstance");l(this,"type");l(this,"container");l(this,"element");l(this,"loaded");l(this,"_setWidget",(e,n)=>{var s;const i={api:this.widgetApi,content:e.template,context:{type:n.type,user:n.user,container:this.container||void 0,engagementMedium:this.type,widgetConfig:e.widgetConfig},type:this.widgetType,domain:((s=this.config)==null?void 0:s.domain)||A,npmCdn:Z,container:this};if(this.type==="EMBED")return new q(i);{const r=this.firstChild?null:void 0;return new P(i,r)}});l(this,"setErrorWidget",e=>{var d;const n=e instanceof Error?e.message:e==null?void 0:e.message,i=e==null?void 0:e.apiErrorCode,s=e==null?void 0:e.rsCode,r=e==null?void 0:e.statusCode,a={api:this.widgetApi,content:"error",context:{type:"error",container:this.container||void 0},type:"ERROR_WIDGET",domain:((d=this.config)==null?void 0:d.domain)||A,npmCdn:Z,container:this,apiErrorCode:i,rsCode:s,statusCode:r,errorMessage:n};if(this.type==="EMBED")return new q(a);{const c=this.firstChild?null:void 0;return new P(a,c)}});l(this,"reload",this.renderWidget);l(this,"show",this.open);l(this,"hide",this.close);this.attachShadow({mode:"open"}).innerHTML="<style>:host { display: block; }</style><slot></slot>",this.config=ee(),this.token=W(),this.tenant=window.squatchTenant,this.container=this}_setupApis(e){var n,i;if(!this.tenant)throw new Error("tenantAlias not provided");this.widgetApi=new F({tenantAlias:(e==null?void 0:e.tenantAlias)||this.tenant,domain:(e==null?void 0:e.domain)||((n=this.config)==null?void 0:n.domain)||A}),this.analyticsApi=new le({domain:(e==null?void 0:e.domain)||((i=this.config)==null?void 0:i.domain)||A})}getWidgetType(e){return e&&e.includes("friendWidget")?"instant-access":"verified-access"}async renderPasswordlessVariant(){return this._setupApis(),z("Rendering as an Instant Access widget"),await this.widgetApi.render({engagementMedium:this.type,widgetType:this.widgetType,locale:this.locale}).then(e=>this._setWidget(e,{type:"passwordless"})).catch(this.setErrorWidget)}async renderUserUpsertVariant(){this._setupApis();const e=De(this.token);if(!e)return this.setErrorWidget(Error("No user object in token."));!this.locale&&e.locale&&(this.locale=e.locale),z("Rendering as a Verified widget");try{await this.widgetApi.upsertUser({user:e,locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType,jwt:this.token})}catch(i){return this.setErrorWidget(i)}return await this.widgetApi.render({locale:this.locale,engagementMedium:this.type,widgetType:this.widgetType}).then(i=>this._setWidget(i,{type:"upsert",user:e})).catch(this.setErrorWidget)}async getWidgetInstance(){let e;this.widgetType=this.getAttribute("widget")||void 0,this.locale=this.getAttribute("locale")||this.locale;const n=this.getWidgetType(this.widgetType);if(!this.widgetType)throw new Error("No widget has been specified");return!this.token&&n==="verified-access"&&z("[SquatchJS] Authentication token is required for this widget type."),this.token?e=await this.renderUserUpsertVariant():e=await this.renderPasswordlessVariant(),this.widgetInstance=e,this.widgetInstance&&this.dispatchEvent(new CustomEvent("sq:widget-loaded")),e}async renderWidget(){await this.getWidgetInstance(),await this.widgetInstance.load()}open(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.open()}close(){if(!this.widgetInstance)throw new Error("Widget has not loaded yet");this.widgetInstance.close()}static get observedAttributes(){return["widget","locale"]}attributeChangedCallback(e,n,i){if(!(n===i||!this.loaded))switch(e){case"locale":case"widget":this.connectedCallback();break}}async connectedCallback(){this.loaded=!0,this.container=this.getAttribute("container"),this.widgetType=this.getAttribute("widget")||void 0;const e=this.getWidgetType(this.widgetType),{getSkeleton:n}=await Promise.resolve().then(()=>pe),i=n({type:e}),s=document.createElement("div");s.id="loading-skeleton",s.innerHTML=i;const r=this.shadowRoot||this.attachShadow({mode:"open"});if(this.type==="POPUP"){const a=r.getElementById("squatchModal");a&&(a.innerHTML="",a.appendChild(s))}else r.innerHTML="",r.appendChild(s);try{await this.renderWidget()}catch(a){z("Failed to render widget",a)}finally{const a=r.getElementById("loading-skeleton");a&&a.remove()}this.getAttribute("open")!==null&&this.open()}}class ne extends ue{constructor(){super(),this.type="EMBED",this.loaded=!1}}class ie extends ue{constructor(){super(),this.type="POPUP",this.loaded=!1,this.addEventListener("click",t=>{t.stopPropagation(),this.open()})}}class Ne extends ne{}class Fe extends ie{}class He extends ne{}class Je extends ie{}window.customElements.get("squatch-embed")||window.customElements.define("squatch-embed",Ne),window.customElements.get("impact-embed")||window.customElements.define("impact-embed",He),window.customElements.get("squatch-popup")||window.customElements.define("squatch-popup",Fe),window.customElements.get("impact-popup")||window.customElements.define("impact-popup",Je);function Be(){console.log("Having trouble using Squatch.js? Go to https://docs.referralsaasquatch.com/developer/ for tutorials, references and error codes.")}const U=v("squatch-js");let G=null,V=null,X=null;function ze(){return G||L({}),G}function Q(){return V||L({}),V}function Ge(){return X||L({}),X}function Ve(o){var t;return(t=Q())==null?void 0:t.render(o)}function Xe(){var t;const o=Oe();if(o){const{squatchConfig:e,widgetConfig:n}=o;return L(e),(t=Q())==null?void 0:t.render(n)}}function L(o){const e=$(o);e.tenantAlias.match("^test")||e.debug?I("squatch-js*"):ke(),U("initializing ..."),G=new F(e),V=new R(e),X=new Pe(e),U("Widget API instance",G),U("Widgets instance",V),U("Events API instance",X)}function Qe(o){o()}function Ye(o){Q().autofill(o)}function ge(){Ce()}typeof document<"u"&&!window.SaaSquatchDoNotAutoDrop&&ge(),(me=window.squatch)!=null&&me.init&&U("Squatchjs is being loaded more than once. This may lead to multiple load events being sent, duplicated widgets, and inaccurate analytics."),typeof document<"u"&&Le();function Ze(o={}){const{rsCode:t,apiErrorCode:e,statusCode:n,message:i,mode:s="modal",style:r=""}=o,a=document.createElement("span"),d=u=>(a.textContent=u,a.innerHTML),c=[];n!==void 0&&c.push(`<dt>Status Code</dt><dd>${d(String(n))}</dd>`),e&&c.push(`<dt>API Error Code</dt><dd>${d(e)}</dd>`),t&&c.push(`<dt>RS Code</dt><dd>${d(t)}</dd>`),i&&c.push(`<dt>Message</dt><dd>${d(i)}</dd>`);const h=c.length>0?`<dl class="error-details">${c.join(`
52
52
  `)}</dl>`:"";return`<!DOCTYPE html>
53
53
  <!--[if IE 7]><html class="ie7 oldie" lang="en"><![endif]-->
54
54
  <!--[if IE 8]><html class="ie8 oldie" lang="en"><![endif]-->