@arbol-ai/maximus 8.0.1 → 8.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 (70) hide show
  1. package/dist/analytics/analytics.d.ts +16 -16
  2. package/dist/analytics/analytics.js +4 -4
  3. package/dist/body.d.ts +2 -2
  4. package/dist/body.js +2 -2
  5. package/dist/capture/index.d.ts +37 -0
  6. package/dist/capture/index.js +181 -0
  7. package/dist/chunks/{define-app-x7uY70_1.js → define-app-CQpWqqqE.js} +44 -14
  8. package/dist/chunks/delay-BsKQP_lF.js +12 -0
  9. package/dist/chunks/{json-B14evE6-.js → destination-DIkn8W6K.js} +65 -1
  10. package/dist/chunks/digest-C51F1bhA.js +12 -0
  11. package/dist/chunks/{errors-C5w9WY1l.js → errors-BoutSmiy.js} +2 -3
  12. package/dist/chunks/execution-Bpq6s4nA.js +265 -0
  13. package/dist/chunks/{generate-C-9FKW0o.js → generate-Dg88LzLU.js} +1 -1
  14. package/dist/chunks/{handler-iebR-urt.js → handler-DSpyrWc-.js} +6 -2
  15. package/dist/chunks/{http-layout-DS8DnPyu.js → http-layout-BcYH4I2w.js} +1 -1
  16. package/dist/chunks/{http-paths-DMBxwpp6.js → http-paths-D043DkJv.js} +50 -81
  17. package/dist/chunks/http-routes-B6tCsnxB.js +29 -0
  18. package/dist/chunks/{openapi-CeolxIqa.js → openapi-D2rds7vy.js} +32 -130
  19. package/dist/chunks/{openapi-file-Bz9FRaE6.js → openapi-file-BK8zET5U.js} +24 -6
  20. package/dist/chunks/{pages-iZTvFs5a.js → pages-B7ysoFAM.js} +1 -1
  21. package/dist/chunks/result-CF4OzG9O.js +29 -0
  22. package/dist/chunks/{runtime-D94vx21X.js → runtime-CGtS2rOb.js} +165 -11
  23. package/dist/chunks/schemas-_UJcx_uY.js +813 -0
  24. package/dist/chunks/{server-Bzf1Q1_4.js → server-CVhTLNj2.js} +38 -101
  25. package/dist/chunks/{src-CPrJpbOM.js → src-D67OfW9B.js} +94 -27
  26. package/dist/chunks/tasks-C873C3le.js +100 -0
  27. package/dist/chunks/tasks-DYdY-dBI.js +267 -0
  28. package/dist/chunks/{telemetry-C3LfZcOB.js → telemetry-BtxJh69Q.js} +4 -4
  29. package/dist/chunks/{types-DTIuIEJ-.d.ts → types-BfGa2aJT.d.ts} +537 -124
  30. package/dist/chunks/validation-CpzAxj2_.js +201 -0
  31. package/dist/chunks/{workers-types-BRk_Xa_5.d.ts → workers-types-Cxf-5cH7.d.ts} +6 -1
  32. package/dist/diagnostics.d.ts +1 -1
  33. package/dist/diagnostics.js +1 -1
  34. package/dist/errors.d.ts +1 -1
  35. package/dist/errors.js +1 -1
  36. package/dist/http-paths.d.ts +1 -1
  37. package/dist/http-paths.js +1 -1
  38. package/dist/index.d.ts +2 -2
  39. package/dist/index.js +12 -11
  40. package/dist/internals.d.ts +2 -2
  41. package/dist/internals.js +6 -6
  42. package/dist/mcp/index.d.ts +1 -1
  43. package/dist/mcp/index.js +1 -1
  44. package/dist/mcp/tasks.d.ts +33 -0
  45. package/dist/mcp/tasks.js +3 -0
  46. package/dist/project/config.d.ts +2 -2
  47. package/dist/project/config.js +3 -2
  48. package/dist/project/index.d.ts +2 -2
  49. package/dist/project/index.js +3 -3
  50. package/dist/schemas.d.ts +2 -2
  51. package/dist/schemas.js +3 -3
  52. package/dist/standard-failures.d.ts +1 -1
  53. package/dist/tooling/cli.js +2 -2
  54. package/dist/vite/index.d.ts +2 -2
  55. package/dist/vite/index.js +15 -9
  56. package/dist/webhooks.d.ts +13 -2
  57. package/dist/webhooks.js +38 -1
  58. package/dist/workers/runtime.d.ts +1 -1
  59. package/dist/workers/runtime.js +1 -1
  60. package/package.json +15 -3
  61. package/skills/maximus/SKILL.md +14 -4
  62. package/skills/maximus/references/project.md +4 -0
  63. package/skills/maximus/references/routes-and-tools.md +11 -1
  64. package/templates/project/CLAUDE.md.template +3 -3
  65. package/templates/project/README.md.template +1 -0
  66. package/templates/project/tsconfig.json.template +1 -0
  67. package/dist/chunks/execution-rOiLo8VG.js +0 -84
  68. package/dist/chunks/result-CKgZHrnj.js +0 -56
  69. package/dist/chunks/schemas-p_aRcMC1.js +0 -227
  70. package/dist/chunks/validation-fTohBT6R.js +0 -420
