// HASHING — the one canonicalizer in this package, the content hash every id and every changeset // hash is built on. import { createHash } from 'node:crypto'; export type SubjectFields = Record; export type FieldChange = { before: unknown; after: unknown }; /** Deterministic JSON: object keys sorted, `undefined` entries dropped, arrays in order. * The one canonicalizer in this package — `hashFieldValue` (action-id content hashing) and * `changesetContentHash` (approval binds to exact bytes) must agree on what "same content" * means, so they share this function rather than each rolling their own. */ export function canonicalJson(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; if (value && typeof value === 'object') { const entries = Object.entries(value as Record) .filter(([, item]) => item !== undefined) .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) .map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`); return `{${entries.join(',')}}`; } return JSON.stringify(value) ?? 'null'; } export function hashFieldValue(value: unknown): string { return createHash('sha256').update(canonicalJson(value)).digest('hex').slice(0, 16); } export function subjectKey(subject: { type: string; id: string }): string { return `${subject.type}:${subject.id}`; } /** Field-level diff of freshly observed subject fields against a shadow of them. */ export type SubjectShadow = { subject: { type: string; id: string }; fields: SubjectFields; fieldHashes: Record; latestEventId: string; updatedAt: string }; export function diffSubjectFields(shadow: SubjectShadow | undefined, observed: SubjectFields): Record { const changed: Record = {}; for (const [field, after] of Object.entries(observed)) { if (after === undefined) continue; const beforeHash = shadow?.fieldHashes[field]; if (beforeHash !== undefined && beforeHash === hashFieldValue(after)) continue; changed[field] = { before: shadow?.fields[field], after }; } return changed; }