Skip to content

Patterns

The patterns the packages share. Following them in application code keeps a service testable and movable between runtimes.

The packages share a small set of patterns. Following them in application code keeps a service testable and movable between runtimes.

A package asks for the methods it calls, such as { limit({ key }) } or { match, put }, never for a vendor’s type. A platform binding, an in-memory implementation and a test double are all adapters for the same port. Everything vendor-specific lives in @edgetime/cloudflare; the other packages name no platform.

Routes live in a module with no platform imports and read their dependencies from env and the context. One entry file per runtime builds those dependencies. The repository’s examples do it from Cloudflare bindings in one and from in-process implementations in the other, around the same routes. See Deploy on Workers.

provide() registers factories for per-request values and perEnv() memoizes per-environment ones. Handlers read them with c.get() and never construct them, so a test swaps a factory instead of a handler.

Cross-cutting behaviour is a function around next(). compose() joins middleware into reusable stacks, mount() joins routers and extend() installs a packaged feature.

Anything with settings is made by a function that validates them once and returns a closure: createJwtVerifier(), createSessionCodec(), createLogger(). A bad setting stops start-up instead of failing requests.

A handler throws an HttpError and one error handler renders it. Operations whose failure is an expected outcome return a value instead: unseal() returns undefined, and verifyTurnstile() returns a result with a reason.

Redundancy and other per-deployment behaviour is switched by a flag in a list of steps (flag(...) && step), not by branching through the code.

import { flag } from '@edgetime/config';
import { firstAvailable, writeAll } from '@edgetime/resilience';
const replica = flag(env.REPLICA_ENABLED) ? env.FILES_REPLICA : undefined;
await writeAll([() => primary.put(key, bytes), replica && (() => replica.put(key, bytes))]);
const object = await firstAvailable([() => primary.get(key), replica && (() => replica.get(key))]);

Nothing request-scoped lives at module level, and imports have no side effects, so every entry point tree-shakes.