Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,5 +1,5 @@
{
"name": "@toolctrl/error-reporter",
"name": "@hivegrid/error-reporter",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -16,7 +16,7 @@ import {
type SentryLikeModule,
} from "./index.js";
describe("@toolctrl/error-reporter", () => {
describe("@hivegrid/error-reporter", () => {
it("redacts nested secrets and unsafe payload keys while preserving correlation fields", () => {
const rawSecrets = [
"Bearer auth-token",
@@ -0,0 +1,40 @@
import { describe, expect, it, vi } from "vitest";
import { reportError, type ErrorReporter } from "./index.js";
describe("reportError reporter guard", () => {
it("is a no-op when the reporter is undefined", () => {
// The runtime wiring passes `undefined` whenever error reporting is not
// configured; the helper must never crash the call-site in that case.
expect(() => reportError(undefined, { component: "api", operation: "request" })).not.toThrow();
});
it("is a no-op when the reporter is null", () => {
expect(() => reportError(null, { component: "worker", operation: "job.failed" })).not.toThrow();
});
it("does not attempt to sanitize or deliver when the reporter is falsy", () => {
// A falsy reporter must short-circuit before any work happens. We prove this
// by passing an event whose getter would throw if it were ever read.
const exploding = {
component: "api",
operation: "request",
get secret(): never {
throw new Error("event must not be inspected when reporter is missing");
},
} as unknown as Parameters<typeof reportError>[1];
expect(() => reportError(undefined, exploding)).not.toThrow();
});
it("still delivers to a real reporter (positive control)", () => {
const report = vi.fn();
const reporter: ErrorReporter = { report };
reportError(reporter, { component: "api", operation: "request", token: "raw-token" });
expect(report).toHaveBeenCalledTimes(1);
// The event is sanitized before it reaches the reporter.
expect((report.mock.calls[0]?.[0] as Record<string, unknown>).token).toBe("[Redacted]");
});
});
@@ -0,0 +1,47 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { sanitizeErrorReportValue, __internal } from "./sanitize.js";
/**
* The byte-length computation has three layers: Buffer (Node), TextEncoder
* (browser / edge), and a `value.length` last resort. Node always provides
* Buffer, so these tests stub the globals to exercise the runtime-portability
* fallbacks the source comment promises. The truncation guarantee (large blobs
* never leak verbatim) must hold in every runtime.
*/
describe("sanitizeErrorReportValue byte-length fallbacks", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("uses the TextEncoder fallback to truncate when Buffer is unavailable", () => {
vi.stubGlobal("Buffer", undefined);
const huge = "a".repeat(__internal.MAX_STRING_BYTES + 16);
const result = sanitizeErrorReportValue({ blob: huge }) as { blob: string };
expect(result.blob).toMatch(/^<string truncated, \d+ bytes>$/);
expect(result.blob).not.toContain("aaa");
});
it("still truncates via String#length when neither Buffer nor TextEncoder exist", () => {
vi.stubGlobal("Buffer", undefined);
vi.stubGlobal("TextEncoder", undefined);
const huge = "b".repeat(__internal.MAX_STRING_BYTES + 1);
const result = sanitizeErrorReportValue({ blob: huge }) as { blob: string };
expect(result.blob).toMatch(/^<string truncated, \d+ bytes>$/);
expect(result.blob).not.toContain("bbb");
});
it("does not truncate a sub-limit string when running on the fallback paths", () => {
vi.stubGlobal("Buffer", undefined);
vi.stubGlobal("TextEncoder", undefined);
const small = "ok";
const result = sanitizeErrorReportValue({ blob: small }) as { blob: string };
expect(result.blob).toBe(small);
});
});
@@ -0,0 +1,256 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createSentryErrorReporter, sanitizeSentryEvent, type SentryLikeModule } from "./sentry.js";
import type { ErrorReportSeverity } from "./index.js";
function makeFakeSentry(overrides: Partial<SentryLikeModule> = {}): SentryLikeModule {
return {
init: vi.fn(),
captureException: vi.fn(),
captureMessage: vi.fn(),
...overrides,
};
}
describe("createSentryErrorReporter dynamic-import fallback", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("uses the real @sentry/node loader and falls back to noop when the package is absent", async () => {
// No `loadSentry` override => the adapter goes through the production
// `loadSentryFromNodeModules` path. `@sentry/node` is not installed in this
// workspace, so the dynamic import rejects and we degrade to the noop.
const warn = vi.fn();
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
onMissingDependency: warn,
});
await reporter.report({ component: "api", operation: "request", errorMessage: "boom" });
expect(warn).toHaveBeenCalledWith(expect.stringContaining("@sentry/node is not installed"));
});
it("routes the missing-DSN warning through the default console.warn logger", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
// No onMissingDependency => exercise defaultMissingDependencyLogger.
const reporter = createSentryErrorReporter({ dsn: "" });
await reporter.report({ component: "api", operation: "request" });
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("SENTRY_DSN is empty"));
});
});
describe("createSentryErrorReporter init failures", () => {
it("logs an init failure with the Error message and degrades to noop", async () => {
const warn = vi.fn();
const captureMessage = vi.fn();
const sentry = makeFakeSentry({
init: () => {
throw new Error("transport boot failed");
},
captureMessage,
});
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => sentry,
onMissingDependency: warn,
});
await reporter.report({ component: "api", operation: "request", errorMessage: "boom" });
expect(warn).toHaveBeenCalledWith(expect.stringContaining("failed to initialize @sentry/node (transport boot failed)"));
// Initialization failed => nothing is captured.
expect(captureMessage).not.toHaveBeenCalled();
});
it("stringifies non-Error init failures via describeCause", async () => {
const warn = vi.fn();
const sentry = makeFakeSentry({
init: () => {
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw "string-shaped boot failure";
},
});
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => sentry,
onMissingDependency: warn,
});
await reporter.report({ component: "api", operation: "request" });
expect(warn).toHaveBeenCalledWith(expect.stringContaining("string-shaped boot failure"));
});
it("initializes the SDK only once across multiple reports", async () => {
const init = vi.fn();
const captureMessage = vi.fn();
const sentry = makeFakeSentry({ init, captureMessage });
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => sentry,
});
await reporter.report({ component: "api", operation: "a", errorMessage: "1" });
await reporter.report({ component: "api", operation: "b", errorMessage: "2" });
expect(init).toHaveBeenCalledTimes(1);
expect(captureMessage).toHaveBeenCalledTimes(2);
});
});
describe("createSentryErrorReporter delivery paths", () => {
it("suppresses delivery when beforeSend throws", async () => {
const captureException = vi.fn();
const captureMessage = vi.fn();
const sentry = makeFakeSentry({ captureException, captureMessage });
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => sentry,
beforeSend: () => {
throw new Error("beforeSend exploded");
},
});
await expect(reporter.report({ component: "api", operation: "request", errorMessage: "boom" })).resolves.toBeUndefined();
expect(captureException).not.toHaveBeenCalled();
expect(captureMessage).not.toHaveBeenCalled();
});
it("captures via captureException when the event carries an error", async () => {
const captureException = vi.fn();
const captureMessage = vi.fn();
const sentry = makeFakeSentry({ captureException, captureMessage });
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => sentry,
});
const boom = new Error("kaboom");
await reporter.report({ component: "worker", operation: "job.failed", severity: "fatal", error: boom });
expect(captureException).toHaveBeenCalledTimes(1);
const [capturedError, context] = captureException.mock.calls[0] ?? [];
// The error is recursively sanitized before delivery, so the Error instance
// becomes a plain { errorName, errorMessage } object (no leaking metadata).
expect(capturedError).toMatchObject({ errorName: "Error", errorMessage: "kaboom" });
expect((context as { level?: string } | undefined)?.level).toBe("fatal");
expect((context as { tags?: Record<string, string> } | undefined)?.tags).toMatchObject({
component: "worker",
operation: "job.failed",
});
expect(captureMessage).not.toHaveBeenCalled();
});
it("falls back to a component:operation message when no errorMessage is present", async () => {
const captureMessage = vi.fn();
const sentry = makeFakeSentry({ captureMessage });
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => sentry,
});
await reporter.report({ component: "mail", operation: "send" });
expect(captureMessage).toHaveBeenCalledTimes(1);
expect(captureMessage.mock.calls[0]?.[0]).toBe("mail:send");
});
it("defaults the level to error for absent and unknown severities", async () => {
const captureMessage = vi.fn();
const sentry = makeFakeSentry({ captureMessage });
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => sentry,
});
await reporter.report({ component: "api", operation: "a", errorMessage: "no severity" });
await reporter.report({
component: "api",
operation: "b",
errorMessage: "bogus severity",
severity: "totally-invalid" as ErrorReportSeverity,
});
const levels = captureMessage.mock.calls.map((call) => (call[1] as { level?: string } | undefined)?.level);
expect(levels).toEqual(["error", "error"]);
});
it("maps the warn severity to the Sentry 'warning' level", async () => {
const captureMessage = vi.fn();
const sentry = makeFakeSentry({ captureMessage });
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => sentry,
});
await reporter.report({ component: "api", operation: "request", errorMessage: "heads up", severity: "warn" });
expect((captureMessage.mock.calls[0]?.[1] as { level?: string } | undefined)?.level).toBe("warning");
});
it("swallows capture transport failures without rethrowing", async () => {
const sentry = makeFakeSentry({
captureMessage: () => {
throw new Error("network down");
},
});
const reporter = createSentryErrorReporter({
dsn: "https://example@sentry.io/1",
loadSentry: async () => sentry,
});
await expect(reporter.report({ component: "api", operation: "request", errorMessage: "boom" })).resolves.toBeUndefined();
});
});
describe("sanitizeSentryEvent shouldDropEvent edge cases", () => {
it("keeps events whose exception has an empty values array", () => {
const event: Record<string, unknown> = { exception: { values: [] } };
expect(sanitizeSentryEvent(event)).not.toBeNull();
});
it("keeps events whose exception is not an object", () => {
const event: Record<string, unknown> = { exception: "boom" };
expect(sanitizeSentryEvent(event)).not.toBeNull();
});
it("keeps events whose first exception value is not an object", () => {
expect(sanitizeSentryEvent({ exception: { values: [null] } })).not.toBeNull();
expect(sanitizeSentryEvent({ exception: { values: [42] } })).not.toBeNull();
});
it("keeps events whose first exception value has no string type", () => {
expect(sanitizeSentryEvent({ exception: { values: [{ value: "no type field" }] } })).not.toBeNull();
expect(sanitizeSentryEvent({ exception: { values: [{ type: 123 }] } })).not.toBeNull();
});
it("still drops a known abort type even when extra values follow", () => {
const result = sanitizeSentryEvent({
exception: { values: [{ type: "AbortError" }, { type: "TypeError" }] },
});
expect(result).toBeNull();
});
});
describe("sanitizeSentryEvent passthrough", () => {
it("returns a shallow clone for events without sensitive sub-objects", () => {
const raw: Record<string, unknown> = { message: "plain", level: "info" };
const result = sanitizeSentryEvent(raw);
expect(result).toEqual(raw);
// Must be a copy, not the same reference, so the SDK's object is untouched.
expect(result).not.toBe(raw);
});
});
@@ -80,7 +80,7 @@ export function createSentryErrorReporter(options: SentryErrorReporterOptions):
const onMissing = options.onMissingDependency ?? defaultMissingDependencyLogger;
if (!options.dsn) {
onMissing("@toolctrl/error-reporter: SENTRY_DSN is empty; falling back to noop reporter.");
onMissing("@hivegrid/error-reporter: SENTRY_DSN is empty; falling back to noop reporter.");
return createNoopErrorReporter();
}
@@ -99,7 +99,7 @@ export function createSentryErrorReporter(options: SentryErrorReporterOptions):
const loader = options.loadSentry ?? loadSentryFromNodeModules;
const loaded = await loader();
if (!loaded) {
onMissing("@toolctrl/error-reporter: @sentry/node is not installed; falling back to noop reporter.");
onMissing("@hivegrid/error-reporter: @sentry/node is not installed; falling back to noop reporter.");
return;
}
@@ -115,7 +115,7 @@ export function createSentryErrorReporter(options: SentryErrorReporterOptions):
});
sentry = loaded;
} catch (cause) {
onMissing(`@toolctrl/error-reporter: failed to initialize @sentry/node (${describeCause(cause)}); falling back to noop reporter.`);
onMissing(`@hivegrid/error-reporter: failed to initialize @sentry/node (${describeCause(cause)}); falling back to noop reporter.`);
} finally {
initialized = true;
}
@@ -0,0 +1,171 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
initializeTracing,
shutdownTracing,
type NodeSdkInstance,
type NodeSdkLikeModule,
type OtlpExporterLikeModule,
} from "./tracing.js";
const ENDPOINT_ENV = "OTEL_EXPORTER_OTLP_ENDPOINT";
/**
* `initializeTracing` keeps a module-level `activeState`. None of the tests in
* this file successfully start the SDK (every path fails to load deps or throws
* during construction), so the global stays clean; the afterEach shutdown is a
* belt-and-braces guard.
*/
describe("initializeTracing dynamic-import fallback", () => {
afterEach(async () => {
await shutdownTracing();
vi.restoreAllMocks();
});
it("uses the real OpenTelemetry loaders and stays disabled when the packages are absent", async () => {
// No loadSdk / loadOtlpExporter overrides => production loaders run. The
// @opentelemetry/* packages are not installed here, so both resolve to
// undefined and the helper degrades to a warning-only no-op.
const warn = vi.fn();
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
onMissingDependency: warn,
});
expect(warn).toHaveBeenCalledWith(
expect.stringContaining("@opentelemetry/sdk-node or @opentelemetry/exporter-trace-otlp-http is not installed")
);
});
it("routes the missing-dependency warning through the default console.warn logger", async () => {
const original = process.env[ENDPOINT_ENV];
delete process.env[ENDPOINT_ENV];
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
try {
// No onMissingDependency and no endpoint => default logger + endpoint warning.
await initializeTracing({ serviceName: "api" });
} finally {
if (original !== undefined) {
process.env[ENDPOINT_ENV] = original;
}
}
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining(ENDPOINT_ENV));
});
});
describe("initializeTracing endpoint resolution from the environment", () => {
afterEach(async () => {
await shutdownTracing();
vi.restoreAllMocks();
});
it("reads and trims the OTLP endpoint from the environment when no option is given", async () => {
const original = process.env[ENDPOINT_ENV];
process.env[ENDPOINT_ENV] = " http://env-endpoint:4318/v1/traces ";
const warn = vi.fn();
try {
await initializeTracing({
serviceName: "api",
// otlpEndpoint omitted on purpose => readEnv must supply the trimmed value.
loadSdk: async () => undefined,
loadOtlpExporter: async () => undefined,
onMissingDependency: warn,
});
} finally {
if (original === undefined) {
delete process.env[ENDPOINT_ENV];
} else {
process.env[ENDPOINT_ENV] = original;
}
}
// Reaching the "not installed" branch proves readEnv returned a usable value
// rather than short-circuiting on a missing endpoint.
expect(warn).toHaveBeenCalledWith(expect.stringContaining("is not installed"));
expect(warn).not.toHaveBeenCalledWith(expect.stringContaining("is not set"));
});
it("treats a whitespace-only endpoint env var as unset", async () => {
const original = process.env[ENDPOINT_ENV];
process.env[ENDPOINT_ENV] = " ";
const warn = vi.fn();
try {
await initializeTracing({ serviceName: "api", onMissingDependency: warn });
} finally {
if (original === undefined) {
delete process.env[ENDPOINT_ENV];
} else {
process.env[ENDPOINT_ENV] = original;
}
}
expect(warn).toHaveBeenCalledWith(expect.stringContaining("OTEL_EXPORTER_OTLP_ENDPOINT is not set"));
});
});
describe("initializeTracing startup failure descriptions", () => {
afterEach(async () => {
await shutdownTracing();
vi.restoreAllMocks();
});
it("stringifies non-Error startup failures via describeCause", async () => {
const warn = vi.fn();
const OTLPTraceExporter = vi.fn().mockImplementation(() => ({}));
const NodeSDK = vi.fn().mockImplementation(() => {
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw "constructor-blew-up";
});
const sdkModule: NodeSdkLikeModule = { NodeSDK: NodeSDK as unknown as NodeSdkLikeModule["NodeSDK"] };
const exporterModule: OtlpExporterLikeModule = {
OTLPTraceExporter: OTLPTraceExporter as unknown as OtlpExporterLikeModule["OTLPTraceExporter"],
};
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => sdkModule,
loadOtlpExporter: async () => exporterModule,
onMissingDependency: warn,
});
expect(warn).toHaveBeenCalledWith(
expect.stringContaining("failed to start OpenTelemetry NodeSDK (constructor-blew-up)")
);
});
it("does not retain active state after a failed startup (shutdown is a no-op)", async () => {
const warn = vi.fn();
const shutdown = vi.fn(async () => undefined);
const start = vi.fn(async () => {
throw new Error("start rejected");
});
const sdkInstance: NodeSdkInstance = { start, shutdown };
const NodeSDK = vi.fn().mockImplementation(() => sdkInstance);
const OTLPTraceExporter = vi.fn().mockImplementation(() => ({}));
const sdkModule: NodeSdkLikeModule = { NodeSDK: NodeSDK as unknown as NodeSdkLikeModule["NodeSDK"] };
const exporterModule: OtlpExporterLikeModule = {
OTLPTraceExporter: OTLPTraceExporter as unknown as OtlpExporterLikeModule["OTLPTraceExporter"],
};
await initializeTracing({
serviceName: "api",
otlpEndpoint: "http://localhost:4318/v1/traces",
loadSdk: async () => sdkModule,
loadOtlpExporter: async () => exporterModule,
onMissingDependency: warn,
});
expect(warn).toHaveBeenCalledWith(expect.stringContaining("failed to start OpenTelemetry NodeSDK (start rejected)"));
// No active state => shutdown must not touch the SDK instance.
await shutdownTracing();
expect(shutdown).not.toHaveBeenCalled();
});
});
@@ -54,7 +54,7 @@ export async function initializeTracing(options: TracingOptions): Promise<void>
const endpoint = options.otlpEndpoint ?? readEnv("OTEL_EXPORTER_OTLP_ENDPOINT");
if (!endpoint) {
onMissing("@toolctrl/error-reporter: OTEL_EXPORTER_OTLP_ENDPOINT is not set; tracing skeleton stays disabled.");
onMissing("@hivegrid/error-reporter: OTEL_EXPORTER_OTLP_ENDPOINT is not set; tracing skeleton stays disabled.");
return;
}
@@ -77,7 +77,7 @@ export async function initializeTracing(options: TracingOptions): Promise<void>
}
if (!sdkModule || !exporterModule) {
onMissing("@toolctrl/error-reporter: @opentelemetry/sdk-node or @opentelemetry/exporter-trace-otlp-http is not installed; tracing skeleton stays disabled.");
onMissing("@hivegrid/error-reporter: @opentelemetry/sdk-node or @opentelemetry/exporter-trace-otlp-http is not installed; tracing skeleton stays disabled.");
return;
}
@@ -90,7 +90,7 @@ export async function initializeTracing(options: TracingOptions): Promise<void>
await sdk.start();
activeState = { sdk };
} catch (cause) {
onMissing(`@toolctrl/error-reporter: failed to start OpenTelemetry NodeSDK (${describeCause(cause)}); tracing skeleton stays disabled.`);
onMissing(`@hivegrid/error-reporter: failed to start OpenTelemetry NodeSDK (${describeCause(cause)}); tracing skeleton stays disabled.`);
}
}