@@ -1,20 +1,20 @@
1
- import { Sn as Observer } from "../chunks/types-DTIuIEJ-.js";
2
- import { Static } from "@sinclair/typebox";
1
+ import { Hn as Observer } from "../chunks/types-BfGa2aJT.js";
2
+ import { Static, Type } from "typebox";
3
3
  /** An analytics event: the allowlisted metadata of one operation call, flattened, with an id of its own. */
4
- export declare const ExecutionEventSchema: import("@sinclair/typebox").TObject<{
5
- id: import("@sinclair/typebox").TString;
6
- service: import("@sinclair/typebox").TString;
7
- operation: import("@sinclair/typebox").TString;
8
- organizationId: import("@sinclair/typebox").TString;
9
- actorId: import("@sinclair/typebox").TString;
10
- actorKind: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"user">, import("@sinclair/typebox").TLiteral<"service">]>;
11
- requestId: import("@sinclair/typebox").TString;
12
- traceId: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TString, import("@sinclair/typebox").TNull]>;
13
- surface: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"http">, import("@sinclair/typebox").TLiteral<"mcp">, import("@sinclair/typebox").TLiteral<"rpc">]>;
14
- occurredAt: import("@sinclair/typebox").TInteger;
15
- durationMicros: import("@sinclair/typebox").TInteger;
16
- outcome: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"success">, import("@sinclair/typebox").TLiteral<"failure">]>;
17
- errorCode: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TString, import("@sinclair/typebox").TNull]>;
4
+ export declare const ExecutionEventSchema: Type.TObject<{
5
+ id: Type.TString;
6
+ service: Type.TString;
7
+ operation: Type.TString;
8
+ organizationId: Type.TString;
9
+ actorId: Type.TString;
10
+ actorKind: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"service">]>;
11
+ requestId: Type.TString;
12
+ traceId: Type.TUnion<[Type.TString, Type.TNull]>;
13
+ surface: Type.TUnion<[Type.TLiteral<"http">, Type.TLiteral<"mcp">, Type.TLiteral<"rpc">]>;
14
+ occurredAt: Type.TInteger;
15
+ durationMicros: Type.TInteger;
16
+ outcome: Type.TUnion<[Type.TLiteral<"success">, Type.TLiteral<"failure">]>;
17
+ errorCode: Type.TUnion<[Type.TString, Type.TNull]>;
18
18
  }>;
19
19
  /** An analytics event. */
20
20
  export type ExecutionEvent = Static<typeof ExecutionEventSchema>;
