@bringweb3/chrome-extension-kit 1.4.4 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -53,44 +53,6 @@ interface Configuration {
53
53
  showNotifications?: boolean;
54
54
  notificationCallback?: () => void;
55
55
  }
56
- /**
57
- * Initializes the background script for the Bring extension.
58
- *
59
- * @async
60
- * @function bringInitBackground
61
- * @param {Object} configuration - The configuration object.
62
- * @param {string} configuration.identifier - The identifier for the extension.
63
- * @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
64
- * @param {string} configuration.whitelistEndpoint - Endpoint for whitelist of redirect urls.
65
- * @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
66
- * @param {boolean} [configuration.isEnabledByDefault] - Determine if the user see the popup by default. defaults to true.
67
- * @param {boolean} [configuration.showNotifications] - Determine if the extension should show notifications about new rewards. defaults to true.
68
- * @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
69
- * @returns {Promise<void>}
70
- *
71
- * @description
72
- * This function sets up the background processes for the Bring extension. It initializes
73
- * the API endpoint, sets up listeners for alarms, runtime messages, and tab updates.
74
- * It handles various actions such as opting out, closing notifications, injecting content
75
- * based on URL changes, and managing quiet domains.
76
- *
77
- * The function performs the following tasks:
78
- * - Validates and sets the API endpoint
79
- * - Updates the cache
80
- * - Sets up listeners for alarms to update cache periodically
81
- * - Handles runtime messages for opting out and closing notifications
82
- * - Monitors tab updates to inject content or show notifications based on URL changes
83
- * - Validates domains and manages quiet domains
84
- *
85
- * @example
86
- * bringInitBackground({
87
- * identifier: '<bring_identifier>',
88
- * apiEndpoint: 'sandbox',
89
- * whitelistEndpoint: 'https://example.com/whitelist.json',
90
- * isEnabledByDefault: true,
91
- * cashbackPagePath: '/cashback.html'
92
- * });
93
- */
94
56
  declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint, isEnabledByDefault, showNotifications, notificationCallback }: Configuration) => Promise<void>;
95
57
 
