import { pathToFileURL } from "node:url"; import { runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { CustomerPortalUatError, parseCustomerPortalUatCommand, safeCustomerPortalUatError, type CustomerPortalFixtureCommand } from "./contracts"; import { withCustomerPortalOperatorDatabase } from "./database"; import { applyCustomerPortalFixture, assessCustomerPortalFixture, readCustomerPortalFixture, type CustomerPortalFixtureAssessment } from "./fixture"; type FixtureExecutionResult = { readonly mode: CustomerPortalFixtureCommand["mode"]; readonly complete: boolean; readonly assessment: CustomerPortalFixtureAssessment; }; function writeResult(result: FixtureExecutionResult): void { process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); } async function executeFixtureCommand(command: CustomerPortalFixtureCommand): Promise { return withCustomerPortalOperatorDatabase(command, (db) => runWithRlsContext({ tenantId: command.expectedTenantId }, async () => { const inspect = async () => { const snapshot = await readCustomerPortalFixture(db, command); return { snapshot, assessment: assessCustomerPortalFixture(snapshot, command.expectedTenantId) }; }; const initial = await inspect(); if (command.mode === "plan") { return { mode: command.mode, complete: initial.assessment.action === "noop", assessment: initial.assessment }; } if (command.mode === "verify") { if (initial.assessment.action !== "noop") { throw new CustomerPortalUatError("customer-portal UAT: fixture verification found missing, drifted, or unsafe state"); } return { mode: command.mode, complete: true, assessment: initial.assessment }; } if (initial.assessment.action === "blocked") { throw new CustomerPortalUatError("customer-portal UAT: fixture apply is blocked by non-UAT or mismatched staging state"); } await applyCustomerPortalFixture(db, command, initial.snapshot); const final = await inspect(); if (final.assessment.action !== "noop") { throw new CustomerPortalUatError("customer-portal UAT: fixture did not converge to the canonical contract"); } return { mode: command.mode, complete: true, assessment: final.assessment }; }) ); } export async function main(argv: readonly string[] = process.argv.slice(2), env: NodeJS.ProcessEnv = process.env): Promise { const command = parseCustomerPortalUatCommand("fixture", argv, env); if (command.target !== "fixture") throw new CustomerPortalUatError("customer-portal UAT: invalid fixture command"); writeResult(await executeFixtureCommand(command)); } const directEntry = process.argv[1] ? pathToFileURL(process.argv[1]).href === import.meta.url : false; if (directEntry) { void main().catch((error) => { process.stderr.write(`${safeCustomerPortalUatError(error)}\n`); process.exitCode = 1; }); }