New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@zenfs/core

Package Overview
Dependencies
Maintainers
1
Versions
182
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@zenfs/core - npm Package Compare versions

Comparing version

to
0.2.2

dist/backends/Overlay.d.ts

7

dist/backends/AsyncStore.d.ts
import { Cred } from '../cred.js';
import { PreloadFile, File, FileFlag } from '../file.js';
import { AsyncFileSystem } from '../filesystem.js';
import { AsyncFileSystem, type FileSystemMetadata } from '../filesystem.js';
import { type Ino } from '../inode.js';

@@ -76,3 +76,3 @@ import { Stats } from '../stats.js';

*/
store: Promise<AsyncStore>;
store: Promise<AsyncStore> | AsyncStore;
/**

@@ -92,2 +92,3 @@ * The size of the cache. If not provided, no cache will be used

ready(): Promise<this>;
get metadata(): FileSystemMetadata;
constructor({ store, cacheSize }: AsyncStoreFileSystemOptions);

@@ -98,3 +99,3 @@ /**

*/
protected _initialize(store: Promise<AsyncStore>): Promise<this>;
protected _initialize(store: Promise<AsyncStore> | AsyncStore): Promise<this>;
/**

@@ -101,0 +102,0 @@ * Delete all contents stored in the file system.

@@ -76,2 +76,8 @@ import { dirname, basename, join, resolve } from '../emulation/path.js';

}
get metadata() {
return {
...super.metadata,
name: this.store.name,
};
}
constructor({ store, cacheSize }) {

@@ -78,0 +84,0 @@ super();

@@ -12,4 +12,3 @@ import { FileSystem } from '../filesystem.js';

/**
* Whether or not the option is required (optional can be set to null or undefined).
* Defaults to false.
* Whether or not the option is required (optional can be set to null or undefined). Defaults to false.
*/

@@ -16,0 +15,0 @@ required?: boolean;

@@ -83,3 +83,6 @@ import { ApiError, ErrorCode } from '../ApiError.js';

}
return backend.create(options);
checkOptions(backend, options);
const fs = backend.create(options);
await fs.ready();
return fs;
}
import { AsyncMirror } from './AsyncMirror.js';
import { InMemory } from './InMemory.js';
import { Overlay } from './OverlayFS.js';
import { Overlay } from './Overlay.js';
import { Backend } from './backend.js';

@@ -5,0 +5,0 @@ export declare const backends: {

import { AsyncMirror } from './AsyncMirror.js';
import { InMemory } from './InMemory.js';
import { Overlay } from './OverlayFS.js';
import { Overlay } from './Overlay.js';
export const backends = {};

@@ -5,0 +5,0 @@ export default backends;

import type { Ino } from '../inode.js';
import { SyncStore, SimpleSyncStore, SyncRWTransaction, SyncStoreFileSystem } from './SyncStore.js';
import { type Backend } from './backend.js';
import type { Backend } from './backend.js';
import { SyncStore, SimpleSyncStore, SyncRWTransaction } from './SyncStore.js';
/**

@@ -17,3 +17,2 @@ * A simple in-memory store

}
export declare const InMemory: Backend;
/**

@@ -23,7 +22,2 @@ * A simple in-memory file system backed by an InMemoryStore.

*/
export declare class _InMemory extends SyncStoreFileSystem {
static isAvailable(): boolean;
static create: any;
static readonly options: {};
constructor();
}
export declare const InMemory: Backend;

@@ -1,4 +0,2 @@

var _a;
import { SimpleSyncRWTransaction, SyncStoreFileSystem } from './SyncStore.js';
import { createBackend } from './backend.js';
/**

@@ -32,2 +30,6 @@ * A simple in-memory store

}
/**
* A simple in-memory file system backed by an InMemoryStore.
* Files are not persisted across page loads.
*/
export const InMemory = {

@@ -48,16 +50,1 @@ name: 'InMemory',

};
/**
* A simple in-memory file system backed by an InMemoryStore.
* Files are not persisted across page loads.
*/
export class _InMemory extends SyncStoreFileSystem {
static isAvailable() {
return true;
}
constructor() {
super({ store: new InMemoryStore() });
}
}
_a = _InMemory;
_InMemory.create = createBackend.bind(_a);
_InMemory.options = {};

@@ -117,8 +117,4 @@ import { dirname, basename, join, resolve, sep } from '../emulation/path.js';

return {
...super.metadata,
name: this.store.name,
readonly: false,
supportsProperties: true,
synchronous: true,
freeSpace: 0,
totalSpace: 0,
};

@@ -125,0 +121,0 @@ }

