@@ -7,6 +7,10 @@ import type { ExtData } from "./ExtData";
77export const DEFAULT_MAX_DEPTH = 100 ;
88export const DEFAULT_INITIAL_BUFFER_SIZE = 2048 ;
99
10+ const hastoJSON = ( value : unknown ) : value is { toJSON : unknown } => {
11+ return typeof value === 'object' && value !== null && 'toJSON' in value ;
12+ } ;
13+
1014export class Encoder < ContextType = undefined > {
1115 private pos = 0 ;
1216 private view = new DataView ( new ArrayBuffer ( this . initialBufferSize ) ) ;
@@ -187,14 +191,19 @@ export class Encoder<ContextType = undefined> {
187191 private encodeObject ( object : unknown , depth : number ) {
188192 // try to encode objects with custom codec first of non-primitives
189193 const ext = this . extensionCodec . tryToEncode ( object , this . context ) ;
194+
190195 if ( ext != null ) {
191196 this . encodeExtension ( ext ) ;
192197 } else if ( Array . isArray ( object ) ) {
193198 this . encodeArray ( object , depth ) ;
194199 } else if ( ArrayBuffer . isView ( object ) ) {
195200 this . encodeBinary ( object ) ;
196201 } else if ( typeof object === "object" ) {
197- this . encodeMap ( object as Record < string , unknown > , depth ) ;
202+ if ( hastoJSON ( object ) && typeof object . toJSON === "function" ) {
203+ this . doEncode ( object . toJSON ( ) , depth ) ;
204+ } else {
205+ this . encodeMap ( object as Record < string , unknown > , depth ) ;
206+ }
198207 } else {
199208 // symbol, function and other special object come here unless extensionCodec handles them.
200209 throw new Error ( `Unrecognized object: ${ Object . prototype . toString . apply ( object ) } ` ) ;
0 commit comments