@bringweb3/chrome-extension-kit 1.3.7 → 1.3.9
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.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var k=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var dt=Object.prototype.hasOwnProperty;var ut=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},ft=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lt(e))!dt.call(t,n)&&n!==r&&k(t,n,{get:()=>e[n],enumerable:!(i=mt(e,n))||i.enumerable});return t};var pt=t=>ft(k({},"__esModule",{value:!0}),t);var Yt={};ut(Yt,{bringInitBackground:()=>st,bringInitContentScript:()=>V,getTurnOff:()=>at,setTurnOff:()=>ct});module.exports=pt(Yt);var gt=t=>{let e=new URLSearchParams,{query:r,prefix:i}=t;return Object.entries(r).forEach(([n,o])=>{o&&(i&&(n=`${i}_${n}`),n==="url"?e.append(n,encodeURIComponent(o)):e.append(n,o))}),e.toString()},U=gt;var W={name:"@bringweb3/chrome-extension-kit",version:"1.3.7",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 wt=()=>W.version,b=wt;var Et=({query:t,theme:e,themeMode:r,text:i,iframeUrl:n,page:o,switchWallet:a})=>{let c=chrome.runtime.id,l=`bringweb3-iframe-${c}`,m=document.getElementById(l),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${o?"/"+o:""}`:n;if(m)return m;let p=U({query:{...t,extensionId:c,v:b(),themeMode:r,textMode:i,switchWallet:String(a)}}),h=e?`&${U({query:e,prefix:"t"})}`:"",d=document.createElement("iframe");return d.id=l,d.src=`${u}?${p}${h}`,d.setAttribute("sandbox","allow-scripts allow-same-origin"),d.style.position="fixed",d.scrolling="no",d.style.overflow="hidden",d.style.width="1px",d.style.height="1px",d.style.right="8px",d.style.borderRadius="10px",d.style.border="none",d.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(d.style.boxShadow=e.popupShadow),document.documentElement.appendChild(d),d},K=Et;var At=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,i])=>{r in t.style&&(t.style[r]=i)})},F=At;var yt=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")},$=yt;var g={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},bt=[g.ACTIVATE],Ot=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:i,action:n,style:o,keyFrames:a,time:c,extensionId:l,url:m,domain:u,redirectUrl:p}=t.data;if(i==="bringweb3"&&!(l!==chrome.runtime.id&&!bt.includes(n)))switch(n){case g.OPEN:F(e,o);break;case g.CLOSE:e&&e.parentNode?.removeChild(e),c&&chrome.runtime.sendMessage({action:n,time:c,domain:u,from:"bringweb3"});break;case g.PROMPT_LOGIN:r();break;case g.ACTIVATE:chrome.runtime.sendMessage({action:n,from:"bringweb3",domain:u,extensionId:l,time:c,redirectUrl:p});break;case g.OPT_OUT:chrome.runtime.sendMessage({action:n,time:c,from:"bringweb3"});break;case g.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:n,from:"bringweb3"});case g.ADD_KEYFRAMES:$(a);break;case g.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:n,url:m,from:"bringweb3"});break;default:break}},j=Ot;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})},Tt=({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 o=t[n];o&&window.addEventListener(o,async()=>G({iframeEl:i,getWalletAddress:r}))}},q=Tt;var vt=t=>t.endsWith("/")?t.slice(0,-1):t,O=vt;var xt=["www.","www1.","www2."],Pt=t=>{for(let r of xt)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=O(e),e},M=Pt;var N=null,B=!1,Dt=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:i,lightTheme:n,darkTheme:o,theme:a,text:c,switchWallet:l=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof i!="function")throw new Error("Missing configuration");q({walletAddressListeners:r,walletAddressUpdateCallback:i,getWalletAddress:t,iframeEl:N}),window.addEventListener("message",m=>j({event:m,iframeEl:N,promptLogin:e})),chrome.runtime.onMessage.addListener((m,u,p)=>{if(m?.from!=="bringweb3")return;let{action:h}=m;switch(h){case"GET_WALLET_ADDRESS":return t().then(R=>p({status:"success",walletAddress:R})).catch(R=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":if(M(location.href)!==M(m.domain))return p({status:"Domain already changed"}),!0;if(B)return p({status:"iframe already open"}),!0;let{token:d,iframeUrl:v,userId:x}=m,P={token:d};return x&&(P.userId=x),N=K({query:P,iframeUrl:v,theme:a==="dark"?o:n,themeMode:a||"light",text:c,switchWallet:l,page:m.page}),B=!0,p({status:"success"}),!0;default:console.error(`Unknown action: ${h}`);break}})}},V=Dt;var H=t=>{t&&chrome.tabs.create({url:t})};var f=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}setWhitelistEndpoint(e){this.whitelistEndpoint=e}setApiEndpoint(e){this.apiEndpoint=e==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(e){this.apiKey=e}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var Ct=async(t,e)=>new Promise((r,i)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?i(chrome.runtime.lastError):r()})}),It=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],i=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(i[`bring_${t}`])})}),St=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),s={set:Ct,get:It,remove:St};var Q=require("uuid"),_t=async()=>{let t=await s.get("id");return t||(t=(0,Q.v4)(),s.set("id",t)),t},w=_t;var kt=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 o=f.getInstance().getApiEndpoint();if(o+=e,r==="GET"){let l=new URLSearchParams({...n,version:b(),timestamp:Date.now().toString(),opt_out:await s.get("optOut")||0,user_id:await w()||"undefined",wallet_address:await s.get("walletAddress")||"undefined"});o+=`?${l.toString()}`}else r==="POST"&&(n={...n,version:b(),timestamp:Date.now(),optOut:await s.get("optOut")||0,userId:await w()||void 0,walletAddress:n?.walletAddress||await s.get("walletAddress")||void 0});return await(await fetch(o,{method:r,headers:{"Content-Type":"application/json","x-api-key":i},body:r==="POST"?JSON.stringify(n):void 0})).json()},E=kt;var Ut=async({apiKey:t,body:e})=>await E({path:"/check/popup",apiKey:t,method:"POST",params:e}),J=Ut;var Mt=["www.","www1.","www2."],Nt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of Mt)t.startsWith(e)&&(t=t.replace(e,""));return t},Y=Nt;var D="updateCache";var z=30*60*1e3,Lt=async(t,e)=>{e||(e=z);let r=await s.get("quietDomains");typeof r=="object"?r[t]=Date.now()+e:r={[t]:Date.now()+z},s.set("quietDomains",r)},T=Lt;var Rt=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})},X=Rt;var Wt=(t,e)=>new Promise((n,o)=>{let a=c=>{chrome.tabs.get(t,l=>{if(chrome.runtime.lastError){n(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},m=>{chrome.runtime.lastError?c<4?setTimeout(()=>a(c+1),1e3*Math.pow(2,c)):n(null):n(m||null)})})};a(0)}),A=Wt;var Kt=async t=>{let e=await s.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 s.set("walletAddress",e))}catch{}return e},C=Kt;var Ft=async(t,e,r)=>{let i={showNotification:!1,token:"",iframeUrl:""},n=await s.get("notificationCheck");if(n&&Date.now()<n)return i;let o=e?await C(e):await s.get("walletAddress");if(!o)return i;let a=await s.get("lastActivation"),c=await X({apiKey:t,walletAddress:o,cashbackUrl:r,lastActivation:a});s.set("notificationCheck",c.nextCall);let l={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:c.expiration};return l.showNotification&&await s.set("notification",l),l},I=Ft;var $t=t=>t?chrome.runtime.getURL(t):"",S=$t;var jt=async t=>{let e=f.getInstance().getWhitelistEndpoint(),r={path:"/domains",apiKey:t,method:"GET"};return e&&(r.params={whitelist:encodeURIComponent(e)}),await E(r)},Z=jt;var tt=async()=>{try{let t=f.getInstance().getWhitelistEndpoint();if(!t)return[];let e=await fetch(t,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!e.ok)throw new Error("Failed to fetch whitelist");let r=await e.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(t){return console.error("Error fetching whitelist:",t),[]}};var Gt=t=>{let e=Date.now();return(t-e)/1e3/60},y=async()=>{let t=await s.get("relevantDomainsCheck"),e=await s.get("relevantDomains"),r=await s.get("redirectsWhitelist"),i=f.getInstance().getApiKey(),n=f.getInstance().getWhitelistEndpoint();if(e?.length&&t&&t>Date.now()&&(!n||n&&r?.length))return e;let o=await Z(i),{nextUpdateTimestamp:a,relevantDomains:c}=o;s.set("relevantDomains",c),s.set("relevantDomainsCheck",a),r=await tt(),r&&s.set("redirectsWhitelist",r);let l=Gt(a);return chrome.alarms.create(D,{delayInMinutes:l||60*24*2}),c};var qt=async(t,e)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await y(),e=await s.get("redirectsWhitelist")),!e?.length)return!r;let n=new URL(t).hostname.toLowerCase();return n=n.replace("www.",""),e.includes(n)?!0:e.some(o=>{if(o.startsWith("*.")){let a=o.slice(2);return n.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},_=qt;var Bt=async(t,e,r,i,n,o,a)=>{if(e===chrome.runtime.id&&await s.set("lastActivation",Date.now()),t&&T(t,n||Date.now()+24*60*60*1e3),o&&a){let c=await s.get("redirectsWhitelist");await _(a,c)&&chrome.tabs.update(o,{url:a})}await I(r,void 0,S(i))},et=Bt;var rt=async t=>t<0?(await s.remove("optOut"),{isOptedOut:!1}):(await s.set("optOut",Date.now()+t),{isOptedOut:!0}),nt=async()=>{let t=await s.get("optOut");return{isOptedOut:!!(t&&t>Date.now())}};var it=async(t,e,r)=>{await A(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await w(),domain:r})},Vt=async(t,e,r,i)=>{let n=await s.get("notification");if(n?.expiration<Date.now())await s.remove("notification");else if(n)return await it(e,n,i);let o=await I(t,e,S(r));if(o.showNotification)return await it(e,o,i)},ot=Vt;var Ht=["www.","www1.","www2."],Qt=async t=>{let e=await y();if(!t||!e||!e.length)return"";let r=null;try{r=new URL(t)}catch{r=new URL(`https://${t}`)}let i=r.hostname,n=O(r.pathname);for(let o of Ht)i=i.replace(o,"");for(let o of e){let a=o;o=O(o);let c=!1;o.startsWith("*.")&&(c=!0);let l="/"+o.split("/").slice(1).join("/")||"";if(l!=="/"&&n.startsWith(l)&&(i+=l),i===o||c&&i.endsWith(o.replace("*.",""))){let m=await s.get("quietDomains");return m&&m[o]&&Date.now()<m[o]?"":a}}return""},L={},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");f.getInstance().setApiEndpoint(e),f.getInstance().setWhitelistEndpoint(i||""),f.getInstance().setApiKey(t),y(),chrome.alarms.onAlarm.addListener(async n=>{let{name:o}=n;switch(o){case D:y();break;default:console.error("alarm with no use case:",o);break}}),chrome.runtime.onMessage.addListener((n,o,a)=>{if(n?.from!=="bringweb3")return;let{action:c}=n;switch(c){case"ACTIVATE":{let{domain:m,extensionId:u,time:p,redirectUrl:h}=n;return et(m,u,t,r,p,o.tab?.id,h).then(()=>a()),!0}case"GET_OPT_OUT":return nt().then(m=>a(m)),!0;case"OPT_OUT":{let{time:m}=n;return rt(m).then(u=>a(u)),!0}case"CLOSE":{let{time:m,domain:u}=n;return u&&(T(u,m),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:m}=n;return m?s.set("walletAddress",m).then(()=>a(m)):s.remove("walletAddress").then(()=>a({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return s.remove("notification").then(()=>a({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${c}`),!0;case"OPEN_CASHBACK_PAGE":let{url:l}=n;return H(l||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(n,o,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let c=Y(a.url),l=await s.get("optOut");if(l&&l>Date.now())return;l&&(s.remove("optOut"),s.remove("optOutKey"));let m=L[n];if(o.status!=="complete"||c===m)return;L[n]=c;let u=await Qt(a.url);if(!u||!u.length){await ot(t,n,r,c);return}let p=await C(n),{token:h,isValid:d,iframeUrl:v,networkUrl:x}=await J({apiKey:t,body:{domain:u,url:a.url,address:p}});if(!d){d===!1&&T(u);return}if(!await _(x,await s.get("redirectsWhitelist")))return;let P=await w();A(n,{action:"INJECT",token:h,domain:c,iframeUrl:v,userId:P})}),chrome.tabs.onRemoved.addListener(n=>delete L[n])},st=Jt;var at=()=>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})})}),ct=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});
|
|
1
|
+
"use strict";var U=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.prototype.hasOwnProperty;var pt=(t,e)=>{for(var r in e)U(t,r,{get:e[r],enumerable:!0})},gt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ut(e))!ft.call(t,i)&&i!==r&&U(t,i,{get:()=>e[i],enumerable:!(n=dt(e,i))||n.enumerable});return t};var ht=t=>gt(U({},"__esModule",{value:!0}),t);var Zt={};pt(Zt,{bringInitBackground:()=>at,bringInitContentScript:()=>H,getTurnOff:()=>ct,setTurnOff:()=>mt});module.exports=ht(Zt);var wt=t=>{let e=new URLSearchParams,{query:r,prefix:n}=t;return Object.entries(r).forEach(([i,s])=>{s&&(n&&(i=`${n}_${i}`),i==="url"?e.append(i,encodeURIComponent(s)):e.append(i,s))}),e.toString()},N=wt;var F={name:"@bringweb3/chrome-extension-kit",version:"1.3.9",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var At=()=>F.version,O=At;var yt=({query:t,theme:e,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:a})=>{let c=chrome.runtime.id,d=`bringweb3-iframe-${c}`,m=document.getElementById(d),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(m)return m;let p=N({query:{...t,extensionId:c,v:O(),themeMode:r,textMode:n,switchWallet:String(a)}}),h=e?`&${N({query:e,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=d,l.src=`${u}?${p}${h}`,l.setAttribute("sandbox","allow-scripts allow-same-origin"),l.style.position="fixed",l.scrolling="no",l.style.overflow="hidden",l.style.width="1px",l.style.height="1px",l.style.right="8px",l.style.borderRadius="10px",l.style.border="none",l.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(l.style.boxShadow=e.popupShadow),document.documentElement.appendChild(l),l},K=yt;var bt=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,n])=>{r in t.style&&(t.style[r]=n)})},$=bt;var Ot=t=>{if(!t||!t.length)return;let e=document.createElement("style");document.head.appendChild(e);let r=e.sheet;r?t.forEach(({name:n,rules:i})=>{r.insertRule(`@keyframes ${n} { ${i} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},j=Ot;var g={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},Tt=[g.ACTIVATE],vt=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:n,action:i,style:s,keyFrames:a,time:c,extensionId:d,url:m,domain:u,redirectUrl:p}=t.data;if(n==="bringweb3"&&!(d!==chrome.runtime.id&&!Tt.includes(i)))switch(i){case g.OPEN:$(e,s);break;case g.CLOSE:e&&e.parentNode?.removeChild(e),c&&chrome.runtime.sendMessage({action:i,time:c,domain:u,from:"bringweb3"});break;case g.PROMPT_LOGIN:r();break;case g.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3",domain:u,extensionId:d,time:c,redirectUrl:p});break;case g.OPT_OUT:chrome.runtime.sendMessage({action:i,time:c,from:"bringweb3"});break;case g.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:i,from:"bringweb3"});case g.ADD_KEYFRAMES:j(a);break;case g.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:i,url:m,from:"bringweb3"});break;default:break}},G=vt;var q=async({iframeEl:t,getWalletAddress:e})=>{if(!t&&(t=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!t)||!t.contentWindow)return;let r=await e();t.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},xt=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:n})=>{if(e)e(()=>q({iframeEl:n,getWalletAddress:r}));else if(t)for(let i=0;i<t.length;i++){let s=t[i];s&&window.addEventListener(s,async()=>q({iframeEl:n,getWalletAddress:r}))}},B=xt;var Pt=t=>t.endsWith("/")?t.slice(0,-1):t,T=Pt;var Dt=["www.","www1.","www2."],It=t=>{for(let r of Dt)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=T(e),e},M=It;var L=null,V=!1,Ct=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:a,text:c,switchWallet:d=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof n!="function")throw new Error("Missing configuration");B({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:t,iframeEl:L}),window.addEventListener("message",m=>G({event:m,iframeEl:L,promptLogin:e})),chrome.runtime.onMessage.addListener((m,u,p)=>{if(m?.from!=="bringweb3")return;let{action:h}=m;switch(h){case"GET_WALLET_ADDRESS":return t().then(l=>p({status:"success",walletAddress:l})).catch(l=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{if(M(location.href)!==M(m.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(V)return p({status:"failed",message:"iframe already open"}),!0;let{token:l,iframeUrl:b,userId:x}=m,P={token:l};return x&&(P.userId=x),L=K({query:P,iframeUrl:b,theme:a==="dark"?s:i,themeMode:a||"light",text:c,switchWallet:d,page:m.page}),V=!0,p({status:"success"}),!0}catch(l){return l instanceof Error?p({status:"failed",message:l.message}):p({status:"failed",message:String(l)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},H=Ct;var Q=t=>{t&&chrome.tabs.create({url:t})};var f=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}setWhitelistEndpoint(e){this.whitelistEndpoint=e}setApiEndpoint(e){this.apiEndpoint=e==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(e){this.apiKey=e}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var St=async(t,e)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),kt=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(n[`bring_${t}`])})}),_t=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),o={set:St,get:kt,remove:_t};var J=require("uuid"),Ut=async()=>{let t=await o.get("id");return t||(t=(0,J.v4)(),o.set("id",t)),t},E=Ut;var Nt=async t=>{let{path:e,method:r,params:n}=t;if(!t||!e||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let i=f.getInstance().getApiEndpoint();i+=e;let s=f.getInstance().getApiKey();if(r==="GET"){let d=new URLSearchParams({...n,version:O(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await E()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});i+=`?${d.toString()}`}else r==="POST"&&(n={...n,version:O(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await E()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(i,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},w=Nt;var Mt=async({body:t})=>await w({path:"/check/popup",method:"POST",params:t}),Y=Mt;var Lt=["www.","www1.","www2."],Rt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of Lt)t.startsWith(e)&&(t=t.replace(e,""));return t},z=Rt;var D="updateCache";var Wt=async(t,e)=>{let r=await o.get("quietDomains");typeof r=="object"?r[t]=e:r={[t]:e},o.set("quietDomains",r)},v=Wt;var Ft=async({walletAddress:t,cashbackUrl:e,lastActivation:r})=>{let n={walletAddress:t};return r&&(n.lastActivation=r),e&&(n.cashbackUrl=e),await w({path:"/check/notification",method:"POST",params:n})},X=Ft;var Kt=(t,e)=>new Promise((i,s)=>{let a=c=>{chrome.tabs.get(t,d=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},m=>{chrome.runtime.lastError?c<4?setTimeout(()=>a(c+1),1e3*Math.pow(2,c)):i(null):i(m||null)})})};a(0)}),A=Kt;var $t=async t=>{let e=await o.get("walletAddress");try{if(!t){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return e;t=n[0].id}let r=await A(t,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&e!==r?.walletAddress&&(e=r?.walletAddress,await o.set("walletAddress",e))}catch{}return e},I=$t;var jt=async(t,e,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},i=await o.get("notificationCheck");if(i&&Date.now()<i)return n;let s=e?await I(e):await o.get("walletAddress");if(!s)return n;let a=await o.get("lastActivation"),c=await X({walletAddress:s,cashbackUrl:r,lastActivation:a});o.set("notificationCheck",c.nextCall);let d={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:c.expiration};return d.showNotification&&await o.set("notification",d),d},C=jt;var Gt=t=>t?chrome.runtime.getURL(t):"",S=Gt;var qt=async()=>{let t=f.getInstance().getWhitelistEndpoint(),e={path:"/domains",method:"GET"};return t&&(e.params={whitelist:encodeURIComponent(t)}),await w(e)},Z=qt;var tt=async()=>{try{let t=f.getInstance().getWhitelistEndpoint();if(!t)return[];let e=await fetch(t,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!e.ok)throw new Error("Failed to fetch whitelist");let r=await e.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(t){return console.error("Error fetching whitelist:",t),[]}};var Bt=t=>{let e=Date.now();return(t-e)/1e3/60},y=async()=>{let t=await o.get("relevantDomainsCheck"),e=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),i=f.getInstance().getWhitelistEndpoint();if(e?.length&&t&&t>Date.now()&&(!i||i&&r?.length))return e;let s=await Z(),{nextUpdateTimestamp:a,relevantDomains:c}=s;o.set("relevantDomains",c),o.set("relevantDomainsCheck",a),r=await tt(),r&&o.set("redirectsWhitelist",r);let d=Bt(a);return chrome.alarms.create(D,{delayInMinutes:d||60*24*2}),c};var Vt=async(t,e)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await y(),e=await o.get("redirectsWhitelist")),!e?.length)return!r;let i=new URL(t).hostname.toLowerCase();return i=i.replace("www.",""),e.includes(i)?!0:e.some(s=>{if(s.startsWith("*.")){let a=s.slice(2);return i.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},k=Vt;var Ht=async(t,e,r,n,i,s,a)=>{if(e===chrome.runtime.id&&await o.set("lastActivation",Date.now()),t&&v(t,i||Date.now()+24*60*60*1e3),s&&a){let c=await o.get("redirectsWhitelist");await k(a,c)&&chrome.tabs.update(s,{url:a})}await C(r,void 0,S(n))},et=Ht;var rt=async t=>t<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+t),{isOptedOut:!0}),it=async()=>{let t=await o.get("optOut");return{isOptedOut:!!(t&&t>Date.now())}};var nt=async(t,e,r)=>{await A(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await E(),domain:r})},Qt=async(t,e,r,n)=>{let i=await o.get("notification");if(i?.expiration<Date.now())await o.remove("notification");else if(i)return await nt(e,i,n);let s=await C(t,e,S(r));if(s.showNotification)return await nt(e,s,n)},st=Qt;var Jt=async t=>{t.category=t?.category||"system",await w({path:"/analytics",method:"POST",params:t})},ot=Jt;var Yt=["www.","www1.","www2."],zt=async t=>{let e=await y();if(!t||!e||!e.length)return"";let r=null;try{r=new URL(t)}catch{r=new URL(`https://${t}`)}let n=r.hostname,i=T(r.pathname);for(let s of Yt)n=n.replace(s,"");for(let s of e){let a=s;s=T(s);let c=!1;s.startsWith("*.")&&(c=!0);let d="/"+s.split("/").slice(1).join("/")||"";if(d!=="/"&&i.startsWith(d)&&(n+=d),n===s||c&&n.endsWith(s.replace("*.",""))){let m=await o.get("quietDomains");return m&&m[s]&&Date.now()<m[s]&&m[s]<Date.now()+60*24*60*60*1e3?"":a}}return""},R={},Xt=async({identifier:t="94cnbcoEYv5A6z1yxSizi8RAa7kq71nq6miZeSNh",apiEndpoint:e="sandbox",cashbackPagePath:r,whitelistEndpoint:n})=>{if(!t||!e)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(e))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(e),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(t),y(),chrome.alarms.onAlarm.addListener(async i=>{let{name:s}=i;switch(s){case D:y();break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener((i,s,a)=>{if(i?.from!=="bringweb3")return;let{action:c}=i;switch(c){case"ACTIVATE":{let{domain:m,extensionId:u,time:p,redirectUrl:h}=i;return et(m,u,t,r,p,s.tab?.id,h).then(()=>a()),!0}case"GET_OPT_OUT":return it().then(m=>a(m)),!0;case"OPT_OUT":{let{time:m}=i;return rt(m).then(u=>a(u)),!0}case"CLOSE":{let{time:m,domain:u}=i;return u&&(v(u,m),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:m}=i;return m?o.set("walletAddress",m).then(()=>a(m)):o.remove("walletAddress").then(()=>a({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>a({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${c}`),!0;case"OPEN_CASHBACK_PAGE":let{url:d}=i;return Q(d||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(i,s,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let c=z(a.url),d=await o.get("optOut");if(d&&d>Date.now())return;d&&(o.remove("optOut"),o.remove("optOutKey"));let m=R[i];if(s.status!=="complete"||c===m)return;R[i]=c;let u=await zt(a.url);if(!u||!u.length){await st(t,i,r,c);return}let p=await I(i),{token:h,isValid:l,iframeUrl:b,networkUrl:x,flowId:P,time:lt=Date.now()+2*60*60*1e3}=await Y({body:{domain:u,url:a.url,address:p}});if(!l){l===!1&&v(u,lt);return}if(!await k(x,await o.get("redirectsWhitelist")))return;let W=await E(),_=await A(i,{action:"INJECT",token:h,domain:c,iframeUrl:b,userId:W});_?.status!=="success"&&ot({type:"no_popup",userId:W,walletAddress:p,details:{url:a.url,match:u,iframeUrl:b,reason:_?.message,status:_?.status},flowId:P})}),chrome.tabs.onRemoved.addListener(i=>delete R[i])},at=Xt;var ct=()=>new Promise((t,e)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_OPT_OUT"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),e(chrome.runtime.lastError);return}t({isTurnedOff:r.isOptedOut})})}),mt=t=>new Promise((e,r)=>{let n=t?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?e({isTurnedOff:i.isOptedOut}):r("No response received")})});0&&(module.exports={bringInitBackground,bringInitContentScript,getTurnOff,setTurnOff});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var nt=t=>{let e=new URLSearchParams,{query:r,prefix:i}=t;return Object.entries(r).forEach(([n,o])=>{o&&(i&&(n=`${i}_${n}`),n==="url"?e.append(n,encodeURIComponent(o)):e.append(n,o))}),e.toString()},k=nt;var R={name:"@bringweb3/chrome-extension-kit",version:"1.3.7",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 ot=()=>R.version,b=ot;var st=({query:t,theme:e,themeMode:r,text:i,iframeUrl:n,page:o,switchWallet:a})=>{let c=chrome.runtime.id,l=`bringweb3-iframe-${c}`,m=document.getElementById(l),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${o?"/"+o:""}`:n;if(m)return m;let p=k({query:{...t,extensionId:c,v:b(),themeMode:r,textMode:i,switchWallet:String(a)}}),h=e?`&${k({query:e,prefix:"t"})}`:"",d=document.createElement("iframe");return d.id=l,d.src=`${u}?${p}${h}`,d.setAttribute("sandbox","allow-scripts allow-same-origin"),d.style.position="fixed",d.scrolling="no",d.style.overflow="hidden",d.style.width="1px",d.style.height="1px",d.style.right="8px",d.style.borderRadius="10px",d.style.border="none",d.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(d.style.boxShadow=e.popupShadow),document.documentElement.appendChild(d),d},W=st;var at=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,i])=>{r in t.style&&(t.style[r]=i)})},K=at;var ct=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=ct;var g={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},mt=[g.ACTIVATE],lt=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:i,action:n,style:o,keyFrames:a,time:c,extensionId:l,url:m,domain:u,redirectUrl:p}=t.data;if(i==="bringweb3"&&!(l!==chrome.runtime.id&&!mt.includes(n)))switch(n){case g.OPEN:K(e,o);break;case g.CLOSE:e&&e.parentNode?.removeChild(e),c&&chrome.runtime.sendMessage({action:n,time:c,domain:u,from:"bringweb3"});break;case g.PROMPT_LOGIN:r();break;case g.ACTIVATE:chrome.runtime.sendMessage({action:n,from:"bringweb3",domain:u,extensionId:l,time:c,redirectUrl:p});break;case g.OPT_OUT:chrome.runtime.sendMessage({action:n,time:c,from:"bringweb3"});break;case g.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:n,from:"bringweb3"});case g.ADD_KEYFRAMES:F(a);break;case g.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:n,url:m,from:"bringweb3"});break;default:break}},$=lt;var j=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(()=>j({iframeEl:i,getWalletAddress:r}));else if(t)for(let n=0;n<t.length;n++){let o=t[n];o&&window.addEventListener(o,async()=>j({iframeEl:i,getWalletAddress:r}))}},G=dt;var ut=t=>t.endsWith("/")?t.slice(0,-1):t,O=ut;var ft=["www.","www1.","www2."],pt=t=>{for(let r of ft)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=O(e),e},U=pt;var M=null,q=!1,gt=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:i,lightTheme:n,darkTheme:o,theme:a,text:c,switchWallet:l=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof i!="function")throw new Error("Missing configuration");G({walletAddressListeners:r,walletAddressUpdateCallback:i,getWalletAddress:t,iframeEl:M}),window.addEventListener("message",m=>$({event:m,iframeEl:M,promptLogin:e})),chrome.runtime.onMessage.addListener((m,u,p)=>{if(m?.from!=="bringweb3")return;let{action:h}=m;switch(h){case"GET_WALLET_ADDRESS":return t().then(L=>p({status:"success",walletAddress:L})).catch(L=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":if(U(location.href)!==U(m.domain))return p({status:"Domain already changed"}),!0;if(q)return p({status:"iframe already open"}),!0;let{token:d,iframeUrl:v,userId:x}=m,P={token:d};return x&&(P.userId=x),M=W({query:P,iframeUrl:v,theme:a==="dark"?o:n,themeMode:a||"light",text:c,switchWallet:l,page:m.page}),q=!0,p({status:"success"}),!0;default:console.error(`Unknown action: ${h}`);break}})}},ht=gt;var B=t=>{t&&chrome.tabs.create({url:t})};var f=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}setWhitelistEndpoint(e){this.whitelistEndpoint=e}setApiEndpoint(e){this.apiEndpoint=e==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(e){this.apiKey=e}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var wt=async(t,e)=>new Promise((r,i)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?i(chrome.runtime.lastError):r()})}),Et=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],i=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(i[`bring_${t}`])})}),At=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),s={set:wt,get:Et,remove:At};import{v4 as yt}from"uuid";var bt=async()=>{let t=await s.get("id");return t||(t=yt(),s.set("id",t)),t},w=bt;var Ot=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 o=f.getInstance().getApiEndpoint();if(o+=e,r==="GET"){let l=new URLSearchParams({...n,version:b(),timestamp:Date.now().toString(),opt_out:await s.get("optOut")||0,user_id:await w()||"undefined",wallet_address:await s.get("walletAddress")||"undefined"});o+=`?${l.toString()}`}else r==="POST"&&(n={...n,version:b(),timestamp:Date.now(),optOut:await s.get("optOut")||0,userId:await w()||void 0,walletAddress:n?.walletAddress||await s.get("walletAddress")||void 0});return await(await fetch(o,{method:r,headers:{"Content-Type":"application/json","x-api-key":i},body:r==="POST"?JSON.stringify(n):void 0})).json()},E=Ot;var Tt=async({apiKey:t,body:e})=>await E({path:"/check/popup",apiKey:t,method:"POST",params:e}),V=Tt;var vt=["www.","www1.","www2."],xt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of vt)t.startsWith(e)&&(t=t.replace(e,""));return t},H=xt;var D="updateCache";var Q=30*60*1e3,Pt=async(t,e)=>{e||(e=Q);let r=await s.get("quietDomains");typeof r=="object"?r[t]=Date.now()+e:r={[t]:Date.now()+Q},s.set("quietDomains",r)},T=Pt;var Dt=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})},J=Dt;var Ct=(t,e)=>new Promise((n,o)=>{let a=c=>{chrome.tabs.get(t,l=>{if(chrome.runtime.lastError){n(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},m=>{chrome.runtime.lastError?c<4?setTimeout(()=>a(c+1),1e3*Math.pow(2,c)):n(null):n(m||null)})})};a(0)}),A=Ct;var It=async t=>{let e=await s.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 s.set("walletAddress",e))}catch{}return e},C=It;var St=async(t,e,r)=>{let i={showNotification:!1,token:"",iframeUrl:""},n=await s.get("notificationCheck");if(n&&Date.now()<n)return i;let o=e?await C(e):await s.get("walletAddress");if(!o)return i;let a=await s.get("lastActivation"),c=await J({apiKey:t,walletAddress:o,cashbackUrl:r,lastActivation:a});s.set("notificationCheck",c.nextCall);let l={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:c.expiration};return l.showNotification&&await s.set("notification",l),l},I=St;var _t=t=>t?chrome.runtime.getURL(t):"",S=_t;var kt=async t=>{let e=f.getInstance().getWhitelistEndpoint(),r={path:"/domains",apiKey:t,method:"GET"};return e&&(r.params={whitelist:encodeURIComponent(e)}),await E(r)},Y=kt;var z=async()=>{try{let t=f.getInstance().getWhitelistEndpoint();if(!t)return[];let e=await fetch(t,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!e.ok)throw new Error("Failed to fetch whitelist");let r=await e.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(t){return console.error("Error fetching whitelist:",t),[]}};var Ut=t=>{let e=Date.now();return(t-e)/1e3/60},y=async()=>{let t=await s.get("relevantDomainsCheck"),e=await s.get("relevantDomains"),r=await s.get("redirectsWhitelist"),i=f.getInstance().getApiKey(),n=f.getInstance().getWhitelistEndpoint();if(e?.length&&t&&t>Date.now()&&(!n||n&&r?.length))return e;let o=await Y(i),{nextUpdateTimestamp:a,relevantDomains:c}=o;s.set("relevantDomains",c),s.set("relevantDomainsCheck",a),r=await z(),r&&s.set("redirectsWhitelist",r);let l=Ut(a);return chrome.alarms.create(D,{delayInMinutes:l||60*24*2}),c};var Mt=async(t,e)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await y(),e=await s.get("redirectsWhitelist")),!e?.length)return!r;let n=new URL(t).hostname.toLowerCase();return n=n.replace("www.",""),e.includes(n)?!0:e.some(o=>{if(o.startsWith("*.")){let a=o.slice(2);return n.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},_=Mt;var Nt=async(t,e,r,i,n,o,a)=>{if(e===chrome.runtime.id&&await s.set("lastActivation",Date.now()),t&&T(t,n||Date.now()+24*60*60*1e3),o&&a){let c=await s.get("redirectsWhitelist");await _(a,c)&&chrome.tabs.update(o,{url:a})}await I(r,void 0,S(i))},X=Nt;var Z=async t=>t<0?(await s.remove("optOut"),{isOptedOut:!1}):(await s.set("optOut",Date.now()+t),{isOptedOut:!0}),tt=async()=>{let t=await s.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})},Lt=async(t,e,r,i)=>{let n=await s.get("notification");if(n?.expiration<Date.now())await s.remove("notification");else if(n)return await et(e,n,i);let o=await I(t,e,S(r));if(o.showNotification)return await et(e,o,i)},rt=Lt;var Rt=["www.","www1.","www2."],Wt=async t=>{let e=await y();if(!t||!e||!e.length)return"";let r=null;try{r=new URL(t)}catch{r=new URL(`https://${t}`)}let i=r.hostname,n=O(r.pathname);for(let o of Rt)i=i.replace(o,"");for(let o of e){let a=o;o=O(o);let c=!1;o.startsWith("*.")&&(c=!0);let l="/"+o.split("/").slice(1).join("/")||"";if(l!=="/"&&n.startsWith(l)&&(i+=l),i===o||c&&i.endsWith(o.replace("*.",""))){let m=await s.get("quietDomains");return m&&m[o]&&Date.now()<m[o]?"":a}}return""},N={},Kt=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");f.getInstance().setApiEndpoint(e),f.getInstance().setWhitelistEndpoint(i||""),f.getInstance().setApiKey(t),y(),chrome.alarms.onAlarm.addListener(async n=>{let{name:o}=n;switch(o){case D:y();break;default:console.error("alarm with no use case:",o);break}}),chrome.runtime.onMessage.addListener((n,o,a)=>{if(n?.from!=="bringweb3")return;let{action:c}=n;switch(c){case"ACTIVATE":{let{domain:m,extensionId:u,time:p,redirectUrl:h}=n;return X(m,u,t,r,p,o.tab?.id,h).then(()=>a()),!0}case"GET_OPT_OUT":return tt().then(m=>a(m)),!0;case"OPT_OUT":{let{time:m}=n;return Z(m).then(u=>a(u)),!0}case"CLOSE":{let{time:m,domain:u}=n;return u&&(T(u,m),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:m}=n;return m?s.set("walletAddress",m).then(()=>a(m)):s.remove("walletAddress").then(()=>a({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return s.remove("notification").then(()=>a({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${c}`),!0;case"OPEN_CASHBACK_PAGE":let{url:l}=n;return B(l||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(n,o,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let c=H(a.url),l=await s.get("optOut");if(l&&l>Date.now())return;l&&(s.remove("optOut"),s.remove("optOutKey"));let m=N[n];if(o.status!=="complete"||c===m)return;N[n]=c;let u=await Wt(a.url);if(!u||!u.length){await rt(t,n,r,c);return}let p=await C(n),{token:h,isValid:d,iframeUrl:v,networkUrl:x}=await V({apiKey:t,body:{domain:u,url:a.url,address:p}});if(!d){d===!1&&T(u);return}if(!await _(x,await s.get("redirectsWhitelist")))return;let P=await w();A(n,{action:"INJECT",token:h,domain:c,iframeUrl:v,userId:P})}),chrome.tabs.onRemoved.addListener(n=>delete N[n])},Ft=Kt;var $t=()=>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})})}),jt=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{Ft as bringInitBackground,ht as bringInitContentScript,$t as getTurnOff,jt as setTurnOff};
|
|
1
|
+
var st=t=>{let e=new URLSearchParams,{query:r,prefix:n}=t;return Object.entries(r).forEach(([i,s])=>{s&&(n&&(i=`${n}_${i}`),i==="url"?e.append(i,encodeURIComponent(s)):e.append(i,s))}),e.toString()},U=st;var W={name:"@bringweb3/chrome-extension-kit",version:"1.3.9",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify",lint:"tsc",test:"vitest --coverage",release:"yarn build && changeset publish"},files:["dist","README.md"],devDependencies:{"@changesets/cli":"^2.27.7","@types/chrome":"^0.0.268","@vitest/coverage-v8":"^2.0.5",tsup:"^8.2.1",typescript:"^5.5.3",vitest:"^2.0.5"},keywords:["cashback","crypto","bringweb3"],dependencies:{uuid:"^11.0.3"}};var at=()=>W.version,O=at;var ct=({query:t,theme:e,themeMode:r,text:n,iframeUrl:i,page:s,switchWallet:a})=>{let c=chrome.runtime.id,d=`bringweb3-iframe-${c}`,m=document.getElementById(d),u=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${s?"/"+s:""}`:i;if(m)return m;let p=U({query:{...t,extensionId:c,v:O(),themeMode:r,textMode:n,switchWallet:String(a)}}),h=e?`&${U({query:e,prefix:"t"})}`:"",l=document.createElement("iframe");return l.id=d,l.src=`${u}?${p}${h}`,l.setAttribute("sandbox","allow-scripts allow-same-origin"),l.style.position="fixed",l.scrolling="no",l.style.overflow="hidden",l.style.width="1px",l.style.height="1px",l.style.right="8px",l.style.borderRadius="10px",l.style.border="none",l.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(l.style.boxShadow=e.popupShadow),document.documentElement.appendChild(l),l},F=ct;var mt=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,n])=>{r in t.style&&(t.style[r]=n)})},K=mt;var lt=t=>{if(!t||!t.length)return;let e=document.createElement("style");document.head.appendChild(e);let r=e.sheet;r?t.forEach(({name:n,rules:i})=>{r.insertRule(`@keyframes ${n} { ${i} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},$=lt;var g={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},dt=[g.ACTIVATE],ut=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:n,action:i,style:s,keyFrames:a,time:c,extensionId:d,url:m,domain:u,redirectUrl:p}=t.data;if(n==="bringweb3"&&!(d!==chrome.runtime.id&&!dt.includes(i)))switch(i){case g.OPEN:K(e,s);break;case g.CLOSE:e&&e.parentNode?.removeChild(e),c&&chrome.runtime.sendMessage({action:i,time:c,domain:u,from:"bringweb3"});break;case g.PROMPT_LOGIN:r();break;case g.ACTIVATE:chrome.runtime.sendMessage({action:i,from:"bringweb3",domain:u,extensionId:d,time:c,redirectUrl:p});break;case g.OPT_OUT:chrome.runtime.sendMessage({action:i,time:c,from:"bringweb3"});break;case g.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:i,from:"bringweb3"});case g.ADD_KEYFRAMES:$(a);break;case g.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:i,url:m,from:"bringweb3"});break;default:break}},j=ut;var G=async({iframeEl:t,getWalletAddress:e})=>{if(!t&&(t=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`),!t)||!t.contentWindow)return;let r=await e();t.contentWindow.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},ft=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:n})=>{if(e)e(()=>G({iframeEl:n,getWalletAddress:r}));else if(t)for(let i=0;i<t.length;i++){let s=t[i];s&&window.addEventListener(s,async()=>G({iframeEl:n,getWalletAddress:r}))}},q=ft;var pt=t=>t.endsWith("/")?t.slice(0,-1):t,T=pt;var gt=["www.","www1.","www2."],ht=t=>{for(let r of gt)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=T(e),e},N=ht;var M=null,B=!1,wt=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:n,lightTheme:i,darkTheme:s,theme:a,text:c,switchWallet:d=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof n!="function")throw new Error("Missing configuration");q({walletAddressListeners:r,walletAddressUpdateCallback:n,getWalletAddress:t,iframeEl:M}),window.addEventListener("message",m=>j({event:m,iframeEl:M,promptLogin:e})),chrome.runtime.onMessage.addListener((m,u,p)=>{if(m?.from!=="bringweb3")return;let{action:h}=m;switch(h){case"GET_WALLET_ADDRESS":return t().then(l=>p({status:"success",walletAddress:l})).catch(l=>p({status:"success",walletAddress:void 0})),!0;case"INJECT":try{if(N(location.href)!==N(m.domain))return p({status:"failed",message:"Domain already changed"}),!0;if(B)return p({status:"failed",message:"iframe already open"}),!0;let{token:l,iframeUrl:b,userId:x}=m,P={token:l};return x&&(P.userId=x),M=F({query:P,iframeUrl:b,theme:a==="dark"?s:i,themeMode:a||"light",text:c,switchWallet:d,page:m.page}),B=!0,p({status:"success"}),!0}catch(l){return l instanceof Error?p({status:"failed",message:l.message}):p({status:"failed",message:String(l)}),!0}default:console.error(`Unknown action: ${h}`);break}})}},Et=wt;var V=t=>{t&&chrome.tabs.create({url:t})};var f=class t{static instance=null;apiEndpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}setWhitelistEndpoint(e){this.whitelistEndpoint=e}setApiEndpoint(e){this.apiEndpoint=e==="prod"?"https://api.bringweb3.io/v1/extension":"https://sandbox-api.bringweb3.io/v1/extension"}setApiKey(e){this.apiKey=e}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var At=async(t,e)=>new Promise((r,n)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):r()})}),yt=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],n=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(n[`bring_${t}`])})}),bt=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),o={set:At,get:yt,remove:bt};import{v4 as Ot}from"uuid";var Tt=async()=>{let t=await o.get("id");return t||(t=Ot(),o.set("id",t)),t},E=Tt;var vt=async t=>{let{path:e,method:r,params:n}=t;if(!t||!e||!r||!n&&r==="POST")throw new Error("Missing endpoint or method");let i=f.getInstance().getApiEndpoint();i+=e;let s=f.getInstance().getApiKey();if(r==="GET"){let d=new URLSearchParams({...n,version:O(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await E()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});i+=`?${d.toString()}`}else r==="POST"&&(n={...n,version:O(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await E()||void 0,walletAddress:n?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(i,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(n):void 0})).json()},w=vt;var xt=async({body:t})=>await w({path:"/check/popup",method:"POST",params:t}),H=xt;var Pt=["www.","www1.","www2."],Dt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of Pt)t.startsWith(e)&&(t=t.replace(e,""));return t},Q=Dt;var D="updateCache";var It=async(t,e)=>{let r=await o.get("quietDomains");typeof r=="object"?r[t]=e:r={[t]:e},o.set("quietDomains",r)},v=It;var Ct=async({walletAddress:t,cashbackUrl:e,lastActivation:r})=>{let n={walletAddress:t};return r&&(n.lastActivation=r),e&&(n.cashbackUrl=e),await w({path:"/check/notification",method:"POST",params:n})},J=Ct;var St=(t,e)=>new Promise((i,s)=>{let a=c=>{chrome.tabs.get(t,d=>{if(chrome.runtime.lastError){i(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},m=>{chrome.runtime.lastError?c<4?setTimeout(()=>a(c+1),1e3*Math.pow(2,c)):i(null):i(m||null)})})};a(0)}),A=St;var kt=async t=>{let e=await o.get("walletAddress");try{if(!t){let n=await chrome.tabs.query({active:!0,currentWindow:!0});if(!n||!n[0]||!n[0].id)return e;t=n[0].id}let r=await A(t,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&e!==r?.walletAddress&&(e=r?.walletAddress,await o.set("walletAddress",e))}catch{}return e},I=kt;var _t=async(t,e,r)=>{let n={showNotification:!1,token:"",iframeUrl:""},i=await o.get("notificationCheck");if(i&&Date.now()<i)return n;let s=e?await I(e):await o.get("walletAddress");if(!s)return n;let a=await o.get("lastActivation"),c=await J({walletAddress:s,cashbackUrl:r,lastActivation:a});o.set("notificationCheck",c.nextCall);let d={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:c.expiration};return d.showNotification&&await o.set("notification",d),d},C=_t;var Ut=t=>t?chrome.runtime.getURL(t):"",S=Ut;var Nt=async()=>{let t=f.getInstance().getWhitelistEndpoint(),e={path:"/domains",method:"GET"};return t&&(e.params={whitelist:encodeURIComponent(t)}),await w(e)},Y=Nt;var z=async()=>{try{let t=f.getInstance().getWhitelistEndpoint();if(!t)return[];let e=await fetch(t,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!e.ok)throw new Error("Failed to fetch whitelist");let r=await e.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r}catch(t){return console.error("Error fetching whitelist:",t),[]}};var Mt=t=>{let e=Date.now();return(t-e)/1e3/60},y=async()=>{let t=await o.get("relevantDomainsCheck"),e=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),n=f.getInstance().getApiKey(),i=f.getInstance().getWhitelistEndpoint();if(e?.length&&t&&t>Date.now()&&(!i||i&&r?.length))return e;let s=await Y(),{nextUpdateTimestamp:a,relevantDomains:c}=s;o.set("relevantDomains",c),o.set("relevantDomainsCheck",a),r=await z(),r&&o.set("redirectsWhitelist",r);let d=Mt(a);return chrome.alarms.create(D,{delayInMinutes:d||60*24*2}),c};var Lt=async(t,e)=>{try{let r=f.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await y(),e=await o.get("redirectsWhitelist")),!e?.length)return!r;let i=new URL(t).hostname.toLowerCase();return i=i.replace("www.",""),e.includes(i)?!0:e.some(s=>{if(s.startsWith("*.")){let a=s.slice(2);return i.endsWith(a)}return!1})}catch{return console.error("Invalid URL:",t),!1}},k=Lt;var Rt=async(t,e,r,n,i,s,a)=>{if(e===chrome.runtime.id&&await o.set("lastActivation",Date.now()),t&&v(t,i||Date.now()+24*60*60*1e3),s&&a){let c=await o.get("redirectsWhitelist");await k(a,c)&&chrome.tabs.update(s,{url:a})}await C(r,void 0,S(n))},X=Rt;var Z=async t=>t<0?(await o.remove("optOut"),{isOptedOut:!1}):(await o.set("optOut",Date.now()+t),{isOptedOut:!0}),tt=async()=>{let t=await o.get("optOut");return{isOptedOut:!!(t&&t>Date.now())}};var et=async(t,e,r)=>{await A(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await E(),domain:r})},Wt=async(t,e,r,n)=>{let i=await o.get("notification");if(i?.expiration<Date.now())await o.remove("notification");else if(i)return await et(e,i,n);let s=await C(t,e,S(r));if(s.showNotification)return await et(e,s,n)},rt=Wt;var Ft=async t=>{t.category=t?.category||"system",await w({path:"/analytics",method:"POST",params:t})},it=Ft;var Kt=["www.","www1.","www2."],$t=async t=>{let e=await y();if(!t||!e||!e.length)return"";let r=null;try{r=new URL(t)}catch{r=new URL(`https://${t}`)}let n=r.hostname,i=T(r.pathname);for(let s of Kt)n=n.replace(s,"");for(let s of e){let a=s;s=T(s);let c=!1;s.startsWith("*.")&&(c=!0);let d="/"+s.split("/").slice(1).join("/")||"";if(d!=="/"&&i.startsWith(d)&&(n+=d),n===s||c&&n.endsWith(s.replace("*.",""))){let m=await o.get("quietDomains");return m&&m[s]&&Date.now()<m[s]&&m[s]<Date.now()+60*24*60*60*1e3?"":a}}return""},L={},jt=async({identifier:t="94cnbcoEYv5A6z1yxSizi8RAa7kq71nq6miZeSNh",apiEndpoint:e="sandbox",cashbackPagePath:r,whitelistEndpoint:n})=>{if(!t||!e)throw new Error("Missing configuration");if(!["prod","sandbox"].includes(e))throw new Error("unknown apiEndpoint");f.getInstance().setApiEndpoint(e),f.getInstance().setWhitelistEndpoint(n||""),f.getInstance().setApiKey(t),y(),chrome.alarms.onAlarm.addListener(async i=>{let{name:s}=i;switch(s){case D:y();break;default:console.error("alarm with no use case:",s);break}}),chrome.runtime.onMessage.addListener((i,s,a)=>{if(i?.from!=="bringweb3")return;let{action:c}=i;switch(c){case"ACTIVATE":{let{domain:m,extensionId:u,time:p,redirectUrl:h}=i;return X(m,u,t,r,p,s.tab?.id,h).then(()=>a()),!0}case"GET_OPT_OUT":return tt().then(m=>a(m)),!0;case"OPT_OUT":{let{time:m}=i;return Z(m).then(u=>a(u)),!0}case"CLOSE":{let{time:m,domain:u}=i;return u&&(v(u,m),a({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:m}=i;return m?o.set("walletAddress",m).then(()=>a(m)):o.remove("walletAddress").then(()=>a({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>a({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${c}`),!0;case"OPEN_CASHBACK_PAGE":let{url:d}=i;return V(d||r),a({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(i,s,a)=>{if(!a?.url?.startsWith("http")||!a.url)return;let c=Q(a.url),d=await o.get("optOut");if(d&&d>Date.now())return;d&&(o.remove("optOut"),o.remove("optOutKey"));let m=L[i];if(s.status!=="complete"||c===m)return;L[i]=c;let u=await $t(a.url);if(!u||!u.length){await rt(t,i,r,c);return}let p=await I(i),{token:h,isValid:l,iframeUrl:b,networkUrl:x,flowId:P,time:nt=Date.now()+2*60*60*1e3}=await H({body:{domain:u,url:a.url,address:p}});if(!l){l===!1&&v(u,nt);return}if(!await k(x,await o.get("redirectsWhitelist")))return;let R=await E(),_=await A(i,{action:"INJECT",token:h,domain:c,iframeUrl:b,userId:R});_?.status!=="success"&&it({type:"no_popup",userId:R,walletAddress:p,details:{url:a.url,match:u,iframeUrl:b,reason:_?.message,status:_?.status},flowId:P})}),chrome.tabs.onRemoved.addListener(i=>delete L[i])},Gt=jt;var qt=()=>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})})}),Bt=t=>new Promise((e,r)=>{let n=t?Number.MAX_SAFE_INTEGER:-1;chrome.runtime.sendMessage({from:"bringweb3",action:"OPT_OUT",time:n},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?e({isTurnedOff:i.isOptedOut}):r("No response received")})});export{Gt as bringInitBackground,Et as bringInitContentScript,qt as getTurnOff,Bt as setTurnOff};
|