const crypto = require('crypto');

function stableStringify(obj) {
    if (obj === null || typeof obj !== 'object') return JSON.stringify(obj);
    if (Array.isArray(obj)) return '[' + obj.map(stableStringify).join(',') + ']';
    const keys = Object.keys(obj).sort();
    return '{' + keys.map(k => JSON.stringify(k) + ':' + stableStringify(obj[k])).join(',') + '}';
}

module.exports = {
    friendlyName: 'Stable JSON hash',
    inputs: { obj: { type: 'ref', required: true } },
    exits: { success: {} },
    fn: async function ({ obj }, exits) {
        const str = stableStringify(obj);
        const hash = crypto.createHash('sha256').update(str).digest('hex');
        return exits.success({ hash, str });
    }
};


