@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.
- package/README.md +36 -38
- package/bin/maximus.js +4 -0
- package/config/oxfmt.mjs +1 -0
- package/config/oxlint.mjs +10 -0
- package/dist/analytics/analytics.d.ts +21 -9
- package/dist/analytics/analytics.js +19 -5
- package/dist/body.d.ts +1 -1
- package/dist/body.js +2 -2
- package/dist/chunks/agent-skills-Ef65jTf_.js +49 -0
- package/dist/chunks/agent-skills-m7y1EUch.js +3 -0
- package/dist/chunks/{body-6LichrQm.js → body-DOIHwIIl.js} +14 -7
- package/dist/chunks/{correlation-BEkcFFGT.js → correlation-4b23a-a4.js} +8 -5
- package/dist/chunks/define-app-x7uY70_1.js +341 -0
- package/dist/chunks/{errors-D7zG9kx9.js → errors-C5w9WY1l.js} +10 -5
- package/dist/chunks/{execution-kVUJPy1A.js → execution-rOiLo8VG.js} +28 -15
- package/dist/chunks/generate-C-9FKW0o.js +197 -0
- package/dist/chunks/handler-iebR-urt.js +141 -0
- package/dist/chunks/http-layout-DS8DnPyu.js +128 -0
- package/dist/chunks/{http-paths-yKD6TSNJ.js → http-paths-DMBxwpp6.js} +50 -31
- package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
- package/dist/chunks/names-ncD7A3DV.js +280 -0
- package/dist/chunks/openapi-CeolxIqa.js +1588 -0
- package/dist/chunks/openapi-file-Bz9FRaE6.js +83 -0
- package/dist/chunks/pages-iZTvFs5a.js +14 -0
- package/dist/chunks/prepare-configured-BmRJLg6J.js +3 -0
- package/dist/chunks/prepare-configured-Cithjf80.js +52 -0
- package/dist/chunks/project-files-C0OX7MQQ.js +130 -0
- package/dist/chunks/query-kind-CWKAXEME.js +40 -0
- package/dist/chunks/record-DQUDTpEA.js +10 -0
- package/dist/chunks/result-CKgZHrnj.js +56 -0
- package/dist/chunks/{runtime-DlqA7J38.js → runtime-D94vx21X.js} +50 -26
- package/dist/chunks/scaffold-DGrcjR3h.js +3 -0
- package/dist/chunks/scaffold-DZD6dfoZ.js +138 -0
- package/dist/chunks/{schemas-CzTvbXb6.js → schemas-p_aRcMC1.js} +30 -14
- package/dist/chunks/server-Bzf1Q1_4.js +410 -0
- package/dist/chunks/src-CPrJpbOM.js +573 -0
- package/dist/chunks/{standard-failures-CLjxS2ea.js → standard-failures-Lh4mSfwG.js} +1 -1
- package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
- package/dist/chunks/{types-DQdfRF3f.d.ts → types-DTIuIEJ-.d.ts} +1000 -342
- package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
- package/dist/chunks/workers-types-BRk_Xa_5.d.ts +143 -0
- package/dist/chunks/yaml-Dk2L24yQ.js +74 -0
- package/dist/diagnostics.d.ts +6 -4
- package/dist/diagnostics.js +2 -2
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +2 -2
- package/dist/http-paths.d.ts +1 -1
- package/dist/http-paths.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +12 -11
- package/dist/internals.d.ts +1 -1
- package/dist/internals.js +5 -4
- package/dist/mcp/index.d.ts +3 -2
- package/dist/mcp/index.js +5 -387
- package/dist/postgres/index.d.ts +25 -8
- package/dist/postgres/index.js +17 -8
- package/dist/project/config.d.ts +110 -72
- package/dist/project/config.js +161 -45
- package/dist/project/index.d.ts +17 -4
- package/dist/project/index.js +44 -9
- package/dist/projection.d.ts +14 -13
- package/dist/projection.js +8 -32
- package/dist/schemas.d.ts +1 -1
- package/dist/schemas.js +2 -2
- package/dist/standard-failures.d.ts +2 -89
- package/dist/standard-failures.js +1 -1
- package/dist/tooling/cli.js +149 -105
- package/dist/tooling/testing.js +2 -2
- package/dist/vite/cloudflare-workers.js +25 -0
- package/dist/vite/index.d.ts +157 -0
- package/dist/vite/index.js +1477 -0
- package/dist/webhooks.d.ts +12 -10
- package/dist/webhooks.js +26 -12
- package/dist/workers/runtime.d.ts +1 -1
- package/dist/workers/runtime.js +1 -1
- package/package.json +26 -22
- package/skills/maximus/SKILL.md +165 -68
- package/skills/maximus/references/deploying.md +73 -0
- package/skills/maximus/references/errors-and-results.md +114 -55
- package/skills/maximus/references/project.md +202 -0
- package/skills/maximus/references/routes-and-tools.md +256 -0
- package/skills/maximus/references/testing.md +137 -50
- package/skills/maximus/references/transports.md +113 -100
- package/skills/maximus/references/writing-code.md +84 -0
- package/templates/mcp/mcp/instructions.md.template +2 -0
- package/templates/mcp/routes/v1/greeting.get.ts.template +12 -0
- package/templates/mcp/tests/mcp.test.ts.template +36 -0
- package/templates/project/.agents/skills/project/SKILL.md.template +21 -12
- package/templates/project/.github/workflows/ci.yml.template +4 -1
- package/templates/project/CLAUDE.md.template +41 -25
- package/templates/project/README.md.template +54 -48
- package/templates/project/middleware/10-response.ts.template +5 -2
- package/templates/project/package.json.template +13 -9
- package/templates/project/pages/index.ts.template +2 -4
- package/templates/project/routes/v1/greeting.get.ts.template +10 -0
- package/templates/project/routes/v1/greeting.post.ts.template +12 -0
- package/templates/project/tests/greeting.test.ts.template +45 -0
- package/templates/project/tsconfig.json.template +8 -6
- package/templates/project/vite.config.ts.template +15 -7
- package/templates/web/app/main.tsx.template +16 -0
- package/templates/web/app/root.tsx.template +17 -0
- package/templates/web/app/routes/index.tsx.template +9 -0
- package/templates/web/index.html.template +12 -0
- package/templates/web/package.json.template +12 -0
- package/templates/web/tsconfig.json.template +7 -0
- package/templates/web/vite.config.ts.template +22 -0
- package/dist/chunks/builder-BiXv7d2v.js +0 -100
- package/dist/chunks/define-app-DvD_1jUE.js +0 -625
- package/dist/chunks/prepare-project-CMyGSEtI.js +0 -236
- package/dist/chunks/prepare-project-MtS0-W_n.js +0 -3
- package/dist/chunks/record-DY-lX9w1.js +0 -34
- package/dist/chunks/src-N3oyx5QF.js +0 -1091
- package/dist/client/client.d.ts +0 -129
- package/dist/client/client.js +0 -321
- package/dist/tooling/vite.d.ts +0 -3
- package/dist/tooling/vite.js +0 -57
- package/skills/maximus/references/adding-an-operation.md +0 -179
- package/skills/maximus/references/building-a-service.md +0 -167
- package/skills/maximus/references/migration-from-v2.md +0 -62
- package/skills/maximus/references/migration-to-v5.md +0 -37
- package/skills/maximus/references/publishing-and-verification.md +0 -42
- package/templates/project/cloudflare.config.ts.template +0 -24
- package/templates/project/maximus.config.ts.template +0 -20
- package/templates/project/routes/v1/greeting.ts.template +0 -38
- package/templates/service/.agents/skills/project/SKILL.md.template +0 -10
- package/templates/service/.github/workflows/ci.yml.template +0 -21
- package/templates/service/.gitignore.template +0 -9
- package/templates/service/CLAUDE.md.template +0 -5
- package/templates/service/README.md.template +0 -45
- package/templates/service/cloudflare.config.ts.template +0 -30
- package/templates/service/package.json.template +0 -36
- package/templates/service/src/app.ts.template +0 -30
- package/templates/service/src/index.ts.template +0 -13
- package/templates/service/tests/contract.test.ts.template +0 -12
- package/templates/service/tsconfig.json.template +0 -16
- package/templates/service/vite.config.ts.template +0 -13
- package/templates/service/vitest.config.ts.template +0 -10
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
import { i as standardErrors } from "./errors-C5w9WY1l.js";
|
|
2
|
+
import { r as readBodyText } from "./body-DOIHwIIl.js";
|
|
3
|
+
import { i as binaryBody, n as defineApp, r as attachmentResponse } from "./define-app-x7uY70_1.js";
|
|
4
|
+
import { t as createHttpRouteResolver } from "./http-paths-DMBxwpp6.js";
|
|
5
|
+
import { r as ok, t as err } from "./result-CKgZHrnj.js";
|
|
6
|
+
import { E as isPublicOperation, S as DEFAULT_MAX_BODY_BYTES, T as composeOperations, c as tokenIssuer, g as isCrossSiteWrite, h as queryKinds, i as createTokenAuthorization, j as operationScopes, k as operationMatchesScopes, m as queryInput, s as tokenAudiences, t as createOpenApi, u as sha256Hex } from "./openapi-CeolxIqa.js";
|
|
7
|
+
import { a as telemetryEnabled, i as reportUnexpected, n as recordAdmission, r as recordExecution, s as withTelemetry } from "./telemetry-C3LfZcOB.js";
|
|
8
|
+
import { t as executeOperation } from "./execution-rOiLo8VG.js";
|
|
9
|
+
import { a as ownsPrefix, i as nativePaths, n as composition, o as servesCloudflareAccess, r as httpTransports, s as servesOwnBearer, t as VERSIONED_PATH } from "./http-layout-DS8DnPyu.js";
|
|
10
|
+
import { n as mediaType } from "./json-B14evE6-.js";
|
|
11
|
+
import { t as toYaml } from "./yaml-Dk2L24yQ.js";
|
|
12
|
+
import { Type as Type$1, Type as t } from "@sinclair/typebox";
|
|
13
|
+
|
|
14
|
+
// src/builder.ts
|
|
15
|
+
/**
|
|
16
|
+
* An application under construction, as `maximus()` starts it. Every method returns a new builder and leaves
|
|
17
|
+
* this one unchanged, so resource modules built from one base share its inferred context without overwriting
|
|
18
|
+
* each other's operations.
|
|
19
|
+
*/
|
|
20
|
+
var ApplicationBuilder = class ApplicationBuilder {
|
|
21
|
+
/**
|
|
22
|
+
* The application declared so far: its configuration, context preparation, middleware and operations, which
|
|
23
|
+
* `.build()` checks.
|
|
24
|
+
*/
|
|
25
|
+
definition;
|
|
26
|
+
root;
|
|
27
|
+
/**
|
|
28
|
+
* Wraps `definition`. `root` identifies the application the builder descends from, and `.mount()` admits
|
|
29
|
+
* only modules of the same one. Start an application with `maximus()` instead.
|
|
30
|
+
*/
|
|
31
|
+
constructor(definition, root = definition) {
|
|
32
|
+
this.definition = definition;
|
|
33
|
+
this.root = root;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Declares an operation: a camelCase name no other operation uses, its definition (scope, words, effect,
|
|
37
|
+
* schemas and exposure) and its handler, which receives the prepared context and the decoded input and
|
|
38
|
+
* returns a Result. A name declared twice throws a TypeError, `Duplicate operation: <name>`.
|
|
39
|
+
*/
|
|
40
|
+
operation(name, definition, execute) {
|
|
41
|
+
const operations = composeOperations(this.definition.operations, { [name]: {
|
|
42
|
+
...definition,
|
|
43
|
+
execute,
|
|
44
|
+
pipeline: {
|
|
45
|
+
context: (invocation) => this.definition.context({
|
|
46
|
+
...invocation,
|
|
47
|
+
operation: name
|
|
48
|
+
}),
|
|
49
|
+
middleware: this.definition.middleware ?? []
|
|
50
|
+
}
|
|
51
|
+
} });
|
|
52
|
+
return new ApplicationBuilder({
|
|
53
|
+
...this.definition,
|
|
54
|
+
operations
|
|
55
|
+
}, this.root);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Adds what `resolve` returns to the context of every operation declared after it. It runs after admission
|
|
59
|
+
* and before the middleware; a failure it returns answers the call. Derive before declaring operations: on
|
|
60
|
+
* a builder that already has one, it throws a TypeError.
|
|
61
|
+
*/
|
|
62
|
+
derive(resolve) {
|
|
63
|
+
if (Object.keys(this.definition.operations).length) throw new TypeError("Derive context before declaring operations.");
|
|
64
|
+
const previous = this.definition.context;
|
|
65
|
+
return new ApplicationBuilder({
|
|
66
|
+
...this.definition,
|
|
67
|
+
context: async (invocation) => {
|
|
68
|
+
const context = await previous(invocation);
|
|
69
|
+
if (!context.ok) return context;
|
|
70
|
+
const derived = await resolve(context.value);
|
|
71
|
+
return derived.ok ? ok({
|
|
72
|
+
...context.value,
|
|
73
|
+
...derived.value
|
|
74
|
+
}) : derived;
|
|
75
|
+
}
|
|
76
|
+
}, this.root);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Wraps every operation declared after it, once the caller is admitted and the context prepared. The
|
|
80
|
+
* middleware calls `next` at most once.
|
|
81
|
+
*/
|
|
82
|
+
use(middleware) {
|
|
83
|
+
return new ApplicationBuilder({
|
|
84
|
+
...this.definition,
|
|
85
|
+
middleware: [...this.definition.middleware ?? [], middleware]
|
|
86
|
+
}, this.root);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Adds the operations of a resource module built from the same application; each keeps the context and
|
|
90
|
+
* middleware it was declared with. A module of another application, or one that declares an operation this
|
|
91
|
+
* builder has, throws a TypeError.
|
|
92
|
+
*/
|
|
93
|
+
mount(module) {
|
|
94
|
+
if (this.root !== module.root) throw new TypeError("Resource groups must derive from the same application.");
|
|
95
|
+
return new ApplicationBuilder({
|
|
96
|
+
...this.definition,
|
|
97
|
+
operations: composeOperations(this.definition.operations, module.definition.operations)
|
|
98
|
+
}, this.root);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Checks every rule the application must keep and returns it. A refusal is a TypeError whose message names
|
|
102
|
+
* the rule; most of the rules about one operation also name that operation.
|
|
103
|
+
*/
|
|
104
|
+
build() {
|
|
105
|
+
return defineApp()(this.definition);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Starts an application: its name, scope namespace, title, version, origin, token policy, error catalog and
|
|
110
|
+
* RPC callers, and its optional limits, rate limit, telemetry and MCP configuration. Chain `.derive()` and
|
|
111
|
+
* `.use()` to prepare each call, `.operation()` to declare operations, `.mount()` to compose resource modules
|
|
112
|
+
* that share this base, then `.build()`.
|
|
113
|
+
*/
|
|
114
|
+
function maximus(configuration) {
|
|
115
|
+
return new ApplicationBuilder({
|
|
116
|
+
...configuration,
|
|
117
|
+
operations: {},
|
|
118
|
+
context: (invocation) => Promise.resolve(ok(invocation))
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// src/oauth.ts
|
|
123
|
+
/** A scope token as RFC 6749 defines it: printable ASCII without spaces, quotes or backslashes. */
|
|
124
|
+
const SCOPE = /^[\u0021\u0023-\u005B\u005D-\u007E]+$/;
|
|
125
|
+
/** Whether a value is an HTTPS URL without credentials or a fragment, and, for an issuer, without a query. */
|
|
126
|
+
function httpsIdentifier(value, issuer) {
|
|
127
|
+
try {
|
|
128
|
+
const url = new URL(value);
|
|
129
|
+
return url.protocol === "https:" && !url.username && !url.password && !url.hash && (!issuer || !url.search);
|
|
130
|
+
} catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The RFC 9728 document of one resource: its `resource`, `authorization_servers`, `bearer_methods_supported`
|
|
136
|
+
* (`header`) and `scopes_supported`, read from configuration and the env, never from the request. It throws a
|
|
137
|
+
* TypeError when the audience or an issuer is not an HTTPS URL without credentials or a fragment (an issuer
|
|
138
|
+
* also without a query), when no issuer is named, or when a scope is malformed.
|
|
139
|
+
*/
|
|
140
|
+
function protectedResourceMetadata(resource, env) {
|
|
141
|
+
const audience = typeof resource.audience === "function" ? resource.audience(env) : resource.audience;
|
|
142
|
+
const servers = typeof resource.authorizationServers === "function" ? resource.authorizationServers(env) : resource.authorizationServers;
|
|
143
|
+
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.");
|
|
144
|
+
return {
|
|
145
|
+
resource: audience,
|
|
146
|
+
authorization_servers: [...new Set(servers)],
|
|
147
|
+
bearer_methods_supported: ["header"],
|
|
148
|
+
scopes_supported: [...new Set(resource.scopes)]
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/http.ts
|
|
153
|
+
/**
|
|
154
|
+
* Serves an application over HTTP as one function, `(request, env, background?) => Promise<Response>`: its
|
|
155
|
+
* operations at their routes, the OpenAPI document as JSON and YAML, OAuth discovery, `/health`, transports
|
|
156
|
+
* such as MCP, plain routes and mounts. Every response but a protocol upgrade (101) carries `x-request-id`,
|
|
157
|
+
* `x-content-type-options: nosniff`, `server-timing` and `cache-control: private, no-store`, unless a plain
|
|
158
|
+
* route, mount, fallback or `before` hook sets its own `cache-control`. Construction throws a TypeError for a
|
|
159
|
+
* path two of them would claim, and for an option, token scheme or token source it cannot serve.
|
|
160
|
+
*/
|
|
161
|
+
function createHttpHandler(manifest, hooks = {}) {
|
|
162
|
+
if (hooks.origins && (!hooks.origins.length || hooks.origins.some((origin) => {
|
|
163
|
+
const url = new URL(origin);
|
|
164
|
+
return url.protocol !== "https:" || url.origin !== origin;
|
|
165
|
+
}))) throw new TypeError("HTTP origins must be exact HTTPS origins.");
|
|
166
|
+
for (const middleware of hooks.middleware ?? []) if (typeof middleware !== "function") throw new TypeError("Every HTTP middleware entry must be a function.");
|
|
167
|
+
const paths = nativePaths(manifest.tokens, hooks);
|
|
168
|
+
const authorize = createTokenAuthorization(manifest.tokens, hooks.verify);
|
|
169
|
+
const operations = Object.entries(manifest.operations);
|
|
170
|
+
const fallbackBodyBytes = manifest.maxBodyBytes ?? 32768;
|
|
171
|
+
const routes = createHttpRouteResolver(operations.map(([name, op]) => ({
|
|
172
|
+
name,
|
|
173
|
+
op,
|
|
174
|
+
http: op.http,
|
|
175
|
+
query: queryKinds(op)
|
|
176
|
+
})));
|
|
177
|
+
const transports = httpTransports(hooks.transports, manifest.mcp !== void 0);
|
|
178
|
+
const mcpTransport = transports.mcp;
|
|
179
|
+
/**
|
|
180
|
+
* The transport's operations a caller may run, those its scopes and actor kind admit: what sizes the body
|
|
181
|
+
* it may send, so no one else's large operation widens it.
|
|
182
|
+
*/
|
|
183
|
+
const runnableBy = (caller) => operations.filter(([, op]) => operationMatchesScopes(op, caller.scopes) && (!op.actorKinds || op.actorKinds.includes(caller.actorKind)));
|
|
184
|
+
const applicationScopes = Object.freeze([.../* @__PURE__ */ new Set([...operations.flatMap(([, op]) => [...operationScopes(op), ...op.conditionalScopes ?? []]), ...[...transports.byPath.values()].map((transport) => transport.scope(manifest.namespace))])]);
|
|
185
|
+
const ownBearer = servesOwnBearer(manifest.tokens, mcpTransport);
|
|
186
|
+
const access = servesCloudflareAccess(manifest.tokens, mcpTransport);
|
|
187
|
+
const oauth = !ownBearer && !access;
|
|
188
|
+
if (mcpTransport?.path === "/") paths.reserved.delete("/");
|
|
189
|
+
const composed = composition(paths, routes, transports, hooks);
|
|
190
|
+
let document;
|
|
191
|
+
/** The origin's OpenAPI document, built once on first use. */
|
|
192
|
+
const contract = () => {
|
|
193
|
+
document ??= createOpenApi(paths.base ? {
|
|
194
|
+
...manifest,
|
|
195
|
+
origin: `${manifest.origin}${paths.base}`
|
|
196
|
+
} : manifest);
|
|
197
|
+
return document;
|
|
198
|
+
};
|
|
199
|
+
/** The document's JSON and YAML texts, each serialized once on first use. */
|
|
200
|
+
const texts = {};
|
|
201
|
+
/** The origin's OpenAPI document as the text one of its URLs serves. */
|
|
202
|
+
const contractText = (format) => texts[format] ??= format === "json" ? JSON.stringify(contract()) : toYaml(contract());
|
|
203
|
+
/** The default RFC 9728 protected-resource metadata: the public scopes the origin serves. */
|
|
204
|
+
const metadata = () => ({
|
|
205
|
+
resource: tokenAudiences(manifest.tokens)[0],
|
|
206
|
+
resource_name: manifest.title,
|
|
207
|
+
authorization_servers: [tokenIssuer(manifest.tokens)],
|
|
208
|
+
bearer_methods_supported: ["header"],
|
|
209
|
+
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))])],
|
|
210
|
+
resource_documentation: `${manifest.origin}${paths.mount("/openapi.json")}`
|
|
211
|
+
});
|
|
212
|
+
/** The failure envelope, with its status, its challenge and its Retry-After. */
|
|
213
|
+
function failure(value, requestId, context, suppliedHeaders) {
|
|
214
|
+
const error = manifest.errors.validate(value);
|
|
215
|
+
const headers = new Headers(suppliedHeaders);
|
|
216
|
+
headers.set("content-type", "application/json");
|
|
217
|
+
headers.set("cache-control", "private, no-store");
|
|
218
|
+
headers.set("x-content-type-options", "nosniff");
|
|
219
|
+
headers.set("x-request-id", requestId);
|
|
220
|
+
const status = manifest.errors.status(error.code);
|
|
221
|
+
if ((status === 401 || status === 403) && !headers.has("www-authenticate")) {
|
|
222
|
+
const challenge = manifest.tokens.challenge?.(error, context);
|
|
223
|
+
if (challenge) headers.set("www-authenticate", challenge);
|
|
224
|
+
}
|
|
225
|
+
if (status === 401 && !headers.has("www-authenticate")) {
|
|
226
|
+
const metadataUrl = oauth ? challengeMetadataUrl(context) : null;
|
|
227
|
+
headers.set("www-authenticate", metadataUrl === null ? "Bearer" : `Bearer resource_metadata="${metadataUrl}"`);
|
|
228
|
+
}
|
|
229
|
+
const retry = manifest.errors.retryAfter(error.code);
|
|
230
|
+
if (retry) headers.set("retry-after", String(error.code === "RATE_LIMITED" ? manifest.rateLimit?.retryAfter ?? retry : retry));
|
|
231
|
+
return Response.json({
|
|
232
|
+
success: false,
|
|
233
|
+
data: null,
|
|
234
|
+
error,
|
|
235
|
+
metadata: { requestId }
|
|
236
|
+
}, {
|
|
237
|
+
status: manifest.errors.status(error.code),
|
|
238
|
+
headers
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
/** The protected-resource metadata a 401 points at, or null when there is none to point at. */
|
|
242
|
+
function challengeMetadataUrl(context) {
|
|
243
|
+
const configured = manifest.tokens.resourceMetadataUrl;
|
|
244
|
+
if (typeof configured === "function") return configured(context);
|
|
245
|
+
if (configured !== void 0) return configured;
|
|
246
|
+
if (manifest.tokens.resources !== void 0 && paths.resources.size === 0) return null;
|
|
247
|
+
return `${manifest.origin}${paths.mount("/.well-known/oauth-protected-resource")}`;
|
|
248
|
+
}
|
|
249
|
+
/** The application's own GET documents: its index, its OpenAPI and its discovery metadata. */
|
|
250
|
+
function nativeDocument(nativePath, reject) {
|
|
251
|
+
switch (nativePath) {
|
|
252
|
+
case "/": return Response.json({
|
|
253
|
+
name: manifest.title,
|
|
254
|
+
openapi: paths.mount("/openapi.json"),
|
|
255
|
+
...mcpTransport ? { mcp: mcpTransport.path } : {}
|
|
256
|
+
});
|
|
257
|
+
case "/openapi.json": return new Response(contractText("json"), { headers: { "content-type": "application/json" } });
|
|
258
|
+
case "/openapi.yaml":
|
|
259
|
+
case "/openapi.yml": return new Response(contractText("yaml"), { headers: { "content-type": "application/yaml; charset=utf-8" } });
|
|
260
|
+
case "/.well-known/oauth-protected-resource":
|
|
261
|
+
case "/.well-known/oauth-protected-resource/mcp":
|
|
262
|
+
if (!oauth || manifest.tokens.resources !== void 0) return reject(standardErrors.notFound.create());
|
|
263
|
+
return Response.json(metadata(), { headers: { "access-control-allow-origin": "*" } });
|
|
264
|
+
default: return null;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
/** Whether the rate limit binding still admits this caller; the key is a digest of who calls. */
|
|
268
|
+
async function withinRateLimit(env, caller) {
|
|
269
|
+
if (!manifest.rateLimit) return true;
|
|
270
|
+
const { success } = await env[manifest.rateLimit.binding].limit({ key: await sha256Hex(`${caller.organizationId}:${caller.actorId}`) });
|
|
271
|
+
return success;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Answers one request: dispatches it, turns an unexpected error into INTERNAL_ERROR, and sets the request
|
|
275
|
+
* id, cache and timing headers on every response.
|
|
276
|
+
*/
|
|
277
|
+
async function handle(incoming, env, background) {
|
|
278
|
+
const started = performance.now();
|
|
279
|
+
const requestId = crypto.randomUUID();
|
|
280
|
+
let principal = null;
|
|
281
|
+
let operation = null;
|
|
282
|
+
let surface = "http";
|
|
283
|
+
let plain = false;
|
|
284
|
+
let requestEnv = env;
|
|
285
|
+
const context = {
|
|
286
|
+
requestId,
|
|
287
|
+
fail: (error, headers) => failure(error, requestId, resolutionContext(), headers),
|
|
288
|
+
waitUntil: (promise) => {
|
|
289
|
+
if (background) background.waitUntil(promise);
|
|
290
|
+
else (async () => {
|
|
291
|
+
try {
|
|
292
|
+
await promise;
|
|
293
|
+
} catch (error) {
|
|
294
|
+
reportUnexpected(error, "route", requestId);
|
|
295
|
+
}
|
|
296
|
+
})();
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
/** What a token resolver and a challenge URL see of this request. */
|
|
300
|
+
const resolutionContext = () => ({
|
|
301
|
+
env: requestEnv,
|
|
302
|
+
request: incoming,
|
|
303
|
+
surface,
|
|
304
|
+
applicationScopes,
|
|
305
|
+
background
|
|
306
|
+
});
|
|
307
|
+
/** A refusal before execution, observed as a rejected admission. */
|
|
308
|
+
function reject(error) {
|
|
309
|
+
recordAdmission(manifest, requestEnv, background, {
|
|
310
|
+
principal,
|
|
311
|
+
operation,
|
|
312
|
+
surface,
|
|
313
|
+
requestId,
|
|
314
|
+
started,
|
|
315
|
+
errorCode: error.code
|
|
316
|
+
});
|
|
317
|
+
return failure(error, requestId, resolutionContext());
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Routes the request: origin pinning, the `before` hook, plain routes and mounts, liveness and discovery
|
|
321
|
+
* documents, then an operation or a transport, else the fallback or NOT_FOUND.
|
|
322
|
+
*/
|
|
323
|
+
async function dispatchNative() {
|
|
324
|
+
const url = new URL(incoming.url);
|
|
325
|
+
if (hooks.before) {
|
|
326
|
+
plain = true;
|
|
327
|
+
const response = await hooks.before(incoming, env, context);
|
|
328
|
+
if (response) return response;
|
|
329
|
+
plain = false;
|
|
330
|
+
}
|
|
331
|
+
const route = composed.routes.get(url.pathname) ?? composed.mounted(url.pathname);
|
|
332
|
+
if (route) {
|
|
333
|
+
plain = true;
|
|
334
|
+
return route(incoming, env, context);
|
|
335
|
+
}
|
|
336
|
+
const nativePath = paths.local(url.pathname);
|
|
337
|
+
const resource = paths.resources.get(url.pathname);
|
|
338
|
+
if (url.pathname === paths.health || resource) {
|
|
339
|
+
if (incoming.method !== "GET") return context.fail(standardErrors.methodNotAllowed.create(), { allow: "GET" });
|
|
340
|
+
return resource ? Response.json(protectedResourceMetadata(resource, env), { headers: { "access-control-allow-origin": "*" } }) : Response.json({
|
|
341
|
+
status: "ok",
|
|
342
|
+
service: manifest.name,
|
|
343
|
+
version: manifest.version
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
if (incoming.method === "GET" && !transports.byPath.has(url.pathname)) {
|
|
347
|
+
const native = nativeDocument(nativePath, reject);
|
|
348
|
+
if (native) return native;
|
|
349
|
+
}
|
|
350
|
+
const operationRoute = routes.match(incoming.method, nativePath ?? "");
|
|
351
|
+
const transport = transports.byPath.get(url.pathname);
|
|
352
|
+
operation = operationRoute?.definition.name ?? null;
|
|
353
|
+
surface = transport ? "mcp" : "http";
|
|
354
|
+
if (!operationRoute && !transport) {
|
|
355
|
+
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));
|
|
356
|
+
if (hooks.fallback && !reserved) {
|
|
357
|
+
plain = true;
|
|
358
|
+
return hooks.fallback(incoming, env, context);
|
|
359
|
+
}
|
|
360
|
+
return reject(standardErrors.notFound.create());
|
|
361
|
+
}
|
|
362
|
+
let invoked = false;
|
|
363
|
+
/**
|
|
364
|
+
* Admits and runs the matched operation or transport with the env `aroundOperation` scoped: token, rate
|
|
365
|
+
* limit, bounded body, then input and execution.
|
|
366
|
+
*/
|
|
367
|
+
async function run(scopedEnv) {
|
|
368
|
+
if (invoked) throw new TypeError("An HTTP operation continuation may run only once.");
|
|
369
|
+
invoked = true;
|
|
370
|
+
requestEnv = scopedEnv;
|
|
371
|
+
if (access && isCrossSiteWrite(incoming)) return reject(standardErrors.forbidden.create());
|
|
372
|
+
const result = await authorize(incoming, operationRoute ? operationScopes(operationRoute.definition.op) : transport?.scope(manifest.namespace) ?? "", {
|
|
373
|
+
env: scopedEnv,
|
|
374
|
+
request: incoming,
|
|
375
|
+
surface,
|
|
376
|
+
applicationScopes,
|
|
377
|
+
background
|
|
378
|
+
}, operationRoute?.definition.op.scopeMatch);
|
|
379
|
+
if (!result.ok) return reject(result.error);
|
|
380
|
+
const authenticated = result.value;
|
|
381
|
+
const accessToken = oauth ? /^Bearer (\S+)$/i.exec(incoming.headers.get("authorization") ?? "")?.[1] : void 0;
|
|
382
|
+
const actor = {
|
|
383
|
+
actorId: authenticated.actorId,
|
|
384
|
+
actorKind: authenticated.actorKind,
|
|
385
|
+
organizationId: authenticated.organizationId,
|
|
386
|
+
requestId
|
|
387
|
+
};
|
|
388
|
+
principal = actor;
|
|
389
|
+
if (!await withinRateLimit(scopedEnv, authenticated)) return reject(standardErrors.rateLimited.create());
|
|
390
|
+
let request = incoming;
|
|
391
|
+
let bodyText = "";
|
|
392
|
+
const byteOperation = operationRoute?.definition.op.http?.body === "bytes";
|
|
393
|
+
const type = request.headers.get("content-type");
|
|
394
|
+
if (operationRoute && !byteOperation && request.method !== "GET" && (type === null ? request.body !== null && request.method !== "DELETE" : mediaType(type) !== "application/json")) return reject(standardErrors.unsupportedMedia.create());
|
|
395
|
+
if (request.body && !byteOperation) {
|
|
396
|
+
const maxBytes = operationRoute ? operationRoute.definition.op.maxBodyBytes ?? fallbackBodyBytes : transport?.maxBodyBytes?.(runnableBy(authenticated), fallbackBodyBytes) ?? fallbackBodyBytes;
|
|
397
|
+
const body = await readBodyText(request, { maxBytes });
|
|
398
|
+
if (!body.ok) return reject(body.error.data.reason === "too_large" ? standardErrors.tooLarge.create() : standardErrors.invalidInput.create());
|
|
399
|
+
bodyText = body.value;
|
|
400
|
+
request = new Request(request.url, {
|
|
401
|
+
method: request.method,
|
|
402
|
+
headers: request.headers,
|
|
403
|
+
body: bodyText,
|
|
404
|
+
signal: request.signal
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Admits the requests a transport's request carries beyond the first (a JSON-RPC batch over MCP),
|
|
409
|
+
* each passing the rate limit as a request of its own would, before any of them runs.
|
|
410
|
+
*/
|
|
411
|
+
async function admitCarried(requests) {
|
|
412
|
+
for (let admitted = 0; admitted < requests; admitted += 1) if (!await withinRateLimit(scopedEnv, authenticated)) return reject(standardErrors.rateLimited.create());
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Runs one operation through the shared execution path as the admitted caller, and records the call.
|
|
416
|
+
*/
|
|
417
|
+
async function invoke(name, op, input) {
|
|
418
|
+
if (transport && !operations.some(([selectedName, selected]) => selectedName === name && selected === op)) return {
|
|
419
|
+
ok: false,
|
|
420
|
+
error: standardErrors.notFound.create()
|
|
421
|
+
};
|
|
422
|
+
if (transport && !operationMatchesScopes(op, authenticated.scopes)) return {
|
|
423
|
+
ok: false,
|
|
424
|
+
error: standardErrors.forbidden.create()
|
|
425
|
+
};
|
|
426
|
+
if (telemetryEnabled(manifest.telemetry, scopedEnv)) hooks.annotate?.(name, requestId);
|
|
427
|
+
const invocationStarted = performance.now();
|
|
428
|
+
const output = await executeOperation(manifest, op, scopedEnv, actor, input, authenticated.client ? {
|
|
429
|
+
surface: transport ? "mcp" : "http",
|
|
430
|
+
scopes: authenticated.scopes,
|
|
431
|
+
client: authenticated.client,
|
|
432
|
+
...accessToken ? { token: accessToken } : {}
|
|
433
|
+
} : void 0, background, byteOperation ? binaryBody(incoming, op.maxBodyBytes ?? fallbackBodyBytes) : void 0);
|
|
434
|
+
recordExecution(manifest, scopedEnv, background, {
|
|
435
|
+
principal: actor,
|
|
436
|
+
operation: name,
|
|
437
|
+
surface: transport ? "mcp" : "http",
|
|
438
|
+
started: invocationStarted,
|
|
439
|
+
result: output
|
|
440
|
+
});
|
|
441
|
+
return output;
|
|
442
|
+
}
|
|
443
|
+
if (transport) return transport.handle({
|
|
444
|
+
request,
|
|
445
|
+
requestId,
|
|
446
|
+
authenticated,
|
|
447
|
+
application: manifest,
|
|
448
|
+
operations,
|
|
449
|
+
contract,
|
|
450
|
+
contractText,
|
|
451
|
+
url: (path) => `${manifest.origin}${paths.mount(path)}`,
|
|
452
|
+
invoke,
|
|
453
|
+
admitCarried,
|
|
454
|
+
refused: (error, name) => {
|
|
455
|
+
recordAdmission(manifest, scopedEnv, background, {
|
|
456
|
+
principal: actor,
|
|
457
|
+
operation: name ?? null,
|
|
458
|
+
surface,
|
|
459
|
+
requestId,
|
|
460
|
+
started,
|
|
461
|
+
errorCode: error.code
|
|
462
|
+
});
|
|
463
|
+
},
|
|
464
|
+
body: bodyText,
|
|
465
|
+
bodyLimit: (op) => op.maxBodyBytes ?? fallbackBodyBytes
|
|
466
|
+
});
|
|
467
|
+
if (!operationRoute) return reject(standardErrors.notFound.create());
|
|
468
|
+
const input = operationInput(operationRoute, incoming, url, bodyText);
|
|
469
|
+
if (!input.ok) return reject(input.error);
|
|
470
|
+
const output = await invoke(operationRoute.definition.name, operationRoute.definition.op, input.value);
|
|
471
|
+
if (!output.ok) return failure(output.error, requestId, resolutionContext());
|
|
472
|
+
const exposure = operationRoute.definition.op.http;
|
|
473
|
+
if (exposure?.response === "attachment") return attachmentResponse(output.value, exposure.successStatus ?? 200);
|
|
474
|
+
return Response.json({
|
|
475
|
+
success: true,
|
|
476
|
+
data: output.value,
|
|
477
|
+
error: null,
|
|
478
|
+
metadata: { requestId }
|
|
479
|
+
}, { status: exposure?.successStatus ?? 200 });
|
|
480
|
+
}
|
|
481
|
+
return operationRoute && hooks.aroundOperation ? hooks.aroundOperation(incoming, env, {
|
|
482
|
+
name: operationRoute.definition.name,
|
|
483
|
+
effect: operationRoute.definition.op.effect
|
|
484
|
+
}, run) : run(env);
|
|
485
|
+
}
|
|
486
|
+
let response;
|
|
487
|
+
try {
|
|
488
|
+
if (hooks.origins && !hooks.origins.includes(new URL(incoming.url).origin)) response = reject(standardErrors.notFound.create());
|
|
489
|
+
else {
|
|
490
|
+
const dispatch = async (index) => {
|
|
491
|
+
const middleware = hooks.middleware?.[index];
|
|
492
|
+
if (!middleware) return dispatchNative();
|
|
493
|
+
let invoked = false;
|
|
494
|
+
let active = true;
|
|
495
|
+
const requestView = new Request(incoming.url, {
|
|
496
|
+
method: incoming.method,
|
|
497
|
+
headers: new Headers(incoming.headers),
|
|
498
|
+
signal: incoming.signal
|
|
499
|
+
});
|
|
500
|
+
try {
|
|
501
|
+
return await middleware(requestView, env, context, () => {
|
|
502
|
+
if (invoked || !active) throw new TypeError("An HTTP middleware continuation may run only once before its wrapper settles.");
|
|
503
|
+
invoked = true;
|
|
504
|
+
return dispatch(index + 1);
|
|
505
|
+
});
|
|
506
|
+
} finally {
|
|
507
|
+
active = false;
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
response = await dispatch(0);
|
|
511
|
+
}
|
|
512
|
+
} catch (error) {
|
|
513
|
+
reportUnexpected(error, plain ? "route" : surface, requestId);
|
|
514
|
+
response = plain ? failure(standardErrors.internal.create(), requestId, resolutionContext()) : reject(standardErrors.internal.create());
|
|
515
|
+
}
|
|
516
|
+
if (response.status === 101) return response;
|
|
517
|
+
const headers = new Headers(response.headers);
|
|
518
|
+
headers.set("x-request-id", requestId);
|
|
519
|
+
if (!(plain && headers.has("cache-control"))) headers.set("cache-control", "private, no-store");
|
|
520
|
+
headers.set("x-content-type-options", "nosniff");
|
|
521
|
+
headers.set("server-timing", `total;dur=${(performance.now() - started).toFixed(1)}`);
|
|
522
|
+
return new Response(response.body, {
|
|
523
|
+
status: response.status,
|
|
524
|
+
statusText: response.statusText,
|
|
525
|
+
headers
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
return (request, env, background) => withTelemetry(manifest.telemetry, env, () => handle(request, env, background));
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* An operation's input from its HTTP request: a byte operation's query and header metadata, a GET's
|
|
532
|
+
* typed query, a DELETE's absent body or a JSON body, with the path parameters added. A path
|
|
533
|
+
* parameter may come only from the path, never also from the query or the body.
|
|
534
|
+
*/
|
|
535
|
+
function operationInput(route, request, url, bodyText) {
|
|
536
|
+
const { op, query } = route.definition;
|
|
537
|
+
let input;
|
|
538
|
+
if (op.http?.body === "bytes") {
|
|
539
|
+
const fields = [...url.searchParams.keys()];
|
|
540
|
+
if (new Set(fields).size !== fields.length) return err(standardErrors.invalidInput.create());
|
|
541
|
+
const inputMetadata = Object.fromEntries(url.searchParams);
|
|
542
|
+
for (const [field, header] of Object.entries(op.http.headers ?? {})) {
|
|
543
|
+
if (url.searchParams.has(field)) return err(standardErrors.invalidInput.create());
|
|
544
|
+
const value = request.headers.get(header);
|
|
545
|
+
if (value !== null) inputMetadata[field] = value;
|
|
546
|
+
}
|
|
547
|
+
input = inputMetadata;
|
|
548
|
+
} else if (request.method === "GET") {
|
|
549
|
+
const fields = queryInput(query, url.searchParams);
|
|
550
|
+
if (!fields) return err(standardErrors.invalidInput.create());
|
|
551
|
+
input = fields;
|
|
552
|
+
} else if (request.method === "DELETE" && bodyText === "" && !request.headers.has("content-type")) input = {};
|
|
553
|
+
else {
|
|
554
|
+
if (mediaType(request.headers.get("content-type")) !== "application/json") return err(standardErrors.unsupportedMedia.create());
|
|
555
|
+
try {
|
|
556
|
+
input = JSON.parse(bodyText);
|
|
557
|
+
} catch {
|
|
558
|
+
return err(standardErrors.invalidInput.create());
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
const { parameters } = route;
|
|
562
|
+
if (Object.keys(parameters).some((name) => url.searchParams.has(name))) return err(standardErrors.invalidInput.create());
|
|
563
|
+
if (Object.keys(parameters).length === 0) return ok(input);
|
|
564
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) return err(standardErrors.invalidInput.create());
|
|
565
|
+
const body = input;
|
|
566
|
+
if (Object.keys(parameters).some((name) => Object.hasOwn(body, name))) return err(standardErrors.invalidInput.create());
|
|
567
|
+
return ok({
|
|
568
|
+
...body,
|
|
569
|
+
...parameters
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
export { maximus as a, protectedResourceMetadata as i, t as n, createHttpHandler as r, Type$1 as t };
|
|
@@ -5,7 +5,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
5
5
|
* Safe error descriptions for diagnostics: an error's known names, its causes' names, its issue count and
|
|
6
6
|
* its stack locations, never a message.
|
|
7
7
|
*/
|
|
8
|
-
/**
|
|
8
|
+
/** The built-in error names a description keeps; `createDiagnostics` adds the names a consumer supplies. */
|
|
9
9
|
const BUILTIN_ERROR_NAMES = [
|
|
10
10
|
"AbortError",
|
|
11
11
|
"AggregateError",
|
|
@@ -19,7 +19,10 @@ const BUILTIN_ERROR_NAMES = [
|
|
|
19
19
|
"TypeError",
|
|
20
20
|
"URIError"
|
|
21
21
|
];
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* A property of a thrown value, or undefined when it has none or reading it throws, so a getter or a Proxy
|
|
24
|
+
* cannot break the handling of an error.
|
|
25
|
+
*/
|
|
23
26
|
function errorProperty(value, key) {
|
|
24
27
|
try {
|
|
25
28
|
return typeof value === "object" && value !== null && key in value ? Reflect.get(value, key) : void 0;
|
|
@@ -28,9 +31,11 @@ function errorProperty(value, key) {
|
|
|
28
31
|
}
|
|
29
32
|
}
|
|
30
33
|
/**
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
+
* The error describer for diagnostics, for an SDK's events or a log line its owner writes: `describeError`
|
|
35
|
+
* answers an `ErrorDescription`, and `safeErrorName` an error's name when it is built in or among
|
|
36
|
+
* `errorNames`, else `UnknownError`. Pass constant names of your own errors, never a value taken from an
|
|
37
|
+
* upstream response. No message, record key, URL or query parameter reaches a description, and nothing is
|
|
38
|
+
* logged.
|
|
34
39
|
*/
|
|
35
40
|
function createDiagnostics(errorNames = []) {
|
|
36
41
|
const names = /* @__PURE__ */ new Set([...BUILTIN_ERROR_NAMES, ...errorNames]);
|
|
@@ -118,7 +123,10 @@ function activeTraceId(config) {
|
|
|
118
123
|
return null;
|
|
119
124
|
}
|
|
120
125
|
}
|
|
121
|
-
/**
|
|
126
|
+
/**
|
|
127
|
+
* Logs a refused admission (`maximus.admission.rejected`) and hands it to the observers as background work.
|
|
128
|
+
* Nothing is recorded while telemetry is off or without a background context.
|
|
129
|
+
*/
|
|
122
130
|
function recordAdmission(manifest, env, background, admission) {
|
|
123
131
|
if (!background || !telemetryEnabled(manifest.telemetry, env)) return;
|
|
124
132
|
const event = {
|
|
@@ -148,11 +156,20 @@ function recordAdmission(manifest, env, background, admission) {
|
|
|
148
156
|
for (const observer of manifest.telemetry?.observers ?? []) if (observer.admission) deliver(background, event.requestId, () => observer.admission?.(event, env));
|
|
149
157
|
}
|
|
150
158
|
/**
|
|
151
|
-
* Whether telemetry is on for this env: it is unless `enabled` is false, or a function that returns false
|
|
152
|
-
* has no env to read.
|
|
159
|
+
* Whether telemetry is on for this env: it is unless `enabled` is false, or a function that returns false,
|
|
160
|
+
* has no env to read or throws.
|
|
153
161
|
*/
|
|
154
162
|
function telemetryEnabled(config, env) {
|
|
155
|
-
|
|
163
|
+
if (typeof config?.enabled !== "function") return config?.enabled !== false;
|
|
164
|
+
if (env === void 0) return false;
|
|
165
|
+
try {
|
|
166
|
+
return config.enabled(env);
|
|
167
|
+
} catch {
|
|
168
|
+
try {
|
|
169
|
+
console.error(JSON.stringify({ event: "maximus.telemetry.switch_failed" }));
|
|
170
|
+
} catch {}
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
156
173
|
}
|
|
157
174
|
/** Describes errors by their built-in names only. */
|
|
158
175
|
const diagnostics = createDiagnostics();
|
|
@@ -182,7 +199,8 @@ function diagnosticsEnabled() {
|
|
|
182
199
|
}
|
|
183
200
|
/**
|
|
184
201
|
* Logs an unexpected error by its safe description only (`maximus.unexpected`: error and cause names, issue
|
|
185
|
-
* count, stack locations; never a message) and tells the observers.
|
|
202
|
+
* count, stack locations; never a message) and tells the observers of the current `withDiagnostics` scope.
|
|
203
|
+
* It does nothing while diagnostics are off.
|
|
186
204
|
*/
|
|
187
205
|
function reportUnexpected(error, surface = "application", requestId) {
|
|
188
206
|
if (!diagnosticsEnabled()) return;
|
|
@@ -198,7 +216,10 @@ function reportUnexpected(error, surface = "application", requestId) {
|
|
|
198
216
|
observer.error?.(error, surface, requestId);
|
|
199
217
|
} catch {}
|
|
200
218
|
}
|
|
201
|
-
/**
|
|
219
|
+
/**
|
|
220
|
+
* Hands the observation of one operation call to the observers, as background work. Nothing is recorded
|
|
221
|
+
* while telemetry is off or without a background context.
|
|
222
|
+
*/
|
|
202
223
|
function recordExecution(manifest, env, background, invocation) {
|
|
203
224
|
if (!background || !telemetryEnabled(manifest.telemetry, env)) return;
|
|
204
225
|
const event = {
|