@arbol-ai/maximus 7.3.1 → 7.4.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 (55) hide show
  1. package/dist/analytics/analytics.d.ts +1 -1
  2. package/dist/body.d.ts +1 -1
  3. package/dist/chunks/builder-BiXv7d2v.js +100 -0
  4. package/dist/chunks/{execution-B-yy4C7N.js → define-app-DvD_1jUE.js} +5 -71
  5. package/dist/chunks/errors-D7zG9kx9.js +126 -0
  6. package/dist/chunks/execution-kVUJPy1A.js +71 -0
  7. package/dist/chunks/http-paths-yKD6TSNJ.js +199 -0
  8. package/dist/chunks/prepare-project-CMyGSEtI.js +236 -0
  9. package/dist/chunks/prepare-project-MtS0-W_n.js +3 -0
  10. package/dist/chunks/{runtime-BPnaa-NK.js → runtime-DlqA7J38.js} +4 -3
  11. package/dist/chunks/{src-DPSpGNnT.js → src-N3oyx5QF.js} +31 -104
  12. package/dist/chunks/standard-failures-CLjxS2ea.js +74 -0
  13. package/dist/chunks/{types-BWxDd3tY.d.ts → types-DQdfRF3f.d.ts} +13 -4
  14. package/dist/client/client.d.ts +1 -1
  15. package/dist/client/client.js +2 -2
  16. package/dist/diagnostics.d.ts +1 -1
  17. package/dist/errors.d.ts +1 -1
  18. package/dist/errors.js +1 -124
  19. package/dist/http-paths.d.ts +1 -1
  20. package/dist/http-paths.js +1 -197
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +5 -4
  23. package/dist/internals.d.ts +1 -1
  24. package/dist/internals.js +3 -2
  25. package/dist/mcp/index.d.ts +1 -1
  26. package/dist/mcp/index.js +3 -3
  27. package/dist/project/config.d.ts +101 -0
  28. package/dist/project/config.js +80 -0
  29. package/dist/project/index.d.ts +1 -1
  30. package/dist/project/index.js +3 -3
  31. package/dist/schemas.d.ts +1 -1
  32. package/dist/standard-failures.js +1 -72
  33. package/dist/tooling/cli.js +10 -10
  34. package/dist/tooling/vite.d.ts +1 -1
  35. package/dist/tooling/vite.js +38 -25
  36. package/dist/webhooks.d.ts +1 -1
  37. package/dist/workers/runtime.d.ts +1 -1
  38. package/dist/workers/runtime.js +1 -1
  39. package/package.json +5 -1
  40. package/skills/maximus/SKILL.md +4 -5
  41. package/skills/maximus/references/building-a-service.md +8 -8
  42. package/skills/maximus/references/publishing-and-verification.md +14 -11
  43. package/templates/project/.agents/skills/project/SKILL.md.template +7 -7
  44. package/templates/project/CLAUDE.md.template +10 -7
  45. package/templates/project/README.md.template +8 -7
  46. package/templates/project/cloudflare.config.ts.template +1 -1
  47. package/templates/project/{src/application.ts.template → maximus.config.ts.template} +4 -10
  48. package/templates/project/middleware/10-response.ts.template +13 -0
  49. package/templates/project/package.json.template +4 -0
  50. package/templates/project/routes/v1/greeting.ts.template +33 -17
  51. package/templates/project/tsconfig.json.template +1 -0
  52. package/dist/chunks/prepare-project-zi106pWF.js +0 -146
  53. package/templates/project/src/app.ts.template +0 -2
  54. package/templates/project/src/index.ts.template +0 -3
  55. package/templates/project/src/worker.ts.template +0 -6
@@ -1,4 +1,4 @@
1
- import { $t as Observer, En as Result, Fn as Failure } from "../chunks/types-BWxDd3tY.js";
1
+ import { Rn as Failure, kn as Result, nn as Observer } from "../chunks/types-DQdfRF3f.js";
2
2
  import { Static } from "@sinclair/typebox";
3
3
  /** An analytics event: the allowlisted metadata of one operation call, flattened, with an id of its own. */
