@bringweb3/chrome-extension-kit 1.0.12 → 1.1.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 CHANGED
@@ -28,7 +28,7 @@ When a user visits supported online retailer websites, the Crypto Cashback syste
28
28
  ## Prerequisites
29
29
 
30
30
  - Node.js >= 14
31
- - Chrome extension manifest >= V3 with required permissions
31
+ - Chrome extension manifest >= V2 with required permissions
32
32
  - Obtain an identifier key from [Bringweb3](https://bringweb3.io/#contact)
33
33
  - Provide a specific logo for the specific outlet
34
34
 
@@ -120,7 +120,10 @@ bringInitContentScript({
120
120
  getWalletAddress: async () => await new Promise(resolve => setTimeout(() => resolve('<USER_WALLET_ADDRESS>'), 200)),// Async function that returns the current user's wallet address
121
121
  promptLogin: () => {...}, // Function that prompts a UI element asking the user to login
122
122
  walletAddressListeners: ["customEvent:addressChanged"], // A list of custom events that dispatched when the user's wallet address had changed
123
- customTheme: {
123
+ themeMode: 'light' // 'light' | 'dark',
124
+ text:'lower' // 'lower' | 'upper'
125
+ darkTheme: {...}, // Same as lightTheme
126
+ lightTheme: {
124
127
  // font
125
128
  fontUrl: 'https://fonts.googleapis.com/css2?family=Matemasie&display=swap',
126
129
  fontFamily: "'Matemasie', system-ui",
@@ -195,6 +198,7 @@ bringInitContentScript({
195
198
  tokenFC: "#DADCE5",
196
199
  tokenBorderW: "2px",
197
200
  tokenBorderC: "#DADCE5",
201
+ tokenRadius: "8px",
198
202
  // Notification popup
199
203
  notificationFS: "14px",
200
204
  notificationFW: "500",
@@ -206,12 +210,12 @@ bringInitContentScript({
206
210
  notificationBtnBorderW: "0",
207
211
  notificationBtnBorderC: "transparent",
208
212
  notificationBtnRadius: "8px",
209
- activateTitleFS: "--activate-title-f-s",
210
- activateTitleFW: "--activate-title-f-w",
211
- activateTitleFC: "--activate-title-f-c",
212
- activateTitleBoldFS: "--activate-title-bold-f-s",
213
- activateTitleBoldFW: "--activate-title-bold-f-w",
214
- activateTitleBoldFC: "--activate-title-bold-f-c",
213
+ activateTitleFS: "14px",
214
+ activateTitleFW: "600",
215
+ activateTitleFC: "white",
216
+ activateTitleBoldFS: "14px",
217
+ activateTitleBoldFW: "700",
218
+ activateTitleBoldFC: "white",
215
219
  }
216
220
  });
217
221
  ```
package/dist/index.d.mts CHANGED
@@ -3,7 +3,10 @@ interface Configuration$1 {
3
3
  getWalletAddress: () => Promise<WalletAddress>;
4
4
  promptLogin: () => Promise<WalletAddress>;
5
5
  walletAddressListeners: string[];
6
- customTheme?: Style;
6
+ lightTheme?: Style;
7
+ darkTheme?: Style;
8
+ theme: string;
9
+ text: 'upper' | 'lower';
7
10
  }
8
11
  /**
9
12
  * Initializes the content script for the Bring extension.
@@ -14,7 +17,10 @@ interface Configuration$1 {
14
17
  * @param {Function} configuration.getWalletAddress - A function that returns a Promise resolving to the wallet address.
15
18
  * @param {Function} configuration.promptLogin - A function to prompt the user to login.
16
19
  * @param {string[]} configuration.walletAddressListeners - An array of strings representing wallet address listeners.
17
- * @param {Object} [configuration.customTheme] - Optional custom theme settings.
20
+ * @param {Object} [configuration.lightTheme] - Optional light theme settings.
21
+ * @param {Object} [configuration.darkTheme] - Optional dark theme settings.
22
+ * @param {string} configuration.theme - The chosen theme, light | dark.
23
+ * @param {string} configuration.text - The chosen case for some of the texts, upper | lower.
18
24
  * @param {string} configuration.iframeEndpoint - The endpoint URL for the iframe.
19
25
  * @throws {Error} Throws an error if any required configuration is missing.
20
26
  * @returns {Promise<void>}
@@ -30,9 +36,13 @@ interface Configuration$1 {
30
36
  * promptLogin: () => { ... },
31
37
  * walletAddressListeners: ["listener1", "listener2"],
32
38
  * iframeEndpoint: 'https://example.com/iframe'
39
+ * theme: 'light',
40
+ * text: 'lower',
41
+ * lightTheme: { ... },
42
+ * darkTheme: { ... }
33
43
  * });
34
44
  */
35
- declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, customTheme, iframeEndpoint }: Configuration$1) => Promise<void>;
45
+ declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, lightTheme, darkTheme, theme, text, iframeEndpoint }: Configuration$1) => Promise<void>;
36
46
 
37
47
  interface Configuration {
38
48
  identifier: string;
package/dist/index.d.ts CHANGED
@@ -3,7 +3,10 @@ interface Configuration$1 {
3
3
  getWalletAddress: () => Promise<WalletAddress>;
4
4
  promptLogin: () => Promise<WalletAddress>;
5
5
  walletAddressListeners: string[];
6
- customTheme?: Style;
6
+ lightTheme?: Style;
7
+ darkTheme?: Style;
8
+ theme: string;
9
+ text: 'upper' | 'lower';
7
10
  }
8
11
  /**
9
12
  * Initializes the content script for the Bring extension.
@@ -14,7 +17,10 @@ interface Configuration$1 {
14
17
  * @param {Function} configuration.getWalletAddress - A function that returns a Promise resolving to the wallet address.
15
18
  * @param {Function} configuration.promptLogin - A function to prompt the user to login.
16
19
  * @param {string[]} configuration.walletAddressListeners - An array of strings representing wallet address listeners.
17
- * @param {Object} [configuration.customTheme] - Optional custom theme settings.
20
+ * @param {Object} [configuration.lightTheme] - Optional light theme settings.
21
+ * @param {Object} [configuration.darkTheme] - Optional dark theme settings.
22
+ * @param {string} configuration.theme - The chosen theme, light | dark.
23
+ * @param {string} configuration.text - The chosen case for some of the texts, upper | lower.
18
24
  * @param {string} configuration.iframeEndpoint - The endpoint URL for the iframe.
19
25
  * @throws {Error} Throws an error if any required configuration is missing.
20
26
  * @returns {Promise<void>}
@@ -30,9 +36,13 @@ interface Configuration$1 {
30
36
  * promptLogin: () => { ... },
31
37
  * walletAddressListeners: ["listener1", "listener2"],
32
38
  * iframeEndpoint: 'https://example.com/iframe'
39
+ * theme: 'light',
40
+ * text: 'lower',
41
+ * lightTheme: { ... },
42
+ * darkTheme: { ... }
33
43
  * });
34
44
  */
35
- declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, customTheme, iframeEndpoint }: Configuration$1) => Promise<void>;
45
+ declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, lightTheme, darkTheme, theme, text, iframeEndpoint }: Configuration$1) => Promise<void>;
36
46
 
37
47
  interface Configuration {
38
48
  identifier: string;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var g=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var K=(e,t)=>{for(var n in t)g(e,n,{get:t[n],enumerable:!0})},B=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of F(t))!V.call(e,s)&&s!==n&&g(e,s,{get:()=>t[s],enumerable:!(r=q(t,s))||r.enumerable});return e};var J=e=>B(g({},"__esModule",{value:!0}),e);var fe={};K(fe,{bringInitBackground:()=>$,bringInitContentScript:()=>L});module.exports=J(fe);var Q=e=>{let t=new URLSearchParams,{query:n,prefix:r}=e;return Object.entries(n).forEach(([s,i])=>{i&&(r&&(s=`${r}_${s}`),s==="url"?t.append(s,encodeURIComponent(i)):t.append(s,i))}),t.toString()},h=Q;var x={name:"@bringweb3/chrome-extension-kit",version:"1.0.12",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"},scripts:{watch:"tsup index.ts --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"}};var H=()=>x.version,D=H;var Y=({query:e,theme:t,iframeSrc:n})=>{let r=chrome.runtime.id,s=`bringweb3-iframe-${r}`,i=document.getElementById(s);if(i)return i;let o=h({query:{...e,extensionId:r,v:D()}}),c=t?`&${h({query:t,prefix:"t"})}`:"",a=document.createElement("iframe");return a.id=s,a.src=`${n}?${o}${c}`,a.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),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},k=Y;var z=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([n,r])=>{n in e.style&&(e.style[n]=r)})},v=z;var X=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let n=t.sheet;n?e.forEach(({name:r,rules:s})=>{n.insertRule(`@keyframes ${r} { ${s} }`,n.cssRules.length)}):console.error("Failed to create stylesheet")},C=X;var u={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},Z=[u.ACTIVATE],ee=({event:e,iframeEl:t,promptLogin:n})=>{let{data:r}=e,{from:s,action:i,style:o,keyFrames:c,time:a,extensionId:m}=r;if(s==="bringweb3"&&!(m!==chrome.runtime.id&&!Z.includes(i)))switch(i){case u.OPEN:v(t,o);break;case u.CLOSE:t&&t.parentNode?.removeChild(t),a&&chrome.runtime.sendMessage({action:i,time:a,from:"bringweb3"});break;case u.PROMPT_LOGIN:n();break;case u.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3"});break;case u.OPT_OUT:chrome.runtime.sendMessage({action:i,time:a,from:"bringweb3"});break;case u.ADD_KEYFRAMES:C(c);break;default:break}},P=ee;var te=({walletAddressListeners:e,getWalletAddress:t,iframeEl:n})=>{for(let r=0;r<e.length;r++){let s=e[r];s&&window.addEventListener(s,async i=>{if(!n&&(n=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!n)||!n.contentWindow)return;let o=await t();n.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:o},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:"address"})})}},S=te;var w=null,R=!1,ne=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:n,customTheme:r,iframeEndpoint:s})=>{if(!e||!t||!n?.length||!s)throw new Error("Missing configuration");S({walletAddressListeners:n,getWalletAddress:e,iframeEl:w}),window.addEventListener("message",i=>P({event:i,iframeEl:w,promptLogin:t})),chrome.runtime.onMessage.addListener((i,o,c)=>{let{action:a}=i;switch(a){case"GET_WALLET_ADDRESS":return e().then(p=>c({status:"success",walletAddress:p})).catch(p=>c({status:"success",walletAddress:void 0})),!0;case"INJECT":if(R)return;let{token:m,page:f}=i;return w=k({query:{token:m},iframeSrc:f==="notification"?`${s}notification`:s,theme:r}),R=!0,c({status:"success"}),!0;default:console.error(`Unknown action: ${a}`);break}})},L=ne;var l=class e{static instance=null;apiEndpoint="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var re=async e=>{let t=l.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},I=re;var se=async({apiKey:e,body:t})=>{let n=l.getInstance().getApiEndpoint();return await(await fetch(`${n}/check/popup`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(t)})).json()},O=se;var ie=async({apiKey:e,walletAddress:t,cashbackUrl:n})=>{let r=l.getInstance().getApiEndpoint(),s={walletAddress:t};return n&&(s.cashbackUrl=n),await(await fetch(`${r}/check/notification`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(s)})).json()},M=ie;var y="updateCache";var oe=async(e,t)=>new Promise((n,r)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):n()})}),ae=async e=>new Promise((t,n)=>{chrome.storage.local.get([`bring_${e}`],r=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t(r[`bring_${e}`])})}),ce=async e=>new Promise((t,n)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t()})}),d={set:oe,get:ae,remove:ce};var _=30*60*1e3,W=async e=>{let t=await d.get("walletAddress");try{if(!e){let r=await chrome.tabs.query({active:!0,currentWindow:!0});if(!r||!r[0]||!r[0].id)return t;e=r[0].id}let n=await b(e,{action:"GET_WALLET_ADDRESS"});n?.walletAddress&&t!==n?.walletAddress&&(t=n?.walletAddress,await d.set("walletAddress",t))}catch{}return t},de=e=>{let t=Date.now();return(e-t)/1e3/60},E=async e=>{let t=await I(e);d.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:n}=t,r=de(n);return chrome.alarms.create(y,{delayInMinutes:r||60*24*2}),t.relevantDomains},le=async(e,t,n,r)=>{let s={showNotification:!1,token:""},i=await d.get("notificationCheck");if(i?.check&&Date.now()<i.check)return s;let o=await W(t);if(!o)return s;let c=await M({apiKey:e,walletAddress:o,cashbackUrl:n}),a={check:r?c.nextRequestTimestampActivated:c.nextRequestTimestampRegular,nextRequestTimestampActivated:c.nextRequestTimestampActivated,nextRequestTimestampRegular:c.nextRequestTimestampRegular};return d.set("notificationCheck",a),{showNotification:c.showNotification,token:c.token}},me=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),N=async(e,t)=>{let n=await d.get("relevantDomains");if(n===void 0&&(n=await E(t)),!e||!n||!n.length)return"";let r=me(e);for(let s of n)if(r.startsWith(s)){let i=await d.get("quietDomains");return i&&i[s]&&Date.now()<i[s]?"":s}return""},j=async(e,t)=>{t||(t=_);let n=await d.get("quietDomains");typeof n=="object"?n[e]=Date.now()+t:n={[e]:Date.now()+_},d.set("quietDomains",n)},ue=e=>e?chrome.runtime.getURL(e):void 0,b=async(e,t)=>{for(let s=0;s<5;s++)try{let i=await chrome.tabs.get(e);return chrome.runtime.lastError?void 0:await chrome.tabs.sendMessage(e,t)}catch{s<4&&await new Promise(o=>setTimeout(o,1e3*Math.pow(2,s)))}},U=async(e,t,n)=>{let r=await le(e,t,ue(n));r.showNotification&&await b(t,{action:"INJECT",token:r.token,page:"notification"})},A={},pe=async({identifier:e,apiEndpoint:t,cashbackPagePath:n})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");l.getInstance().setApiEndpoint(t),E(e),chrome.alarms.onAlarm.addListener(async r=>{let{name:s}=r;switch(s){case y:E(e);break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener(async(r,s)=>{if(r?.from!=="bringweb3")return;let{action:i}=r;switch(i){case"ACTIVATE":{let o=await d.get("notificationCheck");if(!o.check||!o.nextRequestTimestampActivated)break;o.check=o.nextRequestTimestampActivated,d.set("notificationCheck",o);break}case"OPT_OUT":{let{time:o}=r;d.set("optOut",Date.now()+o);break}case"CLOSE":{let{time:o}=r,c=await N(s.tab?.url||s.origin,e);if(!c)break;j(c,o);break}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:o}=r;d.set("walletAddress",o);break}default:{console.warn(`Bring unknown action: ${i}`);break}}}),chrome.tabs.onUpdated.addListener(async(r,s,i)=>{let o=await d.get("optOut");if(o&&o>Date.now()){await U(e,r,n);return}if(!i.url)return;let c=i.url.replace("www.",""),a=A[r];if(s.status!=="complete"||c===a)return;A[r]=c;let m=await N(i.url,e);if(!m||!m.length){await U(e,r,n);return}let f=await W(r),{token:p,isValid:T}=await O({apiKey:e,body:{domain:m,url:i.url,address:f}});if(!T){T===!1&&j(m);return}b(r,{action:"INJECT",token:p,domain:c})}),chrome.tabs.onRemoved.addListener(r=>delete A[r])},$=pe;0&&(module.exports={bringInitBackground,bringInitContentScript});
1
+ "use strict";var h=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var J=(e,t)=>{for(var n in t)h(e,n,{get:t[n],enumerable:!0})},Q=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of K(t))!B.call(e,s)&&s!==n&&h(e,s,{get:()=>t[s],enumerable:!(r=V(t,s))||r.enumerable});return e};var G=e=>Q(h({},"__esModule",{value:!0}),e);var he={};J(he,{bringInitBackground:()=>q,bringInitContentScript:()=>R});module.exports=G(he);var H=e=>{let t=new URLSearchParams,{query:n,prefix:r}=e;return Object.entries(n).forEach(([s,i])=>{i&&(r&&(s=`${r}_${s}`),s==="url"?t.append(s,encodeURIComponent(i)):t.append(s,i))}),t.toString()},w=H;var D={name:"@bringweb3/chrome-extension-kit",version:"1.1.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"},scripts:{watch:"tsup index.ts --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"}};var z=()=>D.version,k=z;var X=({query:e,theme:t,themeMode:n,text:r,iframeSrc:s})=>{let i=chrome.runtime.id,o=`bringweb3-iframe-${i}`,a=document.getElementById(o);if(a)return a;let d=w({query:{...e,extensionId:i,v:k(),themeMode:n,textMode:r}}),m=t?`&${w({query:t,prefix:"t"})}`:"",c=document.createElement("iframe");return c.id=o,c.src=`${s}?${d}${m}`,c.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),c.style.position="fixed",c.scrolling="no",c.style.overflow="hidden",c.style.width="1px",c.style.height="1px",c.style.right="8px",c.style.borderRadius="10px",c.style.border="none",c.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(c.style.boxShadow=t.popupShadow),document.documentElement.appendChild(c),c},v=X;var Z=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([n,r])=>{n in e.style&&(e.style[n]=r)})},C=Z;var ee=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let n=t.sheet;n?e.forEach(({name:r,rules:s})=>{n.insertRule(`@keyframes ${r} { ${s} }`,n.cssRules.length)}):console.error("Failed to create stylesheet")},P=ee;var p={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},te=[p.ACTIVATE],ne=({event:e,iframeEl:t,promptLogin:n})=>{let{data:r}=e,{from:s,action:i,style:o,keyFrames:a,time:d,extensionId:m}=r;if(s==="bringweb3"&&!(m!==chrome.runtime.id&&!te.includes(i)))switch(i){case p.OPEN:C(t,o);break;case p.CLOSE:t&&t.parentNode?.removeChild(t),d&&chrome.runtime.sendMessage({action:i,time:d,from:"bringweb3"});break;case p.PROMPT_LOGIN:n();break;case p.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3"});break;case p.OPT_OUT:chrome.runtime.sendMessage({action:i,time:d,from:"bringweb3"});break;case p.ADD_KEYFRAMES:P(a);break;default:break}},S=ne;var re=({walletAddressListeners:e,getWalletAddress:t,iframeEl:n})=>{for(let r=0;r<e.length;r++){let s=e[r];s&&window.addEventListener(s,async i=>{if(!n&&(n=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!n)||!n.contentWindow)return;let o=await t();n.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:o},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:"address"})})}},L=re;var E=null,M=!1,se=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:n,lightTheme:r,darkTheme:s,theme:i,text:o,iframeEndpoint:a})=>{if(!e||!t||!n?.length||!a)throw new Error("Missing configuration");L({walletAddressListeners:n,getWalletAddress:e,iframeEl:E}),window.addEventListener("message",d=>S({event:d,iframeEl:E,promptLogin:t})),chrome.runtime.onMessage.addListener((d,m,c)=>{let{action:f}=d;switch(f){case"GET_WALLET_ADDRESS":return e().then(x=>c({status:"success",walletAddress:x})).catch(x=>c({status:"success",walletAddress:void 0})),!0;case"INJECT":if(M)return;let{token:g,page:F}=d;return E=v({query:{token:g},iframeSrc:F==="notification"?`${a}notification`:a,theme:i==="dark"?s:r,themeMode:i||"light",text:o}),M=!0,c({status:"success"}),!0;default:console.error(`Unknown action: ${f}`);break}})},R=se;var u=class e{static instance=null;apiEndpoint="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var ie=async e=>{let t=u.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},O=ie;var oe=async({apiKey:e,body:t})=>{let n=u.getInstance().getApiEndpoint();return await(await fetch(`${n}/check/popup`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(t)})).json()},I=oe;var ae=async({apiKey:e,walletAddress:t,cashbackUrl:n})=>{let r=u.getInstance().getApiEndpoint(),s={walletAddress:t};return n&&(s.cashbackUrl=n),await(await fetch(`${r}/check/notification`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(s)})).json()},_=ae;var y="updateCache";var ce=async(e,t)=>new Promise((n,r)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):n()})}),de=async e=>new Promise((t,n)=>{chrome.storage.local.get([`bring_${e}`],r=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t(r[`bring_${e}`])})}),le=async e=>new Promise((t,n)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t()})}),l={set:ce,get:de,remove:le};var N=30*60*1e3,$=async e=>{let t=await l.get("walletAddress");try{if(!e){let r=await chrome.tabs.query({active:!0,currentWindow:!0});if(!r||!r[0]||!r[0].id)return t;e=r[0].id}let n=await T(e,{action:"GET_WALLET_ADDRESS"});n?.walletAddress&&t!==n?.walletAddress&&(t=n?.walletAddress,await l.set("walletAddress",t))}catch{}return t},me=e=>{let t=Date.now();return(e-t)/1e3/60},b=async e=>{let t=await O(e);l.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:n}=t,r=me(n);return chrome.alarms.create(y,{delayInMinutes:r||60*24*2}),t.relevantDomains},ue=async(e,t,n,r)=>{let s={showNotification:!1,token:""},i=await l.get("notificationCheck");if(i?.check&&Date.now()<i.check)return s;let o=await $(t);if(!o)return s;let a=await _({apiKey:e,walletAddress:o,cashbackUrl:n}),d={check:r?a.nextRequestTimestampActivated:a.nextRequestTimestampRegular,nextRequestTimestampActivated:a.nextRequestTimestampActivated,nextRequestTimestampRegular:a.nextRequestTimestampRegular};return l.set("notificationCheck",d),{showNotification:a.showNotification,token:a.token}},pe=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),U=async(e,t)=>{let n=await l.get("relevantDomains");if(n===void 0&&(n=await b(t)),!e||!n||!n.length)return"";let r=pe(e);for(let s of n)if(r.startsWith(s)){let i=await l.get("quietDomains");return i&&i[s]&&Date.now()<i[s]?"":s}return""},j=async(e,t)=>{t||(t=N);let n=await l.get("quietDomains");typeof n=="object"?n[e]=Date.now()+t:n={[e]:Date.now()+N},l.set("quietDomains",n)},fe=e=>e?chrome.runtime.getURL(e):void 0,T=(e,t)=>new Promise((s,i)=>{let o=a=>{chrome.tabs.get(e,d=>{if(chrome.runtime.lastError){i(new Error(chrome.runtime.lastError.message));return}chrome.tabs.sendMessage(e,t,m=>{chrome.runtime.lastError?a<4?setTimeout(()=>o(a+1),1e3*Math.pow(2,a)):i(new Error(chrome.runtime.lastError.message)):s(m)})})};o(0)}),W=async(e,t,n)=>{let r=await ue(e,t,fe(n));r.showNotification&&await T(t,{action:"INJECT",token:r.token,page:"notification"})},A={},ge=async({identifier:e,apiEndpoint:t,cashbackPagePath:n})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");u.getInstance().setApiEndpoint(t),b(e),chrome.alarms.onAlarm.addListener(async r=>{let{name:s}=r;switch(s){case y:b(e);break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener(async(r,s)=>{if(r?.from!=="bringweb3")return;let{action:i}=r;switch(i){case"ACTIVATE":{let o=await l.get("notificationCheck");if(!o.check||!o.nextRequestTimestampActivated)break;o.check=o.nextRequestTimestampActivated,l.set("notificationCheck",o);break}case"OPT_OUT":{let{time:o}=r;l.set("optOut",Date.now()+o);break}case"CLOSE":{let{time:o}=r,a=await U(s.tab?.url||s.origin,e);if(!a)break;j(a,o);break}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:o}=r;l.set("walletAddress",o);break}default:{console.warn(`Bring unknown action: ${i}`);break}}}),chrome.tabs.onUpdated.addListener(async(r,s,i)=>{let o=await l.get("optOut");if(o&&o>Date.now()){await W(e,r,n);return}if(!i.url)return;let a=i.url.replace("www.",""),d=A[r];if(s.status!=="complete"||a===d)return;A[r]=a;let m=await U(i.url,e);if(!m||!m.length){await W(e,r,n);return}let c=await $(r),{token:f,isValid:g}=await I({apiKey:e,body:{domain:m,url:i.url,address:c}});if(!g){g===!1&&j(m);return}T(r,{action:"INJECT",token:f,domain:a})}),chrome.tabs.onRemoved.addListener(r=>delete A[r])},q=ge;0&&(module.exports={bringInitBackground,bringInitContentScript});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var U=e=>{let t=new URLSearchParams,{query:n,prefix:r}=e;return Object.entries(n).forEach(([s,i])=>{i&&(r&&(s=`${r}_${s}`),s==="url"?t.append(s,encodeURIComponent(i)):t.append(s,i))}),t.toString()},g=U;var T={name:"@bringweb3/chrome-extension-kit",version:"1.0.12",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"},scripts:{watch:"tsup index.ts --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"}};var $=()=>T.version,x=$;var q=({query:e,theme:t,iframeSrc:n})=>{let r=chrome.runtime.id,s=`bringweb3-iframe-${r}`,i=document.getElementById(s);if(i)return i;let o=g({query:{...e,extensionId:r,v:x()}}),c=t?`&${g({query:t,prefix:"t"})}`:"",a=document.createElement("iframe");return a.id=s,a.src=`${n}?${o}${c}`,a.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),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},D=q;var F=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([n,r])=>{n in e.style&&(e.style[n]=r)})},k=F;var V=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let n=t.sheet;n?e.forEach(({name:r,rules:s})=>{n.insertRule(`@keyframes ${r} { ${s} }`,n.cssRules.length)}):console.error("Failed to create stylesheet")},v=V;var u={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},K=[u.ACTIVATE],B=({event:e,iframeEl:t,promptLogin:n})=>{let{data:r}=e,{from:s,action:i,style:o,keyFrames:c,time:a,extensionId:m}=r;if(s==="bringweb3"&&!(m!==chrome.runtime.id&&!K.includes(i)))switch(i){case u.OPEN:k(t,o);break;case u.CLOSE:t&&t.parentNode?.removeChild(t),a&&chrome.runtime.sendMessage({action:i,time:a,from:"bringweb3"});break;case u.PROMPT_LOGIN:n();break;case u.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3"});break;case u.OPT_OUT:chrome.runtime.sendMessage({action:i,time:a,from:"bringweb3"});break;case u.ADD_KEYFRAMES:v(c);break;default:break}},C=B;var J=({walletAddressListeners:e,getWalletAddress:t,iframeEl:n})=>{for(let r=0;r<e.length;r++){let s=e[r];s&&window.addEventListener(s,async i=>{if(!n&&(n=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!n)||!n.contentWindow)return;let o=await t();n.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:o},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:"address"})})}},P=J;var h=null,S=!1,Q=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:n,customTheme:r,iframeEndpoint:s})=>{if(!e||!t||!n?.length||!s)throw new Error("Missing configuration");P({walletAddressListeners:n,getWalletAddress:e,iframeEl:h}),window.addEventListener("message",i=>C({event:i,iframeEl:h,promptLogin:t})),chrome.runtime.onMessage.addListener((i,o,c)=>{let{action:a}=i;switch(a){case"GET_WALLET_ADDRESS":return e().then(p=>c({status:"success",walletAddress:p})).catch(p=>c({status:"success",walletAddress:void 0})),!0;case"INJECT":if(S)return;let{token:m,page:f}=i;return h=D({query:{token:m},iframeSrc:f==="notification"?`${s}notification`:s,theme:r}),S=!0,c({status:"success"}),!0;default:console.error(`Unknown action: ${a}`);break}})},G=Q;var l=class e{static instance=null;apiEndpoint="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var H=async e=>{let t=l.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},R=H;var Y=async({apiKey:e,body:t})=>{let n=l.getInstance().getApiEndpoint();return await(await fetch(`${n}/check/popup`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(t)})).json()},L=Y;var z=async({apiKey:e,walletAddress:t,cashbackUrl:n})=>{let r=l.getInstance().getApiEndpoint(),s={walletAddress:t};return n&&(s.cashbackUrl=n),await(await fetch(`${r}/check/notification`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(s)})).json()},I=z;var w="updateCache";var X=async(e,t)=>new Promise((n,r)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):n()})}),Z=async e=>new Promise((t,n)=>{chrome.storage.local.get([`bring_${e}`],r=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t(r[`bring_${e}`])})}),ee=async e=>new Promise((t,n)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t()})}),d={set:X,get:Z,remove:ee};var O=30*60*1e3,j=async e=>{let t=await d.get("walletAddress");try{if(!e){let r=await chrome.tabs.query({active:!0,currentWindow:!0});if(!r||!r[0]||!r[0].id)return t;e=r[0].id}let n=await E(e,{action:"GET_WALLET_ADDRESS"});n?.walletAddress&&t!==n?.walletAddress&&(t=n?.walletAddress,await d.set("walletAddress",t))}catch{}return t},te=e=>{let t=Date.now();return(e-t)/1e3/60},A=async e=>{let t=await R(e);d.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:n}=t,r=te(n);return chrome.alarms.create(w,{delayInMinutes:r||60*24*2}),t.relevantDomains},ne=async(e,t,n,r)=>{let s={showNotification:!1,token:""},i=await d.get("notificationCheck");if(i?.check&&Date.now()<i.check)return s;let o=await j(t);if(!o)return s;let c=await I({apiKey:e,walletAddress:o,cashbackUrl:n}),a={check:r?c.nextRequestTimestampActivated:c.nextRequestTimestampRegular,nextRequestTimestampActivated:c.nextRequestTimestampActivated,nextRequestTimestampRegular:c.nextRequestTimestampRegular};return d.set("notificationCheck",a),{showNotification:c.showNotification,token:c.token}},re=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),M=async(e,t)=>{let n=await d.get("relevantDomains");if(n===void 0&&(n=await A(t)),!e||!n||!n.length)return"";let r=re(e);for(let s of n)if(r.startsWith(s)){let i=await d.get("quietDomains");return i&&i[s]&&Date.now()<i[s]?"":s}return""},_=async(e,t)=>{t||(t=O);let n=await d.get("quietDomains");typeof n=="object"?n[e]=Date.now()+t:n={[e]:Date.now()+O},d.set("quietDomains",n)},se=e=>e?chrome.runtime.getURL(e):void 0,E=async(e,t)=>{for(let s=0;s<5;s++)try{let i=await chrome.tabs.get(e);return chrome.runtime.lastError?void 0:await chrome.tabs.sendMessage(e,t)}catch{s<4&&await new Promise(o=>setTimeout(o,1e3*Math.pow(2,s)))}},N=async(e,t,n)=>{let r=await ne(e,t,se(n));r.showNotification&&await E(t,{action:"INJECT",token:r.token,page:"notification"})},y={},ie=async({identifier:e,apiEndpoint:t,cashbackPagePath:n})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");l.getInstance().setApiEndpoint(t),A(e),chrome.alarms.onAlarm.addListener(async r=>{let{name:s}=r;switch(s){case w:A(e);break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener(async(r,s)=>{if(r?.from!=="bringweb3")return;let{action:i}=r;switch(i){case"ACTIVATE":{let o=await d.get("notificationCheck");if(!o.check||!o.nextRequestTimestampActivated)break;o.check=o.nextRequestTimestampActivated,d.set("notificationCheck",o);break}case"OPT_OUT":{let{time:o}=r;d.set("optOut",Date.now()+o);break}case"CLOSE":{let{time:o}=r,c=await M(s.tab?.url||s.origin,e);if(!c)break;_(c,o);break}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:o}=r;d.set("walletAddress",o);break}default:{console.warn(`Bring unknown action: ${i}`);break}}}),chrome.tabs.onUpdated.addListener(async(r,s,i)=>{let o=await d.get("optOut");if(o&&o>Date.now()){await N(e,r,n);return}if(!i.url)return;let c=i.url.replace("www.",""),a=y[r];if(s.status!=="complete"||c===a)return;y[r]=c;let m=await M(i.url,e);if(!m||!m.length){await N(e,r,n);return}let f=await j(r),{token:p,isValid:b}=await L({apiKey:e,body:{domain:m,url:i.url,address:f}});if(!b){b===!1&&_(m);return}E(r,{action:"INJECT",token:p,domain:c})}),chrome.tabs.onRemoved.addListener(r=>delete y[r])},oe=ie;export{oe as bringInitBackground,G as bringInitContentScript};
1
+ var $=e=>{let t=new URLSearchParams,{query:n,prefix:r}=e;return Object.entries(n).forEach(([s,i])=>{i&&(r&&(s=`${r}_${s}`),s==="url"?t.append(s,encodeURIComponent(i)):t.append(s,i))}),t.toString()},h=$;var x={name:"@bringweb3/chrome-extension-kit",version:"1.1.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"},scripts:{watch:"tsup index.ts --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"}};var F=()=>x.version,D=F;var V=({query:e,theme:t,themeMode:n,text:r,iframeSrc:s})=>{let i=chrome.runtime.id,o=`bringweb3-iframe-${i}`,a=document.getElementById(o);if(a)return a;let d=h({query:{...e,extensionId:i,v:D(),themeMode:n,textMode:r}}),m=t?`&${h({query:t,prefix:"t"})}`:"",c=document.createElement("iframe");return c.id=o,c.src=`${s}?${d}${m}`,c.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),c.style.position="fixed",c.scrolling="no",c.style.overflow="hidden",c.style.width="1px",c.style.height="1px",c.style.right="8px",c.style.borderRadius="10px",c.style.border="none",c.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(c.style.boxShadow=t.popupShadow),document.documentElement.appendChild(c),c},k=V;var K=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([n,r])=>{n in e.style&&(e.style[n]=r)})},v=K;var B=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let n=t.sheet;n?e.forEach(({name:r,rules:s})=>{n.insertRule(`@keyframes ${r} { ${s} }`,n.cssRules.length)}):console.error("Failed to create stylesheet")},C=B;var p={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},J=[p.ACTIVATE],Q=({event:e,iframeEl:t,promptLogin:n})=>{let{data:r}=e,{from:s,action:i,style:o,keyFrames:a,time:d,extensionId:m}=r;if(s==="bringweb3"&&!(m!==chrome.runtime.id&&!J.includes(i)))switch(i){case p.OPEN:v(t,o);break;case p.CLOSE:t&&t.parentNode?.removeChild(t),d&&chrome.runtime.sendMessage({action:i,time:d,from:"bringweb3"});break;case p.PROMPT_LOGIN:n();break;case p.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3"});break;case p.OPT_OUT:chrome.runtime.sendMessage({action:i,time:d,from:"bringweb3"});break;case p.ADD_KEYFRAMES:C(a);break;default:break}},P=Q;var G=({walletAddressListeners:e,getWalletAddress:t,iframeEl:n})=>{for(let r=0;r<e.length;r++){let s=e[r];s&&window.addEventListener(s,async i=>{if(!n&&(n=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!n)||!n.contentWindow)return;let o=await t();n.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:o},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:"address"})})}},S=G;var w=null,L=!1,H=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:n,lightTheme:r,darkTheme:s,theme:i,text:o,iframeEndpoint:a})=>{if(!e||!t||!n?.length||!a)throw new Error("Missing configuration");S({walletAddressListeners:n,getWalletAddress:e,iframeEl:w}),window.addEventListener("message",d=>P({event:d,iframeEl:w,promptLogin:t})),chrome.runtime.onMessage.addListener((d,m,c)=>{let{action:f}=d;switch(f){case"GET_WALLET_ADDRESS":return e().then(T=>c({status:"success",walletAddress:T})).catch(T=>c({status:"success",walletAddress:void 0})),!0;case"INJECT":if(L)return;let{token:g,page:W}=d;return w=k({query:{token:g},iframeSrc:W==="notification"?`${a}notification`:a,theme:i==="dark"?s:r,themeMode:i||"light",text:o}),L=!0,c({status:"success"}),!0;default:console.error(`Unknown action: ${f}`);break}})},Y=H;var u=class e{static instance=null;apiEndpoint="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setApiEndpoint(t){this.apiEndpoint=t==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var z=async e=>{let t=u.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},M=z;var X=async({apiKey:e,body:t})=>{let n=u.getInstance().getApiEndpoint();return await(await fetch(`${n}/check/popup`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(t)})).json()},R=X;var Z=async({apiKey:e,walletAddress:t,cashbackUrl:n})=>{let r=u.getInstance().getApiEndpoint(),s={walletAddress:t};return n&&(s.cashbackUrl=n),await(await fetch(`${r}/check/notification`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e},body:JSON.stringify(s)})).json()},O=Z;var E="updateCache";var ee=async(e,t)=>new Promise((n,r)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):n()})}),te=async e=>new Promise((t,n)=>{chrome.storage.local.get([`bring_${e}`],r=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t(r[`bring_${e}`])})}),ne=async e=>new Promise((t,n)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t()})}),l={set:ee,get:te,remove:ne};var I=30*60*1e3,j=async e=>{let t=await l.get("walletAddress");try{if(!e){let r=await chrome.tabs.query({active:!0,currentWindow:!0});if(!r||!r[0]||!r[0].id)return t;e=r[0].id}let n=await b(e,{action:"GET_WALLET_ADDRESS"});n?.walletAddress&&t!==n?.walletAddress&&(t=n?.walletAddress,await l.set("walletAddress",t))}catch{}return t},re=e=>{let t=Date.now();return(e-t)/1e3/60},A=async e=>{let t=await M(e);l.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:n}=t,r=re(n);return chrome.alarms.create(E,{delayInMinutes:r||60*24*2}),t.relevantDomains},se=async(e,t,n,r)=>{let s={showNotification:!1,token:""},i=await l.get("notificationCheck");if(i?.check&&Date.now()<i.check)return s;let o=await j(t);if(!o)return s;let a=await O({apiKey:e,walletAddress:o,cashbackUrl:n}),d={check:r?a.nextRequestTimestampActivated:a.nextRequestTimestampRegular,nextRequestTimestampActivated:a.nextRequestTimestampActivated,nextRequestTimestampRegular:a.nextRequestTimestampRegular};return l.set("notificationCheck",d),{showNotification:a.showNotification,token:a.token}},ie=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),_=async(e,t)=>{let n=await l.get("relevantDomains");if(n===void 0&&(n=await A(t)),!e||!n||!n.length)return"";let r=ie(e);for(let s of n)if(r.startsWith(s)){let i=await l.get("quietDomains");return i&&i[s]&&Date.now()<i[s]?"":s}return""},N=async(e,t)=>{t||(t=I);let n=await l.get("quietDomains");typeof n=="object"?n[e]=Date.now()+t:n={[e]:Date.now()+I},l.set("quietDomains",n)},oe=e=>e?chrome.runtime.getURL(e):void 0,b=(e,t)=>new Promise((s,i)=>{let o=a=>{chrome.tabs.get(e,d=>{if(chrome.runtime.lastError){i(new Error(chrome.runtime.lastError.message));return}chrome.tabs.sendMessage(e,t,m=>{chrome.runtime.lastError?a<4?setTimeout(()=>o(a+1),1e3*Math.pow(2,a)):i(new Error(chrome.runtime.lastError.message)):s(m)})})};o(0)}),U=async(e,t,n)=>{let r=await se(e,t,oe(n));r.showNotification&&await b(t,{action:"INJECT",token:r.token,page:"notification"})},y={},ae=async({identifier:e,apiEndpoint:t,cashbackPagePath:n})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");u.getInstance().setApiEndpoint(t),A(e),chrome.alarms.onAlarm.addListener(async r=>{let{name:s}=r;switch(s){case E:A(e);break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener(async(r,s)=>{if(r?.from!=="bringweb3")return;let{action:i}=r;switch(i){case"ACTIVATE":{let o=await l.get("notificationCheck");if(!o.check||!o.nextRequestTimestampActivated)break;o.check=o.nextRequestTimestampActivated,l.set("notificationCheck",o);break}case"OPT_OUT":{let{time:o}=r;l.set("optOut",Date.now()+o);break}case"CLOSE":{let{time:o}=r,a=await _(s.tab?.url||s.origin,e);if(!a)break;N(a,o);break}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:o}=r;l.set("walletAddress",o);break}default:{console.warn(`Bring unknown action: ${i}`);break}}}),chrome.tabs.onUpdated.addListener(async(r,s,i)=>{let o=await l.get("optOut");if(o&&o>Date.now()){await U(e,r,n);return}if(!i.url)return;let a=i.url.replace("www.",""),d=y[r];if(s.status!=="complete"||a===d)return;y[r]=a;let m=await _(i.url,e);if(!m||!m.length){await U(e,r,n);return}let c=await j(r),{token:f,isValid:g}=await R({apiKey:e,body:{domain:m,url:i.url,address:c}});if(!g){g===!1&&N(m);return}b(r,{action:"INJECT",token:f,domain:a})}),chrome.tabs.onRemoved.addListener(r=>delete y[r])},ce=ae;export{ce as bringInitBackground,Y as bringInitContentScript};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bringweb3/chrome-extension-kit",
3
- "version": "1.0.12",
3
+ "version": "1.1.1",
4
4
  "description": "Crypto cashback integration kit for crypto outlets extension",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",