@bringweb3/chrome-extension-kit 1.1.5 → 1.1.6
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 +2 -1
- package/dist/index.d.mts +5 -3
- package/dist/index.d.ts +5 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -118,7 +118,8 @@ import { bringInitContentScript } from "@bringweb3/chrome-extension-kit";
|
|
|
118
118
|
bringInitContentScript({
|
|
119
119
|
getWalletAddress: async () => await new Promise(resolve => setTimeout(() => resolve('<USER_WALLET_ADDRESS>'), 200)),// Async function that returns the current user's wallet address
|
|
120
120
|
promptLogin: () => {...}, // Function that prompts a UI element asking the user to login
|
|
121
|
-
walletAddressListeners: ["customEvent:addressChanged"], //
|
|
121
|
+
walletAddressListeners: ["customEvent:addressChanged"], // An optional list of custom events that dispatched when the user's wallet address had changed, don't add it if you are using walletAddressUpdateCallback
|
|
122
|
+
walletAddressUpdateCallback: (callback)=>{...}, //an optional function that runs when the user's wallet address had changed and execute the callback, don't add it if you are using walletAddressUpdateCallback
|
|
122
123
|
themeMode: 'light' // 'light' | 'dark',
|
|
123
124
|
text:'lower' // 'lower' | 'upper'
|
|
124
125
|
darkTheme: {...}, // Same as lightTheme
|
package/dist/index.d.mts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
interface Configuration$1 {
|
|
2
2
|
iframeEndpoint: string;
|
|
3
3
|
getWalletAddress: () => Promise<WalletAddress>;
|
|
4
|
+
walletAddressUpdateCallback?: (callback: () => void) => void;
|
|
5
|
+
walletAddressListeners?: string[];
|
|
4
6
|
promptLogin: () => Promise<void>;
|
|
5
|
-
walletAddressListeners: string[];
|
|
6
7
|
lightTheme?: Style;
|
|
7
8
|
darkTheme?: Style;
|
|
8
9
|
theme: string;
|
|
@@ -16,7 +17,8 @@ interface Configuration$1 {
|
|
|
16
17
|
* @param {Object} configuration - The configuration object.
|
|
17
18
|
* @param {Function} configuration.getWalletAddress - A function that returns a Promise resolving to the wallet address.
|
|
18
19
|
* @param {Function} configuration.promptLogin - A function to prompt the user to login.
|
|
19
|
-
* @param {string[]} configuration.walletAddressListeners - An array of strings representing wallet address listeners.
|
|
20
|
+
* @param {string[]} configuration.walletAddressListeners - An optional array of strings representing wallet address listeners.
|
|
21
|
+
* @param {Function} [configuration.walletAddressUpdateCallback] - An optional callback function for wallet address updates.
|
|
20
22
|
* @param {Object} [configuration.lightTheme] - Optional light theme settings.
|
|
21
23
|
* @param {Object} [configuration.darkTheme] - Optional dark theme settings.
|
|
22
24
|
* @param {string} configuration.theme - The chosen theme, light | dark.
|
|
@@ -40,7 +42,7 @@ interface Configuration$1 {
|
|
|
40
42
|
* darkTheme: { ... }
|
|
41
43
|
* });
|
|
42
44
|
*/
|
|
43
|
-
declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, lightTheme, darkTheme, theme, text, }: Configuration$1) => Promise<void>;
|
|
45
|
+
declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, walletAddressUpdateCallback, lightTheme, darkTheme, theme, text, }: Configuration$1) => Promise<void>;
|
|
44
46
|
|
|
45
47
|
interface Configuration {
|
|
46
48
|
identifier: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
interface Configuration$1 {
|
|
2
2
|
iframeEndpoint: string;
|
|
3
3
|
getWalletAddress: () => Promise<WalletAddress>;
|
|
4
|
+
walletAddressUpdateCallback?: (callback: () => void) => void;
|
|
5
|
+
walletAddressListeners?: string[];
|
|
4
6
|
promptLogin: () => Promise<void>;
|
|
5
|
-
walletAddressListeners: string[];
|
|
6
7
|
lightTheme?: Style;
|
|
7
8
|
darkTheme?: Style;
|
|
8
9
|
theme: string;
|
|
@@ -16,7 +17,8 @@ interface Configuration$1 {
|
|
|
16
17
|
* @param {Object} configuration - The configuration object.
|
|
17
18
|
* @param {Function} configuration.getWalletAddress - A function that returns a Promise resolving to the wallet address.
|
|
18
19
|
* @param {Function} configuration.promptLogin - A function to prompt the user to login.
|
|
19
|
-
* @param {string[]} configuration.walletAddressListeners - An array of strings representing wallet address listeners.
|
|
20
|
+
* @param {string[]} configuration.walletAddressListeners - An optional array of strings representing wallet address listeners.
|
|
21
|
+
* @param {Function} [configuration.walletAddressUpdateCallback] - An optional callback function for wallet address updates.
|
|
20
22
|
* @param {Object} [configuration.lightTheme] - Optional light theme settings.
|
|
21
23
|
* @param {Object} [configuration.darkTheme] - Optional dark theme settings.
|
|
22
24
|
* @param {string} configuration.theme - The chosen theme, light | dark.
|
|
@@ -40,7 +42,7 @@ interface Configuration$1 {
|
|
|
40
42
|
* darkTheme: { ... }
|
|
41
43
|
* });
|
|
42
44
|
*/
|
|
43
|
-
declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, lightTheme, darkTheme, theme, text, }: Configuration$1) => Promise<void>;
|
|
45
|
+
declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAddressListeners, walletAddressUpdateCallback, lightTheme, darkTheme, theme, text, }: Configuration$1) => Promise<void>;
|
|
44
46
|
|
|
45
47
|
interface Configuration {
|
|
46
48
|
identifier: string;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var w=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var K=Object.prototype.hasOwnProperty;var B=(e,t)=>{for(var n in t)w(e,n,{get:t[n],enumerable:!0})},J=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of V(t))!K.call(e,s)&&s!==n&&w(e,s,{get:()=>t[s],enumerable:!(r=F(t,s))||r.enumerable});return e};var Q=e=>J(w({},"__esModule",{value:!0}),e);var ge={};B(ge,{bringInitBackground:()=>q,bringInitContentScript:()=>M});module.exports=Q(ge);var G=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()},E=G;var D={name:"@bringweb3/chrome-extension-kit",version:"1.1.5",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 --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"},dependencies:{}};var Y=()=>D.version,k=Y;var z=({query:e,theme:t,themeMode:n,text:r,iframeUrl:s})=>{let i=chrome.runtime.id,o=`bringweb3-iframe-${i}`,a=document.getElementById(o);if(a)return a;let m=E({query:{...e,extensionId:i,v:k(),themeMode:n,textMode:r}}),l=t?`&${E({query:t,prefix:"t"})}`:"",c=document.createElement("iframe");return c.id=o,c.src=`${process.env.IFRAME_URL||s}?${m}${l}`,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=z;var X=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([n,r])=>{n in e.style&&(e.style[n]=r)})},C=X;var Z=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=Z;var p={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},ee=[p.ACTIVATE],te=({event:e,iframeEl:t,promptLogin:n})=>{let{data:r}=e,{from:s,action:i,style:o,keyFrames:a,time:m,extensionId:l}=r;if(s==="bringweb3"&&!(l!==chrome.runtime.id&&!ee.includes(i)))switch(i){case p.OPEN:C(t,o);break;case p.CLOSE:t&&t.parentNode?.removeChild(t),m&&chrome.runtime.sendMessage({action:i,time:m,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:m,from:"bringweb3"});break;case p.ADD_KEYFRAMES:P(a);break;default:break}},S=te;var ne=({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:o})})}},R=ne;var y=null,L=!1,re=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:n,lightTheme:r,darkTheme:s,theme:i,text:o})=>{if(!e||!t||!n?.length)throw new Error("Missing configuration");R({walletAddressListeners:n,getWalletAddress:e,iframeEl:y}),window.addEventListener("message",a=>S({event:a,iframeEl:y,promptLogin:t})),chrome.runtime.onMessage.addListener((a,m,l)=>{let{action:c}=a;switch(c){case"GET_WALLET_ADDRESS":return e().then(g=>l({status:"success",walletAddress:g})).catch(g=>l({status:"success",walletAddress:void 0})),!0;case"INJECT":if(L)return;let{token:h,iframeUrl:f}=a;return console.log({iframeUrl:f}),y=v({query:{token:h},iframeUrl:f,theme:i==="dark"?s:r,themeMode:i||"light",text:o}),L=!0,l({status:"success"}),!0;default:console.error(`Unknown action: ${c}`);break}})},M=re;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 se=async e=>{let t=u.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},I=se;var ie=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()},O=ie;var oe=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()},_=oe;var A="updateCache";var ae=async(e,t)=>new Promise((n,r)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):n()})}),ce=async e=>new Promise((t,n)=>{chrome.storage.local.get([`bring_${e}`],r=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t(r[`bring_${e}`])})}),de=async e=>new Promise((t,n)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t()})}),d={set:ae,get:ce,remove:de};var U=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 x(e,{action:"GET_WALLET_ADDRESS"});n?.walletAddress&&t!==n?.walletAddress&&(t=n?.walletAddress,await d.set("walletAddress",t))}catch{}return t},le=e=>{let t=Date.now();return(e-t)/1e3/60},T=async e=>{let t=await I(e);d.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:n}=t,r=le(n);return chrome.alarms.create(A,{delayInMinutes:r||60*24*2}),t.relevantDomains},me=async(e,t,n,r)=>{let s={showNotification:!1,token:"",iframeUrl:""},i=await d.get("notificationCheck");if(i?.check&&Date.now()<i.check)return s;let o=await W(t);if(!o)return s;let a=await _({apiKey:e,walletAddress:o,cashbackUrl:n}),m={check:r?a.nextRequestTimestampActivated:a.nextRequestTimestampRegular,nextRequestTimestampActivated:a.nextRequestTimestampActivated,nextRequestTimestampRegular:a.nextRequestTimestampRegular};return d.set("notificationCheck",m),{showNotification:a.showNotification,token:a.token,iframeUrl:a.iframeUrl}},ue=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),N=async(e,t)=>{let n=await d.get("relevantDomains");if(n===void 0&&(n=await T(t)),!e||!n||!n.length)return"";let r=ue(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=U);let n=await d.get("quietDomains");typeof n=="object"?n[e]=Date.now()+t:n={[e]:Date.now()+U},d.set("quietDomains",n)},pe=e=>e?chrome.runtime.getURL(e):void 0,x=(e,t)=>new Promise((s,i)=>{let o=a=>{chrome.tabs.get(e,m=>{if(chrome.runtime.lastError){i(new Error(chrome.runtime.lastError.message));return}chrome.tabs.sendMessage(e,t,l=>{chrome.runtime.lastError?a<4?setTimeout(()=>o(a+1),1e3*Math.pow(2,a)):i(new Error(chrome.runtime.lastError.message)):s(l)})})};o(0)}),$=async(e,t,n)=>{let r=await me(e,t,pe(n));r.showNotification&&await x(t,{action:"INJECT",token:r.token,iframeUrl:r.iframeUrl})},b={},fe=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),T(e),chrome.alarms.onAlarm.addListener(async r=>{let{name:s}=r;switch(s){case A:T(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,a=await N(s.tab?.url||s.origin,e);if(!a)break;j(a,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 $(e,r,n);return}if(!i.url)return;let a=i.url.replace("www.",""),m=b[r];if(s.status!=="complete"||a===m)return;b[r]=a;let l=await N(i.url,e);if(!l||!l.length){await $(e,r,n);return}let c=await W(r),{token:h,isValid:f,iframeUrl:g}=await O({apiKey:e,body:{domain:l,url:i.url,address:c}});if(!f){f===!1&&j(l);return}x(r,{action:"INJECT",token:h,domain:a,iframeUrl:g})}),chrome.tabs.onRemoved.addListener(r=>delete b[r])},q=fe;0&&(module.exports={bringInitBackground,bringInitContentScript});
|
|
1
|
+
"use strict";var w=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var Q=(e,t)=>{for(var n in t)w(e,n,{get:t[n],enumerable:!0})},G=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of B(t))!J.call(e,s)&&s!==n&&w(e,s,{get:()=>t[s],enumerable:!(r=K(t,s))||r.enumerable});return e};var H=e=>G(w({},"__esModule",{value:!0}),e);var we={};Q(we,{bringInitBackground:()=>V,bringInitContentScript:()=>O});module.exports=H(we);var Y=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()},E=Y;var k={name:"@bringweb3/chrome-extension-kit",version:"1.1.6",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 --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"},dependencies:{}};var X=()=>k.version,D=X;var Z=({query:e,theme:t,themeMode:n,text:r,iframeUrl:s})=>{let i=chrome.runtime.id,o=`bringweb3-iframe-${i}`,a=document.getElementById(o);if(a)return a;let d=E({query:{...e,extensionId:i,v:D(),themeMode:n,textMode:r}}),m=t?`&${E({query:t,prefix:"t"})}`:"",c=document.createElement("iframe");return c.id=o,c.src=`${process.env.IFRAME_URL||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},P=Z;var ee=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([n,r])=>{n in e.style&&(e.style[n]=r)})},C=ee;var te=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")},S=te;var p={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},ne=[p.ACTIVATE],re=({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&&!ne.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:S(a);break;default:break}},R=re;var M=async({iframeEl:e,getWalletAddress:t})=>{if(!e&&(e=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!e)||!e.contentWindow)return;let n=await t();e.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:n},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:n})},se=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:n,iframeEl:r})=>{if(t)t(()=>M({iframeEl:r,getWalletAddress:n}));else if(e)for(let s=0;s<e.length;s++){let i=e[s];i&&window.addEventListener(i,async()=>M({iframeEl:r,getWalletAddress:n}))}},I=se;var y=null,L=!1,ie=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:n,walletAddressUpdateCallback:r,lightTheme:s,darkTheme:i,theme:o,text:a})=>{if(!e||!t||!n?.length&&typeof r!="function")throw new Error("Missing configuration");I({walletAddressListeners:n,walletAddressUpdateCallback:r,getWalletAddress:e,iframeEl:y}),window.addEventListener("message",d=>R({event:d,iframeEl:y,promptLogin:t})),chrome.runtime.onMessage.addListener((d,m,c)=>{if(d?.from!=="bringweb3")return;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(L)return;let{token:g,iframeUrl:h}=d;return console.log({iframeUrl:h}),y=P({query:{token:g},iframeUrl:h,theme:o==="dark"?i:s,themeMode:o||"light",text:a}),L=!0,c({status:"success"}),!0;default:console.error(`Unknown action: ${f}`);break}})},O=ie;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 oe=async e=>{let t=u.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},_=oe;var ae=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()},U=ae;var ce=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()},N=ce;var A="updateCache";var de=async(e,t)=>new Promise((n,r)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):n()})}),le=async e=>new Promise((t,n)=>{chrome.storage.local.get([`bring_${e}`],r=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t(r[`bring_${e}`])})}),me=async e=>new Promise((t,n)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t()})}),l={set:de,get:le,remove:me};var j=30*60*1e3,q=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 v(e,{action:"GET_WALLET_ADDRESS"});n?.walletAddress&&t!==n?.walletAddress&&(t=n?.walletAddress,await l.set("walletAddress",t))}catch{}return t},ue=e=>{let t=Date.now();return(e-t)/1e3/60},T=async e=>{let t=await _(e);l.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:n}=t,r=ue(n);return chrome.alarms.create(A,{delayInMinutes:r||60*24*2}),t.relevantDomains},pe=async(e,t,n,r)=>{let s={showNotification:!1,token:"",iframeUrl:""},i=await l.get("notificationCheck");if(i?.check&&Date.now()<i.check)return s;let o=await q(t);if(!o)return s;let a=await N({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,iframeUrl:a.iframeUrl}},fe=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),W=async(e,t)=>{let n=await l.get("relevantDomains");if(n===void 0&&(n=await T(t)),!e||!n||!n.length)return"";let r=fe(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""},$=async(e,t)=>{t||(t=j);let n=await l.get("quietDomains");typeof n=="object"?n[e]=Date.now()+t:n={[e]:Date.now()+j},l.set("quietDomains",n)},ge=e=>e?chrome.runtime.getURL(e):void 0,v=(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,from:"bringweb3"},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)}),F=async(e,t,n)=>{let r=await pe(e,t,ge(n));r.showNotification&&await v(t,{action:"INJECT",token:r.token,iframeUrl:r.iframeUrl})},b={},he=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),T(e),chrome.alarms.onAlarm.addListener(async r=>{let{name:s}=r;switch(s){case A:T(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 W(s.tab?.url||s.origin,e);if(!a)break;$(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 F(e,r,n);return}if(!i.url)return;let a=i.url.replace("www.",""),d=b[r];if(s.status!=="complete"||a===d)return;b[r]=a;let m=await W(i.url,e);if(!m||!m.length){await F(e,r,n);return}let c=await q(r),{token:f,isValid:g,iframeUrl:h}=await U({apiKey:e,body:{domain:m,url:i.url,address:c}});if(!g){g===!1&&$(m);return}v(r,{action:"INJECT",token:f,domain:a,iframeUrl:h})}),chrome.tabs.onRemoved.addListener(r=>delete b[r])},V=he;0&&(module.exports={bringInitBackground,bringInitContentScript});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var F=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=F;var x={name:"@bringweb3/chrome-extension-kit",version:"1.1.6",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 --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"},dependencies:{}};var V=()=>x.version,k=V;var K=({query:e,theme:t,themeMode:n,text:r,iframeUrl: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=`${process.env.IFRAME_URL||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},D=K;var B=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([n,r])=>{n in e.style&&(e.style[n]=r)})},P=B;var J=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=J;var p={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES"},Q=[p.ACTIVATE],G=({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&&!Q.includes(i)))switch(i){case p.OPEN:P(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}},S=G;var R=async({iframeEl:e,getWalletAddress:t})=>{if(!e&&(e=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!e)||!e.contentWindow)return;let n=await t();e.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:n},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:n})},H=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:n,iframeEl:r})=>{if(t)t(()=>R({iframeEl:r,getWalletAddress:n}));else if(e)for(let s=0;s<e.length;s++){let i=e[s];i&&window.addEventListener(i,async()=>R({iframeEl:r,getWalletAddress:n}))}},M=H;var E=null,I=!1,Y=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:n,walletAddressUpdateCallback:r,lightTheme:s,darkTheme:i,theme:o,text:a})=>{if(!e||!t||!n?.length&&typeof r!="function")throw new Error("Missing configuration");M({walletAddressListeners:n,walletAddressUpdateCallback:r,getWalletAddress:e,iframeEl:E}),window.addEventListener("message",d=>S({event:d,iframeEl:E,promptLogin:t})),chrome.runtime.onMessage.addListener((d,m,c)=>{if(d?.from!=="bringweb3")return;let{action:f}=d;switch(f){case"GET_WALLET_ADDRESS":return e().then(v=>c({status:"success",walletAddress:v})).catch(v=>c({status:"success",walletAddress:void 0})),!0;case"INJECT":if(I)return;let{token:g,iframeUrl:h}=d;return console.log({iframeUrl:h}),E=D({query:{token:g},iframeUrl:h,theme:o==="dark"?i:s,themeMode:o||"light",text:a}),I=!0,c({status:"success"}),!0;default:console.error(`Unknown action: ${f}`);break}})},z=Y;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 X=async e=>{let t=u.getInstance().getApiEndpoint();return await(await fetch(`${t}/domains`,{headers:{"x-api-key":e}})).json()},L=X;var Z=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()},O=Z;var ee=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()},_=ee;var y="updateCache";var te=async(e,t)=>new Promise((n,r)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):n()})}),ne=async e=>new Promise((t,n)=>{chrome.storage.local.get([`bring_${e}`],r=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t(r[`bring_${e}`])})}),re=async e=>new Promise((t,n)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):t()})}),l={set:te,get:ne,remove:re};var U=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},se=e=>{let t=Date.now();return(e-t)/1e3/60},b=async e=>{let t=await L(e);l.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:n}=t,r=se(n);return chrome.alarms.create(y,{delayInMinutes:r||60*24*2}),t.relevantDomains},ie=async(e,t,n,r)=>{let s={showNotification:!1,token:"",iframeUrl:""},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,iframeUrl:a.iframeUrl}},oe=e=>e.replace(/^(https?:\/\/)?(www\.)?/,""),N=async(e,t)=>{let n=await l.get("relevantDomains");if(n===void 0&&(n=await b(t)),!e||!n||!n.length)return"";let r=oe(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=U);let n=await l.get("quietDomains");typeof n=="object"?n[e]=Date.now()+t:n={[e]:Date.now()+U},l.set("quietDomains",n)},ae=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,from:"bringweb3"},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 ie(e,t,ae(n));r.showNotification&&await T(t,{action:"INJECT",token:r.token,iframeUrl:r.iframeUrl})},A={},ce=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 N(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 N(i.url,e);if(!m||!m.length){await W(e,r,n);return}let c=await $(r),{token:f,isValid:g,iframeUrl:h}=await O({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,iframeUrl:h})}),chrome.tabs.onRemoved.addListener(r=>delete A[r])},de=ce;export{de as bringInitBackground,z as bringInitContentScript};
|