@givefreely/adunit 2.5.1-dev.0 → 2.5.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.
- package/GiveFreely-background.cjs.js +1 -1
- package/GiveFreely-background.cjs.js.map +1 -1
- package/GiveFreely-background.esm.js +1 -1
- package/GiveFreely-background.esm.js.map +1 -1
- package/GiveFreely-content.cjs.js +1 -1
- package/GiveFreely-content.cjs.js.map +1 -1
- package/GiveFreely-content.esm.js +1 -1
- package/GiveFreely-content.esm.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(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 t={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 n=(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",s=(e,t,r)=>new Proxy(t,{apply:(t,i,n)=>r.call(i,e,...n)});let o=Function.call.bind(Object.prototype.hasOwnProperty);const c=(e,t={},r={})=>{let i=Object.create(null),l={has:(t,r)=>r in e||r in i,get(l,g,h){if(g in i)return i[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(o(r,g)){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,s)=>{if(t.fallbackToNoCallback)try{r[e](...i,n({resolve:a,reject:s},t))}catch(n){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,n),r[e](...i),t.fallbackToNoCallback=!1,t.noCallback=!0,a()}else t.noCallback?(r[e](...i),a()):r[e](...i,n({resolve:a,reject:s},t))}))})(g,r[g]);d=s(e,e[g],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(o(t,g)||o(r,g)))d=c(d,t[g],r[g]);else{if(!o(r,"*"))return Object.defineProperty(i,g,{configurable:!0,enumerable:!0,get:()=>e[g],set(t){e[g]=t}}),d;d=c(d,t[g],r["*"])}return i[g]=d,d},set:(t,r,n,a)=>(r in i?i[r]=n:e[r]=n,!0),defineProperty:(e,t,r)=>Reflect.defineProperty(i,t,r),deleteProperty:(e,t)=>Reflect.deleteProperty(i,t)},g=Object.create(e);return new Proxy(g,l)},l=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))}}),g=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 n,a,s=!1,o=new Promise((e=>{n=function(t){s=!0,e(t)}}));try{a=e(t,r,n)}catch(e){a=Promise.reject(e)}const c=!0!==a&&((l=a)&&"object"==typeof l&&"function"==typeof l.then);var l;if(!0!==a&&!c&&!s)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},n)=>{e.runtime.lastError?e.runtime.lastError.message===t?i():r(new Error(e.runtime.lastError.message)):n&&n.__mozWebExtensionPolyfillReject__?r(new Error(n.message)):i(n)},u=(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 n=d.bind(null,{resolve:e,reject:t});i.push(n),r.sendMessage(...i)}))},m={devtools:{network:{onRequestFinished:l(g)}},runtime:{onMessage:l(h),onMessageExternal:l(h),sendMessage:u.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:u.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,m,r)};e.exports=r(chrome)}}(t);var r,i,browser=e(t.exports);class n{constructor(){this.isLocal=!0}log({level:e,message:t,timestamp:r,data:i,title:a}){let s;switch(e){case"debug":default:s="log";break;case"info":s="info";break;case"warn":s="warn";break;case"error":case"critical":case"fatal":s="error"}const o=a?`[${a}]`:"";void 0!==i?console[s](`[${r}] - ${n.LOGGER_PREFIX} ${o} ${t}`,i):console[s](`[${r}] - ${n.LOGGER_PREFIX} ${o} ${t}`)}}n.LOGGER_PREFIX="[DonationPopup] -",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",e.checkoutPopupWhyAmISeeingThisClicked="CHECKOUT-POPUP-WHY-AM-I-SEEING-THIS-CLICKED",e.checkoutPopupLooserExtension="CHECKOUT-POPUP-LOOSER-EXTENSION",e.checkoutPopupActiveDomain="CHECKOUT-POPUP-ACTIVE-DOMAIN",e.checkoutPopupSiteMatches="CHECKOUT-POPUP-SITE-MATCHES",e.checkoutPopupMerchantInResultsFound="CHECKOUT-MERCHANT-IN-RESULTS-FOUND",e.checkoutPopupNotShownPerViewportSize="CHECKOUT-POPUP-NOT-SHOWN-PER-VIEWPORT-SIZE",e.checkoutPopupHiddenProgrammatically="CHECKOUT-POPUP-HIDDEN-PROGRAMMATICALLY",e.checkoutPopupGoogleSearch="CHECKOUT-POPUP-GOOGLE-SEARCH",e.checkoutPopupGooglePartnerAnnCreated="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-CREATED",e.checkoutPopupGooglePartnerAnnClicked="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-CLICKED",e.checkoutPopupGooglePartnerAnnHidden="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-HIDDEN",e.checkoutPopupStoodDown="CHECKOUT-POPUP-STOOD-DOWN"}(r||(r={})),function(e){e.libLog="GFLIB-LOG"}(i||(i={}));class a{constructor(e){this.isLocal=!1,this.backgroundService=e}log({level:e,message:t,data:r,title:n}){this.backgroundService.trackEvent(i.libLog,{log:{level:e,message:t,data:r,title:n}})}}const s=["debug","info","warn","error","critical","fatal"];class o{constructor(e){this.config={minLevel:e?.minLevel??"debug",enabled:e?.enabled??!1,transports:e?.transports??[new n],title:e?.title??""}}static getInstance(e){return o.instance||(o.instance=new o(e)),o.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&s.indexOf(e)>=s.indexOf(this.config.minLevel)}createLogMessage(e,t,r){return{level:e,version:"2.5.1",message:t,timestamp:(new Date).toISOString(),data:r,title:this.config.title}}log(e,t,r,i){if(!this.shouldLog(e))return;const n=this.createLogMessage(e,t,i);this.config.transports.filter((e=>!r||e.isLocal)).forEach((e=>e.log(n)))}debug(e,t,r=!1){this.log("debug",e,r,t)}info(e,t,r=!1){this.log("info",e,r,t)}warn(e,t,r=!1){this.log("warn",e,r,t)}error(e,t,r=!1){this.log("error",e,r,t)}critical(e,t,r=!1){this.log("critical",e,r,t)}fatal(e,t,r=!1){this.log("fatal",e,r,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}const c=3,l=e=>1e3*e;async function g(e,t={},r){const{maxAttempts:i=c,delayFn:n=l}=t;let a=null;for(let t=1;t<=i;t+=1)try{return await e()}catch(e){a=e,t<i&&await new Promise((e=>{setTimeout(e,n(t))}))}throw a&&t.logger&&t.operationName&&t.logger.error(`Operation ${t.operationName} failed after ${i} attempts.`,a,!0),a||new Error("Operation failed after multiple attempts")}const h=browser,d={TRACK_EVENT:"GF_TRACK_EVENT",HIDE_POPUP:"GF_HIDE_POPUP",GET_POPUP_CONFIG:"GF_GET_POPUP_CONFIG",IS_ACTIVE_DOMAIN:"GF_IS_ACTIVE_DOMAIN",LOG_MERCHANTS_IN_SEARCH_RESULTS:"GF_LOG_MERCHANTS_IN_SEARCH_RESULTS",SHOULD_STAND_DOWN:"GF_SHOULD_STAND_DOWN",ACTIVATE_OFFER:"GF_ACTIVATE_OFFER",STORE_SHOPIFY_SHOP_ID:"GF_STORE_SHOPIFY_SHOP_ID",GET_DOMAIN_BY_SHOP_ID:"GF_GET_DOMAIN_BY_SHOP_ID",GET_LANGUAGE_CONTENT:"GF_GET_LANGUAGE_CONTENT",GET_ACTIVE_DOMAINS:"GF_GET_ACTIVE_DOMAINS",MUTE_PARTNER_SERP_BOX:"GF_MUTE_PARTNER_SERP_BOX",GET_GF_DATA:"GF_GET_GF_DATA"},u="shopify_shop_ids",m="gf_last_health_check",f="gf_partner_config",p="gf_global_config",A="countryCode",y="version",w="gf_anonymous_user_info",v="gf_anonymous_encrypted_token",C="gf_event_history",E="gf_popup_everywhere",S={DEVICE:"wfDevice",DOMAINS:"wfDomains",STANDDOWN_POLICY:"wfStanddownPolicy",STANDDOWN_HISTORY:"wfStanddownHistory",STANDDOWN_ACTIVATIONS:"wfStanddownActivations",LAST_CACHE_REFRESH:"wfLastCacheRefresh",MERCHANT_RATES:"wfMerchantRates"},T="gfPreActivation",b="gfStanddownHistory",P="gfStanddownActivations",_="en",O="GIVE_FREELY_",x={async get(e){const t=`${O}${e}`;return(await browser.storage.local.get(t))[t]||null},async set(e,t){const r=`${O}${e}`;await browser.storage.local.set({[r]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${O}${e}`)):`${O}${e}`;await browser.storage.local.remove(t)}},F=()=>String("2.5.1"),I=async(e=!0)=>{const t=await x.get(y),r=await F(),i=t!==r;var n;return e&&i&&await(n=r,x.set(y,n)),i},k=o.getInstance(),D={async get(e,t,r,i=!1,n){let a=await x.get(e);const s=a;let o=!1,c=r??a?.retentionInSeconds??600;if(a&&Date.now()<=a.lastFetch+1e3*c&&!i)return{content:a.content,isStale:o};try{const r=await t(),i=n?n(r):null;null!=i&&(c=i),a=await this.set(e,r,c)}catch(e){k.error("Error getting cached value",{error:e}),o=!0}return{content:a?.content??s?.content,isStale:o}},async set(e,t,r){const i=r??600,n={content:t,lastFetch:Date.now(),retentionInSeconds:i};return await x.set(e,n),n},async clear(e){await x.remove(e)}};class U{constructor(){this.listeners=new Map,this.wildcardListeners=new Set}on(e,t){return this.addListener(e,t,!1)}once(e,t){return this.addListener(e,t,!0)}off(e,t){if(!t)return this.listeners.delete(e),void(this.wildcardListeners=new Set(Array.from(this.wildcardListeners).filter((t=>t.pattern!==e))));if(e.includes("*"))this.wildcardListeners=new Set(Array.from(this.wildcardListeners).filter((r=>!(r.pattern===e&&r.callback===t))));else{const r=this.listeners.get(e);if(r){const i=Array.from(r).filter((e=>e.callback!==t));i.length>0?this.listeners.set(e,new Set(i)):this.listeners.delete(e)}}}emit(e){const t=this.listeners.get(e.path)||new Set,r=new Set;for(const e of t)r.add(e);for(const t of this.wildcardListeners)this.matchesPattern(e.path,t.pattern)&&r.add(t);for(const t of r)t.callback(e),t.once&&this.removeListener(t)}clear(){this.listeners.clear(),this.wildcardListeners.clear()}addListener(e,t,r){const i={pattern:e,callback:t,once:r};if(e.includes("*"))this.wildcardListeners.add(i);else{const t=this.listeners.get(e);t?t.add(i):this.listeners.set(e,new Set([i]))}return()=>this.off(e,t)}removeListener(e){if(e.pattern.includes("*"))this.wildcardListeners.delete(e);else{const t=this.listeners.get(e.pattern);t&&(t.delete(e),0===t.size&&this.listeners.delete(e.pattern))}}matchesPattern(e,t){if("*"===t)return!0;const r=t.split(".").map((e=>"*"===e?"[^.]+":"**"===e?".*":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"))).join("\\.");return new RegExp(`^${r}$`).test(e)}}function L(e,t,r=""){const i=[];if(e===t)return i;if(R(e)||R(t))return e!==t&&i.push({path:r||"root",oldValue:e,newValue:t}),i;if(Array.isArray(e)&&Array.isArray(t))return JSON.stringify(e)!==JSON.stringify(t)&&i.push({path:r||"root",oldValue:e,newValue:t}),i;if(N(e)&&N(t)){const n=e,a=t,s=new Set([...Object.keys(n),...Object.keys(a)]);for(const e of s){const t=r?`${r}.${e}`:e,s=n[e],o=a[e];if(e in n)if(e in a){const e=L(s,o,t);i.push(...e)}else i.push({path:t,oldValue:s,newValue:void 0});else i.push({path:t,oldValue:void 0,newValue:o})}}else e!==t&&i.push({path:r||"root",oldValue:e,newValue:t});return i}function R(e){return null==e||"object"!=typeof e}function N(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var G;!function(e){e.CLOSED="CLOSED",e.OPEN="OPEN",e.HALF_OPEN="HALF_OPEN"}(G||(G={}));class H{constructor(e={}){this.state=G.CLOSED,this.failures=[],this.lastFailureTime=0,this.halfOpenCalls=0,this.logger=o.getInstance({minLevel:"warn"}),this.options={failureThreshold:5,recoveryTimeout:6e4,monitoringWindow:3e5,halfOpenMaxCalls:3,storageKey:"circuit_breaker_state",...e},this.storageKey=this.options.storageKey}async initialize(){await this.loadFromStorage()}static async create(e={}){const t=new H(e);return await t.initialize(),t}async loadFromStorage(){try{if("undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local){const e=(await chrome.storage.local.get(this.storageKey))[this.storageKey];e&&(this.state=e.state,this.failures=e.failures||[],this.lastFailureTime=e.lastFailureTime||0,this.halfOpenCalls=e.halfOpenCalls||0,this.cleanupOldFailures())}else if("undefined"!=typeof localStorage){const e=localStorage.getItem(this.storageKey);if(e){const t=JSON.parse(e);this.state=t.state,this.failures=t.failures||[],this.lastFailureTime=t.lastFailureTime||0,this.halfOpenCalls=t.halfOpenCalls||0,this.cleanupOldFailures()}}}catch(e){this.logger.warn("Failed to load circuit breaker state from storage:",e)}}async saveToStorage(){try{const e={state:this.state,failures:this.failures,lastFailureTime:this.lastFailureTime,halfOpenCalls:this.halfOpenCalls};"undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local?await chrome.storage.local.set({[this.storageKey]:e}):"undefined"!=typeof localStorage&&localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){this.logger.warn("Failed to save circuit breaker state to storage:",e)}}cleanupOldFailures(){const e=Date.now();this.failures=this.failures.filter((t=>e-t.timestamp<=this.options.monitoringWindow))}async execute(e,t){if(this.state===G.OPEN){if(!this.shouldAttemptRecovery()){if(t)return t();throw new Error("Circuit breaker is OPEN - service temporarily unavailable")}this.state=G.HALF_OPEN,this.halfOpenCalls=0,await this.saveToStorage()}if(this.state===G.HALF_OPEN){if(this.halfOpenCalls>=this.options.halfOpenMaxCalls)throw new Error("Circuit breaker HALF_OPEN call limit exceeded");this.halfOpenCalls+=1,await this.saveToStorage()}try{const t=await e();return await this.onSuccess(),t}catch(e){throw await this.onFailure(e),e}}async onSuccess(){this.state===G.HALF_OPEN&&(this.state=G.CLOSED,this.failures=[],await this.saveToStorage())}async onFailure(e){const t=Date.now();this.lastFailureTime=t,this.failures.push({timestamp:t,error:e.message}),this.failures=this.failures.filter((e=>t-e.timestamp<=this.options.monitoringWindow)),this.failures.length>=this.options.failureThreshold&&(this.state=G.OPEN),await this.saveToStorage()}shouldAttemptRecovery(){return Date.now()-this.lastFailureTime>=this.options.recoveryTimeout}getState(){return this.state}getFailureCount(){const e=Date.now();return this.failures.filter((t=>e-t.timestamp<=this.options.monitoringWindow)).length}async reset(){this.state=G.CLOSED,this.failures=[],this.lastFailureTime=0,this.halfOpenCalls=0,await this.saveToStorage()}async clearStorage(){"undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local?await chrome.storage.local.remove(this.storageKey):"undefined"!=typeof localStorage&&localStorage.removeItem(this.storageKey)}getStatus(){return{state:this.state,failureCount:this.getFailureCount(),nextAttemptTime:this.state===G.OPEN?this.lastFailureTime+this.options.recoveryTimeout:null}}}const $="https://cdn.givefreely.com/data/behavioral/";class M{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.mergedConfig=null,this.globalConfigRefreshInterval=null,this.partnerConfigRefreshInterval=null,this.eventEmitter=new U,this.isInitialized=!1,this.partnerCircuitBreaker=new H({failureThreshold:3,recoveryTimeout:6e4,monitoringWindow:3e5,storageKey:`gf_partner_circuit_breaker_${e}`}),this.globalCircuitBreaker=new H({failureThreshold:3,recoveryTimeout:6e4,monitoringWindow:3e5,storageKey:"gf_global_circuit_breaker"})}async initialize(){this.isInitialized||(await Promise.all([this.partnerCircuitBreaker.initialize(),this.globalCircuitBreaker.initialize()]),this.isInitialized=!0)}ensureInitialized(){if(!this.isInitialized)throw new Error("GiveFreelyConfigService must be initialized before use. Call initialize() or use create() method.")}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchPartnerConfig(){const e=await g((async()=>{const e=await fetch(`${$}${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions());if(!e)throw new Error("Failed to fetch or get from cache partner config");return this.partnerConfigRefreshInterval=e.configRefreshInterval||this.partnerConfigRefreshInterval,e}async fetchGlobalConfig(){const e=await g((async()=>{const e=await fetch(`${$}global.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config => Status code: ${e.status} .${e.statusText}`);return e.json()}),this.getRetryOptions());if(!e)throw new Error("Failed to fetch or get from cache global config",e);return this.globalConfigRefreshInterval=e.configRefreshInterval||this.globalConfigRefreshInterval,e}async getCachedConfig(){return this.mergedConfig}async getConfig(e=!1){this.ensureInitialized();let t=!1;e&&(t=await I());const[r,i]=await Promise.all([D.get(f,this.fetchPartnerConfig.bind(this),this.partnerConfigRefreshInterval,t,(e=>e?.configRefreshInterval??null)),D.get(p,this.fetchGlobalConfig.bind(this),this.globalConfigRefreshInterval,t,(e=>e?.configRefreshInterval??null))]);if(!i.content)throw new Error("Global config is required");if(!r.content)throw new Error("Partner config is required");this.partnerConfig=r.content,this.globalConfig=i.content;const n=this.mergeConfigs(JSON.parse(JSON.stringify(this.globalConfig)),JSON.parse(JSON.stringify(this.partnerConfig)));if(!n)throw new Error("Was not able to merge configs");return((e,t,r)=>{const i=[...t.merchantExclusions??[],...r.merchantExclusions??[]];e.merchantExclusions=i})(n,this.globalConfig,this.partnerConfig),this.emitConfigChanges(n),n}async clearCache(){this.ensureInitialized(),await Promise.all([D.clear(f),D.clear(p)]),this.partnerConfig=null,this.globalConfig=null,this.mergedConfig=null,this.eventEmitter.clear(),await Promise.all([this.partnerCircuitBreaker.reset(),this.globalCircuitBreaker.reset()])}getCircuitBreakerStatus(){return this.ensureInitialized(),{partner:this.partnerCircuitBreaker.getStatus(),global:this.globalCircuitBreaker.getStatus()}}mergeConfigs(e,t){if(!t)return e;if(!e)return t;const r={...e};return Object.keys(t).forEach((i=>{if(!Object.prototype.hasOwnProperty.call(t,i))return;const n=e[i],a=t[i];void 0!==a&&(Array.isArray(a)?r[i]=[...a]:r[i]=null===a||"object"!=typeof a||null===n||"object"!=typeof n?a:this.mergeConfigs(n,a))})),r}on(e,t){return this.eventEmitter.on(e,t)}once(e,t){return this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}emitConfigChanges(e){if(!this.mergedConfig)return this.mergedConfig=e,void this.eventEmitter.emit({path:"root",oldValue:null,newValue:e,config:e});const t=L(this.mergedConfig,e);for(const r of t)this.eventEmitter.emit({path:r.path,oldValue:r.oldValue,newValue:r.newValue,config:e});this.mergedConfig=e}}class z{constructor(e,t,r,i=60){this.track=async(e,t,r=!1,i=!1)=>{const n={partner:`gfLib_${this._partnerApiKey}`,eventType:e,eventData:{userId:r?void 0:this._userService?.user?.id,libVersion:F(),...t}};try{const e=JSON.stringify(n,((e,t)=>t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t)),t=await this.getEventsUrl();return t?await this.BroadcastEvent(t,e,n,i):(this._logger.info("Cant broadcast event. eventsUrl cant be retrieved from config",n,!0),!1)}catch(e){return this._logger.error("Something unexpected happened when dispatching a gf event",{error:e,event:n},!0),!1}},this.getEventsHistory=async()=>{const e=await x.get(C),t=(e=>{const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()})(-this._debounceWindowInMinutes),r=(e||[]).filter((e=>e.createdAt>t));return await x.set(C,r),r},this.shouldBroadcastEvent=async(e,t)=>!!t||!(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 x.set(C,t)},this._partnerApiKey=e,this._userService=t,this._debounceWindowInMinutes=i,this._logger=o.getInstance({title:"Analytics"}),this._configService=r}async BroadcastEvent(e,t,r,i){if(await this.shouldBroadcastEvent(t,i)){const i=await fetch(e,{headers:{"Content-Type":"application/json"},method:"POST",body:t,cache:"no-store"});return i.ok?(await this.pushEventToHistory(t),!0):(this._logger.error("Something unexpected happened when dispatching an event",{status:i.status,statusText:i.statusText,event:r},!0),!1)}return this._logger.info("This event has already been broadcasted during the past hour",r,!0),!1}async getEventsUrl(){const e=await this._configService.getCachedConfig();return e?.eventsUrl}}z.trackEvent=async(e,t,r=!1,i=!1)=>{await async function(e){return await h.runtime.sendMessage(e)}({type:d.TRACK_EVENT,payload:{eventType:e,eventData:t,anonymous:r,skipThrottling:i}})};class K{constructor(e,t){this.lastCheck=null,this.trackEvent=e,this.logger=t}async initialize(){const e=await x.get(m);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&&(this.lastCheck=Date.now(),await x.set(m,this.lastCheck),await this.trackEvent(r.checkoutPopupHealthCheck,{language:browser.i18n.getUILanguage()}))}catch(e){this.logger.error("Health check failed",{error:e instanceof Error?e.message:"Unknown error"},!0)}}}var j;!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"}(j||(j={}));class B{constructor(e,t,r){this.libraryId=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. Status code: ${i.status} .${i.statusText}`);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}?gfLibId=${this.libraryId}`,{method:"PUT",headers:{"Content-Type":"application/json","X-GF-Platform":"GFLibrary","X-AnonymousUserToken":t??""},body:JSON.stringify(e)});if(!r.ok)throw this.logger.error(`Failed to create/update anonymous user. Status code: ${r.status}. ${r.statusText}`),new Error(`Failed to create/update anonymous user. Status code: ${r.status}. ${r.statusText}`);this.logger.info("[GiveFreelyApiClient] anonymous user created/updated successfully.");const i=await r.json(),n=r.headers.get("X-AnonymousUserToken");return{resultUser:{...i,charity:{ein:i.selectedCharity,thirdPartyId:i.selectedCharityThirdPartyIdentifier,name:void 0}},resultToken:n}}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error creating anonymous user:",{error:e},!0),e}}}class V{constructor(e,t){this._giveFreelyApiClient=e,this._logger=t,this.user=null}async resetUser(){await x.remove(v),await x.remove(w)}async upsertUser(e){let t=await this.fetchUser();try{const r={selectedCharity:e?.ein,selectedCharityThirdPartyIdentifier:e?.thirdPartyId};if(!await this.shouldCreateOrUpdateUser(t,r))return t;const i=await x.get(v),{resultUser:n,resultToken:a}=await this._giveFreelyApiClient.createOrUpdateAnonymousUser(r,i);a&&await x.set(v,a),n&&(await x.set(w,n),t=n)}catch(e){this._logger.error("Error creating/updating anonymous user:",e)}return this.user=t,t}async fetchUser(){const e=await x.get(w);return this.user=e,e}async shouldCreateOrUpdateUser(e,t){return!e||e.charity?.ein!==t.selectedCharity||e.charity?.thirdPartyId!==t.selectedCharityThirdPartyIdentifier}}const W=e=>{try{return new URL(e),!0}catch{return!1}};async function q(e,t,r,i){try{const n=(await J())?.[t],a=await this.getStanddownPolicy(),s=ee(a,new URL(r).search);if(n&&n>Date.now())return e.info("Standing down because current affiliate stand down session has not expired"),X(t,void 0,!s&&null),{result:!0,reason:"sessionNotExpired"};if(ee(a,new URL(r).search))return e.info("Standing down because url has affiliate params"),X(t,void 0,!1),{result:!0,reason:"hasAffiliateParams"};if(te(a,i))return e.info("Standing down because a standdown cookie is present"),X(t,void 0,!1),{result:!0,reason:"hasAffiliateCookies"};e.info("No need to stand down.")}catch(t){e.error("Exception produced when trying to determine if it should stand down",t)}return{result:!1}}function Y(e,t){if(!this.standDownPolicy)return this.logger.warn("Could not check affiliation. No stand down policy found"),this.getStanddownPolicy().then((e=>{this.standDownPolicy=e})),!1;const r=e.some((e=>Q(this.standDownPolicy,e)))||ee(this.standDownPolicy,t);return this.logger.info("Affiliation result:",r),r}const J=async()=>x.get(b),X=async(e,t=1,r=null)=>{const i=await J()??{},n=i?.[e]??0,a=Date.now()+60*t*60*1e3;if(i[e]=a,await x.set(b,i),null!==r){const t=await Z(e);if(r||!r&&t&&a-n>2e4){const t=await x.get(P)??{};t[e]=r,await x.set(P,t)}}},Z=async e=>{const t=await x.get(P);return t?.[e]??!1},Q=(e,t)=>{if(!t)return!1;const{Domains:r}=e;return r.some((e=>t.includes(e)))},ee=(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()}`)))},te=(e,t)=>{if(!t)return!1;const{Cookies:r}=e;return!!r?.length&&r.some((e=>t.includes(e)))},re=new Set,ie=new Set,ne={urls:["<all_urls>"],types:["main_frame"]};class ae extends Error{constructor(e="Service not initialized"){super(e),this.name="UninitializedServiceError"}}const se=e=>{if(!e)throw new ae};class oe{static register(e,t){this.strategies.set(e,t)}static get(e){return this.strategies.get(e)}static exists(e){return!!function(e){return"object"==typeof e&&null!==e&&"type"in e&&"payload"in e&&"string"==typeof e.type}(e)&&this.knownMessageTypes.has(e.type)}}oe.strategies=new Map,oe.knownMessageTypes=new Set([...Object.values(d)]);const ce=e=>{let t;if(browser.webRequest){const i=(e=>{const t=e.getLogger();return({requestId:r,url:i,initiator:n})=>{try{if(re.has(r)||ie.has(r)||!W(i))return;const{hostname:a,search:s}=new URL(i);let o;n&&W(n)&&(o=new URL(n).hostname),(e.hasAffiliation([a,o],s)||e.isCustomStandownMatch([i,n]))&&(t.info("Affiliation found or custom standown match on url, adding request id to track"),re.add(r))}catch(e){t.error("Error on handleAffiliateOnBeforeRequest",e)}}})(e);browser.webRequest.onBeforeRequest.addListener(i,ne);const n=(e=>{const t=e.getLogger();return async({requestId:i,redirectUrl:n})=>{try{if(!re.has(i))return;t.info("Attempting to find active domain");const{hostname:a}=new URL(n),s=(await e.getActiveDomains()).find((e=>a===e.domain||a.endsWith(`.${e.domain}`)));if(!s)return;t.info("Found active domain. Updating standdown state"),await X(s.domain,void 0,!1),(await e.getCachedConfig()).enhancedLogging&&e.trackEvent(r.checkoutPopupStoodDown,{domain:s.domain,reason:"vendorPolicy (at webReq listener)"})}catch(e){t.error("Error on handleAffiliateOnBeforeRedirect",e)}}})(e);browser.webRequest.onBeforeRedirect.addListener(n,ne);const a=(e=>{const t=e.getLogger();return({requestId:e})=>{try{re.has(e)&&(t.info("Tracking request completed. Request Id:",e),re.delete(e))}catch(e){t.error("Error on handleAffiliateOnCompleted",e)}}})(e);browser.webRequest.onCompleted.addListener(a,ne),t=()=>{browser.webRequest.onBeforeRequest.removeListener(i),browser.webRequest.onBeforeRedirect.removeListener(n),browser.webRequest.onCompleted.removeListener(a)}}const i=function(){const t=o.getInstance(),r=(r,i,n)=>{function a(e){n(e)}const s=(async t=>(e.getLogger().debug("Received message",{type:t.type,payload:t.payload}),le(e,t)))(r,0);return s instanceof Promise?(s.then((e=>{e&&a(e)})).catch((e=>{t.warn("Async message callback error:",e)})),!0):!0===s||void 0};return h.runtime.onMessage.addListener(r),r}();return function(){t&&t(),browser.runtime.onMessage.removeListener(i)}},le=async(e,t)=>{se(e.isInitialized());const r=oe.get(t.type);if(!r)return;const i={giveFreelyService:e};return r.handle(t,i)};class ge{async handle(e,t){const{activeDomain:i,originalUrl:n,selectedCharity:a,gfCommissionUniqueId:s,openTab:o}=e.payload,{giveFreelyService:c}=t,l=c.getLogger();l.debug("Activating offer",{activeDomain:i,selectedCharity:a});try{if(i?.merchantId&&(async e=>{try{const t=await(async()=>await x.get(E)??{})();t[e]&&delete t[e],await x.set(E,t)}catch{}})(parseInt(i.merchantId)),!a?.ein||!a?.thirdPartyId)throw new Error("Missing charity information");const e=await c.upsertUser(a);l.debug("Upserted user",{currentUser:e}),e||l.info("Failed to create user. Using default bucket's user");const t=await c.getProviderPreActivation(i.provider),r=await c.generateAffiliateUrl(i,n,e,s,t);return l.debug("Generated affiliate URL",{affiliateUrl:r}),!1!==o?((async e=>{const t=h.tabs.getCurrent(),r=await t,i=await h.tabs.create({url:e,openerTabId:r?.id,active:!1,pinned:!0});await(async e=>new Promise((t=>{h.tabs.onUpdated.addListener((async function r(i,n){if(i===e&&"complete"===n.status){if(h.tabs.onUpdated.removeListener(r),!(await h.tabs.get(e)).url)return void t(!1);t(!0)}}))})))(i.id)&&setTimeout((()=>{i?.id&&h.tabs.remove(i.id)}),3e4)})(r),await c.updateStanddownHistory(i.domain,!0)):await c.updateStanddownHistoryByMerchantId(i.merchantId,!0),l.debug("Activated offer",{activeDomain:i,selectedCharity:a,gfCommissionUniqueId:s}),{type:d.ACTIVATE_OFFER,payload:{response:!0,activationLink:r}}}catch(e){return l.error("Error activating offer",{activeDomain:i,error:e}),c.trackEvent(r.checkoutPopupFailedActivation,{activeDomain:i,error:e}),{type:d.ACTIVATE_OFFER,payload:{response:!1}}}}}class he{async handle(e,t){const{urls:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=await i.getActiveDomains();if(!e||0===e.length)throw new Error("No active domains");const t={},n=r.map((async r=>{try{const{hostname:n}=new URL(r),a=e.find((e=>n===e.domain||n.endsWith(`.${e.domain}`)));if(a){const{result:e}=await i.shouldStandDown(a.domain,r);t[r]={activeDomain:a,shouldStandDown:e,currentlyActivated:await i.wasLastStandDownAnActivation(a.domain)}}}catch{}}));return await Promise.all(n),{type:d.GET_ACTIVE_DOMAINS,payload:{result:t}}}catch(e){return n.error("Error checking domain",{urls:r,error:e}),{type:d.GET_ACTIVE_DOMAINS,payload:{result:{}}}}}}class de{async handle(e,t){const{shopId:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=u,t=await x.get(e)||[];if(t.length>0&&"Merchant"in t[0].domain)return n.warn("Detected legacy WildfireActiveDomain in Shopify storage — data should have been pruned. Clearing stale entries."),await x.remove(e),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}};const i=t.find((e=>e.shopId===r));return i?(n.debug("Found domain for shop ID",{shopId:r,domain:i.domain}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!0,domain:i.domain,shopInfo:i}}):(n.debug("No domain found for shop ID",{shopId:r}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}})}catch(e){return n.error("Error getting domain for shop ID",{shopId:r,error:e}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}}}}}class ue{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger();try{const e=r.getConfig()?.gfDataUrl;if(!e)return i.warn("gfDataUrl is not configured — skipping GF data fetch"),{type:d.GET_GF_DATA,payload:{data:null}};i.debug("Fetching GF data",{url:e});const t=await g((async()=>{const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}),{logger:i,operationName:"GetGfData"});return i.debug("GF data fetched successfully",{data:t}),{type:d.GET_GF_DATA,payload:{data:t}}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return i.error(`Failed to fetch GF data: ${t}`,{error:e},!0),{type:d.GET_GF_DATA,payload:{data:null}}}}}class me{async handle(e,t){const{lang:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();n.debug("Getting language strings",{lang:r});try{const e=await i.getLanguage(r);return n.debug("Language strings fetched",{language:e}),{type:d.GET_LANGUAGE_CONTENT,payload:{translations:e.translations,charities:e.charities}}}catch(e){return n.error("Error getting language strings",{error:e}),{type:d.GET_LANGUAGE_CONTENT,payload:{translations:null,charities:null}}}}}class fe{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger(),n=await r.getCachedConfig();try{return i.debug("Fetching popup config"),{type:d.GET_POPUP_CONFIG,payload:{config:n}}}catch(e){return i.error("Error fetching popup config",{error:e}),{type:d.GET_POPUP_CONFIG,payload:{config:null}}}}}class pe{async handle(e,t){const{days:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=new Date;return e.setDate(e.getDate()+r),await x.set("popup_hide",{popupHide:e.getTime()}),n.debug("Popup hidden",{days:r,expiry:e}),{type:d.HIDE_POPUP,payload:{ack:!0}}}catch(e){return n.error("Error hiding popup",{days:r,error:e}),{type:d.HIDE_POPUP,payload:{ack:!1}}}}}class Ae{async handle(e,t){const{hostname:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const{merchantExclusions:e}=await i.getConfig();if(n.debug("Checking hostname",{hostname:r}),i.healthCheck(),e.some((e=>e.disableDomain&&(r===e.domain||r.endsWith(`.${e.domain}`)))))return n.debug("Hostname is in merchant exclusions",{hostname:r}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!1,domain:void 0}};const t=await i.getActiveDomains();n.debug("Retrieved active domains",{count:t.length});const a=t.find((e=>r===e.domain||r.endsWith(`.${e.domain}`)));return n.debug("Domain check result",{hostname:r,isActive:!!a}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!!a,domain:a}}}catch(e){return n.error("Error checking domain",{hostname:r,error:e}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!1,domain:void 0}}}}}class ye{async handle(e,t){const{currentUrl:i,searchResults:n,source:a}=e.payload,{giveFreelyService:s}=t,o=s.getLogger();try{const e=await s.getActiveDomains();o.debug("Finding merchants in search results",{currentUrl:i});const c=n.filter((t=>{try{const{hostname:r}=new URL(t.url);return e.some((e=>e.domain===r||r.endsWith(`.${e.domain}`)))}catch{return o.debug("Couldn't parse the following search result url",{x:t}),!1}}));if(o.info("Number of merchants identified in the search result",{number:c.length}),c.length>0){const e=Math.floor(Math.random()*Date.now());for(const n of c)t.giveFreelyService.trackEvent(r.checkoutPopupMerchantInResultsFound,{source:a,searchResultsId:e,currentUrl:i,searchResultUrl:n.url,sponsored:n.isSponsored},!0)}return{type:d.LOG_MERCHANTS_IN_SEARCH_RESULTS,payload:{result:!0}}}catch(e){return o.error("Error sending logs for merchants in search results",{currentUrl:i,error:e}),{type:d.LOG_MERCHANTS_IN_SEARCH_RESULTS,payload:{result:!1}}}}}class we{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger();try{return await x.set("gf_partner_serp_muted",!0),i.debug("Partner Serp box hidden"),{type:d.MUTE_PARTNER_SERP_BOX,payload:{ack:!0}}}catch(e){return i.error("Error hiding partner serp box",{error:e}),{type:d.MUTE_PARTNER_SERP_BOX,payload:{ack:!1}}}}}class ve{async handle(e,t){const r=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=u;let t=await x.get(e)||[];t.length>0&&"Merchant"in t[0].domain&&(n.warn("Detected legacy WildfireActiveDomain in Shopify storage — data should have been pruned. Clearing stale entries."),t=[],await x.remove(e));const i=t.findIndex((e=>e.shopId===r.shopId));return i>=0?t[i]=r:t.push(r),await x.set(e,t),n.debug("Stored Shopify shop ID",{shopInfo:r}),{type:d.STORE_SHOPIFY_SHOP_ID,payload:{success:!0}}}catch(e){return n.error("Error storing Shopify shop ID",{shopInfo:r,error:e}),{type:d.STORE_SHOPIFY_SHOP_ID,payload:{success:!1}}}}}class Ce{async handle(e,t){const{activeDomain:r,url:i,cookies:n}=e.payload,{giveFreelyService:a}=t,s=a.getLogger();s.debug("Checking if we should stand down",{activeDomain:r});try{const e=await a.shouldStandDown(r,i,n);return{type:d.SHOULD_STAND_DOWN,payload:e}}catch(e){return s.error("Error checking if we should stand down. Returning false",{activeDomain:r,error:e}),{type:d.SHOULD_STAND_DOWN,payload:{result:!1}}}}}class Ee{async handle(e,t){const{eventType:r,eventData:i,anonymous:n,skipThrottling:a}=e.payload,{giveFreelyService:s}=t,o=s.getLogger();o.debug("Broadcasting event",{eventType:r,eventData:i,anonymous:n,skipThrottling:a});try{const e=await s.trackEvent(r,i,n,a);return{type:d.TRACK_EVENT,payload:{result:e}}}catch(e){return o.error("Error broadcasting event. Returning false",{eventType:r,eventData:i,error:e}),{type:d.TRACK_EVENT,payload:{result:!1}}}}}const Se=o.getInstance(),Te=async()=>await x.get(A)||(async()=>{Se.debug("detecting country");const e={method:"GET",headers:{"Content-Type":"application/json",Authorization:"Basic OTEzOTkxOnFlYmpaWF9DOGNRY0lxSHA4WTVjNGxzU1pRSlM2VW9MMExzTF9tbWs="}};try{const t=await fetch("https://geoip.maxmind.com/geoip/v2.1/country/me",e);if(Se.debug("Received geolocation response",{status:t.status}),!t.ok)return void Se.error("Failed to get geolocation data",{status:t.status,statusText:t.statusText});const r=await t.json();if(!r)throw new Error("There was an error fetching geoip look up");return await x.set(A,r.country.iso_code),r.country.iso_code}catch(e){return void Se.error("Failed to get geolocation data",{error:e},!0)}})(),be="https://cdn.givefreely.com/data/language",Pe=async(e,t,r,i,n=[],a=!1)=>{const s=(n??[]).includes(r)?_:r;e.debug(`Requested lang ${r} and current lang ${s}`);const o=`lang-${_}`,c=await D.get(o,(async()=>(e.debug(`Fetching default language ${_} for partner ${t}`),_e(t,_))),i||600,a);if(!c.content)throw new Error(`Failed to fetch default language ${_} and no cache version available`);if(_===s)return c.content;const l=`lang-${s}`,g=await D.get(l,(async()=>(e.debug(`Fetching language ${s} for partner ${t}`),_e(t,s))),i||600,a);if(!g.content)return c.content;const h=Fe(c.content,g.content);return await D.set(l,h,i||600),h},_e=async(e,t)=>{const r=`/global-${t}.json`,i=`/${e}/${t}.json`,[n,a]=await Promise.allSettled([Oe(`${be}${r}`),Oe(`${be}${i}`)]);let s,o;"fulfilled"===n.status&&(s=n.value),"fulfilled"===a.status&&(o=a.value);const c=xe(s,o);return{translations:c.translations,charities:c.charities}},Oe=async e=>{const t=await fetch(e,{cache:"no-store"});if(!t.ok)throw new Error(`Failed to fetch partner language file ${e}. Status: ${t.status}. Reason: ${t.statusText}`);return t.json()},xe=(e,t)=>({translations:{...e?.translations??{},...t??{}},charities:{...e?.charities??{}}}),Fe=(e,t)=>({translations:{...e.translations,...t.translations},charities:{...e.charities,...t.charities}});class Ie{constructor(e,t,r,i){this._logger=e,this.feedUrl=t,this.activationUrl=r,this.preActivationUrl=i}async getRawFeed(){try{const e=`${this.feedUrl}`,t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch feed from ${e}. Status ${t.status}. ${t.statusText}`);return t.json()}catch(e){throw this._logger.error("Failed to fetch the feed",{err:e}),new Error("Failed to fetch the feed")}}async preActivation(e,t){try{const r=await fetch(this.preActivationUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({partnerId:e,...t&&{provider:t}})});if(!r.ok)throw new Error(`Failed to pre-activate. Status ${r.status}. ${r.statusText}`);return r.json()}catch(e){throw this._logger.error("Failed to pre-activate",{err:e}),new Error("Failed to pre-activate")}}async generateAffiliateUrl(e,t,r,i,n,a){try{const s=await fetch(`${this.activationUrl}?redirect=false`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e.provider,partnerId:i,userId:r?.id||"",ein:r?.charity?.ein||"",tpi:r?.charity?.thirdPartyId||"",url:t,gfCommissionUniqueId:n,merchantId:e.merchantId,domainId:e.id,providerCustom:a})});if(!s.ok)throw new Error(`Failed to generate affiliate url. Status ${s.status}. ${s.statusText}`);return(await s.json()).affiliateLink}catch(e){throw this._logger.error("Failed to generate affiliate url",{err:e}),new Error("Failed to generate affiliate url")}}}class ke{constructor(e){this.raw=e}static mapKind(e){return 1===e?"FLAT":"PERCENTAGE"}static mapOfferRate(e){return{Kind:ke.mapKind(e.k),Amount:e.a,Name:e.n,Currency:e.c??void 0}}static fromRawArray(e){return e.map((e=>new ke(e)))}static fromRaw(e){return new ke(e)}get id(){return parseInt(this.raw.di,10)||0}get domain(){return this.raw.d}get provider(){return this.raw.p}get merchantId(){return this.raw.mi}get merchantName(){return this.raw.mn}get commission(){return{amount:this.raw.c.a,kind:ke.mapKind(this.raw.c.k)}}get rates(){return this.raw.r?.map(ke.mapOfferRate)??[]}toRaw(){return this.raw}toJSON(){return{id:this.id,domain:this.domain,provider:this.provider,merchantId:this.merchantId,merchantName:this.merchantName,commission:this.commission,rates:this.rates}}}class De{constructor(e,t,r=600){this.standDownPolicy=null,this.shouldStandDown=q.bind(this),this.hasAffiliation=Y.bind(this),this.updateStanddownHistory=X,this.refreshInterval=r,this.giveFreelyFeedClient=e,this.logger=t}async getActiveDomains(e=!1){try{const t=await D.get("gfFeed",(async()=>this.fetchRawActiveDomains()),this.refreshInterval,e);if(!t.content)throw new Error("Failed to retrieve feed from cache");return ke.fromRawArray(t.content)}catch(e){return this.logger.error("Failed to get active domains:",e),[]}}async preActivation(e,t){return this.giveFreelyFeedClient.preActivation(e,t)}async generateAffiliateUrl(e,t,r,i,n,a){return this.giveFreelyFeedClient.generateAffiliateUrl(e,t,r,i,n,a)}async fetchRawActiveDomains(){const e=await this.giveFreelyFeedClient.getRawFeed();return this.standDownPolicy=e.standdownRules,e.activeDomains}async getStanddownPolicy(){if(this.standDownPolicy)return this.standDownPolicy;const e=await this.giveFreelyFeedClient.getRawFeed();return this.standDownPolicy=e.standdownRules,this.standDownPolicy}static async createGiveFreelyFeedService(e,t){e.debug("Initializing givefreely feed service with config",t);const{feedUrl:r,activationUrl:i,preActivationUrl:n}=t.multiAffiliate??{};if(!r||!i||!n)throw new Error("multiAffiliate config is missing required URLs (feedUrl, activationUrl, preActivationUrl)");const a=new Ie(e,r,i,n),s=new De(a,e,t.multiAffiliate?.feedRefreshInterval);return await s.getActiveDomains(),s}}async function Ue(e){const t=[...Object.values(S),u];try{await Promise.all(t.map((e=>x.remove(e)))),e.info("Pruned legacy Wildfire storage keys",{keys:t})}catch(t){e.debug("Failed to prune legacy Wildfire storage keys",t)}}var Le=Object.freeze({__proto__:null,generateAffiliateUrl:async function(e,t,r,i,n){return se(this.state.initialized),this.state.giveFreelyFeedService.generateAffiliateUrl(e,t,r,this.state.partnerApiKey,i,n)},getActiveDomains:async function(){return se(this.state.initialized),this.state.giveFreelyFeedService.getActiveDomains()},pruneLegacyWildfireStorage:Ue});async function Re(e,t,r){try{const i={...t};for(const e of r)delete i[e];return await x.set(T,i),e.info("Pruned preActivation providers",{providers:r}),i}catch(r){return e.debug("Failed to prune preActivation providers",r),t}}var Ne=Object.freeze({__proto__:null,getCurrentUser:function(){return se(this.state.initialized),this.state.giveFreelyUserService.user},getLanguage:async function(e){return se(this.state.initialized),Pe(this.logger,this.state.partnerApiKey,e,this.state.config?.configRefreshInterval,this.state.config?.ignoredLanguages)},getProviderPreActivation:async function(e){if(se(this.state.initialized),this.state.preActivation&&e in this.state.preActivation)return this.state.preActivation[e];const t=await x.get(T);if(t&&e in t)return this.state.preActivation=t,t[e];const r=(await this.state.giveFreelyFeedService.preActivation(this.state.partnerApiKey,e))[e]??{},i={...t||{},...this.state.preActivation||{},[e]:r};return this.state.preActivation=i,await x.set(T,i),r},initializePreActivation:async function(e){const t=await x.get(T);if(t&&Object.keys(t).length>0)return this.state.preActivation=t,t;const r=await e.preActivation(this.state.partnerApiKey);return this.state.preActivation=r,await x.set(T,r),r},prunePreActivationProviders:Re,upsertUser:function(e){return se(this.state.initialized),this.state.giveFreelyUserService.upsertUser(e)}});async function Ge(e=async()=>(this.logger.debug("Using default partnerFilter."),!0)){if(!this.state.initialized){this.logger.info("Starting initialization with mutex protection");try{await this.dependencies.configService.initialize();const t=await I(!1),r=await this.dependencies.configService.getConfig(!0);this.logger.configure({enabled:r.loggingEnabled??!0,minLevel:r.backgroundMinLogLevel??"error"}),this.logger.info("Initializing GiveFreelyService",{partnerApiKey:this.partnerApiKey}),!r.multiAffiliate?.skipWildfirePruning&&t&&await Ue(this.logger);const i=await De.createGiveFreelyFeedService(this.logger,r);this.state.healthCheck=new K(this.trackEvent.bind(this),this.logger),await this.state.healthCheck.initialize();const n=new B(this.partnerApiKey,r,this.logger);this.state.giveFreelyUserService=new V(n,this.logger),await this.state.giveFreelyUserService.fetchUser(),this.state.giveFreelyUserService.user?.id||await this.state.giveFreelyUserService.upsertUser(),this.state.analytics=new z(this.partnerApiKey,this.state.giveFreelyUserService,this.dependencies.configService);try{if(r.multiAffiliate?.prunePreActivationProviders?.length){const e=await x.get(T);e&&await Re(this.logger,e,r.multiAffiliate.prunePreActivationProviders)}await this.initializePreActivation(i)}catch(e){this.logger.debug("Pre-activation initialization failed — will retry on first offer activation",e)}oe.register(d.IS_ACTIVE_DOMAIN,new Ae),oe.register(d.GET_POPUP_CONFIG,new fe),oe.register(d.HIDE_POPUP,new pe),oe.register(d.SHOULD_STAND_DOWN,new Ce),oe.register(d.TRACK_EVENT,new Ee),oe.register(d.ACTIVATE_OFFER,new ge),oe.register(d.STORE_SHOPIFY_SHOP_ID,new ve),oe.register(d.GET_DOMAIN_BY_SHOP_ID,new de),oe.register(d.GET_LANGUAGE_CONTENT,new me),oe.register(d.LOG_MERCHANTS_IN_SEARCH_RESULTS,new ye),oe.register(d.GET_ACTIVE_DOMAINS,new he),oe.register(d.MUTE_PARTNER_SERP_BOX,new we),oe.register(d.GET_GF_DATA,new ue),await(async e=>{try{await Te()}catch(t){e.debug("Failed to get geolocation data",{error:t})}})(this.logger),await(async(e,t,r)=>{t.purgeLanguages&&t.purgeLanguages.length>0&&await Promise.all(t.purgeLanguages.flatMap((e=>[D.clear(`lang-${e}`),D.clear(`global-${e}`)]))),g((async()=>{e.debug("Initializing default language with partner API key",{partnerApiKey:r}),await Pe(e,r,_,t.configRefreshInterval)}))})(this.logger,r,this.partnerApiKey),this.state=((e,t)=>{const{partnerFilter:r,config:i,giveFreelyFeedService:n}=t;return{...e,initialized:!0,partnerFilter:r,config:i,giveFreelyFeedService:n}})(this.state,{partnerFilter:e,config:r,giveFreelyFeedService:i}),this.logger.addTransport(new a(this)),this.cleanupListeners=ce(this),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}`)}}}function He(){return this.state.initialized}var $e={config:Object.freeze({__proto__:null,getCachedConfig:async function(){return se(this.state.initialized),this.state.config=await this.dependencies.configService.getConfig(),this.logger.configure({minLevel:this.state.config.backgroundMinLogLevel??"error"}),this.state.config},getConfig:function(){return se(this.state.initialized),this.state.config},offConfigChange:function(e,t){se(this.state.initialized),this.dependencies.configService.off(e,t)},onConfigChange:function(e,t){return se(this.state.initialized),this.dependencies.configService.on(e,t)},onceConfigChange:function(e,t){return se(this.state.initialized),this.dependencies.configService.once(e,t)}}),merchants:Le,observability:Object.freeze({__proto__:null,getLogger:function(){return se(this.state.initialized),this.logger},healthCheck:async function(){se(this.state.initialized),await this.state.healthCheck.check()},trackEvent:function(e,t,r=!1,i=!1){return se(this.state.initialized),this.state.analytics.track(e,t,r,i)}}),standdown:Object.freeze({__proto__:null,hasAffiliation:function(e,t){if(!this.state.giveFreelyFeedService)return this.logger.warn("GiveFreely Feed service not initialized yet"),!1;const r=this.state.giveFreelyFeedService.hasAffiliation(e,t);return r&&this.logger.info("Affiliation identified"),r},isCustomStandownMatch:function(e){const t=e.some((e=>this.getConfig().customStandownPolicy?.urlRegex?.some((t=>!!e&&function(e,t){return new RegExp(t).test(e)}(e,t)))));return t&&this.logger.info("Custom Standown identified"),t},shouldStandDown:async function(e,t,r){se(this.state.initialized);const i=new URL(t);if(!await this.state.partnerFilter(i.hostname))return this.logger.info("Should standdown due to partner filter."),{result:!0,reason:"partner filter"};if(this.getConfig().merchantExclusions.some((t=>t.mutePopups&&e===t.domain)))return this.logger.info("Should standdown due to merchant exclusions"),{result:!0,reason:"merchant exclusions"};const n=await this.state.giveFreelyFeedService.shouldStandDown(this.logger,e,t,r);return n.result&&this.logger.info(`Should standdown due to ${n.reason}`),n},updateStanddownHistory:function(e,t=null){return se(this.state.initialized),X(e,void 0,t)},updateStanddownHistoryByMerchantId:function(e,t=null){return se(this.state.initialized),this.state.giveFreelyFeedService.getActiveDomains().then((r=>{const i=r.find((t=>t.merchantId===e));if(i)return X(i.domain,void 0,t)}))},wasLastStandDownAnActivation:async function(e){return Z(e)}}),identity:Ne};class Me{constructor(e){this.partnerApiKey=e,this.cleanupListeners=null,this.initialize=Ge.bind(this),this.isInitialized=He.bind(this),this.getConfig=$e.config.getConfig.bind(this),this.getCachedConfig=$e.config.getCachedConfig.bind(this),this.onConfigChange=$e.config.onConfigChange.bind(this),this.onceConfigChange=$e.config.onceConfigChange.bind(this),this.offConfigChange=$e.config.offConfigChange.bind(this),this.getLogger=$e.observability.getLogger.bind(this),this.healthCheck=$e.observability.healthCheck.bind(this),this.trackEvent=$e.observability.trackEvent.bind(this),this.getProviderPreActivation=$e.identity.getProviderPreActivation.bind(this),this.initializePreActivation=$e.identity.initializePreActivation.bind(this),this.upsertUser=$e.identity.upsertUser.bind(this),this.getCurrentUser=$e.identity.getCurrentUser.bind(this),this.getLanguage=$e.identity.getLanguage.bind(this),this.getActiveDomains=$e.merchants.getActiveDomains.bind(this),this.generateAffiliateUrl=$e.merchants.generateAffiliateUrl.bind(this),this.shouldStandDown=$e.standdown.shouldStandDown.bind(this),this.updateStanddownHistory=$e.standdown.updateStanddownHistory.bind(this),this.updateStanddownHistoryByMerchantId=$e.standdown.updateStanddownHistoryByMerchantId.bind(this),this.wasLastStandDownAnActivation=$e.standdown.wasLastStandDownAnActivation.bind(this),this.hasAffiliation=$e.standdown.hasAffiliation.bind(this),this.isCustomStandownMatch=$e.standdown.isCustomStandownMatch.bind(this),this.dependencies={configService:new M(e)},this.logger=o.getInstance(),this.logger.configure({enabled:!0,title:"Background - GiveFreelyService"}),this.state=(e=>({initialized:!1,giveFreelyFeedService:null,partnerFilter:null,config:null,preActivation:null,analytics:null,giveFreelyUserService:null,partnerApiKey:e,healthCheck:null}))(e)}async destroy(){var e;this.logger.info("Destroying GiveFreelyService"),await Promise.all([this.dependencies.configService.clearCache(),this.state.giveFreelyUserService?.resetUser()]),this.cleanupListeners&&(this.cleanupListeners(),this.logger.info("Event listeners cleared."),this.cleanupListeners=null),this.state=(e=this.state,{...e,initialized:!1,giveFreelyFeedService:null,partnerFilter:null,analytics:null,config:null})}}class GiveFreelyService{constructor(e){this.partnerApiKey=e,this.initialize=e=>this._coreService.initialize(e),this.destroy=()=>this._coreService.destroy(),this._coreService=new Me(e)}}const ze=e=>oe.exists(e);export{GiveFreelyService,browser,ze as isGiveFreelyMessage};
|
|
1
|
+
function e(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 t={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 n=(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",s=(e,t,r)=>new Proxy(t,{apply:(t,i,n)=>r.call(i,e,...n)});let o=Function.call.bind(Object.prototype.hasOwnProperty);const c=(e,t={},r={})=>{let i=Object.create(null),l={has:(t,r)=>r in e||r in i,get(l,g,h){if(g in i)return i[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(o(r,g)){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,s)=>{if(t.fallbackToNoCallback)try{r[e](...i,n({resolve:a,reject:s},t))}catch(n){console.warn(`${e} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `,n),r[e](...i),t.fallbackToNoCallback=!1,t.noCallback=!0,a()}else t.noCallback?(r[e](...i),a()):r[e](...i,n({resolve:a,reject:s},t))}))})(g,r[g]);d=s(e,e[g],t)}else d=d.bind(e);else if("object"==typeof d&&null!==d&&(o(t,g)||o(r,g)))d=c(d,t[g],r[g]);else{if(!o(r,"*"))return Object.defineProperty(i,g,{configurable:!0,enumerable:!0,get:()=>e[g],set(t){e[g]=t}}),d;d=c(d,t[g],r["*"])}return i[g]=d,d},set:(t,r,n,a)=>(r in i?i[r]=n:e[r]=n,!0),defineProperty:(e,t,r)=>Reflect.defineProperty(i,t,r),deleteProperty:(e,t)=>Reflect.deleteProperty(i,t)},g=Object.create(e);return new Proxy(g,l)},l=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))}}),g=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 n,a,s=!1,o=new Promise((e=>{n=function(t){s=!0,e(t)}}));try{a=e(t,r,n)}catch(e){a=Promise.reject(e)}const c=!0!==a&&((l=a)&&"object"==typeof l&&"function"==typeof l.then);var l;if(!0!==a&&!c&&!s)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},n)=>{e.runtime.lastError?e.runtime.lastError.message===t?i():r(new Error(e.runtime.lastError.message)):n&&n.__mozWebExtensionPolyfillReject__?r(new Error(n.message)):i(n)},u=(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 n=d.bind(null,{resolve:e,reject:t});i.push(n),r.sendMessage(...i)}))},m={devtools:{network:{onRequestFinished:l(g)}},runtime:{onMessage:l(h),onMessageExternal:l(h),sendMessage:u.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:u.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,m,r)};e.exports=r(chrome)}}(t);var r,i,browser=e(t.exports);class n{constructor(){this.isLocal=!0}log({level:e,message:t,timestamp:r,data:i,title:a}){let s;switch(e){case"debug":default:s="log";break;case"info":s="info";break;case"warn":s="warn";break;case"error":case"critical":case"fatal":s="error"}const o=a?`[${a}]`:"";void 0!==i?console[s](`[${r}] - ${n.LOGGER_PREFIX} ${o} ${t}`,i):console[s](`[${r}] - ${n.LOGGER_PREFIX} ${o} ${t}`)}}n.LOGGER_PREFIX="[DonationPopup] -",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",e.checkoutPopupWhyAmISeeingThisClicked="CHECKOUT-POPUP-WHY-AM-I-SEEING-THIS-CLICKED",e.checkoutPopupLooserExtension="CHECKOUT-POPUP-LOOSER-EXTENSION",e.checkoutPopupActiveDomain="CHECKOUT-POPUP-ACTIVE-DOMAIN",e.checkoutPopupSiteMatches="CHECKOUT-POPUP-SITE-MATCHES",e.checkoutPopupMerchantInResultsFound="CHECKOUT-MERCHANT-IN-RESULTS-FOUND",e.checkoutPopupNotShownPerViewportSize="CHECKOUT-POPUP-NOT-SHOWN-PER-VIEWPORT-SIZE",e.checkoutPopupHiddenProgrammatically="CHECKOUT-POPUP-HIDDEN-PROGRAMMATICALLY",e.checkoutPopupGoogleSearch="CHECKOUT-POPUP-GOOGLE-SEARCH",e.checkoutPopupGooglePartnerAnnCreated="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-CREATED",e.checkoutPopupGooglePartnerAnnClicked="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-CLICKED",e.checkoutPopupGooglePartnerAnnHidden="CHECKOUT-POPUP-GOOGLE-PARTNER-ANN-HIDDEN",e.checkoutPopupStoodDown="CHECKOUT-POPUP-STOOD-DOWN"}(r||(r={})),function(e){e.libLog="GFLIB-LOG"}(i||(i={}));class a{constructor(e){this.isLocal=!1,this.backgroundService=e}log({level:e,message:t,data:r,title:n}){this.backgroundService.trackEvent(i.libLog,{log:{level:e,message:t,data:r,title:n}})}}const s=["debug","info","warn","error","critical","fatal"];class o{constructor(e){this.config={minLevel:e?.minLevel??"error",enabled:e?.enabled??!1,transports:e?.transports??[new n],title:e?.title??""}}static getInstance(e){return o.instance||(o.instance=new o(e)),o.instance}configure(e){this.config={...this.config,...e}}shouldLog(e){return!!this.config.enabled&&s.indexOf(e)>=s.indexOf(this.config.minLevel)}createLogMessage(e,t,r){return{level:e,version:"2.5.1",message:t,timestamp:(new Date).toISOString(),data:r,title:this.config.title}}log(e,t,r,i){if(!this.shouldLog(e))return;const n=this.createLogMessage(e,t,i);this.config.transports.filter((e=>!r||e.isLocal)).forEach((e=>e.log(n)))}debug(e,t,r=!1){this.log("debug",e,r,t)}info(e,t,r=!1){this.log("info",e,r,t)}warn(e,t,r=!1){this.log("warn",e,r,t)}error(e,t,r=!1){this.log("error",e,r,t)}critical(e,t,r=!1){this.log("critical",e,r,t)}fatal(e,t,r=!1){this.log("fatal",e,r,t)}addTransport(e){this.config.transports.push(e)}clearTransports(){this.config.transports=[]}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}}const c=3,l=e=>1e3*e;async function g(e,t={},r){const{maxAttempts:i=c,delayFn:n=l}=t;let a=null;for(let t=1;t<=i;t+=1)try{return await e()}catch(e){a=e,t<i&&await new Promise((e=>{setTimeout(e,n(t))}))}throw a&&t.logger&&t.operationName&&t.logger.error(`Operation ${t.operationName} failed after ${i} attempts.`,a,!0),a||new Error("Operation failed after multiple attempts")}const h=browser,d={TRACK_EVENT:"GF_TRACK_EVENT",HIDE_POPUP:"GF_HIDE_POPUP",GET_POPUP_CONFIG:"GF_GET_POPUP_CONFIG",IS_ACTIVE_DOMAIN:"GF_IS_ACTIVE_DOMAIN",LOG_MERCHANTS_IN_SEARCH_RESULTS:"GF_LOG_MERCHANTS_IN_SEARCH_RESULTS",SHOULD_STAND_DOWN:"GF_SHOULD_STAND_DOWN",ACTIVATE_OFFER:"GF_ACTIVATE_OFFER",STORE_SHOPIFY_SHOP_ID:"GF_STORE_SHOPIFY_SHOP_ID",GET_DOMAIN_BY_SHOP_ID:"GF_GET_DOMAIN_BY_SHOP_ID",GET_LANGUAGE_CONTENT:"GF_GET_LANGUAGE_CONTENT",GET_ACTIVE_DOMAINS:"GF_GET_ACTIVE_DOMAINS",MUTE_PARTNER_SERP_BOX:"GF_MUTE_PARTNER_SERP_BOX",GET_GF_DATA:"GF_GET_GF_DATA"},u="shopify_shop_ids",m="gf_last_health_check",f="gf_partner_config",p="gf_global_config",A="countryCode",y="version",w="gf_anonymous_user_info",v="gf_anonymous_encrypted_token",C="gf_event_history",E="gf_popup_everywhere",S={DEVICE:"wfDevice",DOMAINS:"wfDomains",STANDDOWN_POLICY:"wfStanddownPolicy",STANDDOWN_HISTORY:"wfStanddownHistory",STANDDOWN_ACTIVATIONS:"wfStanddownActivations",LAST_CACHE_REFRESH:"wfLastCacheRefresh",MERCHANT_RATES:"wfMerchantRates"},T="gfPreActivation",b="gfStanddownHistory",P="gfStanddownActivations",_="en",O="GIVE_FREELY_",x={async get(e){const t=`${O}${e}`;return(await browser.storage.local.get(t))[t]||null},async set(e,t){const r=`${O}${e}`;await browser.storage.local.set({[r]:t})},async remove(e){const t=Array.isArray(e)?e.map((e=>`${O}${e}`)):`${O}${e}`;await browser.storage.local.remove(t)}},F=()=>String("2.5.1"),I=async(e=!0)=>{const t=await x.get(y),r=await F(),i=t!==r;var n;return e&&i&&await(n=r,x.set(y,n)),i},k=o.getInstance(),D={async get(e,t,r,i=!1,n){let a=await x.get(e);const s=a;let o=!1,c=r??a?.retentionInSeconds??600;if(a&&Date.now()<=a.lastFetch+1e3*c&&!i)return{content:a.content,isStale:o};try{const r=await t(),i=n?n(r):null;null!=i&&(c=i),a=await this.set(e,r,c)}catch(e){k.error("Error getting cached value",{error:e}),o=!0}return{content:a?.content??s?.content,isStale:o}},async set(e,t,r){const i=r??600,n={content:t,lastFetch:Date.now(),retentionInSeconds:i};return await x.set(e,n),n},async clear(e){await x.remove(e)}};class U{constructor(){this.listeners=new Map,this.wildcardListeners=new Set}on(e,t){return this.addListener(e,t,!1)}once(e,t){return this.addListener(e,t,!0)}off(e,t){if(!t)return this.listeners.delete(e),void(this.wildcardListeners=new Set(Array.from(this.wildcardListeners).filter((t=>t.pattern!==e))));if(e.includes("*"))this.wildcardListeners=new Set(Array.from(this.wildcardListeners).filter((r=>!(r.pattern===e&&r.callback===t))));else{const r=this.listeners.get(e);if(r){const i=Array.from(r).filter((e=>e.callback!==t));i.length>0?this.listeners.set(e,new Set(i)):this.listeners.delete(e)}}}emit(e){const t=this.listeners.get(e.path)||new Set,r=new Set;for(const e of t)r.add(e);for(const t of this.wildcardListeners)this.matchesPattern(e.path,t.pattern)&&r.add(t);for(const t of r)t.callback(e),t.once&&this.removeListener(t)}clear(){this.listeners.clear(),this.wildcardListeners.clear()}addListener(e,t,r){const i={pattern:e,callback:t,once:r};if(e.includes("*"))this.wildcardListeners.add(i);else{const t=this.listeners.get(e);t?t.add(i):this.listeners.set(e,new Set([i]))}return()=>this.off(e,t)}removeListener(e){if(e.pattern.includes("*"))this.wildcardListeners.delete(e);else{const t=this.listeners.get(e.pattern);t&&(t.delete(e),0===t.size&&this.listeners.delete(e.pattern))}}matchesPattern(e,t){if("*"===t)return!0;const r=t.split(".").map((e=>"*"===e?"[^.]+":"**"===e?".*":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"))).join("\\.");return new RegExp(`^${r}$`).test(e)}}function L(e,t,r=""){const i=[];if(e===t)return i;if(R(e)||R(t))return e!==t&&i.push({path:r||"root",oldValue:e,newValue:t}),i;if(Array.isArray(e)&&Array.isArray(t))return JSON.stringify(e)!==JSON.stringify(t)&&i.push({path:r||"root",oldValue:e,newValue:t}),i;if(N(e)&&N(t)){const n=e,a=t,s=new Set([...Object.keys(n),...Object.keys(a)]);for(const e of s){const t=r?`${r}.${e}`:e,s=n[e],o=a[e];if(e in n)if(e in a){const e=L(s,o,t);i.push(...e)}else i.push({path:t,oldValue:s,newValue:void 0});else i.push({path:t,oldValue:void 0,newValue:o})}}else e!==t&&i.push({path:r||"root",oldValue:e,newValue:t});return i}function R(e){return null==e||"object"!=typeof e}function N(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var G;!function(e){e.CLOSED="CLOSED",e.OPEN="OPEN",e.HALF_OPEN="HALF_OPEN"}(G||(G={}));class H{constructor(e={}){this.state=G.CLOSED,this.failures=[],this.lastFailureTime=0,this.halfOpenCalls=0,this.logger=o.getInstance({minLevel:"warn"}),this.options={failureThreshold:5,recoveryTimeout:6e4,monitoringWindow:3e5,halfOpenMaxCalls:3,storageKey:"circuit_breaker_state",...e},this.storageKey=this.options.storageKey}async initialize(){await this.loadFromStorage()}static async create(e={}){const t=new H(e);return await t.initialize(),t}async loadFromStorage(){try{if("undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local){const e=(await chrome.storage.local.get(this.storageKey))[this.storageKey];e&&(this.state=e.state,this.failures=e.failures||[],this.lastFailureTime=e.lastFailureTime||0,this.halfOpenCalls=e.halfOpenCalls||0,this.cleanupOldFailures())}else if("undefined"!=typeof localStorage){const e=localStorage.getItem(this.storageKey);if(e){const t=JSON.parse(e);this.state=t.state,this.failures=t.failures||[],this.lastFailureTime=t.lastFailureTime||0,this.halfOpenCalls=t.halfOpenCalls||0,this.cleanupOldFailures()}}}catch(e){this.logger.warn("Failed to load circuit breaker state from storage:",e)}}async saveToStorage(){try{const e={state:this.state,failures:this.failures,lastFailureTime:this.lastFailureTime,halfOpenCalls:this.halfOpenCalls};"undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local?await chrome.storage.local.set({[this.storageKey]:e}):"undefined"!=typeof localStorage&&localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){this.logger.warn("Failed to save circuit breaker state to storage:",e)}}cleanupOldFailures(){const e=Date.now();this.failures=this.failures.filter((t=>e-t.timestamp<=this.options.monitoringWindow))}async execute(e,t){if(this.state===G.OPEN){if(!this.shouldAttemptRecovery()){if(t)return t();throw new Error("Circuit breaker is OPEN - service temporarily unavailable")}this.state=G.HALF_OPEN,this.halfOpenCalls=0,await this.saveToStorage()}if(this.state===G.HALF_OPEN){if(this.halfOpenCalls>=this.options.halfOpenMaxCalls)throw new Error("Circuit breaker HALF_OPEN call limit exceeded");this.halfOpenCalls+=1,await this.saveToStorage()}try{const t=await e();return await this.onSuccess(),t}catch(e){throw await this.onFailure(e),e}}async onSuccess(){this.state===G.HALF_OPEN&&(this.state=G.CLOSED,this.failures=[],await this.saveToStorage())}async onFailure(e){const t=Date.now();this.lastFailureTime=t,this.failures.push({timestamp:t,error:e.message}),this.failures=this.failures.filter((e=>t-e.timestamp<=this.options.monitoringWindow)),this.failures.length>=this.options.failureThreshold&&(this.state=G.OPEN),await this.saveToStorage()}shouldAttemptRecovery(){return Date.now()-this.lastFailureTime>=this.options.recoveryTimeout}getState(){return this.state}getFailureCount(){const e=Date.now();return this.failures.filter((t=>e-t.timestamp<=this.options.monitoringWindow)).length}async reset(){this.state=G.CLOSED,this.failures=[],this.lastFailureTime=0,this.halfOpenCalls=0,await this.saveToStorage()}async clearStorage(){"undefined"!=typeof chrome&&chrome.storage&&chrome.storage.local?await chrome.storage.local.remove(this.storageKey):"undefined"!=typeof localStorage&&localStorage.removeItem(this.storageKey)}getStatus(){return{state:this.state,failureCount:this.getFailureCount(),nextAttemptTime:this.state===G.OPEN?this.lastFailureTime+this.options.recoveryTimeout:null}}}const $="https://cdn.givefreely.com/data/behavioral/";class M{constructor(e){this.partnerApiKey=e,this.partnerConfig=null,this.globalConfig=null,this.mergedConfig=null,this.globalConfigRefreshInterval=null,this.partnerConfigRefreshInterval=null,this.eventEmitter=new U,this.isInitialized=!1,this.partnerCircuitBreaker=new H({failureThreshold:3,recoveryTimeout:6e4,monitoringWindow:3e5,storageKey:`gf_partner_circuit_breaker_${e}`}),this.globalCircuitBreaker=new H({failureThreshold:3,recoveryTimeout:6e4,monitoringWindow:3e5,storageKey:"gf_global_circuit_breaker"})}async initialize(){this.isInitialized||(await Promise.all([this.partnerCircuitBreaker.initialize(),this.globalCircuitBreaker.initialize()]),this.isInitialized=!0)}ensureInitialized(){if(!this.isInitialized)throw new Error("GiveFreelyConfigService must be initialized before use. Call initialize() or use create() method.")}getRetryOptions(){return{delayFn:e=>1e3*e,maxAttempts:3}}async fetchPartnerConfig(){const e=await g((async()=>{const e=await fetch(`${$}${this.partnerApiKey}.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch partner config: ${e.statusText}`);return e.json()}),this.getRetryOptions());if(!e)throw new Error("Failed to fetch or get from cache partner config");return this.partnerConfigRefreshInterval=e.configRefreshInterval||this.partnerConfigRefreshInterval,e}async fetchGlobalConfig(){const e=await g((async()=>{const e=await fetch(`${$}global.json`,{cache:"no-store"});if(!e.ok)throw new Error(`Failed to fetch global config => Status code: ${e.status} .${e.statusText}`);return e.json()}),this.getRetryOptions());if(!e)throw new Error("Failed to fetch or get from cache global config",e);return this.globalConfigRefreshInterval=e.configRefreshInterval||this.globalConfigRefreshInterval,e}async getCachedConfig(){return this.mergedConfig}async getConfig(e=!1){this.ensureInitialized();let t=!1;e&&(t=await I());const[r,i]=await Promise.all([D.get(f,this.fetchPartnerConfig.bind(this),this.partnerConfigRefreshInterval,t,(e=>e?.configRefreshInterval??null)),D.get(p,this.fetchGlobalConfig.bind(this),this.globalConfigRefreshInterval,t,(e=>e?.configRefreshInterval??null))]);if(!i.content)throw new Error("Global config is required");if(!r.content)throw new Error("Partner config is required");this.partnerConfig=r.content,this.globalConfig=i.content;const n=this.mergeConfigs(JSON.parse(JSON.stringify(this.globalConfig)),JSON.parse(JSON.stringify(this.partnerConfig)));if(!n)throw new Error("Was not able to merge configs");return((e,t,r)=>{const i=[...t.merchantExclusions??[],...r.merchantExclusions??[]];e.merchantExclusions=i})(n,this.globalConfig,this.partnerConfig),this.emitConfigChanges(n),n}async clearCache(){this.ensureInitialized(),await Promise.all([D.clear(f),D.clear(p)]),this.partnerConfig=null,this.globalConfig=null,this.mergedConfig=null,this.eventEmitter.clear(),await Promise.all([this.partnerCircuitBreaker.reset(),this.globalCircuitBreaker.reset()])}getCircuitBreakerStatus(){return this.ensureInitialized(),{partner:this.partnerCircuitBreaker.getStatus(),global:this.globalCircuitBreaker.getStatus()}}mergeConfigs(e,t){if(!t)return e;if(!e)return t;const r={...e};return Object.keys(t).forEach((i=>{if(!Object.prototype.hasOwnProperty.call(t,i))return;const n=e[i],a=t[i];void 0!==a&&(Array.isArray(a)?r[i]=[...a]:r[i]=null===a||"object"!=typeof a||null===n||"object"!=typeof n?a:this.mergeConfigs(n,a))})),r}on(e,t){return this.eventEmitter.on(e,t)}once(e,t){return this.eventEmitter.once(e,t)}off(e,t){this.eventEmitter.off(e,t)}emitConfigChanges(e){if(!this.mergedConfig)return this.mergedConfig=e,void this.eventEmitter.emit({path:"root",oldValue:null,newValue:e,config:e});const t=L(this.mergedConfig,e);for(const r of t)this.eventEmitter.emit({path:r.path,oldValue:r.oldValue,newValue:r.newValue,config:e});this.mergedConfig=e}}class z{constructor(e,t,r,i=60){this.track=async(e,t,r=!1,i=!1)=>{const n={partner:`gfLib_${this._partnerApiKey}`,eventType:e,eventData:{userId:r?void 0:this._userService?.user?.id,libVersion:F(),...t}};try{const e=JSON.stringify(n,((e,t)=>t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t)),t=await this.getEventsUrl();return t?await this.BroadcastEvent(t,e,n,i):(this._logger.info("Cant broadcast event. eventsUrl cant be retrieved from config",n,!0),!1)}catch(e){return this._logger.error("Something unexpected happened when dispatching a gf event",{error:e,event:n},!0),!1}},this.getEventsHistory=async()=>{const e=await x.get(C),t=(e=>{const t=new Date;return t.setTime(t.getTime()+60*e*1e3),t.getTime()})(-this._debounceWindowInMinutes),r=(e||[]).filter((e=>e.createdAt>t));return await x.set(C,r),r},this.shouldBroadcastEvent=async(e,t)=>!!t||!(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 x.set(C,t)},this._partnerApiKey=e,this._userService=t,this._debounceWindowInMinutes=i,this._logger=o.getInstance({title:"Analytics"}),this._configService=r}async BroadcastEvent(e,t,r,i){if(await this.shouldBroadcastEvent(t,i)){const i=await fetch(e,{headers:{"Content-Type":"application/json"},method:"POST",body:t,cache:"no-store"});return i.ok?(await this.pushEventToHistory(t),!0):(this._logger.error("Something unexpected happened when dispatching an event",{status:i.status,statusText:i.statusText,event:r},!0),!1)}return this._logger.info("This event has already been broadcasted during the past hour",r,!0),!1}async getEventsUrl(){const e=await this._configService.getCachedConfig();return e?.eventsUrl}}z.trackEvent=async(e,t,r=!1,i=!1)=>{await async function(e){return await h.runtime.sendMessage(e)}({type:d.TRACK_EVENT,payload:{eventType:e,eventData:t,anonymous:r,skipThrottling:i}})};class K{constructor(e,t){this.lastCheck=null,this.trackEvent=e,this.logger=t}async initialize(){const e=await x.get(m);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&&(this.lastCheck=Date.now(),await x.set(m,this.lastCheck),await this.trackEvent(r.checkoutPopupHealthCheck,{language:browser.i18n.getUILanguage()}))}catch(e){this.logger.error("Health check failed",{error:e instanceof Error?e.message:"Unknown error"},!0)}}}var j;!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"}(j||(j={}));class B{constructor(e,t,r){this.libraryId=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. Status code: ${i.status} .${i.statusText}`);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}?gfLibId=${this.libraryId}`,{method:"PUT",headers:{"Content-Type":"application/json","X-GF-Platform":"GFLibrary","X-AnonymousUserToken":t??""},body:JSON.stringify(e)});if(!r.ok)throw this.logger.error(`Failed to create/update anonymous user. Status code: ${r.status}. ${r.statusText}`),new Error(`Failed to create/update anonymous user. Status code: ${r.status}. ${r.statusText}`);this.logger.info("[GiveFreelyApiClient] anonymous user created/updated successfully.");const i=await r.json(),n=r.headers.get("X-AnonymousUserToken");return{resultUser:{...i,charity:{ein:i.selectedCharity,thirdPartyId:i.selectedCharityThirdPartyIdentifier,name:void 0}},resultToken:n}}catch(e){throw this.logger.error("[GiveFreelyApiClient] Error creating anonymous user:",{error:e},!0),e}}}class V{constructor(e,t){this._giveFreelyApiClient=e,this._logger=t,this.user=null}async resetUser(){await x.remove(v),await x.remove(w)}async upsertUser(e){let t=await this.fetchUser();try{const r={selectedCharity:e?.ein,selectedCharityThirdPartyIdentifier:e?.thirdPartyId};if(!await this.shouldCreateOrUpdateUser(t,r))return t;const i=await x.get(v),{resultUser:n,resultToken:a}=await this._giveFreelyApiClient.createOrUpdateAnonymousUser(r,i);a&&await x.set(v,a),n&&(await x.set(w,n),t=n)}catch(e){this._logger.error("Error creating/updating anonymous user:",e)}return this.user=t,t}async fetchUser(){const e=await x.get(w);return this.user=e,e}async shouldCreateOrUpdateUser(e,t){return!e||e.charity?.ein!==t.selectedCharity||e.charity?.thirdPartyId!==t.selectedCharityThirdPartyIdentifier}}const W=e=>{try{return new URL(e),!0}catch{return!1}};async function q(e,t,r,i){try{const n=(await J())?.[t],a=await this.getStanddownPolicy(),s=ee(a,new URL(r).search);if(n&&n>Date.now())return e.info("Standing down because current affiliate stand down session has not expired"),X(t,void 0,!s&&null),{result:!0,reason:"sessionNotExpired"};if(ee(a,new URL(r).search))return e.info("Standing down because url has affiliate params"),X(t,void 0,!1),{result:!0,reason:"hasAffiliateParams"};if(te(a,i))return e.info("Standing down because a standdown cookie is present"),X(t,void 0,!1),{result:!0,reason:"hasAffiliateCookies"};e.info("No need to stand down.")}catch(t){e.error("Exception produced when trying to determine if it should stand down",t)}return{result:!1}}function Y(e,t){if(!this.standDownPolicy)return this.logger.warn("Could not check affiliation. No stand down policy found"),this.getStanddownPolicy().then((e=>{this.standDownPolicy=e})),!1;const r=e.some((e=>Q(this.standDownPolicy,e)))||ee(this.standDownPolicy,t);return this.logger.info("Affiliation result:",r),r}const J=async()=>x.get(b),X=async(e,t=1,r=null)=>{const i=await J()??{},n=i?.[e]??0,a=Date.now()+60*t*60*1e3;if(i[e]=a,await x.set(b,i),null!==r){const t=await Z(e);if(r||!r&&t&&a-n>2e4){const t=await x.get(P)??{};t[e]=r,await x.set(P,t)}}},Z=async e=>{const t=await x.get(P);return t?.[e]??!1},Q=(e,t)=>{if(!t)return!1;const{Domains:r}=e;return r.some((e=>t.includes(e)))},ee=(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()}`)))},te=(e,t)=>{if(!t)return!1;const{Cookies:r}=e;return!!r?.length&&r.some((e=>t.includes(e)))},re=new Set,ie=new Set,ne={urls:["<all_urls>"],types:["main_frame"]};class ae extends Error{constructor(e="Service not initialized"){super(e),this.name="UninitializedServiceError"}}const se=e=>{if(!e)throw new ae};class oe{static register(e,t){this.strategies.set(e,t)}static get(e){return this.strategies.get(e)}static exists(e){return!!function(e){return"object"==typeof e&&null!==e&&"type"in e&&"payload"in e&&"string"==typeof e.type}(e)&&this.knownMessageTypes.has(e.type)}}oe.strategies=new Map,oe.knownMessageTypes=new Set([...Object.values(d)]);const ce=e=>{let t;if(browser.webRequest){const i=(e=>{const t=e.getLogger();return({requestId:r,url:i,initiator:n})=>{try{if(re.has(r)||ie.has(r)||!W(i))return;const{hostname:a,search:s}=new URL(i);let o;n&&W(n)&&(o=new URL(n).hostname),(e.hasAffiliation([a,o],s)||e.isCustomStandownMatch([i,n]))&&(t.info("Affiliation found or custom standown match on url, adding request id to track"),re.add(r))}catch(e){t.error("Error on handleAffiliateOnBeforeRequest",e)}}})(e);browser.webRequest.onBeforeRequest.addListener(i,ne);const n=(e=>{const t=e.getLogger();return async({requestId:i,redirectUrl:n})=>{try{if(!re.has(i))return;t.info("Attempting to find active domain");const{hostname:a}=new URL(n),s=(await e.getActiveDomains()).find((e=>a===e.domain||a.endsWith(`.${e.domain}`)));if(!s)return;t.info("Found active domain. Updating standdown state"),await X(s.domain,void 0,!1),(await e.getCachedConfig()).enhancedLogging&&e.trackEvent(r.checkoutPopupStoodDown,{domain:s.domain,reason:"vendorPolicy (at webReq listener)"})}catch(e){t.error("Error on handleAffiliateOnBeforeRedirect",e)}}})(e);browser.webRequest.onBeforeRedirect.addListener(n,ne);const a=(e=>{const t=e.getLogger();return({requestId:e})=>{try{re.has(e)&&(t.info("Tracking request completed. Request Id:",e),re.delete(e))}catch(e){t.error("Error on handleAffiliateOnCompleted",e)}}})(e);browser.webRequest.onCompleted.addListener(a,ne),t=()=>{browser.webRequest.onBeforeRequest.removeListener(i),browser.webRequest.onBeforeRedirect.removeListener(n),browser.webRequest.onCompleted.removeListener(a)}}const i=function(){const t=o.getInstance(),r=(r,i,n)=>{function a(e){n(e)}const s=(async t=>(e.getLogger().debug("Received message",{type:t.type,payload:t.payload}),le(e,t)))(r,0);return s instanceof Promise?(s.then((e=>{e&&a(e)})).catch((e=>{t.warn("Async message callback error:",e)})),!0):!0===s||void 0};return h.runtime.onMessage.addListener(r),r}();return function(){t&&t(),browser.runtime.onMessage.removeListener(i)}},le=async(e,t)=>{se(e.isInitialized());const r=oe.get(t.type);if(!r)return;const i={giveFreelyService:e};return r.handle(t,i)};class ge{async handle(e,t){const{activeDomain:i,originalUrl:n,selectedCharity:a,gfCommissionUniqueId:s,openTab:o}=e.payload,{giveFreelyService:c}=t,l=c.getLogger();l.debug("Activating offer",{activeDomain:i,selectedCharity:a});try{if(i?.merchantId&&(async e=>{try{const t=await(async()=>await x.get(E)??{})();t[e]&&delete t[e],await x.set(E,t)}catch{}})(parseInt(i.merchantId)),!a?.ein||!a?.thirdPartyId)throw new Error("Missing charity information");const e=await c.upsertUser(a);l.debug("Upserted user",{currentUser:e}),e||l.info("Failed to create user. Using default bucket's user");const t=await c.getProviderPreActivation(i.provider),r=await c.generateAffiliateUrl(i,n,e,s,t);return l.debug("Generated affiliate URL",{affiliateUrl:r}),!1!==o?((async e=>{const t=h.tabs.getCurrent(),r=await t,i=await h.tabs.create({url:e,openerTabId:r?.id,active:!1,pinned:!0});await(async e=>new Promise((t=>{h.tabs.onUpdated.addListener((async function r(i,n){if(i===e&&"complete"===n.status){if(h.tabs.onUpdated.removeListener(r),!(await h.tabs.get(e)).url)return void t(!1);t(!0)}}))})))(i.id)&&setTimeout((()=>{i?.id&&h.tabs.remove(i.id)}),3e4)})(r),await c.updateStanddownHistory(i.domain,!0)):await c.updateStanddownHistoryByMerchantId(i.merchantId,!0),l.debug("Activated offer",{activeDomain:i,selectedCharity:a,gfCommissionUniqueId:s}),{type:d.ACTIVATE_OFFER,payload:{response:!0,activationLink:r}}}catch(e){return l.error("Error activating offer",{activeDomain:i,error:e}),c.trackEvent(r.checkoutPopupFailedActivation,{activeDomain:i,error:e}),{type:d.ACTIVATE_OFFER,payload:{response:!1}}}}}class he{async handle(e,t){const{urls:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=await i.getActiveDomains();if(!e||0===e.length)throw new Error("No active domains");const t={},n=r.map((async r=>{try{const{hostname:n}=new URL(r),a=e.find((e=>n===e.domain||n.endsWith(`.${e.domain}`)));if(a){const{result:e}=await i.shouldStandDown(a.domain,r);t[r]={activeDomain:a,shouldStandDown:e,currentlyActivated:await i.wasLastStandDownAnActivation(a.domain)}}}catch{}}));return await Promise.all(n),{type:d.GET_ACTIVE_DOMAINS,payload:{result:t}}}catch(e){return n.error("Error checking domain",{urls:r,error:e}),{type:d.GET_ACTIVE_DOMAINS,payload:{result:{}}}}}}class de{async handle(e,t){const{shopId:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=u,t=await x.get(e)||[];if(t.length>0&&"Merchant"in t[0].domain)return n.warn("Detected legacy WildfireActiveDomain in Shopify storage — data should have been pruned. Clearing stale entries."),await x.remove(e),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}};const i=t.find((e=>e.shopId===r));return i?(n.debug("Found domain for shop ID",{shopId:r,domain:i.domain}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!0,domain:i.domain,shopInfo:i}}):(n.debug("No domain found for shop ID",{shopId:r}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}})}catch(e){return n.error("Error getting domain for shop ID",{shopId:r,error:e}),{type:d.GET_DOMAIN_BY_SHOP_ID,payload:{found:!1}}}}}class ue{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger();try{const e=r.getConfig()?.gfDataUrl;if(!e)return i.warn("gfDataUrl is not configured — skipping GF data fetch"),{type:d.GET_GF_DATA,payload:{data:null}};i.debug("Fetching GF data",{url:e});const t=await g((async()=>{const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}),{logger:i,operationName:"GetGfData"});return i.debug("GF data fetched successfully",{data:t}),{type:d.GET_GF_DATA,payload:{data:t}}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return i.error(`Failed to fetch GF data: ${t}`,{error:e},!0),{type:d.GET_GF_DATA,payload:{data:null}}}}}class me{async handle(e,t){const{lang:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();n.debug("Getting language strings",{lang:r});try{const e=await i.getLanguage(r);return n.debug("Language strings fetched",{language:e}),{type:d.GET_LANGUAGE_CONTENT,payload:{translations:e.translations,charities:e.charities}}}catch(e){return n.error("Error getting language strings",{error:e}),{type:d.GET_LANGUAGE_CONTENT,payload:{translations:null,charities:null}}}}}class fe{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger(),n=await r.getCachedConfig();try{return i.debug("Fetching popup config"),{type:d.GET_POPUP_CONFIG,payload:{config:n}}}catch(e){return i.error("Error fetching popup config",{error:e}),{type:d.GET_POPUP_CONFIG,payload:{config:null}}}}}class pe{async handle(e,t){const{days:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=new Date;return e.setDate(e.getDate()+r),await x.set("popup_hide",{popupHide:e.getTime()}),n.debug("Popup hidden",{days:r,expiry:e}),{type:d.HIDE_POPUP,payload:{ack:!0}}}catch(e){return n.error("Error hiding popup",{days:r,error:e}),{type:d.HIDE_POPUP,payload:{ack:!1}}}}}class Ae{async handle(e,t){const{hostname:r}=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const{merchantExclusions:e}=await i.getConfig();if(n.debug("Checking hostname",{hostname:r}),i.healthCheck(),e.some((e=>e.disableDomain&&(r===e.domain||r.endsWith(`.${e.domain}`)))))return n.debug("Hostname is in merchant exclusions",{hostname:r}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!1,domain:void 0}};const t=await i.getActiveDomains();n.debug("Retrieved active domains",{count:t.length});const a=t.find((e=>r===e.domain||r.endsWith(`.${e.domain}`)));return n.debug("Domain check result",{hostname:r,isActive:!!a}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!!a,domain:a}}}catch(e){return n.error("Error checking domain",{hostname:r,error:e}),{type:d.IS_ACTIVE_DOMAIN,payload:{isActive:!1,domain:void 0}}}}}class ye{async handle(e,t){const{currentUrl:i,searchResults:n,source:a}=e.payload,{giveFreelyService:s}=t,o=s.getLogger();try{const e=await s.getActiveDomains();o.debug("Finding merchants in search results",{currentUrl:i});const c=n.filter((t=>{try{const{hostname:r}=new URL(t.url);return e.some((e=>e.domain===r||r.endsWith(`.${e.domain}`)))}catch{return o.debug("Couldn't parse the following search result url",{x:t}),!1}}));if(o.info("Number of merchants identified in the search result",{number:c.length}),c.length>0){const e=Math.floor(Math.random()*Date.now());for(const n of c)t.giveFreelyService.trackEvent(r.checkoutPopupMerchantInResultsFound,{source:a,searchResultsId:e,currentUrl:i,searchResultUrl:n.url,sponsored:n.isSponsored},!0)}return{type:d.LOG_MERCHANTS_IN_SEARCH_RESULTS,payload:{result:!0}}}catch(e){return o.error("Error sending logs for merchants in search results",{currentUrl:i,error:e}),{type:d.LOG_MERCHANTS_IN_SEARCH_RESULTS,payload:{result:!1}}}}}class we{async handle(e,t){const{giveFreelyService:r}=t,i=r.getLogger();try{return await x.set("gf_partner_serp_muted",!0),i.debug("Partner Serp box hidden"),{type:d.MUTE_PARTNER_SERP_BOX,payload:{ack:!0}}}catch(e){return i.error("Error hiding partner serp box",{error:e}),{type:d.MUTE_PARTNER_SERP_BOX,payload:{ack:!1}}}}}class ve{async handle(e,t){const r=e.payload,{giveFreelyService:i}=t,n=i.getLogger();try{const e=u;let t=await x.get(e)||[];t.length>0&&"Merchant"in t[0].domain&&(n.warn("Detected legacy WildfireActiveDomain in Shopify storage — data should have been pruned. Clearing stale entries."),t=[],await x.remove(e));const i=t.findIndex((e=>e.shopId===r.shopId));return i>=0?t[i]=r:t.push(r),await x.set(e,t),n.debug("Stored Shopify shop ID",{shopInfo:r}),{type:d.STORE_SHOPIFY_SHOP_ID,payload:{success:!0}}}catch(e){return n.error("Error storing Shopify shop ID",{shopInfo:r,error:e}),{type:d.STORE_SHOPIFY_SHOP_ID,payload:{success:!1}}}}}class Ce{async handle(e,t){const{activeDomain:r,url:i,cookies:n}=e.payload,{giveFreelyService:a}=t,s=a.getLogger();s.debug("Checking if we should stand down",{activeDomain:r});try{const e=await a.shouldStandDown(r,i,n);return{type:d.SHOULD_STAND_DOWN,payload:e}}catch(e){return s.error("Error checking if we should stand down. Returning false",{activeDomain:r,error:e}),{type:d.SHOULD_STAND_DOWN,payload:{result:!1}}}}}class Ee{async handle(e,t){const{eventType:r,eventData:i,anonymous:n,skipThrottling:a}=e.payload,{giveFreelyService:s}=t,o=s.getLogger();o.debug("Broadcasting event",{eventType:r,eventData:i,anonymous:n,skipThrottling:a});try{const e=await s.trackEvent(r,i,n,a);return{type:d.TRACK_EVENT,payload:{result:e}}}catch(e){return o.error("Error broadcasting event. Returning false",{eventType:r,eventData:i,error:e}),{type:d.TRACK_EVENT,payload:{result:!1}}}}}const Se=o.getInstance(),Te=async()=>await x.get(A)||(async()=>{Se.debug("detecting country");const e={method:"GET",headers:{"Content-Type":"application/json",Authorization:"Basic OTEzOTkxOnFlYmpaWF9DOGNRY0lxSHA4WTVjNGxzU1pRSlM2VW9MMExzTF9tbWs="}};try{const t=await fetch("https://geoip.maxmind.com/geoip/v2.1/country/me",e);if(Se.debug("Received geolocation response",{status:t.status}),!t.ok)return void Se.error("Failed to get geolocation data",{status:t.status,statusText:t.statusText});const r=await t.json();if(!r)throw new Error("There was an error fetching geoip look up");return await x.set(A,r.country.iso_code),r.country.iso_code}catch(e){return void Se.error("Failed to get geolocation data",{error:e},!0)}})(),be="https://cdn.givefreely.com/data/language",Pe=async(e,t,r,i,n=[],a=!1)=>{const s=(n??[]).includes(r)?_:r;e.debug(`Requested lang ${r} and current lang ${s}`);const o=`lang-${_}`,c=await D.get(o,(async()=>(e.debug(`Fetching default language ${_} for partner ${t}`),_e(t,_))),i||600,a);if(!c.content)throw new Error(`Failed to fetch default language ${_} and no cache version available`);if(_===s)return c.content;const l=`lang-${s}`,g=await D.get(l,(async()=>(e.debug(`Fetching language ${s} for partner ${t}`),_e(t,s))),i||600,a);if(!g.content)return c.content;const h=Fe(c.content,g.content);return await D.set(l,h,i||600),h},_e=async(e,t)=>{const r=`/global-${t}.json`,i=`/${e}/${t}.json`,[n,a]=await Promise.allSettled([Oe(`${be}${r}`),Oe(`${be}${i}`)]);let s,o;"fulfilled"===n.status&&(s=n.value),"fulfilled"===a.status&&(o=a.value);const c=xe(s,o);return{translations:c.translations,charities:c.charities}},Oe=async e=>{const t=await fetch(e,{cache:"no-store"});if(!t.ok)throw new Error(`Failed to fetch partner language file ${e}. Status: ${t.status}. Reason: ${t.statusText}`);return t.json()},xe=(e,t)=>({translations:{...e?.translations??{},...t??{}},charities:{...e?.charities??{}}}),Fe=(e,t)=>({translations:{...e.translations,...t.translations},charities:{...e.charities,...t.charities}});class Ie{constructor(e,t,r,i){this._logger=e,this.feedUrl=t,this.activationUrl=r,this.preActivationUrl=i}async getRawFeed(){try{const e=`${this.feedUrl}`,t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch feed from ${e}. Status ${t.status}. ${t.statusText}`);return t.json()}catch(e){throw this._logger.error("Failed to fetch the feed",{err:e}),new Error("Failed to fetch the feed")}}async preActivation(e,t){try{const r=await fetch(this.preActivationUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({partnerId:e,...t&&{provider:t}})});if(!r.ok)throw new Error(`Failed to pre-activate. Status ${r.status}. ${r.statusText}`);return r.json()}catch(e){throw this._logger.error("Failed to pre-activate",{err:e}),new Error("Failed to pre-activate")}}async generateAffiliateUrl(e,t,r,i,n,a){try{const s=await fetch(`${this.activationUrl}?redirect=false`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e.provider,partnerId:i,userId:r?.id||"",ein:r?.charity?.ein||"",tpi:r?.charity?.thirdPartyId||"",url:t,gfCommissionUniqueId:n,merchantId:e.merchantId,domainId:e.id,providerCustom:a})});if(!s.ok)throw new Error(`Failed to generate affiliate url. Status ${s.status}. ${s.statusText}`);return(await s.json()).affiliateLink}catch(e){throw this._logger.error("Failed to generate affiliate url",{err:e}),new Error("Failed to generate affiliate url")}}}class ke{constructor(e){this.raw=e}static mapKind(e){return 1===e?"FLAT":"PERCENTAGE"}static mapOfferRate(e){return{Kind:ke.mapKind(e.k),Amount:e.a,Name:e.n,Currency:e.c??void 0}}static fromRawArray(e){return e.map((e=>new ke(e)))}static fromRaw(e){return new ke(e)}get id(){return parseInt(this.raw.di,10)||0}get domain(){return this.raw.d}get provider(){return this.raw.p}get merchantId(){return this.raw.mi}get merchantName(){return this.raw.mn}get commission(){return{amount:this.raw.c.a,kind:ke.mapKind(this.raw.c.k)}}get rates(){return this.raw.r?.map(ke.mapOfferRate)??[]}toRaw(){return this.raw}toJSON(){return{id:this.id,domain:this.domain,provider:this.provider,merchantId:this.merchantId,merchantName:this.merchantName,commission:this.commission,rates:this.rates}}}class De{constructor(e,t,r=600){this.standDownPolicy=null,this.shouldStandDown=q.bind(this),this.hasAffiliation=Y.bind(this),this.updateStanddownHistory=X,this.refreshInterval=r,this.giveFreelyFeedClient=e,this.logger=t}async getActiveDomains(e=!1){try{const t=await D.get("gfFeed",(async()=>this.fetchRawActiveDomains()),this.refreshInterval,e);if(!t.content)throw new Error("Failed to retrieve feed from cache");return ke.fromRawArray(t.content)}catch(e){return this.logger.error("Failed to get active domains:",e),[]}}async preActivation(e,t){return this.giveFreelyFeedClient.preActivation(e,t)}async generateAffiliateUrl(e,t,r,i,n,a){return this.giveFreelyFeedClient.generateAffiliateUrl(e,t,r,i,n,a)}async fetchRawActiveDomains(){const e=await this.giveFreelyFeedClient.getRawFeed();return this.standDownPolicy=e.standdownRules,e.activeDomains}async getStanddownPolicy(){if(this.standDownPolicy)return this.standDownPolicy;const e=await this.giveFreelyFeedClient.getRawFeed();return this.standDownPolicy=e.standdownRules,this.standDownPolicy}static async createGiveFreelyFeedService(e,t){e.debug("Initializing givefreely feed service with config",t);const{feedUrl:r,activationUrl:i,preActivationUrl:n}=t.multiAffiliate??{};if(!r||!i||!n)throw new Error("multiAffiliate config is missing required URLs (feedUrl, activationUrl, preActivationUrl)");const a=new Ie(e,r,i,n),s=new De(a,e,t.multiAffiliate?.feedRefreshInterval);return await s.getActiveDomains(),s}}async function Ue(e){const t=[...Object.values(S),u];try{await Promise.all(t.map((e=>x.remove(e)))),e.info("Pruned legacy Wildfire storage keys",{keys:t})}catch(t){e.debug("Failed to prune legacy Wildfire storage keys",t)}}var Le=Object.freeze({__proto__:null,generateAffiliateUrl:async function(e,t,r,i,n){return se(this.state.initialized),this.state.giveFreelyFeedService.generateAffiliateUrl(e,t,r,this.state.partnerApiKey,i,n)},getActiveDomains:async function(){return se(this.state.initialized),this.state.giveFreelyFeedService.getActiveDomains()},pruneLegacyWildfireStorage:Ue});async function Re(e,t,r){try{const i={...t};for(const e of r)delete i[e];return await x.set(T,i),e.info("Pruned preActivation providers",{providers:r}),i}catch(r){return e.debug("Failed to prune preActivation providers",r),t}}var Ne=Object.freeze({__proto__:null,getCurrentUser:function(){return se(this.state.initialized),this.state.giveFreelyUserService.user},getLanguage:async function(e){return se(this.state.initialized),Pe(this.logger,this.state.partnerApiKey,e,this.state.config?.configRefreshInterval,this.state.config?.ignoredLanguages)},getProviderPreActivation:async function(e){if(se(this.state.initialized),this.state.preActivation&&e in this.state.preActivation)return this.state.preActivation[e];const t=await x.get(T);if(t&&e in t)return this.state.preActivation=t,t[e];const r=(await this.state.giveFreelyFeedService.preActivation(this.state.partnerApiKey,e))[e]??{},i={...t||{},...this.state.preActivation||{},[e]:r};return this.state.preActivation=i,await x.set(T,i),r},initializePreActivation:async function(e){const t=await x.get(T);if(t&&Object.keys(t).length>0)return this.state.preActivation=t,t;const r=await e.preActivation(this.state.partnerApiKey);return this.state.preActivation=r,await x.set(T,r),r},prunePreActivationProviders:Re,upsertUser:function(e){return se(this.state.initialized),this.state.giveFreelyUserService.upsertUser(e)}});async function Ge(e=async()=>(this.logger.debug("Using default partnerFilter."),!0)){if(!this.state.initialized){this.logger.info("Starting initialization with mutex protection");try{await this.dependencies.configService.initialize();const t=await I(!1),r=await this.dependencies.configService.getConfig(!0);this.logger.configure({enabled:r.loggingEnabled??!0,minLevel:r.backgroundMinLogLevel??"error"}),this.logger.info("Initializing GiveFreelyService",{partnerApiKey:this.partnerApiKey}),!r.multiAffiliate?.skipWildfirePruning&&t&&await Ue(this.logger);const i=await De.createGiveFreelyFeedService(this.logger,r);this.state.healthCheck=new K(this.trackEvent.bind(this),this.logger),await this.state.healthCheck.initialize();const n=new B(this.partnerApiKey,r,this.logger);this.state.giveFreelyUserService=new V(n,this.logger),await this.state.giveFreelyUserService.fetchUser(),this.state.giveFreelyUserService.user?.id||await this.state.giveFreelyUserService.upsertUser(),this.state.analytics=new z(this.partnerApiKey,this.state.giveFreelyUserService,this.dependencies.configService);try{if(r.multiAffiliate?.prunePreActivationProviders?.length){const e=await x.get(T);e&&await Re(this.logger,e,r.multiAffiliate.prunePreActivationProviders)}await this.initializePreActivation(i)}catch(e){this.logger.debug("Pre-activation initialization failed — will retry on first offer activation",e)}oe.register(d.IS_ACTIVE_DOMAIN,new Ae),oe.register(d.GET_POPUP_CONFIG,new fe),oe.register(d.HIDE_POPUP,new pe),oe.register(d.SHOULD_STAND_DOWN,new Ce),oe.register(d.TRACK_EVENT,new Ee),oe.register(d.ACTIVATE_OFFER,new ge),oe.register(d.STORE_SHOPIFY_SHOP_ID,new ve),oe.register(d.GET_DOMAIN_BY_SHOP_ID,new de),oe.register(d.GET_LANGUAGE_CONTENT,new me),oe.register(d.LOG_MERCHANTS_IN_SEARCH_RESULTS,new ye),oe.register(d.GET_ACTIVE_DOMAINS,new he),oe.register(d.MUTE_PARTNER_SERP_BOX,new we),oe.register(d.GET_GF_DATA,new ue),await(async e=>{try{await Te()}catch(t){e.debug("Failed to get geolocation data",{error:t})}})(this.logger),await(async(e,t,r)=>{t.purgeLanguages&&t.purgeLanguages.length>0&&await Promise.all(t.purgeLanguages.flatMap((e=>[D.clear(`lang-${e}`),D.clear(`global-${e}`)]))),g((async()=>{e.debug("Initializing default language with partner API key",{partnerApiKey:r}),await Pe(e,r,_,t.configRefreshInterval)}))})(this.logger,r,this.partnerApiKey),this.state=((e,t)=>{const{partnerFilter:r,config:i,giveFreelyFeedService:n}=t;return{...e,initialized:!0,partnerFilter:r,config:i,giveFreelyFeedService:n}})(this.state,{partnerFilter:e,config:r,giveFreelyFeedService:i}),this.logger.addTransport(new a(this)),this.cleanupListeners=ce(this),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}`)}}}function He(){return this.state.initialized}var $e={config:Object.freeze({__proto__:null,getCachedConfig:async function(){return se(this.state.initialized),this.state.config=await this.dependencies.configService.getConfig(),this.logger.configure({minLevel:this.state.config.backgroundMinLogLevel??"error"}),this.state.config},getConfig:function(){return se(this.state.initialized),this.state.config},offConfigChange:function(e,t){se(this.state.initialized),this.dependencies.configService.off(e,t)},onConfigChange:function(e,t){return se(this.state.initialized),this.dependencies.configService.on(e,t)},onceConfigChange:function(e,t){return se(this.state.initialized),this.dependencies.configService.once(e,t)}}),merchants:Le,observability:Object.freeze({__proto__:null,getLogger:function(){return se(this.state.initialized),this.logger},healthCheck:async function(){se(this.state.initialized),await this.state.healthCheck.check()},trackEvent:function(e,t,r=!1,i=!1){return se(this.state.initialized),this.state.analytics.track(e,t,r,i)}}),standdown:Object.freeze({__proto__:null,hasAffiliation:function(e,t){if(!this.state.giveFreelyFeedService)return this.logger.warn("GiveFreely Feed service not initialized yet"),!1;const r=this.state.giveFreelyFeedService.hasAffiliation(e,t);return r&&this.logger.info("Affiliation identified"),r},isCustomStandownMatch:function(e){const t=e.some((e=>this.getConfig().customStandownPolicy?.urlRegex?.some((t=>!!e&&function(e,t){return new RegExp(t).test(e)}(e,t)))));return t&&this.logger.info("Custom Standown identified"),t},shouldStandDown:async function(e,t,r){se(this.state.initialized);const i=new URL(t);if(!await this.state.partnerFilter(i.hostname))return this.logger.info("Should standdown due to partner filter."),{result:!0,reason:"partner filter"};if(this.getConfig().merchantExclusions.some((t=>t.mutePopups&&e===t.domain)))return this.logger.info("Should standdown due to merchant exclusions"),{result:!0,reason:"merchant exclusions"};const n=await this.state.giveFreelyFeedService.shouldStandDown(this.logger,e,t,r);return n.result&&this.logger.info(`Should standdown due to ${n.reason}`),n},updateStanddownHistory:function(e,t=null){return se(this.state.initialized),X(e,void 0,t)},updateStanddownHistoryByMerchantId:function(e,t=null){return se(this.state.initialized),this.state.giveFreelyFeedService.getActiveDomains().then((r=>{const i=r.find((t=>t.merchantId===e));if(i)return X(i.domain,void 0,t)}))},wasLastStandDownAnActivation:async function(e){return Z(e)}}),identity:Ne};class Me{constructor(e){this.partnerApiKey=e,this.cleanupListeners=null,this.initialize=Ge.bind(this),this.isInitialized=He.bind(this),this.getConfig=$e.config.getConfig.bind(this),this.getCachedConfig=$e.config.getCachedConfig.bind(this),this.onConfigChange=$e.config.onConfigChange.bind(this),this.onceConfigChange=$e.config.onceConfigChange.bind(this),this.offConfigChange=$e.config.offConfigChange.bind(this),this.getLogger=$e.observability.getLogger.bind(this),this.healthCheck=$e.observability.healthCheck.bind(this),this.trackEvent=$e.observability.trackEvent.bind(this),this.getProviderPreActivation=$e.identity.getProviderPreActivation.bind(this),this.initializePreActivation=$e.identity.initializePreActivation.bind(this),this.upsertUser=$e.identity.upsertUser.bind(this),this.getCurrentUser=$e.identity.getCurrentUser.bind(this),this.getLanguage=$e.identity.getLanguage.bind(this),this.getActiveDomains=$e.merchants.getActiveDomains.bind(this),this.generateAffiliateUrl=$e.merchants.generateAffiliateUrl.bind(this),this.shouldStandDown=$e.standdown.shouldStandDown.bind(this),this.updateStanddownHistory=$e.standdown.updateStanddownHistory.bind(this),this.updateStanddownHistoryByMerchantId=$e.standdown.updateStanddownHistoryByMerchantId.bind(this),this.wasLastStandDownAnActivation=$e.standdown.wasLastStandDownAnActivation.bind(this),this.hasAffiliation=$e.standdown.hasAffiliation.bind(this),this.isCustomStandownMatch=$e.standdown.isCustomStandownMatch.bind(this),this.dependencies={configService:new M(e)},this.logger=o.getInstance(),this.logger.configure({enabled:!0,title:"Background - GiveFreelyService"}),this.state=(e=>({initialized:!1,giveFreelyFeedService:null,partnerFilter:null,config:null,preActivation:null,analytics:null,giveFreelyUserService:null,partnerApiKey:e,healthCheck:null}))(e)}async destroy(){var e;this.logger.info("Destroying GiveFreelyService"),await Promise.all([this.dependencies.configService.clearCache(),this.state.giveFreelyUserService?.resetUser()]),this.cleanupListeners&&(this.cleanupListeners(),this.logger.info("Event listeners cleared."),this.cleanupListeners=null),this.state=(e=this.state,{...e,initialized:!1,giveFreelyFeedService:null,partnerFilter:null,analytics:null,config:null})}}class GiveFreelyService{constructor(e){this.partnerApiKey=e,this.initialize=e=>this._coreService.initialize(e),this.destroy=()=>this._coreService.destroy(),this._coreService=new Me(e)}}const ze=e=>oe.exists(e);export{GiveFreelyService,browser,ze as isGiveFreelyMessage};
|
|
2
2
|
//# sourceMappingURL=GiveFreely-background.esm.js.map
|