@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
import path from "node:path" ;
3
3
4
4
import { loadConfig } from "config/util.js" ;
5
+ import { safeParseJsonFile } from "utils/safe-json-parse.js" ;
5
6
import logger from "../logger.js" ;
6
7
import type { TagCacheMetaFile } from "../types/cache.js" ;
7
8
import { isBinaryContentType } from "../utils/binary.js" ;
@@ -159,15 +160,20 @@ export function createCacheAssets(options: buildHelper.BuildOptions) {
159
160
// Generate cache file
160
161
Object . entries ( cacheFilesPath ) . forEach ( ( [ cacheFilePath , files ] ) => {
161
162
const cacheFileMeta = files . meta
162
- ? JSON . parse ( fs . readFileSync ( files . meta , "utf8" ) )
163
+ ? safeParseJsonFile ( fs . readFileSync ( files . meta , "utf8" ) , cacheFilePath )
163
164
: undefined ;
165
+ const cacheJson = files . json
166
+ ? safeParseJsonFile ( fs . readFileSync ( files . json , "utf8" ) , cacheFilePath )
167
+ : undefined ;
168
+ if ( ( files . meta && ! cacheFileMeta ) || ( files . json && ! cacheJson ) ) {
169
+ logger . warn ( `Skipping invalid cache file: ${ cacheFilePath } ` ) ;
170
+ return ;
171
+ }
164
172
const cacheFileContent = {
165
173
type : files . body ? "route" : files . json ? "page" : "app" ,
166
174
meta : cacheFileMeta ,
167
175
html : files . html ? fs . readFileSync ( files . html , "utf8" ) : undefined ,
168
- json : files . json
169
- ? JSON . parse ( fs . readFileSync ( files . json , "utf8" ) )
170
- : undefined ,
176
+ json : cacheJson ,
171
177
rsc : files . rsc ? fs . readFileSync ( files . rsc , "utf8" ) : undefined ,
172
178
body : files . body
173
179
? fs
@@ -203,7 +209,7 @@ export function createCacheAssets(options: buildHelper.BuildOptions) {
203
209
( ) => true ,
204
210
( { absolutePath, relativePath } ) => {
205
211
const fileContent = fs . readFileSync ( absolutePath , "utf8" ) ;
206
- const fileData = JSON . parse ( fileContent ) ;
212
+ const fileData = safeParseJsonFile ( fileContent , absolutePath ) ;
207
213
fileData ?. tags ?. forEach ( ( tag : string ) => {
208
214
metaFiles . push ( {
209
215
tag : { S : path . posix . join ( buildId , tag ) } ,
@@ -227,8 +233,8 @@ export function createCacheAssets(options: buildHelper.BuildOptions) {
227
233
absolutePath . endsWith ( ".meta" ) && ! isFileSkipped ( relativePath ) ,
228
234
( { absolutePath, relativePath } ) => {
229
235
const fileContent = fs . readFileSync ( absolutePath , "utf8" ) ;
230
- const fileData = JSON . parse ( fileContent ) ;
231
- if ( fileData . headers ?. [ "x-next-cache-tags" ] ) {
236
+ const fileData = safeParseJsonFile ( fileContent , absolutePath ) ;
237
+ if ( fileData ? .headers ?. [ "x-next-cache-tags" ] ) {
232
238
fileData . headers [ "x-next-cache-tags" ]
233
239
. split ( "," )
234
240
. forEach ( ( tag : string ) => {
0 commit comments