Skip to main content

API reference

This page lists every public export of @ltv/cwb 0.2.0, checked against the package's public API snapshot (etc/cwb.api.d.ts). Anything not exported from @ltv/cwb or @ltv/cwb/datasources is internal and may change in any release (support policy).

Kinds: function, class, const (runtime value), type (type alias or interface, erased at runtime), namespace.

@ltv/cwb

App and modules

ExportKindDescription
createApp(config)functionBuilds a Hono app with the standard middleware stack, module routes and OpenAPI router. Guide
AppConfig<E>typeOptions for createApp. Reference
RequestIdConfigtypeboolean or RequestIdOptions
RequestIdOptionstype{trustIncomingHeader?: boolean}
RequestLoggingConfigtypeboolean or RequestLoggingOptions
RequestLoggingOptionstype{level?, skip?} for the per-request log line
RequestLogLeveltype'trace', 'debug', 'info' or 'warn'
defineModule(module)functionNormalizes an ApiModule (version 2 becomes 'v2', default 'v1'). Guide
ApiModuletype{version?, routes, middleware?}
RouteKeytypeTemplate literal type for "METHOD /path" keys
RouteMethodtype'GET', 'POST', 'PUT', 'PATCH' or 'DELETE'
EndpointRegistryclassCollects endpoints and applies them to a chanfana router (register, get, post, put, patch, delete, applyTo, getEndpoints)
EndpointConfigtype{method, path, handler, middleware?} stored by the registry
EndpointMethodtypeLowercase route method
ENDPOINT_METHODSconst['get', 'post', 'put', 'patch', 'delete']
OpenAPIRoutertypeMinimal shape of a chanfana router, as returned by fromHono(app)
buildEndpointPath(base, version, route)functionJoins base path, optional version and route into a normalized path

Context and responses

ExportKindDescription
contextHelpersconstMiddleware that adds the c.respond* helpers; installed by createApp. Guide
ContextResponseHelperstypeSignatures of the c.respond* methods added to Hono's Context
buildPaginationMeta(page, limit, total)functionPagination metadata; throws a 400 BAD_REQUEST ApiError on invalid input
PaginationMetatype{page, limit, total, totalPages, hasNext, hasPrev}
ApiResponse<T>typeApiSuccessResponse<T> or ApiErrorResponse, discriminated on success
ApiSuccessResponse<T>type{success: true, data, meta?}
ApiErrorResponsetype{success: false, error: {id, code, message, details?}, meta?}
ApiResponseMetatype{timestamp, requestId?, traceId?, pagination?}
PaginationParamstype{page?, limit?, sort?, order?} list-query shape
QueryParamstypePaginationParams plus search? and filter?
BaseUsertype{id, email?, name?}
BaseTenanttype{id, name}
BaseContextVariablestypeuser, tenant, tenantId, requestId, traceId; no index signature
BaseEnvironmentBindingstypeNODE_ENV?, APP_VERSION?
AppEnv<Variables, Bindings>typeHono env generic: {Variables, Bindings}
TenantContexttype{tenantId?, tenant?}
TenantContextVariablestypeBaseContextVariables with tenant extended by schema?, features?, config?

OpenAPI schemas

All json* helpers return a chanfana responses object keyed by status code. Guide

ExportKindDescription
jsonSuccess(description, schema)function200 success envelope
jsonCreated(description, schema)function201 success envelope
jsonAccepted(description, schema)function202 success envelope
jsonNoContent(description)function204 without body
jsonPaginated(description, schema)function200 with data: schema[] and required meta.pagination
jsonBadRequest(description?)function400 error envelope
jsonUnauthorized(description?)function401 error envelope
jsonForbidden(description?)function403 error envelope
jsonNotFound(description?)function404 error envelope
jsonConflict(description?)function409 error envelope
jsonValidationError(description?)function422 envelope with details: [{field, message, code?}]
jsonInternalError(description?)function500 error envelope
jsonCrudResponses(resource, schema)function200, 400, 401, 404, 500
jsonListResponses(resource, schema)functionPaginated 200, 400, 401, 500
jsonCreateResponses(resource, schema)function201, 400, 401, 409, 422, 500
jsonUpdateResponses(resource, schema)function200, 400, 401, 404, 422, 500
jsonDeleteResponses(resource)function204, 400, 401, 404, 500
jsonCustomResponse(statusCode, description, schema?)functionAny status, no envelope
MetaSchemaconstzod schema for meta
PaginationMetaSchemaconstzod schema for meta.pagination
ErrorSchemaconstzod schema for error (id, code, message, details?)