4
4
  export declare const ExecutionEventSchema: import("@sinclair/typebox").TObject<{
package/dist/body.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { S as readBodyText, _ as retryAfterSeconds, b as HttpBodyFailureReason, g as readJsonResponse, h as readJsonBody, m as isJsonMediaType, v as BodyReadOptions, x as readBodyBytes, y as HttpBodyFailure } from "./chunks/types-BWxDd3tY.js";
1
+ import { S as readBodyText, _ as retryAfterSeconds, b as HttpBodyFailureReason, g as readJsonResponse, h as readJsonBody, m as isJsonMediaType, v as BodyReadOptions, x as readBodyBytes, y as HttpBodyFailure } from "./chunks/types-DQdfRF3f.js";
2
2
  export { type BodyReadOptions, type HttpBodyFailure, type HttpBodyFailureReason, isJsonMediaType, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
@@ -0,0 +1,100 @@
1
+ import { _ as composeOperations, f as ok, t as defineApp } from "./define-app-DvD_1jUE.js";
2
+
3
+ // src/builder.ts
4
+ /** Immutable builders let independent resource modules share inferred context without overwriting routes. */
5
+ var ApplicationBuilder = class ApplicationBuilder {
6
+ /**
7
+ * The application declared so far: its configuration, context preparation, middleware and operations, which
8
+ * `.build()` checks.
9
+ */
10
+ definition;
11
+ root;
12
+ constructor(definition, root = definition) {
13
+ this.definition = definition;
14
+ this.root = root;
15
+ }
16
+ /**
17
+ * Declares an operation: a camelCase name no other operation uses, its definition (scope, words, effect,
18
+ * schemas and exposure) and its handler, which receives the prepared context and the decoded input and
19
+ * returns a Result.
20
+ */
21
+ operation(name, definition, execute) {
22
+ const operations = composeOperations(this.definition.operations, { [name]: {
23
+ ...definition,
24
+ execute,
25
+ pipeline: {
26
+ context: (invocation) => this.definition.context({
27
+ ...invocation,
28
+ operation: name
29
+ }),
30
+ middleware: this.definition.middleware ?? []
31
+ }
32
+ } });
33
+ return new ApplicationBuilder({
34
+ ...this.definition,
35
+ operations
36
+ }, this.root);
37
+ }
38
+ /**
39
+ * Adds what `resolve` returns to the context of every operation declared after it. It runs after admission
40
+ * and before the middleware; a failure it returns answers the call. Derive before declaring operations.
41
+ */
42
+ derive(resolve) {
43
+ if (Object.keys(this.definition.operations).length) throw new TypeError("Derive context before declaring operations.");
44
+ const previous = this.definition.context;
45
+ return new ApplicationBuilder({
46
+ ...this.definition,
47
+ context: async (invocation) => {
48
+ const context = await previous(invocation);
49
+ if (!context.ok) return context;
50
+ const derived = await resolve(context.value);
51
+ return derived.ok ? ok({
52
+ ...context.value,
53
+ ...derived.value
54
+ }) : derived;
55
+ }
56
+ }, this.root);
57
+ }
58
+ /**
59
+ * Wraps every operation declared after it, once the caller is admitted and the context prepared. The
60
+ * middleware calls `next` at most once.
61
+ */
62
+ use(middleware) {
63
+ return new ApplicationBuilder({
64
+ ...this.definition,
65
+ middleware: [...this.definition.middleware ?? [], middleware]
66
+ }, this.root);
67
+ }
68
+ /**
69
+ * Adds the operations of a resource module built from the same application; each keeps the context and
70
+ * middleware it was declared with.
71
+ */
72
+ mount(module) {
73
+ if (this.root !== module.root) throw new TypeError("Resource groups must derive from the same application.");
74
+ return new ApplicationBuilder({
75
+ ...this.definition,
76
+ operations: composeOperations(this.definition.operations, module.definition.operations)
77
+ }, this.root);
78
+ }
79
+ /**
80
+ * Checks every rule the application must keep and returns it. A refusal is a TypeError that names the rule
81
+ * and the operation that breaks it.
82
+ */
83
+ build() {
84
+ return defineApp()(this.definition);
85
+ }
86
+ };
87
+ /**
88
+ * Starts an application: its name, scope namespace, origin, token policy, error catalog and RPC callers.
89
+ * Chain `.derive()` and `.use()` to prepare each call, `.operation()` to declare operations, `.mount()` to
90
+ * compose resource modules that share this base, then `.build()`.
91
+ */
92
+ function maximus(configuration) {
93
+ return new ApplicationBuilder({
94
+ ...configuration,
95
+ operations: {},
96
+ context: (invocation) => Promise.resolve(ok(invocation))
97
+ });
98
+ }
99
+
100
+ export { maximus as t };
@@ -1,13 +1,11 @@
1
- import { STANDARD_FAILURES } from "../standard-failures.js";
2
- import { l as hasUncompiledCodecs, r as parseInput, t as decodeInput } from "./validation-r-sgmsqb.js";
3
- import { standardErrors } from "../errors.js";
1
+ import { t as STANDARD_FAILURES } from "./standard-failures-CLjxS2ea.js";
2
+ import { l as hasUncompiledCodecs, r as parseInput } from "./validation-r-sgmsqb.js";
3
+ import { i as standardErrors } from "./errors-D7zG9kx9.js";
4
4
  import { n as readBodyBytes } from "./body-6LichrQm.js";
5
5
  import { n as exactLength, t as isRecord } from "./record-DY-lX9w1.js";
6
- import { createHttpRouteResolver, isInputHeaderName, operationPathParameters } from "../http-paths.js";
6
+ import { a as operationPathParameters, r as isInputHeaderName, t as createHttpRouteResolver } from "./http-paths-yKD6TSNJ.js";
7
7
  import { i as UuidSchema, n as OrganizationIdSchema } from "./schemas-CzTvbXb6.js";
8
- import { a as telemetryEnabled, i as reportUnexpected } from "./telemetry-BTwB68m5.js";
9
8
  import { Kind, Type } from "@sinclair/typebox";
10
- import { Value } from "@sinclair/typebox/value";
11
9
  import { createRemoteJWKSet, jwtVerify } from "jose";
12
10
 
13
11
  // src/binary.ts
@@ -624,68 +622,4 @@ function strictObject(schema, unions) {
624
622
  return unions && Array.isArray(members) && members.length > 0 && members.every((member) => strictObject(member, false));
625
623
  }
626
624
 
627
- // src/execution.ts
628
- /**
629
- * The one execution path every transport calls: the caller's eligibility, input decoding, context
630
- * preparation, middleware, the handler, and the checks on what it returns.
631
- */
632
- /**
633
- * The execution path every transport shares: checks that the caller may run the operation, decodes the input,
634
- * prepares the context, runs the middleware and the handler, then checks the result against the declared
635
- * output and failures. An unexpected error becomes `INTERNAL_ERROR` and is reported, never thrown.
636
- */
637
- async function executeOperation(manifest, operation, env, principal, input, authority, background, body) {
638
- if (operation.conditionalScopes?.length && !authority || authority && !operationMatchesScopes(operation, authority.scopes) || operation.actorKinds && !operation.actorKinds.includes(principal.actorKind)) return err(standardErrors.forbidden.create());
639
- const admitted = decodeInput(operation.input, input);
640
- if (!admitted.ok) return err(standardErrors.invalidInput.create(admitted.error.data));
641
- try {
642
- const trustedAuthority = authority ? Object.freeze({
643
- surface: authority.surface,
644
- scopes: Object.freeze([...authority.scopes]),
645
- client: Object.freeze({ ...authority.client }),
646
- ...authority.token ? { token: authority.token } : {}
647
- }) : void 0;
648
- const invocation = {
649
- env,
650
- principal,
651
- input: admitted.value,
652
- ...body ? { body } : {},
653
- ...background ? { background } : {},
654
- ...trustedAuthority ? { authority: trustedAuthority } : {}
655
- };
656
- const context = operation.pipeline ? await operation.pipeline.context(invocation) : await manifest.context(invocation);
657
- if (!context.ok) return err(manifest.errors.validate(context.error));
658
- const chain = operation.pipeline?.middleware ?? manifest.middleware ?? [];
659
- let latest = -1;
660
- /**
661
- * Runs the middleware at `index`, whose `next` runs the following one, until the handler; each `next`
662
- * runs once.
663
- */
664
- const dispatch = async (index) => {
665
- if (index <= latest) throw new Error("Middleware next() may be called only once.");
666
- latest = index;
667
- const middleware = chain[index];
668
- return await (middleware ? middleware(context.value, () => dispatch(index + 1)) : operation.execute(context.value, admitted.value));
669
- };
670
- const result = await dispatch(0);
671
- 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");
672
- if (!result.ok) {
673
- const failure = manifest.errors.validate(result.error);
674
- if (operation.failures && !STANDARD_CODES.has(failure.code) && !operation.failures.includes(failure.code)) throw new TypeError(`Undeclared failure ${failure.code}`);
675
- return err(failure);
676
- }
677
- const maxOutputBytes = operationOutputLimit(manifest, operation);
678
- if (isAttachmentSchema(operation.output)) {
679
- if (!validAttachment(result.value, maxOutputBytes)) throw new TypeError("Invalid attachment output");
680
- return result;
681
- }
682
- if (!Value.Check(operation.output, result.value)) throw new TypeError("Invalid operation output");
683
- if (new TextEncoder().encode(JSON.stringify(result.value)).byteLength > maxOutputBytes) throw new TypeError("Operation output exceeds its limit");
684
- return result;
685
- } catch (error) {
686
- if (telemetryEnabled(manifest.telemetry, env)) reportUnexpected(error, "operation", principal.requestId);
687
- return err(standardErrors.internal.create());
688
- }
689
- }
690
-
691
- export { operationMatchesScopes as C, pathParameterSchemas as D, matchesScopes as E, attachmentResponse as O, operationBodyLimit as S, operationScopes as T, STANDARD_CODES as _, createTokenVerifier as a, mcpOpenWorld as b, tokenEndpoints as c, err as d, isResult as f, MAX_BODY_BYTES_CEILING as g, DEFAULT_MAX_BODY_BYTES as h, createTokenAuthorization as i, binaryBody as k, tokenIssuer as l, sha256Hex as m, defineApp as n, projectToken as o, ok as p, PrincipalSchema as r, tokenAudiences as s, executeOperation as t, usesOwnBearer as u, composeOperations as v, operationOutputLimit as w, operation as x, isPublicOperation as y };
625
+ export { validAttachment as A, operationOutputLimit as C, attachmentResponse as D, pathParameterSchemas as E, binaryBody as O, operationMatchesScopes as S, matchesScopes as T, composeOperations as _, projectToken as a, operation as b, tokenIssuer as c, isResult as d, ok as f, STANDARD_CODES as g, MAX_BODY_BYTES_CEILING as h, createTokenVerifier as i, isAttachmentSchema as k, usesOwnBearer as l, DEFAULT_MAX_BODY_BYTES as m, PrincipalSchema as n, tokenAudiences as o, sha256Hex as p, createTokenAuthorization as r, tokenEndpoints as s, defineApp as t, err as u, isPublicOperation as v, operationScopes as w, operationBodyLimit as x, mcpOpenWorld as y };
@@ -0,0 +1,126 @@
1
+ import { t as STANDARD_FAILURES } from "./standard-failures-CLjxS2ea.js";
2
+ import { i as parseSchema } from "./validation-r-sgmsqb.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 base each catalog's failures narrow. The OpenAPI document
14
+ * names it `Failure`, so every service's errors share one type.
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
+ /** The standard failures as a catalog defines them; INVALID_INPUT carries its field issues. */
37
+ const STANDARD = {
38
+ ...STANDARD_FAILURES,
39
+ invalidInput: {
40
+ ...STANDARD_FAILURES.invalidInput,
41
+ dataSchema: InputIssuesSchema
42
+ }
43
+ };
44
+ /** One failure's schema, its `create()` and its `is()`, from its definition. */
45
+ function factory(definition) {
46
+ const dataSchema = definition.dataSchema ?? Type.Object({}, { additionalProperties: false });
47
+ const schema = Type.Object({
48
+ code: Type.Literal(definition.code),
49
+ message: Type.Literal(definition.message),
50
+ retryable: Type.Literal(definition.retryable ?? false),
51
+ data: dataSchema
52
+ }, { additionalProperties: false });
53
+ return {
54
+ schema,
55
+ create(...args) {
56
+ const data = parseSchema(dataSchema, args.at(0) ?? {});
57
+ return {
58
+ code: definition.code,
59
+ message: definition.message,
60
+ retryable: definition.retryable ?? false,
61
+ data
62
+ };
63
+ },
64
+ is(value) {
65
+ return Value.Check(schema, value);
66
+ }
67
+ };
68
+ }
69
+ /** The catalog's own members, which no failure may be named after. */
70
+ const CATALOG_MEMBERS = {
71
+ schema: true,
72
+ definitions: true,
73
+ status: true,
74
+ retryAfter: true,
75
+ validate: true
76
+ };
77
+ /**
78
+ * An error catalog: the standard failures and the application's own, each with a fixed code, status, message
79
+ * and retry semantics. `catalog.name.create(data?)` builds a failure; the application validates every failure
80
+ * an operation returns against the catalog.
81
+ */
82
+ function defineErrors(domain) {
83
+ const own = domain;
84
+ 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.");
85
+ const definitions = {
86
+ ...STANDARD,
87
+ ...own
88
+ };
89
+ const byCode = /* @__PURE__ */ new Map();
90
+ for (const definition of Object.values(definitions)) {
91
+ if (byCode.has(definition.code) || definition.status < 400 || definition.status > 599) throw new TypeError("Error definitions require unique codes and failure statuses.");
92
+ 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.");
93
+ byCode.set(definition.code, definition);
94
+ }
95
+ const factories = Object.fromEntries(Object.entries(definitions).map(([name, value]) => [name, factory(value)]));
96
+ const schema = Type.Union(Object.values(factories).map((value) => value.schema));
97
+ return Object.assign(factories, {
98
+ schema,
99
+ definitions,
100
+ status(code) {
101
+ return byCode.get(code)?.status ?? 500;
102
+ },
103
+ retryAfter(code) {
104
+ return byCode.get(code)?.retryAfter;
105
+ },
106
+ validate(error) {
107
+ return parseSchema(schema, error);
108
+ }
109
+ });
110
+ }
111
+ /**
112
+ * The catalog of the framework's own failures (`INVALID_INPUT`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, …).
113
+ */
114
+ const standardErrors = defineErrors({});
115
+ /** The schema of a Result: `{ ok: true, value } | { ok: false, error }`. */
116
+ function resultSchema(value, error) {
117
+ return Type.Union([Type.Object({
118
+ ok: Type.Literal(true),
119
+ value
120
+ }, { additionalProperties: false }), Type.Object({
121
+ ok: Type.Literal(false),
122
+ error
123
+ }, { additionalProperties: false })]);
124
+ }
125
+
126
+ export { standardErrors as i, defineErrors as n, resultSchema as r, FailureSchema as t };
@@ -0,0 +1,71 @@
1
+ import { t as decodeInput } from "./validation-r-sgmsqb.js";
2
+ import { i as standardErrors } from "./errors-D7zG9kx9.js";
3
+ import { A as validAttachment, C as operationOutputLimit, S as operationMatchesScopes, g as STANDARD_CODES, k as isAttachmentSchema, u as err } from "./define-app-DvD_1jUE.js";
4
+ import { a as telemetryEnabled, i as reportUnexpected } from "./telemetry-BTwB68m5.js";
5
+ import { Value } from "@sinclair/typebox/value";
6
+
7
+ // src/execution.ts
8
+ /**
9
+ * The one execution path every transport calls: the caller's eligibility, input decoding, context
10
+ * preparation, middleware, the handler, and the checks on what it returns.
11
+ */
12
+ /**
13
+ * The execution path every transport shares: checks that the caller may run the operation, decodes the input,
14
+ * prepares the context, runs the middleware and the handler, then checks the result against the declared
15
+ * output and failures. An unexpected error becomes `INTERNAL_ERROR` and is reported, never thrown.
16
+ */
17
+ async function executeOperation(manifest, operation, env, principal, input, authority, background, body) {
18
+ if (operation.conditionalScopes?.length && !authority || authority && !operationMatchesScopes(operation, authority.scopes) || operation.actorKinds && !operation.actorKinds.includes(principal.actorKind)) return err(standardErrors.forbidden.create());
19
+ const admitted = decodeInput(operation.input, input);
20
+ if (!admitted.ok) return err(standardErrors.invalidInput.create(admitted.error.data));
21
+ try {
22
+ const trustedAuthority = authority ? Object.freeze({
23
+ surface: authority.surface,
24
+ scopes: Object.freeze([...authority.scopes]),
25
+ client: Object.freeze({ ...authority.client }),
26
+ ...authority.token ? { token: authority.token } : {}
27
+ }) : void 0;
28
+ const invocation = {
29
+ env,
30
+ principal,
31
+ input: admitted.value,
32
+ ...body ? { body } : {},
33
+ ...background ? { background } : {},
34
+ ...trustedAuthority ? { authority: trustedAuthority } : {}
35
+ };
36
+ const context = operation.pipeline ? await operation.pipeline.context(invocation) : await manifest.context(invocation);
37
+ if (!context.ok) return err(manifest.errors.validate(context.error));
38
+ const chain = operation.pipeline?.middleware ?? manifest.middleware ?? [];
39
+ let latest = -1;
40
+ /**
41
+ * Runs the middleware at `index`, whose `next` runs the following one, until the handler; each `next`
42
+ * runs once.
43
+ */
44
+ const dispatch = async (index) => {
45
+ if (index <= latest) throw new Error("Middleware next() may be called only once.");
46
+ latest = index;
47
+ const middleware = chain[index];
48
+ return await (middleware ? middleware(context.value, () => dispatch(index + 1)) : operation.execute(context.value, admitted.value));
49
+ };
50
+ const result = await dispatch(0);
51
+ 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");
52
+ if (!result.ok) {
53
+ const failure = manifest.errors.validate(result.error);
54
+ if (operation.failures && !STANDARD_CODES.has(failure.code) && !operation.failures.includes(failure.code)) throw new TypeError(`Undeclared failure ${failure.code}`);
55
+ return err(failure);
56
+ }
57
+ const maxOutputBytes = operationOutputLimit(manifest, operation);
58
+ if (isAttachmentSchema(operation.output)) {
59
+ if (!validAttachment(result.value, maxOutputBytes)) throw new TypeError("Invalid attachment output");
60
+ return result;
61
+ }
62
+ if (!Value.Check(operation.output, result.value)) throw new TypeError("Invalid operation output");
63
+ if (new TextEncoder().encode(JSON.stringify(result.value)).byteLength > maxOutputBytes) throw new TypeError("Operation output exceeds its limit");
64
+ return result;
65
+ } catch (error) {
66
+ if (telemetryEnabled(manifest.telemetry, env)) reportUnexpected(error, "operation", principal.requestId);
67
+ return err(standardErrors.internal.create());
68
+ }
69
+ }
70
+
71
+ export { executeOperation as t };
@@ -0,0 +1,199 @@
1
+ // src/http-paths.ts
2
+ /**
3
+ * `@arbol-ai/maximus/http-paths`: versioned route templates, path parameter decoding, and the router that
4
+ * matches a request to exactly one operation.
5
+ */
6
+ /** A fixed path segment of a route template. */
7
+ const STATIC_SEGMENT = /^[a-zA-Z0-9_-]+$/;
8
+ /** A parameter segment of a route template, `{name}`, occupying the whole segment. */
9
+ const PARAMETER_SEGMENT = /^\{([a-zA-Z][a-zA-Z0-9_]*)\}$/;
10
+ /** Parameter names that would reach an object's prototype. */
11
+ const UNSAFE_PARAMETERS = /* @__PURE__ */ new Set([
12
+ "constructor",
13
+ "prototype",
14
+ "__proto__"
15
+ ]);
16
+ /** Headers that carry authority or framing: never an operation's input metadata. */
17
+ const RESERVED_HEADERS = /* @__PURE__ */ new Set([
18
+ "authorization",
19
+ "cookie",
20
+ "host",
21
+ "content-length",
22
+ "content-encoding"
23
+ ]);
24
+ /** Whether a byte operation may read one of its input fields from this header. */
25
+ function isInputHeaderName(header) {
26
+ return /^[A-Za-z0-9-]+$/u.test(header) && !RESERVED_HEADERS.has(header.toLowerCase());
27
+ }
28
+ /** Parse declared templates, never caller paths. Parameters occupy one complete path segment. */
29
+ function operationPathParameters(path) {
30
+ const segments = path.split("/");
31
+ if (segments[0] !== "" || !/^v[1-9][0-9]*$/.test(segments[1] ?? "") || segments.length < 3) throw new TypeError("Operations require a versioned path.");
32
+ const parameters = [];
33
+ for (const segment of segments.slice(2)) {
34
+ const parameter = PARAMETER_SEGMENT.exec(segment)?.[1];
35
+ if (parameter) {
36
+ if (UNSAFE_PARAMETERS.has(parameter) || parameters.includes(parameter)) throw new TypeError("Path parameter names must be unique and safe.");
37
+ parameters.push(parameter);
38
+ } else if (!STATIC_SEGMENT.test(segment)) throw new TypeError("Use fixed routes or complete {parameter} segments; empty and malformed segments are forbidden.");
39
+ }
40
+ return parameters;
41
+ }
42
+ /** A decoded item key stays in one segment; dot segments and controls cannot alter URL ownership. */
43
+ function decodePathParameter(segment) {
44
+ try {
45
+ const value = decodeURIComponent(segment);
46
+ return isPathParameterValue(value) ? value : null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ /** Item keys are nonempty strings that cannot change URL path ownership when encoded. */
52
+ function isPathParameterValue(value) {
53
+ if (typeof value !== "string" || value.length === 0 || value === "." || value === ".." || /[\\/]/.test(value)) return false;
54
+ for (const character of value) {
55
+ const code = character.charCodeAt(0);
56
+ if (code < 32 || code === 127) return false;
57
+ }
58
+ return true;
59
+ }
60
+ /** The methods an operation route may use. */
61
+ const HTTP_METHODS = /* @__PURE__ */ new Set([
62
+ "GET",
63
+ "POST",
64
+ "PUT",
65
+ "PATCH",
66
+ "DELETE"
67
+ ]);
68
+ /**
69
+ * Exact routes use a Map. Template branches compile into deterministic states at construction:
70
+ * one transition per segment, including overlapping fixed prefixes, with no per-request route scan.
71
+ */
72
+ function createHttpRouteResolver(definitions) {
73
+ const exact = /* @__PURE__ */ new Map();
74
+ const roots = /* @__PURE__ */ new Map();
75
+ let nextId = 0;
76
+ /** A new tree node with the next id. */
77
+ const branch = () => {
78
+ const node = {
79
+ id: nextId,
80
+ fixed: /* @__PURE__ */ new Map()
81
+ };
82
+ nextId += 1;
83
+ return node;
84
+ };
85
+ for (const definition of definitions) {
86
+ if (!definition.http) continue;
87
+ if (!HTTP_METHODS.has(definition.http.method)) throw new TypeError("Operation routes require a supported HTTP method.");
88
+ const names = operationPathParameters(definition.http.path);
89
+ const segments = definition.http.path.slice(1).split("/");
90
+ const route = {
91
+ definition,
92
+ parameters: segments.flatMap((segment, position) => {
93
+ const parameter = segment.startsWith("{") ? segment.slice(1, -1) : void 0;
94
+ return parameter ? [{
95
+ name: parameter,
96
+ position
97
+ }] : [];
98
+ })
99
+ };
100
+ if (names.length === 0) {
101
+ const key = `${definition.http.method} ${definition.http.path}`;
102
+ if (exact.has(key)) throw new TypeError("Duplicate operation route.");
103
+ exact.set(key, route);
104
+ continue;
105
+ }
106
+ let node = roots.get(definition.http.method);
107
+ if (!node) {
108
+ node = branch();
109
+ roots.set(definition.http.method, node);
110
+ }
111
+ for (const segment of segments) if (segment.startsWith("{")) {
112
+ node.parameter ??= branch();
113
+ node = node.parameter;
114
+ } else {
115
+ let child = node.fixed.get(segment);
116
+ if (!child) {
117
+ child = branch();
118
+ node.fixed.set(segment, child);
119
+ }
120
+ node = child;
121
+ }
122
+ if (node.route) throw new TypeError("Ambiguous operation path templates.");
123
+ node.route = route;
124
+ }
125
+ const states = /* @__PURE__ */ new Map();
126
+ /**
127
+ * The state for a set of tree nodes: their routes (at most one), and for each next segment the state of
128
+ * every node it can lead to, compiled once per set.
129
+ */
130
+ function compile(nodes) {
131
+ const distinct = [...new Map(nodes.map((node) => [node.id, node])).values()];
132
+ const key = distinct.map((node) => node.id).toSorted((left, right) => left - right).join(",");
133
+ const known = states.get(key);
134
+ if (known) return known;
135
+ const routes = distinct.flatMap((node) => node.route ? [node.route] : []);
136
+ if (routes.length > 1) throw new TypeError("Ambiguous overlapping operation path templates.");
137
+ const state = {
138
+ fixed: /* @__PURE__ */ new Map(),
139
+ route: routes[0]
140
+ };
141
+ states.set(key, state);
142
+ const parameters = distinct.flatMap((node) => node.parameter ? [node.parameter] : []);
143
+ if (parameters.length > 0) state.parameter = compile(parameters);
144
+ const fixed = new Set(distinct.flatMap((node) => [...node.fixed.keys()]));
145
+ for (const segment of fixed) {
146
+ const children = distinct.flatMap((node) => {
147
+ const child = node.fixed.get(segment);
148
+ return child ? [child] : [];
149
+ });
150
+ state.fixed.set(segment, compile([...children, ...parameters]));
151
+ }
152
+ return state;
153
+ }
154
+ const templates = new Map([...roots].map(([method, root]) => [method, compile([root])]));
155
+ /**
156
+ * The route for a method and path: an exact route first, then one transition per segment through the
157
+ * compiled states.
158
+ */
159
+ function findRoute(method, path) {
160
+ const fixed = exact.get(`${method} ${path}`);
161
+ if (fixed) return fixed;
162
+ if (!path.startsWith("/") || path.endsWith("/")) return null;
163
+ const segments = path.slice(1).split("/");
164
+ let state = templates.get(method);
165
+ for (const segment of segments) {
166
+ if (!segment || !state) return null;
167
+ state = state.fixed.get(segment) ?? state.parameter;
168
+ }
169
+ return state?.route ?? null;
170
+ }
171
+ /**
172
+ * The route a request reaches, with its path parameters decoded; null when none matches or a parameter
173
+ * value is unsafe.
174
+ */
175
+ function match(method, path) {
176
+ const route = findRoute(method, path);
177
+ if (!route) return null;
178
+ const segments = path.slice(1).split("/");
179
+ const parameters = {};
180
+ for (const parameter of route.parameters) {
181
+ const value = decodePathParameter(segments[parameter.position] ?? "");
182
+ if (value === null) return null;
183
+ parameters[parameter.name] = value;
184
+ }
185
+ return {
186
+ definition: route.definition,
187
+ parameters
188
+ };
189
+ }
190
+ return {
191
+ match,
192
+ /** Used only at construction to prevent a transport from bypassing item-route authorization. */
193
+ ownsPath(path) {
194
+ return [...HTTP_METHODS].some((method) => findRoute(method, path) !== null);
195
+ }
196
+ };
197
+ }
198
+
199
+ export { operationPathParameters as a, isPathParameterValue as i, decodePathParameter as n, isInputHeaderName as r, createHttpRouteResolver as t };