### Install @effect/platform using deno Source: https://effect.website/docs/platform/introduction Use this command to install the beta version of @effect/platform with deno. ```bash deno add npm:@effect/platform ``` -------------------------------- ### Install @effect/platform-bun using bun Source: https://effect.website/docs/platform/introduction Install the Bun-specific package for @effect/platform using bun. ```bash bun add @effect/platform-bun ``` -------------------------------- ### Install Effect with bun Source: https://effect.website/docs/getting-started/importing-effect Install the effect package using bun. ```bash bun add effect ``` -------------------------------- ### Install Effect with Deno Source: https://effect.website/docs/getting-started/importing-effect Install the effect package for Deno. ```bash deno add npm:effect ``` -------------------------------- ### Install @effect/platform using bun Source: https://effect.website/docs/platform/introduction Use this command to install the beta version of @effect/platform with bun. ```bash bun add @effect/platform ``` -------------------------------- ### Install Project Dependencies Source: https://effect.website/docs/getting-started/installation Navigate into your project directory and install the necessary packages using your preferred package manager. ```bash cd hello-effect npm install ``` ```bash cd hello-effect pnpm install ``` ```bash cd hello-effect yarn install ``` ```bash cd hello-effect bun install ``` ```bash cd hello-effect den install ``` -------------------------------- ### Install @effect/platform using yarn Source: https://effect.website/docs/platform/introduction Use this command to install the beta version of @effect/platform with yarn. ```bash yarn add @effect/platform ``` -------------------------------- ### Install Effect with yarn Source: https://effect.website/docs/getting-started/importing-effect Install the effect package using yarn. ```bash yarn add effect ``` -------------------------------- ### Creating a Test Instance with Leaked Dependencies Source: https://effect.website/docs/requirements-management/layers This example demonstrates creating a test instance of a Database service where dependencies are leaked in the interface. It shows how attempting to provide only the Database service without its leaked dependencies (Config, Logger) results in an incomplete setup. ```typescript import { Effect, Context } from "effect" // Declaring a tag for the Config service class Config extends Context.Tag("Config")() {} // Declaring a tag for the Logger service class Logger extends Context.Tag("Logger")() {} // Declaring a tag for the Database service class Database extends Context.Tag("Database")< Database, { readonly query: ( sql: string ) => Effect.Effect } >() {} // Declaring a test instance of the Database service const DatabaseTest = Database.of({ // Simulating a simple response query: (sql: string) => Effect.succeed([]) }) import * as assert from "node:assert" // A test that uses the Database service const test = Effect.gen(function* () { const database = yield* Database const result = yield* database.query("SELECT * FROM users") assert.deepStrictEqual(result, []) }) // ┌─── Effect // ▼ const incompleteTestSetup = test.pipe( // Attempt to provide only the Database service without Config and Logger Effect.provideService(Database, DatabaseTest) ) ``` -------------------------------- ### Install @effect/platform using npm Source: https://effect.website/docs/platform/introduction Use this command to install the beta version of @effect/platform with npm. ```bash npm install @effect/platform ``` -------------------------------- ### Install @effect/platform using pnpm Source: https://effect.website/docs/platform/introduction Use this command to install the beta version of @effect/platform with pnpm. ```bash pnpm add @effect/platform ``` -------------------------------- ### Install @effect/platform-node using deno Source: https://effect.website/docs/platform/introduction Install the Node.js-specific package for @effect/platform using deno. ```bash deno add npm:@effect/platform-node ``` -------------------------------- ### Start Development Server Source: https://effect.website/docs/getting-started/installation Run the development server to preview your application. Press 'o' to open it in your browser. ```bash npm run dev ``` ```bash pnpm run dev ``` ```bash yarn run dev ``` ```bash bun run dev ``` ```bash deno run dev ``` -------------------------------- ### Install Metrics Dependency Source: https://effect.website/docs/observability/tracing Command to install the OpenTelemetry metrics SDK. ```bash bun add @opentelemetry/sdk-metrics ``` -------------------------------- ### Full Server-Client Example with SubscriptionRef Source: https://effect.website/docs/state-management/subscriptionref This example demonstrates a complete server-client model using SubscriptionRef. It forks a server that continuously updates a value, launches multiple clients to observe these changes, and then interrupts the server. The results collected by each client are logged. ```typescript import { Ref, Effect, Stream, Random, SubscriptionRef, Fiber } from "effect" // Server function that increments a shared value forever const server = (ref: Ref.Ref) => Ref.update(ref, (n) => n + 1).pipe(Effect.forever) // Client function that observes the stream of changes const client = (changes: Stream.Stream) => Effect.gen(function* () { const n = yield* Random.nextIntBetween(1, 10) const chunk = yield* Stream.runCollect(Stream.take(changes, n)) return chunk }) const program = Effect.gen(function* () { // Create a SubscriptionRef with an initial value of 0 const ref = yield* SubscriptionRef.make(0) // Fork the server to run concurrently const serverFiber = yield* Effect.fork(server(ref)) // Create 5 clients that subscribe to the changes stream const clients = new Array(5).fill(null).map(() => client(ref.changes)) // Run all clients in concurrently and collect their results const chunks = yield* Effect.all(clients, { concurrency: "unbounded" }) // Interrupt the server when clients are done yield* Fiber.interrupt(serverFiber) // Output the results collected by each client for (const chunk of chunks) { console.log(chunk) } }) Effect.runPromise(program) /* Example Output: { _id: 'Chunk', values: [ 4, 5, 6, 7, 8, 9 ] } { _id: 'Chunk', values: [ 4 ] } { _id: 'Chunk', values: [ 4, 5, 6, 7, 8, 9 ] } { _id: 'Chunk', values: [ 4, 5 ] } { _id: 'Chunk', values: [ 4, 5, 6, 7, 8, 9 ] } */ ``` -------------------------------- ### Install Effect with pnpm Source: https://effect.website/docs/getting-started/importing-effect Install the effect package using pnpm. ```bash pnpm add effect ``` -------------------------------- ### Install Effect with npm Source: https://effect.website/docs/getting-started/importing-effect Install the effect package using npm. ```bash npm install effect ``` -------------------------------- ### Initialize Do Simulation Source: https://effect.website/docs/code-style/do The entry point for starting a Do simulation block. ```typescript const program = Effect.Do.pipe(/* ... rest of the code */) ``` -------------------------------- ### Initialize TypeScript Project Source: https://effect.website/docs/getting-started/installation Commands to initialize a project and install TypeScript as a development dependency. ```bash npm init -y npm install --save-dev typescript ``` ```bash pnpm init pnpm add --save-dev typescript ``` ```bash yarn init -y yarn add --dev typescript ``` -------------------------------- ### Install @effect/platform-node using yarn Source: https://effect.website/docs/platform/introduction Install the Node.js-specific package for @effect/platform using yarn. ```bash yarn add @effect/platform-node ``` -------------------------------- ### Install @effect/platform-node using pnpm Source: https://effect.website/docs/platform/introduction Install the Node.js-specific package for @effect/platform using pnpm. ```bash pnpm add @effect/platform-node ``` -------------------------------- ### Install @effect/platform-node using npm Source: https://effect.website/docs/platform/introduction Install the Node.js-specific package for @effect/platform using npm. ```bash npm install @effect/platform-node ``` -------------------------------- ### Install Tracing Dependencies Source: https://effect.website/docs/observability/tracing Install the necessary OpenTelemetry libraries for tracing and metrics using your preferred package manager. ```bash # 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 ``` ```bash # 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 ``` ```bash # 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 ``` ```bash # 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 ``` -------------------------------- ### Install @effect/experimental Dependency Source: https://effect.website/docs/getting-started/devtools Install the experimental package required for the built-in tracer and metrics view. ```bash npm install @effect/experimental ``` ```bash pnpm install @effect/experimental ``` ```bash yarn add @effect/experimental ``` ```bash bun add @effect/experimental ``` -------------------------------- ### Test Configuration Scenarios Source: https://effect.website/docs/schema/effect-data-types Examples of CLI output when testing configuration with missing, invalid, or valid data. ```bash npx tsx config.ts # Output: # [(Missing data at Foo: "Expected Foo to exist in the process context")] ``` ```bash Foo=bar npx tsx config.ts # Output: # [(Invalid data at Foo: "a string at least 4 character(s) long # └─ Predicate refinement failure # └─ Expected a string at least 4 character(s) long, actual "bar"")] ``` ```bash Foo=foobar npx tsx config.ts # Output: # ok: foobar ``` -------------------------------- ### Using the Path Service Source: https://effect.website/docs/platform/path Example demonstrating how to access the Path service within an Effect program. ```APIDOC ## Usage Example ### Description This example shows how to retrieve the Path service and use the `join` method to construct a file path. ### Code Example ```typescript import { Path } from "@effect/platform" import { Effect } from "effect" import { NodeContext, NodeRuntime } from "@effect/platform-node" const program = Effect.gen(function* () { const path = yield* Path.Path const mypath = path.join("tmp", "file.txt") console.log(mypath) }) NodeRuntime.runMain(program.pipe(Effect.provide(NodeContext.layer))) // Output: "tmp/file.txt" ``` ``` -------------------------------- ### Install Effect AI Packages Source: https://effect.website/docs/ai/getting-started Commands to install the core Effect AI abstractions and provider integrations using various package managers. ```bash # 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 ``` ```bash # 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 ``` ```bash # 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 ``` ```bash # 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 Dependency Source: https://effect.website/docs/getting-started/installation Commands to add the Effect library to the project. ```bash npm install effect ``` ```bash pnpm add effect ``` ```bash yarn add effect ``` -------------------------------- ### Reading a File as a String Source: https://effect.website/docs/platform/file-system Example demonstrating how to read the contents of a file as a string using the FileSystem module. ```APIDOC ## readFileString ### Description Reads the contents of a file at the specified path and returns it as a string. ### Request Example ```typescript const program = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem const content = yield* fs.readFileString("./index.ts", "utf8") console.log(content) }) ``` ``` -------------------------------- ### Basic Effect Program Source: https://effect.website/docs/getting-started/installation A simple program to verify the Effect installation. ```typescript 1 import { Effect, Console } from "effect" 2 3 const program = Console.log("Hello, World!") 4 5 Effect.runSync(program) ``` -------------------------------- ### Install Effect Package Source: https://effect.website/docs/getting-started/installation Add the Effect library as a dependency to your project. Use the appropriate command for your package manager. ```bash npm install effect ``` ```bash pnpm add effect ``` ```bash yarn add effect ``` ```bash bun add effect ``` ```bash deno add npm:effect ``` -------------------------------- ### Define a basic Effect program with OpenAI Source: https://effect.website/docs/ai/getting-started Initial program setup requiring an OpenAiClient to execute. ```typescript 1 import { OpenAiLanguageModel } from "@effect/ai-openai" 2 import { LanguageModel } from "@effect/ai" 3 import { Effect } from "effect" 4 7 collapsed lines 5 const generateDadJoke = Effect.gen(function*() { 6 const response = yield* LanguageModel.generateText({ 7 prompt: "Generate a dad joke" 8 }) 9 console.log(response.text) 10 return response 11 }) 12 13 const Gpt4o = OpenAiLanguageModel.model("gpt-4o") 14 15 // ┌─── Effect, AiError, OpenAiClient> 16 // ▼ 17 const main = generateDadJoke.pipe( 18 Effect.provide(Gpt4o) 19 ) ``` -------------------------------- ### Create a SubscriptionRef Source: https://effect.website/docs/state-management/subscriptionref Use the `SubscriptionRef.make` constructor to initialize a new SubscriptionRef with a starting value. This is the primary way to create a SubscriptionRef. ```typescript import { SubscriptionRef } from "effect" const ref = SubscriptionRef.make(0) ``` -------------------------------- ### Extract Failures and Defects from Cause Source: https://effect.website/docs/data-types/cause Use `Cause.failures` to get an array of expected errors and `Cause.defects` to get an array of unexpected defects from a combined cause. This example runs an Effect that combines failures and defects. ```typescript import { Effect, Cause } from "effect" const program = Effect.gen(function* () { const cause = yield* Effect.cause( Effect.all([ Effect.fail("error 1"), Effect.die("defect"), Effect.fail("error 2") ]) ) console.log(Cause.failures(cause)) console.log(Cause.defects(cause)) }) Effect.runPromise(program) /* Output: { _id: 'Chunk', values: [ 'error 1' ] } { _id: 'Chunk', values: [] } */ ``` -------------------------------- ### Create Source Directory and File Source: https://effect.website/docs/getting-started/installation Commands to set up the source directory and index file. ```bash mkdir src touch src/index.ts ``` -------------------------------- ### Annotating a Span with Effect Source: https://effect.website/docs/observability/tracing This example demonstrates how to add extra information to a span using `Effect.annotateCurrentSpan`. It attaches a key-value pair to the current span for more context. Requires OpenTelemetry SDK setup. ```typescript import { Effect } from "effect" import { NodeSdk } from "@effect/opentelemetry" import { ConsoleSpanExporter, BatchSpanProcessor } from "@opentelemetry/sdk-trace-base" const program = Effect.void.pipe( Effect.delay("100 millis"), // Annotate the span with a key-value pair Effect.tap(() => Effect.annotateCurrentSpan("key", "value")), // Wrap the effect in a span named 'myspan' Effect.withSpan("myspan") ) // Set up tracing with the OpenTelemetry SDK const NodeSdkLive = NodeSdk.layer(() => ({ resource: { serviceName: "example" }, spanProcessor: new BatchSpanProcessor(new ConsoleSpanExporter()) })) // Run the effect, providing the tracing layer Effect.runPromise(program.pipe(Effect.provide(NodeSdkLive))) /* Example Output: { resource: { attributes: { 'service.name': 'example', 'telemetry.sdk.language': 'nodejs', 'telemetry.sdk.name': '@effect/opentelemetry', 'telemetry.sdk.version': '1.28.0' } }, instrumentationScope: { name: 'example', version: undefined, schemaUrl: undefined }, traceId: 'c8120e01c0f1ea83ccc1d388e5cdebd3', parentId: undefined, traceState: undefined, name: 'myspan', id: '81c430ba4979f1db', kind: 0, timestamp: 1733220874356084, duration: 102821.417, attributes: { key: 'value' }, status: { code: 1 }, events: [], links: [] } */ ``` -------------------------------- ### Initialize Deno Project Source: https://effect.website/docs/getting-started/installation Command to initialize a Deno project. ```bash deno init ``` -------------------------------- ### Define a Counter Class with Ref Source: https://effect.website/docs/state-management/ref This snippet defines a Counter class that uses Effect's Ref to manage an internal mutable state. It provides methods to increment, decrement, and get the current value of the counter. The `make` function initializes a new Ref with a starting value of 0 and then creates a new Counter instance. ```typescript import { Effect, Ref } from "effect" class Counter { inc: Effect.Effect dec: Effect.Effect get: Effect.Effect constructor(private value: Ref.Ref) { this.inc = Ref.update(this.value, (n) => n + 1) this.dec = Ref.update(this.value, (n) => n - 1) this.get = Ref.get(this.value) } } const make = Effect.andThen(Ref.make(0), (value) => new Counter(value)) ``` -------------------------------- ### Initialize Bun Project Source: https://effect.website/docs/getting-started/installation Command to initialize a Bun project. ```bash bun init ``` -------------------------------- ### Create Project Directory Source: https://effect.website/docs/getting-started/installation Commands to create and enter a new project directory. ```bash mkdir hello-effect cd hello-effect ``` -------------------------------- ### Creating a SubscriptionRef Source: https://effect.website/docs/state-management/subscriptionref Demonstrates how to create a new SubscriptionRef with an initial value using the `SubscriptionRef.make` constructor. ```APIDOC ## Creating a SubscriptionRef ### Description To create a `SubscriptionRef`, you can use the `SubscriptionRef.make` constructor, specifying the initial value. ### Method `SubscriptionRef.make(initialValue: A): Effect>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { SubscriptionRef } from "effect" const ref = SubscriptionRef.make(0) ``` ### Response #### Success Response (200) - **ref** (SubscriptionRef) - The newly created SubscriptionRef. #### Response Example (This is a constructor, the result is the `SubscriptionRef` object itself.) ``` -------------------------------- ### Providing a Mock Service Implementation Source: https://effect.website/docs/requirements-management/layers Demonstrates how to create a mock implementation of a service and provide it to a program using Effect.provideService. This is useful for testing or when a specific runtime implementation is needed. ```typescript const mock = new MyService({ /* mocked methods */ }) program.pipe(Effect.provideService(MyService, mock)) ``` -------------------------------- ### Effect Diagnostic Example Source: https://effect.website/docs/getting-started/devtools Example code that triggers a diagnostic warning when an Effect is not properly yielded or assigned. ```typescript 1 import { Effect } from "effect" 2 3 Effect.log("Hello world!") 4 // ^- should be run or assigned to a variable! ``` -------------------------------- ### Build a Transaction Pipeline Source: https://effect.website/docs/getting-started/building-pipelines Demonstrates building a transaction pipeline using pipe, Effect.all, and Effect.andThen. This pipeline fetches transaction details, applies a discount, adds a service charge, and formats the final amount. ```typescript import { Effect, pipe } from "effect" // Function to add a small service charge to a transaction amount const addServiceCharge = (amount: number) => amount + 1 // 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)) // Simulated asynchronous task to fetch a discount rate // from a configuration file const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) // Assembling the program using a pipeline of effects const program = pipe( // Combine both fetch effects to get the transaction amount // and discount rate Effect.all([fetchTransactionAmount, fetchDiscountRate]), // Apply the discount to the transaction amount Effect.andThen(([transactionAmount, discountRate]) => applyDiscount(transactionAmount, discountRate) ), // Add the service charge to the discounted amount Effect.andThen(addServiceCharge), // Format the final result for display Effect.andThen( (finalAmount) => `Final amount to charge: ${finalAmount}` ) ) // Execute the program and log the result Effect.runPromise(program).then(console.log) // Output: "Final amount to charge: 96" ``` -------------------------------- ### Mock Configuration Provider for Testing Source: https://effect.website/docs/configuration Shows how to create a mock configuration provider using ConfigProvider.fromMap with a Map of key-value pairs. This allows running Effect programs with specific test configurations. ```typescript import { Config, ConfigProvider, Effect } from "effect" class HostPort { constructor(readonly host: string, readonly port: number) {} get url() { return `${this.host}:${this.port}` } } const config = Config.map( Config.all([Config.string("HOST"), Config.number("PORT")]), ([host, port]) => new HostPort(host, port) ) const program = Effect.gen(function* () { const hostPort = yield* config console.log(`Application started: ${hostPort.url}`) }) // Create a mock config provider using a map with test data const mockConfigProvider = ConfigProvider.fromMap( new Map([ ["HOST", "localhost"], ["PORT", "8080"] ]) ) // Run the program using the mock config provider Effect.runPromise(Effect.withConfigProvider(program, mockConfigProvider)) ``` -------------------------------- ### Late Fiber Start Captures Only One Value with Effect.fork Source: https://effect.website/docs/concurrency/fibers When using Effect.fork, the forked fiber starts execution after the current fiber completes or yields. This can lead to missed updates if the fiber starts too late. Ensure proper yielding or delays if all updates need to be captured. ```typescript 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) ``` -------------------------------- ### Basic KeyValueStore Operations Source: https://effect.website/docs/platform/key-value-store Illustrates fundamental operations like setting, getting, and removing key-value pairs using the in-memory KeyValueStore implementation. Shows how to check the store's size before and after operations. ```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))) ``` -------------------------------- ### Start OpenTelemetry Backend with Docker Source: https://effect.website/docs/observability/tracing Run the OpenTelemetry backend using Docker. Ensure ports 3000, 4317, and 4318 are available. ```bash docker run -p 3000:3000 -p 4317:4317 -p 4318:4318 --rm -it docker.io/grafana/otel-lgtm ``` -------------------------------- ### Install Effect OpenTelemetry Dependencies with bun Source: https://effect.website/docs/observability/tracing Install necessary Effect and OpenTelemetry packages using bun. This includes the core Effect library, the OpenTelemetry integration, and trace exporters. ```bash # 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 ``` -------------------------------- ### Provide and Use a Service Implementation Source: https://effect.website/docs/micro/new-users Implement a service and provide it to a program using Micro.provideService. The program can then be run using Micro.runPromise. ```typescript import { Micro, Context } from "effect" // Declaring a tag for a service that generates random numbers class Random extends Context.Tag("MyRandomService")< Random, { readonly next: Micro.Micro } >() {} // Using the service const program = Micro.gen(function* () { // Access the Random service const random = yield* Micro.service(Random) // Retrieve a random number from the service const randomNumber = yield* random.next console.log(`random number: ${randomNumber}`) }) // Providing the implementation // // ┌─── Micro // ▼ const runnable = Micro.provideService(program, Random, { next: Micro.sync(() => Math.random()) }) Micro.runPromise(runnable) /* Example Output: random number: 0.8241872233134417 */ ``` -------------------------------- ### Install Effect OpenTelemetry Dependencies with yarn Source: https://effect.website/docs/observability/tracing Install necessary Effect and OpenTelemetry packages using yarn. This includes the core Effect library, the OpenTelemetry integration, and trace exporters. ```bash # 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 ``` -------------------------------- ### Run Deno Program Source: https://effect.website/docs/getting-started/installation Command to execute the main Deno file. ```bash deno run main.ts ``` -------------------------------- ### Install Effect OpenTelemetry Dependencies with pnpm Source: https://effect.website/docs/observability/tracing Install necessary Effect and OpenTelemetry packages using pnpm. This includes the core Effect library, the OpenTelemetry integration, and trace exporters. ```bash # 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 ``` -------------------------------- ### Handle Full Queue with Effect.fork Source: https://effect.website/docs/concurrency/queue Demonstrates how to handle a full bounded queue by forking the `Queue.offer` operation. This prevents blocking the main fiber and allows the offer to complete once space becomes available. ```typescript 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 ``` -------------------------------- ### Install Effect OpenTelemetry Dependencies with npm Source: https://effect.website/docs/observability/tracing Install necessary Effect and OpenTelemetry packages using npm. This includes the core Effect library, the OpenTelemetry integration, and trace exporters. ```bash # 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 ``` -------------------------------- ### Cross-Platform Path Handling Example Source: https://effect.website/docs/platform/introduction This example demonstrates using the Path module to join path segments, which works across different environments. It requires importing Path from '@effect/platform' and Effect from 'effect'. ```typescript import { Path } from "@effect/platform" import { Effect } from "effect" const program = Effect.gen(function* () { // Access the Path service const path = yield* Path.Path // Join parts of a path to create a complete file path const mypath = path.join("tmp", "file.txt") console.log(mypath) }) ``` -------------------------------- ### Customize Schema with Annotations Source: https://effect.website/docs/schema/annotations Use annotations to add custom error messages, length restrictions, identifiers, titles, descriptions, and examples to a string schema. This example demonstrates how to build a robust 'Password' schema. ```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...` }) ``` -------------------------------- ### Create Options from Predicates Source: https://effect.website/docs/data-types/option Demonstrates manual creation versus using liftPredicate for cleaner code. ```typescript 1 import { Option } from "effect" 2 3 const isPositive = (n: number) => n > 0 4 5 const parsePositive = (n: number): Option.Option => 6 isPositive(n) ? Option.some(n) : Option.none() ``` ```typescript 1 import { Option } from "effect" 2 3 const isPositive = (n: number) => n > 0 4 5 // ┌─── (b: number) => Option 6 // ▼ 7 const parsePositive = Option.liftPredicate(isPositive) ``` -------------------------------- ### Run Bun Program Source: https://effect.website/docs/getting-started/installation Command to execute the index file with Bun. ```bash bun index.ts ``` -------------------------------- ### Create a Schedule from a Cron Expression Source: https://effect.website/docs/scheduling/cron Convert a cron expression or `Cron` instance into an Effect-TS `Schedule` using `Schedule.cron`. This schedule triggers at the start of each interval defined by the cron, producing a tuple of the interval's start and end timestamps in milliseconds. ```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 ] ... */ ``` -------------------------------- ### Create a Bounded Queue Source: https://effect.website/docs/concurrency/queue Illustrates how to create a bounded queue with a specified capacity. Back-pressure is applied when the queue is full. ```typescript import { Queue } from "effect" // Creating a bounded queue with a capacity of 100 const boundedQueue = Queue.bounded(100) ``` -------------------------------- ### Using Clock and Console Services Source: https://effect.website/docs/requirements-management/default-services Demonstrates using Clock and Console services without manual dependency injection. ```typescript 1 import { Effect, Clock, Console } from "effect" 2 3 // ┌─── Effect 4 // ▼ 5 const program = Effect.gen(function* () { 6 const now = yield* Clock.currentTimeMillis 7 yield* Console.log(`Application started at ${new Date(now)}`) 8 }) 9 10 Effect.runFork(program) 11 // Output: Application started at ``` -------------------------------- ### Get Duration in Milliseconds Source: https://effect.website/docs/data-types/duration Retrieve the duration value as a number of milliseconds. ```typescript import { Duration } from "effect" console.log(Duration.toMillis(Duration.seconds(30))) // Output: 30000 ``` -------------------------------- ### Providing Bun Context for Path Handling Source: https://effect.website/docs/platform/introduction This example demonstrates providing the Bun-specific context to the program, enabling it to run in a Bun environment. It imports BunContext and BunRuntime from '@effect/platform-bun'. ```typescript import { Path } from "@effect/platform" import { Effect } from "effect" import { BunContext, BunRuntime } from "@effect/platform-bun" const program = Effect.gen(function* () { // Access the Path service const path = yield* Path.Path // Join parts of a path to create a complete file path const mypath = path.join("tmp", "file.txt") console.log(mypath) }) BunRuntime.runMain(program.pipe(Effect.provide(BunContext.layer))) ``` -------------------------------- ### Traditional Exception Handling Source: https://effect.website/docs/getting-started/creating-effects Example of a function that throws an error, which is not reflected in its type signature. ```typescript 1 // Type signature doesn't show possible exceptions 2 const divide = (a: number, b: number): number => { 3 if (b === 0) { 4 throw new Error("Cannot divide by zero") 5 } 6 return a / b 7 } ``` -------------------------------- ### Use data-first directly Source: https://effect.website/docs/code-style/dual Example of calling the data-first variant without using pipe. ```typescript const mappedEffect = Effect.map(effect, func) ``` -------------------------------- ### Use data-last with pipe Source: https://effect.website/docs/code-style/dual Examples of using the data-last variant within a pipe chain. ```typescript const mappedEffect = pipe(effect, Effect.map(func)) ``` ```typescript pipe(effect, Effect.map(func1), Effect.map(func2), ...) ``` -------------------------------- ### Define User and Address Models Source: https://effect.website/docs/data-types/option Example interfaces for a User model with nested optional properties. ```typescript import { Option } from "effect" interface User { readonly id: number readonly username: string readonly email: Option.Option readonly address: Option.Option
} interface Address { readonly city: string readonly street: Option.Option } ```