Repository Public
1#!/usr/bin/env node2// Author: Simon-Pierre Boucher — contact@spboucher.ai3// File: Scripts/dev-replay-proxy.mjs4// Description: Development-only reverse proxy in front of the LOCAL dev backend, for the apps' self-test: every request is relayed as is, except5// `POST /api/templates/generate`, which is answered by REPLAYING the recorded stream of a real generation (no AI call, no cost). The template of the6// recording is stored on the dev backend with the caller's own token, so the `done` event names a template that really exists there.7//8// Usage: node Scripts/dev-replay-proxy.mjs (listens on SPMAIL_REPLAY_PORT, default 8822; backend SPMAIL_DEV_PORT, default 8821)9// SPMAIL_REPLAY_MODE=ok (default) | cut (the stream stops before `done`) | error:<code> (an `error` event, e.g. error:ai_refused)10import fs from "node:fs"11import http from "node:http"12import path from "node:path"13import { fileURLToPath } from "node:url"1415const HERE = path.dirname(fileURLToPath(import.meta.url))16const PORT = Number(process.env.SPMAIL_REPLAY_PORT ?? 8822)17const BACKEND = Number(process.env.SPMAIL_DEV_PORT ?? 8821)18const MODE = process.env.SPMAIL_REPLAY_MODE ?? "ok"19const RECORDING = fs.readFileSync(path.join(HERE, "..", "Packages/SPMailCore/Tests/SPMailCoreTests/Resources/generation-stream.sse"), "utf8")20const events = RECORDING.split("\n\n").map((b) => b.trim()).filter(Boolean).map((b) => ({ event: /^event: (.*)$/m.exec(b)?.[1], data: /^data: (.*)$/m.exec(b)?.[1] })).filter((e) => e.event && e.data)21const sleep = (ms) => new Promise((r) => setTimeout(r, ms))2223async function backend(method, url, auth, body) {24 const r = await fetch(`http://127.0.0.1:${BACKEND}${url}`, { method, headers: { authorization: auth, "content-type": "application/json", "x-spmail-client": "native" }, body: JSON.stringify(body) })25 if (!r.ok) throw new Error(`${method} ${url} → ${r.status} ${await r.text()}`)26 return r.json()27}2829async function replay(req, res) {30 let raw = ""31 for await (const c of req) raw += c32 const body = JSON.parse(raw || "{}")33 const auth = req.headers.authorization ?? ""34 res.writeHead(200, { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-store", connection: "keep-alive" })35 const send = (event, data) => res.write(`event: ${event}\ndata: ${typeof data === "string" ? data : JSON.stringify(data)}\n\n`)36 let n = 037 for (const e of events) {38 if (res.destroyed) return39 if (e.event === "start") { send("start", { ...JSON.parse(e.data), revising: !!body.base_template_id }); await sleep(300); res.write(": ping\n\n"); continue }40 if (e.event === "progress") { send("progress", e.data); await sleep(60); if (MODE === "cut" && ++n > 6) { res.destroy(); return }; continue }41 if (e.event !== "done") continue42 if (MODE.startsWith("error:")) { send("error", { code: MODE.slice(6), message: "replayed failure" }); break }43 const rec = JSON.parse(e.data)44 const t = rec.template45 try {46 // the recorded template becomes a real one on the dev backend (a new template, or a new version of the base for a revision)47 const stored = body.base_template_id48 ? await backend("PUT", `/api/templates/${body.base_template_id}`, auth, { subject: `${t.subject} (retouche)`, preheader: t.preheader, html: t.html.replace("</body>", `<!-- ${String(body.brief).slice(0, 60).replace(/--/g, "")} --></body>`), text: t.text, variables: t.variables, note: `retouche rejouée : ${String(body.brief).slice(0, 100)}` })49 : await backend("POST", "/api/templates", auth, { name: t.name, category: t.category, subject: t.subject, preheader: t.preheader, html: t.html, text: t.text, variables: t.variables, brand: body.brand ?? {} })50 send("done", { template: stored, usage: rec.usage })51 } catch (err) { send("error", { code: "ai_error", message: String(err.message).slice(0, 200) }) }52 }53 res.end()54}5556http.createServer((req, res) => {57 if (req.method === "POST" && req.url === "/api/templates/generate") { replay(req, res).catch(() => res.destroy()); return }58 const up = http.request({ host: "127.0.0.1", port: BACKEND, method: req.method, path: req.url, headers: { ...req.headers, host: `localhost:${BACKEND}` } }, (r) => {59 res.writeHead(r.statusCode ?? 502, r.headers)60 r.pipe(res)61 })62 up.on("error", () => { if (!res.headersSent) res.writeHead(502, { "content-type": "application/json" }); res.end('{"error":"backend_down"}') })63 res.on("close", () => up.destroy())64 req.pipe(up)65}).listen(PORT, "127.0.0.1", () => console.log(`replay proxy on http://localhost:${PORT} → backend :${BACKEND} (${events.length} recorded events, mode ${MODE})`))66