@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
@@ -0,0 +1,382 @@
1
+ import { FormatRegistry, Kind, TransformKind, Type } from "@sinclair/typebox";
2
+ import { AssertError, HasTransform, TransformDecode, TransformDecodeError, Value } from "@sinclair/typebox/value";
3
+ import { fullFormats } from "ajv-formats/dist/formats.js";
4
+
5
+ //#region src/input-schemas.ts
6
+ /**
7
+ * Owner codecs on TypeBox schemas: defaults, normalizers, transforms, inspections, refinements, pipes and
8
+ * unknown-key stripping. `inputSchema()` compiles them into one input schema, so the wire is checked as
9
+ * declared and the handler receives the decoded value.
10
+ */
11
+ /** Every issue of a refused value, as `readSchema` throws it and `checkSchema` returns it. */
12
+ var SchemaValidationError = class extends TypeError {
13
+ /** Every issue of the refused value; the error's message is the first one's. */
14
+ issues;
15
+ constructor(issues) {
16
+ super(issues[0]?.message ?? "The input does not match its schema.");
17
+ this.name = "SchemaValidationError";
18
+ this.issues = issues;
19
+ }
20
+ };
21
+ /** The ordered codec steps a schema runs inside `inputSchema()`. */
22
+ const STEPS = Symbol("maximus.schema.steps");
23
+ /** The transforms a schema applies after its source value is valid. */
24
+ const TRANSFORMERS = Symbol("maximus.schema.transformers");
25
+ /** The normalizers a schema applies before its own checks. */
26
+ const NORMALIZERS = Symbol("maximus.schema.normalizers");
27
+ /** The inspections and refinements a schema runs on a valid value. */
28
+ const INSPECTORS = Symbol("maximus.schema.inspectors");
29
+ /** The source schema of a `pipeSchema`, which the wire value is first read as. */
30
+ const SOURCE = Symbol("maximus.schema.source");
31
+ /** Whether an object drops unknown keys when read with `stripUnknown`. */
32
+ const STRIP = Symbol("maximus.schema.strip");
33
+ /** A union of literals: `literalUnion(['open', 'done'])`. */
34
+ const literalUnion = (values) => Type.Union(values.map((value) => Type.Literal(value)));
35
+ /**
36
+ * The schema with a default that decoding applies when the field is absent, so the field is optional on the
37
+ * wire.
38
+ */
39
+ const defaultSchema = (schema, value) => ({
40
+ ...schema,
41
+ default: value
42
+ });
43
+ /**
44
+ * A strict object that, read with `stripUnknown` (as `readSchema` does), drops unknown keys instead of
45
+ * refusing them. Wrap an input that uses it in `inputSchema()`.
46
+ */
47
+ const stripObject = (properties) => ({
48
+ ...Type.Object(properties, { additionalProperties: false }),
49
+ [STRIP]: true
50
+ });
51
+ /** The object, refusing unknown keys even where a read strips them. */
52
+ const strictObject = (schema) => ({
53
+ ...schema,
54
+ additionalProperties: false,
55
+ [STRIP]: false
56
+ });
57
+ /** The object, admitting and keeping unknown keys. */
58
+ const looseObject = (schema) => ({
59
+ ...schema,
60
+ additionalProperties: true,
61
+ [STRIP]: false
62
+ });
63
+ /** The object with more properties, keeping how it treats unknown keys. */
64
+ const extendObject = (schema, properties) => ({
65
+ ...Type.Object({
66
+ ...schema.properties,
67
+ ...properties
68
+ }, { additionalProperties: schema.additionalProperties }),
69
+ [STRIP]: schema[STRIP]
70
+ });
71
+ /** Owner normalization keeps persisted/document input behavior separate from wire validation. */
72
+ const normalizeSchema = (schema, normalize) => Type.Unsafe({
73
+ ...schema,
74
+ [NORMALIZERS]: [...schema[NORMALIZERS] ?? [], normalize],
75
+ [STEPS]: [...schema[STEPS] ?? [], {
76
+ kind: "normalize",
77
+ apply: normalize
78
+ }]
79
+ });
80
+ /** Apply a domain transform only after validating its source value. */
81
+ const transformSchema = (schema, transform) => Type.Unsafe({
82
+ ...schema,
83
+ [TRANSFORMERS]: [...schema[TRANSFORMERS] ?? [], transform],
84
+ [STEPS]: [...schema[STEPS] ?? [], {
85
+ kind: "transform",
86
+ apply: transform
87
+ }]
88
+ });
89
+ /**
90
+ * Admits a value as `source`, then checks and decodes the result as `target`: a wire shape read into its
91
+ * canonical one. Runs inside `inputSchema()`.
92
+ */
93
+ const pipeSchema = (source, target) => ({
94
+ ...target,
95
+ [SOURCE]: source
96
+ });
97
+ /**
98
+ * Runs `inspect` on a value the schema admits; every `addIssue` refuses the value with that issue. Runs
99
+ * inside `inputSchema()`.
100
+ */
101
+ const inspectSchema = (schema, inspect) => ({
102
+ ...schema,
103
+ [INSPECTORS]: [...schema[INSPECTORS] ?? [], inspect],
104
+ [STEPS]: [...schema[STEPS] ?? [], {
105
+ kind: "inspect",
106
+ apply: inspect
107
+ }]
108
+ });
109
+ /**
110
+ * Refuses a value the schema admits when `predicate` rejects it, with `detail` as the issue's message and
111
+ * path. Runs inside `inputSchema()`.
112
+ */
113
+ const refineSchema = (schema, predicate, detail) => inspectSchema(schema, (value, context) => {
114
+ if (!predicate(value)) context.addIssue({
115
+ code: "custom",
116
+ message: typeof detail === "string" ? detail : detail?.message ?? detail?.error ?? "Invalid value",
117
+ path: typeof detail === "object" ? detail.path ?? [] : []
118
+ });
119
+ });
120
+ /** A URL whose protocol, and optionally hostname, match the given patterns. Runs inside `inputSchema()`. */
121
+ const urlSchema = (options) => refineSchema(Type.String({
122
+ format: "uri",
123
+ ...options.maxLength ? { maxLength: options.maxLength } : {}
124
+ }), (value) => {
125
+ try {
126
+ const url = new URL(value);
127
+ return options.protocol.test(url.protocol.slice(0, -1)) && (!options.hostname || options.hostname.test(url.hostname));
128
+ } catch {
129
+ return false;
130
+ }
131
+ });
132
+ /** Compile owner semantics into real native TypeBox source codecs. Canonical output schemas stay strict. */
133
+ const projectOwnerInput = (schema, stripUnknown) => {
134
+ if (schema[SOURCE]) {
135
+ const source = projectOwnerInput(schema[SOURCE], stripUnknown);
136
+ const targetSchema = {
137
+ ...schema,
138
+ [SOURCE]: void 0
139
+ };
140
+ const target = projectOwnerInput(targetSchema, stripUnknown);
141
+ return Type.Transform(source).Decode((value) => {
142
+ const targetInput = Value.Default(target, value);
143
+ Value.Assert(target, targetInput);
144
+ return TransformDecode(target, [], targetInput);
145
+ }).Encode((value) => value);
146
+ }
147
+ const projected = { ...schema };
148
+ if (schema.properties) {
149
+ projected.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => [key, projectOwnerInput(value, stripUnknown)]));
150
+ projected.required = schema.required?.filter((key) => !("default" in schema.properties[key]));
151
+ if (stripUnknown && schema[STRIP]) projected.additionalProperties = true;
152
+ }
153
+ if (schema.items) projected.items = Array.isArray(schema.items) ? schema.items.map((value) => projectOwnerInput(value, stripUnknown)) : projectOwnerInput(schema.items, stripUnknown);
154
+ if (schema.anyOf) projected.anyOf = schema.anyOf.map((value) => {
155
+ if ((schema[NORMALIZERS]?.length ?? 0) > 0 && value.type === "string") {
156
+ const source = { ...value };
157
+ delete source.pattern;
158
+ delete source.format;
159
+ delete source.minLength;
160
+ delete source.maxLength;
161
+ return projectOwnerInput(source, stripUnknown);
162
+ }
163
+ return projectOwnerInput(value, stripUnknown);
164
+ });
165
+ if (schema.patternProperties) projected.patternProperties = Object.fromEntries(Object.entries(schema.patternProperties).map(([key, value]) => [key, projectOwnerInput(value, stripUnknown)]));
166
+ const normalizers = schema[NORMALIZERS] ?? [];
167
+ if (schema.type === "string" && normalizers.length) {
168
+ delete projected.pattern;
169
+ delete projected.format;
170
+ delete projected.minLength;
171
+ delete projected.maxLength;
172
+ }
173
+ const transforms = schema[TRANSFORMERS] ?? [];
174
+ const inspectors = schema[INSPECTORS] ?? [];
175
+ const strip = stripUnknown && schema[STRIP] && schema.properties;
176
+ if (!(normalizers.length || transforms.length || inspectors.length || strip)) return projected;
177
+ return Type.Transform(projected).Decode((input) => {
178
+ let value = input;
179
+ if (strip && value !== null && typeof value === "object" && !Array.isArray(value)) value = Object.fromEntries(Object.entries(value).filter(([key]) => key in schema.properties));
180
+ const issues = [];
181
+ const steps = schema[STEPS] ?? [];
182
+ for (const [index, step] of steps.entries()) if (step.kind === "inspect") {
183
+ step.apply(value, { addIssue: (issue) => issues.push(issue) });
184
+ if (issues.length) throw new SchemaValidationError(issues);
185
+ } else {
186
+ value = step.apply(value);
187
+ if (step.kind === "normalize" && steps[index + 1]?.kind !== "normalize" && (schema.type === "string" || schema.anyOf?.every((branch) => branch.type === "string" || branch.type === "null")) && !Value.Check(schema, value)) throw new SchemaValidationError([{
188
+ code: "invalid_input",
189
+ message: "The normalized value does not match its schema.",
190
+ path: []
191
+ }]);
192
+ }
193
+ return value;
194
+ }).Encode((value) => value);
195
+ };
196
+ /**
197
+ * Whether a schema carries owner codecs that only `inputSchema()` compiles: a normalizer, transform,
198
+ * inspector or refinement, a `pipeSchema` source, or a `stripObject`. A plain decode ignores their
199
+ * markers, so such a schema used directly as an operation input would admit raw, unnormalized and
200
+ * unrefined values without a word. A compiled subtree (a TypeBox transform) is already honest.
201
+ */
202
+ function hasUncompiledCodecs(schema) {
203
+ const seen = /* @__PURE__ */ new Set();
204
+ /**
205
+ * Whether this schema, or any schema below it that no transform already compiled, carries a codec marker.
206
+ */
207
+ const visit = (node) => {
208
+ if (!node || typeof node !== "object" || seen.has(node) || TransformKind in node) return false;
209
+ seen.add(node);
210
+ const owner = node;
211
+ if ((owner[STEPS]?.length ?? 0) > 0 || owner[SOURCE] || owner[STRIP] === true) return true;
212
+ return [
213
+ ...Object.values(owner.properties ?? {}),
214
+ ...Object.values(owner.patternProperties ?? {}),
215
+ ...[owner.items].flat(),
216
+ ...owner.anyOf ?? [],
217
+ ...owner.allOf ?? [],
218
+ ...owner.oneOf ?? []
219
+ ].some(visit);
220
+ };
221
+ return visit(schema);
222
+ }
223
+ function inputSchema(schema, source) {
224
+ const wire = source && Kind in source ? source : void 0;
225
+ const stripUnknown = !wire && source && "stripUnknown" in source && source.stripUnknown === true;
226
+ const projected = projectOwnerInput(schema, Boolean(stripUnknown));
227
+ return Type.Transform(Type.Unsafe(wire ? projectOwnerInput(wire, false) : projected)).Decode((input) => {
228
+ if (!wire) return input;
229
+ const value = Value.Default(projected, input);
230
+ Value.Assert(projected, value);
231
+ return TransformDecode(projected, [], value);
232
+ }).Encode((value) => value);
233
+ }
234
+
235
+ //#endregion
236
+ //#region src/internal/decode-issues.ts
237
+ /**
238
+ * Turns a failed TypeBox decode into field issues whose paths start at the input's root, as the
239
+ * INVALID_INPUT failure carries them.
240
+ */
241
+ /** The segments of a JSON Pointer, unescaped. */
242
+ function segments(path) {
243
+ return path.split("/").slice(1).filter(Boolean).map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
244
+ }
245
+ /**
246
+ * The issues of a failed decode, at most `limit`, each with its path from the input's root, or null
247
+ * when the failure is not the input's (an owner codec's own fault is rethrown by the caller). TypeBox
248
+ * finds issues one at a time, so an input with millions of them costs no more than `limit`.
249
+ */
250
+ function decodeIssues(error, limit = Number.POSITIVE_INFINITY) {
251
+ let cause = error;
252
+ let path = [];
253
+ while (cause instanceof TransformDecodeError) {
254
+ path = segments(cause.path);
255
+ cause = cause.error;
256
+ }
257
+ if (cause instanceof SchemaValidationError) return cause.issues.slice(0, limit).map((issue) => ({
258
+ ...issue,
259
+ path: [...path, ...issue.path]
260
+ }));
261
+ if (cause instanceof AssertError) {
262
+ const issues = [];
263
+ for (const issue of cause.Errors()) {
264
+ issues.push({
265
+ code: "invalid_input",
266
+ message: issue.message,
267
+ path: segments(issue.path)
268
+ });
269
+ if (issues.length >= limit) break;
270
+ }
271
+ return issues;
272
+ }
273
+ if (cause instanceof TypeError) return [{
274
+ code: "invalid_input",
275
+ message: cause.message,
276
+ path: []
277
+ }];
278
+ return null;
279
+ }
280
+ /** RFC 6901 JSON Pointer of an issue path; the empty string names the whole input. */
281
+ function jsonPointer(path) {
282
+ return path.map((part) => `/${String(part).replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
283
+ }
284
+
285
+ //#endregion
286
+ //#region src/validation.ts
287
+ /**
288
+ * Schema validation: the check-only and the decoding validators, the guard that admits only bounded plain
289
+ * JSON, and the RFC format validators registered once with TypeBox.
290
+ */
291
+ for (const name of [
292
+ "date",
293
+ "time",
294
+ "date-time",
295
+ "email",
296
+ "uuid",
297
+ "uri"
298
+ ]) {
299
+ const format = fullFormats[name];
300
+ const validator = typeof format === "object" && !(format instanceof RegExp) ? format.validate : format;
301
+ FormatRegistry.Set(name, (value) => {
302
+ if (value.length > 8192) return false;
303
+ if (validator instanceof RegExp) return validator.test(value);
304
+ return typeof validator === "function" && validator(value) === true;
305
+ });
306
+ }
307
+ /**
308
+ * Checks a value against a schema without decoding it: the value when it matches, else an `INVALID_INPUT`
309
+ * failure without issues. Use `decodeInput` for input with defaults and codecs.
310
+ */
311
+ function parseInput(schema, input) {
312
+ if (Value.Check(schema, input)) return {
313
+ ok: true,
314
+ value: input
315
+ };
316
+ return {
317
+ ok: false,
318
+ error: {
319
+ code: "INVALID_INPUT",
320
+ message: "The input does not match its schema.",
321
+ retryable: false,
322
+ data: {}
323
+ }
324
+ };
325
+ }
326
+ /** Checks a value against a schema and returns it typed, or throws a TypeError that names no value. */
327
+ function parseSchema(schema, input) {
328
+ if (!Value.Check(schema, input)) throw new TypeError("Value does not match its schema");
329
+ return input;
330
+ }
331
+ /** TypeBox traversals operate on bounded JSON trees; native RPC must obey the same input boundary as HTTP. */
332
+ function boundedInput(value, depth = 0, parents = /* @__PURE__ */ new Set()) {
333
+ if (depth > 100) return false;
334
+ if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") return true;
335
+ if (typeof value === "number") return Number.isFinite(value);
336
+ if (typeof value !== "object" || parents.has(value)) return false;
337
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false;
338
+ parents.add(value);
339
+ const valid = Object.values(value).every((child) => boundedInput(child, depth + 1, parents));
340
+ parents.delete(value);
341
+ return valid;
342
+ }
343
+ /** Admit a real wire schema once, materialize declared defaults, and decode native TypeBox transforms.
344
+ * Output validation deliberately remains check-only: response data must already be canonical. */
345
+ function decodeSchema(schema, input) {
346
+ if (!boundedInput(input)) throw new TypeError("Input must be a bounded plain JSON tree.");
347
+ const value = Value.Default(schema, Value.Clone(input));
348
+ Value.Assert(schema, value);
349
+ return HasTransform(schema, []) ? TransformDecode(schema, [], value) : value;
350
+ }
351
+ /** The most field issues one refusal carries. */
352
+ const MAX_ISSUES = 10;
353
+ /** The longest path or message one issue carries. */
354
+ const MAX_ISSUE_TEXT = 256;
355
+ /**
356
+ * The transport maps schema codec failures to its declared INVALID_INPUT contract, with the first
357
+ * field issues. Schema messages name the expectation, not the value; owner refinements must too.
358
+ */
359
+ function decodeInput(schema, input) {
360
+ try {
361
+ return {
362
+ ok: true,
363
+ value: decodeSchema(schema, input)
364
+ };
365
+ } catch (error) {
366
+ return {
367
+ ok: false,
368
+ error: {
369
+ code: "INVALID_INPUT",
370
+ message: "The input does not match its schema.",
371
+ retryable: false,
372
+ data: { issues: (decodeIssues(error, MAX_ISSUES) ?? []).map((issue) => ({
373
+ path: jsonPointer(issue.path).slice(0, MAX_ISSUE_TEXT),
374
+ message: issue.message.slice(0, MAX_ISSUE_TEXT)
375
+ })) }
376
+ }
377
+ };
378
+ }
379
+ }
380
+
381
+ //#endregion
382
+ export { strictObject as _, decodeIssues as a, urlSchema as b, extendObject as c, inspectSchema as d, literalUnion as f, refineSchema as g, pipeSchema as h, parseSchema as i, hasUncompiledCodecs as l, normalizeSchema as m, decodeSchema as n, SchemaValidationError as o, looseObject as p, parseInput as r, defaultSchema as s, decodeInput as t, inputSchema as u, stripObject as v, transformSchema as y };
@@ -0,0 +1,131 @@
1
+ import { kn as Failure, r as Static, zt as OperationShape } from "../chunks/types-CGwAhnTE.js";
2
+ //#region src/client/client.d.ts
3
+ /** What every HTTP operation answers: its data on success, its failure otherwise, and the request id. */
4
+ export type Envelope<T> = {
5
+ success: true;
6
+ data: T;
7
+ error: null;
8
+ metadata: {
9
+ requestId: string;
10
+ };
11
+ } | {
12
+ success: false;
13
+ data: null;
14
+ error: Failure;
15
+ metadata: {
16
+ requestId: string;
17
+ };
18
+ };
19
+ /** The part of an application the client's types read: its operations. `typeof app` satisfies it. */
20
+ export type ClientManifest = {
21
+ /** The application's operations by name; each one public over HTTP becomes a client method of that name. */
22
+ operations: Record<string, OperationShape>;
23
+ };
24
+ /** Public HTTP operation identifiers derive from the service's native manifest. */
25
+ export type OperationName<M extends ClientManifest> = Extract<{ [K in keyof M['operations']]: M['operations'][K] extends {
26
+ http: object;
27
+ } ? M['operations'][K] extends {
28
+ visibility: 'internal';
29
+ } ? never : K : never; }[keyof M['operations']], string>;
30
+ /** Read effects include POST searches; transport method does not determine cache ownership. */
31
+ export type ReadOperationName<M extends ClientManifest> = { [K in OperationName<M>]: M['operations'][K] extends {
32
+ effect: 'read';
33
+ } ? K : never; }[OperationName<M>];
34
+ /** The complete declared input includes item path and mapped metadata-header fields. */
35
+ export type OperationInput<M extends ClientManifest, K extends OperationName<M>> = Static<M['operations'][K]['input']>;
36
+ /** JSON outputs retain their native schema type; validated attachments expose the Web Response API. */
37
+ export type OperationOutput<M extends ClientManifest, K extends OperationName<M>> = ClientOutput<M['operations'][K]>;
38
+ /** Whether a method answers the whole envelope or only its data. */
39
+ export type ResponseMode = 'envelope' | 'data';
40
+ /** What one method answers in a response mode. */
41
+ type ClientResponse<O extends OperationShape, Mode extends ResponseMode> = Mode extends 'data' ? ClientOutput<O> : Envelope<ClientOutput<O>>;
42
+ /**
43
+ * The typed client of an application: one method per public HTTP operation. A byte operation also takes its
44
+ * body in the call options.
45
+ */
46
+ export type AppClientContract<M extends ClientManifest, Mode extends ResponseMode = 'envelope'> = { [K in OperationName<M>]: M['operations'][K] extends {
47
+ http: {
48
+ body: 'bytes';
49
+ };
50
+ } ? (input: OperationInput<M, K>, options: BinaryCallOptions) => Promise<ClientResponse<M['operations'][K], Mode>> : (input: OperationInput<M, K>, options?: CallOptions) => Promise<ClientResponse<M['operations'][K], Mode>>; };
51
+ /** An operation's output as the client returns it: its declared type, or a Response for an attachment. */
52
+ type ClientOutput<Operation extends OperationShape> = Operation extends {
53
+ http: {
54
+ response: 'attachment';
55
+ };
56
+ } ? Response : Static<Operation['output']>;
57
+ /** Options of one call: a signal that cancels it. */
58
+ export interface CallOptions {
59
+ /** Cancels this call when it aborts, as do the client's `timeoutMs` deadline and its `signal` option. */
60
+ signal?: AbortSignal;
61
+ }
62
+ /** Options of one call to a byte operation: its body and the transfer's progress. */
63
+ export interface BinaryCallOptions extends CallOptions {
64
+ /**
65
+ * The bytes to upload; without a mapped `content-type` input field, a `Blob`'s own type is sent, else
66
+ * `application/octet-stream`.
67
+ */
68
+ body: Blob | Uint8Array<ArrayBuffer>;
69
+ /** Transfer lifecycle only: 0 when sending begins, 1 after a validated success response; not byte progress. */
70
+ onUploadProgress?: (share: 0 | 1) => void;
71
+ }
72
+ /** A validated native refusal; applications select finite, localized presentation without parsing responses. */
73
+ export interface ClientFailure {
74
+ /** Actual HTTP status, including a refusal whose protocol body could not be decoded. */
75
+ status: number;
76
+ /** Validated native failure, or the canonical internal failure for malformed refusal bodies. */
77
+ failure: Failure;
78
+ /** Technical UUID/edge-ray correlation; empty when the response provides no valid identifier. */
79
+ requestId: string;
80
+ }
81
+ /**
82
+ * How the client answers, authenticates, times out and bounds what it reads, and the hooks around each
83
+ * request.
84
+ */
85
+ export interface ClientOptions {
86
+ /** Data mode rejects native refusals; omitted mode preserves typed success/failure envelopes. */
87
+ response?: ResponseMode;
88
+ /** Captured once at operation entry, before discovery or token acquisition can await. */
89
+ signal?: () => AbortSignal;
90
+ /** Optional application presentation of an already validated refusal, used only in data mode. */
91
+ onFailure?: (refusal: ClientFailure) => Error;
92
+ /**
93
+ * The fetch implementation every request goes through, the global `fetch` by default; for tests or a
94
+ * Service Binding's `fetch`.
95
+ */
96
+ fetch?: typeof fetch;
97
+ /**
98
+ * The deadline of each call in milliseconds, discovery and token acquisition included; 30000 by default.
99
+ */
100
+ timeoutMs?: number;
101
+ /** Headers may be augmented; method, URL, body, bearer and declared metadata remain client-owned. */
102
+ beforeRequest?: (request: Request) => void | Promise<void>;
103
+ /** Receives the same request object, including admitted request headers for consistency cursors. */
104
+ afterResponse?: (response: Response, request: Request) => void | Promise<void>;
105
+ /**
106
+ * The Fetch credentials mode, `'omit'` by default. Its values are written out because the Workers and
107
+ * Node type libraries declare no `RequestCredentials`.
108
+ */
109
+ credentials?: 'omit' | 'same-origin' | 'include';
110
+ /** The Fetch cache mode, `'no-store'` by default; written out for the same reason (`RequestCache`). */
111
+ cache?: 'default' | 'no-store' | 'reload' | 'no-cache' | 'force-cache' | 'only-if-cached';
112
+ /** Raw attachments are bounded independently of small JSON metadata responses; defaults to 16 MiB. */
113
+ maxAttachmentBytes?: number;
114
+ /** Operation response byte limit, including chunked bodies; defaults to 1 MiB and cannot exceed 16 MiB. */
115
+ maxResponseBytes?: number;
116
+ }
117
+ /**
118
+ * A typed HTTP client for an application, from its type alone (`createClient<typeof app>(…)`): one
119
+ * method per public HTTP operation, named as the operation. On its first call it reads the routes
120
+ * from the service's live `/openapi.json` at `origin`, an HTTPS base URL that may carry a path.
121
+ * With `response: 'data'`, a method returns the data and throws on a refusal.
122
+ */
123
+ export declare function createClient<M extends ClientManifest>(origin: string, token: string | (() => Promise<string>), options: ClientOptions & {
124
+ response: 'data';
125
+ }): AppClientContract<M, 'data'>;
126
+ /** The same, answering each call with its success or failure envelope. */
127
+ export declare function createClient<M extends ClientManifest>(origin: string, token: string | (() => Promise<string>), options?: ClientOptions & {
128
+ response?: 'envelope';
129
+ }): AppClientContract<M>;
130
+ //#endregion
131
+ export {};