Skip to content
Moku
@moku-labs/worker pages

API reference

Every export of @moku-labs/worker, with signatures.

On this page

Entries

ImportFormatFor
@moku-labs/workerESM and CJSEverything: the Worker runtime, the Node-only plugins and the types. A Worker needs the nodejs_compat flag, see How it works.

Signatures below are simplified for reading. The installed dist/index.d.mts is the source.

createApp

function createApp<const ExtraPlugins extends readonly AnyPluginInstance[] = readonly []>(options?: {
  plugins?: ExtraPlugins;
  config?: { name?: string; stage?: "production" | "development" | "test"; compatibilityDate?: string };
  pluginConfigs?: { [pluginName: string]: Partial<PluginConfig> };
  onReady?: (ctx: AppCallbackContext) => void;
  onError?: (error: Error, ctx: AppCallbackContext) => void;
  onStart?: (ctx: AppCallbackContext) => void | Promise<void>;
  onStop?: (ctx: AppCallbackContext) => void | Promise<void>;
}): App;

Creates and initializes an app. It is synchronous and the result is frozen. The plugin list is [log, env, bindings, server, ...plugins]. A plugin comes after the plugins it depends on, and listing a name twice throws.

OptionDefaultDescription
plugins[]Extra plugins, merged into the app and into its type.
config.name"worker"The Worker name.
config.stage"production"The default deploy stage.
config.compatibilityDate""The Cloudflare compatibility date.
pluginConfigs{}Per-plugin overrides, keyed by plugin name.

The returned app:

MemberWhat it is
log, envThe core plugin APIs.
bindings, serverThe default plugin APIs.
<name>The API of every plugin in plugins, for example app.kv, app.cli.
require(plugin), has(name)Plugin lookup.
emit(event, payload)Emits a typed event.
start(), stop()Run onStart and onStop. A Worker never needs them.

createPlugin

function createPlugin<Name extends string, Config, State, Api, Deps, Events, Hooks, Helpers>(
  name: Name,
  spec: {
    config?: Config;
    depends?: Deps;
    createState?: (ctx: { global; config }) => State;
    events?: (register) => Events;
    api?: (ctx: PluginContext) => Api;
    hooks?: (ctx: PluginContext) => Hooks;
    helpers?: Helpers;
    onInit?: (ctx: PluginContext) => void;
    onStart?: (ctx: PluginContext) => void | Promise<void>;
    onStop?: (ctx: { global; config; state }) => void | Promise<void>;
  }
): PluginInstance<Name, Config, State, Api, Events> & Helpers;

Writes a plugin bound to this framework's config, events and core plugins. ctx carries global, config, state, emit, require, has, log and env. A plugin in depends makes its events available to hooks. Keep the rule of the package: take env as an argument, and never store it.

src/plugins/metrics.ts
import { createPlugin, queuesPlugin } from "@moku-labs/worker";

export const metricsPlugin = createPlugin("metrics", {
  depends: [queuesPlugin],
  hooks: ctx => ({
    "queue:message": ({ queue, messageId }) => ctx.log.info(`${queue} ${messageId}`),
    "request:end": ({ path, status, ms }) => ctx.log.info(`${path} ${status} ${ms}ms`)
  })
});
  1. queue:message is local to queues, so the hook needs this.

Plugins

Exportapp.<name>DefaultPage
bindingsPluginbindingsyesbindings
serverPluginserveryesserver
kvPluginkvnokv
d1Plugind1nod1
storagePluginstoragenostorage
queuesPluginqueuesnoqueues
durableObjectsPlugindurableObjectsnodurableObjects
turnPluginturnnoturn
deployPlugindeployno, Node onlydeploy
cliPluginclino, Node onlycli
logPluginlogcoreFrom @moku-labs/common.
envPluginenvcoreFrom @moku-labs/common. Reads environment variables through process.env.

Helpers

const endpoint: GuardedEndpointFactory;

type GuardedEndpointFactory<Extension = {}> = {
  <Path extends string>(path: Path): EndpointBuilder<Path, Extension>;
  new: <R>(guard: (ctx: RequestContext & Extension) => R) => GuardedEndpointFactory<Extension & GuardExtension<Awaited<R>>>;
};

type EndpointBuilder<Path extends string, Extension> = {
  get(handler: EndpointHandler<PathParams<Path>, Extension>): Endpoint;
  // post, put, patch, delete, head, options and all have the same shape.
};

const defineDurableObject: (name: string) => DurableObjectBaseConstructor & { readonly doName: string };

endpoint builds the server table. defineDurableObject returns the base class of a Durable Object. Both are pure, and safe to call before createApp.

Plugin APIs on app

PluginMethods
bindingsrequire, has
serverhandle, scheduled
kvget, put, delete, list, use, deployManifest
d1query, first, run, batch, prepare, use, deployManifest
storageget, put, delete, list, use, deployManifest
queuessend, sendBatch, consume, use, deployManifest
durableObjectsget, deployManifest
turndeployManifest
deployrun, destroy, dev, seed, init, checkInfra, provisionInfra, verifyAuth, requiredToken, ciToken, tokenInstructions, wrangler
clidev, deploy, seed, auth, doctor, whoami, wrangler

Types

All type-only exports. Cloudflare types such as KVNamespace and D1Database are ambient, from @cloudflare/workers-types.

TypeWhat it is
WorkerConfig{ stage; name; compatibilityDate }.
WorkerEnvRecord<string, unknown>, the per-invocation bindings.
WorkerEventsThe global event map.
WorkerPluginCtx<Config, State, Events>A plugin context with WorkerEvents merged in. Use it to type a plugin's helper functions.
PluginCtxThe raw context from @moku-labs/core, re-exported.
EndpointGuard<Extension>A guard: returns a Response, an extension object, or nothing.
GuardedEndpointFactory<Extension>The type of endpoint and of each .new().
DeployReportWhat deploy.run and cli.deploy resolve to.
ExternalManifest{ name; compatibilityDate; resources }, for run({ manifest }).
ResourceManifestOne resource: a union on kind (r2, kv, d1, queue, do, turn).
SeedConfig{ file; binding?; resetKv? }.

Six namespaces hold each plugin's own types:

NamespaceMembers
BindingsConfig, BindingsApi, Context
ServerEndpoint, EndpointHandler, EndpointGuard, RequestContext, PathParams, Method, RequireFn, ServerConfig, ServerEvents, Api and the matcher types
D1Config, D1Instance, D1DatabaseApi, Api, D1Ctx
StorageStorageConfig, R2Instance, StorageBucketApi, StorageApi, StorageProvider, StorageCtx
QueuesConfig, QueueInstance, QueueProducerApi, QueueEvents, Api, Ctx
DurableObjectsConfig, DoInstance, Api, Ctx
src/types.ts
import type { D1, DeployReport, Server, WorkerEnv } from "@moku-labs/worker";

export type Context = Server.RequestContext<{ id: string }>;
export type Database = D1.D1Instance;
export type Report = Pick<DeployReport, "status" | "url">;
export const readId = (ctx: Context, env: WorkerEnv) => [ctx.params.id, Object.keys(env).length] as const;