This commit is contained in:
franklin
2024-07-12 22:00:06 +01:00
commit a222d266bd
823 changed files with 108626 additions and 0 deletions
@@ -0,0 +1,66 @@
const querystring = require("querystring");
const logger = (msg) => {
console.log(`[BGC] ${msg}`);
};
logger("background client up.");
logger("connecting to SSE service...");
const port = querystring.parse(__resourceQuery.slice(1)).port;
const es = new EventSource(`http://localhost:${port}/__server_sent_events__`);
es.addEventListener(
"open",
() => {
logger("SSE service connected!");
},
false
);
es.addEventListener(
"error",
(event) => {
if (event.target.readyState === 0) {
console.error("[BGC] you need to open devServer first!");
} else {
console.error(event);
}
},
false
);
es.addEventListener("background-updated", () => {
logger("received 'background-updated' event from SSE service.");
logger("extension will reload to reload background...");
chrome.runtime.reload(); // reload extension to reload background.
});
es.addEventListener(
"content-scripts-updated",
() => {
logger("received 'content-scripts-updated' event from SSE service.");
chrome.tabs.query({}, (tabs) => {
tabs.forEach((tab) => {
chrome.tabs.sendMessage(
tab.id,
{
from: "backgroundClient",
action: "reload-yourself",
},
(res) => {
if (chrome.runtime.lastError && !res) return;
const { from, action } = res;
if (from === "contentScriptClient" && action === "yes-sir") {
es.close();
logger("extension will reload to update content scripts...");
chrome.runtime.reload();
}
}
);
});
});
},
false
);
@@ -0,0 +1,16 @@
const logger = (msg) => {
console.log(`[CSC] ${msg}`);
};
logger("content script client up.");
chrome.runtime.onMessage.addListener((request, _sender, sendResp) => {
const shouldReload =
request.from === "backgroundClient" && request.action === "reload-yourself";
if (shouldReload) {
sendResp({ from: "contentScriptClient", action: "yes-sir" });
// wait 100ms for extension reload.
logger("page will reload to reload content script...");
setTimeout(() => window.location.reload(), 100);
}
});
+16
View File
@@ -0,0 +1,16 @@
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = "production";
process.env.NODE_ENV = "production";
process.env.ASSET_PATH = "/";
var webpack = require("webpack"),
config = require("../webpack.config");
//delete config.chromeExtensionBoilerplate;
delete config.custom;
config.mode = "production";
webpack(config, function (err) {
if (err) throw err;
});
+5
View File
@@ -0,0 +1,5 @@
// tiny wrapper with default env vars
module.exports = {
NODE_ENV: process.env.NODE_ENV || 'development',
PORT: process.env.PORT || 3000,
};
+9
View File
@@ -0,0 +1,9 @@
import axios from "axios";
const BASE_URL = "https://my-techpassport-dev.caprover.manaknightdigital.com"
export const request = axios.create({
baseURL: BASE_URL
});
+43
View File
@@ -0,0 +1,43 @@
import React from "react";
export const useFetchEmailCampaigns = () => {
const [campaigns, setCampaigns] = useState([]);
const [loading, setLoading] = useState(false);
const fetchData = async () => {
setLoading(true);
const token = "mtp_GbXcgngXzBqeBnc4vXvR";
const url = "/v2/api/tools/email-tracking/";
try {
const response = await request.get(url, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
setLoading(false);
console.log("Data posted successfully:", response.data);
setCampaigns(response?.data?.list);
} catch (error) {
setLoading(false);
if (error.response) {
console.error("Error response:", error.response.data);
console.error("Error status:", error.response.status);
console.error("Error headers:", error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.error("Error request:", error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.error("Error message:", error.message);
}
console.error("Error config:", error.config);
}
};
// useEffect(() => {
// fetchData();
// }, []);
return { campaigns, loading, refetch: fetchData };
};
+170
View File
@@ -0,0 +1,170 @@
// Do this as the first thing so that any code reading it knows the right env.
// process.env.BABEL_ENV = "development";
// process.env.NODE_ENV = "development";
process.env.BABEL_ENV = "production";
process.env.NODE_ENV = "production";
process.env.ASSET_PATH = "/";
const WebpackDevServer = require("webpack-dev-server"),
webpack = require("webpack"),
config = require("../webpack.config"),
env = require("./env"),
path = require("path");
const { custom } = require("../webpack.config");
const debounce = require("lodash").debounce;
const SSEStream = require("ssestream").default;
const customOptions = config.custom;
for (let entryName in config.entry) {
if (customOptions.notHMR.indexOf(entryName) === -1) {
config.entry[entryName] = [
"webpack/hot/dev-server.js",
`webpack-dev-server/client/index.js?hot=true&hostname=localhost&port=${env.PORT}`,
].concat(config.entry[entryName]);
}
}
if (
customOptions.enableBackgroundAutoReload ||
customOptions.enableContentScriptsAutoReload
) {
config.entry["background"] = [
path.resolve(
__dirname,
`autoReloadClients/backgroundClient.js?port=${env.PORT}`
),
].concat(config.entry["background"]);
}
if (customOptions.enableContentScriptsAutoReload) {
config.entry["contentScript"] = [
path.resolve(__dirname, "autoReloadClients/contentScriptClient.js"),
].concat(config.entry["contentScript"]);
}
config.plugins = [new webpack.HotModuleReplacementPlugin()].concat(
config.plugins || []
);
delete config.custom;
const compiler = webpack(config);
const server = new WebpackDevServer(
{
https: false,
hot: false,
client: false,
compress: false, // if set true, server-sent events will not work!
host: "localhost",
port: env.PORT,
static: {
directory: path.join(__dirname, "../build"),
},
devMiddleware: {
publicPath: `http://localhost:${env.PORT}/`,
writeToDisk: true,
},
headers: {
"Access-Control-Allow-Origin": "*",
},
allowedHosts: "all",
// the following option really matters!
setupMiddlewares: (middlewares, devServer) => {
// if auto-reload is not needed, this middleware is not needed.
if (
!customOptions.enableBackgroundAutoReload &&
!customOptions.enableContentScriptsAutoReload
) {
return middlewares;
}
if (!devServer) {
throw new Error("webpack-dev-server is not defined");
}
// imagine you are using app.use(path, middleware) in express.
// in fact, devServer is an express server.
middlewares.push({
path: "/__server_sent_events__", // you can find this path requested by backgroundClient.js.
middleware: (req, res) => {
const sseStream = new SSEStream(req);
sseStream.pipe(res);
sseStream.write("message from webserver.");
let closed = false;
const compileDoneHook = debounce((stats) => {
const { modules } = stats.toJson({ all: false, modules: true });
const updatedJsModules = modules.filter(
(module) =>
module.type === "module" &&
module.moduleType === "javascript/auto"
);
const isBackgroundUpdated = updatedJsModules.some((module) =>
module.nameForCondition.startsWith(
path.resolve(__dirname, "../src/pages/Background")
)
);
const isContentScriptsUpdated = updatedJsModules.some((module) =>
module.nameForCondition.startsWith(
path.resolve(__dirname, "../src/pages/ContentScripts")
)
);
const shouldBackgroundReload =
!stats.hasErrors() &&
isBackgroundUpdated &&
customOptions.enableBackgroundAutoReload;
const shouldContentScriptsReload =
!stats.hasErrors() &&
isContentScriptsUpdated &&
customOptions.enableContentScriptsAutoReload;
if (shouldBackgroundReload) {
sseStream.writeMessage(
{
event: "background-updated",
data: {}, // "data" key should be reserved though it is empty.
},
"utf-8"
);
}
if (shouldContentScriptsReload) {
sseStream.writeMessage(
{
event: "content-scripts-updated",
data: {},
},
"utf-8"
);
}
}, 1000);
const plugin = (stats) => {
if (!closed) {
compileDoneHook(stats);
}
};
// a mini webpack plugin just born!
// this plugin will be triggered after each compilation done.
compiler.hooks.done.tap("extension-auto-reload-plugin", plugin);
res.on("close", () => {
closed = true;
sseStream.unpipe(res);
});
},
});
return middlewares;
},
},
compiler
);
(async () => {
await server.start();
})();
+60
View File
@@ -0,0 +1,60 @@
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
process.env.ASSET_PATH = '/';
var WebpackDevServer = require('webpack-dev-server'),
webpack = require('webpack'),
config = require('../webpack.config'),
env = require('./env'),
path = require('path');
var options = config.chromeExtensionBoilerplate || {};
var excludeEntriesToHotReload = options.notHotReload || [];
for (var entryName in config.entry) {
if (excludeEntriesToHotReload.indexOf(entryName) === -1) {
config.entry[entryName] = [
'webpack/hot/dev-server',
`webpack-dev-server/client?hot=true&hostname=localhost&port=${env.PORT}`,
].concat(config.entry[entryName]);
}
}
config.plugins = [new webpack.HotModuleReplacementPlugin()].concat(
config.plugins || []
);
delete config.chromeExtensionBoilerplate;
var compiler = webpack(config);
var server = new WebpackDevServer(
{
https: false,
hot: false,
client: false,
host: 'localhost',
port: env.PORT,
static: {
directory: path.join(__dirname, '../build'),
},
devMiddleware: {
publicPath: `http://localhost:${env.PORT}/`,
writeToDisk: true,
},
headers: {
'Access-Control-Allow-Origin': '*',
},
allowedHosts: 'all',
},
compiler
);
if (process.env.NODE_ENV === 'development' && module.hot) {
module.hot.accept();
}
(async () => {
await server.start();
})();