UNPKG

@neodx/vfs

Version:

Simple virtual file system - working dir context, lazy changes, different modes, integrations and moreover

54 lines (50 loc) 2.15 kB
import { parseJson, serializeJson } from '@neodx/fs'; import { mapKeysToObject } from '@neodx/std'; import { c as createVfsPlugin } from '../_internal/create-vfs-plugin-BzqnUd8c.mjs'; const createFileApi = (vfs, path) => ({ path: vfs.resolve(path), ...mapKeysToObject(inheritedApis, key => vfs[key].bind(vfs, path)) }); const inheritedApis = ['tryRead', 'exists', 'delete', 'rename', 'write', 'read']; function json() { return createVfsPlugin('json', vfs => { vfs.jsonFile = path => createJsonFileApi(vfs, path); vfs.readJson = (path, options) => readVfsJson(vfs, path, options); vfs.writeJson = (path, json, options) => writeVfsJson(vfs, path, json, options); vfs.updateJson = (path, updater, options) => updateVfsJson(vfs, path, updater, options); return vfs; }); } function createJsonFileApi(vfs, path) { return { ...createFileApi(vfs, path), read: options => readVfsJson(vfs, path, options), tryRead: options => readVfsJson(vfs, path, options).catch(() => null), write: (json, options) => writeVfsJson(vfs, path, json, options), update: (updater, options) => updateVfsJson(vfs, path, updater, options), experimental_toResource: async (defaultValue, options) => { const data = (await readVfsJson(vfs, path, options)) ?? defaultValue; return { data, [Symbol.asyncDispose]: async () => await writeVfsJson(vfs, path, data, options) }; } }; } async function readVfsJson(vfs, path, options) { try { return parseJson(await vfs.read(path, 'utf-8'), options); } catch (error) { throw new Error(`Cannot parse ${path}:\n${error.message}`); } } async function writeVfsJson(vfs, path, json, options) { return await vfs.write(path, serializeJson(json, options)); } async function updateVfsJson(vfs, path, updater, options) { // TODO Implement support for empty, damaged, or nonexistent files const current = await readVfsJson(vfs, path, options); return await writeVfsJson(vfs, path, (await updater(current)) ?? current, options); } export { createJsonFileApi, json, readVfsJson, updateVfsJson, writeVfsJson }; //# sourceMappingURL=json.mjs.map