@lvce-editor/file-system-process 1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Lvce Editor
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 ADDED
@@ -0,0 +1,7 @@
1
+ # File System Process
2
+
3
+ File System Process
4
+
5
+ ## Gitpod
6
+
7
+ [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/lvce-editor/file-system-process)
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+
3
+ import '../dist/index.js'
package/dist/index.js ADDED
@@ -0,0 +1,445 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as os from 'node:os';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { string } from '@lvce-editor/assert';
5
+ import { VError } from '@lvce-editor/verror';
6
+ import { join } from 'node:path';
7
+ import { existsSync } from 'node:fs';
8
+ import { NodeWebSocketRpcClient, ElectronMessagePortRpcClient, ElectronUtilityProcessRpcClient, NodeWorkerRpcClient, NodeForkedProcessRpcClient } from '@lvce-editor/rpc';
9
+ import { invoke as invoke$1 } from '@lvce-editor/json-rpc';
10
+ import _trash from 'trash';
11
+
12
+ const Utf8 = 'utf8';
13
+
14
+ const ENOENT = 'ENOENT';
15
+ const EXDEV = 'EXDEV';
16
+
17
+ // @ts-ignore
18
+ const getDisplayPath = path => {
19
+ if (path === '') {
20
+ return '<empty string>';
21
+ }
22
+ return path;
23
+ };
24
+ class FileNotFoundError extends VError {
25
+ // @ts-ignore
26
+ constructor(path) {
27
+ super(`File not found: '${getDisplayPath(path)}'`);
28
+ // @ts-ignore
29
+ this.code = ENOENT;
30
+ }
31
+ }
32
+
33
+ const BlockDevice = 1;
34
+ const CharacterDevice = 2;
35
+ const Directory = 3;
36
+ const Fifo = 6;
37
+ const File = 7;
38
+ const Socket = 8;
39
+ const Symlink = 9;
40
+ const Unknown = 12;
41
+
42
+ /**
43
+ * @param {import('fs').Dirent|import('fs').StatsBase} dirent
44
+ */
45
+ // @ts-ignore
46
+ const getDirentType = dirent => {
47
+ if (dirent.isFile()) {
48
+ return File;
49
+ }
50
+ if (dirent.isDirectory()) {
51
+ return Directory;
52
+ }
53
+ if (dirent.isSymbolicLink()) {
54
+ return Symlink;
55
+ }
56
+ if (dirent.isSocket()) {
57
+ return Socket;
58
+ }
59
+ if (dirent.isBlockDevice()) {
60
+ return BlockDevice;
61
+ }
62
+ if (dirent.isCharacterDevice()) {
63
+ return CharacterDevice;
64
+ }
65
+ if (dirent.isFIFO()) {
66
+ return Fifo;
67
+ }
68
+ return Unknown;
69
+ };
70
+
71
+ const getFolderSizeInternal = async path => {
72
+ if (path === '/') {
73
+ throw new Error('Invalid path for folder size');
74
+ }
75
+ let total = 0;
76
+ try {
77
+ const stats = await fs.stat(path);
78
+ total += stats.size;
79
+ if (stats.isDirectory() && !stats.isSymbolicLink()) {
80
+ const dirents = await fs.readdir(path);
81
+ for (const dirent of dirents) {
82
+ total += await getFolderSizeInternal(join(path, dirent));
83
+ }
84
+ }
85
+ } catch {
86
+ return 0;
87
+ }
88
+ return total;
89
+ };
90
+
91
+ // @ts-ignore
92
+ const isEnoentErrorWindows = error => {
93
+ return error && error.message && error.message.includes('The system cannot find the path specified.');
94
+ };
95
+
96
+ // @ts-ignore
97
+ const isEnoentErrorLinux = error => {
98
+ return error.code === ENOENT;
99
+ };
100
+
101
+ // @ts-ignore
102
+ const isEnoentError = error => {
103
+ if (!error) {
104
+ return false;
105
+ }
106
+ return isEnoentErrorLinux(error) || isEnoentErrorWindows(error);
107
+ };
108
+
109
+ const getElectronRunAsNode = () => {
110
+ return process.env.ELECTRON_RUN_AS_NODE;
111
+ };
112
+ process;
113
+
114
+ const isElectron = Boolean(getElectronRunAsNode()) || 'electron' in process.versions;
115
+
116
+ const NodeWorker = 1;
117
+ const NodeForkedProcess = 2;
118
+ const ElectronUtilityProcess = 3;
119
+ const ElectronMessagePort = 4;
120
+ const WebSocket = 6;
121
+ const Auto = argv => {
122
+ if (argv.includes('--ipc-type=node-worker')) {
123
+ return NodeWorker;
124
+ }
125
+ if (argv.includes('--ipc-type=node-forked-process')) {
126
+ return NodeForkedProcess;
127
+ }
128
+ if (argv.includes('--ipc-type=electron-utility-process')) {
129
+ return ElectronUtilityProcess;
130
+ }
131
+ throw new Error(`[file-system-process] unknown ipc type`);
132
+ };
133
+
134
+ const getModule = method => {
135
+ switch (method) {
136
+ case NodeForkedProcess:
137
+ return NodeForkedProcessRpcClient;
138
+ case NodeWorker:
139
+ return NodeWorkerRpcClient;
140
+ case ElectronUtilityProcess:
141
+ return ElectronUtilityProcessRpcClient;
142
+ case ElectronMessagePort:
143
+ return ElectronMessagePortRpcClient;
144
+ case WebSocket:
145
+ return NodeWebSocketRpcClient;
146
+ default:
147
+ throw new Error('unexpected ipc type');
148
+ }
149
+ };
150
+
151
+ const listen$1 = async ({
152
+ method,
153
+ ...params
154
+ }) => {
155
+ const module = getModule(method);
156
+ const rpc = await module.create(params);
157
+ return rpc;
158
+ };
159
+
160
+ // TODO add tests for this
161
+
162
+ // TODO handle structure: one shared process multiple extension hosts
163
+
164
+ // TODO pass socket / port handle also in electron
165
+
166
+ const state = {
167
+ ipc: undefined
168
+ };
169
+ const invoke = (method, ...params) => {
170
+ return invoke$1(state.ipc, method, ...params);
171
+ };
172
+
173
+ // @ts-ignore
174
+ const trash$2 = async path => {
175
+ if (!existsSync(path)) {
176
+ return;
177
+ }
178
+ await invoke('Trash.trash', path);
179
+ };
180
+
181
+ // @ts-ignore
182
+ const trash$1 = async path => {
183
+ await _trash(path);
184
+ };
185
+
186
+ const getFn = () => {
187
+ if (isElectron) {
188
+ return trash$2;
189
+ }
190
+ return trash$1;
191
+ };
192
+
193
+ // @ts-ignore
194
+ const trash = async path => {
195
+ try {
196
+ const fn = getFn();
197
+ await fn(path);
198
+ } catch (error) {
199
+ throw new VError(error, 'Failed to move item to trash');
200
+ }
201
+ };
202
+
203
+ // TODO lazyload chokidar and trash (but doesn't work currently because of bug with jest)
204
+
205
+ // @ts-ignore
206
+ const assertUri = uri => {
207
+ if (!uri.startsWith('file://')) {
208
+ throw new Error(`path must be a valid file uri`);
209
+ }
210
+ };
211
+ const copy = async (sourceUri, targetUri) => {
212
+ try {
213
+ assertUri(sourceUri);
214
+ assertUri(targetUri);
215
+ const source = fileURLToPath(sourceUri);
216
+ const target = fileURLToPath(targetUri);
217
+ await fs.cp(source, target, {
218
+ recursive: true
219
+ });
220
+ } catch (error) {
221
+ if (error && error.message && error.message.startsWith('Invalid src or dest: cp returned EINVAL (src and dest cannot be the same)')) {
222
+ throw new VError(`Failed to copy "${sourceUri}" to "${targetUri}": src and dest cannot be the same`);
223
+ }
224
+ throw new VError(error, `Failed to copy "${sourceUri}" to "${targetUri}"`);
225
+ }
226
+ };
227
+
228
+ /**
229
+ *
230
+ * @param {string} uri
231
+ * @param {BufferEncoding} encoding
232
+ * @returns
233
+ */
234
+ // @ts-ignore
235
+ const readFile = async (uri, encoding = Utf8) => {
236
+ try {
237
+ string(uri);
238
+ assertUri(uri);
239
+ const path = fileURLToPath(uri);
240
+ // @ts-ignore
241
+ const content = await fs.readFile(path, encoding);
242
+ return content;
243
+ } catch (error) {
244
+ if (isEnoentError(error)) {
245
+ throw new FileNotFoundError(uri);
246
+ }
247
+ throw new VError(error, `Failed to read file "${uri}"`);
248
+ }
249
+ };
250
+
251
+ /**
252
+ *
253
+ * @param {string} uri
254
+ * @param {string} content
255
+ * @param {BufferEncoding} encoding
256
+ */
257
+ // @ts-ignore
258
+ const writeFile = async (uri, content, encoding = Utf8) => {
259
+ try {
260
+ assertUri(uri);
261
+ string(uri);
262
+ string(content);
263
+ const path = fileURLToPath(uri);
264
+ // queue would be more correct for concurrent writes but also slower
265
+ // Queue.add(`writeFile/${path}`, () =>
266
+ // @ts-ignore
267
+ await fs.writeFile(path, content, encoding);
268
+ } catch (error) {
269
+ if (isEnoentError(error)) {
270
+ throw new FileNotFoundError(uri);
271
+ }
272
+ throw new VError(error, `Failed to write to file "${uri}"`);
273
+ }
274
+ };
275
+
276
+ // @ts-ignore
277
+ const isOkayToRemove = path => {
278
+ if (path === '/') {
279
+ return false;
280
+ }
281
+ if (path === '~') {
282
+ return false;
283
+ }
284
+ if (path === os.homedir()) {
285
+ return false;
286
+ }
287
+ return true;
288
+ };
289
+
290
+ // @ts-ignore
291
+ const remove = async uri => {
292
+ assertUri(uri);
293
+ const path = fileURLToPath(uri);
294
+ if (!isOkayToRemove(path)) {
295
+ console.warn('not removing path');
296
+ return;
297
+ }
298
+
299
+ // TODO lazyload trash (doesn't work currently because of bug with jest)
300
+ // const { trash } = await import('../../wrap/trash.js')
301
+ try {
302
+ await trash(path);
303
+ } catch (error) {
304
+ throw new VError(error, `Failed to remove "${uri}"`);
305
+ }
306
+ };
307
+
308
+ /**
309
+ * @param {import('fs').Dirent} dirent
310
+ */
311
+ // @ts-ignore
312
+ const toPrettyDirent = dirent => {
313
+ return {
314
+ name: dirent.name,
315
+ type: getDirentType(dirent)
316
+ };
317
+ };
318
+
319
+ // @ts-ignore
320
+ const readDirWithFileTypes = async uri => {
321
+ try {
322
+ assertUri(uri);
323
+ const path = fileURLToPath(uri);
324
+ const dirents = await fs.readdir(path, {
325
+ withFileTypes: true
326
+ });
327
+ const prettyDirents = dirents.map(toPrettyDirent);
328
+ return prettyDirents;
329
+ } catch (error) {
330
+ throw new VError(error, `Failed to read directory "${uri}"`);
331
+ }
332
+ };
333
+
334
+ // @ts-ignore
335
+ const mkdir = async uri => {
336
+ try {
337
+ assertUri(uri);
338
+ const path = fileURLToPath(uri);
339
+ await fs.mkdir(path, {
340
+ recursive: true
341
+ });
342
+ } catch (error) {
343
+ throw new VError(error, `Failed to create directory "${uri}"`);
344
+ }
345
+ };
346
+
347
+ // @ts-ignore
348
+ const fallbackRename = async (oldUri, newUri) => {
349
+ try {
350
+ const oldPath = fileURLToPath(oldUri);
351
+ const newPath = fileURLToPath(newUri);
352
+ await fs.cp(oldPath, newPath, {
353
+ recursive: true
354
+ });
355
+ await fs.rm(oldPath, {
356
+ recursive: true
357
+ });
358
+ } catch (error) {
359
+ throw new VError(error, `Failed to rename "${oldUri}" to "${newUri}"`);
360
+ }
361
+ };
362
+
363
+ // @ts-ignore
364
+ const rename = async (oldUri, newUri) => {
365
+ try {
366
+ const oldPath = fileURLToPath(oldUri);
367
+ const newPath = fileURLToPath(newUri);
368
+ await fs.rename(oldPath, newPath);
369
+ } catch (error) {
370
+ if (error && error.code === EXDEV) {
371
+ return fallbackRename(oldUri, newUri);
372
+ }
373
+ throw new VError(error, `Failed to rename "${oldUri}" to "${newUri}"`);
374
+ }
375
+ };
376
+ const getPathSeparator = () => {
377
+ return '/';
378
+ };
379
+
380
+ // TODO handle error
381
+ // @ts-ignore
382
+ const stat = async uri => {
383
+ const path = fileURLToPath(uri);
384
+ const stats = await fs.stat(path);
385
+ const type = getDirentType(stats);
386
+ return type;
387
+ };
388
+
389
+ // @ts-ignore
390
+ const chmod = async (uri, permissions) => {
391
+ const path = fileURLToPath(uri);
392
+ await fs.chmod(path, permissions);
393
+ };
394
+
395
+ // @ts-ignore
396
+ const readJson = async uri => {
397
+ try {
398
+ string(uri);
399
+ assertUri(uri);
400
+ const path = fileURLToPath(uri);
401
+ const content = await fs.readFile(path, 'utf8');
402
+ const parsed = JSON.parse(content);
403
+ return parsed;
404
+ } catch (error) {
405
+ if (isEnoentError(error)) {
406
+ throw new FileNotFoundError(uri);
407
+ }
408
+ throw new VError(error, `Failed to read file as json "${uri}"`);
409
+ }
410
+ };
411
+
412
+ // @ts-ignore
413
+ const getFolderSize = async uri => {
414
+ const path = fileURLToPath(uri);
415
+ const total = await getFolderSizeInternal(path);
416
+ return total;
417
+ };
418
+
419
+ const commandMap = {
420
+ chmod: chmod,
421
+ copy: copy,
422
+ getPathSeparator: getPathSeparator,
423
+ mkdir: mkdir,
424
+ readDirWithFileTypes: readDirWithFileTypes,
425
+ readFile: readFile,
426
+ readJson: readJson,
427
+ remove: remove,
428
+ rename: rename,
429
+ stat: stat,
430
+ writeFile: writeFile,
431
+ getFolderSize: getFolderSize
432
+ };
433
+
434
+ const listen = async argv => {
435
+ await listen$1({
436
+ method: Auto(argv),
437
+ commandMap: commandMap
438
+ });
439
+ };
440
+
441
+ const main = async () => {
442
+ await listen(process.argv);
443
+ };
444
+
445
+ main();
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@lvce-editor/file-system-process",
3
+ "version": "1.0.0",
4
+ "description": "File System Process",
5
+ "keywords": [
6
+ "Lvce Editor",
7
+ "File System"
8
+ ],
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/lvce-editor/file-system-process.git"
12
+ },
13
+ "license": "MIT",
14
+ "author": "Lvce Editor",
15
+ "type": "module",
16
+ "main": "dist/index.js",
17
+ "bin": {
18
+ "file-system-process": "bin/fileSystemProcess.js"
19
+ },
20
+ "dependencies": {
21
+ "@lvce-editor/assert": "^1.3.0",
22
+ "@lvce-editor/json-rpc": "^5.4.0",
23
+ "@lvce-editor/rpc": "^1.27.0",
24
+ "@lvce-editor/verror": "^1.6.0",
25
+ "execa": "^9.5.2",
26
+ "open": "^10.1.1",
27
+ "tail": "^2.2.6",
28
+ "tmp-promise": "^3.0.3",
29
+ "trash": "^9.0.0"
30
+ },
31
+ "engines": {
32
+ "node": ">=22"
33
+ }
34
+ }