export type PortalActorAttributionInput = { readonly createdByUserId?: string | null; readonly createdByPortalUserId?: string | null; }; export type PortalActorAttribution = | { readonly actorKind: "user"; readonly actorId: string; readonly createdByUserId: string; readonly createdByPortalUserId: null; } | { readonly actorKind: "portal_user"; readonly actorId: string; readonly createdByUserId: null; readonly createdByPortalUserId: string; }; export class PortalActorAttributionError extends Error { readonly code = "portal_actor_exactly_one_required"; constructor() { super("Exactly one internal or portal actor is required"); this.name = "PortalActorAttributionError"; } } function normalizedId(value: string | null | undefined): string | null { const normalized = value?.trim() ?? ""; return normalized.length > 0 ? normalized : null; } /** * Mirrors the merge-migration CHECK for File, FileUpload, FileEntityLink and * authenticated FormSubmission writes. Portal services call this before any * Prisma mutation so feature-branch db-push databases fail closed too. */ export function requireExactlyOneActor(input: PortalActorAttributionInput): PortalActorAttribution { const createdByUserId = normalizedId(input.createdByUserId); const createdByPortalUserId = normalizedId(input.createdByPortalUserId); if ((createdByUserId === null) === (createdByPortalUserId === null)) { throw new PortalActorAttributionError(); } if (createdByPortalUserId !== null) { return { actorKind: "portal_user", actorId: createdByPortalUserId, createdByUserId: null, createdByPortalUserId }; } const actorId = createdByUserId!; return { actorKind: "user", actorId, createdByUserId: actorId, createdByPortalUserId: null }; } /** Portal mutations must never smuggle in a synthetic TenantUser actor. */ export function requirePortalUserActor(input: PortalActorAttributionInput): Extract { const actor = requireExactlyOneActor(input); if (actor.actorKind !== "portal_user") { throw new PortalActorAttributionError(); } return actor; }