@arbol-ai/maximus 7.3.1 → 8.0.0

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