UNPKG

snapshot-fs

Version:

Create a filesystem snapshot for use with memfs

62 lines 2.24 kB
import stableStringify from 'json-stable-stringify'; import { memfs } from 'memfs'; import { toBinarySnapshot, toJsonSnapshot, } from 'memfs/lib/snapshot/index.js'; import nodeFs from 'node:fs'; import { CBOR_KIND, readSnapshot } from './read.js'; /** * All files will be relative to this path in the output * {@link memfs DirectoryJSON} object */ export const DEFAULT_MEMFS_ROOT = '/'; /** * Creates a CBOR snapshot from the `from` path using the filesystem API `fs`. * * @param opts Options for creating the snapshot * @returns A promise that resolves to the snapshot */ export async function createCBORSnapshot({ fs, source: path = process.cwd(), } = {}) { const snapshot = await toBinarySnapshot({ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment fs: fs ? fs.promises : nodeFs.promises, path, }); return snapshot; } /** * Creates a CJSON snapshot from the `from` path using the filesystem API `fs`. * * @param opts Options for creating the snapshot * @returns A promise that resolves to the snapshot */ export async function createCJSONSnapshot({ fs, separator, source: path = process.cwd(), } = {}) { const snapshot = await toJsonSnapshot({ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment fs: fs ? fs.promises : nodeFs.promises, path, separator, }); return snapshot; } /** * Creates a CJSON snapshot from the `from` path using the filesystem API `fs`. * * @param opts Options for creating the snapshot * @returns A promise that resolves to the snapshot */ export async function createJSONSnapshot({ fs, separator, source: path = process.cwd(), } = {}) { const { vol } = memfs(); const tempSnapshot = await toBinarySnapshot({ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment fs: fs ? fs.promises : nodeFs.promises, path, separator, }); await readSnapshot(CBOR_KIND, tempSnapshot, { fs: vol, separator }); const snapshot = stableStringify(vol.toJSON()); /* c8 ignore next */ if (snapshot === undefined) { throw new Error('Snapshot is empty!'); } return snapshot; } //# sourceMappingURL=snapshot.js.map