Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+298
@@ -0,0 +1,298 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { createHiveGridClient } from "./client.js";
|
||||
|
||||
// Local copies of the helpers used by client.test.ts — kept identical so the new
|
||||
// suite stays independent of the existing test file (no shared-fixture edits).
|
||||
function mockFetchSequence(responses: Array<Response | Error>): typeof fetch {
|
||||
let index = 0;
|
||||
return (async () => {
|
||||
const next = responses[index++];
|
||||
if (next === undefined) {
|
||||
throw new Error("mock fetch exhausted");
|
||||
}
|
||||
if (next instanceof Error) throw next;
|
||||
return next;
|
||||
}) as unknown as typeof fetch;
|
||||
}
|
||||
|
||||
function jsonResponse(status: number, body: unknown, headers: Record<string, string> = {}): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "content-type": "application/json", ...headers },
|
||||
});
|
||||
}
|
||||
|
||||
function textResponse(status: number, body: string, headers: Record<string, string> = {}): Response {
|
||||
return new Response(body, { status, headers });
|
||||
}
|
||||
|
||||
describe("createHiveGridClient — request body parsing", () => {
|
||||
it("returns parsed text when the response is not JSON", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: mockFetchSequence([textResponse(200, "plain-pong", { "content-type": "text/plain" })]),
|
||||
});
|
||||
const result = await client.request<string>({ method: "GET", path: "/v1/ping" });
|
||||
expect(result).toBe("plain-pong");
|
||||
});
|
||||
|
||||
it("returns null for an empty non-JSON body", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: mockFetchSequence([textResponse(200, "")]),
|
||||
});
|
||||
const result = await client.request({ method: "GET", path: "/v1/empty" });
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when a JSON content-type carries an unparseable body", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: mockFetchSequence([textResponse(200, "{not-valid-json", { "content-type": "application/json" })]),
|
||||
});
|
||||
const result = await client.request({ method: "GET", path: "/v1/broken" });
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createHiveGridClient — idempotency edge cases", () => {
|
||||
it("forwards a caller idempotency key on a non-mutating method", async () => {
|
||||
const captured: { headers: Headers | null } = { headers: null };
|
||||
const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => {
|
||||
captured.headers = init.headers as Headers;
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
||||
await client.request({ method: "GET", path: "/v1/items", idempotencyKey: "explicit-get-key" });
|
||||
// GET never auto-generates, but an explicit key must still be honored.
|
||||
expect(captured.headers!.get("idempotency-key")).toBe("explicit-get-key");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createHiveGridClient — URL building", () => {
|
||||
it("uses an absolute path verbatim instead of prefixing the base url", async () => {
|
||||
const captured: { url: string | null } = { url: null };
|
||||
const stub: typeof fetch = (async (url: string) => {
|
||||
captured.url = url;
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
||||
await client.request({ method: "GET", path: "https://other.example.test/v2/thing" });
|
||||
expect(captured.url).toBe("https://other.example.test/v2/thing");
|
||||
});
|
||||
|
||||
it("skips undefined query values while serializing the rest", async () => {
|
||||
const captured: { url: string | null } = { url: null };
|
||||
const stub: typeof fetch = (async (url: string) => {
|
||||
captured.url = url;
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
||||
await client.request({ method: "GET", path: "/v1/items", query: { a: 1, b: undefined, c: true } });
|
||||
const parsed = new URL(captured.url!);
|
||||
expect(parsed.searchParams.get("a")).toBe("1");
|
||||
expect(parsed.searchParams.get("c")).toBe("true");
|
||||
expect(parsed.searchParams.has("b")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createHiveGridClient — Retry-After handling", () => {
|
||||
it("honors an HTTP-date Retry-After header, capped by maxDelayMs", async () => {
|
||||
const future = new Date(Date.now() + 60_000).toUTCString();
|
||||
const t0 = Date.now();
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 3, baseDelayMs: 1000, maxDelayMs: 5 },
|
||||
fetch: mockFetchSequence([jsonResponse(429, { error: "rate" }, { "retry-after": future }), jsonResponse(200, { ok: true })]),
|
||||
});
|
||||
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
|
||||
expect(result.ok).toBe(true);
|
||||
// The 60s date must be clamped to the 5ms maxDelay, not waited out in full.
|
||||
expect(Date.now() - t0).toBeLessThan(1000);
|
||||
});
|
||||
|
||||
it("falls back to exponential backoff when Retry-After is unparseable", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 5 },
|
||||
fetch: mockFetchSequence([jsonResponse(503, { error: "down" }, { "retry-after": "soon-ish" }), jsonResponse(200, { ok: true })]),
|
||||
});
|
||||
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a past HTTP-date Retry-After as a zero delay", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 2, baseDelayMs: 1000, maxDelayMs: 1000 },
|
||||
fetch: mockFetchSequence([
|
||||
jsonResponse(429, { error: "rate" }, { "retry-after": "Thu, 01 Jan 1970 00:00:00 GMT" }),
|
||||
jsonResponse(200, { ok: true }),
|
||||
]),
|
||||
});
|
||||
const t0 = Date.now();
|
||||
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
|
||||
expect(result.ok).toBe(true);
|
||||
expect(Date.now() - t0).toBeLessThan(500);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createHiveGridClient — network retry recovery", () => {
|
||||
it("retries a transient network error and then succeeds", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 5 },
|
||||
fetch: mockFetchSequence([new Error("ECONNRESET"), jsonResponse(200, { ok: true })]),
|
||||
});
|
||||
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createHiveGridClient — error message extraction", () => {
|
||||
it("falls back to `HTTP <status>` when the error body has no message", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 1 },
|
||||
fetch: mockFetchSequence([jsonResponse(400, { error: {} })]),
|
||||
});
|
||||
await expect(client.request({ method: "GET", path: "/v1/x" })).rejects.toMatchObject({
|
||||
name: "HiveGridApiError",
|
||||
status: 400,
|
||||
message: "HTTP 400",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to `HTTP <status>` when `error` is not an object", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 1 },
|
||||
fetch: mockFetchSequence([jsonResponse(422, { error: "validation failed" })]),
|
||||
});
|
||||
await expect(client.request({ method: "GET", path: "/v1/x" })).rejects.toMatchObject({
|
||||
status: 422,
|
||||
message: "HTTP 422",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses `HTTP <status>` for a non-JSON error body and omits a missing requestId", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 1 },
|
||||
fetch: mockFetchSequence([textResponse(500, "internal boom", { "content-type": "text/plain" })]),
|
||||
});
|
||||
await expect(client.request({ method: "GET", path: "/v1/x" })).rejects.toMatchObject({
|
||||
status: 500,
|
||||
message: "HTTP 500",
|
||||
body: "internal boom",
|
||||
requestId: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("createHiveGridClient — pagination edge cases", () => {
|
||||
it("follows nextPageToken cursors", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: mockFetchSequence([
|
||||
jsonResponse(200, { data: [{ id: "a" }], nextPageToken: "tok-2" }),
|
||||
jsonResponse(200, { data: [{ id: "b" }], nextPageToken: null }),
|
||||
]),
|
||||
});
|
||||
const ids: string[] = [];
|
||||
for await (const item of client.paginate<{ id: string }>("/v1/items")) {
|
||||
ids.push(item.id);
|
||||
}
|
||||
expect(ids).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("stops cleanly when a page returns a null body", async () => {
|
||||
let calls = 0;
|
||||
const stub: typeof fetch = (async () => {
|
||||
calls += 1;
|
||||
// JSON literal null → readBody returns null → request resolves null.
|
||||
return textResponse(200, "null", { "content-type": "application/json" });
|
||||
}) as unknown as typeof fetch;
|
||||
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
||||
|
||||
const items: unknown[] = [];
|
||||
for await (const item of client.paginate("/v1/items")) items.push(item);
|
||||
expect(items).toEqual([]);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("yields nothing when `data` is not an array", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: mockFetchSequence([jsonResponse(200, { data: { not: "an-array" } })]),
|
||||
});
|
||||
const items: unknown[] = [];
|
||||
for await (const item of client.paginate("/v1/items")) items.push(item);
|
||||
expect(items).toEqual([]);
|
||||
});
|
||||
|
||||
it("breaks on an empty page even when a next cursor is present (safety stop)", async () => {
|
||||
let calls = 0;
|
||||
const stub: typeof fetch = (async () => {
|
||||
calls += 1;
|
||||
// A server that keeps advertising a cursor but never returns rows must not loop forever.
|
||||
return jsonResponse(200, { data: [], nextCursor: "always-more" });
|
||||
}) as unknown as typeof fetch;
|
||||
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
||||
|
||||
const items: unknown[] = [];
|
||||
for await (const item of client.paginate("/v1/items")) items.push(item);
|
||||
expect(items).toEqual([]);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("respects the maxPages safety cap", async () => {
|
||||
let calls = 0;
|
||||
const stub: typeof fetch = (async () => {
|
||||
calls += 1;
|
||||
return jsonResponse(200, { data: [{ id: calls }], nextCursor: `c-${calls}` });
|
||||
}) as unknown as typeof fetch;
|
||||
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
|
||||
|
||||
const items: Array<{ id: number }> = [];
|
||||
for await (const item of client.paginate<{ id: number }>("/v1/items", { maxPages: 3 })) {
|
||||
items.push(item);
|
||||
}
|
||||
expect(items).toHaveLength(3);
|
||||
expect(calls).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createHiveGridClient — refreshAuth", () => {
|
||||
it("refreshes and caches the bearer token via the configured getter", async () => {
|
||||
let issued = 0;
|
||||
const captured: Array<string | null> = [];
|
||||
const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => {
|
||||
captured.push((init.headers as Headers).get("authorization"));
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
auth: { getToken: async () => `jwt-${++issued}` },
|
||||
fetch: stub,
|
||||
});
|
||||
await client.refreshAuth();
|
||||
expect(issued).toBe(1);
|
||||
// The getter is re-invoked per request, so the next call advances the counter.
|
||||
await client.request({ method: "GET", path: "/v1/me" });
|
||||
expect(captured).toEqual(["Bearer jwt-2"]);
|
||||
});
|
||||
|
||||
it("is a no-op when no token getter is configured", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
auth: { apiKey: "ak_123" },
|
||||
fetch: mockFetchSequence([]),
|
||||
});
|
||||
await expect(client.refreshAuth()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
+27
-27
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { createToolctrlClient, ToolctrlApiError, ToolctrlNetworkError } from "./client.js";
|
||||
import { createHiveGridClient, HiveGridApiError, HiveGridNetworkError } from "./client.js";
|
||||
|
||||
function mockFetchSequence(responses: Array<Response | Error>): typeof fetch {
|
||||
let index = 0;
|
||||
@@ -20,13 +20,13 @@ function jsonResponse(status: number, body: unknown, headers: Record<string, str
|
||||
});
|
||||
}
|
||||
|
||||
describe("createToolctrlClient", () => {
|
||||
describe("createHiveGridClient", () => {
|
||||
it("rejects when baseUrl is missing", () => {
|
||||
expect(() => createToolctrlClient({ baseUrl: "" } as never)).toThrow(/baseUrl/);
|
||||
expect(() => createHiveGridClient({ baseUrl: "" } as never)).toThrow(/baseUrl/);
|
||||
});
|
||||
|
||||
it("strips trailing slashes from the base url", () => {
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com///",
|
||||
fetch: mockFetchSequence([jsonResponse(200, { ok: true })]),
|
||||
});
|
||||
@@ -40,7 +40,7 @@ describe("createToolctrlClient", () => {
|
||||
return jsonResponse(200, { hello: "world" });
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
auth: { bearerToken: "secret-token" },
|
||||
fetch: stub,
|
||||
@@ -57,7 +57,7 @@ describe("createToolctrlClient", () => {
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
auth: { apiKey: "ak_test_123" },
|
||||
fetch: stub,
|
||||
@@ -73,7 +73,7 @@ describe("createToolctrlClient", () => {
|
||||
return jsonResponse(201, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: stub,
|
||||
});
|
||||
@@ -88,7 +88,7 @@ describe("createToolctrlClient", () => {
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: stub,
|
||||
});
|
||||
@@ -103,7 +103,7 @@ describe("createToolctrlClient", () => {
|
||||
return jsonResponse(201, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
idempotency: { autoGenerate: false },
|
||||
fetch: stub,
|
||||
@@ -119,7 +119,7 @@ describe("createToolctrlClient", () => {
|
||||
return jsonResponse(201, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: stub,
|
||||
});
|
||||
@@ -134,7 +134,7 @@ describe("createToolctrlClient", () => {
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
tenantId: "ten_abc",
|
||||
sentry: { trace: "abc-1", baggage: "k=v" },
|
||||
@@ -147,7 +147,7 @@ describe("createToolctrlClient", () => {
|
||||
});
|
||||
|
||||
it("retries on 5xx then succeeds", async () => {
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 5 },
|
||||
fetch: mockFetchSequence([jsonResponse(503, { error: "down" }), jsonResponse(200, { ok: true })]),
|
||||
@@ -157,7 +157,7 @@ describe("createToolctrlClient", () => {
|
||||
});
|
||||
|
||||
it("retries on 429 honoring Retry-After", async () => {
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 3, baseDelayMs: 1000, maxDelayMs: 10_000 },
|
||||
fetch: mockFetchSequence([
|
||||
@@ -172,8 +172,8 @@ describe("createToolctrlClient", () => {
|
||||
expect(Date.now() - t0).toBeLessThan(1000);
|
||||
});
|
||||
|
||||
it("throws ToolctrlApiError on non-retryable 4xx", async () => {
|
||||
const client = createToolctrlClient({
|
||||
it("throws HiveGridApiError on non-retryable 4xx", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 3, baseDelayMs: 1 },
|
||||
fetch: mockFetchSequence([
|
||||
@@ -181,23 +181,23 @@ describe("createToolctrlClient", () => {
|
||||
]),
|
||||
});
|
||||
await expect(client.request({ method: "GET", path: "/v1/missing" })).rejects.toMatchObject({
|
||||
name: "ToolctrlApiError",
|
||||
name: "HiveGridApiError",
|
||||
status: 404,
|
||||
requestId: "req_1",
|
||||
});
|
||||
});
|
||||
|
||||
it("throws ToolctrlNetworkError after exhausting retries", async () => {
|
||||
const client = createToolctrlClient({
|
||||
it("throws HiveGridNetworkError after exhausting retries", async () => {
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
retry: { maxAttempts: 2, baseDelayMs: 1, maxDelayMs: 5 },
|
||||
fetch: mockFetchSequence([new Error("ECONNRESET"), new Error("ECONNRESET")]),
|
||||
});
|
||||
await expect(client.request({ method: "GET", path: "/v1/ping" })).rejects.toBeInstanceOf(ToolctrlNetworkError);
|
||||
await expect(client.request({ method: "GET", path: "/v1/ping" })).rejects.toBeInstanceOf(HiveGridNetworkError);
|
||||
});
|
||||
|
||||
it("paginate auto-follows nextCursor and stops on null", async () => {
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: mockFetchSequence([
|
||||
jsonResponse(200, { data: [{ id: 1 }, { id: 2 }], nextCursor: "c1" }),
|
||||
@@ -212,7 +212,7 @@ describe("createToolctrlClient", () => {
|
||||
});
|
||||
|
||||
it("paginate handles nextPage offset pagination", async () => {
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
fetch: mockFetchSequence([
|
||||
jsonResponse(200, { data: [{ id: "a" }], nextPage: 2 }),
|
||||
@@ -234,7 +234,7 @@ describe("createToolctrlClient", () => {
|
||||
return jsonResponse(200, {});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const client = createToolctrlClient({
|
||||
const client = createHiveGridClient({
|
||||
baseUrl: "https://api.example.com",
|
||||
auth: {
|
||||
getToken: async () => `jwt-${++calls}`,
|
||||
@@ -248,15 +248,15 @@ describe("createToolctrlClient", () => {
|
||||
});
|
||||
|
||||
describe("error types", () => {
|
||||
it("ToolctrlApiError carries status, body, and requestId", () => {
|
||||
const err = new ToolctrlApiError(403, "Forbidden", { error: { code: "forbidden" } }, "req_x");
|
||||
expect(err.name).toBe("ToolctrlApiError");
|
||||
it("HiveGridApiError carries status, body, and requestId", () => {
|
||||
const err = new HiveGridApiError(403, "Forbidden", { error: { code: "forbidden" } }, "req_x");
|
||||
expect(err.name).toBe("HiveGridApiError");
|
||||
expect(err.status).toBe(403);
|
||||
expect(err.requestId).toBe("req_x");
|
||||
});
|
||||
it("ToolctrlNetworkError preserves cause", () => {
|
||||
it("HiveGridNetworkError preserves cause", () => {
|
||||
const cause = new Error("ECONNRESET");
|
||||
const err = new ToolctrlNetworkError("net", cause);
|
||||
const err = new HiveGridNetworkError("net", cause);
|
||||
expect(err.cause).toBe(cause);
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
export interface ToolctrlAuthConfig {
|
||||
export interface HiveGridAuthConfig {
|
||||
/** Bearer-token style — set as `Authorization: Bearer <key>`. */
|
||||
bearerToken?: string;
|
||||
/** API-key style — set as `X-API-Key: <key>`. */
|
||||
@@ -22,7 +22,7 @@ export interface ToolctrlAuthConfig {
|
||||
getToken?: () => Promise<string>;
|
||||
}
|
||||
|
||||
export interface ToolctrlRetryConfig {
|
||||
export interface HiveGridRetryConfig {
|
||||
/** Maximum number of retry attempts (default 5). The initial request counts as 1. */
|
||||
maxAttempts?: number;
|
||||
/** Initial delay in ms before the first retry (default 1000). */
|
||||
@@ -31,25 +31,25 @@ export interface ToolctrlRetryConfig {
|
||||
maxDelayMs?: number;
|
||||
}
|
||||
|
||||
export interface ToolctrlIdempotencyConfig {
|
||||
export interface HiveGridIdempotencyConfig {
|
||||
/** Auto-generate `Idempotency-Key` headers on POST/PUT/PATCH. Defaults to true. */
|
||||
autoGenerate?: boolean;
|
||||
}
|
||||
|
||||
export interface ToolctrlClientConfig {
|
||||
/** Base URL of the toolctrl API, e.g. `https://api.toolctrl.de`. */
|
||||
export interface HiveGridClientConfig {
|
||||
/** Base URL of the hivegrid API, e.g. `https://api.hivegrid.de`. */
|
||||
baseUrl: string;
|
||||
/** Auth configuration. Exactly one of bearerToken / apiKey / getToken should be set. */
|
||||
auth?: ToolctrlAuthConfig;
|
||||
auth?: HiveGridAuthConfig;
|
||||
/** Optional tenant scope; forwarded as `X-Tenant-ID` on every call. */
|
||||
tenantId?: string;
|
||||
/** User-Agent override. Defaults to `@toolctrl/api-client-ts/<version>`. */
|
||||
/** User-Agent override. Defaults to `@hivegrid/api-client-ts/<version>`. */
|
||||
userAgent?: string;
|
||||
/** Retry policy for 429 + 5xx + network errors. */
|
||||
retry?: ToolctrlRetryConfig;
|
||||
retry?: HiveGridRetryConfig;
|
||||
/** Idempotency-Key policy. */
|
||||
idempotency?: ToolctrlIdempotencyConfig;
|
||||
/** Optional fetch implementation (defaults to global fetch). Useful for Capacitor or test stubs. */
|
||||
idempotency?: HiveGridIdempotencyConfig;
|
||||
/** Optional fetch implementation (defaults to global fetch). Useful for custom runtimes or test stubs. */
|
||||
fetch?: typeof fetch;
|
||||
/** Sentry trace headers to forward (optional). */
|
||||
sentry?: { trace?: string; baggage?: string };
|
||||
@@ -72,29 +72,29 @@ export interface PaginateOptions {
|
||||
query?: Record<string, string | number | undefined>;
|
||||
}
|
||||
|
||||
export class ToolctrlApiError extends Error {
|
||||
export class HiveGridApiError extends Error {
|
||||
public readonly status: number;
|
||||
public readonly body: unknown;
|
||||
public readonly requestId?: string;
|
||||
constructor(status: number, message: string, body: unknown, requestId?: string) {
|
||||
super(message);
|
||||
this.name = "ToolctrlApiError";
|
||||
this.name = "HiveGridApiError";
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
this.requestId = requestId;
|
||||
}
|
||||
}
|
||||
|
||||
export class ToolctrlNetworkError extends Error {
|
||||
export class HiveGridNetworkError extends Error {
|
||||
public readonly cause: unknown;
|
||||
constructor(message: string, cause: unknown) {
|
||||
super(message);
|
||||
this.name = "ToolctrlNetworkError";
|
||||
this.name = "HiveGridNetworkError";
|
||||
this.cause = cause;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ToolctrlClient {
|
||||
export interface HiveGridClient {
|
||||
/** Issue a typed request against the API. */
|
||||
request<T = unknown>(input: {
|
||||
method: string;
|
||||
@@ -158,16 +158,16 @@ async function readBody(response: Response): Promise<unknown> {
|
||||
return text.length === 0 ? null : text;
|
||||
}
|
||||
|
||||
export function createToolctrlClient(config: ToolctrlClientConfig): ToolctrlClient {
|
||||
export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClient {
|
||||
if (!config.baseUrl) {
|
||||
throw new Error("createToolctrlClient: baseUrl is required");
|
||||
throw new Error("createHiveGridClient: baseUrl is required");
|
||||
}
|
||||
|
||||
const baseUrl = config.baseUrl.replace(/\/+$/, "");
|
||||
const fetchImpl: typeof fetch =
|
||||
config.fetch ?? (typeof fetch !== "undefined" ? fetch.bind(globalThis) : (undefined as unknown as typeof fetch));
|
||||
if (!fetchImpl) {
|
||||
throw new Error("createToolctrlClient: no fetch implementation available — pass `fetch` in the config");
|
||||
throw new Error("createHiveGridClient: no fetch implementation available — pass `fetch` in the config");
|
||||
}
|
||||
const retryMaxAttempts = config.retry?.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;
|
||||
const retryBaseMs = config.retry?.baseDelayMs ?? DEFAULT_RETRY_BASE_MS;
|
||||
@@ -194,7 +194,7 @@ export function createToolctrlClient(config: ToolctrlClientConfig): ToolctrlClie
|
||||
const headers = new Headers();
|
||||
headers.set("Accept", "application/json");
|
||||
headers.set("Content-Type", "application/json");
|
||||
headers.set("User-Agent", config.userAgent ?? `@toolctrl/api-client-ts/${PACKAGE_VERSION}`);
|
||||
headers.set("User-Agent", config.userAgent ?? `@hivegrid/api-client-ts/${PACKAGE_VERSION}`);
|
||||
if (config.tenantId) headers.set("X-Tenant-ID", config.tenantId);
|
||||
if (config.sentry?.trace) headers.set("sentry-trace", config.sentry.trace);
|
||||
if (config.sentry?.baggage) headers.set("baggage", config.sentry.baggage);
|
||||
@@ -279,7 +279,7 @@ export function createToolctrlClient(config: ToolctrlClientConfig): ToolctrlClie
|
||||
errorBody && typeof errorBody === "object" && "error" in errorBody && errorBody.error && typeof errorBody.error === "object"
|
||||
? String((errorBody.error as { message?: unknown }).message ?? `HTTP ${response.status}`)
|
||||
: `HTTP ${response.status}`;
|
||||
throw new ToolctrlApiError(response.status, message, errorBody, requestId);
|
||||
throw new HiveGridApiError(response.status, message, errorBody, requestId);
|
||||
}
|
||||
|
||||
// Network error path
|
||||
@@ -292,7 +292,7 @@ export function createToolctrlClient(config: ToolctrlClientConfig): ToolctrlClie
|
||||
break;
|
||||
}
|
||||
|
||||
throw new ToolctrlNetworkError("Network request failed after retries", lastError);
|
||||
throw new HiveGridNetworkError("Network request failed after retries", lastError);
|
||||
}
|
||||
|
||||
async function* paginate<T = unknown>(path: string, options: PaginateOptions = {}): AsyncIterable<T> {
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
// @vitest-environment node
|
||||
// Mirrors generated-client.test.ts: the generated fetch client runs server-side,
|
||||
// so we pin the node environment to match the real runtime (Headers/Response
|
||||
// semantics differ under jsdom).
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createClient } from "./generated/client/client.gen.js";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function eventStream(chunks: Array<string>): ReadableStream<Uint8Array> {
|
||||
let index = 0;
|
||||
return new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
if (index < chunks.length) {
|
||||
controller.enqueue(encoder.encode(chunks[index]));
|
||||
index += 1;
|
||||
return;
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("generated fetch client — response parsing matrix", () => {
|
||||
it("parses a text/plain body via content-type auto-detection", async () => {
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response("just text", { headers: { "Content-Type": "text/plain" } }),
|
||||
responseStyle: "data",
|
||||
});
|
||||
await expect(client.get({ url: "/v1/text" })).resolves.toBe("just text");
|
||||
});
|
||||
|
||||
it("parses a binary body as a Blob", async () => {
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response(new Blob([new Uint8Array([1, 2, 3])]), { headers: { "Content-Type": "image/png" } }),
|
||||
responseStyle: "data",
|
||||
});
|
||||
const blob = (await client.get({ url: "/v1/img" })) as unknown as Blob;
|
||||
expect(blob).toBeInstanceOf(Blob);
|
||||
expect(blob.size).toBe(3);
|
||||
});
|
||||
|
||||
it("parses an explicit arrayBuffer response", async () => {
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response(new Uint8Array([7, 8]).buffer, { headers: { "Content-Type": "application/octet-stream" } }),
|
||||
responseStyle: "data",
|
||||
});
|
||||
const buf = (await client.get({ parseAs: "arrayBuffer", url: "/v1/bin" })) as unknown as ArrayBuffer;
|
||||
expect(buf.byteLength).toBe(2);
|
||||
});
|
||||
|
||||
it("returns the raw stream when parseAs is stream", async () => {
|
||||
const body = eventStream(["chunk"]);
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response(body, { headers: { "Content-Type": "application/octet-stream" } }),
|
||||
responseStyle: "data",
|
||||
});
|
||||
const result = await client.get({ parseAs: "stream", url: "/v1/stream" });
|
||||
expect(result).toBeInstanceOf(ReadableStream);
|
||||
});
|
||||
|
||||
it("returns an empty object for a 200 JSON response with an empty body", async () => {
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response("", { headers: { "Content-Type": "application/json" } }),
|
||||
responseStyle: "data",
|
||||
});
|
||||
await expect(client.get({ url: "/v1/empty-json" })).resolves.toEqual({});
|
||||
});
|
||||
|
||||
it("returns empty text for a 204 with parseAs text", async () => {
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response(null, { status: 204 }),
|
||||
responseStyle: "data",
|
||||
});
|
||||
await expect(client.delete({ parseAs: "text", url: "/v1/gone" })).resolves.toBe("");
|
||||
});
|
||||
|
||||
it("treats a Content-Length:0 response as an empty result", async () => {
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response("", { headers: { "Content-Length": "0", "Content-Type": "application/json" } }),
|
||||
responseStyle: "data",
|
||||
});
|
||||
await expect(client.get({ url: "/v1/no-content" })).resolves.toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("generated fetch client — response style fields", () => {
|
||||
it("wraps successful data with request and response when responseStyle is fields", async () => {
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response('{"id":"x"}', { headers: { "Content-Type": "application/json" } }),
|
||||
responseStyle: "fields",
|
||||
});
|
||||
const result = (await client.get({ url: "/v1/thing" })) as {
|
||||
data: { id: string };
|
||||
response: Response;
|
||||
request: Request;
|
||||
};
|
||||
expect(result.data).toEqual({ id: "x" });
|
||||
expect(result.response.status).toBe(200);
|
||||
expect(result.request).toBeInstanceOf(Request);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generated fetch client — error handling", () => {
|
||||
it("throws the raw text error when the body is not JSON and throwOnError is set", async () => {
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response("upstream exploded", { status: 502 }),
|
||||
throwOnError: true,
|
||||
});
|
||||
await expect(client.get({ url: "/v1/boom" })).rejects.toBe("upstream exploded");
|
||||
});
|
||||
|
||||
it("returns an error envelope for a non-JSON error when throwOnError is disabled", async () => {
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async () => new Response("nope", { status: 500 }),
|
||||
throwOnError: false,
|
||||
responseStyle: "fields",
|
||||
});
|
||||
const result = (await client.get({ url: "/v1/boom" })) as { error: unknown; response: Response };
|
||||
expect(result.error).toBe("nope");
|
||||
expect(result.response.status).toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generated fetch client — SSE method wiring", () => {
|
||||
it("opens an SSE stream and runs request interceptors through onRequest", async () => {
|
||||
let interceptorRan = false;
|
||||
const client = createClient({
|
||||
baseUrl: "https://api.example.test",
|
||||
fetch: async (requestInfo) => {
|
||||
const request = requestInfo as Request;
|
||||
// The interceptor registered below must have stamped the header before fetch.
|
||||
expect(request.headers.get("X-Sse-Interceptor")).toBe("ran");
|
||||
return new Response(eventStream(['data: {"n":1}\n\n']), { headers: { "Content-Type": "text/event-stream" } });
|
||||
},
|
||||
});
|
||||
|
||||
client.interceptors.request.use((request) => {
|
||||
interceptorRan = true;
|
||||
request.headers.set("X-Sse-Interceptor", "ran");
|
||||
return request;
|
||||
});
|
||||
|
||||
const sse = await client.sse.get<{ n: number }>({ url: "/v1/stream" });
|
||||
await expect(sse.stream.next()).resolves.toEqual({ done: false, value: { n: 1 } });
|
||||
expect(interceptorRan).toBe(true);
|
||||
});
|
||||
});
|
||||
+6
@@ -1,3 +1,9 @@
|
||||
// @vitest-environment node
|
||||
// The generated SDK runs server-side (Node), where Headers.append("Cookie", ...)
|
||||
// is RFC-6265-joined with "; ". The repo-root vitest config defaults to jsdom, whose
|
||||
// Headers polyfill joins Cookie with ", " and breaks the auth-cookie assertion. Pin
|
||||
// node here so the test matches the real runtime; keeps src/generated/ codegen-clean
|
||||
// (no manual edit → no SDK-codegen-drift failure).
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getAuthToken } from "./generated/core/auth.gen.js";
|
||||
import { createClient } from "./generated/client/client.gen.js";
|
||||
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
separatorArrayExplode,
|
||||
separatorArrayNoExplode,
|
||||
separatorObjectExplode,
|
||||
serializeArrayParam,
|
||||
serializeObjectParam,
|
||||
serializePrimitiveParam,
|
||||
} from "./generated/core/pathSerializer.gen.js";
|
||||
import { defaultPathSerializer, getUrl, getValidRequestBody } from "./generated/core/utils.gen.js";
|
||||
import { queryKeyJsonReplacer, serializeQueryKeyValue } from "./generated/core/queryKeySerializer.gen.js";
|
||||
import { buildClientParams } from "./generated/core/params.gen.js";
|
||||
|
||||
describe("pathSerializer separators (RFC6570 style table)", () => {
|
||||
it("maps explode separators per style", () => {
|
||||
expect(separatorArrayExplode("matrix")).toBe(";");
|
||||
expect(separatorArrayExplode("simple")).toBe(",");
|
||||
expect(separatorArrayExplode("form")).toBe("&");
|
||||
});
|
||||
|
||||
it("maps no-explode separators per style", () => {
|
||||
expect(separatorArrayNoExplode("form")).toBe(",");
|
||||
expect(separatorArrayNoExplode("spaceDelimited")).toBe("%20");
|
||||
// unknown styles fall back to a comma
|
||||
expect(separatorArrayNoExplode("simple")).toBe(",");
|
||||
});
|
||||
|
||||
it("maps object explode separators per style", () => {
|
||||
expect(separatorObjectExplode("label")).toBe(".");
|
||||
expect(separatorObjectExplode("simple")).toBe(",");
|
||||
expect(separatorObjectExplode("form")).toBe("&");
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeArrayParam — non-explode styles", () => {
|
||||
it("serializes label, matrix, and simple styles", () => {
|
||||
expect(serializeArrayParam({ explode: false, name: "x", style: "label", value: ["a", "b"] })).toBe(".a,b");
|
||||
expect(serializeArrayParam({ explode: false, name: "x", style: "matrix", value: ["a", "b"] })).toBe(";x=a,b");
|
||||
expect(serializeArrayParam({ explode: false, name: "x", style: "simple", value: ["a", "b"] })).toBe("a,b");
|
||||
});
|
||||
|
||||
it("keeps reserved characters when allowReserved is set", () => {
|
||||
expect(serializeArrayParam({ allowReserved: true, explode: false, name: "x", style: "form", value: ["a/b", "c"] })).toBe("x=a/b,c");
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeArrayParam — explode styles", () => {
|
||||
it("uses the style separator and encodes each member for label/simple", () => {
|
||||
expect(serializeArrayParam({ explode: true, name: "x", style: "label", value: ["a/b", "c"] })).toBe(".a%2Fb.c");
|
||||
expect(serializeArrayParam({ explode: true, name: "x", style: "simple", value: ["a/b", "c"] })).toBe("a%2Fb,c");
|
||||
});
|
||||
|
||||
it("emits name=value pairs for matrix and form", () => {
|
||||
expect(serializeArrayParam({ explode: true, name: "id", style: "matrix", value: ["a", "b"] })).toBe(";id=a;id=b");
|
||||
expect(serializeArrayParam({ explode: true, name: "id", style: "form", value: ["a", "b"] })).toBe("id=a&id=b");
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializePrimitiveParam — nullish guards", () => {
|
||||
it("returns an empty string for null and undefined", () => {
|
||||
expect(serializePrimitiveParam({ name: "x", value: undefined as never })).toBe("");
|
||||
expect(serializePrimitiveParam({ name: "x", value: null as never })).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeObjectParam — non-explode styles", () => {
|
||||
it("serializes matrix and the default (simple) styles", () => {
|
||||
expect(serializeObjectParam({ explode: false, name: "f", style: "matrix", value: { status: "open", owner: "me" } })).toBe(
|
||||
";f=status,open,owner,me"
|
||||
);
|
||||
expect(serializeObjectParam({ explode: false, name: "f", style: "simple" as never, value: { status: "open" } })).toBe("status,open");
|
||||
});
|
||||
|
||||
it("keeps reserved characters in object values when allowReserved is set", () => {
|
||||
expect(serializeObjectParam({ allowReserved: true, explode: false, name: "f", style: "form", value: { path: "a/b" } })).toBe(
|
||||
"f=path,a/b"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("defaultPathSerializer — uncommon param shapes", () => {
|
||||
it("leaves a placeholder untouched when the value is missing", () => {
|
||||
expect(defaultPathSerializer({ path: {}, url: "/v1/{ghost}" })).toBe("/v1/{ghost}");
|
||||
});
|
||||
|
||||
it("serializes a matrix-style primitive path parameter", () => {
|
||||
expect(defaultPathSerializer({ path: { id: "5" }, url: "/v1/{;id}" })).toBe("/v1/;id=5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUrl — without a base url", () => {
|
||||
it("prefixes nothing when baseUrl is omitted", () => {
|
||||
const url = getUrl({
|
||||
path: { id: "a" },
|
||||
query: { x: 1 },
|
||||
querySerializer: (q) => `x=${(q as { x: number }).x}`,
|
||||
url: "v1/{id}",
|
||||
});
|
||||
expect(url).toBe("/v1/a?x=1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getValidRequestBody — serializer without serializedBody property", () => {
|
||||
it("returns the raw body when no serializedBody key is present", () => {
|
||||
expect(getValidRequestBody({ body: { ok: true }, bodySerializer: JSON.stringify })).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it("returns null for an empty body even without a serializedBody key", () => {
|
||||
expect(getValidRequestBody({ body: "", bodySerializer: JSON.stringify })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("queryKeyJsonReplacer", () => {
|
||||
it("converts Date and bigint, and drops functions/undefined", () => {
|
||||
expect(queryKeyJsonReplacer("k", new Date("2026-01-02T03:04:05.000Z"))).toBe("2026-01-02T03:04:05.000Z");
|
||||
expect(queryKeyJsonReplacer("k", 7n)).toBe("7");
|
||||
expect(queryKeyJsonReplacer("k", undefined)).toBeUndefined();
|
||||
expect(queryKeyJsonReplacer("k", () => undefined)).toBeUndefined();
|
||||
expect(queryKeyJsonReplacer("k", "kept")).toBe("kept");
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeQueryKeyValue — primitive and edge inputs", () => {
|
||||
it("passes through null, numbers, and booleans", () => {
|
||||
expect(serializeQueryKeyValue(null)).toBeNull();
|
||||
expect(serializeQueryKeyValue(42)).toBe(42);
|
||||
expect(serializeQueryKeyValue(true)).toBe(true);
|
||||
});
|
||||
|
||||
it("normalizes bigint and Date scalars", () => {
|
||||
expect(serializeQueryKeyValue(99n)).toBe("99");
|
||||
expect(serializeQueryKeyValue(new Date("2026-01-02T00:00:00.000Z"))).toBe("2026-01-02T00:00:00.000Z");
|
||||
});
|
||||
|
||||
it("serializes arrays via JSON round-trip", () => {
|
||||
expect(serializeQueryKeyValue([1, "a", true])).toEqual([1, "a", true]);
|
||||
});
|
||||
|
||||
it("collapses three repeated search-param keys into one array", () => {
|
||||
const params = new URLSearchParams([
|
||||
["a", "1"],
|
||||
["a", "2"],
|
||||
["a", "3"],
|
||||
]);
|
||||
expect(serializeQueryKeyValue(params)).toEqual({ a: ["1", "2", "3"] });
|
||||
});
|
||||
|
||||
it("returns undefined for non-plain objects like Map", () => {
|
||||
expect(serializeQueryKeyValue(new Map([["a", 1]]))).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildClientParams — sparse and aliasing configs", () => {
|
||||
it("skips arguments that have no matching field config", () => {
|
||||
expect(buildClientParams(["orphan"], [])).toEqual({});
|
||||
});
|
||||
|
||||
it("tolerates an undefined object argument", () => {
|
||||
expect(buildClientParams([undefined], [{ args: [{ in: "query", key: "q" }] }])).toEqual({});
|
||||
});
|
||||
|
||||
it("falls back to the field key when no map override is given", () => {
|
||||
expect(buildClientParams([{ q: "drill" }], [{ args: [{ in: "query", key: "q" }] }])).toEqual({ query: { q: "drill" } });
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -13,4 +13,4 @@ import type { ClientOptions as ClientOptions2 } from "./types.gen";
|
||||
*/
|
||||
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
|
||||
|
||||
export const client = createClient(createConfig<ClientOptions2>({ baseUrl: "https://api.toolctrl.de" }));
|
||||
export const client = createClient(createConfig<ClientOptions2>({ baseUrl: "https://api.hivegrid.de" }));
|
||||
+47
-58
@@ -4,12 +4,8 @@ export {
|
||||
acceptWorkspaceInvite,
|
||||
createAnalyticsEvent,
|
||||
createAnalyticsPageView,
|
||||
createLegacyEntityRow,
|
||||
createLegacyRowRelationship,
|
||||
createSupportTicketFromInboundEmail,
|
||||
createWorkspaceInvite,
|
||||
deleteLegacyEntityRow,
|
||||
deleteLegacyRowRelationship,
|
||||
enqueueExportArtifactRetention,
|
||||
getAccount,
|
||||
getAdminAnalyticsOverview,
|
||||
@@ -19,9 +15,6 @@ export {
|
||||
getExportDownloadUrl,
|
||||
getExportJobProgress,
|
||||
getHealthz,
|
||||
getLegacyEntityByName,
|
||||
getLegacyEntityRow,
|
||||
getLegacyRowRelationship,
|
||||
getMetrics,
|
||||
getOpenApiDocument,
|
||||
getPublicAnalyticsOverview,
|
||||
@@ -29,7 +22,12 @@ export {
|
||||
getStatus,
|
||||
getV1Health,
|
||||
listAccounts,
|
||||
listLegacyEntityRows,
|
||||
listPublicApiCompanies,
|
||||
listPublicApiContacts,
|
||||
listPublicApiDeals,
|
||||
listPublicApiLeads,
|
||||
listPublicApiProjects,
|
||||
listPublicApiTasks,
|
||||
listWorkspaceAuthProviders,
|
||||
listWorkspaceInvites,
|
||||
loginWithPassword,
|
||||
@@ -38,13 +36,13 @@ export {
|
||||
postDeviceRegister,
|
||||
postDeviceRevoke,
|
||||
receiveEmailSequenceMailjetWebhook,
|
||||
receiveStripeBillingWebhook,
|
||||
receiveMollieBillingWebhook,
|
||||
receivePublicApiIncomingWebhook,
|
||||
refreshJwtToken,
|
||||
retryEventWebhookAttempt,
|
||||
revalidateWorkspaceContext,
|
||||
revokeWorkspaceInvite,
|
||||
streamNotifications,
|
||||
updateLegacyEntityRow,
|
||||
uploadAiFile,
|
||||
validateApiKey,
|
||||
} from "./sdk.gen";
|
||||
@@ -65,16 +63,6 @@ export type {
|
||||
CreateAnalyticsPageViewErrors,
|
||||
CreateAnalyticsPageViewResponse,
|
||||
CreateAnalyticsPageViewResponses,
|
||||
CreateLegacyEntityRowData,
|
||||
CreateLegacyEntityRowError,
|
||||
CreateLegacyEntityRowErrors,
|
||||
CreateLegacyEntityRowResponse,
|
||||
CreateLegacyEntityRowResponses,
|
||||
CreateLegacyRowRelationshipData,
|
||||
CreateLegacyRowRelationshipError,
|
||||
CreateLegacyRowRelationshipErrors,
|
||||
CreateLegacyRowRelationshipResponse,
|
||||
CreateLegacyRowRelationshipResponses,
|
||||
CreateSupportTicketFromInboundEmailData,
|
||||
CreateSupportTicketFromInboundEmailError,
|
||||
CreateSupportTicketFromInboundEmailErrors,
|
||||
@@ -84,16 +72,6 @@ export type {
|
||||
CreateWorkspaceInviteErrors,
|
||||
CreateWorkspaceInviteResponse,
|
||||
CreateWorkspaceInviteResponses,
|
||||
DeleteLegacyEntityRowData,
|
||||
DeleteLegacyEntityRowError,
|
||||
DeleteLegacyEntityRowErrors,
|
||||
DeleteLegacyEntityRowResponse,
|
||||
DeleteLegacyEntityRowResponses,
|
||||
DeleteLegacyRowRelationshipData,
|
||||
DeleteLegacyRowRelationshipError,
|
||||
DeleteLegacyRowRelationshipErrors,
|
||||
DeleteLegacyRowRelationshipResponse,
|
||||
DeleteLegacyRowRelationshipResponses,
|
||||
EnqueueExportArtifactRetentionData,
|
||||
EnqueueExportArtifactRetentionError,
|
||||
EnqueueExportArtifactRetentionErrors,
|
||||
@@ -134,20 +112,6 @@ export type {
|
||||
GetHealthzData,
|
||||
GetHealthzResponse,
|
||||
GetHealthzResponses,
|
||||
GetLegacyEntityByNameData,
|
||||
GetLegacyEntityByNameError,
|
||||
GetLegacyEntityByNameErrors,
|
||||
GetLegacyEntityByNameResponses,
|
||||
GetLegacyEntityRowData,
|
||||
GetLegacyEntityRowError,
|
||||
GetLegacyEntityRowErrors,
|
||||
GetLegacyEntityRowResponse,
|
||||
GetLegacyEntityRowResponses,
|
||||
GetLegacyRowRelationshipData,
|
||||
GetLegacyRowRelationshipError,
|
||||
GetLegacyRowRelationshipErrors,
|
||||
GetLegacyRowRelationshipResponse,
|
||||
GetLegacyRowRelationshipResponses,
|
||||
GetMetricsData,
|
||||
GetMetricsError,
|
||||
GetMetricsErrors,
|
||||
@@ -178,11 +142,36 @@ export type {
|
||||
ListAccountsErrors,
|
||||
ListAccountsResponse,
|
||||
ListAccountsResponses,
|
||||
ListLegacyEntityRowsData,
|
||||
ListLegacyEntityRowsError,
|
||||
ListLegacyEntityRowsErrors,
|
||||
ListLegacyEntityRowsResponse,
|
||||
ListLegacyEntityRowsResponses,
|
||||
ListPublicApiCompaniesData,
|
||||
ListPublicApiCompaniesError,
|
||||
ListPublicApiCompaniesErrors,
|
||||
ListPublicApiCompaniesResponse,
|
||||
ListPublicApiCompaniesResponses,
|
||||
ListPublicApiContactsData,
|
||||
ListPublicApiContactsError,
|
||||
ListPublicApiContactsErrors,
|
||||
ListPublicApiContactsResponse,
|
||||
ListPublicApiContactsResponses,
|
||||
ListPublicApiDealsData,
|
||||
ListPublicApiDealsError,
|
||||
ListPublicApiDealsErrors,
|
||||
ListPublicApiDealsResponse,
|
||||
ListPublicApiDealsResponses,
|
||||
ListPublicApiLeadsData,
|
||||
ListPublicApiLeadsError,
|
||||
ListPublicApiLeadsErrors,
|
||||
ListPublicApiLeadsResponse,
|
||||
ListPublicApiLeadsResponses,
|
||||
ListPublicApiProjectsData,
|
||||
ListPublicApiProjectsError,
|
||||
ListPublicApiProjectsErrors,
|
||||
ListPublicApiProjectsResponse,
|
||||
ListPublicApiProjectsResponses,
|
||||
ListPublicApiTasksData,
|
||||
ListPublicApiTasksError,
|
||||
ListPublicApiTasksErrors,
|
||||
ListPublicApiTasksResponse,
|
||||
ListPublicApiTasksResponses,
|
||||
ListWorkspaceAuthProvidersData,
|
||||
ListWorkspaceAuthProvidersError,
|
||||
ListWorkspaceAuthProvidersErrors,
|
||||
@@ -215,10 +204,15 @@ export type {
|
||||
ReceiveEmailSequenceMailjetWebhookError,
|
||||
ReceiveEmailSequenceMailjetWebhookErrors,
|
||||
ReceiveEmailSequenceMailjetWebhookResponses,
|
||||
ReceiveStripeBillingWebhookData,
|
||||
ReceiveStripeBillingWebhookError,
|
||||
ReceiveStripeBillingWebhookErrors,
|
||||
ReceiveStripeBillingWebhookResponses,
|
||||
ReceiveMollieBillingWebhookData,
|
||||
ReceiveMollieBillingWebhookError,
|
||||
ReceiveMollieBillingWebhookErrors,
|
||||
ReceiveMollieBillingWebhookResponses,
|
||||
ReceivePublicApiIncomingWebhookData,
|
||||
ReceivePublicApiIncomingWebhookError,
|
||||
ReceivePublicApiIncomingWebhookErrors,
|
||||
ReceivePublicApiIncomingWebhookResponse,
|
||||
ReceivePublicApiIncomingWebhookResponses,
|
||||
RefreshJwtTokenData,
|
||||
RefreshJwtTokenError,
|
||||
RefreshJwtTokenErrors,
|
||||
@@ -242,11 +236,6 @@ export type {
|
||||
StreamNotificationsErrors,
|
||||
StreamNotificationsResponse,
|
||||
StreamNotificationsResponses,
|
||||
UpdateLegacyEntityRowData,
|
||||
UpdateLegacyEntityRowError,
|
||||
UpdateLegacyEntityRowErrors,
|
||||
UpdateLegacyEntityRowResponse,
|
||||
UpdateLegacyEntityRowResponses,
|
||||
UploadAiFileData,
|
||||
UploadAiFileError,
|
||||
UploadAiFileErrors,
|
||||
|
||||
+110
-161
@@ -1,6 +1,6 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Client, Options as Options2, TDataShape } from "./client";
|
||||
import { type Client, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from "./client";
|
||||
import { client } from "./client.gen";
|
||||
import type {
|
||||
AcceptWorkspaceInviteData,
|
||||
@@ -12,24 +12,12 @@ import type {
|
||||
CreateAnalyticsPageViewData,
|
||||
CreateAnalyticsPageViewErrors,
|
||||
CreateAnalyticsPageViewResponses,
|
||||
CreateLegacyEntityRowData,
|
||||
CreateLegacyEntityRowErrors,
|
||||
CreateLegacyEntityRowResponses,
|
||||
CreateLegacyRowRelationshipData,
|
||||
CreateLegacyRowRelationshipErrors,
|
||||
CreateLegacyRowRelationshipResponses,
|
||||
CreateSupportTicketFromInboundEmailData,
|
||||
CreateSupportTicketFromInboundEmailErrors,
|
||||
CreateSupportTicketFromInboundEmailResponses,
|
||||
CreateWorkspaceInviteData,
|
||||
CreateWorkspaceInviteErrors,
|
||||
CreateWorkspaceInviteResponses,
|
||||
DeleteLegacyEntityRowData,
|
||||
DeleteLegacyEntityRowErrors,
|
||||
DeleteLegacyEntityRowResponses,
|
||||
DeleteLegacyRowRelationshipData,
|
||||
DeleteLegacyRowRelationshipErrors,
|
||||
DeleteLegacyRowRelationshipResponses,
|
||||
EnqueueExportArtifactRetentionData,
|
||||
EnqueueExportArtifactRetentionErrors,
|
||||
EnqueueExportArtifactRetentionResponses,
|
||||
@@ -55,15 +43,6 @@ import type {
|
||||
GetExportJobProgressResponses,
|
||||
GetHealthzData,
|
||||
GetHealthzResponses,
|
||||
GetLegacyEntityByNameData,
|
||||
GetLegacyEntityByNameErrors,
|
||||
GetLegacyEntityByNameResponses,
|
||||
GetLegacyEntityRowData,
|
||||
GetLegacyEntityRowErrors,
|
||||
GetLegacyEntityRowResponses,
|
||||
GetLegacyRowRelationshipData,
|
||||
GetLegacyRowRelationshipErrors,
|
||||
GetLegacyRowRelationshipResponses,
|
||||
GetMetricsData,
|
||||
GetMetricsErrors,
|
||||
GetMetricsResponses,
|
||||
@@ -83,9 +62,24 @@ import type {
|
||||
ListAccountsData,
|
||||
ListAccountsErrors,
|
||||
ListAccountsResponses,
|
||||
ListLegacyEntityRowsData,
|
||||
ListLegacyEntityRowsErrors,
|
||||
ListLegacyEntityRowsResponses,
|
||||
ListPublicApiCompaniesData,
|
||||
ListPublicApiCompaniesErrors,
|
||||
ListPublicApiCompaniesResponses,
|
||||
ListPublicApiContactsData,
|
||||
ListPublicApiContactsErrors,
|
||||
ListPublicApiContactsResponses,
|
||||
ListPublicApiDealsData,
|
||||
ListPublicApiDealsErrors,
|
||||
ListPublicApiDealsResponses,
|
||||
ListPublicApiLeadsData,
|
||||
ListPublicApiLeadsErrors,
|
||||
ListPublicApiLeadsResponses,
|
||||
ListPublicApiProjectsData,
|
||||
ListPublicApiProjectsErrors,
|
||||
ListPublicApiProjectsResponses,
|
||||
ListPublicApiTasksData,
|
||||
ListPublicApiTasksErrors,
|
||||
ListPublicApiTasksResponses,
|
||||
ListWorkspaceAuthProvidersData,
|
||||
ListWorkspaceAuthProvidersErrors,
|
||||
ListWorkspaceAuthProvidersResponses,
|
||||
@@ -107,9 +101,12 @@ import type {
|
||||
ReceiveEmailSequenceMailjetWebhookData,
|
||||
ReceiveEmailSequenceMailjetWebhookErrors,
|
||||
ReceiveEmailSequenceMailjetWebhookResponses,
|
||||
ReceiveStripeBillingWebhookData,
|
||||
ReceiveStripeBillingWebhookErrors,
|
||||
ReceiveStripeBillingWebhookResponses,
|
||||
ReceiveMollieBillingWebhookData,
|
||||
ReceiveMollieBillingWebhookErrors,
|
||||
ReceiveMollieBillingWebhookResponses,
|
||||
ReceivePublicApiIncomingWebhookData,
|
||||
ReceivePublicApiIncomingWebhookErrors,
|
||||
ReceivePublicApiIncomingWebhookResponses,
|
||||
RefreshJwtTokenData,
|
||||
RefreshJwtTokenErrors,
|
||||
RefreshJwtTokenResponses,
|
||||
@@ -126,9 +123,6 @@ import type {
|
||||
StreamNotificationsErrors,
|
||||
StreamNotificationsResponse,
|
||||
StreamNotificationsResponses,
|
||||
UpdateLegacyEntityRowData,
|
||||
UpdateLegacyEntityRowErrors,
|
||||
UpdateLegacyEntityRowResponses,
|
||||
UploadAiFileData,
|
||||
UploadAiFileErrors,
|
||||
UploadAiFileResponses,
|
||||
@@ -403,12 +397,76 @@ export const getApiUsage = <ThrowOnError extends boolean = false>(options?: Opti
|
||||
});
|
||||
|
||||
/**
|
||||
* Canonical API-host entry point for Stripe billing lifecycle webhooks. The API runtime preserves the raw body and signature headers and applies subscription updates through API-owned billing services.
|
||||
* Tenant-scoped private-person contacts from the CRM core. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
|
||||
*/
|
||||
export const receiveStripeBillingWebhook = <ThrowOnError extends boolean = false>(options: Options<ReceiveStripeBillingWebhookData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<ReceiveStripeBillingWebhookResponses, ReceiveStripeBillingWebhookErrors, ThrowOnError>({
|
||||
security: [{ name: "stripe-signature", type: "apiKey" }],
|
||||
url: "/v1/billing/stripe/webhooks",
|
||||
export const listPublicApiContacts = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiContactsData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<ListPublicApiContactsResponses, ListPublicApiContactsErrors, ThrowOnError>({
|
||||
security: [{ name: "x-api-key", type: "apiKey" }],
|
||||
url: "/v1/contacts",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Tenant-scoped organisation contacts from the CRM core. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
|
||||
*/
|
||||
export const listPublicApiCompanies = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiCompaniesData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<ListPublicApiCompaniesResponses, ListPublicApiCompaniesErrors, ThrowOnError>({
|
||||
security: [{ name: "x-api-key", type: "apiKey" }],
|
||||
url: "/v1/companies",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Sales-pipeline project view. Deals and projects share the Projekt core. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
|
||||
*/
|
||||
export const listPublicApiDeals = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiDealsData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<ListPublicApiDealsResponses, ListPublicApiDealsErrors, ThrowOnError>({
|
||||
security: [{ name: "x-api-key", type: "apiKey" }],
|
||||
url: "/v1/deals",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Tenant-scoped project records from the Projekt core. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
|
||||
*/
|
||||
export const listPublicApiProjects = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiProjectsData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<ListPublicApiProjectsResponses, ListPublicApiProjectsErrors, ThrowOnError>({
|
||||
security: [{ name: "x-api-key", type: "apiKey" }],
|
||||
url: "/v1/projects",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Tenant-scoped task records. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
|
||||
*/
|
||||
export const listPublicApiTasks = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiTasksData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<ListPublicApiTasksResponses, ListPublicApiTasksErrors, ThrowOnError>({
|
||||
security: [{ name: "x-api-key", type: "apiKey" }],
|
||||
url: "/v1/tasks",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Tenant-scoped lead-inbox records. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
|
||||
*/
|
||||
export const listPublicApiLeads = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiLeadsData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<ListPublicApiLeadsResponses, ListPublicApiLeadsErrors, ThrowOnError>({
|
||||
security: [{ name: "x-api-key", type: "apiKey" }],
|
||||
url: "/v1/leads",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Tenant-scoped incoming lead webhook. The endpoint authenticates by the endpoint's configured mode: API key, HMAC token/signature, or URL/header token. Successful requests create an InboxLead and queue webhook.received automation executions.
|
||||
*/
|
||||
export const receivePublicApiIncomingWebhook = <ThrowOnError extends boolean = false>(options: Options<ReceivePublicApiIncomingWebhookData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<ReceivePublicApiIncomingWebhookResponses, ReceivePublicApiIncomingWebhookErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ name: "x-api-key", type: "apiKey" },
|
||||
{ name: "X-HiveGrid-Webhook-Token", type: "apiKey" },
|
||||
{ name: "X-HiveGrid-Signature", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/webhooks/incoming/{tenant}/{slug}",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -416,6 +474,20 @@ export const receiveStripeBillingWebhook = <ThrowOnError extends boolean = false
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Canonical API-host entry point for Mollie payment lifecycle webhooks. Mollie posts a payment id; the API refetches that payment from Mollie server-side before syncing tenant billing state.
|
||||
*/
|
||||
export const receiveMollieBillingWebhook = <ThrowOnError extends boolean = false>(options: Options<ReceiveMollieBillingWebhookData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<ReceiveMollieBillingWebhookResponses, ReceiveMollieBillingWebhookErrors, ThrowOnError>({
|
||||
...urlSearchParamsBodySerializer,
|
||||
url: "/v1/billing/mollie/webhooks",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Accepts Mailjet provider event webhooks for email sequences, authenticated with HTTP Basic Auth. Bounce, blocked, and spam events correlate by provider message id (Message_GUID), mark the sequence delivery bounced, and fail the in-flight run without echoing provider payloads.
|
||||
*/
|
||||
@@ -453,122 +525,6 @@ export const enqueueExportArtifactRetention = <ThrowOnError extends boolean = fa
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
|
||||
*/
|
||||
export const listLegacyEntityRows = <ThrowOnError extends boolean = false>(options: Options<ListLegacyEntityRowsData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<ListLegacyEntityRowsResponses, ListLegacyEntityRowsErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ scheme: "bearer", type: "http" },
|
||||
{ name: "x-api-key", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/entities/{entity}/rows",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
|
||||
*/
|
||||
export const createLegacyEntityRow = <ThrowOnError extends boolean = false>(options: Options<CreateLegacyEntityRowData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<CreateLegacyEntityRowResponses, CreateLegacyEntityRowErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ scheme: "bearer", type: "http" },
|
||||
{ name: "x-api-key", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/entities/{entity}/rows",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
|
||||
*/
|
||||
export const deleteLegacyEntityRow = <ThrowOnError extends boolean = false>(options: Options<DeleteLegacyEntityRowData, ThrowOnError>) =>
|
||||
(options.client ?? client).delete<DeleteLegacyEntityRowResponses, DeleteLegacyEntityRowErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ scheme: "bearer", type: "http" },
|
||||
{ name: "x-api-key", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/entities/{entity}/rows/{rowId}",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
|
||||
*/
|
||||
export const getLegacyEntityRow = <ThrowOnError extends boolean = false>(options: Options<GetLegacyEntityRowData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<GetLegacyEntityRowResponses, GetLegacyEntityRowErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ scheme: "bearer", type: "http" },
|
||||
{ name: "x-api-key", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/entities/{entity}/rows/{rowId}",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
|
||||
*/
|
||||
export const updateLegacyEntityRow = <ThrowOnError extends boolean = false>(options: Options<UpdateLegacyEntityRowData, ThrowOnError>) =>
|
||||
(options.client ?? client).patch<UpdateLegacyEntityRowResponses, UpdateLegacyEntityRowErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ scheme: "bearer", type: "http" },
|
||||
{ name: "x-api-key", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/entities/{entity}/rows/{rowId}",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
|
||||
*/
|
||||
export const createLegacyRowRelationship = <ThrowOnError extends boolean = false>(options: Options<CreateLegacyRowRelationshipData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<CreateLegacyRowRelationshipResponses, CreateLegacyRowRelationshipErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ scheme: "bearer", type: "http" },
|
||||
{ name: "x-api-key", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/relationships",
|
||||
...options,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
|
||||
*/
|
||||
export const deleteLegacyRowRelationship = <ThrowOnError extends boolean = false>(options: Options<DeleteLegacyRowRelationshipData, ThrowOnError>) =>
|
||||
(options.client ?? client).delete<DeleteLegacyRowRelationshipResponses, DeleteLegacyRowRelationshipErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ scheme: "bearer", type: "http" },
|
||||
{ name: "x-api-key", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/relationships/{id}",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
|
||||
*/
|
||||
export const getLegacyRowRelationship = <ThrowOnError extends boolean = false>(options: Options<GetLegacyRowRelationshipData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<GetLegacyRowRelationshipResponses, GetLegacyRowRelationshipErrors, ThrowOnError>({
|
||||
security: [
|
||||
{ scheme: "bearer", type: "http" },
|
||||
{ name: "x-api-key", type: "apiKey" },
|
||||
],
|
||||
url: "/v1/relationships/{id}",
|
||||
...options,
|
||||
});
|
||||
|
||||
/**
|
||||
* Creates a short-lived signed GET URL for a completed, unexpired export job. Authorize with either the configured service token bearer credential or a tenant-bound stored API key supplied in x-api-key; stored API keys are scoped to their own tenant and this route does not publish CRUD entity-scope claims. Responses never include export artifact bucket/key values, storage credentials, signed URL internals beyond the URL envelope, payload filters, or object bodies.
|
||||
*/
|
||||
@@ -596,7 +552,7 @@ export const getExportJobProgress = <ThrowOnError extends boolean = false>(optio
|
||||
});
|
||||
|
||||
/**
|
||||
* Register or update a mobile push token (APNs / FCM / WebPush) for the authenticated principal. Requires a service-token bearer credential; the body's userId + tenantId are reconciled downstream against the authenticated principal. Tokens are upserted by their globally unique value so cold-start replays are idempotent.
|
||||
* Register or update a Web Push token for the authenticated principal. Requires a service-token bearer credential; the body's userId + tenantId are reconciled downstream against the authenticated principal. Tokens are upserted by their globally unique value so cold-start replays are idempotent.
|
||||
*/
|
||||
export const postDeviceRegister = <ThrowOnError extends boolean = false>(options: Options<PostDeviceRegisterData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<PostDeviceRegisterResponses, PostDeviceRegisterErrors, ThrowOnError>({
|
||||
@@ -610,7 +566,7 @@ export const postDeviceRegister = <ThrowOnError extends boolean = false>(options
|
||||
});
|
||||
|
||||
/**
|
||||
* Revoke a mobile push token. Requires a service-token bearer credential; the handler revokes by token hash and never echoes the raw token in the response.
|
||||
* Revoke a Web Push token. Requires a service-token bearer credential; the handler revokes by token hash and never echoes the raw token in the response.
|
||||
*/
|
||||
export const postDeviceRevoke = <ThrowOnError extends boolean = false>(options: Options<PostDeviceRevokeData, ThrowOnError>) =>
|
||||
(options.client ?? client).post<PostDeviceRevokeResponses, PostDeviceRevokeErrors, ThrowOnError>({
|
||||
@@ -622,10 +578,3 @@ export const postDeviceRevoke = <ThrowOnError extends boolean = false>(options:
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
export const getLegacyEntityByName = <ThrowOnError extends boolean = false>(options: Options<GetLegacyEntityByNameData, ThrowOnError>) =>
|
||||
(options.client ?? client).get<GetLegacyEntityByNameResponses, GetLegacyEntityByNameErrors, ThrowOnError>({
|
||||
security: [{ scheme: "bearer", type: "http" }],
|
||||
url: "/v1/entities/{entity}",
|
||||
...options,
|
||||
});
|
||||
+1305
-834
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* @toolctrl/api-client-ts
|
||||
* @hivegrid/api-client-ts
|
||||
*
|
||||
* Official TypeScript SDK for the toolctrl boilerplate REST API.
|
||||
* Official TypeScript SDK for the HiveGrid REST API.
|
||||
*
|
||||
* The public surface is a thin Higher-Level-Wrapper around the @hey-api/openapi-ts
|
||||
* generated client. The wrapper adds auth header injection, retry with exponential
|
||||
@@ -12,14 +12,14 @@
|
||||
*/
|
||||
|
||||
export {
|
||||
createToolctrlClient,
|
||||
ToolctrlApiError,
|
||||
ToolctrlNetworkError,
|
||||
type ToolctrlClient,
|
||||
type ToolctrlClientConfig,
|
||||
type ToolctrlAuthConfig,
|
||||
type ToolctrlRetryConfig,
|
||||
type ToolctrlIdempotencyConfig,
|
||||
createHiveGridClient,
|
||||
HiveGridApiError,
|
||||
HiveGridNetworkError,
|
||||
type HiveGridClient,
|
||||
type HiveGridClientConfig,
|
||||
type HiveGridAuthConfig,
|
||||
type HiveGridRetryConfig,
|
||||
type HiveGridIdempotencyConfig,
|
||||
type PaginatedResponse,
|
||||
type PaginateOptions,
|
||||
} from "./client.js";
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { verifyWebhookSignature, signWebhookPayload } from "./webhooks.js";
|
||||
|
||||
const SECRET = "whsec_test_super_secret";
|
||||
const PAYLOAD = `{"event":"contact.created","data":{"id":"c_42"}}`;
|
||||
const TIMESTAMP = 1_700_000_000;
|
||||
|
||||
describe("verifyWebhookSignature — defensive paths", () => {
|
||||
it("returns false when the provided signature is same-length but not valid hex", () => {
|
||||
// expectedHex is 64 hex chars; a 64-char all-`g` string passes the length
|
||||
// gate but decodes to an empty buffer, so timingSafeEqual throws and is caught.
|
||||
const provided = "g".repeat(64);
|
||||
expect(
|
||||
verifyWebhookSignature({
|
||||
secret: SECRET,
|
||||
payload: PAYLOAD,
|
||||
signature: provided,
|
||||
timestamp: TIMESTAMP,
|
||||
now: () => TIMESTAMP * 1000,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("defaults to Date.now() for the replay window when no clock override is given", () => {
|
||||
const fresh = Math.floor(Date.now() / 1000);
|
||||
const signature = signWebhookPayload({ secret: SECRET, payload: PAYLOAD, timestamp: fresh });
|
||||
// No `now` passed → exercises the Date.now() default branch; a just-issued
|
||||
// signature is inside the 5-minute window.
|
||||
expect(verifyWebhookSignature({ secret: SECRET, payload: PAYLOAD, signature, timestamp: fresh })).toBe(true);
|
||||
});
|
||||
|
||||
it("does not strip a late `=` (index >= 16) as an algorithm prefix", () => {
|
||||
const signature = signWebhookPayload({ secret: SECRET, payload: PAYLOAD, timestamp: TIMESTAMP });
|
||||
// Insert an `=` past position 16 — normalizeSignature must keep the value as-is,
|
||||
// so the now-malformed/longer string fails verification rather than being trimmed.
|
||||
const withLateEquals = `${signature.slice(0, 20)}=${signature.slice(20)}`;
|
||||
expect(
|
||||
verifyWebhookSignature({
|
||||
secret: SECRET,
|
||||
payload: PAYLOAD,
|
||||
signature: withLateEquals,
|
||||
timestamp: TIMESTAMP,
|
||||
now: () => TIMESTAMP * 1000,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,7 @@ export interface VerifyWebhookOptions {
|
||||
secret: string;
|
||||
/** Raw request body, exactly as received (do not re-serialize). */
|
||||
payload: string | Buffer;
|
||||
/** Hex-encoded HMAC-SHA256 signature delivered via header (e.g. `X-Toolctrl-Signature`). */
|
||||
/** Hex-encoded HMAC-SHA256 signature delivered via header (e.g. `X-HiveGrid-Signature`). */
|
||||
signature: string;
|
||||
/** Unix timestamp in seconds when the webhook was emitted. */
|
||||
timestamp: number | string;
|
||||
|
||||
Reference in new issue
Block a user