@arbol-ai/maximus 7.4.0 → 8.0.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.
Files changed (137) hide show
  1. package/README.md +36 -38
  2. package/bin/maximus.js +4 -0
  3. package/config/oxfmt.mjs +1 -0
  4. package/config/oxlint.mjs +10 -0
  5. package/dist/analytics/analytics.d.ts +21 -9
  6. package/dist/analytics/analytics.js +19 -5
  7. package/dist/body.d.ts +1 -1
  8. package/dist/body.js +2 -2
  9. package/dist/chunks/agent-skills-Ef65jTf_.js +49 -0
  10. package/dist/chunks/agent-skills-m7y1EUch.js +3 -0
  11. package/dist/chunks/{body-6LichrQm.js → body-DOIHwIIl.js} +14 -7
  12. package/dist/chunks/{correlation-BEkcFFGT.js → correlation-4b23a-a4.js} +8 -5
  13. package/dist/chunks/define-app-x7uY70_1.js +341 -0
  14. package/dist/chunks/{errors-D7zG9kx9.js → errors-C5w9WY1l.js} +10 -5
  15. package/dist/chunks/{execution-kVUJPy1A.js → execution-rOiLo8VG.js} +28 -15
  16. package/dist/chunks/generate-C-9FKW0o.js +197 -0
  17. package/dist/chunks/handler-iebR-urt.js +141 -0
  18. package/dist/chunks/http-layout-DS8DnPyu.js +128 -0
  19. package/dist/chunks/{http-paths-yKD6TSNJ.js → http-paths-DMBxwpp6.js} +50 -31
  20. package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
  21. package/dist/chunks/names-ncD7A3DV.js +280 -0
  22. package/dist/chunks/openapi-CeolxIqa.js +1588 -0
  23. package/dist/chunks/openapi-file-Bz9FRaE6.js +83 -0
  24. package/dist/chunks/pages-iZTvFs5a.js +14 -0
  25. package/dist/chunks/prepare-configured-BmRJLg6J.js +3 -0
  26. package/dist/chunks/prepare-configured-Cithjf80.js +52 -0
  27. package/dist/chunks/project-files-C0OX7MQQ.js +130 -0
  28. package/dist/chunks/query-kind-CWKAXEME.js +40 -0
  29. package/dist/chunks/record-DQUDTpEA.js +10 -0
  30. package/dist/chunks/result-CKgZHrnj.js +56 -0
  31. package/dist/chunks/{runtime-DlqA7J38.js → runtime-D94vx21X.js} +50 -26
  32. package/dist/chunks/scaffold-DGrcjR3h.js +3 -0
  33. package/dist/chunks/scaffold-DZD6dfoZ.js +138 -0
  34. package/dist/chunks/{schemas-CzTvbXb6.js → schemas-p_aRcMC1.js} +30 -14
  35. package/dist/chunks/server-Bzf1Q1_4.js +410 -0
  36. package/dist/chunks/src-CPrJpbOM.js +573 -0
  37. package/dist/chunks/{standard-failures-CLjxS2ea.js → standard-failures-Lh4mSfwG.js} +1 -1
  38. package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
  39. package/dist/chunks/{types-DQdfRF3f.d.ts → types-DTIuIEJ-.d.ts} +1000 -342
  40. package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
  41. package/dist/chunks/workers-types-BRk_Xa_5.d.ts +143 -0
  42. package/dist/chunks/yaml-Dk2L24yQ.js +74 -0
  43. package/dist/diagnostics.d.ts +6 -4
  44. package/dist/diagnostics.js +2 -2
  45. package/dist/errors.d.ts +2 -2
  46. package/dist/errors.js +2 -2
  47. package/dist/http-paths.d.ts +1 -1
  48. package/dist/http-paths.js +1 -1
  49. package/dist/index.d.ts +2 -2
  50. package/dist/index.js +12 -11
  51. package/dist/internals.d.ts +1 -1
  52. package/dist/internals.js +5 -4
  53. package/dist/mcp/index.d.ts +3 -2
  54. package/dist/mcp/index.js +5 -387
  55. package/dist/postgres/index.d.ts +25 -8
  56. package/dist/postgres/index.js +17 -8
  57. package/dist/project/config.d.ts +110 -72
  58. package/dist/project/config.js +161 -45
  59. package/dist/project/index.d.ts +17 -4
  60. package/dist/project/index.js +44 -9
  61. package/dist/projection.d.ts +14 -13
  62. package/dist/projection.js +8 -32
  63. package/dist/schemas.d.ts +1 -1
  64. package/dist/schemas.js +2 -2
  65. package/dist/standard-failures.d.ts +2 -89
  66. package/dist/standard-failures.js +1 -1
  67. package/dist/tooling/cli.js +149 -105
  68. package/dist/tooling/testing.js +2 -2
  69. package/dist/vite/cloudflare-workers.js +25 -0
  70. package/dist/vite/index.d.ts +157 -0
  71. package/dist/vite/index.js +1477 -0
  72. package/dist/webhooks.d.ts +12 -10
  73. package/dist/webhooks.js +26 -12
  74. package/dist/workers/runtime.d.ts +1 -1
  75. package/dist/workers/runtime.js +1 -1
  76. package/package.json +26 -22
  77. package/skills/maximus/SKILL.md +165 -68
  78. package/skills/maximus/references/deploying.md +73 -0
  79. package/skills/maximus/references/errors-and-results.md +114 -55
  80. package/skills/maximus/references/project.md +202 -0
  81. package/skills/maximus/references/routes-and-tools.md +256 -0
  82. package/skills/maximus/references/testing.md +137 -50
  83. package/skills/maximus/references/transports.md +113 -100
  84. package/skills/maximus/references/writing-code.md +84 -0
  85. package/templates/mcp/mcp/instructions.md.template +2 -0
  86. package/templates/mcp/routes/v1/greeting.get.ts.template +12 -0
  87. package/templates/mcp/tests/mcp.test.ts.template +36 -0
  88. package/templates/project/.agents/skills/project/SKILL.md.template +21 -12
  89. package/templates/project/.github/workflows/ci.yml.template +4 -1
  90. package/templates/project/CLAUDE.md.template +41 -25
  91. package/templates/project/README.md.template +54 -48
  92. package/templates/project/middleware/10-response.ts.template +5 -2
  93. package/templates/project/package.json.template +13 -9
  94. package/templates/project/pages/index.ts.template +2 -4
  95. package/templates/project/routes/v1/greeting.get.ts.template +10 -0
  96. package/templates/project/routes/v1/greeting.post.ts.template +12 -0
  97. package/templates/project/tests/greeting.test.ts.template +45 -0
  98. package/templates/project/tsconfig.json.template +8 -6
  99. package/templates/project/vite.config.ts.template +15 -7
  100. package/templates/web/app/main.tsx.template +16 -0
  101. package/templates/web/app/root.tsx.template +17 -0
  102. package/templates/web/app/routes/index.tsx.template +9 -0
  103. package/templates/web/index.html.template +12 -0
  104. package/templates/web/package.json.template +12 -0
  105. package/templates/web/tsconfig.json.template +7 -0
  106. package/templates/web/vite.config.ts.template +22 -0
  107. package/dist/chunks/builder-BiXv7d2v.js +0 -100
  108. package/dist/chunks/define-app-DvD_1jUE.js +0 -625
  109. package/dist/chunks/prepare-project-CMyGSEtI.js +0 -236
  110. package/dist/chunks/prepare-project-MtS0-W_n.js +0 -3
  111. package/dist/chunks/record-DY-lX9w1.js +0 -34
  112. package/dist/chunks/src-N3oyx5QF.js +0 -1091
  113. package/dist/client/client.d.ts +0 -129
  114. package/dist/client/client.js +0 -321
  115. package/dist/tooling/vite.d.ts +0 -3
  116. package/dist/tooling/vite.js +0 -57
  117. package/skills/maximus/references/adding-an-operation.md +0 -179
  118. package/skills/maximus/references/building-a-service.md +0 -167
  119. package/skills/maximus/references/migration-from-v2.md +0 -62
  120. package/skills/maximus/references/migration-to-v5.md +0 -37
  121. package/skills/maximus/references/publishing-and-verification.md +0 -42
  122. package/templates/project/cloudflare.config.ts.template +0 -24
  123. package/templates/project/maximus.config.ts.template +0 -20
  124. package/templates/project/routes/v1/greeting.ts.template +0 -38
  125. package/templates/service/.agents/skills/project/SKILL.md.template +0 -10
  126. package/templates/service/.github/workflows/ci.yml.template +0 -21
  127. package/templates/service/.gitignore.template +0 -9
  128. package/templates/service/CLAUDE.md.template +0 -5
  129. package/templates/service/README.md.template +0 -45
  130. package/templates/service/cloudflare.config.ts.template +0 -30
  131. package/templates/service/package.json.template +0 -36
  132. package/templates/service/src/app.ts.template +0 -30
  133. package/templates/service/src/index.ts.template +0 -13
  134. package/templates/service/tests/contract.test.ts.template +0 -12
  135. package/templates/service/tsconfig.json.template +0 -16
  136. package/templates/service/vite.config.ts.template +0 -13
  137. package/templates/service/vitest.config.ts.template +0 -10
