UNPKG

@azowl/agentops-sdk

Version:

AgentOps REST client and local task execution SDK for Node.js

80 lines (70 loc) • 2.43 kB
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; export const HASH = /^[0-9a-f]{64}$/; export const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,159}$/; const MAX_RESPONSE_BYTES = 4 * 1024 * 1024; export class AgentOpsError extends Error { constructor(message, options = {}) { super(message); this.name = "AgentOpsError"; this.code = options.code ?? "REQUEST_FAILED"; this.status = options.status ?? null; this.clientRequestId = options.clientRequestId ?? null; this.requestId = options.requestId ?? null; this.retryAfterMs = options.retryAfterMs ?? null; this.outcomeUnknown = options.outcomeUnknown ?? false; } } export function fail(code, message) { throw new AgentOpsError(message, { code }); } export function object(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } export function uuid(value, field = "id") { if (typeof value !== "string" || !UUID.test(value)) { fail("INVALID_INPUT", `${field} must be a UUID.`); } return value.toLowerCase(); } export function duration(value, field) { if (!Number.isSafeInteger(value) || value < 1 || value > 2_147_483_647) { fail("INVALID_INPUT", `${field} must be a positive integer in milliseconds.`); } return value; } export function validUuid(value) { return typeof value === "string" && UUID.test(value); } export function invalidResponse() { fail("INVALID_RESPONSE", "The service returned an invalid response."); } export function scopeMismatch() { fail("RESPONSE_SCOPE_MISMATCH", "The response does not match the requested organization or operation."); } export async function jsonBody(response) { if (!response.body) invalidResponse(); const reader = response.body.getReader(); const decoder = new TextDecoder("utf-8", { fatal: true }); let bytes = 0; let text = ""; try { for (;;) { const chunk = await reader.read(); if (chunk.done) break; bytes += chunk.value.byteLength; if (bytes > MAX_RESPONSE_BYTES) { void reader.cancel().catch(() => {}); invalidResponse(); } text += decoder.decode(chunk.value, { stream: true }); } text += decoder.decode(); return JSON.parse(text); } catch (error) { void reader.cancel().catch(() => {}); if (error instanceof AgentOpsError) throw error; invalidResponse(); } finally { reader.releaseLock(); } }