@arbol-ai/maximus 8.1.0 → 8.5.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 (64) hide show
  1. package/dist/analytics/analytics.d.ts +16 -16
  2. package/dist/analytics/analytics.js +3 -3
  3. package/dist/body.d.ts +2 -2
  4. package/dist/body.js +2 -1
  5. package/dist/capture/index.d.ts +1 -1
  6. package/dist/capture/index.js +3 -4
  7. package/dist/chunks/{define-app-BxGZdNmS.js → define-app-CQpWqqqE.js} +33 -14
  8. package/dist/chunks/destination-5xTX0b7E.js +65 -0
  9. package/dist/chunks/{digest-C7UGt760.js → digest-C51F1bhA.js} +1 -2
  10. package/dist/chunks/{errors-CWgE9uvM.js → errors-BoutSmiy.js} +2 -3
  11. package/dist/chunks/{execution-BTiAWA4n.js → execution-Bpq6s4nA.js} +9 -8
  12. package/dist/chunks/{generate-C-9FKW0o.js → generate-Dg88LzLU.js} +1 -1
  13. package/dist/chunks/{handler-iebR-urt.js → handler-DSpyrWc-.js} +6 -2
  14. package/dist/chunks/{http-layout-BvlbD__1.js → http-layout-BcYH4I2w.js} +1 -1
  15. package/dist/chunks/{http-paths-DMBxwpp6.js → http-paths-D043DkJv.js} +50 -81
  16. package/dist/chunks/http-routes-B6tCsnxB.js +29 -0
  17. package/dist/chunks/{openapi-BF3eCpux.js → openapi-D2rds7vy.js} +27 -116
  18. package/dist/chunks/{openapi-file-RcXoq0AF.js → openapi-file-BK8zET5U.js} +24 -6
  19. package/dist/chunks/{pages-BCksUeRf.js → pages-B7ysoFAM.js} +1 -1
  20. package/dist/chunks/result-CF4OzG9O.js +29 -0
  21. package/dist/chunks/{runtime-D5eR9-Es.js → runtime-8OpxAvsI.js} +132 -7
  22. package/dist/chunks/schemas-_UJcx_uY.js +813 -0
  23. package/dist/chunks/{server-B9C8KPwa.js → server-CVhTLNj2.js} +37 -101
  24. package/dist/chunks/{src-C-4z443M.js → src-B_LthUVU.js} +39 -18
  25. package/dist/chunks/tasks-C873C3le.js +100 -0
  26. package/dist/chunks/tasks-DYdY-dBI.js +267 -0
  27. package/dist/chunks/{types-Dqo3oGig.d.ts → types-BfGa2aJT.d.ts} +346 -138
  28. package/dist/chunks/validation-CpzAxj2_.js +201 -0
  29. package/dist/chunks/{workers-types-BgjyDtGd.d.ts → workers-types-Cxf-5cH7.d.ts} +6 -1
  30. package/dist/client.d.ts +92 -0
  31. package/dist/client.js +300 -0
  32. package/dist/diagnostics.d.ts +1 -1
  33. package/dist/errors.d.ts +1 -1
  34. package/dist/errors.js +1 -1
  35. package/dist/http-paths.d.ts +1 -1
  36. package/dist/http-paths.js +1 -1
  37. package/dist/index.d.ts +2 -2
  38. package/dist/index.js +11 -9
  39. package/dist/internals.d.ts +1 -1
  40. package/dist/internals.js +4 -4
  41. package/dist/mcp/index.d.ts +1 -1
  42. package/dist/mcp/index.js +1 -1
  43. package/dist/mcp/tasks.d.ts +33 -0
  44. package/dist/mcp/tasks.js +3 -0
  45. package/dist/project/config.d.ts +2 -2
  46. package/dist/project/config.js +3 -2
  47. package/dist/project/index.d.ts +2 -2
  48. package/dist/project/index.js +3 -3
  49. package/dist/schemas.d.ts +2 -2
  50. package/dist/schemas.js +3 -3
  51. package/dist/standard-failures.d.ts +1 -1
  52. package/dist/tooling/cli.js +2 -2
  53. package/dist/vite/index.d.ts +1 -1
  54. package/dist/vite/index.js +6 -5
  55. package/dist/webhooks.d.ts +13 -2
  56. package/dist/webhooks.js +38 -1
  57. package/dist/workers/runtime.d.ts +1 -1
  58. package/dist/workers/runtime.js +1 -1
  59. package/package.json +15 -3
  60. package/skills/maximus/SKILL.md +7 -4
  61. package/skills/maximus/references/routes-and-tools.md +9 -1
  62. package/dist/chunks/result-CKgZHrnj.js +0 -56
  63. package/dist/chunks/schemas-BOFxZP1c.js +0 -227
  64. package/dist/chunks/validation-DMu0rkMQ.js +0 -670