@@ -1,101 +1,139 @@
1
- import { A as HttpMiddleware, Bt as Invocation, Dn as BinaryBody, En as StaticDecode$1, Ft as KnownOperationFields, Gt as OperationMiddleware, It as OperationFields, Nt as ApplicationBuilder, Pt as ApplicationConfiguration, Rn as Failure, Rt as AppManifest, kn as Result, n as WorkerOptions, qt as OperationShape, zn as FailureData, zt as Exposure } from "../chunks/types-DQdfRF3f.js";
2
- import { Static, TSchema } from "@sinclair/typebox";
3
- type RouteExposure = Omit<Exposure, 'http'> & {
4
- http?: Omit<NonNullable<Exposure['http']>, 'method' | 'path'>;
5
- };
6
- type Definition<I extends TSchema, O extends TSchema, X extends RouteExposure> = X & OperationFields<I, O>;
7
- type KnownRouteFields<X> = KnownOperationFields<X> & (X extends {
8
- http: infer H;
1
+ import { Gt as ToolDeclaration, Lt as HandlerDeclaration, T as HttpMiddleware, an as Invocation, dn as OperationMiddleware, en as ApplicationBuilder, in as Exposure, jt as ContextDeclaration, pn as OperationShape, rn as AppManifest, un as OperationHandler } from "../chunks/types-DTIuIEJ-.js";
2
+ import { TSchema } from "@sinclair/typebox";
3
+ /** A route's HTTP method. */
4
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
5
+ /**
6
+ * A route's operation name: `GET /v1/notes` is `listNotes`, `GET /v1/notes/{noteId}` is `getNote`,
7
+ * `POST /v1/notes` is `createNote`, `PATCH /v1/notes/{noteId}` is `updateNote`,
8
+ * `POST /v1/notes/{noteId}/archive` is `archiveNote` and `GET /v1/days/{date}/slots` is `listDaySlots`. A
9
+ * version other than 1 ends the name: `GET /v2/notes` is `listNotesV2`.
10
+ */
11
+ export declare function routeName(method: HttpMethod, path: string): string;
12
+ /** A segment or parameter name in PascalCase: `task-lists` and `task_lists` are `TaskLists`. */
13
+ type Word<S extends string> = S extends `${infer Head}-${infer Tail}` ? `${Word<Head>}${Word<Tail>}` : S extends `${infer Head}_${infer Tail}` ? `${Word<Head>}${Word<Tail>}` : Capitalize<S>;
14
+ /** A tool's operation name: the file `summarize-tasks` is `summarizeTasks`. */
15
+ type ToolName<F extends string> = Uncapitalize<Word<F>>;
16
+ /** A tool's MCP name: the file `summarize-tasks` is `summarize_tasks`. */
17
+ type ToolMcpName<F extends string> = F extends `${infer Head}-${infer Tail}` ? `${Head}_${ToolMcpName<Tail>}` : F;
18
+ /** A route's operation name: its `operationId`, else the name its method and path derive. */
19
+ type BoundRouteName<X, N extends string> = X extends {
20
+ operationId: infer D extends string;
21
+ } ? D : N;
22
+ /** A route's effect: the declared one, else its method's. */
23
+ type RouteEffect<X, M> = X extends {
24
+ effect: infer E;
25
+ } ? E : M extends 'GET' ? 'read' : M extends 'DELETE' ? 'delete' : 'write';
26
+ /** The exposure a bound route keeps: what it declares, its path and method, and its effect. */
27
+ type BoundRoute<X, M extends HttpMethod, P extends string> = Pick<X, Extract<keyof X, 'actorKinds' | 'visibility' | 'rpc'>> & {
28
+ http: (X extends {
29
+ http: infer H;
30
+ } ? H : unknown) & {
31
+ method: M;
32
+ path: P;
33
+ };
34
+ effect: RouteEffect<X, M>;
35
+ } & (X extends {
36
+ mcp: infer T;
9
37
  } ? {
10
- http: H & Readonly<Record<Exclude<keyof H, keyof NonNullable<RouteExposure['http']>>, never>>;
38
+ mcp: T & {
39
+ idempotent: boolean;
40
+ };
11
41
  } : unknown);
12
- /** Bind named method declarations to one shared, fully inferred application context. */
13
- export declare function createRoute<E, C>(base: ApplicationBuilder<E, C, Record<never, never>>): <const N extends string, I extends TSchema, O extends TSchema, const X extends RouteExposure>(name: N, definition: Definition<I, O, X> & KnownRouteFields<X>, execute: (context: C & (X extends {
14
- http: {
15
- body: 'bytes';
42
+ /** The exposure a bound tool keeps: what it declares, its effect and its MCP tool. */
43
+ type BoundTool<X, F extends string> = Pick<X, Extract<keyof X, 'actorKinds' | 'rpc' | 'effect'>> & {
44
+ mcp: {
45
+ name: ToolMcpName<F>;
46
+ idempotent: boolean;
47
+ openWorld?: boolean;
16
48
  };
17
- } ? {
18
- body: BinaryBody;
19
- } : object), input: StaticDecode$1<I>) => Promise<Result<Static<O>, Failure>>) => <const P extends string, const M extends NonNullable<Exposure['http']>['method']>(path: P, method: M) => ApplicationBuilder<E, C, Record<never, never> & Record<N, X & {
49
+ };
50
+ /** A tool's operation name, as `ToolName` types it. */
51
+ export declare function toolName(file: string): string;
52
+ /**
53
+ * Prepares every call's context with `context.ts`'s declaration, after admission: what it returns joins the
54
+ * context, and `fail(code)` answers the call. The base must not declare operations yet.
55
+ */
56
+ export declare function bindContext<E, D extends object>(base: ApplicationBuilder<E, Invocation<E>, Record<never, never>>, declaration: ContextDeclaration<D, E>): ApplicationBuilder<E, Invocation<E> & Awaited<D>, Record<never, never>>;
57
+ /**
58
+ * Binds a `defineHandler` declaration to the application, under the path and method its filename gives. The
59
+ * operation is named by its `operationId`, else by `name`, the one `maximus prepare` derives from its method
60
+ * and path with `routeName`: `getNote` for `GET /v1/notes/{noteId}`.
61
+ */
62
+ export declare function bindRoute<E, C, I extends TSchema, O extends TSchema, X, const P extends string, const M extends HttpMethod, const N extends string>(base: ApplicationBuilder<E, C, Record<never, never>>, declaration: HandlerDeclaration<I, O, X, C>, path: P, method: M, name: N): ApplicationBuilder<E, C, Record<never, never> & Record<BoundRouteName<X, N>, Pick<X, Extract<keyof X, "actorKinds" | "rpc" | "visibility">> & {
20
63
  http: (X extends {
21
64
  http: infer H;
22
- } ? H : object) & {
23
- path: P;
65
+ } ? H : unknown) & {
24
66
  method: M;
67
+ path: P;
68
+ };
69
+ effect: RouteEffect<X, M>;
70
+ } & (X extends {
71
+ mcp: infer T;
72
+ } ? {
73
+ mcp: T & {
74
+ idempotent: boolean;
75
+ };
76
+ } : unknown) & Omit<OperationShape, "execute" | "input" | "output" | "pipeline" | keyof Exposure> & {
77
+ input: I;
78
+ output: O;
79
+ } & {
80
+ execute: OperationHandler<C, I, O, BoundRoute<X, M, P>>;
81
+ }>>;
82
+ /**
83
+ * Binds a `defineTool` declaration to the application, under the name its file gives: `summarize-tasks` is
84
+ * the operation `summarizeTasks` and the tool `summarize_tasks`.
85
+ */
86
+ export declare function bindTool<E, C, I extends TSchema, O extends TSchema, X, const F extends string>(base: ApplicationBuilder<E, C, Record<never, never>>, declaration: ToolDeclaration<I, O, X, C>, file: F): ApplicationBuilder<E, C, Record<never, never> & Record<Uncapitalize<Word<F>>, Pick<X, Extract<keyof X, "actorKinds" | "effect" | "rpc">> & {
87
+ mcp: {
88
+ name: ToolMcpName<F>;
89
+ idempotent: boolean;
90
+ openWorld?: boolean;
25
91
  };
26
92
  } & Omit<OperationShape, "execute" | "input" | "output" | "pipeline" | keyof Exposure> & {
27
93
  input: I;
28
94
  output: O;
29
95
  } & {
30
- execute: (context: C & (X & {
31
- http: (X extends {
32
- http: infer H;
33
- } ? H : object) & {
34
- path: P;
35
- method: M;
36
- };
37
- } extends (infer T) ? T extends X & {
38
- http: (X extends {
39
- http: infer H;
40
- } ? H : object) & {
41
- path: P;
42
- method: M;
43
- };
44
- } ? T extends {
45
- http: {
46
- body: 'bytes';
47
- };
48
- } ? {
49
- body: BinaryBody;
50
- } : object : never : never), input: StaticDecode$1<I>) => Promise<Result<(O & {
51
- params: [];
52
- })["static"], Failure<FailureData>>>;
96
+ execute: OperationHandler<C, I, O, BoundTool<X, F>>;
53
97
  }>>;
54
- /** Configuration owns the shared builder and transport policy, never discovered application modules. */
55
- export interface ProjectConfiguration<E, C> {
56
- application: ApplicationBuilder<E, C, Record<never, never>>;
57
- worker: WorkerOptions<E>;
58
- }
59
- /** A simple application configuration needs no hand-written builder or Worker entry. */
60
- export declare function defineConfig<E>(configuration: ApplicationConfiguration<E> & {
61
- worker?: WorkerOptions<E>;
62
- }): ProjectConfiguration<E, Invocation<E>>;
63
- /** An existing fluent base retains its derived context and middleware. */
64
- export declare function defineConfig<E, C>(configuration: {
65
- application: ApplicationBuilder<E, C, Record<never, never>>;
66
- worker?: WorkerOptions<E>;
67
- }): ProjectConfiguration<E, C>;
68
- /** Request middleware has no principal; authentication belongs to the native transport continuation. */
98
+ /** A `middleware/` module that wraps every HTTP request before token admission: it sees no principal. */
69
99
  export interface RequestMiddlewareModule<E> {
70
100
  readonly phase: 'request';
71
101
  readonly handle: HttpMiddleware<E>;
72
102
  }
73
- /** Declare a global HTTP wrapper in middleware/, ordered by filename. */
103
+ /**
104
+ * Declares a `middleware/` module that wraps every HTTP request, in filename order, before the request's
105
+ * token is verified: CORS, security headers, request ids. It cannot authenticate a caller or bypass admission.
106
+ */
74
107
  export declare function defineMiddleware<E>(handle: HttpMiddleware<E>): RequestMiddlewareModule<E>;
75
- /** Post-admission middleware runs on HTTP, MCP and RPC and may inspect verified invocation context. */
108
+ /** A `middleware/` module that runs after admission, on every operation over HTTP, MCP and RPC. */
76
109
  export interface OperationMiddlewareModule<C> {
77
110
  readonly phase: 'operation';
78
111
  readonly handle: OperationMiddleware<C>;
79
112
  }
80
- /** Use this phase for business policy that must apply to every operation transport. */
113
+ /**
114
+ * Declares a `middleware/` module that runs after the caller is admitted, around every operation over HTTP,
115
+ * MCP and RPC, with the verified invocation: business policy that must hold on every transport.
116
+ */
81
117
  export declare function defineOperationMiddleware<C>(handle: OperationMiddleware<C>): OperationMiddlewareModule<C>;
82
- /** Legacy bare functions retain their post-admission meaning. */
83
- export type ProjectMiddleware<E, C> = OperationMiddleware<C> | OperationMiddlewareModule<C> | RequestMiddlewareModule<E>;
84
- type OperationHandle<M> = M extends OperationMiddlewareModule<infer C> ? OperationMiddleware<C> : M extends OperationMiddleware<never> ? M : never;
118
+ /** What a `middleware/` module default-exports. */
119
+ export type ProjectMiddleware<E, C> = OperationMiddlewareModule<C> | RequestMiddlewareModule<E>;
120
+ /** The operation middleware of a module, with its own context type. */
121
+ type OperationHandle<M> = M extends OperationMiddlewareModule<infer C> ? OperationMiddleware<C> : never;
122
+ /** The request middleware of a module, with its own bindings type. */
85
123
  type RequestHandle<M> = M extends RequestMiddlewareModule<infer E> ? HttpMiddleware<E> : never;
86
- /** Split phases, retaining every module's context type rather than widening legacy middleware. */
124
+ /**
125
+ * Splits `middleware/`'s modules by phase, in their order, keeping each module's own context type. A default
126
+ * export that neither helper made is refused.
127
+ */
87
128
  export declare function collectMiddleware<const Modules extends readonly ProjectMiddleware<never, never>[]>(modules: Modules): {
88
129
  middleware: OperationHandle<Modules[number]>[];
89
130
  requestMiddleware: RequestHandle<Modules[number]>[];
90
131
  };
91
- /** Apply discovered policy before route factories capture the base's native execution pipeline. */
132
+ /** Applies the project's operation middleware to its base, before any route binds to it. */
92
133
  export declare function useProjectMiddleware<E, C>(base: ApplicationBuilder<E, C, Record<never, never>>, middleware: readonly OperationMiddleware<C>[]): ApplicationBuilder<E, C, Record<never, never>>;
93
- /** Typed invocation of a project, available to middleware through a type-only configuration import. */
94
- export type ProjectContext<T> = T extends ProjectConfiguration<infer _E, infer C> ? C : T extends ApplicationBuilder<infer _E, infer C, infer _O> ? C : never;
95
- /** Bindings inferred from the project's configuration. */
96
- export type ProjectEnv<T> = T extends ProjectConfiguration<infer E, infer _C> ? E : T extends ApplicationBuilder<infer E, infer _C, infer _O> ? E : never;
97
- /** Refuse a route factory that captured an earlier base and silently omitted discovered policy. */
134
+ /**
135
+ * Refuses an application whose operations do not all run the project's middleware, as a route bound to an
136
+ * earlier base would: its policy would silently be skipped.
137
+ */
98
138
  export declare function checkProjectPipeline<E, C, BC, O extends Record<string, OperationShape>>(base: ApplicationBuilder<E, BC, Record<never, never>>, app: AppManifest<E, C, O>): AppManifest<E, C, O>;
99
- /** Explicit request-phase spelling; defineMiddleware remains the concise file-convention helper. */
100
- export declare const defineRequestMiddleware: typeof defineMiddleware;
101
- export {};
139
+ export type { ToolMcpName, ToolName };
@@ -1,80 +1,196 @@
1
- import { t as maximus } from "../chunks/builder-BiXv7d2v.js";
1
+ import { a as routeGroup, r as ok, t as err } from "../chunks/result-CKgZHrnj.js";
2
+ import { c as isHandlerDeclaration, l as isToolDeclaration, s as isContextDeclaration, t as Failed } from "../chunks/handler-iebR-urt.js";
3
+ import { n as routeTitle, t as routeName } from "../chunks/names-ncD7A3DV.js";
2
4
 
3
- // src/project/route.ts
4
- /** Bind named method declarations to one shared, fully inferred application context. */
5
- function createRoute(base) {
6
- return function defineRoute(name, definition, execute) {
7
- if (definition.http && ("method" in definition.http || "path" in definition.http)) throw new TypeError("The route filename and method export own http.path and http.method.");
8
- return (path, method) => {
9
- const bound = {
10
- ...definition,
11
- http: {
12
- ...definition.http,
13
- path,
14
- method
15
- }
16
- };
17
- return base.operation(name, bound, (context, input) => execute(context, input));
18
- };
5
+ // src/project/bind.ts
6
+ /** A route's effect when it declares none: GET reads, DELETE deletes and the other methods write. */
7
+ function methodEffect(method) {
8
+ if (method === "GET") return "read";
9
+ return method === "DELETE" ? "delete" : "write";
10
+ }
11
+ /** The methods HTTP defines as idempotent: the default idempotent hint of a route's tool. */
12
+ const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
13
+ "GET",
14
+ "PUT",
15
+ "DELETE"
16
+ ]);
17
+ /** `complete_task` as `Complete task`: a tool's default title. */
18
+ function humanize(name) {
19
+ const words = name.replaceAll("_", " ");
20
+ return words.charAt(0).toUpperCase() + words.slice(1);
21
+ }
22
+ /** A segment name in PascalCase, as `Word` types it. */
23
+ function word(segment) {
24
+ return segment.split(/[-_]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
25
+ }
26
+ /** A tool's operation name, as `ToolName` types it. */
27
+ function toolName(file) {
28
+ const name = word(file);
29
+ return name.charAt(0).toLowerCase() + name.slice(1);
30
+ }
31
+ /** The resource a route's scope names by default: its first fixed segment after the version, in kebab-case. */
32
+ function routeResource(path) {
33
+ const segments = path.split("/").filter(Boolean);
34
+ return segments.slice(/^v[1-9][0-9]*$/.test(segments[0] ?? "") ? 1 : 0).find((segment) => !segment.startsWith("{"))?.replaceAll(/([a-z0-9])([A-Z])/g, "$1-$2").replaceAll("_", "-").toLowerCase();
35
+ }
36
+ /**
37
+ * The `fail` a declaration receives: the catalog's failure for a code, with the data the code declares. An
38
+ * unknown code, or data its code refuses, throws, which the execution path reports as `INTERNAL_ERROR`.
39
+ */
40
+ function catalogFail(errors) {
41
+ const names = new Map(Object.entries(errors.definitions).map(([name, { code }]) => [code, name]));
42
+ return (code, data) => {
43
+ const factory = Reflect.get(errors, names.get(code) ?? "");
44
+ if (typeof factory !== "object" || factory === null || !("create" in factory) || typeof factory.create !== "function") throw new TypeError(`The error catalog has no failure ${code}.`);
45
+ return new Failed(factory.create(data));
19
46
  };
20
47
  }
21
-
22
- // src/project/config.ts
23
- /** Runtime-neutral project configuration. Importing it never loads workerd or build tooling. */
24
- function defineConfig(configuration) {
25
- if ("application" in configuration) {
26
- if (Object.keys(configuration.application.definition.operations).length) throw new TypeError("Project configuration accepts a base before operations are declared.");
27
- return {
28
- application: configuration.application,
29
- worker: configuration.worker ?? {}
30
- };
31
- }
32
- const { worker = {}, ...application } = configuration;
33
- return {
34
- application: maximus(application),
35
- worker
48
+ /** A byte body as a route reads it: a failure to read is one the route answers as it is. */
49
+ function routeBody(body) {
50
+ return { async read() {
51
+ const bytes = await body.read();
52
+ return bytes.ok ? bytes : err(new Failed(bytes.error));
53
+ } };
54
+ }
55
+ /**
56
+ * Runs a declaration's handler as an operation: its output answers a success and `fail(code)` the catalog's
57
+ * failure. The execution path checks the declared failures and the output once, as for every operation.
58
+ */
59
+ function execute(errors, handler) {
60
+ const fail = catalogFail(errors);
61
+ return async (context, input) => {
62
+ const answer = await handler({
63
+ ...context,
64
+ input,
65
+ fail,
66
+ ...context.body ? { body: routeBody(context.body) } : {}
67
+ });
68
+ return Failed.is(answer) ? err(answer.failure) : ok(answer);
69
+ };
70
+ }
71
+ /**
72
+ * Prepares every call's context with `context.ts`'s declaration, after admission: what it returns joins the
73
+ * context, and `fail(code)` answers the call. The base must not declare operations yet.
74
+ */
75
+ function bindContext(base, declaration) {
76
+ if (!isContextDeclaration(declaration)) throw new TypeError("context.ts's default export must come from defineContext.");
77
+ const fail = catalogFail(base.definition.errors);
78
+ return base.derive(async (invocation) => {
79
+ const answer = await declaration.prepare({
80
+ ...invocation,
81
+ fail
82
+ });
83
+ return Failed.is(answer) ? err(answer.failure) : ok(answer);
84
+ });
85
+ }
86
+ /**
87
+ * Binds a `defineHandler` declaration to the application, under the path and method its filename gives. The
88
+ * operation is named by its `operationId`, else by `name`, the one `maximus prepare` derives from its method
89
+ * and path with `routeName`: `getNote` for `GET /v1/notes/{noteId}`.
90
+ */
91
+ function bindRoute(base, declaration, path, method, name) {
92
+ if (!isHandlerDeclaration(declaration)) throw new TypeError(`${method} ${path}: a route file's default export must come from defineHandler.`);
93
+ const { operationId, effect = methodEffect(method), scope, title = routeTitle(method, path), group = routeGroup(path), description = "", http, mcp, ...options } = declaration.options;
94
+ const resource = routeResource(path);
95
+ if (scope === void 0 && resource === void 0) throw new TypeError(`${method} ${path}: no fixed segment names its scope; declare its scope.`);
96
+ if (mcp && !description.trim()) throw new TypeError(`${method} ${path}: a route that is an MCP tool describes what it does.`);
97
+ if (method === "DELETE" && effect === "read") throw new TypeError(`${method} ${path}: a DELETE route deletes; its effect is delete or write, never read.`);
98
+ const definition = {
99
+ ...options,
100
+ title,
101
+ ...group === void 0 ? {} : { group },
102
+ description,
103
+ effect,
104
+ scope: scope ?? `${base.definition.namespace}:${resource}:${effect === "read" ? "read" : "write"}`,
105
+ input: declaration.input,
106
+ output: declaration.output,
107
+ http: {
108
+ ...http,
109
+ method,
110
+ path
111
+ },
112
+ ...mcp ? { mcp: {
113
+ ...mcp,
114
+ idempotent: mcp.idempotent ?? IDEMPOTENT_METHODS.has(method)
115
+ } } : {}
36
116
  };
117
+ return base.operation(operationId ?? name, definition, execute(base.definition.errors, declaration.handler));
37
118
  }
38
- /** Declare a global HTTP wrapper in middleware/, ordered by filename. */
119
+ /**
120
+ * Binds a `defineTool` declaration to the application, under the name its file gives: `summarize-tasks` is
121
+ * the operation `summarizeTasks` and the tool `summarize_tasks`.
122
+ */
123
+ function bindTool(base, declaration, file) {
124
+ if (!isToolDeclaration(declaration)) throw new TypeError(`Tool ${file}: an MCP tool file's default export must come from defineTool.`);
125
+ if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(file)) throw new TypeError(`Tool ${file}: name tool files in kebab-case, such as summarize-tasks.ts.`);
126
+ const { effect, scope, title, idempotent = effect === "read", openWorld, ...options } = declaration.options;
127
+ const name = file.replaceAll("-", "_");
128
+ const definition = {
129
+ ...options,
130
+ title: title ?? humanize(name),
131
+ effect,
132
+ scope: scope ?? `${base.definition.namespace}:${file}:${effect === "read" ? "read" : "write"}`,
133
+ input: declaration.input,
134
+ output: declaration.output,
135
+ mcp: {
136
+ name,
137
+ idempotent,
138
+ ...openWorld === void 0 ? {} : { openWorld }
139
+ }
140
+ };
141
+ return base.operation(toolName(file), definition, execute(base.definition.errors, declaration.handler));
142
+ }
143
+
144
+ // src/project/config.ts
145
+ /**
146
+ * Declares a `middleware/` module that wraps every HTTP request, in filename order, before the request's
147
+ * token is verified: CORS, security headers, request ids. It cannot authenticate a caller or bypass admission.
148
+ */
39
149
  function defineMiddleware(handle) {
40
150
  return {
41
151
  phase: "request",
42
152
  handle
43
153
  };
44
154
  }
45
- /** Use this phase for business policy that must apply to every operation transport. */
155
+ /**
156
+ * Declares a `middleware/` module that runs after the caller is admitted, around every operation over HTTP,
157
+ * MCP and RPC, with the verified invocation: business policy that must hold on every transport.
158
+ */
46
159
  function defineOperationMiddleware(handle) {
47
160
  return {
48
161
  phase: "operation",
49
162
  handle
50
163
  };
51
164
  }
52
- /** Split phases, retaining every module's context type rather than widening legacy middleware. */
165
+ /**
166
+ * Splits `middleware/`'s modules by phase, in their order, keeping each module's own context type. A default
167
+ * export that neither helper made is refused.
168
+ */
53
169
  function collectMiddleware(modules) {
54
170
  const middleware = [];
55
171
  const requestMiddleware = [];
56
- for (const module of modules) if (typeof module === "function") middleware.push(module);
57
- else if (module.phase === "operation" && typeof module.handle === "function") middleware.push(module.handle);
58
- else if (module.phase === "request" && typeof module.handle === "function") requestMiddleware.push(module.handle);
59
- else throw new TypeError("A middleware module must use defineMiddleware or defineOperationMiddleware.");
172
+ for (const module of modules) if (module?.phase === "operation" && typeof module.handle === "function") middleware.push(module.handle);
173
+ else if (module?.phase === "request" && typeof module.handle === "function") requestMiddleware.push(module.handle);
174
+ else throw new TypeError("A middleware module must default-export defineMiddleware or defineOperationMiddleware.");
60
175
  return {
61
176
  middleware,
62
177
  requestMiddleware
63
178
  };
64
179
  }
65
- /** Apply discovered policy before route factories capture the base's native execution pipeline. */
180
+ /** Applies the project's operation middleware to its base, before any route binds to it. */
66
181
  function useProjectMiddleware(base, middleware) {
67
182
  let application = base;
68
183
  for (const handler of middleware) application = application.use(handler);
69
184
  return application;
70
185
  }
71
- /** Refuse a route factory that captured an earlier base and silently omitted discovered policy. */
186
+ /**
187
+ * Refuses an application whose operations do not all run the project's middleware, as a route bound to an
188
+ * earlier base would: its policy would silently be skipped.
189
+ */
72
190
  function checkProjectPipeline(base, app) {
73
191
  const expected = base.definition.middleware ?? [];
74
- for (const [name, operation] of Object.entries(app.operations)) if (expected.some((handler, index) => operation.pipeline?.middleware[index] !== handler)) throw new TypeError(`Operation "${name}" omits project middleware. Derive its factory from .maximus/base or .maximus/routes.`);
192
+ for (const [name, operation] of Object.entries(app.operations)) if (expected.some((handler, index) => operation.pipeline?.middleware[index] !== handler)) throw new TypeError(`Operation "${name}" omits project middleware. Bind it to the base in .maximus/base.ts.`);
75
193
  return app;
76
194
  }
77
- /** Explicit request-phase spelling; defineMiddleware remains the concise file-convention helper. */
78
- const defineRequestMiddleware = defineMiddleware;
79
195
 
80
- export { checkProjectPipeline, collectMiddleware, createRoute, defineConfig, defineMiddleware, defineOperationMiddleware, defineRequestMiddleware, useProjectMiddleware };
196
+ export { bindContext, bindRoute, bindTool, checkProjectPipeline, collectMiddleware, defineMiddleware, defineOperationMiddleware, routeName, toolName, useProjectMiddleware };
@@ -1,4 +1,5 @@
1
- import { M as HttpRoute, Rt as AppManifest, n as WorkerOptions, qt as OperationShape, r as WorkerRuntime } from "../chunks/types-DQdfRF3f.js";
1
+ import { D as HttpRoute, pn as OperationShape, rn as AppManifest } from "../chunks/types-DTIuIEJ-.js";
2
+ import { n as WorkerOptions, r as WorkerRuntime } from "../chunks/workers-types-BRk_Xa_5.js";
2
3
  /** File modules use native Workers handlers; unmatched events fail instead of disappearing. */
3
4
  type Handlers<E> = Omit<ExportedHandler<E>, 'fetch'>;
4
5
  /** One schedule, declared beside the code it runs. Configure its trigger in Cloudflare as well. */
@@ -12,13 +13,25 @@ interface ProjectEvents<E> {
12
13
  queues?: Readonly<Record<string, NonNullable<Handlers<E>['queue']>>>;
13
14
  email?: Readonly<Record<string, NonNullable<Handlers<E>['email']>>>;
14
15
  }
15
- /** Pages are native response handlers; rendering libraries stay in the application. */
16
+ /** The methods a page may answer; one that answers `GET` also answers `HEAD`. */
17
+ export type PageMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
18
+ /**
19
+ * A page: a native response handler at a fixed path outside the API, such as a landing page or a provider's
20
+ * webhook. A function answers `GET`; a record answers each method it names, `{ POST: receive }`.
21
+ */
22
+ export type ProjectPage<E> = HttpRoute<E> | Readonly<Partial<Record<PageMethod, HttpRoute<E>>>>;
23
+ /** The modules a project's Worker composes: its pages and its event handlers. */
16
24
  export interface ProjectModules<E> extends ProjectEvents<E> {
17
- pages?: Readonly<Record<string, HttpRoute<E>>>;
25
+ /**
26
+ * The pages, keyed by their path: fixed paths the API, discovery and the Worker's other routes leave free.
27
+ * Rendering libraries stay in the application.
28
+ */
29
+ pages?: Readonly<Record<string, ProjectPage<E>>>;
18
30
  }
19
31
  /**
20
32
  * Compose discovered modules through the existing runtime. Operations keep its single authorization,
21
- * schema and diagnostic pipeline; pages only answer paths outside the API and protocol namespaces.
33
+ * schema and diagnostic pipeline; pages only answer paths outside the API and protocol namespaces, each the
34
+ * methods it declares, and `405` with an `allow` header for any other.
22
35
  */
23
36
  export declare function createProjectWorker<E, C, O extends Record<string, OperationShape>>(app: AppManifest<E, C, O>, modules: ProjectModules<E>, options?: WorkerOptions<E>): WorkerRuntime<E, O>;
24
37
  export type { ProjectCron, ProjectEvents };
@@ -1,6 +1,6 @@
1
- import { i as standardErrors } from "../chunks/errors-D7zG9kx9.js";
2
- import { c as nativePaths, l as ownsPrefix, s as VERSIONED_PATH } from "../chunks/src-N3oyx5QF.js";
3
- import { r as createAssetHandler, t as createWorker } from "../chunks/runtime-DlqA7J38.js";
1
+ import { i as standardErrors } from "../chunks/errors-C5w9WY1l.js";
2
+ import { r as createAssetHandler, t as createWorker } from "../chunks/runtime-D94vx21X.js";
3
+ import { t as checkPagePaths } from "../chunks/pages-iZTvFs5a.js";
4
4
 
5
5
  // src/project/handlers.ts
6
6
  /** Compose file handlers with explicit fallbacks, preserving the platform's execution context. */
@@ -50,15 +50,49 @@ function projectHandlers(events, fallback = {}) {
50
50
 
51
51
  // src/project/index.ts
52
52
  /** Optional Workers composition for projects whose modules are discovered by `maximus prepare`. */
53
+ /** The methods a page record may name. */
54
+ const PAGE_METHODS = /* @__PURE__ */ new Set([
55
+ "GET",
56
+ "POST",
57
+ "PUT",
58
+ "PATCH",
59
+ "DELETE"
60
+ ]);
61
+ /** The order an `allow` header lists a page's methods in: `HEAD` beside the `GET` that answers it. */
62
+ const ALLOW_ORDER = [
63
+ "GET",
64
+ "HEAD",
65
+ "POST",
66
+ "PUT",
67
+ "PATCH",
68
+ "DELETE"
69
+ ];
70
+ /**
71
+ * Each method a page answers, with its handler. Refuses a method other than `GET`, `POST`, `PUT`, `PATCH`
72
+ * and `DELETE`, a handler that is not a function, and a record that names no method.
73
+ */
74
+ function pageRoutes(path, page) {
75
+ const entries = typeof page === "function" ? [["GET", page]] : Object.entries(page);
76
+ const methods = /* @__PURE__ */ new Map();
77
+ for (const [method, route] of entries) {
78
+ if (!PAGE_METHODS.has(method) || typeof route !== "function") throw new TypeError(`Page ${path} must map GET, POST, PUT, PATCH or DELETE to a handler function; it maps ${method}.`);
79
+ methods.set(method, route);
80
+ }
81
+ if (methods.size === 0) throw new TypeError(`Page ${path} must answer at least one method.`);
82
+ return {
83
+ methods,
84
+ allow: ALLOW_ORDER.filter((method) => methods.has(method === "HEAD" ? "GET" : method)).join(", ")
85
+ };
86
+ }
53
87
  /**
54
88
  * Compose discovered modules through the existing runtime. Operations keep its single authorization,
55
- * schema and diagnostic pipeline; pages only answer paths outside the API and protocol namespaces.
89
+ * schema and diagnostic pipeline; pages only answer paths outside the API and protocol namespaces, each the
90
+ * methods it declares, and `405` with an `allow` header for any other.
56
91
  */
57
92
  function createProjectWorker(app, modules, options = {}) {
58
93
  if (options.assets && options.http?.fallback) throw new TypeError("Worker assets and an HTTP fallback cannot both own unmatched paths.");
59
- const pages = new Map(Object.entries(modules.pages ?? {}));
60
- const native = nativePaths(app.tokens, options.http ?? {});
61
- for (const path of pages.keys()) if (!/^\/(?:[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*)?$/.test(path) || path.split("/").some((segment) => segment === "." || segment === "..") || native.reserved.has(path) || native.base && ownsPrefix(native.base, path) || VERSIONED_PATH.test(path) || ownsPrefix("/.well-known", path) || Object.hasOwn(options.routes ?? {}, path) || Object.keys(options.http?.mounts ?? {}).some((prefix) => ownsPrefix(prefix, path)) || options.transports?.some((transport) => ownsPrefix(transport.path, path))) throw new TypeError(`Page path is reserved or malformed: ${path}. Move the API with http.basePath.`);
94
+ const pages = new Map(Object.entries(modules.pages ?? {}).map(([path, page]) => [path, pageRoutes(path, page)]));
95
+ checkPagePaths(pages.keys(), app.tokens, options);
62
96
  const fallback = options.assets ? createAssetHandler(options.assets) : options.http?.fallback;
63
97
  return createWorker(app, {
64
98
  ...options,
@@ -69,8 +103,9 @@ function createProjectWorker(app, modules, options = {}) {
69
103
  async fallback(request, env, context) {
70
104
  const page = pages.get(new URL(request.url).pathname);
71
105
  if (page) {
72
- if (request.method !== "GET" && request.method !== "HEAD") return context.fail(standardErrors.methodNotAllowed.create(), { allow: "GET, HEAD" });
73
- const response = await page(request, env, context);
106
+ const route = page.methods.get(request.method === "HEAD" ? "GET" : request.method);
107
+ if (!route) return context.fail(standardErrors.methodNotAllowed.create(), { allow: page.allow });
108
+ const response = await route(request, env, context);
74
109
  return request.method === "HEAD" ? new Response(null, response) : response;
75
110
  }
76
111
  return fallback ? await fallback(request, env, context) : context.fail(standardErrors.notFound.create());
@@ -1,13 +1,13 @@
1
- /**
2
- * How a service's names and input schemas project onto the surfaces a gateway builds from its OpenAPI
3
- * document, so the service, the gateway and the gateway's generated clients agree without coordinating:
4
- * the MCP tool, the CLI's kebab-case words, a permission's description and the typed query codec.
5
- * Browser-safe: no runtime, no schema library.
6
- */
7
1
  /** How one input field travels in a query string. */
8
- export type QueryKind = 'string' | 'integer' | 'number' | 'boolean' | 'list';
2
+ type QueryKind = 'string' | 'integer' | 'number' | 'boolean' | 'list';
9
3
  /** Resolves a local `$ref` (`#/components/schemas/<name>`) of a bundled document. */
10
- export type SchemaResolver = (reference: string) => unknown;
4
+ type SchemaResolver = (reference: string) => unknown;
5
+ /**
6
+ * How one input field travels in a query string, its `$ref`s followed through `resolve`, or null when it
7
+ * cannot: objects and nested lists do not. Lists are comma separated; a `null` alternative is not
8
+ * expressible and is ignored.
9
+ */
10
+ export declare function queryKind(schema: unknown, resolve?: SchemaResolver): QueryKind | null;
11
11
  /** A resource and the verb that acts on it, such as `appointments` and `findNearest`. */
12
12
  export interface ProjectedName {
13
13
  /** The resource, in camelCase. */
@@ -25,10 +25,11 @@ export declare function snake(value: string): string;
25
25
  * never stands in, since a permission covers several operations.
26
26
  */
27
27
  export declare function permissionDescription(scope: string): string;
28
- /** Portable across MCP clients and model providers (`^[a-z][a-z0-9_]{0,63}$`). */
29
- export declare function mcpToolName(namespace: string, name: ProjectedName): string;
30
28
  /**
31
- * How one input field travels in a query string, or null when it cannot: objects and nested lists
32
- * do not. Lists are comma separated; a `null` alternative is not expressible and is ignored.
29
+ * The MCP tool name a gateway gives an operation, `<namespace>_<resource>_<verb>` in snake_case: the
30
+ * namespace `scheduling` with `{ resource: 'appointments', verb: 'findNearest' }` is
31
+ * `scheduling_appointments_find_nearest`. A name that is not portable across MCP clients and model providers
32
+ * (`^[a-z][a-z0-9_]{0,63}$`) throws a TypeError.
33
33
  */
34
- export declare function queryKind(schema: unknown, resolve?: SchemaResolver): QueryKind | null;
34
+ export declare function mcpToolName(namespace: string, name: ProjectedName): string;
35
+ export type { QueryKind, SchemaResolver };