### Installation and Setup Source: https://effect.website/docs/platform/introduction Instructions for installing the @effect/platform-node package and initializing the Node.js context in an Effect application. ```APIDOC ## Installation ### npm `npm install @effect/platform-node` ### pnpm `pnpm add @effect/platform-node` ### Yarn `yarn add @effect/platform-node` ### Deno `deno add npm:@effect/platform-node` ## Usage ### Description To use Node.js specific services (like Path, FileSystem, etc.) in an Effect program, you must import `NodeContext` and `NodeRuntime` from `@effect/platform-node`. ### 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 const mypath = path.join("tmp", "file.txt") console.log(mypath) }) // Run the program with Node.js context NodeRuntime.runMain(program.pipe(Effect.provide(NodeContext.layer))) ``` ``` -------------------------------- ### Class Instantiation Example Source: https://effect.website/docs/schema/classes Example of how to instantiate a class with an identifier and its expected output. ```APIDOC ## POST /api/classes/instantiate ### Description Instantiates a class with a given identifier and properties. ### Method POST ### Endpoint /api/classes/instantiate ### Parameters #### Request Body - **className** (string) - Required - The name of the class to instantiate. - **id** (number) - Required - The unique identifier for the class instance. - **props** (object) - Required - Properties for the class instance. - **id** (number) - Required - The ID of the instance. - **name** (string) - Required - The name of the instance. ### Request Example ```json { "className": "Person", "id": 1, "props": { "id": 1, "name": "John" } } ``` ### Response #### Success Response (200) - **instance** (object) - The instantiated class object. - **id** (number) - The ID of the instance. - **name** (string) - The name of the instance. #### Response Example ```json { "instance": { "id": 1, "name": "John" } } ``` ``` -------------------------------- ### Installation Commands Source: https://effect.website/docs/getting-started/importing-effect Commands to install the Effect library using different package managers. ```APIDOC ## Installation ### Description Install the Effect library using your preferred package manager. ### Commands - **npm**: `npm install effect` - **pnpm**: `pnpm add effect` - **yarn**: `yarn add effect` - **bun**: `bun add effect` - **deno**: `deno add npm:effect` ``` -------------------------------- ### Install @effect/ai with Bun Source: https://effect.website/docs/ai/getting-started Install the base package for core abstractions and an OpenAI provider integration using Bun. ```APIDOC ## Install @effect/ai with Bun ### Description Install the base package for the core abstractions and an OpenAI provider integration using Bun. ### Method bun add ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```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 ``` ### Response #### Success Response (200) Installation successful. #### Response Example N/A ``` -------------------------------- ### Install @effect/platform Beta Source: https://effect.website/docs/platform/introduction Commands to install the beta version of the @effect/platform package using different package managers. ```bash npm install @effect/platform ``` ```bash pnpm add @effect/platform ``` ```bash yarn add @effect/platform ``` ```bash bun add @effect/platform ``` ```bash deno add npm:@effect/platform ``` -------------------------------- ### Install Effect-OpenTelemetry with Bun Source: https://effect.website/docs/observability/tracing Installs the main library for integrating OpenTelemetry with Effect and the required OpenTelemetry SDKs for tracing and metrics using Bun. Ensure `@opentelemetry/api` is installed if your package manager doesn't handle peer dependencies automatically. ```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/ai with pnpm Source: https://effect.website/docs/ai/getting-started Install the base package for core abstractions and an OpenAI provider integration using pnpm. ```APIDOC ## Install @effect/ai with pnpm ### Description Install the base package for the core abstractions and an OpenAI provider integration using pnpm. ### Method pnpm add ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```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 ``` ### Response #### Success Response (200) Installation successful. #### Response Example N/A ``` -------------------------------- ### Defining a Tool Example Source: https://effect.website/docs/ai/tool-use This section provides a step-by-step example of defining, implementing, and using a tool to fetch a dad joke from the icanhazdadjoke.com API. ```APIDOC ## Defining a Tool ### Description Let’s walk through a complete example of how to define, implement, and use a tool that fetches a dad joke from the [icanhazdadjoke.com](https://icanhazdadjoke.com) API. ### Steps 1. **Define the Tool**: Specify the tool's name, description, and parameters. 2. **Create a Toolkit**: Group related tools into a `Toolkit`. 3. **Implement the Logic**: Write the actual code that executes the tool's functionality. 4. **Give the Tools to the Model**: Provide the `Toolkit` to the language model. 5. **Bring It All Together**: Combine the model, tools, and application logic. ``` -------------------------------- ### Effect-TS Deferred Example Source: https://effect.website/docs/concurrency/deferred Illustrates the lifecycle of a Deferred in Effect-TS. It shows starting a task to complete a Deferred, starting another task to get the value, completing the Deferred, and finally retrieving the value. The output demonstrates the successful retrieval of the value. ```typescript /* 33/*34Starting task to complete the Deferred35Starting task to get the value from the Deferred36Completing the Deferred37Got the value from the Deferred38[ true, 'hello world' ]39*/ ``` -------------------------------- ### Creating a Model Instance (OpenAI Example) Source: https://effect.website/docs/ai/getting-started Demonstrates how to create a `Model` instance for interacting with OpenAI's GPT-4o model. ```APIDOC ## Creating a `Model` Instance ### Description To create a `Model`, use the model-specific factory from Effect's provider integration packages. This example shows creating a `Model` for OpenAI's GPT-4o. ### Method Factory Method (`OpenAiLanguageModel.model`) ### Endpoint N/A ### Parameters * **`"gpt-4o"`** (string) - Required - The specific model identifier for the OpenAI provider. ### Request Example ```typescript import { OpenAiLanguageModel } from "@effect/ai-openai" // Creates a Model that provides LanguageModel and requires OpenAiClient const Gpt4o = OpenAiLanguageModel.model("gpt-4o") ``` ### Response * **`Gpt4o`** (`Model<"openai", LanguageModel | ProviderName, OpenAiClient>`) - A `Model` instance configured for GPT-4o. ### Model Breakdown * **Provides**: `ProviderName` (for introspection), `LanguageModel` (OpenAI implementation for \"gpt-4o\"). * **Requires**: `OpenAiClient`. ``` -------------------------------- ### Concurrent Task Execution Source: https://effect.website/docs/additional-resources/effect-vs-promise This example shows how to fork multiple tasks and join them to get their results. ```APIDOC ## Effect.fork and Fiber.join Example ### Description This example demonstrates how to run multiple asynchronous tasks concurrently using `Effect.fork` and then collect their results using `Fiber.join`. ### Method `Effect.fork` and `Fiber.join` ### Endpoint N/A (Client-side code) ### Parameters N/A ### Request Example ```typescript import { Effect, Fiber } from "effect" const task = (delay: number, name: string): Effect.Effect => Effect.gen(function* () { yield* Effect.sleep(delay) return `${name} done after ${delay}ms` }) const program = Effect.gen(function* () { const fiber1 = yield* Effect.fork(task(1000, "Task 1")) const fiber2 = yield* Effect.fork(task(500, "Task 2")) const fiber3 = yield* Effect.fork(task(1500, "Task 3")) const result1 = yield* Fiber.join(fiber1) const result2 = yield* Fiber.join(fiber2) const result3 = yield* Fiber.join(fiber3) return [result1, result2, result3] }) Effect.runPromise(program).then(console.log) ``` ### Response #### Success Response (200) - **Array** (string[]) - An array containing the results of each forked task. #### Response Example ```json [ "Task 1 done after 1000ms", "Task 2 done after 500ms", "Task 3 done after 1500ms" ] ``` ``` -------------------------------- ### Using Layers for Environment Setup Source: https://effect.website/docs/requirements-management/services Demonstrates how to compose layers to set up a modular and reusable environment for effects, including configuring services like databases. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new user resources. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address for the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "usr_123abc", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### GET /docs/data-types/either Source: https://effect.website/docs/data-types/either Documentation for the Either data type, including examples of logging and handling Either objects. ```APIDOC ## GET /docs/data-types/either ### Description This endpoint provides documentation on the Either data type, which represents a value of one of two possible types (a disjoint union). It is commonly used for error handling. ### Method GET ### Endpoint /docs/data-types/either ### Parameters None ### Request Example N/A ### Response #### Success Response (200) - **content** (string) - The documentation content for the Either data type. #### Response Example { "message": "Documentation for Either data type retrieved successfully" } ``` -------------------------------- ### Configure and Map Application Settings Source: https://effect.website/docs/configuration Demonstrates how to aggregate multiple configuration sources (HOST and PORT) into a tuple and map them into a custom HostPort class instance. ```typescript const both = Config.all([Config.string("HOST"), Config.number("PORT")]); const config = Config.map(both, ([host, port]) => new HostPort(host, port)); ``` -------------------------------- ### Logging Application Start with Console Source: https://effect.website/docs/configuration Shows how to use the global console object to log application start information, including host and port details. This example demonstrates basic logging within an Effect context. ```typescript log(`Application started: ${const host: stringhost}:${const port: numberport}`) ``` -------------------------------- ### Example: Using the `array` Combinator Source: https://effect.website/docs/configuration Demonstrates how to load an environment variable as an array of strings using the `Config.array` constructor within an Effect.gen block. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of a new user in the system. It accepts user details in the request body and returns the newly created user's information. ### Method POST ### Endpoint `/api/users` ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "usr_12345abcde", "username": "johndoe", "email": "john.doe@example.com" } ``` #### Error Response (400 Bad Request) - **error** (string) - A message describing the validation error. #### Error Response Example ```json { "error": "Username is required." } ``` ``` -------------------------------- ### Get Todos API Source: https://effect.website/docs/batching Fetches a list of todos from the example API. This endpoint demonstrates asynchronous data fetching and error handling using Effect. ```APIDOC ## GET /api/todos ### Description Fetches a list of todos from the example API. This endpoint demonstrates asynchronous data fetching and error handling using Effect. ### Method GET ### Endpoint https://api.example.demo/todos ### Parameters #### Query Parameters - **signal** (AbortSignal) - Optional - Signal to abort the request. ### Request Example ```json { "example": "No request body for GET request" } ``` ### Response #### Success Response (200) - **todos** (Array) - A list of todo items. #### Response Example ```json { "example": [ { "id": 1, "title": "Learn Effect TS", "completed": false } ] } ``` #### Error Response (400) - **error** (GetTodosError) - An error object if fetching todos fails. #### Error Response Example ```json { "example": { "_tag": "GetTodosError" } } ``` ``` -------------------------------- ### Calculating the size of an Effect-TS MutableHashSet Source: https://effect.website/docs/data-types/hash-set Provides an example of how to get the number of unique elements in a MutableHashSet using the size() function. It covers empty sets and sets with duplicate additions. ```typescript import { MutableHashSet } from "effect" import assert from "node:assert/strict" assert.equal(MutableHashSet.size(MutableHashSet.empty()), 0) assert.equal( MutableHashSet.size(MutableHashSet.make(1, 2, 2, 3, 4, 3)), 4) ``` -------------------------------- ### Adding Affixes to a Stream using intersperseAffixes Source: https://effect.website/docs/stream/operations This example demonstrates how to use Stream.intersperseAffixes to prepend a start character, insert a middle delimiter between elements, and append an end character to a stream of numbers. ```typescript import { Effect, Stream } from "effect"; const stream = Stream.make(1, 2, 3, 4, 5).pipe( Stream.intersperseAffixes({ start: "[", middle: "|", end: "]" }) ); Effect.runPromise(Stream.runCollect(stream)).then(console.log); ``` -------------------------------- ### Context and Dependency Injection Source: https://effect.website/docs/requirements-management/services Illustrates setting up and accessing context with dependencies like Port and Timeout, and how to provide these dependencies to an effect. ```APIDOC ## Context and Dependency Injection ### Description Demonstrates the use of `Context.make` and `Context.add` to create and manage dependencies within an effectful program. It also shows how `Effect.provide` can be used to supply these dependencies. ### Method Context.make, Context.add, Effect.provide ### Endpoint N/A (This is a conceptual example of dependency management) ### Parameters None for the core concepts shown. ### Request Example ```typescript import { Context, Effect } from "effect" const Port = Context.GenericTag<{ PORT: number }>("Port") const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") const someContext = Context.make(Port, { PORT: 8080 }) const Services = pipe( someContext, Context.add(Timeout, { TIMEOUT: 5000 }) ) // Assertions to verify context values assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) // Example of providing context to an effect const runnable: Effect.Effect = Effect.unit // Replace with your actual effect const providedRunnable = Effect.provide(runnable, Services) ``` ### Response #### Success Response (200) N/A (This example focuses on setup and execution context) #### Response Example N/A ``` -------------------------------- ### Loading Basic Configuration from Environment Variables Source: https://effect.website/docs/configuration This example demonstrates how to load basic configuration values like HOST and PORT from environment variables using Effect's Config module. ```APIDOC ## Loading Basic Configuration from Environment Variables ### Description This example shows how to define a program that loads `HOST` as a string and `PORT` as a number from environment variables. ### Method GET (Implicit, as it reads from environment) ### Endpoint N/A (Reads from environment variables) ### Parameters #### Environment Variables - **HOST** (string) - Required - The host address. - **PORT** (number) - Required - The port number. ### Request Example Environment variables: ```bash export HOST=localhost export PORT=3000 ``` ### Response #### Success Response (200) This example doesn't produce a direct HTTP response but rather loads values into the Effect runtime. #### Response Example (No direct response body, values are available within the Effect program) ```typescript import { Effect, Config } from "effect"; // Define a program that loads HOST and PORT configuration const program = Effect.gen(function* (_) { const host = yield* _(Config.string("HOST")); const port = yield* _(Config.number("PORT")); console.log(`Host: ${host}, Port: ${port}`); }); Effect.runPromise(program); ``` ``` -------------------------------- ### Scheduling Exponential Delays with Effect Source: https://effect.website/docs/scheduling/built-in-schedules Uses the Effect framework's Schedule module to create an exponential backoff schedule. This example logs increasing delays starting from a base duration. ```typescript import { Schedule, Duration } from "effect"; const schedule = Schedule.exponential("10 millis"); const log = (schedule: Schedule.Schedule, delay?: Duration.DurationInput) => { // Implementation logic for logging schedule iterations }; log(schedule); ``` -------------------------------- ### Initialize Effect Toolkit Source: https://effect.website/docs/ai/tool-use Demonstrates how to instantiate a toolkit by passing an array of available tools. This setup allows for structured tool execution within the Effect ecosystem. ```typescript const toolkit = Toolkit.make(GetCurrentTime, GetWeather); ``` -------------------------------- ### Get DateTime Part - Effect-TS Source: https://effect.website/docs/data-types/datetime Retrieves a specific part (e.g., year, month, day) from a DateTime object, adjusted for its time zone. Requires Effect-TS and Node.js assert module for example. ```typescript import * as assert from "node:assert" import { DateTime } from "effect" const now = DateTime.unsafeMakeZoned({ year: 2024 }, { timeZone: "Europe/London" }) const year = DateTime.getPart(now, "year") assert.strictEqual(year, 2024) const month = DateTime.getPart(now, "month") assert.strictEqual(month, 1) ``` -------------------------------- ### Custom Console Source: https://effect.website/docs/additional-resources/effect-vs-promise Example of creating and using a custom Console instance with specified output streams. ```APIDOC ## Custom Console ### Description Illustrates how to create a `Console` instance that directs output to specific streams, allowing for more controlled logging. ### Method N/A (Client-side JavaScript) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.log('hello %s', 'world'); myConsole.error(new Error('Whoops, something bad happened')); const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); ``` ### Response #### Success Response (200) N/A #### Response Example ``` hello world (to out) hello world (to out) [Error: Whoops, something bad happened] (to err) Danger Will Robinson! Danger! (to err) ``` ``` -------------------------------- ### Implementing Retries with Fixed Delay Source: https://effect.website/docs/error-management/retrying Demonstrates how to use the Effect.retry function combined with a Schedule policy to automatically retry an operation upon failure. This example shows a basic setup for handling intermittent errors. ```typescript import { Effect, Schedule } from "effect"; let count: number = 0; const program = Effect.retry( Effect.sync(() => { count++; if (count < 3) throw new Error("Temporary failure"); return "Success!"; }), Schedule.fixed("100 millis") ); Effect.runPromise(program).then(console.log); ``` -------------------------------- ### Clamping Numbers to a Range using Effect Source: https://effect.website/docs/behaviour/order This example demonstrates how to use Order.clamp with Number.Order to restrict a number between a minimum and maximum value. It shows both the setup of the clamp function and its behavior when values are within or outside the specified bounds. ```typescript import { Order, Number } from "effect"; const clamp = Order.clamp(Number.Order)({ minimum: 20, maximum: 30 }); console.log(clamp(26)); // Output: 26 console.log(clamp(10)); // Output: 20 ``` -------------------------------- ### Initialize Custom Console with Streams Source: https://effect.website/docs/sink/creating Demonstrates how to create a custom console instance by providing specific output and error streams. This allows redirection of log and error messages to custom destinations. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.error(new Error('Whoops, something bad happened')); myConsole.warn(`Danger ${name}! Danger!`); ``` -------------------------------- ### Implement Fixed Interval Recurrence with Effect Source: https://effect.website/docs/scheduling/built-in-schedules Demonstrates how to define a schedule that recurs at fixed intervals using the Effect library. The example shows the setup of a logger function that utilizes Schedule and Duration inputs to manage execution timing. ```typescript import { Effect, Schedule, Duration, Chunk } from "effect"; const log = (schedule: Schedule.Schedule, delay: Duration.DurationInput = 0): void => { const maxRecurs = 10; const delays = Chunk.toArray( Effect.runSync(Effect.succeed(Chunk.empty())) ); }; ``` -------------------------------- ### Execute an Effect and Return a Promise with Effect.js Source: https://effect.website/docs/stream/creating This example shows how to use Effect.runPromise to execute an Effect and get its result as a JavaScript Promise. It covers both successful execution, where the promise resolves with the result, and failure, where the promise rejects with an error. This is useful for integrating Effect-based code with promise-based systems. ```typescript import { Effect } from "effect" // Example of a successful effect Effect.runPromise(Effect.succeed(1)).then(console.log) // Expected output: 1 // Example of a failing effect Effect.runPromise(Effect.fail("my error")).catch(console.error) // Expected output: (FiberFailure) Error: my error ``` -------------------------------- ### Custom Console Instance Source: https://effect.website/docs/data-types/either Illustrates how to create and use a custom console instance with specific output streams. ```APIDOC ## Custom Console Instance ### Description This section explains how to create a custom `console.Console` instance, directing output to specified streams. ### Method `new console.Console(stdout, stderr)` ### Endpoint N/A (Class constructor) ### Parameters - `stdout` (Stream) - The writable stream for standard output. - `stderr` (Stream) - The writable stream for standard error. ### Request Example ```javascript const out = getStreamSomehow(); // Assume this returns a writable stream const err = getStreamSomehow(); // Assume this returns a writable stream const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Logs to 'out' myConsole.error(new Error('Whoops, something bad happened')); // Logs to 'err' const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Logs to 'err' ``` ### Response #### Success Response (200) Output is directed to the streams provided during instantiation. #### Response Example ``` // Output to 'out' stream: hello world // Output to 'err' stream: [Error: Whoops, something bad happened] Danger Will Robinson! Danger! ``` ``` -------------------------------- ### Loading Basic Configuration from Environment Variables Source: https://effect.website/docs/configuration Demonstrates how to define and load configuration values for HOST and PORT using Effect's built-in Config primitives and Effect.gen. ```typescript import { Effect, Config } from "effect"; const program = Effect.gen(function* () { const host = yield* Config.string("HOST"); const port = yield* Config.number("PORT"); console.log(`Server running at ${host}:${port}`); }); ``` -------------------------------- ### Bounded Queue Operations with Fibers (Effect) Source: https://effect.website/docs/concurrency/queue This example showcases the usage of a bounded queue in Effect. It demonstrates creating a bounded queue, offering elements, handling suspension when the queue is full, taking elements to free up space, and joining fibers. The code also illustrates how to get the size of the queue. ```typescript const queue: Queue.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: Fiber.RuntimeFiber = 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 Sink.filterInput Example Source: https://effect.website/docs/sink/operations An example demonstrating how to use Sink.filterInput from the Effect library to process only elements that meet a specific condition. This example filters out negative numbers when collecting chunks. ```typescript import { Stream, Sink, Effect } from "effect" // Define a stream with positive, negative, and zero values const stream = Stream.fromIterable([1, 2, 3, -1, -2, 0, 4, 5]) // Example usage (assuming a sink that collects chunks of three) // This part is conceptual as the sink definition is not fully provided in the input. // const result = await Effect.runPromise(stream.run(Sink.filterInput(n => n > 0))) // console.log(result) ``` -------------------------------- ### Configuration Handling Source: https://effect.website/docs/configuration Illustrates how to construct a configuration for a hash set of strings using Effect's configuration module. ```APIDOC ## Configuration Handling ### Description This snippet shows how to define a configuration for a hash set of strings. It utilizes `Config.const.hashSet` and `Config.const.string` from the Effect configuration library. ### Method N/A (Configuration definition) ### Endpoint N/A ### Parameters #### Query Parameters - **name** (string) - Optional - A name for the configuration. ### Request Example N/A ### Response N/A (This defines configuration, not an API response) ### Notes - `@since ― 2.0.0` indicates the version when this feature was introduced. ``` -------------------------------- ### Console Class Methods Source: https://effect.website/docs/schema/effect-data-types Examples of creating and using a custom Console instance with specific output streams. ```APIDOC ## Console Class Usage ### Description Demonstrates how to create a `Console` instance with custom output streams (stdout and stderr) and use its logging methods. ### Method N/A (Class Instantiation) ### Endpoint N/A (Class Instantiation) ### Parameters - `out` (stream) - Required - The writable stream for standard output. - `err` (stream) - Required - The writable stream for standard error. ### Request Example ```javascript const { Console } = require('console'); // Assume getStreamSomehow() returns a writable stream const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new Console(out, err); myConsole.log('hello world'); // Prints to 'out' myConsole.error(new Error('Whoops, something bad happened')); // Prints to 'err' const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints to 'err' ``` ### Response #### Success Response (200) Output is directed to the streams provided during `Console` instantiation. #### Response Example ``` hello world (to 'out' stream) [Error: Whoops, something bad happened] (to 'err' stream) Danger Will Robinson! Danger! (to 'err' stream) ``` ``` -------------------------------- ### Option Creation and Usage Source: https://effect.website/docs/schema/advanced-usage Demonstrates how to create Option instances using `Option.none()` for representing no value and `Option.some()` for representing a present value. It also shows how to extract values and handle empty strings. ```APIDOC ## Option API ### Description The Option API in Effect provides a way to represent values that may or may not be present. It helps in handling null or undefined values more robustly. ### Functions #### `Option.none() => Option` * **Description**: Represents the absence of a value by creating an empty Option. It returns an `Option`, which is a subtype of `Option`, meaning it can be used in place of any `Option`. * **Example**: ```typescript import { Option } from "effect" const noValue = Option.none() console.log(noValue) // Output: { _id: 'Option', _tag: 'None' } ``` #### `Option.some(value: A) => Option` * **Description**: Wraps the given value into an Option to represent its presence. * **Example**: ```typescript import { Option } from "effect" const value = Option.some(1) console.log(value) // Output: { _id: 'Option', _tag: 'Some', value: 1 } ``` ### Handling Empty Strings * **Description**: The `encode` function within a schema can be used to transform Option values. This example shows how empty strings are treated as missing values by returning `Option.none()`. * **Code Snippet**: ```typescript // ... within a schema definition encode: (maybeString: Option.Option) => { if (const value: string = maybeString.value; value === "") { // Treat empty strings as missing in the output by returning Option.none() return Option.none() } // Include non-empty strings in the output. return Option.some(value) } // ... ``` ``` -------------------------------- ### Duration Decode Example Source: https://effect.website/docs/schema/effect-data-types Example demonstrating the decoding of duration strings using a hypothetical Duration module. ```APIDOC ## Duration Decode Example ### Description This example shows how to decode a duration string into a Duration object using a hypothetical `Duration` module. ### Usage Import the `Duration` module and use its `decode` function. ### Example ```javascript // Assuming Duration module is imported as Duration // const { decode } = require('some-duration-module'); // Hypothetical import // Example 1 const duration1 = decode("2 seconds"); console.log(duration1); // Output: { _id: 'Duration', _tag: 'Millis', millis: 5000 } // Example 2 const duration2 = decode("6 seconds"); console.log(duration2); // Output: { _id: 'Duration', _tag: 'Millis', millis: 6000 } ``` ### Note The specific output format `{ _id: 'Duration', _tag: 'Millis', millis: ... }` depends on the implementation of the `Duration.decode` function. ``` -------------------------------- ### Logging with Global Console and Console Class Source: https://effect.website/docs/resource-management/scope Shows how to use the global console instance for standard logging and how to instantiate a custom Console class to write to specific streams. ```javascript console.log('hello world'); console.log('hello %s', 'world'); console.error(new Error('Whoops, something bad happened')); const myConsole = new console.Console(process.stdout, process.stderr); myConsole.log('hello world'); ``` -------------------------------- ### Stream.unfold Example: Natural Numbers Source: https://effect.website/docs/stream/creating Example demonstrating how to create a stream of natural numbers using Stream.unfold. ```APIDOC ## Stream.unfold Example: Natural Numbers ### Description This example shows how to generate a stream of natural numbers starting from 1, taking the first 5 elements, and logging them to the console. ### Method `Stream.unfold` combined with `Stream.take` and `Effect.runPromise`. ### Endpoint None (This is a function usage example) ### Parameters None ### Request Example ```typescript import { Effect, Option, Stream } from "effect" const stream = Stream.unfold(1, (n) => Option.some([n, n + 1])) Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log) ``` ### Response #### Success Response (200) ```json { "_id": "Chunk", "values": [ 1, 2, 3, 4, 5 ] } ``` #### Response Example ```json { "_id": "Chunk", "values": [ 1, 2, 3, 4, 5 ] } ``` ``` -------------------------------- ### Install Effect and OpenTelemetry Dependencies Source: https://effect.website/docs/observability/tracing Installs the required Effect and OpenTelemetry SDK packages for tracing and metrics. ```bash npm install effect @effect/opentelemetry @opentelemetry/exporter-trace-otlp-http @opentelemetry/sdk-trace-base @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-web @opentelemetry/sdk-metrics ``` ```bash pnpm add effect @effect/opentelemetry @opentelemetry/exporter-trace-otlp-http @opentelemetry/sdk-trace-base @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-web @opentelemetry/sdk-metrics ``` ```bash yarn add effect @effect/opentelemetry @opentelemetry/exporter-trace-otlp-http @opentelemetry/sdk-trace-base @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-web @opentelemetry/sdk-metrics ``` ```bash bun add effect @effect/opentelemetry @opentelemetry/exporter-trace-otlp-http @opentelemetry/sdk-trace-base @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-web @opentelemetry/sdk-metrics ``` -------------------------------- ### PubSub Creation Source: https://effect.website/docs/concurrency/pubsub Demonstrates how to create different types of PubSub instances: Bounded and Dropping. ```APIDOC ## PubSub Creation ### Description This section covers the creation of PubSub instances, which are used for message queuing and distribution. Two types are detailed: Bounded PubSub (with back pressure) and Dropping PubSub (discards messages when full). ### Bounded PubSub #### Description A bounded `PubSub` applies back pressure to publishers when it reaches capacity, suspending additional publishing until space becomes available. This ensures all subscribers receive all messages while subscribed, but can slow delivery if a subscriber is slow. #### Method PubSub.bounded #### Endpoint N/A (Function within the PubSub module) #### Parameters - **capacity** (number | { readonly capacity: number; readonly replay?: number | undefined; }) - Required - The capacity of the bounded PubSub. Powers of two are recommended for performance. ### Dropping PubSub #### Description A dropping `PubSub` discards new values when full. The `PubSub.publish` operation returns `false` if the message is dropped. Publishers can continue to publish, but subscribers are not guaranteed to receive all messages. #### Method PubSub.dropping #### Endpoint N/A (Function within the PubSub module) #### Parameters - **capacity** (number | { readonly capacity: number; readonly replay?: number | undefined; }) - Required - The capacity of the dropping PubSub. Powers of two are recommended for performance. ### Request Example (Bounded PubSub) ```json { "example": "import { PubSub } from \"effect\" const boundedPubSub = PubSub.bounded(2)" } ``` ### Request Example (Dropping PubSub) ```json { "example": "import { PubSub } from \"effect\" const droppingPubSub = PubSub.dropping(2)" } ``` ### Response #### Success Response (200) - **PubSub** (PubSub.PubSub) - An instance of the created PubSub. #### Response Example ```json { "example": "// The PubSub instance" } ``` ``` -------------------------------- ### Node.js: Console Logging Examples Source: https://effect.website/docs/micro/new-users This snippet provides examples of using the built-in Node.js `console` module for logging messages to standard output and standard error. It includes examples using the global console object and the `Console` class. ```javascript console.log('hello world');// Prints: hello world, to stdout console.log('hello %s', 'world');// Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened'));// Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to stderr const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world');// Prints: hello world, to out myConsole.log('hello %s', 'world');// Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened'));// Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`);// Prints: Danger Will Robinson! Danger!, to err console.Console.log(message?: any, ...optionalParams: any[]): void // Prints to stdout with newline. Multiple arguments can be passed, with the // first used as the primary message and all additional used as substitution // values similar to printf(3) // (the arguments are all passed to util.format()). const count = 5; console.log('count: %d', count);// Prints: count: 5, to stdout console.log('count:', count);// Prints: count: 5, to stdout ``` -------------------------------- ### Create and Execute System Commands Source: https://effect.website/docs/platform/command Illustrates how to define a system command using Command.make and execute it within an Effect context. ```typescript import { Command } from "@effect/platform"; const command = Command.make("ls"); const [exitCode, stdout, stderr] = yield* pipe(command, ...); ``` -------------------------------- ### Layer Composition Example Source: https://effect.website/docs/error-management/expected-errors Demonstrates composing layers to set up dependencies like a database service. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of a new user in the system. It takes user details in the request body and returns the created user's information. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Providing a Service Implementation Source: https://effect.website/docs/requirements-management/services Shows how to provide an actual implementation of a declared service using `Effect.provideService`. ```APIDOC ## Providing a Service Implementation To fulfill the declared requirements of an effect, you need to provide an implementation for the services it depends on. This is typically done using `Effect.provideService` or `Layer`. **Example** (Providing a concrete implementation for `RandomService`) ```typescript import { Effect, Context, Layer } from "effect" // Assume RandomService is defined as in the previous example const RandomService = Context.Tag }>("MyRandomService") // A concrete implementation of the random number service class LiveRandomService implements Context.Service { readonly next = Effect.succeed(Math.random()) } // Providing the service implementation const program = Effect.gen(function* (_){ const randomNumber = yield* RandomService.next return randomNumber }) const live = Layer.succeed(RandomService, new LiveRandomService()) // Running the program with the provided service const result = program.pipe(Effect.provideLayer(live)) Effect.runPromise(result).then(console.log) ``` ``` -------------------------------- ### Install Effect-OpenTelemetry with Yarn Source: https://effect.website/docs/observability/tracing Installs the main library for integrating OpenTelemetry with Effect and the required OpenTelemetry SDKs for tracing and metrics using Yarn. Ensure `@opentelemetry/api` is installed if your package manager doesn't handle peer dependencies automatically. ```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 ``` -------------------------------- ### Install Effect-OpenTelemetry with pnpm Source: https://effect.website/docs/observability/tracing Installs the main library for integrating OpenTelemetry with Effect and the required OpenTelemetry SDKs for tracing and metrics using pnpm. Ensure `@opentelemetry/api` is installed if your package manager doesn't handle peer dependencies automatically. ```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 ``` -------------------------------- ### Initialize and Use Custom Console Source: https://effect.website/docs/concurrency/queue Demonstrates how to create a new instance of the console.Console class by providing custom output and error streams. It shows how to log messages and errors to these specific streams. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.log('hello %s', 'world'); myConsole.error(new Error('Whoops, something bad happened')); const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); ``` -------------------------------- ### Install Effect-OpenTelemetry with npm Source: https://effect.website/docs/observability/tracing Installs the main library for integrating OpenTelemetry with Effect and the required OpenTelemetry SDKs for tracing and metrics using npm. Ensure `@opentelemetry/api` is installed if your package manager doesn't handle peer dependencies automatically. ```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 ``` -------------------------------- ### Instantiating a Custom Console Class Source: https://effect.website/docs/behaviour/equivalence Shows how to create a new Console instance that writes to specific custom streams instead of the default process stdout/stderr. ```javascript const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); myConsole.error(new Error('Whoops, something bad happened')); ```