SPB Git

Repository Public

helpers.mjs 5.3 KB 128 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SPIDER — Universal Web Intelligence Engine8 * File             : sdk/typescript/test/helpers.mjs9 * Module           : Tests10 * Repository       : https://git.spboucher.ai/spider11 * Project Website  : Not specified12 * Created          : 2026-12-0413 * Last Modified    : 2026-12-0414 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : ISC34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Test helpers: a tiny scripted HTTP server and the OpenAPI document.44import { createServer } from "node:http";45import { readFileSync } from "node:fs";46import { fileURLToPath } from "node:url";4748import { Spider } from "../dist/index.js";4950export const API_KEY = "sk_test_unit_0123456789";51export const OPENAPI = JSON.parse(readFileSync(fileURLToPath(new URL("../../../docs/openapi.json", import.meta.url)), "utf8"));5253export const json = (status, body, headers = {}) => ({ status, body, headers });54export const apiError = (status, code, details = null, headers = {}) =>55  json(status, { error: { code, message: "explained", details, request_id: "rid-1" } }, { "X-Request-Id": "rid-1", ...headers });56export const reset = { reset: true }; // the server processes the request, then drops the connection without answering57export const sse = (...chunks) => ({ status: 200, headers: { "Content-Type": "text/event-stream" }, chunks });5859/**60 * Start a server that answers each request with the next step of `steps` (or with `fallback(req)`).61 * A step is {status, body, headers} | {reset: true} | {chunks: [...]} | a function (request) => step.62 */63export async function mockServer(steps = [], fallback = null) {64  const requests = [];65  const server = createServer((req, res) => {66    const parts = [];67    req.on("data", (c) => parts.push(c));68    req.on("end", async () => {69      const raw = Buffer.concat(parts).toString("utf8");70      const url = new URL(req.url, "http://mock");71      const record = { method: req.method, path: url.pathname, rawPath: req.url.split("?")[0], query: Object.fromEntries(url.searchParams), headers: req.headers,72                       body: raw ? JSON.parse(raw) : undefined, raw };73      requests.push(record);74      let step = steps.length ? steps.shift() : fallback;75      if (typeof step === "function") step = await step(record);76      if (!step) {77        res.writeHead(599, { "Content-Type": "application/json" });78        res.end(JSON.stringify({ error: { code: "unexpected_request", message: `${req.method} ${req.url}`, details: null, request_id: "x" } }));79        return;80      }81      if (step.reset) {82        req.socket.destroy();83        return;84      }85      if (step.chunks) {86        res.writeHead(step.status ?? 200, step.headers ?? {});87        for (const c of step.chunks) {88          res.write(c);89          await new Promise((r) => setTimeout(r, 5));90        }91        if (!step.hold) res.end(); // hold: the stream stays open and silent92        return;93      }94      const isBytes = Buffer.isBuffer(step.body) || step.body instanceof Uint8Array;95      const payload = isBytes ? Buffer.from(step.body) : typeof step.body === "string" ? step.body : JSON.stringify(step.body ?? {});96      res.writeHead(step.status ?? 200, { "Content-Type": isBytes ? "application/octet-stream" : typeof step.body === "string" ? "text/plain" : "application/json", ...step.headers });97      res.end(payload);98    });99  });100  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));101  const url = `http://127.0.0.1:${server.address().port}`;102  const sleeps = [];103  return {104    url, requests, sleeps, steps,105    client: (options = {}) => new Spider({ baseUrl: url, apiKey: API_KEY, sleep: async (ms) => void sleeps.push(ms), ...options }),106    close: () => new Promise((resolve) => {107      server.closeAllConnections();108      server.close(resolve);109    }),110  };111}112113/** Run `fn(server)` against a scripted server and always close it. */114export async function withServer(steps, fn, fallback = null) {115  const s = await mockServer(steps, fallback);116  try {117    return await fn(s);118  } finally {119    await s.close();120  }121}122123export async function drain(iterable) {124  const out = [];125  for await (const x of iterable) out.push(x);126  return out;127}128
Files main
Menu

Theme