-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
fs.ts
599 lines (566 loc) · 14.2 KB
/
fs.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
// Copyright 2019-2022 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/**
* Access the file system.
*
* This package is also accessible with `window.__TAURI__.fs` when [`build.withGlobalTauri`](https://tauri.app/v1/api/config/#buildconfig.withglobaltauri) in `tauri.conf.json` is set to `true`.
*
* The APIs must be added to [`tauri.allowlist.fs`](https://tauri.app/v1/api/config/#allowlistconfig.fs) in `tauri.conf.json`:
* ```json
* {
* "tauri": {
* "allowlist": {
* "fs": {
* "all": true, // enable all FS APIs
* "readFile": true,
* "writeFile": true,
* "readDir": true,
* "copyFile": true,
* "createDir": true,
* "removeDir": true,
* "removeFile": true,
* "renameFile": true,
* "exists": true
* }
* }
* }
* }
* ```
* It is recommended to allowlist only the APIs you use for optimal bundle size and security.
*
* ## Security
*
* This module prevents path traversal, not allowing absolute paths or parent dir components
* (i.e. "/usr/path/to/file" or "../path/to/file" paths are not allowed).
* Paths accessed with this API must be relative to one of the {@link BaseDirectory | base directories}
* so if you need access to arbitrary filesystem paths, you must write such logic on the core layer instead.
*
* The API has a scope configuration that forces you to restrict the paths that can be accessed using glob patterns.
*
* The scope configuration is an array of glob patterns describing folder paths that are allowed.
* For instance, this scope configuration only allows accessing files on the
* *databases* folder of the {@link path.appDir | $APP directory}:
* ```json
* {
* "tauri": {
* "allowlist": {
* "fs": {
* "scope": ["$APP/databases/*"]
* }
* }
* }
* }
* ```
*
* Notice the use of the `$APP` variable. The value is injected at runtime, resolving to the {@link path.appDir | app directory}.
* The available variables are:
* {@link path.audioDir | `$AUDIO`}, {@link path.cacheDir | `$CACHE`}, {@link path.configDir | `$CONFIG`}, {@link path.dataDir | `$DATA`},
* {@link path.localDataDir | `$LOCALDATA`}, {@link path.desktopDir | `$DESKTOP`}, {@link path.documentDir | `$DOCUMENT`},
* {@link path.downloadDir | `$DOWNLOAD`}, {@link path.executableDir | `$EXE`}, {@link path.fontDir | `$FONT`}, {@link path.homeDir | `$HOME`},
* {@link path.pictureDir | `$PICTURE`}, {@link path.publicDir | `$PUBLIC`}, {@link path.runtimeDir | `$RUNTIME`},
* {@link path.templateDir | `$TEMPLATE`}, {@link path.videoDir | `$VIDEO`}, {@link path.resourceDir | `$RESOURCE`}, {@link path.appDir | `$APP`},
* {@link path.logDir | `$LOG`}, {@link os.tempdir | `$TEMP`}.
*
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
*
* Note that this scope applies to **all** APIs on this module.
*
* @module
*/
import { invokeTauriCommand } from './helpers/tauri'
/**
* @since 1.0.0
*/
export enum BaseDirectory {
Audio = 1,
Cache,
Config,
Data,
LocalData,
Desktop,
Document,
Download,
Executable,
Font,
Home,
Picture,
Public,
Runtime,
Template,
Video,
Resource,
App,
Log,
Temp
}
/**
* @since 1.0.0
*/
interface FsOptions {
dir?: BaseDirectory
// note that adding fields here needs a change in the writeBinaryFile check
}
/**
* @since 1.0.0
*/
interface FsDirOptions {
dir?: BaseDirectory
recursive?: boolean
}
/**
* Options object used to write a UTF-8 string to a file.
*
* @since 1.0.0
*/
interface FsTextFileOption {
/** Path to the file to write. */
path: string
/** The UTF-8 string to write to the file. */
contents: string
}
type BinaryFileContents = Iterable<number> | ArrayLike<number> | ArrayBuffer
/**
* Options object used to write a binary data to a file.
*
* @since 1.0.0
*/
interface FsBinaryFileOption {
/** Path to the file to write. */
path: string
/** The byte array contents. */
contents: BinaryFileContents
}
/**
* @since 1.0.0
*/
interface FileEntry {
path: string
/**
* Name of the directory/file
* can be null if the path terminates with `..`
*/
name?: string
/** Children of this entry if it's a directory; null otherwise */
children?: FileEntry[]
}
/**
* Reads a file as an UTF-8 encoded string.
* @example
* ```typescript
* import { readTextFile, BaseDirectory } from '@tauri-apps/api/fs';
* // Read the text file in the `$APPDIR/app.conf` path
* const contents = await readTextFile('app.conf', { dir: BaseDirectory.App });
* ```
*
* @since 1.0.0
*/
async function readTextFile(
filePath: string,
options: FsOptions = {}
): Promise<string> {
return invokeTauriCommand<string>({
__tauriModule: 'Fs',
message: {
cmd: 'readTextFile',
path: filePath,
options
}
})
}
/**
* Reads a file as byte array.
* @example
* ```typescript
* import { readBinaryFile, BaseDirectory } from '@tauri-apps/api/fs';
* // Read the image file in the `$RESOURCEDIR/avatar.png` path
* const contents = await readBinaryFile('avatar.png', { dir: BaseDirectory.Resource });
* ```
*
* @since 1.0.0
*/
async function readBinaryFile(
filePath: string,
options: FsOptions = {}
): Promise<Uint8Array> {
const arr = await invokeTauriCommand<number[]>({
__tauriModule: 'Fs',
message: {
cmd: 'readFile',
path: filePath,
options
}
})
return Uint8Array.from(arr)
}
/**
* Writes a UTF-8 text file.
* @example
* ```typescript
* import { writeTextFile, BaseDirectory } from '@tauri-apps/api/fs';
* // Write a text file to the `$APPDIR/app.conf` path
* await writeTextFile('app.conf', 'file contents', { dir: BaseDirectory.App });
* ```
*
* @since 1.0.0
*/
async function writeTextFile(
path: string,
contents: string,
options?: FsOptions
): Promise<void>
/**
* Writes a UTF-8 text file.
* @example
* ```typescript
* import { writeTextFile, BaseDirectory } from '@tauri-apps/api/fs';
* // Write a text file to the `$APPDIR/app.conf` path
* await writeTextFile({ path: 'app.conf', contents: 'file contents' }, { dir: BaseDirectory.App });
* ```
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function writeTextFile(
file: FsTextFileOption,
options?: FsOptions
): Promise<void>
/**
* Writes a UTF-8 text file.
*
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function writeTextFile(
path: string | FsTextFileOption,
contents?: string | FsOptions,
options?: FsOptions
): Promise<void> {
if (typeof options === 'object') {
Object.freeze(options)
}
if (typeof path === 'object') {
Object.freeze(path)
}
const file: FsTextFileOption = { path: '', contents: '' }
let fileOptions: FsOptions | undefined = options
if (typeof path === 'string') {
file.path = path
} else {
file.path = path.path
file.contents = path.contents
}
if (typeof contents === 'string') {
file.contents = contents ?? ''
} else {
fileOptions = contents
}
return invokeTauriCommand({
__tauriModule: 'Fs',
message: {
cmd: 'writeFile',
path: file.path,
contents: Array.from(new TextEncoder().encode(file.contents)),
options: fileOptions
}
})
}
/**
* Writes a byte array content to a file.
* @example
* ```typescript
* import { writeBinaryFile, BaseDirectory } from '@tauri-apps/api/fs';
* // Write a binary file to the `$APPDIR/avatar.png` path
* await writeBinaryFile('avatar.png', new Uint8Array([]), { dir: BaseDirectory.App });
* ```
*
* @param options Configuration object.
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function writeBinaryFile(
path: string,
contents: BinaryFileContents,
options?: FsOptions
): Promise<void>
/**
* Writes a byte array content to a file.
* @example
* ```typescript
* import { writeBinaryFile, BaseDirectory } from '@tauri-apps/api/fs';
* // Write a binary file to the `$APPDIR/avatar.png` path
* await writeBinaryFile({ path: 'avatar.png', contents: new Uint8Array([]) }, { dir: BaseDirectory.App });
* ```
*
* @param file The object containing the file path and contents.
* @param options Configuration object.
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function writeBinaryFile(
file: FsBinaryFileOption,
options?: FsOptions
): Promise<void>
/**
* Writes a byte array content to a file.
*
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function writeBinaryFile(
path: string | FsBinaryFileOption,
contents?: BinaryFileContents | FsOptions,
options?: FsOptions
): Promise<void> {
if (typeof options === 'object') {
Object.freeze(options)
}
if (typeof path === 'object') {
Object.freeze(path)
}
const file: FsBinaryFileOption = { path: '', contents: [] }
let fileOptions: FsOptions | undefined = options
if (typeof path === 'string') {
file.path = path
} else {
file.path = path.path
file.contents = path.contents
}
if (contents && 'dir' in contents) {
fileOptions = contents
} else if (typeof path === 'string') {
// @ts-expect-error
file.contents = contents ?? []
}
return invokeTauriCommand({
__tauriModule: 'Fs',
message: {
cmd: 'writeFile',
path: file.path,
contents: Array.from(
file.contents instanceof ArrayBuffer
? new Uint8Array(file.contents)
: file.contents
),
options: fileOptions
}
})
}
/**
* List directory files.
* @example
* ```typescript
* import { readDir, BaseDirectory } from '@tauri-apps/api/fs';
* // Reads the `$APPDIR/users` directory recursively
* const entries = await readDir('users', { dir: BaseDirectory.App, recursive: true });
*
* function processEntries(entries) {
* for (const entry of entries) {
* console.log(`Entry: ${entry.path}`);
* if (entry.children) {
* processEntries(entry.children)
* }
* }
* }
* ```
*
* @since 1.0.0
*/
async function readDir(
dir: string,
options: FsDirOptions = {}
): Promise<FileEntry[]> {
return invokeTauriCommand({
__tauriModule: 'Fs',
message: {
cmd: 'readDir',
path: dir,
options
}
})
}
/**
* Creates a directory.
* If one of the path's parent components doesn't exist
* and the `recursive` option isn't set to true, the promise will be rejected.
* @example
* ```typescript
* import { createDir, BaseDirectory } from '@tauri-apps/api/fs';
* // Create the `$APPDIR/users` directory
* await createDir('users', { dir: BaseDirectory.App, recursive: true });
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function createDir(
dir: string,
options: FsDirOptions = {}
): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Fs',
message: {
cmd: 'createDir',
path: dir,
options
}
})
}
/**
* Removes a directory.
* If the directory is not empty and the `recursive` option isn't set to true, the promise will be rejected.
* @example
* ```typescript
* import { removeDir, BaseDirectory } from '@tauri-apps/api/fs';
* // Remove the directory `$APPDIR/users`
* await removeDir('users', { dir: BaseDirectory.App });
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function removeDir(
dir: string,
options: FsDirOptions = {}
): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Fs',
message: {
cmd: 'removeDir',
path: dir,
options
}
})
}
/**
* Copies a file to a destination.
* @example
* ```typescript
* import { copyFile, BaseDirectory } from '@tauri-apps/api/fs';
* // Copy the `$APPDIR/app.conf` file to `$APPDIR/app.conf.bk`
* await copyFile('app.conf', 'app.conf.bk', { dir: BaseDirectory.App });
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function copyFile(
source: string,
destination: string,
options: FsOptions = {}
): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Fs',
message: {
cmd: 'copyFile',
source,
destination,
options
}
})
}
/**
* Removes a file.
* @example
* ```typescript
* import { removeFile, BaseDirectory } from '@tauri-apps/api/fs';
* // Remove the `$APPDIR/app.conf` file
* await removeFile('app.conf', { dir: BaseDirectory.App });
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function removeFile(
file: string,
options: FsOptions = {}
): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Fs',
message: {
cmd: 'removeFile',
path: file,
options
}
})
}
/**
* Renames a file.
* @example
* ```typescript
* import { renameFile, BaseDirectory } from '@tauri-apps/api/fs';
* // Rename the `$APPDIR/avatar.png` file
* await renameFile('avatar.png', 'deleted.png', { dir: BaseDirectory.App });
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @since 1.0.0
*/
async function renameFile(
oldPath: string,
newPath: string,
options: FsOptions = {}
): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Fs',
message: {
cmd: 'renameFile',
oldPath,
newPath,
options
}
})
}
/**
* Check if a path exists.
* @example
* ```typescript
* import { exists, BaseDirectory } from '@tauri-apps/api/fs';
* // Check if the `$APPDIR/avatar.png` file exists
* await exists('avatar.png', { dir: BaseDirectory.App });
* ```
*
* @since 1.1.0
*/
async function exists(path: string, options: FsOptions = {}): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Fs',
message: {
cmd: 'exists',
path,
options
}
})
}
export type {
FsOptions,
FsDirOptions,
FsTextFileOption,
BinaryFileContents,
FsBinaryFileOption,
FileEntry
}
export {
BaseDirectory as Dir,
readTextFile,
readBinaryFile,
writeTextFile,
writeTextFile as writeFile,
writeBinaryFile,
readDir,
createDir,
removeDir,
copyFile,
removeFile,
renameFile,
exists
}