Errors

Guide

ExportKindDescription
ApiErrorclassError with id, code, status, category, severity, details, cause; static factories and type guards
ApiErrorOptionstypeConstructor options for ApiError
ApiErrorJSONtypeResult of ApiError#toJSON() (no stack)
ErrorCategoryconstAUTHENTICATION, AUTHORIZATION, VALIDATION, BUSINESS_LOGIC, EXTERNAL_SERVICE, DATABASE, RATE_LIMIT, SYSTEM, UNKNOWN
ErrorCategoryTypetypeUnion of ErrorCategory values
ErrorSeverityconstLOW, MEDIUM, HIGH, CRITICAL
ErrorSeverityTypetypeUnion of ErrorSeverity values
createErrorHandler(config?)functionHono error handler producing the envelope, with logging, reporting, redaction, throttling and getMetrics()
errorHandlerconstcreateErrorHandler() with default options, for plain Hono apps
ErrorHandlerConfigtypeOptions for createErrorHandler and AppConfig.errors. Reference
ErrorHandlerWithMetricstypeHono ErrorHandler plus getMetrics()
ErrorHandlerFactorytype(config?) => ErrorHandlerWithMetrics
ErrorClassifiertype(error, c) => {category, severity}
ErrorTransformertype(error, c) => ErrorTransformResult
ErrorTransformResulttypeApiErrorOptions plus an optional client-safe message
ErrorInfotypeStructured error passed to logs, customLogger and errorReporter
ErrorContexttypeRequest context in ErrorInfo (ids, method, path, ip, user agent, redacted headers and query)
ErrorContextRedactiontype{headers?, queryParams?, includeClientInfo?} for buildErrorContext
ErrorResponsetypeError envelope shape with required meta
ErrorMetricstype{total, byCategory, bySeverity, byStatusCode, rate}
ErrorMetricsTrackerclassPer-isolate counters and one-minute window used for metrics and throttling
buildErrorContext(c, requestId, redaction?)functionCollects redacted request, user and tenant context
isProductionContext(c)functiontrue unless c.env.NODE_ENV (or the Worker env) is a development value

Logging

Guide

ExportKindDescription
loggerconstRoot pino logger with base fields
LoggertypeType of logger
createLogger(context)functionChild of the root logger with extra fields
getRequestLogger(c)functionRequest-scoped logger bound to requestId, or the root logger
serializersconstpino serializers err, req, res with redaction
serializeError(error, options?)functionJSON-safe error with its cause chain; never throws
SerializedErrortype{type?, message, stack?, code?, statusCode?, cause?}
SerializeErrorOptionstype{includeStack?, maxDepth?}
RequestLiketypeFetch Request, HonoRequest or similar object accepted by serializers.req
ResponseLiketypeObject with optional status and headers
createLoggerOptions(writers?)functionThe pino options used by the library, with optional per-level writers
LogWritertype(entry: object) => void
baseLogBindingsconst{env, service, runtime} attached to every line

Redaction

ExportKindDescription
redactHeaders(headers, extra?)functionHeaders as a plain object with sensitive values replaced
redactQueryParams(query, extra?)functionCopy of query params with sensitive values replaced
redactUrl(url, extra?)functionURL with sensitive query values replaced; unparseable URLs returned as-is
addSensitiveHeaders(...names)functionRegisters extra header names to redact everywhere
addSensitiveQueryParams(...names)functionRegisters extra query parameter names to redact everywhere
isSensitiveName(name, exactNames)functiontrue for an exact match or a name containing a sensitive fragment
SENSITIVE_HEADERSconstHeader names redacted by exact match
SENSITIVE_QUERY_PARAMSconstQuery parameter names redacted by exact match
SENSITIVE_NAME_FRAGMENTSconstFragments that mark any header or parameter name as sensitive
REDACTEDconst'[REDACTED]'

Environment

Guide

