LLM Spend TripwireChecklistCodeHosted waitlist

test/helpers.mjs

Commit 01f96e7. All files · Download the tarball.

// Test doubles: an in-memory stand-in for the one D1 query shape we use, and a fake fetch for Anthropic + webhooks.
export function fakeDb() {
  const db = { row: null, writes: 0 };
  db.prepare = (sql) => {
    let args = [];
    const stmt = {
      bind: (...a) => { args = a; return stmt; },
      run: async () => {
        if (/^INSERT INTO tripwire_state/.test(sql)) { db.row = { v: args[0], updated_at: args[1] }; db.writes++; }
        return { success: true };
      },
      first: async () => (/^SELECT v FROM tripwire_state/.test(sql) ? db.row : null),
    };
    return stmt;
  };
  return db;
}

// Build a usage_report/messages response in the documented shape.
export function usageResponse(buckets, { has_more = false, next_page = null } = {}) {
  return {
    data: buckets.map(({ start, widthMin = 1, results = [] }) => ({
      starting_at: new Date(start * 60000).toISOString().replace(".000Z", "Z"),
      ending_at: new Date((start + widthMin) * 60000).toISOString().replace(".000Z", "Z"),
      results: results.map((r) => ({
        account_id: null,
        api_key_id: r.key === undefined ? "apikey_A" : r.key,
        cache_creation: { ephemeral_1h_input_tokens: r.w1h || 0, ephemeral_5m_input_tokens: r.w5m || 0 },
        cache_read_input_tokens: r.read || 0,
        context_window: null,
        inference_geo: null,
        model: r.model || "claude-sonnet-5-5",
        output_tokens: r.out || 0,
        server_tool_use: { web_search_requests: 0 },
        service_account_id: null,
        service_tier: null,
        speed: null,
        uncached_input_tokens: r.in || 0,
        workspace_id: null,
      })),
    })),
    has_more,
    next_page,
  };
}

export function keysResponse(keys, { has_more = false, last_id = null } = {}) {
  return {
    data: keys.map((k) => ({ type: "api_key", id: k.id, name: k.name || "key", partial_key_hint: k.hint || "sk-ant-api03-R2D...igAA", created_at: k.created_at || "2026-11-01T00:00:00Z",
      created_by: { id: "user_01", type: "user" }, expires_at: null, principal: null, scope: { type: "workspace", workspace_id: "wrkspc_01" }, status: "active" })),
    first_id: keys[0] ? keys[0].id : null, has_more, last_id,
  };
}

// usage(url) -> response body for usage calls; keys(url) -> body for key list calls.
export function fakeFetch({ usage, keys = () => keysResponse([]), webhookStatus = 200, usageStatus = 200 }) {
  const calls = [];
  const f = async (url, init = {}) => {
    const u = String(url);
    calls.push({ url: u, init });
    const ok = (body, status = 200) => new Response(typeof body === "string" ? body : JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
    if (u.startsWith("https://api.anthropic.com/v1/organizations/usage_report/messages")) {
      if (usageStatus !== 200) return ok({ type: "error", error: { type: "authentication_error", message: "invalid x-api-key" } }, usageStatus);
      return ok(usage(u));
    }
    if (u.startsWith("https://api.anthropic.com/v1/organizations/api_keys")) return ok(keys(u));
    if (u.startsWith("https://hooks.slack.com/") || u.startsWith("https://discord.com/")) return ok("ok", webhookStatus);
    throw new Error("unexpected fetch to " + u);
  };
  f.calls = calls;
  return f;
}

export const minuteOf = (iso) => Math.floor(Date.parse(iso) / 60000);