@@ -1,7 +1,7 @@
1
- import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-p_aRcMC1.js";
2
- import { a as telemetryEnabled } from "../chunks/telemetry-C3LfZcOB.js";
3
- import { Type } from "@sinclair/typebox";
4
- import { Value } from "@sinclair/typebox/value";
1
+ import { f as Value } from "../chunks/validation-CpzAxj2_.js";
2
+ import { i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-_UJcx_uY.js";
3
+ import { s as telemetryEnabled } from "../chunks/telemetry-BtxJh69Q.js";
4
+ import { Type } from "typebox";
5
5
 
6
6
  // src/analytics/analytics.ts
7
7
  /**
package/dist/body.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { _ as readBodyText, d as readJsonResponse, f as retryAfterSeconds, g as readBodyBytes, h as HttpBodyFailureReason, l as isJsonMediaType, m as HttpBodyFailure, p as BodyReadOptions, u as readJsonBody } from "./chunks/types-DTIuIEJ-.js";
2
- export { type BodyReadOptions, type HttpBodyFailure, type HttpBodyFailureReason, isJsonMediaType, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
1
+ import { _ as readBodyText, c as isJsonMediaType, d as retryAfterSeconds, f as publicDestination, g as readBodyBytes, h as HttpBodyFailureReason, l as readJsonBody, m as HttpBodyFailure, p as BodyReadOptions, u as readJsonResponse } from "./chunks/types-BfGa2aJT.js";
2
+ export { type BodyReadOptions, type HttpBodyFailure, type HttpBodyFailureReason, isJsonMediaType, publicDestination, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
package/dist/body.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { n as readBodyBytes, r as readBodyText } from "./chunks/body-DOIHwIIl.js";
2
- import { a as retryAfterSeconds, i as readJsonResponse, r as readJsonBody, t as isJsonMediaType } from "./chunks/json-B14evE6-.js";
2
+ import { a as readJsonResponse, i as readJsonBody, n as isJsonMediaType, o as retryAfterSeconds, t as publicDestination } from "./chunks/destination-DIkn8W6K.js";
3
3
 
4
- export { isJsonMediaType, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
4
+ export { isJsonMediaType, publicDestination, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
@@ -0,0 +1,37 @@
1
+ import { An as CaptureConfig, Kt as RegisteredEnv, Mn as CaptureInvocation, Nn as CaptureSink, ct as withoutSecrets, hr as CaptureRecordSchema, jn as CaptureDimensions, kn as AnyContext, mr as CaptureRecord } from "../chunks/types-BfGa2aJT.js";
2
+ /** What `pipeline()` takes. */
3
+ interface PipelineOptions<E> {
4
+ /**
5
+ * The name of the Pipelines binding. While the env has no such binding, capture records nothing and logs
6
+ * nothing, so a preview or a local run without the stream costs nothing.
7
+ */
8
+ binding: string;
9
+ /**
10
+ * Turns a record into the row the stream's schema expects: the stream gets the record itself without it. A
11
+ * structured stream drops a row its schema refuses, so a stream of another shape needs this. An answer of
12
+ * `null` or `undefined` sends nothing.
13
+ */
14
+ map?: (record: CaptureRecord, env: E) => unknown;
15
+ /**
16
+ * The name of an R2 binding for what the stream cannot take. A payload over 900 KB is written to
17
+ * `payloads/<organizationId>/<id>.json`, and the record carries `payloadRef` instead; a row the stream
18
+ * refused twice is written to `dlq/<service>/<yyyy-mm-dd>/<id>.json`, for a job to send again. Without it,
19
+ * both count as failed deliveries.
20
+ */
21
+ blobs?: string;
22
+ }
23
+ /**
24
+ * Sends each record to a Pipelines stream, the binding `env[binding]`. A send that fails is retried once after
25
+ * 200 ms, with the same record id, then written to the dead letter when `blobs` is set; the delivery still
26
+ * counts as failed, so the failure is logged. A stream is a durable buffer that accepts a repeated row, and a
27
+ * consumer deduplicates on the record's id. A sink for an append whose outcome may be lost should never retry.
28
+ */
29
+ export declare function pipeline<E>(options: PipelineOptions<E>): CaptureSink<E>;
30
+ /**
31
+ * Declares, as `capture.ts`'s default export, whether calls are captured (`enabled`), where the records go
32
+ * (`sink`), whether they carry each input and output (`payloads`) and what each call is about (`dimensions`).
33
+ * `C` names the context `dimensions` reads, `PreparedContext<typeof context>`, importing the type alone. Any other
34
+ * field throws a TypeError.
35
+ */
36
+ export declare function defineCapture<C = AnyContext>(capture: CaptureConfig<RegisteredEnv, C>): CaptureConfig<RegisteredEnv, C>;
37
+ export { type CaptureConfig, type CaptureDimensions, type CaptureInvocation, type CaptureRecord, CaptureRecordSchema, type CaptureSink, type PipelineOptions, withoutSecrets };
@@ -0,0 +1,181 @@
1
+ import { B as withoutSecrets, i as UuidSchema, n as OrganizationIdSchema } from "../chunks/schemas-_UJcx_uY.js";
2
+ import { t as isRecord } from "../chunks/record-DQUDTpEA.js";
3
+ import { t as sha256Hex } from "../chunks/digest-C51F1bhA.js";
4
+ import { t as delay } from "../chunks/delay-BsKQP_lF.js";
5
+ import { Type } from "typebox";
6
+
7
+ // src/capture-record.ts
8
+ /**
9
+ * The capture record: what one operation call, or one refusal, becomes for the sink that keeps it. The fields
10
+ * an analytics event has keep its names, so live counters and a store of records agree.
11
+ */
12
+ /** A field a record leaves null when the call never reached what fills it. */
13
+ const nullable = (schema, description) => Type.Union([schema, Type.Null()], { description });
14
+ /**
15
+ * One complete record of a call: who called which operation over which transport, when and for how long, what
16
+ * it answered, and, under `payloads: 'all'`, its input and output without what their schemas mark
17
+ * `secret: true`. A refusal before the operation ran has `stage: 'admission'` and null wherever admission had
18
+ * not learned the value: a token is never read before it is verified.
19
+ */
20
+ const CaptureRecordSchema = Type.Object({
21
+ id: UuidSchema,
22
+ service: Type.String({ description: "The application's name." }),
23
+ operation: nullable(Type.String(), "The operation, or null when the refusal names none."),
24
+ organizationId: nullable(OrganizationIdSchema, "The verified caller's organization, never one a request names; null before verification."),
25
+ actorId: nullable(Type.String(), "The verified caller; null before verification."),
26
+ actorKind: nullable(Type.Union([Type.Literal("user"), Type.Literal("service")]), "The verified caller's kind; null before verification."),
27
+ requestId: UuidSchema,
28
+ traceId: nullable(Type.String({ pattern: "^[0-9a-f]{32}$" }), "The active trace id `telemetry.traceId` returns; never generated, never read from a header."),
29
+ surface: Type.Union([
30
+ Type.Literal("http"),
31
+ Type.Literal("mcp"),
32
+ Type.Literal("rpc")
33
+ ], { description: "The transport that admitted the call." }),
34
+ occurredAt: Type.Integer({
35
+ minimum: 0,
36
+ description: "When the call finished, in Unix milliseconds."
37
+ }),
38
+ durationMicros: Type.Integer({
39
+ minimum: 0,
40
+ description: "How long execution took, or admission for a refusal, in whole microseconds."
41
+ }),
42
+ outcome: Type.Union([Type.Literal("success"), Type.Literal("failure")], { description: "`success` when the caller received the output, `failure` when it received a failure." }),
43
+ errorCode: nullable(Type.String(), "The code of the failure the caller received; null on success."),
44
+ stage: Type.Union([Type.Literal("execution"), Type.Literal("admission")], { description: "`admission` for a refusal before the shared execution path, `execution` from there on." }),
45
+ version: Type.String({ description: "The application's version." }),
46
+ effect: nullable(Type.Union([
47
+ Type.Literal("read"),
48
+ Type.Literal("write"),
49
+ Type.Literal("delete")
50
+ ]), "The operation's declared effect."),
51
+ scopes: Type.Array(Type.String(), { description: "The scopes the operation declares." }),
52
+ visibility: nullable(Type.Union([Type.Literal("public"), Type.Literal("internal")]), "The operation's visibility."),
53
+ httpMethod: nullable(Type.String(), "The route's method, on HTTP."),
54
+ httpPath: nullable(Type.String(), "The route's path template, never the requested path, on HTTP."),
55
+ mcpTool: nullable(Type.String(), "The operation's tool name, on MCP."),
56
+ rpcCaller: nullable(Type.String(), "Over RPC, the `caller` of the Service Binding, as admission checked it or, when it refused the binding, as it claimed."),
57
+ clientId: nullable(Type.String(), "The OAuth client the verified token was issued to."),
58
+ clientClass: nullable(Type.Union([
59
+ Type.Literal("human"),
60
+ Type.Literal("machine"),
61
+ Type.Literal("dcr")
62
+ ]), "That client's class."),
63
+ grantedScopes: nullable(Type.Array(Type.String()), "The scopes the verified token grants."),
64
+ userAgent: nullable(Type.String({ maxLength: 200 }), "On HTTP and MCP, the request's `user-agent`, cut to 200 characters. What the caller claims."),
65
+ tokenSha256: nullable(Type.String({ pattern: "^[0-9a-f]{64}$" }), "The hex SHA-256 of the verified token: it joins the calls of one session, and the token never travels."),
66
+ dimensions: Type.Record(Type.String(), Type.String(), { description: "What the `dimensions` callback named for this call." }),
67
+ startedAt: Type.Integer({
68
+ minimum: 0,
69
+ description: "When the transport began admitting the call, in Unix milliseconds."
70
+ }),
71
+ admissionMicros: Type.Integer({
72
+ minimum: 0,
73
+ description: "How long admission took, in whole microseconds."
74
+ }),
75
+ input: Type.Unknown({ description: "Under `payloads: all`, the decoded input without its secrets; null for a refused input or `payloads: none`. An input whose schema has both codecs and secrets is the value its schema checked, before the codecs ran." }),
76
+ output: Type.Unknown({ description: "Under `payloads: all`, the checked output without its secrets, as the caller received it; for an attachment, its `contentType`, `filename` and `byteLength`, never its bytes. Null otherwise." }),
77
+ failureData: Type.Unknown({ description: "Under `payloads: all`, the failure's data without its secrets: `issues` for `INVALID_INPUT`, never the refused values. Null otherwise." }),
78
+ payloadRef: nullable(Type.Object({
79
+ $ref: Type.String({ description: "The key the payload was written to." }),
80
+ bytes: Type.Integer({
81
+ minimum: 0,
82
+ description: "The size of the payload written, in bytes."
83
+ }),
84
+ sha256: Type.String({
85
+ pattern: "^[0-9a-f]{64}$",
86
+ description: "The payload's hex SHA-256."
87
+ })
88
+ }, { additionalProperties: false }), "Where a sink wrote `input`, `output` and `failureData` when they were too large to send, as JSON; they are then null.")
89
+ }, { additionalProperties: false });
90
+
91
+ // src/capture/pipeline.ts
92
+ /** The largest `input`, `output` and `failureData` one record carries together, in bytes. */
93
+ const MAX_PAYLOAD_BYTES = 9e5;
94
+ /** How long the one retry waits. A stream that refuses a send usually recovers within a moment. */
95
+ const RETRY_DELAY_MILLISECONDS = 200;
96
+ /** A binding of the env, by name. */
97
+ function bindingOf(env, name) {
98
+ return isRecord(env) ? env[name] : void 0;
99
+ }
100
+ /** The record, with a payload over the limit written to the bucket: it fails when there is no bucket. */
101
+ async function withinLimit(record, bucket) {
102
+ const { input, output, failureData } = record;
103
+ const payload = new TextEncoder().encode(JSON.stringify({
104
+ input,
105
+ output,
106
+ failureData
107
+ }));
108
+ if (payload.byteLength <= MAX_PAYLOAD_BYTES) return record;
109
+ if (!bucket) throw new RangeError("A capture payload over the limit needs a blobs binding.");
110
+ const key = `payloads/${record.organizationId ?? "platform"}/${record.id}.json`;
111
+ await bucket.put(key, payload, { httpMetadata: { contentType: "application/json" } });
112
+ return {
113
+ ...record,
114
+ input: null,
115
+ output: null,
116
+ failureData: null,
117
+ payloadRef: {
118
+ $ref: key,
119
+ bytes: payload.byteLength,
120
+ sha256: await sha256Hex(payload)
121
+ }
122
+ };
123
+ }
124
+ /** Keeps a row the stream refused twice, for a job to send again. The record's id names it, so a replay finds one. */
125
+ async function deadLetter(record, row, bucket) {
126
+ const day = new Date(record.occurredAt).toISOString().slice(0, 10);
127
+ await bucket.put(`dlq/${record.service}/${day}/${record.id}.json`, JSON.stringify(row), { httpMetadata: { contentType: "application/json" } });
128
+ }
129
+ /**
130
+ * Sends each record to a Pipelines stream, the binding `env[binding]`. A send that fails is retried once after
131
+ * 200 ms, with the same record id, then written to the dead letter when `blobs` is set; the delivery still
132
+ * counts as failed, so the failure is logged. A stream is a durable buffer that accepts a repeated row, and a
133
+ * consumer deduplicates on the record's id. A sink for an append whose outcome may be lost should never retry.
134
+ */
135
+ function pipeline(options) {
136
+ const { binding, blobs, map } = options;
137
+ if (typeof binding !== "string" || !binding) throw new TypeError("pipeline() takes the name of a Pipelines binding.");
138
+ return {
139
+ available: (env) => typeof bindingOf(env, binding)?.send === "function",
140
+ async send(record, env) {
141
+ const stream = bindingOf(env, binding);
142
+ const bucket = blobs === void 0 ? void 0 : bindingOf(env, blobs);
143
+ const carried = await withinLimit(record, bucket);
144
+ const row = map ? await map(carried, env) : carried;
145
+ if (row === null || row === void 0) return;
146
+ try {
147
+ await stream.send([row]);
148
+ } catch {
149
+ await delay(RETRY_DELAY_MILLISECONDS);
150
+ try {
151
+ await stream.send([row]);
152
+ } catch (error) {
153
+ if (bucket) await deadLetter(carried, row, bucket);
154
+ throw error;
155
+ }
156
+ }
157
+ }
158
+ };
159
+ }
160
+
161
+ // src/capture/index.ts
162
+ /** The fields `capture.ts` states. */
163
+ const CAPTURE_FIELDS = /* @__PURE__ */ new Set([
164
+ "enabled",
165
+ "sink",
166
+ "payloads",
167
+ "dimensions"
168
+ ]);
169
+ /**
170
+ * Declares, as `capture.ts`'s default export, whether calls are captured (`enabled`), where the records go
171
+ * (`sink`), whether they carry each input and output (`payloads`) and what each call is about (`dimensions`).
172
+ * `C` names the context `dimensions` reads, `PreparedContext<typeof context>`, importing the type alone. Any other
173
+ * field throws a TypeError.
174
+ */
175
+ function defineCapture(capture) {
176
+ const unknown = Object.keys(capture).filter((field) => !CAPTURE_FIELDS.has(field));
177
+ if (unknown.length) throw new TypeError(`capture.ts states only enabled, sink, payloads and dimensions: remove ${unknown.join(", ")}.`);
178
+ return Object.freeze(capture);
179
+ }
180
+
181
+ export { CaptureRecordSchema, defineCapture, pipeline, withoutSecrets };
@@ -1,10 +1,11 @@
1
- import { u as hasUncompiledCodecs } from "./validation-fTohBT6R.js";
2
- import { i as standardErrors } from "./errors-C5w9WY1l.js";
1
+ import { R as holdsSecrets, T as hasUncompiledCodecs } from "./schemas-_UJcx_uY.js";
2
+ import { i as standardErrors } from "./errors-BoutSmiy.js";
3
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-CeolxIqa.js";
7
- import { Kind } from "@sinclair/typebox";
4
+ import { a as operationPathParameters, r as isInputHeaderName, t as createHttpRouteResolver } from "./http-paths-D043DkJv.js";
5
+ import { t as pathParameterSchemas } from "./http-routes-B6tCsnxB.js";
6
+ import { b as operationScopes, d as MAX_BODY_BYTES_CEILING, f as STANDARD_CODES, t as MAX_TASK_TTL_MS, x as isNamespacedScope } from "./tasks-DYdY-dBI.js";
7
+ import { c as tokenAudiences, f as hasSchemaReferences, r as checkTokenAuthority, t as createOpenApi } from "./openapi-D2rds7vy.js";
8
+ import { IsKind } from "typebox";
8
9
 
9
10
  // src/internal/exact-length.ts
10
11
  /**
@@ -62,7 +63,7 @@ function binaryBody(request, maxBytes) {
62
63
  }
63
64
  /** Whether an output schema is `AttachmentOutputSchema`. */
64
65
  function isAttachmentSchema(schema) {
65
- return schema[Kind] === "HttpAttachment";
66
+ return IsKind(schema, "HttpAttachment");
66
67
  }
67
68
  /**
68
69
  * Whether an output is a well-formed `Attachment` within `maxBytes`: exactly its four fields, bytes of
@@ -121,6 +122,11 @@ function attachmentStream(body, byteLength) {
121
122
  }
122
123
 
123
124
  // src/define-app.ts
125
+ /**
126
+ * What `.build()` refuses. Every rule an application must keep is checked once, at construction, so a
127
+ * service that breaks one never starts: each refusal is a TypeError whose message names the rule, and most
128
+ * of the rules about one operation also name that operation.
129
+ */
124
130
  /** Names a Worker entrypoint already uses, or that would break a class or a promise. */
125
131
  const RESERVED_NAMES = /* @__PURE__ */ new Set([
126
132
  "fetch",
@@ -142,6 +148,7 @@ const OPERATION_FIELDS = new Set(Object.keys({
142
148
  visibility: true,
143
149
  mcp: true,
144
150
  rpc: true,
151
+ task: true,
145
152
  scope: true,
146
153
  scopeMatch: true,
147
154
  conditionalScopes: true,
@@ -190,6 +197,7 @@ function checkApplication(manifest) {
190
197
  if (!validBodyLimit(manifest.maxOutputBytes)) throw new TypeError("The application output limit is a positive integer up to 16 MiB.");
191
198
  if (new URL(manifest.origin).protocol !== "https:") throw new TypeError("Application origin must use HTTPS.");
192
199
  checkTelemetry(manifest.telemetry);
200
+ checkCapture(manifest.capture);
193
201
  checkTokenAuthority(manifest.tokens, manifest.namespace);
194
202
  tokenAudiences(manifest.tokens);
195
203
  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.");
@@ -217,6 +225,16 @@ function checkTelemetry(telemetry) {
217
225
  if (telemetry === void 0) return;
218
226
  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.");
219
227
  }
228
+ /**
229
+ * The capture option, as code untyped by TypeScript may give it: a switch that is a boolean or a function, a
230
+ * sink that can send, `payloads` of `all` or `none`, and a `dimensions` callback that is a function. A sink
231
+ * that cannot send would lose every record it is handed, and a `payloads` such as `'al'` would silently send
232
+ * metadata alone.
233
+ */
234
+ function checkCapture(capture) {
235
+ if (capture === void 0) return;
236
+ if (typeof capture !== "object" || capture === null || capture.enabled !== void 0 && typeof capture.enabled !== "boolean" && typeof capture.enabled !== "function" || typeof capture.sink?.send !== "function" || capture.sink.available !== void 0 && typeof capture.sink.available !== "function" || capture.payloads !== void 0 && capture.payloads !== "all" && capture.payloads !== "none" || capture.dimensions !== void 0 && typeof capture.dimensions !== "function") throw new TypeError("Capture takes enabled as true, false or a function of env, sink as an object whose send and available are functions, payloads as all or none, and dimensions as a function.");
237
+ }
220
238
  /** An operation's `failures` name domain codes of the catalog, each once. */
221
239
  function checkDeclaredFailures(operations, errors) {
222
240
  const domainCodes = new Set(Object.values(errors.definitions).map(({ code }) => code).filter((code) => !STANDARD_CODES.has(code)));
@@ -246,13 +264,20 @@ function checkOperationContract(name, op, namespace) {
246
264
  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.`);
247
265
  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.`);
248
266
  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.`);
267
+ if (!validTask(op.task)) throw new TypeError(`Operation "${name}": task is true or { ttlMs }, a positive integer of milliseconds up to a day.`);
268
+ if (op.task && holdsSecrets(op.output)) throw new TypeError(`Operation "${name}": a task keeps its result until it expires, so its output marks nothing secret: true.`);
269
+ }
270
+ /** Whether `task` is absent, `true` or `{ ttlMs }`: a positive integer of milliseconds up to a day. */
271
+ function validTask(task) {
272
+ if (task === void 0 || task === true) return true;
273
+ return typeof task === "object" && Object.keys(task).length === 1 && Number.isInteger(task.ttlMs) && task.ttlMs > 0 && task.ttlMs <= 864e5;
249
274
  }
250
275
  /** Byte bodies, attachments, limits, header-sourced fields and the route itself. */
251
276
  function checkHttpExposure(name, op, routes) {
252
277
  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.`);
253
278
  const binary = op.http?.body === "bytes";
254
279
  const attachment = isAttachmentSchema(op.output);
255
- if ((binary || attachment) && (!op.http || op.mcp || op.rpc)) throw new TypeError(`Operation "${name}": byte bodies and attachments are HTTP-only.`);
280
+ if ((binary || attachment) && (!op.http || op.mcp || op.rpc || op.task)) throw new TypeError(`Operation "${name}": byte bodies and attachments are HTTP-only and never tasks.`);
256
281
  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.`);
257
282
  if (!validBodyLimit(op.maxOutputBytes)) throw new TypeError(`Operation "${name}": invalid output byte limit.`);
258
283
  if (op.http?.successStatus !== void 0 && ![
@@ -263,7 +288,8 @@ function checkHttpExposure(name, op, routes) {
263
288
  if (op.http?.headers) {
264
289
  const pathFields = new Set(operationPathParameters(op.http.path));
265
290
  const headers = Object.entries(op.http.headers);
266
- 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.`);
291
+ const input = op.input;
292
+ if (!binary || input.type !== "object" || new Set(headers.map(([, wire]) => wire.toLowerCase())).size !== headers.length || headers.some(([field, wire]) => !Object.hasOwn(input.properties ?? {}, field) || pathFields.has(field) || !isInputHeaderName(wire))) throw new TypeError(`Operation "${name}": byte operation headers must name unique, non-authority metadata fields.`);
267
293
  }
268
294
  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.`);
269
295
  if (op.http) {
@@ -274,7 +300,7 @@ function checkHttpExposure(name, op, routes) {
274
300
  }
275
301
  }
276
302
  /**
277
- * A schema reference (TypeBox `Ref` or `Recursive`) resolves when the OpenAPI document bundles the schemas,
303
+ * A schema reference (TypeBox `Ref` or `Cyclic`) resolves when the OpenAPI document bundles the schemas,
278
304
  * to the one definition its name has. An application whose schemas refer to a name is bundled at
279
305
  * construction, so a reference that names no single definition is refused before the service starts rather
280
306
  * than when the document is first requested; schemas without references have nothing to resolve.
@@ -313,8 +339,11 @@ function checkSkillTool(mcp, tools) {
313
339
  function validBodyLimit(value) {
314
340
  return value === void 0 || Number.isInteger(value) && value > 0 && value <= 16777216;
315
341
  }
316
- /** The key pattern of `t.Record(t.String(), value)`, which every key matches, so every value is checked. */
317
- const ANY_KEY = "^(.*)$";
342
+ /**
343
+ * The key patterns of `t.Record(t.String(), value)`, which every key matches, so every value is checked: TypeBox
344
+ * 1.x writes the first, and 0.34 wrote the second.
345
+ */
346
+ const ANY_KEYS = /* @__PURE__ */ new Set(["^.*$", "^(.*)$"]);
318
347
  /**
319
348
  * Whether a schema holds, at any depth, a record whose keys follow a pattern but that admits other keys:
320
349
  * without `additionalProperties: false`, a key outside the pattern passes with any value at all.
@@ -324,7 +353,7 @@ function looseRecord(schema) {
324
353
  if (!schema || typeof schema !== "object") return false;
325
354
  const node = schema;
326
355
  const patterns = node.patternProperties;
327
- if (patterns && typeof patterns === "object" && node.additionalProperties !== false && Object.keys(patterns).some((pattern) => pattern !== ANY_KEY)) return true;
356
+ if (patterns && typeof patterns === "object" && node.additionalProperties !== false && Object.keys(patterns).some((pattern) => !ANY_KEYS.has(pattern))) return true;
328
357
  return Object.values(node).some(looseRecord);
329
358
  }
330
359
  /**
@@ -332,7 +361,8 @@ function looseRecord(schema) {
332
361
  * a union whose every member is a strict object, so a request body or a result
333
362
  * can be discriminated by a field (`{ channel: 'email', … } | { channel: 'sms', … }`).
334
363
  */
335
- function strictObject(schema, unions) {
364
+ function strictObject(node, unions) {
365
+ const schema = (node.$ref === void 0 ? void 0 : node.$defs?.[node.$ref]) ?? node;
336
366
  if (schema.type === "object") return schema.additionalProperties === false;
337
367
  const members = schema.anyOf;
338
368
  return unions && Array.isArray(members) && members.length > 0 && members.every((member) => strictObject(member, false));
@@ -0,0 +1,12 @@
1
+ // src/internal/delay.ts
2
+ /**
3
+ * A wait on the runtime's global timer, for code the core reaches: it may load where `node:timers` does not.
4
+ */
5
+ /** Resolves after `milliseconds`. */
6
+ function delay(milliseconds) {
7
+ return new Promise((resolve) => {
8
+ setTimeout(resolve, milliseconds);
9
+ });
10
+ }
11
+
12
+ export { delay as t };
@@ -75,4 +75,68 @@ function retryAfterSeconds(value, nowMs, maximum = 3600) {
75
75
  return Number.isFinite(seconds) ? Math.min(maximum, Math.max(0, Math.ceil(seconds))) : void 0;
76
76
  }
77
77
 
78
- export { retryAfterSeconds as a, readJsonResponse as i, mediaType as n, readJsonBody as r, isJsonMediaType as t };
78
+ // src/internal/destination.ts
79
+ /**
80
+ * Where a Worker may send a request for someone it does not control, such as a server an organization
81
+ * registered. A Worker cannot resolve a name before it fetches it, so the rules hold on the URL itself.
82
+ */
83
+ /**
84
+ * Top-level names reserved for special use or private networks (RFC 2606, 6761, 6762, 7686, 8375 and 9476),
85
+ * and the ones internal networks use.
86
+ */
87
+ const PRIVATE_TOP_LEVEL_NAMES = /* @__PURE__ */ new Set([
88
+ "alt",
89
+ "arpa",
90
+ "cloudflare",
91
+ "corp",
92
+ "example",
93
+ "home",
94
+ "internal",
95
+ "intranet",
96
+ "invalid",
97
+ "lan",
98
+ "local",
99
+ "localdomain",
100
+ "localhost",
101
+ "onion",
102
+ "private",
103
+ "test"
104
+ ]);
105
+ /**
106
+ * Cloudflare's own domains and Arbol's, subdomains included: Arbol's services are reached through the Gateway
107
+ * and native RPC, and neither ever stands for someone else's server.
108
+ */
109
+ const PLATFORM_DOMAINS = [
110
+ "cloudflare.com",
111
+ "cloudflareaccess.com",
112
+ "cloudflareclient.com",
113
+ "cloudflare-dns.com",
114
+ "cloudflare-gateway.com",
115
+ "getarbol.app",
116
+ "getarbol.com"
117
+ ];
118
+ /**
119
+ * A DNS name of two labels or more: letters, digits and inner hyphens, at most 63 characters a label and 253
120
+ * in all, under a top-level name of letters. An IP literal is none.
121
+ */
122
+ const DNS_NAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
123
+ /**
124
+ * The URL, when a Worker may send a request there for someone it does not control: https on its default port,
125
+ * with no credentials or fragment, to a public DNS name; never an IP literal, a special-use or private-network
126
+ * name, nor Cloudflare's or Arbol's own hosts. Undefined for anything else. Send the request with
127
+ * `redirect: 'manual'` and refuse a `3xx`, so no redirect takes it elsewhere.
128
+ */
129
+ function publicDestination(value) {
130
+ let url;
131
+ try {
132
+ url = new URL(value);
133
+ } catch {
134
+ return;
135
+ }
136
+ const host = url.hostname;
137
+ const topLevelName = host.slice(host.lastIndexOf(".") + 1);
138
+ if (url.protocol !== "https:" || url.port !== "" || url.username !== "" || url.password !== "" || url.hash !== "" || !DNS_NAME.test(host) || PRIVATE_TOP_LEVEL_NAMES.has(topLevelName) || PLATFORM_DOMAINS.some((domain) => host === domain || host.endsWith(`.${domain}`))) return;
139
+ return url;
140
+ }
141
+
142
+ export { readJsonResponse as a, readJsonBody as i, isJsonMediaType as n, retryAfterSeconds as o, mediaType as r, publicDestination as t };
@@ -0,0 +1,12 @@
1
+ // src/internal/digest.ts
2
+ /**
3
+ * SHA-256 digests in hexadecimal, for rate limit keys, the development token's comparison and capture.
4
+ */
5
+ /** The SHA-256 digest of text or bytes, in lowercase hexadecimal. */
6
+ async function sha256Hex(value) {
7
+ const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
8
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
9
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
10
+ }
11
+
12
+ export { sha256Hex as t };
@@ -1,7 +1,6 @@
1
+ import { a as parseSchema, f as Value } from "./validation-CpzAxj2_.js";
1
2
  import { t as STANDARD_FAILURES } from "./standard-failures-Lh4mSfwG.js";
2
- import { i as parseSchema } from "./validation-fTohBT6R.js";
3
- import { Type } from "@sinclair/typebox";
4
- import { Value } from "@sinclair/typebox/value";
3
+ import { Type } from "typebox";
5
4
 
6
5
  // src/errors.ts
7
6
  /**