### View Minigit CLI Subcommand Help Documentation (sh) Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md Use this command to retrieve detailed help information for a specific `minigit` subcommand, such as `add`. It outlines the subcommand's arguments, specific options, and usage examples, aiding in understanding its functionality. ```sh npx tsx minigit.ts add --help ``` -------------------------------- ### Serve Static Files with HttpRouter and HttpServer Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Demonstrates how to serve static files like HTML using HttpServerResponse.file(). Creates an HTTP router with a GET endpoint that serves an index.html file, then starts the server on port 3000. Requires the @effect/platform package and a listen utility function. ```typescript import { HttpRouter, HttpServer, HttpServerResponse } from "@effect/platform" import { listen } from "./listen.js" const router = HttpRouter.empty.pipe( HttpRouter.get("/", HttpServerResponse.file("index.html")) ) const app = router.pipe(HttpServer.serve()) listen(app, 3000) ``` -------------------------------- ### Execute Minigit CLI 'add' Command (sh) Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This example demonstrates how to use the `minigit add` command to stage all changes in the current directory. By default, this execution runs without verbose output, indicating a successful staging operation. ```sh npx tsx minigit.ts add . # Output: Running 'minigit add .' with '--verbose false' ``` -------------------------------- ### Serve Auto-Generated Swagger Documentation for an @effect/platform API (TypeScript) Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This example extends the basic HTTP API setup to include auto-generated Swagger documentation. It demonstrates how to integrate `HttpApiSwagger.layer()` into the server configuration, allowing clients to access interactive API documentation at a dedicated `/docs` endpoint. This ensures consistency between the API definition and its documentation. ```typescript import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup, HttpApiSwagger } from "@effect/platform" import { NodeHttpServer, NodeRuntime } from "@effect/platform-node" import { Effect, Layer, Schema } from "effect" import { createServer } from "node:http" const MyApi = HttpApi.make("MyApi").add( HttpApiGroup.make("Greetings").add( HttpApiEndpoint.get("hello-world")`/`.addSuccess(Schema.String) ) ) const GreetingsLive = HttpApiBuilder.group(MyApi, "Greetings", (handlers) => handlers.handle("hello-world", () => Effect.succeed("Hello, World!")) ) const MyApiLive = HttpApiBuilder.api(MyApi).pipe(Layer.provide(GreetingsLive)) const ServerLive = HttpApiBuilder.serve().pipe( // Provide the Swagger layer so clients can access auto-generated docs Layer.provide(HttpApiSwagger.layer()), Layer.provide(MyApiLive), Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })) ) Layer.launch(ServerLive).pipe(NodeRuntime.runMain) ``` -------------------------------- ### Define and Implement a Basic HTTP API with @effect/platform (TypeScript) Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This example demonstrates how to define a simple HTTP API using `@effect/platform` with a single GET endpoint that returns 'Hello, World!'. It shows the creation of an `HttpApi`, an `HttpApiGroup`, and an `HttpApiEndpoint`, followed by its implementation and serving using `NodeHttpServer` on port 3000. The `NodeRuntime.runMain` function is used to launch the server. ```typescript import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "@effect/platform" import { NodeHttpServer, NodeRuntime } from "@effect/platform-node" import { Effect, Layer, Schema } from "effect" import { createServer } from "node:http" // Define our API with one group named "Greetings" and one endpoint called "hello-world" const MyApi = HttpApi.make("MyApi").add( HttpApiGroup.make("Greetings").add( HttpApiEndpoint.get("hello-world")`/`.addSuccess(Schema.String) ) ) // Implement the "Greetings" group const GreetingsLive = HttpApiBuilder.group(MyApi, "Greetings", (handlers) => handlers.handle("hello-world", () => Effect.succeed("Hello, World!")) ) // Provide the implementation for the API const MyApiLive = HttpApiBuilder.api(MyApi).pipe(Layer.provide(GreetingsLive)) // Set up the server using NodeHttpServer on port 3000 const ServerLive = HttpApiBuilder.serve().pipe( Layer.provide(MyApiLive), Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })) ) // Launch the server Layer.launch(ServerLive).pipe(NodeRuntime.runMain) ``` -------------------------------- ### Install @effect/vitest package Source: https://github.com/effect-ts/effect/blob/main/packages/vitest/README.md Install the @effect/vitest package to integrate Effect with Vitest. ```sh pnpm add -D @effect/vitest ``` -------------------------------- ### GET / Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This endpoint demonstrates a simple 'Hello, World!' API, returning a string response when accessed. ```APIDOC ## GET / ### Description Returns a simple 'Hello, World!' string. ### Method GET ### Endpoint / ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example {} ### Response #### Success Response (200) - **response** (string) - The 'Hello, World!' message. #### Response Example "Hello, World!" ``` -------------------------------- ### Example Wizard Mode Interaction Output Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This output illustrates a typical interactive session when running an Effect-TS CLI in Wizard Mode. It shows the prompts and guidance provided to the user for constructing a command, concluding with an option to execute the generated command after all necessary inputs are gathered. ```text Wizard Mode for CLI Application: Hello World CLI (v1.0.0) Instructions The wizard mode will assist you with constructing commands for Hello World CLI (v1.0.0). Please answer all prompts provided by the wizard. COMMAND: hello-world Wizard Mode Complete! You may now execute your command directly with the following options and arguments: hello-world ✔ Would you like to run the command? … yes / no ``` -------------------------------- ### Install vitest dependency Source: https://github.com/effect-ts/effect/blob/main/packages/vitest/README.md Install vitest version 1.6.0 or later as a development dependency. ```sh pnpm add -D vitest ``` -------------------------------- ### Install @effect/printer-ansi package Source: https://github.com/effect-ts/effect/blob/main/packages/printer-ansi/README.md Install the `@effect/printer-ansi` package using your preferred Node.js package manager. ```bash npm install @effect/printer-ansi ``` ```bash pnpm install @effect/printer-ansi ``` ```bash yarn add @effect/printer-ansi ``` -------------------------------- ### Execute Effect-TS CLI Command with Parent and Subcommand Options (Shell) Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This shell command provides an example of executing the `minigit` CLI application, passing configuration parameters to the parent command (`-c key1=value1`) and specific options (`--depth 1`) and arguments (`https://github.com/Effect-TS/cli.git`) to the `clone` subcommand. It also shows the expected output, confirming that both parent and subcommand configurations are processed. ```sh npx tsx minigit.ts -c key1=value1 clone --depth 1 https://github.com/Effect-TS/cli.git # Running 'minigit clone' with the following options and arguments: '--depth 1, https://github.com/Effect-TS/cli.git' # and the following configuration parameters: key1=value1 ``` -------------------------------- ### Define Wildcard Route Path Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Creates a GET route with wildcard matching that responds to any path starting with "/user" (e.g., "/user", "/users", "/user/profile"). Extracts and returns the requested URL in the response. Demonstrates pattern matching with wildcards. ```typescript HttpRouter.get( "/user*", Effect.map(HttpServerRequest.HttpServerRequest, (req) => HttpServerResponse.text(req.url) ) ) ``` -------------------------------- ### Install @effect/cli with npm, pnpm, and yarn Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md Install the @effect/cli package using three popular package managers. Choose the appropriate command based on your project's package manager preference. ```bash npm install @effect/cli ``` ```bash pnpm add @effect/cli ``` ```bash yarn add @effect/cli ``` -------------------------------- ### Install `@effect/printer` package Source: https://github.com/effect-ts/effect/blob/main/packages/printer/README.md Instructions for installing the `@effect/printer` package using various JavaScript/TypeScript package managers like npm, pnpm, yarn, deno, and bun. Choose the command appropriate for your project's package manager. ```bash npm install @effect/printer ``` ```bash pnpm install @effect/printer ``` ```bash yarn add @effect/printer ``` ```bash deno add npm:@effect/printer ``` ```bash bun add @effect/printer ``` -------------------------------- ### Check JSDoc Examples with pnpm docgen Source: https://github.com/effect-ts/effect/blob/main/AGENTS.md Verify that JSDoc examples within the codebase compile correctly. This ensures documentation examples remain valid and functional, providing reliable guidance for users. ```bash pnpm docgen ``` -------------------------------- ### Define Basic HTTP GET Route Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Creates a simple GET route handler that responds with plain text. The route responds to requests at the root path ("/") with the text "Hello World". Uses HttpRouter.get() and HttpServerResponse.text() for text responses. ```typescript HttpRouter.get("/", HttpServerResponse.text("Hello World")) ``` -------------------------------- ### GET /docs Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This endpoint serves the auto-generated Swagger UI documentation for the defined API, allowing interactive exploration of all available endpoints. ```APIDOC ## GET /docs ### Description Access the interactive Swagger UI for API documentation. ### Method GET ### Endpoint /docs ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example {} ### Response #### Success Response (200) - **swagger_ui** (HTML) - The HTML content for the Swagger UI. #### Response Example (HTML content for Swagger UI) ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/effect-ts/effect/blob/main/README.md Installs all required project dependencies using pnpm package manager. Requires pnpm version 10.4.0 or higher. This must be completed before making any changes to the codebase. ```bash pnpm install ``` -------------------------------- ### JSDoc Comment Example for Effect-TS Feature Source: https://github.com/effect-ts/effect/blob/main/README.md Demonstrates proper JSDoc documentation format for Effect-TS features, including description, example usage with @example tag, and @since version tag. Shows how to document synchronous Effect execution with output comments. ```typescript import { Effect } from "effect" console.log(Effect.runSyncExit(Effect.succeed(1))) /* Output: { _id: "Exit", _tag: "Success", value: 1 } */ ``` -------------------------------- ### Define GET and POST Route Methods Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Demonstrates defining separate route handlers for GET and POST HTTP methods on the same path. Each method returns a different text response. Shows how HttpRouter supports multiple HTTP verbs for the same endpoint. ```typescript // GET method route HttpRouter.get("/", HttpServerResponse.text("GET request to the homepage")) // POST method route HttpRouter.post("/", HttpServerResponse.text("POST request to the homepage")) ``` -------------------------------- ### GET /users Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Retrieves a list of all user accounts. ```APIDOC ## GET /users ### Description Retrieves a list of all user accounts. ### Method GET ### Endpoint /users ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (None) ### Response #### Success Response (200) - **id** (number) - The unique identifier of the user. - **name** (string) - The name of the user. - **createdAt** (string) - The timestamp when the user account was created (ISO 8601 format). #### Response Example ```json [ { "id": 1, "name": "Alice", "createdAt": "2023-01-01T10:00:00Z" }, { "id": 2, "name": "Bob", "createdAt": "2023-01-02T11:00:00Z" } ] ``` ``` -------------------------------- ### Create a GET Web Handler with Effect-TS HttpLayerRouter Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This snippet illustrates how to define a simple GET route (`/hello`) that responds with 'Hellow, World!' using `@effect/platform/HttpLayerRouter`. It also shows how to convert the router into a web handler and includes a `SIGINT` handler for graceful resource disposal upon process interruption. The `handler` can then be exported and used with a compatible HTTP server. ```typescript import * as HttpLayerRouter from "@effect/platform/HttpLayerRouter" import * as HttpServerResponse from "@effect/platform/HttpServerResponse" import * as Effect from "effect/Effect" const HelloRoute = HttpLayerRouter.use( Effect.fn(function* (router) { yield* router.add( "GET", "/hello", HttpServerResponse.text("Hellow, World!") ) }) ) const { dispose, handler } = HttpLayerRouter.toWebHandler(HelloRoute) // When the process is interrupted, we want to clean up resources process.on("SIGINT", () => { dispose().then( () => { process.exit(0) }, () => { process.exit(1) } ) }) // Use the handler in your server setup export { handler } ``` -------------------------------- ### Execute Effect-TS CLI Application with tsx Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This shell command demonstrates how to run the `hello-world.ts` CLI application directly from the terminal using `npx tsx`. `tsx` compiles and executes TypeScript on-the-fly, eliminating the need for manual compilation, while `npx` handles temporary package installation and execution. ```sh npx tsx hello-world.ts ``` -------------------------------- ### GET /* (Catch-All) Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Defines a catch-all endpoint that matches any incoming path. This is useful for handling unmatched routes or providing a fallback response for unhandled requests. ```APIDOC ## GET /* ### Description This endpoint acts as a catch-all for any path that hasn't been explicitly matched by other routes. It can be used for fallback responses or error handling. ### Method GET ### Endpoint * ### Parameters #### Path Parameters - No Path Parameters #### Query Parameters - No Query Parameters #### Request Body - No Request Body ### Request Example ```json {} ``` ### Response #### Success Response (200) - No explicit schema provided, typically a generic response or redirect. #### Response Example ```json { "message": "No specific route matched, this is the catch-all response." } ``` ``` -------------------------------- ### GET /users Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Retrieves a list of all users. This example shows a basic GET endpoint without specific error handling defined directly on it, but it would inherit group or API-level errors, such as 'Unauthorized'. ```APIDOC ## GET /users ### Description Retrieves a list of all users. ### Method GET ### Endpoint /users ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (None) ### Response #### Success Response (200) - **id** (number) - The unique identifier of the user. - **name** (string) - The name of the user. - **createdAt** (string) - The UTC timestamp when the user was created (ISO 8601 format). #### Response Example ```json [ { "id": 1, "name": "Alice", "createdAt": "2023-01-01T12:00:00Z" }, { "id": 2, "name": "Bob", "createdAt": "2023-01-02T13:00:00Z" } ] ``` #### Error Response (401 Unauthorized) - Inherited from group - **_tag** (string) - "Unauthorized" #### Error Response Example (401) ```json { "_tag": "Unauthorized" } ``` ``` -------------------------------- ### Retrieve JSON Data with HttpClient Service (GET) Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Demonstrates accessing the HttpClient service via Effect context and executing a GET request to retrieve JSON data. The example uses FetchHttpClient.layer to provide the HttpClient implementation and processes the response as JSON. ```typescript import { FetchHttpClient, HttpClient } from "@effect/platform" import { Effect } from "effect" const program = Effect.gen(function* () { // Access HttpClient const client = yield* HttpClient.HttpClient // Create and execute a GET request const response = yield* client.get( "https://jsonplaceholder.typicode.com/posts/1" ) const json = yield* response.json console.log(json) }).pipe( // Provide the HttpClient Effect.provide(FetchHttpClient.layer) ) Effect.runPromise(program) ``` -------------------------------- ### Global Help Command Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md Display the main help documentation for Minigit, showing all available commands and global options. This is the entry point for understanding the CLI structure and available functionality. ```APIDOC ## HELP COMMAND ### Description Display comprehensive help documentation for Minigit CLI, including all available commands and global options. ### Command ```sh npx tsx minigit.ts --help ``` ### Global Options #### -c text - **Type**: String (property argument) - **Required**: Optional - **Description**: A user-defined piece of text. May be specified a single time or multiple times. - **Examples**: - Single: `-c key1=value key2=value2` - Multiple: `-c key1=value -c key2=value2` #### --completions - **Type**: Enum (sh | bash | fish | zsh) - **Required**: Optional - **Description**: Generate a completion script for a specific shell. #### -h, --help - **Type**: Boolean - **Required**: Optional - **Description**: Show the help documentation for a command. #### --wizard - **Type**: Boolean - **Required**: Optional - **Description**: Start wizard mode for a command. #### --version - **Type**: Boolean - **Required**: Optional - **Description**: Show the version of the application. ### Available Commands - `add [(-v, --verbose)] ...` - `clone [--depth integer] []` ``` -------------------------------- ### View Minigit CLI Global Help Documentation (sh) Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This command displays the comprehensive help documentation for the `minigit` tool. It lists all available global options and top-level commands, providing an overview of the CLI's capabilities and usage. ```sh npx tsx minigit.ts --help ``` -------------------------------- ### Define URL Parameters with Metadata for GET Endpoint (Effect-TS) Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This example demonstrates using `setUrlParams` to define the structure of URL query parameters for a GET endpoint. It shows how to specify schemas for parameters like `page` and `sort`, including adding metadata such as a description to `sort` for better documentation. ```ts import { HttpApiEndpoint } from "@effect/platform" import { Schema } from "effect" const User = Schema.Struct({ id: Schema.Number, name: Schema.String, createdAt: Schema.DateTimeUtc }) const getUsers = HttpApiEndpoint.get("getUsers", "/users") // Specify the URL parameters schema .setUrlParams( Schema.Struct({ // Parameter "page" for pagination page: Schema.NumberFromString, // Parameter "sort" for sorting options with an added description sort: Schema.String.annotations({ description: "Sorting criteria (e.g., 'name', 'date')" }) }) ) .addSuccess(Schema.Array(User)) ``` -------------------------------- ### Create minigit CLI with Config Options and Subcommands Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md Demonstrates building a minigit CLI application with built-in version and help options, plus add and clone subcommands. The main command accepts optional key-value configuration pairs via the -c flag, while subcommands handle specific Git-like operations with their own options and arguments. ```typescript import { Args, Command, Options } from "@effect/cli" import { Console, Option, Array } from "effect" // minigit [--version] [-h | --help] [-c =] const configs = Options.keyValueMap("c").pipe(Options.optional) const minigit = Command.make("minigit", { configs }, ({ configs }) => Option.match(configs, { onNone: () => Console.log("Running 'minigit'"), onSome: (configs) => { const keyValuePairs = Array.fromIterable(configs) .map(([key, value]) => `${key}=${value}`) .join(", ") return Console.log( `Running 'minigit' with the following configs: ${keyValuePairs}` ) } }) ) // minigit add [-v | --verbose] [--] [...] const pathspec = Args.text({ name: "pathspec" }).pipe(Args.repeated) const verbose = Options.boolean("verbose").pipe(Options.withAlias("v")) const minigitAdd = Command.make( "add", { pathspec, verbose }, ({ pathspec, verbose }) => { const paths = Array.match(pathspec, { onEmpty: () => "", onNonEmpty: (paths) => ` ${Array.join(paths, " ")}` }) return Console.log( `Running 'minigit add${paths}' with '--verbose ${verbose}'` ) } ) // minigit clone [--depth ] [--] [] const repository = Args.text({ name: "repository" }) const directory = Args.text({ name: "directory" }).pipe(Args.optional) const depth = Options.integer("depth").pipe(Options.optional) const minigitClone = Command.make( "clone", { repository, directory, depth }, (config) => { const depth = Option.map(config.depth, (depth) => `--depth ${depth}`) const repository = Option.some(config.repository) const optionsAndArgs = Array.getSomes([depth, repository, config.directory]) return Console.log( "Running 'minigit clone' with the following options and arguments: " + `'${Array.join(optionsAndArgs, ", ')}'` ) } ) ``` -------------------------------- ### Define basic HTTP routes (GET, POST, PUT, DELETE) with Effect-TS HttpRouter Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This snippet illustrates how to define various HTTP routes using the `HttpRouter` from `@effect/platform`. It shows examples for responding to different HTTP methods (GET, POST, PUT, DELETE) on specific paths like the root URL and `/user`. ```ts router.pipe(HttpRouter.get("/", HttpServerResponse.text("Hello World"))) router.pipe(HttpRouter.post("/", HttpServerResponse.text("Got a POST request"))) router.pipe( HttpRouter.put("/user", HttpServerResponse.text("Got a PUT request at /user")) ) router.pipe( HttpRouter.del( "/user", HttpServerResponse.text("Got a DELETE request at /user") ) ) ``` -------------------------------- ### Defining a GET Endpoint with `HttpApiEndpoint.get` in Effect-TS Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This example illustrates how to define a simple GET endpoint using `HttpApiEndpoint.get`. It demonstrates specifying the endpoint's name and path, and then using `.addSuccess` to define the schema for a successful response, in this case, an array of `User` objects. If no success schema is provided, the default response is `204 No Content`. ```ts import { HttpApiEndpoint } from "@effect/platform" import { Schema } from "effect" // Define a schema representing a User entity const User = Schema.Struct({ id: Schema.Number, name: Schema.String, createdAt: Schema.DateTimeUtc }) // Define the "getUsers" endpoint, returning a list of users const getUsers = HttpApiEndpoint // ┌─── Endpoint name // │ ┌─── Endpoint path // ▼ ▼ .get("getUsers", "/users") // Define the success schema for the response (optional). // If no response schema is specified, the default response is `204 No Content`. .addSuccess(Schema.Array(User)) ``` -------------------------------- ### Create a basic 'Hello World' HTTP server using Effect-TS Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This snippet demonstrates how to set up a simple HTTP server that responds with 'Hello World!' on the root path. It includes implementations for both Node.js and Bun runtimes, listening on port 3000 and logging the server address. ```ts import { HttpRouter, HttpServer, HttpServerResponse } from "@effect/platform" import { NodeHttpServer, NodeRuntime } from "@effect/platform-node" import { Layer } from "effect" import { createServer } from "node:http" // Define the router with a single route for the root URL const router = HttpRouter.empty.pipe( HttpRouter.get("/", HttpServerResponse.text("Hello World")) ) // Set up the application server with logging const app = router.pipe(HttpServer.serve(), HttpServer.withLogAddress) // Specify the port const port = 3000 // Create a server layer with the specified port const ServerLive = NodeHttpServer.layer(() => createServer(), { port }) // Run the application NodeRuntime.runMain(Layer.launch(Layer.provide(app, ServerLive))) ``` ```ts import { HttpRouter, HttpServer, HttpServerResponse } from "@effect/platform" import { BunHttpServer, BunRuntime } from "@effect/platform-bun" import { Layer } from "effect" // Define the router with a single route for the root URL const router = HttpRouter.empty.pipe( HttpRouter.get("/", HttpServerResponse.text("Hello World")) ) // Set up the application server with logging const app = router.pipe(HttpServer.serve(), HttpServer.withLogAddress) // Specify the port const port = 3000 // Create a server layer with the specified port const ServerLive = BunHttpServer.layer({ port }) // Run the application BunRuntime.runMain(Layer.launch(Layer.provide(app, ServerLive))) ``` -------------------------------- ### Add Predefined Error Type to HTTP Endpoint Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Demonstrates adding a predefined error type (HttpApiError.NotFound) to an HTTP endpoint definition. This example shows how to define a User schema, create a path parameter, and attach both success and error responses to a GET endpoint. ```typescript import { HttpApiEndpoint, HttpApiError, HttpApiSchema } from "@effect/platform" import { Schema } from "effect" const User = Schema.Struct({ id: Schema.Number, name: Schema.String, createdAt: Schema.DateTimeUtc }) const idParam = HttpApiSchema.param("id", Schema.NumberFromString) const getUser = HttpApiEndpoint.get("getUser")`/user/${idParam}` .addSuccess(User) .addError(HttpApiError.NotFound) ``` -------------------------------- ### Derive and Use HttpApiClient with Server Implementation in TypeScript Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Shows how to create a complete API setup with server handlers and derive a client to interact with it. Includes schema definitions, endpoint grouping, server implementation with handlers, middleware configuration, and client usage with Fetch HTTP client. Demonstrates the full workflow from API definition to client invocation. ```typescript import { FetchHttpClient, HttpApi, HttpApiBuilder, HttpApiClient, HttpApiEndpoint, HttpApiGroup, HttpApiSchema, HttpApiSwagger, HttpMiddleware, HttpServer } from "@effect/platform" import { NodeHttpServer, NodeRuntime } from "@effect/platform-node" import { DateTime, Effect, Layer, Schema } from "effect" import { createServer } from "node:http" const User = Schema.Struct({ id: Schema.Number, name: Schema.String, createdAt: Schema.DateTimeUtc }) const idParam = HttpApiSchema.param("id", Schema.NumberFromString) const usersGroup = HttpApiGroup.make("users").add( HttpApiEndpoint.get("getUser")`/user/${idParam}`.addSuccess(User) ) const api = HttpApi.make("myApi").add(usersGroup) const usersGroupLive = HttpApiBuilder.group(api, "users", (handlers) => handlers.handle("getUser", ({ path: { id } }) => Effect.succeed({ id, name: "John Doe", createdAt: DateTime.unsafeNow() }) ) ) const MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(usersGroupLive)) const HttpLive = HttpApiBuilder.serve(HttpMiddleware.logger).pipe( Layer.provide(HttpApiSwagger.layer()), Layer.provide(HttpApiBuilder.middlewareCors()), Layer.provide(MyApiLive), HttpServer.withLogAddress, Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })) ) Layer.launch(HttpLive).pipe(NodeRuntime.runMain) // Create a program that derives and uses the client const program = Effect.gen(function* () { // Derive the client const client = yield* HttpApiClient.make(api, { baseUrl: "http://localhost:3000" }) // Call the `getUser` endpoint const user = yield* client.users.getUser({ path: { id: 1 } }) console.log(user) }) // Provide a Fetch-based HTTP client and run the program Effect.runFork(program.pipe(Effect.provide(FetchHttpClient.layer))) ``` -------------------------------- ### Assemble minigit CLI with Commands and Subcommands Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md Creates a complete CLI application structure with a main 'minigit' command and subcommands for 'add' and 'clone'. Demonstrates command composition using Effect's CLI module, including option parsing, argument handling, and command integration. Requires @effect/cli and @effect/platform-node packages. ```typescript import { Args, Command, Options } from "@effect/cli" import { NodeContext, NodeRuntime } from "@effect/platform-node" import { Console, Effect, Option, Array } from "effect" // minigit [--version] [-h | --help] [-c =] const configs = Options.keyValueMap("c").pipe(Options.optional) const minigit = Command.make("minigit", { configs }, ({ configs }) => Option.match(configs, { onNone: () => Console.log("Running 'minigit'"), onSome: (configs) => { const keyValuePairs = Array.fromIterable(configs) .map(([key, value]) => `${key}=${value}`) .join(", ") return Console.log( `Running 'minigit' with the following configs: ${keyValuePairs}` ) } }) ) // minigit add [-v | --verbose] [--] [...] const pathspec = Args.text({ name: "pathspec" }).pipe(Args.repeated) const verbose = Options.boolean("verbose").pipe(Options.withAlias("v")) const minigitAdd = Command.make( "add", { pathspec, verbose }, ({ pathspec, verbose }) => { const paths = Array.match(pathspec, { onEmpty: () => "", onNonEmpty: (paths) => ` ${Array.join(paths, " ")}` }) return Console.log( `Running 'minigit add${paths}' with '--verbose ${verbose}'` ) } ) // minigit clone [--depth ] [--] [] const repository = Args.text({ name: "repository" }) const directory = Args.text({ name: "directory" }).pipe(Args.optional) const depth = Options.integer("depth").pipe(Options.optional) const minigitClone = Command.make( "clone", { repository, directory, depth }, (config) => { const depth = Option.map(config.depth, (depth) => `--depth ${depth}`) const repository = Option.some(config.repository) const optionsAndArgs = Array.getSomes([depth, repository, config.directory]) return Console.log( "Running 'minigit clone' with the following options and arguments: " + `'${Array.join(optionsAndArgs, ", ')}'` ) } ) // Combine all commands into the main 'minigit' command const command = minigit.pipe( Command.withSubcommands([minigitAdd, minigitClone]) ) // Initialize and run the CLI application const cli = Command.run(command, { name: "Minigit Distributed Version Control", version: "v1.0.0" }) cli(process.argv).pipe(Effect.provide(NodeContext.layer), NodeRuntime.runMain) ``` -------------------------------- ### Deriving and Using an HTTP API Client Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Learn how to derive a client from a defined API and use it to make HTTP requests to your endpoints. This example demonstrates creating a simple API with a greeting endpoint, setting up a server, and then using the derived client to call the endpoint. ```APIDOC ## HTTP API Client Derivation ### Description Derives a typed client from an HttpApi definition to interact with API endpoints without manually handling HTTP requests. ### Method GET, POST, PUT, DELETE (varies by endpoint) ### Endpoint Configurable via baseUrl parameter ### Usage The HttpApiClient.make function creates a client instance that provides type-safe access to all defined API endpoints. ### Parameters #### Configuration Parameters - **MyApi** (HttpApi) - Required - The API definition to create a client for - **baseUrl** (string) - Required - The base URL for all API requests (e.g., "http://localhost:3000") ### Request Example ```ts const client = yield* HttpApiClient.make(MyApi, { baseUrl: "http://localhost:3000" }) const hello = yield* client.Greetings["hello-world"]() ``` ### Response #### Success Response - **result** (any) - The typed response from the endpoint based on the endpoint's success schema #### Response Example ```ts // Output: Hello, World! ``` ### Notes - Requires FetchHttpClient.layer to be provided - Client methods are organized by API groups - All responses are type-safe based on endpoint definitions ``` -------------------------------- ### Map Request Input and Output with HttpClient in TypeScript Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Shows the difference between `mapRequest` (appends transformations at the end of the chain) and `mapRequestInput` (prepends transformations at the start). The example demonstrates execution order by logging numbers, with mapRequestInput executing first (3), followed by appended transformations (1, 2). ```typescript import { FetchHttpClient, HttpClient } from "@effect/platform" import { Effect } from "effect" const program = Effect.gen(function* () { const client = (yield* HttpClient.HttpClient).pipe( // Append transformation HttpClient.mapRequest((req) => { console.log(1) return req }), // Another append transformation HttpClient.mapRequest((req) => { console.log(2) return req }), // Prepend transformation, this executes first HttpClient.mapRequestInput((req) => { console.log(3) return req }) ) const response = yield* client.get( "https://jsonplaceholder.typicode.com/posts/1" ) const json = yield* response.json console.log(json) }).pipe(Effect.provide(FetchHttpClient.layer)) Effect.runPromise(program) ``` -------------------------------- ### Create Command with Key-Value Options in TypeScript Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md Demonstrates creating a minigit command that accepts optional key-value pair configurations using Options.keyValueMap and Options.optional. The handler uses Option.match to conditionally log output based on whether configurations were provided, showcasing practical option handling and user feedback. ```typescript import { Command, Options } from "@effect/cli" import { Console, Option } from "effect" // minigit [--version] [-h | --help] [-c =] const configs = Options.keyValueMap("c").pipe(Options.optional) // Define the main 'minigit' command const minigit = Command.make( "minigit", // Configuration object for the command { configs }, // Handler function that executes the command ({ configs }) => Option.match(configs, { onNone: () => Console.log("Running 'minigit'"), onSome: (configs) => { const keyValuePairs = Array.from( configs, ([key, value]) => `${key}=${value}` ).join(", ") return Console.log( `Running 'minigit' with the following configs: ${keyValuePairs}` ) } }) ) ``` -------------------------------- ### Extract and Validate Route Parameters with Schema Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Demonstrates how to define routes with named parameters (e.g., :userId, :bookId) and validate them using Effect Schema. Creates a router that captures URL parameters, validates them against a schema, and returns the parsed parameters as JSON. Includes a complete example with server setup. ```typescript import { HttpRouter, HttpServer, HttpServerResponse } from "@effect/platform" import { Effect, Schema } from "effect" import { listen } from "./listen.js" // Define the schema for route parameters const Params = Schema.Struct({ userId: Schema.String, bookId: Schema.String }) // Create a router with a route that captures parameters const router = HttpRouter.empty.pipe( HttpRouter.get( "/users/:userId/books/:bookId", HttpRouter.schemaPathParams(Params).pipe( Effect.flatMap((params) => HttpServerResponse.json(params)) ) ) ) const app = router.pipe(HttpServer.serve()) listen(app, 3000) ``` -------------------------------- ### Apply Cookie Validator Middleware to HTTP Server in TypeScript Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Demonstrates a complete HTTP server setup using Effect.ts that applies the cookie validator middleware at the router level. The server responds with 'Hello World' for GET requests to '/' if the cookie validation passes, otherwise returns 'Invalid cookie'. ```typescript import { HttpMiddleware, HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "@effect/platform" import { Effect } from "effect" import { listen } from "./listen.js" class CookieError { readonly _tag = "CookieError" } const externallyValidateCookie = (testCookie: string | undefined) => testCookie && testCookie.length > 0 ? Effect.succeed(testCookie) : Effect.fail(new CookieError()) const cookieValidator = HttpMiddleware.make((app) => Effect.gen(function* () { const req = yield* HttpServerRequest.HttpServerRequest yield* externallyValidateCookie(req.cookies.testCookie) return yield* app }).pipe( Effect.catchTag("CookieError", () => HttpServerResponse.text("Invalid cookie") ) ) ) const router = HttpRouter.empty.pipe( HttpRouter.get("/", HttpServerResponse.text("Hello World")) ) const app = router.pipe(HttpRouter.use(cookieValidator), HttpServer.serve()) listen(app, 3000) ``` -------------------------------- ### Deriving and Using an Effect-TS API Client Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This example demonstrates the complete flow of defining an API, setting up a server, deriving a client from the API definition, and then using that client to interact with the API endpoints. It showcases the `HttpApiClient` module for client generation and `FetchHttpClient` for execution, allowing programmatic interaction with your API without manual HTTP request handling. ```ts import { FetchHttpClient, HttpApi, HttpApiBuilder, HttpApiClient, HttpApiEndpoint, HttpApiGroup, HttpApiSwagger } from "@effect/platform" import { NodeHttpServer, NodeRuntime } from "@effect/platform-node" import { Effect, Layer, Schema } from "effect" import { createServer } from "node:http" const MyApi = HttpApi.make("MyApi").add( HttpApiGroup.make("Greetings").add( HttpApiEndpoint.get("hello-world")`/`.addSuccess(Schema.String) ) ) const GreetingsLive = HttpApiBuilder.group(MyApi, "Greetings", (handlers) => handlers.handle("hello-world", () => Effect.succeed("Hello, World!")) ) const MyApiLive = HttpApiBuilder.api(MyApi).pipe(Layer.provide(GreetingsLive)) const ServerLive = HttpApiBuilder.serve().pipe( Layer.provide(HttpApiSwagger.layer()), Layer.provide(MyApiLive), Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })) ) Layer.launch(ServerLive).pipe(NodeRuntime.runMain) // Create a program that derives and uses the client const program = Effect.gen(function* () { // Derive the client const client = yield* HttpApiClient.make(MyApi, { baseUrl: "http://localhost:3000" }) // Call the "hello-world" endpoint const hello = yield* client.Greetings["hello-world"]() console.log(hello) }) // Provide a Fetch-based HTTP client and run the program Effect.runFork(program.pipe(Effect.provide(FetchHttpClient.layer))) // Output: Hello, World! ``` -------------------------------- ### Activate Wizard Mode in Effect-TS CLI Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This command demonstrates how to activate the interactive Wizard Mode in an Effect-TS CLI application. The `--wizard` option guides users through command construction, making it easier for new users or when dealing with complex commands by providing interactive prompts. ```sh npx tsx hello-world.ts --wizard ``` -------------------------------- ### Define and Run Basic Effect-TS CLI Application Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This TypeScript snippet defines a simple 'Hello World' CLI application using `@effect/cli`, integrating with Node.js runtime via `@effect/platform-node`. It sets up a command to print 'Hello World', configures the CLI's name and version, and prepares it for execution by processing command-line arguments and providing the Node.js context. ```ts // Import necessary modules from the libraries import { Command } from "@effect/cli" import { NodeContext, NodeRuntime } from "@effect/platform-node" import { Console, Effect } from "effect" // Define the top-level command const command = Command.make("hello-world", {}, () => Console.log("Hello World") ) // Set up the CLI application const cli = Command.run(command, { name: "Hello World CLI", version: "v1.0.0" }) // Prepare and run the CLI application cli(process.argv).pipe(Effect.provide(NodeContext.layer), NodeRuntime.runMain) ``` -------------------------------- ### POST /users Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md Creates a new user account. ```APIDOC ## POST /users ### Description Creates a new user account. ### Method POST ### Endpoint /users ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body - **name** (string) - Required - The name of the user to create. ### Request Example ```json { "name": "Charlie" } ``` ### Response #### Success Response (200) - **id** (number) - The unique identifier of the newly created user. - **name** (string) - The name of the user. - **createdAt** (string) - The timestamp when the user account was created (ISO 8601 format). #### Response Example ```json { "id": 3, "name": "Charlie", "createdAt": "2023-01-03T12:00:00Z" } ``` ``` -------------------------------- ### Define `minigit` CLI Command Structure with Effect/CLI Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This snippet illustrates the desired command-line interface structure for a `minigit` application, showcasing how to define a main command with global options and multiple subcommands like `add` and `clone`, each with their specific arguments and options. This serves as a blueprint for building a Git-style CLI using `@effect/cli`. ```shell minigit [-v | --version] [-h | --help] [-c =] minigit add [-v | --verbose] [--] [...] minigit clone [--depth ] [--] [] ``` -------------------------------- ### Handle Incorrect Argument Parsing in Effect-TS CLI Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This example illustrates a common mistake when running CLIs: providing multiple unquoted words as an argument. The CLI interprets each word as a separate argument, leading to an 'unknown argument' error for subsequent words. This highlights the importance of quoting multi-word inputs to ensure they are parsed as a single argument. ```sh npx tsx echo.ts This is a test # Output: Received unknown argument: 'is' ``` -------------------------------- ### Combine Effect-TS CLI Commands and Erase Parent Context (TypeScript) Source: https://github.com/effect-ts/effect/blob/main/packages/cli/README.md This TypeScript example demonstrates how to integrate a subcommand (`minigitClone`) into its parent command (`minigit`) using `Command.withSubcommands`. It also highlights that the parent command's context, which was previously required by the subcommand, is 'erased' from the combined command's environment, simplifying the top-level command's execution. ```ts const command = minigit.pipe(Command.withSubcommands([minigitClone])) // ^? Command<"minigit", never, ..., ...> ``` -------------------------------- ### Configuring FetchHttpClient with RequestInit Options in Effect-TS Source: https://github.com/effect-ts/effect/blob/main/packages/platform/README.md This example illustrates how to customize the `FetchHttpClient` by providing standard `RequestInit` options, such as `credentials`. It demonstrates using `Layer.succeed` to inject a configuration object for `RequestInit` into the `FetchHttpClient.layer`, ensuring that all subsequent requests made by this client will include the specified options. ```ts import { FetchHttpClient, HttpClient } from "@effect/platform" import { Effect, Layer } from "effect" const CustomFetchLive = FetchHttpClient.layer.pipe( Layer.provide( Layer.succeed(FetchHttpClient.RequestInit, { credentials: "include" }) ) ) const program = Effect.gen(function* () { const client = yield* HttpClient.HttpClient const response = yield* client.get( "https://jsonplaceholder.typicode.com/posts/1" ) const json = yield* response.json console.log(json) }).pipe(Effect.provide(CustomFetchLive)) ``` -------------------------------- ### CSS Styling Example for JSDoc Source: https://github.com/effect-ts/effect/blob/main/scripts/jsdocs/code2jsdoc-example.html An example of CSS styling that could be included within a JSDoc `@example` block. It defines basic styles for the `body` and `textarea` elements, setting fonts, borders, margins, and padding for a consistent UI appearance. ```css body { font-family: Arial; } textarea { font-family: Courier, monospace; border: 1px solid #ccc; border-radius: 4px; margin: 0.5rem; padding: 0.5rem; font-size: medium; } ```