@mandujs/core 0.30.0 → 0.31.0

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.
@@ -0,0 +1,443 @@
1
+ /**
2
+ * Mandu Typed RPC — Server Side
3
+ *
4
+ * tRPC-like end-to-end typed RPC built on Mandu's existing contract +
5
+ * client layer. No external tRPC dependency. Zod contracts on the
6
+ * server flow through to auto-typed client proxies.
7
+ *
8
+ * Phase 18.κ — see `docs/architect/typed-rpc.md` for the comparison
9
+ * against tRPC / SvelteKit form actions / Next.js server actions plus
10
+ * the migration recipe.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ import type { z } from "zod";
16
+
17
+ // ========== Types ==========
18
+
19
+ /**
20
+ * Per-procedure call context.
21
+ *
22
+ * `input` is the Zod-parsed, validated request body (or `undefined`
23
+ * when the procedure declares no `input` schema). `request` is the
24
+ * raw Fetch `Request` so procedures can read cookies / headers. `ctx`
25
+ * is a free-form object threaded from the dispatcher — Phase 18.κ
26
+ * ships an empty object by default; session / DB / user wiring is
27
+ * layered on via `ManduConfig.rpc.context` in a future patch.
28
+ */
29
+ export interface RpcContext<TInput = unknown, TCtx = Record<string, unknown>> {
30
+ /** Validated input (parsed by the procedure's `input` Zod schema). */
31
+ input: TInput;
32
+ /** Raw Fetch Request — cookies / headers / auth state. */
33
+ request: Request;
34
+ /** Per-request context (session, db, user, …). */
35
+ ctx: TCtx;
36
+ }
37
+
38
+ /**
39
+ * A single RPC procedure definition.
40
+ *
41
+ * Each procedure pairs an `input` schema (optional — allow
42
+ * parameter-less RPCs), an `output` schema (required — the contract
43
+ * guarantee), and a `handler` function. `handler` receives the
44
+ * validated input + the raw Request + a shared context object and
45
+ * returns the output shape; the dispatcher validates the return
46
+ * value against `output` before shipping.
47
+ */
48
+ export interface RpcProcedure<
49
+ TInputSchema extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined,
50
+ TOutputSchema extends z.ZodTypeAny = z.ZodTypeAny,
51
+ TCtx extends Record<string, unknown> = Record<string, unknown>,
52
+ > {
53
+ /** Zod schema for procedure input. `undefined` for no-arg procedures. */
54
+ input?: TInputSchema;
55
+ /** Zod schema for the return value (response body). */
56
+ output: TOutputSchema;
57
+ /** Procedure body. Receives validated input + request + shared ctx. */
58
+ handler: (
59
+ args: RpcContext<
60
+ TInputSchema extends z.ZodTypeAny ? z.infer<TInputSchema> : undefined,
61
+ TCtx
62
+ >
63
+ ) => Promise<z.infer<TOutputSchema>> | z.infer<TOutputSchema>;
64
+ }
65
+
66
+ /** Record of procedures — the raw user input to {@link defineRpc}. */
67
+ export type RpcProcedureRecord = Record<
68
+ string,
69
+ RpcProcedure<z.ZodTypeAny | undefined, z.ZodTypeAny>
70
+ >;
71
+
72
+ /**
73
+ * Tagged RPC definition — the return value of {@link defineRpc}.
74
+ *
75
+ * The `__rpc` brand lets the client proxy and the route dispatcher
76
+ * distinguish RPC definitions from plain contract objects without
77
+ * reaching for `instanceof`.
78
+ */
79
+ export interface RpcDefinition<TProcedures extends RpcProcedureRecord = RpcProcedureRecord> {
80
+ /** The raw procedure record (used by both server dispatch and client proxy). */
81
+ procedures: TProcedures;
82
+ /** Brand — distinguishes RPC defs from contract objects. */
83
+ readonly __rpc: true;
84
+ }
85
+
86
+ /**
87
+ * Client-facing type derived from a {@link RpcDefinition}.
88
+ *
89
+ * Maps each procedure key to a function whose argument is the Zod
90
+ * input type (or `undefined`/no-arg for procedures without input)
91
+ * and whose return is `Promise<Output>`. Used by
92
+ * `createRpcClient<typeof postsRpc>()`.
93
+ */
94
+ export type RpcClient<TDef extends RpcDefinition<RpcProcedureRecord>> = {
95
+ [K in keyof TDef["procedures"]]: TDef["procedures"][K]["input"] extends z.ZodTypeAny
96
+ ? (input: z.infer<TDef["procedures"][K]["input"]>) => Promise<z.infer<TDef["procedures"][K]["output"]>>
97
+ : (input?: undefined) => Promise<z.infer<TDef["procedures"][K]["output"]>>;
98
+ };
99
+
100
+ // ========== Core API ==========
101
+
102
+ /**
103
+ * Define a tRPC-style typed RPC module.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * import { z } from "zod";
108
+ * import { defineRpc } from "@mandujs/core/contract/rpc";
109
+ *
110
+ * export const postsRpc = defineRpc({
111
+ * list: {
112
+ * input: z.object({ limit: z.number().optional() }).optional(),
113
+ * output: z.array(z.object({ id: z.string(), title: z.string() })),
114
+ * handler: async ({ input }) => db.posts.findMany({ limit: input?.limit ?? 10 }),
115
+ * },
116
+ * get: {
117
+ * input: z.object({ id: z.string() }),
118
+ * output: z.object({ id: z.string(), title: z.string(), body: z.string() }),
119
+ * handler: async ({ input }) => db.posts.findUnique({ where: { id: input.id } }),
120
+ * },
121
+ * });
122
+ * ```
123
+ *
124
+ * Wire to a server by passing to {@link registerRpc} (or via
125
+ * `ManduConfig.rpc.endpoints`). Requests resolve to
126
+ * `POST /api/rpc/<name>/<method>` where `<name>` is the endpoint key.
127
+ */
128
+ export function defineRpc<TProcedures extends RpcProcedureRecord>(
129
+ procedures: TProcedures
130
+ ): RpcDefinition<TProcedures> {
131
+ // Validate each procedure shape at define-time so a missing `output`
132
+ // or `handler` fails fast with a readable message instead of a
133
+ // runtime NPE inside the dispatcher.
134
+ for (const [key, proc] of Object.entries(procedures)) {
135
+ if (!proc || typeof proc !== "object") {
136
+ throw new Error(
137
+ `[Mandu RPC] Procedure "${key}" is not an object. Each procedure must be { input?, output, handler }.`
138
+ );
139
+ }
140
+ if (typeof proc.handler !== "function") {
141
+ throw new Error(
142
+ `[Mandu RPC] Procedure "${key}" is missing a handler function.`
143
+ );
144
+ }
145
+ if (!proc.output || typeof (proc.output as z.ZodTypeAny).safeParse !== "function") {
146
+ throw new Error(
147
+ `[Mandu RPC] Procedure "${key}" is missing an output Zod schema.`
148
+ );
149
+ }
150
+ if (proc.input !== undefined && typeof (proc.input as z.ZodTypeAny).safeParse !== "function") {
151
+ throw new Error(
152
+ `[Mandu RPC] Procedure "${key}" has an invalid input schema (not a Zod type).`
153
+ );
154
+ }
155
+ }
156
+
157
+ return {
158
+ procedures,
159
+ __rpc: true,
160
+ };
161
+ }
162
+
163
+ // ========== Registry ==========
164
+
165
+ /**
166
+ * Global RPC endpoint registry.
167
+ *
168
+ * Keyed by endpoint name (the `<name>` in `/api/rpc/<name>/<method>`).
169
+ * Populated by {@link registerRpc} (typically at boot via
170
+ * `ManduConfig.rpc.endpoints`) and consumed by the dispatcher in
171
+ * `runtime/server.ts`.
172
+ */
173
+ const rpcRegistry = new Map<string, RpcDefinition<RpcProcedureRecord>>();
174
+
175
+ /**
176
+ * Register an RPC endpoint under `name`.
177
+ *
178
+ * Same name twice overwrites (HMR-friendly). Pass `null` / `undefined`
179
+ * to clear a registration. Typically called automatically from
180
+ * `startServer` when `ManduConfig.rpc.endpoints` is set, but public
181
+ * so user code can register additional endpoints at runtime.
182
+ */
183
+ export function registerRpc(
184
+ name: string,
185
+ definition: RpcDefinition<RpcProcedureRecord>
186
+ ): void {
187
+ if (!definition?.__rpc) {
188
+ throw new Error(
189
+ `[Mandu RPC] registerRpc("${name}", …) expected a defineRpc() result, got ${typeof definition}.`
190
+ );
191
+ }
192
+ rpcRegistry.set(name, definition);
193
+ }
194
+
195
+ /** Look up an RPC endpoint by name. Returns `undefined` on miss. */
196
+ export function getRpc(name: string): RpcDefinition<RpcProcedureRecord> | undefined {
197
+ return rpcRegistry.get(name);
198
+ }
199
+
200
+ /** Clear all RPC registrations (test helper). */
201
+ export function clearRpcRegistry(): void {
202
+ rpcRegistry.clear();
203
+ }
204
+
205
+ /** Enumerate registered endpoint names. */
206
+ export function listRpcEndpoints(): string[] {
207
+ return Array.from(rpcRegistry.keys());
208
+ }
209
+
210
+ // ========== Dispatch ==========
211
+
212
+ /**
213
+ * Shape of the JSON envelope that flows over the wire.
214
+ *
215
+ * Mirrors {@link RpcWireError} for the failure case — the client
216
+ * proxy inspects `ok` and unwraps `data` or throws {@link RpcCallError}.
217
+ */
218
+ export type RpcWireEnvelope<T = unknown> =
219
+ | { ok: true; data: T }
220
+ | { ok: false; error: RpcWireError };
221
+
222
+ export interface RpcWireError {
223
+ /** Machine-readable code: `INPUT_INVALID` | `OUTPUT_INVALID` | `NOT_FOUND` | `HANDLER_ERROR` | `METHOD_NOT_ALLOWED` | `BAD_JSON`. */
224
+ code: string;
225
+ /** Human-readable message (generic in prod, full in dev). */
226
+ message: string;
227
+ /** Optional field-level issues for `INPUT_INVALID` / `OUTPUT_INVALID`. */
228
+ issues?: Array<{ path: (string | number)[]; message: string; code?: string }>;
229
+ }
230
+
231
+ /**
232
+ * Match `/api/rpc/<name>/<method>` — the canonical RPC URL shape.
233
+ * Returns `null` for any path that is not an RPC call, so the
234
+ * dispatcher can fall through to the normal route matcher.
235
+ *
236
+ * `<name>` and `<method>` are restricted to `[A-Za-z0-9_-]+` to
237
+ * prevent path-traversal style abuse of the lookup key.
238
+ */
239
+ export function matchRpcPath(
240
+ pathname: string
241
+ ): { endpoint: string; method: string } | null {
242
+ if (!pathname.startsWith("/api/rpc/")) return null;
243
+ const rest = pathname.slice("/api/rpc/".length);
244
+ // Only two non-empty segments; reject nested paths.
245
+ const parts = rest.split("/");
246
+ if (parts.length !== 2) return null;
247
+ const [endpoint, method] = parts;
248
+ if (!endpoint || !method) return null;
249
+ if (!/^[A-Za-z0-9_-]+$/.test(endpoint)) return null;
250
+ if (!/^[A-Za-z0-9_-]+$/.test(method)) return null;
251
+ return { endpoint, method };
252
+ }
253
+
254
+ /**
255
+ * Serialize a Zod error to the wire-level `issues` array.
256
+ */
257
+ function zodIssues(err: z.ZodError): RpcWireError["issues"] {
258
+ return err.errors.map((iss) => ({
259
+ path: iss.path,
260
+ message: iss.message,
261
+ code: iss.code,
262
+ }));
263
+ }
264
+
265
+ function jsonResponse(envelope: RpcWireEnvelope, status: number): Response {
266
+ return new Response(JSON.stringify(envelope), {
267
+ status,
268
+ headers: { "Content-Type": "application/json; charset=utf-8" },
269
+ });
270
+ }
271
+
272
+ /**
273
+ * Dispatch an RPC call.
274
+ *
275
+ * Handles (in order): method gate (POST only), endpoint lookup,
276
+ * procedure lookup, input parse + validate, handler invocation,
277
+ * output validate, response shaping. Every failure path returns a
278
+ * structured {@link RpcWireEnvelope} — callers do not throw.
279
+ *
280
+ * `isDev` toggles whether handler errors include the raw message +
281
+ * stack. In prod (`isDev === false`) we return a generic
282
+ * `"Internal RPC error"` to avoid leaking stack frames.
283
+ */
284
+ export async function dispatchRpc(
285
+ req: Request,
286
+ endpoint: string,
287
+ method: string,
288
+ options: { isDev?: boolean; ctx?: Record<string, unknown> } = {}
289
+ ): Promise<Response> {
290
+ const isDev = options.isDev ?? false;
291
+ const sharedCtx = options.ctx ?? {};
292
+
293
+ if (req.method !== "POST") {
294
+ return jsonResponse(
295
+ {
296
+ ok: false,
297
+ error: {
298
+ code: "METHOD_NOT_ALLOWED",
299
+ message: `RPC endpoints accept POST only (got ${req.method}).`,
300
+ },
301
+ },
302
+ 405
303
+ );
304
+ }
305
+
306
+ const definition = rpcRegistry.get(endpoint);
307
+ if (!definition) {
308
+ return jsonResponse(
309
+ {
310
+ ok: false,
311
+ error: {
312
+ code: "NOT_FOUND",
313
+ message: `Unknown RPC endpoint "${endpoint}".`,
314
+ },
315
+ },
316
+ 404
317
+ );
318
+ }
319
+
320
+ const procedure = definition.procedures[method];
321
+ if (!procedure) {
322
+ return jsonResponse(
323
+ {
324
+ ok: false,
325
+ error: {
326
+ code: "NOT_FOUND",
327
+ message: `RPC endpoint "${endpoint}" has no procedure "${method}".`,
328
+ },
329
+ },
330
+ 404
331
+ );
332
+ }
333
+
334
+ // ---- Parse body ----
335
+ let rawBody: unknown = undefined;
336
+ const contentLength = req.headers.get("content-length");
337
+ const hasBody = contentLength !== "0" && req.headers.get("content-type")?.includes("application/json");
338
+ if (hasBody) {
339
+ try {
340
+ const text = await req.text();
341
+ if (text.length > 0) {
342
+ rawBody = JSON.parse(text);
343
+ }
344
+ } catch (err) {
345
+ return jsonResponse(
346
+ {
347
+ ok: false,
348
+ error: {
349
+ code: "BAD_JSON",
350
+ message: `Request body is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,
351
+ },
352
+ },
353
+ 400
354
+ );
355
+ }
356
+ }
357
+
358
+ // Wire envelope: { input: <value> } — matches createRpcClient output.
359
+ const rawInput = rawBody && typeof rawBody === "object" && rawBody !== null && "input" in rawBody
360
+ ? (rawBody as { input: unknown }).input
361
+ : rawBody;
362
+
363
+ // ---- Validate input ----
364
+ let parsedInput: unknown = undefined;
365
+ if (procedure.input) {
366
+ const result = procedure.input.safeParse(rawInput);
367
+ if (!result.success) {
368
+ return jsonResponse(
369
+ {
370
+ ok: false,
371
+ error: {
372
+ code: "INPUT_INVALID",
373
+ message: "Input failed schema validation.",
374
+ issues: zodIssues(result.error),
375
+ },
376
+ },
377
+ 400
378
+ );
379
+ }
380
+ parsedInput = result.data;
381
+ }
382
+
383
+ // ---- Invoke handler ----
384
+ let handlerResult: unknown;
385
+ try {
386
+ handlerResult = await procedure.handler({
387
+ input: parsedInput as never,
388
+ request: req,
389
+ ctx: sharedCtx,
390
+ });
391
+ } catch (err) {
392
+ const message =
393
+ isDev && err instanceof Error
394
+ ? err.message
395
+ : "Internal RPC error";
396
+ if (isDev) {
397
+ // Dev mode: surface the stack on the server console so the
398
+ // user can debug without peering at network tab payloads.
399
+ console.error(
400
+ `[Mandu RPC] handler error in ${endpoint}.${method}:`,
401
+ err
402
+ );
403
+ }
404
+ return jsonResponse(
405
+ {
406
+ ok: false,
407
+ error: {
408
+ code: "HANDLER_ERROR",
409
+ message,
410
+ },
411
+ },
412
+ 500
413
+ );
414
+ }
415
+
416
+ // ---- Validate output ----
417
+ const outResult = procedure.output.safeParse(handlerResult);
418
+ if (!outResult.success) {
419
+ // Output-schema mismatch is a programmer bug (server returned
420
+ // wrong shape). Log loud in dev; return a generic 500 in prod.
421
+ if (isDev) {
422
+ console.error(
423
+ `[Mandu RPC] output validation failed in ${endpoint}.${method}:`,
424
+ outResult.error.errors
425
+ );
426
+ }
427
+ return jsonResponse(
428
+ {
429
+ ok: false,
430
+ error: {
431
+ code: "OUTPUT_INVALID",
432
+ message: isDev
433
+ ? "Handler returned a value that does not match the output schema."
434
+ : "Internal RPC error",
435
+ issues: isDev ? zodIssues(outResult.error) : undefined,
436
+ },
437
+ },
438
+ 500
439
+ );
440
+ }
441
+
442
+ return jsonResponse({ ok: true, data: outResult.data }, 200);
443
+ }
@@ -29,6 +29,13 @@ export {
29
29
  rateLimitMiddleware,
30
30
  } from "./bridge";
31
31
 
32
+ export {
33
+ schedulerCron,
34
+ setActiveSchedulerRegistration,
35
+ getActiveSchedulerRegistration,
36
+ type SchedulerCronMiddlewareOptions,
37
+ } from "./scheduler-cron";
38
+
32
39
  export { cors, type CorsMiddlewareOptions } from "./cors";
33
40
  export { jwt, type JwtMiddlewareOptions } from "./jwt";
34
41
  export { csrf, type CsrfMiddlewareOptions } from "./csrf";
@@ -0,0 +1,96 @@
1
+ /**
2
+ * `scheduler-cron` — request-level middleware that exposes the running
3
+ * scheduler registration on `ctx` so handlers can inspect job status or
4
+ * trigger an ad-hoc tick for debugging.
5
+ *
6
+ * This is intentionally a thin bridge — the cron jobs themselves are
7
+ * defined with {@link import("../scheduler").defineCron} and started at
8
+ * `startServer()` boot time. The middleware does NOT start or stop the
9
+ * scheduler; its only job is to make the `CronRegistration` handle
10
+ * available to downstream request handlers (e.g., an observability
11
+ * dashboard API that wants to render `status()`).
12
+ *
13
+ * The middleware is opt-in — it's NOT part of the default chain. Add it
14
+ * to `mandu.config.ts` `middleware: [...]` only if you have a route that
15
+ * needs `ctx.scheduler`.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * // mandu.config.ts
20
+ * import { defineConfig } from "@mandujs/core";
21
+ * import { schedulerCron } from "@mandujs/core/middleware";
22
+ * import { jobs } from "./jobs";
23
+ *
24
+ * export default defineConfig({
25
+ * scheduler: { jobs },
26
+ * middleware: [schedulerCron()],
27
+ * });
28
+ * ```
29
+ */
30
+
31
+ import { defineMiddleware } from "./define";
32
+ import type { Middleware } from "./define";
33
+ import type { CronRegistration } from "../scheduler";
34
+
35
+ /**
36
+ * Global handle to the active {@link CronRegistration}, set by
37
+ * `startServer()` when it boots the scheduler. `scheduler-cron` middleware
38
+ * reads this slot on every request so the registration is always the one
39
+ * actually running.
40
+ *
41
+ * We store it on `globalThis` rather than module-scope so that multiple
42
+ * bundles (e.g., `@mandujs/core` loaded twice in a monorepo hot-reload)
43
+ * still see the same handle — matches the registry pattern in
44
+ * `runtime/server.ts`.
45
+ */
46
+ const GLOBAL_KEY = "__MANDU_SCHEDULER_REGISTRATION__";
47
+
48
+ interface SchedulerGlobal {
49
+ [GLOBAL_KEY]?: CronRegistration | null;
50
+ }
51
+
52
+ export function setActiveSchedulerRegistration(reg: CronRegistration | null): void {
53
+ (globalThis as unknown as SchedulerGlobal)[GLOBAL_KEY] = reg;
54
+ }
55
+
56
+ export function getActiveSchedulerRegistration(): CronRegistration | null {
57
+ return (globalThis as unknown as SchedulerGlobal)[GLOBAL_KEY] ?? null;
58
+ }
59
+
60
+ export interface SchedulerCronMiddlewareOptions {
61
+ /**
62
+ * Custom header to stamp on the response with the current scheduler job
63
+ * count. Useful for smoke-checking that the scheduler is running in a
64
+ * given environment. Default: no header is added.
65
+ */
66
+ statusHeader?: string;
67
+ }
68
+
69
+ /**
70
+ * Creates a middleware that exposes the scheduler registration via a response
71
+ * header and (optionally) stamps a status header. The registration itself is
72
+ * wired into `ctx` via the request-level composition chain — downstream
73
+ * code reads it with {@link getActiveSchedulerRegistration}.
74
+ */
75
+ export function schedulerCron(options: SchedulerCronMiddlewareOptions = {}): Middleware {
76
+ return defineMiddleware({
77
+ name: "scheduler-cron",
78
+ async handler(_req, next) {
79
+ const response = await next();
80
+ const reg = getActiveSchedulerRegistration();
81
+ if (reg && options.statusHeader) {
82
+ const status = reg.status();
83
+ const jobCount = Object.keys(status).length;
84
+ // Clone headers to avoid mutating an immutable response body.
85
+ const headers = new Headers(response.headers);
86
+ headers.set(options.statusHeader, String(jobCount));
87
+ return new Response(response.body, {
88
+ status: response.status,
89
+ statusText: response.statusText,
90
+ headers,
91
+ });
92
+ }
93
+ return response;
94
+ },
95
+ });
96
+ }