/** * Business-QA module API: anonymize and recontextualize endpoints. * Mount at /v1/business-qa. Used by example page and tooling. */ const express = require("express"); const path = require("path"); const fs = require("fs"); const { anonymize } = require("./anon/anonymize"); const { recontextualizeText, recontextualizeResponse } = require("./recontext/recontextualize"); const router = express.Router(); const CONFIG_DIR = path.join(__dirname, "config"); router.use("/example", express.static(path.join(__dirname, "example"))); /** * Load config by name (e.g. "default" -> config/default.json). * @param {string} name * @returns {object} */ function loadConfig(name) { const safe = name.replace(/[^a-zA-Z0-9-_]/g, "") || "default"; const p = path.join(CONFIG_DIR, `${safe}.json`); if (!fs.existsSync(p)) return {}; try { return JSON.parse(fs.readFileSync(p, "utf8")); } catch (e) { return {}; } } router.get("/config/:name", (req, res) => { const config = loadConfig(req.params.name || "default"); res.status(200).json(config); }); router.post("/anonymize", (req, res) => { const body = req.body || {}; const payload = body.payload; let config = body.config; if (!payload || typeof payload !== "object") { return res.status(400).json({ message: "Missing or invalid payload" }); } if (!config || typeof config !== "object") { config = loadConfig(body.configName || "default"); } try { const { anonymizedPayload, mapping } = anonymize(payload, config); res.status(200).json({ anonymizedPayload, mapping }); } catch (err) { console.error("[business-qa] anonymize error", err); res.status(500).json({ message: "Anonymization failed" }); } }); router.post("/recontextualize", (req, res) => { const body = req.body || {}; const mapping = body.mapping; if (!Array.isArray(mapping)) { return res.status(400).json({ message: "Missing or invalid mapping" }); } if (body.response !== undefined) { try { const response = recontextualizeResponse(body.response, mapping); return res.status(200).json({ response }); } catch (err) { console.error("[business-qa] recontextualize response error", err); return res.status(500).json({ message: "Recontextualization failed" }); } } if (body.text !== undefined) { try { const text = recontextualizeText(body.text, mapping); return res.status(200).json({ text }); } catch (err) { console.error("[business-qa] recontextualize text error", err); return res.status(500).json({ message: "Recontextualization failed" }); } } res.status(400).json({ message: "Provide response or text" }); }); module.exports = { router, loadConfig, anonymize, recontextualizeResponse };