@@ -7,3 +7,3 @@ export * from './callbacks.js';

export * from './dir.js';
export { initialize, getMount, getMounts, mount, umount, _toUnixTimestamp } from './shared.js';
export { initialize, mounts, mount, umount, _toUnixTimestamp } from './shared.js';
export { Stats, BigIntStats } from '../stats.js';

@@ -7,3 +7,3 @@ export * from './callbacks.js';

export * from './dir.js';
export { initialize, getMount, getMounts, mount, umount, _toUnixTimestamp } from './shared.js';
export { initialize, mounts, mount, umount, _toUnixTimestamp } from './shared.js';
export { Stats, BigIntStats } from '../stats.js';

@@ -8,8 +8,26 @@ /// <reference types="node" resolution-mode="require"/>

* Grabbed from NodeJS sources (lib/fs.js)
*
* @internal
*/
export declare function _toUnixTimestamp(time: Date | number): number;
/**
* Normalizes a mode
* @internal
*/
export declare function normalizeMode(mode: string | number | unknown, def?: number): number;
/**
* Normalizes a time
* @internal
*/
export declare function normalizeTime(time: string | number | Date): Date;
/**
* Normalizes a path
* @internal
*/
export declare function normalizePath(p: string): string;
export declare function normalizeOptions(options: any, defEnc: string | null, defFlag: string, defMode: number | null): {
/**
* Normalizes options
* @internal
*/
export declare function normalizeOptions(options: unknown, defEnc: string | null, defFlag: string, defMode: number | null): {
encoding: BufferEncoding;

@@ -19,2 +37,6 @@ flag: string;

};
/**
* Do nothing
* @internal
*/
export declare function nop(): void;

@@ -29,12 +51,8 @@ export declare let cred: Cred;

}
export declare const mounts: Map<string, FileSystem>;
/**
* Gets the file system mounted at `mountPoint`
* The map of mount points
* @internal
*/
export declare function getMount(mountPoint: string): FileSystem;
export declare const mounts: Map<string, FileSystem>;
/**
* Gets an object of mount points (keys) and filesystems (values)
*/
export declare function getMounts(): MountMapping;
/**
* Mounts the file system at the given mount point.

@@ -41,0 +59,0 @@ */

@@ -9,2 +9,4 @@ // Utilities and shared data

* Grabbed from NodeJS sources (lib/fs.js)
*
* @internal
*/

