From 518f060ca2e494a3187f51a2f69f18457ee93b64 Mon Sep 17 00:00:00 2001 From: Mayank Dhingra Date: Sat, 14 Nov 2026 11:15:21 -0500 Subject: [PATCH] Preserve own data Error causes through serialization --- cjs/deserialize.js | 10 +++++- cjs/serialize.js | 12 ++++++-- esm/deserialize.js | 10 +++++- esm/serialize.js | 12 ++++++-- structured-json.js | 2 +- test/error-cause.js | 74 +++++++++++++++++++++++++++++++++++++++++++++ test/index.js | 2 ++ 7 files changed, 115 insertions(+), 7 deletions(-) create mode 100644 test/error-cause.js diff --git a/cjs/deserialize.js b/cjs/deserialize.js index cb84880..caf9b02 100644 --- a/cjs/deserialize.js +++ b/cjs/deserialize.js @@ -4,6 +4,7 @@ const { } = require('./types.js'); const { defineProperty } = Object; +const {hasOwnProperty} = Object.prototype; const env = typeof self === 'object' ? self : globalThis; const guard = (name, init) => { @@ -74,12 +75,19 @@ const deserializer = ($, _) => { } case ERROR: { const {name, message} = value; - return as( + const error = as( typeof env[name] === 'function' ? guard(name, message) : new Error(message), index ); + if (hasOwnProperty.call(value, 'cause')) + defineProperty(error, 'cause', { + value: unpair(value.cause), + configurable: true, + writable: true + }); + return error; } case BIGINT: return as(BigInt(value), index); diff --git a/cjs/serialize.js b/cjs/serialize.js index 45bce6e..68e78aa 100644 --- a/cjs/serialize.js +++ b/cjs/serialize.js @@ -6,7 +6,7 @@ const { const EMPTY = ''; const {toString} = {}; -const {keys, is} = Object; +const {keys, is, getOwnPropertyDescriptor} = Object; const typeOf = value => { const type = typeof value; @@ -149,7 +149,15 @@ const serializer = (strict, json, $, _) => { } const {message} = value; - return as([TYPE, {name: type, message}], value); + const error = {name: type, message}; + const index = as([TYPE, error], value); + const descriptor = getOwnPropertyDescriptor(value, 'cause'); + if (descriptor && 'value' in descriptor) { + const cause = descriptor.value; + if (strict || !shouldSkip(typeOf(cause))) + error.cause = pair(cause); + } + return index; }; return pair; diff --git a/esm/deserialize.js b/esm/deserialize.js index 86920f0..2cfbf9c 100644 --- a/esm/deserialize.js +++ b/esm/deserialize.js @@ -6,6 +6,7 @@ import { } from './types.js'; const { defineProperty } = Object; +const {hasOwnProperty} = Object.prototype; const env = typeof self === 'object' ? self : globalThis; const guard = (name, init) => { @@ -76,12 +77,19 @@ const deserializer = ($, _) => { } case ERROR: { const {name, message} = value; - return as( + const error = as( typeof env[name] === 'function' ? guard(name, message) : new Error(message), index ); + if (hasOwnProperty.call(value, 'cause')) + defineProperty(error, 'cause', { + value: unpair(value.cause), + configurable: true, + writable: true + }); + return error; } case BIGINT: return as(BigInt(value), index); diff --git a/esm/serialize.js b/esm/serialize.js index 6217735..4e58803 100644 --- a/esm/serialize.js +++ b/esm/serialize.js @@ -8,7 +8,7 @@ import { const EMPTY = ''; const {toString} = {}; -const {keys, is} = Object; +const {keys, is, getOwnPropertyDescriptor} = Object; const typeOf = value => { const type = typeof value; @@ -151,7 +151,15 @@ const serializer = (strict, json, $, _) => { } const {message} = value; - return as([TYPE, {name: type, message}], value); + const error = {name: type, message}; + const index = as([TYPE, error], value); + const descriptor = getOwnPropertyDescriptor(value, 'cause'); + if (descriptor && 'value' in descriptor) { + const cause = descriptor.value; + if (strict || !shouldSkip(typeOf(cause))) + error.cause = pair(cause); + } + return index; }; return pair; diff --git a/structured-json.js b/structured-json.js index 4fa6359..f68da87 100644 --- a/structured-json.js +++ b/structured-json.js @@ -1 +1 @@ -var StructuredJSON=function(e){"use strict";const{defineProperty:r}=Object,t="object"==typeof self?self:globalThis,n=(e,r)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new t[e](r)},s=e=>((e,s)=>{const a=(r,t)=>(e.set(t,r),r),c=o=>{if(e.has(o))return e.get(o);const[u,i]=s[o];switch(u){case 0:case-1:return a(i,o);case 1:{const e=a([],o);for(const r of i)e.push(c(r));return e}case 2:{const e=a({},o);for(const[t,n]of i){const s=c(t),a=c(n);"__proto__"===s?r(e,s,{value:a,configurable:!0,enumerable:!0,writable:!0}):e[s]=a}return e}case 3:return a(new Date(i),o);case 4:{const{source:e,flags:r}=i;return a(new RegExp(e,r),o)}case 5:{const e=a(new Map,o);for(const[r,t]of i)e.set(c(r),c(t));return e}case 6:{const e=a(new Set,o);for(const r of i)e.add(c(r));return e}case 7:{const{name:e,message:r}=i;return a("function"==typeof t[e]?n(e,r):new Error(r),o)}case 8:return a(BigInt(i),o);case"BigInt":return a(Object(BigInt(i)),o);case"ArrayBuffer":return a(new Uint8Array(i).buffer,i);case"DataView":{const{buffer:e}=new Uint8Array(i);return a(new DataView(e),i)}case"-0":return-0}return a(n(u,i),o)};return c})(new Map,e)(0),a="",{toString:c}={},{keys:o,is:u}=Object,i=e=>{const r=typeof e;if("object"!==r||!e)return[0,r];const t=c.call(e).slice(8,-1);switch(t){case"Array":return[1,a];case"Object":return[2,a];case"Date":return[3,a];case"RegExp":return[4,a];case"Map":return[5,a];case"Set":return[6,a];case"DataView":return[1,t]}return t.includes("Array")?[1,t]:e instanceof Error?[7,e.name||"Error"]:[2,t]},f=([e,r])=>0===e&&("function"===r||"symbol"===r),l=(e,{json:r,lossy:t}={})=>{const n=[];return((e,r,t,n)=>{const s=(e,r)=>{const s=n.push(e)-1;return t.set(r,s),s},c=l=>{if(t.has(l))return t.get(l);let[w,g]=i(l);switch(w){case 0:{let r=l;switch(g){case"bigint":w=8,r=l.toString();break;case"number":if(!l&&u(l,-0))return n.push(["-0"])-1;break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+g);r=null;break;case"undefined":return s([-1],l)}return s([w,r],l)}case 1:{if(g){let e=l;return"DataView"===g?e=new Uint8Array(l.buffer):"ArrayBuffer"===g&&(e=new Uint8Array(l)),s([g,[...e]],l)}const e=[],r=s([w,e],l);for(const r of l)e.push(c(r));return r}case 2:{if(g)switch(g){case"BigInt":return s([g,l.toString()],l);case"Boolean":case"Number":case"String":return s([g,l.valueOf()],l)}if(r&&"toJSON"in l)return c(l.toJSON());const t=[],n=s([w,t],l);for(const r of o(l))!e&&f(i(l[r]))||t.push([c(r),c(l[r])]);return n}case 3:return s([w,isNaN(l.getTime())?a:l.toISOString()],l);case 4:{const{source:e,flags:r}=l;return s([w,{source:e,flags:r}],l)}case 5:{const r=[],t=s([w,r],l);for(const[t,n]of l)(e||!f(i(t))&&!f(i(n)))&&r.push([c(t),c(n)]);return t}case 6:{const r=[],t=s([w,r],l);for(const t of l)!e&&f(i(t))||r.push(c(t));return t}}const{message:b}=l;return s([w,{name:g,message:b}],l)};return c})(!(r||t),!!r,new Map,n)(e),n},{parse:w,stringify:g}=JSON,b={json:!0,lossy:!0};return e.parse=e=>s(w(e)),e.stringify=e=>g(l(e,b)),e}({}); +var StructuredJSON=function(e){"use strict";const{defineProperty:r}=Object,{hasOwnProperty:t}=Object.prototype,n="object"==typeof self?self:globalThis,s=(e,r)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new n[e](r)},a=e=>((e,a)=>{const c=(r,t)=>(e.set(t,r),r),o=u=>{if(e.has(u))return e.get(u);const[i,f]=a[u];switch(i){case 0:case-1:return c(f,u);case 1:{const e=c([],u);for(const r of f)e.push(o(r));return e}case 2:{const e=c({},u);for(const[t,n]of f){const s=o(t),a=o(n);"__proto__"===s?r(e,s,{value:a,configurable:!0,enumerable:!0,writable:!0}):e[s]=a}return e}case 3:return c(new Date(f),u);case 4:{const{source:e,flags:r}=f;return c(new RegExp(e,r),u)}case 5:{const e=c(new Map,u);for(const[r,t]of f)e.set(o(r),o(t));return e}case 6:{const e=c(new Set,u);for(const r of f)e.add(o(r));return e}case 7:{const{name:e,message:a}=f,i=c("function"==typeof n[e]?s(e,a):new Error(a),u);return t.call(f,"cause")&&r(i,"cause",{value:o(f.cause),configurable:!0,writable:!0}),i}case 8:return c(BigInt(f),u);case"BigInt":return c(Object(BigInt(f)),u);case"ArrayBuffer":return c(new Uint8Array(f).buffer,f);case"DataView":{const{buffer:e}=new Uint8Array(f);return c(new DataView(e),f)}case"-0":return-0}return c(s(i,f),u)};return o})(new Map,e)(0),c="",{toString:o}={},{keys:u,is:i,getOwnPropertyDescriptor:f}=Object,l=e=>{const r=typeof e;if("object"!==r||!e)return[0,r];const t=o.call(e).slice(8,-1);switch(t){case"Array":return[1,c];case"Object":return[2,c];case"Date":return[3,c];case"RegExp":return[4,c];case"Map":return[5,c];case"Set":return[6,c];case"DataView":return[1,t]}return t.includes("Array")?[1,t]:e instanceof Error?[7,e.name||"Error"]:[2,t]},w=([e,r])=>0===e&&("function"===r||"symbol"===r),g=(e,{json:r,lossy:t}={})=>{const n=[];return((e,r,t,n)=>{const s=(e,r)=>{const s=n.push(e)-1;return t.set(r,s),s},a=o=>{if(t.has(o))return t.get(o);let[g,p]=l(o);switch(g){case 0:{let r=o;switch(p){case"bigint":g=8,r=o.toString();break;case"number":if(!o&&i(o,-0))return n.push(["-0"])-1;break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);r=null;break;case"undefined":return s([-1],o)}return s([g,r],o)}case 1:{if(p){let e=o;return"DataView"===p?e=new Uint8Array(o.buffer):"ArrayBuffer"===p&&(e=new Uint8Array(o)),s([p,[...e]],o)}const e=[],r=s([g,e],o);for(const r of o)e.push(a(r));return r}case 2:{if(p)switch(p){case"BigInt":return s([p,o.toString()],o);case"Boolean":case"Number":case"String":return s([p,o.valueOf()],o)}if(r&&"toJSON"in o)return a(o.toJSON());const t=[],n=s([g,t],o);for(const r of u(o))!e&&w(l(o[r]))||t.push([a(r),a(o[r])]);return n}case 3:return s([g,isNaN(o.getTime())?c:o.toISOString()],o);case 4:{const{source:e,flags:r}=o;return s([g,{source:e,flags:r}],o)}case 5:{const r=[],t=s([g,r],o);for(const[t,n]of o)(e||!w(l(t))&&!w(l(n)))&&r.push([a(t),a(n)]);return t}case 6:{const r=[],t=s([g,r],o);for(const t of o)!e&&w(l(t))||r.push(a(t));return t}}const{message:b}=o,y={name:p,message:b},h=s([g,y],o),S=f(o,"cause");if(S&&"value"in S){const r=S.value;!e&&w(l(r))||(y.cause=a(r))}return h};return a})(!(r||t),!!r,new Map,n)(e),n},{parse:p,stringify:b}=JSON,y={json:!0,lossy:!0};return e.parse=e=>a(p(e)),e.stringify=e=>b(g(e,y)),e}({}); diff --git a/test/error-cause.js b/test/error-cause.js new file mode 100644 index 0000000..66dba10 --- /dev/null +++ b/test/error-cause.js @@ -0,0 +1,74 @@ +const assert = require('node:assert/strict'); +const {serialize, deserialize, default: clone} = require('../cjs'); +const {parse, stringify} = require('../cjs/json'); + +for (const roundTrip of [ + value => deserialize(serialize(value)), + value => parse(stringify(value)), + value => clone(value, {lossy: false}) +]) { + for (const Class of [Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError]) { + const original = new Class('outer', {cause: new TypeError('inner')}); + const native = globalThis.structuredClone(original); + const actual = roundTrip(original); + assert.equal(actual.constructor, native.constructor); + assert.equal(actual.cause.constructor, native.cause.constructor); + assert.equal(actual.cause.message, native.cause.message); + assert.deepEqual(Object.getOwnPropertyDescriptor(actual, 'cause'), { + value: actual.cause, enumerable: false, configurable: true, writable: true + }); + } + + for (const cause of [undefined, null, false, 0, '', 'reason', 1n, {status: 500}]) { + const actual = roundTrip(new Error('outer', {cause})); + assert.equal(Object.hasOwn(actual, 'cause'), true); + assert.deepEqual(actual.cause, cause); + } + + const shared = {status: 500}; + const actual = roundTrip({error: new Error('outer', {cause: shared}), shared}); + assert.equal(actual.error.cause, actual.shared); + + const self = new Error('self'); + self.cause = self; + const selfClone = roundTrip(self); + assert.equal(selfClone.cause, selfClone); + + const first = new Error('first'); + const second = new TypeError('second', {cause: first}); + first.cause = second; + const cycle = roundTrip(first); + assert.equal(cycle.cause.cause, cycle); + assert.equal(cycle.cause.message, 'second'); + + const inherited = new Error('inherited'); + Object.setPrototypeOf(inherited, Object.create(Error.prototype, { + cause: {value: 'inherited cause'} + })); + assert.equal(Object.hasOwn(roundTrip(inherited), 'cause'), false); + + let reads = 0; + const getter = new Error('getter'); + Object.defineProperty(getter, 'cause', {get() { reads++; return shared; }}); + const nativeGetter = globalThis.structuredClone(getter); + const actualGetter = roundTrip(getter); + assert.equal(Object.hasOwn(actualGetter, 'cause'), Object.hasOwn(nativeGetter, 'cause')); + assert.equal(reads, 0); + + const throwing = new Error('throwing getter'); + Object.defineProperty(throwing, 'cause', {get() { throw new Error('must not run'); }}); + assert.equal(Object.hasOwn(roundTrip(throwing), 'cause'), false); + assert.equal(Object.hasOwn(globalThis.structuredClone(throwing), 'cause'), false); +} + +for (const cause of [() => {}, Symbol('reason')]) { + const error = new Error('outer', {cause}); + assert.throws(() => serialize(error), TypeError); + assert.equal(Object.hasOwn(deserialize(serialize(error, {lossy: true})), 'cause'), false); + assert.equal(Object.hasOwn(parse(stringify(error)), 'cause'), false); +} + +const legacy = [[7, {name: 'Error', message: 'legacy'}]]; +assert.equal(deserialize(legacy).message, 'legacy'); +assert.equal(Object.hasOwn(deserialize(legacy), 'cause'), false); +assert.deepEqual(serialize(new Error('legacy')), legacy); diff --git a/test/index.js b/test/index.js index b03edc4..9ad9b02 100644 --- a/test/index.js +++ b/test/index.js @@ -199,3 +199,5 @@ for (const Class of [Error, EvalError, RangeError, ReferenceError, SyntaxError, } require('./eval.js'); + +require('./error-cause.js');