@@ -497,6 +497,41 @@ describe("safeWriteJson", () => {
497497 expect ( content ) . toEqual ( { value : 42 } )
498498 } )
499499
500+ test ( "should propagate non-ENOENT read errors during merge instead of silently losing data" , async ( ) => {
501+ const initial = { a : 1 , b : 2 }
502+ await safeWriteJson ( currentTestFilePath , initial )
503+
504+ const eio = Object . assign ( new Error ( "I/O error" ) , { code : "EIO" } )
505+ vi . mocked ( fs . readFile ) . mockRejectedValueOnce ( eio )
506+
507+ await expect (
508+ safeWriteJson (
509+ currentTestFilePath ,
510+ { b : 99 } ,
511+ {
512+ merge : ( existing , incoming ) => ( {
513+ ...( existing as Record < string , unknown > ) ,
514+ ...( incoming as Record < string , unknown > ) ,
515+ } ) ,
516+ } ,
517+ ) ,
518+ ) . rejects . toThrow ( "I/O error" )
519+
520+ const content = await readFileContent ( currentTestFilePath )
521+ expect ( content ) . toEqual ( { a : 1 , b : 2 } )
522+ } )
523+
524+ test ( "should treat corrupt JSON as null during merge" , async ( ) => {
525+ await fs . writeFile ( currentTestFilePath , "not valid json" , "utf8" )
526+
527+ const mergeFn = vi . fn ( ( _existing , incoming ) => incoming )
528+ await safeWriteJson ( currentTestFilePath , { value : 1 } , { merge : mergeFn } )
529+
530+ expect ( mergeFn ) . toHaveBeenCalledWith ( null , { value : 1 } )
531+ const content = await readFileContent ( currentTestFilePath )
532+ expect ( content ) . toEqual ( { value : 1 } )
533+ } )
534+
500535 test ( "should write incoming data directly when no merge callback is provided" , async ( ) => {
501536 const initial = { a : 1 , b : 2 }
502537 await safeWriteJson ( currentTestFilePath , initial )
0 commit comments