@@ -0,0 +1,201 @@
1
+ import "ajv-formats/dist/formats.js";
2
+ import "typebox/format";
3
+ import "typebox/system";
4
+ import { AssertError, DecodeUnsafe, HasCodec, Value } from "typebox/value";
5
+
6
+ // src/internal/decode-issues.ts
7
+ /** Every issue of a refused value, as `readSchema` throws it and `checkSchema` returns it. */
8
+ var SchemaValidationError = class extends TypeError {
9
+ /** Every issue of the refused value; the error's message is the first one's. */
10
+ issues;
11
+ constructor(issues) {
12
+ super(issues[0]?.message ?? "The input does not match its schema.");
13
+ this.name = "SchemaValidationError";
14
+ this.issues = issues;
15
+ }
16
+ };
17
+ /**
18
+ * What an owner refinement's message starts with when it carries issues of its own, as JSON, or the errors of
19
+ * the schema a pipe reads its value into: TypeBox reports a refinement as one message at the refined value.
20
+ */
21
+ const CARRIED = "\0maximus:";
22
+ /** A refinement's message that carries issues at their paths below the refined value. */
23
+ function carriedIssues(issues) {
24
+ return `${CARRIED}${JSON.stringify(issues)}`;
25
+ }
26
+ /** A refinement's message that carries the errors of another schema, read below the refined value. */
27
+ function carriedErrors(errors) {
28
+ return carriedIssues(schemaIssues(errors));
29
+ }
30
+ /** The segments of a JSON Pointer, unescaped. */
31
+ function segments(path) {
32
+ return path.split("/").slice(1).map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
33
+ }
34
+ /** The issues of a refinement's error at its value's path: those it carries, or its own message. */
35
+ function refinementIssues(message, path) {
36
+ if (!message.startsWith(CARRIED)) return [{
37
+ code: "custom",
38
+ message,
39
+ path
40
+ }];
41
+ return JSON.parse(message.slice(9)).map((issue) => ({
42
+ ...issue,
43
+ path: [...path, ...issue.path]
44
+ }));
45
+ }
46
+ /**
47
+ * Field issues for TypeBox's errors, in their order. A missing or an unexpected property is an issue at its own
48
+ * path; a union that matched no member is one issue, its members' errors left out; a refinement is the issues
49
+ * it carries, or its message.
50
+ */
51
+ function schemaIssues(errors) {
52
+ const unions = errors.filter((error) => error.keyword === "anyOf").map(({ schemaPath }) => `${schemaPath}/anyOf/`);
53
+ const issues = [];
54
+ for (const error of errors) {
55
+ if (unions.some((union) => error.schemaPath.startsWith(union))) continue;
56
+ const path = segments(error.instancePath);
57
+ if (error.keyword === "required") for (const name of error.params.requiredProperties) issues.push({
58
+ code: "invalid_input",
59
+ message: "must be present",
60
+ path: [...path, name]
61
+ });
62
+ else if (error.keyword === "additionalProperties") for (const name of error.params.additionalProperties) issues.push({
63
+ code: "invalid_input",
64
+ message: "must not be present",
65
+ path: [...path, name]
66
+ });
67
+ else if (error.keyword === "~refine") issues.push(...refinementIssues(error.params.message, path));
68
+ else if (!(error.keyword === "boolean" && error.schemaPath.endsWith("/additionalProperties"))) issues.push({
69
+ code: "invalid_input",
70
+ message: error.message,
71
+ path
72
+ });
73
+ }
74
+ return issues;
75
+ }
76
+ /**
77
+ * The issues of a refused decode, at most `limit`, each with its path from the input's root, or null when
78
+ * nothing refused the input: an owner codec threw something other than a `SchemaValidationError`, which is the
79
+ * codec's fault for the caller to report. TypeBox builds at most as many errors as `internal/value.ts` allows,
80
+ * so an input with millions of them costs no more than a refusal carries.
81
+ */
82
+ function decodeIssues(error, limit = Number.POSITIVE_INFINITY) {
83
+ if (error instanceof SchemaValidationError) return error.issues.slice(0, limit);
84
+ if (error instanceof AssertError) return schemaIssues(error.cause.errors).slice(0, limit);
85
+ return null;
86
+ }
87
+ /** RFC 6901 JSON Pointer of an issue path; the empty string names the whole input. */
88
+ function jsonPointer(path) {
89
+ return path.map((part) => `/${String(part).replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
90
+ }
91
+
92
+ // src/validation.ts
93
+ /**
94
+ * Checks a value against a schema without decoding it: the value when it matches, else an `INVALID_INPUT`
95
+ * failure without issues. Use `decodeInput` for input with defaults and codecs.
96
+ */
97
+ function parseInput(schema, input) {
98
+ if (Value.Check(schema, input)) return {
99
+ ok: true,
100
+ value: input
101
+ };
102
+ return {
103
+ ok: false,
104
+ error: {
105
+ code: "INVALID_INPUT",
106
+ message: "The input does not match its schema.",
107
+ retryable: false,
108
+ data: {}
109
+ }
110
+ };
111
+ }
112
+ /** Checks a value against a schema and returns it typed, or throws a TypeError that names no value. */
113
+ function parseSchema(schema, input) {
114
+ if (!Value.Check(schema, input)) throw new TypeError("Value does not match its schema");
115
+ return input;
116
+ }
117
+ /**
118
+ * Whether a value is a bounded plain JSON tree, which TypeBox's traversals expect and every transport admits:
119
+ * no cycles, class instances, functions, non-finite numbers, nesting beyond 100 levels or own `__proto__` key.
120
+ */
121
+ function boundedInput(value, depth = 0, parents = /* @__PURE__ */ new Set()) {
122
+ if (depth > 100) return false;
123
+ if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") return true;
124
+ if (typeof value === "number") return Number.isFinite(value);
125
+ if (typeof value !== "object" || parents.has(value)) return false;
126
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false;
127
+ if (Object.hasOwn(value, "__proto__")) return false;
128
+ parents.add(value);
129
+ const valid = Object.values(value).every((child) => boundedInput(child, depth + 1, parents));
130
+ parents.delete(value);
131
+ return valid;
132
+ }
133
+ /**
134
+ * Decodes input against its schema: admits only a bounded plain JSON tree, applies the declared defaults to a
135
+ * copy, checks it, refinements included, and runs its codecs. Throws a `SchemaValidationError` (or TypeBox's
136
+ * assertion error) when the input is refused, and whatever an owner codec throws otherwise. Output is checked,
137
+ * never decoded: what a handler returns must already be canonical.
138
+ */
139
+ function decodeSchema(schema, input) {
140
+ return admitSchema(schema, input).value;
141
+ }
142
+ /** Decodes input as `decodeSchema` does, and also answers what the schema checked, before any codec ran. */
143
+ function admitSchema(schema, input) {
144
+ if (!boundedInput(input)) throw new SchemaValidationError([{
145
+ code: "invalid_input",
146
+ message: "Input must be a bounded plain JSON tree.",
147
+ path: []
148
+ }]);
149
+ const checked = Value.Default(schema, Value.Clone(input));
150
+ Value.Assert(schema, checked);
151
+ return {
152
+ value: HasCodec(schema) ? DecodeUnsafe({}, schema, Value.Clone(checked)) : checked,
153
+ checked
154
+ };
155
+ }
156
+ /** The longest path or message one issue carries. */
157
+ const MAX_ISSUE_TEXT = 256;
158
+ /**
159
+ * Decodes input as `decodeSchema` does and answers a refusal as the `INVALID_INPUT` failure, with its first
160
+ * field issues: where the input failed and what was expected, never a value. A fault of an owner codec, an
161
+ * error that refuses nothing, is thrown for the caller to report: it is the server's failure, not the input's.
162
+ */
163
+ function decodeInput(schema, input) {
164
+ const admitted = admitInput(schema, input);
165
+ return admitted.ok ? {
166
+ ok: true,
167
+ value: admitted.value
168
+ } : admitted;
169
+ }
170
+ /**
171
+ * `decodeInput`, also answering, for an admitted input, `checked`: the plain JSON its schema checked before any
172
+ * codec ran, the one shape the schema's own keywords describe.
173
+ */
174
+ function admitInput(schema, input) {
175
+ let admitted;
176
+ try {
177
+ admitted = admitSchema(schema, input);
178
+ } catch (error) {
179
+ const refused = decodeIssues(error, 10);
180
+ if (!refused) throw error;
181
+ return {
182
+ ok: false,
183
+ error: {
184
+ code: "INVALID_INPUT",
185
+ message: "The input does not match its schema.",
186
+ retryable: false,
187
+ data: { issues: refused.map((issue) => ({
188
+ path: jsonPointer(issue.path).slice(0, MAX_ISSUE_TEXT),
189
+ message: issue.message.slice(0, MAX_ISSUE_TEXT)
190
+ })) }
191
+ }
192
+ };
193
+ }
194
+ return {
195
+ ok: true,
196
+ value: admitted.value,
197
+ checked: admitted.checked
198
+ };
199
+ }
200
+
201
+ export { parseSchema as a, carriedIssues as c, HasCodec as d, Value as f, parseInput as i, decodeIssues as l, decodeInput as n, SchemaValidationError as o, decodeSchema as r, carriedErrors as s, admitInput as t, DecodeUnsafe as u };
@@ -1,4 +1,4 @@
1
- import { Cr as Failure, E as HttpRoute, T as HttpOptions, dr as Result, er as Principal, in as AppManifest, mn as OperationShape, n as Static, r as TSchema } from "./types-Dqo3oGig.js";
1
+ import { D as HttpRoute, E as HttpOptions, cr as Principal, dn as AppManifest, jr as Failure, n as Static, r as TSchema, un as TaskStore, xn as OperationShape, yr as Result } from "./types-BfGa2aJT.js";
2
2
  import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
3
3
  /** A Workers static-assets binding; product stores and secrets never satisfy this capability. */
4
4
  interface AssetBinding {
@@ -101,6 +101,11 @@ interface WorkerRuntime<E, O extends Record<string, OperationShape>> {
101
101
  * methods and type.
102
102
  */
103
103
  durableObject: <T extends DurableObject<E>, D extends new (state: DurableObject['ctx'], env: E) => T>(implementation: D) => D;
104
+ /**
105
+ * The task store of the operations that declare `task: true`: export it by name, `MaximusTasks`, as the class
106
+ * of a SQLite Durable Object binding named `MAXIMUS_TASKS`.
107
+ */
108
+ tasks: new (state: DurableObject['ctx'], env: E) => DurableObject<E> & TaskStore;
104
109
  }
105
110
  /**
106
111
  * What `createWorker` takes besides the application: the Worker's other handlers, its transports, the HTTP
@@ -0,0 +1,92 @@
1
+ import { F as Static, jr as Failure, xn as OperationShape } from "./chunks/types-BfGa2aJT.js";
2
+ /** What every HTTP operation answers: its data on success, its failure otherwise, and the request id. */
3
+ export type Envelope<T> = {
4
+ success: true;
5
+ data: T;
6
+ error: null;
7
+ metadata: {
8
+ requestId: string;
9
+ };
10
+ } | {
11
+ success: false;
12
+ data: null;
13
+ error: Failure;
14
+ metadata: {
15
+ requestId: string;
16
+ };
17
+ };
18
+ /** The part of an application the client's types read: its operations. `typeof app` satisfies it. */
19
+ export interface ClientManifest {
20
+ operations: Record<string, OperationShape>;
21
+ }
22
+ /** The operations public over HTTP: those with a route that are not internal. */
23
+ export type OperationName<M extends ClientManifest> = Extract<{ [K in keyof M['operations']]: M['operations'][K] extends {
24
+ http: object;
25
+ } ? M['operations'][K] extends {
26
+ visibility: 'internal';
27
+ } ? never : K : never; }[keyof M['operations']], string>;
28
+ /** The operations that read, POST searches included: what a read cache may own, whatever the method. */
29
+ export type ReadOperationName<M extends ClientManifest> = { [K in OperationName<M>]: M['operations'][K] extends {
30
+ effect: 'read';
31
+ } ? K : never; }[OperationName<M>];
32
+ /** What an operation takes, as callers send it, path fields included. */
33
+ export type OperationInput<M extends ClientManifest, K extends OperationName<M>> = Static<M['operations'][K]['input']>;
34
+ /** What an operation answers: its output, or the Response of an attachment. */
35
+ export type OperationOutput<M extends ClientManifest, K extends OperationName<M>> = M['operations'][K] extends {
36
+ http: {
37
+ response: 'attachment';
38
+ };
39
+ } ? Response : Static<M['operations'][K]['output']>;
40
+ /** Options of one call: a signal that cancels it. */
41
+ export interface CallOptions {
42
+ signal?: AbortSignal;
43
+ }
44
+ /** Options of one call to a byte operation: the bytes and the transfer's two moments. */
45
+ export interface BinaryCallOptions extends CallOptions {
46
+ /** Sent with its own type, unless a header field of the input names the content type. */
47
+ body: Blob | Uint8Array<ArrayBuffer>;
48
+ /** 0 when sending begins, 1 after a success response; not byte progress. */
49
+ onUploadProgress?: (share: 0 | 1) => void;
50
+ }
51
+ /** A refusal the service answered: its status, its failure and the request's id (empty when invalid). */
52
+ export interface ClientFailure {
53
+ status: number;
54
+ failure: Failure;
55
+ requestId: string;
56
+ }
57
+ /** How the client answers and bounds what it reads, and the hooks around each request. */
58
+ export interface ClientOptions {
59
+ /** `data` answers each call's data and throws its refusal; the envelope is answered otherwise. */
60
+ response?: 'data' | 'envelope';
61
+ /** A signal taken at each call, before anything awaits. */
62
+ signal?: () => AbortSignal;
63
+ /** The Error a refusal throws in `data` mode. */
64
+ onFailure?: (refusal: ClientFailure) => Error;
65
+ /** The fetch every request goes through: the global one, or a test's Worker. */
66
+ fetch?: typeof fetch;
67
+ /** May add headers; the method, URL, body and bearer stay the client's. */
68
+ beforeRequest?: (request: Request) => void | Promise<void>;
69
+ afterResponse?: (response: Response, request: Request) => void | Promise<void>;
70
+ /** The largest operation response read: 1 MiB unless set. */
71
+ maxResponseBytes?: number;
72
+ }
73
+ type Answer<M extends ClientManifest, K extends OperationName<M>, Mode> = Mode extends 'data' ? OperationOutput<M, K> : Envelope<OperationOutput<M, K>>;
74
+ /** One method per public HTTP operation; a byte operation also takes its body in the call options. */
75
+ export type AppClientContract<M extends ClientManifest, Mode extends 'data' | 'envelope' = 'envelope'> = { [K in OperationName<M>]: M['operations'][K] extends {
76
+ http: {
77
+ body: 'bytes';
78
+ };
79
+ } ? (input: OperationInput<M, K>, options: BinaryCallOptions) => Promise<Answer<M, K, Mode>> : (input: OperationInput<M, K>, options?: CallOptions) => Promise<Answer<M, K, Mode>>; };
80
+ /**
81
+ * A typed client of an application, from its type alone (`createClient<typeof app>(…)`), for the service at
82
+ * `origin` (a base URL that may carry a path, such as `https://agenda.getarbol.com/api`). `token` is the
83
+ * bearer, or a function asked for it before every request, so a renewed token is always the one sent. With
84
+ * `response: 'data'`, a method answers the data and throws on a refusal; otherwise it answers the envelope.
85
+ */
86
+ export declare function createClient<M extends ClientManifest>(origin: string, token: string | (() => Promise<string>), options: ClientOptions & {
87
+ response: 'data';
88
+ }): AppClientContract<M, 'data'>;
89
+ export declare function createClient<M extends ClientManifest>(origin: string, token: string | (() => Promise<string>), options?: ClientOptions & {
90
+ response?: 'envelope';
91
+ }): AppClientContract<M>;
92
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,300 @@
1
+ import { a as operationPathParameters, i as isPathParameterValue, r as isInputHeaderName } from "./chunks/http-paths-D043DkJv.js";
2
+ import { i as readJsonResponse } from "./chunks/json-B14evE6-.js";
3
+
4
+ // src/client.ts
5
+ const TIMEOUT_MS = 3e4;
6
+ const MAX_CONTRACT_BYTES = 4194304;
7
+ const DEFAULT_MAX_RESPONSE_BYTES = 1048576;
8
+ const MAX_FAILURE_BYTES = 16384;
9
+ const MAX_ATTACHMENT_BYTES = 16777216;
10
+ const METHODS = /* @__PURE__ */ new Set([
11
+ "get",
12
+ "post",
13
+ "put",
14
+ "patch",
15
+ "delete"
16
+ ]);
17
+ /** Maximus's request ids: a UUID, or a Cloudflare ray. */
18
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
19
+ const RAY = /^[0-9a-f]{16}(?:-[A-Z]{3})?$/u;
20
+ /** What a malformed refusal reads as: the service's own failure, never its unchecked text. */
21
+ const INTERNAL_FAILURE = {
22
+ code: "INTERNAL_ERROR",
23
+ message: "The service could not complete the operation.",
24
+ retryable: false,
25
+ data: {}
26
+ };
27
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
28
+ const isRequestId = (value) => typeof value === "string" && (UUID.test(value) || RAY.test(value));
29
+ const isFailure = (value) => isRecord(value) && Object.keys(value).length === 4 && typeof value.code === "string" && /^[^\p{Cc}]{1,128}$/u.test(value.code) && typeof value.message === "string" && typeof value.retryable === "boolean" && isRecord(value.data);
30
+ /** What an abort listener is before it is listening. */
31
+ const ignore = () => {};
32
+ /** Waits for `pending` until `signal` aborts, then rejects with its reason; the work itself goes on. */
33
+ async function untilAborted(pending, signal) {
34
+ signal.throwIfAborted();
35
+ let abort = ignore;
36
+ const aborted = new Promise((_resolve, reject) => {
37
+ abort = () => reject(signal.reason);
38
+ signal.addEventListener("abort", abort, { once: true });
39
+ });
40
+ try {
41
+ return await Promise.race([pending, aborted]);
42
+ } finally {
43
+ signal.removeEventListener("abort", abort);
44
+ }
45
+ }
46
+ /** A GET input value as the service's query reads it back; null for one a query string cannot carry. */
47
+ function queryValue(value) {
48
+ if (typeof value === "string") return value;
49
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : null;
50
+ if (typeof value === "boolean") return String(value);
51
+ return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string" && item !== "" && !item.includes(",")) ? value.join(",") : null;
52
+ }
53
+ /** One operation's route, or null for a method the client does not send. */
54
+ function readRoute(path, method, operation) {
55
+ if (!METHODS.has(method)) return null;
56
+ const headers = isRecord(operation) ? operation["x-input-headers"] ?? {} : null;
57
+ if (!isRecord(operation) || typeof operation.operationId !== "string" || !isRecord(headers) || Object.values(headers).some((header) => typeof header !== "string" || !isInputHeaderName(header))) throw new Error("Invalid service operation.");
58
+ return [operation.operationId, {
59
+ method: method.toUpperCase(),
60
+ path,
61
+ parameters: operationPathParameters(path),
62
+ headers,
63
+ bytes: operation["x-body"] === "bytes",
64
+ attachment: operation["x-response"] === "attachment"
65
+ }];
66
+ }
67
+ /** Every operation's route, method, header fields, byte body and attachment, from an OpenAPI document. */
68
+ function readRoutes(document) {
69
+ const paths = isRecord(document) ? document.paths : void 0;
70
+ if (!isRecord(paths)) throw new Error("Invalid service contract.");
71
+ const routes = /* @__PURE__ */ new Map();
72
+ for (const [path, methods] of Object.entries(paths)) for (const [method, operation] of Object.entries(isRecord(methods) ? methods : {})) {
73
+ const entry = readRoute(path, method, operation);
74
+ if (entry && routes.has(entry[0])) throw new Error("Invalid service operation.");
75
+ if (entry) routes.set(...entry);
76
+ }
77
+ return routes;
78
+ }
79
+ /** An operation's envelope, its shape and status checked before any data or failure reaches the caller. */
80
+ function readEnvelope(value, status) {
81
+ if (isRecord(value) && Object.keys(value).length === 4 && Object.hasOwn(value, "data") && isRecord(value.metadata) && Object.keys(value.metadata).length === 1 && isRequestId(value.metadata.requestId)) {
82
+ const metadata = { requestId: value.metadata.requestId };
83
+ if (value.success === true && value.error === null && status >= 200 && status < 300) return {
84
+ success: true,
85
+ data: value.data,
86
+ error: null,
87
+ metadata
88
+ };
89
+ if (value.success === false && value.data === null && isFailure(value.error) && status >= 400 && status < 600) return {
90
+ success: false,
91
+ data: null,
92
+ error: value.error,
93
+ metadata
94
+ };
95
+ }
96
+ throw new Error(`Invalid service response (${status}).`);
97
+ }
98
+ /** A byte operation's request: the bytes as its body, its string fields as headers or query. */
99
+ function prepareBytes(route, url, rest, options) {
100
+ const upload = options;
101
+ if (!(upload?.body instanceof Blob || upload?.body instanceof Uint8Array)) throw new TypeError("A binary body is required.");
102
+ const headers = new Headers();
103
+ for (const [field, value] of rest) {
104
+ if (value === void 0) continue;
105
+ if (typeof value !== "string") throw new TypeError("Header and query values of a byte operation must be strings.");
106
+ const header = route.headers[field];
107
+ if (header) headers.set(header, value);
108
+ else url.searchParams.set(field, value);
109
+ }
110
+ if (!headers.has("content-type")) {
111
+ const type = upload.body instanceof Blob ? upload.body.type : "";
112
+ headers.set("content-type", type || "application/octet-stream");
113
+ }
114
+ return {
115
+ url,
116
+ headers,
117
+ body: upload.body,
118
+ upload
119
+ };
120
+ }
121
+ /** A GET request: every field that is not in the path travels in the query. */
122
+ function prepareQuery(url, rest) {
123
+ for (const [field, value] of rest) {
124
+ if (value === void 0) continue;
125
+ const text = queryValue(value);
126
+ if (text === null) throw new TypeError("Query values must be strings, finite numbers, booleans or lists of strings.");
127
+ url.searchParams.set(field, text);
128
+ }
129
+ return {
130
+ url,
131
+ headers: new Headers(),
132
+ body: void 0,
133
+ upload: void 0
134
+ };
135
+ }
136
+ /** The service URL of one route, its path fields filled in and encoded. */
137
+ function routeUrl(route, input, serviceUrl) {
138
+ let { path } = route;
139
+ for (const parameter of route.parameters) {
140
+ const value = input[parameter];
141
+ if (!isPathParameterValue(value)) throw new TypeError("Path values must be nonempty strings without slashes, dot segments or controls.");
142
+ path = path.replace(`{${parameter}}`, encodeURIComponent(value));
143
+ }
144
+ return serviceUrl(path);
145
+ }
146
+ /** The call's URL, headers and body: path fields in the path, the rest in the query, headers or JSON body. */
147
+ function prepare(route, input, options, serviceUrl) {
148
+ const url = routeUrl(route, input, serviceUrl);
149
+ const rest = Object.entries(input).filter(([field]) => !route.parameters.includes(field));
150
+ if (route.bytes) return prepareBytes(route, url, rest, options);
151
+ if (route.method === "GET") return prepareQuery(url, rest);
152
+ return {
153
+ url,
154
+ headers: new Headers({ "content-type": "application/json" }),
155
+ body: JSON.stringify(Object.fromEntries(rest)),
156
+ upload: void 0
157
+ };
158
+ }
159
+ /** An attachment's answer: the Response itself, once its declared length is within bounds. */
160
+ function attachmentAnswer(response, dataMode) {
161
+ const length = Number(response.headers.get("content-length") ?? NaN);
162
+ if (!Number.isSafeInteger(length) || length < 0 || length > MAX_ATTACHMENT_BYTES) throw new Error("Invalid attachment length.");
163
+ if (dataMode) return response;
164
+ return {
165
+ success: true,
166
+ data: response,
167
+ error: null,
168
+ metadata: { requestId: response.headers.get("x-request-id") ?? "" }
169
+ };
170
+ }
171
+ /** The envelope a response carries; in data mode a malformed refusal reads as the internal failure. */
172
+ function answeredEnvelope(value, response, dataMode) {
173
+ try {
174
+ return readEnvelope(value, response.status);
175
+ } catch (error) {
176
+ if (!dataMode || response.ok) throw error;
177
+ const requestId = response.headers.get("x-request-id");
178
+ return {
179
+ success: false,
180
+ data: null,
181
+ error: INTERNAL_FAILURE,
182
+ metadata: { requestId: isRequestId(requestId) ? requestId : "" }
183
+ };
184
+ }
185
+ }
186
+ function createClient(origin, token, options = {}) {
187
+ const base = new URL(origin);
188
+ const prefix = base.pathname.replace(/\/$/u, "");
189
+ const serviceUrl = (path) => new URL(`${prefix}${path}`, base.origin);
190
+ const transport = options.fetch ?? fetch;
191
+ const dataMode = options.response === "data";
192
+ let routes;
193
+ /** The bearer of one request: the token, or the one its function answers now. */
194
+ async function bearer(signal) {
195
+ if (typeof token === "string") return token;
196
+ return await untilAborted(token(), signal);
197
+ }
198
+ /** Sends one request after the hooks: they add headers, never the bearer, method, body or deadline. */
199
+ async function send(url, init, authenticated = true) {
200
+ const { signal } = init;
201
+ const authorization = authenticated ? `Bearer ${await bearer(signal)}` : void 0;
202
+ const request = new Request(url, {
203
+ ...init,
204
+ redirect: "manual",
205
+ credentials: "omit",
206
+ cache: "no-store"
207
+ });
208
+ await untilAborted(Promise.resolve(options.beforeRequest?.(request)), signal);
209
+ for (const [header, value] of new Headers(init.headers)) request.headers.set(header, value);
210
+ if (authorization) request.headers.set("authorization", authorization);
211
+ else request.headers.delete("authorization");
212
+ const response = await untilAborted(transport(url, {
213
+ ...init,
214
+ headers: Object.fromEntries(request.headers),
215
+ redirect: "manual",
216
+ credentials: "omit",
217
+ cache: "no-store"
218
+ }), signal);
219
+ await untilAborted(Promise.resolve(options.afterResponse?.(response, request)), signal);
220
+ return response;
221
+ }
222
+ /** The routes, read once from the live contract. */
223
+ async function discover() {
224
+ const signal = AbortSignal.timeout(TIMEOUT_MS);
225
+ const response = await send(serviceUrl("/openapi.json"), {
226
+ method: "GET",
227
+ signal
228
+ }, false);
229
+ const document = await readJsonResponse(response, {
230
+ signal,
231
+ maxBytes: MAX_CONTRACT_BYTES
232
+ });
233
+ if (!response.ok || !document.ok) throw new Error("Invalid service contract.");
234
+ return readRoutes(document.value);
235
+ }
236
+ /** The route of an operation; a failed read of the contract is tried again by the next call. */
237
+ async function routeOf(name, signal) {
238
+ routes ??= discover();
239
+ let known;
240
+ try {
241
+ known = await untilAborted(routes, signal);
242
+ } catch (error) {
243
+ routes = void 0;
244
+ throw error;
245
+ }
246
+ const route = known.get(name);
247
+ if (!route) throw new Error("Operation is not exposed over HTTP.");
248
+ return route;
249
+ }
250
+ /** What a call answers in data mode: the data, or the Error its refusal throws. */
251
+ function dataOf(envelope, status) {
252
+ if (envelope.success) return envelope.data;
253
+ const refusal = {
254
+ status,
255
+ failure: envelope.error,
256
+ requestId: envelope.metadata.requestId
257
+ };
258
+ throw options.onFailure?.(refusal) ?? new Error("The service refused the request.", { cause: refusal });
259
+ }
260
+ /** One call: route, request, then the envelope, or the attachment, as the client's mode answers it. */
261
+ async function call(name, input, callOptions) {
262
+ const signals = [
263
+ AbortSignal.timeout(TIMEOUT_MS),
264
+ options.signal?.(),
265
+ callOptions?.signal
266
+ ];
267
+ const signal = AbortSignal.any(signals.filter((entry) => entry !== void 0));
268
+ signal.throwIfAborted();
269
+ const route = await routeOf(name, signal);
270
+ const { url, headers, body, upload } = prepare(route, input, callOptions, serviceUrl);
271
+ upload?.onUploadProgress?.(0);
272
+ const response = await send(url, {
273
+ method: route.method,
274
+ signal,
275
+ headers,
276
+ body
277
+ });
278
+ if (route.attachment && response.ok) {
279
+ const answer = attachmentAnswer(response, dataMode);
280
+ upload?.onUploadProgress?.(1);
281
+ return answer;
282
+ }
283
+ const maxBytes = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
284
+ const limit = response.ok ? maxBytes : Math.min(maxBytes, MAX_FAILURE_BYTES);
285
+ const read = await readJsonResponse(response, {
286
+ signal,
287
+ maxBytes: limit
288
+ });
289
+ signal.throwIfAborted();
290
+ const envelope = answeredEnvelope(read.ok ? read.value : void 0, response, dataMode);
291
+ if (envelope.success) upload?.onUploadProgress?.(1);
292
+ return dataMode ? dataOf(envelope, response.status) : envelope;
293
+ }
294
+ return new Proxy(Object.create(null), { get(_target, name) {
295
+ if (typeof name !== "string" || name === "then") return;
296
+ return (input, callOptions) => call(name, input, callOptions);
297
+ } });
298
+ }
299
+
300
+ export { createClient };
@@ -1,4 +1,4 @@
1
- import { Ar as TraceParent, Bn as withDiagnostics, Fn as TelemetryConfig, In as diagnosticsEnabled, Ln as recordExecution, Mn as BackgroundContext, Mr as durableCorrelation, Nn as ExecutionObservation, Nr as isRequestId, Pn as Observer, Pr as parseTraceParent, Rn as reportUnexpected, jr as createRequestId, kr as DurableCorrelation, zn as telemetryEnabled } from "./chunks/types-Dqo3oGig.js";
1
+ import { Bn as BackgroundContext, Br as durableCorrelation, Gn as recordExecution, Hn as Observer, Hr as parseTraceParent, Jn as withDiagnostics, Kn as reportUnexpected, Lr as DurableCorrelation, Rr as TraceParent, Un as TelemetryConfig, Vn as ExecutionObservation, Vr as isRequestId, Wn as diagnosticsEnabled, qn as telemetryEnabled, zr as createRequestId } from "./chunks/types-BfGa2aJT.js";
2
2
  /**
3
3
  * What diagnostics may say about an error: its name, its causes' names, its issue count and its stack
4
4
  * locations.
package/dist/errors.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { Cr as Failure, Dr as resultSchema, Er as defineErrors, Nr as isRequestId, Or as standardErrors, Sr as ErrorFactory, Tr as FailureSchema, br as ErrorCatalog, vr as CreateArguments, wr as FailureData, xr as ErrorDefinition, yr as DefinedErrors } from "./chunks/types-Dqo3oGig.js";
1
+ import { Ar as ErrorFactory, Dr as DefinedErrors, Er as CreateArguments, Fr as resultSchema, Ir as standardErrors, Mr as FailureData, Nr as FailureSchema, Or as ErrorCatalog, Pr as defineErrors, Vr as isRequestId, jr as Failure, kr as ErrorDefinition } from "./chunks/types-BfGa2aJT.js";
2
2
  export { CreateArguments, DefinedErrors, ErrorCatalog, ErrorDefinition, ErrorFactory, Failure, FailureData, FailureSchema, defineErrors, isRequestId, resultSchema, standardErrors };
package/dist/errors.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { r as isRequestId } from "./chunks/correlation-4b23a-a4.js";
2
- import { i as standardErrors, n as defineErrors, r as resultSchema, t as FailureSchema } from "./chunks/errors-CWgE9uvM.js";
2
+ import { i as standardErrors, n as defineErrors, r as resultSchema, t as FailureSchema } from "./chunks/errors-BoutSmiy.js";
3
3
 
4
4
  export { FailureSchema, defineErrors, isRequestId, resultSchema, standardErrors };
@@ -1,2 +1,2 @@
1
- import { C as operationPathParameters, S as isPathParameterValue, _ as HttpRouteDefinition, b as decodePathParameter, v as HttpRouteMatch, x as isInputHeaderName, y as createHttpRouteResolver } from "./chunks/types-Dqo3oGig.js";
1
+ import { C as isPathParameterValue, S as isInputHeaderName, b as createHttpRouteResolver, v as HttpRouteDefinition, w as operationPathParameters, x as decodePathParameter, y as HttpRouteMatch } from "./chunks/types-BfGa2aJT.js";
2
2
  export { HttpRouteDefinition, HttpRouteMatch, createHttpRouteResolver, decodePathParameter, isInputHeaderName, isPathParameterValue, operationPathParameters };
@@ -1,3 +1,3 @@
1
- import { a as operationPathParameters, i as isPathParameterValue, n as decodePathParameter, r as isInputHeaderName, t as createHttpRouteResolver } from "./chunks/http-paths-DMBxwpp6.js";
1
+ import { a as operationPathParameters, i as isPathParameterValue, n as decodePathParameter, r as isInputHeaderName, t as createHttpRouteResolver } from "./chunks/http-paths-D043DkJv.js";
2
2
 
3
3
  export { createHttpRouteResolver, decodePathParameter, isInputHeaderName, isPathParameterValue, operationPathParameters };