const assert = require("assert"); const { Readable } = require("stream"); const { loadModule } = require("./_shared.cjs"); const tests = []; const test = (name, fn) => tests.push({ name, fn }); const createRedirectRes = () => { const state = { redirectedTo: null, headers: {}, piped: false, headersSent: false }; return { state, get headersSent() { return state.headersSent; }, setHeader(key, value) { state.headers[key.toLowerCase()] = value; }, redirect(path) { state.redirectedTo = path; state.headersSent = true; return path; } }; }; test("documents download redirects when id/hash query is missing", async () => { const mod = loadModule("pages/api/documents/download/[id].js", { getToken: async () => ({ access_token: "tok" }), consoleLogger: () => {}, axios: { get: async () => ({}) } }); const req = { query: { id: "DOC-1" } }; const res = createRedirectRes(); await mod.default(req, res); assert.strictEqual(res.state.redirectedTo, "/filenotavailable"); }); test("documents download success sets attachment headers and pipes stream", async () => { const stream = new Readable({ read() {} }); const mod = loadModule("pages/api/documents/download/[id].js", { setTimeout: (fn) => { fn(); return 0; }, getToken: async () => ({ access_token: "tok" }), consoleLogger: () => {}, axios: { get: async () => ({ headers: { "content-disposition": "attachment; filename=test-file.pdf" }, data: stream }) } }); const req = { query: { id: "DOC-1", hash: "h1" } }; const res = createRedirectRes(); stream.pipe = (target) => { target.state.piped = true; target.state.headersSent = true; return target; }; await mod.default(req, res); assert.strictEqual( res.state.headers["content-disposition"], "attachment; filename=test-file.pdf" ); assert.strictEqual( res.state.headers["content-type"], "application/octet-stream" ); assert.strictEqual(res.state.piped, true); assert.strictEqual(res.state.redirectedTo, null); }); test("documents download redirects when relay request fails", async () => { const mod = loadModule("pages/api/documents/download/[id].js", { setTimeout: (fn) => { fn(); return 0; }, getToken: async () => ({ access_token: "tok" }), consoleLogger: () => {}, axios: { get: async () => { throw new Error("relay failed"); } } }); const req = { query: { id: "DOC-1", hash: "h1" } }; const res = createRedirectRes(); await mod.default(req, res); assert.strictEqual(res.state.redirectedTo, "/filenotavailable"); }); const run = async () => { let passed = 0; for (const currentTest of tests) { await currentTest.fn(); passed += 1; } console.log( `Phase 21 documents-handler contract tests passed (${passed}/${tests.length}).` ); }; module.exports = run; if (require.main === module) { run().catch((error) => { console.error(error); process.exit(1); }); }