opfs-mock 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -1,21 +1,21 @@
1
- The MIT License (MIT)
2
-
3
- Copyright © 2024 Jure Rotar
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE
1
+ The MIT License (MIT)
2
+
3
+ Copyright © 2024 Jure Rotar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
package/README.md CHANGED
@@ -1,159 +1,159 @@
1
- # opfs-mock
2
-
3
- This is a pure JS in-memory implementation of the [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system). Its main utility is for testing OPFS-dependent code in Node.js.
4
-
5
- ## Installation
6
-
7
- ```shell
8
- npm install -save-dev opfs-mock
9
- ```
10
-
11
- ## Usage
12
-
13
- It replicates the behavior of origin private file system, except data is not persisted to disk.
14
-
15
- The easiest way to use it is to import `opfs-mock`, which will polyfill OPFS API to global scope.
16
-
17
- ```ts
18
- import "opfs-mock";
19
- ```
20
-
21
- Alternatively, you can explicitly import `storageFactory`:
22
-
23
- ```ts
24
- import { storageFactory } from "opfs-mock";
25
-
26
- test('Your test', async () => {
27
- const storage = await storageFactory();
28
- const root = await storage.getDirectory();
29
- const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
30
- // rest of your test
31
- });
32
- ```
33
-
34
- `storageFactory` has predefined `quota` and `estimate` values set to `0`, which is fine if you're not using these properties.
35
- In case you need specific values, you can pass both as arguments to `storageFactory`.
36
-
37
- ```ts
38
- import { storageFactory } from "opfs-mock";
39
-
40
- test('Your test', async () => {
41
- const storage = await storageFactory({ quota: 1_000_000, estimate: 1_000 });
42
- const root = await storage.getDirectory();
43
- const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
44
- // rest of your test
45
- });
46
- ```
47
-
48
- ### Vitest
49
-
50
- To use `opfs-mock` in a single Vitest test suite, require `opfs-mock` at the beginning of the test file, as described above.
51
-
52
- To use it on all Vitest tests without having to include it in each file, add the auto setup script to the `test.setupFiles` in your Vite config:
53
-
54
- ```ts
55
- // vite.config.ts
56
-
57
- import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
58
- import { defineConfig as defineVitestConfig } from 'vitest/config';
59
-
60
- const viteConfig = defineViteConfig({
61
- ...
62
- });
63
-
64
- const vitestConfig = defineVitestConfig({
65
- test: {
66
- setupFiles: ['opfs-mock'],
67
- },
68
- });
69
-
70
- export default mergeConfig(viteConfig, vitestConfig);
71
- ```
72
-
73
- Alternatively you can create a new setup file which then imports this module.
74
-
75
- ```ts
76
- // vitest-setup.ts
77
-
78
- import "opfs-mock";
79
- ```
80
-
81
- Add that file to your `test.setupFiles` array:
82
-
83
- ```ts
84
- // vite.config.ts
85
-
86
- import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
87
- import { defineConfig as defineVitestConfig } from 'vitest/config';
88
-
89
- const viteConfig = defineViteConfig({
90
- ...
91
- });
92
-
93
- const vitestConfig = defineVitestConfig({
94
- test: {
95
- setupFiles: ['vitest-setup.ts'],
96
- },
97
- });
98
-
99
- export default mergeConfig(viteConfig, vitestConfig);
100
- ```
101
-
102
-
103
- ### Jest
104
-
105
- To use `opfs-mock` in a single Jest test suite, require `opfs-mock` at the beginning of the test file, as described above.
106
-
107
- To use it on all Jest tests without having to include it in each file, add the auto setup script to the `setupFiles` in your Jest config:
108
-
109
- ```ts
110
- // jest.config.js
111
-
112
- {
113
- ...
114
- "setupFiles": [
115
- "opfs-mock"
116
- ]
117
- }
118
- ```
119
-
120
- Alternatively you can create a new setup file which then imports this module.
121
-
122
- ```ts
123
- // jest-setup.ts
124
-
125
- import "opfs-mock";
126
- ```
127
-
128
- Add that file to your `setupFiles` array:
129
-
130
- ```ts
131
- // jest.config.js
132
-
133
- {
134
- ...
135
- "setupFiles": [
136
- "jest-setup"
137
- ]
138
- }
139
- ```
140
-
141
- ## Wiping/resetting the OPFS mock for a fresh state
142
-
143
- If you are keeping your tests completely isolated you might want to "reset" the state of the mocked OPFS. You can do this by using `resetMockOPFS` function, which creates a completely new instance of the mock.
144
-
145
- ```ts
146
- import { resetMockOPFS } from 'opfs-mock';
147
-
148
- beforeEach(() => {
149
- resetMockOPFS();
150
- });
151
-
152
- test('First isolated test', async () => {
153
- // rest of your test
154
- });
155
-
156
- test('Second isolated test', async () => {
157
- // rest of your test
158
- });
159
- ```
1
+ # opfs-mock
2
+
3
+ This is a pure JS in-memory implementation of the [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system). Its main utility is for testing OPFS-dependent code in Node.js.
4
+
5
+ ## Installation
6
+
7
+ ```shell
8
+ npm install -save-dev opfs-mock
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ It replicates the behavior of origin private file system, except data is not persisted to disk.
14
+
15
+ The easiest way to use it is to import `opfs-mock`, which will polyfill OPFS API to global scope.
16
+
17
+ ```ts
18
+ import "opfs-mock";
19
+ ```
20
+
21
+ Alternatively, you can explicitly import `storageFactory`:
22
+
23
+ ```ts
24
+ import { storageFactory } from "opfs-mock";
25
+
26
+ test('Your test', async () => {
27
+ const storage = await storageFactory();
28
+ const root = await storage.getDirectory();
29
+ const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
30
+ // rest of your test
31
+ });
32
+ ```
33
+
34
+ `storageFactory` has predefined `quota` and `estimate` values set to `0`, which is fine if you're not using these properties.
35
+ In case you need specific values, you can pass both as arguments to `storageFactory`.
36
+
37
+ ```ts
38
+ import { storageFactory } from "opfs-mock";
39
+
40
+ test('Your test', async () => {
41
+ const storage = await storageFactory({ quota: 1_000_000, estimate: 1_000 });
42
+ const root = await storage.getDirectory();
43
+ const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
44
+ // rest of your test
45
+ });
46
+ ```
47
+
48
+ ### Vitest
49
+
50
+ To use `opfs-mock` in a single Vitest test suite, require `opfs-mock` at the beginning of the test file, as described above.
51
+
52
+ To use it on all Vitest tests without having to include it in each file, add the auto setup script to the `test.setupFiles` in your Vite config:
53
+
54
+ ```ts
55
+ // vite.config.ts
56
+
57
+ import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
58
+ import { defineConfig as defineVitestConfig } from 'vitest/config';
59
+
60
+ const viteConfig = defineViteConfig({
61
+ ...
62
+ });
63
+
64
+ const vitestConfig = defineVitestConfig({
65
+ test: {
66
+ setupFiles: ['opfs-mock'],
67
+ },
68
+ });
69
+
70
+ export default mergeConfig(viteConfig, vitestConfig);
71
+ ```
72
+
73
+ Alternatively you can create a new setup file which then imports this module.
74
+
75
+ ```ts
76
+ // vitest-setup.ts
77
+
78
+ import "opfs-mock";
79
+ ```
80
+
81
+ Add that file to your `test.setupFiles` array:
82
+
83
+ ```ts
84
+ // vite.config.ts
85
+
86
+ import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
87
+ import { defineConfig as defineVitestConfig } from 'vitest/config';
88
+
89
+ const viteConfig = defineViteConfig({
90
+ ...
91
+ });
92
+
93
+ const vitestConfig = defineVitestConfig({
94
+ test: {
95
+ setupFiles: ['vitest-setup.ts'],
96
+ },
97
+ });
98
+
99
+ export default mergeConfig(viteConfig, vitestConfig);
100
+ ```
101
+
102
+
103
+ ### Jest
104
+
105
+ To use `opfs-mock` in a single Jest test suite, require `opfs-mock` at the beginning of the test file, as described above.
106
+
107
+ To use it on all Jest tests without having to include it in each file, add the auto setup script to the `setupFiles` in your Jest config:
108
+
109
+ ```ts
110
+ // jest.config.js
111
+
112
+ {
113
+ ...
114
+ "setupFiles": [
115
+ "opfs-mock"
116
+ ]
117
+ }
118
+ ```
119
+
120
+ Alternatively you can create a new setup file which then imports this module.
121
+
122
+ ```ts
123
+ // jest-setup.ts
124
+
125
+ import "opfs-mock";
126
+ ```
127
+
128
+ Add that file to your `setupFiles` array:
129
+
130
+ ```ts
131
+ // jest.config.js
132
+
133
+ {
134
+ ...
135
+ "setupFiles": [
136
+ "jest-setup"
137
+ ]
138
+ }
139
+ ```
140
+
141
+ ## Wiping/resetting the OPFS mock for a fresh state
142
+
143
+ If you are keeping your tests completely isolated you might want to "reset" the state of the mocked OPFS. You can do this by using `resetMockOPFS` function, which creates a completely new instance of the mock.
144
+
145
+ ```ts
146
+ import { resetMockOPFS } from 'opfs-mock';
147
+
148
+ beforeEach(() => {
149
+ resetMockOPFS();
150
+ });
151
+
152
+ test('First isolated test', async () => {
153
+ // rest of your test
154
+ });
155
+
156
+ test('Second isolated test', async () => {
157
+ // rest of your test
158
+ });
159
+ ```
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
- export declare const storageFactory: ({ usage, quota }?: StorageEstimate) => StorageManager;
2
- export declare const mockOPFS: () => void;
3
- export declare const resetMockOPFS: () => void;
1
+ declare const storageFactory: ({ usage, quota }?: StorageEstimate) => StorageManager;
2
+ declare const mockOPFS: () => void;
3
+ declare const resetMockOPFS: () => void;
4
+
5
+ export { mockOPFS, resetMockOPFS, storageFactory };
package/dist/index.js CHANGED
@@ -1,128 +1,262 @@
1
- const g = (o, n) => ({
2
- kind: "file",
3
- name: o,
4
- isSameEntry: async (t) => t.name === o && t.kind === "file",
5
- getFile: async () => new File([n.content], o, {
6
- type: "application/json"
7
- }),
8
- // @ts-ignore TODO: Implement options, add missing properties
9
- createWritable: async (t) => new WritableStream({
10
- write: (e) => {
11
- const r = new TextDecoder().decode(e);
12
- n.content += r;
13
- },
14
- close: () => {
15
- },
16
- abort: (e) => {
17
- }
18
- }).getWriter(),
19
- createSyncAccessHandle: async () => ({
20
- getSize: () => n.content.length,
21
- read: (t, { at: s = 0 } = {}) => {
22
- const e = new TextEncoder().encode(n.content), r = Math.min(t.length, e.length - s);
23
- return t.set(e.subarray(s, s + r)), r;
24
- },
25
- write: (t, { at: s = 0 } = {}) => {
26
- const e = new TextDecoder().decode(t), r = n.content.length;
27
- return s < r ? n.content = n.content.slice(0, s) + e + n.content.slice(s + e.length) : n.content += e, t.byteLength;
28
- },
29
- // Flush is a no-op in memory
30
- flush: async () => {
1
+ // src/opfs.ts
2
+ var fileSystemFileHandleFactory = (name, fileData) => {
3
+ return {
4
+ kind: "file",
5
+ name,
6
+ isSameEntry: async (other) => {
7
+ return other.name === name && other.kind === "file";
31
8
  },
32
- // Close is a no-op in memory
33
- close: async () => {
9
+ getFile: async () => new File([fileData.content], name),
10
+ createWritable: async (_options) => {
11
+ let newContent = "";
12
+ let cursorPosition = 0;
13
+ let aborted = false;
14
+ let closed = false;
15
+ const locked = false;
16
+ const writableStream = new WritableStream({
17
+ write: async (chunk) => {
18
+ if (aborted) {
19
+ throw new DOMException("Write operation aborted", "AbortError");
20
+ }
21
+ if (closed) {
22
+ throw new TypeError("Cannot write to a CLOSED writable stream");
23
+ }
24
+ if (chunk === void 0) {
25
+ throw new TypeError("Cannot write undefined data to the stream");
26
+ }
27
+ let chunkText;
28
+ if (typeof chunk === "string") {
29
+ chunkText = chunk;
30
+ } else if (chunk instanceof Blob) {
31
+ chunkText = await chunk.text();
32
+ } else if (ArrayBuffer.isView(chunk)) {
33
+ chunkText = new TextDecoder().decode(new Uint8Array(chunk.buffer));
34
+ } else if (typeof chunk === "object" && "data" in chunk) {
35
+ if (chunk.position !== void 0 && (typeof chunk.position !== "number" || chunk.position < 0)) {
36
+ throw new TypeError("Invalid position value in write parameters");
37
+ }
38
+ if (chunk.size !== void 0 && (typeof chunk.size !== "number" || chunk.size < 0)) {
39
+ throw new TypeError("Invalid size value in write parameters");
40
+ }
41
+ if (chunk.position !== void 0 && chunk.position !== null) {
42
+ cursorPosition = chunk.position;
43
+ }
44
+ if (chunk.data) {
45
+ if (typeof chunk.data === "string") {
46
+ chunkText = chunk.data;
47
+ } else if (chunk.data instanceof Blob) {
48
+ chunkText = await chunk.data.text();
49
+ } else {
50
+ chunkText = new TextDecoder().decode(new Uint8Array(chunk.data instanceof ArrayBuffer ? chunk.data : chunk.data.buffer));
51
+ }
52
+ } else {
53
+ chunkText = "";
54
+ }
55
+ } else {
56
+ throw new TypeError("Invalid data type written to the file. Data must be of type FileSystemWriteChunkType.");
57
+ }
58
+ newContent = newContent.slice(0, cursorPosition) + chunkText + newContent.slice(cursorPosition + chunkText.length);
59
+ cursorPosition += chunkText.length;
60
+ },
61
+ close: async () => {
62
+ if (aborted) {
63
+ throw new DOMException("Stream has been aborted", "AbortError");
64
+ }
65
+ closed = true;
66
+ fileData.content = newContent;
67
+ },
68
+ abort: (reason) => {
69
+ if (aborted) {
70
+ return Promise.reject(new TypeError("Cannot abort an already aborted writable stream"));
71
+ }
72
+ if (locked) {
73
+ return Promise.reject(new TypeError("Cannot abort a locked writable stream"));
74
+ }
75
+ aborted = true;
76
+ return Promise.resolve(reason);
77
+ }
78
+ });
79
+ const writer = writableStream.getWriter();
80
+ return Object.assign(writer, {
81
+ locked: false,
82
+ truncate: async (size) => {
83
+ if (size < 0) {
84
+ throw new DOMException("Invalid truncate size", "IndexSizeError");
85
+ }
86
+ if (size < newContent.length) {
87
+ newContent = newContent.slice(0, size);
88
+ } else {
89
+ newContent = newContent.padEnd(size, "\0");
90
+ }
91
+ cursorPosition = Math.min(cursorPosition, size);
92
+ },
93
+ getWriter: () => writer,
94
+ seek: async (position) => {
95
+ if (position < 0 || position > newContent.length) {
96
+ throw new DOMException("Invalid seek position", "IndexSizeError");
97
+ }
98
+ cursorPosition = position;
99
+ }
100
+ });
34
101
  },
35
- truncate: async (t) => {
36
- n.content = n.content.slice(0, t);
37
- }
38
- })
39
- }), y = (o) => {
40
- const n = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map(), s = () => new Map([...n, ...t]);
102
+ createSyncAccessHandle: async () => ({
103
+ getSize: () => fileData.content.length,
104
+ read: (buffer, { at = 0 } = {}) => {
105
+ const text = new TextEncoder().encode(fileData.content);
106
+ const bytesRead = Math.min(buffer.length, text.length - at);
107
+ buffer.set(text.subarray(at, at + bytesRead));
108
+ return bytesRead;
109
+ },
110
+ write: (data, { at = 0 } = {}) => {
111
+ const newContent = new TextDecoder().decode(data);
112
+ const originalLength = fileData.content.length;
113
+ if (at < originalLength) {
114
+ fileData.content = fileData.content.slice(0, at) + newContent + fileData.content.slice(at + newContent.length);
115
+ } else {
116
+ fileData.content += newContent;
117
+ }
118
+ return data.byteLength;
119
+ },
120
+ // Flush is a no-op in memory
121
+ flush: async () => {
122
+ },
123
+ // Close is a no-op in memory
124
+ close: async () => {
125
+ },
126
+ truncate: async (size) => {
127
+ fileData.content = fileData.content.slice(0, size);
128
+ }
129
+ })
130
+ };
131
+ };
132
+ var fileSystemDirectoryHandleFactory = (name) => {
133
+ const files = /* @__PURE__ */ new Map();
134
+ const directories = /* @__PURE__ */ new Map();
135
+ const getJoinedMaps = () => {
136
+ return new Map([...files, ...directories]);
137
+ };
41
138
  return {
42
139
  kind: "directory",
43
- name: o,
44
- isSameEntry: async (e) => e.name === o && e.kind === "directory",
45
- getFileHandle: async (e, r) => {
46
- !n.has(e) && (r != null && r.create) && n.set(e, g(e, { content: "" }));
47
- const c = n.get(e);
48
- if (!c)
49
- throw new Error(`File not found: ${e}`);
50
- return c;
140
+ name,
141
+ isSameEntry: async (other) => {
142
+ return other.name === name && other.kind === "directory";
143
+ },
144
+ getFileHandle: async (fileName, options) => {
145
+ if (!files.has(fileName) && options?.create) {
146
+ files.set(fileName, fileSystemFileHandleFactory(fileName, { content: "" }));
147
+ }
148
+ const fileHandle = files.get(fileName);
149
+ if (!fileHandle) {
150
+ throw new Error(`File not found: ${fileName}`);
151
+ }
152
+ return fileHandle;
51
153
  },
52
- getDirectoryHandle: async (e, r) => {
53
- !t.has(e) && (r != null && r.create) && t.set(e, y(e));
54
- const c = t.get(e);
55
- if (!c)
56
- throw new Error(`Directory not found: ${e}`);
57
- return c;
154
+ getDirectoryHandle: async (dirName, options) => {
155
+ if (!directories.has(dirName) && options?.create) {
156
+ directories.set(dirName, fileSystemDirectoryHandleFactory(dirName));
157
+ }
158
+ const directoryHandle = directories.get(dirName);
159
+ if (!directoryHandle) {
160
+ throw new Error(`Directory not found: ${dirName}`);
161
+ }
162
+ return directoryHandle;
58
163
  },
59
- removeEntry: async (e) => {
60
- if (n.has(e))
61
- n.delete(e);
62
- else if (t.has(e))
63
- t.delete(e);
64
- else
65
- throw new Error(`Entry not found: ${e}`);
164
+ removeEntry: async (entryName) => {
165
+ if (files.has(entryName)) {
166
+ files.delete(entryName);
167
+ } else if (directories.has(entryName)) {
168
+ directories.delete(entryName);
169
+ } else {
170
+ throw new Error(`Entry not found: ${entryName}`);
171
+ }
66
172
  },
67
173
  entries: async function* () {
68
- yield* s().entries();
174
+ const joinedMaps = getJoinedMaps();
175
+ yield* joinedMaps.entries();
69
176
  },
70
177
  keys: async function* () {
71
- yield* s().keys();
178
+ const joinedMaps = getJoinedMaps();
179
+ yield* joinedMaps.keys();
72
180
  },
73
181
  values: async function* () {
74
- yield* s().values();
182
+ const joinedMaps = getJoinedMaps();
183
+ yield* joinedMaps.values();
75
184
  },
76
- resolve: async (e) => {
77
- const r = async (c, a, l = []) => {
78
- if (await c.isSameEntry(a))
79
- return l;
80
- for await (const [d, i] of c.entries())
81
- if (i.kind === "directory") {
82
- const u = await r(i, a, [...l, d]);
83
- if (u)
84
- return u;
85
- } else if (i.kind === "file" && await i.isSameEntry(a))
86
- return [...l, d];
185
+ resolve: async (possibleDescendant) => {
186
+ const traverseDirectory = async (directory, target, path = []) => {
187
+ if (await directory.isSameEntry(target)) {
188
+ return path;
189
+ }
190
+ for await (const [name2, handle] of directory.entries()) {
191
+ if (handle.kind === "directory") {
192
+ const subDirectory = handle;
193
+ const result = await traverseDirectory(subDirectory, target, [...path, name2]);
194
+ if (result) {
195
+ return result;
196
+ }
197
+ } else if (handle.kind === "file") {
198
+ if (await handle.isSameEntry(target)) {
199
+ return [...path, name2];
200
+ }
201
+ }
202
+ }
87
203
  return null;
88
204
  };
89
- return r(void 0, e);
205
+ return traverseDirectory(void 0, possibleDescendant);
90
206
  }
91
207
  };
92
- }, w = ({ usage: o = 0, quota: n = 0 } = {}) => {
93
- const t = y("root");
208
+ };
209
+
210
+ // src/index.ts
211
+ var storageFactory = ({ usage = 0, quota = 0 } = {}) => {
212
+ const root = fileSystemDirectoryHandleFactory("root");
94
213
  return {
95
- estimate: async () => ({
96
- usage: o,
97
- quota: n
98
- }),
99
- getDirectory: async () => t,
100
- persist: async () => !0,
101
- persisted: async () => !0
214
+ estimate: async () => {
215
+ return {
216
+ usage,
217
+ quota
218
+ };
219
+ },
220
+ getDirectory: async () => {
221
+ return root;
222
+ },
223
+ persist: async () => {
224
+ return true;
225
+ },
226
+ persisted: async () => {
227
+ return true;
228
+ }
102
229
  };
103
- }, b = () => {
104
- if ("navigator" in globalThis || Object.defineProperty(globalThis, "navigator", {
105
- value: {},
106
- writable: !0
107
- }), !globalThis.navigator.storage) {
108
- const { getDirectory: o } = w();
230
+ };
231
+ var mockOPFS = () => {
232
+ if (!("navigator" in globalThis)) {
233
+ Object.defineProperty(globalThis, "navigator", {
234
+ value: {},
235
+ writable: true
236
+ });
237
+ }
238
+ if (!globalThis.navigator.storage) {
239
+ const { getDirectory } = storageFactory();
109
240
  Object.defineProperty(globalThis.navigator, "storage", {
110
241
  value: {
111
- getDirectory: o
242
+ getDirectory
112
243
  },
113
- writable: !0
244
+ writable: true
114
245
  });
115
246
  }
116
- }, h = () => {
117
- const o = y("root");
247
+ };
248
+ var resetMockOPFS = () => {
249
+ const root = fileSystemDirectoryHandleFactory("root");
118
250
  Object.defineProperty(globalThis.navigator.storage, "getDirectory", {
119
- value: () => o,
120
- writable: !0
251
+ value: () => root,
252
+ writable: true
121
253
  });
122
254
  };
123
- typeof globalThis < "u" && b();
255
+ if (typeof globalThis !== "undefined") {
256
+ mockOPFS();
257
+ }
124
258
  export {
125
- b as mockOPFS,
126
- h as resetMockOPFS,
127
- w as storageFactory
259
+ mockOPFS,
260
+ resetMockOPFS,
261
+ storageFactory
128
262
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opfs-mock",
3
- "version": "1.0.1",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "description": "Mock all origin private file system APIs for your Jest or Vitest tests",
6
6
  "author": "Jure Rotar <hello@jurerotar.com>",
@@ -23,25 +23,25 @@
23
23
  "import": "./dist/index.js"
24
24
  }
25
25
  },
26
+ "main": "dist/index.js",
26
27
  "module": "dist/index.js",
27
28
  "files": ["dist"],
28
29
  "scripts": {
29
- "dev": "vite",
30
- "build": "vite build",
30
+ "dev": "tsup --watch",
31
+ "build": "tsup",
31
32
  "lint:check": "npx @biomejs/biome lint",
32
33
  "lint": "npx @biomejs/biome lint --fix",
33
34
  "format:check": "npx @biomejs/biome format",
34
35
  "format": "npx @biomejs/biome format --write",
35
36
  "type-check": "tsc --noEmit",
36
37
  "test": "vitest",
37
- "build:types": "tsc --emitDeclarationOnly",
38
- "prepublishOnly": "npm run build && npm run build:types",
38
+ "prepublishOnly": "npm run build",
39
39
  "release": "npm publish --access public"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@biomejs/biome": "1.9.4",
43
+ "tsup": "8.3.6",
43
44
  "typescript": "5.7.3",
44
- "vite": "6.0.7",
45
- "vitest": "2.1.8"
45
+ "vitest": "3.0.6"
46
46
  }
47
47
  }
package/dist/opfs.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const fileSystemDirectoryHandleFactory: (name: string) => FileSystemDirectoryHandle;