# Middleware API
URL: /docs/api/middleware



Middleware API [#middleware-api]

Use the middleware API when extending kernel behavior with caching, coordinate transforms, or geometry post-processing. Middleware wraps kernel operations in an onion-model pipeline.

Types [#types]

<TypeTable
  type={{
  "name": "MiddlewareState",
  "description": "Type-safe state for middleware to persist data during an operation.\n\nThe state is scoped to a single middleware and persists for the duration of\none operation (e.g., one createGeometry call). In wrap-style hooks, state\ncan be updated before calling handler() and read after it returns.",
  "entries": [
    {
      "name": "value",
      "description": "Current state value.\nType is PartialDeep<T> since update() may be called with partial data\nor not called at all.",
      "tags": [],
      "type": "PartialDeep<T>",
      "simplifiedType": "PartialDeep<T>",
      "required": true,
      "deprecated": false
    },
    {
      "name": "update",
      "description": "Update the state with partial data.\nValues are validated against the Zod schema before being merged.",
      "tags": [
        {
          "name": "param",
          "text": "partial - Partial data to merge into the state"
        }
      ],
      "type": "(partial: Partial<T>) => void",
      "simplifiedType": "function",
      "required": true,
      "deprecated": false
    }
  ]
}}
/>

<TypeTable
  type={{
  "name": "KernelMiddlewareRuntime",
  "description": "Runtime context provided to middleware wrap hooks.\nContains services and utilities available during hook execution.",
  "entries": [
    {
      "name": "logger",
      "description": "Logger with middleware name pre-configured as the component",
      "tags": [],
      "type": "RuntimeLogger",
      "simplifiedType": "RuntimeLogger",
      "required": true,
      "deprecated": false
    },
    {
      "name": "filesystem",
      "description": "Filesystem for all file operations (uses absolute path methods for middleware)",
      "tags": [],
      "type": "RuntimeFileSystem",
      "simplifiedType": "RuntimeFileSystem",
      "required": true,
      "deprecated": false
    },
    {
      "name": "state",
      "description": "Type-safe state for persisting data during the wrap hook execution",
      "tags": [],
      "type": "MiddlewareState<State>",
      "simplifiedType": "MiddlewareState<State>",
      "required": true,
      "deprecated": false
    },
    {
      "name": "options",
      "description": "Resolved options (optionsSchema defaults merged with caller overrides)",
      "tags": [],
      "type": "Options",
      "simplifiedType": "Options",
      "required": true,
      "deprecated": false
    },
    {
      "name": "dependencies",
      "description": "Dependencies for cache key computation.\nIncludes file dependencies (source files, fonts), middleware signatures,\nframework version, and kernel options.",
      "tags": [],
      "type": "readonly Dependency[]",
      "simplifiedType": "array",
      "required": true,
      "deprecated": false
    },
    {
      "name": "dependencyHash",
      "description": "Pre-computed SHA-256 hash of all dependencies.\nCan be used as a cache key or unique geometry identifier.\nThis is a 64-character hex string.",
      "tags": [],
      "type": "string",
      "simplifiedType": "string",
      "required": true,
      "deprecated": false
    },
    {
      "name": "registerWatchPath",
      "description": "Register a file path for the kernel's watch set with an optional debounce tier.\nPaths registered here are included in the kernel's filesystem watcher.\nThe debounce tier controls how quickly changes to this path trigger a re-render\n(e.g., 50ms for parameter files vs 500ms default for source code).\n\nIdempotent — re-registering the same path updates the debounce value.",
      "tags": [
        {
          "name": "param",
          "text": "absolutePath - Absolute filesystem path to watch"
        },
        {
          "name": "param",
          "text": "options - Optional configuration with debounceMs override"
        }
      ],
      "type": "(absolutePath: string, options?: { debounceMs?: number; }) => void",
      "simplifiedType": "function",
      "required": true,
      "deprecated": false
    }
  ]
}}
/>

<TypeTable
  type={{
  "name": "MiddlewarePlugin",
  "description": "Registration object for a middleware plugin. Returned by factory functions like `parameterCache()`.",
  "entries": [
    {
      "name": "id",
      "description": "Unique identifier for this middleware",
      "tags": [],
      "type": "string",
      "simplifiedType": "string",
      "required": true,
      "deprecated": false
    },
    {
      "name": "moduleUrl",
      "description": "URL of the middleware module",
      "tags": [],
      "type": "string",
      "simplifiedType": "string",
      "required": true,
      "deprecated": false
    },
    {
      "name": "options",
      "description": "Middleware-specific options",
      "tags": [],
      "type": "Record<string, unknown> | undefined",
      "simplifiedType": "Record<string, unknown>",
      "required": false,
      "deprecated": false
    }
  ]
}}
/>

defineMiddleware [#definemiddleware]

`defineMiddleware` creates a middleware instance from a configuration object. Provide optional wrap hooks: `wrapGetParameters`, `wrapCreateGeometry`, `wrapExportGeometry`. Each hook receives `(input, handler, runtime)` where `runtime` is `KernelMiddlewareRuntime`.

Built-in Factories [#built-in-factories]

| Factory                     | Purpose                                           |
| --------------------------- | ------------------------------------------------- |
| `parameterCache()`          | Cache parameter definitions by dependency hash    |
| `geometryCache()`           | Cache geometry output by dependency hash          |
| `gltfCoordinateTransform()` | Apply coordinate system transforms to glTF output |
| `gltfEdgeDetection()`       | Add edge geometry to glTF meshes                  |

Usage [#usage]

```typescript
import { createRuntimeClient, fromMemoryFS } from '@taucad/runtime';
import { replicad } from '@taucad/runtime/kernels';
import { esbuild } from '@taucad/runtime/bundler';
import { parameterCache, geometryCache, gltfCoordinateTransform, gltfEdgeDetection } from '@taucad/runtime/middleware';

const client = createRuntimeClient({
  kernels: [replicad()],
  bundlers: [esbuild()],
  fileSystem: fromMemoryFS(),
  middleware: [parameterCache(), geometryCache(), gltfCoordinateTransform(), gltfEdgeDetection()],
});
```

Related [#related]

* [Use Middleware](../guides/using-middleware)
* [Create Custom Middleware](../guides/custom-middleware)
* [Middleware Model](../concepts/middleware-model)
