@arbol-ai/maximus 8.5.0 → 8.5.1

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.
@@ -0,0 +1,792 @@
1
+ import { L as wireInput } from "./schemas-_UJcx_uY.js";
2
+ import { a as operationPathParameters } from "./http-paths-D043DkJv.js";
3
+ import { n as routeGroup, t as pathParameterSchemas } from "./http-routes-B6tCsnxB.js";
4
+ import { _ as operationBodyLimit, b as operationScopes, f as STANDARD_CODES, h as mcpOpenWorld, l as BODY_CODES, m as isPublicOperation, n as TASK_GROUP, r as TASK_GROUP_DESCRIPTION, y as operationOutputLimit } from "./tasks-DYdY-dBI.js";
5
+ import { _ as schemaIds, f as usesCloudflareAccess, h as canonical, m as bundleSchemas, s as tokenEndpoints } from "./tokens-D4gRyyPu.js";
6
+ import { t as queryKind } from "./query-kind-CWKAXEME.js";
7
+ import { Type } from "typebox";
8
+
9
+ // src/internal/http-query.ts
10
+ /**
11
+ * The typed GET query codec: which input fields travel in the query string, and how each value is read as
12
+ * its kind.
13
+ */
14
+ /** An integer as a query value: no leading zeros and at most 16 digits, so it stays exact. */
15
+ const INTEGER = /^-?(?:0|[1-9]\d{0,15})$/;
16
+ /** A decimal number as a query value, with an optional exponent. */
17
+ const NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
18
+ /** A GET's query fields and the kind each one is read as: every input field outside the path. */
19
+ function queryKinds(op) {
20
+ const path = new Set(op.http ? operationPathParameters(op.http.path) : []);
21
+ const kinds = /* @__PURE__ */ new Map();
22
+ for (const [field, schema] of Object.entries(op.input.properties ?? {})) {
23
+ const kind = path.has(field) ? null : queryKind(schema);
24
+ if (kind) kinds.set(field, kind);
25
+ }
26
+ return kinds;
27
+ }
28
+ /**
29
+ * A GET's input from its query string, each declared field read once as its kind:
30
+ * `?limit=2&active=true&tags=a,b` is `{ limit: 2, active: true, tags: ['a', 'b'] }`. A list is one
31
+ * comma-separated value, never a repeated key. A field the input does not declare stays a string for the
32
+ * schema to judge. Null when a field repeats, is named `__proto__` or does not read as its kind.
33
+ */
34
+ function queryInput(kinds, params) {
35
+ const keys = [...params.keys()];
36
+ if (new Set(keys).size !== keys.length) return null;
37
+ const input = {};
38
+ for (const [key, text] of params) {
39
+ if (key === "__proto__") return null;
40
+ let value = text;
41
+ switch (kinds.get(key)) {
42
+ case "integer":
43
+ value = INTEGER.test(text) ? Number(text) : null;
44
+ break;
45
+ case "number":
46
+ value = NUMBER.test(text) && Number.isFinite(Number(text)) ? Number(text) : null;
47
+ break;
48
+ case "boolean":
49
+ value = text === "true" || text === "false" ? text === "true" : null;
50
+ break;
51
+ case "list": {
52
+ const items = text.split(",");
53
+ value = items.every(Boolean) ? items : null;
54
+ break;
55
+ }
56
+ }
57
+ if (value === null) return null;
58
+ input[key] = value;
59
+ }
60
+ return input;
61
+ }
62
+
63
+ // src/internal/openapi-components.ts
64
+ /** A reference to the component schema `name`. */
65
+ function schemaReference(name) {
66
+ return { $ref: `#/components/schemas/${name}` };
67
+ }
68
+ /** A camelCase name or an uppercase code in PascalCase: `createNote` is `CreateNote`, `NOTE_NOT_FOUND` `NoteNotFound`. */
69
+ function pascalCase(name) {
70
+ return (/^[A-Z0-9_]+$/.test(name) ? name.toLowerCase().split("_") : [name]).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
71
+ }
72
+ /** The reason phrase of each HTTP status a failure may answer, in PascalCase, as RFC 9110 names it. */
73
+ const REASONS = {
74
+ 400: "BadRequest",
75
+ 401: "Unauthorized",
76
+ 402: "PaymentRequired",
77
+ 403: "Forbidden",
78
+ 404: "NotFound",
79
+ 405: "MethodNotAllowed",
80
+ 406: "NotAcceptable",
81
+ 408: "RequestTimeout",
82
+ 409: "Conflict",
83
+ 410: "Gone",
84
+ 411: "LengthRequired",
85
+ 412: "PreconditionFailed",
86
+ 413: "ContentTooLarge",
87
+ 415: "UnsupportedMediaType",
88
+ 422: "UnprocessableContent",
89
+ 423: "Locked",
90
+ 424: "FailedDependency",
91
+ 425: "TooEarly",
92
+ 428: "PreconditionRequired",
93
+ 429: "TooManyRequests",
94
+ 451: "UnavailableForLegalReasons",
95
+ 500: "InternalServerError",
96
+ 501: "NotImplemented",
97
+ 502: "BadGateway",
98
+ 503: "ServiceUnavailable",
99
+ 504: "GatewayTimeout",
100
+ 507: "InsufficientStorage"
101
+ };
102
+ /** A status's reason phrase in PascalCase: 400 is `BadRequest`, and a status without one `Status499`. */
103
+ function statusReason(status) {
104
+ return REASONS[status] ?? `Status${status}`;
105
+ }
106
+ /** A failure code without the `_ERROR` its name would repeat: `INTERNAL_ERROR` is `INTERNAL`. */
107
+ function failureWords(code) {
108
+ return pascalCase(code.replace(/_ERROR$/, ""));
109
+ }
110
+ /** The component of one failure: `NOTE_NOT_FOUND` is `NoteNotFoundFailure`. */
111
+ function failureName(code) {
112
+ return `${failureWords(code)}Failure`;
113
+ }
114
+ /** The envelope of one failure, the answer's whole body: `NOTE_NOT_FOUND` is `NoteNotFoundError`. */
115
+ function failureEnvelopeName(code) {
116
+ return `${failureWords(code)}Error`;
117
+ }
118
+ /**
119
+ * The names a generator gives each operation's own types, which a component must not take: openapi-typescript
120
+ * and Hey API write `CreateNoteData`, `CreateNoteResponse` and `CreateNoteError`, and the OpenAPI Generator
121
+ * `CreateNoteRequest`.
122
+ */
123
+ const GENERATED_SUFFIXES = [
124
+ "Data",
125
+ "Error",
126
+ "Errors",
127
+ "Response",
128
+ "Responses",
129
+ "Request"
130
+ ];
131
+ /** The component names a generator writes for an operation's own types: `createNote`'s `CreateNoteResponse`. */
132
+ function generatedNames(operation) {
133
+ const name = pascalCase(operation);
134
+ return GENERATED_SUFFIXES.map((suffix) => `${name}${suffix}`);
135
+ }
136
+ /** The component schemas of a document, each name given to one schema only. */
137
+ var ComponentSchemas = class {
138
+ /** The schemas by name, in the order they were added. */
139
+ schemas = {};
140
+ /** Whether another schema than this one already has the name. */
141
+ holdsOther(name, schema) {
142
+ const existing = this.schemas[name];
143
+ return existing !== void 0 && canonical(existing) !== canonical(schema);
144
+ }
145
+ /**
146
+ * Names a schema and answers a reference to it. The same schema under a name it already has is the same
147
+ * component; another schema under a taken name throws, since a reference would then name two shapes.
148
+ */
149
+ add(name, schema) {
150
+ if (this.holdsOther(name, schema)) throw new TypeError(`Two different schemas claim the OpenAPI component ${name}.`);
151
+ this.schemas[name] = schema;
152
+ return schemaReference(name);
153
+ }
154
+ };
155
+ /** The JSON a field holds when the answer carries none: success has no error, a failure no data. */
156
+ const NONE = { const: null };
157
+ /** The metadata every answer carries, as the component `ResponseMetadata`. */
158
+ const RESPONSE_METADATA = {
159
+ type: "object",
160
+ description: "What every answer carries besides its data or error.",
161
+ additionalProperties: false,
162
+ required: ["requestId"],
163
+ properties: { requestId: {
164
+ type: "string",
165
+ description: "Request correlation identifier, also sent as X-Request-Id."
166
+ } }
167
+ };
168
+ /** The empty object, as the component `Empty`: the data of an answer, or of a failure, that carries none. */
169
+ const EMPTY_OBJECT = {
170
+ type: "object",
171
+ description: "No fields.",
172
+ additionalProperties: false,
173
+ properties: {}
174
+ };
175
+ /** The envelope of a successful answer: `success` is true, `data` the operation's output and `error` null. */
176
+ function successEnvelope(data) {
177
+ return {
178
+ type: "object",
179
+ description: "A successful answer.",
180
+ additionalProperties: false,
181
+ required: [
182
+ "success",
183
+ "data",
184
+ "error",
185
+ "metadata"
186
+ ],
187
+ properties: {
188
+ success: {
189
+ type: "boolean",
190
+ enum: [true]
191
+ },
192
+ data,
193
+ error: NONE,
194
+ metadata: schemaReference("ResponseMetadata")
195
+ }
196
+ };
197
+ }
198
+ /** The envelope of a failed answer: `success` is false, `data` null and `error` the failure. */
199
+ function failureEnvelope(error) {
200
+ return {
201
+ type: "object",
202
+ description: "A failed answer.",
203
+ additionalProperties: false,
204
+ required: [
205
+ "success",
206
+ "data",
207
+ "error",
208
+ "metadata"
209
+ ],
210
+ properties: {
211
+ success: {
212
+ type: "boolean",
213
+ enum: [false]
214
+ },
215
+ data: NONE,
216
+ error,
217
+ metadata: schemaReference("ResponseMetadata")
218
+ }
219
+ };
220
+ }
221
+ /**
222
+ * One failure as the component its code names: its code a one-value enum, which every generator reads as
223
+ * the literal, its retryability fixed and its data the schema its definition declares. Its message is a
224
+ * plain string: clients branch on the code, never on the text.
225
+ */
226
+ function failureSchema(definition, data) {
227
+ return {
228
+ type: "object",
229
+ description: definition.message,
230
+ additionalProperties: false,
231
+ required: [
232
+ "code",
233
+ "message",
234
+ "retryable",
235
+ "data"
236
+ ],
237
+ properties: {
238
+ code: {
239
+ type: "string",
240
+ enum: [definition.code],
241
+ description: "The failure code, stable across releases."
242
+ },
243
+ message: {
244
+ type: "string",
245
+ description: "What went wrong, for people; it never contains input values."
246
+ },
247
+ retryable: {
248
+ type: "boolean",
249
+ enum: [definition.retryable ?? false],
250
+ description: "Whether repeating the same request may succeed."
251
+ },
252
+ data
253
+ }
254
+ };
255
+ }
256
+ /** Several failures as one component, told apart by their `code`, as generators that read a discriminator expect. */
257
+ function failureUnion(codes) {
258
+ return {
259
+ oneOf: codes.map((code) => schemaReference(failureName(code))),
260
+ discriminator: {
261
+ propertyName: "code",
262
+ mapping: Object.fromEntries(codes.map((code) => [code, schemaReference(failureName(code)).$ref]))
263
+ }
264
+ };
265
+ }
266
+
267
+ // src/openapi.ts
268
+ /**
269
+ * An application's OpenAPI 3.1 document, as its origin serves it and as SDK generators read it: one tag per
270
+ * group of routes, and every request body, success envelope and failure a named component, so a generated
271
+ * client reads `createNote(body: CreateNoteBody): NoteResponse`. The `x-*` extensions carry what OpenAPI
272
+ * cannot say: scopes, effects, limits, MCP tools and native RPC.
273
+ */
274
+ /** The standard failures only routing answers, before a request reaches any operation's route. */
275
+ const ROUTING_CODES = /* @__PURE__ */ new Set(["NOT_FOUND", "HTTP_METHOD_NOT_ALLOWED"]);
276
+ /** The headers every answer, and a failure that asks for a wait, carry, as the document's components. */
277
+ const HEADERS = {
278
+ RequestId: {
279
+ description: "Request correlation identifier.",
280
+ schema: { type: "string" }
281
+ },
282
+ RetryAfter: {
283
+ description: "Seconds before another attempt.",
284
+ schema: {
285
+ type: "integer",
286
+ minimum: 0
287
+ }
288
+ }
289
+ };
290
+ /** A reference to one of `HEADERS`. */
291
+ function headerReference(name) {
292
+ return { $ref: `#/components/headers/${name}` };
293
+ }
294
+ /** Whether an object schema holds no field at all, so that `{}` is its one value. */
295
+ function isEmptyObject(schema) {
296
+ return schema.type === "object" && Object.keys(schema.properties ?? {}).length === 0 && schema.patternProperties === void 0 && schema.additionalProperties === false;
297
+ }
298
+ /**
299
+ * A request body without the fields its path carries, in each member of a union. An object that loses
300
+ * fields is no longer the schema its `$id` names, so it loses the name, and its property counts lose the
301
+ * path's fields.
302
+ */
303
+ function bodyWithoutPathParameters(input, names) {
304
+ if (input.type !== "object") {
305
+ const { $id: _id, ...union } = input;
306
+ return {
307
+ ...union,
308
+ anyOf: (input.anyOf ?? []).map((schema) => bodyWithoutPathParameters(schema, names))
309
+ };
310
+ }
311
+ const carried = Object.keys(input.properties ?? {}).filter((name) => names.has(name)).length;
312
+ if (!carried) return input;
313
+ const { $id: _id, minProperties, maxProperties, ...object } = input;
314
+ return {
315
+ ...object,
316
+ properties: Object.fromEntries(Object.entries(input.properties ?? {}).filter(([name]) => !names.has(name))),
317
+ required: (input.required ?? []).filter((name) => !names.has(name)),
318
+ ...typeof minProperties === "number" && minProperties > carried ? { minProperties: minProperties - carried } : {},
319
+ ...typeof maxProperties === "number" ? { maxProperties: maxProperties - carried } : {}
320
+ };
321
+ }
322
+ /**
323
+ * The document the origin serves at `/openapi.json`: every public operation that declares an HTTP route,
324
+ * never an internal one, under one tag per group. Each request body, success envelope and failure is a named
325
+ * component, which a generated client names its types after; each operation also carries its scopes,
326
+ * effect, limits in force, MCP tool hints and native RPC as `x-*` extensions.
327
+ *
328
+ * Every schema reference in it is a local `#/components/schemas/<name>` pointer: the `$id`-named
329
+ * schemas of its paths and components (TypeBox Cyclic/Ref) become components, as `bundleSchemas`
330
+ * describes. A schema `$id` that takes the name of a component the document writes itself, and a component
331
+ * named as a generator names an operation's own types, such as `CreateNoteResponse`, throw a TypeError.
332
+ */
333
+ function createOpenApi(manifest, options) {
334
+ const document = openApiDocument(manifest, "http");
335
+ if (options?.operationExtensions) {
336
+ const paths = document.paths;
337
+ for (const methods of Object.values(paths)) for (const declared of Object.values(methods)) {
338
+ const name = String(declared.operationId);
339
+ const operation = manifest.operations[name];
340
+ if (!operation) throw new TypeError("The document names an undeclared operation.");
341
+ const extensions = options.operationExtensions(name, operation);
342
+ if (Object.keys(extensions).some((key) => !key.startsWith("x-"))) throw new TypeError("OpenAPI extensions must use x- names.");
343
+ Object.assign(declared, extensions);
344
+ }
345
+ }
346
+ return bundledDocument(document, manifest);
347
+ }
348
+ /**
349
+ * The document of the operations an application serves over native RPC, which another service binds to:
350
+ * each operation that declares `rpc`, internal ones and tools included, as `POST /rpc/<name>` whose body is
351
+ * the operation's whole input, with its answer and failures named as in the HTTP document. No HTTP route
352
+ * answers these paths: each names a method of the Worker's `Service` entrypoint, which a Service Binding
353
+ * calls with the caller's principal. `maximus openapi` writes it to `rpc.openapi.json`, and a caller's
354
+ * `services` option types its binding from it.
355
+ */
356
+ function createRpcOpenApi(manifest) {
357
+ return bundledDocument(openApiDocument(manifest, "rpc"), manifest);
358
+ }
359
+ /**
360
+ * A document with its `$id`-named schemas bundled into components, every component in name order, after the
361
+ * names it publishes are checked.
362
+ */
363
+ function bundledDocument(document, manifest) {
364
+ const own = Object.entries(document.components.schemas);
365
+ const sources = [document.paths, ...own.map(([, schema]) => schema)];
366
+ checkComponentNames(own.map(([name]) => name), schemaIds(sources), Object.keys(manifest.operations));
367
+ const bundled = bundleSchemas(sources, document.components.schemas);
368
+ const [paths, ...schemas] = bundled.values;
369
+ const named = {
370
+ ...Object.fromEntries(own.map(([name], index) => [name, schemas[index]])),
371
+ ...bundled.components
372
+ };
373
+ return {
374
+ ...document,
375
+ paths,
376
+ components: {
377
+ ...document.components,
378
+ schemas: Object.fromEntries(Object.entries(named).toSorted(([a], [b]) => a < b ? -1 : Number(a > b)))
379
+ }
380
+ };
381
+ }
382
+ /**
383
+ * Refuses the names a document cannot publish: a schema `$id` that takes the name of a component the document
384
+ * writes itself, which bundling would otherwise rename, and a component a generator would name an operation's
385
+ * own types after (`CreateNoteResponse` for `createNote`).
386
+ */
387
+ function checkComponentNames(own, ids, operations) {
388
+ const taken = new Set(own);
389
+ for (const id of ids) if (taken.has(id)) throw new TypeError(`The schema $id "${id}" is the name of a component the OpenAPI document writes for its bodies, answers or failures; rename the schema.`);
390
+ const generated = new Map(operations.flatMap((operation) => generatedNames(operation).map((name) => [name, operation])));
391
+ for (const name of [...own, ...ids]) {
392
+ const operation = generated.get(name);
393
+ if (operation) throw new TypeError(`The OpenAPI component ${name} takes the name a generated client gives operation "${operation}"'s own types; rename the schema or the operation.`);
394
+ }
395
+ }
396
+ /**
397
+ * The operations a document lists: for the HTTP document, each public operation that declares a route, at that
398
+ * route; for the RPC document, each operation that declares `rpc`, at `POST /rpc/<name>`. Each keeps the group
399
+ * its route gives it.
400
+ */
401
+ function documentedOperations(manifest, kind) {
402
+ return Object.entries(manifest.operations).flatMap(([name, op]) => {
403
+ const group = op.group ?? (op.http ? routeGroup(op.http.path) : void 0) ?? manifest.title;
404
+ if (kind === "rpc") return op.rpc ? [{
405
+ name,
406
+ op,
407
+ http: {
408
+ method: "POST",
409
+ path: `/rpc/${name}`
410
+ },
411
+ group
412
+ }] : [];
413
+ return op.http && isPublicOperation(op) ? [{
414
+ name,
415
+ op,
416
+ http: op.http,
417
+ group
418
+ }] : [];
419
+ });
420
+ }
421
+ /**
422
+ * Refuses a description of a group no document lists: each name `groups` describes must be the group of a
423
+ * public route or of an operation served over native RPC.
424
+ */
425
+ function checkDescribedGroups(manifest) {
426
+ const described = Object.keys(manifest.groups ?? {});
427
+ if (!described.length) return;
428
+ const listed = new Set([...documentedOperations(manifest, "http"), ...documentedOperations(manifest, "rpc")].map(({ group }) => group));
429
+ for (const group of described) if (!listed.has(group)) throw new TypeError(`groups describes "${group}", which no public route or RPC method has as its group; the groups are ${[...listed].join(", ") || "none"}.`);
430
+ }
431
+ /** What an RPC document says about itself, in place of servers its paths do not have. */
432
+ function rpcDescription(title) {
433
+ return `The operations ${title} serves over native RPC, to the Workers its rpc.callers name, through a Service Binding to its Service entrypoint. No HTTP route answers these paths: each names a method, called with the caller's principal and the operation's whole input.`;
434
+ }
435
+ /** The document `createOpenApi` or `createRpcOpenApi` builds, before its `$id`-named schemas are bundled. */
436
+ function openApiDocument(manifest, kind) {
437
+ const entries = documentedOperations(manifest, kind);
438
+ const rpc = kind === "rpc";
439
+ const scopes = Object.fromEntries(entries.flatMap(({ op }) => [...operationScopes(op), ...op.conditionalScopes ?? []].map((scope) => [scope, scopeDescription(scope)])));
440
+ const components = new ComponentSchemas();
441
+ if (entries.length) components.add("ResponseMetadata", RESPONSE_METADATA);
442
+ const headers = new Set(entries.length ? ["RequestId"] : []);
443
+ const groups = [];
444
+ const paths = {};
445
+ for (const { name, op, http, group } of entries) {
446
+ if (!groups.includes(group)) groups.push(group);
447
+ const request = rpc ? rpcRequest(name, op, components) : requestContract(name, op, http, components);
448
+ const failures = failureResponses(name, op, !rpc && "requestBody" in request, manifest.errors.definitions, components);
449
+ if (Object.values(failures).some((response) => "Retry-After" in response.headers)) headers.add("RetryAfter");
450
+ (paths[http.path] ??= {})[http.method.toLowerCase()] = {
451
+ operationId: name,
452
+ summary: op.title,
453
+ ...op.description ? { description: op.description } : {},
454
+ tags: [group],
455
+ ...rpc ? rpcExtensions(manifest, op) : httpExtensions(manifest, op, http),
456
+ ...request,
457
+ responses: {
458
+ [http.successStatus ?? 200]: successResponse(name, op, http, components),
459
+ ...failures
460
+ }
461
+ };
462
+ }
463
+ checkDescribedGroups(manifest);
464
+ return JSON.parse(JSON.stringify({
465
+ openapi: "3.1.0",
466
+ info: {
467
+ title: manifest.title,
468
+ version: manifest.version,
469
+ ...rpc ? { description: rpcDescription(manifest.title) } : {},
470
+ ...!rpc && manifest.description ? { description: manifest.description } : {}
471
+ },
472
+ ...rpc ? {} : { servers: [{ url: manifest.origin }] },
473
+ tags: groups.map((group) => {
474
+ const description = manifest.groups?.[group] ?? (group === "Operation tasks" ? "The tasks of operations that answer before they finish: read one you started, or cancel one that has not started running." : void 0);
475
+ return description ? {
476
+ name: group,
477
+ description
478
+ } : { name: group };
479
+ }),
480
+ paths,
481
+ components: {
482
+ schemas: components.schemas,
483
+ ...headers.size ? { headers: Object.fromEntries([...headers].map((name) => [name, HEADERS[name]])) } : {},
484
+ ...rpc || !entries.length ? {} : { securitySchemes: securitySchemes(manifest.tokens, scopes) }
485
+ }
486
+ }));
487
+ }
488
+ /**
489
+ * What an HTTP operation adds beside OpenAPI's own fields: the requirements that admit it, its scopes,
490
+ * effect, MCP tool, native RPC and limits, and how its body and answer travel.
491
+ */
492
+ function httpExtensions(manifest, op, http) {
493
+ return {
494
+ security: operationSecurity(op, manifest.tokens),
495
+ "x-required-scopes": [...operationScopes(op)],
496
+ ...operationScopes(op).length > 1 ? { "x-scope-match": op.scopeMatch ?? "any" } : {},
497
+ ...op.conditionalScopes ? { "x-conditional-scopes": op.conditionalScopes } : {},
498
+ "x-effect": op.effect,
499
+ ...op.mcp ? {
500
+ "x-mcp-tool": op.mcp.name,
501
+ "x-mcp-idempotent": op.mcp.idempotent,
502
+ "x-mcp-open-world": mcpOpenWorld(op.mcp)
503
+ } : {},
504
+ "x-native-rpc": Boolean(op.rpc),
505
+ "x-max-body-bytes": operationBodyLimit(manifest, op),
506
+ "x-max-output-bytes": operationOutputLimit(manifest, op),
507
+ ...http.body ? {
508
+ "x-body": http.body,
509
+ "x-input-headers": http.headers ?? {}
510
+ } : {},
511
+ ...http.response ? { "x-response": http.response } : {}
512
+ };
513
+ }
514
+ /**
515
+ * What a native RPC operation adds beside OpenAPI's own fields: its effect, the callers that may call it,
516
+ * and the output limit in force. A Service Binding names its caller, so it has no security requirement.
517
+ */
518
+ function rpcExtensions(manifest, op) {
519
+ return {
520
+ "x-effect": op.effect,
521
+ "x-native-rpc": true,
522
+ "x-rpc-callers": op.rpc === true ? [...manifest.rpc.callers] : [...op.rpc?.callers ?? []],
523
+ "x-max-output-bytes": operationOutputLimit(manifest, op)
524
+ };
525
+ }
526
+ /** A scope as people read it: `notes:notes:read` reads notes, `notes:task-lists:write` writes task lists. */
527
+ function scopeDescription(scope) {
528
+ const [namespace, resource, action, ...deeper] = scope.split(":");
529
+ if (namespace === void 0 || resource === void 0 || deeper.length) return scope;
530
+ const words = resource.replaceAll("-", " ");
531
+ if (action === "read") return `Read ${words}.`;
532
+ if (action === "write") return `Create, change and delete ${words}.`;
533
+ return scope;
534
+ }
535
+ /** Whether a body schema requires a field, so no empty body is valid: a union does when each member does. */
536
+ function requiresField(schema) {
537
+ const node = schema;
538
+ return node.anyOf ? node.anyOf.every(requiresField) : (node.required ?? []).length > 0;
539
+ }
540
+ /**
541
+ * A parameter, described on the parameter itself, where generators read it: by its schema's description, or
542
+ * else by its name in words (`noteId` is `The note id.`).
543
+ */
544
+ function parameter(name, location, required, schema, style = {}) {
545
+ const words = name.replaceAll(/([a-z0-9])([A-Z])/g, "$1 $2").replaceAll(/[_-]+/g, " ").toLowerCase();
546
+ return {
547
+ name,
548
+ in: location,
549
+ required,
550
+ description: typeof schema.description === "string" ? schema.description : `The ${words}.`,
551
+ ...style,
552
+ schema
553
+ };
554
+ }
555
+ /**
556
+ * Where an operation's input travels: its path parameters, then a byte body's query and header
557
+ * metadata, a GET's query, or a JSON body without the fields the path carries. A DELETE whose input the
558
+ * path carries whole sends no body.
559
+ */
560
+ function requestContract(name, op, http, components) {
561
+ const input = wireInput(op.input);
562
+ const parameterNames = operationPathParameters(http.path);
563
+ const pathNames = new Set(parameterNames);
564
+ const pathParameters = parameterNames.map((pathName) => {
565
+ const schemas = pathParameterSchemas(input, pathName);
566
+ return parameter(pathName, "path", true, schemas.length === 1 && schemas[0] ? schemas[0] : Type.Union(schemas));
567
+ });
568
+ const properties = input.properties ?? {};
569
+ const required = input.required ?? [];
570
+ const fields = Object.entries(properties).filter(([field]) => !pathNames.has(field));
571
+ if (http.body === "bytes") return {
572
+ parameters: [...pathParameters, ...fields.map(([field, schema]) => {
573
+ const header = http.headers && Object.hasOwn(http.headers, field) ? http.headers[field] : void 0;
574
+ return {
575
+ ...parameter(header ?? field, header ? "header" : "query", required.includes(field), schema),
576
+ "x-input-field": field
577
+ };
578
+ })],
579
+ requestBody: {
580
+ required: true,
581
+ content: { "application/octet-stream": { schema: {
582
+ type: "string",
583
+ format: "binary"
584
+ } } }
585
+ }
586
+ };
587
+ if (http.method === "GET") {
588
+ const kinds = queryKinds(op);
589
+ return { parameters: [...pathParameters, ...fields.map(([field, schema]) => parameter(field, "query", required.includes(field), schema, kinds.get(field) === "list" ? {
590
+ style: "form",
591
+ explode: false
592
+ } : {}))] };
593
+ }
594
+ const body = pathNames.size ? bodyWithoutPathParameters(input, pathNames) : input;
595
+ const located = pathParameters.length ? { parameters: pathParameters } : {};
596
+ if (http.method === "DELETE" && isEmptyObject(body)) return located;
597
+ return {
598
+ ...located,
599
+ requestBody: {
600
+ required: http.method !== "DELETE" || requiresField(body),
601
+ content: { "application/json": { schema: bodySchema(name, body, components) } }
602
+ }
603
+ };
604
+ }
605
+ /**
606
+ * The schema of a JSON request body: `Empty` for one without fields, which still travels as `{}`; the
607
+ * input's own when it is named and the path carries none of it; else the component `<Operation>Body`, or
608
+ * `<Operation>Input` for a native RPC method's whole input.
609
+ */
610
+ function bodySchema(name, body, components, suffix = "Body") {
611
+ if (isEmptyObject(body)) return components.add("Empty", EMPTY_OBJECT);
612
+ if (typeof body.$id === "string") return body;
613
+ return components.add(`${pascalCase(name)}${suffix}`, body);
614
+ }
615
+ /** A native RPC method's request: its whole input, as callers send it, which the method takes as one object. */
616
+ function rpcRequest(name, op, components) {
617
+ return { requestBody: {
618
+ required: true,
619
+ content: { "application/json": { schema: bodySchema(name, wireInput(op.input), components, "Input") } }
620
+ } };
621
+ }
622
+ /** The success response: the JSON envelope, or a validated attachment's bytes and headers. */
623
+ function successResponse(name, op, http, components) {
624
+ const headers = { "X-Request-Id": headerReference("RequestId") };
625
+ if (http.response !== "attachment") return {
626
+ description: "Successful operation.",
627
+ headers,
628
+ content: { "application/json": { schema: successSchema(name, op.output, components) } }
629
+ };
630
+ return {
631
+ description: "Successful operation.",
632
+ content: { "application/octet-stream": { schema: {
633
+ type: "string",
634
+ format: "binary"
635
+ } } },
636
+ headers: {
637
+ ...headers,
638
+ "Content-Type": {
639
+ schema: { type: "string" },
640
+ description: "Validated attachment media type."
641
+ },
642
+ "Content-Length": {
643
+ schema: {
644
+ type: "integer",
645
+ minimum: 0
646
+ },
647
+ description: "Exact attachment byte length."
648
+ },
649
+ "Content-Disposition": {
650
+ schema: { type: "string" },
651
+ description: "Attachment filename in ASCII and RFC 5987 UTF-8 forms."
652
+ }
653
+ }
654
+ };
655
+ }
656
+ /**
657
+ * The component of a successful answer: named after its output's `$id` (`NoteResponse`, which every
658
+ * operation that answers a note shares), `EmptyResponse` for an output without fields, and otherwise after
659
+ * the operation, with its output as `<Operation>Result`.
660
+ */
661
+ function successSchema(name, output, components) {
662
+ if (isEmptyObject(output)) return components.add("EmptyResponse", successEnvelope(components.add("Empty", EMPTY_OBJECT)));
663
+ const operation = pascalCase(name);
664
+ if (typeof output.$id === "string") {
665
+ const envelope = successEnvelope(output);
666
+ const named = `${output.$id}Response`;
667
+ return components.add(components.holdsOther(named, envelope) ? `${operation}ResultResponse` : named, envelope);
668
+ }
669
+ return components.add(`${operation}ResultResponse`, successEnvelope(components.add(`${operation}Result`, output)));
670
+ }
671
+ /**
672
+ * The failures an operation documents, one response per status, in catalog order: the standard failures
673
+ * its route can meet, never routing's (an unknown path or method) and, when it sends no body, never a
674
+ * body's; then the domain failures it declares, or every one when it declares none.
675
+ */
676
+ function failureResponses(name, op, sendsBody, definitions, components) {
677
+ const statuses = /* @__PURE__ */ new Map();
678
+ for (const definition of Object.values(definitions)) if (documentsFailure(op, sendsBody, definition.code)) statuses.set(definition.status, [...statuses.get(definition.status) ?? [], definition]);
679
+ return Object.fromEntries([...statuses].map(([status, failures]) => [status, failureResponse(name, status, failures, components)]));
680
+ }
681
+ /** Whether an operation's document lists a failure, as `failureResponses` describes. */
682
+ function documentsFailure(op, sendsBody, code) {
683
+ if (ROUTING_CODES.has(code)) return false;
684
+ if (BODY_CODES.has(code)) return sendsBody;
685
+ return STANDARD_CODES.has(code) || !op.failures || op.failures.includes(code);
686
+ }
687
+ /**
688
+ * One status an operation documents: each failure as its component, and the envelope of the answer, named
689
+ * after its code when it is the status's only one (`NoteNotFoundError`), else after the operation and the
690
+ * status (`ListNotesBadRequestError`), whose failures a discriminator on `code` tells apart.
691
+ */
692
+ function failureResponse(name, status, failures, components) {
693
+ for (const failure of failures) addFailure(failure, components);
694
+ const codes = failures.map(({ code }) => code);
695
+ const [only] = codes;
696
+ const statusName = `${pascalCase(name)}${statusReason(status)}`;
697
+ const envelope = codes.length === 1 && only !== void 0 ? components.add(failureEnvelopeName(only), failureEnvelope(schemaReference(failureName(only)))) : components.add(`${statusName}Error`, failureEnvelope(components.add(`${statusName}Failure`, failureUnion(codes))));
698
+ const lines = failures.map((failure) => `\`${failure.code}\`: ${failure.message}`);
699
+ return {
700
+ description: lines.length === 1 && lines[0] !== void 0 ? lines[0] : lines.map((line) => `- ${line}`).join("\n"),
701
+ headers: {
702
+ "X-Request-Id": headerReference("RequestId"),
703
+ ...status === 429 || failures.some((failure) => failure.retryAfter) ? { "Retry-After": headerReference("RetryAfter") } : {}
704
+ },
705
+ "x-failure-codes": codes,
706
+ content: { "application/json": { schema: envelope } }
707
+ };
708
+ }
709
+ /** A failure as its component, `<Code>Failure`, with its data: the schema its definition declares, else `Empty`. */
710
+ function addFailure(definition, components) {
711
+ const dataSchema = definition.dataSchema;
712
+ let data;
713
+ if (dataSchema === void 0 || isEmptyObject(dataSchema)) data = components.add("Empty", EMPTY_OBJECT);
714
+ else if (typeof dataSchema.$id === "string") data = dataSchema;
715
+ else data = components.add(`${failureName(definition.code)}Data`, dataSchema);
716
+ components.add(failureName(definition.code), failureSchema(definition, data));
717
+ }
718
+ /**
719
+ * The security requirements that admit an operation, any one of which is enough: its scopes as
720
+ * OAuth requirements (all of them in one requirement when it needs all), or the application's own
721
+ * bearer tokens. With both schemes, users present OAuth tokens and services the application's own.
722
+ * Behind Cloudflare Access, a client presents a service token's two headers together.
723
+ */
724
+ function operationSecurity(op, tokens) {
725
+ if (usesCloudflareAccess(tokens)) return [{
726
+ accessClientId: [],
727
+ accessClientSecret: []
728
+ }];
729
+ let security;
730
+ if (tokens.scheme?.type === "bearer") security = [{ bearer: [] }];
731
+ else if (op.scopeMatch === "all") security = [{ oauth2: [...operationScopes(op)] }];
732
+ else security = operationScopes(op).map((scope) => ({ oauth2: [scope] }));
733
+ if (tokens.scheme?.type === "oauth+bearer") {
734
+ const actors = op.actorKinds ?? [];
735
+ if (!actors.includes("user")) security = [];
736
+ if (actors.includes("service")) security.push({ bearer: [] });
737
+ }
738
+ return security;
739
+ }
740
+ /**
741
+ * How callers obtain a token: the OAuth 2.0 flows of the issuer (authorization code, and client
742
+ * credentials unless services use the application's own tokens), the application's own bearer
743
+ * tokens, or both. Behind Cloudflare Access, the headers of an Access service token, which Access
744
+ * exchanges at the edge for the application token the API verifies; people sign in to Access in a
745
+ * browser, which no scheme describes.
746
+ */
747
+ function securitySchemes(tokens, scopes) {
748
+ if (usesCloudflareAccess(tokens)) return {
749
+ accessClientId: {
750
+ type: "apiKey",
751
+ in: "header",
752
+ name: "CF-Access-Client-Id",
753
+ description: "The Client ID of a Cloudflare Access service token, sent with its Client Secret."
754
+ },
755
+ accessClientSecret: {
756
+ type: "apiKey",
757
+ in: "header",
758
+ name: "CF-Access-Client-Secret",
759
+ description: "The Client Secret of the Cloudflare Access service token whose Client ID is sent."
760
+ }
761
+ };
762
+ const { scheme } = tokens;
763
+ if (scheme?.type === "bearer") return { bearer: {
764
+ type: "http",
765
+ scheme: "bearer",
766
+ description: scheme.description
767
+ } };
768
+ const { authorization, token: tokenUrl } = tokenEndpoints(tokens);
769
+ return {
770
+ oauth2: {
771
+ type: "oauth2",
772
+ flows: {
773
+ authorizationCode: {
774
+ authorizationUrl: authorization,
775
+ tokenUrl,
776
+ scopes
777
+ },
778
+ ...scheme?.type === "oauth+bearer" ? {} : { clientCredentials: {
779
+ tokenUrl,
780
+ scopes
781
+ } }
782
+ }
783
+ },
784
+ ...scheme?.type === "oauth+bearer" ? { bearer: {
785
+ type: "http",
786
+ scheme: "bearer",
787
+ description: scheme.description
788
+ } } : {}
789
+ };
790
+ }
791
+
792
+ export { queryKinds as i, createRpcOpenApi as n, queryInput as r, createOpenApi as t };