You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

58 lines
2.1 KiB

"use strict";
// DSH Memory - background service worker.
// Единственное место, откуда идут HTTP-запросы к локальному мосту (CORS не мешает).
const BRIDGE_BASE = "http://127.0.0.1:8766";
const TOKEN_KEY = "dshmem-bridge-token";
const TIMEOUT_MS = 65000;
async function readToken() {
const v = await chrome.storage.local.get(TOKEN_KEY);
return v && v[TOKEN_KEY] ? String(v[TOKEN_KEY]) : "";
}
async function postTool(payload) {
const token = await readToken();
if (!token) return { ok: false, error: { code: "E_NO_TOKEN", message: "token not configured" } };
const ctrl = new AbortController();
const timer = setTimeout(function () { ctrl.abort(); }, TIMEOUT_MS);
try {
const res = await fetch(BRIDGE_BASE + "/tool", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: "Bearer " + token },
body: JSON.stringify(payload),
signal: ctrl.signal
});
const text = await res.text();
let json = null;
try { json = JSON.parse(text); } catch (e) { json = null; }
if (!json) return { ok: false, error: { code: "E_BAD_RESPONSE", message: text.slice(0, 300) } };
return json;
} catch (e) {
const msg = e && e.message ? e.message : String(e);
return { ok: false, error: { code: "E_NETWORK", message: msg } };
} finally {
clearTimeout(timer);
}
}
async function getHealth() {
const token = await readToken();
if (!token) return { ok: false, error: { code: "E_NO_TOKEN", message: "token not configured" } };
try {
const res = await fetch(BRIDGE_BASE + "/health", { headers: { Authorization: "Bearer " + token } });
return await res.json();
} catch (e) {
const msg = e && e.message ? e.message : String(e);
return { ok: false, error: { code: "E_NETWORK", message: msg } };
}
}
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (!msg || typeof msg !== "object") return false;
if (msg.type === "DSH_BRIDGE_CALL") { postTool(msg.payload).then(sendResponse); return true; }
if (msg.type === "DSH_BRIDGE_HEALTH") { getHealth().then(sendResponse); return true; }
return false;
});
console.log("dsh-memory background ready");