opfs-mock 2.2.0 → 2.3.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.
Files changed (4) hide show
  1. package/LICENSE.md +21 -21
  2. package/README.md +168 -168
  3. package/dist/index.js +74 -33
  4. package/package.json +1 -1
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,168 +1,168 @@
1
- # opfs-mock
2
-
3
- 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. It's tested
4
- on Node.js versions 20-24.
5
-
6
- ## Installation
7
-
8
- ```shell
9
- npm install -save-dev opfs-mock
10
- ```
11
-
12
- ## Limitations
13
-
14
- - `opfs-mock` requires **Node.js v20.0.0** or higher. It can work on Node v18.0.0 with either `--experimental-fetch` flag enabled or a global
15
- `File` polyfill.
16
-
17
- - `jsdom` testing environment is missing `File.prototype.text()` method, which is required for reading opfs files. Ensure your opfs-dependant tests are ran
18
- in `node` or `happy-dom` environment.
19
-
20
- ## Usage
21
-
22
- It replicates the behavior of origin private file system, except data is not persisted to disk.
23
-
24
- The easiest way to use it is to import `opfs-mock`, which will polyfill OPFS API to global scope.
25
-
26
- ```ts
27
- import "opfs-mock";
28
- ```
29
-
30
- Alternatively, you can explicitly import `storageFactory`:
31
-
32
- ```ts
33
- import { storageFactory } from "opfs-mock";
34
-
35
- test('Your test', async () => {
36
- const storage = await storageFactory();
37
- const root = await storage.getDirectory();
38
- const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
39
- // rest of your test
40
- });
41
- ```
42
-
43
- `storageFactory` has `quota` and `usage` values set to `1024 ** 3 (1 GB)` and `0` respectively. When calling `storage.estimate()`, `usage` is dynamically calculated by summing the predefined usage value and any additional computed storage consumption.
44
- In case you need specific values, you can pass both as arguments to `storageFactory`.
45
-
46
- ```ts
47
- import { storageFactory } from "opfs-mock";
48
-
49
- test('Your test', async () => {
50
- const storage = await storageFactory({ quota: 1_000_000, usage: 1_000 });
51
- const root = await storage.getDirectory();
52
- const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
53
- // rest of your test
54
- });
55
- ```
56
-
57
- ### Vitest
58
-
59
- To use `opfs-mock` in a single Vitest test suite, require `opfs-mock` at the beginning of the test file, as described above.
60
-
61
- 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:
62
-
63
- ```ts
64
- // vite.config.ts
65
-
66
- import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
67
- import { defineConfig as defineVitestConfig } from 'vitest/config';
68
-
69
- const viteConfig = defineViteConfig({
70
- ...
71
- });
72
-
73
- const vitestConfig = defineVitestConfig({
74
- test: {
75
- setupFiles: ['opfs-mock'],
76
- },
77
- });
78
-
79
- export default mergeConfig(viteConfig, vitestConfig);
80
- ```
81
-
82
- Alternatively you can create a new setup file which then imports this module.
83
-
84
- ```ts
85
- // vitest-setup.ts
86
-
87
- import "opfs-mock";
88
- ```
89
-
90
- Add that file to your `test.setupFiles` array:
91
-
92
- ```ts
93
- // vite.config.ts
94
-
95
- import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
96
- import { defineConfig as defineVitestConfig } from 'vitest/config';
97
-
98
- const viteConfig = defineViteConfig({
99
- ...
100
- });
101
-
102
- const vitestConfig = defineVitestConfig({
103
- test: {
104
- setupFiles: ['vitest-setup.ts'],
105
- },
106
- });
107
-
108
- export default mergeConfig(viteConfig, vitestConfig);
109
- ```
110
-
111
-
112
- ### Jest
113
-
114
- To use `opfs-mock` in a single Jest test suite, require `opfs-mock` at the beginning of the test file, as described above.
115
-
116
- 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:
117
-
118
- ```ts
119
- // jest.config.js
120
-
121
- {
122
- ...
123
- "setupFiles": [
124
- "opfs-mock"
125
- ]
126
- }
127
- ```
128
-
129
- Alternatively you can create a new setup file which then imports this module.
130
-
131
- ```ts
132
- // jest-setup.ts
133
-
134
- import "opfs-mock";
135
- ```
136
-
137
- Add that file to your `setupFiles` array:
138
-
139
- ```ts
140
- // jest.config.js
141
-
142
- {
143
- ...
144
- "setupFiles": [
145
- "jest-setup"
146
- ]
147
- }
148
- ```
149
-
150
- ## Wiping/resetting the OPFS mock for a fresh state
151
-
152
- 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.
153
-
154
- ```ts
155
- import { resetMockOPFS } from 'opfs-mock';
156
-
157
- beforeEach(() => {
158
- resetMockOPFS();
159
- });
160
-
161
- test('First isolated test', async () => {
162
- // rest of your test
163
- });
164
-
165
- test('Second isolated test', async () => {
166
- // rest of your test
167
- });
168
- ```
1
+ # opfs-mock
2
+
3
+ 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. It's tested
4
+ on Node.js versions 20-24.
5
+
6
+ ## Installation
7
+
8
+ ```shell
9
+ npm install -save-dev opfs-mock
10
+ ```
11
+
12
+ ## Limitations
13
+
14
+ - `opfs-mock` requires **Node.js v20.0.0** or higher. It can work on Node v18.0.0 with either `--experimental-fetch` flag enabled or a global
15
+ `File` polyfill.
16
+
17
+ - `jsdom` testing environment is missing `File.prototype.text()` method, which is required for reading opfs files. Ensure your opfs-dependant tests are ran
18
+ in `node` or `happy-dom` environment.
19
+
20
+ ## Usage
21
+
22
+ It replicates the behavior of origin private file system, except data is not persisted to disk.
23
+
24
+ The easiest way to use it is to import `opfs-mock`, which will polyfill OPFS API to global scope.
25
+
26
+ ```ts
27
+ import "opfs-mock";
28
+ ```
29
+
30
+ Alternatively, you can explicitly import `storageFactory`:
31
+
32
+ ```ts
33
+ import { storageFactory } from "opfs-mock";
34
+
35
+ test('Your test', async () => {
36
+ const storage = await storageFactory();
37
+ const root = await storage.getDirectory();
38
+ const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
39
+ // rest of your test
40
+ });
41
+ ```
42
+
43
+ `storageFactory` has `quota` and `usage` values set to `1024 ** 3 (1 GB)` and `0` respectively. When calling `storage.estimate()`, `usage` is dynamically calculated by summing the predefined usage value and any additional computed storage consumption.
44
+ In case you need specific values, you can pass both as arguments to `storageFactory`.
45
+
46
+ ```ts
47
+ import { storageFactory } from "opfs-mock";
48
+
49
+ test('Your test', async () => {
50
+ const storage = await storageFactory({ quota: 1_000_000, usage: 1_000 });
51
+ const root = await storage.getDirectory();
52
+ const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
53
+ // rest of your test
54
+ });
55
+ ```
56
+
57
+ ### Vitest
58
+
59
+ To use `opfs-mock` in a single Vitest test suite, require `opfs-mock` at the beginning of the test file, as described above.
60
+
61
+ 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:
62
+
63
+ ```ts
64
+ // vite.config.ts
65
+
66
+ import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
67
+ import { defineConfig as defineVitestConfig } from 'vitest/config';
68
+
69
+ const viteConfig = defineViteConfig({
70
+ ...
71
+ });
72
+
73
+ const vitestConfig = defineVitestConfig({
74
+ test: {
75
+ setupFiles: ['opfs-mock'],
76
+ },
77
+ });
78
+
79
+ export default mergeConfig(viteConfig, vitestConfig);
80
+ ```
81
+
82
+ Alternatively you can create a new setup file which then imports this module.
83
+
84
+ ```ts
85
+ // vitest-setup.ts
86
+
87
+ import "opfs-mock";
88
+ ```
89
+
90
+ Add that file to your `test.setupFiles` array:
91
+
92
+ ```ts
93
+ // vite.config.ts
94
+
95
+ import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
96
+ import { defineConfig as defineVitestConfig } from 'vitest/config';
97
+
98
+ const viteConfig = defineViteConfig({
99
+ ...
100
+ });
101
+
102
+ const vitestConfig = defineVitestConfig({
103
+ test: {
104
+ setupFiles: ['vitest-setup.ts'],
105
+ },
106
+ });
107
+
108
+ export default mergeConfig(viteConfig, vitestConfig);
109
+ ```
110
+
111
+
112
+ ### Jest
113
+
114
+ To use `opfs-mock` in a single Jest test suite, require `opfs-mock` at the beginning of the test file, as described above.
115
+
116
+ 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:
117
+
118
+ ```ts
119
+ // jest.config.js
120
+
121
+ {
122
+ ...
123
+ "setupFiles": [
124
+ "opfs-mock"
125
+ ]
126
+ }
127
+ ```
128
+
129
+ Alternatively you can create a new setup file which then imports this module.
130
+
131
+ ```ts
132
+ // jest-setup.ts
133
+
134
+ import "opfs-mock";
135
+ ```
136
+
137
+ Add that file to your `setupFiles` array:
138
+
139
+ ```ts
140
+ // jest.config.js
141
+
142
+ {
143
+ ...
144
+ "setupFiles": [
145
+ "jest-setup"
146
+ ]
147
+ }
148
+ ```
149
+
150
+ ## Wiping/resetting the OPFS mock for a fresh state
151
+
152
+ 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.
153
+
154
+ ```ts
155
+ import { resetMockOPFS } from 'opfs-mock';
156
+
157
+ beforeEach(() => {
158
+ resetMockOPFS();
159
+ });
160
+
161
+ test('First isolated test', async () => {
162
+ // rest of your test
163
+ });
164
+
165
+ test('Second isolated test', async () => {
166
+ // rest of your test
167
+ });
168
+ ```
package/dist/index.js CHANGED
@@ -29,7 +29,7 @@ const fileSystemFileHandleFactory = (name, fileData) => {
29
29
  let abortReason = "";
30
30
  let isAborted = false;
31
31
  let isClosed = false;
32
- let content = keepExistingData ? fileData.content : "";
32
+ let content = keepExistingData ? new Uint8Array(fileData.content) : new Uint8Array();
33
33
  let cursorPosition = keepExistingData ? fileData.content.length : 0;
34
34
  const writableStream = new WritableStream({
35
35
  write: () => {},
@@ -42,21 +42,46 @@ const fileSystemFileHandleFactory = (name, fileData) => {
42
42
  if (isAborted) throw new Error(abortReason);
43
43
  if (isClosed) throw new TypeError("Cannot write to a CLOSED writable stream");
44
44
  if (chunk === void 0) throw new TypeError("Cannot write undefined data to the stream");
45
- let chunkText;
46
- if (typeof chunk === "string") chunkText = chunk;
47
- else if (chunk instanceof Blob) chunkText = await chunk.text();
48
- else if (ArrayBuffer.isView(chunk)) chunkText = new TextDecoder().decode(new Uint8Array(chunk.buffer));
45
+ if (typeof chunk === "object" && "type" in chunk && chunk.type === "truncate") {
46
+ if (typeof chunk.size !== "number" || chunk.size < 0) throw new TypeError("Invalid size value in truncate parameters");
47
+ if (chunk.size < content.length) content = content.slice(0, chunk.size);
48
+ else {
49
+ const extended = new Uint8Array(chunk.size);
50
+ extended.set(content);
51
+ content = extended;
52
+ }
53
+ cursorPosition = Math.min(cursorPosition, chunk.size);
54
+ return;
55
+ }
56
+ let encoded;
57
+ if (typeof chunk === "string") encoded = new TextEncoder().encode(chunk);
58
+ else if (chunk instanceof Blob) {
59
+ const text = await chunk.text();
60
+ encoded = new TextEncoder().encode(text);
61
+ } else if (ArrayBuffer.isView(chunk)) encoded = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
62
+ else if (chunk instanceof ArrayBuffer) encoded = new Uint8Array(chunk);
49
63
  else if (typeof chunk === "object" && "data" in chunk) {
50
64
  if (chunk.position !== void 0 && (typeof chunk.position !== "number" || chunk.position < 0)) throw new TypeError("Invalid position value in write parameters");
51
65
  if (chunk.size !== void 0 && (typeof chunk.size !== "number" || chunk.size < 0)) throw new TypeError("Invalid size value in write parameters");
52
66
  if (chunk.position !== void 0 && chunk.position !== null) cursorPosition = chunk.position;
53
- if (chunk.data) if (typeof chunk.data === "string") chunkText = chunk.data;
54
- else if (chunk.data instanceof Blob) chunkText = await chunk.data.text();
55
- else chunkText = new TextDecoder().decode(new Uint8Array(chunk.data instanceof ArrayBuffer ? chunk.data : chunk.data.buffer));
56
- else chunkText = "";
67
+ const data = chunk.data;
68
+ if (data === void 0 || data === null) encoded = new Uint8Array();
69
+ else if (typeof data === "string") encoded = new TextEncoder().encode(data);
70
+ else if (data instanceof Blob) {
71
+ const text = await data.text();
72
+ encoded = new TextEncoder().encode(text);
73
+ } else if (ArrayBuffer.isView(data)) encoded = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
74
+ else if (data instanceof ArrayBuffer) encoded = new Uint8Array(data);
75
+ else throw new TypeError("Invalid data in WriteParams");
57
76
  } else throw new TypeError("Invalid data type written to the file. Data must be of type FileSystemWriteChunkType.");
58
- content = content.slice(0, cursorPosition) + chunkText + content.slice(cursorPosition + chunkText.length);
59
- cursorPosition += chunkText.length;
77
+ const requiredSize = cursorPosition + encoded.length;
78
+ if (content.length < requiredSize) {
79
+ const extended = new Uint8Array(requiredSize);
80
+ extended.set(content);
81
+ content = extended;
82
+ }
83
+ content.set(encoded, cursorPosition);
84
+ cursorPosition += encoded.length;
60
85
  },
61
86
  close: async function() {
62
87
  if (isClosed) throw new TypeError("Cannot close a CLOSED writable stream");
@@ -73,11 +98,15 @@ const fileSystemFileHandleFactory = (name, fileData) => {
73
98
  truncate: async function(size) {
74
99
  if (size < 0) throw new DOMException("Invalid truncate size", "IndexSizeError");
75
100
  if (size < content.length) content = content.slice(0, size);
76
- else content = content.padEnd(size, "\0");
101
+ else if (size > content.length) {
102
+ const newBuffer = new Uint8Array(size);
103
+ newBuffer.set(content);
104
+ content = newBuffer;
105
+ }
77
106
  cursorPosition = Math.min(cursorPosition, size);
78
107
  },
79
108
  seek: async function(position) {
80
- if (position < 0 || position > content.length) throw new DOMException("Invalid seek position", "IndexSizeError");
109
+ if (position < 0) throw new DOMException("Invalid seek position", "IndexSizeError");
81
110
  cursorPosition = position;
82
111
  }
83
112
  });
@@ -87,26 +116,41 @@ const fileSystemFileHandleFactory = (name, fileData) => {
87
116
  return {
88
117
  getSize: () => {
89
118
  if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
90
- return fileData.content.length;
119
+ return fileData.content.byteLength;
91
120
  },
92
121
  read: (buffer, { at = 0 } = {}) => {
93
122
  if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
94
- const text = new TextEncoder().encode(fileData.content);
95
- const bytesRead = Math.min(buffer.length, text.length - at);
96
- buffer.set(text.subarray(at, at + bytesRead));
97
- return bytesRead;
123
+ const content = fileData.content;
124
+ if (at >= content.length) return 0;
125
+ const available = content.length - at;
126
+ const writable = buffer instanceof DataView ? buffer.byteLength : buffer.length;
127
+ const bytesToRead = Math.min(writable, available);
128
+ const slice = content.subarray(at, at + bytesToRead);
129
+ if (buffer instanceof DataView) for (let i = 0; i < slice.length; i++) buffer.setUint8(i, slice[i]);
130
+ else buffer.set(slice, 0);
131
+ return bytesToRead;
98
132
  },
99
- write: (data, options) => {
100
- const at = options?.at ?? 0;
133
+ write: (data, { at = 0 } = {}) => {
101
134
  if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
102
- const newContent = new TextDecoder().decode(data);
103
- if (at < fileData.content.length) fileData.content = fileData.content.slice(0, at) + newContent + fileData.content.slice(at + newContent.length);
104
- else fileData.content += newContent;
105
- return data.byteLength;
135
+ const writeLength = data instanceof DataView ? data.byteLength : data.length;
136
+ const requiredSize = at + writeLength;
137
+ if (fileData.content.length < requiredSize) {
138
+ const newBuffer = new Uint8Array(requiredSize);
139
+ newBuffer.set(fileData.content);
140
+ fileData.content = newBuffer;
141
+ }
142
+ if (data instanceof DataView) for (let i = 0; i < data.byteLength; i++) fileData.content[at + i] = data.getUint8(i);
143
+ else fileData.content.set(data, at);
144
+ return writeLength;
106
145
  },
107
146
  truncate: (size) => {
108
147
  if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
109
- fileData.content = fileData.content.slice(0, size);
148
+ if (size < fileData.content.length) fileData.content = fileData.content.slice(0, size);
149
+ else if (size > fileData.content.length) {
150
+ const newBuffer = new Uint8Array(size);
151
+ newBuffer.set(fileData.content);
152
+ fileData.content = newBuffer;
153
+ }
110
154
  },
111
155
  flush: async () => {
112
156
  if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
@@ -131,7 +175,7 @@ const fileSystemDirectoryHandleFactory = (name) => {
131
175
  return other.name === name && other.kind === "directory";
132
176
  },
133
177
  getFileHandle: async (fileName, options) => {
134
- if (!files.has(fileName) && options?.create) files.set(fileName, fileSystemFileHandleFactory(fileName, { content: "" }));
178
+ if (!files.has(fileName) && options?.create) files.set(fileName, fileSystemFileHandleFactory(fileName, { content: new Uint8Array() }));
135
179
  const fileHandle = files.get(fileName);
136
180
  if (!fileHandle) throw new DOMException(`File not found: ${fileName}`, "NotFoundError");
137
181
  return fileHandle;
@@ -210,13 +254,10 @@ const mockOPFS = () => {
210
254
  value: {},
211
255
  writable: true
212
256
  });
213
- if (!globalThis.navigator.storage) {
214
- const { getDirectory } = storageFactory();
215
- Object.defineProperty(globalThis.navigator, "storage", {
216
- value: { getDirectory },
217
- writable: true
218
- });
219
- }
257
+ if (!globalThis.navigator.storage) Object.defineProperty(globalThis.navigator, "storage", {
258
+ value: storageFactory(),
259
+ writable: true
260
+ });
220
261
  };
221
262
  const resetMockOPFS = () => {
222
263
  const root = fileSystemDirectoryHandleFactory("root");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opfs-mock",
3
- "version": "2.2.0",
3
+ "version": "2.3.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>",