"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = void 0;
var _lruCache = _interopRequireDefault(require("next/dist/compiled/lru-cache"));
var _path = _interopRequireDefault(require("../../../shared/lib/isomorphic/path"));
class FileSystemCache {
    constructor(ctx){
        this.fs = ctx.fs;
        this.flushToDisk = ctx.flushToDisk;
        this.serverDistDir = ctx.serverDistDir;
        this.appDir = !!ctx._appDir;
        if (ctx.maxMemoryCacheSize && !memoryCache) {
            memoryCache = new _lruCache.default({
                max: ctx.maxMemoryCacheSize,
                length ({ value  }) {
                    var ref;
                    if (!value) {
                        return 25;
                    } else if (value.kind === "REDIRECT") {
                        return JSON.stringify(value.props).length;
                    } else if (value.kind === "IMAGE") {
                        throw new Error("invariant image should not be incremental-cache");
                    } else if (value.kind === "FETCH") {
                        return JSON.stringify(value.data || "").length;
                    } else if (value.kind === "ROUTE") {
                        return value.body.length;
                    }
                    // rough estimate of size of cache value
                    return value.html.length + (((ref = JSON.stringify(value.pageData)) == null ? void 0 : ref.length) || 0);
                }
            });
        }
    }
    async get(key, fetchCache) {
        let data = memoryCache == null ? void 0 : memoryCache.get(key);
        // let's check the disk for seed data
        if (!data && process.env.NEXT_RUNTIME !== "edge") {
            try {
                const { filePath  } = await this.getFsPath({
                    pathname: `${key}.body`,
                    appDir: true
                });
                const fileData = await this.fs.readFile(filePath);
                const { mtime  } = await this.fs.stat(filePath);
                const meta = JSON.parse((await this.fs.readFile(filePath.replace(/\.body$/, ".meta"))).toString("utf8"));
                const cacheEntry = {
                    lastModified: mtime.getTime(),
                    value: {
                        kind: "ROUTE",
                        body: fileData,
                        headers: meta.headers,
                        status: meta.status
                    }
                };
                return cacheEntry;
            } catch (_) {
            // no .meta data for the related key
            }
            try {
                const { filePath , isAppPath  } = await this.getFsPath({
                    pathname: fetchCache ? key : `${key}.html`,
                    fetchCache
                });
                const fileData = await this.fs.readFile(filePath);
                const { mtime  } = await this.fs.stat(filePath);
                if (fetchCache) {
                    const lastModified = mtime.getTime();
                    data = {
                        lastModified,
                        value: JSON.parse(fileData.toString("utf8"))
                    };
                } else {
                    const pageData = isAppPath ? (await this.fs.readFile((await this.getFsPath({
                        pathname: `${key}.rsc`,
                        appDir: true
                    })).filePath)).toString("utf8") : JSON.parse((await this.fs.readFile((await this.getFsPath({
                        pathname: `${key}.json`,
                        appDir: false
                    })).filePath)).toString("utf8"));
                    data = {
                        lastModified: mtime.getTime(),
                        value: {
                            kind: "PAGE",
                            html: fileData.toString("utf8"),
                            pageData
                        }
                    };
                }
                if (data) {
                    memoryCache == null ? void 0 : memoryCache.set(key, data);
                }
            } catch (_1) {
            // unable to get data from disk
            }
        }
        return data || null;
    }
    async set(key, data) {
        memoryCache == null ? void 0 : memoryCache.set(key, {
            value: data,
            lastModified: Date.now()
        });
        if (!this.flushToDisk) return;
        if ((data == null ? void 0 : data.kind) === "ROUTE") {
            const { filePath  } = await this.getFsPath({
                pathname: `${key}.body`,
                appDir: true
            });
            await this.fs.mkdir(_path.default.dirname(filePath));
            await this.fs.writeFile(filePath, data.body);
            await this.fs.writeFile(filePath.replace(/\.body$/, ".meta"), JSON.stringify({
                headers: data.headers,
                status: data.status
            }));
            return;
        }
        if ((data == null ? void 0 : data.kind) === "PAGE") {
            const isAppPath = typeof data.pageData === "string";
            const { filePath: htmlPath  } = await this.getFsPath({
                pathname: `${key}.html`,
                appDir: isAppPath
            });
            await this.fs.mkdir(_path.default.dirname(htmlPath));
            await this.fs.writeFile(htmlPath, data.html);
            await this.fs.writeFile((await this.getFsPath({
                pathname: `${key}.${isAppPath ? "rsc" : "json"}`,
                appDir: isAppPath
            })).filePath, isAppPath ? data.pageData : JSON.stringify(data.pageData));
        } else if ((data == null ? void 0 : data.kind) === "FETCH") {
            const { filePath  } = await this.getFsPath({
                pathname: key,
                fetchCache: true
            });
            await this.fs.mkdir(_path.default.dirname(filePath));
            await this.fs.writeFile(filePath, JSON.stringify(data));
        }
    }
    async getFsPath({ pathname , appDir , fetchCache  }) {
        if (fetchCache) {
            // we store in .next/cache/fetch-cache so it can be persisted
            // across deploys
            return {
                filePath: _path.default.join(this.serverDistDir, "..", "cache", "fetch-cache", pathname),
                isAppPath: false
            };
        }
        let isAppPath = false;
        let filePath = _path.default.join(this.serverDistDir, "pages", pathname);
        if (!this.appDir || appDir === false) return {
            filePath,
            isAppPath
        };
        try {
            await this.fs.readFile(filePath);
            return {
                filePath,
                isAppPath
            };
        } catch (err) {
            return {
                filePath: _path.default.join(this.serverDistDir, "app", pathname),
                isAppPath: true
            };
        }
    }
}
exports.default = FileSystemCache;
function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
let memoryCache;

//# sourceMappingURL=file-system-cache.js.map