Skip to content

API Reference

Quick reference of all exported functions, types, and classes per package.

Export Kind Description
Result<T,E> type Discriminated union: { ok: true, value: T } or { ok: false, error: E }
AsyncResult<T,E> type Promise<Result<T,E>>
Ok(value) function Create a success Result
Err(error) function Create an error Result
isOk(result) function Type guard for success
isErr(result) function Type guard for error
unwrap(result) function Extract value or throw
Branded<T, Brand> type Nominal typing helper
brand(value, tag) function Brand a value
kvKey(value) function Brand as KVKey
d1RowId(value) function Brand as D1RowId
r2ObjectKey(value) function Brand as R2ObjectKey
durableObjectId(value) function Brand as DurableObjectId
queueMessageId(value) function Brand as QueueMessageId
TypedKVNamespace<T> type Typed KV binding augmentation
TypedD1Result<T> type Typed D1 query result
TypedR2Object type Typed R2 object
TypedQueue<T> type Typed queue binding
TypedMessageBatch<T> type Typed message batch
TypedDurableObjectStorage type Typed DO storage
JsonValue, JsonObject, JsonArray types JSON-safe types
DeepPartial<T>, DeepReadonly<T> types Recursive utility types
WorkerFetchHandler type fetch() handler signature
WorkerScheduledHandler type scheduled() handler signature
WorkerQueueHandler type queue() handler signature
WorkerModule type Full worker module export
ExecutionContext type Worker execution context
ScheduledEvent type Cron trigger event
MaybePromise<T> type `T
Prettify<T> type Flatten intersection types
assertNever(x) function Exhaustive switch helper
Export Kind Description
WorkkitError abstract class Base error with code, statusCode, retryable, retryStrategy
NotFoundError class 404, not retryable
ConflictError class 409, retryable (exponential)
ValidationError class 400, not retryable, carries issues[]
UnauthorizedError class 401, not retryable
ForbiddenError class 403, not retryable
TimeoutError class 504, retryable (exponential)
RateLimitError class 429, retryable (fixed)
ServiceUnavailableError class 503, retryable (exponential)
BindingError class 500, not retryable
BindingNotFoundError class 500, not retryable
InternalError class 500, not retryable
ConfigError class 500, not retryable
RetryStrategies object Factory for retry strategies: .none(), .immediate(), .fixed(), .exponential()
getRetryDelay(strategy, attempt) function Calculate delay for attempt, returns `number
isRetryable(error) function Type guard: is error retryable?
getRetryStrategy(error) function Extract retry strategy from any error
errorToResponse(error) function Convert WorkkitError to HTTP Response
fromHttpStatus(status, msg?) function Create WorkkitError from HTTP status code
isWorkkitError(error) function Type guard for WorkkitError
isErrorCode(error, code) function Type guard for specific error code
serializeError(error) function Serialize any error to structured JSON
wrapError(error, msg?) function Wrap unknown error as WorkkitError
Export Kind Description
parseEnv(rawEnv, schema) async function Validate env (async validators)
parseEnvSync(rawEnv, schema) function Validate env (sync only, throws on async)
createEnvParser(schema) function Create reusable parser with .parse() and .parseSync()
EnvValidationError class Error with .issues: EnvIssue[]
isStandardSchema(value) function Type guard for Standard Schema objects
detectPlatform() function Returns `‘workerd’
resolveEnv() function Get env from current platform
EnvSchema type Record<string, StandardSchemaV1>
InferEnv<T> type Infer output types from schema
InferRawEnv<T> type Infer input types from schema
Export Kind Description
d1() function D1Database binding validator
kv() function KVNamespace binding validator
r2() function R2Bucket binding validator
queue() function Queue binding validator
ai() function AI binding validator
durableObject() function DurableObjectNamespace binding validator
service() function Service binding validator
Export Kind Description
d1(binding, options?) function Create typed D1 client
D1Error class Base D1 error
D1QueryError class SQL query error
D1ConstraintError class Constraint violation (409)
D1BatchError class Batch operation error
D1MigrationError class Migration error
classifyD1Error(error, sql?, params?) function Classify raw D1 errors
snakeToCamel(column) function Column name transformer
migrate(db, migrations, options?) function Run pending migrations
migrationStatus(db, migrations, options?) function Check migration status
Method Returns Description
.first<T>(sql, params?) Promise<T | null> Single row query
.all<T>(sql, params?) Promise<T[]> Multi-row query
.run(sql, params?) Promise<D1RunResult> Mutation (INSERT/UPDATE/DELETE)
.exec(sql) Promise<D1ExecResult> Raw SQL execution
.prepare<T>(sql, params?) TypedPreparedStatement<T> Create prepared statement
.batch(statements) Promise<D1BatchResult[]> Atomic batch execution
.select<T>(table) SelectBuilder<T> Fluent SELECT builder
.insert(table) InsertBuilder Fluent INSERT builder
.update(table) UpdateBuilder Fluent UPDATE builder
.delete(table) DeleteBuilder Fluent DELETE builder
.raw D1Database Underlying binding
Export Kind Description
kv<T>(binding, options?) function Create typed KV client
validateKey(key) function Validate KV key
prefixKey(prefix, key) function Prepend prefix to key
stripPrefix(prefix, key) function Remove prefix from key
wrapKVError(error, context) function Wrap KV errors with context
assertKVBinding(binding) function Assert binding exists
assertValidTtl(ttl) function Assert TTL >= 60
Method Returns Description
.get(key, options?) Promise<T | null> Get value
.getWithMetadata<M>(key, options?) Promise<{value, metadata, cacheStatus}> Get with metadata
.put(key, value, options?) Promise<void> Store value
.delete(key) Promise<void> Delete key
.getMany(keys, options?) Promise<Map<string, T>> Batch get
.putMany(entries, options?) Promise<void> Batch put
.deleteMany(keys) Promise<void> Batch delete
.list<M>(options?) AsyncIterable<KVListEntry<M>> List keys (auto-paginate)
.listKeys(options?) Promise<KVListEntry[]> Collect all keys
.has(key) Promise<boolean> Check key existence
.raw KVNamespace Underlying binding
Export Kind Description
signJWT(payload, options) async function Sign a JWT token
verifyJWT(token, options) async function Verify and decode JWT
decodeJWT(token) function Decode JWT without verification
parseDuration(str) function Parse ‘1h’, ‘30m’, ‘7d’ to seconds
hashPassword(password, options?) async function PBKDF2 password hashing
verifyPassword(password, stored) async function Constant-time password verification
createSessionManager(config) function KV-backed session manager
createAuthHandler(config) function Auth middleware factory
extractBearerToken(request) function Extract Bearer token from header
extractBasicAuth(request) function Extract Basic auth credentials
Export Kind Description
fixedWindow(options) function Fixed window rate limiter
slidingWindow(options) function Sliding window rate limiter
tokenBucket(options) function Token bucket rate limiter
composite(limiters) function Combine multiple limiters
parseDuration(str) function Parse duration to milliseconds
rateLimitHeaders(result) function Generate X-RateLimit-* headers
rateLimitResponse(result, msg?) function Generate 429 Response
Export Kind Description
ai(binding) function Create typed AI client
streamAI(binding, model, input, options?) async function Stream text generation
fallback(binding, models, inputs, options?) async function Try models in order
withRetry(fn, options?) async function Retry wrapper
estimateTokens(text) function Approximate token count
Export Kind Description
createGateway(config) function Multi-provider AI gateway
createRouter(config) function Model-to-provider router
createCostTracker(config) function Token usage and cost tracker
withCache(gateway, config) function Cache wrapper for gateway
withLogging(gateway, config) function Logging wrapper for gateway
Export Kind Description
queue<T>(binding) function Create typed queue producer
createConsumer<T>(options) function Per-message consumer handler
createBatchConsumer<T>(options) function Batch consumer handler
createDLQProcessor<T>(options) function Dead letter queue processor
RetryAction enum ACK, RETRY, DEAD_LETTER
Export Kind Description
createCronHandler(options) function Route scheduled events to tasks
matchCron(schedule, cron) function Check if cron matches
parseCron(expression) function Parse cron expression
describeCron(expression) function Human-readable description
nextRun(expression) function Next scheduled Date
isValidCron(expression) function Validate cron expression
withTimeout(ms) function Timeout middleware
withRetry(maxRetries, options?) function Retry middleware
withErrorReporting(getQueue, reporter?) function Error reporting middleware
withLock(getKV, key, options, handler) function Distributed lock wrapper
acquireLock(kv, key, options?) function Acquire a KV-based lock
Export Kind Description
typedStorage<T>(raw) function Type-safe DO storage wrapper
createStateMachine(config) function Finite state machine for DOs
scheduleAlarm(storage, schedule) async function Schedule a DO alarm
createAlarmHandler(config) function Route alarms to named handlers
parseDuration(str) function Parse duration to milliseconds
createDOClient<T>(namespace, id) function Typed RPC client for DO stubs
singleton(namespace, name) function Get named DO instance
Export Kind Description
createLogger(options?) function Create a standalone structured logger
logger(options?) function Hono middleware for structured request logging
getLogger(c) function Get a logger from Hono context with request context
getRequestContext() function Get current request context from AsyncLocalStorage
LogLevel type "debug" | "info" | "warn" | "error"
LogFields type Record<string, unknown>
LogEntry type Structured log entry with level, msg, ts, and fields
Logger type Logger interface with .debug(), .info(), .warn(), .error(), .child()
CreateLoggerOptions type Options for createLogger
LoggerMiddlewareOptions type Options for logger middleware
RequestContext type Request context: requestId, method, path, startTime, fields
Export Kind Description
createTestEnv(config) function One-call typed env factory
createMockKV() function In-memory KVNamespace mock
createMockD1() function In-memory D1Database mock
createFailingD1() function Always-failing D1 mock
createMockR2() function In-memory R2Bucket mock
createMockQueue() function In-memory Queue mock
createMockDO() function In-memory DO storage mock
createRequest(path, options?) function Request factory
createExecutionContext() function Mock ExecutionContext
Export Kind Description
r2(bucket, options?) function Typed R2 client wrapper
createPresignedUrl(bucket, options) function Generate presigned PUT/GET URLs
multipartUpload(bucket, key, options?) function Start a multipart upload session
streamToBuffer(stream) / streamToText(stream) / streamToJson<T>(stream) function Body stream helpers
fromS3Key(key) / toS3Key(key) function S3 ↔ R2 key migration helpers
validateR2Key(key) / assertR2Binding(b) / wrapR2Error(err, ctx) function Defensive helpers
Export Kind Description
cache(kv, options?) function Typed KV-backed cache client
swr(kv, key, fetcher, options?) function Stale-while-revalidate read-through
cacheAside(kv, options?) function Cache-aside pattern helper
taggedCache(kv, options?) function Tagged invalidation client
createMemoryCache(options?) function In-process LRU cache
buildCacheUrl(key) function Compose cache key URL
Export Kind Description
encrypt(key, data) / decrypt(key, ciphertext) function AES-256-GCM encrypt / decrypt
encryptWithAAD(key, data, aad) / decryptWithAAD(key, ciphertext, aad) function AES-GCM with additional authenticated data
generateKey() / exportKey(key) / importKey(base64) function AES-256-GCM key lifecycle
deriveKey(source, context) function PBKDF2 (string) or HKDF (CryptoKey) key derivation
envelope.seal / open / rotate object Envelope encryption (DEK + master key)
hash(algo, data) function SHA-1 / SHA-256 / SHA-384 / SHA-512
hmac(secret, data) / hmac.verify(secret, data, mac) function HMAC sign + constant-time verify
generateSigningKeyPair(algo?) function Ed25519 (default) or ECDSA keypair
exportSigningKey(key) / importSigningKey(base64, type, algo?) function Public/private signing key serialization
sign(privateKey, data) / sign.verify(publicKey, data, signature) function Detached signature + verify
randomBytes(n) / randomHex(n) / randomUUID() function Crypto-secure random
Export Kind Description
api(config) function Define a typed API surface
createRouter(config) function Build a router from API definitions
generateOpenAPI(api) function Build OpenAPI 3.1 spec from definitions
parsePath / matchPath / buildPath / toOpenAPIPath / parseQuery function Path utilities
validate / validateSync / tryValidate / isStandardSchema function Standard Schema validation helpers
createLlmsRoutes / generateLlmsTxt / generateLlmsFullTxt function llms.txt generation
Export Kind Description
createHealthCheck(probes, options?) function Compose probes into a HealthChecker
healthHandler(probes, options?) function Hono-style /health handler
kvProbe(kv) / d1Probe(db) / r2Probe(bucket) / doProbe(ns) / aiProbe(ai) / queueProbe(q) function Built-in binding probes
Export Kind Description
verifyTurnstile(token, secret, options?) function Server-side CAPTCHA verification
turnstile(options) function Hono middleware that gates handlers on a valid token
Export Kind Description
createFlags(kv, options?) function KV-backed feature flag client
evaluate(flag, context) function Evaluate a flag against a user context (rollout %, targeting)
Export Kind Description
mail(binding, options?) function Typed email send client over SendEmail binding
parseEmail(raw) function Parse Email Routing inbound message
createEmailHandler(opts) function Build an inbound email handler
createEmailRouter(routes) function Route inbound emails to handlers
composeMessage(opts) function Compose a MailMessage from address/subject/body parts
validateAddress(addr) / isValidAddress(addr) function Address validation helpers
MailError / InvalidAddressError / DeliveryError class Domain errors
Export Kind Description
createChatTransport(env, options?) function WebSocket transport factory
ChatSessionDO DO class Re-exportable Durable Object for chat sessions
ChatMessage type Discriminated union of typed chat events
Export Kind Description
define(spec, options) function Define a typed notification with channel rendering
createNotifyConsumer(adapters) function Queue consumer that dispatches via adapters
ALL_MIGRATIONS const D1 schema for core (preferences, opt-out, records)

Subpath imports: @workkit/notify/email, @workkit/notify/inapp, @workkit/notify/whatsapp — each ships an *_MIGRATION_SQL plus an *Adapter factory.

Export Kind Description
browser(binding, options?) function Acquire a Browser Rendering session
withPage(session, fn, options?) function Run fn(page) with guaranteed cleanup
loadFonts(page, fonts, options?) function Inject @font-face declarations safely
Export Kind Description
renderPdf(session, html, options?) function Render HTML to PDF with header/footer presets
storePdf(bucket, key, bytes, options?) function Store rendered PDF in R2
presignPdf(bucket, key, options) function Generate a presigned download URL
presets object Page-size and margin presets
raw(html) function Mark a string as already-escaped HTML
Export Kind Description
tool(spec) function Define a Standard-Schema-validated tool
defineAgent(spec) function Compose a multi-turn agent loop
handoff(target, options?) function Synthetic tool that hands off to another agent
AgentEvent type Discriminated union streamed by agent.stream()
HandoffCycleError / BudgetExceededError error class Domain-specific failures
Export Kind Description
createMemory(options) function Memory factory (D1 + optional Vectorize/AI/KV)
getSchema() function D1 schema SQL for migrations
cosineSimilarity / estimateTokens / extractSearchTerms function Recall scoring utilities
Memory / Conversation / Fact / RecallResult / MemoryError type Public types
Export Kind Description
createMCPServer(config) function MCP server with tools, resources, prompts
generateOpenAPISpec(server) function Export OpenAPI from a server instance
validateInput(schema, input) function Standard Schema validation helper
ToolAnnotations type MCP 2025-06 tool safety hints
Export Kind Description
createDurableWorkflow(name, config) function Builder for DO-backed workflows
createWorkflow(name, config) function Alias for non-durable testing flows
WorkflowExecutionDO DO class Re-exportable Durable Object for execution state
parseDuration(str) function Parse "30s", "5m", "1h" to ms
generateExecutionId() function Create a unique execution ID
Export Kind Description
createApprovalGate(config) function Approval gate factory
ApprovalRequestDO DO class Re-exportable Durable Object for live requests
evaluatePolicies(action, policies) function Match an action against registered policies
generateApprovalToken / verifyApprovalToken / generateApprovalKeys function Ed25519 signed approval tokens
createAuditProjection(db) function Append-only audit projection over D1

The workkit CLI is published as a single binary. Run via bunx workkit <cmd>.

Command Description
init Scaffold a new Workers project with workkit defaults
add [packages...] Interactively add @workkit/* packages to an existing project
catalog List every workkit package with one-line descriptions
check Run the constitution check on the current repo
gen-client Generate a typed client from an @workkit/api definition
gen-docs Generate API reference markdown from src/index.ts exports
migrate Apply D1 migrations from a directory
seed Seed a D1 database from a JSON or SQL fixture