### Run create-effect-app with Bun Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/create-effect-app.mdx Use this command to start an interactive project setup with the latest version of create-effect-app using Bun. ```bash bunx create-effect-app@latest ``` -------------------------------- ### Run create-effect-app with npm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/create-effect-app.mdx Use this command to start an interactive project setup with the latest version of create-effect-app using npm. ```bash npx create-effect-app@latest ``` -------------------------------- ### Install @effect/platform with Bun Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/platform/introduction.mdx Use this command to install the beta version of @effect/platform using Bun. ```sh bun add @effect/platform ``` -------------------------------- ### Run create-effect-app with pnpm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/create-effect-app.mdx Use this command to start an interactive project setup with the latest version of create-effect-app using pnpm. ```bash pnpm create effect-app@latest ``` -------------------------------- ### Basic Usage Example Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/platform/key-value-store.mdx Demonstrates basic operations like setting, getting, and removing key-value pairs using the in-memory store. ```typescript import { KeyValueStore, layerMemory } from "@effect/platform/KeyValueStore" import { Effect } from "effect" const program = Effect.gen(function* () { const kv = yield* KeyValueStore // Store is initially empty console.log(yield* kv.size) // Set a key-value pair yield* kv.set("key", "value") console.log(yield* kv.size) // Retrieve the value const value = yield* kv.get("key") console.log(value) // Remove the key yield* kv.remove("key") console.log(yield* kv.size) }) // Run the program using the in-memory store implementation Effect.runPromise(program.pipe(Effect.provide(layerMemory))) /* Output: 0 1 { _id: 'Option', _tag: 'Some', value: 'value' } 0 */ ``` -------------------------------- ### Install @effect/platform with Deno Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/platform/introduction.mdx Use this command to install the beta version of @effect/platform with Deno. ```sh deno add npm:@effect/platform ``` -------------------------------- ### Run create-effect-app with Yarn Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/create-effect-app.mdx Use this command to start an interactive project setup with the latest version of create-effect-app using Yarn. ```bash yarn create effect-app@latest ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/installation.mdx Navigate into your project directory and install the required packages using your chosen package manager. ```sh cd hello-effect npm install ``` ```sh cd hello-effect pnpm install ``` ```sh cd hello-effect yarn install ``` ```sh cd hello-effect bun install ``` ```sh cd hello-effect denO install ``` -------------------------------- ### Install @effect/platform with Yarn Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/platform/introduction.mdx Use this command to install the beta version of @effect/platform using Yarn. ```sh yarn add @effect/platform ``` -------------------------------- ### Install @effect/platform with pnpm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/platform/introduction.mdx Use this command to install the beta version of @effect/platform using pnpm. ```sh pnpm add @effect/platform ``` -------------------------------- ### Install Effect v4 Beta with Bun Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/effect/4.0-beta.mdx Use this command to install the beta version of Effect using Bun. ```bash bun add effect@beta ``` -------------------------------- ### Install @effect/platform with npm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/platform/introduction.mdx Use this command to install the beta version of @effect/platform using npm. ```sh npm install @effect/platform ``` -------------------------------- ### Install Effect v4 Beta with Yarn Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/effect/4.0-beta.mdx Use this command to install the beta version of Effect using Yarn. ```bash yarn add effect@beta ``` -------------------------------- ### Create Project Directory and Navigate Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/installation.mdx Use these commands to create a new project directory and move into it for your Effect project setup. ```bash mkdir hello-effect cd hello-effect ``` -------------------------------- ### Install Effect v4 Beta with npm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/effect/4.0-beta.mdx Use this command to install the beta version of Effect using npm. ```bash npm install effect@beta ``` -------------------------------- ### Install Effect v4 Beta with pnpm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/effect/4.0-beta.mdx Use this command to install the beta version of Effect using pnpm. ```bash pnpm add effect@beta ``` -------------------------------- ### Install Effect Language Service with Bun Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/devtools.mdx Install the Effect Language Service as a development dependency using Bun. ```sh bun add --dev @effect/language-service ``` -------------------------------- ### Install Effect Experimental Package Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/devtools.mdx Install the @effect/experimental package to use the built-in tracer and metrics view. Choose the command for your package manager. ```sh npm install @effect/experimental ``` ```sh pnpm install @effect/experimental ``` ```sh yarn add @effect/experimental ``` ```sh bun add @effect/experimental ``` -------------------------------- ### Schema Type Examples Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/schema/introduction.mdx Provides examples of Schema type instantiations. Use these to understand how to define schemas for different data types and encoding requirements. ```typescript Schema ``` ```typescript Schema ``` -------------------------------- ### Install Effect AI Packages Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/ai/getting-started.mdx Install the base `@effect/ai` package and a provider integration like `@effect/ai-openai`. The core `effect` package is also required. ```sh # Install the base package for the core abstractions (always required) npm install @effect/ai # Install one (or more) provider integrations npm install @effect/ai-openai # Also add the core Effect package (if not already installed) npm install effect ``` ```sh # Install the base package for the core abstractions (always required) pnpm add @effect/ai # Install one (or more) provider integrations pnpm add @effect/ai-openai # Also add the core Effect package (if not already installed) pnpm add effect ``` ```sh # Install the base package for the core abstractions (always required) yarn add @effect/ai # Install one (or more) provider integrations yarn add @effect/ai-openai # Also add the core Effect package (if not already installed) yarn add effect ``` ```sh # Install the base package for the core abstractions (always required) bun add @effect/ai # Install one (or more) provider integrations bun add @effect/ai-openai # Also add the core Effect package (if not already installed) bun add effect ``` -------------------------------- ### Install Effect-TS OpenTelemetry Integration and SDKs Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/observability/tracing.mdx Install the main library for integrating OpenTelemetry with Effect and the required OpenTelemetry SDKs for tracing and metrics. ```bash bun add @effect/opentelemetry bun add @opentelemetry/sdk-trace-base bun add @opentelemetry/sdk-trace-node bun add @opentelemetry/sdk-trace-web bun add @opentelemetry/sdk-metrics ``` -------------------------------- ### Initialize TypeScript Project with npm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/installation.mdx Initialize a new Node.js project and install TypeScript as a development dependency using npm. ```bash npm init -y npm install --save-dev typescript ``` -------------------------------- ### Install Effect Language Service with Yarn Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/devtools.mdx Install the Effect Language Service as a development dependency using Yarn. ```sh yarn add --dev @effect/language-service ``` -------------------------------- ### Encode Examples with optionalToOptional Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/schema/advanced-usage.mdx Demonstrates encoding with the defined schema, showing how the output is generated based on the input. ```typescript const encode = Schema.encodeSync(schema) console.log(encode({})) // Output: {} console.log(encode({ nonEmpty: "" })) // Output: { nonEmpty: '' } console.log(encode({ nonEmpty: "a non-empty string" })) // Output: { nonEmpty: 'a non-empty string' } ``` -------------------------------- ### Initialize TypeScript Project with pnpm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/installation.mdx Initialize a new Node.js project and install TypeScript as a development dependency using pnpm. ```bash pnpm init pnpm add --save-dev typescript ``` -------------------------------- ### Decode Examples with optionalToOptional Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/schema/advanced-usage.mdx Demonstrates decoding with the defined schema, showing how empty strings and absent fields are handled. ```typescript const decode = Schema.decodeUnknownSync(schema) console.log(decode({})) // Output: {} console.log(decode({ nonEmpty: "" })) // Output: {} console.log(decode({ nonEmpty: "a non-empty string" })) // Output: { nonEmpty: 'a non-empty string' } ``` -------------------------------- ### Initialize TypeScript Project with Yarn Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/installation.mdx Initialize a new Node.js project and install TypeScript as a development dependency using Yarn. ```bash yarn init -y yarn add --dev typescript ``` -------------------------------- ### End-to-End LLM Interaction with Effect Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/effect-ai.mdx A complete example showing how to define a provider-agnostic AI interaction, create a specific model, build a program, and set up layers for the OpenAI client and HTTP transport. This example requires `@effect/ai`, `@effect/ai-openai`, and `@effect/platform-node`. ```typescript import { LanguageModel } from "@effect/ai" import { OpenAiClient, OpenAiLanguageModel } from "@effect/ai-openai" import { NodeHttpClient } from "@effect/platform-node" import { Config, Console, Effect, Layer } from "effect" // 1. Define our provider-agnostic AI interaction const generateDadJoke = LanguageModel.generateText({ prompt: "Generate a dad joke" }) // 2. Create an AiModel for a specific provider and model const Gpt4o = OpenAiLanguageModel.model("gpt-4o") // 3. Create a program that uses the model const main = generateDadJoke.pipe( Effect.flatMap((response) => Console.log(response.text)), Effect.provide(Gpt4o) ) // 4. Create a Layer that provides the OpenAI client const OpenAi = OpenAiClient.layerConfig({ apiKey: Config.redacted("OPENAI_API_KEY") }) // 5. Provide an HTTP client implementation const OpenAiWithHttp = Layer.provide(OpenAi, NodeHttpClient.layerUndici) // 6. Run the program with the provided dependencies main.pipe( Effect.provide(OpenAiWithHttp), Effect.runPromise ) ``` -------------------------------- ### Start OpenTelemetry Backend with Docker Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/observability/tracing.mdx Run the OpenTelemetry backend using Docker. This command exposes the necessary ports for trace collection. ```sh docker run -p 3000:3000 -p 4317:4317 -p 4318:4318 --rm -it docker.io/grafana/otel-lgtm ``` -------------------------------- ### Non-interactive create-effect-app usage Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/create-effect-app.mdx Command structure for non-interactive project setup, allowing specification of template, features, and project name. ```bash create-effect-app (-t, --template basic | cli | monorepo) [--changesets] [--flake] [--eslint] [--workflows] [] create-effect-app (-e, --example http-server) [] ``` -------------------------------- ### Install Effect 3.20.0 Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/effect-3-20-security-update.mdx Use this command to upgrade Effect to the patched version 3.20.0 or later. This is the recommended solution for the security issue. ```bash pnpm add effect@^3.20.0 ``` -------------------------------- ### Initialize Deno Project Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/installation.mdx Initialize a new Deno project in the current directory. ```bash deno init ``` -------------------------------- ### Late Fiber Start Captures Only One Value Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/concurrency/fibers.mdx When a fiber is forked using `Effect.fork` without any yielding, it may start after updates have occurred, leading to missed events. This example demonstrates how a stream only captures a single value because the forked fiber starts too late. ```ts import { Effect, SubscriptionRef, Stream, Console } from "effect" const program = Effect.gen(function* () { const ref = yield* SubscriptionRef.make(0) yield* ref.changes.pipe( // Log each change in SubscriptionRef Stream.tap((n) => Console.log(`SubscriptionRef changed to ${n}`)), Stream.runDrain, // Fork a fiber to run the stream Effect.fork ) yield* SubscriptionRef.set(ref, 1) yield* SubscriptionRef.set(ref, 2) }) Effect.runFork(program) ``` -------------------------------- ### Starting an Effect without awaiting (Forking) Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/additional-resources/effect-vs-promise.mdx Demonstrates the Effect-TS equivalent of starting a task without immediate awaiting using `Effect.fork`. This returns a Fiber, which can be joined later to get the result, enabling true concurrency. ```typescript import { Effect, Fiber } from "effect" const task = (delay: number, name: string) => Effect.gen(function* () { yield* Effect.sleep(delay) console.log(`${name} done`) return name }) const program = Effect.gen(function* () { const r0 = yield* Effect.fork(task(2_000, "long running task")) const r1 = yield* task(200, "task 2") const r2 = yield* task(100, "task 3") return { r1, r2, r0: yield* Fiber.join(r0) } }) Effect.runPromise(program).then(console.log) /* Output: task 2 done task 3 done long running task done { r1: 'task 2', r2: 'task 3', r0: 'long running promise' } */ ``` -------------------------------- ### Start Development Server Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/installation.mdx Run the development server to see your Vite + React + Effect application in action. Use the command corresponding to your package manager. ```sh npm run dev ``` ```sh pnpm run dev ``` ```sh yarn run dev ``` ```sh bun run dev ``` ```sh deno run dev ``` -------------------------------- ### Unbounded Concurrency Example Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/concurrency/basic-concurrency.mdx Shows how to run an unlimited number of effects concurrently by setting `concurrency` to 'unbounded'. All tasks will start as soon as possible. ```typescript import { Effect, Duration } from "effect" // Helper function to simulate a task with a delay const makeTask = (n: number, delay: Duration.DurationInput) => Effect.promise( () => new Promise((resolve) => { console.log(`start task${n}`) setTimeout(() => { console.log(`task${n} done`) resolve() }, Duration.toMillis(delay)) }) ) const task1 = makeTask(1, "200 millis") const task2 = makeTask(2, "100 millis") const task3 = makeTask(3, "210 millis") const task4 = makeTask(4, "110 millis") const task5 = makeTask(5, "150 millis") const unbounded = Effect.all([task1, task2, task3, task4, task5], { concurrency: "unbounded" }) Effect.runPromise(unbounded) /* Output: start task1 start task2 start task3 start task4 start task5 task2 done task4 done task5 done task1 done task3 done */ ``` -------------------------------- ### Interleaving Two Streams with Stream.merge Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/stream/operations.mdx Combines elements from two source streams into a single stream, interleaving elements as they are produced. Unlike Stream.concat, Stream.merge does not wait for one stream to finish before starting the other. This example merges two streams with different emission intervals. ```typescript import { Schedule, Stream, Effect } from "effect" // Create two streams with different emission intervals const s1 = Stream.make(1, 2, 3).pipe( Stream.schedule(Schedule.spaced("100 millis")) ) const s2 = Stream.make(4, 5, 6).pipe( Stream.schedule(Schedule.spaced("200 millis")) ) // Merge s1 and s2 into a single stream that interleaves their values const merged = Stream.merge(s1, s2) Effect.runPromise(Stream.runCollect(merged)).then(console.log) /* Output: { _id: 'Chunk', values: [ 1, 4, 2, 3, 5, 6 ] } */ ``` -------------------------------- ### Notify Todo Owners with Effect-TS Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/batching.mdx This example demonstrates how to fetch todos and notify their owners using Effect-TS. It includes models for User and Todo, and API functions for getting users, todos, and sending emails. Note that this implementation may lead to redundant API calls if multiple todos share the same owner. ```typescript import { Effect, Data } from "effect" // ------------------------------ // Model // ------------------------------ interface User { readonly _tag: "User" readonly id: number readonly name: string readonly email: string } class GetUserError extends Data.TaggedError("GetUserError")<{}> {} interface Todo { readonly _tag: "Todo" readonly id: number readonly message: string readonly ownerId: number } class GetTodosError extends Data.TaggedError("GetTodosError")<{}> {} class SendEmailError extends Data.TaggedError("SendEmailError")<{}> {} // ------------------------------ // API // ------------------------------ // Fetches a list of todos from an external API const getTodos = Effect.tryPromise({ try: () => fetch("https://api.example.demo/todos").then( (res) => res.json() as Promise> ), catch: () => new GetTodosError() }) // Retrieves a user by their ID from an external API const getUserById = (id: number) => Effect.tryPromise({ try: () => fetch(`https://api.example.demo/getUserById?id=${id}`).then( (res) => res.json() as Promise ), catch: () => new GetUserError() }) // Sends an email via an external API const sendEmail = (address: string, text: string) => Effect.tryPromise({ try: () => fetch("https://api.example.demo/sendEmail", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ address, text }) }).then((res) => res.json() as Promise), catch: () => new SendEmailError() }) // Sends an email to a user by fetching their details first const sendEmailToUser = (id: number, message: string) => getUserById(id).pipe( Effect.andThen((user) => sendEmail(user.email, message)) ) // Notifies the owner of a todo by sending them an email const notifyOwner = (todo: Todo) => getUserById(todo.ownerId).pipe( Effect.andThen((user) => sendEmailToUser(user.id, `hey ${user.name} you got a todo!`) ) ) // Orchestrates operations on todos, notifying their owners const program = Effect.gen(function* () { const todos = yield* getTodos yield* Effect.forEach(todos, (todo) => notifyOwner(todo), { concurrency: "unbounded" }) }) ``` -------------------------------- ### Initialize Bun Project Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/installation.mdx Run this command to initialize a new Bun project. It generates a tsconfig.json file. ```bash bun init ``` -------------------------------- ### Create Source Directory and Index File Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/installation.mdx Set up the 'src' directory and create an 'index.ts' file for your Effect application. ```bash mkdir src touch src/index.ts ``` -------------------------------- ### Basic Queue Operations: Offer and Take Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/concurrency/queue.mdx Demonstrates the fundamental operations of adding an item to a queue using `Queue.offer` and retrieving it with `Queue.take`. This example uses a bounded queue with a capacity of 100. ```ts import { Effect, Queue } from "effect" const program = Effect.gen(function* () { // Creates a bounded queue with capacity 100 const queue = yield* Queue.bounded(100) // Adds 1 to the queue yield* Queue.offer(queue, 1) // Retrieves and removes the oldest value const value = yield* Queue.take(queue) return value }) Effect.runPromise(program).then(console.log) // Output: 1 ``` -------------------------------- ### Install Effect Package Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/importing-effect.mdx Install the Effect package using your preferred package manager. This command is for npm. ```sh npm install effect ``` ```sh pnpm add effect ``` ```sh yarn add effect ``` ```sh bun add effect ``` ```sh deno add npm:effect ``` -------------------------------- ### Basic HashSet Example Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/data-types/hash-set.mdx Demonstrates the creation and basic operations of a HashSet, including adding elements, performing set operations like union, intersection, and difference. ```APIDOC ```ts twoslash import { HashSet } from "effect" // Create an initial set with 3 values const set1 = HashSet.make(1, 2, 3) // Add a value (returns a new set) const set2 = HashSet.add(set1, 4) // The original set is unchanged console.log(HashSet.toValues(set1)) // Output: [1, 2, 3] console.log(HashSet.toValues(set2)) // Output: [1, 2, 3, 4] // Perform set operations with another set const set3 = HashSet.make(3, 4, 5) // Combine both sets const union = HashSet.union(set2, set3) console.log(HashSet.toValues(union)) // Output: [1, 2, 3, 4, 5] // Shared values const intersection = HashSet.intersection(set2, set3) console.log(HashSet.toValues(intersection)) // Output: [3, 4] // Values only in set2 const difference = HashSet.difference(set2, set3) console.log(HashSet.toValues(difference)) // Output: [1, 2] ``` ``` -------------------------------- ### Install Effect Language Service with pnpm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/devtools.mdx Install the Effect Language Service as a development dependency using pnpm. ```sh pnpm add -D @effect/language-service ``` -------------------------------- ### Install Effect Language Service with npm Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/devtools.mdx Install the Effect Language Service as a development dependency using npm. ```sh npm install @effect/language-service --save-dev ``` -------------------------------- ### Handle Full Queue with Effect.fork Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/concurrency/queue.mdx Demonstrates how to handle a full bounded queue by forking the `Queue.offer` operation. This prevents the main fiber from suspending and allows the operation to complete once space becomes available. ```ts import { Effect, Queue, Fiber } from "effect" const program = Effect.gen(function* () { const queue = yield* Queue.bounded(1) // Fill the queue with one item yield* Queue.offer(queue, 1) // Attempting to add a second item will suspend as the queue is full const fiber = yield* Effect.fork(Queue.offer(queue, 2)) // Empties the queue to make space yield* Queue.take(queue) // Joins the fiber, completing the suspended offer yield* Fiber.join(fiber) // Returns the size of the queue after additions return yield* Queue.size(queue) }) Effect.runPromise(program).then(console.log) // Output: 1 ``` -------------------------------- ### Create and Operate on HashSets Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/data-types/hash-set.mdx Demonstrates basic HashSet creation using `make`, adding elements with `add`, and performing set operations like `union`, `intersection`, and `difference`. Note that operations return new sets, leaving the original unchanged. ```ts import { HashSet } from "effect" // Create an initial set with 3 values const set1 = HashSet.make(1, 2, 3) // Add a value (returns a new set) const set2 = HashSet.add(set1, 4) // The original set is unchanged console.log(HashSet.toValues(set1)) // Output: [1, 2, 3] console.log(HashSet.toValues(set2)) // Output: [1, 2, 3, 4] // Perform set operations with another set const set3 = HashSet.make(3, 4, 5) // Combine both sets const union = HashSet.union(set2, set3) console.log(HashSet.toValues(union)) // Output: [1, 2, 3, 4, 5] // Shared values const intersection = HashSet.intersection(set2, set3) console.log(HashSet.toValues(intersection)) // Output: [3, 4] // Values only in set2 const difference = HashSet.difference(set2, set3) console.log(HashSet.toValues(difference)) // Output: [1, 2] ``` -------------------------------- ### Install OpenTelemetry Dependencies Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/observability/tracing.mdx Install the necessary libraries for integrating OpenTelemetry with Effect-TS for tracing and metrics. Choose the appropriate package manager for your project. ```sh # Install the main library for integrating OpenTelemetry with Effect npm install @effect/opentelemetry # Install the required OpenTelemetry SDKs for tracing and metrics npm install @opentelemetry/sdk-trace-base npm install @opentelemetry/sdk-trace-node npm install @opentelemetry/sdk-trace-web npm install @opentelemetry/sdk-metrics ``` ```sh # Install the main library for integrating OpenTelemetry with Effect pnpm add @effect/opentelemetry # Install the required OpenTelemetry SDKs for tracing and metrics pnpm add @opentelemetry/sdk-trace-base pnpm add @opentelemetry/sdk-trace-node pnpm add @opentelemetry/sdk-trace-web pnpm add @opentelemetry/sdk-metrics ``` ```sh # Install the main library for integrating OpenTelemetry with Effect yarn add @effect/opentelemetry # Install the required OpenTelemetry SDKs for tracing and metrics yarn add @opentelemetry/sdk-trace-base yarn add @opentelemetry/sdk-trace-node yarn add @opentelemetry/sdk-trace-web yarn add @opentelemetry/sdk-metrics ``` ```sh # Install the main library for integrating OpenTelemetry with Effect bun add @effect/opentelemetry # Install the required OpenTelemetry SDKs for tracing and metrics bun add @opentelemetry/sdk-trace-base bun add @opentelemetry/sdk-trace-node bun add @opentelemetry/sdk-trace-web bun add @opentelemetry/sdk-metrics ``` -------------------------------- ### Create Effect project with Bun (non-interactive) Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/releases/create-effect-app.mdx Example of creating a new Effect project named 'my-effect-app' using the basic template and ESLint integration via Bun. ```bash bunx create-effect-app@latest --template basic --eslint my-effect-app ``` -------------------------------- ### Finding Configuration with Fallbacks Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/error-management/fallback.mdx This example demonstrates how to use Effect.firstSuccessOf to retrieve configuration from a primary source and fall back to other sources if the primary fails. It simulates retrieving configuration from different nodes, prioritizing the master node and then trying a list of other nodes. ```typescript import { Effect, Console } from "effect" interface Config { host: string port: number apiKey: string } // Create a configuration object with sample values const makeConfig = (name: string): Config => ({ host: `${name}.example.com`, port: 8080, apiKey: "12345-abcde" }) // Simulate retrieving configuration from a remote node const remoteConfig = (name: string): Effect.Effect => Effect.gen(function* () { // Simulate node3 being the only one with available config if (name === "node3") { yield* Console.log(`Config for ${name} found`) return makeConfig(name) } else { yield* Console.log(`Unavailable config for ${name}`) return yield* Effect.fail(new Error(`Config not found for ${name}`)) } }) // Define the master configuration and potential fallback nodes const masterConfig = remoteConfig("master") const nodeConfigs = ["node1", "node2", "node3", "node4"].map(remoteConfig) // Attempt to find a working configuration, // starting with the master and then falling back to other nodes const config = Effect.firstSuccessOf([masterConfig, ...nodeConfigs]) // Run the effect to retrieve the configuration const result = Effect.runSync(config) console.log(result) /* Output: Unavailable config for master Unavailable config for node1 Unavailable config for node2 Config for node3 found { host: 'node3.example.com', port: 8080, apiKey: '12345-abcde' } */ ``` -------------------------------- ### Create a SubscriptionRef Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/state-management/subscriptionref.mdx Demonstrates how to create a new SubscriptionRef with an initial value using the `SubscriptionRef.make` constructor. ```typescript import { SubscriptionRef } from "effect" const ref = SubscriptionRef.make(0) ``` -------------------------------- ### Install Effect-TS OpenTelemetry Dependencies (Bun) Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/observability/tracing.mdx Install the required Effect-TS and OpenTelemetry packages using Bun. This includes the core Effect library, the OpenTelemetry integration, and exporters. ```sh # If not already installed bun add effect # Required to integrate Effect with OpenTelemetry bun add @effect/opentelemetry # Required to export traces over HTTP in OTLP format bun add @opentelemetry/exporter-trace-otlp-http # Required by all applications bun add @opentelemetry/sdk-trace-base # For NodeJS applications bun add @opentelemetry/sdk-trace-node # For browser applications bun add @opentelemetry/sdk-trace-web # If you also need to export metrics bun add @opentelemetry/sdk-metrics ``` -------------------------------- ### Install Effect-TS OpenTelemetry Dependencies (Yarn) Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/observability/tracing.mdx Install the required Effect-TS and OpenTelemetry packages using Yarn. This includes the core Effect library, the OpenTelemetry integration, and exporters. ```sh # If not already installed yarn add effect # Required to integrate Effect with OpenTelemetry yarn add @effect/opentelemetry # Required to export traces over HTTP in OTLP format yarn add @opentelemetry/exporter-trace-otlp-http # Required by all applications yarn add @opentelemetry/sdk-trace-base # For NodeJS applications yarn add @opentelemetry/sdk-trace-node # For browser applications yarn add @opentelemetry/sdk-trace-web # If you also need to export metrics yarn add @opentelemetry/sdk-metrics ``` -------------------------------- ### Install Effect-TS OpenTelemetry Dependencies (pnpm) Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/observability/tracing.mdx Install the required Effect-TS and OpenTelemetry packages using pnpm. This includes the core Effect library, the OpenTelemetry integration, and exporters. ```sh # If not already installed pnpm add effect # Required to integrate Effect with OpenTelemetry pnpm add @effect/opentelemetry # Required to export traces over HTTP in OTLP format pnpm add @opentelemetry/exporter-trace-otlp-http # Required by all applications pnpm add @opentelemetry/sdk-trace-base # For NodeJS applications pnpm add @opentelemetry/sdk-trace-node # For browser applications pnpm add @opentelemetry/sdk-trace-web # If you also need to export metrics pnpm add @opentelemetry/sdk-metrics ``` -------------------------------- ### Install Effect-TS OpenTelemetry Dependencies (npm) Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/observability/tracing.mdx Install the required Effect-TS and OpenTelemetry packages using npm. This includes the core Effect library, the OpenTelemetry integration, and exporters. ```sh # If not already installed npm install effect # Required to integrate Effect with OpenTelemetry npm install @effect/opentelemetry # Required to export traces over HTTP in OTLP format npm install @opentelemetry/exporter-trace-otlp-http # Required by all applications npm install @opentelemetry/sdk-trace-base # For NodeJS applications npm install @opentelemetry/sdk-trace-node # For browser applications npm install @opentelemetry/sdk-trace-web # If you also need to export metrics npm install @opentelemetry/sdk-metrics ``` -------------------------------- ### Create and Use OpenAI Language Model Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/blog/effect-ai.mdx Demonstrates creating an `AiModel` for OpenAI's GPT-4o to satisfy the `LanguageModel` service and using it to generate text. Ensure the necessary Effect AI and AI provider packages are installed. ```typescript import { LanguageModel } from "@effect/ai" import { OpenAiLanguageModel } from "@effect/ai-openai" import { Console, Effect } from "effect" const generateDadJoke = LanguageModel.generateText({ prompt: "Generate a dad joke" }) // Create an AiModel for OpenAI's GPT-4o const Gpt4o = OpenAiLanguageModel.model("gpt-4o") const main = generateDadJoke.pipe( // Log out the generated text Effect.flatMap((response) => Console.log(response.text)), // Provide the concrete model to the program Effect.provide(Gpt4o) ) ``` -------------------------------- ### Effect flatMap Example: Applying a Discount Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/building-pipelines.mdx Chains an asynchronous fetch operation with a discount application function using Effect.flatMap. This example shows how to handle potential errors from the discount function. ```typescript import { pipe, Effect } from "effect" // Function to apply a discount safely to a transaction amount const applyDiscount = ( total: number, discountRate: number ): Effect.Effect => discountRate === 0 ? Effect.fail(new Error("Discount rate cannot be zero")) : Effect.succeed(total - (total * discountRate) / 100) // Simulated asynchronous task to fetch a transaction amount from database const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) // Chaining the fetch and discount application using `flatMap` const finalAmount = pipe( fetchTransactionAmount, Effect.flatMap((amount) => applyDiscount(amount, 5)) ) Effect.runPromise(finalAmount).then(console.log) // Output: 95 ``` -------------------------------- ### Run Effect Synchronously and Get Exit with runSyncExit Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/getting-started/running-effects.mdx Use `Effect.runSyncExit` to run an effect synchronously and get its outcome as an `Exit` type. This allows inspection of success or failure without exceptions, but will result in a `Die` cause for asynchronous operations. ```typescript import { Effect } from "effect" console.log(Effect.runSyncExit(Effect.succeed(1))) /* Output: { _id: "Exit", _tag: "Success", value: 1 } */ console.log(Effect.runSyncExit(Effect.fail("my error"))) /* Output: { _id: "Exit", _tag: "Failure", cause: { _id: "Cause", _tag: "Fail", failure: "my error" } } */ ``` ```typescript import { Effect } from "effect" console.log(Effect.runSyncExit(Effect.promise(() => Promise.resolve(1)))) /* Output: { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Die', defect: [Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work] { fiber: [FiberRuntime], _tag: 'AsyncFiberException', name: 'AsyncFiberException' } } } */ ``` -------------------------------- ### Interactive Number Guessing Game Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/platform/terminal.mdx An example of a complete number-guessing game that reads input, provides feedback, and continues until the correct number is guessed. It utilizes various `Terminal` service methods and Effect utilities for randomness and control flow. This example requires the Node.js runtime environment. ```typescript import { Terminal } from "@effect/platform" import type { PlatformError } from "@effect/platform/Error" import { Effect, Option, Random } from "effect" import { NodeRuntime, NodeTerminal } from "@effect/platform-node" // Generate a secret random number between 1 and 100 const secret = Random.nextIntBetween(1, 100) // Parse the user's input into a valid number const parseGuess = (input: string) => { const n = parseInt(input, 10) return isNaN(n) || n < 1 || n > 100 ? Option.none() : Option.some(n) } // Display a message on the terminal const display = (message: string) => Effect.gen(function* () { const terminal = yield* Terminal.Terminal yield* terminal.display(`${message}\n`) }) // Prompt the user for a guess const prompt = Effect.gen(function* () { const terminal = yield* Terminal.Terminal yield* terminal.display("Enter a guess: ") return yield* terminal.readLine }) // Get the user's guess, validating it as an integer between 1 and 100 const answer: Effect.Effect< number, Terminal.QuitException | PlatformError, Terminal.Terminal > = Effect.gen(function* () { const input = yield* prompt const guess = parseGuess(input) if (Option.isNone(guess)) { yield* display("You must enter an integer from 1 to 100") return yield* answer } return guess.value }) // Check if the guess is too high, too low, or correct const check = ( secret: number, guess: number, ok: Effect.Effect, ko: Effect.Effect ) => Effect.gen(function* () { if (guess > secret) { yield* display("Too high") return yield* ko } else if (guess < secret) { yield* display("Too low") return yield* ko } else { return yield* ok } }) // End the game with a success message const end = display("You guessed it!") // Main game loop const loop = ( secret: number ): Effect.Effect< void, Terminal.QuitException | PlatformError, Terminal.Terminal > => Effect.gen(function* () { const guess = yield* answer return yield* check( secret, guess, end, Effect.suspend(() => loop(secret)) ) }) // Full game setup and execution const game = Effect.gen(function* () { yield* display( `We have selected a random number between 1 and 100. See if you can guess it in 10 turns or fewer. We'll tell you if your guess was too high or too low.` ) yield* loop(yield* secret) }) // Run the game NodeRuntime.runMain(game.pipe(Effect.provide(NodeTerminal.layer))) ``` -------------------------------- ### Create a Bounded Queue Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/concurrency/queue.mdx Illustrates how to create a bounded queue with a specified maximum capacity. `Queue.bounded` ensures that the queue will not exceed the given size, applying back-pressure when full. ```ts import { Queue } from "effect" // Creating a bounded queue with a capacity of 100 const boundedQueue = Queue.bounded(100) ``` -------------------------------- ### Providing a Mock Service Implementation Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/requirements-management/layers.mdx Demonstrates how to provide an alternative implementation for a service, such as a mock, by supplying a value for the service class when wiring layers. This is useful for testing or specific runtime configurations. ```typescript const mock = new MyService({ /* mocked methods */ }) program.pipe(Effect.provideService(MyService, mock)) ``` -------------------------------- ### Create Schedule from Cron Expression Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/scheduling/cron.mdx Convert a cron expression or `Cron` instance into an Effect `Schedule` using `Schedule.cron`. This schedule will trigger at the start of each cron interval, producing the interval's start and end timestamps in milliseconds. This is useful for implementing retry logic or periodic tasks based on cron. ```typescript import { Effect, Schedule, TestClock, Fiber, TestContext, Cron, Console } from "effect" // A helper function to log output at each interval of the schedule const log = ( action: Effect.Effect, schedule: Schedule.Schedule<[number, number], void> ): void => { let i = 0 Effect.gen(function* () { const fiber: Fiber.RuntimeFiber<[[number, number], number]> = yield* Effect.gen(function* () { yield* action i++ }).pipe( Effect.repeat( schedule.pipe( // Limit the number of iterations for the example Schedule.intersect(Schedule.recurs(10)), Schedule.tapOutput(([Out]) => Console.log( i === 11 ? "..." : [new Date(Out[0]), new Date(Out[1])] ) ) ) ), Effect.fork ) yield* TestClock.adjust(Infinity) yield* Fiber.join(fiber) }).pipe(Effect.provide(TestContext.TestContext), Effect.runPromise) } // Build a cron that triggers at 4:00 AM // on the 8th to the 14th of each month const cron = Cron.unsafeParse("0 0 4 8-14 * *", "UTC") // Convert the Cron into a Schedule const schedule = Schedule.cron(cron) // Define a dummy action to repeat const action = Effect.void // Log the schedule intervals log(action, schedule) /* Output: [ 1970-01-08T04:00:00.000Z, 1970-01-08T04:00:01.000Z ] [ 1970-01-09T04:00:00.000Z, 1970-01-09T04:00:01.000Z ] [ 1970-01-10T04:00:00.000Z, 1970-01-10T04:00:01.000Z ] [ 1970-01-11T04:00:00.000Z, 1970-01-11T04:00:01.000Z ] [ 1970-01-12T04:00:00.000Z, 1970-01-12T04:00:01.000Z ] [ 1970-01-13T04:00:00.000Z, 1970-01-13T04:00:01.000Z ] [ 1970-01-14T04:00:00.000Z, 1970-01-14T04:00:01.000Z ] [ 1970-02-08T04:00:00.000Z, 1970-02-08T04:00:01.000Z ] [ 1970-02-09T04:00:00.000Z, 1970-02-09T04:00:01.000Z ] [ 1970-02-10T04:00:00.000Z, 1970-02-10T04:00:01.000Z ] ... */ ``` -------------------------------- ### Customize Schema with Annotations Source: https://github.com/effect-ts/website/blob/main/content/src/content/docs/docs/schema/annotations.mdx This example demonstrates how to use annotations to customize a string schema. It adds custom error messages for validation failures like non-string types, empty strings, and exceeding maximum length. It also includes metadata such as an identifier, title, description, examples, and general documentation. ```typescript import { Schema } from "effect" // Define a Password schema, starting with a string type const Password = Schema.String // Add a custom error message for non-string values .annotations({ message: () => "not a string" }) .pipe( // Enforce non-empty strings and provide a custom error message Schema.nonEmptyString({ message: () => "required" }), // Restrict the string length to 10 characters or fewer // with a custom error message for exceeding length Schema.maxLength(10, { message: (issue) => `${issue.actual} is too long` }) ) .annotations({ // Add a unique identifier for the schema identifier: "Password", // Provide a title for the schema title: "password", // Include a description explaining what this schema represents description: "A password is a secret string used to authenticate a user", // Add examples for better clarity examples: ["1Ki77y", "jelly22fi$h"], // Include any additional documentation documentation: `...technical information on Password schema...` }) ```