@bringweb3/chrome-extension-kit 1.3.11 → 1.4.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/README.md +1 -1
- package/dist/index.d.mts +27 -2
- package/dist/index.d.ts +27 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -49,6 +49,9 @@ interface Configuration {
|
|
|
49
49
|
apiEndpoint: string;
|
|
50
50
|
whitelistEndpoint?: string;
|
|
51
51
|
cashbackPagePath?: string;
|
|
52
|
+
isEnabledByDefault: boolean;
|
|
53
|
+
showNotifications?: boolean;
|
|
54
|
+
notificationCallback?: () => void;
|
|
52
55
|
}
|
|
53
56
|
/**
|
|
54
57
|
* Initializes the background script for the Bring extension.
|
|
@@ -60,6 +63,8 @@ interface Configuration {
|
|
|
60
63
|
* @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
|
|
61
64
|
* @param {string} configuration.whitelistEndpoint - Endpoint for whitelist of redirect urls.
|
|
62
65
|
* @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
|
|
66
|
+
* @param {boolean} [configuration.isEnabledByDefault] - Determine if the user see the popup by default. defaults to true.
|
|
67
|
+
* @param {boolean} [configuration.showNotifications] - Determine if the extension should show notifications about new rewards. defaults to true.
|
|
63
68
|
* @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
|
|
64
69
|
* @returns {Promise<void>}
|
|
65
70
|
*
|
|
@@ -82,10 +87,11 @@ interface Configuration {
|
|
|
82
87
|
* identifier: '<bring_identifier>',
|
|
83
88
|
* apiEndpoint: 'sandbox',
|
|
84
89
|
* whitelistEndpoint: 'https://example.com/whitelist.json',
|
|
90
|
+
* isEnabledByDefault: true,
|
|
85
91
|
* cashbackPagePath: '/cashback.html'
|
|
86
92
|
* });
|
|
87
93
|
*/
|
|
88
|
-
declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint }: Configuration) => Promise<void>;
|
|
94
|
+
declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint, isEnabledByDefault, showNotifications, notificationCallback }: Configuration) => Promise<void>;
|
|
89
95
|
|
|
90
96
|
interface TurnOff {
|
|
91
97
|
isTurnedOff: boolean;
|
|
@@ -106,4 +112,23 @@ declare const getTurnOff: () => Promise<TurnOff>;
|
|
|
106
112
|
*/
|
|
107
113
|
declare const setTurnOff: (state: boolean) => Promise<TurnOff>;
|
|
108
114
|
|
|
109
|
-
|
|
115
|
+
interface PopupEnabled {
|
|
116
|
+
isPopupEnabled: boolean;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Retrieves the current "turn off" status, true means turned off and false is turned on
|
|
120
|
+
*
|
|
121
|
+
* @returns A Promise resolving to the turn-off state
|
|
122
|
+
* @throws Will reject if there's an error communicating with the background script
|
|
123
|
+
*/
|
|
124
|
+
declare const getPopupEnabled: () => Promise<PopupEnabled>;
|
|
125
|
+
/**
|
|
126
|
+
* Sets if popup feature is enabled or disabled
|
|
127
|
+
*
|
|
128
|
+
* @param state - Boolean indicating whether popup feature is enabled (true) or disabled (false)
|
|
129
|
+
* @returns A Promise resolving to the new turn-off state
|
|
130
|
+
* @throws Will reject if there's an error communicating with the background script
|
|
131
|
+
*/
|
|
132
|
+
declare const setPopupEnabled: (state: boolean) => Promise<PopupEnabled>;
|
|
133
|
+
|
|
134
|
+
export { bringInitBackground, bringInitContentScript, getPopupEnabled, getTurnOff, setPopupEnabled, setTurnOff };
|
package/dist/index.d.ts
CHANGED
|
@@ -49,6 +49,9 @@ interface Configuration {
|
|
|
49
49
|
apiEndpoint: string;
|
|
50
50
|
whitelistEndpoint?: string;
|
|
51
51
|
cashbackPagePath?: string;
|
|
52
|
+
isEnabledByDefault: boolean;
|
|
53
|
+
showNotifications?: boolean;
|
|
54
|
+
notificationCallback?: () => void;
|
|
52
55
|
}
|
|
53
56
|
/**
|
|
54
57
|
* Initializes the background script for the Bring extension.
|
|
@@ -60,6 +63,8 @@ interface Configuration {
|
|
|
60
63
|
* @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
|
|
61
64
|
* @param {string} configuration.whitelistEndpoint - Endpoint for whitelist of redirect urls.
|
|
62
65
|
* @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
|
|
66
|
+
* @param {boolean} [configuration.isEnabledByDefault] - Determine if the user see the popup by default. defaults to true.
|
|
67
|
+
* @param {boolean} [configuration.showNotifications] - Determine if the extension should show notifications about new rewards. defaults to true.
|
|
63
68
|
* @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
|
|
64
69
|
* @returns {Promise<void>}
|
|
65
70
|
*
|
|
@@ -82,10 +87,11 @@ interface Configuration {
|
|
|
82
87
|
* identifier: '<bring_identifier>',
|
|
83
88
|
* apiEndpoint: 'sandbox',
|
|
84
89
|
* whitelistEndpoint: 'https://example.com/whitelist.json',
|
|
90
|
+
* isEnabledByDefault: true,
|
|
85
91
|
* cashbackPagePath: '/cashback.html'
|
|
86
92
|
* });
|
|
87
93
|
*/
|
|
88
|
-
declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint }: Configuration) => Promise<void>;
|
|
94
|
+
declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint, isEnabledByDefault, showNotifications, notificationCallback }: Configuration) => Promise<void>;
|
|
89
95
|
|
|
90
96
|
interface TurnOff {
|
|
91
97
|
isTurnedOff: boolean;
|
|
@@ -106,4 +112,23 @@ declare const getTurnOff: () => Promise<TurnOff>;
|
|
|
106
112
|
*/
|
|
107
113
|
declare const setTurnOff: (state: boolean) => Promise<TurnOff>;
|
|
108
114
|
|
|
109
|
-
|
|
115
|
+
interface PopupEnabled {
|
|
116
|
+
isPopupEnabled: boolean;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Retrieves the current "turn off" status, true means turned off and false is turned on
|
|
120
|
+
*
|
|
121
|
+
* @returns A Promise resolving to the turn-off state
|
|
122
|
+
* @throws Will reject if there's an error communicating with the background script
|
|
123
|
+
*/
|
|
124
|
+
declare const getPopupEnabled: () => Promise<PopupEnabled>;
|
|
125
|
+
/**
|
|
126
|
+
* Sets if popup feature is enabled or disabled
|
|
127
|
+
*
|
|
128
|
+
* @param state - Boolean indicating whether popup feature is enabled (true) or disabled (false)
|
|
129
|
+
* @returns A Promise resolving to the new turn-off state
|
|
130
|
+
* @throws Will reject if there's an error communicating with the background script
|
|
131
|
+
*/
|
|
132
|
+
declare const setPopupEnabled: (state: boolean) => Promise<PopupEnabled>;
|
|
133
|
+
|
|
134
|
+
export { bringInitBackground, bringInitContentScript, getPopupEnabled, getTurnOff, setPopupEnabled, setTurnOff };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var U=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.prototype.hasOwnProperty;var pt=(t,e)=>{for(var r in e)U(t,r,{get:e[r],enumerable:!0})},gt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ut(e))!ft.call(t,i)&&i!==r&&U(t,i,{get:()=>e[i],enumerable:!(n=dt(e,i))||n.enumerable});return t};var ht=t=>gt(U({},"__esModule",{value:!0}),t);var Zt={};pt(Zt,{bringInitBackground:()=>at,bringInitContentScript:()=>H,getTurnOff:()=>ct,setTurnOff:()=>mt});module.exports=ht(Zt);var wt=t=>{let e=new URLSearchParams,{query:r,prefix:n}=t;return Object.entries(r).forEach(([i,s])=>{s&&(n&&(i=`${n}_${i}`),i==="url"?e.append(i,encodeURIComponent(s)):e.append(i,s))}),e.toString()},M=wt;var F={name:"@bringweb3/chrome-extension-kit",version:"1.3.11",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var At=()=>F.version,O=At;var yt=({query:t,theme:e,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:a})=>{let c=chrome.runtime.id,d=`bringweb3-iframe-${c}`,m=document.getElementById(d),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(m)return m;let p=M({query:{...t,extensionId:c,v:O(),themeMode:r,textMode:n,switchWallet:String(a)}}),h=e?`&${M({query:e,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=d,l.src=`${u}?${p}${h}`,l.setAttribute("sandbox","allow-scripts allow-same-origin"),l.style.position="fixed",l.scrolling="no",l.style.overflow="hidden",l.style.width="1px",l.style.height="1px",l.style.right="8px",l.style.borderRadius="10px",l.style.border="none",l.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(l.style.boxShadow=e.popupShadow),document.documentElement.appendChild(l),l},K=yt;var bt=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,n])=>{r in t.style&&(t.style[r]=n)})},$=bt;var Ot=t=>{if(!t||!t.length)return;let e=document.createElement("style");document.head.appendChild(e);let r=e.sheet;r?t.forEach(({name:n,rules:i})=>{r.insertRule(`@keyframes ${n} { ${i} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},j=Ot;var g={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},Tt=[g.ACTIVATE],vt=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:n,action:i,style:s,keyFrames:a,time:c,extensionId:d,url:m,domain:u,redirectUrl:p}=t.data;if(n==="bringweb3"&&!(d!==chrome.runtime.id&&!Tt.includes(i)))switch(i){case g.OPEN:$(e,s);break;case g.CLOSE:e&&e.parentNode?.removeChild(e),c&&chrome.runtime.sendMessage({action:i,time:c,domain:u,from:"bringweb3"});break;case g.PROMPT_LOGIN:r();break;case g.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3",domain:u,extensionId:d,time:c,redirectUrl:p});break;case g.OPT_OUT:chrome.runtime.sendMessage({action:i,time:c,from:"bringweb3"});break;case g.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:i,from:"bringweb3"});case g.ADD_KEYFRAMES:j(a);break;case g.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:i,url:m,from:"bringweb3"});break;default:break}},G=vt;var B=async({iframeEl:t,getWalletAddress:e})=>{if(!t&&(t=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!t)||!t.contentWindow)return;let r=await e();t.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},xt=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:n})=>{if(e)e(()=>B({iframeEl:n,getWalletAddress:r}));else if(t)for(let i=0;i<t.length;i++){let s=t[i];s&&window.addEventListener(s,async()=>B({iframeEl:n,getWalletAddress:r}))}},q=xt;var Pt=t=>t.endsWith("/")?t.slice(0,-1):t,T=Pt;var Dt=["www.","www1.","www2."],It=t=>{for(let r of Dt)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=T(e),e},N=It;var L=null,V=!1,Ct=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:a,text:c,switchWallet:d=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof n!="function")throw new Error("Missing configuration");q({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:t,iframeEl:L}),window.addEventListener("message",m=>G({event:m,iframeEl:L,promptLogin:e})),chrome.runtime.onMessage.addListener((m,u,p)=>{if(m?.from!=="bringweb3")return;let{action:h}=m;switch(h){case"GET_WALLET_ADDRESS":return t().then(l=>p({status:"success",walletAddress:l})).catch(l=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{if(N(location.href)!==N(m.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(V)return p({status:"failed",message:"iframe already open"}),!0;let{token:l,iframeUrl:b,userId:x}=m,P={token:l};return x&&(P.userId=x),L=K({query:P,iframeUrl:b,theme:a==="dark"?s:i,themeMode:a||"light",text:c,switchWallet:d,page:m.page}),V=!0,p({status:"success"}),!0}catch(l){return l instanceof Error?p({status:"failed",message:l.message}):p({status:"failed",message:String(l)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},H=Ct;var Q=t=>{t&&chrome.tabs.create({url:t})};var f=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}setWhitelistEndpoint(e){this.whitelistEndpoint=e}setApiEndpoint(e){this.apiEndpoint=e==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(e){this.apiKey=e}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var St=async(t,e)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),_t=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(n[`bring_${t}`])})}),kt=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),o={set:St,get:_t,remove:kt};var J=require("uuid"),Ut=async()=>{let t=await o.get("id");return t||(t=(0,J.v4)(),o.set("id",t)),t},E=Ut;var Mt=async t=>{let{path:e,method:r,params:n}=t;if(!t||!e||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let i=f.getInstance().getApiEndpoint();i+=e;let s=f.getInstance().getApiKey();if(r==="GET"){let d=new URLSearchParams({...n,version:O(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await E()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});i+=`?${d.toString()}`}else r==="POST"&&(n={...n,version:O(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await E()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(i,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},w=Mt;var Nt=async({body:t})=>await w({path:"/check/popup",method:"POST",params:t}),Y=Nt;var Lt=["www.","www1.","www2."],Wt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of Lt)t.startsWith(e)&&(t=t.replace(e,""));return t},z=Wt;var D="updateCache";var Rt=async(t,e)=>{let r=await o.get("quietDomains");typeof r=="object"?r[t]=e:r={[t]:e},o.set("quietDomains",r)},v=Rt;var Ft=async({walletAddress:t,cashbackUrl:e,lastActivation:r})=>{let n={walletAddress:t};return r&&(n.lastActivation=r),e&&(n.cashbackUrl=e),await w({path:"/check/notification",method:"POST",params:n})},X=Ft;var Kt=(t,e)=>new Promise((i,s)=>{let a=c=>{chrome.tabs.get(t,d=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},m=>{chrome.runtime.lastError?c<4?setTimeout(()=>a(c+1),1e3*Math.pow(2,c)):i(null):i(m||null)})})};a(0)}),A=Kt;var $t=async t=>{let e=await o.get("walletAddress");try{if(!t){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return e;t=n[0].id}let r=await A(t,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&e!==r?.walletAddress&&(e=r?.walletAddress,await o.set("walletAddress",e))}catch{}return e},I=$t;var jt=async(t,e,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},i=await o.get("notificationCheck");if(i&&Date.now()<i)return n;let s=e?await I(e):await o.get("walletAddress");if(!s)return n;let a=await o.get("lastActivation"),c=await X({walletAddress:s,cashbackUrl:r,lastActivation:a});o.set("notificationCheck",c.nextCall);let d={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:c.expiration};return d.showNotification&&await o.set("notification",d),d},C=jt;var Gt=t=>t?chrome.runtime.getURL(t):"",S=Gt;var Bt=async()=>{let t=f.getInstance().getWhitelistEndpoint(),e={path:"/domains",method:"GET"};return t&&(e.params={whitelist:encodeURIComponent(t)}),await w(e)},Z=Bt;var tt=async()=>{try{let t=f.getInstance().getWhitelistEndpoint();if(!t)return[];let e=await fetch(t,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!e.ok)throw new Error("Failed to fetch whitelist");let r=await e.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(t){return console.error("Error fetching whitelist:",t),[]}};var qt=t=>{let e=Date.now();return(t-e)/1e3/60},y=async()=>{let t=await o.get("relevantDomainsCheck"),e=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),i=f.getInstance().getWhitelistEndpoint();if(e?.length&&t&&t>Date.now()&&(!i||i&&r?.length))return e;let s=await Z(),{nextUpdateTimestamp:a,relevantDomains:c}=s;o.set("relevantDomains",c),o.set("relevantDomainsCheck",a),r=await tt(),r&&o.set("redirectsWhitelist",r);let d=qt(a);return chrome.alarms.create(D,{delayInMinutes:d||60*24*2}),c};var Vt=async(t,e)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await y(),e=await o.get("redirectsWhitelist")),!e?.length)return!r;let i=new URL(t).hostname.toLowerCase();return i=i.replace("www.",""),e.includes(i)?!0:e.some(s=>{if(s.startsWith("*.")){let a=s.slice(2);return i.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},_=Vt;var Ht=async(t,e,r,n,i,s,a)=>{if(e===chrome.runtime.id&&await o.set("lastActivation",Date.now()),t&&v(t,i||Date.now()+24*60*60*1e3),s&&a){let c=await o.get("redirectsWhitelist");await _(a,c)&&chrome.tabs.update(s,{url:a})}await C(r,void 0,S(n))},et=Ht;var rt=async t=>t<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+t),{isOptedOut:!0}),it=async()=>{let t=await o.get("optOut");return{isOptedOut:!!(t&&t>Date.now())}};var nt=async(t,e,r)=>{await A(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await E(),domain:r})},Qt=async(t,e,r,n)=>{let i=await o.get("notification");if(i?.expiration<Date.now())await o.remove("notification");else if(i)return await nt(e,i,n);let s=await C(t,e,S(r));if(s.showNotification)return await nt(e,s,n)},st=Qt;var Jt=async t=>{t.category=t?.category||"system",await w({path:"/analytics",method:"POST",params:t})},ot=Jt;var Yt=["www.","www1.","www2."],zt=async t=>{let e=await y();if(!t||!e||!e.length)return"";let r=null;try{r=new URL(t)}catch{r=new URL(`https://${t}`)}let n=r.hostname,i=T(r.pathname);for(let s of Yt)n=n.replace(s,"");for(let s of e){let a=s;s=T(s);let c=!1;s.startsWith("*.")&&(c=!0);let d="/"+s.split("/").slice(1).join("/")||"";if(d!=="/"&&i.startsWith(d)&&(n+=d),n===s||c&&n.endsWith(s.replace("*.",""))){let m=await o.get("quietDomains");return m&&m[s]&&Date.now()<m[s]&&m[s]<Date.now()+60*24*60*60*1e3?"":a}}return""},W={},Xt=async({identifier:t,apiEndpoint:e,cashbackPagePath:r,whitelistEndpoint:n})=>{if(!t||!e)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(e))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(e),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(t),y(),chrome.alarms.onAlarm.addListener(async i=>{let{name:s}=i;switch(s){case D:y();break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener((i,s,a)=>{if(i?.from!=="bringweb3")return;let{action:c}=i;switch(c){case"ACTIVATE":{let{domain:m,extensionId:u,time:p,redirectUrl:h}=i;return et(m,u,t,r,p,s.tab?.id,h).then(()=>a()),!0}case"GET_OPT_OUT":return it().then(m=>a(m)),!0;case"OPT_OUT":{let{time:m}=i;return rt(m).then(u=>a(u)),!0}case"CLOSE":{let{time:m,domain:u}=i;return u&&(v(u,m),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:m}=i;return m?o.set("walletAddress",m).then(()=>a(m)):o.remove("walletAddress").then(()=>a({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>a({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${c}`),!0;case"OPEN_CASHBACK_PAGE":let{url:d}=i;return Q(d||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(i,s,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let c=z(a.url),d=await o.get("optOut");if(d&&d>Date.now())return;d&&(o.remove("optOut"),o.remove("optOutKey"));let m=W[i];if(s.status!=="complete"||c===m)return;W[i]=c;let u=await zt(a.url);if(!u||!u.length){await st(t,i,r,c);return}let p=await I(i),{token:h,isValid:l,iframeUrl:b,networkUrl:x,flowId:P,time:lt=Date.now()+24*60*60*1e3}=await Y({body:{domain:u,url:a.url,address:p}});if(!l){l===!1&&v(u,lt);return}if(!await _(x,await o.get("redirectsWhitelist")))return;let R=await E(),k=await A(i,{action:"INJECT",token:h,domain:c,iframeUrl:b,userId:R});k?.status!=="success"&&ot({type:"no_popup",userId:R,walletAddress:p,details:{url:a.url,match:u,iframeUrl:b,reason:k?.message,status:k?.status},flowId:P})}),chrome.tabs.onRemoved.addListener(i=>delete W[i])},at=Xt;var ct=()=>new Promise((t,e)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_OPT_OUT"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),e(chrome.runtime.lastError);return}t({isTurnedOff:r.isOptedOut})})}),mt=t=>new Promise((e,r)=>{let n=t?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?e({isTurnedOff:i.isOptedOut}):r("No response received")})});0&&(module.exports={bringInitBackground,bringInitContentScript,getTurnOff,setTurnOff});
|
|
1
|
+
"use strict";var M=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ve=Object.prototype.hasOwnProperty;var De=(e,t)=>{for(var r in t)M(e,r,{get:t[r],enumerable:!0})},xe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Te(t))!ve.call(e,i)&&i!==r&&M(e,i,{get:()=>t[i],enumerable:!(n=Pe(t,i))||n.enumerable});return e};var Ce=e=>xe(M({},"__esModule",{value:!0}),e);var ut={};De(ut,{bringInitBackground:()=>ge,bringInitContentScript:()=>Z,getPopupEnabled:()=>Ee,getTurnOff:()=>he,setPopupEnabled:()=>be,setTurnOff:()=>we});module.exports=Ce(ut);var Ie=e=>{let t=new URLSearchParams,{query:r,prefix:n}=e;return Object.entries(r).forEach(([i,s])=>{s&&(n&&(i=`${n}_${i}`),i==="url"?t.append(i,encodeURIComponent(s)):t.append(i,s))}),t.toString()},W=Ie;var V={name:"@bringweb3/chrome-extension-kit",version:"1.4.1",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var Se=()=>V.version,x=Se;var Ue=({query:e,theme:t,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:m})=>{let l=chrome.runtime.id,c=`bringweb3-iframe-${l}`,d=document.getElementById(c),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(d)return d;let p=W({query:{...e,extensionId:l,v:x(),themeMode:r,textMode:n,switchWallet:String(m)}}),h=t?`&${W({query:t,prefix:"t"})}`:"",a=document.createElement("iframe");return a.id=c,a.src=`${u}?${p}${h}`,a.setAttribute("sandbox","allow-scripts allow-same-origin"),a.style.position="fixed",a.scrolling="no",a.style.overflow="hidden",a.style.width="1px",a.style.height="1px",a.style.right="8px",a.style.borderRadius="10px",a.style.border="none",a.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(a.style.boxShadow=t.popupShadow),document.documentElement.appendChild(a),a},H=Ue;var ke=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,n])=>{r in e.style&&(e.style[r]=n)})},Q=ke;var Ne=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let r=t.sheet;r?e.forEach(({name:n,rules:i})=>{r.insertRule(`@keyframes ${n} { ${i} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},q=Ne;var E={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",OPT_OUT_SPECIFIC:"OPT_OUT_SPECIFIC",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},Le=[E.ACTIVATE],Me=({event:e,iframeEl:t,promptLogin:r})=>{if(!e?.data)return;let{from:n,action:i,style:s,keyFrames:m,time:l,extensionId:c,url:d,domain:u,redirectUrl:p}=e.data;if(n==="bringweb3"&&!(c!==chrome.runtime.id&&!Le.includes(i)))switch(i){case E.OPEN:Q(t,s);break;case E.CLOSE:t&&t.parentNode?.removeChild(t),l&&chrome.runtime.sendMessage({action:i,time:l,domain:u,from:"bringweb3"});break;case E.PROMPT_LOGIN:r();break;case E.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3",domain:u,extensionId:c,time:l,redirectUrl:p});break;case E.OPT_OUT:chrome.runtime.sendMessage({action:i,time:l,from:"bringweb3"});break;case E.OPT_OUT_SPECIFIC:chrome.runtime.sendMessage({action:i,domain:u,time:l,from:"bringweb3"});break;case E.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:i,from:"bringweb3"});case E.ADD_KEYFRAMES:q(m);break;case E.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:i,url:d,from:"bringweb3"});break;default:break}},J=Me;var Y=async({iframeEl:e,getWalletAddress:t})=>{if(!e&&(e=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!e)||!e.contentWindow)return;let r=await t();e.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},We=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:r,iframeEl:n})=>{if(t)t(()=>Y({iframeEl:n,getWalletAddress:r}));else if(e)for(let i=0;i<e.length;i++){let s=e[i];s&&window.addEventListener(s,async()=>Y({iframeEl:n,getWalletAddress:r}))}},z=We;var Re=e=>e.endsWith("/")?e.slice(0,-1):e,C=Re;var Fe=["www.","www1.","www2."],Ke=e=>{for(let r of Fe)e=e.replace(r,"");let t="";try{t=new URL(e).host}catch{t=new URL(`https://${e}`).host}return t=C(t),t},b=Ke;var R=null,X=!1,$e=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:m,text:l,switchWallet:c=!1})=>{if(window.self===window.top){if(!e||!t||!r?.length&&typeof n!="function")throw new Error("Missing configuration");z({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:e,iframeEl:R}),window.addEventListener("message",d=>J({event:d,iframeEl:R,promptLogin:t})),chrome.runtime.onMessage.addListener((d,u,p)=>{if(d?.from!=="bringweb3")return;let{action:h}=d;switch(h){case"GET_WALLET_ADDRESS":return e().then(a=>p({status:"success",walletAddress:a})).catch(a=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{let{referrer:a}=document,g=d.portalReferrers||[];if(b(location.href)!==b(d.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(X)return p({status:"failed",message:"iframe already open"}),!0;if(a&&g.includes(b(a)))return p({status:"failed",message:`already activated by ${b(a)}`,action:"activate"}),!0;let{token:y,iframeUrl:w,userId:D}=d,_={token:y};return D&&(_.userId=D),R=H({query:_,iframeUrl:w,theme:m==="dark"?s:i,themeMode:m||"light",text:l,switchWallet:c,page:d.page}),X=!0,p({status:"success"}),!0}catch(a){return a instanceof Error?p({status:"failed",message:a.message}):p({status:"failed",message:String(a)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},Z=$e;var ee=e=>{e&&chrome.tabs.create({url:e})};var f=class e{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setWhitelistEndpoint(t){this.whitelistEndpoint=t}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(t){this.apiKey=t}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var Ge=async(e,t)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),Be=async e=>new Promise((t,r)=>{chrome.storage.local.get([`bring_${e}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t(n[`bring_${e}`])})}),je=async e=>new Promise((t,r)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t()})}),o={set:Ge,get:Be,remove:je};var te=require("uuid"),Ve=async()=>{let e=await o.get("id");return e||(e=(0,te.v4)(),o.set("id",e)),e},O=Ve;var He=async e=>{let{path:t,method:r,params:n}=e;if(!e||!t||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let i=f.getInstance().getApiEndpoint();i+=t;let s=f.getInstance().getApiKey();if(r==="GET"){let c=new URLSearchParams({...n,version:x(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await O()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});i+=`?${c.toString()}`}else r==="POST"&&(n={...n,version:x(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await O()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(i,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},A=He;var Qe=async({body:e})=>await A({path:"/check/popup",method:"POST",params:e}),re=Qe;var qe=["www.","www1.","www2."],Je=e=>{if(!e)return"";e=e.split("://").reverse()[0]||"";for(let t of qe)e.startsWith(t)&&(e=e.replace(t,""));return e},ne=Je;var S="updateCache";var ie="quietDomains",Ye=async(e,t)=>{let r=await o.get(ie);typeof r=="object"?r[e]=t:r={[e]:t},o.set(ie,r)},I=Ye;var ze=async({walletAddress:e,cashbackUrl:t,lastActivation:r})=>{let n={walletAddress:e};return r&&(n.lastActivation=r),t&&(n.cashbackUrl=t),await A({path:"/check/notification",method:"POST",params:n})},oe=ze;var Xe=(e,t)=>new Promise((i,s)=>{let m=l=>{chrome.tabs.get(e,c=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(e,{...t,from:"bringweb3"},d=>{chrome.runtime.lastError?l<4?setTimeout(()=>m(l+1),1e3*Math.pow(2,l)):i(null):i(d||null)})})};m(0)}),T=Xe;var Ze=async e=>{let t=await o.get("walletAddress");try{if(!e){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return t;e=n[0].id}let r=await T(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await o.set("walletAddress",t))}catch{}return t},U=Ze;var et=async(e,t,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},i=await o.get("notificationCheck");if(i&&Date.now()<i)return n;let s=t?await U(t):await o.get("walletAddress");if(!s)return n;let m=await o.get("lastActivation"),l=await oe({walletAddress:s,cashbackUrl:r,lastActivation:m});o.set("notificationCheck",l.nextCall);let c={showNotification:l.showNotification,token:l.token,iframeUrl:l.iframeUrl,expiration:l.expiration};return c.showNotification&&await o.set("notification",c),c},k=et;var tt=e=>e?chrome.runtime.getURL(e):"",N=tt;var rt=async()=>{let e=f.getInstance().getWhitelistEndpoint(),t={path:"/domains",method:"GET"};return e&&(t.params={whitelist:encodeURIComponent(e)}),await A(t)},se=rt;var ae=async()=>{try{let e=f.getInstance().getWhitelistEndpoint();if(!e)return[];let t=await fetch(e,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!t.ok)throw new Error("Failed to fetch whitelist");let r=await t.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(e){return console.error("Error fetching whitelist:",e),[]}};var nt=e=>{let t=Date.now();return(e-t)/1e3/60},v=async()=>{let e=await o.get("relevantDomainsCheck"),t=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),i=f.getInstance().getWhitelistEndpoint();if(t?.length&&e&&e>Date.now()&&(!i||i&&r?.length))return t;let s=await se(),{nextUpdateTimestamp:m,relevantDomains:l}=s;o.set("relevantDomains",l),o.set("relevantDomainsCheck",m),r=await ae(),r&&o.set("redirectsWhitelist",r);let c=nt(m);return chrome.alarms.create(S,{delayInMinutes:c||60*24*2}),l};var it=async(e,t)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!t?.length&&(await v(),t=await o.get("redirectsWhitelist")),!t?.length)return!r;let i=new URL(e).hostname.toLowerCase();return i=i.replace("www.",""),t.includes(i)?!0:t.some(s=>{if(s.startsWith("*.")){let m=s.slice(2);return i.endsWith(m)}return!1})}catch{return console.error("Invalid URL:",e),!1}},L=it;var ot=async(e,t,r,n,i,s,m)=>{if(t===chrome.runtime.id&&await o.set("lastActivation",Date.now()),e&&I(e,i||Date.now()+24*60*60*1e3),s&&m){let l=await o.get("redirectsWhitelist");await L(m,l)&&chrome.tabs.update(s,{url:m})}await k(r,void 0,N(n))},F=ot;var ce=async e=>e<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+e),{isOptedOut:!0}),le=async()=>{let e=await o.get("optOut");return{isOptedOut:!!(e&&e>Date.now())}};var me=async(e,t,r)=>{await T(e,{action:"INJECT",page:"notification",token:t.token,iframeUrl:t.iframeUrl,userId:await O(),domain:r})},st=async(e,t,r,n,i,s)=>{let m=await o.get("notification");if(m?.expiration<Date.now())await o.remove("notification");else if(m)return await me(t,m,n);let l=await k(e,t,N(r));l.showNotification&&(i&&await me(t,l,n),s&&s())},de=st;var at=async e=>{e.category=e?.category||"system",await A({path:"/analytics",method:"POST",params:e})},ue=at;var pe="optOutDomains",ct=async(e,t)=>{if(!e)return;let r=await o.get(pe);typeof r=="object"?r[e]=t:r={[e]:t},o.set(pe,r)},fe=ct;var lt=["www.","www1.","www2."],mt=async e=>{let t=await v();if(!e||!t||!t.length)return"";let r=null;try{r=new URL(e)}catch{r=new URL(`https://${e}`)}let n=r.hostname,i=C(r.pathname);for(let s of lt)n=n.replace(s,"");for(let s of t){let m=s;s=C(s);let l=!1;s.startsWith("*.")&&(l=!0);let c="/"+s.split("/").slice(1).join("/")||"";if(c!=="/"&&i.startsWith(c)&&(n+=c),n===s||l&&n.endsWith(s.replace("*.",""))){let d=await o.get("quietDomains");return d&&d[s]&&Date.now()<d[s]&&d[s]<Date.now()+60*24*60*60*1e3?"":m}}return""},K={},dt=async({identifier:e,apiEndpoint:t,cashbackPagePath:r,whitelistEndpoint:n,isEnabledByDefault:i=!0,showNotifications:s=!0,notificationCallback:m})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(t),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(e),await o.get("popupEnabled")===void 0&&await o.set("popupEnabled",i),v(),chrome.alarms.onAlarm.addListener(async c=>{let{name:d}=c;switch(d){case S:v();break;default:console.error("alarm with no use case:",d);break}}),chrome.runtime.onMessage.addListener((c,d,u)=>{if(c?.from!=="bringweb3")return;let{action:p}=c;switch(p){case"ACTIVATE":{let{domain:a,extensionId:g,time:y,redirectUrl:w}=c;return F(a,g,e,r,y,d.tab?.id,w).then(()=>u()),!0}case"GET_OPT_OUT":return le().then(a=>u(a)),!0;case"OPT_OUT":{let{time:a}=c;return ce(a).then(g=>u(g)),!0}case"OPT_OUT_SPECIFIC":{let{domain:a,time:g}=c;return fe(a,g).then(y=>u(y)),!0}case"GET_POPUP_ENABLED":return o.get("popupEnabled").then(a=>u({isPopupEnabled:a})),!0;case"SET_POPUP_ENABLED":{let{isPopupEnabled:a}=c;return o.set("popupEnabled",a).then(()=>{u({isPopupEnabled:a})}).catch(g=>{console.error("Error setting popup enabled:",g),u({error:"Failed to set popup enabled state"})}),!0}case"CLOSE":{let{time:a,domain:g}=c;return g&&(I(g,a),u({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:a}=c;return a?o.set("walletAddress",a).then(()=>u(a)):o.remove("walletAddress").then(()=>u({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>u({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${p}`),!0;case"OPEN_CASHBACK_PAGE":let{url:h}=c;return ee(h||r),u({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(c,d,u)=>{if(!u?.url?.startsWith("http")||!u.url)return;let p=ne(u.url),h=await o.get("optOut");if(!await o.get("popupEnabled")||h&&h>Date.now())return;h&&(o.remove("optOut"),o.remove("optOutKey"));let g=await o.get("optOutDomains");if(g&&g[b(p)]&&g[b(p)]>Date.now())return;let y=K[c];if(d.status!=="complete"||p===y)return;K[c]=p;let w=await mt(u.url);if(!w||!w.length){await de(e,c,r,p,s,m);return}let D=await U(c),{token:_,isValid:$,iframeUrl:G,networkUrl:Ae,flowId:ye,portalReferrers:Oe,time:B=Date.now()+24*60*60*1e3}=await re({body:{domain:w,url:u.url,address:D}});if(!$){$===!1&&I(w,B);return}if(!await L(Ae,await o.get("redirectsWhitelist")))return;let j=await O(),P=await T(c,{action:"INJECT",token:_,domain:p,iframeUrl:G,userId:j,portalReferrers:Oe});if(P?.action)switch(P.action){case"activate":F(w,chrome.runtime.id,e,r,B,c);break;default:console.error(`Unknown action: ${P.action}`);break}P?.status!=="success"&&ue({type:"no_popup",userId:j,walletAddress:D,details:{url:u.url,match:w,iframeUrl:G,reason:P?.message,status:P?.status},flowId:ye})}),chrome.tabs.onRemoved.addListener(c=>delete K[c])},ge=dt;var he=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_OPT_OUT"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e({isTurnedOff:r.isOptedOut})})}),we=e=>new Promise((t,r)=>{let n=e?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?t({isTurnedOff:i.isOptedOut}):r("No response received")})});var Ee=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_POPUP_ENABLED"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e(r)})}),be=e=>new Promise((t,r)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"SET_POPUP_ENABLED",isPopupEnabled:e},n=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}n?t({isPopupEnabled:n.isPopupEnabled}):r("No response received")})});0&&(module.exports={bringInitBackground,bringInitContentScript,getPopupEnabled,getTurnOff,setPopupEnabled,setTurnOff});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var st=t=>{let e=new URLSearchParams,{query:r,prefix:n}=t;return Object.entries(r).forEach(([i,s])=>{s&&(n&&(i=`${n}_${i}`),i==="url"?e.append(i,encodeURIComponent(s)):e.append(i,s))}),e.toString()},U=st;var R={name:"@bringweb3/chrome-extension-kit",version:"1.3.11",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var at=()=>R.version,O=at;var ct=({query:t,theme:e,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:a})=>{let c=chrome.runtime.id,d=`bringweb3-iframe-${c}`,m=document.getElementById(d),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(m)return m;let p=U({query:{...t,extensionId:c,v:O(),themeMode:r,textMode:n,switchWallet:String(a)}}),h=e?`&${U({query:e,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=d,l.src=`${u}?${p}${h}`,l.setAttribute("sandbox","allow-scripts allow-same-origin"),l.style.position="fixed",l.scrolling="no",l.style.overflow="hidden",l.style.width="1px",l.style.height="1px",l.style.right="8px",l.style.borderRadius="10px",l.style.border="none",l.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(l.style.boxShadow=e.popupShadow),document.documentElement.appendChild(l),l},F=ct;var mt=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,n])=>{r in t.style&&(t.style[r]=n)})},K=mt;var lt=t=>{if(!t||!t.length)return;let e=document.createElement("style");document.head.appendChild(e);let r=e.sheet;r?t.forEach(({name:n,rules:i})=>{r.insertRule(`@keyframes ${n} { ${i} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},$=lt;var g={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},dt=[g.ACTIVATE],ut=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:n,action:i,style:s,keyFrames:a,time:c,extensionId:d,url:m,domain:u,redirectUrl:p}=t.data;if(n==="bringweb3"&&!(d!==chrome.runtime.id&&!dt.includes(i)))switch(i){case g.OPEN:K(e,s);break;case g.CLOSE:e&&e.parentNode?.removeChild(e),c&&chrome.runtime.sendMessage({action:i,time:c,domain:u,from:"bringweb3"});break;case g.PROMPT_LOGIN:r();break;case g.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3",domain:u,extensionId:d,time:c,redirectUrl:p});break;case g.OPT_OUT:chrome.runtime.sendMessage({action:i,time:c,from:"bringweb3"});break;case g.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:i,from:"bringweb3"});case g.ADD_KEYFRAMES:$(a);break;case g.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:i,url:m,from:"bringweb3"});break;default:break}},j=ut;var G=async({iframeEl:t,getWalletAddress:e})=>{if(!t&&(t=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!t)||!t.contentWindow)return;let r=await e();t.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},ft=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:n})=>{if(e)e(()=>G({iframeEl:n,getWalletAddress:r}));else if(t)for(let i=0;i<t.length;i++){let s=t[i];s&&window.addEventListener(s,async()=>G({iframeEl:n,getWalletAddress:r}))}},B=ft;var pt=t=>t.endsWith("/")?t.slice(0,-1):t,T=pt;var gt=["www.","www1.","www2."],ht=t=>{for(let r of gt)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=T(e),e},M=ht;var N=null,q=!1,wt=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:a,text:c,switchWallet:d=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof n!="function")throw new Error("Missing configuration");B({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:t,iframeEl:N}),window.addEventListener("message",m=>j({event:m,iframeEl:N,promptLogin:e})),chrome.runtime.onMessage.addListener((m,u,p)=>{if(m?.from!=="bringweb3")return;let{action:h}=m;switch(h){case"GET_WALLET_ADDRESS":return t().then(l=>p({status:"success",walletAddress:l})).catch(l=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{if(M(location.href)!==M(m.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(q)return p({status:"failed",message:"iframe already open"}),!0;let{token:l,iframeUrl:b,userId:x}=m,P={token:l};return x&&(P.userId=x),N=F({query:P,iframeUrl:b,theme:a==="dark"?s:i,themeMode:a||"light",text:c,switchWallet:d,page:m.page}),q=!0,p({status:"success"}),!0}catch(l){return l instanceof Error?p({status:"failed",message:l.message}):p({status:"failed",message:String(l)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},Et=wt;var V=t=>{t&&chrome.tabs.create({url:t})};var f=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}setWhitelistEndpoint(e){this.whitelistEndpoint=e}setApiEndpoint(e){this.apiEndpoint=e==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(e){this.apiKey=e}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var At=async(t,e)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),yt=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(n[`bring_${t}`])})}),bt=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),o={set:At,get:yt,remove:bt};import{v4 as Ot}from"uuid";var Tt=async()=>{let t=await o.get("id");return t||(t=Ot(),o.set("id",t)),t},E=Tt;var vt=async t=>{let{path:e,method:r,params:n}=t;if(!t||!e||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let i=f.getInstance().getApiEndpoint();i+=e;let s=f.getInstance().getApiKey();if(r==="GET"){let d=new URLSearchParams({...n,version:O(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await E()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});i+=`?${d.toString()}`}else r==="POST"&&(n={...n,version:O(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await E()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(i,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},w=vt;var xt=async({body:t})=>await w({path:"/check/popup",method:"POST",params:t}),H=xt;var Pt=["www.","www1.","www2."],Dt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of Pt)t.startsWith(e)&&(t=t.replace(e,""));return t},Q=Dt;var D="updateCache";var It=async(t,e)=>{let r=await o.get("quietDomains");typeof r=="object"?r[t]=e:r={[t]:e},o.set("quietDomains",r)},v=It;var Ct=async({walletAddress:t,cashbackUrl:e,lastActivation:r})=>{let n={walletAddress:t};return r&&(n.lastActivation=r),e&&(n.cashbackUrl=e),await w({path:"/check/notification",method:"POST",params:n})},J=Ct;var St=(t,e)=>new Promise((i,s)=>{let a=c=>{chrome.tabs.get(t,d=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},m=>{chrome.runtime.lastError?c<4?setTimeout(()=>a(c+1),1e3*Math.pow(2,c)):i(null):i(m||null)})})};a(0)}),A=St;var _t=async t=>{let e=await o.get("walletAddress");try{if(!t){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return e;t=n[0].id}let r=await A(t,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&e!==r?.walletAddress&&(e=r?.walletAddress,await o.set("walletAddress",e))}catch{}return e},I=_t;var kt=async(t,e,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},i=await o.get("notificationCheck");if(i&&Date.now()<i)return n;let s=e?await I(e):await o.get("walletAddress");if(!s)return n;let a=await o.get("lastActivation"),c=await J({walletAddress:s,cashbackUrl:r,lastActivation:a});o.set("notificationCheck",c.nextCall);let d={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:c.expiration};return d.showNotification&&await o.set("notification",d),d},C=kt;var Ut=t=>t?chrome.runtime.getURL(t):"",S=Ut;var Mt=async()=>{let t=f.getInstance().getWhitelistEndpoint(),e={path:"/domains",method:"GET"};return t&&(e.params={whitelist:encodeURIComponent(t)}),await w(e)},Y=Mt;var z=async()=>{try{let t=f.getInstance().getWhitelistEndpoint();if(!t)return[];let e=await fetch(t,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!e.ok)throw new Error("Failed to fetch whitelist");let r=await e.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(t){return console.error("Error fetching whitelist:",t),[]}};var Nt=t=>{let e=Date.now();return(t-e)/1e3/60},y=async()=>{let t=await o.get("relevantDomainsCheck"),e=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),i=f.getInstance().getWhitelistEndpoint();if(e?.length&&t&&t>Date.now()&&(!i||i&&r?.length))return e;let s=await Y(),{nextUpdateTimestamp:a,relevantDomains:c}=s;o.set("relevantDomains",c),o.set("relevantDomainsCheck",a),r=await z(),r&&o.set("redirectsWhitelist",r);let d=Nt(a);return chrome.alarms.create(D,{delayInMinutes:d||60*24*2}),c};var Lt=async(t,e)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await y(),e=await o.get("redirectsWhitelist")),!e?.length)return!r;let i=new URL(t).hostname.toLowerCase();return i=i.replace("www.",""),e.includes(i)?!0:e.some(s=>{if(s.startsWith("*.")){let a=s.slice(2);return i.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},_=Lt;var Wt=async(t,e,r,n,i,s,a)=>{if(e===chrome.runtime.id&&await o.set("lastActivation",Date.now()),t&&v(t,i||Date.now()+24*60*60*1e3),s&&a){let c=await o.get("redirectsWhitelist");await _(a,c)&&chrome.tabs.update(s,{url:a})}await C(r,void 0,S(n))},X=Wt;var Z=async t=>t<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+t),{isOptedOut:!0}),tt=async()=>{let t=await o.get("optOut");return{isOptedOut:!!(t&&t>Date.now())}};var et=async(t,e,r)=>{await A(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await E(),domain:r})},Rt=async(t,e,r,n)=>{let i=await o.get("notification");if(i?.expiration<Date.now())await o.remove("notification");else if(i)return await et(e,i,n);let s=await C(t,e,S(r));if(s.showNotification)return await et(e,s,n)},rt=Rt;var Ft=async t=>{t.category=t?.category||"system",await w({path:"/analytics",method:"POST",params:t})},it=Ft;var Kt=["www.","www1.","www2."],$t=async t=>{let e=await y();if(!t||!e||!e.length)return"";let r=null;try{r=new URL(t)}catch{r=new URL(`https://${t}`)}let n=r.hostname,i=T(r.pathname);for(let s of Kt)n=n.replace(s,"");for(let s of e){let a=s;s=T(s);let c=!1;s.startsWith("*.")&&(c=!0);let d="/"+s.split("/").slice(1).join("/")||"";if(d!=="/"&&i.startsWith(d)&&(n+=d),n===s||c&&n.endsWith(s.replace("*.",""))){let m=await o.get("quietDomains");return m&&m[s]&&Date.now()<m[s]&&m[s]<Date.now()+60*24*60*60*1e3?"":a}}return""},L={},jt=async({identifier:t,apiEndpoint:e,cashbackPagePath:r,whitelistEndpoint:n})=>{if(!t||!e)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(e))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(e),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(t),y(),chrome.alarms.onAlarm.addListener(async i=>{let{name:s}=i;switch(s){case D:y();break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener((i,s,a)=>{if(i?.from!=="bringweb3")return;let{action:c}=i;switch(c){case"ACTIVATE":{let{domain:m,extensionId:u,time:p,redirectUrl:h}=i;return X(m,u,t,r,p,s.tab?.id,h).then(()=>a()),!0}case"GET_OPT_OUT":return tt().then(m=>a(m)),!0;case"OPT_OUT":{let{time:m}=i;return Z(m).then(u=>a(u)),!0}case"CLOSE":{let{time:m,domain:u}=i;return u&&(v(u,m),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:m}=i;return m?o.set("walletAddress",m).then(()=>a(m)):o.remove("walletAddress").then(()=>a({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>a({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${c}`),!0;case"OPEN_CASHBACK_PAGE":let{url:d}=i;return V(d||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(i,s,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let c=Q(a.url),d=await o.get("optOut");if(d&&d>Date.now())return;d&&(o.remove("optOut"),o.remove("optOutKey"));let m=L[i];if(s.status!=="complete"||c===m)return;L[i]=c;let u=await $t(a.url);if(!u||!u.length){await rt(t,i,r,c);return}let p=await I(i),{token:h,isValid:l,iframeUrl:b,networkUrl:x,flowId:P,time:nt=Date.now()+24*60*60*1e3}=await H({body:{domain:u,url:a.url,address:p}});if(!l){l===!1&&v(u,nt);return}if(!await _(x,await o.get("redirectsWhitelist")))return;let W=await E(),k=await A(i,{action:"INJECT",token:h,domain:c,iframeUrl:b,userId:W});k?.status!=="success"&&it({type:"no_popup",userId:W,walletAddress:p,details:{url:a.url,match:u,iframeUrl:b,reason:k?.message,status:k?.status},flowId:P})}),chrome.tabs.onRemoved.addListener(i=>delete L[i])},Gt=jt;var Bt=()=>new Promise((t,e)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_OPT_OUT"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),e(chrome.runtime.lastError);return}t({isTurnedOff:r.isOptedOut})})}),qt=t=>new Promise((e,r)=>{let n=t?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?e({isTurnedOff:i.isOptedOut}):r("No response received")})});export{Gt as bringInitBackground,Et as bringInitContentScript,Bt as getTurnOff,qt as setTurnOff};
|
|
1
|
+
var ge=e=>{let t=new URLSearchParams,{query:r,prefix:n}=e;return Object.entries(r).forEach(([o,s])=>{s&&(n&&(o=`${n}_${o}`),o==="url"?t.append(o,encodeURIComponent(s)):t.append(o,s))}),t.toString()},M=ge;var j={name:"@bringweb3/chrome-extension-kit",version:"1.4.1",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var we=()=>j.version,x=we;var Ee=({query:e,theme:t,themeMode:r,text:n,iframeUrl:o,page:s,switchWallet:m})=>{let l=chrome.runtime.id,c=`bringweb3-iframe-${l}`,d=document.getElementById(c),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:o;if(d)return d;let p=M({query:{...e,extensionId:l,v:x(),themeMode:r,textMode:n,switchWallet:String(m)}}),h=t?`&${M({query:t,prefix:"t"})}`:"",a=document.createElement("iframe");return a.id=c,a.src=`${u}?${p}${h}`,a.setAttribute("sandbox","allow-scripts allow-same-origin"),a.style.position="fixed",a.scrolling="no",a.style.overflow="hidden",a.style.width="1px",a.style.height="1px",a.style.right="8px",a.style.borderRadius="10px",a.style.border="none",a.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(a.style.boxShadow=t.popupShadow),document.documentElement.appendChild(a),a},V=Ee;var be=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,n])=>{r in e.style&&(e.style[r]=n)})},H=be;var Ae=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let r=t.sheet;r?e.forEach(({name:n,rules:o})=>{r.insertRule(`@keyframes ${n} { ${o} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},Q=Ae;var E={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",OPT_OUT_SPECIFIC:"OPT_OUT_SPECIFIC",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},ye=[E.ACTIVATE],Oe=({event:e,iframeEl:t,promptLogin:r})=>{if(!e?.data)return;let{from:n,action:o,style:s,keyFrames:m,time:l,extensionId:c,url:d,domain:u,redirectUrl:p}=e.data;if(n==="bringweb3"&&!(c!==chrome.runtime.id&&!ye.includes(o)))switch(o){case E.OPEN:H(t,s);break;case E.CLOSE:t&&t.parentNode?.removeChild(t),l&&chrome.runtime.sendMessage({action:o,time:l,domain:u,from:"bringweb3"});break;case E.PROMPT_LOGIN:r();break;case E.ACTIVATE:chrome.runtime.sendMessage({action:o,from:"bringweb3",domain:u,extensionId:c,time:l,redirectUrl:p});break;case E.OPT_OUT:chrome.runtime.sendMessage({action:o,time:l,from:"bringweb3"});break;case E.OPT_OUT_SPECIFIC:chrome.runtime.sendMessage({action:o,domain:u,time:l,from:"bringweb3"});break;case E.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:o,from:"bringweb3"});case E.ADD_KEYFRAMES:Q(m);break;case E.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:o,url:d,from:"bringweb3"});break;default:break}},q=Oe;var J=async({iframeEl:e,getWalletAddress:t})=>{if(!e&&(e=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!e)||!e.contentWindow)return;let r=await t();e.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},Pe=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:r,iframeEl:n})=>{if(t)t(()=>J({iframeEl:n,getWalletAddress:r}));else if(e)for(let o=0;o<e.length;o++){let s=e[o];s&&window.addEventListener(s,async()=>J({iframeEl:n,getWalletAddress:r}))}},Y=Pe;var Te=e=>e.endsWith("/")?e.slice(0,-1):e,C=Te;var ve=["www.","www1.","www2."],De=e=>{for(let r of ve)e=e.replace(r,"");let t="";try{t=new URL(e).host}catch{t=new URL(`https://${e}`).host}return t=C(t),t},b=De;var W=null,z=!1,xe=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:o,darkTheme:s,theme:m,text:l,switchWallet:c=!1})=>{if(window.self===window.top){if(!e||!t||!r?.length&&typeof n!="function")throw new Error("Missing configuration");Y({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:e,iframeEl:W}),window.addEventListener("message",d=>q({event:d,iframeEl:W,promptLogin:t})),chrome.runtime.onMessage.addListener((d,u,p)=>{if(d?.from!=="bringweb3")return;let{action:h}=d;switch(h){case"GET_WALLET_ADDRESS":return e().then(a=>p({status:"success",walletAddress:a})).catch(a=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{let{referrer:a}=document,g=d.portalReferrers||[];if(b(location.href)!==b(d.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(z)return p({status:"failed",message:"iframe already open"}),!0;if(a&&g.includes(b(a)))return p({status:"failed",message:`already activated by ${b(a)}`,action:"activate"}),!0;let{token:y,iframeUrl:w,userId:D}=d,_={token:y};return D&&(_.userId=D),W=V({query:_,iframeUrl:w,theme:m==="dark"?s:o,themeMode:m||"light",text:l,switchWallet:c,page:d.page}),z=!0,p({status:"success"}),!0}catch(a){return a instanceof Error?p({status:"failed",message:a.message}):p({status:"failed",message:String(a)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},Ce=xe;var X=e=>{e&&chrome.tabs.create({url:e})};var f=class e{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setWhitelistEndpoint(t){this.whitelistEndpoint=t}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(t){this.apiKey=t}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var Ie=async(e,t)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),_e=async e=>new Promise((t,r)=>{chrome.storage.local.get([`bring_${e}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t(n[`bring_${e}`])})}),Se=async e=>new Promise((t,r)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t()})}),i={set:Ie,get:_e,remove:Se};import{v4 as Ue}from"uuid";var ke=async()=>{let e=await i.get("id");return e||(e=Ue(),i.set("id",e)),e},O=ke;var Ne=async e=>{let{path:t,method:r,params:n}=e;if(!e||!t||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let o=f.getInstance().getApiEndpoint();o+=t;let s=f.getInstance().getApiKey();if(r==="GET"){let c=new URLSearchParams({...n,version:x(),timestamp:Date.now().toString(),opt_out:await i.get("optOut")||0,user_id:await O()||"undefined",wallet_address:await i.get("walletAddress")||"undefined"});o+=`?${c.toString()}`}else r==="POST"&&(n={...n,version:x(),timestamp:Date.now(),optOut:await i.get("optOut")||0,userId:await O()||void 0,walletAddress:n?.walletAddress||await i.get("walletAddress")||void 0});return await(await fetch(o,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},A=Ne;var Le=async({body:e})=>await A({path:"/check/popup",method:"POST",params:e}),Z=Le;var Me=["www.","www1.","www2."],We=e=>{if(!e)return"";e=e.split("://").reverse()[0]||"";for(let t of Me)e.startsWith(t)&&(e=e.replace(t,""));return e},ee=We;var S="updateCache";var te="quietDomains",Re=async(e,t)=>{let r=await i.get(te);typeof r=="object"?r[e]=t:r={[e]:t},i.set(te,r)},I=Re;var Fe=async({walletAddress:e,cashbackUrl:t,lastActivation:r})=>{let n={walletAddress:e};return r&&(n.lastActivation=r),t&&(n.cashbackUrl=t),await A({path:"/check/notification",method:"POST",params:n})},re=Fe;var Ke=(e,t)=>new Promise((o,s)=>{let m=l=>{chrome.tabs.get(e,c=>{if(chrome.runtime.lastError){o(null);return}chrome.tabs.sendMessage(e,{...t,from:"bringweb3"},d=>{chrome.runtime.lastError?l<4?setTimeout(()=>m(l+1),1e3*Math.pow(2,l)):o(null):o(d||null)})})};m(0)}),T=Ke;var $e=async e=>{let t=await i.get("walletAddress");try{if(!e){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return t;e=n[0].id}let r=await T(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await i.set("walletAddress",t))}catch{}return t},U=$e;var Ge=async(e,t,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},o=await i.get("notificationCheck");if(o&&Date.now()<o)return n;let s=t?await U(t):await i.get("walletAddress");if(!s)return n;let m=await i.get("lastActivation"),l=await re({walletAddress:s,cashbackUrl:r,lastActivation:m});i.set("notificationCheck",l.nextCall);let c={showNotification:l.showNotification,token:l.token,iframeUrl:l.iframeUrl,expiration:l.expiration};return c.showNotification&&await i.set("notification",c),c},k=Ge;var Be=e=>e?chrome.runtime.getURL(e):"",N=Be;var je=async()=>{let e=f.getInstance().getWhitelistEndpoint(),t={path:"/domains",method:"GET"};return e&&(t.params={whitelist:encodeURIComponent(e)}),await A(t)},ne=je;var ie=async()=>{try{let e=f.getInstance().getWhitelistEndpoint();if(!e)return[];let t=await fetch(e,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!t.ok)throw new Error("Failed to fetch whitelist");let r=await t.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(e){return console.error("Error fetching whitelist:",e),[]}};var Ve=e=>{let t=Date.now();return(e-t)/1e3/60},v=async()=>{let e=await i.get("relevantDomainsCheck"),t=await i.get("relevantDomains"),r=await i.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),o=f.getInstance().getWhitelistEndpoint();if(t?.length&&e&&e>Date.now()&&(!o||o&&r?.length))return t;let s=await ne(),{nextUpdateTimestamp:m,relevantDomains:l}=s;i.set("relevantDomains",l),i.set("relevantDomainsCheck",m),r=await ie(),r&&i.set("redirectsWhitelist",r);let c=Ve(m);return chrome.alarms.create(S,{delayInMinutes:c||60*24*2}),l};var He=async(e,t)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!t?.length&&(await v(),t=await i.get("redirectsWhitelist")),!t?.length)return!r;let o=new URL(e).hostname.toLowerCase();return o=o.replace("www.",""),t.includes(o)?!0:t.some(s=>{if(s.startsWith("*.")){let m=s.slice(2);return o.endsWith(m)}return!1})}catch{return console.error("Invalid URL:",e),!1}},L=He;var Qe=async(e,t,r,n,o,s,m)=>{if(t===chrome.runtime.id&&await i.set("lastActivation",Date.now()),e&&I(e,o||Date.now()+24*60*60*1e3),s&&m){let l=await i.get("redirectsWhitelist");await L(m,l)&&chrome.tabs.update(s,{url:m})}await k(r,void 0,N(n))},R=Qe;var oe=async e=>e<0?(await i.remove("optOut"),{isOptedOut:!1}):(await i.set("optOut",Date.now()+e),{isOptedOut:!0}),se=async()=>{let e=await i.get("optOut");return{isOptedOut:!!(e&&e>Date.now())}};var ae=async(e,t,r)=>{await T(e,{action:"INJECT",page:"notification",token:t.token,iframeUrl:t.iframeUrl,userId:await O(),domain:r})},qe=async(e,t,r,n,o,s)=>{let m=await i.get("notification");if(m?.expiration<Date.now())await i.remove("notification");else if(m)return await ae(t,m,n);let l=await k(e,t,N(r));l.showNotification&&(o&&await ae(t,l,n),s&&s())},ce=qe;var Je=async e=>{e.category=e?.category||"system",await A({path:"/analytics",method:"POST",params:e})},le=Je;var me="optOutDomains",Ye=async(e,t)=>{if(!e)return;let r=await i.get(me);typeof r=="object"?r[e]=t:r={[e]:t},i.set(me,r)},de=Ye;var ze=["www.","www1.","www2."],Xe=async e=>{let t=await v();if(!e||!t||!t.length)return"";let r=null;try{r=new URL(e)}catch{r=new URL(`https://${e}`)}let n=r.hostname,o=C(r.pathname);for(let s of ze)n=n.replace(s,"");for(let s of t){let m=s;s=C(s);let l=!1;s.startsWith("*.")&&(l=!0);let c="/"+s.split("/").slice(1).join("/")||"";if(c!=="/"&&o.startsWith(c)&&(n+=c),n===s||l&&n.endsWith(s.replace("*.",""))){let d=await i.get("quietDomains");return d&&d[s]&&Date.now()<d[s]&&d[s]<Date.now()+60*24*60*60*1e3?"":m}}return""},F={},Ze=async({identifier:e,apiEndpoint:t,cashbackPagePath:r,whitelistEndpoint:n,isEnabledByDefault:o=!0,showNotifications:s=!0,notificationCallback:m})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(t),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(e),await i.get("popupEnabled")===void 0&&await i.set("popupEnabled",o),v(),chrome.alarms.onAlarm.addListener(async c=>{let{name:d}=c;switch(d){case S:v();break;default:console.error("alarm with no use case:",d);break}}),chrome.runtime.onMessage.addListener((c,d,u)=>{if(c?.from!=="bringweb3")return;let{action:p}=c;switch(p){case"ACTIVATE":{let{domain:a,extensionId:g,time:y,redirectUrl:w}=c;return R(a,g,e,r,y,d.tab?.id,w).then(()=>u()),!0}case"GET_OPT_OUT":return se().then(a=>u(a)),!0;case"OPT_OUT":{let{time:a}=c;return oe(a).then(g=>u(g)),!0}case"OPT_OUT_SPECIFIC":{let{domain:a,time:g}=c;return de(a,g).then(y=>u(y)),!0}case"GET_POPUP_ENABLED":return i.get("popupEnabled").then(a=>u({isPopupEnabled:a})),!0;case"SET_POPUP_ENABLED":{let{isPopupEnabled:a}=c;return i.set("popupEnabled",a).then(()=>{u({isPopupEnabled:a})}).catch(g=>{console.error("Error setting popup enabled:",g),u({error:"Failed to set popup enabled state"})}),!0}case"CLOSE":{let{time:a,domain:g}=c;return g&&(I(g,a),u({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:a}=c;return a?i.set("walletAddress",a).then(()=>u(a)):i.remove("walletAddress").then(()=>u({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return i.remove("notification").then(()=>u({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${p}`),!0;case"OPEN_CASHBACK_PAGE":let{url:h}=c;return X(h||r),u({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(c,d,u)=>{if(!u?.url?.startsWith("http")||!u.url)return;let p=ee(u.url),h=await i.get("optOut");if(!await i.get("popupEnabled")||h&&h>Date.now())return;h&&(i.remove("optOut"),i.remove("optOutKey"));let g=await i.get("optOutDomains");if(g&&g[b(p)]&&g[b(p)]>Date.now())return;let y=F[c];if(d.status!=="complete"||p===y)return;F[c]=p;let w=await Xe(u.url);if(!w||!w.length){await ce(e,c,r,p,s,m);return}let D=await U(c),{token:_,isValid:K,iframeUrl:$,networkUrl:ue,flowId:pe,portalReferrers:fe,time:G=Date.now()+24*60*60*1e3}=await Z({body:{domain:w,url:u.url,address:D}});if(!K){K===!1&&I(w,G);return}if(!await L(ue,await i.get("redirectsWhitelist")))return;let B=await O(),P=await T(c,{action:"INJECT",token:_,domain:p,iframeUrl:$,userId:B,portalReferrers:fe});if(P?.action)switch(P.action){case"activate":R(w,chrome.runtime.id,e,r,G,c);break;default:console.error(`Unknown action: ${P.action}`);break}P?.status!=="success"&&le({type:"no_popup",userId:B,walletAddress:D,details:{url:u.url,match:w,iframeUrl:$,reason:P?.message,status:P?.status},flowId:pe})}),chrome.tabs.onRemoved.addListener(c=>delete F[c])},et=Ze;var tt=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_OPT_OUT"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e({isTurnedOff:r.isOptedOut})})}),rt=e=>new Promise((t,r)=>{let n=e?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},o=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}o?t({isTurnedOff:o.isOptedOut}):r("No response received")})});var nt=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_POPUP_ENABLED"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e(r)})}),it=e=>new Promise((t,r)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"SET_POPUP_ENABLED",isPopupEnabled:e},n=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}n?t({isPopupEnabled:n.isPopupEnabled}):r("No response received")})});export{et as bringInitBackground,Ce as bringInitContentScript,nt as getPopupEnabled,tt as getTurnOff,it as setPopupEnabled,rt as setTurnOff};
|