diff --git a/packages/effect/src/.index.ts b/packages/effect/src/.index.ts new file mode 100644 index 0000000000..c12c6cf5c6 --- /dev/null +++ b/packages/effect/src/.index.ts @@ -0,0 +1,30 @@ +/** + * @since 2.0.0 + */ + +export { + /** + * @since 2.0.0 + */ + absurd, + /** + * @since 2.0.0 + */ + flow, + /** + * @since 2.0.0 + */ + hole, + /** + * @since 2.0.0 + */ + identity, + /** + * @since 2.0.0 + */ + pipe, + /** + * @since 2.0.0 + */ + unsafeCoerce +} from "./Function.js" diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index a46c98d814..f27567cd16 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -299,3 +299,36 @@ export interface ExceededCapacityError extends YieldableError { * @category errors */ export const ExceededCapacityError: new(message?: string) => ExceededCapacityError = effect.ExceededCapacityError + +/** + * @since 4.0.0 + * @category errors + */ +export const UnknownErrorTypeId: unique symbol = effect.UnknownErrorTypeId + +/** + * @since 4.0.0 + * @category errors + */ +export type UnknownErrorTypeId = typeof UnknownErrorTypeId + +/** + * @since 4.0.0 + * @category errors + */ +export const isUnknownError: (u: unknown) => u is UnknownError = effect.isUnknownError + +/** + * @since 4.0.0 + * @category errors + */ +export interface UnknownError extends YieldableError { + readonly [UnknownErrorTypeId]: UnknownErrorTypeId + readonly _tag: "UnknownError" +} + +/** + * @since 4.0.0 + * @category errors + */ +export const UnknownError: new(message?: string) => UnknownError = effect.UnknownError diff --git a/packages/effect/src/Channel.ts b/packages/effect/src/Channel.ts index bcadfbb0bc..626e9b729f 100644 --- a/packages/effect/src/Channel.ts +++ b/packages/effect/src/Channel.ts @@ -335,7 +335,7 @@ export const acquireRelease: { self: Effect.Effect, release: (z: Z, e: Exit.Exit) => Effect.Effect ): Channel => - unwrapScoped(Effect.map( + unwrap(Effect.map( Effect.acquireRelease(self, release), succeed ))) @@ -425,6 +425,14 @@ export const fromIterableArray = ( */ export const succeed = (value: A): Channel => fromEffect(Effect.succeed(value)) +/** + * Writes a single value to the channel. + * + * @since 4.0.0 + * @category constructors + */ +export const end = (value: A): Channel => fromPull(Effect.succeed(Pull.halt(value))) + /** * Writes a single value to the channel. * @@ -447,7 +455,43 @@ export const empty: Channel = fromPull(Effect.succeed(Pull.haltVoid)) * @since 2.0.0 * @category constructors */ -export const never: Channel = fromPull(Effect.succeed(Effect.never)) +export const never: Channel = fromPull(Effect.succeed(Effect.never)) + +/** + * Constructs a channel that fails immediately with the specified error. + * + * @since 2.0.0 + * @category constructors + */ +export const fail = (error: E): Channel => fromPull(Effect.fail(error)) + +/** + * Constructs a channel that succeeds immediately with the specified lazily + * evaluated value. + * + * @since 2.0.0 + * @category constructors + */ +export const failSync = (evaluate: LazyArg): Channel => fromPull(Effect.failSync(evaluate)) + +/** + * Constructs a channel that fails immediately with the specified `Cause`. + * + * @since 2.0.0 + * @category constructors + */ +export const failCause = (cause: Cause.Cause): Channel => fromPull(Effect.failCause(cause)) + +/** + * Constructs a channel that succeeds immediately with the specified lazily + * evaluated `Cause`. + * + * @since 2.0.0 + * @category constructors + */ +export const failCauseSync = ( + evaluate: LazyArg> +): Channel => fromPull(Effect.failCauseSync(evaluate)) /** * Use an effect to write a single value to the channel. @@ -522,7 +566,7 @@ export const fromSubscriptionArray = ( */ export const fromPubSub = ( pubsub: PubSub.PubSub -): Channel => unwrapScoped(Effect.map(PubSub.subscribe(pubsub), fromSubscription)) +): Channel => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscription)) /** * Create a channel from a PubSub @@ -534,7 +578,7 @@ export const fromPubSubArray = ( pubsub: PubSub.PubSub, chunkSize = DefaultChunkSize ): Channel> => - unwrapScoped(Effect.map(PubSub.subscribe(pubsub), (sub) => fromSubscriptionArray(sub, chunkSize))) + unwrap(Effect.map(PubSub.subscribe(pubsub), (sub) => fromSubscriptionArray(sub, chunkSize))) /** * Maps the output of this channel using the specified function. @@ -1611,23 +1655,6 @@ export const pipeToOrFail: { ) ) -/** - * Constructs a `Channel` from an effect that will result in a `Channel` if - * successful. - * - * @since 2.0.0 - * @category constructors - */ -export const unwrap = ( - channel: Effect.Effect, E, R> -): Channel => - fromTransform((upstream, scope) => - Effect.flatMap( - channel, - (channel) => toTransform(channel)(upstream, scope) - ) - ) - /** * Constructs a `Channel` from a scoped effect that will result in a * `Channel` if successful. @@ -1635,7 +1662,7 @@ export const unwrap = ( +export const unwrap = ( channel: Effect.Effect, E, R> ): Channel | R2> => fromTransform((upstream, scope) => diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 9daac255e7..9da2a8fb40 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -611,6 +611,76 @@ export const promise: ( evaluate: (signal: AbortSignal) => PromiseLike ) => Effect = internal.promise +/** + * Creates an `Effect` that represents an asynchronous computation that might + * fail. + * + * **When to Use** + * + * In situations where you need to perform asynchronous operations that might + * fail, such as fetching data from an API, you can use the `tryPromise` + * constructor. This constructor is designed to handle operations that could + * throw exceptions by capturing those exceptions and transforming them into + * manageable errors. + * + * **Error Handling** + * + * There are two ways to handle errors with `tryPromise`: + * + * 1. If you don't provide a `catch` function, the error is caught and the + * effect fails with an `UnknownError`. + * 2. If you provide a `catch` function, the error is caught and the `catch` + * function maps it to an error of type `E`. + * + * **Interruptions** + * + * An optional `AbortSignal` can be provided to allow for interruption of the + * wrapped `Promise` API. + * + * **Example** (Fetching a TODO Item) + * + * ```ts + * import { Effect } from "effect" + * + * const getTodo = (id: number) => + * // Will catch any errors and propagate them as UnknownError + * Effect.tryPromise(() => + * fetch(`https://jsonplaceholder.typicode.com/todos/${id}`) + * ) + * + * // ┌─── Effect + * // ▼ + * const program = getTodo(1) + * ``` + * + * **Example** (Custom Error Handling) + * + * ```ts + * import { Effect } from "effect" + * + * const getTodo = (id: number) => + * Effect.tryPromise({ + * try: () => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`), + * // remap the error + * catch: (unknown) => new Error(`something went wrong ${unknown}`) + * }) + * + * // ┌─── Effect + * // ▼ + * const program = getTodo(1) + * ``` + * + * @see {@link promise} if the effectful computation is asynchronous and does not throw errors. + * + * @since 2.0.0 + * @category Creating Effects + */ +export const tryPromise: ( + options: + | { readonly try: (signal: AbortSignal) => PromiseLike; readonly catch: (error: unknown) => E } + | ((signal: AbortSignal) => PromiseLike) +) => Effect = internal.tryPromise + /** * Creates an `Effect` that always succeeds with a given value. * @@ -1021,7 +1091,7 @@ export { * There are two ways to handle errors with `try`: * * 1. If you don't provide a `catch` function, the error is caught and the - * effect fails with an `UnknownException`. + * effect fails with an `UnknownError`. * 2. If you provide a `catch` function, the error is caught and the `catch` * function maps it to an error of type `E`. * diff --git a/packages/effect/src/Effectify.ts b/packages/effect/src/Effectify.ts new file mode 100644 index 0000000000..7b0e2c3094 --- /dev/null +++ b/packages/effect/src/Effectify.ts @@ -0,0 +1,271 @@ +/** + * @since 1.0.0 + */ +import * as Effect from "./Effect.js" + +interface Callback { + (err: E, a?: A): void +} + +type ArgsWithCallback, E, A> = [...args: Args, cb: Callback] + +type WithoutNull = unknown extends A ? void : Exclude + +/** + * Converts a callback-based function to a function that returns an `Effect`. + * + * @since 1.0.0 + */ +export type Effectify = T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + (...args: ArgsWithCallback): infer _R9 + (...args: ArgsWithCallback): infer _R10 +} ? { + (...args: Args1): Effect.Effect, E> + (...args: Args2): Effect.Effect, E> + (...args: Args3): Effect.Effect, E> + (...args: Args4): Effect.Effect, E> + (...args: Args5): Effect.Effect, E> + (...args: Args6): Effect.Effect, E> + (...args: Args7): Effect.Effect, E> + (...args: Args8): Effect.Effect, E> + (...args: Args9): Effect.Effect, E> + (...args: Args10): Effect.Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + (...args: ArgsWithCallback): infer _R9 + } ? { + (...args: Args1): Effect.Effect, E> + (...args: Args2): Effect.Effect, E> + (...args: Args3): Effect.Effect, E> + (...args: Args4): Effect.Effect, E> + (...args: Args5): Effect.Effect, E> + (...args: Args6): Effect.Effect, E> + (...args: Args7): Effect.Effect, E> + (...args: Args8): Effect.Effect, E> + (...args: Args9): Effect.Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + } ? { + (...args: Args1): Effect.Effect, E> + (...args: Args2): Effect.Effect, E> + (...args: Args3): Effect.Effect, E> + (...args: Args4): Effect.Effect, E> + (...args: Args5): Effect.Effect, E> + (...args: Args6): Effect.Effect, E> + (...args: Args7): Effect.Effect, E> + (...args: Args8): Effect.Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + } ? { + (...args: Args1): Effect.Effect, E> + (...args: Args2): Effect.Effect, E> + (...args: Args3): Effect.Effect, E> + (...args: Args4): Effect.Effect, E> + (...args: Args5): Effect.Effect, E> + (...args: Args6): Effect.Effect, E> + (...args: Args7): Effect.Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + } ? { + (...args: Args1): Effect.Effect, E> + (...args: Args2): Effect.Effect, E> + (...args: Args3): Effect.Effect, E> + (...args: Args4): Effect.Effect, E> + (...args: Args5): Effect.Effect, E> + (...args: Args6): Effect.Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + } ? { + (...args: Args1): Effect.Effect, E> + (...args: Args2): Effect.Effect, E> + (...args: Args3): Effect.Effect, E> + (...args: Args4): Effect.Effect, E> + (...args: Args5): Effect.Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + } ? { + (...args: Args1): Effect.Effect, E> + (...args: Args2): Effect.Effect, E> + (...args: Args3): Effect.Effect, E> + (...args: Args4): Effect.Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + } ? { + (...args: Args1): Effect.Effect, E> + (...args: Args2): Effect.Effect, E> + (...args: Args3): Effect.Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + } ? { + (...args: Args1): Effect.Effect, E> + (...args: Args2): Effect.Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + } ? { + (...args: Args1): Effect.Effect, E> + } + : never + +/** + * @category util + * @since 1.0.0 + */ +export type EffectifyError = T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + (...args: ArgsWithCallback): infer _R9 + (...args: ArgsWithCallback): infer _R10 +} ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + (...args: ArgsWithCallback): infer _R9 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + } ? NonNullable + : never + +/** + * @since 1.0.0 + */ +export const effectify: { + ) => any>(fn: F): Effectify> + ) => any, E>( + fn: F, + onError: (error: EffectifyError, args: Parameters) => E + ): Effectify + ) => any, E, E2>( + fn: F, + onError: (error: EffectifyError, args: Parameters) => E, + onSyncError: (error: unknown, args: Parameters) => E2 + ): Effectify +} = + ((fn: Function, onError?: (e: any, args: any) => any, onSyncError?: (e: any, args: any) => any) => + (...args: Array) => + Effect.callback((resume) => { + try { + fn(...args, (err: Error | null, result: A) => { + if (err) { + resume(Effect.fail(onError ? onError(err, args) : err)) + } else { + resume(Effect.succeed(result)) + } + }) + } catch (err) { + resume(onSyncError ? Effect.fail(onSyncError(err, args)) : Effect.die(err)) + } + })) as any diff --git a/packages/effect/src/FileSystem.ts b/packages/effect/src/FileSystem.ts new file mode 100644 index 0000000000..5315674c4a --- /dev/null +++ b/packages/effect/src/FileSystem.ts @@ -0,0 +1,805 @@ +/** + * @since 1.0.0 + */ +import * as Arr from "effect/Array" +import * as Brand from "effect/Brand" +import type { Tag } from "effect/Context" +import * as Context from "effect/Context" +import * as Data from "effect/Data" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Option from "effect/Option" +import * as Pull from "effect/Pull" +import type { Scope } from "effect/Scope" +import * as Sink from "effect/Sink" +import * as Stream from "effect/Stream" +import { pipe } from "./Function.js" +import type { PlatformError } from "./PlatformError.js" +import { BadArgument, SystemError } from "./PlatformError.js" + +/** + * @since 1.0.0 + * @category model + */ +export interface FileSystem { + /** + * Check if a file can be accessed. + * You can optionally specify the level of access to check for. + */ + readonly access: ( + path: string, + options?: AccessFileOptions + ) => Effect.Effect + /** + * Copy a file or directory from `fromPath` to `toPath`. + * + * Equivalent to `cp -r`. + */ + readonly copy: ( + fromPath: string, + toPath: string, + options?: CopyOptions + ) => Effect.Effect + /** + * Copy a file from `fromPath` to `toPath`. + */ + readonly copyFile: ( + fromPath: string, + toPath: string + ) => Effect.Effect + /** + * Change the permissions of a file. + */ + readonly chmod: ( + path: string, + mode: number + ) => Effect.Effect + /** + * Change the owner and group of a file. + */ + readonly chown: ( + path: string, + uid: number, + gid: number + ) => Effect.Effect + /** + * Check if a path exists. + */ + readonly exists: ( + path: string + ) => Effect.Effect + /** + * Create a hard link from `fromPath` to `toPath`. + */ + readonly link: ( + fromPath: string, + toPath: string + ) => Effect.Effect + /** + * Create a directory at `path`. You can optionally specify the mode and + * whether to recursively create nested directories. + */ + readonly makeDirectory: ( + path: string, + options?: MakeDirectoryOptions + ) => Effect.Effect + /** + * Create a temporary directory. + * + * By default the directory will be created inside the system's default + * temporary directory, but you can specify a different location by setting + * the `directory` option. + * + * You can also specify a prefix for the directory name by setting the + * `prefix` option. + */ + readonly makeTempDirectory: ( + options?: MakeTempDirectoryOptions + ) => Effect.Effect + /** + * Create a temporary directory inside a scope. + * + * Functionally equivalent to `makeTempDirectory`, but the directory will be + * automatically deleted when the scope is closed. + */ + readonly makeTempDirectoryScoped: ( + options?: MakeTempDirectoryOptions + ) => Effect.Effect + /** + * Create a temporary file. + * The directory creation is functionally equivalent to `makeTempDirectory`. + * The file name will be a randomly generated string. + */ + readonly makeTempFile: ( + options?: MakeTempFileOptions + ) => Effect.Effect + /** + * Create a temporary file inside a scope. + * + * Functionally equivalent to `makeTempFile`, but the file will be + * automatically deleted when the scope is closed. + */ + readonly makeTempFileScoped: ( + options?: MakeTempFileOptions + ) => Effect.Effect + /** + * Open a file at `path` with the specified `options`. + * + * The file handle will be automatically closed when the scope is closed. + */ + readonly open: ( + path: string, + options?: OpenFileOptions + ) => Effect.Effect + /** + * List the contents of a directory. + * + * You can recursively list the contents of nested directories by setting the + * `recursive` option. + */ + readonly readDirectory: ( + path: string, + options?: ReadDirectoryOptions + ) => Effect.Effect, PlatformError> + /** + * Read the contents of a file. + */ + readonly readFile: ( + path: string + ) => Effect.Effect + /** + * Read the contents of a file. + */ + readonly readFileString: ( + path: string, + encoding?: string + ) => Effect.Effect + /** + * Read the destination of a symbolic link. + */ + readonly readLink: ( + path: string + ) => Effect.Effect + /** + * Resolve a path to its canonicalized absolute pathname. + */ + readonly realPath: ( + path: string + ) => Effect.Effect + /** + * Remove a file or directory. + */ + readonly remove: ( + path: string, + options?: RemoveOptions + ) => Effect.Effect + /** + * Rename a file or directory. + */ + readonly rename: ( + oldPath: string, + newPath: string + ) => Effect.Effect + /** + * Create a writable `Sink` for the specified `path`. + */ + readonly sink: ( + path: string, + options?: SinkOptions + ) => Sink.Sink + /** + * Get information about a file at `path`. + */ + readonly stat: ( + path: string + ) => Effect.Effect + /** + * Create a readable `Stream` for the specified `path`. + * + * Changing the `bufferSize` option will change the internal buffer size of + * the stream. It defaults to `4`. + * + * The `chunkSize` option will change the size of the chunks emitted by the + * stream. It defaults to 64kb. + * + * Changing `offset` and `bytesToRead` will change the offset and the number + * of bytes to read from the file. + */ + readonly stream: ( + path: string, + options?: StreamOptions + ) => Stream.Stream + /** + * Create a symbolic link from `fromPath` to `toPath`. + */ + readonly symlink: ( + fromPath: string, + toPath: string + ) => Effect.Effect + /** + * Truncate a file to a specified length. If the `length` is not specified, + * the file will be truncated to length `0`. + */ + readonly truncate: ( + path: string, + length?: SizeInput + ) => Effect.Effect + /** + * Change the file system timestamps of the file at `path`. + */ + readonly utimes: ( + path: string, + atime: Date | number, + mtime: Date | number + ) => Effect.Effect + /** + * Watch a directory or file for changes + */ + readonly watch: (path: string) => Stream.Stream + /** + * Write data to a file at `path`. + */ + readonly writeFile: ( + path: string, + data: Uint8Array, + options?: WriteFileOptions + ) => Effect.Effect + /** + * Write a string to a file at `path`. + */ + readonly writeFileString: ( + path: string, + data: string, + options?: WriteFileStringOptions + ) => Effect.Effect +} + +/** + * Represents a size in bytes. + * + * @since 1.0.0 + * @category sizes + */ +export type Size = Brand.Branded + +/** + * Represents a size in bytes. + * + * @since 1.0.0 + * @category sizes + */ +export type SizeInput = bigint | number | Size + +/** + * @since 1.0.0 + * @category sizes + */ +export const Size = (bytes: SizeInput): Size => typeof bytes === "bigint" ? bytes as Size : BigInt(bytes) as Size + +/** + * @since 1.0.0 + * @category sizes + */ +export const KiB = (n: number): Size => Size(n * 1024) + +/** + * @since 1.0.0 + * @category sizes + */ +export const MiB = (n: number): Size => Size(n * 1024 * 1024) + +/** + * @since 1.0.0 + * @category sizes + */ +export const GiB = (n: number): Size => Size(n * 1024 * 1024 * 1024) + +/** + * @since 1.0.0 + * @category sizes + */ +export const TiB = (n: number): Size => Size(n * 1024 * 1024 * 1024 * 1024) + +const bigint1024 = BigInt(1024) +const bigintPiB = bigint1024 * bigint1024 * bigint1024 * bigint1024 * bigint1024 + +/** + * @since 1.0.0 + * @category sizes + */ +export const PiB = (n: number): Size => Size(BigInt(n) * bigintPiB) + +/** + * @since 1.0.0 + * @category model + */ +export type OpenFlag = + | "r" + | "r+" + | "w" + | "wx" + | "w+" + | "wx+" + | "a" + | "ax" + | "a+" + | "ax+" + +/** + * @since 1.0.0 + * @category options + */ +export interface AccessFileOptions { + readonly ok?: boolean + readonly readable?: boolean + readonly writable?: boolean +} + +/** + * @since 1.0.0 + * @category options + */ +export interface MakeDirectoryOptions { + readonly recursive?: boolean + readonly mode?: number +} + +/** + * @since 1.0.0 + * @category options + */ +export interface CopyOptions { + readonly overwrite?: boolean + readonly preserveTimestamps?: boolean +} + +/** + * @since 1.0.0 + * @category options + */ +export interface MakeTempDirectoryOptions { + readonly directory?: string + readonly prefix?: string +} + +/** + * @since 1.0.0 + * @category options + */ +export interface MakeTempFileOptions { + readonly directory?: string + readonly prefix?: string +} + +/** + * @since 1.0.0 + * @category options + */ +export interface OpenFileOptions { + readonly flag?: OpenFlag + readonly mode?: number +} + +/** + * @since 1.0.0 + * @category options + */ +export interface ReadDirectoryOptions { + readonly recursive?: boolean +} + +/** + * @since 1.0.0 + * @category options + */ +export interface RemoveOptions { + /** + * When `true`, you can recursively remove nested directories. + */ + readonly recursive?: boolean + /** + * When `true`, exceptions will be ignored if `path` does not exist. + */ + readonly force?: boolean +} + +/** + * @since 1.0.0 + * @category options + */ +export interface SinkOptions extends OpenFileOptions {} + +/** + * @since 1.0.0 + * @category options + */ +export interface StreamOptions { + readonly bytesToRead?: SizeInput + readonly chunkSize?: SizeInput + readonly offset?: SizeInput +} + +/** + * @since 1.0.0 + * @category options + */ +export interface WriteFileOptions { + readonly flag?: OpenFlag + readonly mode?: number +} + +/** + * @since 1.0.0 + * @category options + */ +export interface WriteFileStringOptions { + readonly flag?: OpenFlag + readonly mode?: number +} + +/** + * @since 1.0.0 + * @category tag + */ +export const FileSystem: Tag = Context.GenericTag("effect/FileSystem") + +/** + * @since 1.0.0 + * @category constructor + */ +export const make = ( + impl: Omit +): FileSystem => + FileSystem.of({ + ...impl, + exists: (path) => + pipe( + impl.access(path), + Effect.as(true), + Effect.catchTag("SystemError", (e) => e.reason === "NotFound" ? Effect.succeed(false) : Effect.fail(e)) + ), + readFileString: (path, encoding) => + Effect.flatMap(impl.readFile(path), (_) => + Effect.try({ + try: () => new TextDecoder(encoding).decode(_), + catch: () => + BadArgument({ + module: "FileSystem", + method: "readFileString", + message: "invalid encoding" + }) + })), + stream: (path, options) => + Stream.unwrap( + Effect.gen(function*() { + const file = yield* impl.open(path, { flag: "r" }) + if (options?.offset) { + yield* file.seek(options.offset, "start") + } + const bytesToRead = options?.bytesToRead !== undefined ? Size(options.bytesToRead) : undefined + let totalBytesRead = BigInt(0) + const chunkSize = Size(options?.chunkSize ?? 64 * 1024) + return Stream.fromPull(Effect.succeed( + Effect.flatMap( + Effect.suspend((): Pull.Pull, PlatformError> => { + if (bytesToRead !== undefined && bytesToRead <= totalBytesRead) { + return Pull.haltVoid + } + const toRead = bytesToRead !== undefined && (bytesToRead - totalBytesRead) < chunkSize + ? bytesToRead - totalBytesRead + : chunkSize + return file.readAlloc(toRead) + }), + Option.match({ + onNone: () => Pull.haltVoid, + onSome: (buf) => { + totalBytesRead += BigInt(buf.length) + return Effect.succeed(Arr.of(buf)) + } + }) + ) + )) + }) + ), + sink: (path, options) => + pipe( + impl.open(path, { flag: "w", ...options }), + Effect.map((file) => Sink.forEach((_: Uint8Array) => file.writeAll(_))), + Sink.unwrap + ), + writeFileString: (path, data, options) => + Effect.flatMap( + Effect.try({ + try: () => new TextEncoder().encode(data), + catch: () => + BadArgument({ + module: "FileSystem", + method: "writeFileString", + message: "could not encode string" + }) + }), + (_) => impl.writeFile(path, _, options) + ) + }) + +const notFound = (method: string, path: string) => + SystemError({ + module: "FileSystem", + method, + reason: "NotFound", + message: "No such file or directory", + pathOrDescriptor: path + }) + +/** + * Create a no-op file system that can be used for testing. + * + * @since 1.0.0 + * @category constructor + */ +export const makeNoop = (fileSystem: Partial): FileSystem => + FileSystem.of({ + access(path) { + return Effect.fail(notFound("access", path)) + }, + chmod(path) { + return Effect.fail(notFound("chmod", path)) + }, + chown(path) { + return Effect.fail(notFound("chown", path)) + }, + copy(path) { + return Effect.fail(notFound("copy", path)) + }, + copyFile(path) { + return Effect.fail(notFound("copyFile", path)) + }, + exists() { + return Effect.succeed(false) + }, + link(path) { + return Effect.fail(notFound("link", path)) + }, + makeDirectory() { + return Effect.die("not implemented") + }, + makeTempDirectory() { + return Effect.die("not implemented") + }, + makeTempDirectoryScoped() { + return Effect.die("not implemented") + }, + makeTempFile() { + return Effect.die("not implemented") + }, + makeTempFileScoped() { + return Effect.die("not implemented") + }, + open(path) { + return Effect.fail(notFound("open", path)) + }, + readDirectory(path) { + return Effect.fail(notFound("readDirectory", path)) + }, + readFile(path) { + return Effect.fail(notFound("readFile", path)) + }, + readFileString(path) { + return Effect.fail(notFound("readFileString", path)) + }, + readLink(path) { + return Effect.fail(notFound("readLink", path)) + }, + realPath(path) { + return Effect.fail(notFound("realPath", path)) + }, + remove() { + return Effect.void + }, + rename(oldPath) { + return Effect.fail(notFound("rename", oldPath)) + }, + sink(path) { + return Sink.fail(notFound("sink", path)) + }, + stat(path) { + return Effect.fail(notFound("stat", path)) + }, + stream(path) { + return Stream.fail(notFound("stream", path)) + }, + symlink(fromPath) { + return Effect.fail(notFound("symlink", fromPath)) + }, + truncate(path) { + return Effect.fail(notFound("truncate", path)) + }, + utimes(path) { + return Effect.fail(notFound("utimes", path)) + }, + watch(path) { + return Stream.fail(notFound("watch", path)) + }, + writeFile(path) { + return Effect.fail(notFound("writeFile", path)) + }, + writeFileString(path) { + return Effect.fail(notFound("writeFileString", path)) + }, + ...fileSystem + }) + +/** + * Create a no-op file system that can be used for testing. + * + * @since 1.0.0 + * @category layers + */ +export const layerNoop = (fileSystem: Partial): Layer.Layer => + Layer.succeed(FileSystem, makeNoop(fileSystem)) + +/** + * @since 1.0.0 + * @category type id + */ +export const FileTypeId: unique symbol = Symbol.for( + "effect/FileSystem/File" +) + +/** + * @since 1.0.0 + * @category type id + */ +export type FileTypeId = typeof FileTypeId + +/** + * @since 1.0.0 + * @category guard + */ +export const isFile = (u: unknown): u is File => typeof u === "object" && u !== null && FileTypeId in u + +/** + * @since 1.0.0 + * @category model + */ +export interface File { + readonly [FileTypeId]: FileTypeId + readonly fd: File.Descriptor + readonly stat: Effect.Effect + readonly seek: (offset: SizeInput, from: SeekMode) => Effect.Effect + readonly sync: Effect.Effect + readonly read: (buffer: Uint8Array) => Effect.Effect + readonly readAlloc: (size: SizeInput) => Effect.Effect, PlatformError> + readonly truncate: (length?: SizeInput) => Effect.Effect + readonly write: (buffer: Uint8Array) => Effect.Effect + readonly writeAll: (buffer: Uint8Array) => Effect.Effect +} + +/** + * @since 1.0.0 + */ +export declare namespace File { + /** + * @since 1.0.0 + * @category model + */ + export type Descriptor = Brand.Branded + + /** + * @since 1.0.0 + * @category model + */ + export type Type = + | "File" + | "Directory" + | "SymbolicLink" + | "BlockDevice" + | "CharacterDevice" + | "FIFO" + | "Socket" + | "Unknown" + + /** + * @since 1.0.0 + * @category model + */ + export interface Info { + readonly type: Type + readonly mtime: Option.Option + readonly atime: Option.Option + readonly birthtime: Option.Option + readonly dev: number + readonly ino: Option.Option + readonly mode: number + readonly nlink: Option.Option + readonly uid: Option.Option + readonly gid: Option.Option + readonly rdev: Option.Option + readonly size: Size + readonly blksize: Option.Option + readonly blocks: Option.Option + } +} + +/** + * @since 1.0.0 + * @category constructor + */ +export const FileDescriptor = Brand.nominal() + +/** + * @since 1.0.0 + * @category model + */ +export type SeekMode = "start" | "current" + +/** + * @since 1.0.0 + * @category model + */ +export type WatchEvent = WatchEvent.Create | WatchEvent.Update | WatchEvent.Remove + +/** + * @since 1.0.0 + * @category model + */ +export declare namespace WatchEvent { + /** + * @since 1.0.0 + * @category model + */ + export interface Create { + readonly _tag: "Create" + readonly path: string + } + + /** + * @since 1.0.0 + * @category model + */ + export interface Update { + readonly _tag: "Update" + readonly path: string + } + + /** + * @since 1.0.0 + * @category model + */ + export interface Remove { + readonly _tag: "Remove" + readonly path: string + } +} + +/** + * @since 1.0.0 + * @category constructor + */ +export const WatchEventCreate: Data.Case.Constructor = Data.tagged( + "Create" +) + +/** + * @since 1.0.0 + * @category constructor + */ +export const WatchEventUpdate: Data.Case.Constructor = Data.tagged( + "Update" +) + +/** + * @since 1.0.0 + * @category constructor + */ +export const WatchEventRemove: Data.Case.Constructor = Data.tagged( + "Remove" +) + +/** + * @since 1.0.0 + * @category file watcher + */ +export class WatchBackend extends Context.Tag Option.Option> +}>()("effect/FileSystem/WatchBackend") {} diff --git a/packages/effect/src/PlatformError.ts b/packages/effect/src/PlatformError.ts new file mode 100644 index 0000000000..8fe910823a --- /dev/null +++ b/packages/effect/src/PlatformError.ts @@ -0,0 +1,131 @@ +/** + * @since 4.0.0 + */ +import type * as Cause from "effect/Cause" +import * as Data from "effect/Data" +import * as Predicate from "effect/Predicate" +import type { Simplify } from "effect/Types" + +/** + * @since 4.0.0 + * @category type id + */ +export const PlatformErrorTypeId: unique symbol = Symbol.for("effect/PlatformError") + +/** + * @since 4.0.0 + * @category type id + */ +export type PlatformErrorTypeId = typeof PlatformErrorTypeId + +/** + * @since 4.0.0 + * @category refinements + */ +export const isPlatformError = (u: unknown): u is PlatformError => Predicate.hasProperty(u, PlatformErrorTypeId) + +/** + * @since 4.0.0 + * @category error + */ +export type PlatformError = BadArgument | SystemError + +/** + * @since 4.0.0 + * @category error + */ +export const TypeIdError = ( + typeId: TypeId, + tag: Tag +): new>( + args: Simplify +) => + & Cause.YieldableError + & Record + & { readonly _tag: Tag } + & Readonly => +{ + class Base extends Data.Error<{}> { + readonly _tag = tag + } + ;(Base.prototype as any)[typeId] = typeId + ;(Base.prototype as any).name = tag + return Base as any +} + +/** + * @since 4.0.0 + */ +export declare namespace PlatformError { + /** + * @since 4.0.0 + * @category models + */ + export interface Base { + readonly [PlatformErrorTypeId]: typeof PlatformErrorTypeId + readonly _tag: string + readonly module: "Clipboard" | "Command" | "FileSystem" | "KeyValueStore" | "Path" | "Stream" | "Terminal" + readonly method: string + readonly message: string + } + + /** + * @since 4.0.0 + */ + export type ProvidedFields = PlatformErrorTypeId | "_tag" +} + +const make = (tag: A["_tag"]) => (props: Omit): A => + Data.struct({ + [PlatformErrorTypeId]: PlatformErrorTypeId, + _tag: tag, + ...props + } as A) + +/** + * @since 4.0.0 + * @category error + */ +export interface BadArgument extends PlatformError.Base { + readonly _tag: "BadArgument" +} + +/** + * @since 4.0.0 + * @category error + */ +export const BadArgument: (props: Omit) => BadArgument = make("BadArgument") + +/** + * @since 4.0.0 + * @category model + */ +export type SystemErrorReason = + | "AlreadyExists" + | "BadResource" + | "Busy" + | "InvalidData" + | "NotFound" + | "PermissionDenied" + | "TimedOut" + | "UnexpectedEof" + | "Unknown" + | "WouldBlock" + | "WriteZero" + +/** + * @since 4.0.0 + * @category models + */ +export interface SystemError extends PlatformError.Base { + readonly _tag: "SystemError" + readonly reason: SystemErrorReason + readonly syscall?: string | undefined + readonly pathOrDescriptor: string | number +} + +/** + * @since 4.0.0 + * @category error + */ +export const SystemError: (props: Omit) => SystemError = make("SystemError") diff --git a/packages/effect/src/Sink.ts b/packages/effect/src/Sink.ts index 9a13ecf3ee..65be176c0b 100644 --- a/packages/effect/src/Sink.ts +++ b/packages/effect/src/Sink.ts @@ -1,10 +1,13 @@ /** * @since 2.0.0 */ +import type * as Cause from "./Cause.js" import * as Channel from "./Channel.js" import * as Effect from "./Effect.js" +import type { LazyArg } from "./Function.js" import { identity } from "./Function.js" import { type Pipeable, pipeArguments } from "./Pipeable.js" +import type * as Scope from "./Scope.js" import type * as Types from "./Types.js" import type * as Unify from "./Unify.js" @@ -124,6 +127,51 @@ export const toChannel = ( self: Sink ): Channel.Channel, E, A, ReadonlyArray, never, void, R> => self.channel +/** + * A sink that immediately ends with the specified value. + * + * @since 2.0.0 + * @category constructors + */ +export const succeed = (a: A): Sink => fromChannel(Channel.end(a)) + +/** + * A sink that always fails with the specified error. + * + * @since 2.0.0 + * @category constructors + */ +export const fail = (e: E): Sink => fromChannel(Channel.fail(e)) + +/** + * A sink that always fails with the specified lazily evaluated error. + * + * @since 2.0.0 + * @category constructors + */ +export const failSync = (evaluate: LazyArg): Sink => + fromChannel(Channel.failSync(evaluate)) + +/** + * Creates a sink halting with a specified `Cause`. + * + * @since 2.0.0 + * @category constructors + */ +export const failCause = (cause: Cause.Cause): Sink => + fromChannel(Channel.failCause(cause)) + +/** + * Creates a sink halting with a specified lazily evaluated `Cause`. + * + * @since 2.0.0 + * @category constructors + */ +export const failCauseSync = (evaluate: LazyArg>): Sink => + fromChannel( + Channel.failCauseSync(evaluate) + ) + /** * A sink that executes the provided effectful function for every item fed * to it. @@ -150,3 +198,13 @@ export const forEachChunk = ( Effect.succeed(Effect.forever(Effect.flatMap(upstream, f), { autoYield: false })) ) ) + +/** + * Creates a sink produced from a scoped effect. + * + * @since 2.0.0 + * @category constructors + */ +export const unwrap = ( + effect: Effect.Effect, E, R> +): Sink | R2> => fromChannel(Channel.unwrap(Effect.map(effect, toChannel))) diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index d2b82a99e3..d3aec163f5 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -2,6 +2,7 @@ * @since 2.0.0 */ import * as Arr from "./Array.js" +import type * as Cause from "./Cause.js" import * as Channel from "./Channel.js" import * as Effect from "./Effect.js" import type { LazyArg } from "./Function.js" @@ -257,6 +258,53 @@ export const sync = (evaluate: LazyArg): Stream => fromChannel(Channel. export const suspend = (stream: LazyArg>): Stream => fromChannel(Channel.suspend(() => stream().channel)) +/** + * Terminates with the specified error. + * + * @example + * ```ts + * import { Effect, Stream } from "effect" + * + * const stream = Stream.fail("Uh oh!") + * + * Effect.runPromiseExit(Stream.runCollect(stream)).then(console.log) + * // { + * // _id: 'Exit', + * // _tag: 'Failure', + * // cause: { _id: 'Cause', _tag: 'Fail', failure: 'Uh oh!' } + * // } + * ``` + * + * @since 2.0.0 + * @category constructors + */ +export const fail = (error: E): Stream => fromChannel(Channel.fail(error)) + +/** + * Terminates with the specified lazily evaluated error. + * + * @since 2.0.0 + * @category constructors + */ +export const failSync = (evaluate: LazyArg): Stream => fromChannel(Channel.failSync(evaluate)) + +/** + * The stream that always fails with the specified `Cause`. + * + * @since 2.0.0 + * @category constructors + */ +export const failCause = (cause: Cause.Cause): Stream => fromChannel(Channel.failCause(cause)) + +/** + * The stream that always fails with the specified lazily evaluated `Cause`. + * + * @since 2.0.0 + * @category constructors + */ +export const failCauseSync = (evaluate: LazyArg>): Stream => + fromChannel(Channel.failCauseSync(evaluate)) + /** * Creates a stream from an iterator * @@ -499,6 +547,16 @@ export const range = ( */ export const never: Stream = fromChannel(Channel.never) +/** + * Creates a stream produced from a scoped `Effect`. + * + * @since 2.0.0 + * @category constructors + */ +export const unwrap = ( + effect: Effect.Effect, E, R> +): Stream> => fromChannel(Channel.unwrap(Effect.map(effect, toChannel))) + /** * Transforms the elements of this stream using the supplied function. * diff --git a/packages/effect/src/index.ts b/packages/effect/src/index.ts index 49d9c1d5e3..798858d19e 100644 --- a/packages/effect/src/index.ts +++ b/packages/effect/src/index.ts @@ -162,6 +162,11 @@ export * as Duration from "./Duration.js" */ export * as Effect from "./Effect.js" +/** + * @since 1.0.0 + */ +export * as Effectify from "./Effectify.js" + /** * @since 2.0.0 */ @@ -207,6 +212,11 @@ export * as FastCheck from "./FastCheck.js" */ export * as Fiber from "./Fiber.js" +/** + * @since 1.0.0 + */ +export * as FileSystem from "./FileSystem.js" + /** * @since 2.0.0 */ @@ -350,6 +360,11 @@ export * as Ordering from "./Ordering.js" */ export * as Pipeable from "./Pipeable.js" +/** + * @since 4.0.0 + */ +export * as PlatformError from "./PlatformError.js" + /** * @since 2.0.0 */ diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index 3f92fe07af..e4bb463b3d 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -614,20 +614,27 @@ export const promise = ( }, evaluate.length !== 0) /** @internal */ -export const tryPromise = (options: { - readonly try: (signal: AbortSignal) => PromiseLike - readonly catch: (error: unknown) => E -}): Effect.Effect => - callbackOptions(function(resume, signal) { +export const tryPromise = ( + options: { + readonly try: (signal: AbortSignal) => PromiseLike + readonly catch: (error: unknown) => E + } | ((signal: AbortSignal) => PromiseLike) +): Effect.Effect => { + const f = typeof options === "function" ? options : options.try + const catcher = typeof options === "function" + ? ((cause: unknown) => new UnknownError(cause, "An error occurred in Effect.tryPromise")) + : options.catch + return callbackOptions(function(resume, signal) { try { - options.try(signal!).then( + f(signal!).then( (a) => resume(succeed(a)), - (e) => resume(fail(options.catch(e))) + (e) => resume(fail(catcher(e) as E)) ) } catch (err) { - resume(fail(options.catch(err))) + resume(fail(catcher(err) as E)) } - }, options.try.length !== 0) + }, eval.length !== 0) +} /** @internal */ export const withFiberId = ( @@ -3787,6 +3794,24 @@ export class ExceededCapacityError extends TaggedError("ExceededCapacityError") } } +/** @internal */ +export const UnknownErrorTypeId: Cause.UnknownErrorTypeId = Symbol.for( + "effect/Cause/UnknownError" +) as Cause.UnknownErrorTypeId + +/** @internal */ +export const isUnknownError = ( + u: unknown +): u is Cause.UnknownError => hasProperty(u, UnknownErrorTypeId) + +/** @internal */ +export class UnknownError extends TaggedError("UnknownError") { + readonly [UnknownErrorTypeId]: Cause.UnknownErrorTypeId = UnknownErrorTypeId + constructor(cause: unknown, message?: string) { + super({ message, cause } as any) + } +} + // ---------------------------------------------------------------------------- // Console // ---------------------------------------------------------------------------- diff --git a/packages/effect/src/unstable/HttpClient.ts b/packages/effect/src/unstable/HttpClient.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/platform-node-shared/LICENSE b/packages/platform-node-shared/LICENSE new file mode 100644 index 0000000000..be1f5c14c7 --- /dev/null +++ b/packages/platform-node-shared/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Effectful Technologies Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/platform-node-shared/README.md b/packages/platform-node-shared/README.md new file mode 100644 index 0000000000..8df2065481 --- /dev/null +++ b/packages/platform-node-shared/README.md @@ -0,0 +1,7 @@ +# `@effect/platform-node` + +Provides Node.js-specific implementations for the abstractions defined in [`@effect/platform`](https://github.com/Effect-TS/effect/tree/main/packages/platform), allowing you to write platform-independent code that integrates smoothly with Node.js. + +## Documentation + +- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/platform-node). diff --git a/packages/platform-node-shared/docgen.json b/packages/platform-node-shared/docgen.json new file mode 100644 index 0000000000..f806321c24 --- /dev/null +++ b/packages/platform-node-shared/docgen.json @@ -0,0 +1,36 @@ +{ + "$schema": "../../node_modules/@effect/docgen/schema.json", + "srcLink": "https://github.com/Effect-TS/effect/tree/main/packages/platform-node/src/", + "exclude": ["src/internal/**/*.ts"], + "examplesCompilerOptions": { + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "module": "ES2022", + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "paths": { + "effect": ["../../../effect/src/index.js"], + "effect/*": ["../../../effect/src/*.js"], + "@effect/cluster": ["../../../cluster/src/index.js"], + "@effect/cluster/*": ["../../../cluster/src/*.js"], + "@effect/experimental": ["../../../experimental/src/index.js"], + "@effect/experimental/*": ["../../../experimental/src/*.js"], + "@effect/platform": ["../../../platform/src/index.js"], + "@effect/platform/*": ["../../../platform/src/*.js"], + "@effect/platform-node": ["../../../platform-node/src/index.js"], + "@effect/platform-node/*": ["../../../platform-node/src/*.js"], + "@effect/platform-node-shared": [ + "../../../platform-node-shared/src/index.js" + ], + "@effect/platform-node-shared/*": [ + "../../../platform-node-shared/src/*.js" + ], + "@effect/rpc": ["../../../rpc/src/index.js"], + "@effect/rpc/*": ["../../../rpc/src/*.js"], + "@effect/sql": ["../../../sql/src/index.js"], + "@effect/sql/*": ["../../../sql/src/*.js"] + } + } +} diff --git a/packages/platform-node-shared/package.json b/packages/platform-node-shared/package.json new file mode 100644 index 0000000000..9bd272f9fa --- /dev/null +++ b/packages/platform-node-shared/package.json @@ -0,0 +1,56 @@ +{ + "name": "@effect/platform-node-shared", + "type": "module", + "version": "0.31.6", + "license": "MIT", + "description": "Unified interfaces for common platform-specific services", + "homepage": "https://effect.website", + "repository": { + "type": "git", + "url": "https://github.com/Effect-TS/effect.git", + "directory": "packages/platform-node-shared" + }, + "bugs": { + "url": "https://github.com/Effect-TS/effect/issues" + }, + "tags": [ + "typescript", + "algebraic-data-types", + "functional-programming" + ], + "keywords": [ + "typescript", + "algebraic-data-types", + "functional-programming" + ], + "publishConfig": { + "access": "public", + "provenance": true, + "directory": "dist", + "linkDirectory": false + }, + "engines": { + "node": ">=18.0.0" + }, + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts", + "./*": "./src/*.ts", + "./internal/*": null + }, + "scripts": { + "build": "pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3", + "build-esm": "tsc -b tsconfig.build.json", + "build-cjs": "babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps", + "build-annotate": "babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps", + "check": "tsc -b tsconfig.json", + "test": "vitest", + "coverage": "vitest --coverage" + }, + "peerDependencies": { + "effect": "workspace:^" + }, + "devDependencies": { + "effect": "workspace:^" + } +} diff --git a/packages/platform-node-shared/src/NodeFileSystem.ts b/packages/platform-node-shared/src/NodeFileSystem.ts new file mode 100644 index 0000000000..078becf6ee --- /dev/null +++ b/packages/platform-node-shared/src/NodeFileSystem.ts @@ -0,0 +1,650 @@ +/** + * @since 1.0.0 + */ +import type * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { effectify } from "effect/Effectify" +import * as Exit from "effect/Exit" +import * as FileSystem from "effect/FileSystem" +import { pipe } from "effect/Function" +import * as Layer from "effect/Layer" +import * as Option from "effect/Option" +import * as Error from "effect/PlatformError" +import * as Queue from "effect/Queue" +import * as Stream from "effect/Stream" +import * as Crypto from "node:crypto" +import * as NFS from "node:fs" +import * as OS from "node:os" +import * as Path from "node:path" +import { handleErrnoException } from "./internal/utils.js" + +const handleBadArgument = (method: string) => (err: unknown) => + Error.BadArgument({ + module: "FileSystem", + method, + message: (err as Error).message ?? String(err) + }) + +// == access + +const access = (() => { + const nodeAccess = effectify( + NFS.access, + handleErrnoException("FileSystem", "access"), + handleBadArgument("access") + ) + return (path: string, options?: FileSystem.AccessFileOptions) => { + let mode = NFS.constants.F_OK + if (options?.readable) { + mode |= NFS.constants.R_OK + } + if (options?.writable) { + mode |= NFS.constants.W_OK + } + return nodeAccess(path, mode) + } +})() + +// == copy + +const copy = (() => { + const nodeCp = effectify( + NFS.cp, + handleErrnoException("FileSystem", "copy"), + handleBadArgument("copy") + ) + return (fromPath: string, toPath: string, options?: FileSystem.CopyOptions) => + nodeCp(fromPath, toPath, { + force: options?.overwrite ?? false, + preserveTimestamps: options?.preserveTimestamps ?? false, + recursive: true + }) +})() + +// == copyFile + +const copyFile = (() => { + const nodeCopyFile = effectify( + NFS.copyFile, + handleErrnoException("FileSystem", "copyFile"), + handleBadArgument("copyFile") + ) + return (fromPath: string, toPath: string) => nodeCopyFile(fromPath, toPath) +})() + +// == chmod + +const chmod = (() => { + const nodeChmod = effectify( + NFS.chmod, + handleErrnoException("FileSystem", "chmod"), + handleBadArgument("chmod") + ) + return (path: string, mode: number) => nodeChmod(path, mode) +})() + +// == chown + +const chown = (() => { + const nodeChown = effectify( + NFS.chown, + handleErrnoException("FileSystem", "chown"), + handleBadArgument("chown") + ) + return (path: string, uid: number, gid: number) => nodeChown(path, uid, gid) +})() + +// == link + +const link = (() => { + const nodeLink = effectify( + NFS.link, + handleErrnoException("FileSystem", "link"), + handleBadArgument("link") + ) + return (existingPath: string, newPath: string) => nodeLink(existingPath, newPath) +})() + +// == makeDirectory + +const makeDirectory = (() => { + const nodeMkdir = effectify( + NFS.mkdir, + handleErrnoException("FileSystem", "makeDirectory"), + handleBadArgument("makeDirectory") + ) + return (path: string, options?: FileSystem.MakeDirectoryOptions) => + nodeMkdir(path, { + recursive: options?.recursive ?? false, + mode: options?.mode + }) +})() + +// == makeTempDirectory + +const makeTempDirectoryFactory = (method: string) => { + const nodeMkdtemp = effectify( + NFS.mkdtemp, + handleErrnoException("FileSystem", method), + handleBadArgument(method) + ) + return (options?: FileSystem.MakeTempDirectoryOptions) => + Effect.suspend(() => { + const prefix = options?.prefix ?? "" + const directory = typeof options?.directory === "string" + ? Path.join(options.directory, ".") + : OS.tmpdir() + + return nodeMkdtemp(prefix ? Path.join(directory, prefix) : directory + "/") + }) +} +const makeTempDirectory = makeTempDirectoryFactory("makeTempDirectory") + +// == remove + +const removeFactory = (method: string) => { + const nodeRm = effectify( + NFS.rm, + handleErrnoException("FileSystem", method), + handleBadArgument(method) + ) + return (path: string, options?: FileSystem.RemoveOptions) => + nodeRm( + path, + { recursive: options?.recursive ?? false, force: options?.force ?? false } + ) +} +const remove = removeFactory("remove") + +// == makeTempDirectoryScoped + +const makeTempDirectoryScoped = (() => { + const makeDirectory = makeTempDirectoryFactory("makeTempDirectoryScoped") + const removeDirectory = removeFactory("makeTempDirectoryScoped") + return ( + options?: FileSystem.MakeTempDirectoryOptions + ) => + Effect.acquireRelease( + makeDirectory(options), + (directory) => Effect.orDie(removeDirectory(directory, { recursive: true })) + ) +})() + +// == open + +const openFactory = (method: string) => { + const nodeOpen = effectify( + NFS.open, + handleErrnoException("FileSystem", method), + handleBadArgument(method) + ) + const nodeClose = effectify( + NFS.close, + handleErrnoException("FileSystem", method), + handleBadArgument(method) + ) + + return (path: string, options?: FileSystem.OpenFileOptions) => + pipe( + Effect.acquireRelease( + nodeOpen(path, options?.flag ?? "r", options?.mode), + (fd) => Effect.orDie(nodeClose(fd)) + ), + Effect.map((fd) => makeFile(FileSystem.FileDescriptor(fd), options?.flag?.startsWith("a") ?? false)) + ) +} +const open = openFactory("open") + +const makeFile = (() => { + const nodeReadFactory = (method: string) => + effectify( + NFS.read, + handleErrnoException("FileSystem", method), + handleBadArgument(method) + ) + const nodeRead = nodeReadFactory("read") + const nodeReadAlloc = nodeReadFactory("readAlloc") + const nodeStat = effectify( + NFS.fstat, + handleErrnoException("FileSystem", "stat"), + handleBadArgument("stat") + ) + const nodeTruncate = effectify( + NFS.ftruncate, + handleErrnoException("FileSystem", "truncate"), + handleBadArgument("truncate") + ) + + const nodeSync = effectify( + NFS.fsync, + handleErrnoException("FileSystem", "sync"), + handleBadArgument("sync") + ) + + const nodeWriteFactory = (method: string) => + effectify( + NFS.write, + handleErrnoException("FileSystem", method), + handleBadArgument(method) + ) + const nodeWrite = nodeWriteFactory("write") + const nodeWriteAll = nodeWriteFactory("writeAll") + + class FileImpl implements FileSystem.File { + readonly [FileSystem.FileTypeId]: FileSystem.FileTypeId + + private readonly semaphore = Effect.unsafeMakeSemaphore(1) + private position: bigint = 0n + + constructor( + readonly fd: FileSystem.File.Descriptor, + private readonly append: boolean + ) { + this[FileSystem.FileTypeId] = FileSystem.FileTypeId + } + + get stat() { + return Effect.map(nodeStat(this.fd), makeFileInfo) + } + + get sync() { + return nodeSync(this.fd) + } + + seek(offset: FileSystem.SizeInput, from: FileSystem.SeekMode) { + const offsetSize = FileSystem.Size(offset) + return this.semaphore.withPermits(1)( + Effect.sync(() => { + if (from === "start") { + this.position = offsetSize + } else if (from === "current") { + this.position = this.position + offsetSize + } + + return this.position + }) + ) + } + + read(buffer: Uint8Array) { + return this.semaphore.withPermits(1)( + Effect.map( + Effect.suspend(() => + nodeRead(this.fd, { + buffer, + position: this.position + }) + ), + (bytesRead) => { + const sizeRead = FileSystem.Size(bytesRead) + this.position = this.position + sizeRead + return sizeRead + } + ) + ) + } + + readAlloc(size: FileSystem.SizeInput) { + const sizeNumber = Number(size) + return this.semaphore.withPermits(1)(Effect.flatMap( + Effect.sync(() => Buffer.allocUnsafeSlow(sizeNumber)), + (buffer) => + Effect.map( + nodeReadAlloc(this.fd, { + buffer, + position: this.position + }), + (bytesRead): Option.Option => { + if (bytesRead === 0) { + return Option.none() + } + + this.position = this.position + BigInt(bytesRead) + if (bytesRead === sizeNumber) { + return Option.some(buffer) + } + + const dst = Buffer.allocUnsafeSlow(bytesRead) + buffer.copy(dst, 0, 0, bytesRead) + return Option.some(dst) + } + ) + )) + } + + truncate(length?: FileSystem.SizeInput) { + return this.semaphore.withPermits(1)( + Effect.map(nodeTruncate(this.fd, length ? Number(length) : undefined), () => { + if (!this.append) { + const len = BigInt(length ?? 0) + if (this.position > len) { + this.position = len + } + } + }) + ) + } + + write(buffer: Uint8Array) { + return this.semaphore.withPermits(1)( + Effect.map( + Effect.suspend(() => + nodeWrite(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(this.position)) + ), + (bytesWritten) => { + const sizeWritten = FileSystem.Size(bytesWritten) + if (!this.append) { + this.position = this.position + sizeWritten + } + + return sizeWritten + } + ) + ) + } + + private writeAllChunk(buffer: Uint8Array): Effect.Effect { + return Effect.flatMap( + Effect.suspend(() => + nodeWriteAll(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(this.position)) + ), + (bytesWritten) => { + if (bytesWritten === 0) { + return Effect.fail(Error.SystemError({ + module: "FileSystem", + method: "writeAll", + reason: "WriteZero", + pathOrDescriptor: this.fd, + message: "write returned 0 bytes written" + })) + } + + if (!this.append) { + this.position = this.position + BigInt(bytesWritten) + } + + return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : Effect.void + } + ) + } + + writeAll(buffer: Uint8Array) { + return this.semaphore.withPermits(1)(this.writeAllChunk(buffer)) + } + } + + return (fd: FileSystem.File.Descriptor, append: boolean): FileSystem.File => new FileImpl(fd, append) +})() + +// == makeTempFile + +const makeTempFileFactory = (method: string) => { + const makeDirectory = makeTempDirectoryFactory(method) + const open = openFactory(method) + const randomHexString = (bytes: number) => Effect.sync(() => Crypto.randomBytes(bytes).toString("hex")) + return (options?: FileSystem.MakeTempFileOptions) => + pipe( + Effect.zip(makeDirectory(options), randomHexString(6)), + Effect.map(([directory, random]) => Path.join(directory, random)), + Effect.tap((path) => Effect.scoped(open(path, { flag: "w+" }))) + ) +} +const makeTempFile = makeTempFileFactory("makeTempFile") + +// == makeTempFileScoped + +const makeTempFileScoped = (() => { + const makeFile = makeTempFileFactory("makeTempFileScoped") + const removeDirectory = removeFactory("makeTempFileScoped") + return (options?: FileSystem.MakeTempFileOptions) => + Effect.acquireRelease( + makeFile(options), + (file) => Effect.orDie(removeDirectory(Path.dirname(file), { recursive: true })) + ) +})() + +// == readDirectory + +const readDirectory = (path: string, options?: FileSystem.ReadDirectoryOptions) => + Effect.tryPromise({ + try: () => NFS.promises.readdir(path, options), + catch: (err) => handleErrnoException("FileSystem", "readDirectory")(err as any, [path]) + }) + +// == readFile + +const readFile = (path: string) => + Effect.callback((resume, signal) => { + try { + NFS.readFile(path, { signal }, (err, data) => { + if (err) { + resume(Effect.fail(handleErrnoException("FileSystem", "readFile")(err, [path]))) + } else { + resume(Effect.succeed(data)) + } + }) + } catch (err) { + resume(Effect.fail(handleBadArgument("readFile")(err))) + } + }) + +// == readLink + +const readLink = (() => { + const nodeReadLink = effectify( + NFS.readlink, + handleErrnoException("FileSystem", "readLink"), + handleBadArgument("readLink") + ) + return (path: string) => nodeReadLink(path) +})() + +// == realPath + +const realPath = (() => { + const nodeRealPath = effectify( + NFS.realpath, + handleErrnoException("FileSystem", "realPath"), + handleBadArgument("realPath") + ) + return (path: string) => nodeRealPath(path) +})() + +// == rename + +const rename = (() => { + const nodeRename = effectify( + NFS.rename, + handleErrnoException("FileSystem", "rename"), + handleBadArgument("rename") + ) + return (oldPath: string, newPath: string) => nodeRename(oldPath, newPath) +})() + +// == stat + +const makeFileInfo = (stat: NFS.Stats): FileSystem.File.Info => ({ + type: stat.isFile() ? + "File" : + stat.isDirectory() ? + "Directory" : + stat.isSymbolicLink() ? + "SymbolicLink" : + stat.isBlockDevice() ? + "BlockDevice" : + stat.isCharacterDevice() ? + "CharacterDevice" : + stat.isFIFO() ? + "FIFO" : + stat.isSocket() ? + "Socket" : + "Unknown", + mtime: Option.fromNullable(stat.mtime), + atime: Option.fromNullable(stat.atime), + birthtime: Option.fromNullable(stat.birthtime), + dev: stat.dev, + rdev: Option.fromNullable(stat.rdev), + ino: Option.fromNullable(stat.ino), + mode: stat.mode, + nlink: Option.fromNullable(stat.nlink), + uid: Option.fromNullable(stat.uid), + gid: Option.fromNullable(stat.gid), + size: FileSystem.Size(stat.size), + blksize: Option.fromNullable(FileSystem.Size(stat.blksize)), + blocks: Option.fromNullable(stat.blocks) +}) +const stat = (() => { + const nodeStat = effectify( + NFS.stat, + handleErrnoException("FileSystem", "stat"), + handleBadArgument("stat") + ) + return (path: string) => Effect.map(nodeStat(path), makeFileInfo) +})() + +// == symlink + +const symlink = (() => { + const nodeSymlink = effectify( + NFS.symlink, + handleErrnoException("FileSystem", "symlink"), + handleBadArgument("symlink") + ) + return (target: string, path: string) => nodeSymlink(target, path) +})() + +// == truncate + +const truncate = (() => { + const nodeTruncate = effectify( + NFS.truncate, + handleErrnoException("FileSystem", "truncate"), + handleBadArgument("truncate") + ) + return (path: string, length?: FileSystem.SizeInput) => + nodeTruncate(path, length !== undefined ? Number(length) : undefined) +})() + +// == utimes + +const utimes = (() => { + const nodeUtimes = effectify( + NFS.utimes, + handleErrnoException("FileSystem", "utime"), + handleBadArgument("utime") + ) + return (path: string, atime: number | Date, mtime: number | Date) => nodeUtimes(path, atime, mtime) +})() + +// == watch + +const watchNode = (path: string) => + Stream.callback((queue) => + Effect.acquireRelease( + Effect.sync(() => { + const watcher = NFS.watch(path, {}, (event, path) => { + if (!path) return + switch (event) { + case "rename": { + Effect.runFork(Effect.matchEffect(stat(path), { + onSuccess: (_) => Queue.offer(queue, FileSystem.WatchEventCreate({ path })), + onFailure: (_) => Queue.offer(queue, FileSystem.WatchEventRemove({ path })) + })) + return + } + case "change": { + Queue.unsafeOffer(queue, FileSystem.WatchEventUpdate({ path })) + return + } + } + }) + watcher.on("error", (error) => { + Queue.unsafeDone( + queue, + Exit.fail( + Error.SystemError({ + module: "FileSystem", + reason: "Unknown", + method: "watch", + pathOrDescriptor: path, + message: error.message + }) + ) + ) + }) + watcher.on("close", () => { + Queue.unsafeEnd(queue) + }) + return watcher + }), + (watcher) => Effect.sync(() => watcher.close()) + ) + ) + +const watch = (backend: Option.Option>, path: string) => + stat(path).pipe( + Effect.map((stat) => + backend.pipe( + Option.flatMap((_) => _.register(path, stat)), + Option.getOrElse(() => watchNode(path)) + ) + ), + Stream.unwrap + ) + +// == writeFile + +const writeFile = (path: string, data: Uint8Array, options?: FileSystem.WriteFileOptions) => + Effect.callback((resume, signal) => { + try { + NFS.writeFile(path, data, { + signal, + flag: options?.flag, + mode: options?.mode + }, (err) => { + if (err) { + resume(Effect.fail(handleErrnoException("FileSystem", "writeFile")(err, [path]))) + } else { + resume(Effect.void) + } + }) + } catch (err) { + resume(Effect.fail(handleBadArgument("writeFile")(err))) + } + }) + +const makeFileSystem = Effect.map(Effect.serviceOption(FileSystem.WatchBackend), (backend) => + FileSystem.make({ + access, + chmod, + chown, + copy, + copyFile, + link, + makeDirectory, + makeTempDirectory, + makeTempDirectoryScoped, + makeTempFile, + makeTempFileScoped, + open, + readDirectory, + readFile, + readLink, + realPath, + remove, + rename, + stat, + symlink, + truncate, + utimes, + watch(path) { + return watch(backend, path) + }, + writeFile + })) + +/** + * @since 1.0.0 + * @category Layers + */ +export const layer: Layer.Layer = Layer.effect(FileSystem.FileSystem, makeFileSystem) diff --git a/packages/platform-node-shared/src/internal/utils.ts b/packages/platform-node-shared/src/internal/utils.ts new file mode 100644 index 0000000000..3664182857 --- /dev/null +++ b/packages/platform-node-shared/src/internal/utils.ts @@ -0,0 +1,51 @@ +import type { PlatformError, SystemErrorReason } from "effect/PlatformError" +import { SystemError } from "effect/PlatformError" +import type { PathLike } from "node:fs" + +/** @internal */ +export const handleErrnoException = (module: SystemError["module"], method: string) => +( + err: NodeJS.ErrnoException, + [path]: [path: PathLike | number, ...args: Array] +): PlatformError => { + let reason: SystemErrorReason = "Unknown" + + switch (err.code) { + case "ENOENT": + reason = "NotFound" + break + + case "EACCES": + reason = "PermissionDenied" + break + + case "EEXIST": + reason = "AlreadyExists" + break + + case "EISDIR": + reason = "BadResource" + break + + case "ENOTDIR": + reason = "BadResource" + break + + case "EBUSY": + reason = "Busy" + break + + case "ELOOP": + reason = "BadResource" + break + } + + return SystemError({ + reason, + module, + method, + pathOrDescriptor: path as string | number, + syscall: err.syscall, + message: err.message + }) +} diff --git a/packages/platform-node-shared/test/NodeFileSystem.test.ts b/packages/platform-node-shared/test/NodeFileSystem.test.ts new file mode 100644 index 0000000000..85486b4267 --- /dev/null +++ b/packages/platform-node-shared/test/NodeFileSystem.test.ts @@ -0,0 +1,214 @@ +import * as NodeFileSystem from "@effect/platform-node-shared/NodeFileSystem" +import { assert, describe, expect, it } from "@effect/vitest" +import { Array } from "effect" +import * as Effect from "effect/Effect" +import * as Fs from "effect/FileSystem" +import * as Stream from "effect/Stream" + +const runPromise = (self: Effect.Effect) => + Effect.runPromise( + Effect.provide(self, NodeFileSystem.layer) + ) + +describe("FileSystem", () => { + it("readFile", () => + runPromise(Effect.gen(function*() { + const fs = yield* Fs.FileSystem + const data = yield* fs.readFile(`${__dirname}/fixtures/text.txt`) + const text = new TextDecoder().decode(data) + expect(text.trim()).toEqual("lorem ipsum dolar sit amet") + }))) + + it("makeTempDirectory", () => + runPromise(Effect.gen(function*() { + const fs = yield* Fs.FileSystem + let dir = "" + yield* Effect.scoped(Effect.gen(function*() { + dir = yield* fs.makeTempDirectory() + const stat = yield* fs.stat(dir) + expect(stat.type).toEqual("Directory") + })) + const stat = yield* fs.stat(dir) + expect(stat.type).toEqual("Directory") + }))) + + it("makeTempDirectoryScoped", () => + runPromise(Effect.gen(function*() { + const fs = yield* Fs.FileSystem + let dir = "" + yield* Effect.scoped( + Effect.gen(function*() { + dir = yield* fs.makeTempDirectoryScoped() + const stat = yield* fs.stat(dir) + expect(stat.type).toEqual("Directory") + }) + ) + const error = yield* Effect.flip(fs.stat(dir)) + assert(error._tag === "SystemError" && error.reason === "NotFound") + }))) + + it("truncate", () => + runPromise(Effect.gen(function*() { + const fs = yield* Fs.FileSystem + const file = yield* fs.makeTempFile() + + const text = "hello world" + yield* fs.writeFile(file, new TextEncoder().encode(text)) + + const before = yield* Effect.map(fs.readFile(file), (_) => new TextDecoder().decode(_)) + expect(before).toEqual(text) + + yield* fs.truncate(file) + + const after = yield* Effect.map(fs.readFile(file), (_) => new TextDecoder().decode(_)) + expect(after).toEqual("") + }))) + + it("should track the cursor position when reading", () => + runPromise(Effect.gen(function*() { + const fs = yield* Fs.FileSystem + + yield* Effect.gen(function*() { + let text: string + const file = yield* fs.open(`${__dirname}/fixtures/text.txt`) + + text = yield* file.readAlloc(Fs.Size(5)).pipe( + Effect.flatMap((_) => _.asEffect()), + Effect.map((_) => new TextDecoder().decode(_)) + ) + expect(text).toBe("lorem") + + yield* file.seek(Fs.Size(7), "current") + text = yield* file.readAlloc(Fs.Size(5)).pipe( + Effect.flatMap((_) => _.asEffect()), + Effect.map((_) => new TextDecoder().decode(_)) + ) + expect(text).toBe("dolar") + + yield* file.seek(Fs.Size(1), "current") + text = yield* file.readAlloc(Fs.Size(8)).pipe( + Effect.flatMap((_) => _.asEffect()), + Effect.map((_) => new TextDecoder().decode(_)) + ) + expect(text).toBe("sit amet") + + yield* file.seek(Fs.Size(0), "start") + text = yield* file.readAlloc(Fs.Size(11)).pipe( + Effect.flatMap((_) => _.asEffect()), + Effect.map((_) => new TextDecoder().decode(_)) + ) + expect(text).toBe("lorem ipsum") + + text = yield* fs.stream(`${__dirname}/fixtures/text.txt`, { offset: Fs.Size(6), bytesToRead: Fs.Size(5) }).pipe( + Stream.map((_) => new TextDecoder().decode(_)), + Stream.runCollect, + Effect.map(Array.join("")) + ) + expect(text).toBe("ipsum") + }).pipe( + Effect.scoped + ) + }))) + + it("should track the cursor position when writing", () => + runPromise(Effect.gen(function*() { + const fs = yield* Fs.FileSystem + + yield* Effect.gen(function*() { + let text: string + const path = yield* fs.makeTempFileScoped() + const file = yield* fs.open(path, { flag: "w+" }) + + yield* file.write(new TextEncoder().encode("lorem ipsum")) + yield* file.write(new TextEncoder().encode(" ")) + yield* file.write(new TextEncoder().encode("dolor sit amet")) + text = yield* fs.readFileString(path) + expect(text).toBe("lorem ipsum dolor sit amet") + + yield* file.seek(Fs.Size(-4), "current") + yield* file.write(new TextEncoder().encode("hello world")) + text = yield* fs.readFileString(path) + expect(text).toBe("lorem ipsum dolor sit hello world") + + yield* file.seek(Fs.Size(6), "start") + yield* file.write(new TextEncoder().encode("blabl")) + text = yield* fs.readFileString(path) + expect(text).toBe("lorem blabl dolor sit hello world") + }).pipe( + Effect.scoped + ) + }))) + + it("should maintain a read cursor in append mode", () => + runPromise(Effect.gen(function*() { + const fs = yield* Fs.FileSystem + + yield* Effect.gen(function*() { + let text: string + const path = yield* fs.makeTempFileScoped() + const file = yield* fs.open(path, { flag: "a+" }) + + yield* file.write(new TextEncoder().encode("foo")) + yield* file.seek(Fs.Size(0), "start") + + yield* file.write(new TextEncoder().encode("bar")) + text = yield* fs.readFileString(path) + expect(text).toBe("foobar") + + text = yield* file.readAlloc(Fs.Size(3)).pipe( + Effect.flatMap((_) => _.asEffect()), + Effect.map((_) => new TextDecoder().decode(_)) + ) + expect(text).toBe("foo") + + yield* file.write(new TextEncoder().encode("baz")) + text = yield* fs.readFileString(path) + expect(text).toBe("foobarbaz") + + text = yield* file.readAlloc(Fs.Size(6)).pipe( + Effect.flatMap((_) => _.asEffect()), + Effect.map((_) => new TextDecoder().decode(_)) + ) + expect(text).toBe("barbaz") + }).pipe( + Effect.scoped + ) + }))) + + it("should keep the current cursor if truncating doesn't affect it", () => + runPromise(Effect.gen(function*() { + const fs = yield* Fs.FileSystem + + yield* Effect.gen(function*() { + const path = yield* fs.makeTempFileScoped() + const file = yield* fs.open(path, { flag: "w+" }) + + yield* file.write(new TextEncoder().encode("lorem ipsum dolor sit amet")) + yield* file.seek(Fs.Size(6), "start") + yield* file.truncate(Fs.Size(11)) + + const cursor = yield* file.seek(Fs.Size(0), "current") + expect(cursor).toBe(Fs.Size(6)) + }).pipe( + Effect.scoped + ) + }))) + + it("should update the current cursor if truncating affects it", () => + runPromise(Effect.gen(function*() { + const fs = yield* Fs.FileSystem + + yield* Effect.gen(function*() { + const path = yield* fs.makeTempFileScoped() + const file = yield* fs.open(path, { flag: "w+" }) + + yield* file.write(new TextEncoder().encode("lorem ipsum dolor sit amet")) + yield* file.truncate(Fs.Size(11)) + + const cursor = yield* file.seek(Fs.Size(0), "current") + expect(cursor).toBe(Fs.Size(11)) + }).pipe( + Effect.scoped + ) + }))) +}) diff --git a/packages/platform-node-shared/test/fixtures/bash/duplex.sh b/packages/platform-node-shared/test/fixtures/bash/duplex.sh new file mode 100755 index 0000000000..249a4de194 --- /dev/null +++ b/packages/platform-node-shared/test/fixtures/bash/duplex.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash + +function echoerr() { + echo "$@" 1>&2 +} + +echo "stdout1" +echoerr "stderr1" + +echo "stdout2" +echoerr "stderr2" diff --git a/packages/platform-node-shared/test/fixtures/bash/no-permissions.sh b/packages/platform-node-shared/test/fixtures/bash/no-permissions.sh new file mode 100644 index 0000000000..2d7f858c6f --- /dev/null +++ b/packages/platform-node-shared/test/fixtures/bash/no-permissions.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +echo "this should not run because it doesn't have execute permissions" diff --git a/packages/platform-node-shared/test/fixtures/bash/non-zero-exit.sh b/packages/platform-node-shared/test/fixtures/bash/non-zero-exit.sh new file mode 100755 index 0000000000..f019ff95ba --- /dev/null +++ b/packages/platform-node-shared/test/fixtures/bash/non-zero-exit.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +exit 1 diff --git a/packages/platform-node-shared/test/fixtures/bash/repeat.sh b/packages/platform-node-shared/test/fixtures/bash/repeat.sh new file mode 100755 index 0000000000..3333fd98c3 --- /dev/null +++ b/packages/platform-node-shared/test/fixtures/bash/repeat.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +for i in {1..60}; do + echo "iteration: $i" + sleep 1 +done diff --git a/packages/platform-node-shared/test/fixtures/config/SHOUTING b/packages/platform-node-shared/test/fixtures/config/SHOUTING new file mode 100644 index 0000000000..6d4e150796 --- /dev/null +++ b/packages/platform-node-shared/test/fixtures/config/SHOUTING @@ -0,0 +1 @@ +value diff --git a/packages/platform-node-shared/test/fixtures/config/integer b/packages/platform-node-shared/test/fixtures/config/integer new file mode 100644 index 0000000000..190a18037c --- /dev/null +++ b/packages/platform-node-shared/test/fixtures/config/integer @@ -0,0 +1 @@ +123 diff --git a/packages/platform-node-shared/test/fixtures/config/nested/config b/packages/platform-node-shared/test/fixtures/config/nested/config new file mode 100644 index 0000000000..ce01362503 --- /dev/null +++ b/packages/platform-node-shared/test/fixtures/config/nested/config @@ -0,0 +1 @@ +hello diff --git a/packages/platform-node-shared/test/fixtures/config/secret b/packages/platform-node-shared/test/fixtures/config/secret new file mode 100644 index 0000000000..4a11bbca4f --- /dev/null +++ b/packages/platform-node-shared/test/fixtures/config/secret @@ -0,0 +1 @@ +keepitsafe diff --git a/packages/platform-node-shared/test/fixtures/helloworld.tar.gz b/packages/platform-node-shared/test/fixtures/helloworld.tar.gz new file mode 100644 index 0000000000..7d47b90010 Binary files /dev/null and b/packages/platform-node-shared/test/fixtures/helloworld.tar.gz differ diff --git a/packages/platform-node-shared/test/fixtures/text.txt b/packages/platform-node-shared/test/fixtures/text.txt new file mode 100644 index 0000000000..72b190ee61 --- /dev/null +++ b/packages/platform-node-shared/test/fixtures/text.txt @@ -0,0 +1 @@ +lorem ipsum dolar sit amet diff --git a/packages/platform-node-shared/tsconfig.build.json b/packages/platform-node-shared/tsconfig.build.json new file mode 100644 index 0000000000..76ee3883a1 --- /dev/null +++ b/packages/platform-node-shared/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.src.json", + "references": [ + { "path": "../effect/tsconfig.build.json" } + ], + "compilerOptions": { + "tsBuildInfoFile": ".tsbuildinfo/build.tsbuildinfo", + "outDir": "build/esm", + "declarationDir": "build/dts", + "stripInternal": true + } +} diff --git a/packages/platform-node-shared/tsconfig.examples.json b/packages/platform-node-shared/tsconfig.examples.json new file mode 100644 index 0000000000..faf5ae008c --- /dev/null +++ b/packages/platform-node-shared/tsconfig.examples.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["examples"], + "references": [ + { "path": "tsconfig.build.json" } + ], + "compilerOptions": { + "tsBuildInfoFile": ".tsbuildinfo/examples.tsbuildinfo", + "rootDir": "examples", + "noEmit": true + } +} diff --git a/packages/platform-node-shared/tsconfig.json b/packages/platform-node-shared/tsconfig.json new file mode 100644 index 0000000000..3edbf6b8a5 --- /dev/null +++ b/packages/platform-node-shared/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "include": [], + "references": [ + { "path": "tsconfig.src.json" }, + { "path": "tsconfig.test.json" }, + { "path": "tsconfig.examples.json" } + ] +} diff --git a/packages/platform-node-shared/tsconfig.src.json b/packages/platform-node-shared/tsconfig.src.json new file mode 100644 index 0000000000..53dac3ddce --- /dev/null +++ b/packages/platform-node-shared/tsconfig.src.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src"], + "references": [ + { "path": "../effect/tsconfig.src.json" } + ], + "compilerOptions": { + "tsBuildInfoFile": ".tsbuildinfo/src.tsbuildinfo", + "rootDir": "src", + "outDir": "build/src", + "types": ["node"] + } +} diff --git a/packages/platform-node-shared/tsconfig.test.json b/packages/platform-node-shared/tsconfig.test.json new file mode 100644 index 0000000000..185e7065e4 --- /dev/null +++ b/packages/platform-node-shared/tsconfig.test.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["test"], + "references": [ + { "path": "tsconfig.src.json" }, + { "path": "../vitest/tsconfig.src.json" } + ], + "compilerOptions": { + "tsBuildInfoFile": ".tsbuildinfo/test.tsbuildinfo", + "rootDir": "test", + "noEmit": true + } +} diff --git a/packages/platform-node-shared/vitest.config.ts b/packages/platform-node-shared/vitest.config.ts new file mode 100644 index 0000000000..adddce25ec --- /dev/null +++ b/packages/platform-node-shared/vitest.config.ts @@ -0,0 +1,7 @@ +import { mergeConfig, type ViteUserConfig } from "vitest/config" +import shared from "../../vitest.shared.js" + +const config: ViteUserConfig = { +} + +export default mergeConfig(shared, config) diff --git a/packages/platform-node/LICENSE b/packages/platform-node/LICENSE new file mode 100644 index 0000000000..be1f5c14c7 --- /dev/null +++ b/packages/platform-node/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Effectful Technologies Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/platform-node/README.md b/packages/platform-node/README.md new file mode 100644 index 0000000000..8df2065481 --- /dev/null +++ b/packages/platform-node/README.md @@ -0,0 +1,7 @@ +# `@effect/platform-node` + +Provides Node.js-specific implementations for the abstractions defined in [`@effect/platform`](https://github.com/Effect-TS/effect/tree/main/packages/platform), allowing you to write platform-independent code that integrates smoothly with Node.js. + +## Documentation + +- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/platform-node). diff --git a/packages/platform-node/docgen.json b/packages/platform-node/docgen.json new file mode 100644 index 0000000000..f806321c24 --- /dev/null +++ b/packages/platform-node/docgen.json @@ -0,0 +1,36 @@ +{ + "$schema": "../../node_modules/@effect/docgen/schema.json", + "srcLink": "https://github.com/Effect-TS/effect/tree/main/packages/platform-node/src/", + "exclude": ["src/internal/**/*.ts"], + "examplesCompilerOptions": { + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "module": "ES2022", + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "paths": { + "effect": ["../../../effect/src/index.js"], + "effect/*": ["../../../effect/src/*.js"], + "@effect/cluster": ["../../../cluster/src/index.js"], + "@effect/cluster/*": ["../../../cluster/src/*.js"], + "@effect/experimental": ["../../../experimental/src/index.js"], + "@effect/experimental/*": ["../../../experimental/src/*.js"], + "@effect/platform": ["../../../platform/src/index.js"], + "@effect/platform/*": ["../../../platform/src/*.js"], + "@effect/platform-node": ["../../../platform-node/src/index.js"], + "@effect/platform-node/*": ["../../../platform-node/src/*.js"], + "@effect/platform-node-shared": [ + "../../../platform-node-shared/src/index.js" + ], + "@effect/platform-node-shared/*": [ + "../../../platform-node-shared/src/*.js" + ], + "@effect/rpc": ["../../../rpc/src/index.js"], + "@effect/rpc/*": ["../../../rpc/src/*.js"], + "@effect/sql": ["../../../sql/src/index.js"], + "@effect/sql/*": ["../../../sql/src/*.js"] + } + } +} diff --git a/packages/platform-node/package.json b/packages/platform-node/package.json new file mode 100644 index 0000000000..173553ec9b --- /dev/null +++ b/packages/platform-node/package.json @@ -0,0 +1,62 @@ +{ + "name": "@effect/platform-node", + "type": "module", + "version": "0.77.6", + "license": "MIT", + "description": "Platform specific implementations for the Node.js runtime", + "homepage": "https://effect.website", + "repository": { + "type": "git", + "url": "https://github.com/Effect-TS/effect.git", + "directory": "packages/platform-node" + }, + "bugs": { + "url": "https://github.com/Effect-TS/effect/issues" + }, + "tags": [ + "node", + "typescript", + "algebraic-data-types", + "functional-programming" + ], + "keywords": [ + "node", + "typescript", + "algebraic-data-types", + "functional-programming" + ], + "publishConfig": { + "access": "public", + "provenance": true, + "directory": "dist", + "linkDirectory": false + }, + "engines": { + "node": ">=18.0.0" + }, + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts", + "./*": "./src/*.ts", + "./internal/*": null + }, + "scripts": { + "codegen": "build-utils prepare-v3", + "build": "pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3", + "build-esm": "tsc -b tsconfig.build.json", + "build-cjs": "babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps", + "build-annotate": "babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps", + "check": "tsc -b tsconfig.json", + "test": "vitest", + "coverage": "vitest --coverage" + }, + "dependencies": { + "@effect/platform-node-shared": "workspace:^" + }, + "peerDependencies": { + "effect": "workspace:^" + }, + "devDependencies": { + "effect": "workspace:^" + } +} diff --git a/packages/platform-node/src/NodeFileSystem.ts b/packages/platform-node/src/NodeFileSystem.ts new file mode 100644 index 0000000000..e7e8f79578 --- /dev/null +++ b/packages/platform-node/src/NodeFileSystem.ts @@ -0,0 +1,12 @@ +/** + * @since 1.0.0 + */ +import * as NodeFileSystem from "@effect/platform-node-shared/NodeFileSystem" +import type { FileSystem } from "effect/FileSystem" +import type { Layer } from "effect/Layer" + +/** + * @since 1.0.0 + * @category layer + */ +export const layer: Layer = NodeFileSystem.layer diff --git a/packages/platform-node/src/index.ts b/packages/platform-node/src/index.ts new file mode 100644 index 0000000000..bd41814d2e --- /dev/null +++ b/packages/platform-node/src/index.ts @@ -0,0 +1,4 @@ +/** + * @since 1.0.0 + */ +export * as NodeFileSystem from "./NodeFileSystem.js" diff --git a/packages/platform-node/tsconfig.build.json b/packages/platform-node/tsconfig.build.json new file mode 100644 index 0000000000..a643c4f534 --- /dev/null +++ b/packages/platform-node/tsconfig.build.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.src.json", + "references": [ + { "path": "../effect/tsconfig.build.json" }, + { "path": "../platform-node-shared/tsconfig.build.json" } + ], + "compilerOptions": { + "tsBuildInfoFile": ".tsbuildinfo/build.tsbuildinfo", + "outDir": "build/esm", + "declarationDir": "build/dts", + "stripInternal": true + } +} diff --git a/packages/platform-node/tsconfig.examples.json b/packages/platform-node/tsconfig.examples.json new file mode 100644 index 0000000000..faf5ae008c --- /dev/null +++ b/packages/platform-node/tsconfig.examples.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["examples"], + "references": [ + { "path": "tsconfig.build.json" } + ], + "compilerOptions": { + "tsBuildInfoFile": ".tsbuildinfo/examples.tsbuildinfo", + "rootDir": "examples", + "noEmit": true + } +} diff --git a/packages/platform-node/tsconfig.json b/packages/platform-node/tsconfig.json new file mode 100644 index 0000000000..3edbf6b8a5 --- /dev/null +++ b/packages/platform-node/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "include": [], + "references": [ + { "path": "tsconfig.src.json" }, + { "path": "tsconfig.test.json" }, + { "path": "tsconfig.examples.json" } + ] +} diff --git a/packages/platform-node/tsconfig.src.json b/packages/platform-node/tsconfig.src.json new file mode 100644 index 0000000000..4e5dc30245 --- /dev/null +++ b/packages/platform-node/tsconfig.src.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src"], + "references": [ + { "path": "../effect/tsconfig.src.json" }, + { "path": "../platform-node-shared/tsconfig.src.json" } + ], + "compilerOptions": { + "tsBuildInfoFile": ".tsbuildinfo/src.tsbuildinfo", + "rootDir": "src", + "outDir": "build/src", + "types": ["node"] + } +} diff --git a/packages/platform-node/tsconfig.test.json b/packages/platform-node/tsconfig.test.json new file mode 100644 index 0000000000..185e7065e4 --- /dev/null +++ b/packages/platform-node/tsconfig.test.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["test"], + "references": [ + { "path": "tsconfig.src.json" }, + { "path": "../vitest/tsconfig.src.json" } + ], + "compilerOptions": { + "tsBuildInfoFile": ".tsbuildinfo/test.tsbuildinfo", + "rootDir": "test", + "noEmit": true + } +} diff --git a/packages/platform-node/vitest.config.ts b/packages/platform-node/vitest.config.ts new file mode 100644 index 0000000000..adddce25ec --- /dev/null +++ b/packages/platform-node/vitest.config.ts @@ -0,0 +1,7 @@ +import { mergeConfig, type ViteUserConfig } from "vitest/config" +import shared from "../../vitest.shared.js" + +const config: ViteUserConfig = { +} + +export default mergeConfig(shared, config) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 88ba851b0e..8ba50bf5f3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -184,6 +184,24 @@ importers: version: 3.24.3 publishDirectory: dist + packages/platform-node: + dependencies: + '@effect/platform-node-shared': + specifier: workspace:^ + version: link:../platform-node-shared + devDependencies: + effect: + specifier: workspace:^ + version: link:../effect + publishDirectory: dist + + packages/platform-node-shared: + devDependencies: + effect: + specifier: workspace:^ + version: link:../effect + publishDirectory: dist + packages/vitest: devDependencies: effect: @@ -196,6 +214,9 @@ importers: scratchpad: dependencies: + '@effect/platform-node': + specifier: workspace:* + version: link:../packages/platform-node effect: specifier: workspace:* version: link:../packages/effect diff --git a/scratchpad/package.json b/scratchpad/package.json index 2a9980360d..704a9e6d1f 100644 --- a/scratchpad/package.json +++ b/scratchpad/package.json @@ -4,6 +4,7 @@ "type": "module", "version": "0.0.0", "dependencies": { - "effect": "workspace:*" + "effect": "workspace:*", + "@effect/platform-node": "workspace:*" } } diff --git a/tsconfig.build.json b/tsconfig.build.json index 5e7428a1b3..f979da17d3 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -3,6 +3,8 @@ "include": [], "references": [ { "path": "packages/effect/tsconfig.build.json" }, + { "path": "packages/platform-node/tsconfig.build.json" }, + { "path": "packages/platform-node-shared/tsconfig.build.json" }, { "path": "packages/vitest/tsconfig.build.json" } ] } diff --git a/tsconfig.json b/tsconfig.json index 9966dbb723..ff5d02bb7e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,6 +3,8 @@ "include": [], "references": [ { "path": "packages/effect" }, + { "path": "packages/platform-node" }, + { "path": "packages/platform-node-shared" }, { "path": "packages/vitest" } ] } diff --git a/vitest.workspace.ts b/vitest.workspace.ts index 58f6bf15e9..f7bfa5fc89 100644 --- a/vitest.workspace.ts +++ b/vitest.workspace.ts @@ -1,5 +1,5 @@ import { defineWorkspace } from "vitest/config" export default defineWorkspace([ - "packages/*/vitest.config.ts", + "packages/*/vitest.config.ts" ])