@givefreely/adunit 1.1.0-rc.1 → 1.1.1-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";const e="1.1.1",t=3,r=e=>1e3*e;async function i(e,i={}){const{maxAttempts:s=t,delayFn:a=r}=i;let n=null;for(let t=1;t<=s;t++)try{return await e()}catch(e){n=e,t<s&&await new Promise((e=>setTimeout(e,a(t))))}throw n||new Error("Operation failed after multiple attempts")}const s=chrome;function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var n={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",r=e=>{const r={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(r).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class i extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const s=(t,r)=>(...i)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):r.singleCallbackArg||i.length<=1&&!1!==r.singleCallbackArg?t.resolve(i[0]):t.resolve(i)},a=e=>1==e?"argument":"arguments",n=(e,t,r)=>new Proxy(t,{apply:(t,i,s)=>r.call(i,e,...s)});let o=Function.call.bind(Object.prototype.hasOwnProperty);const c=(e,t={},r={})=>{let i=Object.create(null),g={has:(t,r)=>r in e||r in i,get(g,l,h){if(l in i)return i[l];if(!(l in e))return;let d=e[l];if("function"==typeof d)if("function"==typeof t[l])d=n(e,e[l],t[l]);else if(o(r,l)){let t=((e,t)=>function(r,...i){if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${a(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${a(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((a,n)=>{if(t.fallbackToNoCallback)try{r[e](...i,s({resolve:a,reject:n},t))}catch(s){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,s),r[e](...i),t.fallbackToNoCallback=!1,t.noCallback=!0,a()}else t.noCallback?(r[e](...i),a()):r[e](...i,s({resolve:a,reject:n},t))}))})(l,r[l]);d=n(e,e[l],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(o(t,l)||o(r,l)))d=c(d,t[l],r[l]);else{if(!o(r,"*"))return Object.defineProperty(i,l,{configurable:!0,enumerable:!0,get:()=>e[l],set(t){e[l]=t}}),d;d=c(d,t[l],r["*"])}return i[l]=d,d},set:(t,r,s,a)=>(r in i?i[r]=s:e[r]=s,!0),defineProperty:(e,t,r)=>Reflect.defineProperty(i,t,r),deleteProperty:(e,t)=>Reflect.deleteProperty(i,t)},l=Object.create(e);return new Proxy(l,g)},g=e=>({addListener(t,r,...i){t.addListener(e.get(r),...i)},hasListener:(t,r)=>t.hasListener(e.get(r)),removeListener(t,r){t.removeListener(e.get(r))}}),l=new i((e=>"function"!=typeof e?e:function(t){const r=c(t,{},{getContent:{minArgs:0,maxArgs:0}});e(r)})),h=new i((e=>"function"!=typeof e?e:function(t,r,i){let s,a,n=!1,o=new Promise((e=>{s=function(t){n=!0,e(t)}}));try{a=e(t,r,s)}catch(e){a=Promise.reject(e)}const c=!0!==a&&((g=a)&&"object"==typeof g&&"function"==typeof g.then);var g;if(!0!==a&&!c&&!n)return!1;return(c?a:o).then((e=>{i(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",i({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:r,resolve:i},s)=>{e.runtime.lastError?e.runtime.lastError.message===t?i():r(new Error(e.runtime.lastError.message)):s&&s.__mozWebExtensionPolyfillReject__?r(new Error(s.message)):i(s)},m=(e,t,r,...i)=>{if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${a(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${a(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((e,t)=>{const s=d.bind(null,{resolve:e,reject:t});i.push(s),r.sendMessage(...i)}))},u={devtools:{network:{onRequestFinished:g(l)}},runtime:{onMessage:g(h),onMessageExternal:g(h),sendMessage:m.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:m.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},f={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return r.privacy={network:{"*":f},services:{"*":f},websites:{"*":f}},c(e,u,r)};e.exports=r(chrome)}}(n);var o=a(n.exports);class c{constructor(e,t,r,i,s){this.wfSecret=e,this.wfAppId=t,this.deviceUrl=r,this.dataUrl=i,this._logger=s}async getWildfireDevice(){return(await fetch(this.deviceUrl,{method:"POST",body:JSON.stringify({}),headers:{"Content-Type":"application/json","WF-Secret":this.wfSecret,"WF-App-ID":this.wfAppId}})).json()}async getActiveDomains(){return(await fetch(`${this.dataUrl}/${this.wfAppId}/active-domain/1`)).json()}async getStanddownPolicy(){const e=`${this.dataUrl}/${this.wfAppId}/stand-down-policy/1`;try{const t=await fetch(e);if(t.ok)return t.json();throw new Error(`Failed to fetch standdown policy. Status ${t.status}`)}catch(t){return this._logger.error("Failed to fetch the standdown policy",{err:t,url:e}),{Domains:[],LostAttribution:[],Params:[],Serp:[]}}}async getMerchantRates(){const e=`${this.dataUrl}/${this.wfAppId}/merchant-rate/1`;try{const t=await fetch(e);if(this._logger.debug("Merchant rates response",{response:t}),!t.ok)throw new Error(`Failed to fetch merchant rates. Status ${t.status}`);const r=t.json();return this._logger.debug("Merchant rates",{rates:r}),r}catch(t){return this._logger.error("Failed to fetch the merchant rates",{err:t,url:e}),[]}}}const g="GIVE_FREELY_",l={async get(e){const t=`${g}${e}`;return(await o.storage.local.get(t))[t]||null},async set(e,t){const r=`${g}${e}`;await o.storage.local.set({[r]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${g}${e}`)):`${g}${e}`;await o.storage.local.remove(t)}},h="wfDevice",d="wfDomains",m="wfStanddownPolicy",u="wfStanddownHistory",f="wfLastCacheRefresh",A="wfMerchantRates";async function y(e,t,r){try{const i=(await w())?.[t];if(i&&i>Date.now())return e.info("Standing down because current affiliate stand down session has not expired"),v(t),!0;await this.refreshCache();const s=await this.getStanddownPolicy();if(E(s,new URL(r).search))return e.info("Standing down because url has affiliate params"),v(t),!0;e.info("No need to stand down.")}catch(t){e.error("Exception produced when trying to determine if it should stand down",t)}return!1}function p(e,t){if(!this.standDownPolicy)return this.logger.warn("Couldnt check affilliation. No stand down policy found"),this.getStanddownPolicy().then((e=>this.standDownPolicy=e)),!1;const r=e.some((e=>x(this.standDownPolicy,e)))||E(this.standDownPolicy,t);return this.logger.info("Affilliation result:",r),r}const w=async()=>await l.get(u),v=async(e,t=1)=>{const r=await w()??{};r[e]=Date.now()+60*t*60*1e3,await l.set(u,r)},x=(e,t)=>{if(!t)return!1;const{Domains:r}=e;return r.some((e=>t.includes(e)))},E=(e,t)=>{if(!t)return!1;const{Params:r}=e;return r.some((e=>t.toLowerCase().includes("?"+e.toLowerCase())))||r.some((e=>t.toLowerCase().includes("&"+e.toLowerCase())))};class C{constructor(e,t,r,i){this.userId=e,this.charityEin=t,this.charityThirdPartyIdentifier=r,this.partnerId=i}toString(){return`userId=${this.encodeUserId(this.userId)},charityEin=${this.charityEin},charityThirdPartyIdentifier=${this.charityThirdPartyIdentifier},partnerId=${this.partnerId}`}encodeUserId(e){return btoa(e).replace(/_/g,"/").replace(/-/g,"+")}}class b{constructor(e,t,r,i=21600){if(this.standDownPolicy=null,this.shouldStandDown=y.bind(this),this.hasAffilliation=p.bind(this),!e||!r)throw new Error("WildfireService requires wildfireClient and vanityBaseUrl");this.wildfireClient=e,this.vanityBaseUrl=r.replace(/\/$/,""),this.refreshInterval=i,this.logger=t}async getActiveDomains(){try{await this.refreshCache();const e=await l.get(d);if(!e)throw Error("Failed to retrieve active domains");return e}catch(e){throw this.logger.error("Failed to get active domains:",e),new Error("Failed to retrieve active domains")}}async getMerchantRates(e){try{await this.refreshCache();const t=await l.get(A);if(!t)throw new Error("Failed to retrieve merchant rates");return t[e]}catch(e){throw this.logger.error("Failed to retrieve merchant rates:",e),new Error("Failed to retrieve merchant rates")}}async generateAffiliateUrl(e,t,r,i){if(!e||!t||!i)throw new Error("Missing required parameters for affiliate URL generation");try{const s=await this.getDevice(),a=await this.generateTrackingCode(r,i,s),n=encodeURIComponent(t),o=encodeURIComponent(a);return`${this.vanityBaseUrl}/e?d=${s.DeviceID}&c=${e.ID}&tc=${o}&url=${n}`}catch(e){throw this.logger.error("Failed to generate affiliate URL:",e),new Error("Failed to generate affiliate URL")}}async clearCache(){try{await Promise.all([l.remove(h),l.remove(d),l.remove(f),l.remove(m),l.remove(A)])}catch(e){throw this.logger.error("Failed to clear cache:",e),new Error("Failed to clear cache")}}async refreshCache(e=!1){try{const t=await l.get(f),r=Date.now();(e||!t||r-t>1e3*this.refreshInterval)&&(await Promise.all([this.syncActiveDomains(),this.syncStanddownPolicy(),this.syncMerchantRates()]),await l.set(f,r)),this.standDownPolicy=await this.getStanddownPolicy()}catch(e){throw this.logger.error("Failed to refresh cache:",e),new Error("Failed to refresh cache")}}async getStanddownPolicy(){return await l.get(m)??(()=>{throw new Error("Failed to retrieve standdown policy. Storage value was null")})()}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async getDevice(){try{const e=await l.get(h);return e?.DeviceID?e:i((()=>this.fetchAndStoreDevice()),this.getRetryOptions())}catch(e){throw this.logger.error("Failed to get device:",e),new Error("Failed to retrieve device information")}}async fetchAndStoreDevice(){const e=await this.wildfireClient.getWildfireDevice();if(!e?.DeviceID)throw new Error("Failed to retrieve device information");return await l.set(h,e),e}async generateTrackingCode(e,t,r){if(!(e?.id&&e?.charity&&e?.charity.ein&&e?.charity.thirdPartyId)){const e=`notregistered-${r.DeviceID}`;return this.logger.info("User not provided. Using GF's default bucket instead.",e),e}return new C(e.id,e.charity.ein,e.charity.thirdPartyId,t).toString()}async syncActiveDomains(){const e=await i((()=>this.wildfireClient.getActiveDomains()),this.getRetryOptions());return await l.set(d,e),e}async syncStanddownPolicy(){const e=await i((()=>this.wildfireClient.getStanddownPolicy()),this.getRetryOptions());return this.logger.info("Updated standdown policy",e),await l.set(m,e),e}async syncMerchantRates(){const e=await i((()=>this.wildfireClient.getMerchantRates()),this.getRetryOptions());return this.logger.debug("Merchant rates",e),await l.set(A,e),e}}class S{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0,this.CONFIG_REFRESH_INTERVAL=3e5,this.PARTNER_CONFIG_STORAGE_KEY="gf_partner_config",this.GLOBAL_CONFIG_STORAGE_KEY="gf_global_config"}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchAndUpdatePartnerConfig(){const e=await i((async()=>{const e=await fetch(`https://cdn.givefreely.com/adunit/config/${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await l.set(this.PARTNER_CONFIG_STORAGE_KEY,t),e}async fetchAndUpdateGlobalConfig(){const e=await i((async()=>{const e=await fetch("https://cdn.givefreely.com/adunit/config/global.json",{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await l.set(this.GLOBAL_CONFIG_STORAGE_KEY,t),e}async getConfig(){const e=Date.now(),t=await l.get(this.PARTNER_CONFIG_STORAGE_KEY),r=await l.get(this.GLOBAL_CONFIG_STORAGE_KEY);if(this.partnerConfig=t?.config||null,this.globalConfig=r?.config||null,this.lastConfigRefresh=Math.max(t?.lastRefresh||0,r?.lastRefresh||0),!this.partnerConfig||!this.globalConfig||e-this.lastConfigRefresh>this.CONFIG_REFRESH_INTERVAL)try{const[t,r]=await Promise.all([this.fetchAndUpdatePartnerConfig(),this.fetchAndUpdateGlobalConfig()]);this.partnerConfig=t,this.globalConfig=r,this.lastConfigRefresh=e}catch(e){if(!this.partnerConfig||!this.globalConfig)throw e;console.warn("Failed to refresh configs, using existing configs:",e)}const i=this.mergeConfigs(this.globalConfig,this.partnerConfig);return((e,t,r)=>{const i=[...t.merchantExclusions??[],...r.merchantExclusions??[]];e.merchantExclusions=i})(i,this.globalConfig,this.partnerConfig),i}async clearCache(){await Promise.all([l.remove(this.PARTNER_CONFIG_STORAGE_KEY),l.remove(this.GLOBAL_CONFIG_STORAGE_KEY)]),this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0}mergeConfigs(e,t){if(!t)return e;const r={...e};for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const s=e,a=t;"object"==typeof a[i]&&null!==a[i]&&"object"==typeof s[i]?r[i]=this.mergeConfigs(s[i],a[i]):r[i]=void 0!==a[i]?a[i]:s[i]}return r}getStoredState(e){return e?{config:e.config,lastRefresh:e.lastRefresh}:{config:null,lastRefresh:0}}}const I="TRACK_EVENT",T="GF_HIDE_POPUP",_="GF_GET_POPUP_CONFIG",P="GF_IS_ACTIVE_DOMAIN",U="GF_SHOULD_STAND_DOWN",D="GF_ACTIVATE_OFFER",O="GF_STORE_SHOPIFY_SHOP_ID",R="GF_GET_DOMAIN_BY_SHOP_ID",k="shopify_shop_ids",F="gf_last_health_check";class L{log({level:e,message:t,timestamp:r,data:i,title:s}){const a="debug"===e?"log":e,n=s?`[${s}]`:"";void 0!==i?console[a](`[${r}] - ${L.LOGGER_PREFIX} ${n} ${t}`,i):console[a](`[${r}] - ${L.LOGGER_PREFIX} ${n} ${t}`)}}var N,G;L.LOGGER_PREFIX="[GFAdUnit] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED"}(N||(N={})),function(e){e.adUnitLog="ADUNIT-LOG"}(G||(G={}));class ${constructor(e){this.gfService=e}log({level:e,message:t,data:r,title:i}){this.gfService.trackEvent(G.adUnitLog,{log:{level:e,message:t,data:r,title:i}})}}const M=["debug","info","warn","error"];class K{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new L],title:e?.title??""}}static getInstance(e){return K.instance||(K.instance=new K(e)),K.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&M.indexOf(e)>=M.indexOf(this.config.minLevel)}createLogMessage(e,t,r){return{level:e,version:"1.1.1",message:t,timestamp:(new Date).toISOString(),data:r,title:this.config.title}}log(e,t,r){if(!this.shouldLog(e))return;const i=this.createLogMessage(e,t,r);this.config.transports.forEach((e=>e.log(i)))}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}class H{static register(e,t){this.strategies.set(e,t)}static get(e){return this.strategies.get(e)}static exists(e){return!(!e?.type||"string"!=typeof e?.type)&&this.strategies.has(e.type)}}H.strategies=new Map;class z{async handle(e,t){const{hostname:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger(),a=await i.getConfig().merchantExclusions,n=await i.getActiveDomains();s.debug("Checking hostname",{hostname:r});try{if(i.healthCheck(),a.some((e=>e.disableDomain&&(r===e.domain||r.endsWith(`.${e.domain}`)))))return s.debug("Hostname is in merchant exclusions",{hostname:r}),{type:P,payload:{isActive:!1,domain:void 0,rates:[]}};if(!n||0===n.length)throw new Error("No active domains");s.debug("Retrieved active domains",{count:n.length});const e=n.find((e=>r===e.Domain||r.endsWith(`.${e.Domain}`)));s.debug("Domain check result",{hostname:r,isActive:!!e});let t=[];if(e?.ID){const r=await i.getMerchantRates(e.Merchant.ID);r&&(s.debug("Retrieved merchant rates",{merchantRates:r}),t=r)}return{type:P,payload:{isActive:!!e,domain:e,rates:t}}}catch(e){return s.error("Error checking domain",{hostname:r,error:e}),{type:P,payload:{isActive:!1,domain:void 0,rates:[]}}}}}class j{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger(),s=await r.getCachedConfig();try{return i.debug("Fetching popup config"),{type:_,payload:{config:s}}}catch(e){return i.error("Error fetching popup config",{error:e}),{type:_,payload:{config:null}}}}}class Y{async handle(e,t){const{days:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=new Date;return e.setDate(e.getDate()+r),await l.set("popup_hide",{popupHide:e.getTime()}),s.debug("Popup hidden",{days:r,expiry:e}),{type:T,payload:{ack:!0}}}catch(e){return s.error("Error hiding popup",{days:r,error:e}),{type:T,payload:{ack:!1}}}}}class B{async handle(e,t){const{activeDomain:r,url:i}=e.payload,{giveFreelyService:s}=t,a=s.getLogger();a.debug("Checking if we should stand down",{activeDomain:r});try{const e=await s.shouldStandDown(r,i);return{type:U,payload:{result:e}}}catch(e){return a.error("Error checking if we should stand down. Returning false",{activeDomain:r,error:e}),{type:U,payload:{result:!1}}}}}class W{constructor(t,r,i=60){this._config=null,this.track=async(t,r,i)=>{null===this._config&&(this._config=await new S(this._partnerApiKey).getConfig());const s={partner:`adUnit_${this._partnerApiKey}`,eventType:t,eventData:{userId:this._userService?.user?.id,libVersion:String(e)??"",wfDeviceId:r,...i}};try{const e=JSON.stringify(s);return await this.shouldBroadcastEvent(e)?(await fetch(this._config.eventsUrl,{headers:{"Content-Type":"application/json"},method:"POST",body:e,cache:"no-store"}),await this.pushEventToHistory(e),!0):(this.log("This event has already been broadcasted during the past hour",s),!1)}catch(e){return this.log("Something unexpected happened when dispatching a gf event",e,s),!1}},this.log=(...e)=>{"debug"===this._config?.backgroundMinLogLevel&&console.log("analytics:",...e)},this.getEventsHistory=async()=>{const{GF_AD_EVENT_HISTORY:e}=await s.storage.local.get({GF_AD_EVENT_HISTORY:""}),t=function(e){const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()}(-this._debounceWindowInMinutes);let r=(e||[]).filter((e=>e.createdAt>t));return await s.storage.local.set({GF_AD_EVENT_HISTORY:r}),r},this.shouldBroadcastEvent=async e=>!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await s.storage.local.set({GF_AD_EVENT_HISTORY:t})},this._partnerApiKey=t,this._userService=r,this._debounceWindowInMinutes=i}}W.trackEvent=async(e,t)=>{await async function(e){return new Promise(((t,r)=>{try{const i=i=>{if(chrome.runtime.lastError)return r({error:chrome.runtime.lastError,message:e});t(i)};s.runtime.sendMessage(e,i)}catch(e){r(e)}}))}({type:I,payload:{eventType:e,eventData:t}})};class q{async handle(e,t){const{eventType:r,eventData:i}=e.payload,{giveFreelyService:s}=t,a=s.getLogger();a.debug("Broadcasting event",{eventType:r,eventData:i});try{const e=await s.trackEvent(r,i);return{type:I,payload:{result:e}}}catch(e){return a.error("Error broadcasting event. Returning false",{eventType:r,eventData:i}),{type:I,payload:{result:!1}}}}}class V{async handle(e,t){const{activeDomain:r,originalUrl:i,selectedCharity:a}=e.payload,{giveFreelyService:n}=t,o=n.getLogger();o.debug("Activating offer",{activeDomain:r,selectedCharity:a});try{if(!a?.ein||!a?.thirdPartyId)throw new Error("Missing charity information");const e=await n.initializeWfDeviceId();if(!e)throw new Error("Failed to initialize Wildfire device ID");const t=await n.upsertUser(a,e);o.debug("Upserted user",{currentUser:t}),t||o.info("Failed to create user. Using default bucket's user");const c=await n.generateAffiliateUrl(r,i,t);return o.debug("Generated affiliate URL",{affiliateUrl:c}),(async e=>{const t=s.tabs.getCurrent(),r=await t,i=await s.tabs.create({url:e,openerTabId:r?.id,active:!1,pinned:!0});await(async e=>new Promise((t=>{s.tabs.onUpdated.addListener((async function r(i,a){if(i===e&&"complete"===a.status){if(s.tabs.onUpdated.removeListener(r),!(await s.tabs.get(e)).url)return void t(!1);t(!0)}}))})))(i.id)&&setTimeout((()=>{i?.id&&s.tabs.remove(i.id)}),3e4)})(c),await n.updateStanddownHistory(r.Domain),o.debug("Activated offer",{activeDomain:r,selectedCharity:a}),{type:D,payload:{response:!0}}}catch(e){return o.error("Error activating offer",{activeDomain:r,error:e}),n.trackEvent(N.checkoutPopupFailedActivation,{activeDomain:r,error:e}),{type:D,payload:{response:!1}}}}}var X;!function(e){e[e.Pending=0]="Pending",e[e.Ready=1]="Ready",e[e.Received=2]="Received",e[e.Donated=3]="Donated",e[e.Disqualified=4]="Disqualified"}(X||(X={}));class Z{constructor(e,t,r){this.adUnitId=e,this.config=t,this.logger=r}async getAnonymousUserCommissions(e,t){try{const r=new URLSearchParams(t).toString(),i=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.getAnonymousUserComissionsPath}?${r}`,{method:"GET",headers:{"Content-Type":"application/json","X-AnonymousUserToken":e}});if(!i.ok)throw new Error("Failed to fetch commissions");return await i.json()}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error fetching anonymous user's commissions:",{error:e}),e}}async createOrUpdateAnonymousUser(e,t){try{const r=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.createAnonymousUserPath}?adUnitId=${this.adUnitId}`,{method:"PUT",headers:{"Content-Type":"application/json","X-GF-Platform":"adUnitLibrary","X-AnonymousUserToken":t??""},body:JSON.stringify(e)});if(!r.ok)throw new Error("Failed to create/update anonymous user");this.logger.info("[GiveFreelyApiClient] anonymous user created/updated succesfuly.");const i=await r.json(),s=r.headers.get("X-AnonymousUserToken");return{resultUser:{...i,charity:{ein:i.selectedCharity,thirdPartyId:i.selectedCharityThirdPartyIdentifier,name:void 0}},resultToken:s}}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error creating anonymous user:",{error:e}),e}}}class J{constructor(e,t){this.ANONYMOUS_USER_STORAGE_KEY="gf_anonymous_user_info",this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY="gf_anonymous_encrypted_token",this._giveFreelyApiClient=e,this._logger=t,this.user=null}async resetUser(){await l.remove(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY),await l.remove(this.ANONYMOUS_USER_STORAGE_KEY)}async upsertUser(e,t){const r=await this.fetchUser();try{const i={selectedCharity:e?.ein,selectedCharityThirdPartyIdentifier:e?.thirdPartyId,deviceId:t};if(!await this.shouldCreateOrUpdateUser(r,i))return this.user=r,r;const s=await l.get(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY),{resultUser:a,resultToken:n}=await this._giveFreelyApiClient.createOrUpdateAnonymousUser(i,s);return n&&await l.set(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY,n),a&&(await l.set(this.ANONYMOUS_USER_STORAGE_KEY,a),this.user=a),a}catch(e){this._logger.error("Error creating/updating anonymous user:",e)}return this.user=r,r}async fetchUser(){return await l.get(this.ANONYMOUS_USER_STORAGE_KEY)}async shouldCreateOrUpdateUser(e,t){return!e||e.charity?.ein!==t.selectedCharity||e.charity?.thirdPartyId!==t.selectedCharityThirdPartyIdentifier||e.deviceId!==t.deviceId}}const Q=e=>{try{return new URL(e),!0}catch(e){return!1}},ee=new Set,te=new Set,re={urls:["<all_urls>"],types:["main_frame"]};class ie{async handle(e,t){const r=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=k,t=await l.get(e)||[],i=t.findIndex((e=>e.shopId===r.shopId));return i>=0?t[i]=r:t.push(r),await l.set(e,t),s.debug("Stored Shopify shop ID",{shopInfo:r}),{type:O,payload:{success:!0}}}catch(e){return s.error("Error storing Shopify shop ID",{shopInfo:r,error:e}),{type:O,payload:{success:!1}}}}}class se{async handle(e,t){const{shopId:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=k,t=(await l.get(e)||[]).find((e=>e.shopId===r));return t?(s.debug("Found domain for shop ID",{shopId:r,domain:t.domain}),{type:R,payload:{found:!0,domain:t.domain,shopInfo:t}}):(s.debug("No domain found for shop ID",{shopId:r}),{type:R,payload:{found:!1}})}catch(e){return s.error("Error getting domain for shop ID",{shopId:r,error:e}),{type:R,payload:{found:!1}}}}}const ae="version";class ne{constructor(e,t){this.lastCheck=null,this.trackEvent=e,this.logger=t}async initialize(){const e=await l.get(F);e&&(this.lastCheck=e)}getToday(){return(new Date).toISOString().split("T")[0]}async check(){try{const e=this.lastCheck??0,t=this.getToday();(e?new Date(e).toISOString().split("T")[0]:null)!==t&&(await this.trackEvent(N.checkoutPopupHealthCheck,{language:chrome.i18n.getUILanguage()}),this.lastCheck=Date.now(),await l.set(F,this.lastCheck))}catch(e){this.logger.error("Health check failed",{error:e instanceof Error?e.message:"Unknown error"})}}}class oe extends Error{constructor(e="Service not initialized"){super(e),this.name="UninitializedServiceError"}}exports.GiveFreelyService=class{constructor(e){this.partnerApiKey=e,this.dependencies={configService:new S(e)},this.logger=K.getInstance(),this.logger.configure({enabled:!0,title:"Background - GiveFreelyService"}),this.state={initialized:!1,wildfireService:null,partnerFilter:null,config:null,wfDeviceId:null,analytics:null,giveFreelyUserService:null,partnerApiKey:e,healthCheck:null}}assertInitialized(){if(!this.state.initialized)throw new oe}async initialize(t=()=>!0){var r;if(!this.state.initialized)try{const i=await this.dependencies.configService.getConfig();this.logger.configure({minLevel:i.backgroundMinLogLevel??"error"}),this.logger.info("Initializing GiveFreelyService",{partnerApiKey:this.partnerApiKey});const a=this.createWildfireService(i),n=await(async(t=!0)=>{const r=await l.get(ae),i=await String(e),s=r!==i;return t&&s&&await(async e=>await l.set(ae,e))(i),s})();n&&this.logger.info("New version detected."),this.state.healthCheck=new ne(this.trackEvent.bind(this),this.logger),await this.state.healthCheck.initialize(),await a.refreshCache(n);const c=new Z(this.partnerApiKey,i,this.logger);this.state.giveFreelyUserService=new J(c,this.logger),await this.state.giveFreelyUserService.upsertUser(),this.state.analytics=new W(this.partnerApiKey,this.state.giveFreelyUserService),this.logger.addTransport(new $(this)),H.register(P,new z),H.register(_,new j),H.register(T,new Y),H.register(U,new B),H.register(I,new q),H.register(D,new V),H.register(O,new ie),H.register(R,new se),this.state.wildfireService=a,this.state.partnerFilter=t,this.state.config=i,this.state.initialized=!0,o.webRequest&&(o.webRequest.onBeforeRequest.addListener((e=>{const t=e.getLogger();return({requestId:r,url:i,initiator:s})=>{try{if(ee.has(r)||te.has(r)||!Q(i))return;const{hostname:a,search:n}=new URL(i);if(a.includes("wild.link"))return t.info("Cashback activation request identified, ignoring affiliate check for request"),void te.add(r);let o;s&&Q(s)&&(o=new URL(s).hostname),e.hasAffiliation([a,o],n)&&(t.info("Affiliation found on url, adding request id to track"),ee.add(r))}catch(e){t.error("Error on handleAffiliateOnBeforeRequest",e)}}})(this),re),o.webRequest.onBeforeRedirect.addListener((e=>{const t=e.getLogger();return async({requestId:r,redirectUrl:i})=>{try{if(!ee.has(r))return;t.info("Attempting to find active domain");const s=new URL(i).hostname,a=(await e.getActiveDomains()).find((e=>s===e.Domain||s.endsWith("."+e.Domain)));if(!a)return;t.info("Found active domain. Updating standdown state"),await v(a.Domain)}catch(e){t.error("Error on handleAffiliateOnBeforeRedirect",e)}}})(this),re),o.webRequest.onCompleted.addListener((()=>{const e=this.getLogger();return({requestId:t})=>{try{ee.has(t)&&(e.info("Tracking request completed. Request Id:",t),ee.delete(t))}catch(t){e.error("Error on handleAffiliateOnCompleted",t)}}})(),re)),r=async(e,t)=>(this.logger.debug("Received message",{type:e.type,payload:e.payload}),this.handleMessage(e)),s.runtime.onMessage.addListener(((e,t,i)=>{function s(e){i(e)}const a=r(e,0);return a instanceof Promise?(a.then((e=>{e&&s(e)})).catch((e=>{console.warn("Async message callback error:",e)})),!0):a})),this.logger.info("GiveFreelyService initialized successfully")}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw this.logger.error("Failed to initialize GiveFreelyService",{error:t}),new Error(`Failed to initialize GiveFreelyService: ${t}`)}}getConfig(){return this.assertInitialized(),this.state.config}async getCachedConfig(){return this.state.config=await this.dependencies.configService.getConfig(),this.logger.configure({minLevel:this.state.config.backgroundMinLogLevel??"error"}),this.state.config}async getActiveDomains(){return this.assertInitialized(),await this.state.wildfireService.getActiveDomains()}async shouldStandDown(e,t){if(this.assertInitialized(),this.getConfig().merchantExclusions.some((t=>t.mutePopups&&e===t.domain)))return this.logger.info("Should standdown due to merchant exclusions"),!0;const r=await this.state.wildfireService.shouldStandDown(this.logger,e,t);return r&&this.logger.info("Should standdown due to vendor policy"),r}hasAffiliation(e,t){if(!this.state.wildfireService)return this.logger.warn("Wildfire service not initialized yet"),!1;const r=this.state.wildfireService.hasAffilliation(e,t);return r&&this.logger.info("Affiliation identified"),r}async trackEvent(e,t){return this.assertInitialized(),await this.state.analytics.track(e,this.state.wfDeviceId?.DeviceID,t)}getLogger(){return this.assertInitialized(),this.logger}async initializeWfDeviceId(){if(this.assertInitialized(),this.state.wfDeviceId=await this.state.wildfireService.getDevice(),!this.state.wfDeviceId)throw new Error("Failed to initialize Wildfire device ID");return this.state.wfDeviceId.DeviceID}getWfDeviceId(){return this.assertInitialized(),this.state.wfDeviceId.DeviceID}async upsertUser(e,t){return this.assertInitialized(),await this.state.giveFreelyUserService.upsertUser(e,t)}async getCurrentUser(){return this.assertInitialized(),await this.state.giveFreelyUserService.user}async generateAffiliateUrl(e,t,r){return this.assertInitialized(),await this.state.wildfireService.generateAffiliateUrl(e,t,r,this.state.partnerApiKey)}async updateStanddownHistory(e){return this.assertInitialized(),await v(e)}isAdUnitMessage(e){return this.assertInitialized(),H.exists(e)}async getMerchantRates(e){if(this.assertInitialized(),!this.state.wildfireService)throw new Error("Wildfire service not initialized");return await this.state.wildfireService.getMerchantRates(e)}async healthCheck(){this.assertInitialized(),await this.state.healthCheck.check()}async handleMessage(e){this.assertInitialized();const t=H.get(e.type);if(!t)return;const r={giveFreelyService:this};return t.handle(e,r)}createWildfireService(e){this.logger.debug("config",this.state.config);const t=new c(e.wfSecret,e.wfAppId,e.deviceUrl,e.dataUrl,this.logger);return new b(t,this.logger,e.vanityBaseUrl,e.refreshInterval)}async destroy(){this.logger.info("Destroying GiveFreelyService"),await Promise.all([this.dependencies.configService.clearCache(),this.state.wildfireService?.clearCache(),this.state.giveFreelyUserService?.resetUser()]),this.state.initialized=!1,this.state.wildfireService=null,this.state.partnerFilter=null,this.state.analytics=null,this.state.config=null}},exports.browser=s;
1
+ "use strict";const e="1.1.0",t=3,r=e=>1e3*e;async function i(e,i={}){const{maxAttempts:s=t,delayFn:a=r}=i;let n=null;for(let t=1;t<=s;t++)try{return await e()}catch(e){n=e,t<s&&await new Promise((e=>setTimeout(e,a(t))))}throw n||new Error("Operation failed after multiple attempts")}const s=chrome;function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var n={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",r=e=>{const r={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(r).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class i extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const s=(t,r)=>(...i)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):r.singleCallbackArg||i.length<=1&&!1!==r.singleCallbackArg?t.resolve(i[0]):t.resolve(i)},a=e=>1==e?"argument":"arguments",n=(e,t,r)=>new Proxy(t,{apply:(t,i,s)=>r.call(i,e,...s)});let o=Function.call.bind(Object.prototype.hasOwnProperty);const c=(e,t={},r={})=>{let i=Object.create(null),g={has:(t,r)=>r in e||r in i,get(g,l,h){if(l in i)return i[l];if(!(l in e))return;let d=e[l];if("function"==typeof d)if("function"==typeof t[l])d=n(e,e[l],t[l]);else if(o(r,l)){let t=((e,t)=>function(r,...i){if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${a(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${a(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((a,n)=>{if(t.fallbackToNoCallback)try{r[e](...i,s({resolve:a,reject:n},t))}catch(s){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,s),r[e](...i),t.fallbackToNoCallback=!1,t.noCallback=!0,a()}else t.noCallback?(r[e](...i),a()):r[e](...i,s({resolve:a,reject:n},t))}))})(l,r[l]);d=n(e,e[l],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(o(t,l)||o(r,l)))d=c(d,t[l],r[l]);else{if(!o(r,"*"))return Object.defineProperty(i,l,{configurable:!0,enumerable:!0,get:()=>e[l],set(t){e[l]=t}}),d;d=c(d,t[l],r["*"])}return i[l]=d,d},set:(t,r,s,a)=>(r in i?i[r]=s:e[r]=s,!0),defineProperty:(e,t,r)=>Reflect.defineProperty(i,t,r),deleteProperty:(e,t)=>Reflect.deleteProperty(i,t)},l=Object.create(e);return new Proxy(l,g)},g=e=>({addListener(t,r,...i){t.addListener(e.get(r),...i)},hasListener:(t,r)=>t.hasListener(e.get(r)),removeListener(t,r){t.removeListener(e.get(r))}}),l=new i((e=>"function"!=typeof e?e:function(t){const r=c(t,{},{getContent:{minArgs:0,maxArgs:0}});e(r)})),h=new i((e=>"function"!=typeof e?e:function(t,r,i){let s,a,n=!1,o=new Promise((e=>{s=function(t){n=!0,e(t)}}));try{a=e(t,r,s)}catch(e){a=Promise.reject(e)}const c=!0!==a&&((g=a)&&"object"==typeof g&&"function"==typeof g.then);var g;if(!0!==a&&!c&&!n)return!1;return(c?a:o).then((e=>{i(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",i({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:r,resolve:i},s)=>{e.runtime.lastError?e.runtime.lastError.message===t?i():r(new Error(e.runtime.lastError.message)):s&&s.__mozWebExtensionPolyfillReject__?r(new Error(s.message)):i(s)},m=(e,t,r,...i)=>{if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${a(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${a(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((e,t)=>{const s=d.bind(null,{resolve:e,reject:t});i.push(s),r.sendMessage(...i)}))},u={devtools:{network:{onRequestFinished:g(l)}},runtime:{onMessage:g(h),onMessageExternal:g(h),sendMessage:m.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:m.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},f={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return r.privacy={network:{"*":f},services:{"*":f},websites:{"*":f}},c(e,u,r)};e.exports=r(chrome)}}(n);var o=a(n.exports);class c{constructor(e,t,r,i,s){this.wfSecret=e,this.wfAppId=t,this.deviceUrl=r,this.dataUrl=i,this._logger=s}async getWildfireDevice(){return(await fetch(this.deviceUrl,{method:"POST",body:JSON.stringify({}),headers:{"Content-Type":"application/json","WF-Secret":this.wfSecret,"WF-App-ID":this.wfAppId}})).json()}async getActiveDomains(){return(await fetch(`${this.dataUrl}/${this.wfAppId}/active-domain/1`)).json()}async getStanddownPolicy(){const e=`${this.dataUrl}/${this.wfAppId}/stand-down-policy/1`;try{const t=await fetch(e);if(t.ok)return t.json();throw new Error(`Failed to fetch standdown policy. Status ${t.status}`)}catch(t){return this._logger.error("Failed to fetch the standdown policy",{err:t,url:e}),{Domains:[],LostAttribution:[],Params:[],Serp:[]}}}async getMerchantRates(){const e=`${this.dataUrl}/${this.wfAppId}/merchant-rate/1`;try{const t=await fetch(e);if(this._logger.debug("Merchant rates response",{response:t}),!t.ok)throw new Error(`Failed to fetch merchant rates. Status ${t.status}`);const r=t.json();return this._logger.debug("Merchant rates",{rates:r}),r}catch(t){return this._logger.error("Failed to fetch the merchant rates",{err:t,url:e}),[]}}}const g="GIVE_FREELY_",l={async get(e){const t=`${g}${e}`;return(await o.storage.local.get(t))[t]||null},async set(e,t){const r=`${g}${e}`;await o.storage.local.set({[r]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${g}${e}`)):`${g}${e}`;await o.storage.local.remove(t)}},h="wfDevice",d="wfDomains",m="wfStanddownPolicy",u="wfStanddownHistory",f="wfLastCacheRefresh",A="wfMerchantRates";async function y(e,t,r){try{const i=(await w())?.[t];if(i&&i>Date.now())return e.info("Standing down because current affiliate stand down session has not expired"),v(t),!0;await this.refreshCache();const s=await this.getStanddownPolicy();if(E(s,new URL(r).search))return e.info("Standing down because url has affiliate params"),v(t),!0;e.info("No need to stand down.")}catch(t){e.error("Exception produced when trying to determine if it should stand down",t)}return!1}function p(e,t){if(!this.standDownPolicy)return this.logger.warn("Couldnt check affilliation. No stand down policy found"),this.getStanddownPolicy().then((e=>this.standDownPolicy=e)),!1;const r=e.some((e=>x(this.standDownPolicy,e)))||E(this.standDownPolicy,t);return this.logger.info("Affilliation result:",r),r}const w=async()=>await l.get(u),v=async(e,t=1)=>{const r=await w()??{};r[e]=Date.now()+60*t*60*1e3,await l.set(u,r)},x=(e,t)=>{if(!t)return!1;const{Domains:r}=e;return r.some((e=>t.includes(e)))},E=(e,t)=>{if(!t)return!1;const{Params:r}=e;return r.some((e=>t.toLowerCase().includes("?"+e.toLowerCase())))||r.some((e=>t.toLowerCase().includes("&"+e.toLowerCase())))};class C{constructor(e,t,r,i){this.userId=e,this.charityEin=t,this.charityThirdPartyIdentifier=r,this.partnerId=i}toString(){return`userId=${this.encodeUserId(this.userId)},charityEin=${this.charityEin},charityThirdPartyIdentifier=${this.charityThirdPartyIdentifier},partnerId=${this.partnerId}`}encodeUserId(e){return btoa(e).replace(/_/g,"/").replace(/-/g,"+")}}class b{constructor(e,t,r,i=21600){if(this.standDownPolicy=null,this.shouldStandDown=y.bind(this),this.hasAffilliation=p.bind(this),!e||!r)throw new Error("WildfireService requires wildfireClient and vanityBaseUrl");this.wildfireClient=e,this.vanityBaseUrl=r.replace(/\/$/,""),this.refreshInterval=i,this.logger=t}async getActiveDomains(){try{await this.refreshCache();const e=await l.get(d);if(!e)throw Error("Failed to retrieve active domains");return e}catch(e){throw this.logger.error("Failed to get active domains:",e),new Error("Failed to retrieve active domains")}}async getMerchantRates(e){try{await this.refreshCache();const t=await l.get(A);if(!t)throw new Error("Failed to retrieve merchant rates");return t[e]}catch(e){throw this.logger.error("Failed to retrieve merchant rates:",e),new Error("Failed to retrieve merchant rates")}}async generateAffiliateUrl(e,t,r,i){if(!e||!t||!i)throw new Error("Missing required parameters for affiliate URL generation");try{const s=await this.getDevice(),a=await this.generateTrackingCode(r,i,s),n=encodeURIComponent(t),o=encodeURIComponent(a);return`${this.vanityBaseUrl}/e?d=${s.DeviceID}&c=${e.ID}&tc=${o}&url=${n}`}catch(e){throw this.logger.error("Failed to generate affiliate URL:",e),new Error("Failed to generate affiliate URL")}}async clearCache(){try{await Promise.all([l.remove(h),l.remove(d),l.remove(f),l.remove(m),l.remove(A)])}catch(e){throw this.logger.error("Failed to clear cache:",e),new Error("Failed to clear cache")}}async refreshCache(e=!1){try{const t=await l.get(f),r=Date.now();(e||!t||r-t>1e3*this.refreshInterval)&&(await Promise.all([this.syncActiveDomains(),this.syncStanddownPolicy(),this.syncMerchantRates()]),await l.set(f,r)),this.standDownPolicy=await this.getStanddownPolicy()}catch(e){throw this.logger.error("Failed to refresh cache:",e),new Error("Failed to refresh cache")}}async getStanddownPolicy(){return await l.get(m)??(()=>{throw new Error("Failed to retrieve standdown policy. Storage value was null")})()}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async getDevice(){try{const e=await l.get(h);return e?.DeviceID?e:i((()=>this.fetchAndStoreDevice()),this.getRetryOptions())}catch(e){throw this.logger.error("Failed to get device:",e),new Error("Failed to retrieve device information")}}async fetchAndStoreDevice(){const e=await this.wildfireClient.getWildfireDevice();if(!e?.DeviceID)throw new Error("Failed to retrieve device information");return await l.set(h,e),e}async generateTrackingCode(e,t,r){if(!(e?.id&&e?.charity&&e?.charity.ein&&e?.charity.thirdPartyId)){const e=`notregistered-${r.DeviceID}`;return this.logger.info("User not provided. Using GF's default bucket instead.",e),e}return new C(e.id,e.charity.ein,e.charity.thirdPartyId,t).toString()}async syncActiveDomains(){const e=await i((()=>this.wildfireClient.getActiveDomains()),this.getRetryOptions());return await l.set(d,e),e}async syncStanddownPolicy(){const e=await i((()=>this.wildfireClient.getStanddownPolicy()),this.getRetryOptions());return this.logger.info("Updated standdown policy",e),await l.set(m,e),e}async syncMerchantRates(){const e=await i((()=>this.wildfireClient.getMerchantRates()),this.getRetryOptions());return this.logger.debug("Merchant rates",e),await l.set(A,e),e}}class S{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0,this.CONFIG_REFRESH_INTERVAL=3e5,this.PARTNER_CONFIG_STORAGE_KEY="gf_partner_config",this.GLOBAL_CONFIG_STORAGE_KEY="gf_global_config"}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchAndUpdatePartnerConfig(){const e=await i((async()=>{const e=await fetch(`https://cdn.givefreely.com/adunit/config/${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await l.set(this.PARTNER_CONFIG_STORAGE_KEY,t),e}async fetchAndUpdateGlobalConfig(){const e=await i((async()=>{const e=await fetch("https://cdn.givefreely.com/adunit/config/global.json",{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await l.set(this.GLOBAL_CONFIG_STORAGE_KEY,t),e}async getConfig(){const e=Date.now(),t=await l.get(this.PARTNER_CONFIG_STORAGE_KEY),r=await l.get(this.GLOBAL_CONFIG_STORAGE_KEY);if(this.partnerConfig=t?.config||null,this.globalConfig=r?.config||null,this.lastConfigRefresh=Math.max(t?.lastRefresh||0,r?.lastRefresh||0),!this.partnerConfig||!this.globalConfig||e-this.lastConfigRefresh>this.CONFIG_REFRESH_INTERVAL)try{const[t,r]=await Promise.all([this.fetchAndUpdatePartnerConfig(),this.fetchAndUpdateGlobalConfig()]);this.partnerConfig=t,this.globalConfig=r,this.lastConfigRefresh=e}catch(e){if(!this.partnerConfig||!this.globalConfig)throw e;console.warn("Failed to refresh configs, using existing configs:",e)}const i=this.mergeConfigs(this.globalConfig,this.partnerConfig);return((e,t,r)=>{const i=[...t.merchantExclusions??[],...r.merchantExclusions??[]];e.merchantExclusions=i})(i,this.globalConfig,this.partnerConfig),i}async clearCache(){await Promise.all([l.remove(this.PARTNER_CONFIG_STORAGE_KEY),l.remove(this.GLOBAL_CONFIG_STORAGE_KEY)]),this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0}mergeConfigs(e,t){if(!t)return e;const r={...e};for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const s=e,a=t;"object"==typeof a[i]&&null!==a[i]&&"object"==typeof s[i]?r[i]=this.mergeConfigs(s[i],a[i]):r[i]=void 0!==a[i]?a[i]:s[i]}return r}getStoredState(e){return e?{config:e.config,lastRefresh:e.lastRefresh}:{config:null,lastRefresh:0}}}const I="TRACK_EVENT",T="GF_HIDE_POPUP",_="GF_GET_POPUP_CONFIG",P="GF_IS_ACTIVE_DOMAIN",U="GF_SHOULD_STAND_DOWN",D="GF_ACTIVATE_OFFER",O="GF_STORE_SHOPIFY_SHOP_ID",R="GF_GET_DOMAIN_BY_SHOP_ID",k="shopify_shop_ids",F="gf_last_health_check";class L{log({level:e,message:t,timestamp:r,data:i,title:s}){const a="debug"===e?"log":e,n=s?`[${s}]`:"";void 0!==i?console[a](`[${r}] - ${L.LOGGER_PREFIX} ${n} ${t}`,i):console[a](`[${r}] - ${L.LOGGER_PREFIX} ${n} ${t}`)}}var N,G;L.LOGGER_PREFIX="[GFAdUnit] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED"}(N||(N={})),function(e){e.adUnitLog="ADUNIT-LOG"}(G||(G={}));class ${constructor(e){this.gfService=e}log({level:e,message:t,data:r,title:i}){this.gfService.trackEvent(G.adUnitLog,{log:{level:e,message:t,data:r,title:i}})}}const M=["debug","info","warn","error"];class K{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new L],title:e?.title??""}}static getInstance(e){return K.instance||(K.instance=new K(e)),K.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&M.indexOf(e)>=M.indexOf(this.config.minLevel)}createLogMessage(e,t,r){return{level:e,version:"1.1.0",message:t,timestamp:(new Date).toISOString(),data:r,title:this.config.title}}log(e,t,r){if(!this.shouldLog(e))return;const i=this.createLogMessage(e,t,r);this.config.transports.forEach((e=>e.log(i)))}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}class H{static register(e,t){this.strategies.set(e,t)}static get(e){return this.strategies.get(e)}static exists(e){return!(!e?.type||"string"!=typeof e?.type)&&this.strategies.has(e.type)}}H.strategies=new Map;class z{async handle(e,t){const{hostname:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger(),a=await i.getConfig().merchantExclusions,n=await i.getActiveDomains();s.debug("Checking hostname",{hostname:r});try{if(i.healthCheck(),a.some((e=>e.disableDomain&&(r===e.domain||r.endsWith(`.${e.domain}`)))))return s.debug("Hostname is in merchant exclusions",{hostname:r}),{type:P,payload:{isActive:!1,domain:void 0,rates:[]}};if(!n||0===n.length)throw new Error("No active domains");s.debug("Retrieved active domains",{count:n.length});const e=n.find((e=>r===e.Domain||r.endsWith(`.${e.Domain}`)));s.debug("Domain check result",{hostname:r,isActive:!!e});let t=[];if(e?.ID){const r=await i.getMerchantRates(e.Merchant.ID);r&&(s.debug("Retrieved merchant rates",{merchantRates:r}),t=r)}return{type:P,payload:{isActive:!!e,domain:e,rates:t}}}catch(e){return s.error("Error checking domain",{hostname:r,error:e}),{type:P,payload:{isActive:!1,domain:void 0,rates:[]}}}}}class j{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger(),s=await r.getCachedConfig();try{return i.debug("Fetching popup config"),{type:_,payload:{config:s}}}catch(e){return i.error("Error fetching popup config",{error:e}),{type:_,payload:{config:null}}}}}class Y{async handle(e,t){const{days:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=new Date;return e.setDate(e.getDate()+r),await l.set("popup_hide",{popupHide:e.getTime()}),s.debug("Popup hidden",{days:r,expiry:e}),{type:T,payload:{ack:!0}}}catch(e){return s.error("Error hiding popup",{days:r,error:e}),{type:T,payload:{ack:!1}}}}}class B{async handle(e,t){const{activeDomain:r,url:i}=e.payload,{giveFreelyService:s}=t,a=s.getLogger();a.debug("Checking if we should stand down",{activeDomain:r});try{const e=await s.shouldStandDown(r,i);return{type:U,payload:{result:e}}}catch(e){return a.error("Error checking if we should stand down. Returning false",{activeDomain:r,error:e}),{type:U,payload:{result:!1}}}}}class W{constructor(t,r,i=60){this._config=null,this.track=async(t,r,i)=>{null===this._config&&(this._config=await new S(this._partnerApiKey).getConfig());const s={partner:`adUnit_${this._partnerApiKey}`,eventType:t,eventData:{userId:this._userService?.user?.id,libVersion:String(e)??"",wfDeviceId:r,...i}};try{const e=JSON.stringify(s);return await this.shouldBroadcastEvent(e)?(await fetch(this._config.eventsUrl,{headers:{"Content-Type":"application/json"},method:"POST",body:e,cache:"no-store"}),await this.pushEventToHistory(e),!0):(this.log("This event has already been broadcasted during the past hour",s),!1)}catch(e){return this.log("Something unexpected happened when dispatching a gf event",e,s),!1}},this.log=(...e)=>{"debug"===this._config?.backgroundMinLogLevel&&console.log("analytics:",...e)},this.getEventsHistory=async()=>{const{GF_AD_EVENT_HISTORY:e}=await s.storage.local.get({GF_AD_EVENT_HISTORY:""}),t=function(e){const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()}(-this._debounceWindowInMinutes);let r=(e||[]).filter((e=>e.createdAt>t));return await s.storage.local.set({GF_AD_EVENT_HISTORY:r}),r},this.shouldBroadcastEvent=async e=>!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await s.storage.local.set({GF_AD_EVENT_HISTORY:t})},this._partnerApiKey=t,this._userService=r,this._debounceWindowInMinutes=i}}W.trackEvent=async(e,t)=>{await async function(e){return new Promise(((t,r)=>{try{const i=i=>{if(chrome.runtime.lastError)return r({error:chrome.runtime.lastError,message:e});t(i)};s.runtime.sendMessage(e,i)}catch(e){r(e)}}))}({type:I,payload:{eventType:e,eventData:t}})};class q{async handle(e,t){const{eventType:r,eventData:i}=e.payload,{giveFreelyService:s}=t,a=s.getLogger();a.debug("Broadcasting event",{eventType:r,eventData:i});try{const e=await s.trackEvent(r,i);return{type:I,payload:{result:e}}}catch(e){return a.error("Error broadcasting event. Returning false",{eventType:r,eventData:i}),{type:I,payload:{result:!1}}}}}class V{async handle(e,t){const{activeDomain:r,originalUrl:i,selectedCharity:a}=e.payload,{giveFreelyService:n}=t,o=n.getLogger();o.debug("Activating offer",{activeDomain:r,selectedCharity:a});try{if(!a?.ein||!a?.thirdPartyId)throw new Error("Missing charity information");const e=await n.initializeWfDeviceId();if(!e)throw new Error("Failed to initialize Wildfire device ID");const t=await n.upsertUser(a,e);o.debug("Upserted user",{currentUser:t}),t||o.info("Failed to create user. Using default bucket's user");const c=await n.generateAffiliateUrl(r,i,t);return o.debug("Generated affiliate URL",{affiliateUrl:c}),(async e=>{const t=s.tabs.getCurrent(),r=await t,i=await s.tabs.create({url:e,openerTabId:r?.id,active:!1,pinned:!0});await(async e=>new Promise((t=>{s.tabs.onUpdated.addListener((async function r(i,a){if(i===e&&"complete"===a.status){if(s.tabs.onUpdated.removeListener(r),!(await s.tabs.get(e)).url)return void t(!1);t(!0)}}))})))(i.id)&&setTimeout((()=>{i?.id&&s.tabs.remove(i.id)}),3e4)})(c),await n.updateStanddownHistory(r.Domain),o.debug("Activated offer",{activeDomain:r,selectedCharity:a}),{type:D,payload:{response:!0}}}catch(e){return o.error("Error activating offer",{activeDomain:r,error:e}),n.trackEvent(N.checkoutPopupFailedActivation,{activeDomain:r,error:e}),{type:D,payload:{response:!1}}}}}var X;!function(e){e[e.Pending=0]="Pending",e[e.Ready=1]="Ready",e[e.Received=2]="Received",e[e.Donated=3]="Donated",e[e.Disqualified=4]="Disqualified"}(X||(X={}));class Z{constructor(e,t,r){this.adUnitId=e,this.config=t,this.logger=r}async getAnonymousUserCommissions(e,t){try{const r=new URLSearchParams(t).toString(),i=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.getAnonymousUserComissionsPath}?${r}`,{method:"GET",headers:{"Content-Type":"application/json","X-AnonymousUserToken":e}});if(!i.ok)throw new Error("Failed to fetch commissions");return await i.json()}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error fetching anonymous user's commissions:",{error:e}),e}}async createOrUpdateAnonymousUser(e,t){try{const r=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.createAnonymousUserPath}?adUnitId=${this.adUnitId}`,{method:"PUT",headers:{"Content-Type":"application/json","X-GF-Platform":"adUnitLibrary","X-AnonymousUserToken":t??""},body:JSON.stringify(e)});if(!r.ok)throw new Error("Failed to create/update anonymous user");this.logger.info("[GiveFreelyApiClient] anonymous user created/updated succesfuly.");const i=await r.json(),s=r.headers.get("X-AnonymousUserToken");return{resultUser:{...i,charity:{ein:i.selectedCharity,thirdPartyId:i.selectedCharityThirdPartyIdentifier,name:void 0}},resultToken:s}}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error creating anonymous user:",{error:e}),e}}}class J{constructor(e,t){this.ANONYMOUS_USER_STORAGE_KEY="gf_anonymous_user_info",this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY="gf_anonymous_encrypted_token",this._giveFreelyApiClient=e,this._logger=t,this.user=null}async resetUser(){await l.remove(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY),await l.remove(this.ANONYMOUS_USER_STORAGE_KEY)}async upsertUser(e,t){const r=await this.fetchUser();try{const i={selectedCharity:e?.ein,selectedCharityThirdPartyIdentifier:e?.thirdPartyId,deviceId:t};if(!await this.shouldCreateOrUpdateUser(r,i))return this.user=r,r;const s=await l.get(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY),{resultUser:a,resultToken:n}=await this._giveFreelyApiClient.createOrUpdateAnonymousUser(i,s);return n&&await l.set(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY,n),a&&(await l.set(this.ANONYMOUS_USER_STORAGE_KEY,a),this.user=a),a}catch(e){this._logger.error("Error creating/updating anonymous user:",e)}return this.user=r,r}async fetchUser(){return await l.get(this.ANONYMOUS_USER_STORAGE_KEY)}async shouldCreateOrUpdateUser(e,t){return!e||e.charity?.ein!==t.selectedCharity||e.charity?.thirdPartyId!==t.selectedCharityThirdPartyIdentifier||e.deviceId!==t.deviceId}}const Q=e=>{try{return new URL(e),!0}catch(e){return!1}},ee=new Set,te=new Set,re={};class ie{async handle(e,t){const r=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=k,t=await l.get(e)||[],i=t.findIndex((e=>e.shopId===r.shopId));return i>=0?t[i]=r:t.push(r),await l.set(e,t),s.debug("Stored Shopify shop ID",{shopInfo:r}),{type:O,payload:{success:!0}}}catch(e){return s.error("Error storing Shopify shop ID",{shopInfo:r,error:e}),{type:O,payload:{success:!1}}}}}class se{async handle(e,t){const{shopId:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=k,t=(await l.get(e)||[]).find((e=>e.shopId===r));return t?(s.debug("Found domain for shop ID",{shopId:r,domain:t.domain}),{type:R,payload:{found:!0,domain:t.domain,shopInfo:t}}):(s.debug("No domain found for shop ID",{shopId:r}),{type:R,payload:{found:!1}})}catch(e){return s.error("Error getting domain for shop ID",{shopId:r,error:e}),{type:R,payload:{found:!1}}}}}const ae="version";class ne{constructor(e,t){this.lastCheck=null,this.trackEvent=e,this.logger=t}async initialize(){const e=await l.get(F);e&&(this.lastCheck=e)}getToday(){return(new Date).toISOString().split("T")[0]}async check(){try{const e=this.lastCheck??0,t=this.getToday();(e?new Date(e).toISOString().split("T")[0]:null)!==t&&(await this.trackEvent(N.checkoutPopupHealthCheck,{language:chrome.i18n.getUILanguage()}),this.lastCheck=Date.now(),await l.set(F,this.lastCheck))}catch(e){this.logger.error("Health check failed",{error:e instanceof Error?e.message:"Unknown error"})}}}class oe extends Error{constructor(e="Service not initialized"){super(e),this.name="UninitializedServiceError"}}exports.GiveFreelyService=class{constructor(e){this.partnerApiKey=e,this.dependencies={configService:new S(e)},this.logger=K.getInstance(),this.logger.configure({enabled:!0,title:"Background - GiveFreelyService"}),this.state={initialized:!1,wildfireService:null,partnerFilter:null,config:null,wfDeviceId:null,analytics:null,giveFreelyUserService:null,partnerApiKey:e,healthCheck:null}}assertInitialized(){if(!this.state.initialized)throw new oe}async initialize(t=()=>!0){var r;if(!this.state.initialized)try{const i=await this.dependencies.configService.getConfig();this.logger.configure({minLevel:i.backgroundMinLogLevel??"error"}),this.logger.info("Initializing GiveFreelyService",{partnerApiKey:this.partnerApiKey});const a=this.createWildfireService(i),n=await(async(t=!0)=>{const r=await l.get(ae),i=await String(e),s=r!==i;return t&&s&&await(async e=>await l.set(ae,e))(i),s})();n&&this.logger.info("New version detected."),this.state.healthCheck=new ne(this.trackEvent.bind(this),this.logger),await this.state.healthCheck.initialize(),await a.refreshCache(n);const c=new Z(this.partnerApiKey,i,this.logger);this.state.giveFreelyUserService=new J(c,this.logger),await this.state.giveFreelyUserService.upsertUser(),this.state.analytics=new W(this.partnerApiKey,this.state.giveFreelyUserService),this.logger.addTransport(new $(this)),H.register(P,new z),H.register(_,new j),H.register(T,new Y),H.register(U,new B),H.register(I,new q),H.register(D,new V),H.register(O,new ie),H.register(R,new se),this.state.wildfireService=a,this.state.partnerFilter=t,this.state.config=i,this.state.initialized=!0,o.webRequest&&(o.webRequest.onBeforeRequest.addListener((e=>{const t=e.getLogger();return({requestId:r,url:i,initiator:s})=>{try{if(ee.has(r)||te.has(r)||!Q(i))return;const{hostname:a,search:n}=new URL(i);if(a.includes("wild.link"))return t.info("Cashback activation request identified, ignoring affiliate check for request"),void te.add(r);let o;s&&Q(s)&&(o=new URL(s).hostname),e.hasAffiliation([a,o],n)&&(t.info("Affiliation found on url, adding request id to track"),ee.add(r))}catch(e){t.error("Error on handleAffiliateOnBeforeRequest",e)}}})(this),re),o.webRequest.onBeforeRedirect.addListener((e=>{const t=e.getLogger();return async({requestId:r,redirectUrl:i})=>{try{if(!ee.has(r))return;t.info("Attempting to find active domain");const s=new URL(i).hostname,a=(await e.getActiveDomains()).find((e=>s===e.Domain||s.endsWith("."+e.Domain)));if(!a)return;t.info("Found active domain. Updating standdown state"),await v(a.Domain)}catch(e){t.error("Error on handleAffiliateOnBeforeRedirect",e)}}})(this),re),o.webRequest.onCompleted.addListener((()=>{const e=this.getLogger();return({requestId:t})=>{try{ee.has(t)&&(e.info("Tracking request completed. Request Id:",t),ee.delete(t))}catch(t){e.error("Error on handleAffiliateOnCompleted",t)}}})(),re)),r=async(e,t)=>(this.logger.debug("Received message",{type:e.type,payload:e.payload}),this.handleMessage(e)),s.runtime.onMessage.addListener(((e,t,i)=>{function s(e){i(e)}const a=r(e,0);return a instanceof Promise?(a.then((e=>{e&&s(e)})).catch((e=>{console.warn("Async message callback error:",e)})),!0):a})),this.logger.info("GiveFreelyService initialized successfully")}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw this.logger.error("Failed to initialize GiveFreelyService",{error:t}),new Error(`Failed to initialize GiveFreelyService: ${t}`)}}getConfig(){return this.assertInitialized(),this.state.config}async getCachedConfig(){return this.state.config=await this.dependencies.configService.getConfig(),this.logger.configure({minLevel:this.state.config.backgroundMinLogLevel??"error"}),this.state.config}async getActiveDomains(){return this.assertInitialized(),await this.state.wildfireService.getActiveDomains()}async shouldStandDown(e,t){if(this.assertInitialized(),this.getConfig().merchantExclusions.some((t=>t.mutePopups&&e===t.domain)))return this.logger.info("Should standdown due to merchant exclusions"),!0;const r=await this.state.wildfireService.shouldStandDown(this.logger,e,t);return r&&this.logger.info("Should standdown due to vendor policy"),r}hasAffiliation(e,t){if(!this.state.wildfireService)return this.logger.warn("Wildfire service not initialized yet"),!1;const r=this.state.wildfireService.hasAffilliation(e,t);return r&&this.logger.info("Affiliation identified"),r}async trackEvent(e,t){return this.assertInitialized(),await this.state.analytics.track(e,this.state.wfDeviceId?.DeviceID,t)}getLogger(){return this.assertInitialized(),this.logger}async initializeWfDeviceId(){if(this.assertInitialized(),this.state.wfDeviceId=await this.state.wildfireService.getDevice(),!this.state.wfDeviceId)throw new Error("Failed to initialize Wildfire device ID");return this.state.wfDeviceId.DeviceID}getWfDeviceId(){return this.assertInitialized(),this.state.wfDeviceId.DeviceID}async upsertUser(e,t){return this.assertInitialized(),await this.state.giveFreelyUserService.upsertUser(e,t)}async getCurrentUser(){return this.assertInitialized(),await this.state.giveFreelyUserService.user}async generateAffiliateUrl(e,t,r){return this.assertInitialized(),await this.state.wildfireService.generateAffiliateUrl(e,t,r,this.state.partnerApiKey)}async updateStanddownHistory(e){return this.assertInitialized(),await v(e)}isAdUnitMessage(e){return this.assertInitialized(),H.exists(e)}async getMerchantRates(e){if(this.assertInitialized(),!this.state.wildfireService)throw new Error("Wildfire service not initialized");return await this.state.wildfireService.getMerchantRates(e)}async healthCheck(){this.assertInitialized(),await this.state.healthCheck.check()}async handleMessage(e){this.assertInitialized();const t=H.get(e.type);if(!t)return;const r={giveFreelyService:this};return t.handle(e,r)}createWildfireService(e){this.logger.debug("config",this.state.config);const t=new c(e.wfSecret,e.wfAppId,e.deviceUrl,e.dataUrl,this.logger);return new b(t,this.logger,e.vanityBaseUrl,e.refreshInterval)}async destroy(){this.logger.info("Destroying GiveFreelyService"),await Promise.all([this.dependencies.configService.clearCache(),this.state.wildfireService?.clearCache(),this.state.giveFreelyUserService?.resetUser()]),this.state.initialized=!1,this.state.wildfireService=null,this.state.partnerFilter=null,this.state.analytics=null,this.state.config=null}},exports.browser=s;
@@ -1 +1 @@
1
- const e="1.1.1",t=3,r=e=>1e3*e;async function i(e,i={}){const{maxAttempts:s=t,delayFn:a=r}=i;let n=null;for(let t=1;t<=s;t++)try{return await e()}catch(e){n=e,t<s&&await new Promise((e=>setTimeout(e,a(t))))}throw n||new Error("Operation failed after multiple attempts")}const s=chrome;function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var n={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",r=e=>{const r={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(r).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class i extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const s=(t,r)=>(...i)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):r.singleCallbackArg||i.length<=1&&!1!==r.singleCallbackArg?t.resolve(i[0]):t.resolve(i)},a=e=>1==e?"argument":"arguments",n=(e,t,r)=>new Proxy(t,{apply:(t,i,s)=>r.call(i,e,...s)});let o=Function.call.bind(Object.prototype.hasOwnProperty);const g=(e,t={},r={})=>{let i=Object.create(null),c={has:(t,r)=>r in e||r in i,get(c,l,h){if(l in i)return i[l];if(!(l in e))return;let d=e[l];if("function"==typeof d)if("function"==typeof t[l])d=n(e,e[l],t[l]);else if(o(r,l)){let t=((e,t)=>function(r,...i){if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${a(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${a(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((a,n)=>{if(t.fallbackToNoCallback)try{r[e](...i,s({resolve:a,reject:n},t))}catch(s){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,s),r[e](...i),t.fallbackToNoCallback=!1,t.noCallback=!0,a()}else t.noCallback?(r[e](...i),a()):r[e](...i,s({resolve:a,reject:n},t))}))})(l,r[l]);d=n(e,e[l],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(o(t,l)||o(r,l)))d=g(d,t[l],r[l]);else{if(!o(r,"*"))return Object.defineProperty(i,l,{configurable:!0,enumerable:!0,get:()=>e[l],set(t){e[l]=t}}),d;d=g(d,t[l],r["*"])}return i[l]=d,d},set:(t,r,s,a)=>(r in i?i[r]=s:e[r]=s,!0),defineProperty:(e,t,r)=>Reflect.defineProperty(i,t,r),deleteProperty:(e,t)=>Reflect.deleteProperty(i,t)},l=Object.create(e);return new Proxy(l,c)},c=e=>({addListener(t,r,...i){t.addListener(e.get(r),...i)},hasListener:(t,r)=>t.hasListener(e.get(r)),removeListener(t,r){t.removeListener(e.get(r))}}),l=new i((e=>"function"!=typeof e?e:function(t){const r=g(t,{},{getContent:{minArgs:0,maxArgs:0}});e(r)})),h=new i((e=>"function"!=typeof e?e:function(t,r,i){let s,a,n=!1,o=new Promise((e=>{s=function(t){n=!0,e(t)}}));try{a=e(t,r,s)}catch(e){a=Promise.reject(e)}const g=!0!==a&&((c=a)&&"object"==typeof c&&"function"==typeof c.then);var c;if(!0!==a&&!g&&!n)return!1;return(g?a:o).then((e=>{i(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",i({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:r,resolve:i},s)=>{e.runtime.lastError?e.runtime.lastError.message===t?i():r(new Error(e.runtime.lastError.message)):s&&s.__mozWebExtensionPolyfillReject__?r(new Error(s.message)):i(s)},m=(e,t,r,...i)=>{if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${a(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${a(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((e,t)=>{const s=d.bind(null,{resolve:e,reject:t});i.push(s),r.sendMessage(...i)}))},u={devtools:{network:{onRequestFinished:c(l)}},runtime:{onMessage:c(h),onMessageExternal:c(h),sendMessage:m.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:m.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},f={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return r.privacy={network:{"*":f},services:{"*":f},websites:{"*":f}},g(e,u,r)};e.exports=r(chrome)}}(n);var o=a(n.exports);class g{constructor(e,t,r,i,s){this.wfSecret=e,this.wfAppId=t,this.deviceUrl=r,this.dataUrl=i,this._logger=s}async getWildfireDevice(){return(await fetch(this.deviceUrl,{method:"POST",body:JSON.stringify({}),headers:{"Content-Type":"application/json","WF-Secret":this.wfSecret,"WF-App-ID":this.wfAppId}})).json()}async getActiveDomains(){return(await fetch(`${this.dataUrl}/${this.wfAppId}/active-domain/1`)).json()}async getStanddownPolicy(){const e=`${this.dataUrl}/${this.wfAppId}/stand-down-policy/1`;try{const t=await fetch(e);if(t.ok)return t.json();throw new Error(`Failed to fetch standdown policy. Status ${t.status}`)}catch(t){return this._logger.error("Failed to fetch the standdown policy",{err:t,url:e}),{Domains:[],LostAttribution:[],Params:[],Serp:[]}}}async getMerchantRates(){const e=`${this.dataUrl}/${this.wfAppId}/merchant-rate/1`;try{const t=await fetch(e);if(this._logger.debug("Merchant rates response",{response:t}),!t.ok)throw new Error(`Failed to fetch merchant rates. Status ${t.status}`);const r=t.json();return this._logger.debug("Merchant rates",{rates:r}),r}catch(t){return this._logger.error("Failed to fetch the merchant rates",{err:t,url:e}),[]}}}const c="GIVE_FREELY_",l={async get(e){const t=`${c}${e}`;return(await o.storage.local.get(t))[t]||null},async set(e,t){const r=`${c}${e}`;await o.storage.local.set({[r]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${c}${e}`)):`${c}${e}`;await o.storage.local.remove(t)}},h="wfDevice",d="wfDomains",m="wfStanddownPolicy",u="wfStanddownHistory",f="wfLastCacheRefresh",A="wfMerchantRates";async function y(e,t,r){try{const i=(await w())?.[t];if(i&&i>Date.now())return e.info("Standing down because current affiliate stand down session has not expired"),v(t),!0;await this.refreshCache();const s=await this.getStanddownPolicy();if(E(s,new URL(r).search))return e.info("Standing down because url has affiliate params"),v(t),!0;e.info("No need to stand down.")}catch(t){e.error("Exception produced when trying to determine if it should stand down",t)}return!1}function p(e,t){if(!this.standDownPolicy)return this.logger.warn("Couldnt check affilliation. No stand down policy found"),this.getStanddownPolicy().then((e=>this.standDownPolicy=e)),!1;const r=e.some((e=>x(this.standDownPolicy,e)))||E(this.standDownPolicy,t);return this.logger.info("Affilliation result:",r),r}const w=async()=>await l.get(u),v=async(e,t=1)=>{const r=await w()??{};r[e]=Date.now()+60*t*60*1e3,await l.set(u,r)},x=(e,t)=>{if(!t)return!1;const{Domains:r}=e;return r.some((e=>t.includes(e)))},E=(e,t)=>{if(!t)return!1;const{Params:r}=e;return r.some((e=>t.toLowerCase().includes("?"+e.toLowerCase())))||r.some((e=>t.toLowerCase().includes("&"+e.toLowerCase())))};class C{constructor(e,t,r,i){this.userId=e,this.charityEin=t,this.charityThirdPartyIdentifier=r,this.partnerId=i}toString(){return`userId=${this.encodeUserId(this.userId)},charityEin=${this.charityEin},charityThirdPartyIdentifier=${this.charityThirdPartyIdentifier},partnerId=${this.partnerId}`}encodeUserId(e){return btoa(e).replace(/_/g,"/").replace(/-/g,"+")}}class b{constructor(e,t,r,i=21600){if(this.standDownPolicy=null,this.shouldStandDown=y.bind(this),this.hasAffilliation=p.bind(this),!e||!r)throw new Error("WildfireService requires wildfireClient and vanityBaseUrl");this.wildfireClient=e,this.vanityBaseUrl=r.replace(/\/$/,""),this.refreshInterval=i,this.logger=t}async getActiveDomains(){try{await this.refreshCache();const e=await l.get(d);if(!e)throw Error("Failed to retrieve active domains");return e}catch(e){throw this.logger.error("Failed to get active domains:",e),new Error("Failed to retrieve active domains")}}async getMerchantRates(e){try{await this.refreshCache();const t=await l.get(A);if(!t)throw new Error("Failed to retrieve merchant rates");return t[e]}catch(e){throw this.logger.error("Failed to retrieve merchant rates:",e),new Error("Failed to retrieve merchant rates")}}async generateAffiliateUrl(e,t,r,i){if(!e||!t||!i)throw new Error("Missing required parameters for affiliate URL generation");try{const s=await this.getDevice(),a=await this.generateTrackingCode(r,i,s),n=encodeURIComponent(t),o=encodeURIComponent(a);return`${this.vanityBaseUrl}/e?d=${s.DeviceID}&c=${e.ID}&tc=${o}&url=${n}`}catch(e){throw this.logger.error("Failed to generate affiliate URL:",e),new Error("Failed to generate affiliate URL")}}async clearCache(){try{await Promise.all([l.remove(h),l.remove(d),l.remove(f),l.remove(m),l.remove(A)])}catch(e){throw this.logger.error("Failed to clear cache:",e),new Error("Failed to clear cache")}}async refreshCache(e=!1){try{const t=await l.get(f),r=Date.now();(e||!t||r-t>1e3*this.refreshInterval)&&(await Promise.all([this.syncActiveDomains(),this.syncStanddownPolicy(),this.syncMerchantRates()]),await l.set(f,r)),this.standDownPolicy=await this.getStanddownPolicy()}catch(e){throw this.logger.error("Failed to refresh cache:",e),new Error("Failed to refresh cache")}}async getStanddownPolicy(){return await l.get(m)??(()=>{throw new Error("Failed to retrieve standdown policy. Storage value was null")})()}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async getDevice(){try{const e=await l.get(h);return e?.DeviceID?e:i((()=>this.fetchAndStoreDevice()),this.getRetryOptions())}catch(e){throw this.logger.error("Failed to get device:",e),new Error("Failed to retrieve device information")}}async fetchAndStoreDevice(){const e=await this.wildfireClient.getWildfireDevice();if(!e?.DeviceID)throw new Error("Failed to retrieve device information");return await l.set(h,e),e}async generateTrackingCode(e,t,r){if(!(e?.id&&e?.charity&&e?.charity.ein&&e?.charity.thirdPartyId)){const e=`notregistered-${r.DeviceID}`;return this.logger.info("User not provided. Using GF's default bucket instead.",e),e}return new C(e.id,e.charity.ein,e.charity.thirdPartyId,t).toString()}async syncActiveDomains(){const e=await i((()=>this.wildfireClient.getActiveDomains()),this.getRetryOptions());return await l.set(d,e),e}async syncStanddownPolicy(){const e=await i((()=>this.wildfireClient.getStanddownPolicy()),this.getRetryOptions());return this.logger.info("Updated standdown policy",e),await l.set(m,e),e}async syncMerchantRates(){const e=await i((()=>this.wildfireClient.getMerchantRates()),this.getRetryOptions());return this.logger.debug("Merchant rates",e),await l.set(A,e),e}}class S{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0,this.CONFIG_REFRESH_INTERVAL=3e5,this.PARTNER_CONFIG_STORAGE_KEY="gf_partner_config",this.GLOBAL_CONFIG_STORAGE_KEY="gf_global_config"}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchAndUpdatePartnerConfig(){const e=await i((async()=>{const e=await fetch(`https://cdn.givefreely.com/adunit/config/${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await l.set(this.PARTNER_CONFIG_STORAGE_KEY,t),e}async fetchAndUpdateGlobalConfig(){const e=await i((async()=>{const e=await fetch("https://cdn.givefreely.com/adunit/config/global.json",{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await l.set(this.GLOBAL_CONFIG_STORAGE_KEY,t),e}async getConfig(){const e=Date.now(),t=await l.get(this.PARTNER_CONFIG_STORAGE_KEY),r=await l.get(this.GLOBAL_CONFIG_STORAGE_KEY);if(this.partnerConfig=t?.config||null,this.globalConfig=r?.config||null,this.lastConfigRefresh=Math.max(t?.lastRefresh||0,r?.lastRefresh||0),!this.partnerConfig||!this.globalConfig||e-this.lastConfigRefresh>this.CONFIG_REFRESH_INTERVAL)try{const[t,r]=await Promise.all([this.fetchAndUpdatePartnerConfig(),this.fetchAndUpdateGlobalConfig()]);this.partnerConfig=t,this.globalConfig=r,this.lastConfigRefresh=e}catch(e){if(!this.partnerConfig||!this.globalConfig)throw e;console.warn("Failed to refresh configs, using existing configs:",e)}const i=this.mergeConfigs(this.globalConfig,this.partnerConfig);return((e,t,r)=>{const i=[...t.merchantExclusions??[],...r.merchantExclusions??[]];e.merchantExclusions=i})(i,this.globalConfig,this.partnerConfig),i}async clearCache(){await Promise.all([l.remove(this.PARTNER_CONFIG_STORAGE_KEY),l.remove(this.GLOBAL_CONFIG_STORAGE_KEY)]),this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0}mergeConfigs(e,t){if(!t)return e;const r={...e};for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const s=e,a=t;"object"==typeof a[i]&&null!==a[i]&&"object"==typeof s[i]?r[i]=this.mergeConfigs(s[i],a[i]):r[i]=void 0!==a[i]?a[i]:s[i]}return r}getStoredState(e){return e?{config:e.config,lastRefresh:e.lastRefresh}:{config:null,lastRefresh:0}}}const I="TRACK_EVENT",T="GF_HIDE_POPUP",_="GF_GET_POPUP_CONFIG",P="GF_IS_ACTIVE_DOMAIN",U="GF_SHOULD_STAND_DOWN",D="GF_ACTIVATE_OFFER",O="GF_STORE_SHOPIFY_SHOP_ID",R="GF_GET_DOMAIN_BY_SHOP_ID",k="shopify_shop_ids",F="gf_last_health_check";class L{log({level:e,message:t,timestamp:r,data:i,title:s}){const a="debug"===e?"log":e,n=s?`[${s}]`:"";void 0!==i?console[a](`[${r}] - ${L.LOGGER_PREFIX} ${n} ${t}`,i):console[a](`[${r}] - ${L.LOGGER_PREFIX} ${n} ${t}`)}}var N,G;L.LOGGER_PREFIX="[GFAdUnit] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED"}(N||(N={})),function(e){e.adUnitLog="ADUNIT-LOG"}(G||(G={}));class ${constructor(e){this.gfService=e}log({level:e,message:t,data:r,title:i}){this.gfService.trackEvent(G.adUnitLog,{log:{level:e,message:t,data:r,title:i}})}}const M=["debug","info","warn","error"];class K{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new L],title:e?.title??""}}static getInstance(e){return K.instance||(K.instance=new K(e)),K.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&M.indexOf(e)>=M.indexOf(this.config.minLevel)}createLogMessage(e,t,r){return{level:e,version:"1.1.1",message:t,timestamp:(new Date).toISOString(),data:r,title:this.config.title}}log(e,t,r){if(!this.shouldLog(e))return;const i=this.createLogMessage(e,t,r);this.config.transports.forEach((e=>e.log(i)))}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}class H{static register(e,t){this.strategies.set(e,t)}static get(e){return this.strategies.get(e)}static exists(e){return!(!e?.type||"string"!=typeof e?.type)&&this.strategies.has(e.type)}}H.strategies=new Map;class z{async handle(e,t){const{hostname:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger(),a=await i.getConfig().merchantExclusions,n=await i.getActiveDomains();s.debug("Checking hostname",{hostname:r});try{if(i.healthCheck(),a.some((e=>e.disableDomain&&(r===e.domain||r.endsWith(`.${e.domain}`)))))return s.debug("Hostname is in merchant exclusions",{hostname:r}),{type:P,payload:{isActive:!1,domain:void 0,rates:[]}};if(!n||0===n.length)throw new Error("No active domains");s.debug("Retrieved active domains",{count:n.length});const e=n.find((e=>r===e.Domain||r.endsWith(`.${e.Domain}`)));s.debug("Domain check result",{hostname:r,isActive:!!e});let t=[];if(e?.ID){const r=await i.getMerchantRates(e.Merchant.ID);r&&(s.debug("Retrieved merchant rates",{merchantRates:r}),t=r)}return{type:P,payload:{isActive:!!e,domain:e,rates:t}}}catch(e){return s.error("Error checking domain",{hostname:r,error:e}),{type:P,payload:{isActive:!1,domain:void 0,rates:[]}}}}}class j{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger(),s=await r.getCachedConfig();try{return i.debug("Fetching popup config"),{type:_,payload:{config:s}}}catch(e){return i.error("Error fetching popup config",{error:e}),{type:_,payload:{config:null}}}}}class Y{async handle(e,t){const{days:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=new Date;return e.setDate(e.getDate()+r),await l.set("popup_hide",{popupHide:e.getTime()}),s.debug("Popup hidden",{days:r,expiry:e}),{type:T,payload:{ack:!0}}}catch(e){return s.error("Error hiding popup",{days:r,error:e}),{type:T,payload:{ack:!1}}}}}class B{async handle(e,t){const{activeDomain:r,url:i}=e.payload,{giveFreelyService:s}=t,a=s.getLogger();a.debug("Checking if we should stand down",{activeDomain:r});try{const e=await s.shouldStandDown(r,i);return{type:U,payload:{result:e}}}catch(e){return a.error("Error checking if we should stand down. Returning false",{activeDomain:r,error:e}),{type:U,payload:{result:!1}}}}}class W{constructor(t,r,i=60){this._config=null,this.track=async(t,r,i)=>{null===this._config&&(this._config=await new S(this._partnerApiKey).getConfig());const s={partner:`adUnit_${this._partnerApiKey}`,eventType:t,eventData:{userId:this._userService?.user?.id,libVersion:String(e)??"",wfDeviceId:r,...i}};try{const e=JSON.stringify(s);return await this.shouldBroadcastEvent(e)?(await fetch(this._config.eventsUrl,{headers:{"Content-Type":"application/json"},method:"POST",body:e,cache:"no-store"}),await this.pushEventToHistory(e),!0):(this.log("This event has already been broadcasted during the past hour",s),!1)}catch(e){return this.log("Something unexpected happened when dispatching a gf event",e,s),!1}},this.log=(...e)=>{"debug"===this._config?.backgroundMinLogLevel&&console.log("analytics:",...e)},this.getEventsHistory=async()=>{const{GF_AD_EVENT_HISTORY:e}=await s.storage.local.get({GF_AD_EVENT_HISTORY:""}),t=function(e){const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()}(-this._debounceWindowInMinutes);let r=(e||[]).filter((e=>e.createdAt>t));return await s.storage.local.set({GF_AD_EVENT_HISTORY:r}),r},this.shouldBroadcastEvent=async e=>!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await s.storage.local.set({GF_AD_EVENT_HISTORY:t})},this._partnerApiKey=t,this._userService=r,this._debounceWindowInMinutes=i}}W.trackEvent=async(e,t)=>{await async function(e){return new Promise(((t,r)=>{try{const i=i=>{if(chrome.runtime.lastError)return r({error:chrome.runtime.lastError,message:e});t(i)};s.runtime.sendMessage(e,i)}catch(e){r(e)}}))}({type:I,payload:{eventType:e,eventData:t}})};class q{async handle(e,t){const{eventType:r,eventData:i}=e.payload,{giveFreelyService:s}=t,a=s.getLogger();a.debug("Broadcasting event",{eventType:r,eventData:i});try{const e=await s.trackEvent(r,i);return{type:I,payload:{result:e}}}catch(e){return a.error("Error broadcasting event. Returning false",{eventType:r,eventData:i}),{type:I,payload:{result:!1}}}}}class V{async handle(e,t){const{activeDomain:r,originalUrl:i,selectedCharity:a}=e.payload,{giveFreelyService:n}=t,o=n.getLogger();o.debug("Activating offer",{activeDomain:r,selectedCharity:a});try{if(!a?.ein||!a?.thirdPartyId)throw new Error("Missing charity information");const e=await n.initializeWfDeviceId();if(!e)throw new Error("Failed to initialize Wildfire device ID");const t=await n.upsertUser(a,e);o.debug("Upserted user",{currentUser:t}),t||o.info("Failed to create user. Using default bucket's user");const g=await n.generateAffiliateUrl(r,i,t);return o.debug("Generated affiliate URL",{affiliateUrl:g}),(async e=>{const t=s.tabs.getCurrent(),r=await t,i=await s.tabs.create({url:e,openerTabId:r?.id,active:!1,pinned:!0});await(async e=>new Promise((t=>{s.tabs.onUpdated.addListener((async function r(i,a){if(i===e&&"complete"===a.status){if(s.tabs.onUpdated.removeListener(r),!(await s.tabs.get(e)).url)return void t(!1);t(!0)}}))})))(i.id)&&setTimeout((()=>{i?.id&&s.tabs.remove(i.id)}),3e4)})(g),await n.updateStanddownHistory(r.Domain),o.debug("Activated offer",{activeDomain:r,selectedCharity:a}),{type:D,payload:{response:!0}}}catch(e){return o.error("Error activating offer",{activeDomain:r,error:e}),n.trackEvent(N.checkoutPopupFailedActivation,{activeDomain:r,error:e}),{type:D,payload:{response:!1}}}}}var X;!function(e){e[e.Pending=0]="Pending",e[e.Ready=1]="Ready",e[e.Received=2]="Received",e[e.Donated=3]="Donated",e[e.Disqualified=4]="Disqualified"}(X||(X={}));class Z{constructor(e,t,r){this.adUnitId=e,this.config=t,this.logger=r}async getAnonymousUserCommissions(e,t){try{const r=new URLSearchParams(t).toString(),i=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.getAnonymousUserComissionsPath}?${r}`,{method:"GET",headers:{"Content-Type":"application/json","X-AnonymousUserToken":e}});if(!i.ok)throw new Error("Failed to fetch commissions");return await i.json()}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error fetching anonymous user's commissions:",{error:e}),e}}async createOrUpdateAnonymousUser(e,t){try{const r=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.createAnonymousUserPath}?adUnitId=${this.adUnitId}`,{method:"PUT",headers:{"Content-Type":"application/json","X-GF-Platform":"adUnitLibrary","X-AnonymousUserToken":t??""},body:JSON.stringify(e)});if(!r.ok)throw new Error("Failed to create/update anonymous user");this.logger.info("[GiveFreelyApiClient] anonymous user created/updated succesfuly.");const i=await r.json(),s=r.headers.get("X-AnonymousUserToken");return{resultUser:{...i,charity:{ein:i.selectedCharity,thirdPartyId:i.selectedCharityThirdPartyIdentifier,name:void 0}},resultToken:s}}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error creating anonymous user:",{error:e}),e}}}class J{constructor(e,t){this.ANONYMOUS_USER_STORAGE_KEY="gf_anonymous_user_info",this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY="gf_anonymous_encrypted_token",this._giveFreelyApiClient=e,this._logger=t,this.user=null}async resetUser(){await l.remove(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY),await l.remove(this.ANONYMOUS_USER_STORAGE_KEY)}async upsertUser(e,t){const r=await this.fetchUser();try{const i={selectedCharity:e?.ein,selectedCharityThirdPartyIdentifier:e?.thirdPartyId,deviceId:t};if(!await this.shouldCreateOrUpdateUser(r,i))return this.user=r,r;const s=await l.get(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY),{resultUser:a,resultToken:n}=await this._giveFreelyApiClient.createOrUpdateAnonymousUser(i,s);return n&&await l.set(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY,n),a&&(await l.set(this.ANONYMOUS_USER_STORAGE_KEY,a),this.user=a),a}catch(e){this._logger.error("Error creating/updating anonymous user:",e)}return this.user=r,r}async fetchUser(){return await l.get(this.ANONYMOUS_USER_STORAGE_KEY)}async shouldCreateOrUpdateUser(e,t){return!e||e.charity?.ein!==t.selectedCharity||e.charity?.thirdPartyId!==t.selectedCharityThirdPartyIdentifier||e.deviceId!==t.deviceId}}const Q=e=>{try{return new URL(e),!0}catch(e){return!1}},ee=new Set,te=new Set,re={urls:["<all_urls>"],types:["main_frame"]};class ie{async handle(e,t){const r=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=k,t=await l.get(e)||[],i=t.findIndex((e=>e.shopId===r.shopId));return i>=0?t[i]=r:t.push(r),await l.set(e,t),s.debug("Stored Shopify shop ID",{shopInfo:r}),{type:O,payload:{success:!0}}}catch(e){return s.error("Error storing Shopify shop ID",{shopInfo:r,error:e}),{type:O,payload:{success:!1}}}}}class se{async handle(e,t){const{shopId:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=k,t=(await l.get(e)||[]).find((e=>e.shopId===r));return t?(s.debug("Found domain for shop ID",{shopId:r,domain:t.domain}),{type:R,payload:{found:!0,domain:t.domain,shopInfo:t}}):(s.debug("No domain found for shop ID",{shopId:r}),{type:R,payload:{found:!1}})}catch(e){return s.error("Error getting domain for shop ID",{shopId:r,error:e}),{type:R,payload:{found:!1}}}}}const ae="version";class ne{constructor(e,t){this.lastCheck=null,this.trackEvent=e,this.logger=t}async initialize(){const e=await l.get(F);e&&(this.lastCheck=e)}getToday(){return(new Date).toISOString().split("T")[0]}async check(){try{const e=this.lastCheck??0,t=this.getToday();(e?new Date(e).toISOString().split("T")[0]:null)!==t&&(await this.trackEvent(N.checkoutPopupHealthCheck,{language:chrome.i18n.getUILanguage()}),this.lastCheck=Date.now(),await l.set(F,this.lastCheck))}catch(e){this.logger.error("Health check failed",{error:e instanceof Error?e.message:"Unknown error"})}}}class oe extends Error{constructor(e="Service not initialized"){super(e),this.name="UninitializedServiceError"}}class GiveFreelyService{constructor(e){this.partnerApiKey=e,this.dependencies={configService:new S(e)},this.logger=K.getInstance(),this.logger.configure({enabled:!0,title:"Background - GiveFreelyService"}),this.state={initialized:!1,wildfireService:null,partnerFilter:null,config:null,wfDeviceId:null,analytics:null,giveFreelyUserService:null,partnerApiKey:e,healthCheck:null}}assertInitialized(){if(!this.state.initialized)throw new oe}async initialize(t=()=>!0){var r;if(!this.state.initialized)try{const i=await this.dependencies.configService.getConfig();this.logger.configure({minLevel:i.backgroundMinLogLevel??"error"}),this.logger.info("Initializing GiveFreelyService",{partnerApiKey:this.partnerApiKey});const a=this.createWildfireService(i),n=await(async(t=!0)=>{const r=await l.get(ae),i=await String(e),s=r!==i;return t&&s&&await(async e=>await l.set(ae,e))(i),s})();n&&this.logger.info("New version detected."),this.state.healthCheck=new ne(this.trackEvent.bind(this),this.logger),await this.state.healthCheck.initialize(),await a.refreshCache(n);const g=new Z(this.partnerApiKey,i,this.logger);this.state.giveFreelyUserService=new J(g,this.logger),await this.state.giveFreelyUserService.upsertUser(),this.state.analytics=new W(this.partnerApiKey,this.state.giveFreelyUserService),this.logger.addTransport(new $(this)),H.register(P,new z),H.register(_,new j),H.register(T,new Y),H.register(U,new B),H.register(I,new q),H.register(D,new V),H.register(O,new ie),H.register(R,new se),this.state.wildfireService=a,this.state.partnerFilter=t,this.state.config=i,this.state.initialized=!0,o.webRequest&&(o.webRequest.onBeforeRequest.addListener((e=>{const t=e.getLogger();return({requestId:r,url:i,initiator:s})=>{try{if(ee.has(r)||te.has(r)||!Q(i))return;const{hostname:a,search:n}=new URL(i);if(a.includes("wild.link"))return t.info("Cashback activation request identified, ignoring affiliate check for request"),void te.add(r);let o;s&&Q(s)&&(o=new URL(s).hostname),e.hasAffiliation([a,o],n)&&(t.info("Affiliation found on url, adding request id to track"),ee.add(r))}catch(e){t.error("Error on handleAffiliateOnBeforeRequest",e)}}})(this),re),o.webRequest.onBeforeRedirect.addListener((e=>{const t=e.getLogger();return async({requestId:r,redirectUrl:i})=>{try{if(!ee.has(r))return;t.info("Attempting to find active domain");const s=new URL(i).hostname,a=(await e.getActiveDomains()).find((e=>s===e.Domain||s.endsWith("."+e.Domain)));if(!a)return;t.info("Found active domain. Updating standdown state"),await v(a.Domain)}catch(e){t.error("Error on handleAffiliateOnBeforeRedirect",e)}}})(this),re),o.webRequest.onCompleted.addListener((()=>{const e=this.getLogger();return({requestId:t})=>{try{ee.has(t)&&(e.info("Tracking request completed. Request Id:",t),ee.delete(t))}catch(t){e.error("Error on handleAffiliateOnCompleted",t)}}})(),re)),r=async(e,t)=>(this.logger.debug("Received message",{type:e.type,payload:e.payload}),this.handleMessage(e)),s.runtime.onMessage.addListener(((e,t,i)=>{function s(e){i(e)}const a=r(e,0);return a instanceof Promise?(a.then((e=>{e&&s(e)})).catch((e=>{console.warn("Async message callback error:",e)})),!0):a})),this.logger.info("GiveFreelyService initialized successfully")}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw this.logger.error("Failed to initialize GiveFreelyService",{error:t}),new Error(`Failed to initialize GiveFreelyService: ${t}`)}}getConfig(){return this.assertInitialized(),this.state.config}async getCachedConfig(){return this.state.config=await this.dependencies.configService.getConfig(),this.logger.configure({minLevel:this.state.config.backgroundMinLogLevel??"error"}),this.state.config}async getActiveDomains(){return this.assertInitialized(),await this.state.wildfireService.getActiveDomains()}async shouldStandDown(e,t){if(this.assertInitialized(),this.getConfig().merchantExclusions.some((t=>t.mutePopups&&e===t.domain)))return this.logger.info("Should standdown due to merchant exclusions"),!0;const r=await this.state.wildfireService.shouldStandDown(this.logger,e,t);return r&&this.logger.info("Should standdown due to vendor policy"),r}hasAffiliation(e,t){if(!this.state.wildfireService)return this.logger.warn("Wildfire service not initialized yet"),!1;const r=this.state.wildfireService.hasAffilliation(e,t);return r&&this.logger.info("Affiliation identified"),r}async trackEvent(e,t){return this.assertInitialized(),await this.state.analytics.track(e,this.state.wfDeviceId?.DeviceID,t)}getLogger(){return this.assertInitialized(),this.logger}async initializeWfDeviceId(){if(this.assertInitialized(),this.state.wfDeviceId=await this.state.wildfireService.getDevice(),!this.state.wfDeviceId)throw new Error("Failed to initialize Wildfire device ID");return this.state.wfDeviceId.DeviceID}getWfDeviceId(){return this.assertInitialized(),this.state.wfDeviceId.DeviceID}async upsertUser(e,t){return this.assertInitialized(),await this.state.giveFreelyUserService.upsertUser(e,t)}async getCurrentUser(){return this.assertInitialized(),await this.state.giveFreelyUserService.user}async generateAffiliateUrl(e,t,r){return this.assertInitialized(),await this.state.wildfireService.generateAffiliateUrl(e,t,r,this.state.partnerApiKey)}async updateStanddownHistory(e){return this.assertInitialized(),await v(e)}isAdUnitMessage(e){return this.assertInitialized(),H.exists(e)}async getMerchantRates(e){if(this.assertInitialized(),!this.state.wildfireService)throw new Error("Wildfire service not initialized");return await this.state.wildfireService.getMerchantRates(e)}async healthCheck(){this.assertInitialized(),await this.state.healthCheck.check()}async handleMessage(e){this.assertInitialized();const t=H.get(e.type);if(!t)return;const r={giveFreelyService:this};return t.handle(e,r)}createWildfireService(e){this.logger.debug("config",this.state.config);const t=new g(e.wfSecret,e.wfAppId,e.deviceUrl,e.dataUrl,this.logger);return new b(t,this.logger,e.vanityBaseUrl,e.refreshInterval)}async destroy(){this.logger.info("Destroying GiveFreelyService"),await Promise.all([this.dependencies.configService.clearCache(),this.state.wildfireService?.clearCache(),this.state.giveFreelyUserService?.resetUser()]),this.state.initialized=!1,this.state.wildfireService=null,this.state.partnerFilter=null,this.state.analytics=null,this.state.config=null}}export{GiveFreelyService,s as browser};
1
+ const e="1.1.0",t=3,r=e=>1e3*e;async function i(e,i={}){const{maxAttempts:s=t,delayFn:a=r}=i;let n=null;for(let t=1;t<=s;t++)try{return await e()}catch(e){n=e,t<s&&await new Promise((e=>setTimeout(e,a(t))))}throw n||new Error("Operation failed after multiple attempts")}const s=chrome;function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var n={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",r=e=>{const r={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(r).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class i extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const s=(t,r)=>(...i)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):r.singleCallbackArg||i.length<=1&&!1!==r.singleCallbackArg?t.resolve(i[0]):t.resolve(i)},a=e=>1==e?"argument":"arguments",n=(e,t,r)=>new Proxy(t,{apply:(t,i,s)=>r.call(i,e,...s)});let o=Function.call.bind(Object.prototype.hasOwnProperty);const g=(e,t={},r={})=>{let i=Object.create(null),c={has:(t,r)=>r in e||r in i,get(c,l,h){if(l in i)return i[l];if(!(l in e))return;let d=e[l];if("function"==typeof d)if("function"==typeof t[l])d=n(e,e[l],t[l]);else if(o(r,l)){let t=((e,t)=>function(r,...i){if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${a(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${a(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((a,n)=>{if(t.fallbackToNoCallback)try{r[e](...i,s({resolve:a,reject:n},t))}catch(s){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,s),r[e](...i),t.fallbackToNoCallback=!1,t.noCallback=!0,a()}else t.noCallback?(r[e](...i),a()):r[e](...i,s({resolve:a,reject:n},t))}))})(l,r[l]);d=n(e,e[l],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(o(t,l)||o(r,l)))d=g(d,t[l],r[l]);else{if(!o(r,"*"))return Object.defineProperty(i,l,{configurable:!0,enumerable:!0,get:()=>e[l],set(t){e[l]=t}}),d;d=g(d,t[l],r["*"])}return i[l]=d,d},set:(t,r,s,a)=>(r in i?i[r]=s:e[r]=s,!0),defineProperty:(e,t,r)=>Reflect.defineProperty(i,t,r),deleteProperty:(e,t)=>Reflect.deleteProperty(i,t)},l=Object.create(e);return new Proxy(l,c)},c=e=>({addListener(t,r,...i){t.addListener(e.get(r),...i)},hasListener:(t,r)=>t.hasListener(e.get(r)),removeListener(t,r){t.removeListener(e.get(r))}}),l=new i((e=>"function"!=typeof e?e:function(t){const r=g(t,{},{getContent:{minArgs:0,maxArgs:0}});e(r)})),h=new i((e=>"function"!=typeof e?e:function(t,r,i){let s,a,n=!1,o=new Promise((e=>{s=function(t){n=!0,e(t)}}));try{a=e(t,r,s)}catch(e){a=Promise.reject(e)}const g=!0!==a&&((c=a)&&"object"==typeof c&&"function"==typeof c.then);var c;if(!0!==a&&!g&&!n)return!1;return(g?a:o).then((e=>{i(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",i({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:r,resolve:i},s)=>{e.runtime.lastError?e.runtime.lastError.message===t?i():r(new Error(e.runtime.lastError.message)):s&&s.__mozWebExtensionPolyfillReject__?r(new Error(s.message)):i(s)},m=(e,t,r,...i)=>{if(i.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${a(t.minArgs)} for ${e}(), got ${i.length}`);if(i.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${a(t.maxArgs)} for ${e}(), got ${i.length}`);return new Promise(((e,t)=>{const s=d.bind(null,{resolve:e,reject:t});i.push(s),r.sendMessage(...i)}))},u={devtools:{network:{onRequestFinished:c(l)}},runtime:{onMessage:c(h),onMessageExternal:c(h),sendMessage:m.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:m.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},f={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return r.privacy={network:{"*":f},services:{"*":f},websites:{"*":f}},g(e,u,r)};e.exports=r(chrome)}}(n);var o=a(n.exports);class g{constructor(e,t,r,i,s){this.wfSecret=e,this.wfAppId=t,this.deviceUrl=r,this.dataUrl=i,this._logger=s}async getWildfireDevice(){return(await fetch(this.deviceUrl,{method:"POST",body:JSON.stringify({}),headers:{"Content-Type":"application/json","WF-Secret":this.wfSecret,"WF-App-ID":this.wfAppId}})).json()}async getActiveDomains(){return(await fetch(`${this.dataUrl}/${this.wfAppId}/active-domain/1`)).json()}async getStanddownPolicy(){const e=`${this.dataUrl}/${this.wfAppId}/stand-down-policy/1`;try{const t=await fetch(e);if(t.ok)return t.json();throw new Error(`Failed to fetch standdown policy. Status ${t.status}`)}catch(t){return this._logger.error("Failed to fetch the standdown policy",{err:t,url:e}),{Domains:[],LostAttribution:[],Params:[],Serp:[]}}}async getMerchantRates(){const e=`${this.dataUrl}/${this.wfAppId}/merchant-rate/1`;try{const t=await fetch(e);if(this._logger.debug("Merchant rates response",{response:t}),!t.ok)throw new Error(`Failed to fetch merchant rates. Status ${t.status}`);const r=t.json();return this._logger.debug("Merchant rates",{rates:r}),r}catch(t){return this._logger.error("Failed to fetch the merchant rates",{err:t,url:e}),[]}}}const c="GIVE_FREELY_",l={async get(e){const t=`${c}${e}`;return(await o.storage.local.get(t))[t]||null},async set(e,t){const r=`${c}${e}`;await o.storage.local.set({[r]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${c}${e}`)):`${c}${e}`;await o.storage.local.remove(t)}},h="wfDevice",d="wfDomains",m="wfStanddownPolicy",u="wfStanddownHistory",f="wfLastCacheRefresh",A="wfMerchantRates";async function y(e,t,r){try{const i=(await w())?.[t];if(i&&i>Date.now())return e.info("Standing down because current affiliate stand down session has not expired"),v(t),!0;await this.refreshCache();const s=await this.getStanddownPolicy();if(E(s,new URL(r).search))return e.info("Standing down because url has affiliate params"),v(t),!0;e.info("No need to stand down.")}catch(t){e.error("Exception produced when trying to determine if it should stand down",t)}return!1}function p(e,t){if(!this.standDownPolicy)return this.logger.warn("Couldnt check affilliation. No stand down policy found"),this.getStanddownPolicy().then((e=>this.standDownPolicy=e)),!1;const r=e.some((e=>x(this.standDownPolicy,e)))||E(this.standDownPolicy,t);return this.logger.info("Affilliation result:",r),r}const w=async()=>await l.get(u),v=async(e,t=1)=>{const r=await w()??{};r[e]=Date.now()+60*t*60*1e3,await l.set(u,r)},x=(e,t)=>{if(!t)return!1;const{Domains:r}=e;return r.some((e=>t.includes(e)))},E=(e,t)=>{if(!t)return!1;const{Params:r}=e;return r.some((e=>t.toLowerCase().includes("?"+e.toLowerCase())))||r.some((e=>t.toLowerCase().includes("&"+e.toLowerCase())))};class C{constructor(e,t,r,i){this.userId=e,this.charityEin=t,this.charityThirdPartyIdentifier=r,this.partnerId=i}toString(){return`userId=${this.encodeUserId(this.userId)},charityEin=${this.charityEin},charityThirdPartyIdentifier=${this.charityThirdPartyIdentifier},partnerId=${this.partnerId}`}encodeUserId(e){return btoa(e).replace(/_/g,"/").replace(/-/g,"+")}}class b{constructor(e,t,r,i=21600){if(this.standDownPolicy=null,this.shouldStandDown=y.bind(this),this.hasAffilliation=p.bind(this),!e||!r)throw new Error("WildfireService requires wildfireClient and vanityBaseUrl");this.wildfireClient=e,this.vanityBaseUrl=r.replace(/\/$/,""),this.refreshInterval=i,this.logger=t}async getActiveDomains(){try{await this.refreshCache();const e=await l.get(d);if(!e)throw Error("Failed to retrieve active domains");return e}catch(e){throw this.logger.error("Failed to get active domains:",e),new Error("Failed to retrieve active domains")}}async getMerchantRates(e){try{await this.refreshCache();const t=await l.get(A);if(!t)throw new Error("Failed to retrieve merchant rates");return t[e]}catch(e){throw this.logger.error("Failed to retrieve merchant rates:",e),new Error("Failed to retrieve merchant rates")}}async generateAffiliateUrl(e,t,r,i){if(!e||!t||!i)throw new Error("Missing required parameters for affiliate URL generation");try{const s=await this.getDevice(),a=await this.generateTrackingCode(r,i,s),n=encodeURIComponent(t),o=encodeURIComponent(a);return`${this.vanityBaseUrl}/e?d=${s.DeviceID}&c=${e.ID}&tc=${o}&url=${n}`}catch(e){throw this.logger.error("Failed to generate affiliate URL:",e),new Error("Failed to generate affiliate URL")}}async clearCache(){try{await Promise.all([l.remove(h),l.remove(d),l.remove(f),l.remove(m),l.remove(A)])}catch(e){throw this.logger.error("Failed to clear cache:",e),new Error("Failed to clear cache")}}async refreshCache(e=!1){try{const t=await l.get(f),r=Date.now();(e||!t||r-t>1e3*this.refreshInterval)&&(await Promise.all([this.syncActiveDomains(),this.syncStanddownPolicy(),this.syncMerchantRates()]),await l.set(f,r)),this.standDownPolicy=await this.getStanddownPolicy()}catch(e){throw this.logger.error("Failed to refresh cache:",e),new Error("Failed to refresh cache")}}async getStanddownPolicy(){return await l.get(m)??(()=>{throw new Error("Failed to retrieve standdown policy. Storage value was null")})()}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async getDevice(){try{const e=await l.get(h);return e?.DeviceID?e:i((()=>this.fetchAndStoreDevice()),this.getRetryOptions())}catch(e){throw this.logger.error("Failed to get device:",e),new Error("Failed to retrieve device information")}}async fetchAndStoreDevice(){const e=await this.wildfireClient.getWildfireDevice();if(!e?.DeviceID)throw new Error("Failed to retrieve device information");return await l.set(h,e),e}async generateTrackingCode(e,t,r){if(!(e?.id&&e?.charity&&e?.charity.ein&&e?.charity.thirdPartyId)){const e=`notregistered-${r.DeviceID}`;return this.logger.info("User not provided. Using GF's default bucket instead.",e),e}return new C(e.id,e.charity.ein,e.charity.thirdPartyId,t).toString()}async syncActiveDomains(){const e=await i((()=>this.wildfireClient.getActiveDomains()),this.getRetryOptions());return await l.set(d,e),e}async syncStanddownPolicy(){const e=await i((()=>this.wildfireClient.getStanddownPolicy()),this.getRetryOptions());return this.logger.info("Updated standdown policy",e),await l.set(m,e),e}async syncMerchantRates(){const e=await i((()=>this.wildfireClient.getMerchantRates()),this.getRetryOptions());return this.logger.debug("Merchant rates",e),await l.set(A,e),e}}class S{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0,this.CONFIG_REFRESH_INTERVAL=3e5,this.PARTNER_CONFIG_STORAGE_KEY="gf_partner_config",this.GLOBAL_CONFIG_STORAGE_KEY="gf_global_config"}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchAndUpdatePartnerConfig(){const e=await i((async()=>{const e=await fetch(`https://cdn.givefreely.com/adunit/config/${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await l.set(this.PARTNER_CONFIG_STORAGE_KEY,t),e}async fetchAndUpdateGlobalConfig(){const e=await i((async()=>{const e=await fetch("https://cdn.givefreely.com/adunit/config/global.json",{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await l.set(this.GLOBAL_CONFIG_STORAGE_KEY,t),e}async getConfig(){const e=Date.now(),t=await l.get(this.PARTNER_CONFIG_STORAGE_KEY),r=await l.get(this.GLOBAL_CONFIG_STORAGE_KEY);if(this.partnerConfig=t?.config||null,this.globalConfig=r?.config||null,this.lastConfigRefresh=Math.max(t?.lastRefresh||0,r?.lastRefresh||0),!this.partnerConfig||!this.globalConfig||e-this.lastConfigRefresh>this.CONFIG_REFRESH_INTERVAL)try{const[t,r]=await Promise.all([this.fetchAndUpdatePartnerConfig(),this.fetchAndUpdateGlobalConfig()]);this.partnerConfig=t,this.globalConfig=r,this.lastConfigRefresh=e}catch(e){if(!this.partnerConfig||!this.globalConfig)throw e;console.warn("Failed to refresh configs, using existing configs:",e)}const i=this.mergeConfigs(this.globalConfig,this.partnerConfig);return((e,t,r)=>{const i=[...t.merchantExclusions??[],...r.merchantExclusions??[]];e.merchantExclusions=i})(i,this.globalConfig,this.partnerConfig),i}async clearCache(){await Promise.all([l.remove(this.PARTNER_CONFIG_STORAGE_KEY),l.remove(this.GLOBAL_CONFIG_STORAGE_KEY)]),this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0}mergeConfigs(e,t){if(!t)return e;const r={...e};for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const s=e,a=t;"object"==typeof a[i]&&null!==a[i]&&"object"==typeof s[i]?r[i]=this.mergeConfigs(s[i],a[i]):r[i]=void 0!==a[i]?a[i]:s[i]}return r}getStoredState(e){return e?{config:e.config,lastRefresh:e.lastRefresh}:{config:null,lastRefresh:0}}}const I="TRACK_EVENT",T="GF_HIDE_POPUP",_="GF_GET_POPUP_CONFIG",P="GF_IS_ACTIVE_DOMAIN",U="GF_SHOULD_STAND_DOWN",D="GF_ACTIVATE_OFFER",O="GF_STORE_SHOPIFY_SHOP_ID",R="GF_GET_DOMAIN_BY_SHOP_ID",k="shopify_shop_ids",F="gf_last_health_check";class L{log({level:e,message:t,timestamp:r,data:i,title:s}){const a="debug"===e?"log":e,n=s?`[${s}]`:"";void 0!==i?console[a](`[${r}] - ${L.LOGGER_PREFIX} ${n} ${t}`,i):console[a](`[${r}] - ${L.LOGGER_PREFIX} ${n} ${t}`)}}var N,G;L.LOGGER_PREFIX="[GFAdUnit] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED"}(N||(N={})),function(e){e.adUnitLog="ADUNIT-LOG"}(G||(G={}));class ${constructor(e){this.gfService=e}log({level:e,message:t,data:r,title:i}){this.gfService.trackEvent(G.adUnitLog,{log:{level:e,message:t,data:r,title:i}})}}const M=["debug","info","warn","error"];class K{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new L],title:e?.title??""}}static getInstance(e){return K.instance||(K.instance=new K(e)),K.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&M.indexOf(e)>=M.indexOf(this.config.minLevel)}createLogMessage(e,t,r){return{level:e,version:"1.1.0",message:t,timestamp:(new Date).toISOString(),data:r,title:this.config.title}}log(e,t,r){if(!this.shouldLog(e))return;const i=this.createLogMessage(e,t,r);this.config.transports.forEach((e=>e.log(i)))}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}class H{static register(e,t){this.strategies.set(e,t)}static get(e){return this.strategies.get(e)}static exists(e){return!(!e?.type||"string"!=typeof e?.type)&&this.strategies.has(e.type)}}H.strategies=new Map;class z{async handle(e,t){const{hostname:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger(),a=await i.getConfig().merchantExclusions,n=await i.getActiveDomains();s.debug("Checking hostname",{hostname:r});try{if(i.healthCheck(),a.some((e=>e.disableDomain&&(r===e.domain||r.endsWith(`.${e.domain}`)))))return s.debug("Hostname is in merchant exclusions",{hostname:r}),{type:P,payload:{isActive:!1,domain:void 0,rates:[]}};if(!n||0===n.length)throw new Error("No active domains");s.debug("Retrieved active domains",{count:n.length});const e=n.find((e=>r===e.Domain||r.endsWith(`.${e.Domain}`)));s.debug("Domain check result",{hostname:r,isActive:!!e});let t=[];if(e?.ID){const r=await i.getMerchantRates(e.Merchant.ID);r&&(s.debug("Retrieved merchant rates",{merchantRates:r}),t=r)}return{type:P,payload:{isActive:!!e,domain:e,rates:t}}}catch(e){return s.error("Error checking domain",{hostname:r,error:e}),{type:P,payload:{isActive:!1,domain:void 0,rates:[]}}}}}class j{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger(),s=await r.getCachedConfig();try{return i.debug("Fetching popup config"),{type:_,payload:{config:s}}}catch(e){return i.error("Error fetching popup config",{error:e}),{type:_,payload:{config:null}}}}}class Y{async handle(e,t){const{days:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=new Date;return e.setDate(e.getDate()+r),await l.set("popup_hide",{popupHide:e.getTime()}),s.debug("Popup hidden",{days:r,expiry:e}),{type:T,payload:{ack:!0}}}catch(e){return s.error("Error hiding popup",{days:r,error:e}),{type:T,payload:{ack:!1}}}}}class B{async handle(e,t){const{activeDomain:r,url:i}=e.payload,{giveFreelyService:s}=t,a=s.getLogger();a.debug("Checking if we should stand down",{activeDomain:r});try{const e=await s.shouldStandDown(r,i);return{type:U,payload:{result:e}}}catch(e){return a.error("Error checking if we should stand down. Returning false",{activeDomain:r,error:e}),{type:U,payload:{result:!1}}}}}class W{constructor(t,r,i=60){this._config=null,this.track=async(t,r,i)=>{null===this._config&&(this._config=await new S(this._partnerApiKey).getConfig());const s={partner:`adUnit_${this._partnerApiKey}`,eventType:t,eventData:{userId:this._userService?.user?.id,libVersion:String(e)??"",wfDeviceId:r,...i}};try{const e=JSON.stringify(s);return await this.shouldBroadcastEvent(e)?(await fetch(this._config.eventsUrl,{headers:{"Content-Type":"application/json"},method:"POST",body:e,cache:"no-store"}),await this.pushEventToHistory(e),!0):(this.log("This event has already been broadcasted during the past hour",s),!1)}catch(e){return this.log("Something unexpected happened when dispatching a gf event",e,s),!1}},this.log=(...e)=>{"debug"===this._config?.backgroundMinLogLevel&&console.log("analytics:",...e)},this.getEventsHistory=async()=>{const{GF_AD_EVENT_HISTORY:e}=await s.storage.local.get({GF_AD_EVENT_HISTORY:""}),t=function(e){const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()}(-this._debounceWindowInMinutes);let r=(e||[]).filter((e=>e.createdAt>t));return await s.storage.local.set({GF_AD_EVENT_HISTORY:r}),r},this.shouldBroadcastEvent=async e=>!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await s.storage.local.set({GF_AD_EVENT_HISTORY:t})},this._partnerApiKey=t,this._userService=r,this._debounceWindowInMinutes=i}}W.trackEvent=async(e,t)=>{await async function(e){return new Promise(((t,r)=>{try{const i=i=>{if(chrome.runtime.lastError)return r({error:chrome.runtime.lastError,message:e});t(i)};s.runtime.sendMessage(e,i)}catch(e){r(e)}}))}({type:I,payload:{eventType:e,eventData:t}})};class q{async handle(e,t){const{eventType:r,eventData:i}=e.payload,{giveFreelyService:s}=t,a=s.getLogger();a.debug("Broadcasting event",{eventType:r,eventData:i});try{const e=await s.trackEvent(r,i);return{type:I,payload:{result:e}}}catch(e){return a.error("Error broadcasting event. Returning false",{eventType:r,eventData:i}),{type:I,payload:{result:!1}}}}}class V{async handle(e,t){const{activeDomain:r,originalUrl:i,selectedCharity:a}=e.payload,{giveFreelyService:n}=t,o=n.getLogger();o.debug("Activating offer",{activeDomain:r,selectedCharity:a});try{if(!a?.ein||!a?.thirdPartyId)throw new Error("Missing charity information");const e=await n.initializeWfDeviceId();if(!e)throw new Error("Failed to initialize Wildfire device ID");const t=await n.upsertUser(a,e);o.debug("Upserted user",{currentUser:t}),t||o.info("Failed to create user. Using default bucket's user");const g=await n.generateAffiliateUrl(r,i,t);return o.debug("Generated affiliate URL",{affiliateUrl:g}),(async e=>{const t=s.tabs.getCurrent(),r=await t,i=await s.tabs.create({url:e,openerTabId:r?.id,active:!1,pinned:!0});await(async e=>new Promise((t=>{s.tabs.onUpdated.addListener((async function r(i,a){if(i===e&&"complete"===a.status){if(s.tabs.onUpdated.removeListener(r),!(await s.tabs.get(e)).url)return void t(!1);t(!0)}}))})))(i.id)&&setTimeout((()=>{i?.id&&s.tabs.remove(i.id)}),3e4)})(g),await n.updateStanddownHistory(r.Domain),o.debug("Activated offer",{activeDomain:r,selectedCharity:a}),{type:D,payload:{response:!0}}}catch(e){return o.error("Error activating offer",{activeDomain:r,error:e}),n.trackEvent(N.checkoutPopupFailedActivation,{activeDomain:r,error:e}),{type:D,payload:{response:!1}}}}}var X;!function(e){e[e.Pending=0]="Pending",e[e.Ready=1]="Ready",e[e.Received=2]="Received",e[e.Donated=3]="Donated",e[e.Disqualified=4]="Disqualified"}(X||(X={}));class Z{constructor(e,t,r){this.adUnitId=e,this.config=t,this.logger=r}async getAnonymousUserCommissions(e,t){try{const r=new URLSearchParams(t).toString(),i=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.getAnonymousUserComissionsPath}?${r}`,{method:"GET",headers:{"Content-Type":"application/json","X-AnonymousUserToken":e}});if(!i.ok)throw new Error("Failed to fetch commissions");return await i.json()}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error fetching anonymous user's commissions:",{error:e}),e}}async createOrUpdateAnonymousUser(e,t){try{const r=await fetch(`${this.config.apiConfig.baseUri}/${this.config.apiConfig.createAnonymousUserPath}?adUnitId=${this.adUnitId}`,{method:"PUT",headers:{"Content-Type":"application/json","X-GF-Platform":"adUnitLibrary","X-AnonymousUserToken":t??""},body:JSON.stringify(e)});if(!r.ok)throw new Error("Failed to create/update anonymous user");this.logger.info("[GiveFreelyApiClient] anonymous user created/updated succesfuly.");const i=await r.json(),s=r.headers.get("X-AnonymousUserToken");return{resultUser:{...i,charity:{ein:i.selectedCharity,thirdPartyId:i.selectedCharityThirdPartyIdentifier,name:void 0}},resultToken:s}}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error creating anonymous user:",{error:e}),e}}}class J{constructor(e,t){this.ANONYMOUS_USER_STORAGE_KEY="gf_anonymous_user_info",this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY="gf_anonymous_encrypted_token",this._giveFreelyApiClient=e,this._logger=t,this.user=null}async resetUser(){await l.remove(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY),await l.remove(this.ANONYMOUS_USER_STORAGE_KEY)}async upsertUser(e,t){const r=await this.fetchUser();try{const i={selectedCharity:e?.ein,selectedCharityThirdPartyIdentifier:e?.thirdPartyId,deviceId:t};if(!await this.shouldCreateOrUpdateUser(r,i))return this.user=r,r;const s=await l.get(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY),{resultUser:a,resultToken:n}=await this._giveFreelyApiClient.createOrUpdateAnonymousUser(i,s);return n&&await l.set(this.ANONYMOUS_ENCRIPTED_TOKEN_STORAGE_KEY,n),a&&(await l.set(this.ANONYMOUS_USER_STORAGE_KEY,a),this.user=a),a}catch(e){this._logger.error("Error creating/updating anonymous user:",e)}return this.user=r,r}async fetchUser(){return await l.get(this.ANONYMOUS_USER_STORAGE_KEY)}async shouldCreateOrUpdateUser(e,t){return!e||e.charity?.ein!==t.selectedCharity||e.charity?.thirdPartyId!==t.selectedCharityThirdPartyIdentifier||e.deviceId!==t.deviceId}}const Q=e=>{try{return new URL(e),!0}catch(e){return!1}},ee=new Set,te=new Set,re={};class ie{async handle(e,t){const r=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=k,t=await l.get(e)||[],i=t.findIndex((e=>e.shopId===r.shopId));return i>=0?t[i]=r:t.push(r),await l.set(e,t),s.debug("Stored Shopify shop ID",{shopInfo:r}),{type:O,payload:{success:!0}}}catch(e){return s.error("Error storing Shopify shop ID",{shopInfo:r,error:e}),{type:O,payload:{success:!1}}}}}class se{async handle(e,t){const{shopId:r}=e.payload,{giveFreelyService:i}=t,s=i.getLogger();try{const e=k,t=(await l.get(e)||[]).find((e=>e.shopId===r));return t?(s.debug("Found domain for shop ID",{shopId:r,domain:t.domain}),{type:R,payload:{found:!0,domain:t.domain,shopInfo:t}}):(s.debug("No domain found for shop ID",{shopId:r}),{type:R,payload:{found:!1}})}catch(e){return s.error("Error getting domain for shop ID",{shopId:r,error:e}),{type:R,payload:{found:!1}}}}}const ae="version";class ne{constructor(e,t){this.lastCheck=null,this.trackEvent=e,this.logger=t}async initialize(){const e=await l.get(F);e&&(this.lastCheck=e)}getToday(){return(new Date).toISOString().split("T")[0]}async check(){try{const e=this.lastCheck??0,t=this.getToday();(e?new Date(e).toISOString().split("T")[0]:null)!==t&&(await this.trackEvent(N.checkoutPopupHealthCheck,{language:chrome.i18n.getUILanguage()}),this.lastCheck=Date.now(),await l.set(F,this.lastCheck))}catch(e){this.logger.error("Health check failed",{error:e instanceof Error?e.message:"Unknown error"})}}}class oe extends Error{constructor(e="Service not initialized"){super(e),this.name="UninitializedServiceError"}}class GiveFreelyService{constructor(e){this.partnerApiKey=e,this.dependencies={configService:new S(e)},this.logger=K.getInstance(),this.logger.configure({enabled:!0,title:"Background - GiveFreelyService"}),this.state={initialized:!1,wildfireService:null,partnerFilter:null,config:null,wfDeviceId:null,analytics:null,giveFreelyUserService:null,partnerApiKey:e,healthCheck:null}}assertInitialized(){if(!this.state.initialized)throw new oe}async initialize(t=()=>!0){var r;if(!this.state.initialized)try{const i=await this.dependencies.configService.getConfig();this.logger.configure({minLevel:i.backgroundMinLogLevel??"error"}),this.logger.info("Initializing GiveFreelyService",{partnerApiKey:this.partnerApiKey});const a=this.createWildfireService(i),n=await(async(t=!0)=>{const r=await l.get(ae),i=await String(e),s=r!==i;return t&&s&&await(async e=>await l.set(ae,e))(i),s})();n&&this.logger.info("New version detected."),this.state.healthCheck=new ne(this.trackEvent.bind(this),this.logger),await this.state.healthCheck.initialize(),await a.refreshCache(n);const g=new Z(this.partnerApiKey,i,this.logger);this.state.giveFreelyUserService=new J(g,this.logger),await this.state.giveFreelyUserService.upsertUser(),this.state.analytics=new W(this.partnerApiKey,this.state.giveFreelyUserService),this.logger.addTransport(new $(this)),H.register(P,new z),H.register(_,new j),H.register(T,new Y),H.register(U,new B),H.register(I,new q),H.register(D,new V),H.register(O,new ie),H.register(R,new se),this.state.wildfireService=a,this.state.partnerFilter=t,this.state.config=i,this.state.initialized=!0,o.webRequest&&(o.webRequest.onBeforeRequest.addListener((e=>{const t=e.getLogger();return({requestId:r,url:i,initiator:s})=>{try{if(ee.has(r)||te.has(r)||!Q(i))return;const{hostname:a,search:n}=new URL(i);if(a.includes("wild.link"))return t.info("Cashback activation request identified, ignoring affiliate check for request"),void te.add(r);let o;s&&Q(s)&&(o=new URL(s).hostname),e.hasAffiliation([a,o],n)&&(t.info("Affiliation found on url, adding request id to track"),ee.add(r))}catch(e){t.error("Error on handleAffiliateOnBeforeRequest",e)}}})(this),re),o.webRequest.onBeforeRedirect.addListener((e=>{const t=e.getLogger();return async({requestId:r,redirectUrl:i})=>{try{if(!ee.has(r))return;t.info("Attempting to find active domain");const s=new URL(i).hostname,a=(await e.getActiveDomains()).find((e=>s===e.Domain||s.endsWith("."+e.Domain)));if(!a)return;t.info("Found active domain. Updating standdown state"),await v(a.Domain)}catch(e){t.error("Error on handleAffiliateOnBeforeRedirect",e)}}})(this),re),o.webRequest.onCompleted.addListener((()=>{const e=this.getLogger();return({requestId:t})=>{try{ee.has(t)&&(e.info("Tracking request completed. Request Id:",t),ee.delete(t))}catch(t){e.error("Error on handleAffiliateOnCompleted",t)}}})(),re)),r=async(e,t)=>(this.logger.debug("Received message",{type:e.type,payload:e.payload}),this.handleMessage(e)),s.runtime.onMessage.addListener(((e,t,i)=>{function s(e){i(e)}const a=r(e,0);return a instanceof Promise?(a.then((e=>{e&&s(e)})).catch((e=>{console.warn("Async message callback error:",e)})),!0):a})),this.logger.info("GiveFreelyService initialized successfully")}catch(e){const t=e instanceof Error?e.message:"Unknown error";throw this.logger.error("Failed to initialize GiveFreelyService",{error:t}),new Error(`Failed to initialize GiveFreelyService: ${t}`)}}getConfig(){return this.assertInitialized(),this.state.config}async getCachedConfig(){return this.state.config=await this.dependencies.configService.getConfig(),this.logger.configure({minLevel:this.state.config.backgroundMinLogLevel??"error"}),this.state.config}async getActiveDomains(){return this.assertInitialized(),await this.state.wildfireService.getActiveDomains()}async shouldStandDown(e,t){if(this.assertInitialized(),this.getConfig().merchantExclusions.some((t=>t.mutePopups&&e===t.domain)))return this.logger.info("Should standdown due to merchant exclusions"),!0;const r=await this.state.wildfireService.shouldStandDown(this.logger,e,t);return r&&this.logger.info("Should standdown due to vendor policy"),r}hasAffiliation(e,t){if(!this.state.wildfireService)return this.logger.warn("Wildfire service not initialized yet"),!1;const r=this.state.wildfireService.hasAffilliation(e,t);return r&&this.logger.info("Affiliation identified"),r}async trackEvent(e,t){return this.assertInitialized(),await this.state.analytics.track(e,this.state.wfDeviceId?.DeviceID,t)}getLogger(){return this.assertInitialized(),this.logger}async initializeWfDeviceId(){if(this.assertInitialized(),this.state.wfDeviceId=await this.state.wildfireService.getDevice(),!this.state.wfDeviceId)throw new Error("Failed to initialize Wildfire device ID");return this.state.wfDeviceId.DeviceID}getWfDeviceId(){return this.assertInitialized(),this.state.wfDeviceId.DeviceID}async upsertUser(e,t){return this.assertInitialized(),await this.state.giveFreelyUserService.upsertUser(e,t)}async getCurrentUser(){return this.assertInitialized(),await this.state.giveFreelyUserService.user}async generateAffiliateUrl(e,t,r){return this.assertInitialized(),await this.state.wildfireService.generateAffiliateUrl(e,t,r,this.state.partnerApiKey)}async updateStanddownHistory(e){return this.assertInitialized(),await v(e)}isAdUnitMessage(e){return this.assertInitialized(),H.exists(e)}async getMerchantRates(e){if(this.assertInitialized(),!this.state.wildfireService)throw new Error("Wildfire service not initialized");return await this.state.wildfireService.getMerchantRates(e)}async healthCheck(){this.assertInitialized(),await this.state.healthCheck.check()}async handleMessage(e){this.assertInitialized();const t=H.get(e.type);if(!t)return;const r={giveFreelyService:this};return t.handle(e,r)}createWildfireService(e){this.logger.debug("config",this.state.config);const t=new g(e.wfSecret,e.wfAppId,e.deviceUrl,e.dataUrl,this.logger);return new b(t,this.logger,e.vanityBaseUrl,e.refreshInterval)}async destroy(){this.logger.info("Destroying GiveFreelyService"),await Promise.all([this.dependencies.configService.clearCache(),this.state.wildfireService?.clearCache(),this.state.giveFreelyUserService?.resetUser()]),this.state.initialized=!1,this.state.wildfireService=null,this.state.partnerFilter=null,this.state.analytics=null,this.state.config=null}}export{GiveFreelyService,s as browser};
@@ -1 +1 @@
1
- "use strict";const e="1.1.1",t={equals:(e,t)=>e===t};let n=C;const r=1,o=2,i={owned:null,cleanups:null,context:null,owner:null};var s=null;let a=null,l=null,c=null,g=null,u=0;function d(e,n){const r={value:e,observers:null,observerSlots:null,comparator:(n=n?Object.assign({},t,n):t).equals||void 0};return[A.bind(r),e=>("function"==typeof e&&(e=e(r.value)),b(r,e))]}function p(e,t,n){x(y(e,t,!1,r))}function m(e,t,o){n=k;const i=y(e,t,!1,r);i.user=!0,g?g.push(i):x(i)}function h(e,n,r){r=r?Object.assign({},t,r):t;const o=y(e,n,!0,0);return o.observers=null,o.observerSlots=null,o.comparator=r.equals||void 0,x(o),A.bind(o)}function f(e){if(null===l)return e();const t=l;l=null;try{return e()}finally{l=t}}function A(){if(this.sources&&this.state)if(this.state===r)x(this);else{const e=c;c=null,w((()=>P(this)),!1),c=e}if(l){const e=this.observers?this.observers.length:0;l.sources?(l.sources.push(this),l.sourceSlots.push(e)):(l.sources=[this],l.sourceSlots=[e]),this.observers?(this.observers.push(l),this.observerSlots.push(l.sources.length-1)):(this.observers=[l],this.observerSlots=[l.sources.length-1])}return this.value}function b(e,t,n){let o=e.value;return e.comparator&&e.comparator(o,t)||(e.value=t,e.observers&&e.observers.length&&w((()=>{for(let t=0;t<e.observers.length;t+=1){const n=e.observers[t],o=a&&a.running;o&&a.disposed.has(n),(o?n.tState:n.state)||(n.pure?c.push(n):g.push(n),n.observers&&S(n)),o||(n.state=r)}if(c.length>1e6)throw c=[],new Error}),!1)),t}function x(e){if(!e.fn)return;E(e);const t=u;!function(e,t,n){let o;const i=s,a=l;l=s=e;try{o=e.fn(t)}catch(t){return e.pure&&(e.state=r,e.owned&&e.owned.forEach(E),e.owned=null),e.updatedAt=n+1,T(t)}finally{l=a,s=i}(!e.updatedAt||e.updatedAt<=n)&&(null!=e.updatedAt&&"observers"in e?b(e,o):e.value=o,e.updatedAt=n)}(e,e.value,t)}function y(e,t,n,o=r,a){const l={fn:e,state:o,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:s,context:s?s.context:null,pure:n};return null===s||s!==i&&(s.owned?s.owned.push(l):s.owned=[l]),l}function v(e){if(0===e.state)return;if(e.state===o)return P(e);if(e.suspense&&f(e.suspense.inFallback))return e.suspense.effects.push(e);const t=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<u);)e.state&&t.push(e);for(let n=t.length-1;n>=0;n--)if((e=t[n]).state===r)x(e);else if(e.state===o){const n=c;c=null,w((()=>P(e,t[0])),!1),c=n}}function w(e,t){if(c)return e();let r=!1;t||(c=[]),g?r=!0:g=[],u++;try{const t=e();return function(e){if(c&&(C(c),c=null),e)return;const t=g;g=null,t.length&&w((()=>n(t)),!1)}(r),t}catch(e){r||(g=null),c=null,T(e)}}function C(e){for(let t=0;t<e.length;t++)v(e[t])}function k(e){let t,n=0;for(t=0;t<e.length;t++){const r=e[t];r.user?e[n++]=r:v(r)}for(t=0;t<n;t++)v(e[t])}function P(e,t){e.state=0;for(let n=0;n<e.sources.length;n+=1){const i=e.sources[n];if(i.sources){const e=i.state;e===r?i!==t&&(!i.updatedAt||i.updatedAt<u)&&v(i):e===o&&P(i,t)}}}function S(e){for(let t=0;t<e.observers.length;t+=1){const n=e.observers[t];n.state||(n.state=o,n.pure?c.push(n):g.push(n),n.observers&&S(n))}}function E(e){let t;if(e.sources)for(;e.sources.length;){const t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){const e=r.pop(),o=t.observerSlots.pop();n<r.length&&(e.sourceSlots[o]=n,r[n]=e,t.observerSlots[n]=o)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)E(e.tOwned[t]);delete e.tOwned}if(e.owned){for(t=e.owned.length-1;t>=0;t--)E(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}e.state=0}function T(e,t=s){const n=function(e){return e instanceof Error?e:new Error("string"==typeof e?e:"Unknown error",{cause:e})}(e);throw n}function O(e,t){return f((()=>e(t||{})))}function D(e){const t=e.keyed,n=h((()=>e.when),void 0,{equals:(e,n)=>t?e===n:!e==!n});return h((()=>{const r=n();if(r){const o=e.children;return"function"==typeof o&&o.length>0?f((()=>o(t?r:()=>{if(!f(n))throw"Stale read from <Show>.";return e.when}))):o}return e.fallback}),void 0,void 0)}const _="_$DX_DELEGATE";function R(e,t,n){let r;const o=()=>{const t=document.createElement("template");return t.innerHTML=e,t.content.firstChild},i=t?()=>f((()=>document.importNode(r||(r=o()),!0))):()=>(r||(r=o())).cloneNode(!0);return i.cloneNode=i,i}function I(e,t=window.document){const n=t[_]||(t[_]=new Set);for(let r=0,o=e.length;r<o;r++){const o=e[r];n.has(o)||(n.add(o),t.addEventListener(o,M))}}function N(e,t,n){null==n?e.removeAttribute(t):e.setAttribute(t,n)}function F(e,t,n,r){Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n}function $(e,t,n){if(!t)return n?N(e,"style"):t;const r=e.style;if("string"==typeof t)return r.cssText=t;let o,i;for(i in"string"==typeof n&&(r.cssText=n=void 0),n||(n={}),t||(t={}),n)null==t[i]&&r.removeProperty(i),delete n[i];for(i in t)o=t[i],o!==n[i]&&(r.setProperty(i,o),n[i]=o);return n}function L(e,t,n,r){if(void 0===n||r||(r=[]),"function"!=typeof t)return U(e,t,r,n);p((r=>U(e,t(),r,n)),r)}function M(e){let t=e.target;const n=`$$${e.type}`,r=e.target,o=e.currentTarget,i=t=>Object.defineProperty(e,"target",{configurable:!0,value:t}),s=()=>{const r=t[n];if(r&&!t.disabled){const o=t[`${n}Data`];if(void 0!==o?r.call(t,o,e):r.call(t,e),e.cancelBubble)return}return t.host&&"string"!=typeof t.host&&!t.host._$host&&t.contains(e.target)&&i(t.host),!0},a=()=>{for(;s()&&(t=t._$host||t.parentNode||t.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get:()=>t||document}),e.composedPath){const n=e.composedPath();i(n[0]);for(let e=0;e<n.length-2&&(t=n[e],s());e++){if(t._$host){t=t._$host,a();break}if(t.parentNode===o)break}}else a();i(r)}function U(e,t,n,r,o){for(;"function"==typeof n;)n=n();if(t===n)return n;const i=typeof t,s=void 0!==r;if(e=s&&n[0]&&n[0].parentNode||e,"string"===i||"number"===i){if("number"===i&&(t=t.toString())===n)return n;if(s){let o=n[0];o&&3===o.nodeType?o.data!==t&&(o.data=t):o=document.createTextNode(t),n=B(e,n,r,o)}else n=""!==n&&"string"==typeof n?e.firstChild.data=t:e.textContent=t}else if(null==t||"boolean"===i)n=B(e,n,r);else{if("function"===i)return p((()=>{let o=t();for(;"function"==typeof o;)o=o();n=U(e,o,n,r)})),()=>n;if(Array.isArray(t)){const i=[],a=n&&Array.isArray(n);if(G(i,t,n,o))return p((()=>n=U(e,i,n,r,!0))),()=>n;if(0===i.length){if(n=B(e,n,r),s)return n}else a?0===n.length?H(e,i,r):function(e,t,n){let r=n.length,o=t.length,i=r,s=0,a=0,l=t[o-1].nextSibling,c=null;for(;s<o||a<i;)if(t[s]!==n[a]){for(;t[o-1]===n[i-1];)o--,i--;if(o===s){const t=i<r?a?n[a-1].nextSibling:n[i-a]:l;for(;a<i;)e.insertBefore(n[a++],t)}else if(i===a)for(;s<o;)c&&c.has(t[s])||t[s].remove(),s++;else if(t[s]===n[i-1]&&n[a]===t[o-1]){const r=t[--o].nextSibling;e.insertBefore(n[a++],t[s++].nextSibling),e.insertBefore(n[--i],r),t[o]=n[i]}else{if(!c){c=new Map;let e=a;for(;e<i;)c.set(n[e],e++)}const r=c.get(t[s]);if(null!=r)if(a<r&&r<i){let l,g=s,u=1;for(;++g<o&&g<i&&null!=(l=c.get(t[g]))&&l===r+u;)u++;if(u>r-a){const o=t[s];for(;a<r;)e.insertBefore(n[a++],o)}else e.replaceChild(n[a++],t[s++])}else s++;else t[s++].remove()}}else s++,a++}(e,n,i):(n&&B(e),H(e,i));n=i}else if(t.nodeType){if(Array.isArray(n)){if(s)return n=B(e,n,r,t);B(e,n,null,t)}else null!=n&&""!==n&&e.firstChild?e.replaceChild(t,e.firstChild):e.appendChild(t);n=t}}return n}function G(e,t,n,r){let o=!1;for(let i=0,s=t.length;i<s;i++){let s,a=t[i],l=n&&n[e.length];if(null==a||!0===a||!1===a);else if("object"==(s=typeof a)&&a.nodeType)e.push(a);else if(Array.isArray(a))o=G(e,a,l)||o;else if("function"===s)if(r){for(;"function"==typeof a;)a=a();o=G(e,Array.isArray(a)?a:[a],Array.isArray(l)?l:[l])||o}else e.push(a),o=!0;else{const t=String(a);l&&3===l.nodeType&&l.data===t?e.push(l):e.push(document.createTextNode(t))}}return o}function H(e,t,n=null){for(let r=0,o=t.length;r<o;r++)e.insertBefore(t[r],n)}function B(e,t,n,r){if(void 0===n)return e.textContent="";const o=r||document.createTextNode("");if(t.length){let r=!1;for(let i=t.length-1;i>=0;i--){const s=t[i];if(o!==s){const t=s.parentNode===e;r||i?t&&s.remove():t?e.replaceChild(o,s):e.insertBefore(o,n)}else r=!0}}else e.insertBefore(o,n);return[o]}const j=3,K=e=>1e3*e;async function W(e,t={}){const{maxAttempts:n=j,delayFn:r=K}=t;let o=null;for(let t=1;t<=n;t++)try{return await e()}catch(e){o=e,t<n&&await new Promise((e=>setTimeout(e,r(t))))}throw o||new Error("Operation failed after multiple attempts")}const V=chrome;async function Y(e,t){return new Promise(((n,r)=>{try{const o=t=>{if(chrome.runtime.lastError)return r({error:chrome.runtime.lastError,message:e});n(t)};t?.tabId||V.runtime.sendMessage(e,o)}catch(e){r(e)}}))}async function z(e,t,n){return W((()=>Y(e,t)),{maxAttempts:j,delayFn:K})}const q={display:"block",position:"fixed",top:"0%",left:"100%",width:"500px",height:"510px","margin-left":"-560px","margin-top":"50px",padding:"2px 5px","background-color":"white",border:"1px solid black","border-radius":"10px","box-shadow":"0 2px 10px rgba(0, 0, 0, 0.1)","z-index":"2147483647","font-family":"Arial","line-height":"1","vertical-align":"baseline","box-sizing":"border-box",color:"rgb(34, 34, 34)","@media (max-width: 600px), (max-height: 480px)":{display:"none !important"}},X={height:"100%","overflow-x":"hidden","overlfow-y":"auto",position:"relative",padding:"0px 15px"},Z={},J={display:"flex","align-items":"center","margin-bottom":"10px"},Q={flex:"1","font-size":"24px","font-weight":"700","margin-top":"20px","margin-bottom":"0px"},ee={background:"none",border:"none",padding:"4px 8px",color:"#666464","font-size":"38px",cursor:"pointer","line-height":"1"},te={"font-size":"18px","font-weight":"400","margin-top":"20px","margin-bottom":"0px"},ne={display:"flex",gap:"10px",width:"100%","margin-top":"20px","margin-bottom":"20px","flex-wrap":"wrap","justify-content":"space-between"},re={width:"28%",display:"flex","flex-direction":"column","align-items":"center",background:"none",border:"1px solid #ccc","border-radius":"5px",padding:"5px",gap:"5px","text-align":"center","font-size":"14px",cursor:"pointer",transition:"background-color 0.2s ease"},oe={"max-width":"120px","max-height":"70px","margin-bottom":"5px","object-fit":"contain"},ie={"background-color":"#FFD812",cursor:"pointer","border-radius":"8px",padding:"8px",color:"white","min-width":"100px",border:"0","font-weight":"600",width:"100%"},se={display:"flex","flex-direction":"column",gap:"10px",width:"100%","color-scheme":"light"},ae={display:"flex","align-items":"center",gap:"5px",border:"1px solid #ddd",padding:"15px","border-radius":"5px","font-weight":"600",cursor:"pointer","margin-bottom":"8px"},le={background:"none",border:"none",color:"blue","text-decoration":"underline",padding:"0",cursor:"pointer","margin-bottom":"15px"},ce={display:"flex","justify-content":"space-between",margin:"30px 0px 10px 0px","font-size":"14px"},ge={color:"#666464","text-decoration":"underline"},ue={color:"rgb(102, 100, 100)","text-decoration":"underline",margin:"0",cursor:"pointer"},de={width:"100%","background-color":"#f2f2f2",border:"1px solid black","border-radius":"10px","border-top":"1px solid #bbb7b7","margin-top":"10px","margin-bottom":"20px","box-sizing":"border-box"},pe={padding:"0 5px 0 10px",width:"100%","font-size":"12px","box-sizing":"border-box"},me={display:"grid","grid-template-columns":"4fr 1fr","padding-right":"15px","padding-bottom":"5px"},he={color:"#000","margin-bottom":"4px"},fe={"font-size":"14px",color:"#555","text-align":"right"},Ae=(e,t)=>{let n=parseFloat(t);return"FLAT"===e&&(n*=.75),((e,t)=>{let n=parseFloat(t);return n<1&&(n=1),n=Math.floor(n),"PERCENTAGE"===e?`${n}%`:`$${n}`})(e,n.toString())};var be=R("<span>");function xe(e){const t=(n=e.title,r=e.activeDomain,n.replace("{0}",Ae(r.Merchant.MaxRate?.Kind,r.Merchant.MaxRate?.Amount??"0")));var n,r,o;return(o=be()).innerHTML=t,o}var ye=R("<div>"),ve=R("<div><div class=gf-offer-details><p>Select a charity to activate a donation during your online shopping session.</p><p> <b>Eligible Transaction:</b> A purchase made immediately after selecting a charity.</p><p><b>Donation rates:</b> <!> for each eligible transaction. The following donation rates and exclusions apply:</p><p><b>Donation amounts:</b> Donation amount is calculated based upon the applicable rates and exclusions, which may change from time to time. Amounts may be adjusted or canceled due to returned items, suspected fraud, or other factors described within the terms and conditions.</p><p><b>Donation timing:</b> On average, donation payouts occur 60-120 days after your completed transaction, but some donations may take 180 days or longer. We provide a donation to the charity you had selected at the time of purchase, in monthly batches, after any holdback periods due to applicable return or cancellation policies have passed.</p><p>See a summary of <a target=_blank rel=noreferrer>terms and conditions</a>."),we=R("<div class=gf-offer-details-rate-item><div></div><div>");const Ce=e=>{return t=ve(),o=(r=(n=t.firstChild).firstChild.nextSibling.nextSibling).firstChild.nextSibling.nextSibling,i=r.nextSibling,s=i.nextSibling.nextSibling.firstChild.nextSibling,L(r,(()=>e.parsedMaxRate?`Up to ${e.parsedMaxRate}`:"Earn"),o),L(n,O(D,{get when(){return!!e.merchantRateDetail?.length},get children(){var t=ye();return L(t,(()=>e.merchantRateDetail?.map((e=>{return t=we(),n=t.firstChild,r=n.nextSibling,L(n,(()=>e.Name||"")),L(r,(()=>((e,t=1,n=1)=>{const r=e.BoostedOffer??null;let o=parseFloat(e?.Amount??"");if(r?.EndDate&&new Date(r.EndDate)<new Date&&(o=parseFloat(r.OriginalMaxRate)),Number.isNaN(o))return"";const i=o*t;return"PERCENTAGE"===e?.Kind?`${i.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:n})}%`:"FLAT"===e?.Kind?i.toLocaleString("en-US",{style:"currency",currency:e.Currency}):""})(e))),p((e=>{var o=me,i=he,s=fe;return e.e=$(t,o,e.e),e.t=$(n,i,e.t),e.a=$(r,s,e.a),e}),{e:void 0,t:void 0,a:void 0}),t;var t,n,r})))),t}}),i),p((r=>{var o=de,i=pe,a=ge,l=e.termsUrl;return r.e=$(t,o,r.e),r.t=$(n,i,r.t),r.a=$(s,a,r.a),l!==r.o&&N(s,"href",r.o=l),r}),{e:void 0,t:void 0,a:void 0,o:void 0}),t;var t,n,r,o,i,s};var ke=R("<button class=give-freely-close-button aria-label=Close>×"),Pe=R('<div><div><div><span></span></div></div><hr><div></div><div><div><div><br><span></span></div><button aria-label="Don\'t show again"></button></div></div><div><p>Offer Details</p><a class=give-freely-footer-link target=_blank rel="noopener noreferrer">Why am I seeing this?'),Se=R("<div><div><img><span></span></div><button>");function Ee(e){const[t,n]=d(!1);return m((()=>{t()&&e.mainContainerRef&&e.mainContainerRef.scroll({top:e.mainContainerRef.scrollHeight,behavior:"smooth"})})),[(r=Pe(),o=r.firstChild,i=o.firstChild,s=i.firstChild,a=o.nextSibling.nextSibling,l=a.nextSibling,c=l.firstChild,g=c.firstChild,u=g.firstChild.nextSibling,f=g.nextSibling,A=l.nextSibling,b=A.firstChild,x=b.nextSibling,L(o,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupMainCloseButtonVisible},get children(){var t=ke();return F(t,"click",e.onClose),p((e=>$(t,ee,e))),t}}),null),L(a,O(xe,{get title(){return e.subtitle},get activeDomain(){return e.activeDomain}})),L(l,(()=>e.checkoutPopupConf.checkoutPopupCharities.map((t=>{return r=(n=Se()).firstChild,i=(o=r.firstChild).nextSibling,s=r.nextSibling,n.$$click=()=>e.onCharitySelect(t),r.style.setProperty("height","100px"),r.style.setProperty("text-align","center"),L(i,(()=>t.title)),L(s,(()=>e.checkoutPopupConf.checkoutPopupCharitySelectString||"Select")),p((r=>{var i=re,a=t.logo,l=oe,c=t.title,g={...ie,"background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812"},u=`Select charity: ${t.title}`;return r.e=$(n,i,r.e),a!==r.t&&N(o,"src",r.t=a),r.a=$(o,l,r.a),c!==r.o&&N(o,"alt",r.o=c),r.i=$(s,g,r.i),u!==r.n&&N(s,"aria-label",r.n=u),r}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),n;var n,r,o,i,s}))),c),F(c,"click",e.onSuppress),g.style.setProperty("height","100px"),g.style.setProperty("text-align","center"),L(f,(()=>e.checkoutPopupConf.checkoutPopupCharitySelectString||"Select")),b.$$click=()=>{e.onOfferDetailsClick(!t()),n(!t())},p((t=>{var n=Z,g=J,d=Q,p=e.checkoutPopupConf.checkoutPopupMainTitle,m=te,h=ne,y=re,v=e.checkoutPopupConf.checkoutPopupSixthBoxWording,w={...ie,"background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812"},C=ce,k=ue,P=ge,S=e.checkoutPopupConf.externalUrls.giveFreelyWhyAmISeeingThis;return t.e=$(r,n,t.e),t.t=$(o,g,t.t),t.a=$(i,d,t.a),p!==t.o&&(s.innerHTML=t.o=p),t.i=$(a,m,t.i),t.n=$(l,h,t.n),t.s=$(c,y,t.s),v!==t.h&&(u.innerHTML=t.h=v),t.r=$(f,w,t.r),t.d=$(A,C,t.d),t.l=$(b,k,t.l),t.u=$(x,P,t.u),S!==t.c&&N(x,"href",t.c=S),t}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0}),r),O(D,{get when(){return t()},get children(){return O(Ce,{get merchantName(){return e.activeDomain.Merchant.Name},get extensionName(){return e.checkoutPopupConf.displayName},get termsUrl(){return e.checkoutPopupConf.externalUrls.giveFreelyTermsAndConditions},get parsedMaxRate(){return h((()=>!!e.activeDomain.Merchant.MaxRate))()?Ae(e.activeDomain.Merchant.MaxRate.Kind,e.activeDomain.Merchant.MaxRate?.Amount):null},get merchantRateDetail(){return e.merchantRates},onClose:()=>n(!1)})}})];var r,o,i,s,a,l,c,g,u,f,A,b,x}I(["click"]);var Te=R("<button class=give-freely-close-button aria-label=Close>×"),Oe=R("<label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=18250><span>Don't ask me again... ever"),De=R("<div><div><div></div></div><button class=give-freely-back-button aria-label=\"Back to charity selection\">I changed my mind! I'd like to select a charity.</button><hr><div id=give-freely-goodbye-screen-options><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=1><span>Don't ask me again for 1 day</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=7><span>Don't ask me again for 7 days</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=30><span>Don't ask me again for 30 days</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=90><span>Don't ask me again for 90 days</span></label></div><button class=give-freely-submit-button>Submit");function _e(e){const[t,n]=d(0);return r=De(),o=r.firstChild,i=o.firstChild,s=o.nextSibling,a=s.nextSibling.nextSibling,c=(l=a.firstChild).firstChild,u=(g=l.nextSibling).firstChild,h=(m=g.nextSibling).firstChild,A=(f=m.nextSibling).firstChild,b=a.nextSibling,r.style.setProperty("font-size","14px"),L(i,(()=>e.checkoutPopupConf.checkoutPopupSupressTitle)),L(o,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupSupressCloseButtonVisible},get children(){var t=Te();return t.$$click=()=>e.onGoodbye(0),p((e=>$(t,ee,e))),t}}),null),F(s,"click",e.onBack),c.addEventListener("change",(()=>n(1))),u.addEventListener("change",(()=>n(7))),h.addEventListener("change",(()=>n(30))),A.addEventListener("change",(()=>n(90))),L(a,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupNeverSuppressionAllowed},get children(){var e=Oe();return e.firstChild.addEventListener("change",(()=>n(18250))),p((t=>$(e,ae,t))),e}}),null),b.$$click=()=>{const n=t();n&&(e.onGoodbye(n),e.setScreen("main"))},p((t=>{var n=J,r=Q,c=le,u=se,d=ae,p=ae,h=ae,A=ae,x={...ie,"font-weight":"700","margin-top":"10px","margin-bottom":"0px","background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812",width:"100px"};return t.e=$(o,n,t.e),t.t=$(i,r,t.t),t.a=$(s,c,t.a),t.o=$(a,u,t.o),t.i=$(l,d,t.i),t.n=$(g,p,t.n),t.s=$(m,h,t.s),t.h=$(f,A,t.h),t.r=$(b,x,t.r),t}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),r;var r,o,i,s,a,l,c,g,u,m,h,f,A,b}I(["click"]);var Re=R("<div><div><div></div><button class=give-freely-close-button aria-label=Close>×</button></div><hr><div><span>");function Ie(e){return t=Re(),n=t.firstChild,r=n.firstChild,o=r.nextSibling,i=n.nextSibling.nextSibling,s=i.firstChild,t.style.setProperty("font-size","14px"),L(r,(()=>e.failedDonation?"Oops! Something went wrong":e.checkoutPopupConf.checkoutPopupDonationTitle)),F(o,"click",e.onClose),i.style.setProperty("padding","30px"),i.style.setProperty("height","150px"),i.style.setProperty("font-size","14px"),p((t=>{var i=J,a=Q,l=ee,c=e.failedDonation?"Please try again later.":e.checkoutPopupConf.checkoutPopupDonationWording;return t.e=$(n,i,t.e),t.t=$(r,a,t.t),t.a=$(o,l,t.a),c!==t.o&&(s.innerHTML=t.o=c),t}),{e:void 0,t:void 0,a:void 0,o:void 0}),t;var t,n,r,o,i,s}I(["click"]);var Ne,Fe,$e=R("<div><div>");function Le(e){const{logger:t}=e,[n,r]=d("main"),[o,i]=d(),[s,a]=d(!1),l=()=>{t.debug("Close button clicked"),e.onClose()},c=async n=>{t.info("Charity selected",{charity:n,domain:e.activeDomain.Domain}),i(n);const o=await e.onDonate(n,e.activeDomain);a(!o),r("donate")},g=()=>{t.debug("Suppress button clicked"),r("goodbye")},u=()=>{t.debug("Navigating back to main screen"),r("main")},m=n=>{t.info("User chose to hide popup",{days:n}),e.onClose(n)};let h;return x=$e(),y=x.firstChild,"function"==typeof h?(A=h,b=y,f((()=>A(b,undefined)))):h=y,L(y,O(D,{get when(){return"main"===n()},get children(){return O(Ee,{mainContainerRef:h,get checkoutPopupConf(){return e.checkoutPopupConf},get activeDomain(){return e.activeDomain},get merchantRates(){return e.merchantRates},onClose:l,onCharitySelect:c,onSuppress:g,get onOfferDetailsClick(){return e.onOfferDetailsClick},get subtitle(){return e.checkoutPopupConf.checkoutPopupSubTitle}})}}),null),L(y,O(D,{get when(){return"goodbye"===n()},get children(){return O(_e,{get checkoutPopupConf(){return e.checkoutPopupConf},onClose:()=>e.onClose(),onBack:u,onGoodbye:m,setScreen:r})}}),null),L(y,O(D,{get when(){return"donate"===n()},get children(){return O(Ie,{get checkoutPopupConf(){return e.checkoutPopupConf},get selectedCharity(){return o()},onClose:()=>e.onClose(),get failedDonation(){return s()},setScreen:r})}}),null),p((t=>{var n=q,r=e.elementId,o=X;return t.e=$(x,n,t.e),r!==t.t&&N(x,"id",t.t=r),t.a=$(y,o,t.a),t}),{e:void 0,t:void 0,a:void 0}),x;var A,b,x,y}class Me{log({level:e,message:t,timestamp:n,data:r,title:o}){const i="debug"===e?"log":e,s=o?`[${o}]`:"";void 0!==r?console[i](`[${n}] - ${Me.LOGGER_PREFIX} ${s} ${t}`,r):console[i](`[${n}] - ${Me.LOGGER_PREFIX} ${s} ${t}`)}}Me.LOGGER_PREFIX="[GFAdUnit] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED"}(Ne||(Ne={})),function(e){e.adUnitLog="ADUNIT-LOG"}(Fe||(Fe={}));const Ue=["debug","info","warn","error"];class Ge{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new Me],title:e?.title??""}}static getInstance(e){return Ge.instance||(Ge.instance=new Ge(e)),Ge.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&Ue.indexOf(e)>=Ue.indexOf(this.config.minLevel)}createLogMessage(e,t,n){return{level:e,version:"1.1.1",message:t,timestamp:(new Date).toISOString(),data:n,title:this.config.title}}log(e,t,n){if(!this.shouldLog(e))return;const r=this.createLogMessage(e,t,n);this.config.transports.forEach((e=>e.log(r)))}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}function He(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var Be={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",n=e=>{const n={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(n).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class r extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const o=(t,n)=>(...r)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):n.singleCallbackArg||r.length<=1&&!1!==n.singleCallbackArg?t.resolve(r[0]):t.resolve(r)},i=e=>1==e?"argument":"arguments",s=(e,t,n)=>new Proxy(t,{apply:(t,r,o)=>n.call(r,e,...o)});let a=Function.call.bind(Object.prototype.hasOwnProperty);const l=(e,t={},n={})=>{let r=Object.create(null),c={has:(t,n)=>n in e||n in r,get(c,g,u){if(g in r)return r[g];if(!(g in e))return;let d=e[g];if("function"==typeof d)if("function"==typeof t[g])d=s(e,e[g],t[g]);else if(a(n,g)){let t=((e,t)=>function(n,...r){if(r.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${r.length}`);if(r.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${r.length}`);return new Promise(((i,s)=>{if(t.fallbackToNoCallback)try{n[e](...r,o({resolve:i,reject:s},t))}catch(o){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,o),n[e](...r),t.fallbackToNoCallback=!1,t.noCallback=!0,i()}else t.noCallback?(n[e](...r),i()):n[e](...r,o({resolve:i,reject:s},t))}))})(g,n[g]);d=s(e,e[g],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(a(t,g)||a(n,g)))d=l(d,t[g],n[g]);else{if(!a(n,"*"))return Object.defineProperty(r,g,{configurable:!0,enumerable:!0,get:()=>e[g],set(t){e[g]=t}}),d;d=l(d,t[g],n["*"])}return r[g]=d,d},set:(t,n,o,i)=>(n in r?r[n]=o:e[n]=o,!0),defineProperty:(e,t,n)=>Reflect.defineProperty(r,t,n),deleteProperty:(e,t)=>Reflect.deleteProperty(r,t)},g=Object.create(e);return new Proxy(g,c)},c=e=>({addListener(t,n,...r){t.addListener(e.get(n),...r)},hasListener:(t,n)=>t.hasListener(e.get(n)),removeListener(t,n){t.removeListener(e.get(n))}}),g=new r((e=>"function"!=typeof e?e:function(t){const n=l(t,{},{getContent:{minArgs:0,maxArgs:0}});e(n)})),u=new r((e=>"function"!=typeof e?e:function(t,n,r){let o,i,s=!1,a=new Promise((e=>{o=function(t){s=!0,e(t)}}));try{i=e(t,n,o)}catch(e){i=Promise.reject(e)}const l=!0!==i&&((c=i)&&"object"==typeof c&&"function"==typeof c.then);var c;if(!0!==i&&!l&&!s)return!1;return(l?i:a).then((e=>{r(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",r({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:n,resolve:r},o)=>{e.runtime.lastError?e.runtime.lastError.message===t?r():n(new Error(e.runtime.lastError.message)):o&&o.__mozWebExtensionPolyfillReject__?n(new Error(o.message)):r(o)},p=(e,t,n,...r)=>{if(r.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${r.length}`);if(r.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${r.length}`);return new Promise(((e,t)=>{const o=d.bind(null,{resolve:e,reject:t});r.push(o),n.sendMessage(...r)}))},m={devtools:{network:{onRequestFinished:c(g)}},runtime:{onMessage:c(u),onMessageExternal:c(u),sendMessage:p.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:p.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},h={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return n.privacy={network:{"*":h},services:{"*":h},websites:{"*":h}},l(e,m,n)};e.exports=n(chrome)}}(Be);var je=He(Be.exports);const Ke="GIVE_FREELY_",We={async get(e){const t=`${Ke}${e}`;return(await je.storage.local.get(t))[t]||null},async set(e,t){const n=`${Ke}${e}`;await je.storage.local.set({[n]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${Ke}${e}`)):`${Ke}${e}`;await je.storage.local.remove(t)}};class Ve{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0,this.CONFIG_REFRESH_INTERVAL=3e5,this.PARTNER_CONFIG_STORAGE_KEY="gf_partner_config",this.GLOBAL_CONFIG_STORAGE_KEY="gf_global_config"}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchAndUpdatePartnerConfig(){const e=await W((async()=>{const e=await fetch(`https://cdn.givefreely.com/adunit/config/${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await We.set(this.PARTNER_CONFIG_STORAGE_KEY,t),e}async fetchAndUpdateGlobalConfig(){const e=await W((async()=>{const e=await fetch("https://cdn.givefreely.com/adunit/config/global.json",{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await We.set(this.GLOBAL_CONFIG_STORAGE_KEY,t),e}async getConfig(){const e=Date.now(),t=await We.get(this.PARTNER_CONFIG_STORAGE_KEY),n=await We.get(this.GLOBAL_CONFIG_STORAGE_KEY);if(this.partnerConfig=t?.config||null,this.globalConfig=n?.config||null,this.lastConfigRefresh=Math.max(t?.lastRefresh||0,n?.lastRefresh||0),!this.partnerConfig||!this.globalConfig||e-this.lastConfigRefresh>this.CONFIG_REFRESH_INTERVAL)try{const[t,n]=await Promise.all([this.fetchAndUpdatePartnerConfig(),this.fetchAndUpdateGlobalConfig()]);this.partnerConfig=t,this.globalConfig=n,this.lastConfigRefresh=e}catch(e){if(!this.partnerConfig||!this.globalConfig)throw e;console.warn("Failed to refresh configs, using existing configs:",e)}const r=this.mergeConfigs(this.globalConfig,this.partnerConfig);return((e,t,n)=>{const r=[...t.merchantExclusions??[],...n.merchantExclusions??[]];e.merchantExclusions=r})(r,this.globalConfig,this.partnerConfig),r}async clearCache(){await Promise.all([We.remove(this.PARTNER_CONFIG_STORAGE_KEY),We.remove(this.GLOBAL_CONFIG_STORAGE_KEY)]),this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0}mergeConfigs(e,t){if(!t)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e,i=t;"object"==typeof i[r]&&null!==i[r]&&"object"==typeof o[r]?n[r]=this.mergeConfigs(o[r],i[r]):n[r]=void 0!==i[r]?i[r]:o[r]}return n}getStoredState(e){return e?{config:e.config,lastRefresh:e.lastRefresh}:{config:null,lastRefresh:0}}}const Ye="TRACK_EVENT",ze="GF_HIDE_POPUP",qe="GF_GET_POPUP_CONFIG",Xe="GF_IS_ACTIVE_DOMAIN",Ze="GF_SHOULD_STAND_DOWN",Je="GF_ACTIVATE_OFFER",Qe="GF_STORE_SHOPIFY_SHOP_ID",et="GF_GET_DOMAIN_BY_SHOP_ID";class tt{constructor(t,n,r=60){this._config=null,this.track=async(t,n,r)=>{null===this._config&&(this._config=await new Ve(this._partnerApiKey).getConfig());const o={partner:`adUnit_${this._partnerApiKey}`,eventType:t,eventData:{userId:this._userService?.user?.id,libVersion:String(e)??"",wfDeviceId:n,...r}};try{const e=JSON.stringify(o);return await this.shouldBroadcastEvent(e)?(await fetch(this._config.eventsUrl,{headers:{"Content-Type":"application/json"},method:"POST",body:e,cache:"no-store"}),await this.pushEventToHistory(e),!0):(this.log("This event has already been broadcasted during the past hour",o),!1)}catch(e){return this.log("Something unexpected happened when dispatching a gf event",e,o),!1}},this.log=(...e)=>{"debug"===this._config?.backgroundMinLogLevel&&console.log("analytics:",...e)},this.getEventsHistory=async()=>{const{GF_AD_EVENT_HISTORY:e}=await V.storage.local.get({GF_AD_EVENT_HISTORY:""}),t=function(e){const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()}(-this._debounceWindowInMinutes);let n=(e||[]).filter((e=>e.createdAt>t));return await V.storage.local.set({GF_AD_EVENT_HISTORY:n}),n},this.shouldBroadcastEvent=async e=>!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await V.storage.local.set({GF_AD_EVENT_HISTORY:t})},this._partnerApiKey=t,this._userService=n,this._debounceWindowInMinutes=r}}function nt(e){const t=["",".asp",".aspx",".php",".js",".htm",".html"],n=["cart","checkout","shopping-bag","shopping-basket","shopping-cart","basket"].flatMap((e=>t.map((t=>e+t)))).filter((e=>"basket"!==e)),r=["tote-cart","tote.cart"],o=e,i=n.filter((e=>o.includes(e))),s=o.split("/");return!s.some((e=>r.some((t=>e.includes(t)))))&&(s.some((e=>n.some((t=>e.startsWith(t)||e.endsWith(t)))))||"basket"===s[s.length-1].toLowerCase()||i.length>1||1===i.length&&o.includes("shopping"))}function rt(e,t){const n=["book"];return e.split("/").some((e=>n.some((t=>e.startsWith(t)||e.endsWith(t)))))&&null!=t.evaluate("//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6][contains(., 'Your Reservation') or contains(., 'Your reservation')]",t,null,XPathResult.ANY_TYPE,null)?.iterateNext()}async function ot(e){try{const t=await Y({type:et,payload:{shopId:e}});return t.payload.found&&t.payload.domain?t.payload.domain:null}catch(e){return null}}function it(){try{const e=Array.from(document.querySelectorAll("script"));for(const t of e){if(t.dataset?.shopId?.startsWith("gid")){const e=parseInt(t.dataset.shopId.replace("gid://shopify/Shop/",""));if(!isNaN(e)&&e>0)return e}const e=t.textContent||"";if(e.includes("ShopifyAnalytics")&&e.includes("shopId")){const t=e.match(/shopId['"]*:\s*['"]*(\d+)['"]*[,}]/);if(t&&t[1]){const e=parseInt(t[1]);if(!isNaN(e)&&e>0)return e}}}const t=document.querySelector("[data-shop-id]");if(t instanceof HTMLElement){const e=t.dataset.shopId;if(e){const t=parseInt(e);if(!isNaN(t)&&t>0)return t}}const n=window?.ShopifyAnalytics?.lib?.trekkie?.defaultAttributes?.shopId;return n&&parseInt(n)||0}catch(e){return console.error("Error accessing ShopifyAnalytics:",e),0}}function st(){try{if(!window.location.href.startsWith("https://shop.app"))return 0;const e=document?.head?.querySelector('meta[name="store"][content]');if(!e)return 0;try{const t=JSON.parse(e.content);return t?.id||0}catch(e){return 0}}catch(e){return 0}}tt.trackEvent=async(e,t)=>{await Y({type:Ye,payload:{eventType:e,eventData:t}})};const at=Ge.getInstance();function lt(e,t,n){try{const r=function(e){try{const t=e.split(".");return t.length>=2?t.slice(-2).join("."):e}catch(e){return at.error("Error extracting domain",e),""}}(n);at.debug("Checking merchant regex rules",{currentDomain:r,currentUrl:t});const o=e.merchantPopupRules.filter((e=>r.includes(e.domain)));if(0===o.length)return at.debug("No matching merchant rules found for domain",{currentDomain:r}),!1;for(const e of o)for(const n of e.rules)try{if(new RegExp(n.rule).test(t))return at.debug("Merchant regex rule matched",{merchant:e.name,rule:n.rule,currentUrl:t}),!0}catch(t){at.error("Invalid regex in merchant rule",{merchant:e.name,rule:n.rule,error:t})}return at.debug("No matching regex rules found",{currentUrl:t}),!1}catch(e){return at.error("Error in merchantRegexRule",e),!1}}var ct=R("<div class=gf-app>");function gt(){const t=Ge.getInstance(),[n,r]=d(null),[o,i]=d(void 0),[s,a]=d(!1),[l,c]=d([]);var g;g=async()=>{t.info("Mounting GfApp component");try{const n=await(async()=>{const e=await Y({type:qe,payload:{}});if(!e.payload.config)throw new Error("No checkout popup config found");return e.payload.config})();if(!n)return void t.error("No checkout popup config found");r(n),t.configure({enabled:!0,title:"Content - GfAdUnit",minLevel:n.checkoutPopupMinLogLevel??"error"});const s=String(e);if(n.minVersion&&((e,t)=>{if(e===t)return!1;const n=e.split(".").map(parseInt),r=t.split(".").map(parseInt);for(let e=0;e<n.length;e++){if(n[e]<r[e])return!0;if(n[e]>r[e])return!1}return!1})(s,n.minVersion))return void t.debug(`Current version: ${s}. Minimum version ${n.minVersion} not met`);if(!1===n.checkoutPopupMasterSwitch)return void t.debug("Checkout popup master switch is disabled");const{domain:l,rates:g}=await(async e=>{const{hostname:t}=window.location;e.debug("Checking if domain is active",{hostname:t});const n=await Y({type:Xe,payload:{hostname:t}});return n.payload.isActive?(e.debug("Active domain",{domain:n.payload.domain}),e.debug("Merchant rates",{rates:n.payload.rates}),e.info("Domain and rates ({})ed successfully."),{isActive:!0,domain:n.payload.domain,rates:n.payload.rates}):{isActive:!1,domain:void 0,rates:[]}})(t);if(c(g),i(l),l)await function(e){const t=it()||st();return t>0&&function(e,t){if(e&&!(e<=0))try{Y({type:Qe,payload:{shopId:e,domain:t}}).catch((e=>{console.error("Error sending shop ID to background:",e)}))}catch(e){console.error("Error sending Shopify shop ID:",e)}}(t,e),t}(l);else{if("shop.app"!==window.location.hostname&&!window.location.hostname.endsWith(".shop.app"))return void a(!1);const e=window.location.pathname.split("/")[2];if(!e)return t.error("Shop ID not found"),void a(!1);const n=await ot(parseInt(e));if(!n)return t.error("Shop domain not found"),void a(!1);t.debug("Shop domain found",{shopDomain:n}),i(n)}const u=await(async e=>{const t=await We.get("popup_hide");if(!t)return e.debug("No expiry found in storage"),!1;const{popupHide:n}=t,r=!!n&&Date.now()<n;return e.debug("Is AdUnit Muted?",{isMuted:r,expiry:n}),r})(t);if(u)return;if(!o())return void a(!1);const d=await(async(e,t)=>{const{Domain:n}=t,r=window.location.href,{payload:o}=await Y({type:Ze,payload:{activeDomain:n,url:r}});return!!o.result&&(e.info("Stand Down detected"),!0)})(t,o());if(d)return void a(!1);const p=setInterval((async()=>{t.debug("Checking checkout rules");const e=await(async e=>{const t=Ge.getInstance();t.configure({enabled:!0,title:"Content - checkoutRulesTest"});const n=new URL(globalThis.location.href),r=n.href,o=n.hostname;t.debug("Checking if popup should be shown",{currentUrl:r});const i=await async function(){const e=it()||st();return!("shop.app"!==window.location.hostname&&!window.location.hostname.endsWith(".shop.app")||!(e>0)||!await ot(e))}(),s=nt(n.pathname.toLowerCase())||rt(r,document)||lt(e,r,o)||i;return t.debug("Popup show decision based on rules",{shouldShow:s,matchesCartRule:nt(n.pathname.toLowerCase()),matchesBookingRule:rt(r,document),matchesShopPayRule:i,matchesMerchantRegexRule:lt(e,r,o)}),s})(n);a(e),e&&(t.debug("Should show popup based on checkout rules",{shouldShowResult:e}),tt.trackEvent(Ne.checkoutPopupShown,{url:globalThis.window.location.href}),clearInterval(p))}),2e3)}catch(e){a(!1),t.error("An error occurred in GfApp",{error:e})}},m((()=>f(g)));const u=async(e,n)=>{t.info("Processing donation",{charity:e,domain:n.Domain});const r=await(async(e,t,n,r)=>{e.debug("Activating offer",{activeDomain:t,selectedCharity:r});const o=await z({type:Je,payload:{activeDomain:t,originalUrl:n,selectedCharity:r}});return e.debug("Activate offer response",{response:o}),o})(t,n,window.location.href,{ein:e.ein,thirdPartyId:e.tpi});return t.debug("Activate offer response",{activationResponse:r}),tt.trackEvent(r.payload.response?Ne.checkoutPopupDonation:Ne.checkoutPopupFailedActivation,{activeDomain:n.Domain,url:globalThis.window.location.href,charity:{ein:e.ein,tpi:e.tpi},rate:n.Merchant.MaxRate}),r.payload.response},p=async e=>{a(await(async(e,t)=>{try{e.info("Hiding ad",{days:t});const n=await z({type:ze,payload:{days:t??0}});return t&&t>0&&tt.trackEvent(Ne.checkoutPopupSupressed,{url:globalThis.window.location.href,days:t}),e.info("Hiding ad response",{hide_response:n}),n.payload.ack?(e.debug("Ad hidden successfully"),!1):(e.warn("Failed to hide ad"),!0)}catch(e){return!1}})(t,e))},A=async e=>{tt.trackEvent(Ne.checkoutPopupOfferDetailsClicked,{action:e?"opened":"closed"})};return L(x=ct(),(b=h((()=>!(!o()||!s()))),()=>b()&&O(Le,{get checkoutPopupConf(){return n()},elementId:"give-freely-checkout-popup",get activeDomain(){return o()},get merchantRates(){return l()},onClose:p,onDonate:u,onOfferDetailsClick:A,logger:t}))),x;var b,x}exports.browser=V,exports.initializeAdUnit=async function(){const e=document.createElement("div");e.id="give-freely-root",document.body.appendChild(e);const t=e.attachShadow({mode:"open"}),n=document.createElement("div"),r=document.createElement("style");r.textContent='\n :host {\n all: initial;\n }\n\n .gf-scroll-remove::-webkit-scrollbar {\n border-radius-bottom-right: 15px;\n }\n\n button {\n cursor: pointer;\n transition: transform 0.1s ease;\n }\n\n button:active {\n transform: scale(0.98);\n }\n\n .give-freely-close-button:hover {\n opacity: 0.7;\n }\n\n input[type="radio"] {\n margin-right: 8px;\n }\n\n hr {\n border: none;\n border-top: 1px solid #e5e5e5;\n margin: 1em 0;\n }\n\n @media (max-width: 600px), (max-height: 480px) {\n #give-freely-checkout-popup {\n display: none !important;\n }\n }\n',t.appendChild(r),t.appendChild(n),function(e,t,n,r={}){let o;(function(e,t){const n=l,r=s,o=0===e.length,a=void 0===t?r:t,c=o?i:{owned:null,cleanups:null,context:a?a.context:null,owner:a},g=o?e:()=>e((()=>f((()=>E(c)))));s=c,l=null;try{return w(g,!0)}finally{l=n,s=r}})((r=>{o=r,t===document?e():L(t,e(),t.firstChild?null:void 0,n)}),r.owner)}((()=>O(gt,{})),n)};
1
+ "use strict";const e="1.1.0",t={equals:(e,t)=>e===t};let n=C;const r=1,o=2,i={owned:null,cleanups:null,context:null,owner:null};var s=null;let a=null,l=null,c=null,g=null,u=0;function d(e,n){const r={value:e,observers:null,observerSlots:null,comparator:(n=n?Object.assign({},t,n):t).equals||void 0};return[A.bind(r),e=>("function"==typeof e&&(e=e(r.value)),b(r,e))]}function p(e,t,n){x(y(e,t,!1,r))}function m(e,t,o){n=k;const i=y(e,t,!1,r);i.user=!0,g?g.push(i):x(i)}function h(e,n,r){r=r?Object.assign({},t,r):t;const o=y(e,n,!0,0);return o.observers=null,o.observerSlots=null,o.comparator=r.equals||void 0,x(o),A.bind(o)}function f(e){if(null===l)return e();const t=l;l=null;try{return e()}finally{l=t}}function A(){if(this.sources&&this.state)if(this.state===r)x(this);else{const e=c;c=null,w((()=>P(this)),!1),c=e}if(l){const e=this.observers?this.observers.length:0;l.sources?(l.sources.push(this),l.sourceSlots.push(e)):(l.sources=[this],l.sourceSlots=[e]),this.observers?(this.observers.push(l),this.observerSlots.push(l.sources.length-1)):(this.observers=[l],this.observerSlots=[l.sources.length-1])}return this.value}function b(e,t,n){let o=e.value;return e.comparator&&e.comparator(o,t)||(e.value=t,e.observers&&e.observers.length&&w((()=>{for(let t=0;t<e.observers.length;t+=1){const n=e.observers[t],o=a&&a.running;o&&a.disposed.has(n),(o?n.tState:n.state)||(n.pure?c.push(n):g.push(n),n.observers&&S(n)),o||(n.state=r)}if(c.length>1e6)throw c=[],new Error}),!1)),t}function x(e){if(!e.fn)return;E(e);const t=u;!function(e,t,n){let o;const i=s,a=l;l=s=e;try{o=e.fn(t)}catch(t){return e.pure&&(e.state=r,e.owned&&e.owned.forEach(E),e.owned=null),e.updatedAt=n+1,T(t)}finally{l=a,s=i}(!e.updatedAt||e.updatedAt<=n)&&(null!=e.updatedAt&&"observers"in e?b(e,o):e.value=o,e.updatedAt=n)}(e,e.value,t)}function y(e,t,n,o=r,a){const l={fn:e,state:o,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:s,context:s?s.context:null,pure:n};return null===s||s!==i&&(s.owned?s.owned.push(l):s.owned=[l]),l}function v(e){if(0===e.state)return;if(e.state===o)return P(e);if(e.suspense&&f(e.suspense.inFallback))return e.suspense.effects.push(e);const t=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<u);)e.state&&t.push(e);for(let n=t.length-1;n>=0;n--)if((e=t[n]).state===r)x(e);else if(e.state===o){const n=c;c=null,w((()=>P(e,t[0])),!1),c=n}}function w(e,t){if(c)return e();let r=!1;t||(c=[]),g?r=!0:g=[],u++;try{const t=e();return function(e){if(c&&(C(c),c=null),e)return;const t=g;g=null,t.length&&w((()=>n(t)),!1)}(r),t}catch(e){r||(g=null),c=null,T(e)}}function C(e){for(let t=0;t<e.length;t++)v(e[t])}function k(e){let t,n=0;for(t=0;t<e.length;t++){const r=e[t];r.user?e[n++]=r:v(r)}for(t=0;t<n;t++)v(e[t])}function P(e,t){e.state=0;for(let n=0;n<e.sources.length;n+=1){const i=e.sources[n];if(i.sources){const e=i.state;e===r?i!==t&&(!i.updatedAt||i.updatedAt<u)&&v(i):e===o&&P(i,t)}}}function S(e){for(let t=0;t<e.observers.length;t+=1){const n=e.observers[t];n.state||(n.state=o,n.pure?c.push(n):g.push(n),n.observers&&S(n))}}function E(e){let t;if(e.sources)for(;e.sources.length;){const t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){const e=r.pop(),o=t.observerSlots.pop();n<r.length&&(e.sourceSlots[o]=n,r[n]=e,t.observerSlots[n]=o)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)E(e.tOwned[t]);delete e.tOwned}if(e.owned){for(t=e.owned.length-1;t>=0;t--)E(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}e.state=0}function T(e,t=s){const n=function(e){return e instanceof Error?e:new Error("string"==typeof e?e:"Unknown error",{cause:e})}(e);throw n}function O(e,t){return f((()=>e(t||{})))}function D(e){const t=e.keyed,n=h((()=>e.when),void 0,void 0),r=t?n:h(n,void 0,{equals:(e,t)=>!e==!t});return h((()=>{const o=r();if(o){const i=e.children;return"function"==typeof i&&i.length>0?f((()=>i(t?o:()=>{if(!f(r))throw"Stale read from <Show>.";return n()}))):i}return e.fallback}),void 0,void 0)}const _="_$DX_DELEGATE";function R(e,t,n,r){let o;const i=()=>{const t=document.createElement("template");return t.innerHTML=e,t.content.firstChild},s=t?()=>f((()=>document.importNode(o||(o=i()),!0))):()=>(o||(o=i())).cloneNode(!0);return s.cloneNode=s,s}function I(e,t=window.document){const n=t[_]||(t[_]=new Set);for(let r=0,o=e.length;r<o;r++){const o=e[r];n.has(o)||(n.add(o),t.addEventListener(o,M))}}function N(e,t,n){null==n?e.removeAttribute(t):e.setAttribute(t,n)}function F(e,t,n,r){Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n}function $(e,t,n){if(!t)return n?N(e,"style"):t;const r=e.style;if("string"==typeof t)return r.cssText=t;let o,i;for(i in"string"==typeof n&&(r.cssText=n=void 0),n||(n={}),t||(t={}),n)null==t[i]&&r.removeProperty(i),delete n[i];for(i in t)o=t[i],o!==n[i]&&(r.setProperty(i,o),n[i]=o);return n}function L(e,t,n,r){if(void 0===n||r||(r=[]),"function"!=typeof t)return U(e,t,r,n);p((r=>U(e,t(),r,n)),r)}function M(e){let t=e.target;const n=`$$${e.type}`,r=e.target,o=e.currentTarget,i=t=>Object.defineProperty(e,"target",{configurable:!0,value:t}),s=()=>{const r=t[n];if(r&&!t.disabled){const o=t[`${n}Data`];if(void 0!==o?r.call(t,o,e):r.call(t,e),e.cancelBubble)return}return t.host&&"string"!=typeof t.host&&!t.host._$host&&t.contains(e.target)&&i(t.host),!0},a=()=>{for(;s()&&(t=t._$host||t.parentNode||t.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get:()=>t||document}),e.composedPath){const n=e.composedPath();i(n[0]);for(let e=0;e<n.length-2&&(t=n[e],s());e++){if(t._$host){t=t._$host,a();break}if(t.parentNode===o)break}}else a();i(r)}function U(e,t,n,r,o){for(;"function"==typeof n;)n=n();if(t===n)return n;const i=typeof t,s=void 0!==r;if(e=s&&n[0]&&n[0].parentNode||e,"string"===i||"number"===i){if("number"===i&&(t=t.toString())===n)return n;if(s){let o=n[0];o&&3===o.nodeType?o.data!==t&&(o.data=t):o=document.createTextNode(t),n=B(e,n,r,o)}else n=""!==n&&"string"==typeof n?e.firstChild.data=t:e.textContent=t}else if(null==t||"boolean"===i)n=B(e,n,r);else{if("function"===i)return p((()=>{let o=t();for(;"function"==typeof o;)o=o();n=U(e,o,n,r)})),()=>n;if(Array.isArray(t)){const i=[],a=n&&Array.isArray(n);if(G(i,t,n,o))return p((()=>n=U(e,i,n,r,!0))),()=>n;if(0===i.length){if(n=B(e,n,r),s)return n}else a?0===n.length?H(e,i,r):function(e,t,n){let r=n.length,o=t.length,i=r,s=0,a=0,l=t[o-1].nextSibling,c=null;for(;s<o||a<i;)if(t[s]!==n[a]){for(;t[o-1]===n[i-1];)o--,i--;if(o===s){const t=i<r?a?n[a-1].nextSibling:n[i-a]:l;for(;a<i;)e.insertBefore(n[a++],t)}else if(i===a)for(;s<o;)c&&c.has(t[s])||t[s].remove(),s++;else if(t[s]===n[i-1]&&n[a]===t[o-1]){const r=t[--o].nextSibling;e.insertBefore(n[a++],t[s++].nextSibling),e.insertBefore(n[--i],r),t[o]=n[i]}else{if(!c){c=new Map;let e=a;for(;e<i;)c.set(n[e],e++)}const r=c.get(t[s]);if(null!=r)if(a<r&&r<i){let l,g=s,u=1;for(;++g<o&&g<i&&null!=(l=c.get(t[g]))&&l===r+u;)u++;if(u>r-a){const o=t[s];for(;a<r;)e.insertBefore(n[a++],o)}else e.replaceChild(n[a++],t[s++])}else s++;else t[s++].remove()}}else s++,a++}(e,n,i):(n&&B(e),H(e,i));n=i}else if(t.nodeType){if(Array.isArray(n)){if(s)return n=B(e,n,r,t);B(e,n,null,t)}else null!=n&&""!==n&&e.firstChild?e.replaceChild(t,e.firstChild):e.appendChild(t);n=t}}return n}function G(e,t,n,r){let o=!1;for(let i=0,s=t.length;i<s;i++){let s,a=t[i],l=n&&n[e.length];if(null==a||!0===a||!1===a);else if("object"==(s=typeof a)&&a.nodeType)e.push(a);else if(Array.isArray(a))o=G(e,a,l)||o;else if("function"===s)if(r){for(;"function"==typeof a;)a=a();o=G(e,Array.isArray(a)?a:[a],Array.isArray(l)?l:[l])||o}else e.push(a),o=!0;else{const t=String(a);l&&3===l.nodeType&&l.data===t?e.push(l):e.push(document.createTextNode(t))}}return o}function H(e,t,n=null){for(let r=0,o=t.length;r<o;r++)e.insertBefore(t[r],n)}function B(e,t,n,r){if(void 0===n)return e.textContent="";const o=r||document.createTextNode("");if(t.length){let r=!1;for(let i=t.length-1;i>=0;i--){const s=t[i];if(o!==s){const t=s.parentNode===e;r||i?t&&s.remove():t?e.replaceChild(o,s):e.insertBefore(o,n)}else r=!0}}else e.insertBefore(o,n);return[o]}const j=3,K=e=>1e3*e;async function W(e,t={}){const{maxAttempts:n=j,delayFn:r=K}=t;let o=null;for(let t=1;t<=n;t++)try{return await e()}catch(e){o=e,t<n&&await new Promise((e=>setTimeout(e,r(t))))}throw o||new Error("Operation failed after multiple attempts")}const V=chrome;async function Y(e,t){return new Promise(((n,r)=>{try{const o=t=>{if(chrome.runtime.lastError)return r({error:chrome.runtime.lastError,message:e});n(t)};t?.tabId||V.runtime.sendMessage(e,o)}catch(e){r(e)}}))}async function z(e,t,n){return W((()=>Y(e,t)),{maxAttempts:j,delayFn:K})}const q={display:"block",position:"fixed",top:"0%",left:"100%",width:"500px",height:"510px","margin-left":"-560px","margin-top":"50px",padding:"2px 5px","background-color":"white",border:"1px solid black","border-radius":"10px","box-shadow":"0 2px 10px rgba(0, 0, 0, 0.1)","z-index":"2147483647","font-family":"Arial","line-height":"1","vertical-align":"baseline","box-sizing":"border-box",color:"rgb(34, 34, 34)","@media (max-width: 600px), (max-height: 480px)":{display:"none !important"}},X={height:"100%","overflow-x":"hidden","overlfow-y":"auto",position:"relative",padding:"0px 15px"},Z={},J={display:"flex","align-items":"center","margin-bottom":"10px"},Q={flex:"1","font-size":"24px","font-weight":"700","margin-top":"20px","margin-bottom":"0px"},ee={background:"none",border:"none",padding:"4px 8px",color:"#666464","font-size":"38px",cursor:"pointer","line-height":"1"},te={"font-size":"18px","font-weight":"400","margin-top":"20px","margin-bottom":"0px"},ne={display:"flex",gap:"10px",width:"100%","margin-top":"20px","margin-bottom":"20px","flex-wrap":"wrap","justify-content":"space-between"},re={width:"28%",display:"flex","flex-direction":"column","align-items":"center",background:"none",border:"1px solid #ccc","border-radius":"5px",padding:"5px",gap:"5px","text-align":"center","font-size":"14px",cursor:"pointer",transition:"background-color 0.2s ease"},oe={"max-width":"120px","max-height":"70px","margin-bottom":"5px","object-fit":"contain"},ie={"background-color":"#FFD812",cursor:"pointer","border-radius":"8px",padding:"8px",color:"white","min-width":"100px",border:"0","font-weight":"600",width:"100%"},se={display:"flex","flex-direction":"column",gap:"10px",width:"100%","color-scheme":"light"},ae={display:"flex","align-items":"center",gap:"5px",border:"1px solid #ddd",padding:"15px","border-radius":"5px","font-weight":"600",cursor:"pointer","margin-bottom":"8px"},le={background:"none",border:"none",color:"blue","text-decoration":"underline",padding:"0",cursor:"pointer","margin-bottom":"15px"},ce={display:"flex","justify-content":"space-between",margin:"30px 0px 10px 0px","font-size":"14px"},ge={color:"#666464","text-decoration":"underline"},ue={color:"rgb(102, 100, 100)","text-decoration":"underline",margin:"0",cursor:"pointer"},de={width:"100%","background-color":"#f2f2f2",border:"1px solid black","border-radius":"10px","border-top":"1px solid #bbb7b7","margin-top":"10px","margin-bottom":"20px","box-sizing":"border-box"},pe={padding:"0 5px 0 10px",width:"100%","font-size":"12px","box-sizing":"border-box"},me={display:"grid","grid-template-columns":"4fr 1fr","padding-right":"15px","padding-bottom":"5px"},he={color:"#000","margin-bottom":"4px"},fe={"font-size":"14px",color:"#555","text-align":"right"},Ae=(e,t)=>{let n=parseFloat(t);return"FLAT"===e&&(n*=.75),((e,t)=>{let n=parseFloat(t);return n<1&&(n=1),n=Math.floor(n),"PERCENTAGE"===e?`${n}%`:`$${n}`})(e,n.toString())};var be=R("<span>");function xe(e){const t=(n=e.title,r=e.activeDomain,n.replace("{0}",Ae(r.Merchant.MaxRate?.Kind,r.Merchant.MaxRate?.Amount??"0")));var n,r,o;return(o=be()).innerHTML=t,o}var ye=R("<div>"),ve=R("<div><div class=gf-offer-details><p>Select a charity to activate a donation during your online shopping session.</p><p> <b>Eligible Transaction:</b> A purchase made immediately after selecting a charity.</p><p><b>Donation rates:</b> <!> for each eligible transaction. The following donation rates and exclusions apply:</p><p><b>Donation amounts:</b> Donation amount is calculated based upon the applicable rates and exclusions, which may change from time to time. Amounts may be adjusted or canceled due to returned items, suspected fraud, or other factors described within the terms and conditions.</p><p><b>Donation timing:</b> On average, donation payouts occur 60-120 days after your completed transaction, but some donations may take 180 days or longer. We provide a donation to the charity you had selected at the time of purchase, in monthly batches, after any holdback periods due to applicable return or cancellation policies have passed.</p><p>See a summary of <a target=_blank rel=noreferrer>terms and conditions</a>."),we=R("<div class=gf-offer-details-rate-item><div></div><div>");const Ce=e=>{return t=ve(),o=(r=(n=t.firstChild).firstChild.nextSibling.nextSibling).firstChild.nextSibling.nextSibling,i=r.nextSibling,s=i.nextSibling.nextSibling.firstChild.nextSibling,L(r,(()=>e.parsedMaxRate?`Up to ${e.parsedMaxRate}`:"Earn"),o),L(n,O(D,{get when(){return!!e.merchantRateDetail?.length},get children(){var t=ye();return L(t,(()=>e.merchantRateDetail?.map((e=>{return t=we(),n=t.firstChild,r=n.nextSibling,L(n,(()=>e.Name||"")),L(r,(()=>((e,t=1,n=1)=>{const r=e.BoostedOffer??null;let o=parseFloat(e?.Amount??"");if(r?.EndDate&&new Date(r.EndDate)<new Date&&(o=parseFloat(r.OriginalMaxRate)),Number.isNaN(o))return"";const i=o*t;return"PERCENTAGE"===e?.Kind?`${i.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:n})}%`:"FLAT"===e?.Kind?i.toLocaleString("en-US",{style:"currency",currency:e.Currency}):""})(e))),p((e=>{var o=me,i=he,s=fe;return e.e=$(t,o,e.e),e.t=$(n,i,e.t),e.a=$(r,s,e.a),e}),{e:void 0,t:void 0,a:void 0}),t;var t,n,r})))),t}}),i),p((r=>{var o=de,i=pe,a=ge,l=e.termsUrl;return r.e=$(t,o,r.e),r.t=$(n,i,r.t),r.a=$(s,a,r.a),l!==r.o&&N(s,"href",r.o=l),r}),{e:void 0,t:void 0,a:void 0,o:void 0}),t;var t,n,r,o,i,s};var ke=R("<button class=give-freely-close-button aria-label=Close>×"),Pe=R('<div><div><div><span></span></div></div><hr><div></div><div><div><div><br><span></span></div><button aria-label="Don\'t show again"></button></div></div><div><p>Offer Details</p><a class=give-freely-footer-link target=_blank rel="noopener noreferrer">Why am I seeing this?'),Se=R("<div><div><img><span></span></div><button>");function Ee(e){const[t,n]=d(!1);return m((()=>{t()&&e.mainContainerRef&&e.mainContainerRef.scroll({top:e.mainContainerRef.scrollHeight,behavior:"smooth"})})),[(r=Pe(),o=r.firstChild,i=o.firstChild,s=i.firstChild,a=o.nextSibling.nextSibling,l=a.nextSibling,c=l.firstChild,g=c.firstChild,u=g.firstChild.nextSibling,f=g.nextSibling,A=l.nextSibling,b=A.firstChild,x=b.nextSibling,L(o,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupMainCloseButtonVisible},get children(){var t=ke();return F(t,"click",e.onClose),p((e=>$(t,ee,e))),t}}),null),L(a,O(xe,{get title(){return e.subtitle},get activeDomain(){return e.activeDomain}})),L(l,(()=>e.checkoutPopupConf.checkoutPopupCharities.map((t=>{return r=(n=Se()).firstChild,i=(o=r.firstChild).nextSibling,s=r.nextSibling,n.$$click=()=>e.onCharitySelect(t),r.style.setProperty("height","100px"),r.style.setProperty("text-align","center"),L(i,(()=>t.title)),L(s,(()=>e.checkoutPopupConf.checkoutPopupCharitySelectString||"Select")),p((r=>{var i=re,a=t.logo,l=oe,c=t.title,g={...ie,"background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812"},u=`Select charity: ${t.title}`;return r.e=$(n,i,r.e),a!==r.t&&N(o,"src",r.t=a),r.a=$(o,l,r.a),c!==r.o&&N(o,"alt",r.o=c),r.i=$(s,g,r.i),u!==r.n&&N(s,"aria-label",r.n=u),r}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),n;var n,r,o,i,s}))),c),F(c,"click",e.onSuppress),g.style.setProperty("height","100px"),g.style.setProperty("text-align","center"),L(f,(()=>e.checkoutPopupConf.checkoutPopupCharitySelectString||"Select")),b.$$click=()=>{e.onOfferDetailsClick(!t()),n(!t())},p((t=>{var n=Z,g=J,d=Q,p=e.checkoutPopupConf.checkoutPopupMainTitle,m=te,h=ne,y=re,v=e.checkoutPopupConf.checkoutPopupSixthBoxWording,w={...ie,"background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812"},C=ce,k=ue,P=ge,S=e.checkoutPopupConf.externalUrls.giveFreelyWhyAmISeeingThis;return t.e=$(r,n,t.e),t.t=$(o,g,t.t),t.a=$(i,d,t.a),p!==t.o&&(s.innerHTML=t.o=p),t.i=$(a,m,t.i),t.n=$(l,h,t.n),t.s=$(c,y,t.s),v!==t.h&&(u.innerHTML=t.h=v),t.r=$(f,w,t.r),t.d=$(A,C,t.d),t.l=$(b,k,t.l),t.u=$(x,P,t.u),S!==t.c&&N(x,"href",t.c=S),t}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0}),r),O(D,{get when(){return t()},get children(){return O(Ce,{get merchantName(){return e.activeDomain.Merchant.Name},get extensionName(){return e.checkoutPopupConf.displayName},get termsUrl(){return e.checkoutPopupConf.externalUrls.giveFreelyTermsAndConditions},get parsedMaxRate(){return h((()=>!!e.activeDomain.Merchant.MaxRate))()?Ae(e.activeDomain.Merchant.MaxRate.Kind,e.activeDomain.Merchant.MaxRate?.Amount):null},get merchantRateDetail(){return e.merchantRates},onClose:()=>n(!1)})}})];var r,o,i,s,a,l,c,g,u,f,A,b,x}I(["click"]);var Te=R("<button class=give-freely-close-button aria-label=Close>×"),Oe=R("<label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=18250><span>Don't ask me again... ever"),De=R("<div><div><div></div></div><button class=give-freely-back-button aria-label=\"Back to charity selection\">I changed my mind! I'd like to select a charity.</button><hr><div id=give-freely-goodbye-screen-options><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=1><span>Don't ask me again for 1 day</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=7><span>Don't ask me again for 7 days</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=30><span>Don't ask me again for 30 days</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=90><span>Don't ask me again for 90 days</span></label></div><button class=give-freely-submit-button>Submit");function _e(e){const[t,n]=d(0);return r=De(),o=r.firstChild,i=o.firstChild,s=o.nextSibling,a=s.nextSibling.nextSibling,c=(l=a.firstChild).firstChild,u=(g=l.nextSibling).firstChild,h=(m=g.nextSibling).firstChild,A=(f=m.nextSibling).firstChild,b=a.nextSibling,r.style.setProperty("font-size","14px"),L(i,(()=>e.checkoutPopupConf.checkoutPopupSupressTitle)),L(o,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupSupressCloseButtonVisible},get children(){var t=Te();return t.$$click=()=>e.onGoodbye(0),p((e=>$(t,ee,e))),t}}),null),F(s,"click",e.onBack),c.addEventListener("change",(()=>n(1))),u.addEventListener("change",(()=>n(7))),h.addEventListener("change",(()=>n(30))),A.addEventListener("change",(()=>n(90))),L(a,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupNeverSuppressionAllowed},get children(){var e=Oe();return e.firstChild.addEventListener("change",(()=>n(18250))),p((t=>$(e,ae,t))),e}}),null),b.$$click=()=>{const n=t();n&&(e.onGoodbye(n),e.setScreen("main"))},p((t=>{var n=J,r=Q,c=le,u=se,d=ae,p=ae,h=ae,A=ae,x={...ie,"font-weight":"700","margin-top":"10px","margin-bottom":"0px","background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812",width:"100px"};return t.e=$(o,n,t.e),t.t=$(i,r,t.t),t.a=$(s,c,t.a),t.o=$(a,u,t.o),t.i=$(l,d,t.i),t.n=$(g,p,t.n),t.s=$(m,h,t.s),t.h=$(f,A,t.h),t.r=$(b,x,t.r),t}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),r;var r,o,i,s,a,l,c,g,u,m,h,f,A,b}I(["click"]);var Re=R("<div><div><div></div><button class=give-freely-close-button aria-label=Close>×</button></div><hr><div><span>");function Ie(e){return t=Re(),n=t.firstChild,r=n.firstChild,o=r.nextSibling,i=n.nextSibling.nextSibling,s=i.firstChild,t.style.setProperty("font-size","14px"),L(r,(()=>e.failedDonation?"Oops! Something went wrong":e.checkoutPopupConf.checkoutPopupDonationTitle)),F(o,"click",e.onClose),i.style.setProperty("padding","30px"),i.style.setProperty("height","150px"),i.style.setProperty("font-size","14px"),p((t=>{var i=J,a=Q,l=ee,c=e.failedDonation?"Please try again later.":e.checkoutPopupConf.checkoutPopupDonationWording;return t.e=$(n,i,t.e),t.t=$(r,a,t.t),t.a=$(o,l,t.a),c!==t.o&&(s.innerHTML=t.o=c),t}),{e:void 0,t:void 0,a:void 0,o:void 0}),t;var t,n,r,o,i,s}I(["click"]);var Ne,Fe,$e=R("<div><div>");function Le(e){const{logger:t}=e,[n,r]=d("main"),[o,i]=d(),[s,a]=d(!1),l=()=>{t.debug("Close button clicked"),e.onClose()},c=async n=>{t.info("Charity selected",{charity:n,domain:e.activeDomain.Domain}),i(n);const o=await e.onDonate(n,e.activeDomain);a(!o),r("donate")},g=()=>{t.debug("Suppress button clicked"),r("goodbye")},u=()=>{t.debug("Navigating back to main screen"),r("main")},m=n=>{t.info("User chose to hide popup",{days:n}),e.onClose(n)};let h;return x=$e(),y=x.firstChild,"function"==typeof h?(A=h,b=y,f((()=>A(b,undefined)))):h=y,L(y,O(D,{get when(){return"main"===n()},get children(){return O(Ee,{mainContainerRef:h,get checkoutPopupConf(){return e.checkoutPopupConf},get activeDomain(){return e.activeDomain},get merchantRates(){return e.merchantRates},onClose:l,onCharitySelect:c,onSuppress:g,get onOfferDetailsClick(){return e.onOfferDetailsClick},get subtitle(){return e.checkoutPopupConf.checkoutPopupSubTitle}})}}),null),L(y,O(D,{get when(){return"goodbye"===n()},get children(){return O(_e,{get checkoutPopupConf(){return e.checkoutPopupConf},onClose:()=>e.onClose(),onBack:u,onGoodbye:m,setScreen:r})}}),null),L(y,O(D,{get when(){return"donate"===n()},get children(){return O(Ie,{get checkoutPopupConf(){return e.checkoutPopupConf},get selectedCharity(){return o()},onClose:()=>e.onClose(),get failedDonation(){return s()},setScreen:r})}}),null),p((t=>{var n=q,r=e.elementId,o=X;return t.e=$(x,n,t.e),r!==t.t&&N(x,"id",t.t=r),t.a=$(y,o,t.a),t}),{e:void 0,t:void 0,a:void 0}),x;var A,b,x,y}class Me{log({level:e,message:t,timestamp:n,data:r,title:o}){const i="debug"===e?"log":e,s=o?`[${o}]`:"";void 0!==r?console[i](`[${n}] - ${Me.LOGGER_PREFIX} ${s} ${t}`,r):console[i](`[${n}] - ${Me.LOGGER_PREFIX} ${s} ${t}`)}}Me.LOGGER_PREFIX="[GFAdUnit] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED"}(Ne||(Ne={})),function(e){e.adUnitLog="ADUNIT-LOG"}(Fe||(Fe={}));const Ue=["debug","info","warn","error"];class Ge{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new Me],title:e?.title??""}}static getInstance(e){return Ge.instance||(Ge.instance=new Ge(e)),Ge.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&Ue.indexOf(e)>=Ue.indexOf(this.config.minLevel)}createLogMessage(e,t,n){return{level:e,version:"1.1.0",message:t,timestamp:(new Date).toISOString(),data:n,title:this.config.title}}log(e,t,n){if(!this.shouldLog(e))return;const r=this.createLogMessage(e,t,n);this.config.transports.forEach((e=>e.log(r)))}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}function He(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var Be={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",n=e=>{const n={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(n).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class r extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const o=(t,n)=>(...r)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):n.singleCallbackArg||r.length<=1&&!1!==n.singleCallbackArg?t.resolve(r[0]):t.resolve(r)},i=e=>1==e?"argument":"arguments",s=(e,t,n)=>new Proxy(t,{apply:(t,r,o)=>n.call(r,e,...o)});let a=Function.call.bind(Object.prototype.hasOwnProperty);const l=(e,t={},n={})=>{let r=Object.create(null),c={has:(t,n)=>n in e||n in r,get(c,g,u){if(g in r)return r[g];if(!(g in e))return;let d=e[g];if("function"==typeof d)if("function"==typeof t[g])d=s(e,e[g],t[g]);else if(a(n,g)){let t=((e,t)=>function(n,...r){if(r.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${r.length}`);if(r.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${r.length}`);return new Promise(((i,s)=>{if(t.fallbackToNoCallback)try{n[e](...r,o({resolve:i,reject:s},t))}catch(o){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,o),n[e](...r),t.fallbackToNoCallback=!1,t.noCallback=!0,i()}else t.noCallback?(n[e](...r),i()):n[e](...r,o({resolve:i,reject:s},t))}))})(g,n[g]);d=s(e,e[g],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(a(t,g)||a(n,g)))d=l(d,t[g],n[g]);else{if(!a(n,"*"))return Object.defineProperty(r,g,{configurable:!0,enumerable:!0,get:()=>e[g],set(t){e[g]=t}}),d;d=l(d,t[g],n["*"])}return r[g]=d,d},set:(t,n,o,i)=>(n in r?r[n]=o:e[n]=o,!0),defineProperty:(e,t,n)=>Reflect.defineProperty(r,t,n),deleteProperty:(e,t)=>Reflect.deleteProperty(r,t)},g=Object.create(e);return new Proxy(g,c)},c=e=>({addListener(t,n,...r){t.addListener(e.get(n),...r)},hasListener:(t,n)=>t.hasListener(e.get(n)),removeListener(t,n){t.removeListener(e.get(n))}}),g=new r((e=>"function"!=typeof e?e:function(t){const n=l(t,{},{getContent:{minArgs:0,maxArgs:0}});e(n)})),u=new r((e=>"function"!=typeof e?e:function(t,n,r){let o,i,s=!1,a=new Promise((e=>{o=function(t){s=!0,e(t)}}));try{i=e(t,n,o)}catch(e){i=Promise.reject(e)}const l=!0!==i&&((c=i)&&"object"==typeof c&&"function"==typeof c.then);var c;if(!0!==i&&!l&&!s)return!1;return(l?i:a).then((e=>{r(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",r({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:n,resolve:r},o)=>{e.runtime.lastError?e.runtime.lastError.message===t?r():n(new Error(e.runtime.lastError.message)):o&&o.__mozWebExtensionPolyfillReject__?n(new Error(o.message)):r(o)},p=(e,t,n,...r)=>{if(r.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${r.length}`);if(r.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${r.length}`);return new Promise(((e,t)=>{const o=d.bind(null,{resolve:e,reject:t});r.push(o),n.sendMessage(...r)}))},m={devtools:{network:{onRequestFinished:c(g)}},runtime:{onMessage:c(u),onMessageExternal:c(u),sendMessage:p.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:p.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},h={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return n.privacy={network:{"*":h},services:{"*":h},websites:{"*":h}},l(e,m,n)};e.exports=n(chrome)}}(Be);var je=He(Be.exports);const Ke="GIVE_FREELY_",We={async get(e){const t=`${Ke}${e}`;return(await je.storage.local.get(t))[t]||null},async set(e,t){const n=`${Ke}${e}`;await je.storage.local.set({[n]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${Ke}${e}`)):`${Ke}${e}`;await je.storage.local.remove(t)}};class Ve{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0,this.CONFIG_REFRESH_INTERVAL=3e5,this.PARTNER_CONFIG_STORAGE_KEY="gf_partner_config",this.GLOBAL_CONFIG_STORAGE_KEY="gf_global_config"}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchAndUpdatePartnerConfig(){const e=await W((async()=>{const e=await fetch(`https://cdn.givefreely.com/adunit/config/${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await We.set(this.PARTNER_CONFIG_STORAGE_KEY,t),e}async fetchAndUpdateGlobalConfig(){const e=await W((async()=>{const e=await fetch("https://cdn.givefreely.com/adunit/config/global.json",{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await We.set(this.GLOBAL_CONFIG_STORAGE_KEY,t),e}async getConfig(){const e=Date.now(),t=await We.get(this.PARTNER_CONFIG_STORAGE_KEY),n=await We.get(this.GLOBAL_CONFIG_STORAGE_KEY);if(this.partnerConfig=t?.config||null,this.globalConfig=n?.config||null,this.lastConfigRefresh=Math.max(t?.lastRefresh||0,n?.lastRefresh||0),!this.partnerConfig||!this.globalConfig||e-this.lastConfigRefresh>this.CONFIG_REFRESH_INTERVAL)try{const[t,n]=await Promise.all([this.fetchAndUpdatePartnerConfig(),this.fetchAndUpdateGlobalConfig()]);this.partnerConfig=t,this.globalConfig=n,this.lastConfigRefresh=e}catch(e){if(!this.partnerConfig||!this.globalConfig)throw e;console.warn("Failed to refresh configs, using existing configs:",e)}const r=this.mergeConfigs(this.globalConfig,this.partnerConfig);return((e,t,n)=>{const r=[...t.merchantExclusions??[],...n.merchantExclusions??[]];e.merchantExclusions=r})(r,this.globalConfig,this.partnerConfig),r}async clearCache(){await Promise.all([We.remove(this.PARTNER_CONFIG_STORAGE_KEY),We.remove(this.GLOBAL_CONFIG_STORAGE_KEY)]),this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0}mergeConfigs(e,t){if(!t)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e,i=t;"object"==typeof i[r]&&null!==i[r]&&"object"==typeof o[r]?n[r]=this.mergeConfigs(o[r],i[r]):n[r]=void 0!==i[r]?i[r]:o[r]}return n}getStoredState(e){return e?{config:e.config,lastRefresh:e.lastRefresh}:{config:null,lastRefresh:0}}}const Ye="TRACK_EVENT",ze="GF_HIDE_POPUP",qe="GF_GET_POPUP_CONFIG",Xe="GF_IS_ACTIVE_DOMAIN",Ze="GF_SHOULD_STAND_DOWN",Je="GF_ACTIVATE_OFFER",Qe="GF_STORE_SHOPIFY_SHOP_ID",et="GF_GET_DOMAIN_BY_SHOP_ID";class tt{constructor(t,n,r=60){this._config=null,this.track=async(t,n,r)=>{null===this._config&&(this._config=await new Ve(this._partnerApiKey).getConfig());const o={partner:`adUnit_${this._partnerApiKey}`,eventType:t,eventData:{userId:this._userService?.user?.id,libVersion:String(e)??"",wfDeviceId:n,...r}};try{const e=JSON.stringify(o);return await this.shouldBroadcastEvent(e)?(await fetch(this._config.eventsUrl,{headers:{"Content-Type":"application/json"},method:"POST",body:e,cache:"no-store"}),await this.pushEventToHistory(e),!0):(this.log("This event has already been broadcasted during the past hour",o),!1)}catch(e){return this.log("Something unexpected happened when dispatching a gf event",e,o),!1}},this.log=(...e)=>{"debug"===this._config?.backgroundMinLogLevel&&console.log("analytics:",...e)},this.getEventsHistory=async()=>{const{GF_AD_EVENT_HISTORY:e}=await V.storage.local.get({GF_AD_EVENT_HISTORY:""}),t=function(e){const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()}(-this._debounceWindowInMinutes);let n=(e||[]).filter((e=>e.createdAt>t));return await V.storage.local.set({GF_AD_EVENT_HISTORY:n}),n},this.shouldBroadcastEvent=async e=>!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await V.storage.local.set({GF_AD_EVENT_HISTORY:t})},this._partnerApiKey=t,this._userService=n,this._debounceWindowInMinutes=r}}function nt(e){const t=["",".asp",".aspx",".php",".js",".htm",".html"],n=["cart","checkout","shopping-bag","shopping-basket","shopping-cart","basket"].flatMap((e=>t.map((t=>e+t)))).filter((e=>"basket"!==e)),r=["tote-cart","tote.cart"],o=e,i=n.filter((e=>o.includes(e))),s=o.split("/");return!s.some((e=>r.some((t=>e.includes(t)))))&&(s.some((e=>n.some((t=>e.startsWith(t)||e.endsWith(t)))))||"basket"===s[s.length-1].toLowerCase()||i.length>1||1===i.length&&o.includes("shopping"))}function rt(e,t){const n=["book"];return e.split("/").some((e=>n.some((t=>e.startsWith(t)||e.endsWith(t)))))&&null!=t.evaluate("//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6][contains(., 'Your Reservation') or contains(., 'Your reservation')]",t,null,XPathResult.ANY_TYPE,null)?.iterateNext()}async function ot(e){try{const t=await Y({type:et,payload:{shopId:e}});return t.payload.found&&t.payload.domain?t.payload.domain:null}catch(e){return null}}function it(){try{const e=Array.from(document.querySelectorAll("script"));for(const t of e){if(t.dataset?.shopId?.startsWith("gid")){const e=parseInt(t.dataset.shopId.replace("gid://shopify/Shop/",""));if(!isNaN(e)&&e>0)return e}const e=t.textContent||"";if(e.includes("ShopifyAnalytics")&&e.includes("shopId")){const t=e.match(/shopId['"]*:\s*['"]*(\d+)['"]*[,}]/);if(t&&t[1]){const e=parseInt(t[1]);if(!isNaN(e)&&e>0)return e}}}const t=document.querySelector("[data-shop-id]");if(t instanceof HTMLElement){const e=t.dataset.shopId;if(e){const t=parseInt(e);if(!isNaN(t)&&t>0)return t}}const n=window?.ShopifyAnalytics?.lib?.trekkie?.defaultAttributes?.shopId;return n&&parseInt(n)||0}catch(e){return console.error("Error accessing ShopifyAnalytics:",e),0}}function st(){try{if(!window.location.href.startsWith("https://shop.app"))return 0;const e=document?.head?.querySelector('meta[name="store"][content]');if(!e)return 0;try{const t=JSON.parse(e.content);return t?.id||0}catch(e){return 0}}catch(e){return 0}}tt.trackEvent=async(e,t)=>{await Y({type:Ye,payload:{eventType:e,eventData:t}})};const at=Ge.getInstance();function lt(e,t,n){try{const r=function(e){try{const t=e.split(".");return t.length>=2?t.slice(-2).join("."):e}catch(e){return at.error("Error extracting domain",e),""}}(n);at.debug("Checking merchant regex rules",{currentDomain:r,currentUrl:t});const o=e.merchantPopupRules.filter((e=>r.includes(e.domain)));if(0===o.length)return at.debug("No matching merchant rules found for domain",{currentDomain:r}),!1;for(const e of o)for(const n of e.rules)try{if(new RegExp(n.rule).test(t))return at.debug("Merchant regex rule matched",{merchant:e.name,rule:n.rule,currentUrl:t}),!0}catch(t){at.error("Invalid regex in merchant rule",{merchant:e.name,rule:n.rule,error:t})}return at.debug("No matching regex rules found",{currentUrl:t}),!1}catch(e){return at.error("Error in merchantRegexRule",e),!1}}var ct=R("<div class=gf-app>");function gt(){const t=Ge.getInstance(),[n,r]=d(null),[o,i]=d(void 0),[s,a]=d(!1),[l,c]=d([]);var g;g=async()=>{t.info("Mounting GfApp component");try{const n=await(async()=>{const e=await Y({type:qe,payload:{}});if(!e.payload.config)throw new Error("No checkout popup config found");return e.payload.config})();if(!n)return void t.error("No checkout popup config found");r(n),t.configure({enabled:!0,title:"Content - GfAdUnit",minLevel:n.checkoutPopupMinLogLevel??"error"});const s=String(e);if(n.minVersion&&((e,t)=>{if(e===t)return!1;const n=e.split(".").map(parseInt),r=t.split(".").map(parseInt);for(let e=0;e<n.length;e++){if(n[e]<r[e])return!0;if(n[e]>r[e])return!1}return!1})(s,n.minVersion))return void t.debug(`Current version: ${s}. Minimum version ${n.minVersion} not met`);if(!1===n.checkoutPopupMasterSwitch)return void t.debug("Checkout popup master switch is disabled");const{domain:l,rates:g}=await(async e=>{const{hostname:t}=window.location;e.debug("Checking if domain is active",{hostname:t});const n=await Y({type:Xe,payload:{hostname:t}});return n.payload.isActive?(e.debug("Active domain",{domain:n.payload.domain}),e.debug("Merchant rates",{rates:n.payload.rates}),e.info("Domain and rates ({})ed successfully."),{isActive:!0,domain:n.payload.domain,rates:n.payload.rates}):{isActive:!1,domain:void 0,rates:[]}})(t);if(c(g),i(l),l)await function(e){const t=it()||st();return t>0&&function(e,t){if(e&&!(e<=0))try{Y({type:Qe,payload:{shopId:e,domain:t}}).catch((e=>{console.error("Error sending shop ID to background:",e)}))}catch(e){console.error("Error sending Shopify shop ID:",e)}}(t,e),t}(l);else{if("shop.app"!==window.location.hostname&&!window.location.hostname.endsWith(".shop.app"))return void a(!1);const e=window.location.pathname.split("/")[2];if(!e)return t.error("Shop ID not found"),void a(!1);const n=await ot(parseInt(e));if(!n)return t.error("Shop domain not found"),void a(!1);t.debug("Shop domain found",{shopDomain:n}),i(n)}const u=await(async e=>{const t=await We.get("popup_hide");if(!t)return e.debug("No expiry found in storage"),!1;const{popupHide:n}=t,r=!!n&&Date.now()<n;return e.debug("Is AdUnit Muted?",{isMuted:r,expiry:n}),r})(t);if(u)return;if(!o())return void a(!1);const d=await(async(e,t)=>{const{Domain:n}=t,r=window.location.href,{payload:o}=await Y({type:Ze,payload:{activeDomain:n,url:r}});return!!o.result&&(e.info("Stand Down detected"),!0)})(t,o());if(d)return void a(!1);const p=setInterval((async()=>{t.debug("Checking checkout rules");const e=await(async e=>{const t=Ge.getInstance();t.configure({enabled:!0,title:"Content - checkoutRulesTest"});const n=new URL(globalThis.location.href),r=n.href,o=n.hostname;t.debug("Checking if popup should be shown",{currentUrl:r});const i=await async function(){const e=it()||st();return!("shop.app"!==window.location.hostname&&!window.location.hostname.endsWith(".shop.app")||!(e>0)||!await ot(e))}(),s=nt(n.pathname.toLowerCase())||rt(r,document)||lt(e,r,o)||i;return t.debug("Popup show decision based on rules",{shouldShow:s,matchesCartRule:nt(n.pathname.toLowerCase()),matchesBookingRule:rt(r,document),matchesShopPayRule:i,matchesMerchantRegexRule:lt(e,r,o)}),s})(n);a(e),e&&(t.debug("Should show popup based on checkout rules",{shouldShowResult:e}),tt.trackEvent(Ne.checkoutPopupShown,{url:globalThis.window.location.href}),clearInterval(p))}),2e3)}catch(e){a(!1),t.error("An error occurred in GfApp",{error:e})}},m((()=>f(g)));const u=async(e,n)=>{t.info("Processing donation",{charity:e,domain:n.Domain});const r=await(async(e,t,n,r)=>{e.debug("Activating offer",{activeDomain:t,selectedCharity:r});const o=await z({type:Je,payload:{activeDomain:t,originalUrl:n,selectedCharity:r}});return e.debug("Activate offer response",{response:o}),o})(t,n,window.location.href,{ein:e.ein,thirdPartyId:e.tpi});return t.debug("Activate offer response",{activationResponse:r}),tt.trackEvent(r.payload.response?Ne.checkoutPopupDonation:Ne.checkoutPopupFailedActivation,{activeDomain:n.Domain,url:globalThis.window.location.href,charity:{ein:e.ein,tpi:e.tpi},rate:n.Merchant.MaxRate}),r.payload.response},p=async e=>{a(await(async(e,t)=>{try{e.info("Hiding ad",{days:t});const n=await z({type:ze,payload:{days:t??0}});return t&&t>0&&tt.trackEvent(Ne.checkoutPopupSupressed,{url:globalThis.window.location.href,days:t}),e.info("Hiding ad response",{hide_response:n}),n.payload.ack?(e.debug("Ad hidden successfully"),!1):(e.warn("Failed to hide ad"),!0)}catch(e){return!1}})(t,e))},A=async e=>{tt.trackEvent(Ne.checkoutPopupOfferDetailsClicked,{action:e?"opened":"closed"})};return L(x=ct(),(b=h((()=>!(!o()||!s()))),()=>b()&&O(Le,{get checkoutPopupConf(){return n()},elementId:"give-freely-checkout-popup",get activeDomain(){return o()},get merchantRates(){return l()},onClose:p,onDonate:u,onOfferDetailsClick:A,logger:t}))),x;var b,x}exports.browser=V,exports.initializeAdUnit=async function(){const e=document.createElement("div");e.id="give-freely-root",document.body.appendChild(e);const t=e.attachShadow({mode:"open"}),n=document.createElement("div"),r=document.createElement("style");r.textContent='\n :host {\n all: initial;\n }\n\n .gf-scroll-remove::-webkit-scrollbar {\n border-radius-bottom-right: 15px;\n }\n\n button {\n cursor: pointer;\n transition: transform 0.1s ease;\n }\n\n button:active {\n transform: scale(0.98);\n }\n\n .give-freely-close-button:hover {\n opacity: 0.7;\n }\n\n input[type="radio"] {\n margin-right: 8px;\n }\n\n hr {\n border: none;\n border-top: 1px solid #e5e5e5;\n margin: 1em 0;\n }\n\n @media (max-width: 600px), (max-height: 480px) {\n #give-freely-checkout-popup {\n display: none !important;\n }\n }\n',t.appendChild(r),t.appendChild(n),function(e,t,n,r={}){let o;(function(e,t){const n=l,r=s,o=0===e.length,a=void 0===t?r:t,c=o?i:{owned:null,cleanups:null,context:a?a.context:null,owner:a},g=o?e:()=>e((()=>f((()=>E(c)))));s=c,l=null;try{return w(g,!0)}finally{l=n,s=r}})((r=>{o=r,t===document?e():L(t,e(),t.firstChild?null:void 0,n)}),r.owner)}((()=>O(gt,{})),n)};
@@ -1 +1 @@
1
- const e="1.1.1",t={equals:(e,t)=>e===t};let n=C;const r=1,o=2,i={owned:null,cleanups:null,context:null,owner:null};var s=null;let a=null,l=null,c=null,g=null,u=0;function d(e,n){const r={value:e,observers:null,observerSlots:null,comparator:(n=n?Object.assign({},t,n):t).equals||void 0};return[A.bind(r),e=>("function"==typeof e&&(e=e(r.value)),b(r,e))]}function p(e,t,n){x(y(e,t,!1,r))}function m(e,t,o){n=k;const i=y(e,t,!1,r);i.user=!0,g?g.push(i):x(i)}function h(e,n,r){r=r?Object.assign({},t,r):t;const o=y(e,n,!0,0);return o.observers=null,o.observerSlots=null,o.comparator=r.equals||void 0,x(o),A.bind(o)}function f(e){if(null===l)return e();const t=l;l=null;try{return e()}finally{l=t}}function A(){if(this.sources&&this.state)if(this.state===r)x(this);else{const e=c;c=null,w((()=>P(this)),!1),c=e}if(l){const e=this.observers?this.observers.length:0;l.sources?(l.sources.push(this),l.sourceSlots.push(e)):(l.sources=[this],l.sourceSlots=[e]),this.observers?(this.observers.push(l),this.observerSlots.push(l.sources.length-1)):(this.observers=[l],this.observerSlots=[l.sources.length-1])}return this.value}function b(e,t,n){let o=e.value;return e.comparator&&e.comparator(o,t)||(e.value=t,e.observers&&e.observers.length&&w((()=>{for(let t=0;t<e.observers.length;t+=1){const n=e.observers[t],o=a&&a.running;o&&a.disposed.has(n),(o?n.tState:n.state)||(n.pure?c.push(n):g.push(n),n.observers&&S(n)),o||(n.state=r)}if(c.length>1e6)throw c=[],new Error}),!1)),t}function x(e){if(!e.fn)return;E(e);const t=u;!function(e,t,n){let o;const i=s,a=l;l=s=e;try{o=e.fn(t)}catch(t){return e.pure&&(e.state=r,e.owned&&e.owned.forEach(E),e.owned=null),e.updatedAt=n+1,T(t)}finally{l=a,s=i}(!e.updatedAt||e.updatedAt<=n)&&(null!=e.updatedAt&&"observers"in e?b(e,o):e.value=o,e.updatedAt=n)}(e,e.value,t)}function y(e,t,n,o=r,a){const l={fn:e,state:o,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:s,context:s?s.context:null,pure:n};return null===s||s!==i&&(s.owned?s.owned.push(l):s.owned=[l]),l}function v(e){if(0===e.state)return;if(e.state===o)return P(e);if(e.suspense&&f(e.suspense.inFallback))return e.suspense.effects.push(e);const t=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<u);)e.state&&t.push(e);for(let n=t.length-1;n>=0;n--)if((e=t[n]).state===r)x(e);else if(e.state===o){const n=c;c=null,w((()=>P(e,t[0])),!1),c=n}}function w(e,t){if(c)return e();let r=!1;t||(c=[]),g?r=!0:g=[],u++;try{const t=e();return function(e){if(c&&(C(c),c=null),e)return;const t=g;g=null,t.length&&w((()=>n(t)),!1)}(r),t}catch(e){r||(g=null),c=null,T(e)}}function C(e){for(let t=0;t<e.length;t++)v(e[t])}function k(e){let t,n=0;for(t=0;t<e.length;t++){const r=e[t];r.user?e[n++]=r:v(r)}for(t=0;t<n;t++)v(e[t])}function P(e,t){e.state=0;for(let n=0;n<e.sources.length;n+=1){const i=e.sources[n];if(i.sources){const e=i.state;e===r?i!==t&&(!i.updatedAt||i.updatedAt<u)&&v(i):e===o&&P(i,t)}}}function S(e){for(let t=0;t<e.observers.length;t+=1){const n=e.observers[t];n.state||(n.state=o,n.pure?c.push(n):g.push(n),n.observers&&S(n))}}function E(e){let t;if(e.sources)for(;e.sources.length;){const t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){const e=r.pop(),o=t.observerSlots.pop();n<r.length&&(e.sourceSlots[o]=n,r[n]=e,t.observerSlots[n]=o)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)E(e.tOwned[t]);delete e.tOwned}if(e.owned){for(t=e.owned.length-1;t>=0;t--)E(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}e.state=0}function T(e,t=s){const n=function(e){return e instanceof Error?e:new Error("string"==typeof e?e:"Unknown error",{cause:e})}(e);throw n}function O(e,t){return f((()=>e(t||{})))}function D(e){const t=e.keyed,n=h((()=>e.when),void 0,{equals:(e,n)=>t?e===n:!e==!n});return h((()=>{const r=n();if(r){const o=e.children;return"function"==typeof o&&o.length>0?f((()=>o(t?r:()=>{if(!f(n))throw"Stale read from <Show>.";return e.when}))):o}return e.fallback}),void 0,void 0)}const _="_$DX_DELEGATE";function R(e,t,n){let r;const o=()=>{const t=document.createElement("template");return t.innerHTML=e,t.content.firstChild},i=t?()=>f((()=>document.importNode(r||(r=o()),!0))):()=>(r||(r=o())).cloneNode(!0);return i.cloneNode=i,i}function I(e,t=window.document){const n=t[_]||(t[_]=new Set);for(let r=0,o=e.length;r<o;r++){const o=e[r];n.has(o)||(n.add(o),t.addEventListener(o,M))}}function N(e,t,n){null==n?e.removeAttribute(t):e.setAttribute(t,n)}function F(e,t,n,r){Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n}function $(e,t,n){if(!t)return n?N(e,"style"):t;const r=e.style;if("string"==typeof t)return r.cssText=t;let o,i;for(i in"string"==typeof n&&(r.cssText=n=void 0),n||(n={}),t||(t={}),n)null==t[i]&&r.removeProperty(i),delete n[i];for(i in t)o=t[i],o!==n[i]&&(r.setProperty(i,o),n[i]=o);return n}function L(e,t,n,r){if(void 0===n||r||(r=[]),"function"!=typeof t)return U(e,t,r,n);p((r=>U(e,t(),r,n)),r)}function M(e){let t=e.target;const n=`$$${e.type}`,r=e.target,o=e.currentTarget,i=t=>Object.defineProperty(e,"target",{configurable:!0,value:t}),s=()=>{const r=t[n];if(r&&!t.disabled){const o=t[`${n}Data`];if(void 0!==o?r.call(t,o,e):r.call(t,e),e.cancelBubble)return}return t.host&&"string"!=typeof t.host&&!t.host._$host&&t.contains(e.target)&&i(t.host),!0},a=()=>{for(;s()&&(t=t._$host||t.parentNode||t.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get:()=>t||document}),e.composedPath){const n=e.composedPath();i(n[0]);for(let e=0;e<n.length-2&&(t=n[e],s());e++){if(t._$host){t=t._$host,a();break}if(t.parentNode===o)break}}else a();i(r)}function U(e,t,n,r,o){for(;"function"==typeof n;)n=n();if(t===n)return n;const i=typeof t,s=void 0!==r;if(e=s&&n[0]&&n[0].parentNode||e,"string"===i||"number"===i){if("number"===i&&(t=t.toString())===n)return n;if(s){let o=n[0];o&&3===o.nodeType?o.data!==t&&(o.data=t):o=document.createTextNode(t),n=B(e,n,r,o)}else n=""!==n&&"string"==typeof n?e.firstChild.data=t:e.textContent=t}else if(null==t||"boolean"===i)n=B(e,n,r);else{if("function"===i)return p((()=>{let o=t();for(;"function"==typeof o;)o=o();n=U(e,o,n,r)})),()=>n;if(Array.isArray(t)){const i=[],a=n&&Array.isArray(n);if(G(i,t,n,o))return p((()=>n=U(e,i,n,r,!0))),()=>n;if(0===i.length){if(n=B(e,n,r),s)return n}else a?0===n.length?H(e,i,r):function(e,t,n){let r=n.length,o=t.length,i=r,s=0,a=0,l=t[o-1].nextSibling,c=null;for(;s<o||a<i;)if(t[s]!==n[a]){for(;t[o-1]===n[i-1];)o--,i--;if(o===s){const t=i<r?a?n[a-1].nextSibling:n[i-a]:l;for(;a<i;)e.insertBefore(n[a++],t)}else if(i===a)for(;s<o;)c&&c.has(t[s])||t[s].remove(),s++;else if(t[s]===n[i-1]&&n[a]===t[o-1]){const r=t[--o].nextSibling;e.insertBefore(n[a++],t[s++].nextSibling),e.insertBefore(n[--i],r),t[o]=n[i]}else{if(!c){c=new Map;let e=a;for(;e<i;)c.set(n[e],e++)}const r=c.get(t[s]);if(null!=r)if(a<r&&r<i){let l,g=s,u=1;for(;++g<o&&g<i&&null!=(l=c.get(t[g]))&&l===r+u;)u++;if(u>r-a){const o=t[s];for(;a<r;)e.insertBefore(n[a++],o)}else e.replaceChild(n[a++],t[s++])}else s++;else t[s++].remove()}}else s++,a++}(e,n,i):(n&&B(e),H(e,i));n=i}else if(t.nodeType){if(Array.isArray(n)){if(s)return n=B(e,n,r,t);B(e,n,null,t)}else null!=n&&""!==n&&e.firstChild?e.replaceChild(t,e.firstChild):e.appendChild(t);n=t}}return n}function G(e,t,n,r){let o=!1;for(let i=0,s=t.length;i<s;i++){let s,a=t[i],l=n&&n[e.length];if(null==a||!0===a||!1===a);else if("object"==(s=typeof a)&&a.nodeType)e.push(a);else if(Array.isArray(a))o=G(e,a,l)||o;else if("function"===s)if(r){for(;"function"==typeof a;)a=a();o=G(e,Array.isArray(a)?a:[a],Array.isArray(l)?l:[l])||o}else e.push(a),o=!0;else{const t=String(a);l&&3===l.nodeType&&l.data===t?e.push(l):e.push(document.createTextNode(t))}}return o}function H(e,t,n=null){for(let r=0,o=t.length;r<o;r++)e.insertBefore(t[r],n)}function B(e,t,n,r){if(void 0===n)return e.textContent="";const o=r||document.createTextNode("");if(t.length){let r=!1;for(let i=t.length-1;i>=0;i--){const s=t[i];if(o!==s){const t=s.parentNode===e;r||i?t&&s.remove():t?e.replaceChild(o,s):e.insertBefore(o,n)}else r=!0}}else e.insertBefore(o,n);return[o]}const j=3,K=e=>1e3*e;async function W(e,t={}){const{maxAttempts:n=j,delayFn:r=K}=t;let o=null;for(let t=1;t<=n;t++)try{return await e()}catch(e){o=e,t<n&&await new Promise((e=>setTimeout(e,r(t))))}throw o||new Error("Operation failed after multiple attempts")}const V=chrome;async function Y(e,t){return new Promise(((n,r)=>{try{const o=t=>{if(chrome.runtime.lastError)return r({error:chrome.runtime.lastError,message:e});n(t)};t?.tabId||V.runtime.sendMessage(e,o)}catch(e){r(e)}}))}async function z(e,t,n){return W((()=>Y(e,t)),{maxAttempts:j,delayFn:K})}const q={display:"block",position:"fixed",top:"0%",left:"100%",width:"500px",height:"510px","margin-left":"-560px","margin-top":"50px",padding:"2px 5px","background-color":"white",border:"1px solid black","border-radius":"10px","box-shadow":"0 2px 10px rgba(0, 0, 0, 0.1)","z-index":"2147483647","font-family":"Arial","line-height":"1","vertical-align":"baseline","box-sizing":"border-box",color:"rgb(34, 34, 34)","@media (max-width: 600px), (max-height: 480px)":{display:"none !important"}},X={height:"100%","overflow-x":"hidden","overlfow-y":"auto",position:"relative",padding:"0px 15px"},Z={},J={display:"flex","align-items":"center","margin-bottom":"10px"},Q={flex:"1","font-size":"24px","font-weight":"700","margin-top":"20px","margin-bottom":"0px"},ee={background:"none",border:"none",padding:"4px 8px",color:"#666464","font-size":"38px",cursor:"pointer","line-height":"1"},te={"font-size":"18px","font-weight":"400","margin-top":"20px","margin-bottom":"0px"},ne={display:"flex",gap:"10px",width:"100%","margin-top":"20px","margin-bottom":"20px","flex-wrap":"wrap","justify-content":"space-between"},re={width:"28%",display:"flex","flex-direction":"column","align-items":"center",background:"none",border:"1px solid #ccc","border-radius":"5px",padding:"5px",gap:"5px","text-align":"center","font-size":"14px",cursor:"pointer",transition:"background-color 0.2s ease"},oe={"max-width":"120px","max-height":"70px","margin-bottom":"5px","object-fit":"contain"},ie={"background-color":"#FFD812",cursor:"pointer","border-radius":"8px",padding:"8px",color:"white","min-width":"100px",border:"0","font-weight":"600",width:"100%"},se={display:"flex","flex-direction":"column",gap:"10px",width:"100%","color-scheme":"light"},ae={display:"flex","align-items":"center",gap:"5px",border:"1px solid #ddd",padding:"15px","border-radius":"5px","font-weight":"600",cursor:"pointer","margin-bottom":"8px"},le={background:"none",border:"none",color:"blue","text-decoration":"underline",padding:"0",cursor:"pointer","margin-bottom":"15px"},ce={display:"flex","justify-content":"space-between",margin:"30px 0px 10px 0px","font-size":"14px"},ge={color:"#666464","text-decoration":"underline"},ue={color:"rgb(102, 100, 100)","text-decoration":"underline",margin:"0",cursor:"pointer"},de={width:"100%","background-color":"#f2f2f2",border:"1px solid black","border-radius":"10px","border-top":"1px solid #bbb7b7","margin-top":"10px","margin-bottom":"20px","box-sizing":"border-box"},pe={padding:"0 5px 0 10px",width:"100%","font-size":"12px","box-sizing":"border-box"},me={display:"grid","grid-template-columns":"4fr 1fr","padding-right":"15px","padding-bottom":"5px"},he={color:"#000","margin-bottom":"4px"},fe={"font-size":"14px",color:"#555","text-align":"right"},Ae=(e,t)=>{let n=parseFloat(t);return"FLAT"===e&&(n*=.75),((e,t)=>{let n=parseFloat(t);return n<1&&(n=1),n=Math.floor(n),"PERCENTAGE"===e?`${n}%`:`$${n}`})(e,n.toString())};var be=R("<span>");function xe(e){const t=(n=e.title,r=e.activeDomain,n.replace("{0}",Ae(r.Merchant.MaxRate?.Kind,r.Merchant.MaxRate?.Amount??"0")));var n,r,o;return(o=be()).innerHTML=t,o}var ye=R("<div>"),ve=R("<div><div class=gf-offer-details><p>Select a charity to activate a donation during your online shopping session.</p><p> <b>Eligible Transaction:</b> A purchase made immediately after selecting a charity.</p><p><b>Donation rates:</b> <!> for each eligible transaction. The following donation rates and exclusions apply:</p><p><b>Donation amounts:</b> Donation amount is calculated based upon the applicable rates and exclusions, which may change from time to time. Amounts may be adjusted or canceled due to returned items, suspected fraud, or other factors described within the terms and conditions.</p><p><b>Donation timing:</b> On average, donation payouts occur 60-120 days after your completed transaction, but some donations may take 180 days or longer. We provide a donation to the charity you had selected at the time of purchase, in monthly batches, after any holdback periods due to applicable return or cancellation policies have passed.</p><p>See a summary of <a target=_blank rel=noreferrer>terms and conditions</a>."),we=R("<div class=gf-offer-details-rate-item><div></div><div>");const Ce=e=>{return t=ve(),o=(r=(n=t.firstChild).firstChild.nextSibling.nextSibling).firstChild.nextSibling.nextSibling,i=r.nextSibling,s=i.nextSibling.nextSibling.firstChild.nextSibling,L(r,(()=>e.parsedMaxRate?`Up to ${e.parsedMaxRate}`:"Earn"),o),L(n,O(D,{get when(){return!!e.merchantRateDetail?.length},get children(){var t=ye();return L(t,(()=>e.merchantRateDetail?.map((e=>{return t=we(),n=t.firstChild,r=n.nextSibling,L(n,(()=>e.Name||"")),L(r,(()=>((e,t=1,n=1)=>{const r=e.BoostedOffer??null;let o=parseFloat(e?.Amount??"");if(r?.EndDate&&new Date(r.EndDate)<new Date&&(o=parseFloat(r.OriginalMaxRate)),Number.isNaN(o))return"";const i=o*t;return"PERCENTAGE"===e?.Kind?`${i.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:n})}%`:"FLAT"===e?.Kind?i.toLocaleString("en-US",{style:"currency",currency:e.Currency}):""})(e))),p((e=>{var o=me,i=he,s=fe;return e.e=$(t,o,e.e),e.t=$(n,i,e.t),e.a=$(r,s,e.a),e}),{e:void 0,t:void 0,a:void 0}),t;var t,n,r})))),t}}),i),p((r=>{var o=de,i=pe,a=ge,l=e.termsUrl;return r.e=$(t,o,r.e),r.t=$(n,i,r.t),r.a=$(s,a,r.a),l!==r.o&&N(s,"href",r.o=l),r}),{e:void 0,t:void 0,a:void 0,o:void 0}),t;var t,n,r,o,i,s};var ke=R("<button class=give-freely-close-button aria-label=Close>×"),Pe=R('<div><div><div><span></span></div></div><hr><div></div><div><div><div><br><span></span></div><button aria-label="Don\'t show again"></button></div></div><div><p>Offer Details</p><a class=give-freely-footer-link target=_blank rel="noopener noreferrer">Why am I seeing this?'),Se=R("<div><div><img><span></span></div><button>");function Ee(e){const[t,n]=d(!1);return m((()=>{t()&&e.mainContainerRef&&e.mainContainerRef.scroll({top:e.mainContainerRef.scrollHeight,behavior:"smooth"})})),[(r=Pe(),o=r.firstChild,i=o.firstChild,s=i.firstChild,a=o.nextSibling.nextSibling,l=a.nextSibling,c=l.firstChild,g=c.firstChild,u=g.firstChild.nextSibling,f=g.nextSibling,A=l.nextSibling,b=A.firstChild,x=b.nextSibling,L(o,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupMainCloseButtonVisible},get children(){var t=ke();return F(t,"click",e.onClose),p((e=>$(t,ee,e))),t}}),null),L(a,O(xe,{get title(){return e.subtitle},get activeDomain(){return e.activeDomain}})),L(l,(()=>e.checkoutPopupConf.checkoutPopupCharities.map((t=>{return r=(n=Se()).firstChild,i=(o=r.firstChild).nextSibling,s=r.nextSibling,n.$$click=()=>e.onCharitySelect(t),r.style.setProperty("height","100px"),r.style.setProperty("text-align","center"),L(i,(()=>t.title)),L(s,(()=>e.checkoutPopupConf.checkoutPopupCharitySelectString||"Select")),p((r=>{var i=re,a=t.logo,l=oe,c=t.title,g={...ie,"background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812"},u=`Select charity: ${t.title}`;return r.e=$(n,i,r.e),a!==r.t&&N(o,"src",r.t=a),r.a=$(o,l,r.a),c!==r.o&&N(o,"alt",r.o=c),r.i=$(s,g,r.i),u!==r.n&&N(s,"aria-label",r.n=u),r}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),n;var n,r,o,i,s}))),c),F(c,"click",e.onSuppress),g.style.setProperty("height","100px"),g.style.setProperty("text-align","center"),L(f,(()=>e.checkoutPopupConf.checkoutPopupCharitySelectString||"Select")),b.$$click=()=>{e.onOfferDetailsClick(!t()),n(!t())},p((t=>{var n=Z,g=J,d=Q,p=e.checkoutPopupConf.checkoutPopupMainTitle,m=te,h=ne,y=re,v=e.checkoutPopupConf.checkoutPopupSixthBoxWording,w={...ie,"background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812"},C=ce,k=ue,P=ge,S=e.checkoutPopupConf.externalUrls.giveFreelyWhyAmISeeingThis;return t.e=$(r,n,t.e),t.t=$(o,g,t.t),t.a=$(i,d,t.a),p!==t.o&&(s.innerHTML=t.o=p),t.i=$(a,m,t.i),t.n=$(l,h,t.n),t.s=$(c,y,t.s),v!==t.h&&(u.innerHTML=t.h=v),t.r=$(f,w,t.r),t.d=$(A,C,t.d),t.l=$(b,k,t.l),t.u=$(x,P,t.u),S!==t.c&&N(x,"href",t.c=S),t}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0}),r),O(D,{get when(){return t()},get children(){return O(Ce,{get merchantName(){return e.activeDomain.Merchant.Name},get extensionName(){return e.checkoutPopupConf.displayName},get termsUrl(){return e.checkoutPopupConf.externalUrls.giveFreelyTermsAndConditions},get parsedMaxRate(){return h((()=>!!e.activeDomain.Merchant.MaxRate))()?Ae(e.activeDomain.Merchant.MaxRate.Kind,e.activeDomain.Merchant.MaxRate?.Amount):null},get merchantRateDetail(){return e.merchantRates},onClose:()=>n(!1)})}})];var r,o,i,s,a,l,c,g,u,f,A,b,x}I(["click"]);var Te=R("<button class=give-freely-close-button aria-label=Close>×"),Oe=R("<label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=18250><span>Don't ask me again... ever"),De=R("<div><div><div></div></div><button class=give-freely-back-button aria-label=\"Back to charity selection\">I changed my mind! I'd like to select a charity.</button><hr><div id=give-freely-goodbye-screen-options><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=1><span>Don't ask me again for 1 day</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=7><span>Don't ask me again for 7 days</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=30><span>Don't ask me again for 30 days</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=90><span>Don't ask me again for 90 days</span></label></div><button class=give-freely-submit-button>Submit");function _e(e){const[t,n]=d(0);return r=De(),o=r.firstChild,i=o.firstChild,s=o.nextSibling,a=s.nextSibling.nextSibling,c=(l=a.firstChild).firstChild,u=(g=l.nextSibling).firstChild,h=(m=g.nextSibling).firstChild,A=(f=m.nextSibling).firstChild,b=a.nextSibling,r.style.setProperty("font-size","14px"),L(i,(()=>e.checkoutPopupConf.checkoutPopupSupressTitle)),L(o,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupSupressCloseButtonVisible},get children(){var t=Te();return t.$$click=()=>e.onGoodbye(0),p((e=>$(t,ee,e))),t}}),null),F(s,"click",e.onBack),c.addEventListener("change",(()=>n(1))),u.addEventListener("change",(()=>n(7))),h.addEventListener("change",(()=>n(30))),A.addEventListener("change",(()=>n(90))),L(a,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupNeverSuppressionAllowed},get children(){var e=Oe();return e.firstChild.addEventListener("change",(()=>n(18250))),p((t=>$(e,ae,t))),e}}),null),b.$$click=()=>{const n=t();n&&(e.onGoodbye(n),e.setScreen("main"))},p((t=>{var n=J,r=Q,c=le,u=se,d=ae,p=ae,h=ae,A=ae,x={...ie,"font-weight":"700","margin-top":"10px","margin-bottom":"0px","background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812",width:"100px"};return t.e=$(o,n,t.e),t.t=$(i,r,t.t),t.a=$(s,c,t.a),t.o=$(a,u,t.o),t.i=$(l,d,t.i),t.n=$(g,p,t.n),t.s=$(m,h,t.s),t.h=$(f,A,t.h),t.r=$(b,x,t.r),t}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),r;var r,o,i,s,a,l,c,g,u,m,h,f,A,b}I(["click"]);var Re=R("<div><div><div></div><button class=give-freely-close-button aria-label=Close>×</button></div><hr><div><span>");function Ie(e){return t=Re(),n=t.firstChild,r=n.firstChild,o=r.nextSibling,i=n.nextSibling.nextSibling,s=i.firstChild,t.style.setProperty("font-size","14px"),L(r,(()=>e.failedDonation?"Oops! Something went wrong":e.checkoutPopupConf.checkoutPopupDonationTitle)),F(o,"click",e.onClose),i.style.setProperty("padding","30px"),i.style.setProperty("height","150px"),i.style.setProperty("font-size","14px"),p((t=>{var i=J,a=Q,l=ee,c=e.failedDonation?"Please try again later.":e.checkoutPopupConf.checkoutPopupDonationWording;return t.e=$(n,i,t.e),t.t=$(r,a,t.t),t.a=$(o,l,t.a),c!==t.o&&(s.innerHTML=t.o=c),t}),{e:void 0,t:void 0,a:void 0,o:void 0}),t;var t,n,r,o,i,s}I(["click"]);var Ne,Fe,$e=R("<div><div>");function Le(e){const{logger:t}=e,[n,r]=d("main"),[o,i]=d(),[s,a]=d(!1),l=()=>{t.debug("Close button clicked"),e.onClose()},c=async n=>{t.info("Charity selected",{charity:n,domain:e.activeDomain.Domain}),i(n);const o=await e.onDonate(n,e.activeDomain);a(!o),r("donate")},g=()=>{t.debug("Suppress button clicked"),r("goodbye")},u=()=>{t.debug("Navigating back to main screen"),r("main")},m=n=>{t.info("User chose to hide popup",{days:n}),e.onClose(n)};let h;return x=$e(),y=x.firstChild,"function"==typeof h?(A=h,b=y,f((()=>A(b,undefined)))):h=y,L(y,O(D,{get when(){return"main"===n()},get children(){return O(Ee,{mainContainerRef:h,get checkoutPopupConf(){return e.checkoutPopupConf},get activeDomain(){return e.activeDomain},get merchantRates(){return e.merchantRates},onClose:l,onCharitySelect:c,onSuppress:g,get onOfferDetailsClick(){return e.onOfferDetailsClick},get subtitle(){return e.checkoutPopupConf.checkoutPopupSubTitle}})}}),null),L(y,O(D,{get when(){return"goodbye"===n()},get children(){return O(_e,{get checkoutPopupConf(){return e.checkoutPopupConf},onClose:()=>e.onClose(),onBack:u,onGoodbye:m,setScreen:r})}}),null),L(y,O(D,{get when(){return"donate"===n()},get children(){return O(Ie,{get checkoutPopupConf(){return e.checkoutPopupConf},get selectedCharity(){return o()},onClose:()=>e.onClose(),get failedDonation(){return s()},setScreen:r})}}),null),p((t=>{var n=q,r=e.elementId,o=X;return t.e=$(x,n,t.e),r!==t.t&&N(x,"id",t.t=r),t.a=$(y,o,t.a),t}),{e:void 0,t:void 0,a:void 0}),x;var A,b,x,y}class Me{log({level:e,message:t,timestamp:n,data:r,title:o}){const i="debug"===e?"log":e,s=o?`[${o}]`:"";void 0!==r?console[i](`[${n}] - ${Me.LOGGER_PREFIX} ${s} ${t}`,r):console[i](`[${n}] - ${Me.LOGGER_PREFIX} ${s} ${t}`)}}Me.LOGGER_PREFIX="[GFAdUnit] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED"}(Ne||(Ne={})),function(e){e.adUnitLog="ADUNIT-LOG"}(Fe||(Fe={}));const Ue=["debug","info","warn","error"];class Ge{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new Me],title:e?.title??""}}static getInstance(e){return Ge.instance||(Ge.instance=new Ge(e)),Ge.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&Ue.indexOf(e)>=Ue.indexOf(this.config.minLevel)}createLogMessage(e,t,n){return{level:e,version:"1.1.1",message:t,timestamp:(new Date).toISOString(),data:n,title:this.config.title}}log(e,t,n){if(!this.shouldLog(e))return;const r=this.createLogMessage(e,t,n);this.config.transports.forEach((e=>e.log(r)))}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}function He(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var Be={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",n=e=>{const n={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(n).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class r extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const o=(t,n)=>(...r)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):n.singleCallbackArg||r.length<=1&&!1!==n.singleCallbackArg?t.resolve(r[0]):t.resolve(r)},i=e=>1==e?"argument":"arguments",s=(e,t,n)=>new Proxy(t,{apply:(t,r,o)=>n.call(r,e,...o)});let a=Function.call.bind(Object.prototype.hasOwnProperty);const l=(e,t={},n={})=>{let r=Object.create(null),c={has:(t,n)=>n in e||n in r,get(c,g,u){if(g in r)return r[g];if(!(g in e))return;let d=e[g];if("function"==typeof d)if("function"==typeof t[g])d=s(e,e[g],t[g]);else if(a(n,g)){let t=((e,t)=>function(n,...r){if(r.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${r.length}`);if(r.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${r.length}`);return new Promise(((i,s)=>{if(t.fallbackToNoCallback)try{n[e](...r,o({resolve:i,reject:s},t))}catch(o){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,o),n[e](...r),t.fallbackToNoCallback=!1,t.noCallback=!0,i()}else t.noCallback?(n[e](...r),i()):n[e](...r,o({resolve:i,reject:s},t))}))})(g,n[g]);d=s(e,e[g],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(a(t,g)||a(n,g)))d=l(d,t[g],n[g]);else{if(!a(n,"*"))return Object.defineProperty(r,g,{configurable:!0,enumerable:!0,get:()=>e[g],set(t){e[g]=t}}),d;d=l(d,t[g],n["*"])}return r[g]=d,d},set:(t,n,o,i)=>(n in r?r[n]=o:e[n]=o,!0),defineProperty:(e,t,n)=>Reflect.defineProperty(r,t,n),deleteProperty:(e,t)=>Reflect.deleteProperty(r,t)},g=Object.create(e);return new Proxy(g,c)},c=e=>({addListener(t,n,...r){t.addListener(e.get(n),...r)},hasListener:(t,n)=>t.hasListener(e.get(n)),removeListener(t,n){t.removeListener(e.get(n))}}),g=new r((e=>"function"!=typeof e?e:function(t){const n=l(t,{},{getContent:{minArgs:0,maxArgs:0}});e(n)})),u=new r((e=>"function"!=typeof e?e:function(t,n,r){let o,i,s=!1,a=new Promise((e=>{o=function(t){s=!0,e(t)}}));try{i=e(t,n,o)}catch(e){i=Promise.reject(e)}const l=!0!==i&&((c=i)&&"object"==typeof c&&"function"==typeof c.then);var c;if(!0!==i&&!l&&!s)return!1;return(l?i:a).then((e=>{r(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",r({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:n,resolve:r},o)=>{e.runtime.lastError?e.runtime.lastError.message===t?r():n(new Error(e.runtime.lastError.message)):o&&o.__mozWebExtensionPolyfillReject__?n(new Error(o.message)):r(o)},p=(e,t,n,...r)=>{if(r.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${r.length}`);if(r.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${r.length}`);return new Promise(((e,t)=>{const o=d.bind(null,{resolve:e,reject:t});r.push(o),n.sendMessage(...r)}))},m={devtools:{network:{onRequestFinished:c(g)}},runtime:{onMessage:c(u),onMessageExternal:c(u),sendMessage:p.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:p.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},h={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return n.privacy={network:{"*":h},services:{"*":h},websites:{"*":h}},l(e,m,n)};e.exports=n(chrome)}}(Be);var je=He(Be.exports);const Ke="GIVE_FREELY_",We={async get(e){const t=`${Ke}${e}`;return(await je.storage.local.get(t))[t]||null},async set(e,t){const n=`${Ke}${e}`;await je.storage.local.set({[n]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${Ke}${e}`)):`${Ke}${e}`;await je.storage.local.remove(t)}};class Ve{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0,this.CONFIG_REFRESH_INTERVAL=3e5,this.PARTNER_CONFIG_STORAGE_KEY="gf_partner_config",this.GLOBAL_CONFIG_STORAGE_KEY="gf_global_config"}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchAndUpdatePartnerConfig(){const e=await W((async()=>{const e=await fetch(`https://cdn.givefreely.com/adunit/config/${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await We.set(this.PARTNER_CONFIG_STORAGE_KEY,t),e}async fetchAndUpdateGlobalConfig(){const e=await W((async()=>{const e=await fetch("https://cdn.givefreely.com/adunit/config/global.json",{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await We.set(this.GLOBAL_CONFIG_STORAGE_KEY,t),e}async getConfig(){const e=Date.now(),t=await We.get(this.PARTNER_CONFIG_STORAGE_KEY),n=await We.get(this.GLOBAL_CONFIG_STORAGE_KEY);if(this.partnerConfig=t?.config||null,this.globalConfig=n?.config||null,this.lastConfigRefresh=Math.max(t?.lastRefresh||0,n?.lastRefresh||0),!this.partnerConfig||!this.globalConfig||e-this.lastConfigRefresh>this.CONFIG_REFRESH_INTERVAL)try{const[t,n]=await Promise.all([this.fetchAndUpdatePartnerConfig(),this.fetchAndUpdateGlobalConfig()]);this.partnerConfig=t,this.globalConfig=n,this.lastConfigRefresh=e}catch(e){if(!this.partnerConfig||!this.globalConfig)throw e;console.warn("Failed to refresh configs, using existing configs:",e)}const r=this.mergeConfigs(this.globalConfig,this.partnerConfig);return((e,t,n)=>{const r=[...t.merchantExclusions??[],...n.merchantExclusions??[]];e.merchantExclusions=r})(r,this.globalConfig,this.partnerConfig),r}async clearCache(){await Promise.all([We.remove(this.PARTNER_CONFIG_STORAGE_KEY),We.remove(this.GLOBAL_CONFIG_STORAGE_KEY)]),this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0}mergeConfigs(e,t){if(!t)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e,i=t;"object"==typeof i[r]&&null!==i[r]&&"object"==typeof o[r]?n[r]=this.mergeConfigs(o[r],i[r]):n[r]=void 0!==i[r]?i[r]:o[r]}return n}getStoredState(e){return e?{config:e.config,lastRefresh:e.lastRefresh}:{config:null,lastRefresh:0}}}const Ye="TRACK_EVENT",ze="GF_HIDE_POPUP",qe="GF_GET_POPUP_CONFIG",Xe="GF_IS_ACTIVE_DOMAIN",Ze="GF_SHOULD_STAND_DOWN",Je="GF_ACTIVATE_OFFER",Qe="GF_STORE_SHOPIFY_SHOP_ID",et="GF_GET_DOMAIN_BY_SHOP_ID";class tt{constructor(t,n,r=60){this._config=null,this.track=async(t,n,r)=>{null===this._config&&(this._config=await new Ve(this._partnerApiKey).getConfig());const o={partner:`adUnit_${this._partnerApiKey}`,eventType:t,eventData:{userId:this._userService?.user?.id,libVersion:String(e)??"",wfDeviceId:n,...r}};try{const e=JSON.stringify(o);return await this.shouldBroadcastEvent(e)?(await fetch(this._config.eventsUrl,{headers:{"Content-Type":"application/json"},method:"POST",body:e,cache:"no-store"}),await this.pushEventToHistory(e),!0):(this.log("This event has already been broadcasted during the past hour",o),!1)}catch(e){return this.log("Something unexpected happened when dispatching a gf event",e,o),!1}},this.log=(...e)=>{"debug"===this._config?.backgroundMinLogLevel&&console.log("analytics:",...e)},this.getEventsHistory=async()=>{const{GF_AD_EVENT_HISTORY:e}=await V.storage.local.get({GF_AD_EVENT_HISTORY:""}),t=function(e){const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()}(-this._debounceWindowInMinutes);let n=(e||[]).filter((e=>e.createdAt>t));return await V.storage.local.set({GF_AD_EVENT_HISTORY:n}),n},this.shouldBroadcastEvent=async e=>!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await V.storage.local.set({GF_AD_EVENT_HISTORY:t})},this._partnerApiKey=t,this._userService=n,this._debounceWindowInMinutes=r}}function nt(e){const t=["",".asp",".aspx",".php",".js",".htm",".html"],n=["cart","checkout","shopping-bag","shopping-basket","shopping-cart","basket"].flatMap((e=>t.map((t=>e+t)))).filter((e=>"basket"!==e)),r=["tote-cart","tote.cart"],o=e,i=n.filter((e=>o.includes(e))),s=o.split("/");return!s.some((e=>r.some((t=>e.includes(t)))))&&(s.some((e=>n.some((t=>e.startsWith(t)||e.endsWith(t)))))||"basket"===s[s.length-1].toLowerCase()||i.length>1||1===i.length&&o.includes("shopping"))}function rt(e,t){const n=["book"];return e.split("/").some((e=>n.some((t=>e.startsWith(t)||e.endsWith(t)))))&&null!=t.evaluate("//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6][contains(., 'Your Reservation') or contains(., 'Your reservation')]",t,null,XPathResult.ANY_TYPE,null)?.iterateNext()}async function ot(e){try{const t=await Y({type:et,payload:{shopId:e}});return t.payload.found&&t.payload.domain?t.payload.domain:null}catch(e){return null}}function it(){try{const e=Array.from(document.querySelectorAll("script"));for(const t of e){if(t.dataset?.shopId?.startsWith("gid")){const e=parseInt(t.dataset.shopId.replace("gid://shopify/Shop/",""));if(!isNaN(e)&&e>0)return e}const e=t.textContent||"";if(e.includes("ShopifyAnalytics")&&e.includes("shopId")){const t=e.match(/shopId['"]*:\s*['"]*(\d+)['"]*[,}]/);if(t&&t[1]){const e=parseInt(t[1]);if(!isNaN(e)&&e>0)return e}}}const t=document.querySelector("[data-shop-id]");if(t instanceof HTMLElement){const e=t.dataset.shopId;if(e){const t=parseInt(e);if(!isNaN(t)&&t>0)return t}}const n=window?.ShopifyAnalytics?.lib?.trekkie?.defaultAttributes?.shopId;return n&&parseInt(n)||0}catch(e){return console.error("Error accessing ShopifyAnalytics:",e),0}}function st(){try{if(!window.location.href.startsWith("https://shop.app"))return 0;const e=document?.head?.querySelector('meta[name="store"][content]');if(!e)return 0;try{const t=JSON.parse(e.content);return t?.id||0}catch(e){return 0}}catch(e){return 0}}tt.trackEvent=async(e,t)=>{await Y({type:Ye,payload:{eventType:e,eventData:t}})};const at=Ge.getInstance();function lt(e,t,n){try{const r=function(e){try{const t=e.split(".");return t.length>=2?t.slice(-2).join("."):e}catch(e){return at.error("Error extracting domain",e),""}}(n);at.debug("Checking merchant regex rules",{currentDomain:r,currentUrl:t});const o=e.merchantPopupRules.filter((e=>r.includes(e.domain)));if(0===o.length)return at.debug("No matching merchant rules found for domain",{currentDomain:r}),!1;for(const e of o)for(const n of e.rules)try{if(new RegExp(n.rule).test(t))return at.debug("Merchant regex rule matched",{merchant:e.name,rule:n.rule,currentUrl:t}),!0}catch(t){at.error("Invalid regex in merchant rule",{merchant:e.name,rule:n.rule,error:t})}return at.debug("No matching regex rules found",{currentUrl:t}),!1}catch(e){return at.error("Error in merchantRegexRule",e),!1}}var ct=R("<div class=gf-app>");function gt(){const t=Ge.getInstance(),[n,r]=d(null),[o,i]=d(void 0),[s,a]=d(!1),[l,c]=d([]);var g;g=async()=>{t.info("Mounting GfApp component");try{const n=await(async()=>{const e=await Y({type:qe,payload:{}});if(!e.payload.config)throw new Error("No checkout popup config found");return e.payload.config})();if(!n)return void t.error("No checkout popup config found");r(n),t.configure({enabled:!0,title:"Content - GfAdUnit",minLevel:n.checkoutPopupMinLogLevel??"error"});const s=String(e);if(n.minVersion&&((e,t)=>{if(e===t)return!1;const n=e.split(".").map(parseInt),r=t.split(".").map(parseInt);for(let e=0;e<n.length;e++){if(n[e]<r[e])return!0;if(n[e]>r[e])return!1}return!1})(s,n.minVersion))return void t.debug(`Current version: ${s}. Minimum version ${n.minVersion} not met`);if(!1===n.checkoutPopupMasterSwitch)return void t.debug("Checkout popup master switch is disabled");const{domain:l,rates:g}=await(async e=>{const{hostname:t}=window.location;e.debug("Checking if domain is active",{hostname:t});const n=await Y({type:Xe,payload:{hostname:t}});return n.payload.isActive?(e.debug("Active domain",{domain:n.payload.domain}),e.debug("Merchant rates",{rates:n.payload.rates}),e.info("Domain and rates ({})ed successfully."),{isActive:!0,domain:n.payload.domain,rates:n.payload.rates}):{isActive:!1,domain:void 0,rates:[]}})(t);if(c(g),i(l),l)await function(e){const t=it()||st();return t>0&&function(e,t){if(e&&!(e<=0))try{Y({type:Qe,payload:{shopId:e,domain:t}}).catch((e=>{console.error("Error sending shop ID to background:",e)}))}catch(e){console.error("Error sending Shopify shop ID:",e)}}(t,e),t}(l);else{if("shop.app"!==window.location.hostname&&!window.location.hostname.endsWith(".shop.app"))return void a(!1);const e=window.location.pathname.split("/")[2];if(!e)return t.error("Shop ID not found"),void a(!1);const n=await ot(parseInt(e));if(!n)return t.error("Shop domain not found"),void a(!1);t.debug("Shop domain found",{shopDomain:n}),i(n)}const u=await(async e=>{const t=await We.get("popup_hide");if(!t)return e.debug("No expiry found in storage"),!1;const{popupHide:n}=t,r=!!n&&Date.now()<n;return e.debug("Is AdUnit Muted?",{isMuted:r,expiry:n}),r})(t);if(u)return;if(!o())return void a(!1);const d=await(async(e,t)=>{const{Domain:n}=t,r=window.location.href,{payload:o}=await Y({type:Ze,payload:{activeDomain:n,url:r}});return!!o.result&&(e.info("Stand Down detected"),!0)})(t,o());if(d)return void a(!1);const p=setInterval((async()=>{t.debug("Checking checkout rules");const e=await(async e=>{const t=Ge.getInstance();t.configure({enabled:!0,title:"Content - checkoutRulesTest"});const n=new URL(globalThis.location.href),r=n.href,o=n.hostname;t.debug("Checking if popup should be shown",{currentUrl:r});const i=await async function(){const e=it()||st();return!("shop.app"!==window.location.hostname&&!window.location.hostname.endsWith(".shop.app")||!(e>0)||!await ot(e))}(),s=nt(n.pathname.toLowerCase())||rt(r,document)||lt(e,r,o)||i;return t.debug("Popup show decision based on rules",{shouldShow:s,matchesCartRule:nt(n.pathname.toLowerCase()),matchesBookingRule:rt(r,document),matchesShopPayRule:i,matchesMerchantRegexRule:lt(e,r,o)}),s})(n);a(e),e&&(t.debug("Should show popup based on checkout rules",{shouldShowResult:e}),tt.trackEvent(Ne.checkoutPopupShown,{url:globalThis.window.location.href}),clearInterval(p))}),2e3)}catch(e){a(!1),t.error("An error occurred in GfApp",{error:e})}},m((()=>f(g)));const u=async(e,n)=>{t.info("Processing donation",{charity:e,domain:n.Domain});const r=await(async(e,t,n,r)=>{e.debug("Activating offer",{activeDomain:t,selectedCharity:r});const o=await z({type:Je,payload:{activeDomain:t,originalUrl:n,selectedCharity:r}});return e.debug("Activate offer response",{response:o}),o})(t,n,window.location.href,{ein:e.ein,thirdPartyId:e.tpi});return t.debug("Activate offer response",{activationResponse:r}),tt.trackEvent(r.payload.response?Ne.checkoutPopupDonation:Ne.checkoutPopupFailedActivation,{activeDomain:n.Domain,url:globalThis.window.location.href,charity:{ein:e.ein,tpi:e.tpi},rate:n.Merchant.MaxRate}),r.payload.response},p=async e=>{a(await(async(e,t)=>{try{e.info("Hiding ad",{days:t});const n=await z({type:ze,payload:{days:t??0}});return t&&t>0&&tt.trackEvent(Ne.checkoutPopupSupressed,{url:globalThis.window.location.href,days:t}),e.info("Hiding ad response",{hide_response:n}),n.payload.ack?(e.debug("Ad hidden successfully"),!1):(e.warn("Failed to hide ad"),!0)}catch(e){return!1}})(t,e))},A=async e=>{tt.trackEvent(Ne.checkoutPopupOfferDetailsClicked,{action:e?"opened":"closed"})};return L(x=ct(),(b=h((()=>!(!o()||!s()))),()=>b()&&O(Le,{get checkoutPopupConf(){return n()},elementId:"give-freely-checkout-popup",get activeDomain(){return o()},get merchantRates(){return l()},onClose:p,onDonate:u,onOfferDetailsClick:A,logger:t}))),x;var b,x}async function ut(){const e=document.createElement("div");e.id="give-freely-root",document.body.appendChild(e);const t=e.attachShadow({mode:"open"}),n=document.createElement("div"),r=document.createElement("style");r.textContent='\n :host {\n all: initial;\n }\n\n .gf-scroll-remove::-webkit-scrollbar {\n border-radius-bottom-right: 15px;\n }\n\n button {\n cursor: pointer;\n transition: transform 0.1s ease;\n }\n\n button:active {\n transform: scale(0.98);\n }\n\n .give-freely-close-button:hover {\n opacity: 0.7;\n }\n\n input[type="radio"] {\n margin-right: 8px;\n }\n\n hr {\n border: none;\n border-top: 1px solid #e5e5e5;\n margin: 1em 0;\n }\n\n @media (max-width: 600px), (max-height: 480px) {\n #give-freely-checkout-popup {\n display: none !important;\n }\n }\n',t.appendChild(r),t.appendChild(n),function(e,t,n,r={}){let o;(function(e,t){const n=l,r=s,o=0===e.length,a=void 0===t?r:t,c=o?i:{owned:null,cleanups:null,context:a?a.context:null,owner:a},g=o?e:()=>e((()=>f((()=>E(c)))));s=c,l=null;try{return w(g,!0)}finally{l=n,s=r}})((r=>{o=r,t===document?e():L(t,e(),t.firstChild?null:void 0,n)}),r.owner)}((()=>O(gt,{})),n)}export{V as browser,ut as initializeAdUnit};
1
+ const e="1.1.0",t={equals:(e,t)=>e===t};let n=C;const r=1,o=2,i={owned:null,cleanups:null,context:null,owner:null};var s=null;let a=null,l=null,c=null,g=null,u=0;function d(e,n){const r={value:e,observers:null,observerSlots:null,comparator:(n=n?Object.assign({},t,n):t).equals||void 0};return[A.bind(r),e=>("function"==typeof e&&(e=e(r.value)),b(r,e))]}function p(e,t,n){x(y(e,t,!1,r))}function m(e,t,o){n=k;const i=y(e,t,!1,r);i.user=!0,g?g.push(i):x(i)}function h(e,n,r){r=r?Object.assign({},t,r):t;const o=y(e,n,!0,0);return o.observers=null,o.observerSlots=null,o.comparator=r.equals||void 0,x(o),A.bind(o)}function f(e){if(null===l)return e();const t=l;l=null;try{return e()}finally{l=t}}function A(){if(this.sources&&this.state)if(this.state===r)x(this);else{const e=c;c=null,w((()=>P(this)),!1),c=e}if(l){const e=this.observers?this.observers.length:0;l.sources?(l.sources.push(this),l.sourceSlots.push(e)):(l.sources=[this],l.sourceSlots=[e]),this.observers?(this.observers.push(l),this.observerSlots.push(l.sources.length-1)):(this.observers=[l],this.observerSlots=[l.sources.length-1])}return this.value}function b(e,t,n){let o=e.value;return e.comparator&&e.comparator(o,t)||(e.value=t,e.observers&&e.observers.length&&w((()=>{for(let t=0;t<e.observers.length;t+=1){const n=e.observers[t],o=a&&a.running;o&&a.disposed.has(n),(o?n.tState:n.state)||(n.pure?c.push(n):g.push(n),n.observers&&S(n)),o||(n.state=r)}if(c.length>1e6)throw c=[],new Error}),!1)),t}function x(e){if(!e.fn)return;E(e);const t=u;!function(e,t,n){let o;const i=s,a=l;l=s=e;try{o=e.fn(t)}catch(t){return e.pure&&(e.state=r,e.owned&&e.owned.forEach(E),e.owned=null),e.updatedAt=n+1,T(t)}finally{l=a,s=i}(!e.updatedAt||e.updatedAt<=n)&&(null!=e.updatedAt&&"observers"in e?b(e,o):e.value=o,e.updatedAt=n)}(e,e.value,t)}function y(e,t,n,o=r,a){const l={fn:e,state:o,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:s,context:s?s.context:null,pure:n};return null===s||s!==i&&(s.owned?s.owned.push(l):s.owned=[l]),l}function v(e){if(0===e.state)return;if(e.state===o)return P(e);if(e.suspense&&f(e.suspense.inFallback))return e.suspense.effects.push(e);const t=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<u);)e.state&&t.push(e);for(let n=t.length-1;n>=0;n--)if((e=t[n]).state===r)x(e);else if(e.state===o){const n=c;c=null,w((()=>P(e,t[0])),!1),c=n}}function w(e,t){if(c)return e();let r=!1;t||(c=[]),g?r=!0:g=[],u++;try{const t=e();return function(e){if(c&&(C(c),c=null),e)return;const t=g;g=null,t.length&&w((()=>n(t)),!1)}(r),t}catch(e){r||(g=null),c=null,T(e)}}function C(e){for(let t=0;t<e.length;t++)v(e[t])}function k(e){let t,n=0;for(t=0;t<e.length;t++){const r=e[t];r.user?e[n++]=r:v(r)}for(t=0;t<n;t++)v(e[t])}function P(e,t){e.state=0;for(let n=0;n<e.sources.length;n+=1){const i=e.sources[n];if(i.sources){const e=i.state;e===r?i!==t&&(!i.updatedAt||i.updatedAt<u)&&v(i):e===o&&P(i,t)}}}function S(e){for(let t=0;t<e.observers.length;t+=1){const n=e.observers[t];n.state||(n.state=o,n.pure?c.push(n):g.push(n),n.observers&&S(n))}}function E(e){let t;if(e.sources)for(;e.sources.length;){const t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){const e=r.pop(),o=t.observerSlots.pop();n<r.length&&(e.sourceSlots[o]=n,r[n]=e,t.observerSlots[n]=o)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)E(e.tOwned[t]);delete e.tOwned}if(e.owned){for(t=e.owned.length-1;t>=0;t--)E(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}e.state=0}function T(e,t=s){const n=function(e){return e instanceof Error?e:new Error("string"==typeof e?e:"Unknown error",{cause:e})}(e);throw n}function O(e,t){return f((()=>e(t||{})))}function D(e){const t=e.keyed,n=h((()=>e.when),void 0,void 0),r=t?n:h(n,void 0,{equals:(e,t)=>!e==!t});return h((()=>{const o=r();if(o){const i=e.children;return"function"==typeof i&&i.length>0?f((()=>i(t?o:()=>{if(!f(r))throw"Stale read from <Show>.";return n()}))):i}return e.fallback}),void 0,void 0)}const _="_$DX_DELEGATE";function R(e,t,n,r){let o;const i=()=>{const t=document.createElement("template");return t.innerHTML=e,t.content.firstChild},s=t?()=>f((()=>document.importNode(o||(o=i()),!0))):()=>(o||(o=i())).cloneNode(!0);return s.cloneNode=s,s}function I(e,t=window.document){const n=t[_]||(t[_]=new Set);for(let r=0,o=e.length;r<o;r++){const o=e[r];n.has(o)||(n.add(o),t.addEventListener(o,M))}}function N(e,t,n){null==n?e.removeAttribute(t):e.setAttribute(t,n)}function F(e,t,n,r){Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n}function $(e,t,n){if(!t)return n?N(e,"style"):t;const r=e.style;if("string"==typeof t)return r.cssText=t;let o,i;for(i in"string"==typeof n&&(r.cssText=n=void 0),n||(n={}),t||(t={}),n)null==t[i]&&r.removeProperty(i),delete n[i];for(i in t)o=t[i],o!==n[i]&&(r.setProperty(i,o),n[i]=o);return n}function L(e,t,n,r){if(void 0===n||r||(r=[]),"function"!=typeof t)return U(e,t,r,n);p((r=>U(e,t(),r,n)),r)}function M(e){let t=e.target;const n=`$$${e.type}`,r=e.target,o=e.currentTarget,i=t=>Object.defineProperty(e,"target",{configurable:!0,value:t}),s=()=>{const r=t[n];if(r&&!t.disabled){const o=t[`${n}Data`];if(void 0!==o?r.call(t,o,e):r.call(t,e),e.cancelBubble)return}return t.host&&"string"!=typeof t.host&&!t.host._$host&&t.contains(e.target)&&i(t.host),!0},a=()=>{for(;s()&&(t=t._$host||t.parentNode||t.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get:()=>t||document}),e.composedPath){const n=e.composedPath();i(n[0]);for(let e=0;e<n.length-2&&(t=n[e],s());e++){if(t._$host){t=t._$host,a();break}if(t.parentNode===o)break}}else a();i(r)}function U(e,t,n,r,o){for(;"function"==typeof n;)n=n();if(t===n)return n;const i=typeof t,s=void 0!==r;if(e=s&&n[0]&&n[0].parentNode||e,"string"===i||"number"===i){if("number"===i&&(t=t.toString())===n)return n;if(s){let o=n[0];o&&3===o.nodeType?o.data!==t&&(o.data=t):o=document.createTextNode(t),n=B(e,n,r,o)}else n=""!==n&&"string"==typeof n?e.firstChild.data=t:e.textContent=t}else if(null==t||"boolean"===i)n=B(e,n,r);else{if("function"===i)return p((()=>{let o=t();for(;"function"==typeof o;)o=o();n=U(e,o,n,r)})),()=>n;if(Array.isArray(t)){const i=[],a=n&&Array.isArray(n);if(G(i,t,n,o))return p((()=>n=U(e,i,n,r,!0))),()=>n;if(0===i.length){if(n=B(e,n,r),s)return n}else a?0===n.length?H(e,i,r):function(e,t,n){let r=n.length,o=t.length,i=r,s=0,a=0,l=t[o-1].nextSibling,c=null;for(;s<o||a<i;)if(t[s]!==n[a]){for(;t[o-1]===n[i-1];)o--,i--;if(o===s){const t=i<r?a?n[a-1].nextSibling:n[i-a]:l;for(;a<i;)e.insertBefore(n[a++],t)}else if(i===a)for(;s<o;)c&&c.has(t[s])||t[s].remove(),s++;else if(t[s]===n[i-1]&&n[a]===t[o-1]){const r=t[--o].nextSibling;e.insertBefore(n[a++],t[s++].nextSibling),e.insertBefore(n[--i],r),t[o]=n[i]}else{if(!c){c=new Map;let e=a;for(;e<i;)c.set(n[e],e++)}const r=c.get(t[s]);if(null!=r)if(a<r&&r<i){let l,g=s,u=1;for(;++g<o&&g<i&&null!=(l=c.get(t[g]))&&l===r+u;)u++;if(u>r-a){const o=t[s];for(;a<r;)e.insertBefore(n[a++],o)}else e.replaceChild(n[a++],t[s++])}else s++;else t[s++].remove()}}else s++,a++}(e,n,i):(n&&B(e),H(e,i));n=i}else if(t.nodeType){if(Array.isArray(n)){if(s)return n=B(e,n,r,t);B(e,n,null,t)}else null!=n&&""!==n&&e.firstChild?e.replaceChild(t,e.firstChild):e.appendChild(t);n=t}}return n}function G(e,t,n,r){let o=!1;for(let i=0,s=t.length;i<s;i++){let s,a=t[i],l=n&&n[e.length];if(null==a||!0===a||!1===a);else if("object"==(s=typeof a)&&a.nodeType)e.push(a);else if(Array.isArray(a))o=G(e,a,l)||o;else if("function"===s)if(r){for(;"function"==typeof a;)a=a();o=G(e,Array.isArray(a)?a:[a],Array.isArray(l)?l:[l])||o}else e.push(a),o=!0;else{const t=String(a);l&&3===l.nodeType&&l.data===t?e.push(l):e.push(document.createTextNode(t))}}return o}function H(e,t,n=null){for(let r=0,o=t.length;r<o;r++)e.insertBefore(t[r],n)}function B(e,t,n,r){if(void 0===n)return e.textContent="";const o=r||document.createTextNode("");if(t.length){let r=!1;for(let i=t.length-1;i>=0;i--){const s=t[i];if(o!==s){const t=s.parentNode===e;r||i?t&&s.remove():t?e.replaceChild(o,s):e.insertBefore(o,n)}else r=!0}}else e.insertBefore(o,n);return[o]}const j=3,K=e=>1e3*e;async function W(e,t={}){const{maxAttempts:n=j,delayFn:r=K}=t;let o=null;for(let t=1;t<=n;t++)try{return await e()}catch(e){o=e,t<n&&await new Promise((e=>setTimeout(e,r(t))))}throw o||new Error("Operation failed after multiple attempts")}const V=chrome;async function Y(e,t){return new Promise(((n,r)=>{try{const o=t=>{if(chrome.runtime.lastError)return r({error:chrome.runtime.lastError,message:e});n(t)};t?.tabId||V.runtime.sendMessage(e,o)}catch(e){r(e)}}))}async function z(e,t,n){return W((()=>Y(e,t)),{maxAttempts:j,delayFn:K})}const q={display:"block",position:"fixed",top:"0%",left:"100%",width:"500px",height:"510px","margin-left":"-560px","margin-top":"50px",padding:"2px 5px","background-color":"white",border:"1px solid black","border-radius":"10px","box-shadow":"0 2px 10px rgba(0, 0, 0, 0.1)","z-index":"2147483647","font-family":"Arial","line-height":"1","vertical-align":"baseline","box-sizing":"border-box",color:"rgb(34, 34, 34)","@media (max-width: 600px), (max-height: 480px)":{display:"none !important"}},X={height:"100%","overflow-x":"hidden","overlfow-y":"auto",position:"relative",padding:"0px 15px"},Z={},J={display:"flex","align-items":"center","margin-bottom":"10px"},Q={flex:"1","font-size":"24px","font-weight":"700","margin-top":"20px","margin-bottom":"0px"},ee={background:"none",border:"none",padding:"4px 8px",color:"#666464","font-size":"38px",cursor:"pointer","line-height":"1"},te={"font-size":"18px","font-weight":"400","margin-top":"20px","margin-bottom":"0px"},ne={display:"flex",gap:"10px",width:"100%","margin-top":"20px","margin-bottom":"20px","flex-wrap":"wrap","justify-content":"space-between"},re={width:"28%",display:"flex","flex-direction":"column","align-items":"center",background:"none",border:"1px solid #ccc","border-radius":"5px",padding:"5px",gap:"5px","text-align":"center","font-size":"14px",cursor:"pointer",transition:"background-color 0.2s ease"},oe={"max-width":"120px","max-height":"70px","margin-bottom":"5px","object-fit":"contain"},ie={"background-color":"#FFD812",cursor:"pointer","border-radius":"8px",padding:"8px",color:"white","min-width":"100px",border:"0","font-weight":"600",width:"100%"},se={display:"flex","flex-direction":"column",gap:"10px",width:"100%","color-scheme":"light"},ae={display:"flex","align-items":"center",gap:"5px",border:"1px solid #ddd",padding:"15px","border-radius":"5px","font-weight":"600",cursor:"pointer","margin-bottom":"8px"},le={background:"none",border:"none",color:"blue","text-decoration":"underline",padding:"0",cursor:"pointer","margin-bottom":"15px"},ce={display:"flex","justify-content":"space-between",margin:"30px 0px 10px 0px","font-size":"14px"},ge={color:"#666464","text-decoration":"underline"},ue={color:"rgb(102, 100, 100)","text-decoration":"underline",margin:"0",cursor:"pointer"},de={width:"100%","background-color":"#f2f2f2",border:"1px solid black","border-radius":"10px","border-top":"1px solid #bbb7b7","margin-top":"10px","margin-bottom":"20px","box-sizing":"border-box"},pe={padding:"0 5px 0 10px",width:"100%","font-size":"12px","box-sizing":"border-box"},me={display:"grid","grid-template-columns":"4fr 1fr","padding-right":"15px","padding-bottom":"5px"},he={color:"#000","margin-bottom":"4px"},fe={"font-size":"14px",color:"#555","text-align":"right"},Ae=(e,t)=>{let n=parseFloat(t);return"FLAT"===e&&(n*=.75),((e,t)=>{let n=parseFloat(t);return n<1&&(n=1),n=Math.floor(n),"PERCENTAGE"===e?`${n}%`:`$${n}`})(e,n.toString())};var be=R("<span>");function xe(e){const t=(n=e.title,r=e.activeDomain,n.replace("{0}",Ae(r.Merchant.MaxRate?.Kind,r.Merchant.MaxRate?.Amount??"0")));var n,r,o;return(o=be()).innerHTML=t,o}var ye=R("<div>"),ve=R("<div><div class=gf-offer-details><p>Select a charity to activate a donation during your online shopping session.</p><p> <b>Eligible Transaction:</b> A purchase made immediately after selecting a charity.</p><p><b>Donation rates:</b> <!> for each eligible transaction. The following donation rates and exclusions apply:</p><p><b>Donation amounts:</b> Donation amount is calculated based upon the applicable rates and exclusions, which may change from time to time. Amounts may be adjusted or canceled due to returned items, suspected fraud, or other factors described within the terms and conditions.</p><p><b>Donation timing:</b> On average, donation payouts occur 60-120 days after your completed transaction, but some donations may take 180 days or longer. We provide a donation to the charity you had selected at the time of purchase, in monthly batches, after any holdback periods due to applicable return or cancellation policies have passed.</p><p>See a summary of <a target=_blank rel=noreferrer>terms and conditions</a>."),we=R("<div class=gf-offer-details-rate-item><div></div><div>");const Ce=e=>{return t=ve(),o=(r=(n=t.firstChild).firstChild.nextSibling.nextSibling).firstChild.nextSibling.nextSibling,i=r.nextSibling,s=i.nextSibling.nextSibling.firstChild.nextSibling,L(r,(()=>e.parsedMaxRate?`Up to ${e.parsedMaxRate}`:"Earn"),o),L(n,O(D,{get when(){return!!e.merchantRateDetail?.length},get children(){var t=ye();return L(t,(()=>e.merchantRateDetail?.map((e=>{return t=we(),n=t.firstChild,r=n.nextSibling,L(n,(()=>e.Name||"")),L(r,(()=>((e,t=1,n=1)=>{const r=e.BoostedOffer??null;let o=parseFloat(e?.Amount??"");if(r?.EndDate&&new Date(r.EndDate)<new Date&&(o=parseFloat(r.OriginalMaxRate)),Number.isNaN(o))return"";const i=o*t;return"PERCENTAGE"===e?.Kind?`${i.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:n})}%`:"FLAT"===e?.Kind?i.toLocaleString("en-US",{style:"currency",currency:e.Currency}):""})(e))),p((e=>{var o=me,i=he,s=fe;return e.e=$(t,o,e.e),e.t=$(n,i,e.t),e.a=$(r,s,e.a),e}),{e:void 0,t:void 0,a:void 0}),t;var t,n,r})))),t}}),i),p((r=>{var o=de,i=pe,a=ge,l=e.termsUrl;return r.e=$(t,o,r.e),r.t=$(n,i,r.t),r.a=$(s,a,r.a),l!==r.o&&N(s,"href",r.o=l),r}),{e:void 0,t:void 0,a:void 0,o:void 0}),t;var t,n,r,o,i,s};var ke=R("<button class=give-freely-close-button aria-label=Close>×"),Pe=R('<div><div><div><span></span></div></div><hr><div></div><div><div><div><br><span></span></div><button aria-label="Don\'t show again"></button></div></div><div><p>Offer Details</p><a class=give-freely-footer-link target=_blank rel="noopener noreferrer">Why am I seeing this?'),Se=R("<div><div><img><span></span></div><button>");function Ee(e){const[t,n]=d(!1);return m((()=>{t()&&e.mainContainerRef&&e.mainContainerRef.scroll({top:e.mainContainerRef.scrollHeight,behavior:"smooth"})})),[(r=Pe(),o=r.firstChild,i=o.firstChild,s=i.firstChild,a=o.nextSibling.nextSibling,l=a.nextSibling,c=l.firstChild,g=c.firstChild,u=g.firstChild.nextSibling,f=g.nextSibling,A=l.nextSibling,b=A.firstChild,x=b.nextSibling,L(o,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupMainCloseButtonVisible},get children(){var t=ke();return F(t,"click",e.onClose),p((e=>$(t,ee,e))),t}}),null),L(a,O(xe,{get title(){return e.subtitle},get activeDomain(){return e.activeDomain}})),L(l,(()=>e.checkoutPopupConf.checkoutPopupCharities.map((t=>{return r=(n=Se()).firstChild,i=(o=r.firstChild).nextSibling,s=r.nextSibling,n.$$click=()=>e.onCharitySelect(t),r.style.setProperty("height","100px"),r.style.setProperty("text-align","center"),L(i,(()=>t.title)),L(s,(()=>e.checkoutPopupConf.checkoutPopupCharitySelectString||"Select")),p((r=>{var i=re,a=t.logo,l=oe,c=t.title,g={...ie,"background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812"},u=`Select charity: ${t.title}`;return r.e=$(n,i,r.e),a!==r.t&&N(o,"src",r.t=a),r.a=$(o,l,r.a),c!==r.o&&N(o,"alt",r.o=c),r.i=$(s,g,r.i),u!==r.n&&N(s,"aria-label",r.n=u),r}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),n;var n,r,o,i,s}))),c),F(c,"click",e.onSuppress),g.style.setProperty("height","100px"),g.style.setProperty("text-align","center"),L(f,(()=>e.checkoutPopupConf.checkoutPopupCharitySelectString||"Select")),b.$$click=()=>{e.onOfferDetailsClick(!t()),n(!t())},p((t=>{var n=Z,g=J,d=Q,p=e.checkoutPopupConf.checkoutPopupMainTitle,m=te,h=ne,y=re,v=e.checkoutPopupConf.checkoutPopupSixthBoxWording,w={...ie,"background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812"},C=ce,k=ue,P=ge,S=e.checkoutPopupConf.externalUrls.giveFreelyWhyAmISeeingThis;return t.e=$(r,n,t.e),t.t=$(o,g,t.t),t.a=$(i,d,t.a),p!==t.o&&(s.innerHTML=t.o=p),t.i=$(a,m,t.i),t.n=$(l,h,t.n),t.s=$(c,y,t.s),v!==t.h&&(u.innerHTML=t.h=v),t.r=$(f,w,t.r),t.d=$(A,C,t.d),t.l=$(b,k,t.l),t.u=$(x,P,t.u),S!==t.c&&N(x,"href",t.c=S),t}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0}),r),O(D,{get when(){return t()},get children(){return O(Ce,{get merchantName(){return e.activeDomain.Merchant.Name},get extensionName(){return e.checkoutPopupConf.displayName},get termsUrl(){return e.checkoutPopupConf.externalUrls.giveFreelyTermsAndConditions},get parsedMaxRate(){return h((()=>!!e.activeDomain.Merchant.MaxRate))()?Ae(e.activeDomain.Merchant.MaxRate.Kind,e.activeDomain.Merchant.MaxRate?.Amount):null},get merchantRateDetail(){return e.merchantRates},onClose:()=>n(!1)})}})];var r,o,i,s,a,l,c,g,u,f,A,b,x}I(["click"]);var Te=R("<button class=give-freely-close-button aria-label=Close>×"),Oe=R("<label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=18250><span>Don't ask me again... ever"),De=R("<div><div><div></div></div><button class=give-freely-back-button aria-label=\"Back to charity selection\">I changed my mind! I'd like to select a charity.</button><hr><div id=give-freely-goodbye-screen-options><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=1><span>Don't ask me again for 1 day</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=7><span>Don't ask me again for 7 days</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=30><span>Don't ask me again for 30 days</span></label><label class=give-freely-radio-option><input type=radio name=gf-rad-goodbye value=90><span>Don't ask me again for 90 days</span></label></div><button class=give-freely-submit-button>Submit");function _e(e){const[t,n]=d(0);return r=De(),o=r.firstChild,i=o.firstChild,s=o.nextSibling,a=s.nextSibling.nextSibling,c=(l=a.firstChild).firstChild,u=(g=l.nextSibling).firstChild,h=(m=g.nextSibling).firstChild,A=(f=m.nextSibling).firstChild,b=a.nextSibling,r.style.setProperty("font-size","14px"),L(i,(()=>e.checkoutPopupConf.checkoutPopupSupressTitle)),L(o,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupSupressCloseButtonVisible},get children(){var t=Te();return t.$$click=()=>e.onGoodbye(0),p((e=>$(t,ee,e))),t}}),null),F(s,"click",e.onBack),c.addEventListener("change",(()=>n(1))),u.addEventListener("change",(()=>n(7))),h.addEventListener("change",(()=>n(30))),A.addEventListener("change",(()=>n(90))),L(a,O(D,{get when(){return e.checkoutPopupConf.checkoutPopupNeverSuppressionAllowed},get children(){var e=Oe();return e.firstChild.addEventListener("change",(()=>n(18250))),p((t=>$(e,ae,t))),e}}),null),b.$$click=()=>{const n=t();n&&(e.onGoodbye(n),e.setScreen("main"))},p((t=>{var n=J,r=Q,c=le,u=se,d=ae,p=ae,h=ae,A=ae,x={...ie,"font-weight":"700","margin-top":"10px","margin-bottom":"0px","background-color":e.checkoutPopupConf.checkoutPopupSelectCharityButtonBgColor||"#FFD812",width:"100px"};return t.e=$(o,n,t.e),t.t=$(i,r,t.t),t.a=$(s,c,t.a),t.o=$(a,u,t.o),t.i=$(l,d,t.i),t.n=$(g,p,t.n),t.s=$(m,h,t.s),t.h=$(f,A,t.h),t.r=$(b,x,t.r),t}),{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),r;var r,o,i,s,a,l,c,g,u,m,h,f,A,b}I(["click"]);var Re=R("<div><div><div></div><button class=give-freely-close-button aria-label=Close>×</button></div><hr><div><span>");function Ie(e){return t=Re(),n=t.firstChild,r=n.firstChild,o=r.nextSibling,i=n.nextSibling.nextSibling,s=i.firstChild,t.style.setProperty("font-size","14px"),L(r,(()=>e.failedDonation?"Oops! Something went wrong":e.checkoutPopupConf.checkoutPopupDonationTitle)),F(o,"click",e.onClose),i.style.setProperty("padding","30px"),i.style.setProperty("height","150px"),i.style.setProperty("font-size","14px"),p((t=>{var i=J,a=Q,l=ee,c=e.failedDonation?"Please try again later.":e.checkoutPopupConf.checkoutPopupDonationWording;return t.e=$(n,i,t.e),t.t=$(r,a,t.t),t.a=$(o,l,t.a),c!==t.o&&(s.innerHTML=t.o=c),t}),{e:void 0,t:void 0,a:void 0,o:void 0}),t;var t,n,r,o,i,s}I(["click"]);var Ne,Fe,$e=R("<div><div>");function Le(e){const{logger:t}=e,[n,r]=d("main"),[o,i]=d(),[s,a]=d(!1),l=()=>{t.debug("Close button clicked"),e.onClose()},c=async n=>{t.info("Charity selected",{charity:n,domain:e.activeDomain.Domain}),i(n);const o=await e.onDonate(n,e.activeDomain);a(!o),r("donate")},g=()=>{t.debug("Suppress button clicked"),r("goodbye")},u=()=>{t.debug("Navigating back to main screen"),r("main")},m=n=>{t.info("User chose to hide popup",{days:n}),e.onClose(n)};let h;return x=$e(),y=x.firstChild,"function"==typeof h?(A=h,b=y,f((()=>A(b,undefined)))):h=y,L(y,O(D,{get when(){return"main"===n()},get children(){return O(Ee,{mainContainerRef:h,get checkoutPopupConf(){return e.checkoutPopupConf},get activeDomain(){return e.activeDomain},get merchantRates(){return e.merchantRates},onClose:l,onCharitySelect:c,onSuppress:g,get onOfferDetailsClick(){return e.onOfferDetailsClick},get subtitle(){return e.checkoutPopupConf.checkoutPopupSubTitle}})}}),null),L(y,O(D,{get when(){return"goodbye"===n()},get children(){return O(_e,{get checkoutPopupConf(){return e.checkoutPopupConf},onClose:()=>e.onClose(),onBack:u,onGoodbye:m,setScreen:r})}}),null),L(y,O(D,{get when(){return"donate"===n()},get children(){return O(Ie,{get checkoutPopupConf(){return e.checkoutPopupConf},get selectedCharity(){return o()},onClose:()=>e.onClose(),get failedDonation(){return s()},setScreen:r})}}),null),p((t=>{var n=q,r=e.elementId,o=X;return t.e=$(x,n,t.e),r!==t.t&&N(x,"id",t.t=r),t.a=$(y,o,t.a),t}),{e:void 0,t:void 0,a:void 0}),x;var A,b,x,y}class Me{log({level:e,message:t,timestamp:n,data:r,title:o}){const i="debug"===e?"log":e,s=o?`[${o}]`:"";void 0!==r?console[i](`[${n}] - ${Me.LOGGER_PREFIX} ${s} ${t}`,r):console[i](`[${n}] - ${Me.LOGGER_PREFIX} ${s} ${t}`)}}Me.LOGGER_PREFIX="[GFAdUnit] -",function(e){e.checkoutPopupShown="CHECKOUT-POPUP-SHOWN",e.checkoutPopupNotShown="CHECKOUT-POPUP-NOT-SHOWN",e.checkoutPopupSupressed="CHECKOUT-POPUP-SUPRESSED",e.checkoutPopupDonation="CHECKOUT-POPUP-DONATION",e.checkoutPopupFailedActivation="CHECKOUT-POPUP-FAILED-ACTIVATION",e.checkoutPopupPurchaseConfirmed="CHECKOUT-POPUP-PURCHASE-CONFIRMED",e.checkoutPopupHealthCheck="CHECKOUT-POPUP-HEALTH-CHECK",e.checkouPopupActivationFailed="CHECKOUT-POPUP-ACTIVATION-FAILED",e.checkoutPopupOfferDetailsClicked="CHECKOUT-POPUP-OFFER-DETAILS-CLICKED"}(Ne||(Ne={})),function(e){e.adUnitLog="ADUNIT-LOG"}(Fe||(Fe={}));const Ue=["debug","info","warn","error"];class Ge{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new Me],title:e?.title??""}}static getInstance(e){return Ge.instance||(Ge.instance=new Ge(e)),Ge.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&Ue.indexOf(e)>=Ue.indexOf(this.config.minLevel)}createLogMessage(e,t,n){return{level:e,version:"1.1.0",message:t,timestamp:(new Date).toISOString(),data:n,title:this.config.title}}log(e,t,n){if(!this.shouldLog(e))return;const r=this.createLogMessage(e,t,n);this.config.transports.forEach((e=>e.log(r)))}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}function He(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var Be={exports:{}};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,function(e){if(!(globalThis.chrome&&globalThis.chrome.runtime&&globalThis.chrome.runtime.id))throw new Error("This script should only be loaded in a browser extension.");if(globalThis.browser&&globalThis.browser.runtime&&globalThis.browser.runtime.id)e.exports=globalThis.browser;else{const t="The message port closed before a response was received.",n=e=>{const n={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(n).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class r extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const o=(t,n)=>(...r)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):n.singleCallbackArg||r.length<=1&&!1!==n.singleCallbackArg?t.resolve(r[0]):t.resolve(r)},i=e=>1==e?"argument":"arguments",s=(e,t,n)=>new Proxy(t,{apply:(t,r,o)=>n.call(r,e,...o)});let a=Function.call.bind(Object.prototype.hasOwnProperty);const l=(e,t={},n={})=>{let r=Object.create(null),c={has:(t,n)=>n in e||n in r,get(c,g,u){if(g in r)return r[g];if(!(g in e))return;let d=e[g];if("function"==typeof d)if("function"==typeof t[g])d=s(e,e[g],t[g]);else if(a(n,g)){let t=((e,t)=>function(n,...r){if(r.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${r.length}`);if(r.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${r.length}`);return new Promise(((i,s)=>{if(t.fallbackToNoCallback)try{n[e](...r,o({resolve:i,reject:s},t))}catch(o){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,o),n[e](...r),t.fallbackToNoCallback=!1,t.noCallback=!0,i()}else t.noCallback?(n[e](...r),i()):n[e](...r,o({resolve:i,reject:s},t))}))})(g,n[g]);d=s(e,e[g],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(a(t,g)||a(n,g)))d=l(d,t[g],n[g]);else{if(!a(n,"*"))return Object.defineProperty(r,g,{configurable:!0,enumerable:!0,get:()=>e[g],set(t){e[g]=t}}),d;d=l(d,t[g],n["*"])}return r[g]=d,d},set:(t,n,o,i)=>(n in r?r[n]=o:e[n]=o,!0),defineProperty:(e,t,n)=>Reflect.defineProperty(r,t,n),deleteProperty:(e,t)=>Reflect.deleteProperty(r,t)},g=Object.create(e);return new Proxy(g,c)},c=e=>({addListener(t,n,...r){t.addListener(e.get(n),...r)},hasListener:(t,n)=>t.hasListener(e.get(n)),removeListener(t,n){t.removeListener(e.get(n))}}),g=new r((e=>"function"!=typeof e?e:function(t){const n=l(t,{},{getContent:{minArgs:0,maxArgs:0}});e(n)})),u=new r((e=>"function"!=typeof e?e:function(t,n,r){let o,i,s=!1,a=new Promise((e=>{o=function(t){s=!0,e(t)}}));try{i=e(t,n,o)}catch(e){i=Promise.reject(e)}const l=!0!==i&&((c=i)&&"object"==typeof c&&"function"==typeof c.then);var c;if(!0!==i&&!l&&!s)return!1;return(l?i:a).then((e=>{r(e)}),(e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",r({__mozWebExtensionPolyfillReject__:!0,message:t})})).catch((e=>{console.error("Failed to send onMessage rejected reply",e)})),!0})),d=({reject:n,resolve:r},o)=>{e.runtime.lastError?e.runtime.lastError.message===t?r():n(new Error(e.runtime.lastError.message)):o&&o.__mozWebExtensionPolyfillReject__?n(new Error(o.message)):r(o)},p=(e,t,n,...r)=>{if(r.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${r.length}`);if(r.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${r.length}`);return new Promise(((e,t)=>{const o=d.bind(null,{resolve:e,reject:t});r.push(o),n.sendMessage(...r)}))},m={devtools:{network:{onRequestFinished:c(g)}},runtime:{onMessage:c(u),onMessageExternal:c(u),sendMessage:p.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:p.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},h={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return n.privacy={network:{"*":h},services:{"*":h},websites:{"*":h}},l(e,m,n)};e.exports=n(chrome)}}(Be);var je=He(Be.exports);const Ke="GIVE_FREELY_",We={async get(e){const t=`${Ke}${e}`;return(await je.storage.local.get(t))[t]||null},async set(e,t){const n=`${Ke}${e}`;await je.storage.local.set({[n]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${Ke}${e}`)):`${Ke}${e}`;await je.storage.local.remove(t)}};class Ve{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0,this.CONFIG_REFRESH_INTERVAL=3e5,this.PARTNER_CONFIG_STORAGE_KEY="gf_partner_config",this.GLOBAL_CONFIG_STORAGE_KEY="gf_global_config"}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchAndUpdatePartnerConfig(){const e=await W((async()=>{const e=await fetch(`https://cdn.givefreely.com/adunit/config/${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await We.set(this.PARTNER_CONFIG_STORAGE_KEY,t),e}async fetchAndUpdateGlobalConfig(){const e=await W((async()=>{const e=await fetch("https://cdn.givefreely.com/adunit/config/global.json",{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config: ${e.statusText}`);return e.json()}),this.getRetryOptions()),t={config:e,lastRefresh:Date.now()};return await We.set(this.GLOBAL_CONFIG_STORAGE_KEY,t),e}async getConfig(){const e=Date.now(),t=await We.get(this.PARTNER_CONFIG_STORAGE_KEY),n=await We.get(this.GLOBAL_CONFIG_STORAGE_KEY);if(this.partnerConfig=t?.config||null,this.globalConfig=n?.config||null,this.lastConfigRefresh=Math.max(t?.lastRefresh||0,n?.lastRefresh||0),!this.partnerConfig||!this.globalConfig||e-this.lastConfigRefresh>this.CONFIG_REFRESH_INTERVAL)try{const[t,n]=await Promise.all([this.fetchAndUpdatePartnerConfig(),this.fetchAndUpdateGlobalConfig()]);this.partnerConfig=t,this.globalConfig=n,this.lastConfigRefresh=e}catch(e){if(!this.partnerConfig||!this.globalConfig)throw e;console.warn("Failed to refresh configs, using existing configs:",e)}const r=this.mergeConfigs(this.globalConfig,this.partnerConfig);return((e,t,n)=>{const r=[...t.merchantExclusions??[],...n.merchantExclusions??[]];e.merchantExclusions=r})(r,this.globalConfig,this.partnerConfig),r}async clearCache(){await Promise.all([We.remove(this.PARTNER_CONFIG_STORAGE_KEY),We.remove(this.GLOBAL_CONFIG_STORAGE_KEY)]),this.partnerConfig=null,this.globalConfig=null,this.lastConfigRefresh=0}mergeConfigs(e,t){if(!t)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=e,i=t;"object"==typeof i[r]&&null!==i[r]&&"object"==typeof o[r]?n[r]=this.mergeConfigs(o[r],i[r]):n[r]=void 0!==i[r]?i[r]:o[r]}return n}getStoredState(e){return e?{config:e.config,lastRefresh:e.lastRefresh}:{config:null,lastRefresh:0}}}const Ye="TRACK_EVENT",ze="GF_HIDE_POPUP",qe="GF_GET_POPUP_CONFIG",Xe="GF_IS_ACTIVE_DOMAIN",Ze="GF_SHOULD_STAND_DOWN",Je="GF_ACTIVATE_OFFER",Qe="GF_STORE_SHOPIFY_SHOP_ID",et="GF_GET_DOMAIN_BY_SHOP_ID";class tt{constructor(t,n,r=60){this._config=null,this.track=async(t,n,r)=>{null===this._config&&(this._config=await new Ve(this._partnerApiKey).getConfig());const o={partner:`adUnit_${this._partnerApiKey}`,eventType:t,eventData:{userId:this._userService?.user?.id,libVersion:String(e)??"",wfDeviceId:n,...r}};try{const e=JSON.stringify(o);return await this.shouldBroadcastEvent(e)?(await fetch(this._config.eventsUrl,{headers:{"Content-Type":"application/json"},method:"POST",body:e,cache:"no-store"}),await this.pushEventToHistory(e),!0):(this.log("This event has already been broadcasted during the past hour",o),!1)}catch(e){return this.log("Something unexpected happened when dispatching a gf event",e,o),!1}},this.log=(...e)=>{"debug"===this._config?.backgroundMinLogLevel&&console.log("analytics:",...e)},this.getEventsHistory=async()=>{const{GF_AD_EVENT_HISTORY:e}=await V.storage.local.get({GF_AD_EVENT_HISTORY:""}),t=function(e){const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()}(-this._debounceWindowInMinutes);let n=(e||[]).filter((e=>e.createdAt>t));return await V.storage.local.set({GF_AD_EVENT_HISTORY:n}),n},this.shouldBroadcastEvent=async e=>!(await this.getEventsHistory()).some((t=>t.payload===e)),this.pushEventToHistory=async e=>{const t=await this.getEventsHistory();t.push({createdAt:Date.now(),payload:e}),await V.storage.local.set({GF_AD_EVENT_HISTORY:t})},this._partnerApiKey=t,this._userService=n,this._debounceWindowInMinutes=r}}function nt(e){const t=["",".asp",".aspx",".php",".js",".htm",".html"],n=["cart","checkout","shopping-bag","shopping-basket","shopping-cart","basket"].flatMap((e=>t.map((t=>e+t)))).filter((e=>"basket"!==e)),r=["tote-cart","tote.cart"],o=e,i=n.filter((e=>o.includes(e))),s=o.split("/");return!s.some((e=>r.some((t=>e.includes(t)))))&&(s.some((e=>n.some((t=>e.startsWith(t)||e.endsWith(t)))))||"basket"===s[s.length-1].toLowerCase()||i.length>1||1===i.length&&o.includes("shopping"))}function rt(e,t){const n=["book"];return e.split("/").some((e=>n.some((t=>e.startsWith(t)||e.endsWith(t)))))&&null!=t.evaluate("//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6][contains(., 'Your Reservation') or contains(., 'Your reservation')]",t,null,XPathResult.ANY_TYPE,null)?.iterateNext()}async function ot(e){try{const t=await Y({type:et,payload:{shopId:e}});return t.payload.found&&t.payload.domain?t.payload.domain:null}catch(e){return null}}function it(){try{const e=Array.from(document.querySelectorAll("script"));for(const t of e){if(t.dataset?.shopId?.startsWith("gid")){const e=parseInt(t.dataset.shopId.replace("gid://shopify/Shop/",""));if(!isNaN(e)&&e>0)return e}const e=t.textContent||"";if(e.includes("ShopifyAnalytics")&&e.includes("shopId")){const t=e.match(/shopId['"]*:\s*['"]*(\d+)['"]*[,}]/);if(t&&t[1]){const e=parseInt(t[1]);if(!isNaN(e)&&e>0)return e}}}const t=document.querySelector("[data-shop-id]");if(t instanceof HTMLElement){const e=t.dataset.shopId;if(e){const t=parseInt(e);if(!isNaN(t)&&t>0)return t}}const n=window?.ShopifyAnalytics?.lib?.trekkie?.defaultAttributes?.shopId;return n&&parseInt(n)||0}catch(e){return console.error("Error accessing ShopifyAnalytics:",e),0}}function st(){try{if(!window.location.href.startsWith("https://shop.app"))return 0;const e=document?.head?.querySelector('meta[name="store"][content]');if(!e)return 0;try{const t=JSON.parse(e.content);return t?.id||0}catch(e){return 0}}catch(e){return 0}}tt.trackEvent=async(e,t)=>{await Y({type:Ye,payload:{eventType:e,eventData:t}})};const at=Ge.getInstance();function lt(e,t,n){try{const r=function(e){try{const t=e.split(".");return t.length>=2?t.slice(-2).join("."):e}catch(e){return at.error("Error extracting domain",e),""}}(n);at.debug("Checking merchant regex rules",{currentDomain:r,currentUrl:t});const o=e.merchantPopupRules.filter((e=>r.includes(e.domain)));if(0===o.length)return at.debug("No matching merchant rules found for domain",{currentDomain:r}),!1;for(const e of o)for(const n of e.rules)try{if(new RegExp(n.rule).test(t))return at.debug("Merchant regex rule matched",{merchant:e.name,rule:n.rule,currentUrl:t}),!0}catch(t){at.error("Invalid regex in merchant rule",{merchant:e.name,rule:n.rule,error:t})}return at.debug("No matching regex rules found",{currentUrl:t}),!1}catch(e){return at.error("Error in merchantRegexRule",e),!1}}var ct=R("<div class=gf-app>");function gt(){const t=Ge.getInstance(),[n,r]=d(null),[o,i]=d(void 0),[s,a]=d(!1),[l,c]=d([]);var g;g=async()=>{t.info("Mounting GfApp component");try{const n=await(async()=>{const e=await Y({type:qe,payload:{}});if(!e.payload.config)throw new Error("No checkout popup config found");return e.payload.config})();if(!n)return void t.error("No checkout popup config found");r(n),t.configure({enabled:!0,title:"Content - GfAdUnit",minLevel:n.checkoutPopupMinLogLevel??"error"});const s=String(e);if(n.minVersion&&((e,t)=>{if(e===t)return!1;const n=e.split(".").map(parseInt),r=t.split(".").map(parseInt);for(let e=0;e<n.length;e++){if(n[e]<r[e])return!0;if(n[e]>r[e])return!1}return!1})(s,n.minVersion))return void t.debug(`Current version: ${s}. Minimum version ${n.minVersion} not met`);if(!1===n.checkoutPopupMasterSwitch)return void t.debug("Checkout popup master switch is disabled");const{domain:l,rates:g}=await(async e=>{const{hostname:t}=window.location;e.debug("Checking if domain is active",{hostname:t});const n=await Y({type:Xe,payload:{hostname:t}});return n.payload.isActive?(e.debug("Active domain",{domain:n.payload.domain}),e.debug("Merchant rates",{rates:n.payload.rates}),e.info("Domain and rates ({})ed successfully."),{isActive:!0,domain:n.payload.domain,rates:n.payload.rates}):{isActive:!1,domain:void 0,rates:[]}})(t);if(c(g),i(l),l)await function(e){const t=it()||st();return t>0&&function(e,t){if(e&&!(e<=0))try{Y({type:Qe,payload:{shopId:e,domain:t}}).catch((e=>{console.error("Error sending shop ID to background:",e)}))}catch(e){console.error("Error sending Shopify shop ID:",e)}}(t,e),t}(l);else{if("shop.app"!==window.location.hostname&&!window.location.hostname.endsWith(".shop.app"))return void a(!1);const e=window.location.pathname.split("/")[2];if(!e)return t.error("Shop ID not found"),void a(!1);const n=await ot(parseInt(e));if(!n)return t.error("Shop domain not found"),void a(!1);t.debug("Shop domain found",{shopDomain:n}),i(n)}const u=await(async e=>{const t=await We.get("popup_hide");if(!t)return e.debug("No expiry found in storage"),!1;const{popupHide:n}=t,r=!!n&&Date.now()<n;return e.debug("Is AdUnit Muted?",{isMuted:r,expiry:n}),r})(t);if(u)return;if(!o())return void a(!1);const d=await(async(e,t)=>{const{Domain:n}=t,r=window.location.href,{payload:o}=await Y({type:Ze,payload:{activeDomain:n,url:r}});return!!o.result&&(e.info("Stand Down detected"),!0)})(t,o());if(d)return void a(!1);const p=setInterval((async()=>{t.debug("Checking checkout rules");const e=await(async e=>{const t=Ge.getInstance();t.configure({enabled:!0,title:"Content - checkoutRulesTest"});const n=new URL(globalThis.location.href),r=n.href,o=n.hostname;t.debug("Checking if popup should be shown",{currentUrl:r});const i=await async function(){const e=it()||st();return!("shop.app"!==window.location.hostname&&!window.location.hostname.endsWith(".shop.app")||!(e>0)||!await ot(e))}(),s=nt(n.pathname.toLowerCase())||rt(r,document)||lt(e,r,o)||i;return t.debug("Popup show decision based on rules",{shouldShow:s,matchesCartRule:nt(n.pathname.toLowerCase()),matchesBookingRule:rt(r,document),matchesShopPayRule:i,matchesMerchantRegexRule:lt(e,r,o)}),s})(n);a(e),e&&(t.debug("Should show popup based on checkout rules",{shouldShowResult:e}),tt.trackEvent(Ne.checkoutPopupShown,{url:globalThis.window.location.href}),clearInterval(p))}),2e3)}catch(e){a(!1),t.error("An error occurred in GfApp",{error:e})}},m((()=>f(g)));const u=async(e,n)=>{t.info("Processing donation",{charity:e,domain:n.Domain});const r=await(async(e,t,n,r)=>{e.debug("Activating offer",{activeDomain:t,selectedCharity:r});const o=await z({type:Je,payload:{activeDomain:t,originalUrl:n,selectedCharity:r}});return e.debug("Activate offer response",{response:o}),o})(t,n,window.location.href,{ein:e.ein,thirdPartyId:e.tpi});return t.debug("Activate offer response",{activationResponse:r}),tt.trackEvent(r.payload.response?Ne.checkoutPopupDonation:Ne.checkoutPopupFailedActivation,{activeDomain:n.Domain,url:globalThis.window.location.href,charity:{ein:e.ein,tpi:e.tpi},rate:n.Merchant.MaxRate}),r.payload.response},p=async e=>{a(await(async(e,t)=>{try{e.info("Hiding ad",{days:t});const n=await z({type:ze,payload:{days:t??0}});return t&&t>0&&tt.trackEvent(Ne.checkoutPopupSupressed,{url:globalThis.window.location.href,days:t}),e.info("Hiding ad response",{hide_response:n}),n.payload.ack?(e.debug("Ad hidden successfully"),!1):(e.warn("Failed to hide ad"),!0)}catch(e){return!1}})(t,e))},A=async e=>{tt.trackEvent(Ne.checkoutPopupOfferDetailsClicked,{action:e?"opened":"closed"})};return L(x=ct(),(b=h((()=>!(!o()||!s()))),()=>b()&&O(Le,{get checkoutPopupConf(){return n()},elementId:"give-freely-checkout-popup",get activeDomain(){return o()},get merchantRates(){return l()},onClose:p,onDonate:u,onOfferDetailsClick:A,logger:t}))),x;var b,x}async function ut(){const e=document.createElement("div");e.id="give-freely-root",document.body.appendChild(e);const t=e.attachShadow({mode:"open"}),n=document.createElement("div"),r=document.createElement("style");r.textContent='\n :host {\n all: initial;\n }\n\n .gf-scroll-remove::-webkit-scrollbar {\n border-radius-bottom-right: 15px;\n }\n\n button {\n cursor: pointer;\n transition: transform 0.1s ease;\n }\n\n button:active {\n transform: scale(0.98);\n }\n\n .give-freely-close-button:hover {\n opacity: 0.7;\n }\n\n input[type="radio"] {\n margin-right: 8px;\n }\n\n hr {\n border: none;\n border-top: 1px solid #e5e5e5;\n margin: 1em 0;\n }\n\n @media (max-width: 600px), (max-height: 480px) {\n #give-freely-checkout-popup {\n display: none !important;\n }\n }\n',t.appendChild(r),t.appendChild(n),function(e,t,n,r={}){let o;(function(e,t){const n=l,r=s,o=0===e.length,a=void 0===t?r:t,c=o?i:{owned:null,cleanups:null,context:a?a.context:null,owner:a},g=o?e:()=>e((()=>f((()=>E(c)))));s=c,l=null;try{return w(g,!0)}finally{l=n,s=r}})((r=>{o=r,t===document?e():L(t,e(),t.firstChild?null:void 0,n)}),r.owner)}((()=>O(gt,{})),n)}export{V as browser,ut as initializeAdUnit};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@givefreely/adunit",
3
- "version": "1.1.0-rc.1",
3
+ "version": "1.1.1-dev.1",
4
4
  "description": "AdUnit module",
5
5
  "main": "./GiveFreely-content.cjs",
6
6
  "module": "./GiveFreely-content.esm",