96
58
  interface TurnOff {
package/dist/index.d.ts CHANGED
@@ -53,44 +53,6 @@ interface Configuration {
53
53
  showNotifications?: boolean;
54
54
  notificationCallback?: () => void;
55
55
  }
56
- /**
57
- * Initializes the background script for the Bring extension.
58
- *
59
- * @async
60
- * @function bringInitBackground
61
- * @param {Object} configuration - The configuration object.
62
- * @param {string} configuration.identifier - The identifier for the extension.
63
- * @param {string} configuration.apiEndpoint - The API endpoint ('prod' or 'sandbox').
64
- * @param {string} configuration.whitelistEndpoint - Endpoint for whitelist of redirect urls.
65
- * @param {string} [configuration.cashbackPagePath] - Optional path to the cashback page.
66
- * @param {boolean} [configuration.isEnabledByDefault] - Determine if the user see the popup by default. defaults to true.
67
- * @param {boolean} [configuration.showNotifications] - Determine if the extension should show notifications about new rewards. defaults to true.
68
- * @throws {Error} Throws an error if identifier or apiEndpoint is missing, or if apiEndpoint is invalid.
69
- * @returns {Promise<void>}
70
- *
71
- * @description
72
- * This function sets up the background processes for the Bring extension. It initializes
73
- * the API endpoint, sets up listeners for alarms, runtime messages, and tab updates.
74
- * It handles various actions such as opting out, closing notifications, injecting content
75
- * based on URL changes, and managing quiet domains.
76
- *
77
- * The function performs the following tasks:
78
- * - Validates and sets the API endpoint
79
- * - Updates the cache
80
- * - Sets up listeners for alarms to update cache periodically
81
- * - Handles runtime messages for opting out and closing notifications
82
- * - Monitors tab updates to inject content or show notifications based on URL changes
83
- * - Validates domains and manages quiet domains
84
- *
85
- * @example
86
- * bringInitBackground({
87
- * identifier: '<bring_identifier>',
88
- * apiEndpoint: 'sandbox',
89
- * whitelistEndpoint: 'https://example.com/whitelist.json',
90
- * isEnabledByDefault: true,
91
- * cashbackPagePath: '/cashback.html'
92
- * });
93
- */
94
56
  declare const bringInitBackground: ({ identifier, apiEndpoint, cashbackPagePath, whitelistEndpoint, isEnabledByDefault, showNotifications, notificationCallback }: Configuration) => Promise<void>;
95
57
 
96
58
  interface TurnOff {
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var $=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var Nt=Object.getOwnPropertyNames;var Ut=Object.prototype.hasOwnProperty;var kt=(t,e)=>{for(var r in e)$(t,r,{get:e[r],enumerable:!0})},Mt=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Nt(e))!Ut.call(t,n)&&n!==r&&$(t,n,{get:()=>e[n],enumerable:!(i=Ct(e,n))||i.enumerable});return t};var Rt=t=>Mt($({},"__esModule",{value:!0}),t);var Ae={};kt(Ae,{bringInitBackground:()=>Ot,bringInitContentScript:()=>rt,getPopupEnabled:()=>_t,getTurnOff:()=>Pt,setPopupEnabled:()=>xt,setTurnOff:()=>Tt});module.exports=Rt(Ae);var Lt=t=>{let e=new URLSearchParams,{query:r,prefix:i}=t;return Object.entries(r).forEach(([n,a])=>{a&&(i&&(n=`${i}_${n}`),n==="url"?e.append(n,encodeURIComponent(a)):e.append(n,a))}),e.toString()},F=Lt;var Q={name:"@bringweb3/chrome-extension-kit",version:"1.4.4",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 $t=()=>Q.version,S=$t;var Ft=({query:t,theme:e,themeMode:r,text:i,iframeUrl:n,page:a,switchWallet:m})=>{let d=chrome.runtime.id,c=`bringweb3-iframe-${d}`,u=document.getElementById(c),l=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${a?"/"+a:""}`:n;if(u)return u;let f=F({query:{...t,extensionId:d,v:S(),themeMode:r,textMode:i,switchWallet:String(m)}}),E=e?`&${F({query:e,prefix:"t"})}`:"",s=document.createElement("iframe");return s.id=c,s.src=encodeURI(`${l}?${f}${E}`),s.setAttribute("sandbox","allow-scripts allow-same-origin"),s.style.position="fixed",s.scrolling="no",s.style.overflow="hidden",s.style.width="1px",s.style.height="1px",s.style.right="8px",s.style.borderRadius="10px",s.style.border="none",s.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(s.style.boxShadow=e.popupShadow),document.documentElement.appendChild(s),s},J=Ft;var jt=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,i])=>{r in t.style&&(t.style[r]=i)})},Y=jt;var Kt=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")},z=Kt;var h={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",OPT_OUT_SPECIFIC:"OPT_OUT_SPECIFIC",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},Gt=[h.ACTIVATE],Bt=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:i,action:n,style:a,keyFrames:m,time:d,extensionId:c,url:u,domain:l,redirectUrl:f}=t.data;if(i==="bringweb3"&&!(c!==chrome.runtime.id&&!Gt.includes(n)))switch(n){case h.OPEN:Y(e,a);break;case h.CLOSE:e&&e.parentNode?.removeChild(e),d&&chrome.runtime.sendMessage({action:n,time:d,domain:l,from:"bringweb3"});break;case h.PROMPT_LOGIN:r();break;case h.ACTIVATE:chrome.runtime.sendMessage({action:n,from:"bringweb3",domain:l,extensionId:c,time:d,redirectUrl:f});break;case h.OPT_OUT:chrome.runtime.sendMessage({action:n,time:d,from:"bringweb3"});break;case h.OPT_OUT_SPECIFIC:chrome.runtime.sendMessage({action:n,domain:l,time:d,from:"bringweb3"});break;case h.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:n,from:"bringweb3"});case h.ADD_KEYFRAMES:z(m);break;case h.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:n,url:u,from:"bringweb3"});break;default:break}},X=Bt;var Z=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})},Vt=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:i})=>{if(e)e(()=>Z({iframeEl:i,getWalletAddress:r}));else if(t)for(let n=0;n<t.length;n++){let a=t[n];a&&window.addEventListener(a,async()=>Z({iframeEl:i,getWalletAddress:r}))}},tt=Vt;var Ht=t=>t.endsWith("/")?t.slice(0,-1):t,I=Ht;var qt=["www.","www1.","www2."],Qt=t=>{for(let r of qt)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=I(e),e},P=Qt;var j=null,et=!1,Jt=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:i,lightTheme:n,darkTheme:a,theme:m,text:d,switchWallet:c=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof i!="function")throw new Error("Missing configuration");tt({walletAddressListeners:r,walletAddressUpdateCallback:i,getWalletAddress:t,iframeEl:j}),window.addEventListener("message",u=>X({event:u,iframeEl:j,promptLogin:e})),chrome.runtime.onMessage.addListener((u,l,f)=>{if(u?.from!=="bringweb3")return;let{action:E}=u;switch(E){case"GET_WALLET_ADDRESS":return t().then(s=>f({status:"success",walletAddress:s})).catch(s=>f({status:"success",walletAddress:void 0})),!0;case"INJECT":try{let{referrer:s}=document,g=u.portalReferrers||[];if(P(location.href)!==P(u.domain))return f({status:"failed",message:"Domain already changed"}),!0;if(et)return f({status:"failed",message:"iframe already open"}),!0;if(s&&g.includes(P(s)))return f({status:"failed",message:`already activated by ${P(s)}`,action:"activate"}),!0;let{token:y,iframeUrl:v,userId:b}=u,D={token:y};return b&&(D.userId=b),j=J({query:D,iframeUrl:v,theme:m==="dark"?a:n,themeMode:m||"light",text:d,switchWallet:c,page:u.page}),et=!0,f({status:"success"}),!0}catch(s){return s instanceof Error?f({status:"failed",message:s.message}):f({status:"failed",message:String(s)}),!0}default:console.error(`Unknown action: ${E}`);break}})}},rt=Jt;var nt=t=>{t&&chrome.tabs.create({url:t})};var p=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 Yt=async(t,e)=>new Promise((r,i)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?i(chrome.runtime.lastError):r()})}),zt=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],i=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(i[`bring_${t}`])})}),Xt=async t=>new Promise((e,r)=>{chrome.storage.local.remove([`bring_${t}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e()})}),o={set:Yt,get:zt,remove:Xt};var it=require("uuid"),Zt=async()=>{let t=await o.get("id");return t||(t=(0,it.v4)(),o.set("id",t)),t},T=Zt;var te=async t=>{let{path:e,method:r,params:i}=t;if(!t||!e||!r||!i&&r==="POST")throw new Error("Missing endpoint or method");let n=p.getInstance().getApiEndpoint();n+=e;let a=p.getInstance().getApiKey();if(r==="GET"){let c=new URLSearchParams({...i,version:S(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await T()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});n+=`?${c.toString()}`}else r==="POST"&&(i={...i,version:S(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await T()||void 0,walletAddress:i?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(n,{method:r,headers:{"Content-Type":"application/json","x-api-key":a},body:r==="POST"?JSON.stringify(i):void 0})).json()},A=te;var ee=async({body:t})=>await A({path:"/check/popup",method:"POST",params:t}),ot=ee;var re=["www.","www1.","www2."],ne=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of re)t.startsWith(e)&&(t=t.replace(e,""));return t},st=ne;var at="quietDomains",ie=async(t,e)=>{let r=await o.get(at);(typeof r!="object"||r===null)&&(r={});let i=Date.now(),n=i+e;r[t]=[i,n],o.set(at,r)},C=ie;var oe=async({walletAddress:t,cashbackUrl:e,lastActivation:r,timeSinceLastActivation:i})=>{let n={walletAddress:t};return r&&(n.lastActivation=r),i&&(n.timeSinceLastActivation=i),e&&(n.cashbackUrl=e),await A({path:"/check/notification",method:"POST",params:n})},ct=oe;var se=(t,e)=>new Promise((n,a)=>{let m=d=>{chrome.tabs.get(t,c=>{if(chrome.runtime.lastError){n(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},u=>{chrome.runtime.lastError?d<4?setTimeout(()=>m(d+1),1e3*Math.pow(2,d)):n(null):n(u||null)})})};m(0)}),x=se;var ae=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 x(t,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&e!==r?.walletAddress&&(e=r?.walletAddress,await o.set("walletAddress",e))}catch{}return e},k=ae;var ce=t=>{if(!t||!Array.isArray(t)||t.length!==2)return!1;let[e,r]=t;return typeof e=="number"&&typeof r=="number"&&e<=r},N=(t,e)=>{if(!ce(t))return!0;let[r,i]=t;return e=e??Date.now(),e<r||e>i},O=(t,e)=>!N(t,e);var me=async(t,e)=>{let r={showNotification:!1,token:"",iframeUrl:""},i=Date.now(),n=await o.get("notificationCheck");if(O(n,i))return r;let a=t?await k(t):await o.get("walletAddress");if(!a)return r;let m=await o.get("lastActivation"),d=m?i-m:void 0,c=await ct({walletAddress:a,cashbackUrl:e,lastActivation:m,timeSinceLastActivation:d});o.set("notificationCheck",[i,i+c.nextCall]);let u={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:[i,i+c.expiration]};return u.showNotification&&await o.set("notification",u),u},M=me;var le=t=>t?chrome.runtime.getURL(t):"",R=le;var ue=async t=>{let e=p.getInstance().getWhitelistEndpoint(),r={path:"/domains",method:"GET"};return r.params={},e&&(r.params.whitelist=encodeURIComponent(e)),t&&(r.params.trigger=t),await A(r)},mt=ue;var lt=t=>{if(t===void 0)return"undefined";if(t===null)return"null";if(typeof t=="string")return`"${t}"`;if(typeof t=="number")return Number.isNaN(t)?"NaN":String(t);if(typeof t=="boolean")return String(t);if(Array.isArray(t))return`[${t.map(e=>e===void 0?"undefined":e===null?"null":lt(e)).join(", ")}]`;if(typeof t=="object")try{return JSON.stringify(t,(e,r)=>r===void 0?"undefined":Number.isNaN(r)?"NaN":r)}catch{return`{object: ${Object.prototype.toString.call(t)}}`}return String(t)},w=lt;var ut=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 U=async()=>{let t=await o.get("relevantDomainsCheck"),e=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),i=p.getInstance().getWhitelistEndpoint(),n=null,a=Date.now();if(e?Array.isArray(e)?t?Array.isArray(t)?t.length!==2?n=`invalid domains timestamp check format__length: ${t.length} - value: ${w(t)}`:t[0]>=a?n=`cache expired - range start is bigger than Date.now()__value: ${w(t)}, now: ${a}`:a>=t[1]?n=`cache expired - range end is smaller than Date.now()__value: ${w(t)}, now: ${a}`:i&&!r?.length?n=`missing whitelist data__endpoint: ${i}, whitelist: ${w(r)}`:N(t,a)&&(n=`cache expired - range is expired__range: ${w(t)}, now: ${a}`):n=`invalid domains timestamp check format - not an array__value: ${w(t)}`:n=`no domains timestamp check found__value: ${w(t)}`:n=`domains list isn't an array__value: ${w(e)}`:n=`no domains in cache__value: ${w(e)}`,!n)return e;let m=await mt(n),{nextUpdateTimestamp:d,relevantDomains:c}=m;return o.set("relevantDomains",c),o.set("relevantDomainsCheck",[a,a+d]),r=await ut(),r&&o.set("redirectsWhitelist",r),c};var de=async(t,e)=>{try{let r=p.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await U(),e=await o.get("redirectsWhitelist")),!e?.length)return!r;let n=new URL(t).hostname.toLowerCase();return n=n.replace("www.",""),e.includes(n)?!0:e.some(a=>{if(a.startsWith("*.")){let m=a.slice(2);return n.endsWith(m)}return!1})}catch{return console.error("Invalid URL:",t),!1}},L=de;var fe=async(t,e,r,i,n,a)=>{let m=Date.now();if(e===chrome.runtime.id&&await o.set("lastActivation",m),t&&C(t,i||864e5),n&&a){let d=await o.get("redirectsWhitelist");await L(a,d)&&chrome.tabs.update(n,{url:a})}await M(void 0,R(r))},K=fe;var dt=async t=>{if(t<0)return await o.remove("optOut"),{isOptedOut:!1};{let e=Date.now();return await o.set("optOut",[e,e+t]),{isOptedOut:!0}}},ft=async()=>{let t=await o.get("optOut");return{isOptedOut:O(t)}};var pt=async(t,e,r)=>{await x(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await T(),domain:r})},pe=async(t,e,r,i,n)=>{let a=await o.get("notification"),m=Date.now(),d=a?.expiration;if(N(d,m))await o.remove("notification");else if(a)return await pt(t,a,r);let c=await M(t,R(e));c.showNotification&&(i&&await pt(t,c,r),n&&n())},gt=pe;var ge=async t=>{t.category=t?.category||"system",await A({path:"/analytics",method:"POST",params:t})},ht=ge;var wt="optOutDomains",he=async(t,e)=>{if(!t)return;let r=await o.get(wt);(typeof r!="object"||r===null)&&(r={});let i=Date.now(),n=i+e;r[t]=[i,n],o.set(wt,r)},Et=he;var bt=1,yt=async(t,e)=>{let r=await o.get(t);if(r&&typeof r=="object"){for(let[i,n]of Object.entries(r))typeof n=="number"&&n>e?r[i]=[e,n]:delete r[i];o.set(t,r)}},we=async()=>{try{let t=Date.now(),e=await o.get("optOut");return e&&typeof e=="number"&&e>t?await o.set("optOut",[t,e]):await o.remove("optOut"),await yt("optOutDomains",t),await yt("quietDomains",t),!0}catch{return!1}},At=async()=>{(await o.get("migrationVersion")||0)<bt&&await we()&&await o.set("migrationVersion",bt)};var Ee=["www.","www1.","www2."],be=async t=>{let e=await U();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=I(r.pathname);for(let m of Ee)i=i.replace(m,"");let a=Date.now();for(let m of e){let d=m;m=I(m);let c=!1;m.startsWith("*.")&&(c=!0);let u="/"+m.split("/").slice(1).join("/")||"";if(u!=="/"&&n.startsWith(u)&&(i+=u),i===m||c&&i.endsWith(m.replace("*.",""))){let l=await o.get("quietDomains");return l&&l[m]&&O(l[m])&&l[m][1]<a+60*864e5?"":d}}return""},G={},ye=async({identifier:t,apiEndpoint:e,cashbackPagePath:r,whitelistEndpoint:i,isEnabledByDefault:n=!0,showNotifications:a=!0,notificationCallback:m})=>{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||""),p.getInstance().setApiKey(t),await o.get("popupEnabled")===void 0&&await o.set("popupEnabled",n),await At(),U(),chrome.runtime.onMessage.addListener((c,u,l)=>{if(c?.from!=="bringweb3")return;let{action:f}=c;switch(f){case"ACTIVATE":{let{domain:s,extensionId:g,time:y,redirectUrl:v}=c;return K(s,g,r,y,u.tab?.id,v).then(()=>l()),!0}case"GET_OPT_OUT":return ft().then(s=>l(s)),!0;case"OPT_OUT":{let{time:s}=c;return dt(s).then(g=>l(g)),!0}case"OPT_OUT_SPECIFIC":{let{domain:s,time:g}=c;return Et(s,g).then(y=>l(y)),!0}case"GET_POPUP_ENABLED":return o.get("popupEnabled").then(s=>l({isPopupEnabled:s})),!0;case"SET_POPUP_ENABLED":{let{isPopupEnabled:s}=c;return o.set("popupEnabled",s).then(()=>{l({isPopupEnabled:s})}).catch(g=>{console.error("Error setting popup enabled:",g),l({error:"Failed to set popup enabled state"})}),!0}case"CLOSE":{let{time:s,domain:g}=c;return g&&(C(g,s),l({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:s}=c;return s?o.set("walletAddress",s).then(()=>l(s)):o.remove("walletAddress").then(()=>l({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>l({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${f}`),!0;case"OPEN_CASHBACK_PAGE":let{url:E}=c;return nt(E||r),l({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(c,u,l)=>{if(!u.url||!l?.url?.startsWith("http"))return;let f=st(l.url),E=await o.get("optOut"),s=await o.get("popupEnabled"),g=Date.now();if(!s||O(E,g))return;E&&o.remove("optOut");let y=await o.get("optOutDomains");if(y&&O(y[P(f)],g))return;let v=G[c];if(f===v)return;G[c]=f;let b=await be(l.url);if(!b||!b.length){await gt(c,r,f,a,m);return}let D=await k(c),{token:vt,isValid:B,iframeUrl:V,networkUrl:Dt,flowId:St,portalReferrers:It,time:H=864e5}=await ot({body:{domain:b,url:l.url,address:D}});if(!B){B===!1&&C(b,H);return}if(!await L(Dt,await o.get("redirectsWhitelist")))return;let q=await T(),_=await x(c,{action:"INJECT",token:vt,domain:f,iframeUrl:V,userId:q,portalReferrers:It});if(_?.action)switch(_.action){case"activate":K(b,chrome.runtime.id,r,H,c);break;default:console.error(`Unknown action: ${_.action}`);break}_?.status!=="success"&&ht({type:"no_popup",userId:q,walletAddress:D,details:{url:l.url,match:b,iframeUrl:V,reason:_?.message,status:_?.status},flowId:St})}),chrome.tabs.onRemoved.addListener(c=>delete G[c])},Ot=ye;var Pt=()=>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})})}),Tt=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")})});var _t=()=>new Promise((t,e)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_POPUP_ENABLED"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),e(chrome.runtime.lastError);return}t(r)})}),xt=t=>new Promise((e,r)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"SET_POPUP_ENABLED",isPopupEnabled:t},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?e({isPopupEnabled:i.isPopupEnabled}):r("No response received")})});0&&(module.exports={bringInitBackground,bringInitContentScript,getPopupEnabled,getTurnOff,setPopupEnabled,setTurnOff});
1
+ "use strict";var re=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var ot=Object.prototype.hasOwnProperty;var st=(e,t)=>{for(var r in t)re(e,r,{get:t[r],enumerable:!0})},at=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of it(t))!ot.call(e,n)&&n!==r&&re(e,n,{get:()=>t[n],enumerable:!(i=nt(t,n))||i.enumerable});return e};var ct=e=>at(re({},"__esModule",{value:!0}),e);var tr={};st(tr,{bringInitBackground:()=>Xe,bringInitContentScript:()=>xe,getPopupEnabled:()=>tt,getTurnOff:()=>Ze,setPopupEnabled:()=>rt,setTurnOff:()=>et});module.exports=ct(tr);var ne=e=>{try{switch(e){case"VERSION":return process?.env?.VERSION;case"ENDPOINT":return process?.env?.ENDPOINT;case"IFRAME_URL":return process?.env?.IFRAME_URL;default:return}}catch{return}},ge=ne("VERSION"),he=ne("ENDPOINT"),ie=ne("IFRAME_URL");var lt=e=>{let t=new URLSearchParams,{query:r,prefix:i}=e;return Object.entries(r).forEach(([n,s])=>{s&&(i&&(n=`${i}_${n}`),n==="url"?t.append(n,encodeURIComponent(s)):t.append(n,s))}),t.toString()},oe=lt;var we={name:"@bringweb3/chrome-extension-kit",version:"1.5.1",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --env.ENDPOINT=dev --env.VERSION=1.5.0 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify","build:dev":"tsup index.ts --format cjs,esm --dts --minify --env.ENDPOINT=dev --env.VERSION=1.5.0",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 dt=()=>ge||we.version,W=dt;var ut=({query:e,theme:t,themeMode:r,text:i,iframeUrl:n,page:s,switchWallet:l})=>{let d=chrome.runtime.id,a=`bringweb3-iframe-${d}`,c=document.getElementById(a),m=ie?`${ie}${s?"/"+s:""}`:n;if(c)return c;let u=oe({query:{...e,extensionId:d,v:W(),themeMode:r,textMode:i,switchWallet:String(l)}}),f=t?`&${oe({query:t,prefix:"t"})}`:"",p=document.createElement("iframe");return p.id=a,p.src=encodeURI(`${m}?${u}${f}`),p.setAttribute("sandbox","allow-scripts allow-same-origin"),p.style.position="fixed",p.scrolling="no",p.style.overflow="hidden",p.style.width="1px",p.style.height="1px",p.style.right="8px",p.style.borderRadius="10px",p.style.border="none",p.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(p.style.boxShadow=t.popupShadow),document.documentElement.appendChild(p),p},Ee=ut;var pt=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,i])=>{r in e.style&&(e.style[r]=i)})},ye=pt;var ft=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let r=t.sheet;r?e.forEach(({name:i,rules:n})=>{r.insertRule(`@keyframes ${i} { ${n} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},be=ft;var b={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",OPT_OUT_SPECIFIC:"OPT_OUT_SPECIFIC",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE",STOP_REMINDERS:"STOP_REMINDERS"},gt=[b.ACTIVATE],ht=({event:e,iframeEl:t,promptLogin:r})=>{if(!e?.data)return;let{from:i,action:n,style:s,keyFrames:l,time:d,extensionId:a,url:c,domain:m,redirectUrl:u,iframeUrl:f,token:p,flowId:g,platformName:h}=e.data;if(i==="bringweb3"&&!(a!==chrome.runtime.id&&!gt.includes(n)))switch(n){case b.OPEN:ye(t,s);break;case b.CLOSE:t&&t.parentNode?.removeChild(t),d&&chrome.runtime.sendMessage({action:n,time:d,domain:m,from:"bringweb3"});break;case b.PROMPT_LOGIN:r();break;case b.ACTIVATE:chrome.runtime.sendMessage({action:n,from:"bringweb3",domain:m,extensionId:a,time:d,redirectUrl:u,iframeUrl:f,token:p,flowId:g,platformName:h});break;case b.OPT_OUT:chrome.runtime.sendMessage({action:n,time:d,from:"bringweb3"});break;case b.OPT_OUT_SPECIFIC:chrome.runtime.sendMessage({action:n,domain:m,time:d,from:"bringweb3"});break;case b.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:n,from:"bringweb3"});case b.ADD_KEYFRAMES:be(l);break;case b.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:n,url:c,from:"bringweb3"});break;case b.STOP_REMINDERS:chrome.runtime.sendMessage({action:n,from:"bringweb3"});break;default:break}},Ae=ht;var Oe=async({iframeEl:e,getWalletAddress:t})=>{e||(e=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`));let r=await t();e?.contentWindow?.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},wt=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:r,iframeEl:i})=>{if(t)t(()=>Oe({iframeEl:i,getWalletAddress:r}));else if(e)for(let n=0;n<e.length;n++){let s=e[n];s&&window.addEventListener(s,async()=>Oe({iframeEl:i,getWalletAddress:r}))}},Pe=wt;var Et=e=>e.endsWith("/")?e.slice(0,-1):e,H=Et;var yt=["www.","www1.","www2."],bt=e=>{for(let r of yt)e=e.replace(r,"");let t="";try{t=new URL(e).host}catch{t=new URL(`https://${e}`).host}return t=H(t),t},P=bt;var N=null,se,ae=!1,ve=null,At=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,walletAddressUpdateCallback:i,lightTheme:n,darkTheme:s,theme:l,text:d,switchWallet:a=!1})=>{if(window.self!==window.top&&H(window.document.location.origin).endsWith("bringweb3.io")){window.addEventListener("message",c=>{if(!c.data||c.data.from!=="bringweb3"||c.data.action!=="PORTAL_ACTIVATE")return;let{action:m,domain:u,extensionId:f,time:p,iframeUrl:g,token:h,platformName:w}=c.data;chrome.runtime.sendMessage({action:m,from:"bringweb3",domain:u,extensionId:f,time:p,iframeUrl:g,token:h,source:"portal",platformName:w})});return}if(!e||!t||!r?.length&&typeof i!="function")throw new Error("Missing configuration");Pe({walletAddressListeners:r,walletAddressUpdateCallback:i,getWalletAddress:e,iframeEl:N}),window.addEventListener("message",c=>Ae({event:c,iframeEl:N,promptLogin:t})),chrome.runtime.onMessage.addListener((c,m,u)=>{if(c?.from!=="bringweb3")return;let{action:f}=c;switch(f){case"GET_WALLET_ADDRESS":return e().then(p=>u({status:"success",walletAddress:p})).catch(p=>u({status:"success",walletAddress:void 0})),!0;case"CLOSE_POPUP":N&&se===c.path&&P(location.href)===P(c.domain)?(N.parentNode?.removeChild(N),ae=!1,se=void 0,u({status:"success",message:"Popup closed",location:window.document.location.href,flowId:ve})):u({status:"failed",message:"Domain mismatch or iframe not open"});case"INJECT":try{let{referrer:p}=document,g=c.referrers||[];if(P(location.href)!==P(c.domain))return u({status:"failed",message:"Domain already changed"}),!0;if(ae)return u({status:"failed",message:"iframe already open"}),!0;if(!!p&&g.includes(P(p))&&c.page==="")return u({status:"failed",message:`already activated by ${P(p)}`,action:"activate"}),!0;let{token:w,iframeUrl:y,userId:$}=c,K={token:w};return $&&(K.userId=$),N=Ee({query:K,iframeUrl:y,theme:l==="dark"?s:n,themeMode:l||"light",text:d,switchWallet:a,page:c.page}),ae=!0,se=`/${c.page||""}`,ve=c.flowId,u({status:"success"}),!0}catch(p){return p instanceof Error?u({status:"failed",message:p.message}):u({status:"failed",message:String(p)}),!0}default:console.error(`Unknown action: ${f}`);break}})},xe=At;var E=class e{static instance=null;apiEndpoint="";endpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setWhitelistEndpoint(t){this.whitelistEndpoint=t}setApiEndpoint(t){switch(this.endpoint=t,t){case"prod":this.apiEndpoint="https://api.bringweb3.io/v1/extension";break;case"sandbox":this.apiEndpoint="https://sandbox-api.bringweb3.io/v1/extension";break;case"dev":this.apiEndpoint="https://dev-api.bringweb3.io/v1/extension";break;default:this.apiEndpoint="https://sandbox-api.bringweb3.io/v1/extension";break}}setApiKey(t){this.apiKey=t}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getEndpoint(){if(!this.endpoint)throw new Error("endpoint not set. Call setApiEndpoint first.");return this.endpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var ce=class{cache=new Map;get(t){let r=this.cache.get(t);return r?r.value:null}set(t,r){this.cache.set(t,{value:r})}delete(t){this.cache.delete(t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}},Te=ce;var _=e=>{try{return new Uint8Array(atob(e).split("").map(t=>t.charCodeAt(0)))}catch{return null}},Q=e=>btoa(String.fromCharCode(...e)),Ot={relevantDomains:{get:_,set:Q},redirectsWhitelist:{get:_,set:Q},portalRelevantDomains:{get:_,set:Q},postPurchaseUrls:{get:_,set:Q}},F=Ot;var T=e=>e.split("").reverse().join(""),J=e=>{let t=[];for(let n of e){let s=n.indexOf("/");if(s===-1)t.push(T(n));else{let l=n.substring(0,s),d=n.substring(s),a=T(l);t.push(a+d)}}t.sort();let r=[],i="";for(let n of t){let s=Math.min(i.length,n.length,32),l=0;for(;l<s&&i[l]===n[l];)l++;let d=n.substring(l),a=new TextEncoder().encode(d);if(a.length>0){let c=Math.min(...a);if(c<33)throw new Error(`Invalid rem byte: ${c}`)}r.push(l),r.push(...a),i=n}return new Uint8Array(r)},Ie=e=>{let t=[],r=0,i="",n=0;for(;r<e.length;){let s=e[r];r++;let l=r;for(;l<e.length;){let u=e[l];if(u===void 0||u<33)break;l++}let d=new TextDecoder().decode(e.slice(r,l)),a=i.substring(0,s)+d,c=a.indexOf("/"),m;if(c===-1)m=T(a);else{let u=a.substring(0,c),f=a.substring(c);m=T(u)+f}t.push(m),i=a,r=l}return t},D=(e,t,r=!1,i=!1)=>{let n=t.indexOf("/"),s=n===-1?t:t.substring(0,n),l=n===-1?"":t.substring(n+1),d=T(s),a=0,c="";for(;a<e.length;){let m=e[a];if(m===void 0||m<0||m>32)throw new Error(`Invalid LCP marker: ${m}`);a++;let u=a;for(;u<e.length;){let y=e[u];if(y===void 0||y<33)break;u++}let f=new TextDecoder().decode(e.slice(a,u));a=u;let p=c.substring(0,m)+f;c=p;let g=p.indexOf("/"),h,w;if(g===-1)h=T(p),w="";else{let y=p.substring(0,g);h=T(y),w=p.substring(g+1)}if(h===s||h.startsWith("*.")&&(s.endsWith("."+h.substring(2))||s===h.substring(2))){if(l===""&&w==="")return{matched:!0,match:`${h}${g!==-1?`/${w}`:""}`};if(r){let y=`^${w}${i?"$":""}`;if(new RegExp(y).test(l))return{matched:!0,match:`${h}${g!==-1?`/${w}`:""}`}}else if(i&&l===w||!i&&l.startsWith(w))return{matched:!0,match:`${h}${g!==-1?`/${w}`:""}`}}if(T(h)>d)return{matched:!1,match:void 0}}return{matched:!1,match:void 0}};var le=e=>{if(!e||!Array.isArray(e)||e.length!==2)return!1;let[t,r]=e;return typeof t=="number"&&typeof r=="number"&&t<=r},V=(e,t,r)=>{if(!le(e))return!0;let[i,n]=e;return t=t??Date.now(),t<i||t>n||r?.maxRange!==void 0&&n-i>r.maxRange},v=(e,t,r)=>!V(e,t,r);var Y="bring_",A=new Te,_e=async(e,t,r=!0)=>(r&&A.set(e,t),new Promise((i,n)=>{F[e]?.set&&(t=F[e].set(t)),chrome.storage.local.set({[`${Y}${e}`]:t},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):i()})})),me=async(e,t=!0)=>{if(t){let r=A.get(e);if(r!==null)return r}return new Promise((r,i)=>{chrome.storage.local.get([`${Y}${e}`],n=>{if(chrome.runtime.lastError)i(chrome.runtime.lastError);else{let s=n[`${Y}${e}`];s&&F[e]?.get&&(s=F[e].get(s)),t&&s!==void 0&&A.set(e,s),r(s)}})})},De=async e=>(A.delete(e),new Promise((t,r)=>{chrome.storage.local.remove([`${Y}${e}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t()})})),Pt=()=>{A.clear()},vt=e=>{A.delete(e)},xt=()=>A.getStats(),Tt=()=>{if(!(typeof globalThis>"u"))try{globalThis.bringCache={clear:()=>A.clear(),stats:()=>A.getStats(),get:async e=>await me(e),getReadable:async e=>{let t=await me(e);return t instanceof Uint8Array?t=Ie(t):le(t)&&(t=`[${new Date(t[0]).toLocaleString("en-GB")} - ${new Date(t[1]).toLocaleString("en-GB")}] Total of ${(t[1]-t[0])/1e3/60} minutes`),t},set:async(e,t)=>await _e(e,t),invalidate:e=>A.delete(e),delete:async e=>await De(e)}}catch(e){console.warn("Failed to initialize debug cache:",e)}},o={set:_e,get:me,remove:De,clearCache:Pt,invalidateCache:vt,getCacheStats:xt,initializeDebugCache:Tt};var z=require("uuid"),Se=2,Ne=async(e,t)=>{let r=await o.get(e);if(r&&typeof r=="object"){for(let[i,n]of Object.entries(r))typeof n=="number"&&n>t?r[i]=[t,n]:delete r[i];await o.set(e,r)}},It=async()=>{try{let e=Date.now(),t=await o.get("optOut");return t&&typeof t=="number"&&t>e?await o.set("optOut",[e,t]):await o.remove("optOut"),await Ne("optOutDomains",e),await Ne("quietDomains",e),!0}catch{return!1}},_t=async()=>{try{let e=await o.get("quietDomains");if(e&&typeof e=="object"){for(let[r,i]of Object.entries(e))Array.isArray(i)&&(e[r]={time:i,phase:"quiet"});await o.set("quietDomains",e)}let t=await o.get("id");return(0,z.validate)(t||"")||(t=(0,z.v4)(),await o.set("id",t)),!0}catch{return!1}},Ce=async()=>{let e=await o.get("migrationVersion")||0;e<1&&await It()&&await o.set("migrationVersion",1),e<Se&&await _t()&&await o.set("migrationVersion",Se)};var Re="quietDomains",Dt=async(e,t,r,i)=>{let n=await o.get(Re);(typeof n!="object"||n===null)&&(n={});let s=Date.now(),l=s+t;n[e]={time:[s,l],phase:i||"quiet"},r&&(n[e].payload=r),await o.set(Re,n)},C=Dt;var X=require("uuid"),St=async()=>{let e=await o.get("id");return(0,X.validate)(e)||(e=(0,X.v4)(),await o.set("id",e)),e},O=St;var Nt=async e=>{let{path:t,method:r,params:i}=e;if(!e||!t||!r||!i&&r==="POST")throw new Error("Missing endpoint or method");let n=E.getInstance().getApiEndpoint();n+=t;let s=E.getInstance().getApiKey();if(r==="GET"){let a=new URLSearchParams({...i,version:W(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await O()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});n+=`?${a.toString()}`}else r==="POST"&&(i={...i,version:W(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await O()||void 0,walletAddress:i?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(n,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(i):void 0})).json()},I=Nt;var Ct=async({walletAddress:e,cashbackUrl:t,lastActivation:r,timeSinceLastActivation:i})=>{let n={walletAddress:e};return await o.get("disableReminders")&&(n.disableReminders=!0),r&&(n.lastActivation=r),i&&(n.timeSinceLastActivation=i),t&&(n.cashbackUrl=t),await I({path:"/check/notification",method:"POST",params:n})},Ue=Ct;var Rt=(e,t,r)=>{r=r||5;let i=1e3;return new Promise((n,s)=>{let l=d=>{chrome.tabs.get(e,a=>{if(chrome.runtime.lastError){n(null);return}chrome.tabs.sendMessage(e,{...t,from:"bringweb3"},c=>{chrome.runtime.lastError?d<r-1?setTimeout(()=>l(d+1),i*Math.pow(2,d)):n(null):n(c||null)})})};l(0)})},x=Rt;var Ut=async e=>{let t=await o.get("walletAddress");try{if(!e){let i=await chrome.tabs.query({active:!0,currentWindow:!0});if(!i||!i[0]||!i[0].id)return t;e=i[0].id}let r=await x(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await o.set("walletAddress",t))}catch{}return t},R=Ut;var Mt=async(e,t,r,i=!1)=>{let n={showNotification:!1,token:"",iframeUrl:""},s=Date.now(),l=await o.get("notificationCheck");if(!i&&v(l,s))return n;let d=t?await R(t):await o.get("walletAddress"),a=await o.get("lastActivation"),c=a?s-a:void 0,m=await Ue({walletAddress:d,cashbackUrl:r,lastActivation:a,timeSinceLastActivation:c});await o.set("notificationCheck",[s,s+m.nextCall]);let u={showNotification:m.showNotification,token:m.token,iframeUrl:m.iframeUrl,expiration:[s,s+m.expiration]};return u.showNotification&&e&&await Promise.all([o.set("notification",u),o.remove("lastActivation")]),u},U=Mt;var kt=e=>e?chrome.runtime.getURL(e):"",M=kt;var Lt=async e=>{let t=E.getInstance().getWhitelistEndpoint(),r={path:"/domains",method:"GET"};r.params={},t&&(r.params.whitelist=encodeURIComponent(t)),e&&(r.params.trigger=e);let i=await I(r);return i.relevantDomains=_(i.relevantDomains),i.postPurchaseUrls=_(i.postPurchaseUrls),i},Me=Lt;var ke=e=>{if(e===void 0)return"undefined";if(e===null)return"null";if(typeof e=="string")return`"${e}"`;if(typeof e=="number")return Number.isNaN(e)?"NaN":String(e);if(typeof e=="boolean")return String(e);if(Array.isArray(e))return`[${e.map(t=>t===void 0?"undefined":t===null?"null":ke(t)).join(", ")}]`;if(typeof e=="object")try{return JSON.stringify(e,(t,r)=>r===void 0?"undefined":Number.isNaN(r)?"NaN":r)}catch{return`{object: ${Object.prototype.toString.call(e)}}`}return String(e)},k=ke;var Le=async()=>{try{let e=E.getInstance().getWhitelistEndpoint();if(!e)return[];let t=await fetch(e,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!t.ok)throw new Error("Failed to fetch whitelist");let r=await t.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r=J(r),r}catch(e){return console.error("Error fetching whitelist:",e),[]}};var Z=async()=>{let e=await o.get("relevantDomainsCheck"),t=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),i=E.getInstance().getWhitelistEndpoint(),n=null,s=Date.now();if(t?t instanceof Uint8Array?e?Array.isArray(e)?e.length!==2?n=`invalid domains timestamp check format__length: ${e.length} - value: ${k(e)}`:e[0]>=s?n=`cache expired - range start is bigger than Date.now()__value: ${k(e)}, now: ${s}`:s>=e[1]?n="cache expired - range end is smaller than Date.now()":i&&(!r?.length||!(r instanceof Uint8Array))?n="missing whitelist data":V(e,s)&&(n=`cache expired - range is expired__range: ${k(e)}, now: ${s}`):n=`invalid domains timestamp check format - not an array__value: ${k(e)}`:n=`no domains timestamp check found__value: ${k(e)}`:n="domains list isn't an Uint8Array":n="no domains in cache",!n)return t;let l=await Me(n),{nextUpdateTimestamp:d,relevantDomains:a,postPurchaseUrls:c}=l;r=await Le();let m=[o.set("relevantDomains",a),o.set("relevantDomainsCheck",[s,s+d]),o.set("postPurchaseUrls",c)];return r&&m.push(o.set("redirectsWhitelist",r)),await Promise.all(m),a};var $t=async e=>{try{if(!E.getInstance().getWhitelistEndpoint())return!0;let r=await o.get("redirectsWhitelist");if((!(r instanceof Uint8Array)||!r?.length)&&(await Z(),r=await o.get("redirectsWhitelist")),!r?.length)return!1;let i=P(e),{matched:n}=D(r,i);return n}catch{return console.error("Invalid URL:",e),!1}},ee=$t;var Wt=async e=>{let t=Array.isArray(e);t?e.forEach(r=>r.category=r.category||"system"):e.category=e?.category||"system",await I({path:"/analytics",method:"POST",params:t?{events:e}:e})},L=Wt;var Ft=async(e,t,r,i)=>{let s=(await chrome.tabs.query({})).map(m=>m.id).filter(m=>m&&m!==t),l=[],d=await O(),a=await R(),c=s.map(m=>x(m,{action:"CLOSE_POPUP",reason:"already_activated",path:i||"/",domain:e},2).then(u=>{u.status==="success"&&l.push({type:"popup_auto_close",location:u.location,flowId:u.flowId,closer:r,domain:e,userId:d,walletAddress:a})}).catch(()=>{}));await Promise.all(c),l.length&&await L(l)},$e=Ft;var Vt=async(e,t,r,i,n,s,l,d,a,c,m)=>{let u=Date.now(),f=t===chrome.runtime.id;if(f){let g=[o.set("lastActivation",u)];r==="portal"&&g.push(o.set("portalRelevantDomains",J([e]))),await Promise.all(g)}e&&C(e,s||864e5,{iframeUrl:d,token:a,flowId:c},f?"activated":"quiet"),$e(e,l||-1,t),l&&m&&await ee(m)&&chrome.tabs.update(l,{url:m}),await U(n,void 0,M(i),f)},G=Vt;var We="optOutDomains",jt=async(e,t)=>{if(!e)return;let r=await o.get(We);(typeof r!="object"||r===null)&&(r={});let i=Date.now(),n=i+t;r[e]=[i,n],await o.set(We,r)},Fe=jt;var Ve=e=>{e&&chrome.tabs.create({url:e})};var je=async e=>{if(e<0)return await o.remove("optOut"),{isOptedOut:!1};{let t=Date.now();return await o.set("optOut",[t,t+e]),{isOptedOut:!0}}},Ge=async()=>{let e=await o.get("optOut");return{isOptedOut:v(e)}};var Gt=(e,t)=>{chrome.runtime.onMessage.addListener((r,i,n)=>{if(r?.from!=="bringweb3")return;let{action:s}=r,l=r.source||"popup";switch(s){case"ACTIVATE":{let{domain:a,extensionId:c,time:m,redirectUrl:u,iframeUrl:f,token:p,flowId:g}=r;return G(a,c,l,e,t,m,i.tab?.id,f,p,g,u).then(()=>n()),!0}case"PORTAL_ACTIVATE":{let{domain:a,extensionId:c,time:m,iframeUrl:u,token:f,flowId:p}=r;return G(a,c,l,e,t,m,i.tab?.id,u,f,p).then(()=>n()),!0}case"GET_OPT_OUT":return Ge().then(a=>n(a)),!0;case"OPT_OUT":{let{time:a}=r;return je(a).then(c=>n(c)),!0}case"OPT_OUT_SPECIFIC":{let{domain:a,time:c}=r;return Fe(a,c).then(m=>n(m)),!0}case"GET_POPUP_ENABLED":return o.get("popupEnabled").then(a=>n({isPopupEnabled:a})),!0;case"SET_POPUP_ENABLED":{let{isPopupEnabled:a}=r;return o.set("popupEnabled",a).then(()=>{n({isPopupEnabled:a})}).catch(c=>{console.error("Error setting popup enabled:",c),n({error:"Failed to set popup enabled state"})}),!0}case"CLOSE":{let{time:a,domain:c}=r;return c&&(C(c,a),n({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:a}=r;return a?o.set("walletAddress",a).then(()=>U(t,void 0,M(e),!0).then(()=>n(a))):o.remove("walletAddress").then(()=>n({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>n({message:"notification erased successfully"})),!0;case"OPEN_CASHBACK_PAGE":let{url:d}=r;return Ve(d||e),n({message:"cashback page opened successfully"}),!0;case"STOP_REMINDERS":return o.set("disableReminders",!0).then(()=>n({message:"stopped reminders successfully"})),!0;default:return console.warn(`Bring unknown action: ${s}`),!0}})},Ke=Gt;var Kt=async({body:e})=>await I({path:"/check/popup",method:"POST",params:e}),Be=Kt;var Bt=["http://","https://","www.","www1.","www2."],qt=e=>{if(!e)return"";for(let t of Bt)e.startsWith(t)&&(e=e.replace(t,""));return e},qe=qt;var Ht=["www.","www1.","www2."],de={matched:!1,match:""},Qt=async e=>{let t=null;try{t=new URL(e)}catch{try{t=new URL(`https://${e}`)}catch{return de}}let{hostname:r,pathname:i}=t;for(let a of Ht)r=r.replace(a,"");i.endsWith("/")||(i+="/");let n=r+i,s=await o.get("postPurchaseUrls");if(!s||!s.length||!(s instanceof Uint8Array))return de;let{matched:l,match:d}=D(s,n,!0,!0);return l?(await L({type:"thank_you_page",page:e,entry:d}).catch(()=>{}),{matched:l,match:d}):de},He=Qt;var Jt=async e=>{let t=await o.get("quietDomains")||{},r="new",i={};if(t[e]){let{time:n}=t[e];v(n,void 0,{maxRange:60*864e5})?(r=t[e].phase||"quiet",i=t[e].payload||{},r==="activated"&&(t[e].phase="quiet",t[e].payload&&delete t[e].payload,await o.set("quietDomains",t))):(delete t[e],await o.set("quietDomains",t))}return{phase:r,payload:i}},Qe=Jt;var Yt=["www.","www1.","www2."],zt=async e=>{let t=await Z(),r=await o.get("portalRelevantDomains"),i={matched:!1,match:"",phase:void 0};if(!e||!t||!t.length||!(t instanceof Uint8Array))return i;let n=null;try{n=new URL(e)}catch{try{n=new URL(`https://${e}`)}catch{return i}}let{hostname:s,pathname:l}=n,d=s+l;for(let m of Yt)d=d.replace(m,"");if(r){let m=D(r,d);if(m.matched)return await o.remove("portalRelevantDomains"),m}let{matched:a,match:c}=D(t,d);return a?{matched:a,match:c}:i},Je=zt;var Ye=async(e,t,r)=>{await x(e,{action:"INJECT",page:"notification",token:t.token,iframeUrl:t.iframeUrl,userId:await O(),domain:r})},Xt=async(e,t,r,i,n)=>{let s=await o.get("notification"),l=Date.now(),d=s?.expiration;if(V(d,l))await o.remove("notification");else if(s)return await Ye(e,s,r);let a=await U(i,e,M(t));a.showNotification&&(i&&await Ye(e,a,r),n&&n())},ue=Xt;var Zt=(e,t,r)=>{chrome.tabs.onUpdated.addListener(async(i,n,s)=>{if(!n.url||!s?.url?.startsWith("http"))return;let l=qe(s.url);if(!await o.get("popupEnabled"))return;await He(s.url);let{matched:a,match:c}=await Je(s.url);if(!a){await ue(i,e,l,t,r);return}let{phase:m,payload:u}=await Qe(c);if(m==="new"){let B=Date.now(),te=await o.get("optOut");if(v(te,B))return;await o.remove("optOut");let q=await o.get("optOutDomains");if(q&&v(q[c],B))return}else if(m==="activated"){let B=await O(),{iframeUrl:te,token:q}=u||{},rr=await x(i,{action:"INJECT",iframeUrl:te,token:q,domain:l,userId:B,page:m});return}else if(m==="quiet"){await ue(i,e,l,t,r);return}let f=await R(i),{token:p,isValid:g,iframeUrl:h,networkUrl:w,flowId:y,time:$=864e5,portalReferrers:K}=await Be({body:{domain:c,phase:m,url:s.url,address:f}});if(g===!1){C(c,$);return}if(!await ee(w))return;let fe=await O(),S=await x(i,{action:"INJECT",token:p,domain:l,iframeUrl:h,userId:fe,referrers:K,page:m==="new"?"":m,flowId:y});if(S?.action)switch(S.action){case"activate":G(c,chrome.runtime.id,"popup",e,$,i);break;default:console.error(`Unknown action: ${S.action}`);break}S?.status!=="success"&&L({type:"no_popup",userId:fe,walletAddress:f,details:{url:s.url,match:c,iframeUrl:h,reason:S?.message,status:S?.status},flowId:y})})},ze=Zt;var pe=he,er=async({identifier:e,apiEndpoint:t,cashbackPagePath:r,whitelistEndpoint:i,isEnabledByDefault:n=!0,showNotifications:s=!0,notificationCallback:l})=>{if(!e||!t)throw new Error("Missing configuration");if(pe&&console.log({ENDPOINT:pe}),!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");let d=E.getInstance();d.setApiEndpoint(pe||t),d.setWhitelistEndpoint(i||""),d.setApiKey(e),o.initializeDebugCache(),await o.get("popupEnabled")===void 0&&await o.set("popupEnabled",n),await Ce(),Ke(r,s),ze(r,s,l)},Xe=er;var Ze=()=>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})})}),et=e=>new Promise((t,r)=>{let i=e?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?t({isTurnedOff:n.isOptedOut}):r("No response received")})});var tt=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_POPUP_ENABLED"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e(r)})}),rt=e=>new Promise((t,r)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"SET_POPUP_ENABLED",isPopupEnabled:e},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?t({isPopupEnabled:i.isPopupEnabled}):r("No response received")})});0&&(module.exports={bringInitBackground,bringInitContentScript,getPopupEnabled,getTurnOff,setPopupEnabled,setTurnOff});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- var Pt=t=>{let e=new URLSearchParams,{query:r,prefix:i}=t;return Object.entries(r).forEach(([n,a])=>{a&&(i&&(n=`${i}_${n}`),n==="url"?e.append(n,encodeURIComponent(a)):e.append(n,a))}),e.toString()},$=Pt;var q={name:"@bringweb3/chrome-extension-kit",version:"1.4.4",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 _t=()=>q.version,S=_t;var xt=({query:t,theme:e,themeMode:r,text:i,iframeUrl:n,page:a,switchWallet:m})=>{let d=chrome.runtime.id,c=`bringweb3-iframe-${d}`,u=document.getElementById(c),l=process?.env?.IFRAME_URL?`${process.env.IFRAME_URL}${a?"/"+a:""}`:n;if(u)return u;let f=$({query:{...t,extensionId:d,v:S(),themeMode:r,textMode:i,switchWallet:String(m)}}),E=e?`&${$({query:e,prefix:"t"})}`:"",s=document.createElement("iframe");return s.id=c,s.src=encodeURI(`${l}?${f}${E}`),s.setAttribute("sandbox","allow-scripts allow-same-origin"),s.style.position="fixed",s.scrolling="no",s.style.overflow="hidden",s.style.width="1px",s.style.height="1px",s.style.right="8px",s.style.borderRadius="10px",s.style.border="none",s.style.cssText+="z-index: 99999999999999 !important;",e?.popupShadow&&(s.style.boxShadow=e.popupShadow),document.documentElement.appendChild(s),s},Q=xt;var vt=(t,e)=>{!t||!e||!Object.keys(e).length||Object.entries(e).forEach(([r,i])=>{r in t.style&&(t.style[r]=i)})},J=vt;var Dt=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")},Y=Dt;var h={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",OPT_OUT_SPECIFIC:"OPT_OUT_SPECIFIC",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE"},St=[h.ACTIVATE],It=({event:t,iframeEl:e,promptLogin:r})=>{if(!t?.data)return;let{from:i,action:n,style:a,keyFrames:m,time:d,extensionId:c,url:u,domain:l,redirectUrl:f}=t.data;if(i==="bringweb3"&&!(c!==chrome.runtime.id&&!St.includes(n)))switch(n){case h.OPEN:J(e,a);break;case h.CLOSE:e&&e.parentNode?.removeChild(e),d&&chrome.runtime.sendMessage({action:n,time:d,domain:l,from:"bringweb3"});break;case h.PROMPT_LOGIN:r();break;case h.ACTIVATE:chrome.runtime.sendMessage({action:n,from:"bringweb3",domain:l,extensionId:c,time:d,redirectUrl:f});break;case h.OPT_OUT:chrome.runtime.sendMessage({action:n,time:d,from:"bringweb3"});break;case h.OPT_OUT_SPECIFIC:chrome.runtime.sendMessage({action:n,domain:l,time:d,from:"bringweb3"});break;case h.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:n,from:"bringweb3"});case h.ADD_KEYFRAMES:Y(m);break;case h.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:n,url:u,from:"bringweb3"});break;default:break}},z=It;var X=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})},Ct=({walletAddressListeners:t,walletAddressUpdateCallback:e,getWalletAddress:r,iframeEl:i})=>{if(e)e(()=>X({iframeEl:i,getWalletAddress:r}));else if(t)for(let n=0;n<t.length;n++){let a=t[n];a&&window.addEventListener(a,async()=>X({iframeEl:i,getWalletAddress:r}))}},Z=Ct;var Nt=t=>t.endsWith("/")?t.slice(0,-1):t,I=Nt;var Ut=["www.","www1.","www2."],kt=t=>{for(let r of Ut)t=t.replace(r,"");let e="";try{e=new URL(t).host}catch{e=new URL(`https://${t}`).host}return e=I(e),e},P=kt;var F=null,tt=!1,Mt=async({getWalletAddress:t,promptLogin:e,walletAddressListeners:r,walletAddressUpdateCallback:i,lightTheme:n,darkTheme:a,theme:m,text:d,switchWallet:c=!1})=>{if(window.self===window.top){if(!t||!e||!r?.length&&typeof i!="function")throw new Error("Missing configuration");Z({walletAddressListeners:r,walletAddressUpdateCallback:i,getWalletAddress:t,iframeEl:F}),window.addEventListener("message",u=>z({event:u,iframeEl:F,promptLogin:e})),chrome.runtime.onMessage.addListener((u,l,f)=>{if(u?.from!=="bringweb3")return;let{action:E}=u;switch(E){case"GET_WALLET_ADDRESS":return t().then(s=>f({status:"success",walletAddress:s})).catch(s=>f({status:"success",walletAddress:void 0})),!0;case"INJECT":try{let{referrer:s}=document,g=u.portalReferrers||[];if(P(location.href)!==P(u.domain))return f({status:"failed",message:"Domain already changed"}),!0;if(tt)return f({status:"failed",message:"iframe already open"}),!0;if(s&&g.includes(P(s)))return f({status:"failed",message:`already activated by ${P(s)}`,action:"activate"}),!0;let{token:y,iframeUrl:v,userId:b}=u,D={token:y};return b&&(D.userId=b),F=Q({query:D,iframeUrl:v,theme:m==="dark"?a:n,themeMode:m||"light",text:d,switchWallet:c,page:u.page}),tt=!0,f({status:"success"}),!0}catch(s){return s instanceof Error?f({status:"failed",message:s.message}):f({status:"failed",message:String(s)}),!0}default:console.error(`Unknown action: ${E}`);break}})}},Rt=Mt;var et=t=>{t&&chrome.tabs.create({url:t})};var p=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 Lt=async(t,e)=>new Promise((r,i)=>{chrome.storage.local.set({[`bring_${t}`]:e},()=>{chrome.runtime.lastError?i(chrome.runtime.lastError):r()})}),Wt=async t=>new Promise((e,r)=>{chrome.storage.local.get([`bring_${t}`],i=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(i[`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:Lt,get:Wt,remove:$t};import{v4 as Ft}from"uuid";var jt=async()=>{let t=await o.get("id");return t||(t=Ft(),o.set("id",t)),t},T=jt;var Kt=async t=>{let{path:e,method:r,params:i}=t;if(!t||!e||!r||!i&&r==="POST")throw new Error("Missing endpoint or method");let n=p.getInstance().getApiEndpoint();n+=e;let a=p.getInstance().getApiKey();if(r==="GET"){let c=new URLSearchParams({...i,version:S(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await T()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});n+=`?${c.toString()}`}else r==="POST"&&(i={...i,version:S(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await T()||void 0,walletAddress:i?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(n,{method:r,headers:{"Content-Type":"application/json","x-api-key":a},body:r==="POST"?JSON.stringify(i):void 0})).json()},A=Kt;var Gt=async({body:t})=>await A({path:"/check/popup",method:"POST",params:t}),rt=Gt;var Bt=["www.","www1.","www2."],Vt=t=>{if(!t)return"";t=t.split("://").reverse()[0]||"";for(let e of Bt)t.startsWith(e)&&(t=t.replace(e,""));return t},nt=Vt;var it="quietDomains",Ht=async(t,e)=>{let r=await o.get(it);(typeof r!="object"||r===null)&&(r={});let i=Date.now(),n=i+e;r[t]=[i,n],o.set(it,r)},C=Ht;var qt=async({walletAddress:t,cashbackUrl:e,lastActivation:r,timeSinceLastActivation:i})=>{let n={walletAddress:t};return r&&(n.lastActivation=r),i&&(n.timeSinceLastActivation=i),e&&(n.cashbackUrl=e),await A({path:"/check/notification",method:"POST",params:n})},ot=qt;var Qt=(t,e)=>new Promise((n,a)=>{let m=d=>{chrome.tabs.get(t,c=>{if(chrome.runtime.lastError){n(null);return}chrome.tabs.sendMessage(t,{...e,from:"bringweb3"},u=>{chrome.runtime.lastError?d<4?setTimeout(()=>m(d+1),1e3*Math.pow(2,d)):n(null):n(u||null)})})};m(0)}),x=Qt;var Jt=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 x(t,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&e!==r?.walletAddress&&(e=r?.walletAddress,await o.set("walletAddress",e))}catch{}return e},k=Jt;var Yt=t=>{if(!t||!Array.isArray(t)||t.length!==2)return!1;let[e,r]=t;return typeof e=="number"&&typeof r=="number"&&e<=r},N=(t,e)=>{if(!Yt(t))return!0;let[r,i]=t;return e=e??Date.now(),e<r||e>i},O=(t,e)=>!N(t,e);var zt=async(t,e)=>{let r={showNotification:!1,token:"",iframeUrl:""},i=Date.now(),n=await o.get("notificationCheck");if(O(n,i))return r;let a=t?await k(t):await o.get("walletAddress");if(!a)return r;let m=await o.get("lastActivation"),d=m?i-m:void 0,c=await ot({walletAddress:a,cashbackUrl:e,lastActivation:m,timeSinceLastActivation:d});o.set("notificationCheck",[i,i+c.nextCall]);let u={showNotification:c.showNotification,token:c.token,iframeUrl:c.iframeUrl,expiration:[i,i+c.expiration]};return u.showNotification&&await o.set("notification",u),u},M=zt;var Xt=t=>t?chrome.runtime.getURL(t):"",R=Xt;var Zt=async t=>{let e=p.getInstance().getWhitelistEndpoint(),r={path:"/domains",method:"GET"};return r.params={},e&&(r.params.whitelist=encodeURIComponent(e)),t&&(r.params.trigger=t),await A(r)},st=Zt;var at=t=>{if(t===void 0)return"undefined";if(t===null)return"null";if(typeof t=="string")return`"${t}"`;if(typeof t=="number")return Number.isNaN(t)?"NaN":String(t);if(typeof t=="boolean")return String(t);if(Array.isArray(t))return`[${t.map(e=>e===void 0?"undefined":e===null?"null":at(e)).join(", ")}]`;if(typeof t=="object")try{return JSON.stringify(t,(e,r)=>r===void 0?"undefined":Number.isNaN(r)?"NaN":r)}catch{return`{object: ${Object.prototype.toString.call(t)}}`}return String(t)},w=at;var ct=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 U=async()=>{let t=await o.get("relevantDomainsCheck"),e=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),i=p.getInstance().getWhitelistEndpoint(),n=null,a=Date.now();if(e?Array.isArray(e)?t?Array.isArray(t)?t.length!==2?n=`invalid domains timestamp check format__length: ${t.length} - value: ${w(t)}`:t[0]>=a?n=`cache expired - range start is bigger than Date.now()__value: ${w(t)}, now: ${a}`:a>=t[1]?n=`cache expired - range end is smaller than Date.now()__value: ${w(t)}, now: ${a}`:i&&!r?.length?n=`missing whitelist data__endpoint: ${i}, whitelist: ${w(r)}`:N(t,a)&&(n=`cache expired - range is expired__range: ${w(t)}, now: ${a}`):n=`invalid domains timestamp check format - not an array__value: ${w(t)}`:n=`no domains timestamp check found__value: ${w(t)}`:n=`domains list isn't an array__value: ${w(e)}`:n=`no domains in cache__value: ${w(e)}`,!n)return e;let m=await st(n),{nextUpdateTimestamp:d,relevantDomains:c}=m;return o.set("relevantDomains",c),o.set("relevantDomainsCheck",[a,a+d]),r=await ct(),r&&o.set("redirectsWhitelist",r),c};var te=async(t,e)=>{try{let r=p.getInstance().getWhitelistEndpoint();if(r&&!e?.length&&(await U(),e=await o.get("redirectsWhitelist")),!e?.length)return!r;let n=new URL(t).hostname.toLowerCase();return n=n.replace("www.",""),e.includes(n)?!0:e.some(a=>{if(a.startsWith("*.")){let m=a.slice(2);return n.endsWith(m)}return!1})}catch{return console.error("Invalid URL:",t),!1}},L=te;var ee=async(t,e,r,i,n,a)=>{let m=Date.now();if(e===chrome.runtime.id&&await o.set("lastActivation",m),t&&C(t,i||864e5),n&&a){let d=await o.get("redirectsWhitelist");await L(a,d)&&chrome.tabs.update(n,{url:a})}await M(void 0,R(r))},j=ee;var mt=async t=>{if(t<0)return await o.remove("optOut"),{isOptedOut:!1};{let e=Date.now();return await o.set("optOut",[e,e+t]),{isOptedOut:!0}}},lt=async()=>{let t=await o.get("optOut");return{isOptedOut:O(t)}};var ut=async(t,e,r)=>{await x(t,{action:"INJECT",page:"notification",token:e.token,iframeUrl:e.iframeUrl,userId:await T(),domain:r})},re=async(t,e,r,i,n)=>{let a=await o.get("notification"),m=Date.now(),d=a?.expiration;if(N(d,m))await o.remove("notification");else if(a)return await ut(t,a,r);let c=await M(t,R(e));c.showNotification&&(i&&await ut(t,c,r),n&&n())},dt=re;var ne=async t=>{t.category=t?.category||"system",await A({path:"/analytics",method:"POST",params:t})},ft=ne;var pt="optOutDomains",ie=async(t,e)=>{if(!t)return;let r=await o.get(pt);(typeof r!="object"||r===null)&&(r={});let i=Date.now(),n=i+e;r[t]=[i,n],o.set(pt,r)},gt=ie;var ht=1,wt=async(t,e)=>{let r=await o.get(t);if(r&&typeof r=="object"){for(let[i,n]of Object.entries(r))typeof n=="number"&&n>e?r[i]=[e,n]:delete r[i];o.set(t,r)}},oe=async()=>{try{let t=Date.now(),e=await o.get("optOut");return e&&typeof e=="number"&&e>t?await o.set("optOut",[t,e]):await o.remove("optOut"),await wt("optOutDomains",t),await wt("quietDomains",t),!0}catch{return!1}},Et=async()=>{(await o.get("migrationVersion")||0)<ht&&await oe()&&await o.set("migrationVersion",ht)};var se=["www.","www1.","www2."],ae=async t=>{let e=await U();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=I(r.pathname);for(let m of se)i=i.replace(m,"");let a=Date.now();for(let m of e){let d=m;m=I(m);let c=!1;m.startsWith("*.")&&(c=!0);let u="/"+m.split("/").slice(1).join("/")||"";if(u!=="/"&&n.startsWith(u)&&(i+=u),i===m||c&&i.endsWith(m.replace("*.",""))){let l=await o.get("quietDomains");return l&&l[m]&&O(l[m])&&l[m][1]<a+60*864e5?"":d}}return""},K={},ce=async({identifier:t,apiEndpoint:e,cashbackPagePath:r,whitelistEndpoint:i,isEnabledByDefault:n=!0,showNotifications:a=!0,notificationCallback:m})=>{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||""),p.getInstance().setApiKey(t),await o.get("popupEnabled")===void 0&&await o.set("popupEnabled",n),await Et(),U(),chrome.runtime.onMessage.addListener((c,u,l)=>{if(c?.from!=="bringweb3")return;let{action:f}=c;switch(f){case"ACTIVATE":{let{domain:s,extensionId:g,time:y,redirectUrl:v}=c;return j(s,g,r,y,u.tab?.id,v).then(()=>l()),!0}case"GET_OPT_OUT":return lt().then(s=>l(s)),!0;case"OPT_OUT":{let{time:s}=c;return mt(s).then(g=>l(g)),!0}case"OPT_OUT_SPECIFIC":{let{domain:s,time:g}=c;return gt(s,g).then(y=>l(y)),!0}case"GET_POPUP_ENABLED":return o.get("popupEnabled").then(s=>l({isPopupEnabled:s})),!0;case"SET_POPUP_ENABLED":{let{isPopupEnabled:s}=c;return o.set("popupEnabled",s).then(()=>{l({isPopupEnabled:s})}).catch(g=>{console.error("Error setting popup enabled:",g),l({error:"Failed to set popup enabled state"})}),!0}case"CLOSE":{let{time:s,domain:g}=c;return g&&(C(g,s),l({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:s}=c;return s?o.set("walletAddress",s).then(()=>l(s)):o.remove("walletAddress").then(()=>l({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>l({message:"notification erased successfully"})),!0;default:return console.warn(`Bring unknown action: ${f}`),!0;case"OPEN_CASHBACK_PAGE":let{url:E}=c;return et(E||r),l({message:"cashback page opened successfully"}),!0}}),chrome.tabs.onUpdated.addListener(async(c,u,l)=>{if(!u.url||!l?.url?.startsWith("http"))return;let f=nt(l.url),E=await o.get("optOut"),s=await o.get("popupEnabled"),g=Date.now();if(!s||O(E,g))return;E&&o.remove("optOut");let y=await o.get("optOutDomains");if(y&&O(y[P(f)],g))return;let v=K[c];if(f===v)return;K[c]=f;let b=await ae(l.url);if(!b||!b.length){await dt(c,r,f,a,m);return}let D=await k(c),{token:bt,isValid:G,iframeUrl:B,networkUrl:yt,flowId:At,portalReferrers:Ot,time:V=864e5}=await rt({body:{domain:b,url:l.url,address:D}});if(!G){G===!1&&C(b,V);return}if(!await L(yt,await o.get("redirectsWhitelist")))return;let H=await T(),_=await x(c,{action:"INJECT",token:bt,domain:f,iframeUrl:B,userId:H,portalReferrers:Ot});if(_?.action)switch(_.action){case"activate":j(b,chrome.runtime.id,r,V,c);break;default:console.error(`Unknown action: ${_.action}`);break}_?.status!=="success"&&ft({type:"no_popup",userId:H,walletAddress:D,details:{url:l.url,match:b,iframeUrl:B,reason:_?.message,status:_?.status},flowId:At})}),chrome.tabs.onRemoved.addListener(c=>delete K[c])},me=ce;var le=()=>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})})}),ue=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")})});var de=()=>new Promise((t,e)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_POPUP_ENABLED"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),e(chrome.runtime.lastError);return}t(r)})}),fe=t=>new Promise((e,r)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"SET_POPUP_ENABLED",isPopupEnabled:t},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?e({isPopupEnabled:i.isPopupEnabled}):r("No response received")})});export{me as bringInitBackground,Rt as bringInitContentScript,de as getPopupEnabled,le as getTurnOff,fe as setPopupEnabled,ue as setTurnOff};
1
+ var ee=e=>{try{switch(e){case"VERSION":return process?.env?.VERSION;case"ENDPOINT":return process?.env?.ENDPOINT;case"IFRAME_URL":return process?.env?.IFRAME_URL;default:return}}catch{return}},ue=ee("VERSION"),pe=ee("ENDPOINT"),te=ee("IFRAME_URL");var Qe=e=>{let t=new URLSearchParams,{query:r,prefix:i}=e;return Object.entries(r).forEach(([n,s])=>{s&&(i&&(n=`${i}_${n}`),n==="url"?t.append(n,encodeURIComponent(s)):t.append(n,s))}),t.toString()},re=Qe;var fe={name:"@bringweb3/chrome-extension-kit",version:"1.5.1",description:"Crypto cashback integration kit for crypto outlets extension",main:"dist/index.js",module:"dist/index.mjs",types:"dist/index.d.ts",license:"MIT",private:!1,publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/Bring-Web3-LTD/chromeExtension.git"},scripts:{watch:"tsup index.ts --env.IFRAME_URL=http://localhost:5173 --env.ENDPOINT=dev --env.VERSION=1.5.0 --format cjs,esm --dts --watch",build:"tsup index.ts --format cjs,esm --dts --minify","build:dev":"tsup index.ts --format cjs,esm --dts --minify --env.ENDPOINT=dev --env.VERSION=1.5.0",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 Ye=()=>ue||fe.version,W=Ye;var ze=({query:e,theme:t,themeMode:r,text:i,iframeUrl:n,page:s,switchWallet:l})=>{let d=chrome.runtime.id,a=`bringweb3-iframe-${d}`,c=document.getElementById(a),m=te?`${te}${s?"/"+s:""}`:n;if(c)return c;let u=re({query:{...e,extensionId:d,v:W(),themeMode:r,textMode:i,switchWallet:String(l)}}),f=t?`&${re({query:t,prefix:"t"})}`:"",p=document.createElement("iframe");return p.id=a,p.src=encodeURI(`${m}?${u}${f}`),p.setAttribute("sandbox","allow-scripts allow-same-origin"),p.style.position="fixed",p.scrolling="no",p.style.overflow="hidden",p.style.width="1px",p.style.height="1px",p.style.right="8px",p.style.borderRadius="10px",p.style.border="none",p.style.cssText+="z-index: 99999999999999 !important;",t?.popupShadow&&(p.style.boxShadow=t.popupShadow),document.documentElement.appendChild(p),p},ge=ze;var Xe=(e,t)=>{!e||!t||!Object.keys(t).length||Object.entries(t).forEach(([r,i])=>{r in e.style&&(e.style[r]=i)})},he=Xe;var Ze=e=>{if(!e||!e.length)return;let t=document.createElement("style");document.head.appendChild(t);let r=t.sheet;r?e.forEach(({name:i,rules:n})=>{r.insertRule(`@keyframes ${i} { ${n} }`,r.cssRules.length)}):console.error("Failed to create stylesheet")},we=Ze;var b={OPEN:"OPEN",CLOSE:"CLOSE",ACTIVATE:"ACTIVATE",PROMPT_LOGIN:"PROMPT_LOGIN",OPT_OUT:"OPT_OUT",OPT_OUT_SPECIFIC:"OPT_OUT_SPECIFIC",ADD_KEYFRAMES:"ADD_KEYFRAMES",ERASE_NOTIFICATION:"ERASE_NOTIFICATION",OPEN_CASHBACK_PAGE:"OPEN_CASHBACK_PAGE",STOP_REMINDERS:"STOP_REMINDERS"},et=[b.ACTIVATE],tt=({event:e,iframeEl:t,promptLogin:r})=>{if(!e?.data)return;let{from:i,action:n,style:s,keyFrames:l,time:d,extensionId:a,url:c,domain:m,redirectUrl:u,iframeUrl:f,token:p,flowId:g,platformName:h}=e.data;if(i==="bringweb3"&&!(a!==chrome.runtime.id&&!et.includes(n)))switch(n){case b.OPEN:he(t,s);break;case b.CLOSE:t&&t.parentNode?.removeChild(t),d&&chrome.runtime.sendMessage({action:n,time:d,domain:m,from:"bringweb3"});break;case b.PROMPT_LOGIN:r();break;case b.ACTIVATE:chrome.runtime.sendMessage({action:n,from:"bringweb3",domain:m,extensionId:a,time:d,redirectUrl:u,iframeUrl:f,token:p,flowId:g,platformName:h});break;case b.OPT_OUT:chrome.runtime.sendMessage({action:n,time:d,from:"bringweb3"});break;case b.OPT_OUT_SPECIFIC:chrome.runtime.sendMessage({action:n,domain:m,time:d,from:"bringweb3"});break;case b.ERASE_NOTIFICATION:chrome.runtime.sendMessage({action:n,from:"bringweb3"});case b.ADD_KEYFRAMES:we(l);break;case b.OPEN_CASHBACK_PAGE:chrome.runtime.sendMessage({action:n,url:c,from:"bringweb3"});break;case b.STOP_REMINDERS:chrome.runtime.sendMessage({action:n,from:"bringweb3"});break;default:break}},Ee=tt;var ye=async({iframeEl:e,getWalletAddress:t})=>{e||(e=document.querySelector(`#bringweb3-iframe-${chrome.runtime.id}`));let r=await t();e?.contentWindow?.postMessage({action:"WALLET_ADDRESS_UPDATE",walletAddress:r},"*"),chrome.runtime.sendMessage({action:"WALLET_ADDRESS_UPDATE",from:"bringweb3",walletAddress:r})},rt=({walletAddressListeners:e,walletAddressUpdateCallback:t,getWalletAddress:r,iframeEl:i})=>{if(t)t(()=>ye({iframeEl:i,getWalletAddress:r}));else if(e)for(let n=0;n<e.length;n++){let s=e[n];s&&window.addEventListener(s,async()=>ye({iframeEl:i,getWalletAddress:r}))}},be=rt;var nt=e=>e.endsWith("/")?e.slice(0,-1):e,H=nt;var it=["www.","www1.","www2."],ot=e=>{for(let r of it)e=e.replace(r,"");let t="";try{t=new URL(e).host}catch{t=new URL(`https://${e}`).host}return t=H(t),t},P=ot;var N=null,ne,ie=!1,Ae=null,st=async({getWalletAddress:e,promptLogin:t,walletAddressListeners:r,walletAddressUpdateCallback:i,lightTheme:n,darkTheme:s,theme:l,text:d,switchWallet:a=!1})=>{if(window.self!==window.top&&H(window.document.location.origin).endsWith("bringweb3.io")){window.addEventListener("message",c=>{if(!c.data||c.data.from!=="bringweb3"||c.data.action!=="PORTAL_ACTIVATE")return;let{action:m,domain:u,extensionId:f,time:p,iframeUrl:g,token:h,platformName:w}=c.data;chrome.runtime.sendMessage({action:m,from:"bringweb3",domain:u,extensionId:f,time:p,iframeUrl:g,token:h,source:"portal",platformName:w})});return}if(!e||!t||!r?.length&&typeof i!="function")throw new Error("Missing configuration");be({walletAddressListeners:r,walletAddressUpdateCallback:i,getWalletAddress:e,iframeEl:N}),window.addEventListener("message",c=>Ee({event:c,iframeEl:N,promptLogin:t})),chrome.runtime.onMessage.addListener((c,m,u)=>{if(c?.from!=="bringweb3")return;let{action:f}=c;switch(f){case"GET_WALLET_ADDRESS":return e().then(p=>u({status:"success",walletAddress:p})).catch(p=>u({status:"success",walletAddress:void 0})),!0;case"CLOSE_POPUP":N&&ne===c.path&&P(location.href)===P(c.domain)?(N.parentNode?.removeChild(N),ie=!1,ne=void 0,u({status:"success",message:"Popup closed",location:window.document.location.href,flowId:Ae})):u({status:"failed",message:"Domain mismatch or iframe not open"});case"INJECT":try{let{referrer:p}=document,g=c.referrers||[];if(P(location.href)!==P(c.domain))return u({status:"failed",message:"Domain already changed"}),!0;if(ie)return u({status:"failed",message:"iframe already open"}),!0;if(!!p&&g.includes(P(p))&&c.page==="")return u({status:"failed",message:`already activated by ${P(p)}`,action:"activate"}),!0;let{token:w,iframeUrl:y,userId:$}=c,K={token:w};return $&&(K.userId=$),N=ge({query:K,iframeUrl:y,theme:l==="dark"?s:n,themeMode:l||"light",text:d,switchWallet:a,page:c.page}),ie=!0,ne=`/${c.page||""}`,Ae=c.flowId,u({status:"success"}),!0}catch(p){return p instanceof Error?u({status:"failed",message:p.message}):u({status:"failed",message:String(p)}),!0}default:console.error(`Unknown action: ${f}`);break}})},at=st;var E=class e{static instance=null;apiEndpoint="";endpoint="";whitelistEndpoint="";apiKey="";constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}setWhitelistEndpoint(t){this.whitelistEndpoint=t}setApiEndpoint(t){switch(this.endpoint=t,t){case"prod":this.apiEndpoint="https://api.bringweb3.io/v1/extension";break;case"sandbox":this.apiEndpoint="https://sandbox-api.bringweb3.io/v1/extension";break;case"dev":this.apiEndpoint="https://dev-api.bringweb3.io/v1/extension";break;default:this.apiEndpoint="https://sandbox-api.bringweb3.io/v1/extension";break}}setApiKey(t){this.apiKey=t}getWhitelistEndpoint(){return this.whitelistEndpoint}getApiEndpoint(){if(!this.apiEndpoint)throw new Error("API endpoint not set. Call setApiEndpoint first.");return this.apiEndpoint}getEndpoint(){if(!this.endpoint)throw new Error("endpoint not set. Call setApiEndpoint first.");return this.endpoint}getApiKey(){if(!this.apiKey)throw new Error("API key not set. Call setApiKey first.");return this.apiKey}};var oe=class{cache=new Map;get(t){let r=this.cache.get(t);return r?r.value:null}set(t,r){this.cache.set(t,{value:r})}delete(t){this.cache.delete(t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}},Oe=oe;var _=e=>{try{return new Uint8Array(atob(e).split("").map(t=>t.charCodeAt(0)))}catch{return null}},Q=e=>btoa(String.fromCharCode(...e)),ct={relevantDomains:{get:_,set:Q},redirectsWhitelist:{get:_,set:Q},portalRelevantDomains:{get:_,set:Q},postPurchaseUrls:{get:_,set:Q}},F=ct;var T=e=>e.split("").reverse().join(""),J=e=>{let t=[];for(let n of e){let s=n.indexOf("/");if(s===-1)t.push(T(n));else{let l=n.substring(0,s),d=n.substring(s),a=T(l);t.push(a+d)}}t.sort();let r=[],i="";for(let n of t){let s=Math.min(i.length,n.length,32),l=0;for(;l<s&&i[l]===n[l];)l++;let d=n.substring(l),a=new TextEncoder().encode(d);if(a.length>0){let c=Math.min(...a);if(c<33)throw new Error(`Invalid rem byte: ${c}`)}r.push(l),r.push(...a),i=n}return new Uint8Array(r)},Pe=e=>{let t=[],r=0,i="",n=0;for(;r<e.length;){let s=e[r];r++;let l=r;for(;l<e.length;){let u=e[l];if(u===void 0||u<33)break;l++}let d=new TextDecoder().decode(e.slice(r,l)),a=i.substring(0,s)+d,c=a.indexOf("/"),m;if(c===-1)m=T(a);else{let u=a.substring(0,c),f=a.substring(c);m=T(u)+f}t.push(m),i=a,r=l}return t},D=(e,t,r=!1,i=!1)=>{let n=t.indexOf("/"),s=n===-1?t:t.substring(0,n),l=n===-1?"":t.substring(n+1),d=T(s),a=0,c="";for(;a<e.length;){let m=e[a];if(m===void 0||m<0||m>32)throw new Error(`Invalid LCP marker: ${m}`);a++;let u=a;for(;u<e.length;){let y=e[u];if(y===void 0||y<33)break;u++}let f=new TextDecoder().decode(e.slice(a,u));a=u;let p=c.substring(0,m)+f;c=p;let g=p.indexOf("/"),h,w;if(g===-1)h=T(p),w="";else{let y=p.substring(0,g);h=T(y),w=p.substring(g+1)}if(h===s||h.startsWith("*.")&&(s.endsWith("."+h.substring(2))||s===h.substring(2))){if(l===""&&w==="")return{matched:!0,match:`${h}${g!==-1?`/${w}`:""}`};if(r){let y=`^${w}${i?"$":""}`;if(new RegExp(y).test(l))return{matched:!0,match:`${h}${g!==-1?`/${w}`:""}`}}else if(i&&l===w||!i&&l.startsWith(w))return{matched:!0,match:`${h}${g!==-1?`/${w}`:""}`}}if(T(h)>d)return{matched:!1,match:void 0}}return{matched:!1,match:void 0}};var se=e=>{if(!e||!Array.isArray(e)||e.length!==2)return!1;let[t,r]=e;return typeof t=="number"&&typeof r=="number"&&t<=r},V=(e,t,r)=>{if(!se(e))return!0;let[i,n]=e;return t=t??Date.now(),t<i||t>n||r?.maxRange!==void 0&&n-i>r.maxRange},v=(e,t,r)=>!V(e,t,r);var Y="bring_",A=new Oe,ve=async(e,t,r=!0)=>(r&&A.set(e,t),new Promise((i,n)=>{F[e]?.set&&(t=F[e].set(t)),chrome.storage.local.set({[`${Y}${e}`]:t},()=>{chrome.runtime.lastError?n(chrome.runtime.lastError):i()})})),ae=async(e,t=!0)=>{if(t){let r=A.get(e);if(r!==null)return r}return new Promise((r,i)=>{chrome.storage.local.get([`${Y}${e}`],n=>{if(chrome.runtime.lastError)i(chrome.runtime.lastError);else{let s=n[`${Y}${e}`];s&&F[e]?.get&&(s=F[e].get(s)),t&&s!==void 0&&A.set(e,s),r(s)}})})},xe=async e=>(A.delete(e),new Promise((t,r)=>{chrome.storage.local.remove([`${Y}${e}`],()=>{chrome.runtime.lastError?r(chrome.runtime.lastError):t()})})),lt=()=>{A.clear()},mt=e=>{A.delete(e)},dt=()=>A.getStats(),ut=()=>{if(!(typeof globalThis>"u"))try{globalThis.bringCache={clear:()=>A.clear(),stats:()=>A.getStats(),get:async e=>await ae(e),getReadable:async e=>{let t=await ae(e);return t instanceof Uint8Array?t=Pe(t):se(t)&&(t=`[${new Date(t[0]).toLocaleString("en-GB")} - ${new Date(t[1]).toLocaleString("en-GB")}] Total of ${(t[1]-t[0])/1e3/60} minutes`),t},set:async(e,t)=>await ve(e,t),invalidate:e=>A.delete(e),delete:async e=>await xe(e)}}catch(e){console.warn("Failed to initialize debug cache:",e)}},o={set:ve,get:ae,remove:xe,clearCache:lt,invalidateCache:mt,getCacheStats:dt,initializeDebugCache:ut};import{v4 as pt,validate as ft}from"uuid";var Te=2,Ie=async(e,t)=>{let r=await o.get(e);if(r&&typeof r=="object"){for(let[i,n]of Object.entries(r))typeof n=="number"&&n>t?r[i]=[t,n]:delete r[i];await o.set(e,r)}},gt=async()=>{try{let e=Date.now(),t=await o.get("optOut");return t&&typeof t=="number"&&t>e?await o.set("optOut",[e,t]):await o.remove("optOut"),await Ie("optOutDomains",e),await Ie("quietDomains",e),!0}catch{return!1}},ht=async()=>{try{let e=await o.get("quietDomains");if(e&&typeof e=="object"){for(let[r,i]of Object.entries(e))Array.isArray(i)&&(e[r]={time:i,phase:"quiet"});await o.set("quietDomains",e)}let t=await o.get("id");return ft(t||"")||(t=pt(),await o.set("id",t)),!0}catch{return!1}},_e=async()=>{let e=await o.get("migrationVersion")||0;e<1&&await gt()&&await o.set("migrationVersion",1),e<Te&&await ht()&&await o.set("migrationVersion",Te)};var De="quietDomains",wt=async(e,t,r,i)=>{let n=await o.get(De);(typeof n!="object"||n===null)&&(n={});let s=Date.now(),l=s+t;n[e]={time:[s,l],phase:i||"quiet"},r&&(n[e].payload=r),await o.set(De,n)},C=wt;import{v4 as Et,validate as yt}from"uuid";var bt=async()=>{let e=await o.get("id");return yt(e)||(e=Et(),await o.set("id",e)),e},O=bt;var At=async e=>{let{path:t,method:r,params:i}=e;if(!e||!t||!r||!i&&r==="POST")throw new Error("Missing endpoint or method");let n=E.getInstance().getApiEndpoint();n+=t;let s=E.getInstance().getApiKey();if(r==="GET"){let a=new URLSearchParams({...i,version:W(),timestamp:Date.now().toString(),opt_out:await o.get("optOut")||0,user_id:await O()||"undefined",wallet_address:await o.get("walletAddress")||"undefined"});n+=`?${a.toString()}`}else r==="POST"&&(i={...i,version:W(),timestamp:Date.now(),optOut:await o.get("optOut")||0,userId:await O()||void 0,walletAddress:i?.walletAddress||await o.get("walletAddress")||void 0});return await(await fetch(n,{method:r,headers:{"Content-Type":"application/json","x-api-key":s},body:r==="POST"?JSON.stringify(i):void 0})).json()},I=At;var Ot=async({walletAddress:e,cashbackUrl:t,lastActivation:r,timeSinceLastActivation:i})=>{let n={walletAddress:e};return await o.get("disableReminders")&&(n.disableReminders=!0),r&&(n.lastActivation=r),i&&(n.timeSinceLastActivation=i),t&&(n.cashbackUrl=t),await I({path:"/check/notification",method:"POST",params:n})},Se=Ot;var Pt=(e,t,r)=>{r=r||5;let i=1e3;return new Promise((n,s)=>{let l=d=>{chrome.tabs.get(e,a=>{if(chrome.runtime.lastError){n(null);return}chrome.tabs.sendMessage(e,{...t,from:"bringweb3"},c=>{chrome.runtime.lastError?d<r-1?setTimeout(()=>l(d+1),i*Math.pow(2,d)):n(null):n(c||null)})})};l(0)})},x=Pt;var vt=async e=>{let t=await o.get("walletAddress");try{if(!e){let i=await chrome.tabs.query({active:!0,currentWindow:!0});if(!i||!i[0]||!i[0].id)return t;e=i[0].id}let r=await x(e,{action:"GET_WALLET_ADDRESS"});r?.walletAddress&&t!==r?.walletAddress&&(t=r?.walletAddress,await o.set("walletAddress",t))}catch{}return t},R=vt;var xt=async(e,t,r,i=!1)=>{let n={showNotification:!1,token:"",iframeUrl:""},s=Date.now(),l=await o.get("notificationCheck");if(!i&&v(l,s))return n;let d=t?await R(t):await o.get("walletAddress"),a=await o.get("lastActivation"),c=a?s-a:void 0,m=await Se({walletAddress:d,cashbackUrl:r,lastActivation:a,timeSinceLastActivation:c});await o.set("notificationCheck",[s,s+m.nextCall]);let u={showNotification:m.showNotification,token:m.token,iframeUrl:m.iframeUrl,expiration:[s,s+m.expiration]};return u.showNotification&&e&&await Promise.all([o.set("notification",u),o.remove("lastActivation")]),u},U=xt;var Tt=e=>e?chrome.runtime.getURL(e):"",M=Tt;var It=async e=>{let t=E.getInstance().getWhitelistEndpoint(),r={path:"/domains",method:"GET"};r.params={},t&&(r.params.whitelist=encodeURIComponent(t)),e&&(r.params.trigger=e);let i=await I(r);return i.relevantDomains=_(i.relevantDomains),i.postPurchaseUrls=_(i.postPurchaseUrls),i},Ne=It;var Ce=e=>{if(e===void 0)return"undefined";if(e===null)return"null";if(typeof e=="string")return`"${e}"`;if(typeof e=="number")return Number.isNaN(e)?"NaN":String(e);if(typeof e=="boolean")return String(e);if(Array.isArray(e))return`[${e.map(t=>t===void 0?"undefined":t===null?"null":Ce(t)).join(", ")}]`;if(typeof e=="object")try{return JSON.stringify(e,(t,r)=>r===void 0?"undefined":Number.isNaN(r)?"NaN":r)}catch{return`{object: ${Object.prototype.toString.call(e)}}`}return String(e)},k=Ce;var Re=async()=>{try{let e=E.getInstance().getWhitelistEndpoint();if(!e)return[];let t=await fetch(e,{method:"GET",cache:"no-store",headers:{"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Pragma:"no-cache"}});if(!t.ok)throw new Error("Failed to fetch whitelist");let r=await t.json();if(!Array.isArray(r))throw new Error("whitelist isn't an array");return r=J(r),r}catch(e){return console.error("Error fetching whitelist:",e),[]}};var z=async()=>{let e=await o.get("relevantDomainsCheck"),t=await o.get("relevantDomains"),r=await o.get("redirectsWhitelist"),i=E.getInstance().getWhitelistEndpoint(),n=null,s=Date.now();if(t?t instanceof Uint8Array?e?Array.isArray(e)?e.length!==2?n=`invalid domains timestamp check format__length: ${e.length} - value: ${k(e)}`:e[0]>=s?n=`cache expired - range start is bigger than Date.now()__value: ${k(e)}, now: ${s}`:s>=e[1]?n="cache expired - range end is smaller than Date.now()":i&&(!r?.length||!(r instanceof Uint8Array))?n="missing whitelist data":V(e,s)&&(n=`cache expired - range is expired__range: ${k(e)}, now: ${s}`):n=`invalid domains timestamp check format - not an array__value: ${k(e)}`:n=`no domains timestamp check found__value: ${k(e)}`:n="domains list isn't an Uint8Array":n="no domains in cache",!n)return t;let l=await Ne(n),{nextUpdateTimestamp:d,relevantDomains:a,postPurchaseUrls:c}=l;r=await Re();let m=[o.set("relevantDomains",a),o.set("relevantDomainsCheck",[s,s+d]),o.set("postPurchaseUrls",c)];return r&&m.push(o.set("redirectsWhitelist",r)),await Promise.all(m),a};var _t=async e=>{try{if(!E.getInstance().getWhitelistEndpoint())return!0;let r=await o.get("redirectsWhitelist");if((!(r instanceof Uint8Array)||!r?.length)&&(await z(),r=await o.get("redirectsWhitelist")),!r?.length)return!1;let i=P(e),{matched:n}=D(r,i);return n}catch{return console.error("Invalid URL:",e),!1}},X=_t;var Dt=async e=>{let t=Array.isArray(e);t?e.forEach(r=>r.category=r.category||"system"):e.category=e?.category||"system",await I({path:"/analytics",method:"POST",params:t?{events:e}:e})},L=Dt;var St=async(e,t,r,i)=>{let s=(await chrome.tabs.query({})).map(m=>m.id).filter(m=>m&&m!==t),l=[],d=await O(),a=await R(),c=s.map(m=>x(m,{action:"CLOSE_POPUP",reason:"already_activated",path:i||"/",domain:e},2).then(u=>{u.status==="success"&&l.push({type:"popup_auto_close",location:u.location,flowId:u.flowId,closer:r,domain:e,userId:d,walletAddress:a})}).catch(()=>{}));await Promise.all(c),l.length&&await L(l)},Ue=St;var Nt=async(e,t,r,i,n,s,l,d,a,c,m)=>{let u=Date.now(),f=t===chrome.runtime.id;if(f){let g=[o.set("lastActivation",u)];r==="portal"&&g.push(o.set("portalRelevantDomains",J([e]))),await Promise.all(g)}e&&C(e,s||864e5,{iframeUrl:d,token:a,flowId:c},f?"activated":"quiet"),Ue(e,l||-1,t),l&&m&&await X(m)&&chrome.tabs.update(l,{url:m}),await U(n,void 0,M(i),f)},G=Nt;var Me="optOutDomains",Ct=async(e,t)=>{if(!e)return;let r=await o.get(Me);(typeof r!="object"||r===null)&&(r={});let i=Date.now(),n=i+t;r[e]=[i,n],await o.set(Me,r)},ke=Ct;var Le=e=>{e&&chrome.tabs.create({url:e})};var $e=async e=>{if(e<0)return await o.remove("optOut"),{isOptedOut:!1};{let t=Date.now();return await o.set("optOut",[t,t+e]),{isOptedOut:!0}}},We=async()=>{let e=await o.get("optOut");return{isOptedOut:v(e)}};var Rt=(e,t)=>{chrome.runtime.onMessage.addListener((r,i,n)=>{if(r?.from!=="bringweb3")return;let{action:s}=r,l=r.source||"popup";switch(s){case"ACTIVATE":{let{domain:a,extensionId:c,time:m,redirectUrl:u,iframeUrl:f,token:p,flowId:g}=r;return G(a,c,l,e,t,m,i.tab?.id,f,p,g,u).then(()=>n()),!0}case"PORTAL_ACTIVATE":{let{domain:a,extensionId:c,time:m,iframeUrl:u,token:f,flowId:p}=r;return G(a,c,l,e,t,m,i.tab?.id,u,f,p).then(()=>n()),!0}case"GET_OPT_OUT":return We().then(a=>n(a)),!0;case"OPT_OUT":{let{time:a}=r;return $e(a).then(c=>n(c)),!0}case"OPT_OUT_SPECIFIC":{let{domain:a,time:c}=r;return ke(a,c).then(m=>n(m)),!0}case"GET_POPUP_ENABLED":return o.get("popupEnabled").then(a=>n({isPopupEnabled:a})),!0;case"SET_POPUP_ENABLED":{let{isPopupEnabled:a}=r;return o.set("popupEnabled",a).then(()=>{n({isPopupEnabled:a})}).catch(c=>{console.error("Error setting popup enabled:",c),n({error:"Failed to set popup enabled state"})}),!0}case"CLOSE":{let{time:a,domain:c}=r;return c&&(C(c,a),n({message:"domain added to quiet list"})),!0}case"WALLET_ADDRESS_UPDATE":{let{walletAddress:a}=r;return a?o.set("walletAddress",a).then(()=>U(t,void 0,M(e),!0).then(()=>n(a))):o.remove("walletAddress").then(()=>n({message:"wallet address removed successfully"})),!0}case"ERASE_NOTIFICATION":return o.remove("notification").then(()=>n({message:"notification erased successfully"})),!0;case"OPEN_CASHBACK_PAGE":let{url:d}=r;return Le(d||e),n({message:"cashback page opened successfully"}),!0;case"STOP_REMINDERS":return o.set("disableReminders",!0).then(()=>n({message:"stopped reminders successfully"})),!0;default:return console.warn(`Bring unknown action: ${s}`),!0}})},Fe=Rt;var Ut=async({body:e})=>await I({path:"/check/popup",method:"POST",params:e}),Ve=Ut;var Mt=["http://","https://","www.","www1.","www2."],kt=e=>{if(!e)return"";for(let t of Mt)e.startsWith(t)&&(e=e.replace(t,""));return e},je=kt;var Lt=["www.","www1.","www2."],ce={matched:!1,match:""},$t=async e=>{let t=null;try{t=new URL(e)}catch{try{t=new URL(`https://${e}`)}catch{return ce}}let{hostname:r,pathname:i}=t;for(let a of Lt)r=r.replace(a,"");i.endsWith("/")||(i+="/");let n=r+i,s=await o.get("postPurchaseUrls");if(!s||!s.length||!(s instanceof Uint8Array))return ce;let{matched:l,match:d}=D(s,n,!0,!0);return l?(await L({type:"thank_you_page",page:e,entry:d}).catch(()=>{}),{matched:l,match:d}):ce},Ge=$t;var Wt=async e=>{let t=await o.get("quietDomains")||{},r="new",i={};if(t[e]){let{time:n}=t[e];v(n,void 0,{maxRange:60*864e5})?(r=t[e].phase||"quiet",i=t[e].payload||{},r==="activated"&&(t[e].phase="quiet",t[e].payload&&delete t[e].payload,await o.set("quietDomains",t))):(delete t[e],await o.set("quietDomains",t))}return{phase:r,payload:i}},Ke=Wt;var Ft=["www.","www1.","www2."],Vt=async e=>{let t=await z(),r=await o.get("portalRelevantDomains"),i={matched:!1,match:"",phase:void 0};if(!e||!t||!t.length||!(t instanceof Uint8Array))return i;let n=null;try{n=new URL(e)}catch{try{n=new URL(`https://${e}`)}catch{return i}}let{hostname:s,pathname:l}=n,d=s+l;for(let m of Ft)d=d.replace(m,"");if(r){let m=D(r,d);if(m.matched)return await o.remove("portalRelevantDomains"),m}let{matched:a,match:c}=D(t,d);return a?{matched:a,match:c}:i},Be=Vt;var qe=async(e,t,r)=>{await x(e,{action:"INJECT",page:"notification",token:t.token,iframeUrl:t.iframeUrl,userId:await O(),domain:r})},jt=async(e,t,r,i,n)=>{let s=await o.get("notification"),l=Date.now(),d=s?.expiration;if(V(d,l))await o.remove("notification");else if(s)return await qe(e,s,r);let a=await U(i,e,M(t));a.showNotification&&(i&&await qe(e,a,r),n&&n())},le=jt;var Gt=(e,t,r)=>{chrome.tabs.onUpdated.addListener(async(i,n,s)=>{if(!n.url||!s?.url?.startsWith("http"))return;let l=je(s.url);if(!await o.get("popupEnabled"))return;await Ge(s.url);let{matched:a,match:c}=await Be(s.url);if(!a){await le(i,e,l,t,r);return}let{phase:m,payload:u}=await Ke(c);if(m==="new"){let B=Date.now(),Z=await o.get("optOut");if(v(Z,B))return;await o.remove("optOut");let q=await o.get("optOutDomains");if(q&&v(q[c],B))return}else if(m==="activated"){let B=await O(),{iframeUrl:Z,token:q}=u||{},Yt=await x(i,{action:"INJECT",iframeUrl:Z,token:q,domain:l,userId:B,page:m});return}else if(m==="quiet"){await le(i,e,l,t,r);return}let f=await R(i),{token:p,isValid:g,iframeUrl:h,networkUrl:w,flowId:y,time:$=864e5,portalReferrers:K}=await Ve({body:{domain:c,phase:m,url:s.url,address:f}});if(g===!1){C(c,$);return}if(!await X(w))return;let de=await O(),S=await x(i,{action:"INJECT",token:p,domain:l,iframeUrl:h,userId:de,referrers:K,page:m==="new"?"":m,flowId:y});if(S?.action)switch(S.action){case"activate":G(c,chrome.runtime.id,"popup",e,$,i);break;default:console.error(`Unknown action: ${S.action}`);break}S?.status!=="success"&&L({type:"no_popup",userId:de,walletAddress:f,details:{url:s.url,match:c,iframeUrl:h,reason:S?.message,status:S?.status},flowId:y})})},He=Gt;var me=pe,Kt=async({identifier:e,apiEndpoint:t,cashbackPagePath:r,whitelistEndpoint:i,isEnabledByDefault:n=!0,showNotifications:s=!0,notificationCallback:l})=>{if(!e||!t)throw new Error("Missing configuration");if(me&&console.log({ENDPOINT:me}),!["prod","sandbox"].includes(t))throw new Error("unknown apiEndpoint");let d=E.getInstance();d.setApiEndpoint(me||t),d.setWhitelistEndpoint(i||""),d.setApiKey(e),o.initializeDebugCache(),await o.get("popupEnabled")===void 0&&await o.set("popupEnabled",n),await _e(),Fe(r,s),He(r,s,l)},Bt=Kt;var qt=()=>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})})}),Ht=e=>new Promise((t,r)=>{let i=e?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?t({isTurnedOff:n.isOptedOut}):r("No response received")})});var Qt=()=>new Promise((e,t)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"GET_POPUP_ENABLED"},r=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),t(chrome.runtime.lastError);return}e(r)})}),Jt=e=>new Promise((t,r)=>{chrome.runtime.sendMessage({from:"bringweb3",action:"SET_POPUP_ENABLED",isPopupEnabled:e},i=>{if(chrome.runtime.lastError){console.error(chrome.runtime.lastError),r(chrome.runtime.lastError);return}i?t({isPopupEnabled:i.isPopupEnabled}):r("No response received")})});export{Bt as bringInitBackground,at as bringInitContentScript,Qt as getPopupEnabled,qt as getTurnOff,Jt as setPopupEnabled,Ht as setTurnOff};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bringweb3/chrome-extension-kit",
3
- "version": "1.4.4",
3
+ "version": "1.5.1",
4
4
  "description": "Crypto cashback integration kit for crypto outlets extension",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -15,8 +15,9 @@
15
15
  "url": "https://github.com/Bring-Web3-LTD/chromeExtension.git"
16
16
  },
17
17
  "scripts": {
18
- "watch": "tsup index.ts --env.IFRAME_URL=http://localhost:5173 --format cjs,esm --dts --watch",
18
+ "watch": "tsup index.ts --env.IFRAME_URL=http://localhost:5173 --env.ENDPOINT=dev --env.VERSION=1.5.0 --format cjs,esm --dts --watch",
19
19
  "build": "tsup index.ts --format cjs,esm --dts --minify",
20
+ "build:dev": "tsup index.ts --format cjs,esm --dts --minify --env.ENDPOINT=dev --env.VERSION=1.5.0",
20
21
  "lint": "tsc",
21
22
  "test": "vitest --coverage",
22
23
  "release": "yarn build && changeset publish"