@@ -20,2 +22,6 @@ export function _toUnixTimestamp(time) {

}
/**
* Normalizes a mode
* @internal
*/
export function normalizeMode(mode, def) {

@@ -38,2 +44,6 @@ switch (typeof mode) {

}
/**
* Normalizes a time
* @internal
*/
export function normalizeTime(time) {

@@ -51,2 +61,6 @@ if (time instanceof Date) {

}
/**
* Normalizes a path
* @internal
*/
export function normalizePath(p) {

@@ -63,2 +77,6 @@ // Node doesn't allow null characters in paths.

}
/**
* Normalizes options
* @internal
*/
export function normalizeOptions(options, defEnc, defFlag, defMode) {

@@ -91,2 +109,6 @@ // typeof null === 'object' so special-case handing is needed.

}
/**
* Do nothing
* @internal
*/
export function nop() {

@@ -114,2 +136,6 @@ // do nothing

}
/**
* The map of mount points
* @internal
*/
export const mounts = new Map();

@@ -121,14 +147,2 @@ /*

/**
* Gets the file system mounted at `mountPoint`
*/
export function getMount(mountPoint) {
return mounts.get(mountPoint);
}
/**
* Gets an object of mount points (keys) and filesystems (values)
*/
export function getMounts() {
return Object.fromEntries(mounts.entries());
}
/**
* Mounts the file system at the given mount point.

@@ -135,0 +149,0 @@ */

@@ -174,2 +174,11 @@ import { ApiError } from './ApiError.js';

}
export declare abstract class ReadonlySyncFileSystem extends SyncFileSystem {
renameSync(oldPath: string, newPath: string, cred: Cred): void;
createFileSync(path: string, flag: FileFlag, mode: number, cred: Cred): File;
unlinkSync(path: string, cred: Cred): void;
rmdirSync(path: string, cred: Cred): void;
mkdirSync(path: string, mode: number, cred: Cred): void;
linkSync(srcpath: string, dstpath: string, cred: Cred): void;
syncSync(path: string, data: Uint8Array, stats: Readonly<Stats>): void;
}
export declare abstract class AsyncFileSystem extends FileSystem {

@@ -188,1 +197,10 @@ renameSync(oldPath: string, newPath: string, cred: Cred): void;

}
export declare abstract class ReadonlyAsyncFileSystem extends AsyncFileSystem {
rename(oldPath: string, newPath: string, cred: Cred): Promise<void>;
createFile(path: string, flag: FileFlag, mode: number, cred: Cred): Promise<File>;
unlink(path: string, cred: Cred): Promise<void>;
rmdir(path: string, cred: Cred): Promise<void>;
mkdir(path: string, mode: number, cred: Cred): Promise<void>;
link(srcpath: string, dstpath: string, cred: Cred): Promise<void>;
sync(path: string, data: Uint8Array, stats: Readonly<Stats>): Promise<void>;
}

@@ -97,2 +97,25 @@ /* eslint-disable @typescript-eslint/no-unused-vars */

}
export class ReadonlySyncFileSystem extends SyncFileSystem {
renameSync(oldPath, newPath, cred) {
throw new ApiError(ErrorCode.EROFS);
}
createFileSync(path, flag, mode, cred) {
throw new ApiError(ErrorCode.EROFS);
}
unlinkSync(path, cred) {
throw new ApiError(ErrorCode.EROFS);
}
rmdirSync(path, cred) {
throw new ApiError(ErrorCode.EROFS);
}
mkdirSync(path, mode, cred) {
throw new ApiError(ErrorCode.EROFS);
}
linkSync(srcpath, dstpath, cred) {
throw new ApiError(ErrorCode.EROFS);
}
syncSync(path, data, stats) {
throw new ApiError(ErrorCode.EROFS);
}
}
export class AsyncFileSystem extends FileSystem {

@@ -133,1 +156,24 @@ renameSync(oldPath, newPath, cred) {

}
export class ReadonlyAsyncFileSystem extends AsyncFileSystem {
async rename(oldPath, newPath, cred) {
throw new ApiError(ErrorCode.EROFS);
}
async createFile(path, flag, mode, cred) {
throw new ApiError(ErrorCode.EROFS);
}
async unlink(path, cred) {
throw new ApiError(ErrorCode.EROFS);
}
async rmdir(path, cred) {
throw new ApiError(ErrorCode.EROFS);
}
async mkdir(path, mode, cred) {
throw new ApiError(ErrorCode.EROFS);
}
async link(srcpath, dstpath, cred) {
throw new ApiError(ErrorCode.EROFS);
}
async sync(path, data, stats) {
throw new ApiError(ErrorCode.EROFS);
}
}

@@ -34,3 +34,2 @@ /**

export * from './cred.js';
export * from './FileIndex.js';
export * from './file.js';

@@ -37,0 +36,0 @@ export * from './filesystem.js';

@@ -15,3 +15,3 @@ /**

setCred(new Cred(uid, gid, uid, gid, uid, gid));
return fs.initialize(mounts);
fs.initialize(mounts);
}

@@ -43,3 +43,3 @@ /**

}
return initialize(config);
initialize(config);
}

@@ -51,3 +51,2 @@ export * from './backends/index.js';

export * from './cred.js';
export * from './FileIndex.js';
export * from './file.js';

@@ -54,0 +53,0 @@ export * from './filesystem.js';

/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/**
* Grab bag of utility functions used across the code.
*/
import { FileSystem } from './filesystem.js';

@@ -7,0 +4,0 @@ import { Cred } from './cred.js';

{
"name": "@zenfs/core",
"version": "0.2.1",
"version": "0.2.2",
"description": "A filesystem in your browser",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

@@ -10,10 +10,9 @@ # ZenFS

- `InMemory`: Stores files in-memory. It is a temporary file store that clears when the user navigates away.
- `OverlayFS`: Mount a read-only file system as read-write by overlaying a writable file system on top of it. Like Docker's overlayfs, it will only write changed files to the writable file system.
- `Overlay`: Mount a read-only file system as read-write by overlaying a writable file system on top of it. Like Docker's overlayfs, it will only write changed files to the writable file system.
- `AsyncMirror`: Use an asynchronous backend synchronously. Invaluable for Emscripten; let your Emscripten applications write to larger file stores with no additional effort!
- `AsyncMirror` loads the entire contents of the async file system into a synchronous backend during construction. It performs operations synchronous file system and then queues them to be mirrored onto the asynchronous backend.
- `FolderAdapter`: Wraps a file system, and scopes all interactions to a subfolder of that file system.
More backends can be defined by separate libraries, so long as they extend they implement `ZenFS.FileSystem`. Multiple backends can be active at once at different locations in the directory hierarchy.
ZenFS supports a number of other backends (as `@zenfs/fs-[name]`).
ZenFS supports a number of other backends (many are provided as seperate packages under `@zenfs`).

@@ -28,9 +27,2 @@ For more information, see the [API documentation for ZenFS](https://zen-fs.github.io/core).

## Building
- Make sure you have Node and NPM installed. You must have Node v18 or newer.
- Install dependencies with `npm install`
- Build using `npm run build`
- You can find the built code in `dist`.
## Usage

@@ -51,11 +43,9 @@

A `InMemory` backend is created by default. If you would like to use a different one, you must configure ZenFS. It is recommended to do so using the `configure` function. Here is an example using the `Storage` backend from `@zenfs/fs-dom`:
A `InMemory` backend is created by default. If you would like to use a different one, you must configure ZenFS. It is recommended to do so using the `configure` function. Here is an example using the `Storage` backend from `@zenfs/dom`:
```js
import { configure, fs, registerBackend } from '@zenfs/core';
import { StorageFileSystem } from '@zenfs/fs-dom';
registerBackend(StorageFileSystem);
import { configure, fs } from '@zenfs/core';
import { StorageStore } from '@zenfs/dom';
// you can also add a callback as the last parameter instead of using promises
await configure({ fs: 'Storage' });
await configure({ backend: StorageStore });

@@ -75,7 +65,5 @@ if (!fs.existsSync('/test.txt')) {

```js
import { configure, registerBackend } from '@zenfs/core';
import { IndexedDBFileSystem } from '@zenfs/fs-dom';
import { ZipFS } from '@zenfs/fs-zip';
import Buffer from 'buffer';
registerBackend(IndexedDBFileSystem, ZipFS);
import { configure } from '@zenfs/core';
import { IndexedDB } from '@zenfs/dom';
import { Zip } from '@zenfs/zip';

@@ -86,9 +74,7 @@ const zipData = await (await fetch('mydata.zip')).arrayBuffer();

'/mnt/zip': {
fs: 'ZipFS',
options: {
zipData: Buffer.from(zipData)
}
backend: Zip,
zipData: zipData,
},
'/tmp': 'InMemory',
'/home': 'IndexedDB',
'/home': IndexedDB,
};

@@ -102,7 +88,6 @@ ```

```js
import { configure, promises, registerBackend } from '@zenfs/core';
import { IndexedDBFileSystem } from '@zenfs/fs-dom';
registerBackend(IndexedDBFileSystem);
import { configure, promises } from '@zenfs/core';
import { IndexedDB } from '@zenfs/dom';
await configure({ '/': 'IndexedDB' });
await configure({ '/': IndexedDB });

@@ -115,18 +100,21 @@ const exists = await promises.exists('/myfile.txt');

ZenFS does _not_ provide a seperate method for importing promises in its built form. If you are using Typescript, you can import the promises API from source code (perhaps to reduce you bundle size). Doing so it not recommended as the files may be moved without notice.
ZenFS does _not_ provide a seperate public import for importing promises in its built form. If you are using ESM, you can import promises functions from `dist/emulation/promises`, though this may change at any time and is not recommended.
#### Using asynchronous backends synchronously
You may have noticed that attempting to use a synchronous method on an asynchronous backend (e.g. IndexedDB) results in a "not supplied" error (`ENOTSUP`). If you wish to use an asynchronous backend synchronously you need to wrap it in an `AsyncMirror`:
You may have noticed that attempting to use a synchronous function on an asynchronous backend (e.g. IndexedDB) results in a "not supplied" error (`ENOTSUP`). If you wish to use an asynchronous backend synchronously you need to wrap it in an `AsyncMirror`:
```js
import { configure, fs } from '@zenfs/core';
import { IndexedDBFileSystem } from '@zenfs/fs-dom';
registerBackend(IndexedDBFileSystem);
import { IndexedDB } from '@zenfs/dom';
await configure({
'/': { fs: 'AsyncMirror', options: { sync: { fs: 'InMemory' }, async: { fs: 'IndexedDB' } } }
'/': {
backend: 'AsyncMirror',
sync: 'InMemory',
async: IndexedDB,
},
});
fs.writeFileSync('/persistant.txt', 'My persistant data'); // This fails if you configure the FS as IndexedDB
fs.writeFileSync('/persistant.txt', 'My persistant data'); // This fails if you configure with only IndexedDB
```

@@ -138,3 +126,3 @@

If you would like to create backends without configure, you may do so by importing the backend's class and calling its `Create` method. You can import the backend directly or with `backends`:
If you would like to create backends without configure, you may do so by importing the backend and calling `createBackend` with it. You can import the backend directly or with `backends`:

@@ -144,15 +132,14 @@ ```js

console.log(backends.InMemory === InMemory) // they are the same
console.log(backends.InMemory === InMemory); // they are the same
const inMemoryFS = await InMemory.Create();
const internalInMemoryFS = await createBackend(InMemory);
```
> ⚠ Instances of backends follow the ***internal*** ZenFS API. You should never use a backend's method unless you are extending a backend.
> ⚠ Instances of backends follow the **_internal_** ZenFS API. You should never use a backend's methods unless you are extending a backend.
Coming soon:
```js
import { configure, InMemory } from '@zenfs/core';
const inMemoryFS = new InMemory();
await inMemoryFS.whenReady();
const internalInMemoryFS = new InMemory();
await internalInMemoryFS.ready();
```

@@ -167,5 +154,5 @@

const inMemoryFS = await InMemory.Create(); // create an FS instance
const internalInMemoryFS = await createBackend(InMemory); // create an FS instance
fs.mount('/tmp', inMemoryFS); // mount
fs.mount('/tmp', internalInMemoryFS); // mount

@@ -178,6 +165,4 @@ fs.umount('/tmp'); // unmount /tmp

```js
import { IndexedDBFileSystem } from '@zenfs/fs-dom';
import { ZipFS } from '@zenfs/fs-zip';
import Buffer from 'buffer';
registerBackend(IndexedDBFileSystem);
import { IndexedDB } from '@zenfs/dom';
import { Zip } from '@zenfs/zip';

@@ -192,4 +177,3 @@ await configure({

const res = await fetch('mydata.zip');
const zipData = Buffer.from(await res.arrayBuffer());
const zipFs = await ZipFS.Create({ zipData });
const zipFs = await createBackend(Zip, { zipData: await res.arrayBuffer() });
fs.mount('/mnt/zip', zipFs);

@@ -206,61 +190,9 @@

#### ESBuild
## Building
tsconfig.json
- Make sure you have Node and NPM installed. You must have Node v18 or newer.
- Install dependencies with `npm install`
- Build using `npm run build`
- You can find the built code in `dist`.
```json
{
...
"paths": {
"fs": ["node_modules/zenfs/dist/index.js"]
}
...
}
```
[Why tsconfig.json?](https://stackoverflow.com/a/71935037/17637456)
Webpack:
```js
module.exports = {
// ...
resolve: {
alias: {
fs: require.resolve('zenfs'),
},
},
// ...
};
```
Rollup:
```js
import alias from '@rollup/plugin-alias';
export default {
// ...
plugins: [
alias({
entries: [{ find: 'fs', replacement: 'zenfs' }],
}),
],
// ...
};
```
## Using with Emscripten
You can use any _synchronous_ ZenFS file systems with Emscripten.
```js
import { EmscriptenFSPlugin } from '@zenfs/fs-emscripten';
const BFS = new EmscriptenFSPlugin(); // Create a ZenFS Emscripten FS plugin.
FS.createFolder(FS.root, 'data', true, true); // Create the folder to turn into a mount point.
FS.mount(BFS, { root: '/' }, '/data'); // Mount BFS's root folder into /data.
```
If you want to use an asynchronous backend, you must wrap it in an `AsyncMirror`.
### Testing

@@ -267,0 +199,0 @@

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet