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

@@ -25,6 +25,8 @@ const item: NotificationStreamItem = {
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: null,
readAt: null,
deeplink: null,
lastError: null,
};
const baseEvent = {
@@ -135,7 +137,7 @@ describe("public realtime package boundary", () => {
});
expect(snapshotFrame).toBe(
`id: ${item.cursor}\nevent: notification.snapshot\ndata: {"event":"notification.snapshot","cursor":"${item.cursor}","requestId":"req_boundary_1","tenantId":"tenant_1","userId":"user_1","items":[{"id":"delivery_boundary_1","cursor":"${item.cursor}","tenantId":"tenant_1","userId":"user_1","channel":"IN_APP","category":"billing","messageKey":"invoice.ready","status":"PENDING","attemptsMade":0,"createdAt":"2026-05-08T19:59:00.000Z","updatedAt":"2026-05-08T20:00:00.000Z","sentAt":null,"readAt":null}]}\n\n`,
`id: ${item.cursor}\nevent: notification.snapshot\ndata: {"event":"notification.snapshot","cursor":"${item.cursor}","requestId":"req_boundary_1","tenantId":"tenant_1","userId":"user_1","items":[{"id":"delivery_boundary_1","cursor":"${item.cursor}","tenantId":"tenant_1","userId":"user_1","channel":"IN_APP","category":"billing","messageKey":"invoice.ready","status":"PENDING","attemptsMade":0,"createdAt":"2026-05-08T19:59:00.000Z","updatedAt":"2026-05-08T20:00:00.000Z","sentAt":null,"readAt":null,"deeplink":null,"lastError":null}]}\n\n`,
);
expect(
@@ -0,0 +1,155 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { REALTIME_EVENT_NAMES, type NotificationStreamItem } from "./events.js";
import {
subscribeToRealtime,
type RealtimeEventSourceLike,
type RealtimeMessageEvent,
type RealtimeSubscriberDiagnostic,
type RealtimeSubscriberOptions,
} from "./client.js";
const item: NotificationStreamItem = {
id: "delivery_cb_1",
cursor: "2026-05-08T20:00:00.000Z:delivery_cb_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
createdAt: "2026-05-08T19:59:00.000Z",
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: "2026-05-08T20:00:00.000Z",
readAt: null,
};
const baseEvent = { cursor: item.cursor, requestId: "req_cb_1", tenantId: "tenant_1", userId: "user_1" };
class FakeEventSource implements RealtimeEventSourceLike {
static instances: FakeEventSource[] = [];
readonly listeners = new Map<string, Array<(event: RealtimeMessageEvent) => void>>();
onopen: (() => void) | null = null;
onmessage: ((event: RealtimeMessageEvent) => void) | null = null;
onerror: ((event: unknown) => void) | null = null;
closed = false;
constructor(readonly url: string | URL) {
FakeEventSource.instances.push(this);
}
emit(data: unknown): void {
this.onmessage?.({ data: typeof data === "string" ? data : JSON.stringify(data) });
}
addEventListener(type: string, listener: (event: RealtimeMessageEvent) => void): void {
const listeners = this.listeners.get(type) ?? [];
listeners.push(listener);
this.listeners.set(type, listeners);
}
close(): void {
this.closed = true;
}
}
function createSubscriber(overrides: Partial<RealtimeSubscriberOptions> = {}) {
FakeEventSource.instances = [];
const diagnostics: RealtimeSubscriberDiagnostic[] = [];
const subscriber = subscribeToRealtime({
...overrides,
url: overrides.url ?? "https://example.test/stream",
EventSource: overrides.EventSource ?? FakeEventSource,
onDiagnostic: (diagnostic) => diagnostics.push(diagnostic),
});
return { diagnostics, source: FakeEventSource.instances[0], subscriber };
}
describe("realtime client subscriber edge cases", () => {
const originalEventSource = (globalThis as { EventSource?: unknown }).EventSource;
afterEach(() => {
if (originalEventSource === undefined) {
delete (globalThis as { EventSource?: unknown }).EventSource;
} else {
(globalThis as { EventSource?: unknown }).EventSource = originalEventSource;
}
});
it("exposes the active source via the source getter", () => {
const { source, subscriber } = createSubscriber();
expect(subscriber.source).toBe(source);
expect(subscriber.currentSource).toBe(source);
});
it("falls back to the global EventSource when no constructor is provided", () => {
FakeEventSource.instances = [];
(globalThis as { EventSource?: unknown }).EventSource = FakeEventSource;
const subscriber = subscribeToRealtime({ url: "https://example.test/global" });
expect(FakeEventSource.instances).toHaveLength(1);
expect(subscriber.source).toBe(FakeEventSource.instances[0]);
subscriber.close();
});
it("throws a guidance error when no EventSource is available at all", () => {
delete (globalThis as { EventSource?: unknown }).EventSource;
expect(() => subscribeToRealtime({ url: "https://example.test/none" })).toThrow(
/EventSource is not available; provide an EventSource option/,
);
});
it("silently ignores valid events when no matching callback is registered", () => {
const { diagnostics, source } = createSubscriber();
expect(() =>
source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationSnapshot, items: [item] }),
).not.toThrow();
expect(diagnostics).toEqual([]);
});
it("emits a context-free diagnostic when the parsed payload is not an object", () => {
const { diagnostics, source } = createSubscriber();
source.emit("42");
expect(diagnostics).toEqual([{ phase: "validation", message: "realtime event must be an object" }]);
});
it("omits diagnostic context fields when envelope identifiers are not strings", () => {
const { diagnostics, source } = createSubscriber();
source.emit({ event: 5, cursor: 6, requestId: 7 });
// toEqual treats `undefined` context fields as absent, proving non-string ids are dropped.
expect(diagnostics).toEqual([{ phase: "validation", message: "event must be a supported realtime event name" }]);
expect(diagnostics[0].eventName).toBeUndefined();
});
it("uses a generic message when a callback throws a non-Error value", () => {
const onKeepalive = vi.fn(() => {
throw "raw string failure with token=secret";
});
const { diagnostics, source } = createSubscriber({ onKeepalive });
source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive });
expect(onKeepalive).toHaveBeenCalledTimes(1);
expect(diagnostics).toEqual([
{
phase: "callback",
message: "Realtime subscriber rejected an invalid event.",
eventName: REALTIME_EVENT_NAMES.keepalive,
cursor: item.cursor,
requestId: "req_cb_1",
},
]);
expect(JSON.stringify(diagnostics)).not.toContain("token=secret");
});
});
@@ -24,6 +24,8 @@ const item: NotificationStreamItem = {
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: "2026-05-08T20:00:00.000Z",
readAt: null,
deeplink: null,
lastError: null,
};
const baseEvent = {
@@ -0,0 +1,127 @@
import { describe, expect, it } from "vitest";
import { REALTIME_EVENT_NAMES, validateRealtimeEvent, type NotificationStreamItem } from "./events.js";
const item: NotificationStreamItem = {
id: "delivery_b_1",
cursor: "2026-05-08T20:00:00.000Z:delivery_b_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
createdAt: "2026-05-08T19:59:00.000Z",
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: "2026-05-08T20:00:00.000Z",
readAt: null,
};
function snapshot(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
event: REALTIME_EVENT_NAMES.notificationSnapshot,
cursor: item.cursor,
requestId: "req_b_1",
items: [item],
...overrides,
};
}
describe("realtime event contract edge cases", () => {
it("rejects top-level inputs that are not plain objects", () => {
expect(() => validateRealtimeEvent(null)).toThrow(/realtime event must be an object/);
expect(() => validateRealtimeEvent(42)).toThrow(/realtime event must be an object/);
expect(() => validateRealtimeEvent("notification.update")).toThrow(/realtime event must be an object/);
// Arrays are records-of-numbers but explicitly disallowed by isRecord.
expect(() => validateRealtimeEvent([item])).toThrow(/realtime event must be an object/);
});
it("rejects unsupported (but non-secret) envelope keys", () => {
expect(() =>
validateRealtimeEvent({ event: REALTIME_EVENT_NAMES.keepalive, cursor: item.cursor, requestId: "req_b_1", region: "eu" }),
).toThrow(/keepalive event contains unsupported key: region/);
});
it("rejects strings that exceed the maximum length", () => {
expect(() =>
validateRealtimeEvent({ event: REALTIME_EVENT_NAMES.keepalive, cursor: item.cursor, requestId: "x".repeat(501) }),
).toThrow(/requestId is too long/);
});
it("rejects snapshot payloads whose items are not an array", () => {
expect(() => validateRealtimeEvent(snapshot({ items: "not-an-array" }))).toThrow(/snapshot event items must be an array/);
expect(() => validateRealtimeEvent(snapshot({ items: { length: 1 } }))).toThrow(/snapshot event items must be an array/);
});
it("rejects snapshot payloads that exceed the per-event item cap", () => {
const tooMany = Array.from({ length: 101 }, () => item);
expect(() => validateRealtimeEvent(snapshot({ items: tooMany }))).toThrow(/too many items/);
});
it("rejects items that are not objects", () => {
expect(() => validateRealtimeEvent(snapshot({ items: [42] }))).toThrow(/notification item must be an object/);
expect(() =>
validateRealtimeEvent({ event: REALTIME_EVENT_NAMES.notificationUpdate, cursor: item.cursor, requestId: "req_b_1", item: null }),
).toThrow(/notification item must be an object/);
});
it("rejects non-negative-integer violations on attemptsMade", () => {
expect(() => validateRealtimeEvent(snapshot({ items: [{ ...item, attemptsMade: -1 }] }))).toThrow(/non-negative integer/);
expect(() => validateRealtimeEvent(snapshot({ items: [{ ...item, attemptsMade: 1.5 }] }))).toThrow(/non-negative integer/);
expect(() => validateRealtimeEvent(snapshot({ items: [{ ...item, attemptsMade: "1" }] }))).toThrow(/non-negative integer/);
});
it("rejects ISO date fields that fail the pattern or are unparseable", () => {
// Fails the strict ISO pattern entirely.
expect(() => validateRealtimeEvent(snapshot({ items: [{ ...item, createdAt: "08.05.2026" }] }))).toThrow(/must be an ISO timestamp/);
// Matches the pattern shape but is not a real calendar instant (Date.parse -> NaN).
expect(() => validateRealtimeEvent(snapshot({ items: [{ ...item, updatedAt: "2026-13-40T25:61:61.000Z" }] }))).toThrow(
/must be an ISO timestamp/,
);
});
it("normalizes explicit null envelope tenant/user scope to null", () => {
expect(
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.keepalive,
cursor: item.cursor,
requestId: "req_b_1",
tenantId: null,
userId: null,
}),
).toEqual({ event: REALTIME_EVENT_NAMES.keepalive, cursor: item.cursor, requestId: "req_b_1", tenantId: null, userId: null });
});
it("defaults omitted optional item fields to null/empty without throwing", () => {
const sparseItem = {
id: "delivery_sparse_1",
cursor: "2026-05-08T20:00:00.000Z:delivery_sparse_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "PENDING",
attemptsMade: 0,
};
const result = validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.notificationUpdate,
cursor: item.cursor,
requestId: "req_b_1",
item: sparseItem,
});
expect(result).toMatchObject({
event: REALTIME_EVENT_NAMES.notificationUpdate,
item: {
id: "delivery_sparse_1",
tenantId: null,
userId: null,
createdAt: "",
updatedAt: "",
sentAt: null,
readAt: null,
},
});
});
});
@@ -16,6 +16,8 @@ const item: NotificationStreamItem = {
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: "2026-05-08T20:00:00.000Z",
readAt: null,
deeplink: null,
lastError: null,
};
describe("realtime event contract", () => {
@@ -25,6 +25,11 @@ export type NotificationStreamItem = {
updatedAt: string;
sentAt?: string | null;
readAt?: string | null;
// AK-P3 DoD 4 (additive): validated app-relative deeplink + pre-redacted
// error line. Deliberately scalars only — payload metadata itself stays
// banned by the secret-key guard.
deeplink?: string | null;
lastError?: string | null;
};
export type RealtimeEventBase = {
@@ -149,7 +154,23 @@ function normalizeItem(value: unknown): NotificationStreamItem {
assertAllowedKeys(
value,
new Set(["id", "cursor", "tenantId", "userId", "channel", "category", "messageKey", "status", "attemptsMade", "createdAt", "updatedAt", "sentAt", "readAt"]),
new Set([
"id",
"cursor",
"tenantId",
"userId",
"channel",
"category",
"messageKey",
"status",
"attemptsMade",
"createdAt",
"updatedAt",
"sentAt",
"readAt",
"deeplink",
"lastError",
]),
"notification item",
);
@@ -171,9 +192,37 @@ function normalizeItem(value: unknown): NotificationStreamItem {
updatedAt: normalizeOptionalIsoDate(value.updatedAt, "item.updatedAt") ?? "",
sentAt: normalizeOptionalIsoDate(value.sentAt, "item.sentAt") ?? null,
readAt: normalizeOptionalIsoDate(value.readAt, "item.readAt") ?? null,
deeplink: normalizeDeeplink(value.deeplink),
lastError: normalizeOptionalString(value.lastError, "item.lastError") ?? null,
};
}
/**
* AK-P3 DoD 4 — fail-closed deeplink guard: only app-relative paths ("/…")
* survive; absolute URLs, protocol-relative, backslashes and whitespace throw
* (a producer sending those is a contract violation, not a display concern).
*/
function normalizeDeeplink(value: unknown): string | null {
if (value === undefined || value === null) {
return null;
}
if (typeof value !== "string") {
throw new Error("item.deeplink must be a string when present");
}
const trimmed = value.trim();
if (
trimmed.length < 2 ||
trimmed.length > MAX_STRING_LENGTH ||
!trimmed.startsWith("/") ||
trimmed.startsWith("//") ||
trimmed.includes("\\") ||
/\s/.test(trimmed)
) {
throw new Error("item.deeplink must be an app-relative path");
}
return trimmed;
}
function normalizeBase(value: Record<string, unknown>): RealtimeEventBase {
const event = value.event;
@@ -0,0 +1,102 @@
import { describe, expect, it } from "vitest";
import { REALTIME_EVENT_NAMES, type NotificationStreamItem, type RealtimeEvent } from "./events.js";
import {
assertNotificationEventInAppScope,
normalizeNotificationStreamScope,
redactNotificationGuardDiagnostic,
} from "./guards.js";
const item: NotificationStreamItem = {
id: "delivery_gb_1",
cursor: "2026-05-08T20:00:00.000Z:delivery_gb_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
createdAt: "2026-05-08T19:59:00.000Z",
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: "2026-05-08T20:00:00.000Z",
readAt: null,
};
const scope = { tenantId: "tenant_1", userId: "user_1" };
describe("notification stream guard edge cases", () => {
it("returns a scope without afterCursor when none is supplied", () => {
const normalized = normalizeNotificationStreamScope({ tenantId: "tenant_1", userId: "user_1" });
expect(normalized).toEqual({ tenantId: "tenant_1", userId: "user_1" });
expect("afterCursor" in normalized).toBe(false);
});
it("rejects non-string scope values", () => {
expect(() => normalizeNotificationStreamScope({ tenantId: 123, userId: "user_1" })).toThrow(/tenantId must be a string/);
expect(() => normalizeNotificationStreamScope({ tenantId: "tenant_1", userId: { id: "x" } })).toThrow(/userId must be a string/);
expect(() => normalizeNotificationStreamScope({ tenantId: "tenant_1", userId: "user_1", afterCursor: 5 })).toThrow(
/afterCursor must be a string/,
);
});
it("rejects scope values that exceed the maximum length", () => {
expect(() => normalizeNotificationStreamScope({ tenantId: "x".repeat(501), userId: "user_1" })).toThrow(/tenantId is too long/);
});
it("accepts a fully in-scope snapshot and iterates over each item", () => {
const event: RealtimeEvent = {
event: REALTIME_EVENT_NAMES.notificationSnapshot,
cursor: item.cursor,
requestId: "req_gb_1",
tenantId: "tenant_1",
userId: "user_1",
items: [item, { ...item, id: "delivery_gb_2" }],
};
expect(() => assertNotificationEventInAppScope(event, scope)).not.toThrow();
});
it("rejects a snapshot whose envelope matches but an item is out of scope", () => {
const event: RealtimeEvent = {
event: REALTIME_EVENT_NAMES.notificationSnapshot,
cursor: item.cursor,
requestId: "req_gb_2",
tenantId: "tenant_1",
userId: "user_1",
items: [item, { ...item, id: "delivery_gb_3", tenantId: "tenant_2" }],
};
expect(() => assertNotificationEventInAppScope(event, scope)).toThrow(/item\.tenantId/);
});
it("accepts in-scope keepalive and error envelopes without inspecting items", () => {
const keepalive: RealtimeEvent = {
event: REALTIME_EVENT_NAMES.keepalive,
cursor: item.cursor,
requestId: "req_gb_3",
tenantId: "tenant_1",
userId: "user_1",
};
const errorEvent: RealtimeEvent = {
event: REALTIME_EVENT_NAMES.error,
cursor: item.cursor,
requestId: "req_gb_4",
tenantId: "tenant_1",
userId: "user_1",
code: "STREAM_FAILED",
message: "Notification stream failed.",
};
expect(() => assertNotificationEventInAppScope(keepalive, scope)).not.toThrow();
expect(() => assertNotificationEventInAppScope(errorEvent, scope)).not.toThrow();
});
it("redacts secret-like text from non-Error diagnostic values", () => {
const diagnostic = redactNotificationGuardDiagnostic("provider token=secret leaked into a plain string");
expect(diagnostic).toContain("[redacted]");
expect(diagnostic).not.toMatch(/provider|token=secret/i);
});
});
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
describe("@toolctrl/realtime public entrypoint", () => {
describe("@hivegrid/realtime public entrypoint", () => {
it("exports realtime event contract bindings", async () => {
const entrypoint = await import("./index.js");
@@ -35,7 +35,7 @@ describe("SSE realtime serialization", () => {
items: [item],
}),
).toBe(
`id: ${item.cursor}\nevent: notification.snapshot\ndata: {"event":"notification.snapshot","cursor":"${item.cursor}","requestId":"req_1","tenantId":"tenant_1","userId":"user_1","items":[{"id":"delivery_1","cursor":"${item.cursor}","tenantId":"tenant_1","userId":"user_1","channel":"IN_APP","category":"billing","messageKey":"invoice.ready","status":"SENT","attemptsMade":1,"createdAt":"2026-05-08T19:59:00.000Z","updatedAt":"2026-05-08T20:00:00.000Z","sentAt":"2026-05-08T20:00:00.000Z","readAt":null}]}\n\n`,
`id: ${item.cursor}\nevent: notification.snapshot\ndata: {"event":"notification.snapshot","cursor":"${item.cursor}","requestId":"req_1","tenantId":"tenant_1","userId":"user_1","items":[{"id":"delivery_1","cursor":"${item.cursor}","tenantId":"tenant_1","userId":"user_1","channel":"IN_APP","category":"billing","messageKey":"invoice.ready","status":"SENT","attemptsMade":1,"createdAt":"2026-05-08T19:59:00.000Z","updatedAt":"2026-05-08T20:00:00.000Z","sentAt":"2026-05-08T20:00:00.000Z","readAt":null,"deeplink":null,"lastError":null}]}\n\n`,
);
});
@@ -50,7 +50,7 @@ describe("SSE realtime serialization", () => {
{ retry: 5000 },
),
).toBe(
`retry: 5000\nid: ${item.cursor}\nevent: notification.update\ndata: {"event":"notification.update","cursor":"${item.cursor}","requestId":"req_1","tenantId":"tenant_1","userId":"user_1","item":{"id":"delivery_1","cursor":"${item.cursor}","tenantId":"tenant_1","userId":"user_1","channel":"IN_APP","category":"billing","messageKey":"invoice.ready","status":"SENT","attemptsMade":1,"createdAt":"2026-05-08T19:59:00.000Z","updatedAt":"2026-05-08T20:00:00.000Z","sentAt":"2026-05-08T20:00:00.000Z","readAt":null}}\n\n`,
`retry: 5000\nid: ${item.cursor}\nevent: notification.update\ndata: {"event":"notification.update","cursor":"${item.cursor}","requestId":"req_1","tenantId":"tenant_1","userId":"user_1","item":{"id":"delivery_1","cursor":"${item.cursor}","tenantId":"tenant_1","userId":"user_1","channel":"IN_APP","category":"billing","messageKey":"invoice.ready","status":"SENT","attemptsMade":1,"createdAt":"2026-05-08T19:59:00.000Z","updatedAt":"2026-05-08T20:00:00.000Z","sentAt":"2026-05-08T20:00:00.000Z","readAt":null,"deeplink":null,"lastError":null}}\n\n`,
);
});