### Basic AutoRouter Setup and GET Routes Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/index.md Demonstrates initializing AutoRouter and defining simple GET routes for string, JSON, and Promise responses. Ensure 'itty-router' is installed. ```javascript import { AutoRouter } from 'itty-router' const router = AutoRouter() router .get('/hello/:name', ({ name }) => `Hello, ${name}!`) .get('/json', () => [1,2,3]) .get('/promises', () => Promise.resolve('foo')) export default { ...router } ``` -------------------------------- ### Install Dependencies and Run Locally Source: https://github.com/kwhitley/itty.dev/blob/main/README.md Use these commands to install project dependencies with Bun and start the development server. ```bash bun install bun dev ``` -------------------------------- ### Build Failure Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example output demonstrating a build failure during the prepare sequence. ```text ๐Ÿš€ Running prepare sequence... ๐Ÿ” Running lint script... โœ… Lint passed ๐Ÿงช Running test script... โœ… Tests passed ๐Ÿ”จ Running built-in build... โŒ Command failed: Build failed: [error details] ``` -------------------------------- ### Usage Examples Source: https://github.com/kwhitley/itty.dev/blob/main/itty-chroma/api.md Illustrative examples demonstrating how to use Chroma for basic and complex console styling, including reusable styles. ```APIDOC ## Examples ```ts // Basic styling chroma.red.log('Error message') chroma.green.bold.log('Success!') // Complex styling chroma.blue.bg('lightgray').padding('10px').radius('5px').log('Card-like styling') // Multiple arguments chroma.log('Normal text', chroma.red.bold, 'Bold red text', chroma.blue, 'Blue text') // Reusable styles const errorStyle = chroma.red.bold.bg('lightyellow').padding('5px') errorStyle.log('Error 1') errorStyle.log('Error 2') ``` ``` -------------------------------- ### Run Prepare with Verbose Output (Example) Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Demonstrates how to run the prepare command and see detailed output from each step. ```bash # See detailed output from each step ity prepare --verbose ``` -------------------------------- ### Prepare then Release Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Shows how to chain the 'itty prepare' command with 'itty release' for a complete release process. ```bash # Prepare then release ity prepare && itty release ``` -------------------------------- ### Create JSON Response Object Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/responses.md This example shows how the `json` helper constructs a `Response` object with the appropriate content type and body. No specific setup is required beyond importing `json`. ```javascript new Response({ status: 418, headers: { 'content-type': 'application/json', }, body: '{"foo":"bar"}' }) ``` -------------------------------- ### Custom Scripts Integration Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example package.json scripts demonstrating integration with custom lint, test, and build tools. ```json { "scripts": { "lint": "eslint . --ext .ts,.js", "test": "vitest run", "build": "tsup src/index.ts", "type-check": "tsc --noEmit" } } ``` -------------------------------- ### Start Development Server with Bun Source: https://github.com/kwhitley/itty.dev/blob/main/CLAUDE.md Starts the development server for local development. This command is an alias for 'npm run dev'. ```bash bun dev ``` -------------------------------- ### Production Ready Build Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Build command for production, enabling minification and hybrid ESM/CJS output. ```bash # Minified with both ESM and CJS itty build --minify --hybrid ``` -------------------------------- ### Prepare Command Progress Indicators Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example output showing the progress indicators during the prepare sequence. ```text ๐Ÿš€ Running prepare sequence... ๐Ÿ” Running lint script... โœ… Lint passed ๐Ÿงช Running test script... โœ… Tests passed ๐Ÿ”จ Running built-in build... โœ… Build completed ๐ŸŽ‰ Prepare sequence completed successfully ``` -------------------------------- ### Installation Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/getting-started.md Install itty-router using your preferred package manager. ```APIDOC ## Installation Install itty-router using your preferred package manager. ### npm ```bash npm install itty-router ``` ### yarn ```bash yarn add itty-router ``` ### pnpm ```bash pnpm i itty-router ``` ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/kwhitley/itty.dev/blob/main/CLAUDE.md Use this command to install project dependencies. Bun is preferred over npm for this project. ```bash bun install ``` -------------------------------- ### Basic Library Build Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Standard command to build a TypeScript library. ```bash # Standard TypeScript library itty build ``` -------------------------------- ### Custom Directories Build Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Build command specifying custom source and output directories. ```bash # Build from lib/ to build/ itty build --from=lib --out=build ``` -------------------------------- ### Itty-router Example with Error Handling Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/errors.md This example demonstrates integrating `error` and `StatusError` into an itty-router setup. It includes catching uncaught errors, transforming responses to JSON, returning errors directly, manual and automatic throwing, and a standard 404 pattern. ```javascript import { Router, error, json } from 'itty-router' const router = Router({ catch: error, // catch uncaught errors finally: [json], // transform responses to JSON (if not already Response) }) router // returning an error directly .get('/error-response', () => error(400)) // manual throwing .get('/manual-throw', () => { const ids = [1, 2, 3] ids.forEach(id => { if (id > 2) { // This works even when a return (error) would not. throw new StatusError(400, 'Yikes!') } }) }) // automatic throwing (will throw a standard Error) .get('/auto-throw', (request) => request.a.b.c.d ) // standard 404 pattern for your outermost router .all('*', () => error(404)) export default { ...router } // which translates to // export default { // fetch: (request, ...otherArguments) => // router.fetch(request, ...otherArguments) // } ``` -------------------------------- ### Release Workflow with Prepare Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example of using 'itty prepare' to validate code before executing a release. ```bash # Validate before releasing ity prepare ity release --minor --tag --push ``` -------------------------------- ### Package.json Scripts for Prepare Command Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example package.json configuration showing scripts that 'itty prepare' will detect and use. ```json { "scripts": { "lint": "eslint src/", // Used for lint step "test": "jest", // Used for test step "build": "tsc && rollup -c" // Used for build step } } ``` -------------------------------- ### Basic Patch Release Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/release.md This example shows the simplest way to perform a patch release using the `itty release` command, which defaults to releasing from the `dist/` directory. ```bash # Simple patch release ity release ``` -------------------------------- ### Initialize and Configure AutoRouter Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/routers/autorouter.md Import and instantiate AutoRouter to create a router with default middleware. This example shows basic GET routes for JSON and parameter extraction. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() router .get('/json', () => ({ foo: 'bar', array: [1,2,3] })) .get('/params/:id', ({ id }) => id) export default { ...router } ``` -------------------------------- ### Development Workflow with Prepare Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example of using 'itty prepare' as part of a typical development workflow before committing code. ```bash # Check before committing ity prepare git add . git commit -m "feat: new feature" ``` -------------------------------- ### Package.json Exports for Multiple Files Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Example of `package.json` exports configuration for a multi-file build. ```json { "exports": { ".": { "import": "./index.mjs", "types": "./index.d.ts" }, "./utils": { "import": "./utils.mjs", "types": "./utils.d.ts" } } } ``` -------------------------------- ### Package.json Exports for Single File Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Example of `package.json` exports configuration for a single-file build. ```json { "exports": { ".": { "import": "./index.mjs", "types": "./index.d.ts" } } } ``` -------------------------------- ### Install itty-packager Globally Source: https://context7.com/kwhitley/itty.dev/llms.txt Command to install the itty-packager CLI tool globally on your system. ```bash # Install globally npm install -g itty-packager ``` -------------------------------- ### Lint Failure Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example output demonstrating a lint failure during the prepare sequence. ```text ๐Ÿš€ Running prepare sequence... ๐Ÿ” Running lint script... โŒ Command failed: Lint failed: ESLint exited with code 1 [ESLint error details] ``` -------------------------------- ### Test Failure Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example output demonstrating a test failure during the prepare sequence. ```text ๐Ÿš€ Running prepare sequence... ๐Ÿ” Running lint script... โœ… Lint passed ๐Ÿงช Running test script... โŒ Command failed: Tests failed: Script 'test' exited with code 1 [Test error details] ``` -------------------------------- ### Install and Use itty-packager Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/index.md Install itty-packager globally or use it with npx. Then, run commands like `itty build`, `itty lint`, `itty prepare`, or `itty release` in your TypeScript project. ```bash # Install globally or use with npx npm install -g itty-packager # In your TypeScript project ity build # Build your project ity lint # Lint your code ity prepare # Run full pre-release sequence ity release --minor # Release with version bump ``` -------------------------------- ### Error Handling Examples Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/errors.md Illustrates various scenarios of error handling within an itty-router setup, including returning errors directly, manual throwing, and automatic error throwing. ```APIDOC ## Examples The following examples demonstrate a few of the possible error scenarios you may run into while using itty-router: ```js import { Router, error, json } from 'itty-router' const router = Router({ catch: error, // catch uncaught errors finally: [json], // transform responses to JSON (if not already Response) }) router // returning an error directly .get('/error-response', () => error(400)) // manual throwing .get('/manual-throw', () => { const ids = [1, 2, 3] ids.forEach(id => { if (id > 2) { // This works even when a return (error) would not. throw new StatusError(400, 'Yikes!') } }) }) // automatic throwing (will throw a standard Error) .get('/auto-throw', (request) => request.a.b.c.d ) // standard 404 pattern for your outermost router .all('*', () => error(404)) export default { ...router } // which translates to // export default { // fetch: (request, ...otherArguments) => // router.fetch(request, ...otherArguments) // } ``` ``` -------------------------------- ### Passing Additional Arguments to Handlers Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/typescript/additional-arguments.md Demonstrates how arguments passed to router.fetch() are passed to all downstream handlers. This example shows a basic setup without explicit typing. ```typescript import { Router } from 'itty-router' const router = Router() router.get('/', (request, ctx) => { // [!code ++] ctx.foo // bar }) // fake request const request = new Request('https://foo.bar') // fake context const CONTEXT = { foo: 'bar' } router.fetch(request, CONTEXT) ``` -------------------------------- ### CI Validation with Prepare Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example of using 'itty prepare --verbose' for comprehensive validation in a CI environment. ```bash # Full validation in CI ity prepare --verbose ``` -------------------------------- ### Basic Itty.dev Router Setup Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/routers/router.md Demonstrates setting up an Itty.dev Router with `before`, `catch`, and `finally` stages. Use this for defining request handling pipelines with middleware and error handling. ```typescript import { Router, error, json, withParams } from 'itty-router' const router = Router({ before: [withParams], catch: error, finally: [json], }) router .get('/json', () => ({ foo: 'bar', array: [1,2,3] })) .get('/params/:id', ({ id }) => id) .all('*', () => error(404)) export default { ...router } ``` -------------------------------- ### Install itty-router with npm, yarn, or pnpm Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/getting-started.md Choose your preferred package manager to install the itty-router library. ```bash npm install itty-router ``` ```bash yarn add itty-router ``` ```bash pnpm i itty-router ``` -------------------------------- ### Build Without Source Maps Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Build command to skip source map generation, useful for production. ```bash # Skip source maps for production itty build --no-sourcemap --minify ``` -------------------------------- ### Integration with package.json Scripts Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Example of how to integrate `itty build` commands into the `scripts` section of `package.json`. ```json { "scripts": { "build": "itty build", "build:prod": "itty build --minify --hybrid", "build:dev": "itty build --sourcemap" } } ``` -------------------------------- ### Output Structure for Multi-File Project Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Example of the output directory structure for a multi-file TypeScript project after building. ```text dist/ โ”œโ”€โ”€ index.mjs โ”œโ”€โ”€ index.d.ts โ”œโ”€โ”€ utils.mjs โ”œโ”€โ”€ utils.d.ts โ””โ”€โ”€ *.mjs.map ``` -------------------------------- ### GitHub Actions CI/CD Integration Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Example of how to integrate the 'itty prepare' command into a GitHub Actions workflow for CI validation. ```yaml # GitHub Actions example - name: Prepare package run: itty prepare --verbose - name: Release run: itty release --dry-run if: github.ref == 'refs/heads/main' ``` -------------------------------- ### Make GET Requests Source: https://github.com/kwhitley/itty.dev/blob/main/itty-fetcher/api.md Use the `.get()` method to perform GET requests. It accepts an optional URL and/or options. If no URL is provided, the base URL is used. ```typescript await api.get('/users') await api.get('/users', { headers: { 'Accept': 'text/xml' } }) await api.get({ headers: { 'Accept': 'text/xml' } }) ``` -------------------------------- ### Basic AutoRouter Setup Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/api.md Initialize an AutoRouter with default behaviors for handling requests, including parameters, JSON parsing, and error handling. Use this for a batteries-included routing experience. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() router .get('/json', () => ({ foo: 'bar', array: [1,2,3] })) .get('/params/:id', ({ id }) => id) export default router ``` -------------------------------- ### Basic IttyRouter Setup Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/api.md Initialize a basic IttyRouter. This router can be configured with options like a base path for all routes. ```typescript import { IttyRouter } from 'itty-router' const router = IttyRouter() router .get('/', () => 'Hello') export default router ``` -------------------------------- ### Event Patterns Source: https://github.com/kwhitley/itty.dev/blob/main/itty-sockets/api.md Examples of subscribing to different event patterns. ```APIDOC ## Event Patterns ### Standard Events ```ts // Chat messages socket.subscribe('chat', ({ user, message, timestamp }) => { addMessageToUI(user, message, timestamp) }) // User presence socket.subscribe('user-joined', ({ userId, username }) => { showUserJoined(username) }) socket.subscribe('user-left', ({ userId, username }) => { showUserLeft(username) }) ``` ### Real-time Collaboration ```ts // Cursor tracking socket.subscribe('cursor', ({ x, y, userId, color }) => { updateCursor(userId, x, y, color) }) // Document edits socket.subscribe('text-edit', ({ position, text, userId }) => { applyEdit(position, text, userId) }) ``` ### Gaming Events ```ts // Game state updates socket.subscribe('game-move', ({ playerId, move, gameState }) => { updateGameBoard(move, gameState) }) // Player actions socket.subscribe('player-action', ({ action, playerId, data }) => { handlePlayerAction(action, playerId, data) }) ``` ``` -------------------------------- ### AutoRouter Setup Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/migrations/v4-v5.md Initialize an AutoRouter with default behaviors like included withParams, JSON formatting, and a default 404 handler. This simplifies common routing configurations. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() router .get('/params/:id', ({ id }) => `Your id is ${id}.`) // withParams already included .get('/json', () => [1,2,3]) // auto-formatted as JSON .get('/throw', (a) => a.b.c) // safely returns a 500 export default { ...router } // CF Workers or Bun ``` -------------------------------- ### package.json for itty-packager Source: https://context7.com/kwhitley/itty.dev/llms.txt Example package.json configuration for itty-packager, defining module exports. ```json // package.json - itty-packager auto-generates exports { "name": "my-package", "version": "1.0.0", "type": "module", "main": "./dist/index.cjs", "module": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": { "import": "./dist/index.js", "require": "./dist/index.cjs", "types": "./dist/index.d.ts" } } } ``` -------------------------------- ### Basic IttyRouter Setup and Fetch Handling Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/routers/ittyrouter.md Use this snippet to set up a basic IttyRouter with common middleware and define routes for JSON responses, parameter extraction, and a 404 handler. The fetch handler chains `.then(json).catch(error)` for response processing. ```typescript import { IttyRouter, error, json, withParams } from 'itty-router' const router = IttyRouter() router .all('*', withParams) .get('/json', () => ({ foo: 'bar', array: [1,2,3] })) .get('/params/:id', ({ id }) => id) .all('*', () => error(404)) export default { fetch: (request, ...args) => router .fetch(request, ...args) .then(json) .catch(error) } ``` -------------------------------- ### itty-router: Route Pattern Examples Source: https://context7.com/kwhitley/itty.dev/llms.txt Demonstrates various route matching patterns including fixed routes, named parameters, optional parameters, file extensions, wildcards, and greedy parameters for flexible URL handling. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() router // Fixed route .get('/api/status', () => 'OK') // Named parameters .get('/users/:id', ({ id }) => `User ${id}`) // Optional parameters .get('/todos/:id/:action?', ({ id, action }) => action ? `${action} todo ${id}` : `View todo ${id}`) // File extensions .get('/files/:name.:ext', ({ name, ext }) => ({ filename: name, extension: ext })) // Wildcards (non-capturing) .all('/api/*', () => 'API route matched') // Greedy params (captures everything including slashes) .get('/proxy/:url+', ({ url }) => fetch(`https://${url}`)) export default { ...router } ``` -------------------------------- ### CORS Configuration and Usage Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/cors.md Demonstrates how to initialize and use the `cors` function to get `preflight` and `corsify` middleware for handling CORS requests. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new users. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com" } ``` ### 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": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Output Structure for Single File Project Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Example of the output directory structure for a single TypeScript file project after building. ```text dist/ โ”œโ”€โ”€ index.mjs # ESM bundle โ”œโ”€โ”€ index.d.ts # TypeScript declarations โ””โ”€โ”€ index.mjs.map # Source map ``` -------------------------------- ### Router Example with Middleware and Handlers Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/getting-started.md Configure Router with upstream middleware, error catching, and downstream response formatting during initialization. This approach is useful for setting up a consistent request processing pipeline. ```typescript import { Router, json, error, withParams } from 'itty-router' const router = Router({ before: [withParams], // upstream middleware catch: error, // error handling finally: [json], // downstream response formatting }) router .get('/hello/:name', ({ name }) => `Hello, ${name}!`) .get('/json', () => ({ foo: 'bar' })) .get('/throw', (a) => a.b.c) // safely throws export default { ...router } ``` -------------------------------- ### Package.json Exports for Root Release Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Example of `package.json` exports when releasing from the project root, including the output directory prefix. ```json { "exports": { ".": { "import": "./dist/index.mjs", "types": "./dist/index.d.ts" } } } ``` -------------------------------- ### Manual CORS Integration Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/cors.md Provides an example of manually integrating `preflight` and `corsify` without relying on router stages. ```APIDOC ## DELETE /api/users/{id} ### Description Deletes a specific user by their ID. ### Method DELETE ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to delete. ### Response #### Success Response (204) No content is returned upon successful deletion. #### Response Example (No content) ``` -------------------------------- ### Basic CORS Setup with itty-router Source: https://context7.com/kwhitley/itty.dev/llms.txt Sets up basic CORS support allowing all origins. The `preflight` middleware handles OPTIONS requests, and `corsify` adds CORS headers to responses. ```typescript import { AutoRouter, cors } from 'itty-router' // Basic CORS (allows all origins) const { preflight, corsify } = cors() const router = AutoRouter({ before: [preflight], finally: [corsify], }) router.get('/api/data', () => ({ message: 'CORS enabled!' })) export default { ...router } ``` -------------------------------- ### Next.js API Route for Itty Router Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/guides/next.md Use this code in a Next.js API route to intercept requests and pass them to itty-router. Ensure 'itty-router' is installed. This setup handles both GET and POST requests. ```typescript import { AutoRouter, withContent } from 'itty-router' const router = AutoRouter() router .get('/', () => 'Success!') .post('/', withContent, ({ content }) => ({ success: true, postedContent: content, })) export const GET = router.fetch export const POST = router.fetch ``` -------------------------------- ### Basic Router Configuration Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/migrations/v4-v5.md Configure a basic itty-router with custom before, catch, and finally middleware. This setup allows for parameter parsing, error handling, and JSON response formatting. ```typescript import { Router, error, json, withParams } from 'itty-router' const router = Router({ before: [withParams], catch: error, finally: [json], }) router .get('/params/:id', ({ id }) => `Your id is ${id}.`) // withParams already included .get('/json', () => [1,2,3]) // auto-formatted as JSON .get('/throw', (a) => a.b.c) // safely returns a 500 export default { ...router } // CF Workers or Bun ``` -------------------------------- ### Practical Usage of itty-time for Cache TTL Source: https://context7.com/kwhitley/itty.dev/llms.txt Shows a practical example of using itty-time functions to define cache time-to-live (TTL) and other time-based constants. ```typescript // Practical usage: Cache TTL const CACHE_TTL = ms('24 hours') const sessionExpiry = datePlus('30 minutes') const tokenRefresh = seconds('15 minutes') ``` -------------------------------- ### Native Fetch API POST request Source: https://github.com/kwhitley/itty.dev/blob/main/itty-fetcher/index.md This example demonstrates the equivalent POST request using the native Fetch API, highlighting the additional boilerplate required for method, headers, body stringification, and response handling. ```typescript const newUser = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Alice' }) }).then(response => { if (!response.ok) throw new Error(`${response.status}: ${response.statusText}`) return response.json() }) ``` -------------------------------- ### itty-router: IttyRouter Minimal Setup Source: https://context7.com/kwhitley/itty.dev/llms.txt Use IttyRouter for maximum control with a minimal footprint. Manual response formatting and error handling are applied via Promise chain after the router fetches. ```typescript import { IttyRouter, json, error, withParams } from 'itty-router' const router = IttyRouter() router .all('*', withParams) // global middleware .get('/users/:id', ({ id }) => ({ id })) .get('/data', () => [1, 2, 3]) export default { fetch: (request, ...args) => router .fetch(request, ...args) .then(json) // format responses as JSON .catch(error) // catch and format errors } ``` -------------------------------- ### Basic Cloudflare Worker with AutoRouter Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/guides/cloudflare-workers.md This snippet demonstrates the basic setup for a Cloudflare Worker using itty-router's AutoRouter. It imports the necessary component and defines a simple GET route for the root path. The router is then exported as the default export, which Cloudflare Workers uses to handle incoming requests. ```javascript import { AutoRouter } from 'itty-router' const router = AutoRouter() router.get('/', () => 'Success!') export default { ...router } // strips the proxy before returningw ``` -------------------------------- ### Run Basic Prepare Sequence Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Execute the default lint, test, and build sequence for package validation. ```bash itty prepare # Run lint โ†’ test โ†’ build ``` -------------------------------- ### Run Prepare Sequence with Verbose Output Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/prepare.md Execute the prepare sequence and display detailed output from each command. ```bash itty prepare --verbose # Show detailed output ``` -------------------------------- ### Register GET and JSON routes Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/getting-started.md Define routes for HTTP GET requests, including dynamic route parameters and JSON responses. Route definitions are chainable. ```typescript // assumes router instance (above) router .get('/hello/:name', ({ params }) => `Hello, ${params.name}!`) .get('/json', () => ({ foo: 'bar' })) ``` -------------------------------- ### Run Pre-release Sequence with itty-packager Source: https://context7.com/kwhitley/itty.dev/llms.txt Command to execute the full pre-release sequence, including linting, testing, and building. Supports verbose output. ```bash # Run full pre-release sequence (lint + test + build) ity prepare ity prepare --verbose # With detailed output ``` -------------------------------- ### Debug Logging Setup Source: https://github.com/kwhitley/itty.dev/blob/main/itty-chroma/examples.md Define distinct styles for debug, error, and success messages using chroma. This setup is useful for consistent logging across an application. ```typescript const debug = chroma.cyan.italic const error = chroma.red.bold const success = chroma.green.bold debug.log('Debug: Processing user data...') success.log('Success: User created successfully') error.log('Error: Validation failed') ``` -------------------------------- ### Beta Release with Tagging Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/release.md Create a pre-release version of type 'beta' and tag it. This is useful for testing upcoming features before a stable release. ```bash itty release --type=beta --tag ``` -------------------------------- ### TypeScript Support Source: https://github.com/kwhitley/itty.dev/blob/main/itty-sockets/api.md Examples of using IttySocket with TypeScript for type safety. ```APIDOC ## TypeScript Support ```ts interface ChatMessage { user: string message: string timestamp: number } interface CursorPosition { x: number y: number userId: string color: string } // Type-safe usage socket.subscribe('chat', (data: ChatMessage) => { // data is properly typed }) socket.send('cursor', { x: 100, y: 200, userId: 'user123', color: '#ff0000' } as CursorPosition) ``` ``` -------------------------------- ### Build Static Site for Production with Bun Source: https://github.com/kwhitley/itty.dev/blob/main/CLAUDE.md Builds the static site for production deployment. This command is an alias for 'npm run build'. ```bash bun run build ``` -------------------------------- ### Preview Production Build Locally with Bun Source: https://github.com/kwhitley/itty.dev/blob/main/CLAUDE.md Previews the production build locally before deployment. This command is an alias for 'npm run preview'. ```bash bun run preview ``` -------------------------------- ### Create a Router instance Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/getting-started.md Instantiate a basic Router for more control over configuration and middleware. ```typescript import { Router } from 'itty-router' const router = Router() ``` -------------------------------- ### Using preflight Middleware Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/cors.md Shows how to integrate the `preflight` middleware into your router, either using stages with `AutoRouter` or manually. ```APIDOC ## GET /api/users/{id} ### Description Retrieves the details of a specific user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to retrieve. #### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Basic WebSocket Connection and Subscription with itty-sockets Source: https://context7.com/kwhitley/itty.dev/llms.txt Demonstrates how to create a WebSocket connection, subscribe to channels, and receive messages. Imports are required. ```typescript import { IttySocket } from 'itty-sockets' // Create socket connection const socket = new IttySocket('my-channel') // Subscribe to events const unsubscribe = socket.subscribe('chat', (data) => { console.log(`${data.user}: ${data.message}`) }) ``` -------------------------------- ### Create New Release with Bun Source: https://github.com/kwhitley/itty.dev/blob/main/CLAUDE.md Automates the creation of a new release by performing a patch version bump. ```bash bun run release ``` -------------------------------- ### Prepare and Release Package Source: https://context7.com/kwhitley/itty.dev/llms.txt Commands to prepare and release a package using itty. ```bash itty prepare && itty release --minor ``` -------------------------------- ### Log Message with Chroma Source: https://github.com/kwhitley/itty.dev/blob/main/itty-chroma/index.md Use chroma.log to output messages to the browser console. This is a basic example of how to use the logging functionality. ```javascript chroma.log('hello') ``` -------------------------------- ### Complete Release Workflow Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/release.md Execute the full release process, including preparing the release, incrementing the version (minor), tagging the release, and pushing changes to the repository. ```bash itty release --prepare --minor --tag --push ``` -------------------------------- ### Get Style Array for Manual Use Source: https://github.com/kwhitley/itty.dev/blob/main/itty-chroma/api.md Retrieve the style array generated by chained methods for manual application in console logging. ```typescript // Get style array for manual use const styleArray = chroma.red.bold.style() console.log('%cHello', ...styleArray) ``` -------------------------------- ### Basic itty build Usage Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Run the build command to compile TypeScript files from `src/` to `dist/`. Use flags for minification, hybrid output, or custom directories. ```bash itty build # Build from src/ to dist/ itty build --minify # Build with minification itty build --hybrid # Build both ESM and CJS itty build --from=lib --out=build # Custom directories ``` -------------------------------- ### Using corsify Response Handler Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/cors.md Illustrates how to apply the `corsify` response handler to add CORS headers to responses, with examples for different router configurations. ```APIDOC ## PUT /api/users/{id} ### Description Updates the details of an existing user. ### Method PUT ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to update. #### Request Body - **username** (string) - Optional - The updated username. - **email** (string) - Optional - The updated email address. ### Request Example ```json { "email": "john.doe.updated@example.com" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **username** (string) - The updated username of the user. - **email** (string) - The updated email address of the user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe.updated@example.com" } ``` ``` -------------------------------- ### Package Structure Before and After Release Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/release.md Illustrates the transformation of the package structure from the repository's `dist/` directory to a flat structure on npm after a release. ```text dist/ โ”œโ”€โ”€ index.mjs โ”œโ”€โ”€ index.d.ts โ””โ”€โ”€ utils.mjs package.json (exports: "./index.mjs") README.md LICENSE ``` ```text index.mjs index.d.ts utils.mjs package.json (exports: "./index.mjs") README.md LICENSE ``` -------------------------------- ### Fetcher and Method Call Options Source: https://github.com/kwhitley/itty.dev/blob/main/itty-fetcher/configuration.md Demonstrates how configuration options can be applied at the fetcher level or per method call. Method-level options override base options. ```typescript const api = fetcher(url?, options?) api.post(url?, payload?, options?) const api = fetcher('https://api.com', { headers: { 'Auth': 'token' } }) await api.get('/users', { headers: { 'Accept': 'text/xml' } }) ``` -------------------------------- ### Add Duration to a Date Source: https://github.com/kwhitley/itty.dev/blob/main/itty-time/index.md Use `datePlus` to add a string duration to a given date. If no starting date is provided, it defaults to the current date and time. ```javascript import { datePlus } from 'itty-time' // from right now datePlus('2 months') // or from a different date datePlus('2 months', datePlus('1 week')) ``` -------------------------------- ### Performance Monitoring Logs Source: https://github.com/kwhitley/itty.dev/blob/main/itty-chroma/examples.md Use distinct styles for start and end markers in performance monitoring logs. This helps visually track the duration of operations. ```typescript const perfStart = chroma.blue.bold const perfEnd = chroma.green.bold perfStart.log('๐Ÿ Starting operation...') // ... your code ... perfEnd.log('โœ… Operation completed in 125ms') ``` -------------------------------- ### Configure Router with catch and finally stages Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/getting-started.md Initialize a Router with custom error catching and response transformation functions for centralized handling. ```typescript import { Router, error, json } from 'itty-router' // add transformers to Router stages const router = Router({ catch: error, finally: [json], }) // catches errors and responds as JSON await router.fetch(request) ``` -------------------------------- ### One-Line Fetch Request Source: https://github.com/kwhitley/itty.dev/blob/main/itty-fetcher/getting-started.md Perform a simple GET request to a specified URL using the fetcher. Optionally, you can provide a TypeScript type for the expected response. ```typescript const items = await fetcher().get('https://example.com/api/items') // or typed... const items = await fetcher() .get('https://example.com/api/items') ``` -------------------------------- ### itty-router Middleware Examples Source: https://context7.com/kwhitley/itty.dev/llms.txt Illustrates the use of built-in middleware for parsing request content, cookies, and route parameters. Middleware can be applied globally or to specific routes. ```typescript import { Router, withParams, withContent, withCookies, json, error } from 'itty-router' const router = Router({ before: [withParams], // global: extract params to request catch: error, finally: [json], }) router // withParams extracts route params to request object .get('/users/:id', ({ id }) => ({ userId: id })) // withContent parses request body (JSON, FormData, or text) .post('/users', withContent, async ({ content }) => { // content is automatically parsed return { created: true, user: content } }) // withCookies extracts cookies from headers .get('/profile', withCookies, ({ cookies }) => { if (!cookies.sessionId) { return error(401, 'Not authenticated') } return { session: cookies.sessionId } }) export default { ...router } // POST /users with body {"name":"Alice"} // => {"created":true,"user":{"name":"Alice"}} // GET /profile with Cookie: sessionId=abc123 // => {"session":"abc123"} ``` -------------------------------- ### AutoRouter Example Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/getting-started.md Use AutoRouter for a built-in, streamlined approach to API creation. It handles common patterns like JSON formatting and error catching automatically. ```typescript import { AutoRouter } from 'itty-router' const router = AutoRouter() router .get('/hello/:name', ({ name }) => `Hello, ${name}!`) .get('/json', () => ({ foo: 'bar' })) .get('/throw', (a) => a.b.c) // safely throws export default { ...router } ``` -------------------------------- ### Use Sync and Async Middleware Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/middleware/index.md itty-router supports both synchronous and asynchronous middleware functions seamlessly. This example demonstrates using both types before a final route handler. ```js // sync middleware const withSyncData = (request) => { request.foo = 'bar' } // async middleware const withAsyncData = async (request) => { request.items = await db.getItems() } // and to use... router.get('/test', withSyncData, withAsyncData, ({ foo, items }) => `foo is ${foo} and you have ${items.length} items` ) ``` -------------------------------- ### Configure Bun Server Port with itty-router Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/guides/bun.md Use itty-router's options to control server configuration like the port. This example sets the port to 3001. ```javascript import { AutoRouter } from 'itty-router' const router = AutoRouter({ port: 3001 }) router.get('/', () => 'Success!') export default { ...router } // strips the proxy before returning ``` -------------------------------- ### Core Functionality Source: https://github.com/kwhitley/itty.dev/blob/main/itty-chroma/api.md The `chroma` object is the main entry point for styling console output. It provides chainable methods for applying various styles. ```APIDOC ## Core Functionality ### `chroma` The main styling proxy that provides chainable methods for console styling. ```ts import { chroma } from 'itty-chroma' ``` ``` -------------------------------- ### Initialize CORS Middleware with AutoRouter Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/cors.md Get the `preflight` and `corsify` pair from the `cors` function and add `preflight` to the router's `before` stage and `corsify` to the `finally` stage. ```typescript import { AutoRouter, cors } from 'itty-router' // get preflight and corsify pair const { preflight, corsify } = cors() const router = AutoRouter({ before: [preflight], // add preflight upstream finally: [corsify], // and corsify downstream }) router.get('/', () => 'Hello World!') export default router ``` -------------------------------- ### Public Channels with Demo API Key Source: https://github.com/kwhitley/itty.dev/blob/main/itty-sockets/channels.md Use the 'demo' API key to create public channels accessible to anyone. Ideal for prototyping and open collaboration. ```typescript // Anyone can join this channel const publicSocket = new IttySocket('public-chat') // or explicitly with demo key const publicSocket = new IttySocket('public-chat', { apiKey: 'demo' }) ``` -------------------------------- ### Recommended TypeScript Configuration Source: https://github.com/kwhitley/itty.dev/blob/main/itty-packager/build.md Recommended `tsconfig.json` settings for use with the `itty build` command. ```json { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "node", "declaration": true, "outDir": "./dist", "strict": true }, "include": ["src/**/*"] } ``` -------------------------------- ### Simple Color Logging with itty-chroma Source: https://context7.com/kwhitley/itty.dev/llms.txt Demonstrates basic color and style application to console logs using the itty-chroma library. Imports are required. ```typescript import { chroma } from 'itty-chroma' // Simple color logging chroma.red.log('Error message') chroma.green.log('Success!') chroma.blue.bold.log('Important info') ``` ```typescript // Compose multiple styles chroma.log( chroma.green.bold, 'Success:', chroma.none, // reset styles 'Operation completed', chroma.blue.italic, '(3 items processed)' ) ``` ```typescript // Use any CSS color name chroma.salmon.log('Salmon colored text') chroma.cornflowerblue.bold.log('Cornflower blue and bold') ``` -------------------------------- ### Advanced AutoRouter Configuration Source: https://github.com/kwhitley/itty.dev/blob/main/itty-router/migrations/v4-v5.md Configure AutoRouter with custom port, before middleware, a custom 404 handler, and finally middleware for logging. This example demonstrates fine-grained control over router behavior. ```javascript import { AutoRouter, error } from 'itty-router' // upstream middleware to embed a start time const withBenchmarking = (request) => { request.start = Date.now() } // downstream handler to log it all out const logger = (res, req) => { console.log(res.status, req.url, Date.now() - req.start, 'ms') } // now let's create the router const router = AutoRouter({ port: 3001, before: [withBenchmarking], missing: () => error(404, 'Custom 404 message.'), finally: [logger], }) router.get('/', () => 'Success!') export default { ...router } // Bun server on port 3001 ``` -------------------------------- ### Using Native RequestInit Options Source: https://github.com/kwhitley/itty.dev/blob/main/itty-fetcher/configuration.md Pass standard `RequestInit` options directly to the fetcher configuration for controlling caching, credentials, mode, redirects, referrer policy, and AbortController signals. ```typescript const api = fetcher({ // Standard fetch options cache: 'no-cache', credentials: 'include', mode: 'cors', redirect: 'follow', referrerPolicy: 'no-referrer', // AbortController support signal: abortController.signal }) ```