@slotform/api 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +50 -2
- package/dist/client.d.ts +16 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +98 -0
- package/dist/client.js.map +1 -0
- package/dist/error.d.ts +2 -0
- package/dist/error.d.ts.map +1 -0
- package/dist/error.js +2 -0
- package/dist/error.js.map +1 -0
- package/dist/index.d.ts +153 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +640 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/chosen.d.ts +12 -0
- package/dist/lib/chosen.d.ts.map +1 -0
- package/dist/lib/chosen.js +18 -0
- package/dist/lib/chosen.js.map +1 -0
- package/dist/lib/cursor.d.ts +68 -0
- package/dist/lib/cursor.d.ts.map +1 -0
- package/dist/lib/cursor.js +220 -0
- package/dist/lib/cursor.js.map +1 -0
- package/dist/lib/limits.d.ts +4 -0
- package/dist/lib/limits.d.ts.map +1 -0
- package/dist/lib/limits.js +10 -0
- package/dist/lib/limits.js.map +1 -0
- package/dist/lib/local-origin.d.ts +2 -0
- package/dist/lib/local-origin.d.ts.map +1 -0
- package/dist/lib/local-origin.js +17 -0
- package/dist/lib/local-origin.js.map +1 -0
- package/dist/lib/slugify.d.ts +4 -0
- package/dist/lib/slugify.d.ts.map +1 -0
- package/dist/lib/slugify.js +26 -0
- package/dist/lib/slugify.js.map +1 -0
- package/dist/lib/window.d.ts +52 -0
- package/dist/lib/window.d.ts.map +1 -0
- package/dist/lib/window.js +70 -0
- package/dist/lib/window.js.map +1 -0
- package/dist/mcp-path.d.ts +2 -0
- package/dist/mcp-path.d.ts.map +1 -0
- package/dist/mcp-path.js +3 -0
- package/dist/mcp-path.js.map +1 -0
- package/dist/mcp.d.ts +15 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +5 -0
- package/dist/mcp.js.map +1 -0
- package/dist/node/barrel.d.ts +3 -0
- package/dist/node/barrel.d.ts.map +1 -0
- package/dist/node/barrel.js +70 -0
- package/dist/node/barrel.js.map +1 -0
- package/dist/node/codegen.d.ts +10 -0
- package/dist/node/codegen.d.ts.map +1 -0
- package/dist/node/codegen.js +132 -0
- package/dist/node/codegen.js.map +1 -0
- package/dist/node/procedure-codegen.d.ts +14 -0
- package/dist/node/procedure-codegen.d.ts.map +1 -0
- package/dist/node/procedure-codegen.js +95 -0
- package/dist/node/procedure-codegen.js.map +1 -0
- package/dist/node/schema-child.d.ts +2 -0
- package/dist/node/schema-child.d.ts.map +1 -0
- package/dist/node/schema-child.js +31 -0
- package/dist/node/schema-child.js.map +1 -0
- package/dist/node/schema-source.d.ts +3 -0
- package/dist/node/schema-source.d.ts.map +1 -0
- package/dist/node/schema-source.js +33 -0
- package/dist/node/schema-source.js.map +1 -0
- package/dist/node/server-client.d.ts +19 -0
- package/dist/node/server-client.d.ts.map +1 -0
- package/dist/node/server-client.js +45 -0
- package/dist/node/server-client.js.map +1 -0
- package/dist/node/types.d.ts +42 -0
- package/dist/node/types.d.ts.map +1 -0
- package/dist/node/types.js +13 -0
- package/dist/node/types.js.map +1 -0
- package/dist/not-found.d.ts +2 -0
- package/dist/not-found.d.ts.map +1 -0
- package/dist/not-found.js +6 -0
- package/dist/not-found.js.map +1 -0
- package/dist/procedure.d.ts +188 -0
- package/dist/procedure.d.ts.map +1 -0
- package/dist/procedure.js +392 -0
- package/dist/procedure.js.map +1 -0
- package/dist/query-invalidation.d.ts +20 -0
- package/dist/query-invalidation.d.ts.map +1 -0
- package/dist/query-invalidation.js +66 -0
- package/dist/query-invalidation.js.map +1 -0
- package/dist/schema.d.ts +32 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +103 -0
- package/dist/schema.js.map +1 -0
- package/dist/types.d.ts +30 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/wire.d.ts +11 -0
- package/dist/wire.d.ts.map +1 -0
- package/dist/wire.js +26 -0
- package/dist/wire.js.map +1 -0
- package/dist/worker/guards.d.ts +6 -0
- package/dist/worker/guards.d.ts.map +1 -0
- package/dist/worker/guards.js +29 -0
- package/dist/worker/guards.js.map +1 -0
- package/dist/worker/index.d.ts +57 -0
- package/dist/worker/index.d.ts.map +1 -0
- package/dist/worker/index.js +418 -0
- package/dist/worker/index.js.map +1 -0
- package/dist/worker/mcp.d.ts +28 -0
- package/dist/worker/mcp.d.ts.map +1 -0
- package/dist/worker/mcp.js +361 -0
- package/dist/worker/mcp.js.map +1 -0
- package/dist/worker/request-log.d.ts +10 -0
- package/dist/worker/request-log.d.ts.map +1 -0
- package/dist/worker/request-log.js +37 -0
- package/dist/worker/request-log.js.map +1 -0
- package/guide/add-a-procedure.md +42 -0
- package/guide/background.md +86 -0
- package/guide/client.md +93 -0
- package/guide/config.md +85 -0
- package/guide/mcp.md +68 -0
- package/guide/middleware.md +79 -0
- package/guide/procedures.md +95 -0
- package/guide/utilities.md +135 -0
- package/package.json +120 -3
- package/src/client.ts +129 -0
- package/src/error.ts +1 -0
- package/src/index.ts +787 -0
- package/src/lib/chosen.ts +31 -0
- package/src/lib/cursor.ts +354 -0
- package/src/lib/limits.ts +10 -0
- package/src/lib/local-origin.ts +18 -0
- package/src/lib/slugify.ts +29 -0
- package/src/lib/window.ts +155 -0
- package/src/mcp-path.ts +2 -0
- package/src/mcp.ts +30 -0
- package/src/node/barrel.ts +77 -0
- package/src/node/codegen.ts +173 -0
- package/src/node/procedure-codegen.ts +131 -0
- package/src/node/schema-child.ts +31 -0
- package/src/node/schema-source.ts +45 -0
- package/src/node/server-client.ts +67 -0
- package/src/node/types.ts +64 -0
- package/src/not-found.ts +6 -0
- package/src/procedure.ts +935 -0
- package/src/query-invalidation.ts +106 -0
- package/src/schema.ts +133 -0
- package/src/types.ts +72 -0
- package/src/wire.ts +34 -0
- package/src/worker/guards.ts +37 -0
- package/src/worker/index.ts +681 -0
- package/src/worker/mcp.ts +470 -0
- package/src/worker/request-log.ts +50 -0
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
import { ORPCError } from "@orpc/server";
|
|
2
|
+
import { RPCHandler } from "@orpc/server/fetch";
|
|
3
|
+
import {
|
|
4
|
+
RequestHeadersPlugin,
|
|
5
|
+
ResponseHeadersPlugin,
|
|
6
|
+
} from "@orpc/server/plugins";
|
|
7
|
+
import type { RuntimePlugin } from "@slotform/cli/runtime";
|
|
8
|
+
import { type Context, Hono, type MiddlewareHandler } from "hono";
|
|
9
|
+
import { cors } from "hono/cors";
|
|
10
|
+
import { secureHeaders } from "hono/secure-headers";
|
|
11
|
+
import type { ContentfulStatusCode } from "hono/utils/http-status";
|
|
12
|
+
import { isLocalOrigin } from "../lib/local-origin.ts";
|
|
13
|
+
import type { McpDefinition } from "../mcp.ts";
|
|
14
|
+
import { MCP_PATH } from "../mcp-path.ts";
|
|
15
|
+
import {
|
|
16
|
+
createProcedure,
|
|
17
|
+
type JobBatch,
|
|
18
|
+
type JobScheduledEvent,
|
|
19
|
+
} from "../procedure.ts";
|
|
20
|
+
import {
|
|
21
|
+
listenerOrigin,
|
|
22
|
+
SLOTFORM_EXPOSED_HEADERS,
|
|
23
|
+
SLOTFORM_NOT_FOUND_HEADER,
|
|
24
|
+
} from "../wire.ts";
|
|
25
|
+
import { ipLimited, ORIGINS_VAR } from "./guards.ts";
|
|
26
|
+
import { buildMcpTools, createMcpEndpoint, createMcpRoute } from "./mcp.ts";
|
|
27
|
+
import { requestLogger } from "./request-log.ts";
|
|
28
|
+
|
|
29
|
+
export { isForbiddenOrigin, RATE_LIMITER_RPC } from "./guards.ts";
|
|
30
|
+
|
|
31
|
+
export interface WorkerExport<
|
|
32
|
+
TRouter extends Record<string, unknown> = Record<string, unknown>,
|
|
33
|
+
> {
|
|
34
|
+
fetch: (
|
|
35
|
+
request: Request,
|
|
36
|
+
env: unknown,
|
|
37
|
+
ctx: unknown,
|
|
38
|
+
) => Response | Promise<Response>;
|
|
39
|
+
// `checkEnv`: docs/architecture/plugins/api.md, "Env vars".
|
|
40
|
+
checkEnv: (env: unknown) => void;
|
|
41
|
+
// The job context, built afresh on each call: docs/architecture/runtime.md, "Background handlers".
|
|
42
|
+
jobContext: (env: unknown, ctx?: unknown) => Promise<Record<string, unknown>>;
|
|
43
|
+
// `queue` and `scheduled`: plugins/api/guide/background.md, "The context".
|
|
44
|
+
queue?: (batch: JobBatch, env: unknown, ctx: unknown) => Promise<void>;
|
|
45
|
+
scheduled?: (
|
|
46
|
+
controller: JobScheduledEvent,
|
|
47
|
+
env: unknown,
|
|
48
|
+
ctx: unknown,
|
|
49
|
+
) => Promise<void>;
|
|
50
|
+
_router: TRouter;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface PluginEntry {
|
|
54
|
+
// biome-ignore lint/suspicious/noExplicitAny: plugins have varying types
|
|
55
|
+
plugin: RuntimePlugin<string, any, any, any>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface FnEntry {
|
|
59
|
+
fn: (
|
|
60
|
+
ctx: Record<string, unknown>,
|
|
61
|
+
) => Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface MiddlewareEntry {
|
|
65
|
+
middleware: MiddlewareHandler;
|
|
66
|
+
// `afterContext` mounts via `.useAfterContext()`: docs/architecture/runtime.md, "Middleware".
|
|
67
|
+
afterContext?: boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
type UseEntry = PluginEntry | FnEntry | MiddlewareEntry;
|
|
71
|
+
|
|
72
|
+
function isPluginEntry(entry: UseEntry): entry is PluginEntry {
|
|
73
|
+
return "plugin" in entry;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function isMiddlewareEntry(entry: UseEntry): entry is MiddlewareEntry {
|
|
77
|
+
return "middleware" in entry;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Plugin entries sort by `dependsOn`: docs/architecture/runtime.md, "Runtime plugin protocol".
|
|
81
|
+
function sortPluginEntries(entries: UseEntry[]): UseEntry[] {
|
|
82
|
+
const pluginPositions: number[] = [];
|
|
83
|
+
const pluginEntries: PluginEntry[] = [];
|
|
84
|
+
entries.forEach((entry, i) => {
|
|
85
|
+
if (isPluginEntry(entry)) {
|
|
86
|
+
pluginPositions.push(i);
|
|
87
|
+
pluginEntries.push(entry);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
if (pluginEntries.length <= 1) return entries;
|
|
92
|
+
|
|
93
|
+
const byName = new Map(pluginEntries.map((e) => [e.plugin.name, e]));
|
|
94
|
+
const visited = new Set<string>();
|
|
95
|
+
const inStack = new Set<string>();
|
|
96
|
+
const sorted: PluginEntry[] = [];
|
|
97
|
+
|
|
98
|
+
function visit(entry: PluginEntry, stack: string[]): void {
|
|
99
|
+
const name = entry.plugin.name;
|
|
100
|
+
if (visited.has(name)) return;
|
|
101
|
+
if (inStack.has(name)) {
|
|
102
|
+
const cycleStart = stack.indexOf(name);
|
|
103
|
+
const cycle = [...stack.slice(cycleStart), name];
|
|
104
|
+
throw new Error(`Runtime plugin dependency cycle: ${cycle.join(" -> ")}`);
|
|
105
|
+
}
|
|
106
|
+
inStack.add(name);
|
|
107
|
+
for (const dep of entry.plugin.dependsOn ?? []) {
|
|
108
|
+
const depEntry = byName.get(dep);
|
|
109
|
+
// A dependsOn naming a plugin that isn't registered is ignored —
|
|
110
|
+
// presence is validated at config level by `requires`.
|
|
111
|
+
if (depEntry) visit(depEntry, [...stack, name]);
|
|
112
|
+
}
|
|
113
|
+
inStack.delete(name);
|
|
114
|
+
visited.add(name);
|
|
115
|
+
sorted.push(entry);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
for (const entry of pluginEntries) {
|
|
119
|
+
visit(entry, []);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const result = [...entries];
|
|
123
|
+
pluginPositions.forEach((pos, i) => {
|
|
124
|
+
result[pos] = sorted[i] as PluginEntry;
|
|
125
|
+
});
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Middleware dispatches on arity: docs/architecture/runtime.md, "Middleware".
|
|
130
|
+
function isHonoMiddleware(fn: (...args: unknown[]) => unknown): boolean {
|
|
131
|
+
return fn.length >= 2;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// `TPluginRoutes` accumulates the routes each `.use(plugin)` registers, so
|
|
135
|
+
// `handler()` types the router as the plugins' routes plus the consumer's.
|
|
136
|
+
export interface AppBuilder<
|
|
137
|
+
TContext extends Record<string, unknown>,
|
|
138
|
+
TPluginRoutes extends Record<string, unknown> = Record<never, never>,
|
|
139
|
+
> {
|
|
140
|
+
use<
|
|
141
|
+
TName extends string,
|
|
142
|
+
TProvides extends Record<string, unknown>,
|
|
143
|
+
TRoutes extends Record<string, unknown>,
|
|
144
|
+
>(
|
|
145
|
+
plugin: RuntimePlugin<TName, TContext, TProvides, TRoutes>,
|
|
146
|
+
): AppBuilder<TContext & TProvides, TPluginRoutes & TRoutes>;
|
|
147
|
+
|
|
148
|
+
use(middleware: MiddlewareHandler): AppBuilder<TContext, TPluginRoutes>;
|
|
149
|
+
|
|
150
|
+
use<TExtra extends Record<string, unknown>>(
|
|
151
|
+
fn: (ctx: TContext) => TExtra | Promise<TExtra>,
|
|
152
|
+
): AppBuilder<TContext & TExtra, TPluginRoutes>;
|
|
153
|
+
|
|
154
|
+
useAfterContext(
|
|
155
|
+
middleware: MiddlewareHandler,
|
|
156
|
+
): AppBuilder<TContext, TPluginRoutes>;
|
|
157
|
+
|
|
158
|
+
// `mcp` mounts `POST /mcp` over the routes it names (the generated worker
|
|
159
|
+
// passes `src/worker/mcp.ts` and the app's name); `queue` and `scheduled`
|
|
160
|
+
// are the consumer's background handlers.
|
|
161
|
+
handler<TRoutes extends Record<string, unknown>>(
|
|
162
|
+
consumerRoutes?: TRoutes,
|
|
163
|
+
mount?: HandlerMount,
|
|
164
|
+
): WorkerExport<TPluginRoutes & TRoutes>;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// What the generated worker mounts beside the routes: the MCP definition with
|
|
168
|
+
// the server's name (`name` comes with `mcp`), and the two job handlers.
|
|
169
|
+
export type HandlerMount = {
|
|
170
|
+
queue?: JobQueueHandler;
|
|
171
|
+
scheduled?: JobScheduledHandler;
|
|
172
|
+
} & ({ mcp: McpDefinition; name: string } | { mcp?: never; name?: never });
|
|
173
|
+
|
|
174
|
+
type JobQueueHandler = (
|
|
175
|
+
// biome-ignore lint/suspicious/noExplicitAny: the consumer types its own body
|
|
176
|
+
batch: JobBatch<any>,
|
|
177
|
+
context: never,
|
|
178
|
+
) => Promise<void>;
|
|
179
|
+
|
|
180
|
+
type JobScheduledHandler = (
|
|
181
|
+
event: JobScheduledEvent,
|
|
182
|
+
context: never,
|
|
183
|
+
) => Promise<void>;
|
|
184
|
+
|
|
185
|
+
// `TEnv` is the env type the deploy target names (`Env` on Cloudflare), baked
|
|
186
|
+
// into the generated `createWorker<Env>(...)`; `unknown` without one.
|
|
187
|
+
export type BaseContext<TEnv = unknown> = {
|
|
188
|
+
env: TEnv;
|
|
189
|
+
// The raw HTTP request, named so no scope's row shadows it.
|
|
190
|
+
httpRequest: Request;
|
|
191
|
+
reqHeaders: Headers;
|
|
192
|
+
resHeaders: Headers;
|
|
193
|
+
// Hono's and wrangler's `ExecutionContext` types disagree on optional
|
|
194
|
+
// members; `waitUntil` is the only part of the contract procedures need.
|
|
195
|
+
executionCtx: { waitUntil(promise: Promise<unknown>): void };
|
|
196
|
+
[key: string]: unknown;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
// One env var the worker asserts before serving: docs/architecture/plugins/api.md, "Env vars".
|
|
200
|
+
export interface EnvCheckSpec {
|
|
201
|
+
name: string;
|
|
202
|
+
minLength?: number;
|
|
203
|
+
url?: boolean;
|
|
204
|
+
devLocalhost?: boolean;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export interface ApiWorkerOptions {
|
|
208
|
+
cors?: string[];
|
|
209
|
+
// Localhost dev-server origins. Honoured only when the worker runs with
|
|
210
|
+
// SLOTFORM_DEV set, so a production deploy never accepts them.
|
|
211
|
+
devCors?: string[];
|
|
212
|
+
prefix?: `/${string}`;
|
|
213
|
+
envChecks?: EnvCheckSpec[];
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
type ResolvedApiOptions = Required<Pick<ApiWorkerOptions, "prefix">> &
|
|
217
|
+
Pick<ApiWorkerOptions, "cors" | "devCors" | "envChecks">;
|
|
218
|
+
|
|
219
|
+
// The single dev predicate every gate reads: set by `slotform dev`, never by a
|
|
220
|
+
// deploy. Also what `ctx._devMode` carries to procedures.
|
|
221
|
+
function isDevMode(env: unknown): boolean {
|
|
222
|
+
return (
|
|
223
|
+
(env as Record<string, unknown> | null | undefined)?.SLOTFORM_DEV === "1"
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Asserts every baked env check against the live env. Throws the first
|
|
228
|
+
// violation by var name; the caller runs this once per isolate.
|
|
229
|
+
function assertEnvChecks(checks: EnvCheckSpec[], env: unknown): void {
|
|
230
|
+
const e = env as Record<string, unknown> | null | undefined;
|
|
231
|
+
const devMode = isDevMode(env);
|
|
232
|
+
for (const check of checks) {
|
|
233
|
+
const value = e?.[check.name];
|
|
234
|
+
if (!value) {
|
|
235
|
+
throw new Error(`Missing env var: ${check.name}`);
|
|
236
|
+
}
|
|
237
|
+
if (typeof value !== "string") continue;
|
|
238
|
+
if (check.minLength !== undefined && value.length < check.minLength) {
|
|
239
|
+
throw new Error(
|
|
240
|
+
`Env var ${check.name} must be at least ${check.minLength} characters (got ${value.length})`,
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
if (check.url || check.devLocalhost) {
|
|
244
|
+
let parsed: URL;
|
|
245
|
+
try {
|
|
246
|
+
parsed = new URL(value);
|
|
247
|
+
} catch {
|
|
248
|
+
// A `devLocalhost` check alone judges no value that is not a URL.
|
|
249
|
+
if (!check.url) continue;
|
|
250
|
+
throw new Error(`Env var ${check.name} must be a valid URL`);
|
|
251
|
+
}
|
|
252
|
+
if (check.devLocalhost && devMode && !isLocalOrigin(value)) {
|
|
253
|
+
throw new Error(
|
|
254
|
+
`Env var ${check.name} points at ${parsed.hostname} while SLOTFORM_DEV is set; refusing to serve. Unset SLOTFORM_DEV outside local dev.`,
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// The Workers execution context a job invocation received, narrowed to the
|
|
262
|
+
// one member a handler needs; a no-op where the runtime supplied none.
|
|
263
|
+
function workersContext(ctx: unknown): {
|
|
264
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
265
|
+
} {
|
|
266
|
+
const given = ctx as
|
|
267
|
+
| { waitUntil(promise: Promise<unknown>): void }
|
|
268
|
+
| null
|
|
269
|
+
| undefined;
|
|
270
|
+
if (typeof given?.waitUntil !== "function") return { waitUntil: () => {} };
|
|
271
|
+
return { waitUntil: (promise) => given.waitUntil(promise) };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export default function createWorker<TEnv = unknown>(
|
|
275
|
+
options?: ApiWorkerOptions,
|
|
276
|
+
): AppBuilder<BaseContext<TEnv>> {
|
|
277
|
+
const apiOptions: ResolvedApiOptions = {
|
|
278
|
+
prefix: "/rpc",
|
|
279
|
+
...options,
|
|
280
|
+
};
|
|
281
|
+
return createAppBuilder<BaseContext<TEnv>>([], apiOptions);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function createAppBuilder<
|
|
285
|
+
TContext extends Record<string, unknown>,
|
|
286
|
+
TPluginRoutes extends Record<string, unknown> = Record<never, never>,
|
|
287
|
+
>(
|
|
288
|
+
entries: UseEntry[],
|
|
289
|
+
apiOptions: ResolvedApiOptions,
|
|
290
|
+
): AppBuilder<TContext, TPluginRoutes> {
|
|
291
|
+
return {
|
|
292
|
+
use(
|
|
293
|
+
pluginOrFn:
|
|
294
|
+
| RuntimePlugin<string>
|
|
295
|
+
| MiddlewareHandler
|
|
296
|
+
| ((
|
|
297
|
+
ctx: TContext,
|
|
298
|
+
) => Record<string, unknown> | Promise<Record<string, unknown>>),
|
|
299
|
+
) {
|
|
300
|
+
if (typeof pluginOrFn === "function") {
|
|
301
|
+
const fn = pluginOrFn as (...args: unknown[]) => unknown;
|
|
302
|
+
const newEntries: UseEntry[] = isHonoMiddleware(fn)
|
|
303
|
+
? [...entries, { middleware: fn as MiddlewareHandler }]
|
|
304
|
+
: [
|
|
305
|
+
...entries,
|
|
306
|
+
{
|
|
307
|
+
fn: fn as (
|
|
308
|
+
ctx: Record<string, unknown>,
|
|
309
|
+
) => Record<string, unknown> | Promise<Record<string, unknown>>,
|
|
310
|
+
},
|
|
311
|
+
];
|
|
312
|
+
// biome-ignore lint/suspicious/noExplicitAny: context type grows dynamically
|
|
313
|
+
return createAppBuilder<any>(newEntries, apiOptions);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const plugin = pluginOrFn as RuntimePlugin<string>;
|
|
317
|
+
|
|
318
|
+
const existingKeys = new Set<string>();
|
|
319
|
+
for (const entry of entries) {
|
|
320
|
+
if (isPluginEntry(entry)) {
|
|
321
|
+
existingKeys.add(entry.plugin.name);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (existingKeys.has(plugin.name)) {
|
|
325
|
+
throw new Error(
|
|
326
|
+
`Context key collision: plugin "${plugin.name}" already registered`,
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const newEntries: UseEntry[] = [...entries, { plugin }];
|
|
331
|
+
// biome-ignore lint/suspicious/noExplicitAny: context type grows dynamically
|
|
332
|
+
return createAppBuilder<any>(newEntries, apiOptions);
|
|
333
|
+
},
|
|
334
|
+
|
|
335
|
+
useAfterContext(middleware: MiddlewareHandler) {
|
|
336
|
+
return createAppBuilder<TContext, TPluginRoutes>(
|
|
337
|
+
[...entries, { middleware, afterContext: true }],
|
|
338
|
+
apiOptions,
|
|
339
|
+
);
|
|
340
|
+
},
|
|
341
|
+
|
|
342
|
+
handler<TRoutes extends Record<string, unknown>>(
|
|
343
|
+
consumerRoutes?: TRoutes,
|
|
344
|
+
mount?: HandlerMount,
|
|
345
|
+
): WorkerExport<TPluginRoutes & TRoutes> {
|
|
346
|
+
const {
|
|
347
|
+
prefix: rpcPrefix,
|
|
348
|
+
cors: corsOrigin,
|
|
349
|
+
devCors: devCorsOrigin,
|
|
350
|
+
envChecks,
|
|
351
|
+
} = apiOptions;
|
|
352
|
+
|
|
353
|
+
// Once per isolate: the first request pays for value validation
|
|
354
|
+
// (length / URL-shape / dev-localhost refusal), every later request
|
|
355
|
+
// skips it. A failed run never sets the flag, so a misconfigured
|
|
356
|
+
// isolate keeps failing loudly instead of caching the miss.
|
|
357
|
+
let envChecked = false;
|
|
358
|
+
|
|
359
|
+
// The allow-list is resolved per request: docs/architecture/plugins/api.md, "At runtime".
|
|
360
|
+
const effectiveOrigins = (env: unknown): string[] => {
|
|
361
|
+
const origins =
|
|
362
|
+
devCorsOrigin?.length && isDevMode(env)
|
|
363
|
+
? [...(corsOrigin ?? []), ...devCorsOrigin]
|
|
364
|
+
: (corsOrigin ?? []);
|
|
365
|
+
const own = listenerOrigin(env);
|
|
366
|
+
return own === null || origins.includes(own)
|
|
367
|
+
? origins
|
|
368
|
+
: [...origins, own];
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
// Sort once at construction time so both the context-building loop
|
|
372
|
+
// and the fetch/routes loops below see plugins in dependency order,
|
|
373
|
+
// regardless of `.use()` registration order.
|
|
374
|
+
const sortedEntries = sortPluginEntries(entries);
|
|
375
|
+
const pluginEntries = sortedEntries.filter(isPluginEntry);
|
|
376
|
+
|
|
377
|
+
const procedure = createProcedure<TContext>();
|
|
378
|
+
|
|
379
|
+
let pluginRoutes: Record<string, unknown> = {};
|
|
380
|
+
// Route-key collisions name the owning plugin: docs/architecture/plugins/api.md, "Routes barrel".
|
|
381
|
+
const routeOwners = new Map<string, string>();
|
|
382
|
+
for (const entry of pluginEntries) {
|
|
383
|
+
const routes = entry.plugin.routes?.(procedure);
|
|
384
|
+
if (routes) {
|
|
385
|
+
for (const key of Object.keys(routes)) {
|
|
386
|
+
routeOwners.set(key, entry.plugin.name);
|
|
387
|
+
}
|
|
388
|
+
pluginRoutes = { ...pluginRoutes, ...routes };
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
if (consumerRoutes) {
|
|
393
|
+
for (const key of Object.keys(consumerRoutes)) {
|
|
394
|
+
const owner = routeOwners.get(key);
|
|
395
|
+
if (owner) {
|
|
396
|
+
throw new Error(
|
|
397
|
+
`createWorker: consumer routes key "${key}" collides with a route ` +
|
|
398
|
+
`namespace already registered by the "${owner}" plugin runtime. ` +
|
|
399
|
+
"Rename the consumer routes export.",
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// `.handler()` (no arg) and `.handler({})` are equivalent: the worker
|
|
406
|
+
// is a runnable shell that 404s every RPC call. Validating this at
|
|
407
|
+
// construction time is intentional — it lets a worker boot before
|
|
408
|
+
// any consumer routes have been authored.
|
|
409
|
+
const fullRouter = { ...pluginRoutes, ...(consumerRoutes ?? {}) };
|
|
410
|
+
|
|
411
|
+
// Resolved at construction, so a tool the endpoint cannot serve fails
|
|
412
|
+
// the boot, naming the tool.
|
|
413
|
+
const mcpRoute = mount?.mcp
|
|
414
|
+
? createMcpRoute(
|
|
415
|
+
createMcpEndpoint({
|
|
416
|
+
tools: buildMcpTools(consumerRoutes, mount.mcp),
|
|
417
|
+
instructions: mount.mcp.instructions,
|
|
418
|
+
name: mount.name,
|
|
419
|
+
}),
|
|
420
|
+
)
|
|
421
|
+
: null;
|
|
422
|
+
|
|
423
|
+
// biome-ignore lint/suspicious/noExplicitAny: oRPC RPCHandler expects internal router type
|
|
424
|
+
const rpcHandler = new RPCHandler(fullRouter as any, {
|
|
425
|
+
plugins: [new RequestHeadersPlugin(), new ResponseHeadersPlugin()],
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
const app = new Hono<{
|
|
429
|
+
Variables: {
|
|
430
|
+
__slotformCtx: Record<string, unknown>;
|
|
431
|
+
[ORIGINS_VAR]: string[];
|
|
432
|
+
};
|
|
433
|
+
}>();
|
|
434
|
+
|
|
435
|
+
// CORS mounts first, and an empty list throws: docs/architecture/plugins/api.md, "At runtime".
|
|
436
|
+
if (corsOrigin !== undefined) {
|
|
437
|
+
if (corsOrigin.length === 0) {
|
|
438
|
+
throw new Error(
|
|
439
|
+
"createWorker: cors was provided but is empty. Check app.domain / app.origins.",
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
app.use(
|
|
443
|
+
"*",
|
|
444
|
+
cors({
|
|
445
|
+
// A function, not the array: the allow-list depends on
|
|
446
|
+
// env (dev origins), which Hono only hands over per
|
|
447
|
+
// request. Wildcard keeps the array form's meaning:
|
|
448
|
+
// `["*"]` answers every origin with `*`.
|
|
449
|
+
origin: (requestOrigin, c) => {
|
|
450
|
+
const allowed = effectiveOrigins(c.env);
|
|
451
|
+
if (allowed.includes("*")) return "*";
|
|
452
|
+
return allowed.includes(requestOrigin) ? requestOrigin : null;
|
|
453
|
+
},
|
|
454
|
+
credentials: true,
|
|
455
|
+
exposeHeaders: [...SLOTFORM_EXPOSED_HEADERS],
|
|
456
|
+
}),
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
app.use("*", requestLogger());
|
|
460
|
+
app.use("*", secureHeaders());
|
|
461
|
+
|
|
462
|
+
// The liveness route precedes the context middleware: docs/architecture/runtime.md, "Request order".
|
|
463
|
+
app.get("/", (c) => c.json({ ok: true }));
|
|
464
|
+
|
|
465
|
+
// Consumer middleware before context injection: docs/architecture/runtime.md, "Request order".
|
|
466
|
+
for (const entry of sortedEntries) {
|
|
467
|
+
if (isMiddlewareEntry(entry) && !entry.afterContext) {
|
|
468
|
+
app.use("*", entry.middleware);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// The plugin context of one invocation: docs/architecture/runtime.md, "Request order".
|
|
473
|
+
const buildContext = async (
|
|
474
|
+
env: unknown,
|
|
475
|
+
base: Record<string, unknown>,
|
|
476
|
+
): Promise<Record<string, unknown>> => {
|
|
477
|
+
if (!envChecked && envChecks && envChecks.length > 0) {
|
|
478
|
+
assertEnvChecks(envChecks, env);
|
|
479
|
+
envChecked = true;
|
|
480
|
+
console.info(`[api] env checks passed (${envChecks.length} vars)`);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
for (const entry of pluginEntries) {
|
|
484
|
+
entry.plugin.validateEnv?.(env);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
let ctx: Record<string, unknown> = {
|
|
488
|
+
env,
|
|
489
|
+
...base,
|
|
490
|
+
_devMode: isDevMode(env),
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
for (const entry of sortedEntries) {
|
|
494
|
+
if (isPluginEntry(entry)) {
|
|
495
|
+
const provided = await entry.plugin.context(env, ctx);
|
|
496
|
+
ctx = { ...ctx, ...provided };
|
|
497
|
+
} else if (!isMiddlewareEntry(entry)) {
|
|
498
|
+
const extra = await entry.fn(ctx);
|
|
499
|
+
ctx = { ...ctx, ...extra };
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return ctx;
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
app.use("*", async (c, next) => {
|
|
506
|
+
const env = c.env;
|
|
507
|
+
const request = c.req.raw;
|
|
508
|
+
|
|
509
|
+
// `c.executionCtx` throws when the runtime supplied none (Node
|
|
510
|
+
// tests, `.handler({})` invoked without a Workers ctx). A no-op
|
|
511
|
+
// waitUntil is behaviorally correct outside Workers: the promise
|
|
512
|
+
// still runs, waitUntil only extends the worker's lifetime.
|
|
513
|
+
let executionCtx: { waitUntil(promise: Promise<unknown>): void };
|
|
514
|
+
try {
|
|
515
|
+
executionCtx = c.executionCtx;
|
|
516
|
+
} catch {
|
|
517
|
+
executionCtx = { waitUntil: () => {} };
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const ctx = await buildContext(env, {
|
|
521
|
+
httpRequest: request,
|
|
522
|
+
executionCtx,
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
for (const entry of pluginEntries) {
|
|
526
|
+
const fetchFn = entry.plugin.fetch;
|
|
527
|
+
if (typeof fetchFn !== "function") continue;
|
|
528
|
+
const claimed = await fetchFn(request, env, ctx);
|
|
529
|
+
if (claimed) return claimed;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
c.set(ORIGINS_VAR, effectiveOrigins(env));
|
|
533
|
+
c.set("__slotformCtx", ctx);
|
|
534
|
+
await next();
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
// Post-context middleware: docs/architecture/runtime.md, "Request order".
|
|
538
|
+
for (const entry of sortedEntries) {
|
|
539
|
+
if (isMiddlewareEntry(entry) && entry.afterContext) {
|
|
540
|
+
app.use("*", entry.middleware);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// Reads travel as GET: docs/architecture/plugins/api.md, "Reads travel as GET".
|
|
545
|
+
app.on(["GET", "POST"], `${rpcPrefix}/*`, async (c) => {
|
|
546
|
+
// A non-GET request must be `application/json`: docs/architecture/plugins/api.md, "Reads travel as GET".
|
|
547
|
+
const contentType = c.req.header("content-type")?.toLowerCase();
|
|
548
|
+
if (
|
|
549
|
+
c.req.method === "POST" &&
|
|
550
|
+
!contentType?.startsWith("application/json")
|
|
551
|
+
) {
|
|
552
|
+
return c.json({ code: "UNSUPPORTED_MEDIA_TYPE" }, 415);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const ctx = c.get("__slotformCtx");
|
|
556
|
+
|
|
557
|
+
if (await ipLimited(c, ctx)) {
|
|
558
|
+
return c.json({ code: "TOO_MANY_REQUESTS" }, 429);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const { matched, response } = await rpcHandler.handle(c.req.raw, {
|
|
562
|
+
prefix: rpcPrefix,
|
|
563
|
+
context: ctx,
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
if (matched) {
|
|
567
|
+
// A read's not found travels as a 200: docs/architecture/plugins/api.md, "Not found".
|
|
568
|
+
if (response.status === 404 && c.req.method === "GET") {
|
|
569
|
+
const headers = new Headers(response.headers);
|
|
570
|
+
headers.set(SLOTFORM_NOT_FOUND_HEADER, "1");
|
|
571
|
+
return c.newResponse(response.body, { status: 200, headers });
|
|
572
|
+
}
|
|
573
|
+
return c.newResponse(response.body, response);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
return c.json({ error: "Not found", code: "NOT_FOUND" }, 404);
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
if (mcpRoute) {
|
|
580
|
+
// The one MCP route: any other method is refused before anything
|
|
581
|
+
// else, and `POST` verifies its bearer token first.
|
|
582
|
+
app.post(MCP_PATH, (c) => mcpRoute(c, c.get("__slotformCtx")));
|
|
583
|
+
app.all(MCP_PATH, (c) => c.body(null, 405, { Allow: "POST" }));
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
app.onError((err, c) => {
|
|
587
|
+
if (err instanceof ORPCError) {
|
|
588
|
+
return c.json(
|
|
589
|
+
{ code: err.code, message: err.message },
|
|
590
|
+
{ status: err.status as ContentfulStatusCode },
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
console.error("API Error:", err);
|
|
595
|
+
return c.json(
|
|
596
|
+
{
|
|
597
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
598
|
+
message: "Internal Server Error",
|
|
599
|
+
},
|
|
600
|
+
500,
|
|
601
|
+
);
|
|
602
|
+
});
|
|
603
|
+
|
|
604
|
+
const honoFetch = app.fetch.bind(app);
|
|
605
|
+
const checkEnv = (env: unknown): void => {
|
|
606
|
+
const problems: string[] = [];
|
|
607
|
+
for (const check of envChecks ?? []) {
|
|
608
|
+
try {
|
|
609
|
+
assertEnvChecks([check], env);
|
|
610
|
+
} catch (error) {
|
|
611
|
+
problems.push(
|
|
612
|
+
error instanceof Error ? error.message : String(error),
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
for (const entry of pluginEntries) {
|
|
617
|
+
try {
|
|
618
|
+
entry.plugin.validateEnv?.(env);
|
|
619
|
+
} catch (error) {
|
|
620
|
+
const message =
|
|
621
|
+
error instanceof Error ? error.message : String(error);
|
|
622
|
+
if (!problems.includes(message)) problems.push(message);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
if (problems.length > 0) {
|
|
626
|
+
throw new Error(
|
|
627
|
+
`the environment is incomplete:\n${problems.map((line) => ` - ${line}`).join("\n")}`,
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
// A job's context is a request's without the request: docs/architecture/runtime.md, "Background handlers".
|
|
633
|
+
const jobContext = (env: unknown, ctx?: unknown) =>
|
|
634
|
+
buildContext(env, {
|
|
635
|
+
executionCtx: workersContext(ctx),
|
|
636
|
+
});
|
|
637
|
+
// A mounted handler declares its own context type (`never` here, so any
|
|
638
|
+
// handler is assignable); the compiler cannot relate it to the built one.
|
|
639
|
+
const queueRun = mount?.queue;
|
|
640
|
+
const scheduledRun = mount?.scheduled;
|
|
641
|
+
|
|
642
|
+
return {
|
|
643
|
+
fetch: (request, env, ctx) => honoFetch(request, env, ctx as undefined),
|
|
644
|
+
checkEnv,
|
|
645
|
+
jobContext,
|
|
646
|
+
...(queueRun
|
|
647
|
+
? {
|
|
648
|
+
queue: async (batch: JobBatch, env: unknown, ctx: unknown) =>
|
|
649
|
+
queueRun(batch, (await jobContext(env, ctx)) as never),
|
|
650
|
+
}
|
|
651
|
+
: {}),
|
|
652
|
+
...(scheduledRun
|
|
653
|
+
? {
|
|
654
|
+
scheduled: async (
|
|
655
|
+
controller: JobScheduledEvent,
|
|
656
|
+
env: unknown,
|
|
657
|
+
ctx: unknown,
|
|
658
|
+
) =>
|
|
659
|
+
scheduledRun(controller, (await jobContext(env, ctx)) as never),
|
|
660
|
+
}
|
|
661
|
+
: {}),
|
|
662
|
+
_router: fullRouter as TPluginRoutes & TRoutes,
|
|
663
|
+
};
|
|
664
|
+
},
|
|
665
|
+
} as AppBuilder<TContext>;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// The injected plugin context (`db`, `auth`, `env`, …), for post-context
|
|
669
|
+
// middleware and raw Hono routes. Annotate the call with the generated
|
|
670
|
+
// `WorkerContext` to get the same typed context a procedure handler sees.
|
|
671
|
+
export function slotformContext<
|
|
672
|
+
TContext extends Record<string, unknown> = BaseContext,
|
|
673
|
+
>(c: Context): TContext {
|
|
674
|
+
const ctx = c.get("__slotformCtx") as TContext | undefined;
|
|
675
|
+
if (!ctx) {
|
|
676
|
+
throw new Error(
|
|
677
|
+
"slotformContext: no context on this request. Register the middleware with .useAfterContext() (src/worker/middleware.context.ts), not .use().",
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
return ctx;
|
|
681
|
+
}
|