ExportKindDescription
envnamespaceenv.default(key, default?) raw reader with typed readers string, int, float, number, bool, json, array, date
env.StringOrUndefined, env.NumberOrUndefined, env.BooleanOrUndefined, env.DateOrUndefined, env.ArrayOfStringOrUndefined, env.CustomOrUndefinedtypeReturn types of the typed readers
NODE_ENVconstNODE_ENV at load time, default 'production'
isDevconstNODE_ENV is a development value
isProdconst!isDev
DEVELOPMENT_ENVIRONMENTSconst['development', 'dev', 'test', 'local']
isDevelopmentEnvironment(nodeEnv)functionFail-safe check: only those values are non-production
LOG_LEVELconstResolved log level
LOG_LEVELSconst['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']
resolveLogLevel(value, fallback, warn?)functionNormalizes a level; unknown values warn and return fallback
SERVICE_NAMEconstSERVICE_NAME at load time, default '@ltv/cwb'

KV cache and utilities

ExportKindDescription
KVCacheclassRead-through KV cache: buildKey, memoize, invalidate, clearAll. Guide
KVCacheOptionstype{defaultNamespace?, defaultTtl?, waitUntil?, logger?}
CacheOptions<T>type{ttl?, namespace?, revive?}
InvalidateOptionstype{cursor?, maxOperations?}
InvalidateResulttype{deleted, complete, cursor?, failed}
MIN_KV_TTL_SECONDSconst60
DEFAULT_MAX_KV_OPERATIONSconst900
getWaitUntil(c)functionexecutionCtx.waitUntil of a Hono context, or undefined
runInBackground(promise, waitUntil, onError)functionRuns work past the response; errors go to onError
WaitUntiltype(promise: Promise<unknown>) => void
createId()functionCUID2 id: 24 lowercase alphanumeric characters, starting with a letter

@ltv/cwb/datasources

Requires the optional peer drizzle-orm 0.45.x. Datasources guide, multi-tenancy guide

Classes

ExportKindDescription
AbstractDatasource<TContext>class (abstract)Context-bound base: logger, withCache, cacheBinding, cacheNamespace, clear, init, connect, disconnect, healthCheck
BaseDatasource<TContext>typeInterface: name, context?, optional lifecycle methods
DrizzleD1Datasource<TSchema, TContext>class (abstract)Drizzle on D1: lazy db, batch, healthCheck, createQueryLogger
DrizzleD1DatasourceOptions<TSchema>type{schema?, binding?, logQueries?}
DrizzleSchematypeRecord<string, unknown>
DrizzleD1TenantDatasource<TSchema, TContext>class (abstract)Tenant-scoped datasource: tenantId, where, values, scopedSelect, scopedCount, scopedInsert, scopedInsertMany, scopedUpsert, scopedUpdate, scopedDelete
DrizzleD1TenantDatasourceOptions<TSchema>typeDrizzleD1DatasourceOptions plus tenantId?

Tenant helpers and types

ExportKindDescription
tenantWhere(table, tenantId, ...conditions)functionWhere clause restricting a table to a tenant; conditions are parenthesized
withTenantId(values, tenantId)functionStamps tenantId on one row or many rows, overriding existing values
withoutTenantId(values)functionRemoves tenantId from update values
toScopedWriteQuery(builder)functionWraps an already tenant-filtered Drizzle insert, update or delete builder in a ScopedWriteQuery; adds no filter itself
toScopedInsertQuery(builder)functionSame for insert builders, exposing only onConflictDoNothing
ScopedWriteQuery<TTable>typeAwaitable D1Result with returning()
ScopedInsertQuery<TTable>typeScopedWriteQuery plus onConflictDoNothing()
ScopedSelectOptionstype{where?, orderBy?, limit?, offset?}
ScopedOrderBytypeSQLite column or SQL expression
TenantScopedTabletypeAny Drizzle table with a string tenantId column
TenantTabletypeSQLiteTable & TenantScopedTable
TenantInsert<TTable>typeInsert model without tenantId
TenantUpsertSet<TTable>typeUpsert set values: insert columns (except tenantId) or SQL
WithTenantId<V>typeV (or each row of V) with tenantId: string

Type augmentations

Importing @ltv/cwb augments the hono module:

AugmentationEffect
Context extends ContextResponseHelpersc.respond* methods are typed on every context (present at runtime only with contextHelpers)
ContextVariableMap.cwbLogger?: LoggerTyped c.var.cwbLogger
ContextVariableMap.traceId?: stringTyped c.get('traceId') / c.set('traceId', ...)