import type { XOTemplate } from '@xo-cash/types'; import { extendedJsonReplacer, extendedJsonReviver } from '../extended-json.ts'; import { TemplateJsonMalformedError, TemplateSerializationFailedError } from './errors.ts'; /** * Serializes an XOTemplate to a JSON string. Encodes `bigint` and `Uint8Array` fields in * Extended JSON format so they can be reconstructed by `deserializeTemplate`. * * @param template The template to serialize. * @returns A JSON string representation of the template. * @throws {TemplateSerializationFailedError} If the template cannot be serialized to JSON. */ export const serializeTemplate = (template: XOTemplate): string => { try { // Serialize the template to a JSON string. return JSON.stringify(template, extendedJsonReplacer); } catch (serializationError) { const reason = serializationError instanceof Error ? serializationError.message : 'unknown error while serializing template'; throw new TemplateSerializationFailedError(reason); } }; /** * Deserializes a JSON string back into an XOTemplate object. Restores `bigint` and * `Uint8Array` fields encoded in Extended JSON format by `serializeTemplate`. * * @param serializedTemplate - A JSON string of an XOTemplate object. * @returns The reconstructed XOTemplate object. * @throws {TemplateJsonMalformedError} If the serialized template is not valid JSON. */ export const deserializeTemplate = (serializedTemplate: string): XOTemplate => { try { // Parse the serialized template using the extended JSON reviver. return JSON.parse(serializedTemplate, extendedJsonReviver); } catch (parsingError) { const reason = parsingError instanceof Error ? parsingError.message : 'unknown error while deserializing template'; throw new TemplateJsonMalformedError(reason); } };