@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,1091 +0,0 @@
1
- import { i as standardErrors, t as FailureSchema } from "./errors-D7zG9kx9.js";
2
- import { r as readBodyText } from "./body-6LichrQm.js";
3
- import { t as isRecord } from "./record-DY-lX9w1.js";
4
- import { C as operationOutputLimit, D as attachmentResponse, E as pathParameterSchemas, O as binaryBody, S as operationMatchesScopes, c as tokenIssuer, f as ok, g as STANDARD_CODES, l as usesOwnBearer, m as DEFAULT_MAX_BODY_BYTES, o as tokenAudiences, p as sha256Hex, r as createTokenAuthorization, s as tokenEndpoints, u as err, v as isPublicOperation, w as operationScopes, x as operationBodyLimit, y as mcpOpenWorld } from "./define-app-DvD_1jUE.js";
5
- import { a as operationPathParameters, t as createHttpRouteResolver } from "./http-paths-yKD6TSNJ.js";
6
- import { a as telemetryEnabled, i as reportUnexpected, n as recordAdmission, r as recordExecution, s as withTelemetry } from "./telemetry-BTwB68m5.js";
7
- import { t as executeOperation } from "./execution-kVUJPy1A.js";
8
- import { n as mediaType } from "./json-Bu4BLT25.js";
9
- import { Type, Type as Type$1, Type as t } from "@sinclair/typebox";
10
- import { stringify } from "yaml";
11
-
12
- // src/oauth.ts
13
- /** A scope token as RFC 6749 defines it: printable ASCII without spaces, quotes or backslashes. */
14
- const SCOPE = /^[\u0021\u0023-\u005B\u005D-\u007E]+$/;
15
- /** Whether a value is an HTTPS URL without credentials or a fragment, and, for an issuer, without a query. */
16
- function httpsIdentifier(value, issuer) {
17
- try {
18
- const url = new URL(value);
19
- return url.protocol === "https:" && !url.username && !url.password && !url.hash && (!issuer || !url.search);
20
- } catch {
21
- return false;
22
- }
23
- }
24
- /** Serialize RFC 9728 metadata without publishing credentials or accepting request-derived authority. */
25
- function protectedResourceMetadata(resource, env) {
26
- const audience = typeof resource.audience === "function" ? resource.audience(env) : resource.audience;
27
- const servers = typeof resource.authorizationServers === "function" ? resource.authorizationServers(env) : resource.authorizationServers;
28
- if (!httpsIdentifier(audience, false) || !servers.length || servers.some((server) => !httpsIdentifier(server, true)) || resource.scopes.some((scope) => !SCOPE.test(scope))) throw new TypeError("OAuth discovery requires HTTPS resource and issuer identifiers and valid scopes.");
29
- return {
30
- resource: audience,
31
- authorization_servers: [...new Set(servers)],
32
- bearer_methods_supported: ["header"],
33
- scopes_supported: [...new Set(resource.scopes)]
34
- };
35
- }
36
-
37
- // src/internal/http-layout.ts
38
- /** The paths an application answers itself, below its base path: discovery and liveness. */
39
- const NATIVE_PATHS = [
40
- "/",
41
- "/health",
42
- "/openapi.json",
43
- "/openapi.yaml",
44
- "/openapi.yml",
45
- "/.well-known/oauth-protected-resource",
46
- "/.well-known/oauth-protected-resource/mcp"
47
- ];
48
- /** An absolute path of slash-separated unreserved characters. */
49
- const PLAIN_ROUTE_PATH = /^\/[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*$/;
50
- /** `/v1`, `/v2/…`: the namespace of operation routes, which nothing else may claim. */
51
- const VERSIONED_PATH = /^\/v[1-9][0-9]*(?:\/|$)/;
52
- /** An absolute path of unreserved characters, without a trailing slash or dot segments. */
53
- function validPath(path) {
54
- return PLAIN_ROUTE_PATH.test(path) && !path.split("/").some((segment) => segment === "." || segment === "..");
55
- }
56
- /** Whether `prefix` owns `path`: the prefix itself, or any slash-delimited descendant. */
57
- function ownsPrefix(prefix, path) {
58
- return path === prefix || path.startsWith(`${prefix}/`);
59
- }
60
- /**
61
- * Checks where the application's own paths live: its base path, its liveness path and its OAuth resources.
62
- */
63
- function nativePaths(tokens, hooks) {
64
- const base = hooks.basePath === "/" ? "" : hooks.basePath ?? "";
65
- if (base && !validPath(base)) throw new TypeError("HTTP basePath must be an absolute path without a trailing slash or dot segments.");
66
- /** A native path as served below the base path. */
67
- const mount = (path) => base ? `${base}${path === "/" ? "" : path}` : path;
68
- /** A served path as the native path it is, or null outside the base path. */
69
- const local = (path) => {
70
- if (base === "") return path;
71
- if (path === base) return "/";
72
- return path.startsWith(`${base}/`) ? path.slice(base.length) : null;
73
- };
74
- const reserved = new Set(NATIVE_PATHS.map(mount));
75
- const health = hooks.healthPath ?? mount("/health");
76
- if (!validPath(health) || reserved.has(health) && health !== mount("/health") || VERSIONED_PATH.test(local(health) ?? "")) throw new TypeError("HTTP healthPath must be an unreserved absolute path.");
77
- reserved.add(health);
78
- const resources = new Map(Object.entries(tokens.resources ?? {}));
79
- for (const path of resources.keys()) {
80
- if (!validPath(path) || !ownsPrefix("/.well-known/oauth-protected-resource", path) || path === health) throw new TypeError("OAuth resources require distinct absolute protected-resource discovery paths.");
81
- reserved.add(path);
82
- }
83
- return {
84
- base,
85
- mount,
86
- local,
87
- reserved,
88
- health,
89
- resources
90
- };
91
- }
92
- /**
93
- * Checks the transports: one per path, at most one MCP transport, and one whenever the application configures
94
- * MCP.
95
- */
96
- function httpTransports(transports = [], mcpConfigured = false) {
97
- const byPath = new Map(transports.map((transport) => [transport.path, transport]));
98
- const mcpTransports = [...byPath.values()].filter((transport) => transport.protocol === "mcp" || transport.path === "/mcp");
99
- if (mcpTransports.length > 1) throw new TypeError("An HTTP handler may mount only one MCP transport.");
100
- const [mcp] = mcpTransports;
101
- if (mcpConfigured && !mcp) throw new TypeError("MCP configuration requires the optional MCP transport.");
102
- if (byPath.size !== transports.length) throw new TypeError("Duplicate transport path.");
103
- return {
104
- byPath,
105
- mcp
106
- };
107
- }
108
- /**
109
- * Whether the application issues its own bearer tokens, refusing a token scheme the handler could
110
- * never serve: own bearer tokens publish no OAuth discovery, need a resolver and cannot serve MCP.
111
- */
112
- function servesOwnBearer(tokens, mcp) {
113
- const ownBearer = usesOwnBearer(tokens);
114
- if (ownBearer && tokens.resources !== void 0) throw new TypeError("A bearer token scheme cannot publish OAuth resource discovery.");
115
- if ((ownBearer || tokens.scheme?.type === "oauth+bearer") && !tokens.resolve) throw new TypeError("An application bearer token scheme requires tokens.resolve to verify the token.");
116
- if (ownBearer && mcp) throw new TypeError("The MCP transport needs OAuth discovery; it cannot serve a bearer token scheme.");
117
- return ownBearer;
118
- }
119
- /**
120
- * Checks that every transport, plain route and mount path is well formed and claims nothing the
121
- * application, an operation route or another of them already owns.
122
- */
123
- function composition(paths, operations, transports, hooks) {
124
- const transportPaths = [...transports.byPath.keys()];
125
- for (const path of transportPaths) if (!(path === "/" && transports.mcp?.path === "/") && !validPath(path) || paths.reserved.has(path) || VERSIONED_PATH.test(paths.local(path) ?? "") || operations.ownsPath(paths.local(path) ?? "") || transportPaths.some((other) => other !== path && (ownsPrefix(other, path) || ownsPrefix(path, other)))) throw new TypeError(`Transport path is reserved: ${path}`);
126
- const routes = new Map(Object.entries(hooks.routes ?? {}));
127
- for (const path of routes.keys()) if (!validPath(path) || VERSIONED_PATH.test(paths.local(path) ?? "") || paths.reserved.has(path) || operations.ownsPath(paths.local(path) ?? "") || transports.byPath.has(path)) throw new TypeError(`Route path is reserved or malformed: ${path}`);
128
- const mounts = new Map(Object.entries(hooks.mounts ?? {}));
129
- for (const prefix of mounts.keys()) {
130
- const local = paths.local(prefix);
131
- if (!validPath(prefix) || VERSIONED_PATH.test(local ?? "") || [...paths.reserved].some((path) => ownsPrefix(prefix, path)) || [...transportPaths, ...routes.keys()].some((path) => ownsPrefix(prefix, path) || ownsPrefix(path, prefix)) || operations.ownsPath(local ?? "")) throw new TypeError(`Mount path is reserved or malformed: ${prefix}`);
132
- }
133
- return {
134
- routes,
135
- mounted(path) {
136
- let route;
137
- let prefix = "";
138
- for (const segment of path.slice(1).split("/")) {
139
- prefix += `/${segment}`;
140
- route = mounts.get(prefix) ?? route;
141
- }
142
- return route;
143
- }
144
- };
145
- }
146
-
147
- // src/internal/http-query.ts
148
- /**
149
- * The typed GET query codec: which input fields travel in the query string, and how each value is read as
150
- * its kind.
151
- */
152
- /** An integer as a query value: no leading zeros and at most 16 digits, so it stays exact. */
153
- const INTEGER = /^-?(?:0|[1-9]\d{0,15})$/;
154
- /** A decimal number as a query value, with an optional exponent. */
155
- const NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
156
- /**
157
- * How one input field travels in a query string, or null when it cannot: objects and nested lists
158
- * do not. Lists are comma separated; a `null` alternative is not expressible and is ignored.
159
- */
160
- function queryKind(value) {
161
- if (!isRecord(value)) return null;
162
- let branches = null;
163
- if (Array.isArray(value.anyOf)) branches = value.anyOf;
164
- else if (Array.isArray(value.oneOf)) branches = value.oneOf;
165
- if (branches) {
166
- const kinds = branches.filter((branch) => !(isRecord(branch) && branch.type === "null")).map((branch) => queryKind(branch));
167
- if (!kinds.length || kinds.includes(null)) return null;
168
- if (kinds.includes("list")) return kinds.every((kind) => kind === "list" || kind === "string") ? "list" : null;
169
- return kinds.every((kind) => kind === kinds[0]) ? kinds[0] ?? null : null;
170
- }
171
- if (value.type === "array") return queryKind(value.items) === "string" ? "list" : null;
172
- if (value.type === "string" || typeof value.const === "string" || Array.isArray(value.enum) && value.enum.every((entry) => typeof entry === "string")) return "string";
173
- return value.type === "integer" || value.type === "number" || value.type === "boolean" ? value.type : null;
174
- }
175
- /** A GET's query fields and the kind each one is read as: every input field outside the path. */
176
- function queryKinds(op) {
177
- const path = new Set(op.http ? operationPathParameters(op.http.path) : []);
178
- const kinds = /* @__PURE__ */ new Map();
179
- for (const [field, schema] of Object.entries(op.input.properties ?? {})) {
180
- const kind = path.has(field) ? null : queryKind(schema);
181
- if (kind) kinds.set(field, kind);
182
- }
183
- return kinds;
184
- }
185
- /**
186
- * A GET's input from its query string, each declared field read once as its kind, the way generated
187
- * clients write it: `?limit=2&active=true&tags=a,b` is
188
- * `{ limit: 2, active: true, tags: ['a', 'b'] }`. A field the input does not declare stays a string for
189
- * the schema to judge. Null when a field repeats or a value does not read as its kind.
190
- */
191
- function queryInput(kinds, params) {
192
- const keys = [...params.keys()];
193
- if (new Set(keys).size !== keys.length) return null;
194
- const input = {};
195
- for (const [key, text] of params) {
196
- let value = text;
197
- switch (kinds.get(key)) {
198
- case "integer":
199
- value = INTEGER.test(text) ? Number(text) : null;
200
- break;
201
- case "number":
202
- value = NUMBER.test(text) && Number.isFinite(Number(text)) ? Number(text) : null;
203
- break;
204
- case "boolean":
205
- value = text === "true" || text === "false" ? text === "true" : null;
206
- break;
207
- case "list": {
208
- const items = text.split(",");
209
- value = items.every(Boolean) ? items : null;
210
- break;
211
- }
212
- }
213
- if (value === null) return null;
214
- input[key] = value;
215
- }
216
- return input;
217
- }
218
-
219
- // src/schema-bundle.ts
220
- /**
221
- * Schema bundling: named schemas (`$id`) become shared components for an OpenAPI document, or are written
222
- * in place for a reader without components, such as an MCP tool listing.
223
- */
224
- /** Plain identifiers TypeBox uses for Recursive/Ref schemas; URLs and pointers are left untouched. */
225
- const SCHEMA_ID = /^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;
226
- /** Use-site annotations: they describe one occurrence and do not change which values validate. */
227
- const ANNOTATIONS = /* @__PURE__ */ new Set([
228
- "description",
229
- "title",
230
- "examples",
231
- "default",
232
- "$comment",
233
- "deprecated",
234
- "readOnly",
235
- "writeOnly"
236
- ]);
237
- /** Marks a reference resolved only once every variant of its name is known. */
238
- const PLACEHOLDER = "\0schema\0";
239
- /** A reference outside any definition, resolved once every variant is known. */
240
- function pending(id) {
241
- return `${PLACEHOLDER}${id}`;
242
- }
243
- /** A value's JSON with sorted keys, so two equal schemas have one text. */
244
- function canonical(value) {
245
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
246
- if (value && typeof value === "object") return `{${Object.entries(value).filter(([, entry]) => entry !== void 0).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`).join(",")}}`;
247
- return JSON.stringify(value);
248
- }
249
- /** Adds every plain `$id` found in a value to `ids`. */
250
- function collectIds(value, ids) {
251
- if (Array.isArray(value)) {
252
- for (const item of value) collectIds(item, ids);
253
- return;
254
- }
255
- if (value && typeof value === "object") {
256
- const id = value.$id;
257
- if (typeof id === "string" && SCHEMA_ID.test(id)) ids.add(id);
258
- for (const child of Object.values(value)) collectIds(child, ids);
259
- }
260
- }
261
- /** A copy of a value with every `$ref` passed through `replace`. */
262
- function replaceReferences(value, replace) {
263
- if (Array.isArray(value)) return value.map((item) => replaceReferences(item, replace));
264
- if (!value || typeof value !== "object") return value;
265
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, key === "$ref" && typeof child === "string" ? replace(child) : replaceReferences(child, replace)]));
266
- }
267
- /**
268
- * Bundles `$id`-named schemas (TypeBox Recursive/Ref) into components so that every reference in an
269
- * OpenAPI document is a local `#/components/schemas/<name>` pointer. A plain-name reference resolves
270
- * against its enclosing `$id`, as in JSON Schema; structurally different definitions that share an
271
- * `$id` (for example a normalized input projection and its output) become distinct components. A
272
- * reference outside any definition must name exactly one variant. Use-site annotations stay beside
273
- * the reference. The owner's runtime schemas are not changed.
274
- */
275
- function bundleSchemas(sources, existing) {
276
- const ids = /* @__PURE__ */ new Set();
277
- for (const source of sources) collectIds(source, ids);
278
- const components = {};
279
- const variants = /* @__PURE__ */ new Map();
280
- const taken = new Set(Object.keys(existing));
281
- /**
282
- * A copy of a value with every `$id`-named schema replaced by a reference to its component, registering
283
- * each distinct shape once, and references resolved against the enclosing names.
284
- */
285
- function rewrite(value, scope) {
286
- if (Array.isArray(value)) return value.map((item) => rewrite(item, scope));
287
- if (!value || typeof value !== "object") return value;
288
- const record = value;
289
- if (typeof record.$id === "string" && ids.has(record.$id)) {
290
- const { $id: id, ...rest } = record;
291
- const definition = Object.fromEntries(Object.entries(rest).filter(([key]) => !ANNOTATIONS.has(key)));
292
- const annotations = Object.fromEntries(Object.entries(rest).filter(([key]) => ANNOTATIONS.has(key)));
293
- const self = `#/components/schemas/${PLACEHOLDER}self`;
294
- const shaped = rewrite(definition, new Map([...scope, [id, self]]));
295
- const shape = canonical(shaped);
296
- const known = variants.get(id) ?? /* @__PURE__ */ new Map();
297
- variants.set(id, known);
298
- let name = known.get(shape);
299
- if (!name) {
300
- name = id;
301
- for (let index = 2; taken.has(name); index += 1) name = `${id}_${index}`;
302
- taken.add(name);
303
- known.set(shape, name);
304
- const target = `#/components/schemas/${name}`;
305
- components[name] = replaceReferences(shaped, (reference) => reference === self ? target : reference);
306
- }
307
- return {
308
- $ref: `#/components/schemas/${name}`,
309
- ...annotations
310
- };
311
- }
312
- return Object.fromEntries(Object.entries(record).map(([key, child]) => {
313
- if (key === "$ref" && typeof child === "string" && ids.has(child)) return [key, scope.get(child) ?? pending(child)];
314
- return [key, rewrite(child, scope)];
315
- }));
316
- }
317
- const rewritten = sources.map((source) => rewrite(source, /* @__PURE__ */ new Map()));
318
- /**
319
- * A pending reference as the one component its name now has; refused when the name has several shapes or
320
- * none.
321
- */
322
- const resolve = (reference) => {
323
- if (!reference.startsWith(PLACEHOLDER)) return reference;
324
- const id = reference.slice(8);
325
- const names = [...variants.get(id)?.values() ?? []];
326
- if (names.length !== 1) throw new TypeError(`Schema reference "${id}" does not name exactly one definition.`);
327
- return `#/components/schemas/${names[0]}`;
328
- };
329
- for (const [name, schema] of Object.entries(components)) components[name] = replaceReferences(schema, resolve);
330
- return {
331
- values: rewritten.map((value) => replaceReferences(value, resolve)),
332
- components
333
- };
334
- }
335
- /** Adds every `$ref` found in a value to `references`. */
336
- function collectReferences(value, references) {
337
- if (Array.isArray(value)) {
338
- for (const item of value) collectReferences(item, references);
339
- return;
340
- }
341
- if (value && typeof value === "object") for (const [key, child] of Object.entries(value)) if (key === "$ref" && typeof child === "string") references.add(child);
342
- else collectReferences(child, references);
343
- }
344
- /**
345
- * The schema with every `$id` nothing refers to removed, the definition left in place: what a reader
346
- * that resolves no components meets, the same as before the schema was named. A definition a `$ref`
347
- * names (TypeBox Recursive or Ref) keeps its `$id`, so the reference still resolves.
348
- */
349
- function inlineSchemaNames(value) {
350
- const references = /* @__PURE__ */ new Set();
351
- collectReferences(value, references);
352
- /** A copy of a node without the `$id`s nothing refers to. */
353
- const strip = (node) => {
354
- if (Array.isArray(node)) return node.map(strip);
355
- if (!node || typeof node !== "object") return node;
356
- return Object.fromEntries(Object.entries(node).filter(([key, child]) => !(key === "$id" && typeof child === "string" && SCHEMA_ID.test(child) && !references.has(child))).map(([key, child]) => [key, strip(child)]));
357
- };
358
- return strip(value);
359
- }
360
- /** Points each component reference at the schema's own `$defs`. */
361
- function local(node) {
362
- return replaceReferences(node, (reference) => reference.startsWith("#/components/schemas/") ? `#/$defs/${reference.slice(21)}` : reference);
363
- }
364
- /**
365
- * A self-contained schema for a reader with no components, such as an MCP tool listing: no `$id`
366
- * left, each named definition written where it is used, and the ones a `$ref` names bundled once
367
- * under `$defs`. JSON Schema validators refuse a schema that declares one `$id` twice.
368
- */
369
- function standaloneSchema(value) {
370
- const { values, components } = bundleSchemas([inlineSchemaNames(value)], {});
371
- if (!Object.keys(components).length) return values[0];
372
- return {
373
- ...local(values[0]),
374
- $defs: local(components)
375
- };
376
- }
377
-
378
- // src/openapi.ts
379
- /**
380
- * An application's OpenAPI 3.1 document, as its origin serves it: paths, response envelopes, failures by
381
- * status, security schemes, and the `x-*` extensions that carry what OpenAPI cannot say (scopes, effects,
382
- * limits, MCP tools and native RPC).
383
- */
384
- /** OpenAPI body ownership excludes fields carried by the path, including each union variant. */
385
- function bodyWithoutPathParameters(input, names) {
386
- if (input.type === "object") return {
387
- ...input,
388
- properties: Object.fromEntries(Object.entries(input.properties).filter(([name]) => !names.has(name))),
389
- required: (input.required ?? []).filter((name) => !names.has(name))
390
- };
391
- return {
392
- ...input,
393
- anyOf: input.anyOf.map((schema) => bodyWithoutPathParameters(schema, names))
394
- };
395
- }
396
- /**
397
- * One status an operation documents: the failure codes that answer with it, each with its message, and
398
- * `FailureResponse` narrowed to them (`error.code` among them, beside the reference, as JSON Schema
399
- * 2020-12 allows). `FailureResponse` itself stays whole, so a reader that ignores the narrowing still
400
- * meets the complete catalog.
401
- */
402
- function failureResponse(status, failures) {
403
- const lines = failures.map((failure) => `\`${failure.code}\`: ${failure.message}`);
404
- return {
405
- description: lines.length === 1 ? lines[0] : lines.map((line) => `- ${line}`).join("\n"),
406
- headers: {
407
- "X-Request-Id": {
408
- schema: { type: "string" },
409
- description: "Request correlation identifier."
410
- },
411
- ...status === 429 || failures.some((failure) => failure.retryAfter) ? { "Retry-After": {
412
- schema: { type: "integer" },
413
- description: "Seconds before another attempt."
414
- } } : {}
415
- },
416
- content: { "application/json": { schema: {
417
- $ref: "#/components/schemas/FailureResponse",
418
- properties: { error: { properties: { code: { enum: failures.map((failure) => failure.code) } } } }
419
- } } }
420
- };
421
- }
422
- /**
423
- * The document the origin serves at `/openapi.json`: every public operation that declares an HTTP route,
424
- * never an internal one. Each operation also carries its scopes, effect, limits in force, MCP tool hints
425
- * and native RPC as `x-*` extensions.
426
- *
427
- * Every schema reference in it is a local `#/components/schemas/<name>` pointer: the `$id`-named
428
- * schemas of its paths and components (TypeBox Recursive/Ref) become components, as `bundleSchemas`
429
- * describes.
430
- */
431
- function createOpenApi(manifest, options) {
432
- const document = openApiDocument(manifest);
433
- if (options?.operationExtensions) {
434
- const paths = document.paths;
435
- for (const methods of Object.values(paths)) for (const declared of Object.values(methods)) {
436
- const name = String(declared.operationId);
437
- const operation = manifest.operations[name];
438
- if (!operation) throw new TypeError("The document names an undeclared operation.");
439
- const extensions = options.operationExtensions(name, operation);
440
- if (Object.keys(extensions).some((key) => !key.startsWith("x-"))) throw new TypeError("OpenAPI extensions must use x- names.");
441
- Object.assign(declared, extensions);
442
- }
443
- }
444
- const own = Object.entries(document.components.schemas);
445
- const bundled = bundleSchemas([document.paths, ...own.map(([, schema]) => schema)], document.components.schemas);
446
- const [paths, ...schemas] = bundled.values;
447
- return {
448
- ...document,
449
- paths,
450
- components: {
451
- ...document.components,
452
- schemas: {
453
- ...Object.fromEntries(own.map(([name], index) => [name, schemas[index]])),
454
- ...bundled.components
455
- }
456
- }
457
- };
458
- }
459
- /** The document `createOpenApi` builds, before its schemas are bundled. */
460
- function openApiDocument(manifest) {
461
- const entries = Object.entries(manifest.operations).filter(([, op]) => op.http && isPublicOperation(op));
462
- const scopes = Object.fromEntries(entries.flatMap(([, op]) => [...operationScopes(op), ...op.conditionalScopes ?? []].map((scope) => [scope, scope])));
463
- const metadata = Type.Object({ requestId: Type.String({ description: "Request correlation identifier, also sent as X-Request-Id." }) }, {
464
- $id: "ResponseMetadata",
465
- additionalProperties: false
466
- });
467
- const failureError = {
468
- allOf: [FailureSchema],
469
- ...manifest.errors.schema
470
- };
471
- const failure = Type.Object({
472
- success: Type.Literal(false),
473
- data: Type.Null(),
474
- error: failureError,
475
- metadata
476
- }, { additionalProperties: false });
477
- const paths = {};
478
- for (const [name, op] of entries) {
479
- if (!op.http) continue;
480
- const response = Type.Object({
481
- success: Type.Literal(true),
482
- data: op.output,
483
- error: Type.Null(),
484
- metadata
485
- }, { additionalProperties: false });
486
- (paths[op.http.path] ??= {})[op.http.method.toLowerCase()] = {
487
- operationId: name,
488
- summary: op.title,
489
- description: op.description,
490
- security: operationSecurity(name, op, manifest.tokens),
491
- tags: [op.group ?? name],
492
- "x-required-scopes": [...operationScopes(op)],
493
- ...operationScopes(op).length > 1 ? { "x-scope-match": op.scopeMatch ?? "any" } : {},
494
- ...op.conditionalScopes ? { "x-conditional-scopes": op.conditionalScopes } : {},
495
- "x-effect": op.effect,
496
- ...op.mcp ? {
497
- "x-mcp-tool": op.mcp.name,
498
- "x-mcp-idempotent": op.mcp.idempotent,
499
- "x-mcp-open-world": mcpOpenWorld(op.mcp)
500
- } : {},
501
- "x-native-rpc": Boolean(op.rpc),
502
- "x-max-body-bytes": operationBodyLimit(manifest, op),
503
- "x-max-output-bytes": operationOutputLimit(manifest, op),
504
- ...op.http.body ? {
505
- "x-body": op.http.body,
506
- "x-input-headers": op.http.headers ?? {}
507
- } : {},
508
- ...op.http.response ? { "x-response": op.http.response } : {},
509
- ...requestContract(op.input, op.http),
510
- responses: {
511
- [op.http.successStatus ?? 200]: successResponse(op.http, response),
512
- ...failureResponses(op, manifest.errors.definitions)
513
- }
514
- };
515
- }
516
- return JSON.parse(JSON.stringify({
517
- openapi: "3.1.0",
518
- info: {
519
- title: manifest.title,
520
- version: manifest.version
521
- },
522
- servers: [{ url: manifest.origin }],
523
- paths,
524
- components: {
525
- schemas: { FailureResponse: failure },
526
- securitySchemes: securitySchemes(manifest.tokens, scopes)
527
- }
528
- }));
529
- }
530
- /**
531
- * Where an operation's input travels: its path parameters, then a byte body's query and header
532
- * metadata, a GET's query, or a JSON body without the fields the path carries.
533
- */
534
- function requestContract(input, http) {
535
- const parameterNames = operationPathParameters(http.path);
536
- const pathNames = new Set(parameterNames);
537
- const pathParameters = parameterNames.map((parameter) => {
538
- const schemas = pathParameterSchemas(input, parameter);
539
- return {
540
- name: parameter,
541
- in: "path",
542
- required: true,
543
- schema: schemas.length === 1 ? schemas[0] : Type.Union(schemas)
544
- };
545
- });
546
- const properties = input.properties ?? {};
547
- const required = input.required ?? [];
548
- const fields = Object.entries(properties).filter(([field]) => !pathNames.has(field));
549
- if (http.body === "bytes") return {
550
- parameters: [...pathParameters, ...fields.map(([field, schema]) => ({
551
- name: http.headers?.[field] ?? field,
552
- in: http.headers && Object.hasOwn(http.headers, field) ? "header" : "query",
553
- required: required.includes(field),
554
- schema,
555
- "x-input-field": field
556
- }))],
557
- requestBody: {
558
- required: true,
559
- content: { "application/octet-stream": { schema: {
560
- type: "string",
561
- format: "binary"
562
- } } }
563
- }
564
- };
565
- if (http.method === "GET") return { parameters: [...pathParameters, ...fields.map(([field, schema]) => ({
566
- name: field,
567
- in: "query",
568
- required: required.includes(field),
569
- schema
570
- }))] };
571
- return {
572
- ...pathParameters.length ? { parameters: pathParameters } : {},
573
- requestBody: {
574
- required: true,
575
- content: { "application/json": { schema: pathNames.size ? bodyWithoutPathParameters(input, pathNames) : input } }
576
- }
577
- };
578
- }
579
- /** The success response: the JSON envelope, or a validated attachment's bytes and headers. */
580
- function successResponse(http, envelope) {
581
- if (http.response !== "attachment") return {
582
- description: "Successful operation.",
583
- content: { "application/json": { schema: envelope } }
584
- };
585
- return {
586
- description: "Successful operation.",
587
- content: { "application/octet-stream": { schema: {
588
- type: "string",
589
- format: "binary"
590
- } } },
591
- headers: {
592
- "Content-Type": {
593
- schema: { type: "string" },
594
- description: "Validated attachment media type."
595
- },
596
- "Content-Length": {
597
- schema: {
598
- type: "integer",
599
- minimum: 0
600
- },
601
- description: "Exact attachment byte length."
602
- },
603
- "Content-Disposition": {
604
- schema: { type: "string" },
605
- description: "Attachment filename in ASCII and RFC 5987 UTF-8 forms."
606
- }
607
- }
608
- };
609
- }
610
- /**
611
- * The failures an operation documents, one response per status naming every code that answers with
612
- * it, in catalog order: the standard ones and, when it declares `failures`, only those of its own.
613
- */
614
- function failureResponses(op, definitions) {
615
- const statuses = /* @__PURE__ */ new Map();
616
- for (const error of Object.values(definitions)) if (!op.failures || STANDARD_CODES.has(error.code) || op.failures.includes(error.code)) statuses.set(error.status, [...statuses.get(error.status) ?? [], error]);
617
- return Object.fromEntries([...statuses].map(([status, failures]) => [status, failureResponse(status, failures)]));
618
- }
619
- /**
620
- * The security requirements that admit an operation, any one of which is enough: its scopes as
621
- * OAuth requirements (all of them in one requirement when it needs all), or the application's own
622
- * bearer tokens. With both schemes, users present OAuth tokens and services the application's own.
623
- */
624
- function operationSecurity(name, op, tokens) {
625
- let security;
626
- if (tokens.scheme?.type === "bearer") security = [{ bearer: [] }];
627
- else if (op.scopeMatch === "all") security = [{ oauth2: [...operationScopes(op)] }];
628
- else security = operationScopes(op).map((scope) => ({ oauth2: [scope] }));
629
- if (tokens.scheme?.type === "oauth+bearer") {
630
- if (!op.actorKinds?.length) throw new TypeError(`Operation "${name}": dual authentication requires explicit actor eligibility.`);
631
- if (!op.actorKinds.includes("user")) security = [];
632
- if (op.actorKinds.includes("service")) security.push({ bearer: [] });
633
- }
634
- return security;
635
- }
636
- /**
637
- * How callers obtain a token: the OAuth 2.0 flows of the issuer (authorization code, and client
638
- * credentials unless services use the application's own tokens), the application's own bearer
639
- * tokens, or both.
640
- */
641
- function securitySchemes(tokens, scopes) {
642
- const { scheme } = tokens;
643
- if (scheme?.type === "bearer") return { bearer: {
644
- type: "http",
645
- scheme: "bearer",
646
- description: scheme.description
647
- } };
648
- const { authorization, token: tokenUrl } = tokenEndpoints(tokens);
649
- return {
650
- oauth2: {
651
- type: "oauth2",
652
- flows: {
653
- authorizationCode: {
654
- authorizationUrl: authorization,
655
- tokenUrl,
656
- scopes
657
- },
658
- ...scheme?.type === "oauth+bearer" ? {} : { clientCredentials: {
659
- tokenUrl,
660
- scopes
661
- } }
662
- }
663
- },
664
- ...scheme?.type === "oauth+bearer" ? { bearer: {
665
- type: "http",
666
- scheme: "bearer",
667
- description: scheme.description
668
- } } : {}
669
- };
670
- }
671
-
672
- // src/http.ts
673
- /**
674
- * The native HTTP handler: one `fetch` function that serves an application's operations, its
675
- * discovery documents (OpenAPI, OAuth protected-resource metadata, liveness), its transports (MCP),
676
- * plain routes and mounts. Every operation call goes through the same admission: the token, then the
677
- * rate limit, then the bounded body, then the shared execution path.
678
- */
679
- /**
680
- * Serves an application over HTTP as one function, `(request, env, background?) => Promise<Response>`: its
681
- * operations at their routes, the OpenAPI document as JSON and YAML, OAuth discovery, `/health`, transports
682
- * such as MCP, plain routes and mounts. Construction refuses a path two of them would claim.
683
- */
684
- function createHttpHandler(manifest, hooks = {}) {
685
- if (hooks.origins && (!hooks.origins.length || hooks.origins.some((origin) => {
686
- const url = new URL(origin);
687
- return url.protocol !== "https:" || url.origin !== origin;
688
- }))) throw new TypeError("HTTP origins must be exact HTTPS origins.");
689
- for (const middleware of hooks.middleware ?? []) if (typeof middleware !== "function") throw new TypeError("Every HTTP middleware entry must be a function.");
690
- const paths = nativePaths(manifest.tokens, hooks);
691
- const authorize = createTokenAuthorization(manifest.tokens, hooks.verify);
692
- const operations = Object.entries(manifest.operations);
693
- const fallbackBodyBytes = manifest.maxBodyBytes ?? 32768;
694
- const routes = createHttpRouteResolver(operations.map(([name, op]) => ({
695
- name,
696
- op,
697
- http: op.http,
698
- query: queryKinds(op)
699
- })));
700
- const transports = httpTransports(hooks.transports, manifest.mcp !== void 0);
701
- const mcpTransport = transports.mcp;
702
- /**
703
- * The transport's operations a caller may run, those its scopes and actor kind admit: what sizes the body
704
- * it may send, so no one else's large operation widens it.
705
- */
706
- const runnableBy = (caller) => operations.filter(([, op]) => operationMatchesScopes(op, caller.scopes) && (!op.actorKinds || op.actorKinds.includes(caller.actorKind)));
707
- const applicationScopes = Object.freeze([.../* @__PURE__ */ new Set([...operations.flatMap(([, op]) => [...operationScopes(op), ...op.conditionalScopes ?? []]), ...[...transports.byPath.values()].map((transport) => transport.scope(manifest.namespace))])]);
708
- const ownBearer = servesOwnBearer(manifest.tokens, mcpTransport);
709
- if (mcpTransport?.path === "/") paths.reserved.delete("/");
710
- const composed = composition(paths, routes, transports, hooks);
711
- let document;
712
- /** The origin's OpenAPI document, built once on first use. */
713
- const contract = () => {
714
- document ??= createOpenApi(paths.base ? {
715
- ...manifest,
716
- origin: `${manifest.origin}${paths.base}`
717
- } : manifest);
718
- return document;
719
- };
720
- /** The document's JSON and YAML texts, each serialized once on first use. */
721
- const texts = {};
722
- /** The origin's OpenAPI document as the text one of its URLs serves. */
723
- const contractText = (format) => texts[format] ??= format === "json" ? JSON.stringify(contract()) : stringify(contract());
724
- /** The default RFC 9728 protected-resource metadata: the public scopes the origin serves. */
725
- const metadata = () => ({
726
- resource: tokenAudiences(manifest.tokens)[0],
727
- resource_name: manifest.title,
728
- authorization_servers: [tokenIssuer(manifest.tokens)],
729
- bearer_methods_supported: ["header"],
730
- scopes_supported: [.../* @__PURE__ */ new Set([...operations.filter(([, op]) => isPublicOperation(op) && (op.http || op.mcp && mcpTransport)).flatMap(([, op]) => operationScopes(op)), ...[...transports.byPath.values()].map((transport) => transport.scope(manifest.namespace))])],
731
- resource_documentation: `${manifest.origin}${paths.mount("/openapi.json")}`
732
- });
733
- /** The failure envelope, with its status, its challenge and its Retry-After. */
734
- function failure(value, requestId, context, suppliedHeaders) {
735
- const error = manifest.errors.validate(value);
736
- const headers = new Headers(suppliedHeaders);
737
- headers.set("content-type", "application/json");
738
- headers.set("cache-control", "private, no-store");
739
- headers.set("x-content-type-options", "nosniff");
740
- headers.set("x-request-id", requestId);
741
- if (error.code === "UNAUTHORIZED" && !headers.has("www-authenticate")) {
742
- const metadataUrl = challengeMetadataUrl(context);
743
- headers.set("www-authenticate", ownBearer || metadataUrl === null ? "Bearer" : `Bearer resource_metadata="${metadataUrl}"`);
744
- }
745
- const retry = manifest.errors.retryAfter(error.code);
746
- if (retry) headers.set("retry-after", String(error.code === "RATE_LIMITED" ? manifest.rateLimit?.retryAfter ?? retry : retry));
747
- return Response.json({
748
- success: false,
749
- data: null,
750
- error,
751
- metadata: { requestId }
752
- }, {
753
- status: manifest.errors.status(error.code),
754
- headers
755
- });
756
- }
757
- /** The protected-resource metadata a 401 points at, or null when there is none to point at. */
758
- function challengeMetadataUrl(context) {
759
- const configured = manifest.tokens.resourceMetadataUrl;
760
- if (typeof configured === "function") return configured(context);
761
- if (configured !== void 0) return configured;
762
- if (manifest.tokens.resources !== void 0 && paths.resources.size === 0) return null;
763
- return `${manifest.origin}${paths.mount("/.well-known/oauth-protected-resource")}`;
764
- }
765
- /** The application's own GET documents: its index, its OpenAPI and its discovery metadata. */
766
- function nativeDocument(nativePath, reject) {
767
- switch (nativePath) {
768
- case "/": return Response.json({
769
- name: manifest.title,
770
- openapi: paths.mount("/openapi.json"),
771
- ...manifest.mcp && mcpTransport ? { mcp: mcpTransport.path } : {}
772
- });
773
- case "/openapi.json": return new Response(contractText("json"), { headers: { "content-type": "application/json" } });
774
- case "/openapi.yaml":
775
- case "/openapi.yml": return new Response(contractText("yaml"), { headers: { "content-type": "application/yaml; charset=utf-8" } });
776
- case "/.well-known/oauth-protected-resource":
777
- case "/.well-known/oauth-protected-resource/mcp":
778
- if (ownBearer || manifest.tokens.resources !== void 0) return reject(standardErrors.notFound.create());
779
- return Response.json(metadata(), { headers: { "access-control-allow-origin": "*" } });
780
- default: return null;
781
- }
782
- }
783
- /** Whether the rate limit binding still admits this caller; the key is a digest of who calls. */
784
- async function withinRateLimit(env, caller) {
785
- if (!manifest.rateLimit) return true;
786
- const { success } = await env[manifest.rateLimit.binding].limit({ key: await sha256Hex(`${caller.organizationId}:${caller.actorId}`) });
787
- return success;
788
- }
789
- /**
790
- * Answers one request: dispatches it, turns an unexpected error into INTERNAL_ERROR, and sets the request
791
- * id, cache and timing headers on every response.
792
- */
793
- async function handle(incoming, env, background) {
794
- const started = performance.now();
795
- const requestId = crypto.randomUUID();
796
- let principal = null;
797
- let operation = null;
798
- let surface = "http";
799
- let plain = false;
800
- let requestEnv = env;
801
- const context = {
802
- requestId,
803
- fail: (error, headers) => failure(error, requestId, resolutionContext(), headers),
804
- waitUntil: (promise) => {
805
- if (background) background.waitUntil(promise);
806
- else (async () => {
807
- try {
808
- await promise;
809
- } catch (error) {
810
- reportUnexpected(error, "route", requestId);
811
- }
812
- })();
813
- }
814
- };
815
- /** What a token resolver and a challenge URL see of this request. */
816
- const resolutionContext = () => ({
817
- env: requestEnv,
818
- request: incoming,
819
- surface,
820
- applicationScopes,
821
- background
822
- });
823
- /** A refusal before execution, observed as a rejected admission. */
824
- function reject(error) {
825
- recordAdmission(manifest, requestEnv, background, {
826
- principal,
827
- operation,
828
- surface,
829
- requestId,
830
- started,
831
- errorCode: error.code
832
- });
833
- return failure(error, requestId, resolutionContext());
834
- }
835
- /**
836
- * Routes the request: origin pinning, the `before` hook, plain routes and mounts, liveness and discovery
837
- * documents, then an operation or a transport, else the fallback or NOT_FOUND.
838
- */
839
- async function dispatchNative() {
840
- const url = new URL(incoming.url);
841
- if (hooks.before) {
842
- plain = true;
843
- const response = await hooks.before(incoming, env, context);
844
- if (response) return response;
845
- plain = false;
846
- }
847
- const route = composed.routes.get(url.pathname) ?? composed.mounted(url.pathname);
848
- if (route) {
849
- plain = true;
850
- return route(incoming, env, context);
851
- }
852
- const nativePath = paths.local(url.pathname);
853
- const resource = paths.resources.get(url.pathname);
854
- if (url.pathname === paths.health || resource) {
855
- if (incoming.method !== "GET") return context.fail(standardErrors.methodNotAllowed.create(), { allow: "GET" });
856
- return resource ? Response.json(protectedResourceMetadata(resource, env), { headers: { "access-control-allow-origin": "*" } }) : Response.json({
857
- status: "ok",
858
- service: manifest.name,
859
- version: manifest.version
860
- });
861
- }
862
- if (incoming.method === "GET" && !transports.byPath.has(url.pathname)) {
863
- const native = nativeDocument(nativePath, reject);
864
- if (native) return native;
865
- }
866
- const operationRoute = routes.match(incoming.method, nativePath ?? "");
867
- const transport = transports.byPath.get(url.pathname);
868
- operation = operationRoute?.definition.name ?? null;
869
- surface = transport ? "mcp" : "http";
870
- if (!operationRoute && !transport) {
871
- const reserved = paths.base && nativePath !== null || ownsPrefix("/.well-known", url.pathname) || VERSIONED_PATH.test(url.pathname) || paths.reserved.has(url.pathname) || [...transports.byPath.keys()].some((prefix) => ownsPrefix(prefix, url.pathname));
872
- if (hooks.fallback && !reserved) {
873
- plain = true;
874
- return hooks.fallback(incoming, env, context);
875
- }
876
- return reject(standardErrors.notFound.create());
877
- }
878
- let invoked = false;
879
- /**
880
- * Admits and runs the matched operation or transport with the env `aroundOperation` scoped: token, rate
881
- * limit, bounded body, then input and execution.
882
- */
883
- async function run(scopedEnv) {
884
- if (invoked) throw new TypeError("An HTTP operation continuation may run only once.");
885
- invoked = true;
886
- requestEnv = scopedEnv;
887
- const result = await authorize(incoming, operationRoute ? operationScopes(operationRoute.definition.op) : transport?.scope(manifest.namespace) ?? "", {
888
- env: scopedEnv,
889
- request: incoming,
890
- surface,
891
- applicationScopes,
892
- background
893
- }, operationRoute?.definition.op.scopeMatch);
894
- if (!result.ok) return reject(result.error);
895
- const authenticated = result.value;
896
- const accessToken = ownBearer ? void 0 : /^Bearer (\S+)$/i.exec(incoming.headers.get("authorization") ?? "")?.[1];
897
- const actor = {
898
- actorId: authenticated.actorId,
899
- actorKind: authenticated.actorKind,
900
- organizationId: authenticated.organizationId,
901
- requestId
902
- };
903
- principal = actor;
904
- if (!await withinRateLimit(scopedEnv, authenticated)) return reject(standardErrors.rateLimited.create());
905
- let request = incoming;
906
- let bodyText = "";
907
- const byteOperation = operationRoute?.definition.op.http?.body === "bytes";
908
- if (request.body && !byteOperation) {
909
- const maxBytes = operationRoute ? operationRoute.definition.op.maxBodyBytes ?? fallbackBodyBytes : transport?.maxBodyBytes?.(runnableBy(authenticated), fallbackBodyBytes) ?? fallbackBodyBytes;
910
- const body = await readBodyText(request, { maxBytes });
911
- if (!body.ok) return reject(body.error.data.reason === "too_large" ? standardErrors.tooLarge.create() : standardErrors.invalidInput.create());
912
- bodyText = body.value;
913
- request = new Request(request.url, {
914
- method: request.method,
915
- headers: request.headers,
916
- body: bodyText,
917
- signal: request.signal
918
- });
919
- }
920
- /** How many requests this one has carried; admission rate limited the first with the request. */
921
- let carried = 0;
922
- /**
923
- * Counts one more request this one carries. A transport may carry several (a JSON-RPC batch over
924
- * MCP): every one after the first passes the rate limit as a request of its own would.
925
- */
926
- async function admitRequest() {
927
- carried += 1;
928
- return carried === 1 || await withinRateLimit(scopedEnv, authenticated);
929
- }
930
- /**
931
- * Runs one operation through the shared execution path as the admitted caller, and records the call.
932
- */
933
- async function invoke(name, op, input) {
934
- if (transport && !operations.some(([selectedName, selected]) => selectedName === name && selected === op)) return {
935
- ok: false,
936
- error: standardErrors.notFound.create()
937
- };
938
- const admissionStarted = performance.now();
939
- if (!await admitRequest()) {
940
- const error = standardErrors.rateLimited.create();
941
- recordAdmission(manifest, scopedEnv, background, {
942
- principal: actor,
943
- operation: name,
944
- surface,
945
- requestId,
946
- started: admissionStarted,
947
- errorCode: error.code
948
- });
949
- return {
950
- ok: false,
951
- error
952
- };
953
- }
954
- if (telemetryEnabled(manifest.telemetry, scopedEnv)) hooks.annotate?.(name, requestId);
955
- const invocationStarted = performance.now();
956
- const output = await executeOperation(manifest, op, scopedEnv, actor, input, authenticated.client ? {
957
- surface: transport ? "mcp" : "http",
958
- scopes: authenticated.scopes,
959
- client: authenticated.client,
960
- ...accessToken ? { token: accessToken } : {}
961
- } : void 0, background, byteOperation ? binaryBody(incoming, op.maxBodyBytes ?? fallbackBodyBytes) : void 0);
962
- recordExecution(manifest, scopedEnv, background, {
963
- principal: actor,
964
- operation: name,
965
- surface: transport ? "mcp" : "http",
966
- started: invocationStarted,
967
- result: output
968
- });
969
- return output;
970
- }
971
- if (transport) return transport.handle({
972
- request,
973
- requestId,
974
- authenticated,
975
- application: manifest,
976
- operations,
977
- contract,
978
- contractText,
979
- url: (path) => `${manifest.origin}${paths.mount(path)}`,
980
- invoke,
981
- admitRequest,
982
- bodyBytes: new TextEncoder().encode(bodyText).byteLength,
983
- bodyLimit: (op) => op.maxBodyBytes ?? fallbackBodyBytes
984
- });
985
- if (!operationRoute) return reject(standardErrors.notFound.create());
986
- const input = operationInput(operationRoute, incoming, url, bodyText);
987
- if (!input.ok) return reject(input.error);
988
- const output = await invoke(operationRoute.definition.name, operationRoute.definition.op, input.value);
989
- if (!output.ok) return failure(output.error, requestId, resolutionContext());
990
- const exposure = operationRoute.definition.op.http;
991
- if (exposure?.response === "attachment") return attachmentResponse(output.value, exposure.successStatus ?? 200);
992
- return Response.json({
993
- success: true,
994
- data: output.value,
995
- error: null,
996
- metadata: { requestId }
997
- }, { status: exposure?.successStatus ?? 200 });
998
- }
999
- return operationRoute && hooks.aroundOperation ? hooks.aroundOperation(incoming, env, {
1000
- name: operationRoute.definition.name,
1001
- effect: operationRoute.definition.op.effect
1002
- }, run) : run(env);
1003
- }
1004
- let response;
1005
- try {
1006
- if (hooks.origins && !hooks.origins.includes(new URL(incoming.url).origin)) response = reject(standardErrors.notFound.create());
1007
- else {
1008
- const dispatch = async (index) => {
1009
- const middleware = hooks.middleware?.[index];
1010
- if (!middleware) return dispatchNative();
1011
- let invoked = false;
1012
- let active = true;
1013
- const requestView = new Request(incoming.url, {
1014
- method: incoming.method,
1015
- headers: new Headers(incoming.headers),
1016
- signal: incoming.signal
1017
- });
1018
- try {
1019
- return await middleware(requestView, env, context, () => {
1020
- if (invoked || !active) throw new TypeError("An HTTP middleware continuation may run only once before its wrapper settles.");
1021
- invoked = true;
1022
- return dispatch(index + 1);
1023
- });
1024
- } finally {
1025
- active = false;
1026
- }
1027
- };
1028
- response = await dispatch(0);
1029
- }
1030
- } catch (error) {
1031
- reportUnexpected(error, plain ? "route" : "http", requestId);
1032
- response = plain ? failure(standardErrors.internal.create(), requestId, resolutionContext()) : reject(standardErrors.internal.create());
1033
- }
1034
- if (response.status === 101) return response;
1035
- const headers = new Headers(response.headers);
1036
- headers.set("x-request-id", requestId);
1037
- if (!(plain && headers.has("cache-control"))) headers.set("cache-control", "private, no-store");
1038
- headers.set("x-content-type-options", "nosniff");
1039
- headers.set("server-timing", `total;dur=${(performance.now() - started).toFixed(1)}`);
1040
- return new Response(response.body, {
1041
- status: response.status,
1042
- statusText: response.statusText,
1043
- headers
1044
- });
1045
- }
1046
- return (request, env, background) => withTelemetry(manifest.telemetry, env, () => handle(request, env, background));
1047
- }
1048
- /**
1049
- * An operation's input from its HTTP request: a byte operation's query and header metadata, a GET's
1050
- * typed query, a DELETE's absent body or a JSON body, with the path parameters added. A path
1051
- * parameter may come only from the path, never also from the query or the body.
1052
- */
1053
- function operationInput(route, request, url, bodyText) {
1054
- const { op, query } = route.definition;
1055
- let input;
1056
- if (op.http?.body === "bytes") {
1057
- const fields = [...url.searchParams.keys()];
1058
- if (new Set(fields).size !== fields.length) return err(standardErrors.invalidInput.create());
1059
- const inputMetadata = Object.fromEntries(url.searchParams);
1060
- for (const [field, header] of Object.entries(op.http.headers ?? {})) {
1061
- if (url.searchParams.has(field)) return err(standardErrors.invalidInput.create());
1062
- const value = request.headers.get(header);
1063
- if (value !== null) inputMetadata[field] = value;
1064
- }
1065
- input = inputMetadata;
1066
- } else if (request.method === "GET") {
1067
- const fields = queryInput(query, url.searchParams);
1068
- if (!fields) return err(standardErrors.invalidInput.create());
1069
- input = fields;
1070
- } else if (request.method === "DELETE" && bodyText === "" && !request.headers.has("content-type")) input = {};
1071
- else {
1072
- if (mediaType(request.headers.get("content-type")) !== "application/json") return err(standardErrors.unsupportedMedia.create());
1073
- try {
1074
- input = JSON.parse(bodyText);
1075
- } catch {
1076
- return err(standardErrors.invalidInput.create());
1077
- }
1078
- }
1079
- const { parameters } = route;
1080
- if (Object.keys(parameters).some((name) => url.searchParams.has(name))) return err(standardErrors.invalidInput.create());
1081
- if (Object.keys(parameters).length === 0) return ok(input);
1082
- if (typeof input !== "object" || input === null || Array.isArray(input)) return err(standardErrors.invalidInput.create());
1083
- const body = input;
1084
- if (Object.keys(parameters).some((name) => Object.hasOwn(body, name))) return err(standardErrors.invalidInput.create());
1085
- return ok({
1086
- ...body,
1087
- ...parameters
1088
- });
1089
- }
1090
-
1091
- export { canonical as a, nativePaths as c, createOpenApi as i, ownsPrefix as l, t as n, standaloneSchema as o, createHttpHandler as r, VERSIONED_PATH as s, Type$1 as t, protectedResourceMetadata as u };