Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Phase 06 #22 — Plugin hook emission helper.
|
||||
*
|
||||
* Wraps `publishOutboxEvent` so host call-sites stay one-line:
|
||||
*
|
||||
* await emitPluginHook(tx, PLUGIN_HOOK_TENANT_CREATED, payload);
|
||||
*
|
||||
* The helper:
|
||||
* 1. Validates the payload against the registered Zod schema.
|
||||
* 2. Publishes a `plugin.hook.<name>` outbox event inside the
|
||||
* surrounding Prisma transaction (atomic with the host write).
|
||||
* 3. Returns the persisted OutboxEvent row so callers can correlate
|
||||
* it in audit logs.
|
||||
*
|
||||
* Bad payloads throw {@link PluginHookValidationError} — callers MUST
|
||||
* either handle it (when the payload is user-derived) or let it
|
||||
* propagate so the host write rolls back.
|
||||
*
|
||||
* Subscriber resolution + fan-out into one outbox row per installed
|
||||
* plugin is intentionally deferred to the worker side: a single
|
||||
* `plugin.hook.<name>` event lands in the outbox queue and the
|
||||
* downstream consumer (worker) expands it into per-plugin invocations.
|
||||
* This keeps the producer path (web request) cheap and avoids
|
||||
* coupling the request thread to the Plugin table.
|
||||
*/
|
||||
|
||||
import type { z } from "zod";
|
||||
import {
|
||||
validatePluginHookPayload,
|
||||
type PluginHookDefinition,
|
||||
} from "./registry.js";
|
||||
|
||||
/**
|
||||
* JSON-compatible value type, structurally identical to
|
||||
* `Prisma.InputJsonValue` without taking the dependency on
|
||||
* `@toolctrl/db` (which would cycle through the worker bootstrap).
|
||||
*/
|
||||
export type PluginHookJsonValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| { [key: string]: PluginHookJsonValue }
|
||||
| ReadonlyArray<PluginHookJsonValue>;
|
||||
|
||||
export class PluginHookValidationError extends Error {
|
||||
public override readonly name = "PluginHookValidationError";
|
||||
public readonly hookName: string;
|
||||
public readonly issues: ReadonlyArray<z.ZodIssue>;
|
||||
constructor(hookName: string, issues: ReadonlyArray<z.ZodIssue>) {
|
||||
super(`Invalid payload for plugin hook '${hookName}': ${JSON.stringify(issues)}`);
|
||||
this.hookName = hookName;
|
||||
this.issues = issues;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal publish surface — kept identical to the @toolctrl/db helper
|
||||
* so this package does not have to depend on @toolctrl/db directly
|
||||
* (avoids a cycle with the worker bootstrap that pulls plugin-runtime
|
||||
* via @toolctrl/db).
|
||||
*/
|
||||
export type PluginHookOutboxPublisher = (
|
||||
tx: unknown,
|
||||
args: {
|
||||
tenantId?: string | null;
|
||||
type: string;
|
||||
payload: PluginHookJsonValue;
|
||||
dispatchKey?: string | null;
|
||||
}
|
||||
) => Promise<unknown>;
|
||||
|
||||
export type EmitPluginHookOptions = {
|
||||
tenantId?: string | null;
|
||||
/**
|
||||
* Optional idempotency key. When two writers might emit the same
|
||||
* hook for the same business object (e.g. two onboarding paths both
|
||||
* creating the same tenant) supplying a stable key prevents
|
||||
* duplicate downstream invocations.
|
||||
*/
|
||||
dispatchKey?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate + publish a plugin-hook outbox event inside a transaction.
|
||||
* The transaction client is intentionally typed as `unknown` so this
|
||||
* package keeps zero runtime dependency on @toolctrl/db — the caller
|
||||
* (a `.server.ts` file in apps/web) already imports the prisma types
|
||||
* and passes the correct shape.
|
||||
*/
|
||||
export async function emitPluginHook<TPayload>(
|
||||
tx: unknown,
|
||||
def: PluginHookDefinition<TPayload>,
|
||||
payload: TPayload,
|
||||
publish: PluginHookOutboxPublisher,
|
||||
options: EmitPluginHookOptions = {}
|
||||
): Promise<void> {
|
||||
const validation = validatePluginHookPayload(def, payload);
|
||||
if (!validation.ok) {
|
||||
throw new PluginHookValidationError(def.name, validation.issues);
|
||||
}
|
||||
await publish(tx, {
|
||||
tenantId: options.tenantId ?? null,
|
||||
type: def.outboxEventType,
|
||||
payload: validation.payload as unknown as PluginHookJsonValue,
|
||||
dispatchKey: options.dispatchKey ?? null,
|
||||
});
|
||||
}
|
||||
+447
@@ -0,0 +1,447 @@
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
PLUGIN_HOOK_ENTITY_CREATED,
|
||||
PLUGIN_HOOK_ENTITY_DELETED,
|
||||
PLUGIN_HOOK_ENTITY_UPDATED,
|
||||
PLUGIN_HOOK_TENANT_CREATED,
|
||||
PLUGIN_HOOK_USER_CREATED,
|
||||
PLUGIN_HOOK_WORKFLOW_CREATED,
|
||||
PLUGIN_HOOK_WORKFLOW_DELETED,
|
||||
PLUGIN_HOOK_WORKFLOW_EXECUTED,
|
||||
PLUGIN_HOOK_WORKFLOW_FAILED,
|
||||
PLUGIN_HOOK_WORKFLOW_UPDATED,
|
||||
PLUGIN_PRODUCTION_AVAILABLE_HOOK_NAMES,
|
||||
__resetPluginHookRegistryForTests,
|
||||
getPluginHook,
|
||||
getUnavailablePluginHookNames,
|
||||
isPluginHookProductionAvailable,
|
||||
listPluginHooks,
|
||||
registerHook,
|
||||
validatePluginHookPayload,
|
||||
} from "./registry.js";
|
||||
import { PluginHookValidationError, emitPluginHook } from "./emit.js";
|
||||
|
||||
afterEach(() => {
|
||||
__resetPluginHookRegistryForTests();
|
||||
});
|
||||
|
||||
describe("plugin hook registry", () => {
|
||||
test("registers the foundation hooks", () => {
|
||||
const hooks = listPluginHooks().map((h) => h.name).sort();
|
||||
expect(hooks).toContain("tenant.created");
|
||||
expect(hooks).toContain("user.created");
|
||||
expect(hooks).toContain("entity.created");
|
||||
expect(hooks).toContain("entity.updated");
|
||||
expect(hooks).toContain("entity.deleted");
|
||||
expect(hooks).toContain("workflow.created");
|
||||
expect(hooks).toContain("workflow.updated");
|
||||
expect(hooks).toContain("workflow.deleted");
|
||||
expect(hooks).toContain("workflow.executed");
|
||||
expect(hooks).toContain("workflow.failed");
|
||||
});
|
||||
|
||||
test("each hook has an outboxEventType matching plugin.hook.<name>", () => {
|
||||
for (const hook of listPluginHooks()) {
|
||||
expect(hook.outboxEventType).toBe(`plugin.hook.${hook.name}`);
|
||||
// Must conform to the outbox eventType pattern.
|
||||
expect(hook.outboxEventType).toMatch(/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*){2,}$/u);
|
||||
}
|
||||
});
|
||||
|
||||
test("marks only foundation hooks as production-available", () => {
|
||||
expect(PLUGIN_PRODUCTION_AVAILABLE_HOOK_NAMES).toEqual([
|
||||
"tenant.created",
|
||||
"user.created",
|
||||
"entity.created",
|
||||
"entity.updated",
|
||||
"entity.deleted",
|
||||
"workflow.created",
|
||||
"workflow.updated",
|
||||
"workflow.deleted",
|
||||
"workflow.executed",
|
||||
"workflow.failed",
|
||||
]);
|
||||
expect(isPluginHookProductionAvailable("tenant.created")).toBe(true);
|
||||
expect(isPluginHookProductionAvailable("workflow.failed")).toBe(true);
|
||||
|
||||
registerHook({
|
||||
name: "billing.paid",
|
||||
outboxEventType: "plugin.hook.billing.paid",
|
||||
payloadSchema: z.object({ invoiceId: z.string() }),
|
||||
});
|
||||
|
||||
expect(getPluginHook("billing.paid")).toBeDefined();
|
||||
expect(isPluginHookProductionAvailable("billing.paid")).toBe(false);
|
||||
expect(getUnavailablePluginHookNames([{ name: "tenant.created" }, { name: "billing.paid" }, "billing.paid", "unknown.hook"])).toEqual([
|
||||
"billing.paid",
|
||||
]);
|
||||
});
|
||||
|
||||
test("getPluginHook returns the registered definition", () => {
|
||||
expect(getPluginHook("tenant.created")).toBe(PLUGIN_HOOK_TENANT_CREATED);
|
||||
expect(getPluginHook("unknown")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validates a well-formed tenant.created payload", () => {
|
||||
const result = validatePluginHookPayload(PLUGIN_HOOK_TENANT_CREATED, {
|
||||
tenantId: "t-1",
|
||||
slug: "acme",
|
||||
ownerEmail: "owner@example.com",
|
||||
plan: "free",
|
||||
createdAt: "2026-05-17T10:00:00.000Z",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects payload missing required fields", () => {
|
||||
const result = validatePluginHookPayload(PLUGIN_HOOK_USER_CREATED, {
|
||||
email: "u@example.com",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.issues.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
test("entity.* hooks accept the canonical payload", () => {
|
||||
const payload = {
|
||||
entityType: "row",
|
||||
entityId: "row-1",
|
||||
tenantId: "t-1",
|
||||
userId: "u-1",
|
||||
occurredAt: "2026-05-17T10:00:00.000Z",
|
||||
};
|
||||
expect(validatePluginHookPayload(PLUGIN_HOOK_ENTITY_CREATED, payload).ok).toBe(true);
|
||||
expect(validatePluginHookPayload(PLUGIN_HOOK_ENTITY_UPDATED, { ...payload, changedFields: ["a"] }).ok).toBe(true);
|
||||
expect(validatePluginHookPayload(PLUGIN_HOOK_ENTITY_DELETED, payload).ok).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects raw or sensitive fields on public hook payloads", () => {
|
||||
expect(
|
||||
validatePluginHookPayload(PLUGIN_HOOK_TENANT_CREATED, {
|
||||
tenantId: "t-1",
|
||||
slug: "acme",
|
||||
ownerEmail: "owner@example.com",
|
||||
plan: "free",
|
||||
createdAt: "2026-05-17T10:00:00.000Z",
|
||||
rawPayload: { billingEmail: "billing@example.com" },
|
||||
}).ok
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
validatePluginHookPayload(PLUGIN_HOOK_USER_CREATED, {
|
||||
userId: "u-1",
|
||||
tenantId: "t-1",
|
||||
email: "u@example.com",
|
||||
locale: "en",
|
||||
createdAt: "2026-05-17T10:00:00.000Z",
|
||||
passwordHash: "secret",
|
||||
}).ok
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
validatePluginHookPayload(PLUGIN_HOOK_ENTITY_CREATED, {
|
||||
entityType: "row",
|
||||
entityId: "row-1",
|
||||
tenantId: "t-1",
|
||||
userId: "u-1",
|
||||
beforeData: { apiKey: "secret" },
|
||||
occurredAt: "2026-05-17T10:00:00.000Z",
|
||||
}).ok
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("workflow.executed validates terminal tenant-scoped execution metadata without payload bodies", () => {
|
||||
const valid = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_EXECUTED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
userId: "user_1",
|
||||
type: "trigger",
|
||||
status: "success",
|
||||
durationMs: 12,
|
||||
errorCode: null,
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
});
|
||||
expect(valid.ok).toBe(true);
|
||||
|
||||
const legacyWithoutUserId = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_EXECUTED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
type: "trigger",
|
||||
status: "success",
|
||||
durationMs: 12,
|
||||
errorCode: null,
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
});
|
||||
expect(legacyWithoutUserId.ok).toBe(true);
|
||||
|
||||
const systemExecution = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_EXECUTED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
userId: null,
|
||||
type: "trigger",
|
||||
status: "success",
|
||||
durationMs: 12,
|
||||
errorCode: null,
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
});
|
||||
expect(systemExecution.ok).toBe(true);
|
||||
|
||||
const withLeakedOutput = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_EXECUTED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
userId: "user_1",
|
||||
type: "trigger",
|
||||
status: "success",
|
||||
durationMs: 12,
|
||||
errorCode: null,
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
output: { secret: "nope" },
|
||||
});
|
||||
expect(withLeakedOutput.ok).toBe(false);
|
||||
|
||||
const waiting = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_EXECUTED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
type: "manual",
|
||||
status: "waitingBlock",
|
||||
durationMs: 12,
|
||||
errorCode: null,
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
});
|
||||
expect(waiting.ok).toBe(false);
|
||||
|
||||
const withRawError = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_EXECUTED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
userId: "user_1",
|
||||
type: "trigger",
|
||||
status: "error",
|
||||
durationMs: 12,
|
||||
errorCode: "workflow_execution_failed",
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
error: "Provider failed with token=sk_live_secret",
|
||||
});
|
||||
expect(withRawError.ok).toBe(false);
|
||||
|
||||
const successWithErrorCode = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_EXECUTED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
type: "trigger",
|
||||
status: "success",
|
||||
durationMs: 12,
|
||||
errorCode: "workflow_execution_failed",
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
});
|
||||
expect(successWithErrorCode.ok).toBe(false);
|
||||
|
||||
const errorWithoutCode = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_EXECUTED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
type: "trigger",
|
||||
status: "error",
|
||||
durationMs: 12,
|
||||
errorCode: null,
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
});
|
||||
expect(errorWithoutCode.ok).toBe(false);
|
||||
});
|
||||
|
||||
test("workflow.failed validates failure-only execution metadata without raw error bodies", () => {
|
||||
const valid = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_FAILED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
type: "trigger",
|
||||
status: "error",
|
||||
durationMs: 12,
|
||||
errorCode: "workflow_execution_failed",
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
});
|
||||
expect(valid.ok).toBe(true);
|
||||
|
||||
const successfulExecution = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_FAILED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
type: "trigger",
|
||||
status: "success",
|
||||
durationMs: 12,
|
||||
errorCode: "workflow_execution_failed",
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
});
|
||||
expect(successfulExecution.ok).toBe(false);
|
||||
|
||||
const withoutCode = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_FAILED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
type: "trigger",
|
||||
status: "error",
|
||||
durationMs: 12,
|
||||
errorCode: null,
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
});
|
||||
expect(withoutCode.ok).toBe(false);
|
||||
|
||||
const withRawError = validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_FAILED, {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
workflowExecutionId: "execution_1",
|
||||
type: "trigger",
|
||||
status: "error",
|
||||
durationMs: 12,
|
||||
errorCode: "workflow_execution_failed",
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
error: "Provider failed with token=sk_live_secret",
|
||||
});
|
||||
expect(withRawError.ok).toBe(false);
|
||||
});
|
||||
|
||||
test("workflow definition hooks validate metadata without workflow bodies", () => {
|
||||
const payload = {
|
||||
tenantId: "tenant_1",
|
||||
workflowId: "workflow_1",
|
||||
userId: "user_1",
|
||||
status: "draft",
|
||||
appliesToAllTenants: false,
|
||||
occurredAt: "2026-05-26T20:00:00.000Z",
|
||||
};
|
||||
|
||||
expect(validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_CREATED, payload).ok).toBe(true);
|
||||
expect(
|
||||
validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_UPDATED, {
|
||||
...payload,
|
||||
status: "live",
|
||||
changedFields: ["status"],
|
||||
}).ok
|
||||
).toBe(true);
|
||||
expect(
|
||||
validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_DELETED, {
|
||||
...payload,
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
appliesToAllTenants: true,
|
||||
}).ok
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_UPDATED, {
|
||||
...payload,
|
||||
changedFields: ["blocks"],
|
||||
blocks: [{ id: "block_1", input: { token: "secret" } }],
|
||||
}).ok
|
||||
).toBe(false);
|
||||
expect(
|
||||
validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_CREATED, {
|
||||
...payload,
|
||||
credentials: { apiKey: "secret" },
|
||||
}).ok
|
||||
).toBe(false);
|
||||
expect(
|
||||
validatePluginHookPayload(PLUGIN_HOOK_WORKFLOW_CREATED, {
|
||||
...payload,
|
||||
input: { raw: true },
|
||||
}).ok
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("registerHook rejects duplicate name", () => {
|
||||
expect(() =>
|
||||
registerHook({
|
||||
name: "tenant.created",
|
||||
outboxEventType: "plugin.hook.tenant.created",
|
||||
payloadSchema: z.object({}),
|
||||
})
|
||||
).toThrow(/already registered/u);
|
||||
});
|
||||
|
||||
test("registerHook rejects malformed outboxEventType", () => {
|
||||
expect(() =>
|
||||
registerHook({
|
||||
name: "custom.singleword",
|
||||
// missing second dot-segment after plugin.hook
|
||||
outboxEventType: "plugin.hook.singleword" as `plugin.hook.${string}`,
|
||||
payloadSchema: z.object({}),
|
||||
})
|
||||
).toThrow(/must end in/u);
|
||||
});
|
||||
|
||||
test("registerHook rejects malformed or mismatched hook names", () => {
|
||||
expect(() =>
|
||||
registerHook({
|
||||
name: "Tenant.created",
|
||||
outboxEventType: "plugin.hook.tenant.created",
|
||||
payloadSchema: z.object({}),
|
||||
})
|
||||
).toThrow(/lower-case dotted/u);
|
||||
|
||||
expect(() =>
|
||||
registerHook({
|
||||
name: "billing.invoice.paid",
|
||||
outboxEventType: "plugin.hook.billing.invoice.created",
|
||||
payloadSchema: z.object({}),
|
||||
})
|
||||
).toThrow(/must match hook name/u);
|
||||
|
||||
expect(getPluginHook("billing.invoice.paid")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("emitPluginHook", () => {
|
||||
test("publishes a validated outbox event for a valid payload", async () => {
|
||||
const publish = vi.fn().mockResolvedValue({ id: "evt-1" });
|
||||
await emitPluginHook(
|
||||
{ fake: "tx" },
|
||||
PLUGIN_HOOK_TENANT_CREATED,
|
||||
{
|
||||
tenantId: "t-1",
|
||||
slug: "acme",
|
||||
ownerEmail: "owner@example.com",
|
||||
plan: "free",
|
||||
createdAt: "2026-05-17T10:00:00.000Z",
|
||||
},
|
||||
publish,
|
||||
{ tenantId: "t-1", dispatchKey: "tenant:t-1:created" }
|
||||
);
|
||||
expect(publish).toHaveBeenCalledOnce();
|
||||
const args = publish.mock.calls[0]?.[1] as { type: string; tenantId: string | null; dispatchKey: string | null };
|
||||
expect(args.type).toBe("plugin.hook.tenant.created");
|
||||
expect(args.tenantId).toBe("t-1");
|
||||
expect(args.dispatchKey).toBe("tenant:t-1:created");
|
||||
});
|
||||
|
||||
test("throws PluginHookValidationError when payload is invalid", async () => {
|
||||
const publish = vi.fn();
|
||||
await expect(
|
||||
emitPluginHook(
|
||||
{},
|
||||
PLUGIN_HOOK_USER_CREATED,
|
||||
{ email: "not-an-email" } as never,
|
||||
publish
|
||||
)
|
||||
).rejects.toBeInstanceOf(PluginHookValidationError);
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Phase 06 #22 — Plugin hook registry.
|
||||
*
|
||||
* Central, immutable registry of hook names with their Zod payload
|
||||
* schemas. Host call-sites import {@link emitPluginHook} to publish a
|
||||
* `plugin.hook.<name>` outbox event; the registry validates the payload
|
||||
* once before the row is written so a bad payload never reaches the
|
||||
* worker / sandbox boundary.
|
||||
*
|
||||
* Foundation scope (the wider plan lists ~18 hooks): we ship the five
|
||||
* most-load-bearing hook points and gate the rest behind {@link registerHook}
|
||||
* so follow-ups can extend the registry without touching this module.
|
||||
*
|
||||
* - `tenant.created`
|
||||
* - `user.created`
|
||||
* - `entity.created`
|
||||
* - `entity.updated`
|
||||
* - `entity.deleted`
|
||||
* - `workflow.created`
|
||||
* - `workflow.updated`
|
||||
* - `workflow.deleted`
|
||||
* - `workflow.executed`
|
||||
* - `workflow.failed`
|
||||
*
|
||||
* Hooks NOT yet wired (output-shaping, billing, auth, webhooks, email,
|
||||
* chatbot, export, integrations, api-keys, workflows) are documented in
|
||||
* `docs/improvement-plan/06-plugin-system/hooks-lifecycle.md` and will
|
||||
* land in follow-up phases alongside the marketplace + audit-docs tasks.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
const TenantCreatedSchema = z
|
||||
.object({
|
||||
tenantId: z.string().min(1),
|
||||
slug: z.string().min(1),
|
||||
ownerEmail: z.string().email().nullable().optional(),
|
||||
plan: z.string().min(1).nullable().optional(),
|
||||
createdAt: z.string().datetime(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const UserCreatedSchema = z
|
||||
.object({
|
||||
userId: z.string().min(1),
|
||||
tenantId: z.string().min(1).nullable().optional(),
|
||||
email: z.string().email(),
|
||||
locale: z.string().min(2).max(10).nullable().optional(),
|
||||
createdAt: z.string().datetime(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const EntityCrudPayloadSchema = z
|
||||
.object({
|
||||
entityType: z.string().min(1),
|
||||
entityId: z.string().min(1),
|
||||
tenantId: z.string().min(1).nullable(),
|
||||
userId: z.string().min(1).nullable().optional(),
|
||||
changedFields: z.array(z.string()).optional(),
|
||||
occurredAt: z.string().datetime(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const WorkflowExecutionPayloadBaseSchema = z
|
||||
.object({
|
||||
tenantId: z.string().min(1),
|
||||
workflowId: z.string().min(1),
|
||||
workflowExecutionId: z.string().min(1),
|
||||
userId: z.string().min(1).nullable().optional(),
|
||||
type: z.enum(["manual", "api", "stream", "trigger"]),
|
||||
status: z.enum(["success", "error"]),
|
||||
durationMs: z.number().int().nonnegative(),
|
||||
errorCode: z.string().min(1).max(128).nullable(),
|
||||
appliesToAllTenants: z.boolean(),
|
||||
occurredAt: z.string().datetime(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const WorkflowExecutedPayloadSchema = WorkflowExecutionPayloadBaseSchema.superRefine((payload, ctx) => {
|
||||
if (payload.status === "success" && payload.errorCode !== null) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["errorCode"],
|
||||
message: "workflow.executed success payloads must not include errorCode.",
|
||||
});
|
||||
}
|
||||
if (payload.status === "error" && payload.errorCode === null) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["errorCode"],
|
||||
message: "workflow.executed error payloads require errorCode.",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const WorkflowFailedPayloadSchema = WorkflowExecutionPayloadBaseSchema.extend({
|
||||
status: z.literal("error"),
|
||||
errorCode: z.string().min(1).max(128),
|
||||
}).strict();
|
||||
|
||||
const WorkflowDefinitionPayloadSchema = z
|
||||
.object({
|
||||
tenantId: z.string().min(1).nullable(),
|
||||
workflowId: z.string().min(1),
|
||||
userId: z.string().min(1).nullable(),
|
||||
status: z.enum(["draft", "live", "archived"]),
|
||||
appliesToAllTenants: z.boolean(),
|
||||
changedFields: z.array(z.string()).optional(),
|
||||
occurredAt: z.string().datetime(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/**
|
||||
* Hook registry row. `outboxEventType` is the canonical eventType used
|
||||
* by {@link publishOutboxEvent} and routed by the worker dispatcher.
|
||||
*/
|
||||
export type PluginHookDefinition<TPayload> = {
|
||||
readonly name: string;
|
||||
readonly outboxEventType: `plugin.hook.${string}`;
|
||||
readonly payloadSchema: z.ZodType<TPayload>;
|
||||
};
|
||||
|
||||
type AnyPluginHookDefinition = PluginHookDefinition<unknown>;
|
||||
|
||||
// Internal mutable map; only mutated via `registerHook`. Exposed
|
||||
// read-only to consumers.
|
||||
const REGISTRY = new Map<string, AnyPluginHookDefinition>();
|
||||
const HOOK_NAME_PATTERN = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)+$/u;
|
||||
|
||||
export const PLUGIN_PRODUCTION_AVAILABLE_HOOK_NAMES = [
|
||||
"tenant.created",
|
||||
"user.created",
|
||||
"entity.created",
|
||||
"entity.updated",
|
||||
"entity.deleted",
|
||||
"workflow.created",
|
||||
"workflow.updated",
|
||||
"workflow.deleted",
|
||||
"workflow.executed",
|
||||
"workflow.failed",
|
||||
] as const;
|
||||
|
||||
const PRODUCTION_AVAILABLE_HOOK_SET = new Set<string>(PLUGIN_PRODUCTION_AVAILABLE_HOOK_NAMES);
|
||||
|
||||
function defineHook<TPayload>(def: PluginHookDefinition<TPayload>): PluginHookDefinition<TPayload> {
|
||||
if (REGISTRY.has(def.name)) {
|
||||
throw new Error(`Plugin hook '${def.name}' is already registered.`);
|
||||
}
|
||||
// outboxEventType must match the publishOutboxEvent pattern
|
||||
// `<domain>.<entity>.<verb>` — `plugin.hook.<name>` qualifies as
|
||||
// long as `<name>` has at least one dot (e.g. `tenant.created`).
|
||||
// We enforce that here so registration fails loudly at module-load.
|
||||
if (!HOOK_NAME_PATTERN.test(def.name)) {
|
||||
throw new Error(`Plugin hook name '${def.name}' must be lower-case dotted '<entity>.<verb>'.`);
|
||||
}
|
||||
const tail = def.outboxEventType.slice("plugin.hook.".length);
|
||||
if (!HOOK_NAME_PATTERN.test(tail)) {
|
||||
throw new Error(
|
||||
`Plugin hook outboxEventType '${def.outboxEventType}' must end in '<entity>.<verb>'.`
|
||||
);
|
||||
}
|
||||
if (def.outboxEventType !== `plugin.hook.${def.name}`) {
|
||||
throw new Error(`Plugin hook outboxEventType '${def.outboxEventType}' must match hook name '${def.name}'.`);
|
||||
}
|
||||
REGISTRY.set(def.name, def as AnyPluginHookDefinition);
|
||||
return def;
|
||||
}
|
||||
|
||||
export const PLUGIN_HOOK_TENANT_CREATED = defineHook({
|
||||
name: "tenant.created",
|
||||
outboxEventType: "plugin.hook.tenant.created",
|
||||
payloadSchema: TenantCreatedSchema,
|
||||
});
|
||||
|
||||
export const PLUGIN_HOOK_USER_CREATED = defineHook({
|
||||
name: "user.created",
|
||||
outboxEventType: "plugin.hook.user.created",
|
||||
payloadSchema: UserCreatedSchema,
|
||||
});
|
||||
|
||||
export const PLUGIN_HOOK_ENTITY_CREATED = defineHook({
|
||||
name: "entity.created",
|
||||
outboxEventType: "plugin.hook.entity.created",
|
||||
payloadSchema: EntityCrudPayloadSchema,
|
||||
});
|
||||
|
||||
export const PLUGIN_HOOK_ENTITY_UPDATED = defineHook({
|
||||
name: "entity.updated",
|
||||
outboxEventType: "plugin.hook.entity.updated",
|
||||
payloadSchema: EntityCrudPayloadSchema,
|
||||
});
|
||||
|
||||
export const PLUGIN_HOOK_ENTITY_DELETED = defineHook({
|
||||
name: "entity.deleted",
|
||||
outboxEventType: "plugin.hook.entity.deleted",
|
||||
payloadSchema: EntityCrudPayloadSchema,
|
||||
});
|
||||
|
||||
export const PLUGIN_HOOK_WORKFLOW_EXECUTED = defineHook({
|
||||
name: "workflow.executed",
|
||||
outboxEventType: "plugin.hook.workflow.executed",
|
||||
payloadSchema: WorkflowExecutedPayloadSchema,
|
||||
});
|
||||
|
||||
export const PLUGIN_HOOK_WORKFLOW_FAILED = defineHook({
|
||||
name: "workflow.failed",
|
||||
outboxEventType: "plugin.hook.workflow.failed",
|
||||
payloadSchema: WorkflowFailedPayloadSchema,
|
||||
});
|
||||
|
||||
export const PLUGIN_HOOK_WORKFLOW_CREATED = defineHook({
|
||||
name: "workflow.created",
|
||||
outboxEventType: "plugin.hook.workflow.created",
|
||||
payloadSchema: WorkflowDefinitionPayloadSchema,
|
||||
});
|
||||
|
||||
export const PLUGIN_HOOK_WORKFLOW_UPDATED = defineHook({
|
||||
name: "workflow.updated",
|
||||
outboxEventType: "plugin.hook.workflow.updated",
|
||||
payloadSchema: WorkflowDefinitionPayloadSchema,
|
||||
});
|
||||
|
||||
export const PLUGIN_HOOK_WORKFLOW_DELETED = defineHook({
|
||||
name: "workflow.deleted",
|
||||
outboxEventType: "plugin.hook.workflow.deleted",
|
||||
payloadSchema: WorkflowDefinitionPayloadSchema,
|
||||
});
|
||||
|
||||
export type PluginHookTenantCreatedPayload = z.infer<typeof TenantCreatedSchema>;
|
||||
export type PluginHookUserCreatedPayload = z.infer<typeof UserCreatedSchema>;
|
||||
export type PluginHookEntityCrudPayload = z.infer<typeof EntityCrudPayloadSchema>;
|
||||
export type PluginHookWorkflowExecutedPayload = z.infer<typeof WorkflowExecutedPayloadSchema>;
|
||||
export type PluginHookWorkflowFailedPayload = z.infer<typeof WorkflowFailedPayloadSchema>;
|
||||
export type PluginHookWorkflowDefinitionPayload = z.infer<typeof WorkflowDefinitionPayloadSchema>;
|
||||
|
||||
/**
|
||||
* Register an additional hook at module-load time. Used by tests and
|
||||
* by follow-up tasks that extend the registry. Throws when the hook
|
||||
* name or outboxEventType is already taken.
|
||||
*/
|
||||
export function registerHook<TPayload>(def: PluginHookDefinition<TPayload>): PluginHookDefinition<TPayload> {
|
||||
return defineHook(def);
|
||||
}
|
||||
|
||||
export function getPluginHook(name: string): AnyPluginHookDefinition | undefined {
|
||||
return REGISTRY.get(name);
|
||||
}
|
||||
|
||||
export function listPluginHooks(): ReadonlyArray<AnyPluginHookDefinition> {
|
||||
return Array.from(REGISTRY.values());
|
||||
}
|
||||
|
||||
export function isPluginHookProductionAvailable(value: unknown): value is (typeof PLUGIN_PRODUCTION_AVAILABLE_HOOK_NAMES)[number] {
|
||||
return typeof value === "string" && PRODUCTION_AVAILABLE_HOOK_SET.has(value);
|
||||
}
|
||||
|
||||
export function getUnavailablePluginHookNames(hooks: ReadonlyArray<string | { name: string }>): string[] {
|
||||
const unavailable = new Set<string>();
|
||||
for (const hook of hooks) {
|
||||
const name = typeof hook === "string" ? hook : hook.name;
|
||||
if (REGISTRY.has(name) && !isPluginHookProductionAvailable(name)) {
|
||||
unavailable.add(name);
|
||||
}
|
||||
}
|
||||
return [...unavailable].sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse-and-typecheck a payload against the registered schema. Returns
|
||||
* the canonical (Zod-parsed) value on success or a structured failure
|
||||
* with the original Zod issues for logging.
|
||||
*/
|
||||
export type PluginHookValidationResult<TPayload> =
|
||||
| { ok: true; payload: TPayload }
|
||||
| { ok: false; issues: ReadonlyArray<z.ZodIssue> };
|
||||
|
||||
export function validatePluginHookPayload<TPayload>(
|
||||
def: PluginHookDefinition<TPayload>,
|
||||
payload: unknown
|
||||
): PluginHookValidationResult<TPayload> {
|
||||
const result = def.payloadSchema.safeParse(payload);
|
||||
if (!result.success) {
|
||||
return { ok: false, issues: result.error.issues };
|
||||
}
|
||||
return { ok: true, payload: result.data };
|
||||
}
|
||||
|
||||
/** Reset hook for tests only. Not exported from package index. */
|
||||
export function __resetPluginHookRegistryForTests(): void {
|
||||
REGISTRY.clear();
|
||||
defineHook(PLUGIN_HOOK_TENANT_CREATED);
|
||||
defineHook(PLUGIN_HOOK_USER_CREATED);
|
||||
defineHook(PLUGIN_HOOK_ENTITY_CREATED);
|
||||
defineHook(PLUGIN_HOOK_ENTITY_UPDATED);
|
||||
defineHook(PLUGIN_HOOK_ENTITY_DELETED);
|
||||
defineHook(PLUGIN_HOOK_WORKFLOW_EXECUTED);
|
||||
defineHook(PLUGIN_HOOK_WORKFLOW_FAILED);
|
||||
defineHook(PLUGIN_HOOK_WORKFLOW_CREATED);
|
||||
defineHook(PLUGIN_HOOK_WORKFLOW_UPDATED);
|
||||
defineHook(PLUGIN_HOOK_WORKFLOW_DELETED);
|
||||
}
|
||||
Reference in new issue
Block a user