import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { createServer, type Server } from "node:net"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { parseRawReply, parseStatusPage, k200lDriver } from "./printer-k200l.js"; import { renderTicket } from "./printer-escpos.js"; import type { MonitorableDevice, PrinterDevice } from "../interfaces.js"; // The K200L (Xprinter / ICS; J-Speed 'POS-80' LAN board) driver. Its status page was captured verbatim // from the unit on the lab bench, 2026-09-09: uppercase tags, values padded with // spaces, and — the part that matters — the board's reply has NO status line and NO // headers (the body starts at byte 0). The tests replay exactly that over a raw // socket, plus a proper-HTTP variant, so the driver is proven against both. /** The board's status table, as sent (CRLF, uppercase, padded values). */ function boardPage(flags: Partial> = {}): string { const v = (k: string) => `${flags[k] ?? "No"} `; return [ '', "Printer Status", "", '
', "", ``, ``, ``, ``, `
Cover Is Open${v("cover")}
Cutter Error${v("cutter")}
Paper End${v("paperEnd")}
Paper Near End${v("nearEnd")}
Printer Off-Line${v("offline")}
`, '
', ].join("\r\n"); } const INDEX = "Ethernet port configuration
Mac Address00-D8-23-5C-58-8C
"; type Reply = { body: string; status?: number; raw?: boolean }; describe("parseRawReply", () => { it("treats a reply without a status line as HTTP/0.9: the whole reply is the body", () => { const r = parseRawReply("x"); expect(r.status).toBe(200); expect(r.body).toBe("x"); }); it("splits a real HTTP reply into status and body", () => { const r = parseRawReply("HTTP/1.0 404 Not Found\r\nContent-Type: text/html\r\n\r\nnope"); expect(r.status).toBe(404); expect(r.body).toBe("nope"); }); }); describe("parseStatusPage", () => { it("reads the board's padded, uppercase table", () => { const f = parseStatusPage(boardPage({ cover: "Yes", nearEnd: "Yes" })); expect(f).toEqual({ coverOpen: true, cutterError: false, paperEnd: false, paperNearEnd: true, offline: false }); }); it("leaves unknown pages empty rather than guessing", () => { expect(parseStatusPage(INDEX)).toEqual({}); }); it("reads a fault's Yes, which the board wraps in (captured live, cover open)", () => { // Verbatim from the unit on 2026-09-09 with the cover open: the three fault cells carry // markup the No cells don't — the first parser rejected them ("missing coverOpen, // paperEnd, offline" on the booth) while the No cells parsed. const page = boardPage() .replace("Cover Is OpenNo ", "Cover Is OpenYes ") .replace("Paper EndNo ", "Paper EndYes ") .replace("Printer Off-LineNo ", "Printer Off-LineYes "); expect(parseStatusPage(page)).toEqual({ coverOpen: true, cutterError: false, paperEnd: true, paperNearEnd: false, offline: true }); }); it("tolerates other markup shapes around a value", () => { const page = boardPage() .replace("Paper EndNo ", "Paper EndYes ") .replace("Printer Off-LineNo ", "Printer Off-Line\r\n\r\nYes\r\n"); expect(parseStatusPage(page)).toEqual({ coverOpen: false, cutterError: false, paperEnd: true, paperNearEnd: false, offline: true }); }); it("reads labels wrapped in markup too", () => { const page = boardPage({ nearEnd: "Yes" }).replace("Paper Near End", "Paper Near End"); expect(parseStatusPage(page).paperNearEnd).toBe(true); }); }); describe("k200lDriver.readStatus over TCP", () => { let server: Server | undefined; const sockets = new Set(); /** A raw TCP server that answers like the board (no status line) unless the reply * says otherwise, and closes after the reply (HTTP/1.0). */ async function serve(reply: (path: string) => Reply): Promise { server = createServer((sock) => { sockets.add(sock); sock.on("close", () => sockets.delete(sock)); sock.once("data", (d) => { const path = /^GET (\S+)/.exec(d.toString())?.[1] ?? ""; const r = reply(path); if (r.raw === false) { sock.end(`HTTP/1.0 ${r.status ?? 200} OK\r\nContent-Type: text/html\r\n\r\n${r.body}`); } else { sock.end(r.body); } }); }); await new Promise((r) => server!.listen(0, "127.0.0.1", () => r())); const addr = server.address(); if (!addr || typeof addr === "string") throw new Error("no port"); return addr.port; } afterEach(async () => { for (const s of sockets) s.destroy(); sockets.clear(); if (server) await new Promise((r) => server!.close(() => r())); server = undefined; }); function device(httpPort: number): MonitorableDevice & { driverId: string } { return k200lDriver.create({ transport: "tcp-ip", host: "127.0.0.1", port: 9100, httpPort, timeoutMs: 1000 }) as unknown as MonitorableDevice & { driverId: string; }; } it("reads the headerless reply: cover open + paper out + off-line → degraded, flags set", async () => { const port = await serve((p) => (p === "/prt_status.htm" ? { body: boardPage({ cover: "Yes", paperEnd: "Yes", offline: "Yes" }) } : { body: INDEX })); const dev = device(port); expect(dev.driverId).toBe("k200l"); const s = await dev.readStatus(); expect(s.status).toBe("degraded"); expect(s.coverOpen).toBe(true); expect(s.paperEnd).toBe(true); expect(s.offline).toBe(true); expect(s.cutterError).toBe(false); expect(s.paperNearEnd).toBe(false); expect(s.detail).toBe("cover open, paper out, printer off-line"); }); it("healthy printer → ready, every flag false", async () => { const port = await serve(() => ({ body: boardPage() })); const s = await device(port).readStatus(); expect(s.status).toBe("ready"); expect(s.coverOpen).toBe(false); expect(s.detail).toBeUndefined(); }); it("paper near end alone → degraded 'paper low' (still prints, warn to reload)", async () => { const port = await serve(() => ({ body: boardPage({ nearEnd: "Yes" }) })); const s = await device(port).readStatus(); expect(s.status).toBe("degraded"); expect(s.paperNearEnd).toBe(true); expect(s.detail).toBe("paper low"); }); it("also understands a proper HTTP reply (a board firmware that sends headers)", async () => { const port = await serve(() => ({ body: boardPage({ cutter: "Yes" }), raw: false })); const s = await device(port).readStatus(); expect(s.status).toBe("degraded"); expect(s.detail).toBe("cutter error"); }); it("a page without the status rows (the index) → degraded 'unexpected status page', never ready", async () => { const port = await serve(() => ({ body: INDEX })); const s = await device(port).readStatus(); expect(s.status).toBe("degraded"); expect(s.detail).toContain("unexpected status page"); expect(s.detail).toContain("missing"); }); it("a non-200 reply → degraded naming the code, never ready", async () => { const port = await serve(() => ({ body: "", status: 404, raw: false })); const s = await device(port).readStatus(); expect(s.status).toBe("degraded"); expect(s.detail).toContain("HTTP 404"); }); it("board unreachable (connection refused) → offline", async () => { const port = await serve(() => ({ body: "" })); await new Promise((r) => server!.close(() => r())); server = undefined; const s = await device(port).readStatus(); expect(s.status).toBe("offline"); expect(s.detail).toMatch(/ECONNREFUSED/); }); it("a board that accepts but never answers → offline 'status page timeout'", async () => { server = createServer((sock) => { sockets.add(sock); // hold the socket open, say nothing sock.on("close", () => sockets.delete(sock)); }); await new Promise((r) => server!.listen(0, "127.0.0.1", () => r())); const addr = server.address(); if (!addr || typeof addr === "string") throw new Error("no port"); const dev = k200lDriver.create({ transport: "tcp-ip", host: "127.0.0.1", port: 9100, httpPort: addr.port, timeoutMs: 200 }) as unknown as MonitorableDevice; const s = await dev.readStatus(); expect(s.status).toBe("offline"); expect(s.detail).toBe("status page timeout"); }); }); describe("k200lDriver — printing and USB are the generic ESC/POS path", () => { let dir: string; let devicePath: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "k200l-usb-")); devicePath = join(dir, "lp0"); writeFileSync(devicePath, ""); }); afterEach(() => { rmSync(dir, { recursive: true, force: true }); }); it("prints the same ticket bytes the generic driver would, to the USB node", async () => { const printer = k200lDriver.create({ transport: "usb", devicePath, timeoutMs: 1000 }) as PrinterDevice; const data = { ticketId: "12345678901", issuedAt: "2026-09-09T10:00:00.000Z" }; await printer.printTicket(data); expect(readFileSync(devicePath).equals(renderTicket(data))).toBe(true); }); it("over USB readStatus is the reachability floor: ready when the node opens, offline when absent", async () => { const present = k200lDriver.create({ transport: "usb", devicePath, timeoutMs: 1000 }) as unknown as MonitorableDevice; expect((await present.readStatus()).status).toBe("ready"); const absent = k200lDriver.create({ transport: "usb", devicePath: join(dir, "absent"), timeoutMs: 1000 }) as unknown as MonitorableDevice; expect((await absent.readStatus()).status).toBe("offline"); }); it("advertises both transports and exposes the status-page port after the print port", () => { expect(k200lDriver.transports).toEqual(["tcp-ip", "usb"]); const keys = k200lDriver.configFields.map((f) => f.key); expect(keys.indexOf("httpPort")).toBe(keys.indexOf("port") + 1); expect(keys).toContain("role"); }); });