@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.
- 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-CfVZBt7D.js +336 -0
- package/dist/chunks/errors-WfyKhiyk.js +131 -0
- package/dist/chunks/execution-CfZEx_JP.js +84 -0
- package/dist/chunks/generate-C-9FKW0o.js +197 -0
- package/dist/chunks/handler-DWTGoduQ.js +140 -0
- package/dist/chunks/http-layout-_h7xwgPC.js +128 -0
- package/dist/chunks/http-paths-DMBxwpp6.js +218 -0
- package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
- package/dist/chunks/names-ncD7A3DV.js +280 -0
- package/dist/chunks/openapi-CV0KmJpS.js +1588 -0
- package/dist/chunks/openapi-file-OjSs9mRv.js +83 -0
- package/dist/chunks/pages-DyC0m8Zb.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-BPnaa-NK.js → runtime-CVVf5hmp.js} +50 -25
- 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-CCc7fil4.js +410 -0
- package/dist/chunks/src--HZrH1U9.js +568 -0
- package/dist/chunks/standard-failures-CLjxS2ea.js +74 -0
- package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
- package/dist/chunks/{types-BWxDd3tY.d.ts → types-BQYB4Ads.d.ts} +998 -337
- package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
- package/dist/chunks/workers-types-iONp32T4.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 -125
- package/dist/http-paths.d.ts +1 -1
- package/dist/http-paths.js +1 -197
- package/dist/index.d.ts +2 -2
- package/dist/index.js +12 -10
- package/dist/internals.d.ts +1 -1
- package/dist/internals.js +5 -3
- 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 +139 -0
- package/dist/project/config.js +196 -0
- 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 -72
- package/dist/tooling/cli.js +151 -107
- 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 +30 -22
- package/skills/maximus/SKILL.md +165 -69
- 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 -22
- package/templates/project/README.md.template +54 -47
- package/templates/project/middleware/10-response.ts.template +16 -0
- package/templates/project/package.json.template +16 -8
- 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 -5
- 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/execution-B-yy4C7N.js +0 -691
- package/dist/chunks/prepare-project-zi106pWF.js +0 -146
- package/dist/chunks/record-DY-lX9w1.js +0 -34
- package/dist/chunks/src-DPSpGNnT.js +0 -1164
- 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 -44
- 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 -39
- package/templates/project/cloudflare.config.ts.template +0 -24
- package/templates/project/routes/v1/greeting.ts.template +0 -22
- package/templates/project/src/app.ts.template +0 -2
- package/templates/project/src/application.ts.template +0 -26
- package/templates/project/src/index.ts.template +0 -3
- package/templates/project/src/worker.ts.template +0 -6
- 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,336 @@
|
|
|
1
|
+
import { u as hasUncompiledCodecs } from "./validation-fTohBT6R.js";
|
|
2
|
+
import { i as standardErrors } from "./errors-WfyKhiyk.js";
|
|
3
|
+
import { n as readBodyBytes } from "./body-DOIHwIIl.js";
|
|
4
|
+
import { a as operationPathParameters, r as isInputHeaderName, t as createHttpRouteResolver } from "./http-paths-DMBxwpp6.js";
|
|
5
|
+
import { i as pathParameterSchemas } from "./result-CKgZHrnj.js";
|
|
6
|
+
import { C as MAX_BODY_BYTES_CEILING, M as isNamespacedScope, f as hasSchemaReferences, j as operationScopes, r as checkTokenAuthority, s as tokenAudiences, t as createOpenApi, w as STANDARD_CODES } from "./openapi-CV0KmJpS.js";
|
|
7
|
+
import { Kind } from "@sinclair/typebox";
|
|
8
|
+
|
|
9
|
+
// src/internal/exact-length.ts
|
|
10
|
+
/**
|
|
11
|
+
* Byte streams held to the length their headers declare.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Passes a byte stream through only while it keeps its declared length: a chunk that is not bytes,
|
|
15
|
+
* a byte beyond `length` or an end before it errors the stream, so a body never carries more or
|
|
16
|
+
* fewer bytes than its headers say.
|
|
17
|
+
*/
|
|
18
|
+
function exactLength(stream, length) {
|
|
19
|
+
let received = 0;
|
|
20
|
+
return stream.pipeThrough(new TransformStream({
|
|
21
|
+
transform(chunk, controller) {
|
|
22
|
+
if (!(chunk instanceof Uint8Array)) throw new TypeError("A byte stream carried a chunk that is not bytes.");
|
|
23
|
+
received += chunk.byteLength;
|
|
24
|
+
if (received > length) throw new TypeError("A byte stream exceeds its declared length.");
|
|
25
|
+
controller.enqueue(chunk);
|
|
26
|
+
},
|
|
27
|
+
flush() {
|
|
28
|
+
if (received !== length) throw new TypeError("A byte stream ended before its declared length.");
|
|
29
|
+
}
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/binary.ts
|
|
34
|
+
/**
|
|
35
|
+
* Byte bodies and file attachments over HTTP: the on-demand reader of a declared byte body, the checks an
|
|
36
|
+
* attachment output passes before anything is sent, and the exact-length response that serves it.
|
|
37
|
+
*/
|
|
38
|
+
/**
|
|
39
|
+
* The on-demand reader of a request's byte body, held to `maxBytes`. Creating it reads nothing and records
|
|
40
|
+
* nothing of the request.
|
|
41
|
+
*/
|
|
42
|
+
function binaryBody(request, maxBytes) {
|
|
43
|
+
let reading;
|
|
44
|
+
return { read() {
|
|
45
|
+
reading ??= (async () => {
|
|
46
|
+
const encoding = request.headers.get("content-encoding");
|
|
47
|
+
if (encoding && encoding.toLowerCase() !== "identity") return {
|
|
48
|
+
ok: false,
|
|
49
|
+
error: standardErrors.unsupportedMedia.create()
|
|
50
|
+
};
|
|
51
|
+
const result = await readBodyBytes(request, {
|
|
52
|
+
maxBytes,
|
|
53
|
+
signal: request.signal
|
|
54
|
+
});
|
|
55
|
+
return result.ok ? result : {
|
|
56
|
+
ok: false,
|
|
57
|
+
error: result.error.data.reason === "too_large" ? standardErrors.tooLarge.create() : standardErrors.invalidInput.create()
|
|
58
|
+
};
|
|
59
|
+
})();
|
|
60
|
+
return reading;
|
|
61
|
+
} };
|
|
62
|
+
}
|
|
63
|
+
/** Whether an output schema is `AttachmentOutputSchema`. */
|
|
64
|
+
function isAttachmentSchema(schema) {
|
|
65
|
+
return schema[Kind] === "HttpAttachment";
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Whether an output is a well-formed `Attachment` within `maxBytes`: exactly its four fields, bytes of
|
|
69
|
+
* exactly `byteLength` or an unlocked stream, a `type/subtype` media type of at most 255 characters, and a
|
|
70
|
+
* filename of 1 to 512 characters without control characters, slashes or backslashes. Execution checks it
|
|
71
|
+
* before anything is sent.
|
|
72
|
+
*/
|
|
73
|
+
function validAttachment(value, maxBytes) {
|
|
74
|
+
if (!value || typeof value !== "object") return false;
|
|
75
|
+
const keys = Object.keys(value);
|
|
76
|
+
if (keys.length !== 4 || keys.some((key) => ![
|
|
77
|
+
"body",
|
|
78
|
+
"contentType",
|
|
79
|
+
"filename",
|
|
80
|
+
"byteLength"
|
|
81
|
+
].includes(key))) return false;
|
|
82
|
+
const file = value;
|
|
83
|
+
if (!(file.body instanceof Uint8Array || file.body instanceof ReadableStream)) return false;
|
|
84
|
+
if (file.body instanceof ReadableStream && file.body.locked) return false;
|
|
85
|
+
if (!Number.isSafeInteger(file.byteLength) || file.byteLength < 0 || file.byteLength > maxBytes) return false;
|
|
86
|
+
if (file.body instanceof Uint8Array && file.body.byteLength !== file.byteLength) return false;
|
|
87
|
+
if (typeof file.contentType !== "string" || file.contentType.length > 255 || !/^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/u.test(file.contentType)) return false;
|
|
88
|
+
if (typeof file.filename !== "string" || !file.filename.length || file.filename.length > 512 || /[\p{Cc}/\\]/u.test(file.filename)) return false;
|
|
89
|
+
try {
|
|
90
|
+
encodeURIComponent(file.filename);
|
|
91
|
+
return true;
|
|
92
|
+
} catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The response that serves an attachment: its bytes with `content-type`, `content-length`, an RFC 8187
|
|
98
|
+
* `content-disposition`, `cache-control: private, no-store`, a sandboxing `content-security-policy` and
|
|
99
|
+
* `x-content-type-options: nosniff`. A stream is held to exactly `byteLength` bytes, so a handler can send
|
|
100
|
+
* neither more nor fewer than it declared.
|
|
101
|
+
*/
|
|
102
|
+
function attachmentResponse(file, status = 200) {
|
|
103
|
+
const encodedFilename = encodeURIComponent(file.filename).replaceAll(/[!'()*]/gu, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
104
|
+
const body = file.body instanceof Uint8Array ? file.body : exactLength(file.body, file.byteLength);
|
|
105
|
+
return new Response(body, {
|
|
106
|
+
status,
|
|
107
|
+
headers: {
|
|
108
|
+
"cache-control": "private, no-store",
|
|
109
|
+
"content-type": file.contentType,
|
|
110
|
+
"content-length": String(file.byteLength),
|
|
111
|
+
"content-disposition": `attachment; filename="${file.filename.replaceAll(/[^\u0020-\u007E]|["\\]/gu, "_")}"; filename*=UTF-8''${encodedFilename}`,
|
|
112
|
+
"content-security-policy": "default-src 'none'; sandbox",
|
|
113
|
+
"x-content-type-options": "nosniff"
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// src/define-app.ts
|
|
119
|
+
/** Names a Worker entrypoint already uses, or that would break a class or a promise. */
|
|
120
|
+
const RESERVED_NAMES = /* @__PURE__ */ new Set([
|
|
121
|
+
"fetch",
|
|
122
|
+
"connect",
|
|
123
|
+
"constructor",
|
|
124
|
+
"then",
|
|
125
|
+
"scheduled",
|
|
126
|
+
"queue",
|
|
127
|
+
"alarm",
|
|
128
|
+
"__proto__",
|
|
129
|
+
"prototype"
|
|
130
|
+
]);
|
|
131
|
+
/** An MCP tool name: a lowercase letter, then up to 63 letters, digits and underscores. */
|
|
132
|
+
const TOOL_NAME = /^[a-z][A-Za-z0-9_]{0,63}$/;
|
|
133
|
+
/** Every field an operation has: any other, such as a misspelled one, would do nothing. */
|
|
134
|
+
const OPERATION_FIELDS = new Set(Object.keys({
|
|
135
|
+
actorKinds: true,
|
|
136
|
+
http: true,
|
|
137
|
+
visibility: true,
|
|
138
|
+
mcp: true,
|
|
139
|
+
rpc: true,
|
|
140
|
+
scope: true,
|
|
141
|
+
scopeMatch: true,
|
|
142
|
+
conditionalScopes: true,
|
|
143
|
+
failures: true,
|
|
144
|
+
title: true,
|
|
145
|
+
description: true,
|
|
146
|
+
group: true,
|
|
147
|
+
effect: true,
|
|
148
|
+
input: true,
|
|
149
|
+
output: true,
|
|
150
|
+
maxBodyBytes: true,
|
|
151
|
+
maxOutputBytes: true,
|
|
152
|
+
execute: true,
|
|
153
|
+
pipeline: true
|
|
154
|
+
}));
|
|
155
|
+
/**
|
|
156
|
+
* Checks an application against every rule `.build()` enforces, then hands it back unchanged; a refusal is a
|
|
157
|
+
* TypeError. Curried, so `Env` and `C` can be given explicitly while the operations' types are inferred from
|
|
158
|
+
* the argument.
|
|
159
|
+
*/
|
|
160
|
+
function defineApp() {
|
|
161
|
+
return (manifest) => {
|
|
162
|
+
checkApplication(manifest);
|
|
163
|
+
return manifest;
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Every rule, in a fixed order, so an application that breaks several always meets the same refusal first.
|
|
168
|
+
*/
|
|
169
|
+
function checkApplication(manifest) {
|
|
170
|
+
if (!/^[a-z][a-z0-9-]{1,63}$/.test(manifest.namespace)) throw new TypeError("A scope namespace is required.");
|
|
171
|
+
if (!/^[a-z][a-z0-9-]{1,63}$/.test(manifest.name)) throw new TypeError("An application name is a lowercase kebab-case word of 2 to 64 characters.");
|
|
172
|
+
checkDeclaredFailures(manifest.operations, manifest.errors);
|
|
173
|
+
const claimed = {
|
|
174
|
+
routes: /* @__PURE__ */ new Set(),
|
|
175
|
+
tools: /* @__PURE__ */ new Set()
|
|
176
|
+
};
|
|
177
|
+
for (const [name, op] of Object.entries(manifest.operations)) checkOperation(name, op, manifest, claimed);
|
|
178
|
+
createHttpRouteResolver(Object.values(manifest.operations));
|
|
179
|
+
checkSchemaReferences(manifest);
|
|
180
|
+
checkGuides(manifest.mcp?.guides ?? []);
|
|
181
|
+
checkSkills(manifest.mcp?.skills ?? []);
|
|
182
|
+
checkMcpResourceNames(manifest.mcp);
|
|
183
|
+
checkSkillTool(manifest.mcp, claimed.tools);
|
|
184
|
+
if (!validBodyLimit(manifest.maxBodyBytes)) throw new TypeError("The application body limit is a positive integer up to 16 MiB.");
|
|
185
|
+
if (!validBodyLimit(manifest.maxOutputBytes)) throw new TypeError("The application output limit is a positive integer up to 16 MiB.");
|
|
186
|
+
if (new URL(manifest.origin).protocol !== "https:") throw new TypeError("Application origin must use HTTPS.");
|
|
187
|
+
checkTelemetry(manifest.telemetry);
|
|
188
|
+
checkTokenAuthority(manifest.tokens, manifest.namespace);
|
|
189
|
+
tokenAudiences(manifest.tokens);
|
|
190
|
+
if (Object.keys(manifest.tokens.resources ?? {}).length > 0 && manifest.tokens.resourceMetadataUrl === void 0) throw new TypeError("tokens.resources requires tokens.resourceMetadataUrl: name the metadata a 401 challenge points at.");
|
|
191
|
+
}
|
|
192
|
+
/** The callbacks an observer may have, each a function when present. */
|
|
193
|
+
const OBSERVER_CALLBACKS = [
|
|
194
|
+
"execution",
|
|
195
|
+
"admission",
|
|
196
|
+
"error"
|
|
197
|
+
];
|
|
198
|
+
/** Whether a value is an observer: an object whose callbacks, when present, are functions. */
|
|
199
|
+
function isObserver(value) {
|
|
200
|
+
return typeof value === "object" && value !== null && OBSERVER_CALLBACKS.every((name) => {
|
|
201
|
+
const callback = Reflect.get(value, name);
|
|
202
|
+
return callback === void 0 || typeof callback === "function";
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* The telemetry option, as code untyped by TypeScript may give it: a switch that is a boolean or a function,
|
|
207
|
+
* observers that are objects whose callbacks are functions, and a trace id accessor that is a function. A
|
|
208
|
+
* malformed observer would fail every call it observes, and a switch such as `'false'` would leave telemetry
|
|
209
|
+
* on.
|
|
210
|
+
*/
|
|
211
|
+
function checkTelemetry(telemetry) {
|
|
212
|
+
if (telemetry === void 0) return;
|
|
213
|
+
if (typeof telemetry !== "object" || telemetry === null || telemetry.enabled !== void 0 && typeof telemetry.enabled !== "boolean" && typeof telemetry.enabled !== "function" || telemetry.observers !== void 0 && (!Array.isArray(telemetry.observers) || !telemetry.observers.every(isObserver)) || telemetry.traceId !== void 0 && typeof telemetry.traceId !== "function") throw new TypeError("Telemetry takes enabled as true, false or a function of env, observers as a list of objects whose execution, admission and error are functions, and traceId as a function.");
|
|
214
|
+
}
|
|
215
|
+
/** An operation's `failures` name domain codes of the catalog, each once. */
|
|
216
|
+
function checkDeclaredFailures(operations, errors) {
|
|
217
|
+
const domainCodes = new Set(Object.values(errors.definitions).map(({ code }) => code).filter((code) => !STANDARD_CODES.has(code)));
|
|
218
|
+
for (const [name, op] of Object.entries(operations)) if (op.failures && (new Set(op.failures).size !== op.failures.length || op.failures.some((code) => !domainCodes.has(code)))) throw new TypeError(`Operation "${name}": failures lists each domain failure code of the error catalog once; standard failures are always allowed.`);
|
|
219
|
+
}
|
|
220
|
+
/** Every rule one operation keeps, in the order a definition is usually written. */
|
|
221
|
+
function checkOperation(name, op, application, claimed) {
|
|
222
|
+
checkOperationContract(name, op, application.namespace);
|
|
223
|
+
if (application.tokens.scheme?.type === "oauth+bearer" && !op.actorKinds) throw new TypeError(`Operation "${name}": dual authentication requires explicit actor eligibility.`);
|
|
224
|
+
checkHttpExposure(name, op, claimed.routes);
|
|
225
|
+
if (op.conditionalScopes && (!op.conditionalScopes.length || new Set(op.conditionalScopes).size !== op.conditionalScopes.length || op.conditionalScopes.some((scope) => operationScopes(op).includes(scope) || !isNamespacedScope(scope, application.namespace)))) throw new TypeError(`Operation "${name}": conditional scopes require unique namespaced declarations distinct from the admission scope.`);
|
|
226
|
+
if (op.mcp) {
|
|
227
|
+
if (!TOOL_NAME.test(op.mcp.name) || claimed.tools.has(op.mcp.name)) throw new TypeError(`Operation "${name}": MCP tools require unique safe names.`);
|
|
228
|
+
claimed.tools.add(op.mcp.name);
|
|
229
|
+
}
|
|
230
|
+
if (op.rpc && op.rpc !== true && op.rpc.callers.some((caller) => !application.rpc.callers.includes(caller))) throw new TypeError(`Operation "${name}": RPC callers must be allowed by the application.`);
|
|
231
|
+
}
|
|
232
|
+
/** The operation's fields, name, scopes, eligible actors and schemas. */
|
|
233
|
+
function checkOperationContract(name, op, namespace) {
|
|
234
|
+
const unknown = Object.keys(op).find((field) => !OPERATION_FIELDS.has(field));
|
|
235
|
+
if (unknown !== void 0) throw new TypeError(`Operation "${name}": "${unknown}" is not an operation field.`);
|
|
236
|
+
if (op.scopeMatch !== void 0 && op.scopeMatch !== "any" && op.scopeMatch !== "all") throw new TypeError(`Operation "${name}": scopeMatch must be any or all.`);
|
|
237
|
+
if (hasUncompiledCodecs(op.input)) throw new TypeError(`Operation "${name}": its input uses codecs (normalize, transform, inspect, refine, pipe or stripObject) that run only inside inputSchema(); wrap the input in inputSchema().`);
|
|
238
|
+
if (op.actorKinds && (!op.actorKinds.length || new Set(op.actorKinds).size !== op.actorKinds.length || op.actorKinds.some((kind) => kind !== "user" && kind !== "service"))) throw new TypeError(`Operation "${name}": actorKinds must explicitly name eligible users or services.`);
|
|
239
|
+
if (!/^[a-z][a-zA-Z0-9]{0,99}$/.test(name) || RESERVED_NAMES.has(name)) throw new TypeError(`Operation "${name}": use a camelCase name of up to 100 characters that is not a reserved Worker method. Use safe operation names, namespaced scopes and strict object schemas.`);
|
|
240
|
+
const scopes = operationScopes(op);
|
|
241
|
+
if (!scopes.length || new Set(scopes).size !== scopes.length || scopes.some((scope) => !isNamespacedScope(scope, namespace))) throw new TypeError(`Operation "${name}": every scope is "${namespace}:<resource>:<action>", listed once. Use safe operation names, namespaced scopes and strict object schemas.`);
|
|
242
|
+
if (!(strictObject(op.input, op.http?.method !== "GET") && (isAttachmentSchema(op.output) || strictObject(op.output, true)))) throw new TypeError(`Operation "${name}": input and output are strict objects or unions of strict objects; a GET input is one strict object (its query). Use safe operation names, namespaced scopes and strict object schemas.`);
|
|
243
|
+
if (looseRecord(op.input) || looseRecord(op.output)) throw new TypeError(`Operation "${name}": a record whose keys follow a pattern takes additionalProperties: false, t.Record(key, value, { additionalProperties: false }), or a key outside the pattern passes unchecked.`);
|
|
244
|
+
}
|
|
245
|
+
/** Byte bodies, attachments, limits, header-sourced fields and the route itself. */
|
|
246
|
+
function checkHttpExposure(name, op, routes) {
|
|
247
|
+
if (op.http?.body !== void 0 && op.http.body !== "bytes" || op.http?.response !== void 0 && op.http.response !== "attachment") throw new TypeError(`Operation "${name}": unsupported HTTP binary contract.`);
|
|
248
|
+
const binary = op.http?.body === "bytes";
|
|
249
|
+
const attachment = isAttachmentSchema(op.output);
|
|
250
|
+
if ((binary || attachment) && (!op.http || op.mcp || op.rpc)) throw new TypeError(`Operation "${name}": byte bodies and attachments are HTTP-only.`);
|
|
251
|
+
if (op.http?.response === "attachment" !== attachment || binary && op.http?.method === "GET") throw new TypeError(`Operation "${name}": declare matching attachment output and non-GET byte bodies.`);
|
|
252
|
+
if (!validBodyLimit(op.maxOutputBytes)) throw new TypeError(`Operation "${name}": invalid output byte limit.`);
|
|
253
|
+
if (op.http?.successStatus !== void 0 && ![
|
|
254
|
+
200,
|
|
255
|
+
201,
|
|
256
|
+
202
|
|
257
|
+
].includes(op.http.successStatus)) throw new TypeError(`Operation "${name}": invalid success status; use 200, 201 or 202.`);
|
|
258
|
+
if (op.http?.headers) {
|
|
259
|
+
const pathFields = new Set(operationPathParameters(op.http.path));
|
|
260
|
+
const headers = Object.entries(op.http.headers);
|
|
261
|
+
if (!binary || op.input.type !== "object" || new Set(headers.map(([, wire]) => wire.toLowerCase())).size !== headers.length || headers.some(([field, wire]) => !Object.hasOwn(op.input.properties, field) || pathFields.has(field) || !isInputHeaderName(wire))) throw new TypeError(`Operation "${name}": byte operation headers must name unique, non-authority metadata fields.`);
|
|
262
|
+
}
|
|
263
|
+
if (!validBodyLimit(op.maxBodyBytes) || op.maxBodyBytes !== void 0 && op.http?.method === "GET") throw new TypeError(`Operation "${name}": an operation body limit is a positive integer up to 16 MiB, on a non-GET route.`);
|
|
264
|
+
if (op.http) {
|
|
265
|
+
for (const parameter of operationPathParameters(op.http.path)) pathParameterSchemas(op.input, parameter);
|
|
266
|
+
const route = `${op.http.method} ${op.http.path}`;
|
|
267
|
+
if (routes.has(route) || op.effect !== "read" && op.http.method === "GET") throw new TypeError(`Operation "${name}": use unique versioned routes; mutations cannot use GET.`);
|
|
268
|
+
routes.add(route);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* A schema reference (TypeBox `Ref` or `Recursive`) resolves when the OpenAPI document bundles the schemas,
|
|
273
|
+
* to the one definition its name has. An application whose schemas refer to a name is bundled at
|
|
274
|
+
* construction, so a reference that names no single definition is refused before the service starts rather
|
|
275
|
+
* than when the document is first requested; schemas without references have nothing to resolve.
|
|
276
|
+
*/
|
|
277
|
+
function checkSchemaReferences(manifest) {
|
|
278
|
+
if ([...Object.values(manifest.operations).flatMap((op) => [op.input, op.output]), ...Object.values(manifest.errors.definitions).map((definition) => definition.dataSchema)].some(hasSchemaReferences)) createOpenApi(manifest);
|
|
279
|
+
}
|
|
280
|
+
/** Guides are named resources and prompts: each name safe and unique. */
|
|
281
|
+
function checkGuides(guides) {
|
|
282
|
+
if (new Set(guides.map((guide) => guide.name)).size !== guides.length || guides.some((guide) => !/^[a-z][a-z0-9-]{0,63}$/.test(guide.name))) throw new TypeError("Guides require unique safe names.");
|
|
283
|
+
}
|
|
284
|
+
/** The names of the MCP resources the server always lists: the OpenAPI document as JSON and as YAML. */
|
|
285
|
+
const OPENAPI_RESOURCES = ["openapi-json", "openapi-yaml"];
|
|
286
|
+
/**
|
|
287
|
+
* Guides and skills name MCP resources beside the OpenAPI document's, so each name stands for one resource: a
|
|
288
|
+
* guide and a skill never share one, and neither takes `openapi-json` or `openapi-yaml`. `maximus prepare`
|
|
289
|
+
* applies this to `mcp/guides/` and `mcp/skills/` too.
|
|
290
|
+
*/
|
|
291
|
+
function checkMcpResourceNames(mcp) {
|
|
292
|
+
const taken = new Set(OPENAPI_RESOURCES);
|
|
293
|
+
for (const { name } of [...mcp?.guides ?? [], ...mcp?.skills ?? []]) {
|
|
294
|
+
if (taken.has(name)) throw new TypeError(`MCP resource name ${name} is taken: guides and skills need names of their own, and openapi-json and openapi-yaml name the OpenAPI document.`);
|
|
295
|
+
taken.add(name);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
/** The MCP skills: unique Agent Skills names, one-line descriptions and instructions. */
|
|
299
|
+
function checkSkills(skills) {
|
|
300
|
+
if (new Set(skills.map((skill) => skill.name)).size !== skills.length || skills.some((skill) => skill.name.length > 64 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skill.name) || !skill.description.trim() || skill.description.length > 1024 || /[\r\n]/.test(skill.description) || !skill.text.trim())) throw new TypeError("Skills require unique Agent Skills names, a one-line description and instructions.");
|
|
301
|
+
}
|
|
302
|
+
/** The skill tool serves the MCP skills under a name no operation's tool takes. */
|
|
303
|
+
function checkSkillTool(mcp, tools) {
|
|
304
|
+
const skillTool = mcp?.skillTool;
|
|
305
|
+
if (skillTool !== void 0 && (!(mcp?.skills ?? []).length || !TOOL_NAME.test(skillTool) || tools.has(skillTool))) throw new TypeError("A skill tool requires skills and a safe name no operation uses.");
|
|
306
|
+
}
|
|
307
|
+
/** Whether a body or output limit is absent, or a positive integer up to 16 MiB. */
|
|
308
|
+
function validBodyLimit(value) {
|
|
309
|
+
return value === void 0 || Number.isInteger(value) && value > 0 && value <= 16777216;
|
|
310
|
+
}
|
|
311
|
+
/** The key pattern of `t.Record(t.String(), value)`, which every key matches, so every value is checked. */
|
|
312
|
+
const ANY_KEY = "^(.*)$";
|
|
313
|
+
/**
|
|
314
|
+
* Whether a schema holds, at any depth, a record whose keys follow a pattern but that admits other keys:
|
|
315
|
+
* without `additionalProperties: false`, a key outside the pattern passes with any value at all.
|
|
316
|
+
*/
|
|
317
|
+
function looseRecord(schema) {
|
|
318
|
+
if (Array.isArray(schema)) return schema.some(looseRecord);
|
|
319
|
+
if (!schema || typeof schema !== "object") return false;
|
|
320
|
+
const node = schema;
|
|
321
|
+
const patterns = node.patternProperties;
|
|
322
|
+
if (patterns && typeof patterns === "object" && node.additionalProperties !== false && Object.keys(patterns).some((pattern) => pattern !== ANY_KEY)) return true;
|
|
323
|
+
return Object.values(node).some(looseRecord);
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* A strict object (`additionalProperties: false`), or — when `unions` is true —
|
|
327
|
+
* a union whose every member is a strict object, so a request body or a result
|
|
328
|
+
* can be discriminated by a field (`{ channel: 'email', … } | { channel: 'sms', … }`).
|
|
329
|
+
*/
|
|
330
|
+
function strictObject(schema, unions) {
|
|
331
|
+
if (schema.type === "object") return schema.additionalProperties === false;
|
|
332
|
+
const members = schema.anyOf;
|
|
333
|
+
return unions && Array.isArray(members) && members.length > 0 && members.every((member) => strictObject(member, false));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export { isAttachmentSchema as a, binaryBody as i, defineApp as n, validAttachment as o, attachmentResponse as r, checkMcpResourceNames as t };
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { t as STANDARD_FAILURES } from "./standard-failures-CLjxS2ea.js";
|
|
2
|
+
import { i as parseSchema } from "./validation-fTohBT6R.js";
|
|
3
|
+
import { Type } from "@sinclair/typebox";
|
|
4
|
+
import { Value } from "@sinclair/typebox/value";
|
|
5
|
+
|
|
6
|
+
// src/errors.ts
|
|
7
|
+
/**
|
|
8
|
+
* `@arbol-ai/maximus/errors`: error catalogs. `defineErrors` joins the standard failures and an
|
|
9
|
+
* application's own into one catalog whose factories build each failure and whose schema validates every
|
|
10
|
+
* failure an operation returns.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Every failure, whatever its code: the shape each catalog's failures narrow, which every service's errors
|
|
14
|
+
* share. The OpenAPI document names each code's own failure, `NoteNotFoundFailure`, which fixes its code.
|
|
15
|
+
*/
|
|
16
|
+
const FailureSchema = Type.Object({
|
|
17
|
+
code: Type.String({ description: "The failure code, stable across releases." }),
|
|
18
|
+
message: Type.String({ description: "What went wrong, for people; it never contains input values." }),
|
|
19
|
+
retryable: Type.Boolean({ description: "Whether repeating the same request may succeed." }),
|
|
20
|
+
data: Type.Object({}, { description: "Diagnostics the code declares; empty for most codes." })
|
|
21
|
+
}, {
|
|
22
|
+
$id: "Failure",
|
|
23
|
+
additionalProperties: false
|
|
24
|
+
});
|
|
25
|
+
/** The first field issues of a refused input: where, and what was expected. Never a value. */
|
|
26
|
+
const InputIssuesSchema = Type.Object({ issues: Type.Optional(Type.Array(Type.Object({
|
|
27
|
+
path: Type.String({
|
|
28
|
+
maxLength: 256,
|
|
29
|
+
description: "RFC 6901 JSON Pointer to the refused field; empty for the whole input."
|
|
30
|
+
}),
|
|
31
|
+
message: Type.String({ maxLength: 256 })
|
|
32
|
+
}, {
|
|
33
|
+
$id: "ValidationIssue",
|
|
34
|
+
additionalProperties: false
|
|
35
|
+
}), { maxItems: 10 })) }, { additionalProperties: false });
|
|
36
|
+
/** A failure code: uppercase words joined by underscores, as clients branch on it and observations carry it. */
|
|
37
|
+
const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,80}$/;
|
|
38
|
+
/** The standard failures as a catalog defines them; INVALID_INPUT carries its field issues. */
|
|
39
|
+
const STANDARD = {
|
|
40
|
+
...STANDARD_FAILURES,
|
|
41
|
+
invalidInput: {
|
|
42
|
+
...STANDARD_FAILURES.invalidInput,
|
|
43
|
+
dataSchema: InputIssuesSchema
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
/** One failure's schema, its `create()` and its `is()`, from its definition. */
|
|
47
|
+
function factory(definition) {
|
|
48
|
+
const dataSchema = definition.dataSchema ?? Type.Object({}, { additionalProperties: false });
|
|
49
|
+
const schema = Type.Object({
|
|
50
|
+
code: Type.Literal(definition.code),
|
|
51
|
+
message: Type.Literal(definition.message),
|
|
52
|
+
retryable: Type.Literal(definition.retryable ?? false),
|
|
53
|
+
data: dataSchema
|
|
54
|
+
}, { additionalProperties: false });
|
|
55
|
+
return {
|
|
56
|
+
schema,
|
|
57
|
+
create(...args) {
|
|
58
|
+
const data = parseSchema(dataSchema, args.at(0) ?? {});
|
|
59
|
+
return {
|
|
60
|
+
code: definition.code,
|
|
61
|
+
message: definition.message,
|
|
62
|
+
retryable: definition.retryable ?? false,
|
|
63
|
+
data
|
|
64
|
+
};
|
|
65
|
+
},
|
|
66
|
+
is(value) {
|
|
67
|
+
return Value.Check(schema, value);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** The catalog's own members, which no failure may be named after. */
|
|
72
|
+
const CATALOG_MEMBERS = {
|
|
73
|
+
schema: true,
|
|
74
|
+
definitions: true,
|
|
75
|
+
status: true,
|
|
76
|
+
retryAfter: true,
|
|
77
|
+
validate: true
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* An error catalog: the standard failures and the application's own, each with a fixed code, status, message
|
|
81
|
+
* and retry semantics. `catalog.name.create(data?)` builds a failure; the application validates every failure
|
|
82
|
+
* an operation returns against the catalog. It throws a TypeError for a name the standard failures or the
|
|
83
|
+
* catalog's members use, a code that is not uppercase words joined by underscores, a repeated code, a status
|
|
84
|
+
* outside 400 to 599, or a `dataSchema` that is not a strict object.
|
|
85
|
+
*/
|
|
86
|
+
function defineErrors(domain) {
|
|
87
|
+
const own = domain;
|
|
88
|
+
if (Object.keys(own).some((name) => Object.hasOwn(STANDARD, name) || Object.hasOwn(CATALOG_MEMBERS, name))) throw new TypeError("Domain errors cannot replace framework errors or catalog members.");
|
|
89
|
+
const definitions = {
|
|
90
|
+
...STANDARD,
|
|
91
|
+
...own
|
|
92
|
+
};
|
|
93
|
+
const byCode = /* @__PURE__ */ new Map();
|
|
94
|
+
for (const definition of Object.values(definitions)) {
|
|
95
|
+
if (!ERROR_CODE.test(definition.code)) throw new TypeError(`An error code is uppercase words joined by underscores, such as RECORD_NOT_FOUND: ${definition.code}`);
|
|
96
|
+
if (byCode.has(definition.code) || definition.status < 400 || definition.status > 599) throw new TypeError("Error definitions require unique codes and failure statuses.");
|
|
97
|
+
if ("dataSchema" in definition && definition.dataSchema && (definition.dataSchema.type !== "object" || definition.dataSchema.additionalProperties !== false)) throw new TypeError("Domain error data must be a strict object schema.");
|
|
98
|
+
byCode.set(definition.code, definition);
|
|
99
|
+
}
|
|
100
|
+
const factories = Object.fromEntries(Object.entries(definitions).map(([name, value]) => [name, factory(value)]));
|
|
101
|
+
const schema = Type.Union(Object.values(factories).map((value) => value.schema));
|
|
102
|
+
return Object.assign(factories, {
|
|
103
|
+
schema,
|
|
104
|
+
definitions,
|
|
105
|
+
status(code) {
|
|
106
|
+
return byCode.get(code)?.status ?? 500;
|
|
107
|
+
},
|
|
108
|
+
retryAfter(code) {
|
|
109
|
+
return byCode.get(code)?.retryAfter;
|
|
110
|
+
},
|
|
111
|
+
validate(error) {
|
|
112
|
+
return parseSchema(schema, error);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The catalog of the framework's own failures (`INVALID_INPUT`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, …).
|
|
118
|
+
*/
|
|
119
|
+
const standardErrors = defineErrors({});
|
|
120
|
+
/** The schema of a Result: `{ ok: true, value } | { ok: false, error }`. */
|
|
121
|
+
function resultSchema(value, error) {
|
|
122
|
+
return Type.Union([Type.Object({
|
|
123
|
+
ok: Type.Literal(true),
|
|
124
|
+
value
|
|
125
|
+
}, { additionalProperties: false }), Type.Object({
|
|
126
|
+
ok: Type.Literal(false),
|
|
127
|
+
error
|
|
128
|
+
}, { additionalProperties: false })]);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export { standardErrors as i, defineErrors as n, resultSchema as r, FailureSchema as t };
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { t as decodeInput } from "./validation-fTohBT6R.js";
|
|
2
|
+
import { i as standardErrors } from "./errors-WfyKhiyk.js";
|
|
3
|
+
import { a as isAttachmentSchema, o as validAttachment } from "./define-app-CfVZBt7D.js";
|
|
4
|
+
import { t as err } from "./result-CKgZHrnj.js";
|
|
5
|
+
import { A as operationOutputLimit, b as ADMISSION_CODES, k as operationMatchesScopes, w as STANDARD_CODES, x as BODY_CODES } from "./openapi-CV0KmJpS.js";
|
|
6
|
+
import { a as telemetryEnabled, i as reportUnexpected } from "./telemetry-C3LfZcOB.js";
|
|
7
|
+
import { Value } from "@sinclair/typebox/value";
|
|
8
|
+
|
|
9
|
+
// src/execution.ts
|
|
10
|
+
/**
|
|
11
|
+
* The one execution path every transport calls: the caller's eligibility, input decoding, context
|
|
12
|
+
* preparation, middleware, the handler, and the checks on what it returns.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* The execution path every transport shares: checks that the caller may run the operation (its scopes when
|
|
16
|
+
* `authority` is given, its actor kind, and `authority` itself when the operation has conditional scopes),
|
|
17
|
+
* decodes the input, prepares the context, runs the middleware and the handler, then checks the result
|
|
18
|
+
* against the catalog, the declared failures, the output schema and the output limit. A refused caller
|
|
19
|
+
* answers `FORBIDDEN` and a refused input `INVALID_INPUT`. An unexpected error becomes `INTERNAL_ERROR`,
|
|
20
|
+
* reported while telemetry is on, and is never thrown.
|
|
21
|
+
*/
|
|
22
|
+
async function executeOperation(manifest, operation, env, principal, input, authority, background, body) {
|
|
23
|
+
if (operation.conditionalScopes?.length && !authority || authority && !operationMatchesScopes(operation, authority.scopes) || operation.actorKinds && !operation.actorKinds.includes(principal.actorKind)) return err(standardErrors.forbidden.create());
|
|
24
|
+
try {
|
|
25
|
+
const admitted = decodeInput(operation.input, input);
|
|
26
|
+
if (!admitted.ok) return err(standardErrors.invalidInput.create(admitted.error.data));
|
|
27
|
+
const trustedAuthority = authority ? Object.freeze({
|
|
28
|
+
surface: authority.surface,
|
|
29
|
+
scopes: Object.freeze([...authority.scopes]),
|
|
30
|
+
client: Object.freeze({ ...authority.client }),
|
|
31
|
+
...authority.token ? { token: authority.token } : {}
|
|
32
|
+
}) : void 0;
|
|
33
|
+
const invocation = {
|
|
34
|
+
env,
|
|
35
|
+
principal,
|
|
36
|
+
input: admitted.value,
|
|
37
|
+
...body ? { body } : {},
|
|
38
|
+
...background ? { background } : {},
|
|
39
|
+
...trustedAuthority ? { authority: trustedAuthority } : {}
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* A failure the call answers, from its context, middleware or handler: one of the catalog and, when the
|
|
43
|
+
* operation declares its failures, a declared or standard one. A failure only admission answers, or a
|
|
44
|
+
* body's for an operation that reads no byte body, is never the operation's. Any other is the server's
|
|
45
|
+
* error.
|
|
46
|
+
*/
|
|
47
|
+
const declared = (answered) => {
|
|
48
|
+
const failure = manifest.errors.validate(answered);
|
|
49
|
+
if (ADMISSION_CODES.has(failure.code) || BODY_CODES.has(failure.code) && operation.http?.body !== "bytes") throw new TypeError(`Failure ${failure.code} is answered before an operation runs, never by it`);
|
|
50
|
+
if (operation.failures && !STANDARD_CODES.has(failure.code) && !operation.failures.includes(failure.code)) throw new TypeError(`Undeclared failure ${failure.code}`);
|
|
51
|
+
return failure;
|
|
52
|
+
};
|
|
53
|
+
const context = operation.pipeline ? await operation.pipeline.context(invocation) : await manifest.context(invocation);
|
|
54
|
+
if (!context.ok) return err(declared(context.error));
|
|
55
|
+
const chain = operation.pipeline?.middleware ?? manifest.middleware ?? [];
|
|
56
|
+
let latest = -1;
|
|
57
|
+
/**
|
|
58
|
+
* Runs the middleware at `index`, whose `next` runs the following one, until the handler; each `next`
|
|
59
|
+
* runs once.
|
|
60
|
+
*/
|
|
61
|
+
const dispatch = async (index) => {
|
|
62
|
+
if (index <= latest) throw new Error("Middleware next() may be called only once.");
|
|
63
|
+
latest = index;
|
|
64
|
+
const middleware = chain[index];
|
|
65
|
+
return await (middleware ? middleware(context.value, () => dispatch(index + 1)) : operation.execute(context.value, admitted.value));
|
|
66
|
+
};
|
|
67
|
+
const result = await dispatch(0);
|
|
68
|
+
if (!result || typeof result.ok !== "boolean" || !Object.hasOwn(result, "ok") || Object.keys(result).length !== 2 || !Object.hasOwn(result, result.ok ? "value" : "error")) throw new TypeError("Invalid operation result");
|
|
69
|
+
if (!result.ok) return err(declared(result.error));
|
|
70
|
+
const maxOutputBytes = operationOutputLimit(manifest, operation);
|
|
71
|
+
if (isAttachmentSchema(operation.output)) {
|
|
72
|
+
if (!validAttachment(result.value, maxOutputBytes)) throw new TypeError("Invalid attachment output");
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
if (!Value.Check(operation.output, result.value)) throw new TypeError("Invalid operation output");
|
|
76
|
+
if (new TextEncoder().encode(JSON.stringify(result.value)).byteLength > maxOutputBytes) throw new TypeError("Operation output exceeds its limit");
|
|
77
|
+
return result;
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (telemetryEnabled(manifest.telemetry, env)) reportUnexpected(error, "operation", principal.requestId);
|
|
80
|
+
return err(standardErrors.internal.create());
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export { executeOperation as t };
|