@arbol-ai/maximus 0.0.0-stage → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -2
  3. package/config/oxfmt.d.mts +8 -0
  4. package/config/oxfmt.mjs +30 -0
  5. package/config/oxlint-plugin.mjs +41 -0
  6. package/config/oxlint.d.mts +8 -0
  7. package/config/oxlint.mjs +118 -0
  8. package/dist/analytics/analytics.d.ts +34 -0
  9. package/dist/analytics/analytics.js +62 -0
  10. package/dist/body.d.ts +2 -0
  11. package/dist/body.js +4 -0
  12. package/dist/chunks/body-BcMbreNd.js +106 -0
  13. package/dist/chunks/correlation-gaiEoMBr.js +45 -0
  14. package/dist/chunks/execution-qfZuMSIu.js +700 -0
  15. package/dist/chunks/json-Dwni3u4c.js +63 -0
  16. package/dist/chunks/record-D2H3cg8S.js +36 -0
  17. package/dist/chunks/schemas-q-51wBMQ.js +216 -0
  18. package/dist/chunks/src-Ph5KHCRP.js +1160 -0
  19. package/dist/chunks/telemetry-DvZgrzZn.js +220 -0
  20. package/dist/chunks/types-CGwAhnTE.d.ts +1630 -0
  21. package/dist/chunks/validation-DWxKk1Js.js +382 -0
  22. package/dist/client/client.d.ts +131 -0
  23. package/dist/client/client.js +325 -0
  24. package/dist/diagnostics.d.ts +41 -0
  25. package/dist/diagnostics.js +4 -0
  26. package/dist/errors.d.ts +2 -0
  27. package/dist/errors.js +128 -0
  28. package/dist/http-paths.d.ts +2 -0
  29. package/dist/http-paths.js +200 -0
  30. package/dist/index.d.ts +2 -0
  31. package/dist/index.js +11 -0
  32. package/dist/internals.d.ts +2 -0
  33. package/dist/internals.js +5 -0
  34. package/dist/mcp/index.d.ts +12 -0
  35. package/dist/mcp/index.js +406 -0
  36. package/dist/postgres/index.d.ts +81 -0
  37. package/dist/postgres/index.js +140 -0
  38. package/dist/schemas.d.ts +2 -0
  39. package/dist/schemas.js +4 -0
  40. package/dist/standard-failures.d.ts +91 -0
  41. package/dist/standard-failures.js +75 -0
  42. package/dist/tooling/cli.js +110 -0
  43. package/dist/tooling/testing.d.ts +7 -0
  44. package/dist/tooling/testing.js +21 -0
  45. package/dist/webhooks.d.ts +69 -0
  46. package/dist/webhooks.js +162 -0
  47. package/dist/workers/runtime.d.ts +112 -0
  48. package/dist/workers/runtime.js +228 -0
  49. package/package.json +153 -4
  50. package/skills/maximus/SKILL.md +89 -0
  51. package/skills/maximus/references/adding-an-operation.md +179 -0
  52. package/skills/maximus/references/building-a-service.md +158 -0
  53. package/skills/maximus/references/errors-and-results.md +77 -0
  54. package/skills/maximus/references/migration-from-v2.md +62 -0
  55. package/skills/maximus/references/migration-to-v5.md +37 -0
  56. package/skills/maximus/references/publishing-and-verification.md +39 -0
  57. package/skills/maximus/references/testing.md +73 -0
  58. package/skills/maximus/references/transports.md +119 -0
  59. package/templates/service/.agents/skills/project/SKILL.md.template +10 -0
  60. package/templates/service/.github/workflows/ci.yml.template +21 -0
  61. package/templates/service/.gitignore.template +8 -0
  62. package/templates/service/CLAUDE.md.template +3 -0
  63. package/templates/service/README.md.template +45 -0
  64. package/templates/service/cloudflare.config.ts.template +30 -0
  65. package/templates/service/oxfmt.config.ts.template +1 -0
  66. package/templates/service/oxlint.config.ts.template +1 -0
  67. package/templates/service/package.json.template +31 -0
  68. package/templates/service/src/app.ts.template +30 -0
  69. package/templates/service/src/index.ts.template +13 -0
  70. package/templates/service/tests/contract.test.ts.template +12 -0
  71. package/templates/service/tsconfig.json.template +16 -0
  72. package/templates/service/vite.config.ts.template +7 -0
  73. package/templates/service/vitest.config.ts.template +10 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arbol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # @arbol-ai/maximus
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Maximus defines an organization-scoped service once and serves it on Cloudflare Workers over HTTP
4
+ with its OpenAPI 3.1 contract, as MCP tools and as Worker RPC methods. It is one package: the root is
5
+ the core (the fluent builder, TypeBox schemas, tokens and scopes, the error catalog, middleware, the
6
+ native HTTP handler and OpenAPI), and each other capability is an entry.
7
+
8
+ ```sh
9
+ bun add @arbol-ai/maximus
10
+ ```
11
+
12
+ ```ts
13
+ import { defineErrors, maximus, ok, t } from '@arbol-ai/maximus';
14
+
15
+ export const app = maximus<Env>({
16
+ name: 'notes',
17
+ namespace: 'notes',
18
+ title: 'Notes',
19
+ version: '1.0.0',
20
+ origin: 'https://notes.example.com',
21
+ tokens: { issuer: 'https://auth.example.com/', audience: 'https://notes.example.com' },
22
+ errors: defineErrors({}),
23
+ rpc: { callers: [] },
24
+ })
25
+ .operation(
26
+ 'listNotes',
27
+ {
28
+ scope: 'notes:notes:read',
29
+ effect: 'read',
30
+ title: 'List notes',
31
+ description: "List the organization's notes.",
32
+ input: t.Object({}, { additionalProperties: false }),
33
+ output: t.Object({ notes: t.Array(t.String()) }, { additionalProperties: false }),
34
+ http: { method: 'GET', path: '/v1/notes' },
35
+ },
36
+ async () => ok({ notes: [] })
37
+ )
38
+ .build();
39
+ ```
40
+
41
+ Entries: the root (the core), `/workers` (the Worker), `/mcp` (MCP tools), `/client` (a typed
42
+ client), `/schemas` (browser-safe schemas), `/errors` and `/failures` (runtime-free), `/body`,
43
+ `/webhooks`, `/http-paths`, `/diagnostics`, `/internals` (the transport SPI), `/analytics`,
44
+ `/postgres` (with the optional peer `pg`), `/testing`, `/oxlint` and `/oxfmt`. It installs the
45
+ `maximus` CLI and ships the Maximus Agent Skill in `skills/maximus/`.
46
+ See [package exports](https://github.com/getarbol/maximus/blob/main/docs/reference/exports.md).
47
+
48
+ - [Getting started](https://github.com/getarbol/maximus/blob/main/docs/getting-started.md)
49
+ - [Concepts](https://github.com/getarbol/maximus/blob/main/docs/concepts.md)
50
+ - [Configuration reference](https://github.com/getarbol/maximus/blob/main/docs/reference/configuration.md) and [operation reference](https://github.com/getarbol/maximus/blob/main/docs/reference/operations.md)
51
+
52
+ Released under the MIT License.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The type of the `@arbol-ai/maximus/oxfmt` preset.
3
+ */
4
+ import type { defineConfig } from 'oxfmt';
5
+
6
+ /** The Maximus oxfmt preset; its `ignorePatterns` are always present, to extend them. */
7
+ declare const config: ReturnType<typeof defineConfig> & { ignorePatterns: string[] };
8
+ export default config;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `@arbol-ai/maximus/oxfmt`: the oxfmt preset for code built on Maximus.
3
+ */
4
+ import { defineConfig } from 'oxfmt';
5
+ import ultracite from 'ultracite/oxfmt';
6
+
7
+ /**
8
+ * Formatting for code built on Maximus: Ultracite's, with single quotes and 110 columns, prose kept
9
+ * as written, and generated or vendored files left alone. Use it as is,
10
+ * `export { default } from '@arbol-ai/maximus/oxfmt'`, or spread it and add ignore patterns.
11
+ */
12
+ export default defineConfig({
13
+ ...ultracite,
14
+ printWidth: 110,
15
+ singleQuote: true,
16
+ proseWrap: 'preserve',
17
+ ignorePatterns: [
18
+ ...ultracite.ignorePatterns,
19
+ '**/.private/**',
20
+ '**/.cloudflare/**',
21
+ '**/.wrangler/**',
22
+ '**/dist/**',
23
+ '**/.agents/**',
24
+ '**/.claude/**',
25
+ '**/.codex/**',
26
+ 'bun.lock',
27
+ 'CLAUDE.md',
28
+ 'AGENTS.md',
29
+ ],
30
+ });
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The `maximus` oxlint plugin: mistakes that type checking cannot see and that have already broken
3
+ * services in production. Loaded by the `@arbol-ai/maximus/oxlint` preset; each rule's message says
4
+ * what to do instead.
5
+ */
6
+
7
+ /** `{ redirect: 'error' }`, wherever it is written: in a Worker it only ever reaches fetch. */
8
+ const isRedirectError = (node) => {
9
+ const key = node.key.type === 'Identifier' ? node.key.name : node.key.value;
10
+ return (
11
+ !node.computed && key === 'redirect' && node.value.type === 'Literal' && node.value.value === 'error'
12
+ );
13
+ };
14
+
15
+ export default {
16
+ meta: { name: 'maximus' },
17
+ rules: {
18
+ 'no-fetch-redirect-error': {
19
+ meta: {
20
+ type: 'problem',
21
+ docs: {
22
+ description: "Disallow fetch's redirect: 'error', which a Worker refuses before sending anything.",
23
+ },
24
+ messages: {
25
+ redirectError:
26
+ "A Worker's fetch throws on redirect: 'error' before sending the request. Use redirect: 'manual' and refuse a 3xx answer yourself.",
27
+ },
28
+ schema: [],
29
+ },
30
+ create(context) {
31
+ return {
32
+ Property(node) {
33
+ if (isRedirectError(node)) {
34
+ context.report({ node, messageId: 'redirectError' });
35
+ }
36
+ },
37
+ };
38
+ },
39
+ },
40
+ },
41
+ };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The type of the `@arbol-ai/maximus/oxlint` preset.
3
+ */
4
+ import type { defineConfig } from 'oxlint';
5
+
6
+ /** The Maximus oxlint preset; its `ignorePatterns` are always present, to repeat them when extending. */
7
+ declare const config: ReturnType<typeof defineConfig> & { ignorePatterns: string[] };
8
+ export default config;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * `@arbol-ai/maximus/oxlint`: the oxlint preset for code built on Maximus.
3
+ */
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ import { defineConfig } from 'oxlint';
7
+ import core from 'ultracite/oxlint/core';
8
+
9
+ /** Why an import of another HTTP router is refused. */
10
+ const ONE_ROUTER =
11
+ 'Maximus serves HTTP, MCP and RPC from one definition; a second router splits the contract. Use plain routes or mounts for anything else.';
12
+
13
+ /** Files that run outside a Worker: tests, scripts, examples and tool configuration. */
14
+ const OUTSIDE_WORKERS = [
15
+ '**/tests/**',
16
+ '**/*.test.{ts,tsx,mts}',
17
+ '**/*.spec.{ts,tsx,mts}',
18
+ '**/scripts/**',
19
+ '**/examples/**',
20
+ '**/*.config.{ts,mts,js,mjs}',
21
+ ];
22
+
23
+ /**
24
+ * Lint for code built on Maximus: Ultracite's core rules, the framework's guardrails (each names
25
+ * the mistake it prevents) and the few relaxations Maximus code needs. Use it as is,
26
+ * `export { default } from '@arbol-ai/maximus/oxlint'`, or extend it with your framework's preset.
27
+ * See docs/guides/lint-and-format.md.
28
+ */
29
+ export default defineConfig({
30
+ extends: [core],
31
+ jsPlugins: [fileURLToPath(new URL('oxlint-plugin.mjs', import.meta.url))],
32
+ ignorePatterns: [
33
+ ...core.ignorePatterns,
34
+ '**/.cloudflare',
35
+ '**/.wrangler',
36
+ '**/.private',
37
+ '**/.agents',
38
+ '**/.claude',
39
+ '**/.codex',
40
+ ],
41
+ rules: {
42
+ // Guardrails: each one has broken, or would silently weaken, a Maximus service.
43
+ 'maximus/no-fetch-redirect-error': 'error',
44
+ 'no-restricted-properties': [
45
+ 'error',
46
+ {
47
+ object: 'process',
48
+ property: 'env',
49
+ message:
50
+ 'A Worker reads configuration from its env bindings and secrets from the Secrets Store (await env.NAME.get()); process.env is not its configuration.',
51
+ },
52
+ ],
53
+ 'no-restricted-imports': [
54
+ 'error',
55
+ {
56
+ paths: [
57
+ {
58
+ name: 'zod',
59
+ message:
60
+ "Maximus schemas are TypeBox: use t from '@arbol-ai/maximus' ('@arbol-ai/maximus/schemas' in a browser).",
61
+ },
62
+ { name: 'hono', message: ONE_ROUTER },
63
+ { name: 'elysia', message: ONE_ROUTER },
64
+ ],
65
+ },
66
+ ],
67
+
68
+ // Fetch handlers are asynchronous by design; this rule is about Express-style servers.
69
+ 'oxc/no-async-endpoint-handlers': 'off',
70
+ // Definitions keep their semantic order (scope, title, description, …), not an alphabetical one.
71
+ 'eslint/sort-keys': 'off',
72
+ // Named functions, top-down modules, and TypeBox's value-and-type pairs of one name.
73
+ 'eslint/func-style': 'off',
74
+ 'eslint/no-use-before-define': 'off',
75
+ 'eslint/no-redeclare': 'off',
76
+ 'import/no-named-as-default': 'off',
77
+ 'unicorn/prefer-export-from': 'off',
78
+ 'unicorn/prefer-ternary': 'off',
79
+ 'unicorn/no-useless-undefined': 'off',
80
+ // Worker entrypoints and Durable Objects are classes whose methods need not touch `this`.
81
+ 'eslint/class-methods-use-this': 'off',
82
+ // Env and RPC interfaces, and exact vendor shapes, keep their declared form.
83
+ 'typescript/consistent-type-definitions': 'off',
84
+ 'typescript/no-empty-interface': 'off',
85
+ 'typescript/no-empty-object-type': 'off',
86
+ // Protocol parsers and codecs work with ASCII groups, code units and bits.
87
+ 'eslint/require-unicode-regexp': 'off',
88
+ 'eslint/prefer-named-capture-group': 'off',
89
+ 'unicorn/prefer-code-point': 'off',
90
+ 'eslint/no-bitwise': 'off',
91
+ // Paginating a provider or retrying one step at a time is sequential on purpose.
92
+ 'eslint/no-await-in-loop': 'off',
93
+ 'eslint/complexity': 'off',
94
+ // Best-effort cleanup, such as cancelling a body, must never mask the original failure.
95
+ 'promise/prefer-await-to-then': 'off',
96
+ 'eslint/no-empty-function': 'off',
97
+ // Node tooling imports stay explicit, and immutable option defaults stay local.
98
+ 'unicorn/import-style': 'off',
99
+ 'unicorn/no-object-as-default-parameter': 'off',
100
+ },
101
+ overrides: [
102
+ {
103
+ files: OUTSIDE_WORKERS,
104
+ rules: {
105
+ // Node runs these: its fetch honors redirect: 'error', and process.env is its configuration.
106
+ 'maximus/no-fetch-redirect-error': 'off',
107
+ 'no-restricted-properties': 'off',
108
+ // Tests exercise JSON wire behavior and native promise signatures.
109
+ 'unicorn/prefer-structured-clone': 'off',
110
+ 'unicorn/consistent-function-scoping': 'off',
111
+ 'unicorn/no-await-expression-member': 'off',
112
+ 'eslint/require-await': 'off',
113
+ 'eslint/no-plusplus': 'off',
114
+ 'unicorn/consistent-assert': 'off',
115
+ },
116
+ },
117
+ ],
118
+ });
@@ -0,0 +1,34 @@
1
+ import { Jt as Observer, bn as Result, kn as Failure } from "../chunks/types-CGwAhnTE.js";
2
+ import { Static } from "@sinclair/typebox";
3
+ //#region src/analytics/analytics.d.ts
4
+ /** An analytics event: the allowlisted metadata of one operation call, flattened, with an id of its own. */
5
+ export declare const ExecutionEventSchema: import("@sinclair/typebox").TObject<{
6
+ id: import("@sinclair/typebox").TString;
7
+ service: import("@sinclair/typebox").TString;
8
+ operation: import("@sinclair/typebox").TString;
9
+ organizationId: import("@sinclair/typebox").TString;
10
+ actorId: import("@sinclair/typebox").TString;
11
+ actorKind: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"user">, import("@sinclair/typebox").TLiteral<"service">]>;
12
+ requestId: import("@sinclair/typebox").TString;
13
+ traceId: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TString, import("@sinclair/typebox").TNull]>;
14
+ surface: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"http">, import("@sinclair/typebox").TLiteral<"mcp">, import("@sinclair/typebox").TLiteral<"rpc">]>;
15
+ occurredAt: import("@sinclair/typebox").TInteger;
16
+ durationMicros: import("@sinclair/typebox").TInteger;
17
+ outcome: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"success">, import("@sinclair/typebox").TLiteral<"failure">]>;
18
+ errorCode: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TString, import("@sinclair/typebox").TNull]>;
19
+ }>;
20
+ /** An analytics event. */
21
+ export type ExecutionEvent = Static<typeof ExecutionEventSchema>;
22
+ /** A store that records analytics events and answers whether it kept each one. */
23
+ export interface ExecutionSink {
24
+ /**
25
+ * Keeps one event; an `ok: false` result means the event was not kept, which counts as a delivery failure.
26
+ */
27
+ record: (event: ExecutionEvent) => Promise<Result<null, Failure>>;
28
+ }
29
+ /** Safe metadata projection; no request or response bodies reach this sink. */
30
+ export declare function analytics<E>(options: {
31
+ enabled?: boolean | ((env: E) => boolean);
32
+ record: (env: E, event: ExecutionEvent) => Promise<unknown>;
33
+ }): Observer<E>;
34
+ //#endregion
@@ -0,0 +1,62 @@
1
+ import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-q-51wBMQ.js";
2
+ import { a as telemetryEnabled } from "../chunks/telemetry-DvZgrzZn.js";
3
+ import { Type } from "@sinclair/typebox";
4
+
5
+ //#region src/analytics/analytics.ts
6
+ /**
7
+ * `@arbol-ai/maximus/analytics`: an observer that turns each operation call's observation into an
8
+ * allowlisted analytics event and records it in a sink the application provides. No input, output or
9
+ * credential ever reaches the event.
10
+ */
11
+ /** An analytics event: the allowlisted metadata of one operation call, flattened, with an id of its own. */
12
+ const ExecutionEventSchema = Type.Object({
13
+ id: UuidSchema,
14
+ service: Type.String({ pattern: "^[a-z][a-z0-9-]{1,80}$" }),
15
+ operation: Type.String({ pattern: "^[a-z][a-zA-Z0-9]{0,100}$" }),
16
+ organizationId: OrganizationIdSchema,
17
+ actorId: Type.String({
18
+ minLength: 1,
19
+ maxLength: 255
20
+ }),
21
+ actorKind: Type.Union([Type.Literal("user"), Type.Literal("service")]),
22
+ requestId: UuidSchema,
23
+ traceId: Type.Union([Type.String({ pattern: "^[0-9a-f]{32}$" }), Type.Null()]),
24
+ surface: Type.Union([
25
+ Type.Literal("http"),
26
+ Type.Literal("mcp"),
27
+ Type.Literal("rpc")
28
+ ]),
29
+ occurredAt: Type.Integer({ minimum: 0 }),
30
+ durationMicros: Type.Integer({
31
+ minimum: 0,
32
+ maximum: Number.MAX_SAFE_INTEGER
33
+ }),
34
+ outcome: Type.Union([Type.Literal("success"), Type.Literal("failure")]),
35
+ errorCode: Type.Union([Type.String({ pattern: "^[A-Z][A-Z0-9_]{0,80}$" }), Type.Null()])
36
+ }, { additionalProperties: false });
37
+ /** Safe metadata projection; no request or response bodies reach this sink. */
38
+ function analytics(options) {
39
+ return { async execution(observation, env) {
40
+ if (!telemetryEnabled(options, env)) return;
41
+ const event = {
42
+ id: crypto.randomUUID(),
43
+ service: observation.service,
44
+ operation: observation.operation,
45
+ organizationId: observation.principal.organizationId,
46
+ actorId: observation.principal.actorId,
47
+ actorKind: observation.principal.actorKind,
48
+ requestId: observation.principal.requestId,
49
+ traceId: observation.traceId,
50
+ surface: observation.surface,
51
+ occurredAt: observation.occurredAt,
52
+ durationMicros: observation.durationMicros,
53
+ outcome: observation.outcome,
54
+ errorCode: observation.errorCode
55
+ };
56
+ const result = await options.record(env, event);
57
+ if (result && typeof result === "object" && "ok" in result && result.ok === false) throw new Error("Analytics sink rejected the event.");
58
+ } };
59
+ }
60
+
61
+ //#endregion
62
+ export { ExecutionEventSchema, analytics };
package/dist/body.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { c as isJsonMediaType, d as retryAfterSeconds, f as BodyReadOptions, g as readBodyText, h as readBodyBytes, l as readJsonBody, m as HttpBodyFailureReason, p as HttpBodyFailure, u as readJsonResponse } from "./chunks/types-CGwAhnTE.js";
2
+ export { type BodyReadOptions, type HttpBodyFailure, type HttpBodyFailureReason, isJsonMediaType, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
package/dist/body.js ADDED
@@ -0,0 +1,4 @@
1
+ import { n as readBodyBytes, r as readBodyText } from "./chunks/body-BcMbreNd.js";
2
+ import { a as retryAfterSeconds, i as readJsonResponse, r as readJsonBody, t as isJsonMediaType } from "./chunks/json-Dwni3u4c.js";
3
+
4
+ export { isJsonMediaType, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
@@ -0,0 +1,106 @@
1
+ //#region src/internal/body.ts
2
+ /** Closed decoding vocabulary used by bounded transport readers. */
3
+ const HTTP_BODY_FAILURES = [
4
+ "too_large",
5
+ "invalid_length",
6
+ "invalid_json",
7
+ "invalid_utf8",
8
+ "unexpected_content_type",
9
+ "aborted",
10
+ "read_failed"
11
+ ];
12
+ /** Construct only closed decoder metadata. No exception, input bytes or telemetry. */
13
+ function httpBodyFailure(reason) {
14
+ if (!HTTP_BODY_FAILURES.includes(reason)) throw new TypeError("Invalid HTTP body reason");
15
+ return {
16
+ code: "HTTP_BODY_INVALID",
17
+ message: "HTTP body could not be decoded",
18
+ retryable: false,
19
+ data: { reason }
20
+ };
21
+ }
22
+ /**
23
+ * Read at most the owner's byte limit, including chunked bodies. Returns original
24
+ * bytes for signature verification. Expected decoding failures are plain results.
25
+ * Rejected streams are cancelled without awaiting a remote acknowledgement.
26
+ */
27
+ async function readBodyBytes(source, options) {
28
+ if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1) throw new RangeError("Invalid body byte limit");
29
+ /** Refuses before reading, cancelling the body without waiting for it. */
30
+ const reject = (reason) => {
31
+ source.body?.cancel().catch(() => {});
32
+ return {
33
+ ok: false,
34
+ error: httpBodyFailure(reason)
35
+ };
36
+ };
37
+ if (options.signal?.aborted) return reject("aborted");
38
+ const length = source.headers.get("content-length");
39
+ if (length !== null && !/^\d+$/.test(length)) return reject("invalid_length");
40
+ if (length !== null && Number(length) > options.maxBytes) return reject("too_large");
41
+ const reader = source.body?.getReader();
42
+ if (!reader) return {
43
+ ok: true,
44
+ value: /* @__PURE__ */ new Uint8Array(0)
45
+ };
46
+ /** Cancels the read, without waiting for the remote side. */
47
+ const cancel = () => {
48
+ reader.cancel().catch(() => {});
49
+ };
50
+ /** Refuses while reading, cancelling the rest of the body. */
51
+ const fail = (reason) => {
52
+ cancel();
53
+ return {
54
+ ok: false,
55
+ error: httpBodyFailure(reason)
56
+ };
57
+ };
58
+ options.signal?.addEventListener("abort", cancel, { once: true });
59
+ const chunks = [];
60
+ let size = 0;
61
+ try {
62
+ while (true) {
63
+ if (options.signal?.aborted) return fail("aborted");
64
+ const chunk = await reader.read();
65
+ if (options.signal?.aborted) return fail("aborted");
66
+ if (chunk.done) break;
67
+ size += chunk.value.byteLength;
68
+ if (size > options.maxBytes) return fail("too_large");
69
+ chunks.push(chunk.value);
70
+ }
71
+ const bytes = new Uint8Array(size);
72
+ let offset = 0;
73
+ for (const chunk of chunks) {
74
+ bytes.set(chunk, offset);
75
+ offset += chunk.byteLength;
76
+ }
77
+ return {
78
+ ok: true,
79
+ value: bytes
80
+ };
81
+ } catch {
82
+ return fail(options.signal?.aborted ? "aborted" : "read_failed");
83
+ } finally {
84
+ options.signal?.removeEventListener("abort", cancel);
85
+ reader.releaseLock();
86
+ }
87
+ }
88
+ /** Decode bounded UTF-8; signed text adapters can retain vendor replacement semantics. */
89
+ async function readBodyText(source, options) {
90
+ const bytes = await readBodyBytes(source, options);
91
+ if (!bytes.ok) return bytes;
92
+ try {
93
+ return {
94
+ ok: true,
95
+ value: new TextDecoder("utf-8", { fatal: options.fatalUtf8 ?? true }).decode(bytes.value)
96
+ };
97
+ } catch {
98
+ return {
99
+ ok: false,
100
+ error: httpBodyFailure("invalid_utf8")
101
+ };
102
+ }
103
+ }
104
+
105
+ //#endregion
106
+ export { readBodyBytes as n, readBodyText as r, httpBodyFailure as t };
@@ -0,0 +1,45 @@
1
+ //#region src/internal/correlation.ts
2
+ /**
3
+ * Request correlation: request ids (a UUID, or a ray id from a trusted Cloudflare edge), W3C `traceparent`
4
+ * parsing, and the correlation that durable work persists.
5
+ */
6
+ /** A UUID in its canonical text form. */
7
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+ /** A Cloudflare ray id, with its optional data center suffix. */
9
+ const RAY_PATTERN = /^[0-9a-f]{16}(?:-[A-Z]{3})?$/;
10
+ /** Only technical support identifiers. Never use these values as authority or dedupe keys. */
11
+ function isRequestId(value) {
12
+ return typeof value === "string" && (UUID_PATTERN.test(value) || RAY_PATTERN.test(value));
13
+ }
14
+ /**
15
+ * Public ingress mints an id by default. Only pass trustedEdgeRay from the
16
+ * Cloudflare edge or a separately authenticated internal caller; arbitrary
17
+ * X-Request-Id/CF-Ray supplied by an untrusted caller must not be adopted.
18
+ */
19
+ function createRequestId(trustedEdgeRay) {
20
+ return isRequestId(trustedEdgeRay) ? trustedEdgeRay : crypto.randomUUID();
21
+ }
22
+ /** Reads a W3C `traceparent` header of version 00, or nothing when it is malformed or all zeros. */
23
+ function parseTraceParent(value) {
24
+ const match = value && /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/.exec(value);
25
+ if (!match?.[1] || !match[2] || /^0+$/.test(match[1]) || /^0+$/.test(match[2])) return;
26
+ return {
27
+ traceId: match[1],
28
+ parentSpanId: match[2],
29
+ sampled: (Number.parseInt(match[3] ?? "00", 16) & 1) === 1
30
+ };
31
+ }
32
+ /**
33
+ * The correlation to persist with durable work: a valid request id and, when it parses, the originating
34
+ * `traceparent`.
35
+ */
36
+ function durableCorrelation(requestId, originTraceParent) {
37
+ if (!isRequestId(requestId)) throw new TypeError("Invalid correlation id");
38
+ return {
39
+ requestId,
40
+ ...parseTraceParent(originTraceParent) ? { originTraceParent } : {}
41
+ };
42
+ }
43
+
44
+ //#endregion
45
+ export { parseTraceParent as i, durableCorrelation as n, isRequestId as r, createRequestId as t };