@bringweb3/chrome-extension-kit 1.2.14 → 1.3.0
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/dist/index.d.mts +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -47,6 +47,7 @@ declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAd
|
|
|
47
47
|
interface Configuration {
|
|
48
48
|
identifier: string;
|
|
49
49
|
apiEndpoint: string;
|
|
50
|
+
whitelistEndpoint?: string;
|
|
50
51
|
cashbackPagePath?: string;
|
|
51
52
|
}
|
|
52
53
|
/**
|
|
@@ -57,6 +58,7 @@ interface Configuration {
|
|
|
57
58
|
* @param {Object} configuration - The configuration object.
|
|
58
59
|
* @param {string} configuration.identifier - The identifier for the extension.
|
|
59
60
|
* @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
|
|
61
|
+
* @param {string} configuration.whitelistEndpoint - Endpoint for whitelist of redirect urls.
|
|
60
62
|
* @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
|
|
61
63
|
* @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
|
|
62
64
|
* @returns {Promise<void>}
|
|
@@ -79,10 +81,11 @@ interface Configuration {
|
|
|
79
81
|
* bringInitBackground({
|
|
80
82
|
* identifier: '<bring_identifier>',
|
|
81
83
|
* apiEndpoint: 'sandbox',
|
|
84
|
+
* whitelistEndpoint: 'https://example.com/whitelist.json',
|
|
82
85
|
* cashbackPagePath: '/cashback.html'
|
|
83
86
|
* });
|
|
84
87
|
*/
|
|
85
|
-
declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath }: Configuration) => Promise<void>;
|
|
88
|
+
declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint }: Configuration) => Promise<void>;
|
|
86
89
|
|
|
87
90
|
interface TurnOff {
|
|
88
91
|
isTurnedOff: boolean;
|
package/dist/index.d.ts
CHANGED
|
@@ -47,6 +47,7 @@ declare const bringInitContentScript: ({ getWalletAddress, promptLogin, walletAd
|
|
|
47
47
|
interface Configuration {
|
|
48
48
|
identifier: string;
|
|
49
49
|
apiEndpoint: string;
|
|
50
|
+
whitelistEndpoint?: string;
|
|
50
51
|
cashbackPagePath?: string;
|
|
51
52
|
}
|
|
52
53
|
/**
|
|
@@ -57,6 +58,7 @@ interface Configuration {
|
|
|
57
58
|
* @param {Object} configuration - The configuration object.
|
|
58
59
|
* @param {string} configuration.identifier - The identifier for the extension.
|
|
59
60
|
* @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
|
|
61
|
+
* @param {string} configuration.whitelistEndpoint - Endpoint for whitelist of redirect urls.
|
|
60
62
|
* @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
|
|
61
63
|
* @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
|
|
62
64
|
* @returns {Promise<void>}
|
|
@@ -79,10 +81,11 @@ interface Configuration {
|
|
|
79
81
|
* bringInitBackground({
|
|
80
82
|
* identifier: '<bring_identifier>',
|
|
81
83
|
* apiEndpoint: 'sandbox',
|
|
84
|
+
* whitelistEndpoint: 'https://example.com/whitelist.json',
|
|
82
85
|
* cashbackPagePath: '/cashback.html'
|
|
83
86
|
* });
|
|
84
87
|
*/
|
|
85
|
-
declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath }: Configuration) => Promise<void>;
|
|
88
|
+
declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint }: Configuration) => Promise<void>;
|
|
86
89
|
|
|
87
90
|
interface TurnOff {
|
|
88
91
|
isTurnedOff: boolean;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var D=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var ae=Object.prototype.hasOwnProperty;var ce=(e,t)=>{for(var r in t)D(e,r,{get:t[r],enumerable:!0})},me=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of oe(t))!ae.call(e,i)&&i!==r&&D(e,i,{get:()=>t[i],enumerable:!(n=se(t,i))||n.enumerable});return e};var de=e=>me(D({},"__esModule",{value:!0}),e);var Ke={};ce(Ke,{bringInitBackground:()=>re,bringInitContentScript:()=>B,getTurnOff:()=>ne,setTurnOff:()=>ie});module.exports=de(Ke);var le=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()},C=le;var L={name:"@bringweb3/chrome-extension-kit",version:"1.2.14",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 fe=()=>L.version,y=fe;var pe=({query:e,theme:t,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:d})=>{let a=chrome.runtime.id,c=`bringweb3-iframe-${a}`,m=document.getElementById(c),A=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(m)return m;let u=C({query:{...e,extensionId:a,v:y(),themeMode:r,textMode:n,switchWallet:String(d)}}),p=t?`&${C({query:t,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=c,l.src=`${A}?${u}${p}`,l.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),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;",t?.popupShadow&&(l.style.boxShadow=t.popupShadow),document.documentElement.appendChild(l),l},R=pe;var ge=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,n])=>{r in e.style&&(e.style[r]=n)})},W=ge;var we=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")},F=we;var f={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"},he=[f.ACTIVATE],Ee=({event:e,iframeEl:t,promptLogin:r})=>{let{data:n}=e,{from:i,action:s,style:d,keyFrames:a,time:c,extensionId:m,url:A,domain:u}=n;if(i==="bringweb3"&&!(m!==chrome.runtime.id&&!he.includes(s)))switch(s){case f.OPEN:W(t,d);break;case f.CLOSE:t&&t.parentNode?.removeChild(t),c&&chrome.runtime.sendMessage({action:s,time:c,domain:u,from:"bringweb3"});break;case f.PROMPT_LOGIN:r();break;case f.ACTIVATE:chrome.runtime.sendMessage({action:s,from:"bringweb3",domain:u,extensionId:m,time:c});break;case f.OPT_OUT:chrome.runtime.sendMessage({action:s,time:c,from:"bringweb3"});break;case f.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:s,from:"bringweb3"});case f.ADD_KEYFRAMES:F(a);break;case f.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:s,from:"bringweb3"});break;default:break}},$=Ee;var K=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})},Ae=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:r,iframeEl:n})=>{if(t)t(()=>K({iframeEl:n,getWalletAddress:r}));else if(e)for(let i=0;i<e.length;i++){let s=e[i];s&&window.addEventListener(s,async()=>K({iframeEl:n,getWalletAddress:r}))}},G=Ae;var ye=["www.","www1.","www2."],be=e=>{if(!e)return"";e=e.split("://").reverse()[0]||"";for(let t of ye)e.startsWith(t)&&(e=e.replace(t,""));return e},b=be;var I=null,j=!1,Oe=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:d,text:a,switchWallet:c=!1})=>{if(window.self===window.top){if(!e||!t||!r?.length&&typeof n!="function")throw new Error("Missing configuration");G({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:e,iframeEl:I}),window.addEventListener("message",m=>$({event:m,iframeEl:I,promptLogin:t})),chrome.runtime.onMessage.addListener((m,A,u)=>{if(m?.from!=="bringweb3")return;let{action:p}=m;switch(p){case"GET_WALLET_ADDRESS":return e().then(M=>u({status:"success",walletAddress:M})).catch(M=>u({status:"success",walletAddress:void 0})),!0;case"INJECT":if(m.domain!==b(location.href)||j)return u({status:"Domain already changed"}),!0;let{token:l,iframeUrl:P,userId:N}=m,U={token:l};return N&&(U.userId=N),I=R({query:U,iframeUrl:P,theme:d==="dark"?s:i,themeMode:d||"light",text:a,switchWallet:c,page:m.page}),j=!0,u({status:"success"}),!0;default:console.error(`Unknown action: ${p}`);break}})}},B=Oe;var V=e=>{chrome.tabs.create({url:e})};var w=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 Te=async(e,t)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),ve=async e=>new Promise((t,r)=>{chrome.storage.local.get([`bring_${e}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t(n[`bring_${e}`])})}),xe=async e=>new Promise((t,r)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t()})}),o={set:Te,get:ve,remove:xe};var q=require("uuid"),Pe=async()=>{let e=await o.get("id");return e||(e=(0,q.v4)(),o.set("id",e)),e},g=Pe;var De=async e=>{let{path:t,method:r,apiKey:n,params:i}=e;if(!e||!t||!r||!i&&r==="POST"||!n)throw new Error("Missing endpoint or method");let s=w.getInstance().getApiEndpoint();if(s+=t,r==="GET"){let c=new URLSearchParams({...i,version:y(),opt_out:await o.get("optOut")||0,user_id:await g()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});s+=`?${c.toString()}`}else r==="POST"&&(i={...i,version:y(),optOut:await o.get("optOut")||0,userId:await g()||void 0,walletAddress:i?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(s,{method:r,headers:{"Content-Type":"application/json","x-api-key":n},body:r==="POST"?JSON.stringify(i):void 0})).json()},h=De;var Ce=async e=>await h({path:"/domains",apiKey:e,method:"GET"}),H=Ce;var Ie=async({apiKey:e,body:t})=>await h({path:"/check/popup",apiKey:e,method:"POST",params:t}),Q=Ie;var S="updateCache";var J=30*60*1e3,Se=async(e,t)=>{t||(t=J);let r=await o.get("quietDomains");typeof r=="object"?r[e]=Date.now()+t:r={[e]:Date.now()+J},o.set("quietDomains",r)},O=Se;var _e=async({apiKey:e,walletAddress:t,cashbackUrl:r,lastActivation:n})=>{let i={walletAddress:t};return n&&(i.lastActivation=n),r&&(i.cashbackUrl=r),await h({path:"/check/notification",apiKey:e,method:"POST",params:i})},Y=_e;var ke=(e,t)=>new Promise((i,s)=>{let d=a=>{chrome.tabs.get(e,c=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(e,{...t,from:"bringweb3"},m=>{chrome.runtime.lastError?a<4?setTimeout(()=>d(a+1),1e3*Math.pow(2,a)):i(null):i(m||null)})})};d(0)}),E=ke;var Ne=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 E(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await o.set("walletAddress",t))}catch{}return t},T=Ne;var Ue=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 T(t):await o.get("walletAddress");if(!s)return n;let d=await o.get("lastActivation"),a=await Y({apiKey:e,walletAddress:s,cashbackUrl:r,lastActivation:d});o.set("notificationCheck",a.nextCall);let c={showNotification:a.showNotification,token:a.token,iframeUrl:a.iframeUrl,expiration:a.expiration};return c.showNotification&&await o.set("notification",c),c},v=Ue;var Me=e=>e?chrome.runtime.getURL(e):"",x=Me;var Le=async(e,t,r,n,i)=>{t===chrome.runtime.id&&await o.set("lastActivation",Date.now()),e&&O(e,i||Date.now()+24*60*60*1e3),await v(r,void 0,x(n))},z=Le;var X=async e=>e<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+e),{isOptedOut:!0}),Z=async()=>{let e=await o.get("optOut");return{isOptedOut:!!(e&&e>Date.now())}};var ee=async(e,t,r)=>{await E(e,{action:"INJECT",page:"notification",token:t.token,iframeUrl:t.iframeUrl,userId:await g(),domain:r})},Re=async(e,t,r,n)=>{let i=await o.get("notification");if(i?.expiration<Date.now())await o.remove("notification");else if(i)return await ee(t,i,n);let s=await v(e,t,x(r));if(s.showNotification)return await ee(t,s,n)},te=Re;var We=e=>{let t=Date.now();return(e-t)/1e3/60},k=async e=>{let t=await H(e);o.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:r}=t,n=We(r);return chrome.alarms.create(S,{delayInMinutes:n||60*24*2}),t.relevantDomains},Fe=async(e,t)=>{let r=await o.get("relevantDomains");if(r===void 0&&(r=await k(t)),!e||!r||!r.length)return"";let n=b(e);for(let i of r)if(n.startsWith(i)){let s=await o.get("quietDomains");return s&&s[i]&&Date.now()<s[i]?"":i}return""},_={},$e=async({identifier:e,apiEndpoint:t,cashbackPagePath:r})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");w.getInstance().setApiEndpoint(t),await o.get("relevantDomains")||k(e),chrome.alarms.onAlarm.addListener(async n=>{let{name:i}=n;switch(i){case S:k(e);break;default:console.error("alarm with no use case:",i);break}}),chrome.runtime.onMessage.addListener((n,i,s)=>{if(n?.from!=="bringweb3")return;let{action:d}=n;switch(d){case"ACTIVATE":{let{domain:a,extensionId:c,time:m}=n;return z(a,c,e,r,m).then(()=>s()),!0}case"GET_OPT_OUT":return Z().then(a=>s(a)),!0;case"OPT_OUT":{let{time:a}=n;return X(a).then(c=>s(c)),!0}case"CLOSE":{let{time:a,domain:c}=n;return c&&(O(c,a),s({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:a}=n;return a?o.set("walletAddress",a).then(()=>s(a)):o.remove("walletAddress").then(()=>s({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>s({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${d}`),!0;case"OPEN_CASHBACK_PAGE":return V(r||""),s({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(n,i,s)=>{if(!s?.url?.startsWith("http")||!s.url)return;let d=b(s.url),a=await o.get("optOut");if(a&&a>Date.now())return;a&&(o.remove("optOut"),o.remove("optOutKey"));let c=_[n];if(i.status!=="complete"||d===c)return;_[n]=d;let m=await Fe(s.url,e);if(!m||!m.length){await te(e,n,r,d);return}let A=await T(n),{token:u,isValid:p,iframeUrl:l}=await Q({apiKey:e,body:{domain:m,url:s.url,address:A}});if(!p){p===!1&&O(m);return}let P=await g();E(n,{action:"INJECT",token:u,domain:d,iframeUrl:l,userId:P})}),chrome.tabs.onRemoved.addListener(n=>delete _[n])},re=$e;var ne=()=>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})})}),ie=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")})});0&&(module.exports={bringInitBackground,bringInitContentScript,getTurnOff,setTurnOff});
|
|
1
|
+
"use strict";var _=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var dt=Object.prototype.hasOwnProperty;var mt=(t,e)=>{for(var r in e)_(t,r,{get:e[r],enumerable:!0})},lt=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ct(e))!dt.call(t,n)&&n!==r&&_(t,n,{get:()=>e[n],enumerable:!(i=at(e,n))||i.enumerable});return t};var ut=t=>lt(_({},"__esModule",{value:!0}),t);var qt={};mt(qt,{bringInitBackground:()=>it,bringInitContentScript:()=>B,getTurnOff:()=>st,setTurnOff:()=>ot});module.exports=ut(qt);var ft=t=>{let e=new URLSearchParams,{query:r,prefix:i}=t;return Object.entries(r).forEach(([n,s])=>{s&&(i&&(n=`${i}_${n}`),n==="url"?e.append(n,encodeURIComponent(s)):e.append(n,s))}),e.toString()},S=ft;var L={name:"@bringweb3/chrome-extension-kit",version:"1.3.0",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 gt=()=>L.version,b=gt;var ht=({query:t,theme:e,themeMode:r,text:i,iframeUrl:n,page:s,switchWallet:a})=>{let d=chrome.runtime.id,m=`bringweb3-iframe-${d}`,c=document.getElementById(m),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:n;if(c)return c;let f=S({query:{...t,extensionId:d,v:b(),themeMode:r,textMode:i,switchWallet:String(a)}}),g=e?`&${S({query:e,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=m,l.src=`${u}?${f}${g}`,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},R=ht;var wt=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,i])=>{r in t.style&&(t.style[r]=i)})},F=wt;var Et=t=>{if(!t||!t.length)return;let e=document.createElement("style");document.head.appendChild(e);let r=e.sheet;r?t.forEach(({name:i,rules:n})=>{r.insertRule(`@keyframes ${i} { ${n} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},$=Et;var h={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"},At=[h.ACTIVATE],bt=({event:t,iframeEl:e,promptLogin:r})=>{let{data:i}=t,{from:n,action:s,style:a,keyFrames:d,time:m,extensionId:c,url:u,domain:f,redirectUrl:g}=i;if(n==="bringweb3"&&!(c!==chrome.runtime.id&&!At.includes(s)))switch(s){case h.OPEN:F(e,a);break;case h.CLOSE:e&&e.parentNode?.removeChild(e),m&&chrome.runtime.sendMessage({action:s,time:m,domain:f,from:"bringweb3"});break;case h.PROMPT_LOGIN:r();break;case h.ACTIVATE:chrome.runtime.sendMessage({action:s,from:"bringweb3",domain:f,extensionId:c,time:m,redirectUrl:g});break;case h.OPT_OUT:chrome.runtime.sendMessage({action:s,time:m,from:"bringweb3"});break;case h.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:s,from:"bringweb3"});case h.ADD_KEYFRAMES:$(d);break;case h.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:s,url:u,from:"bringweb3"});break;default:break}},G=bt;var K=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})},yt=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:i})=>{if(e)e(()=>K({iframeEl:i,getWalletAddress:r}));else if(t)for(let n=0;n<t.length;n++){let s=t[n];s&&window.addEventListener(s,async()=>K({iframeEl:i,getWalletAddress:r}))}},j=yt;var Ot=["www.","www1.","www2."],Tt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of Ot)t.startsWith(e)&&(t=t.replace(e,""));return t},y=Tt;var k=null,q=!1,vt=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:i,lightTheme:n,darkTheme:s,theme:a,text:d,switchWallet:m=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof i!="function")throw new Error("Missing configuration");j({walletAddressListeners:r,walletAddressUpdateCallback:i,getWalletAddress:t,iframeEl:k}),window.addEventListener("message",c=>G({event:c,iframeEl:k,promptLogin:e})),chrome.runtime.onMessage.addListener((c,u,f)=>{if(c?.from!=="bringweb3")return;let{action:g}=c;switch(g){case"GET_WALLET_ADDRESS":return t().then(W=>f({status:"success",walletAddress:W})).catch(W=>f({status:"success",walletAddress:void 0})),!0;case"INJECT":if(c.domain!==y(location.href)||q)return f({status:"Domain already changed"}),!0;let{token:l,iframeUrl:T,userId:v}=c,x={token:l};return v&&(x.userId=v),k=R({query:x,iframeUrl:T,theme:a==="dark"?s:n,themeMode:a||"light",text:d,switchWallet:m,page:c.page}),q=!0,f({status:"success"}),!0;default:console.error(`Unknown action: ${g}`);break}})}},B=vt;var V=t=>{t&&chrome.tabs.create({url:t})};var p=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";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"}getWhitelistEndpoint(){if(!this.whitelistEndpoint)throw new Error("Whitelist endpoint not set. Call setWhitelistEndpoint first.");return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var xt=async(t,e)=>new Promise((r,i)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?i(chrome.runtime.lastError):r()})}),Pt=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],i=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(i[`bring_${t}`])})}),Dt=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),o={set:xt,get:Pt,remove:Dt};var H=require("uuid"),Ct=async()=>{let t=await o.get("id");return t||(t=(0,H.v4)(),o.set("id",t)),t},w=Ct;var It=async t=>{let{path:e,method:r,apiKey:i,params:n}=t;if(!t||!e||!r||!n&&r==="POST"||!i)throw new Error("Missing endpoint or method");let s=p.getInstance().getApiEndpoint();if(s+=e,r==="GET"){let m=new URLSearchParams({...n,version:b(),opt_out:await o.get("optOut")||0,user_id:await w()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});s+=`?${m.toString()}`}else r==="POST"&&(n={...n,version:b(),optOut:await o.get("optOut")||0,userId:await w()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(s,{method:r,headers:{"Content-Type":"application/json","x-api-key":i},body:r==="POST"?JSON.stringify(n):void 0})).json()},E=It;var _t=async t=>{let e=p.getInstance().getWhitelistEndpoint(),r={path:"/domains",apiKey:t,method:"GET"};return e&&(r.params={whitelist:encodeURIComponent(e)}),await E(r)},Q=_t;var St=async({apiKey:t,body:e})=>await E({path:"/check/popup",apiKey:t,method:"POST",params:e}),J=St;var U="updateCache";var Y=30*60*1e3,kt=async(t,e)=>{e||(e=Y);let r=await o.get("quietDomains");typeof r=="object"?r[t]=Date.now()+e:r={[t]:Date.now()+Y},o.set("quietDomains",r)},O=kt;var Ut=async({apiKey:t,walletAddress:e,cashbackUrl:r,lastActivation:i})=>{let n={walletAddress:e};return i&&(n.lastActivation=i),r&&(n.cashbackUrl=r),await E({path:"/check/notification",apiKey:t,method:"POST",params:n})},z=Ut;var Nt=(t,e)=>new Promise((n,s)=>{let a=d=>{chrome.tabs.get(t,m=>{if(chrome.runtime.lastError){n(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},c=>{chrome.runtime.lastError?d<4?setTimeout(()=>a(d+1),1e3*Math.pow(2,d)):n(null):n(c||null)})})};a(0)}),A=Nt;var Mt=async t=>{let e=await o.get("walletAddress");try{if(!t){let i=await chrome.tabs.query({active:!0,currentWindow:!0});if(!i||!i[0]||!i[0].id)return e;t=i[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},P=Mt;var Wt=async(t,e,r)=>{let i={showNotification:!1,token:"",iframeUrl:""},n=await o.get("notificationCheck");if(n&&Date.now()<n)return i;let s=e?await P(e):await o.get("walletAddress");if(!s)return i;let a=await o.get("lastActivation"),d=await z({apiKey:t,walletAddress:s,cashbackUrl:r,lastActivation:a});o.set("notificationCheck",d.nextCall);let m={showNotification:d.showNotification,token:d.token,iframeUrl:d.iframeUrl,expiration:d.expiration};return m.showNotification&&await o.set("notification",m),m},D=Wt;var Lt=t=>t?chrome.runtime.getURL(t):"",C=Lt;var Rt=(t,e)=>{try{let r=p.getInstance().getWhitelistEndpoint();if(!e.length)return!!r;let n=new URL(t).hostname.toLowerCase();return n=n.replace("www.",""),e.includes(n)?!0:e.some(s=>{if(s.startsWith("*.")){let a=s.slice(2);return n.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},I=Rt;var Ft=async(t,e,r,i,n,s,a)=>{if(e===chrome.runtime.id&&await o.set("lastActivation",Date.now()),t&&O(t,n||Date.now()+24*60*60*1e3),s&&a){let d=await o.get("redirectsWhitelist");(!d?.length||I(a,d))&&chrome.tabs.update(s,{url:a})}await D(r,void 0,C(i))},X=Ft;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 w(),domain:r})},$t=async(t,e,r,i)=>{let n=await o.get("notification");if(n?.expiration<Date.now())await o.remove("notification");else if(n)return await et(e,n,i);let s=await D(t,e,C(r));if(s.showNotification)return await et(e,s,i)},rt=$t;var nt=async()=>{try{let t=p.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 Gt=t=>{let e=Date.now();return(t-e)/1e3/60},M=async t=>{let e=await Q(t);o.set("relevantDomains",e.relevantDomains);let r=await nt();r&&o.set("redirectsWhitelist",r);let{nextUpdateTimestamp:i}=e,n=Gt(i);return chrome.alarms.create(U,{delayInMinutes:n||60*24*2}),e.relevantDomains},Kt=async(t,e)=>{let r=await o.get("relevantDomains");if(r===void 0&&(r=await M(e)),!t||!r||!r.length)return"";let i=y(t);for(let n of r)if(i.startsWith(n)){let s=await o.get("quietDomains");return s&&s[n]&&Date.now()<s[n]?"":n}return""},N={},jt=async({identifier:t,apiEndpoint:e,cashbackPagePath:r,whitelistEndpoint:i})=>{if(!t||!e)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(e))throw new Error("unknown apiEndpoint");p.getInstance().setApiEndpoint(e),p.getInstance().setWhitelistEndpoint(i||""),await o.get("relevantDomains")||M(t),chrome.alarms.onAlarm.addListener(async n=>{let{name:s}=n;switch(s){case U:M(t);break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener((n,s,a)=>{if(n?.from!=="bringweb3")return;let{action:d}=n;switch(d){case"ACTIVATE":{let{domain:c,extensionId:u,time:f,redirectUrl:g}=n;return X(c,u,t,r,f,s.tab?.id,g).then(()=>a()),!0}case"GET_OPT_OUT":return tt().then(c=>a(c)),!0;case"OPT_OUT":{let{time:c}=n;return Z(c).then(u=>a(u)),!0}case"CLOSE":{let{time:c,domain:u}=n;return u&&(O(u,c),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:c}=n;return c?o.set("walletAddress",c).then(()=>a(c)):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: ${d}`),!0;case"OPEN_CASHBACK_PAGE":let{url:m}=n;return V(m||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(n,s,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let d=y(a.url),m=await o.get("optOut");if(m&&m>Date.now())return;m&&(o.remove("optOut"),o.remove("optOutKey"));let c=N[n];if(s.status!=="complete"||d===c)return;N[n]=d;let u=await Kt(a.url,t);if(!u||!u.length){await rt(t,n,r,d);return}let f=await P(n),{token:g,isValid:l,iframeUrl:T,networkUrl:v}=await J({apiKey:t,body:{domain:u,url:a.url,address:f}});if(!l){l===!1&&O(u);return}if(!I(v,await o.get("redirectsWhitelist")))return;let x=await w();A(n,{action:"INJECT",token:g,domain:d,iframeUrl:T,userId:x})}),chrome.tabs.onRemoved.addListener(n=>delete N[n])},it=jt;var st=()=>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})})}),ot=t=>new Promise((e,r)=>{let i=t?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:i},n=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}n?e({isTurnedOff:n.isOptedOut}):r("No response received")})});0&&(module.exports={bringInitBackground,bringInitContentScript,getTurnOff,setTurnOff});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Z=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()},D=Z;var M={name:"@bringweb3/chrome-extension-kit",version:"1.2.14",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 te=()=>M.version,y=te;var re=({query:e,theme:t,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:d})=>{let a=chrome.runtime.id,c=`bringweb3-iframe-${a}`,m=document.getElementById(c),A=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(m)return m;let u=D({query:{...e,extensionId:a,v:y(),themeMode:r,textMode:n,switchWallet:String(d)}}),p=t?`&${D({query:t,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=c,l.src=`${A}?${u}${p}`,l.setAttribute("sandbox","allow-popups allow-scripts allow-same-origin allow-top-navigation-by-user-activation"),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;",t?.popupShadow&&(l.style.boxShadow=t.popupShadow),document.documentElement.appendChild(l),l},L=re;var ne=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,n])=>{r in e.style&&(e.style[r]=n)})},R=ne;var ie=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")},W=ie;var f={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"},se=[f.ACTIVATE],oe=({event:e,iframeEl:t,promptLogin:r})=>{let{data:n}=e,{from:i,action:s,style:d,keyFrames:a,time:c,extensionId:m,url:A,domain:u}=n;if(i==="bringweb3"&&!(m!==chrome.runtime.id&&!se.includes(s)))switch(s){case f.OPEN:R(t,d);break;case f.CLOSE:t&&t.parentNode?.removeChild(t),c&&chrome.runtime.sendMessage({action:s,time:c,domain:u,from:"bringweb3"});break;case f.PROMPT_LOGIN:r();break;case f.ACTIVATE:chrome.runtime.sendMessage({action:s,from:"bringweb3",domain:u,extensionId:m,time:c});break;case f.OPT_OUT:chrome.runtime.sendMessage({action:s,time:c,from:"bringweb3"});break;case f.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:s,from:"bringweb3"});case f.ADD_KEYFRAMES:W(a);break;case f.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:s,from:"bringweb3"});break;default:break}},F=oe;var $=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})},ae=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:r,iframeEl:n})=>{if(t)t(()=>$({iframeEl:n,getWalletAddress:r}));else if(e)for(let i=0;i<e.length;i++){let s=e[i];s&&window.addEventListener(s,async()=>$({iframeEl:n,getWalletAddress:r}))}},K=ae;var ce=["www.","www1.","www2."],me=e=>{if(!e)return"";e=e.split("://").reverse()[0]||"";for(let t of ce)e.startsWith(t)&&(e=e.replace(t,""));return e},b=me;var C=null,G=!1,de=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:d,text:a,switchWallet:c=!1})=>{if(window.self===window.top){if(!e||!t||!r?.length&&typeof n!="function")throw new Error("Missing configuration");K({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:e,iframeEl:C}),window.addEventListener("message",m=>F({event:m,iframeEl:C,promptLogin:t})),chrome.runtime.onMessage.addListener((m,A,u)=>{if(m?.from!=="bringweb3")return;let{action:p}=m;switch(p){case"GET_WALLET_ADDRESS":return e().then(U=>u({status:"success",walletAddress:U})).catch(U=>u({status:"success",walletAddress:void 0})),!0;case"INJECT":if(m.domain!==b(location.href)||G)return u({status:"Domain already changed"}),!0;let{token:l,iframeUrl:P,userId:k}=m,N={token:l};return k&&(N.userId=k),C=L({query:N,iframeUrl:P,theme:d==="dark"?s:i,themeMode:d||"light",text:a,switchWallet:c,page:m.page}),G=!0,u({status:"success"}),!0;default:console.error(`Unknown action: ${p}`);break}})}},le=de;var j=e=>{chrome.tabs.create({url:e})};var w=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 ue=async(e,t)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${e}`]:t},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),fe=async e=>new Promise((t,r)=>{chrome.storage.local.get([`bring_${e}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t(n[`bring_${e}`])})}),pe=async e=>new Promise((t,r)=>{chrome.storage.local.remove([`bring_${e}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t()})}),o={set:ue,get:fe,remove:pe};import{v4 as ge}from"uuid";var we=async()=>{let e=await o.get("id");return e||(e=ge(),o.set("id",e)),e},g=we;var he=async e=>{let{path:t,method:r,apiKey:n,params:i}=e;if(!e||!t||!r||!i&&r==="POST"||!n)throw new Error("Missing endpoint or method");let s=w.getInstance().getApiEndpoint();if(s+=t,r==="GET"){let c=new URLSearchParams({...i,version:y(),opt_out:await o.get("optOut")||0,user_id:await g()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});s+=`?${c.toString()}`}else r==="POST"&&(i={...i,version:y(),optOut:await o.get("optOut")||0,userId:await g()||void 0,walletAddress:i?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(s,{method:r,headers:{"Content-Type":"application/json","x-api-key":n},body:r==="POST"?JSON.stringify(i):void 0})).json()},h=he;var Ee=async e=>await h({path:"/domains",apiKey:e,method:"GET"}),B=Ee;var Ae=async({apiKey:e,body:t})=>await h({path:"/check/popup",apiKey:e,method:"POST",params:t}),V=Ae;var I="updateCache";var q=30*60*1e3,ye=async(e,t)=>{t||(t=q);let r=await o.get("quietDomains");typeof r=="object"?r[e]=Date.now()+t:r={[e]:Date.now()+q},o.set("quietDomains",r)},O=ye;var be=async({apiKey:e,walletAddress:t,cashbackUrl:r,lastActivation:n})=>{let i={walletAddress:t};return n&&(i.lastActivation=n),r&&(i.cashbackUrl=r),await h({path:"/check/notification",apiKey:e,method:"POST",params:i})},H=be;var Oe=(e,t)=>new Promise((i,s)=>{let d=a=>{chrome.tabs.get(e,c=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(e,{...t,from:"bringweb3"},m=>{chrome.runtime.lastError?a<4?setTimeout(()=>d(a+1),1e3*Math.pow(2,a)):i(null):i(m||null)})})};d(0)}),E=Oe;var Te=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 E(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await o.set("walletAddress",t))}catch{}return t},T=Te;var ve=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 T(t):await o.get("walletAddress");if(!s)return n;let d=await o.get("lastActivation"),a=await H({apiKey:e,walletAddress:s,cashbackUrl:r,lastActivation:d});o.set("notificationCheck",a.nextCall);let c={showNotification:a.showNotification,token:a.token,iframeUrl:a.iframeUrl,expiration:a.expiration};return c.showNotification&&await o.set("notification",c),c},v=ve;var xe=e=>e?chrome.runtime.getURL(e):"",x=xe;var Pe=async(e,t,r,n,i)=>{t===chrome.runtime.id&&await o.set("lastActivation",Date.now()),e&&O(e,i||Date.now()+24*60*60*1e3),await v(r,void 0,x(n))},Q=Pe;var J=async e=>e<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+e),{isOptedOut:!0}),Y=async()=>{let e=await o.get("optOut");return{isOptedOut:!!(e&&e>Date.now())}};var z=async(e,t,r)=>{await E(e,{action:"INJECT",page:"notification",token:t.token,iframeUrl:t.iframeUrl,userId:await g(),domain:r})},De=async(e,t,r,n)=>{let i=await o.get("notification");if(i?.expiration<Date.now())await o.remove("notification");else if(i)return await z(t,i,n);let s=await v(e,t,x(r));if(s.showNotification)return await z(t,s,n)},X=De;var Ce=e=>{let t=Date.now();return(e-t)/1e3/60},_=async e=>{let t=await B(e);o.set("relevantDomains",t.relevantDomains);let{nextUpdateTimestamp:r}=t,n=Ce(r);return chrome.alarms.create(I,{delayInMinutes:n||60*24*2}),t.relevantDomains},Ie=async(e,t)=>{let r=await o.get("relevantDomains");if(r===void 0&&(r=await _(t)),!e||!r||!r.length)return"";let n=b(e);for(let i of r)if(n.startsWith(i)){let s=await o.get("quietDomains");return s&&s[i]&&Date.now()<s[i]?"":i}return""},S={},Se=async({identifier:e,apiEndpoint:t,cashbackPagePath:r})=>{if(!e||!t)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");w.getInstance().setApiEndpoint(t),await o.get("relevantDomains")||_(e),chrome.alarms.onAlarm.addListener(async n=>{let{name:i}=n;switch(i){case I:_(e);break;default:console.error("alarm with no use case:",i);break}}),chrome.runtime.onMessage.addListener((n,i,s)=>{if(n?.from!=="bringweb3")return;let{action:d}=n;switch(d){case"ACTIVATE":{let{domain:a,extensionId:c,time:m}=n;return Q(a,c,e,r,m).then(()=>s()),!0}case"GET_OPT_OUT":return Y().then(a=>s(a)),!0;case"OPT_OUT":{let{time:a}=n;return J(a).then(c=>s(c)),!0}case"CLOSE":{let{time:a,domain:c}=n;return c&&(O(c,a),s({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:a}=n;return a?o.set("walletAddress",a).then(()=>s(a)):o.remove("walletAddress").then(()=>s({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>s({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${d}`),!0;case"OPEN_CASHBACK_PAGE":return j(r||""),s({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(n,i,s)=>{if(!s?.url?.startsWith("http")||!s.url)return;let d=b(s.url),a=await o.get("optOut");if(a&&a>Date.now())return;a&&(o.remove("optOut"),o.remove("optOutKey"));let c=S[n];if(i.status!=="complete"||d===c)return;S[n]=d;let m=await Ie(s.url,e);if(!m||!m.length){await X(e,n,r,d);return}let A=await T(n),{token:u,isValid:p,iframeUrl:l}=await V({apiKey:e,body:{domain:m,url:s.url,address:A}});if(!p){p===!1&&O(m);return}let P=await g();E(n,{action:"INJECT",token:u,domain:d,iframeUrl:l,userId:P})}),chrome.tabs.onRemoved.addListener(n=>delete S[n])},_e=Se;var ke=()=>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})})}),Ne=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")})});export{_e as bringInitBackground,le as bringInitContentScript,ke as getTurnOff,Ne as setTurnOff};
|
|
1
|
+
var et=t=>{let e=new URLSearchParams,{query:r,prefix:i}=t;return Object.entries(r).forEach(([n,s])=>{s&&(i&&(n=`${i}_${n}`),n==="url"?e.append(n,encodeURIComponent(s)):e.append(n,s))}),e.toString()},_=et;var W={name:"@bringweb3/chrome-extension-kit",version:"1.3.0",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 nt=()=>W.version,b=nt;var it=({query:t,theme:e,themeMode:r,text:i,iframeUrl:n,page:s,switchWallet:a})=>{let d=chrome.runtime.id,m=`bringweb3-iframe-${d}`,c=document.getElementById(m),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:n;if(c)return c;let f=_({query:{...t,extensionId:d,v:b(),themeMode:r,textMode:i,switchWallet:String(a)}}),g=e?`&${_({query:e,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=m,l.src=`${u}?${f}${g}`,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},L=it;var st=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,i])=>{r in t.style&&(t.style[r]=i)})},R=st;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:i,rules:n})=>{r.insertRule(`@keyframes ${i} { ${n} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},F=ot;var h={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"},at=[h.ACTIVATE],ct=({event:t,iframeEl:e,promptLogin:r})=>{let{data:i}=t,{from:n,action:s,style:a,keyFrames:d,time:m,extensionId:c,url:u,domain:f,redirectUrl:g}=i;if(n==="bringweb3"&&!(c!==chrome.runtime.id&&!at.includes(s)))switch(s){case h.OPEN:R(e,a);break;case h.CLOSE:e&&e.parentNode?.removeChild(e),m&&chrome.runtime.sendMessage({action:s,time:m,domain:f,from:"bringweb3"});break;case h.PROMPT_LOGIN:r();break;case h.ACTIVATE:chrome.runtime.sendMessage({action:s,from:"bringweb3",domain:f,extensionId:c,time:m,redirectUrl:g});break;case h.OPT_OUT:chrome.runtime.sendMessage({action:s,time:m,from:"bringweb3"});break;case h.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:s,from:"bringweb3"});case h.ADD_KEYFRAMES:F(d);break;case h.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:s,url:u,from:"bringweb3"});break;default:break}},$=ct;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})},dt=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:i})=>{if(e)e(()=>G({iframeEl:i,getWalletAddress:r}));else if(t)for(let n=0;n<t.length;n++){let s=t[n];s&&window.addEventListener(s,async()=>G({iframeEl:i,getWalletAddress:r}))}},K=dt;var mt=["www.","www1.","www2."],lt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of mt)t.startsWith(e)&&(t=t.replace(e,""));return t},y=lt;var S=null,j=!1,ut=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:i,lightTheme:n,darkTheme:s,theme:a,text:d,switchWallet:m=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof i!="function")throw new Error("Missing configuration");K({walletAddressListeners:r,walletAddressUpdateCallback:i,getWalletAddress:t,iframeEl:S}),window.addEventListener("message",c=>$({event:c,iframeEl:S,promptLogin:e})),chrome.runtime.onMessage.addListener((c,u,f)=>{if(c?.from!=="bringweb3")return;let{action:g}=c;switch(g){case"GET_WALLET_ADDRESS":return t().then(M=>f({status:"success",walletAddress:M})).catch(M=>f({status:"success",walletAddress:void 0})),!0;case"INJECT":if(c.domain!==y(location.href)||j)return f({status:"Domain already changed"}),!0;let{token:l,iframeUrl:T,userId:v}=c,x={token:l};return v&&(x.userId=v),S=L({query:x,iframeUrl:T,theme:a==="dark"?s:n,themeMode:a||"light",text:d,switchWallet:m,page:c.page}),j=!0,f({status:"success"}),!0;default:console.error(`Unknown action: ${g}`);break}})}},ft=ut;var q=t=>{t&&chrome.tabs.create({url:t})};var p=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";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"}getWhitelistEndpoint(){if(!this.whitelistEndpoint)throw new Error("Whitelist endpoint not set. Call setWhitelistEndpoint first.");return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}};var pt=async(t,e)=>new Promise((r,i)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?i(chrome.runtime.lastError):r()})}),gt=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],i=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(i[`bring_${t}`])})}),ht=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),o={set:pt,get:gt,remove:ht};import{v4 as wt}from"uuid";var Et=async()=>{let t=await o.get("id");return t||(t=wt(),o.set("id",t)),t},w=Et;var At=async t=>{let{path:e,method:r,apiKey:i,params:n}=t;if(!t||!e||!r||!n&&r==="POST"||!i)throw new Error("Missing endpoint or method");let s=p.getInstance().getApiEndpoint();if(s+=e,r==="GET"){let m=new URLSearchParams({...n,version:b(),opt_out:await o.get("optOut")||0,user_id:await w()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});s+=`?${m.toString()}`}else r==="POST"&&(n={...n,version:b(),optOut:await o.get("optOut")||0,userId:await w()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(s,{method:r,headers:{"Content-Type":"application/json","x-api-key":i},body:r==="POST"?JSON.stringify(n):void 0})).json()},E=At;var bt=async t=>{let e=p.getInstance().getWhitelistEndpoint(),r={path:"/domains",apiKey:t,method:"GET"};return e&&(r.params={whitelist:encodeURIComponent(e)}),await E(r)},B=bt;var yt=async({apiKey:t,body:e})=>await E({path:"/check/popup",apiKey:t,method:"POST",params:e}),V=yt;var k="updateCache";var H=30*60*1e3,Ot=async(t,e)=>{e||(e=H);let r=await o.get("quietDomains");typeof r=="object"?r[t]=Date.now()+e:r={[t]:Date.now()+H},o.set("quietDomains",r)},O=Ot;var Tt=async({apiKey:t,walletAddress:e,cashbackUrl:r,lastActivation:i})=>{let n={walletAddress:e};return i&&(n.lastActivation=i),r&&(n.cashbackUrl=r),await E({path:"/check/notification",apiKey:t,method:"POST",params:n})},Q=Tt;var vt=(t,e)=>new Promise((n,s)=>{let a=d=>{chrome.tabs.get(t,m=>{if(chrome.runtime.lastError){n(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},c=>{chrome.runtime.lastError?d<4?setTimeout(()=>a(d+1),1e3*Math.pow(2,d)):n(null):n(c||null)})})};a(0)}),A=vt;var xt=async t=>{let e=await o.get("walletAddress");try{if(!t){let i=await chrome.tabs.query({active:!0,currentWindow:!0});if(!i||!i[0]||!i[0].id)return e;t=i[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},P=xt;var Pt=async(t,e,r)=>{let i={showNotification:!1,token:"",iframeUrl:""},n=await o.get("notificationCheck");if(n&&Date.now()<n)return i;let s=e?await P(e):await o.get("walletAddress");if(!s)return i;let a=await o.get("lastActivation"),d=await Q({apiKey:t,walletAddress:s,cashbackUrl:r,lastActivation:a});o.set("notificationCheck",d.nextCall);let m={showNotification:d.showNotification,token:d.token,iframeUrl:d.iframeUrl,expiration:d.expiration};return m.showNotification&&await o.set("notification",m),m},D=Pt;var Dt=t=>t?chrome.runtime.getURL(t):"",C=Dt;var Ct=(t,e)=>{try{let r=p.getInstance().getWhitelistEndpoint();if(!e.length)return!!r;let n=new URL(t).hostname.toLowerCase();return n=n.replace("www.",""),e.includes(n)?!0:e.some(s=>{if(s.startsWith("*.")){let a=s.slice(2);return n.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},I=Ct;var It=async(t,e,r,i,n,s,a)=>{if(e===chrome.runtime.id&&await o.set("lastActivation",Date.now()),t&&O(t,n||Date.now()+24*60*60*1e3),s&&a){let d=await o.get("redirectsWhitelist");(!d?.length||I(a,d))&&chrome.tabs.update(s,{url:a})}await D(r,void 0,C(i))},J=It;var Y=async t=>t<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+t),{isOptedOut:!0}),z=async()=>{let t=await o.get("optOut");return{isOptedOut:!!(t&&t>Date.now())}};var X=async(t,e,r)=>{await A(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await w(),domain:r})},_t=async(t,e,r,i)=>{let n=await o.get("notification");if(n?.expiration<Date.now())await o.remove("notification");else if(n)return await X(e,n,i);let s=await D(t,e,C(r));if(s.showNotification)return await X(e,s,i)},Z=_t;var tt=async()=>{try{let t=p.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 St=t=>{let e=Date.now();return(t-e)/1e3/60},N=async t=>{let e=await B(t);o.set("relevantDomains",e.relevantDomains);let r=await tt();r&&o.set("redirectsWhitelist",r);let{nextUpdateTimestamp:i}=e,n=St(i);return chrome.alarms.create(k,{delayInMinutes:n||60*24*2}),e.relevantDomains},kt=async(t,e)=>{let r=await o.get("relevantDomains");if(r===void 0&&(r=await N(e)),!t||!r||!r.length)return"";let i=y(t);for(let n of r)if(i.startsWith(n)){let s=await o.get("quietDomains");return s&&s[n]&&Date.now()<s[n]?"":n}return""},U={},Ut=async({identifier:t,apiEndpoint:e,cashbackPagePath:r,whitelistEndpoint:i})=>{if(!t||!e)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(e))throw new Error("unknown apiEndpoint");p.getInstance().setApiEndpoint(e),p.getInstance().setWhitelistEndpoint(i||""),await o.get("relevantDomains")||N(t),chrome.alarms.onAlarm.addListener(async n=>{let{name:s}=n;switch(s){case k:N(t);break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener((n,s,a)=>{if(n?.from!=="bringweb3")return;let{action:d}=n;switch(d){case"ACTIVATE":{let{domain:c,extensionId:u,time:f,redirectUrl:g}=n;return J(c,u,t,r,f,s.tab?.id,g).then(()=>a()),!0}case"GET_OPT_OUT":return z().then(c=>a(c)),!0;case"OPT_OUT":{let{time:c}=n;return Y(c).then(u=>a(u)),!0}case"CLOSE":{let{time:c,domain:u}=n;return u&&(O(u,c),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:c}=n;return c?o.set("walletAddress",c).then(()=>a(c)):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: ${d}`),!0;case"OPEN_CASHBACK_PAGE":let{url:m}=n;return q(m||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(n,s,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let d=y(a.url),m=await o.get("optOut");if(m&&m>Date.now())return;m&&(o.remove("optOut"),o.remove("optOutKey"));let c=U[n];if(s.status!=="complete"||d===c)return;U[n]=d;let u=await kt(a.url,t);if(!u||!u.length){await Z(t,n,r,d);return}let f=await P(n),{token:g,isValid:l,iframeUrl:T,networkUrl:v}=await V({apiKey:t,body:{domain:u,url:a.url,address:f}});if(!l){l===!1&&O(u);return}if(!I(v,await o.get("redirectsWhitelist")))return;let x=await w();A(n,{action:"INJECT",token:g,domain:d,iframeUrl:T,userId:x})}),chrome.tabs.onRemoved.addListener(n=>delete U[n])},Nt=Ut;var Mt=()=>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})})}),Wt=t=>new Promise((e,r)=>{let i=t?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:i},n=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}n?e({isTurnedOff:n.isOptedOut}):r("No response received")})});export{Nt as bringInitBackground,ft as bringInitContentScript,Mt as getTurnOff,Wt as setTurnOff};
|