import { PublicPayloadLeakError, assertNoPublicPayloadLeaks, formatPublicPayloadGuardFailureBody, } from "../security/redactionBoundary.js";
const DEFAULT_JSON_SURFACE = "http.response";
const GUARD_FAILURE_JSON_SURFACE = "http.response.guard-failure";
export const PUBLIC_IDENTIFIER_SCAN_OPTIONS = {
    allowedFieldNames: [
        "id",
        "workspaceId",
        "deviceId",
        "userSessionId",
        "runId",
        "requestId",
        "decisionId",
        "messageId",
        "toolCallId",
    ],
};
export const AUTHORITY_CONTRACT_SCAN_OPTIONS = {
    allowedFieldNames: [
        ...PUBLIC_IDENTIFIER_SCAN_OPTIONS.allowedFieldNames,
        "tokenPrefix",
        "fragmentParameter",
    ],
    allowedFindingLabels: ["forbidden field assignment"],
};
export function writeJson(response, statusCode, payload, policy = {}) {
    response.setHeader("content-type", "application/json; charset=utf-8");
    response.setHeader("cache-control", "no-store");
    try {
        assertNoPublicPayloadLeaks(policy.surface ?? DEFAULT_JSON_SURFACE, payload, policy.scanOptions);
        response.statusCode = statusCode;
        response.end(`${JSON.stringify(payload)}\n`);
    }
    catch (error) {
        if (!(error instanceof PublicPayloadLeakError))
            throw error;
        const failureBody = formatPublicPayloadGuardFailureBody(error);
        assertNoPublicPayloadLeaks(GUARD_FAILURE_JSON_SURFACE, failureBody);
        response.statusCode = 500;
        response.end(`${JSON.stringify(failureBody)}\n`);
    }
}
