import { CODE_FIELD, CODE_KIND, JSON_EXTENSION, JSON_FOLDER, PAYLOAD_CONTENT_KEY, PAYLOAD_ID_KEY, PAYLOAD_KIND_KEY, PAYLOAD_LABEL_KEY, PAYLOAD_SECTIONS_KEY, PAYLOAD_TABS_KEY, PAYLOAD_TITLE_KEY, } from "#configuration/constants/leak.constants"; import type { PagePayload, PayloadTab } from "#types/leak.types"; import { absolutePath } from "@ssot/paths"; import { readJsonOrNull } from "#core/persistence/report.persistence"; const isRecord = function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null; }; const isCodeSample = function isCodeSample(record: Record, key: string): boolean { return record[PAYLOAD_KIND_KEY] === CODE_KIND && key === CODE_FIELD; }; const collectStrings = function collectStrings(value: unknown): string[] { if (typeof value === "string") { return [value]; } if (Array.isArray(value)) { return value.flatMap((entry: unknown) => collectStrings(entry)); } if (!isRecord(value)) { return []; } return Object.entries(value).flatMap(([key, entry]) => (isCodeSample(value, key) ? [] : collectStrings(entry))); }; const idsOf = function idsOf(list: unknown): string[] { if (!Array.isArray(list)) { return []; } return list.flatMap((entry: unknown) => isRecord(entry) && typeof entry[PAYLOAD_ID_KEY] === "string" ? [entry[PAYLOAD_ID_KEY]] : [], ); }; const tabsOf = function tabsOf(list: unknown): PayloadTab[] { if (!Array.isArray(list)) { return []; } return list.flatMap((entry: unknown) => { if (!isRecord(entry)) { return []; } const id = entry[PAYLOAD_ID_KEY]; const label = entry[PAYLOAD_LABEL_KEY]; return typeof id === "string" && typeof label === "string" ? [{ id, label }] : []; }); }; export const payloadFileOf = function payloadFileOf(page: string): string { return absolutePath("builds.web", JSON_FOLDER, page + JSON_EXTENSION); }; export const readPageContent = function readPageContent(page: string): unknown { const parsed = readJsonOrNull(payloadFileOf(page)); return isRecord(parsed) ? (parsed[PAYLOAD_CONTENT_KEY] ?? null) : null; }; export const readPagePayload = function readPagePayload(page: string): PagePayload | null { const file = payloadFileOf(page); const parsed = readJsonOrNull(file); if (!isRecord(parsed) || !isRecord(parsed[PAYLOAD_CONTENT_KEY])) { return null; } const content = parsed[PAYLOAD_CONTENT_KEY]; const tabs = Array.isArray(content[PAYLOAD_TABS_KEY]) ? content[PAYLOAD_TABS_KEY] : []; const sections = tabs.flatMap((tab: unknown) => (isRecord(tab) ? idsOf(tab[PAYLOAD_SECTIONS_KEY]) : [])); const title = parsed[PAYLOAD_TITLE_KEY]; const label = parsed[PAYLOAD_LABEL_KEY]; return { file, label: typeof label === "string" ? label : "", page, sections, strings: collectStrings(content), tabs: tabsOf(tabs), title: typeof title === "string" ? title : "", }; };