stock-bot/apps/stock/orchestrator/src/canonical-json.ts

23 lines
879 B
TypeScript

/** Only JSON values are checkpointable; reject lossy JSON.stringify conversions. */
export function canonicalJson(value: unknown): string {
const visit = (input: unknown): unknown => {
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
return input;
}
if (typeof input === 'number' && Number.isFinite(input)) {
return input;
}
if (Array.isArray(input)) {
return Array.from(input, visit);
}
if (input && typeof input === 'object' && Object.getPrototypeOf(input) === Object.prototype) {
return Object.fromEntries(
Object.entries(input)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([key, item]) => [key, visit(item)])
);
}
throw new Error('Strategy checkpoints require finite, plain JSON values');
};
return JSON.stringify(visit(value));
}