Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add opfs driver #319

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/content/6.drivers/origin-private-file-system.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
navigation.title: Origin Private File System
---

# Origin Private File System

Maps data to the [origin private file system (OPFS)](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system) using directory structure for nested keys.

This driver implements meta for each key including `mtime` (last modified time), `type` (mime type) and `size` (file size) of the underlying [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) object.

The origin private file system cannot be watched.

```js
import { createStorage } from "unstorage";
import opfsDriver from "unstorage/drivers/opfs";

const storage = createStorage({
driver: opfsDriver({ base: "tmp" }),
});
```

**Options:**

- `base`: Base directory to isolate operations on this directory
- `ignore`: Ignore patterns for key listing
- `fs`: An alternative file system handle using the [`FileSystemDirectoryHandle`](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryHandle) interface (e.g. the user's native file system using `window.showDirectoryPicker()`)
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"eslint": "^8.51.0",
"eslint-config-unjs": "^0.2.1",
"fake-indexeddb": "^4.0.2",
"file-system-access": "^1.0.4",
"idb-keyval": "^6.2.1",
"ioredis-mock": "^8.9.0",
"jiti": "^1.20.0",
Expand Down
36 changes: 36 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

104 changes: 104 additions & 0 deletions src/drivers/opfs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { defineDriver, createError } from "./utils";
import {
DRIVER_NAME,
exists,
getFileObject,
joinPaths,
normalizePath,
readFile,
readdirRecursive,
remove,
removeChildren,
unlink,
writeFile,
} from "./utils/opfs-utils";

export interface OPFSStorageOptions {
/**
* The filesystem root to use
* Defaults to the OPFS root at `navigator.storage.getDirectory()`
*/
fs?: FileSystemDirectoryHandle | Promise<FileSystemDirectoryHandle>;

/**
* The base path to use for all operations
* Defaults to the root directory (empty string)
*/
base?: string;

/**
* A callback to ignore certain files in getKeys()
*/
ignore?: (path: string) => boolean;
}

let defaultFsHandle: Promise<FileSystemDirectoryHandle> | undefined;
async function getDefaultFs() {
// Use memoized OPFS handle if available
if (typeof defaultFsHandle !== "undefined") return defaultFsHandle;

// If no file system is provided, OPFS needs to be available
if (typeof globalThis?.navigator?.storage !== "object") {
throw createError(
DRIVER_NAME,
"No filesystem provided and navigator.storage is not available"
);
}

defaultFsHandle = navigator.storage.getDirectory();
return defaultFsHandle;
}

export default defineDriver<OPFSStorageOptions | undefined>(
(opts: OPFSStorageOptions = {}) => {
opts.base = normalizePath(opts.base ?? "");
const getFs = () => opts.fs ?? getDefaultFs();
const resolve = (path: string) => joinPaths(opts.base!, path);

return {
name: DRIVER_NAME,
options: opts,
async hasItem(key) {
return exists(await getFs(), resolve(key), "file");
},
async getItem(key) {
if (!(await exists(await getFs(), resolve(key), "file"))) return null;
return readFile(await getFs(), resolve(key), "utf8");
},
async getItemRaw(key) {
if (!(await exists(await getFs(), resolve(key), "file"))) return null;
return readFile(await getFs(), resolve(key));
},
async getMeta(key) {
const file = await getFileObject(await getFs(), resolve(key));
if (!file) return null;

return {
mtime: new Date(file.lastModified),
size: file.size,
type: file.type,
};
},
async setItem(key, value) {
return writeFile(await getFs(), resolve(key), value);
},
async setItemRaw(key, value) {
return writeFile(await getFs(), resolve(key), value);
},
async removeItem(key) {
return unlink(await getFs(), resolve(key));
},
async getKeys() {
return readdirRecursive(await getFs(), resolve(""), opts.ignore);
},
async clear() {
if (opts.base!.length === 0) {
// We cannot delete an OPFS root, so we just empty it
await removeChildren(await getFs(), resolve(""));
} else {
await remove(await getFs(), resolve(""));
}
},
};
}
);
Loading