Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FileSystem.ts

1,407 lines39.3 KB

1/**
2 * Defines the portable file system service for Effect programs.
3 *
4 * `FileSystem` is the boundary between Effect code and the host file system.
5 * Platform packages provide concrete layers, while this module defines the
6 * operations for reading, writing, inspecting, streaming, and watching files.
7 * Operations return `Effect`, `Stream`, or `Sink` values and fail with
8 * `PlatformError`. The module also includes file handles, size helpers, open
9 * flags, watch events, and the watch backend service.
10 *
11 * @since 4.0.0
12 */
13import * as Arr from "./Array.ts"
14import * as Brand from "./Brand.ts"
15import * as Cause from "./Cause.ts"
16import * as Context from "./Context.ts"
17import * as Effect from "./Effect.ts"
18import { pipe } from "./Function.ts"
19import * as Layer from "./Layer.ts"
20import * as Option from "./Option.ts"
21import { badArgument, type PlatformError, systemError } from "./PlatformError.ts"
22import { hasProperty } from "./Predicate.ts"
23import type * as Pull from "./Pull.ts"
24import type { Scope } from "./Scope.ts"
25import * as Sink from "./Sink.ts"
26import * as Stream from "./Stream.ts"
27​
28const TypeId = "~effect/platform/FileSystem"
29​
30/**
31 * Core interface for file system operations in Effect.
32 *
33 * **Details**
34 *
35 * The FileSystem interface provides a comprehensive set of file and directory operations
36 * that work cross-platform. All operations return Effect values that can be composed,
37 * transformed, and executed safely with proper error handling.
38 *
39 * **Example** (Accessing file system operations)
40 *
41 * ```ts
42 * import { Console, Effect, FileSystem } from "effect"
43 *
44 * const program = Effect.gen(function*() {
45 * const fs = yield* FileSystem.FileSystem
46 *
47 * // Basic file operations
48 * const exists = yield* fs.exists("./config.json")
49 * if (!exists) {
50 * yield* fs.writeFileString("./config.json", "{\"env\": \"development\"}")
51 * }
52 *
53 * // Directory operations
54 * yield* fs.makeDirectory("./logs", { recursive: true })
55 *
56 * // File information
57 * const stats = yield* fs.stat("./config.json")
58 * yield* Console.log(`File size: ${stats.size} bytes`)
59 *
60 * // Streaming operations
61 * const content = yield* fs.readFileString("./config.json")
62 * yield* Console.log("Config:", content)
63 * })
64 * ```
65 *
66 * @category models
67 * @since 4.0.0
68 */
69export interface FileSystem {
70 readonly [TypeId]: typeof TypeId
71​
72 /**
73 * Checks whether a file can be accessed.
74 * You can optionally specify the level of access to check for.
75 */
76 readonly access: (
77 path: string,
78 options?: {
79 readonly ok?: boolean | undefined
80 readonly readable?: boolean | undefined
81 readonly writable?: boolean | undefined
82 }
83 ) => Effect.Effect<void, PlatformError>
84 /**
85 * Copy a file or directory from `fromPath` to `toPath`.
86 *
87 * **Details**
88 *
89 * Equivalent to `cp -r`.
90 */
91 readonly copy: (
92 fromPath: string,
93 toPath: string,
94 options?: {
95 readonly overwrite?: boolean | undefined
96 readonly preserveTimestamps?: boolean | undefined
97 }
98 ) => Effect.Effect<void, PlatformError>
99 /**
100 * Copy a file from `fromPath` to `toPath`.
101 */
102 readonly copyFile: (
103 fromPath: string,
104 toPath: string
105 ) => Effect.Effect<void, PlatformError>
106 /**
107 * Change the permissions of a file.
108 */
109 readonly chmod: (
110 path: string,
111 mode: number
112 ) => Effect.Effect<void, PlatformError>
113 /**
114 * Change the owner and group of a file.
115 */
116 readonly chown: (
117 path: string,
118 uid: number,
119 gid: number
120 ) => Effect.Effect<void, PlatformError>
121 /**
122 * Glob a directory.
123 */
124 readonly glob: (
125 pattern: string,
126 options?: {
127 readonly root?: string | undefined
128 readonly exclude?: ReadonlyArray<string> | undefined
129 }
130 ) => Effect.Effect<Array<string>, PlatformError>
131 /**
132 * Checks whether a path exists.
133 */
134 readonly exists: (
135 path: string
136 ) => Effect.Effect<boolean, PlatformError>
137 /**
138 * Create a hard link from `fromPath` to `toPath`.
139 */
140 readonly link: (
141 fromPath: string,
142 toPath: string
143 ) => Effect.Effect<void, PlatformError>
144 /**
145 * Create a directory at `path`. You can optionally specify the mode and
146 * whether to recursively create nested directories.
147 */
148 readonly makeDirectory: (
149 path: string,
150 options?: {
151 readonly recursive?: boolean | undefined
152 readonly mode?: number | undefined
153 }
154 ) => Effect.Effect<void, PlatformError>
155 /**
156 * Create a temporary directory.
157 *
158 * **Details**
159 *
160 * By default the directory will be created inside the system's default
161 * temporary directory, but you can specify a different location by setting
162 * the `directory` option.
163 *
164 * You can also specify a prefix for the directory name by setting the
165 * `prefix` option.
166 */
167 readonly makeTempDirectory: (options?: {
168 readonly directory?: string | undefined
169 readonly prefix?: string | undefined
170 }) => Effect.Effect<string, PlatformError>
171 /**
172 * Create a temporary directory inside a scope.
173 *
174 * **Details**
175 *
176 * Functionally equivalent to `makeTempDirectory`, but the directory will be
177 * automatically deleted when the scope is closed.
178 */
179 readonly makeTempDirectoryScoped: (options?: {
180 readonly directory?: string | undefined
181 readonly prefix?: string | undefined
182 }) => Effect.Effect<string, PlatformError, Scope>
183 /**
184 * Create a temporary file.
185 * The directory creation is functionally equivalent to `makeTempDirectory`.
186 * The file name will be a randomly generated string.
187 */
188 readonly makeTempFile: (options?: {
189 readonly directory?: string | undefined
190 readonly prefix?: string | undefined
191 readonly suffix?: string | undefined
192 }) => Effect.Effect<string, PlatformError>
193 /**
194 * Create a temporary file inside a scope.
195 *
196 * **Details**
197 *
198 * Functionally equivalent to `makeTempFile`, but the file will be
199 * automatically deleted when the scope is closed.
200 */
201 readonly makeTempFileScoped: (options?: {
202 readonly directory?: string | undefined
203 readonly prefix?: string | undefined
204 readonly suffix?: string | undefined
205 }) => Effect.Effect<string, PlatformError, Scope>
206 /**
207 * Open a file at `path` with the specified `options`.
208 *
209 * **Details**
210 *
211 * The file handle will be automatically closed when the scope is closed.
212 */
213 readonly open: (
214 path: string,
215 options?: {
216 readonly flag?: OpenFlag | undefined
217 readonly mode?: number | undefined
218 }
219 ) => Effect.Effect<File, PlatformError, Scope>
220 /**
221 * List the contents of a directory.
222 *
223 * **Details**
224 *
225 * You can recursively list the contents of nested directories by setting the
226 * `recursive` option.
227 */
228 readonly readDirectory: (
229 path: string,
230 options?: {
231 readonly recursive?: boolean | undefined
232 }
233 ) => Effect.Effect<Array<string>, PlatformError>
234 /**
235 * Read the contents of a file.
236 */
237 readonly readFile: (
238 path: string
239 ) => Effect.Effect<Uint8Array, PlatformError>
240 /**
241 * Read the contents of a file.
242 */
243 readonly readFileString: (
244 path: string,
245 encoding?: string
246 ) => Effect.Effect<string, PlatformError>
247 /**
248 * Read the destination of a symbolic link.
249 */
250 readonly readLink: (
251 path: string
252 ) => Effect.Effect<string, PlatformError>
253 /**
254 * Resolve a path to its canonicalized absolute pathname.
255 */
256 readonly realPath: (
257 path: string
258 ) => Effect.Effect<string, PlatformError>
259 /**
260 * Remove a file or directory.
261 */
262 readonly remove: (
263 path: string,
264 options?: {
265 /**
266 * When `true`, you can recursively remove nested directories.
267 */
268 readonly recursive?: boolean | undefined
269 /**
270 * When `true`, exceptions will be ignored if `path` does not exist.
271 */
272 readonly force?: boolean | undefined
273 }
274 ) => Effect.Effect<void, PlatformError>
275 /**
276 * Rename a file or directory.
277 */
278 readonly rename: (
279 oldPath: string,
280 newPath: string
281 ) => Effect.Effect<void, PlatformError>
282 /**
283 * Create a writable `Sink` for the specified `path`.
284 */
285 readonly sink: (
286 path: string,
287 options?: {
288 readonly flag?: OpenFlag | undefined
289 readonly mode?: number | undefined
290 }
291 ) => Sink.Sink<void, Uint8Array, never, PlatformError>
292 /**
293 * Get information about a file at `path`.
294 */
295 readonly stat: (
296 path: string
297 ) => Effect.Effect<File.Info, PlatformError>
298 /**
299 * Create a readable `Stream` for the specified `path`.
300 *
301 * **Details**
302 *
303 * Changing the `bufferSize` option will change the internal buffer size of
304 * the stream. It defaults to `4`.
305 *
306 * The `chunkSize` option will change the size of the chunks emitted by the
307 * stream. It defaults to 64kb.
308 *
309 * Changing `offset` and `bytesToRead` will change the offset and the number
310 * of bytes to read from the file.
311 */
312 readonly stream: (
313 path: string,
314 options?: {
315 readonly bytesToRead?: SizeInput | undefined
316 readonly chunkSize?: SizeInput | undefined
317 readonly offset?: SizeInput | undefined
318 }
319 ) => Stream.Stream<Uint8Array, PlatformError>
320 /**
321 * Create a symbolic link from `fromPath` to `toPath`.
322 */
323 readonly symlink: (
324 fromPath: string,
325 toPath: string
326 ) => Effect.Effect<void, PlatformError>
327 /**
328 * Truncate a file to a specified length. If the `length` is not specified,
329 * the file will be truncated to length `0`.
330 */
331 readonly truncate: (
332 path: string,
333 length?: SizeInput
334 ) => Effect.Effect<void, PlatformError>
335 /**
336 * Change the file system timestamps of the file at `path`.
337 */
338 readonly utimes: (
339 path: string,
340 atime: Date | number,
341 mtime: Date | number
342 ) => Effect.Effect<void, PlatformError>
343 /**
344 * Watch a directory or file for changes
345 */
346 readonly watch: (path: string) => Stream.Stream<WatchEvent, PlatformError>
347 /**
348 * Write data to a file at `path`.
349 */
350 readonly writeFile: (
351 path: string,
352 data: Uint8Array,
353 options?: {
354 readonly flag?: OpenFlag | undefined
355 readonly mode?: number | undefined
356 }
357 ) => Effect.Effect<void, PlatformError>
358 /**
359 * Write a string to a file at `path`.
360 */
361 readonly writeFileString: (
362 path: string,
363 data: string,
364 options?: {
365 readonly flag?: OpenFlag | undefined
366 readonly mode?: number | undefined
367 }
368 ) => Effect.Effect<void, PlatformError>
370​
371/**
372 * Represents a file size in bytes using a branded bigint.
373 *
374 * **Details**
375 *
376 * This type ensures type safety when working with file sizes, preventing
377 * accidental mixing of regular numbers with size values. The underlying
378 * bigint allows for handling very large file sizes beyond JavaScript's
379 * number precision limits.
380 *
381 * **Example** (Creating branded file sizes)
382 *
383 * ```ts
384 * import { Effect, FileSystem } from "effect"
385 *
386 * // Create sizes using the Size constructor
387 * const smallFile = FileSystem.Size(1024) // 1 KB
388 * const largeFile = FileSystem.Size(BigInt("9007199254740992")) // Very large
389 *
390 * // Use with file operations
391 * const truncateToSize = Effect.fnUntraced(function*(path: string, size: FileSystem.Size) {
392 * const fs = yield* FileSystem.FileSystem
393 * return yield* fs.truncate(path, size)
394 * })
395 * ```
396 *
397 * @category sizes
398 * @since 4.0.0
399 */
400export type Size = Brand.Branded<bigint, "Size">
401​
402/**
403 * Input type for size parameters that accepts multiple numeric types.
404 *
405 * **Details**
406 *
407 * This union type allows file system operations to accept size values in
408 * different formats for convenience, which are then normalized to the
409 * branded `Size` type internally.
410 *
411 * **Example** (Using size inputs)
412 *
413 * ```ts
414 * import { Effect, FileSystem } from "effect"
415 *
416 * const program = Effect.gen(function*() {
417 * const fs = yield* FileSystem.FileSystem
418 *
419 * // All of these are valid SizeInput values
420 * yield* fs.truncate("file1.txt", 1024) // number
421 * yield* fs.truncate("file2.txt", BigInt(2048)) // bigint
422 * yield* fs.truncate("file3.txt", FileSystem.Size(4096)) // Size
423 * })
424 * ```
425 *
426 * @category sizes
427 * @since 4.0.0
428 */
429export type SizeInput = bigint | number | Size
430​
431/**
432 * Creates a `Size` from various numeric input types.
433 *
434 * **Details**
435 *
436 * Converts numbers, bigints, or existing Size values into a properly
437 * branded Size type. This function handles the conversion and ensures
438 * type safety for file size operations.
439 *
440 * **Example** (Converting size inputs)
441 *
442 * ```ts
443 * import { Effect, FileSystem } from "effect"
444 *
445 * // From number
446 * const size1 = FileSystem.Size(1024)
447 * console.log(typeof size1) // "bigint"
448 *
449 * // From bigint
450 * const size2 = FileSystem.Size(BigInt(2048))
451 *
452 * // From existing Size (identity)
453 * const size3 = FileSystem.Size(size1)
454 *
455 * // Use in file operations
456 * const readChunk = (path: string, chunkSize: number) =>
457 * Effect.gen(function*() {
458 * const fs = yield* FileSystem.FileSystem
459 * return fs.stream(path, {
460 * chunkSize: FileSystem.Size(chunkSize)
461 * })
462 * })
463 * ```
464 *
465 * @category sizes
466 * @since 4.0.0
467 */
468export const Size = (bytes: SizeInput): Size => typeof bytes === "bigint" ? bytes as Size : BigInt(bytes) as Size
469​
470/**
471 * Creates a `Size` representing kilobytes (1024 bytes).
472 *
473 * **Details**
474 *
475 * Converts a number of kilobytes to the equivalent size in bytes.
476 * Uses binary kilobytes (1024 bytes) rather than decimal (1000 bytes).
477 *
478 * **Example** (Creating kibibyte sizes)
479 *
480 * ```ts
481 * import { Effect, FileSystem } from "effect"
482 *
483 * const program = Effect.gen(function*() {
484 * const fs = yield* FileSystem.FileSystem
485 *
486 * // Create a 64 KiB buffer size for streaming
487 * const bufferSize = FileSystem.KiB(64)
488 *
489 * const stream = fs.stream("large-file.txt", {
490 * chunkSize: bufferSize
491 * })
492 *
493 * // Truncate file to 100 KiB
494 * yield* fs.truncate("data.txt", FileSystem.KiB(100))
495 * })
496 * ```
497 *
498 * @category sizes
499 * @since 4.0.0
500 */
501export const KiB = (n: number): Size => Size(n * 1024)
502​
503/**
504 * Creates a `Size` representing mebibytes (1024² bytes).
505 *
506 * **Details**
507 *
508 * Converts a number of mebibytes to the equivalent size in bytes.
509 * Uses binary mebibytes (1,048,576 bytes) rather than decimal megabytes.
510 *
511 * **Example** (Creating mebibyte sizes)
512 *
513 * ```ts
514 * import { Effect, FileSystem } from "effect"
515 *
516 * const program = Effect.gen(function*() {
517 * const fs = yield* FileSystem.FileSystem
518 *
519 * // Set a 10 MiB chunk size for large file operations
520 * const largeChunkSize = FileSystem.MiB(10)
521 *
522 * const stream = fs.stream("video.mp4", {
523 * chunkSize: largeChunkSize
524 * })
525 *
526 * // Check if file is larger than 100 MiB
527 * const stats = yield* fs.stat("archive.zip")
528 * const maxSize = FileSystem.MiB(100)
529 * if (stats.size > maxSize) {
530 * yield* Effect.log("File is very large!")
531 * }
532 * })
533 * ```
534 *
535 * @category sizes
536 * @since 4.0.0
537 */
538export const MiB = (n: number): Size => Size(n * 1024 * 1024)
539​
540/**
541 * Creates a `Size` representing gibibytes (1024³ bytes).
542 *
543 * **Details**
544 *
545 * Converts a number of gibibytes to the equivalent size in bytes.
546 * Uses binary gibibytes (1,073,741,824 bytes) rather than decimal gigabytes.
547 *
548 * **Example** (Creating gibibyte sizes)
549 *
550 * ```ts
551 * import { Effect, FileSystem } from "effect"
552 *
553 * const program = Effect.gen(function*() {
554 * const fs = yield* FileSystem.FileSystem
555 *
556 * // Use GiB values as size thresholds
557 * const maxArchiveSize = FileSystem.GiB(1)
558 * console.log(maxArchiveSize.toString()) // "1073741824"
559 *
560 * const tempFile = yield* fs.makeTempFile({ prefix: "archive-" })
561 * yield* fs.writeFileString(tempFile, "backup data")
562 *
563 * const info = yield* fs.stat(tempFile)
564 * console.log(info.size < maxArchiveSize) // true
565 *
566 * yield* fs.remove(tempFile)
567 * })
568 * ```
569 *
570 * @category sizes
571 * @since 4.0.0
572 */
573export const GiB = (n: number): Size => Size(n * 1024 * 1024 * 1024)
574​
575/**
576 * Creates a `Size` representing tebibytes (1024⁴ bytes).
577 *
578 * **Details**
579 *
580 * Converts a number of tebibytes to the equivalent size in bytes.
581 * Uses binary tebibytes (1,099,511,627,776 bytes) rather than decimal terabytes.
582 *
583 * **Example** (Creating tebibyte sizes)
584 *
585 * ```ts
586 * import { Console, Effect, FileSystem } from "effect"
587 *
588 * const program = Effect.gen(function*() {
589 * const fs = yield* FileSystem.FileSystem
590 *
591 * // Check if we're dealing with very large files
592 * const stats = yield* fs.stat("database-backup.sql")
593 * const oneTiB = FileSystem.TiB(1)
594 *
595 * if (stats.size > oneTiB) {
596 * yield* Console.log("This is a very large database backup!")
597 *
598 * // Use larger chunk sizes for such files
599 * const stream = fs.stream("database-backup.sql", {
600 * chunkSize: FileSystem.MiB(100) // 100 MiB chunks
601 * })
602 * }
603 * })
604 * ```
605 *
606 * @category sizes
607 * @since 4.0.0
608 */
609export const TiB = (n: number): Size => Size(n * 1024 * 1024 * 1024 * 1024)
610​
611const bigint1024 = BigInt(1024)
612const bigintPiB = bigint1024 * bigint1024 * bigint1024 * bigint1024 * bigint1024
613​
614/**
615 * Creates a `Size` representing pebibytes (1024⁵ bytes).
616 *
617 * **Details**
618 *
619 * Converts a number of pebibytes to the equivalent size in bytes.
620 * Uses binary pebibytes (1,125,899,906,842,624 bytes) rather than decimal petabytes.
621 * This function uses BigInt arithmetic to handle the very large numbers involved.
622 *
623 * **Example** (Creating pebibyte sizes)
624 *
625 * ```ts
626 * import { Console, Effect, FileSystem } from "effect"
627 *
628 * const program = Effect.gen(function*() {
629 * const fs = yield* FileSystem.FileSystem
630 *
631 * // For extremely large data processing scenarios
632 * const massiveDataset = FileSystem.PiB(2) // 2 PiB
633 *
634 * // This would typically be used in enterprise/cloud scenarios
635 * yield* Console.log(`Processing ${massiveDataset} bytes of data`)
636 *
637 * // Such large files would require specialized streaming
638 * const stream = fs.stream("massive-dataset.bin", {
639 * chunkSize: FileSystem.GiB(1), // 1 GiB chunks
640 * offset: FileSystem.TiB(100) // Start from 100 TiB offset
641 * })
642 * })
643 * ```
644 *
645 * @category sizes
646 * @since 4.0.0
647 */
648export const PiB = (n: number): Size => Size(BigInt(n) * bigintPiB)
649​
650/**
651 * File open flags that determine how a file is opened and what operations are allowed.
652 *
653 * **Details**
654 *
655 * These flags correspond to standard POSIX file open modes and control the file access
656 * permissions and behavior when opening files.
657 *
658 * - `"r"` - Read-only. File must exist.
659 * - `"r+"` - Read/write. File must exist.
660 * - `"w"` - Write-only. Truncates file to zero length or creates new file.
661 * - `"wx"` - Like 'w' but fails if file exists.
662 * - `"w+"` - Read/write. Truncates file to zero length or creates new file.
663 * - `"wx+"` - Like 'w+' but fails if file exists.
664 * - `"a"` - Write-only. Appends to file or creates new file.
665 * - `"ax"` - Like 'a' but fails if file exists.
666 * - `"a+"` - Read/write. Appends to file or creates new file.
667 * - `"ax+"` - Like 'a+' but fails if file exists.
668 *
669 * **Example** (Opening files with flags)
670 *
671 * ```ts
672 * import { Effect, FileSystem } from "effect"
673 *
674 * const program = Effect.gen(function*() {
675 * const fs = yield* FileSystem.FileSystem
676 *
677 * // Open for reading only
678 * const readFile = yield* fs.open("data.txt", { flag: "r" })
679 *
680 * // Open for writing, truncating existing content
681 * const writeFile = yield* fs.open("output.txt", { flag: "w" })
682 *
683 * // Open for appending
684 * const appendFile = yield* fs.open("log.txt", { flag: "a" })
685 *
686 * // Open for read/write, but fail if file doesn't exist
687 * const editFile = yield* fs.open("config.json", { flag: "r+" })
688 * })
689 * ```
690 *
691 * @category models
692 * @since 4.0.0
693 */
694export type OpenFlag =
695 | "r"
696 | "r+"
697 | "w"
698 | "wx"
699 | "w+"
700 | "wx+"
701 | "a"
702 | "ax"
703 | "a+"
704 | "ax+"
705​
706/**
707 * Service tag for platform file-system operations.
708 *
709 * **When to use**
710 *
711 * Use to access or provide operations for files, directories, permissions,
712 * streams, and sinks through the Effect context.
713 *
714 * **Details**
715 *
716 * This key is used to provide and access the FileSystem service in the Effect context.
717 *
718 * **Example** (Accessing and providing FileSystem)
719 *
720 * ```ts
721 * import { Effect, FileSystem } from "effect"
722 *
723 * // Access the FileSystem service
724 * const program = Effect.gen(function*() {
725 * const fs = yield* FileSystem.FileSystem
726 *
727 * const exists = yield* fs.exists("./data.txt")
728 * if (exists) {
729 * const content = yield* fs.readFileString("./data.txt")
730 * yield* Effect.log("File content:", content)
731 * }
732 * })
733 *
734 * // Provide a custom FileSystem implementation
735 * declare const platformImpl: Omit<
736 * FileSystem.FileSystem,
737 * "exists" | "readFileString" | "stream" | "sink" | "writeFileString"
738 * >
739 * const customFs = FileSystem.make(platformImpl)
740 *
741 * const withCustomFs = Effect.provideService(
742 * program,
743 * FileSystem.FileSystem,
744 * customFs
745 * )
746 * ```
747 *
748 * @category services
749 * @since 4.0.0
750 */
751export const FileSystem: Context.Service<FileSystem, FileSystem> = Context.Service("effect/platform/FileSystem")
752​
753/**
754 * Creates a FileSystem implementation from a partial implementation.
755 *
756 * **When to use**
757 *
758 * Use to build a concrete `FileSystem` service from platform-specific core
759 * operations while deriving the convenience methods that can be implemented
760 * from them.
761 *
762 * **Details**
763 *
764 * This function takes a partial FileSystem implementation and automatically provides
765 * default implementations for `exists`, `readFileString`, `stream`, `sink`, and
766 * `writeFileString` methods based on the provided core methods.
767 *
768 * @see {@link makeNoop} for a testing stub that accepts method overrides without requiring a complete implementation
769 * @see {@link layerNoop} for providing a no-op `FileSystem` as a `Layer` in tests
770 *
771 * @category constructors
772 * @since 4.0.0
773 */
774export const make = (
775 impl: Omit<FileSystem, typeof TypeId | "exists" | "readFileString" | "stream" | "sink" | "writeFileString">
776): FileSystem =>
777 FileSystem.of({
778 ...impl,
779 [TypeId]: TypeId,
780 exists: (path) =>
781 pipe(
782 impl.access(path),
783 Effect.as(true),
784 Effect.catchTag(
785 "PlatformError",
786 (e) => e.reason._tag === "NotFound" ? Effect.succeed(false) : Effect.fail(e)
787 )
788 ),
789 readFileString: (path, encoding) =>
790 Effect.flatMap(impl.readFile(path), (_) =>
791 Effect.try({
792 try: () => new TextDecoder(encoding).decode(_),
793 catch: (cause) =>
794 badArgument({
795 module: "FileSystem",
796 method: "readFileString",
797 description: "invalid encoding",
798 cause
799 })
800 })),
801 stream: Effect.fnUntraced(function*(path, options) {
802 const file = yield* impl.open(path, { flag: "r" })
803 if (options?.offset) {
804 yield* file.seek(options.offset, "start")
805 }
806 const bytesToRead = options?.bytesToRead !== undefined ? Size(options.bytesToRead) : undefined
807 let totalBytesRead = BigInt(0)
808 const chunkSize = Size(options?.chunkSize ?? 64 * 1024)
809 const readChunk = file.readAlloc(chunkSize)
810 return Stream.fromPull(Effect.succeed(
811 Effect.flatMap(
812 Effect.suspend((): Pull.Pull<Option.Option<Uint8Array>, PlatformError> => {
813 if (bytesToRead !== undefined && bytesToRead <= totalBytesRead) {
814 return Cause.done()
815 }
816 return bytesToRead !== undefined && (bytesToRead - totalBytesRead) < chunkSize
817 ? file.readAlloc(bytesToRead - totalBytesRead)
818 : readChunk
819 }),
820 Option.match({
821 onNone: () => Cause.done(),
822 onSome: (buf) => {
823 totalBytesRead += BigInt(buf.length)
824 return Effect.succeed(Arr.of(buf))
825 }
826 })
827 )
828 ))
829 }, Stream.unwrap),
830 sink: (path, options) =>
831 pipe(
832 impl.open(path, { flag: "w", ...options }),
833 Effect.map((file) => Sink.forEach((_: Uint8Array) => file.writeAll(_))),
834 Sink.unwrap
835 ),
836 writeFileString: (path, data, options) =>
837 Effect.flatMap(
838 Effect.try({
839 try: () => new TextEncoder().encode(data),
840 catch: (cause) =>
841 badArgument({
842 module: "FileSystem",
843 method: "writeFileString",
844 description: "could not encode string",
845 cause
846 })
847 }),
848 (_) => impl.writeFile(path, _, options)
849 )
850 })
851​
852const notFound = (method: string, path: string) =>
853 systemError({
854 module: "FileSystem",
855 method,
856 _tag: "NotFound",
857 description: "No such file or directory",
858 pathOrDescriptor: path
859 })
860​
861/**
862 * Creates a stub `FileSystem` implementation for tests.
863 *
864 * **Details**
865 *
866 * By default, `exists` returns `false`, `remove` succeeds, many file operations
867 * fail with `PlatformError` `NotFound`, and temporary-directory/file operations
868 * die as not implemented. Pass method overrides to provide the behavior needed
869 * by a specific test without touching the real file system.
870 *
871 * **Example** (Creating a no-op FileSystem)
872 *
873 * ```ts
874 * import { Effect, FileSystem, PlatformError } from "effect"
875 *
876 * // Create a test filesystem that only allows reading specific files
877 * const testFs = FileSystem.makeNoop({
878 * readFileString: (path) => {
879 * if (path === "test-config.json") {
880 * return Effect.succeed("{\"test\": true}")
881 * }
882 * return Effect.fail(
883 * PlatformError.systemError({
884 * _tag: "NotFound",
885 * module: "FileSystem",
886 * method: "readFileString",
887 * description: "File not found",
888 * pathOrDescriptor: path
889 * })
890 * )
891 * },
892 * exists: (path) => Effect.succeed(path === "test-config.json")
893 * })
894 *
895 * // Use in tests
896 * const program = Effect.gen(function*() {
897 * const content = yield* testFs.readFileString("test-config.json")
898 * // Will succeed with mocked content
899 * })
900 *
901 * // Test with the no-op filesystem
902 * const testProgram = Effect.provideService(
903 * program,
904 * FileSystem.FileSystem,
905 * testFs
906 * )
907 * ```
908 *
909 * @category constructors
910 * @since 4.0.0
911 */
912export const makeNoop = (fileSystem: Partial<FileSystem>): FileSystem =>
913 FileSystem.of({
914 [TypeId]: TypeId,
915 access(path) {
916 return Effect.fail(notFound("access", path))
917 },
918 chmod(path) {
919 return Effect.fail(notFound("chmod", path))
920 },
921 chown(path) {
922 return Effect.fail(notFound("chown", path))
923 },
924 copy(path) {
925 return Effect.fail(notFound("copy", path))
926 },
927 copyFile(path) {
928 return Effect.fail(notFound("copyFile", path))
929 },
930 glob(pattern) {
931 return Effect.fail(notFound("glob", pattern))
932 },
933 exists() {
934 return Effect.succeed(false)
935 },
936 link(path) {
937 return Effect.fail(notFound("link", path))
938 },
939 makeDirectory() {
940 return Effect.die("not implemented")
941 },
942 makeTempDirectory() {
943 return Effect.die("not implemented")
944 },
945 makeTempDirectoryScoped() {
946 return Effect.die("not implemented")
947 },
948 makeTempFile() {
949 return Effect.die("not implemented")
950 },
951 makeTempFileScoped() {
952 return Effect.die("not implemented")
953 },
954 open(path) {
955 return Effect.fail(notFound("open", path))
956 },
957 readDirectory(path) {
958 return Effect.fail(notFound("readDirectory", path))
959 },
960 readFile(path) {
961 return Effect.fail(notFound("readFile", path))
962 },
963 readFileString(path) {
964 return Effect.fail(notFound("readFileString", path))
965 },
966 readLink(path) {
967 return Effect.fail(notFound("readLink", path))
968 },
969 realPath(path) {
970 return Effect.fail(notFound("realPath", path))
971 },
972 remove() {
973 return Effect.void
974 },
975 rename(oldPath) {
976 return Effect.fail(notFound("rename", oldPath))
977 },
978 sink(path) {
979 return Sink.fail(notFound("sink", path))
980 },
981 stat(path) {
982 return Effect.fail(notFound("stat", path))
983 },
984 stream(path) {
985 return Stream.fail(notFound("stream", path))
986 },
987 symlink(fromPath) {
988 return Effect.fail(notFound("symlink", fromPath))
989 },
990 truncate(path) {
991 return Effect.fail(notFound("truncate", path))
992 },
993 utimes(path) {
994 return Effect.fail(notFound("utimes", path))
995 },
996 watch(path) {
997 return Stream.fail(notFound("watch", path))
998 },
999 writeFile(path) {
1000 return Effect.fail(notFound("writeFile", path))
1001 },
1002 writeFileString(path) {
1003 return Effect.fail(notFound("writeFileString", path))
1004 },
1005 ...fileSystem
1006 })
1007​
1008/**
1009 * Creates a Layer that provides a no-op FileSystem implementation for testing.
1011 * **Details**
1013 * This is a convenience function that wraps `makeNoop` in a Layer, making it easy
1014 * to provide the test filesystem to your Effect programs.
1016 * **Example** (Providing a no-op FileSystem layer)
1018 * ```ts
1019 * import { Effect, FileSystem } from "effect"
1021 * // Create a test layer with specific behaviors
1022 * const testLayer = FileSystem.layerNoop({
1023 * readFileString: (path) => Effect.succeed("mocked content"),
1024 * exists: () => Effect.succeed(true)
1025 * })
1027 * const program = Effect.gen(function*() {
1028 * const fs = yield* FileSystem.FileSystem
1029 * const content = yield* fs.readFileString("any-file.txt")
1030 * return content
1031 * })
1033 * // Provide the test layer
1034 * const testProgram = Effect.provide(program, testLayer)
1035 * ```
1037 * @category layers
1038 * @since 4.0.0
1039 */
1040export const layerNoop = (fileSystem: Partial<FileSystem>): Layer.Layer<FileSystem> =>
1041 Layer.succeed(FileSystem)(makeNoop(fileSystem))
1042​
1043/**
1044 * Runtime type identifier attached to `FileSystem.File` handles and used by
1045 * `isFile` to recognize them.
1047 * **Details**
1049 * This marker is part of the runtime representation of file handles. Prefer
1050 * `isFile` when narrowing unknown values.
1052 * @see {@link File} for the open file handle shape that carries this marker
1053 * @see {@link isFile} for the public guard that checks this marker
1055 * @category type IDs
1056 * @since 4.0.0
1057 */
1058export const FileTypeId = "~effect/platform/FileSystem/File"
1059​
1060/**
1061 * Returns `true` if a value is a `File` handle by checking for the
1062 * `FileTypeId` marker.
1064 * **When to use**
1066 * Use when accepting an unknown value and you need to narrow it to a `File`
1067 * before calling file-handle operations.
1069 * **Details**
1071 * This is a structural marker check. It does not validate the marker value or
1072 * the shape of the file handle.
1074 * @see {@link File} for the file-handle interface narrowed by this guard
1075 * @see {@link FileTypeId} for the runtime marker checked by this guard
1077 * @category file
1078 * @since 4.0.0
1079 */
1080export const isFile = (u: unknown): u is File => hasProperty(u, FileTypeId)
1081​
1082/**
1083 * Interface representing an open file handle.
1085 * **Details**
1087 * Provides low-level file operations including reading, writing, seeking,
1088 * and retrieving file information. File handles are automatically managed
1089 * within scoped operations to ensure proper cleanup.
1091 * **Example** (Working with file handles)
1093 * ```ts
1094 * import { Console, Effect, FileSystem } from "effect"
1096 * const program = Effect.gen(function*() {
1097 * const fs = yield* FileSystem.FileSystem
1099 * // Open a file and work with the handle
1100 * yield* Effect.scoped(
1101 * Effect.gen(function*() {
1102 * const file = yield* fs.open("./data.txt", { flag: "r+" })
1104 * // Get file information
1105 * const stats = yield* file.stat
1106 * yield* Console.log(`File size: ${stats.size} bytes`)
1108 * // Read from specific position
1109 * yield* file.seek(10, "start")
1110 * const buffer = new Uint8Array(5)
1111 * const bytesRead = yield* file.read(buffer)
1112 * yield* Console.log(`Read ${bytesRead} bytes:`, buffer)
1114 * // Write data
1115 * const data = new TextEncoder().encode("Hello")
1116 * yield* file.write(data)
1117 * yield* file.sync // Flush to disk
1118 * })
1119 * )
1120 * })
1121 * ```
1123 * @category file
1124 * @since 4.0.0
1125 */
1126export interface File {
1127 readonly [FileTypeId]: typeof FileTypeId
1128 readonly fd: File.Descriptor
1129 readonly stat: Effect.Effect<File.Info, PlatformError>
1130 readonly seek: (offset: SizeInput, from: SeekMode) => Effect.Effect<void>
1131 readonly sync: Effect.Effect<void, PlatformError>
1132 readonly read: (buffer: Uint8Array) => Effect.Effect<Size, PlatformError>
1133 readonly readAlloc: (size: SizeInput) => Effect.Effect<Option.Option<Uint8Array>, PlatformError>
1134 readonly truncate: (length?: SizeInput) => Effect.Effect<void, PlatformError>
1135 readonly write: (buffer: Uint8Array) => Effect.Effect<Size, PlatformError>
1136 readonly writeAll: (buffer: Uint8Array) => Effect.Effect<void, PlatformError>
1138​
1139/**
1140 * Namespace containing types associated with open file handles, including file
1141 * descriptors, entry kinds, and stat information.
1143 * @since 4.0.0
1144 */
1145export declare namespace File {
1146 /**
1147 * Branded type for file descriptors.
1149 * **Details**
1151 * File descriptors are numeric handles used by the operating system
1152 * to identify open files. The branded type ensures type safety.
1154 * @category file
1155 * @since 4.0.0
1156 */
1157 export type Descriptor = Brand.Branded<number, "FileDescriptor">
1158​
1159 /**
1160 * Enumeration of possible file system entry types.
1162 * **Details**
1164 * Represents the different types of entries that can exist in a file system,
1165 * from regular files to special device files and symbolic links.
1167 * @category file
1168 * @since 4.0.0
1169 */
1170 export type Type =
1171 | "File"
1172 | "Directory"
1173 | "SymbolicLink"
1174 | "BlockDevice"
1175 | "CharacterDevice"
1176 | "FIFO"
1177 | "Socket"
1178 | "Unknown"
1179​
1180 /**
1181 * Comprehensive file information structure.
1183 * **Details**
1185 * Contains metadata about a file or directory including type, timestamps,
1186 * permissions, and size information. This structure is returned by file
1187 * stat operations.
1189 * **Example** (Inspecting file information)
1191 * ```ts
1192 * import { Effect, FileSystem, Option } from "effect"
1194 * const program = Effect.gen(function*() {
1195 * const fs = yield* FileSystem.FileSystem
1197 * const path = yield* fs.makeTempFile({ prefix: "info-" })
1198 * yield* fs.writeFileString(path, "hello")
1200 * const info: FileSystem.File.Info = yield* fs.stat(path)
1202 * console.log(`File type: ${info.type}`) // "File type: File"
1203 * console.log(`File size: ${info.size} bytes`) // "File size: 5 bytes"
1204 * console.log(`Mode: ${info.mode.toString(8)}`) // Octal permissions
1206 * // Handle optional timestamps without inventing a fallback date
1207 * const modified = Option.match(info.mtime, {
1208 * onNone: () => "unavailable",
1209 * onSome: (mtime) => mtime.toISOString()
1210 * })
1211 * console.log(`Modified: ${modified}`)
1213 * // Check if it's a regular file
1214 * if (info.type === "File") {
1215 * console.log("Processing regular file...") // "Processing regular file..."
1216 * }
1218 * yield* fs.remove(path)
1219 * })
1220 * ```
1222 * @category file
1223 * @since 4.0.0
1224 */
1225 export interface Info {
1226 readonly type: Type
1227 readonly mtime: Option.Option<Date>
1228 readonly atime: Option.Option<Date>
1229 readonly birthtime: Option.Option<Date>
1230 readonly dev: number
1231 readonly ino: Option.Option<number>
1232 readonly mode: number
1233 readonly nlink: Option.Option<number>
1234 readonly uid: Option.Option<number>
1235 readonly gid: Option.Option<number>
1236 readonly rdev: Option.Option<number>
1237 readonly size: Size
1238 readonly blksize: Option.Option<Size>
1239 readonly blocks: Option.Option<number>
1242​
1243/**
1244 * Creates a `File.Descriptor` from a number.
1246 * **When to use**
1248 * Use to brand an operating-system file descriptor number when implementing a
1249 * `FileSystem` that returns custom `File` handles.
1251 * **Details**
1253 * `File.Descriptor` is a branded integer handle used by operating systems to
1254 * identify open files.
1256 * **Gotchas**
1258 * This constructor is nominal and does not check that the number is an integer
1259 * or that it refers to an open file descriptor.
1261 * @see {@link File.Descriptor} for the branded descriptor type produced by this constructor
1262 * @see {@link File} for file handles that expose a descriptor through `fd`
1264 * @category constructors
1265 * @since 4.0.0
1266 */
1267export const FileDescriptor = Brand.nominal<File.Descriptor>()
1268​
1269/**
1270 * Specifies the reference point for seeking within an open file.
1272 * **When to use**
1274 * Use with `File` handles when positioning the cursor before a read or write
1275 * and the offset must be interpreted from either the start of the file or the
1276 * current cursor.
1278 * **Details**
1280 * - `"start"` seeks from the beginning of the file.
1281 * - `"current"` seeks from the current cursor position.
1283 * @see {@link File} for the open file handle API whose `seek` method consumes this mode
1285 * @category models
1286 * @since 4.0.0
1287 */
1288export type SeekMode = "start" | "current"
1289​
1290/**
1291 * Represents file system events emitted when watching files or directories.
1293 * **When to use**
1295 * Use when consuming file system watch streams and pattern matching on `_tag`
1296 * to handle created, updated, or removed paths.
1298 * **Details**
1300 * The union covers create, update, and remove events. Each event carries the
1301 * reported `path`.
1303 * @see {@link FileSystem} for the service interface whose `watch` operation emits these events
1305 * @category models
1306 * @since 4.0.0
1307 */
1308export type WatchEvent = WatchEvent.Create | WatchEvent.Update | WatchEvent.Remove
1309​
1310/**
1311 * Namespace containing the concrete event shapes emitted by `FileSystem.watch`.
1313 * @since 4.0.0
1314 */
1315export declare namespace WatchEvent {
1316 /**
1317 * Event representing the creation of a new file or directory.
1319 * **Details**
1321 * This event is triggered when a new file or directory is created
1322 * in the watched location.
1324 * @category models
1325 * @since 4.0.0
1326 */
1327 export interface Create {
1328 readonly _tag: "Create"
1329 readonly path: string
1331​
1332 /**
1333 * Event representing the modification of an existing file or directory.
1335 * **Details**
1337 * This event is triggered when an existing file or directory is
1338 * modified in the watched location.
1340 * @category models
1341 * @since 4.0.0
1342 */
1343 export interface Update {
1344 readonly _tag: "Update"
1345 readonly path: string
1347​
1348 /**
1349 * Event representing the deletion of a file or directory.
1351 * **Details**
1353 * This event is triggered when a file or directory is deleted
1354 * from the watched location.
1356 * @category models
1357 * @since 4.0.0
1358 */
1359 export interface Remove {
1360 readonly _tag: "Remove"
1361 readonly path: string
1364​
1365/**
1366 * Service key for file system watch backend implementations.
1368 * **Details**
1370 * This service provides the low-level file watching capabilities that can be
1371 * implemented differently on various platforms (e.g., inotify on Linux,
1372 * FSEvents on macOS, etc.).
1374 * **Example** (Providing a custom watch backend)
1376 * ```ts
1377 * import { Effect, FileSystem, Option, Stream } from "effect"
1379 * // Custom watch backend implementation
1380 * const customWatchBackend = {
1381 * register: (path: string, stat: FileSystem.File.Info) => {
1382 * // Implementation would depend on platform
1383 * return Option.some(Stream.empty) // Placeholder implementation
1384 * }
1385 * }
1387 * // Provide custom watch backend
1388 * const program = Effect.gen(function*() {
1389 * const fs = yield* FileSystem.FileSystem
1391 * // File watching will use the custom backend
1392 * const watcher = fs.watch("./directory")
1393 * })
1395 * const withCustomBackend = Effect.provideService(
1396 * program,
1397 * FileSystem.WatchBackend,
1398 * customWatchBackend
1399 * )
1400 * ```
1402 * @category file watcher
1403 * @since 4.0.0
1404 */
1405export class WatchBackend extends Context.Service<WatchBackend, {
1406 readonly register: (path: string, stat: File.Info) => Option.Option<Stream.Stream<WatchEvent, PlatformError>>
1407}>()("effect/platform/FileSystem/WatchBackend") {}