apps 0.0.1-beta.0 → 0.0.1-beta.10

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 (141) hide show
  1. package/README.md +145 -30
  2. package/framework-reference.json +1 -1
  3. package/js/browser-XIPJGLH2.js +65 -0
  4. package/js/{chunk-36DNRFZQ.js → chunk-27F7W2LG.js} +1 -1
  5. package/js/{chunk-VFUZI3NY.js → chunk-57RKNWL2.js} +4 -4
  6. package/js/{chunk-BPEFS4YF.js → chunk-5T57N25Q.js} +122 -18
  7. package/js/chunk-72JNVHPK.js +41 -0
  8. package/js/{chunk-2OTCEKL2.js → chunk-CDL5PM2Q.js} +2643 -1646
  9. package/js/{chunk-KWTCHVLT.js → chunk-CRDWFA74.js} +69 -54
  10. package/js/chunk-CZ7CSFO4.js +39 -0
  11. package/js/{chunk-WIDTG42X.js → chunk-EPT3ZP52.js} +79 -26
  12. package/js/chunk-FL2QR3XW.js +507 -0
  13. package/js/{chunk-3ANFZFCV.js → chunk-IJX4CYZO.js} +15 -18
  14. package/js/chunk-IPI4MFSN.js +78 -0
  15. package/js/chunk-JU7VHODU.js +104 -0
  16. package/js/chunk-KUMBKVJD.js +39 -0
  17. package/js/{chunk-YDR4CPJA.js → chunk-M3B3DE4K.js} +8 -8
  18. package/js/chunk-MKWZPDR6.js +63 -0
  19. package/js/{chunk-7JXHF5IF.js → chunk-N7YDVXYJ.js} +49 -1
  20. package/js/chunk-NKLWZJLE.js +172 -0
  21. package/js/{chunk-OWD2YICM.js → chunk-ODEIDRGW.js} +116 -88
  22. package/js/{chunk-D6BKYP2L.js → chunk-PJJ24GU7.js} +4 -4
  23. package/js/{chunk-EP6AEUZO.js → chunk-PZB6T6KU.js} +1 -1
  24. package/js/chunk-R3EV5FTO.js +97 -0
  25. package/js/chunk-RFVIONFX.js +189 -0
  26. package/js/{chunk-W7Q5EOTS.js → chunk-UK573G7W.js} +32 -32
  27. package/js/chunk-UVL56Z6E.js +6641 -0
  28. package/js/{chunk-Q2FD5IBM.js → chunk-V5KNQVCT.js} +505 -124
  29. package/js/{chunk-SBKHUC5L.js → chunk-VFZKSM3T.js} +5 -25
  30. package/js/{chunk-HP7E42X6.js → chunk-WLE7WX2U.js} +1158 -232
  31. package/js/{chunk-X3YBZCJW.js → chunk-YXQHV65J.js} +58 -62
  32. package/js/chunk-Z5M2LQOZ.js +209 -0
  33. package/js/{chunk-R6JMJSVT.js → chunk-ZQINWV4W.js} +60 -20
  34. package/js/client.js +11 -27
  35. package/js/contracts.js +138 -27
  36. package/js/effect.js +20 -15
  37. package/js/es-APDZKREY.js +40968 -0
  38. package/js/graphql.js +220 -123
  39. package/js/host.js +75 -19
  40. package/js/index.js +261 -117
  41. package/js/mcp/effect.js +24 -17
  42. package/js/mcp/stdio.js +26 -21
  43. package/js/mcp.js +127 -26
  44. package/js/openapi.js +3048 -150
  45. package/js/operations/approval.js +1 -1
  46. package/js/react.js +4 -4
  47. package/js/skills/effect.js +11 -0
  48. package/js/skills.js +893 -0
  49. package/js/storage/facet.js +7 -7
  50. package/js/ui/auth/contracts.js +9 -10
  51. package/js/ui/auth.js +17 -15
  52. package/js/ui/contracts.js +5 -5
  53. package/js/ui/serving.js +14 -13
  54. package/package.json +9 -1
  55. package/runtime.json +1 -1
  56. package/types/app-cache/src/contracts/cache.d.ts +119 -0
  57. package/types/app-cache/src/index.d.ts +93 -0
  58. package/types/app-data/src/contracts/database.d.ts +33 -6
  59. package/types/app-data/src/implementation/schema.d.ts +2 -17
  60. package/types/apps/src/contracts/api-response-error.d.ts +43 -0
  61. package/types/apps/src/contracts/app.d.ts +16 -4
  62. package/types/apps/src/contracts/cache.d.ts +44 -0
  63. package/types/apps/src/contracts/dynamic-skills.d.ts +10 -0
  64. package/types/apps/src/contracts/failure.d.ts +25 -0
  65. package/types/apps/src/contracts/graphql.d.ts +18 -1
  66. package/types/apps/src/contracts/host.d.ts +76 -528
  67. package/types/apps/src/contracts/mcp.d.ts +19 -1
  68. package/types/apps/src/contracts/openapi-compile.d.ts +11 -0
  69. package/types/apps/src/contracts/openapi-document.d.ts +53 -0
  70. package/types/apps/src/contracts/openapi.d.ts +160 -30
  71. package/types/apps/src/contracts/operations.d.ts +0 -5
  72. package/types/apps/src/contracts/protocol-version.d.ts +6 -0
  73. package/types/apps/src/contracts/protocols/1.d.ts +1589 -0
  74. package/types/apps/src/contracts/protocols/2.d.ts +668 -0
  75. package/types/apps/src/contracts/protocols/3.d.ts +676 -0
  76. package/types/apps/src/contracts/protocols/4.d.ts +1229 -0
  77. package/types/apps/src/contracts/protocols/5.d.ts +1090 -0
  78. package/types/apps/src/contracts/provider-error.d.ts +15 -0
  79. package/types/apps/src/contracts/provider.d.ts +69 -6
  80. package/types/apps/src/contracts/router.d.ts +59 -0
  81. package/types/apps/src/contracts/skills.d.ts +122 -0
  82. package/types/apps/src/contracts/storage.d.ts +3 -3
  83. package/types/apps/src/contracts/swagger-client.d.ts +29 -0
  84. package/types/apps/src/contracts/ui-auth.d.ts +6 -14
  85. package/types/apps/src/contracts/workflows.d.ts +34 -3
  86. package/types/apps/src/graphql.d.ts +5 -7
  87. package/types/apps/src/host.d.ts +1 -0
  88. package/types/apps/src/implementation/account-router.d.ts +12 -0
  89. package/types/apps/src/implementation/app.d.ts +5 -4
  90. package/types/apps/src/implementation/cache-session.d.ts +7 -0
  91. package/types/apps/src/implementation/cache.d.ts +8 -0
  92. package/types/apps/src/implementation/catalog-cache.d.ts +36 -0
  93. package/types/apps/src/implementation/dynamic-skills.d.ts +7 -0
  94. package/types/apps/src/implementation/elicitation.d.ts +13 -13
  95. package/types/apps/src/implementation/failure-detail.d.ts +25 -0
  96. package/types/apps/src/implementation/git.d.ts +25 -0
  97. package/types/apps/src/implementation/graphql-catalog.d.ts +7 -0
  98. package/types/apps/src/implementation/graphql.d.ts +81 -3
  99. package/types/apps/src/implementation/inflate.d.ts +16 -0
  100. package/types/apps/src/implementation/input-problems.d.ts +3 -0
  101. package/types/apps/src/implementation/mcp-call.d.ts +3 -2
  102. package/types/apps/src/implementation/mcp-catalog.d.ts +9 -0
  103. package/types/apps/src/implementation/mcp-client.d.ts +39 -22
  104. package/types/apps/src/implementation/mcp-stdio.d.ts +1 -1
  105. package/types/apps/src/implementation/mcp-tools.d.ts +6 -3
  106. package/types/apps/src/implementation/mcp.d.ts +55 -2
  107. package/types/apps/src/implementation/openapi-compile.d.ts +120 -0
  108. package/types/apps/src/implementation/openapi-document.d.ts +51 -0
  109. package/types/apps/src/implementation/openapi-names.d.ts +18 -0
  110. package/types/apps/src/implementation/openapi-request.d.ts +10 -4
  111. package/types/apps/src/implementation/openapi-source.d.ts +36 -0
  112. package/types/apps/src/implementation/openapi.d.ts +39 -3
  113. package/types/apps/src/implementation/operations.d.ts +26 -3
  114. package/types/apps/src/implementation/protocol-operations.d.ts +3 -4
  115. package/types/apps/src/implementation/provider-error.d.ts +10 -0
  116. package/types/apps/src/implementation/provider.d.ts +9 -4
  117. package/types/apps/src/implementation/router-catalog.d.ts +225 -0
  118. package/types/apps/src/implementation/router.d.ts +59 -0
  119. package/types/apps/src/implementation/schema.d.ts +11 -6
  120. package/types/apps/src/implementation/skill-files.d.ts +10 -0
  121. package/types/apps/src/implementation/skills.d.ts +43 -0
  122. package/types/apps/src/implementation/storage.d.ts +5 -3
  123. package/types/apps/src/implementation/swagger-client.d.ts +28 -0
  124. package/types/apps/src/implementation/ui-auth.d.ts +11 -5
  125. package/types/apps/src/implementation/ui-serving.d.ts +4 -2
  126. package/types/apps/src/implementation/webhooks.d.ts +1 -1
  127. package/types/apps/src/implementation/workflow-context.d.ts +11 -3
  128. package/types/apps/src/index.d.ts +11 -3
  129. package/types/apps/src/mcp-stdio.d.ts +2 -5
  130. package/types/apps/src/mcp.d.ts +8 -7
  131. package/types/apps/src/openapi.d.ts +8 -6
  132. package/types/apps/src/skills.d.ts +75 -0
  133. package/types/apps/src/ui-auth.d.ts +2 -2
  134. package/types/telemetry/src/browser-operations.d.ts +5 -2
  135. package/types/telemetry/src/config.d.ts +2 -0
  136. package/js/chunk-22WRQZT7.js +0 -389
  137. package/js/chunk-BKVL7XAJ.js +0 -47
  138. package/js/chunk-C24KEZXR.js +0 -59
  139. package/js/chunk-LOKGDT6B.js +0 -28
  140. package/js/chunk-MLKGABMK.js +0 -9
  141. package/types/apps/src/implementation/account-operations.d.ts +0 -32
package/js/openapi.js CHANGED
@@ -1,167 +1,296 @@
1
1
  import {
2
- protocolOperations
3
- } from "./chunk-LOKGDT6B.js";
4
- import "./chunk-C24KEZXR.js";
2
+ parse
3
+ } from "./chunk-UVL56Z6E.js";
4
+ import {
5
+ protocolOperations,
6
+ protocolRouter
7
+ } from "./chunk-72JNVHPK.js";
8
+ import {
9
+ OpenapiError,
10
+ OpenapiErrorResponse,
11
+ OpenapiOperation,
12
+ OpenapiParameter,
13
+ OpenapiRequestBody,
14
+ OpenapiToolsOptions,
15
+ defaultOpenapiResponseLimits,
16
+ isOpenapiFileSchema,
17
+ isOpenapiTextMedia,
18
+ openapiBinaryResultSchema,
19
+ openapiMediaKind
20
+ } from "./chunk-FL2QR3XW.js";
21
+ import "./chunk-IPI4MFSN.js";
22
+ import {
23
+ fromPromise,
24
+ nativeOperation,
25
+ routerDeclaration,
26
+ toPromise
27
+ } from "./chunk-Z5M2LQOZ.js";
28
+ import {
29
+ accountProviderError,
30
+ httpProviderError
31
+ } from "./chunk-MKWZPDR6.js";
32
+ import {
33
+ ApiErrorRecovery,
34
+ ApiErrorResponse,
35
+ OpenapiResponseError,
36
+ RouterMeta,
37
+ defaultOpenapiErrorLimits
38
+ } from "./chunk-WLE7WX2U.js";
39
+ import "./chunk-N7YDVXYJ.js";
40
+ import {
41
+ ProviderError
42
+ } from "./chunk-R3EV5FTO.js";
43
+ import "./chunk-JU7VHODU.js";
5
44
  import {
6
45
  FetchHttpClient_exports
7
- } from "./chunk-VFUZI3NY.js";
46
+ } from "./chunk-57RKNWL2.js";
8
47
  import {
9
48
  HttpClientRequest_exports,
10
49
  HttpClient_exports
11
- } from "./chunk-W7Q5EOTS.js";
50
+ } from "./chunk-UK573G7W.js";
12
51
  import {
13
- jsonSchemaDecoder
14
- } from "./chunk-BPEFS4YF.js";
52
+ jsonSchema,
53
+ lazyJsonSchemaDecoder,
54
+ once,
55
+ wrap
56
+ } from "./chunk-5T57N25Q.js";
57
+ import "./chunk-PZB6T6KU.js";
15
58
  import {
16
- HttpUrl,
17
- JsonObject
18
- } from "./chunk-36DNRFZQ.js";
59
+ JsonObject,
60
+ JsonValue
61
+ } from "./chunk-27F7W2LG.js";
19
62
  import {
63
+ Deferred_exports,
64
+ Duration_exports,
20
65
  Effect_exports,
21
- Schema_exports
22
- } from "./chunk-2OTCEKL2.js";
23
- import "./chunk-MLKGABMK.js";
24
-
25
- // src/contracts/openapi.ts
26
- var RequestParameter = Schema_exports.Struct({
27
- name: Schema_exports.String,
28
- in: Schema_exports.Literals(["path", "query", "header"]),
29
- style: Schema_exports.String,
30
- explode: Schema_exports.Boolean
31
- });
32
- var OpenapiOperation = Schema_exports.Struct({
33
- name: Schema_exports.NonEmptyString,
34
- description: Schema_exports.String,
35
- method: Schema_exports.Literals(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]),
36
- path: Schema_exports.String,
37
- baseUrl: HttpUrl,
38
- parameters: Schema_exports.Array(RequestParameter),
39
- body: Schema_exports.Literals(["json", "base64", "none"]),
40
- /** Streams remain in the metadata but cannot run through a single-result tool call. */
41
- streaming: Schema_exports.optionalKey(Schema_exports.Literal(true)),
42
- security: Schema_exports.Array(Schema_exports.Array(Schema_exports.String)),
43
- input: JsonObject,
44
- outputSchema: Schema_exports.optionalKey(JsonObject)
45
- });
46
- var CredentialBinding = Schema_exports.Struct({
47
- scheme: Schema_exports.String,
48
- field: Schema_exports.String,
49
- in: Schema_exports.Literals(["header", "query"]),
50
- name: Schema_exports.String,
51
- prefix: Schema_exports.String
52
- });
53
- var OpenapiAccount = Schema_exports.Struct({
54
- method: Schema_exports.String,
55
- fields: Schema_exports.Record(Schema_exports.String, Schema_exports.Unknown)
56
- });
57
- var OpenapiToolsOptions = Schema_exports.Struct({
58
- operations: Schema_exports.Array(OpenapiOperation),
59
- methods: Schema_exports.Record(Schema_exports.String, Schema_exports.Array(CredentialBinding)),
60
- oauth: Schema_exports.Array(Schema_exports.String),
61
- account: Schema_exports.optional(OpenapiAccount),
62
- signal: Schema_exports.optional(Schema_exports.instanceOf(AbortSignal)),
63
- fetch: Schema_exports.optional(
64
- Schema_exports.declare((value) => typeof value === "function")
65
- )
66
- });
67
- var OpenapiError = class extends Schema_exports.TaggedError()("OpenapiError", {
68
- reason: Schema_exports.Literals(["invalid_definition", "invalid_input", "request"]),
69
- status: Schema_exports.optional(Schema_exports.Number)
70
- }) {
71
- };
66
+ Encoding_exports,
67
+ JsonPointer_exports,
68
+ JsonSchema_exports,
69
+ Option_exports,
70
+ Schema_exports,
71
+ Stream_exports
72
+ } from "./chunk-CDL5PM2Q.js";
73
+ import "./chunk-CZ7CSFO4.js";
74
+
75
+ // src/implementation/swagger-client.ts
76
+ var loadSwaggerClient = () => import("./es-APDZKREY.js").then((module) => module.default);
72
77
 
73
78
  // src/implementation/openapi-request.ts
79
+ var bodyRecovery = Schema_exports.decodeUnknownOption(Schema_exports.Struct({ recovery: ApiErrorRecovery }));
80
+ function responseError(response, errors) {
81
+ return Effect_exports.gen(function* () {
82
+ const candidates = errors.filter((error) => error.status === response.status);
83
+ if (candidates.length === 0 || !/^application\/(?:[\w.-]+\+)?json$/i.test(
84
+ response.headers["content-type"]?.split(";")[0]?.trim() ?? ""
85
+ ))
86
+ return;
87
+ const length = response.headers["content-length"];
88
+ if (length !== void 0 && Number(length) > defaultOpenapiErrorLimits.maxBodyBytes) return;
89
+ const json = yield* response.stream.pipe(
90
+ Stream_exports.mapError(() => new OpenapiError({ reason: "request", status: response.status })),
91
+ Stream_exports.limitBytes(
92
+ defaultOpenapiErrorLimits.maxBodyBytes,
93
+ () => Stream_exports.fail(new OpenapiError({ reason: "request", status: response.status }))
94
+ ),
95
+ Stream_exports.decodeText,
96
+ Stream_exports.mkString,
97
+ Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(Schema_exports.fromJsonString(Schema_exports.Json))),
98
+ Effect_exports.timeout(defaultOpenapiErrorLimits.readTimeoutMs)
99
+ );
100
+ for (const candidate of candidates) {
101
+ const parsed = yield* Schema_exports.decodeUnknownEffect(candidate.decoder)(json).pipe(Effect_exports.option);
102
+ if (Option_exports.isSome(parsed)) {
103
+ const message = candidate.message.source === "schema" ? Option_exports.some({ message: candidate.message.value }) : Schema_exports.decodeUnknownOption(
104
+ Schema_exports.Struct({ message: ApiErrorResponse.fields.message })
105
+ )(parsed.value);
106
+ if (Option_exports.isNone(message)) continue;
107
+ const recovery = bodyRecovery(parsed.value);
108
+ return new OpenapiResponseError({
109
+ code: candidate.code,
110
+ status: response.status,
111
+ message: message.value.message,
112
+ ...Option_exports.isSome(recovery) ? { recovery: recovery.value.recovery } : {}
113
+ });
114
+ }
115
+ }
116
+ }).pipe(Effect_exports.catch(() => Effect_exports.succeed(void 0)));
117
+ }
74
118
  var object = Schema_exports.decodeUnknownSync(Schema_exports.Record(Schema_exports.String, Schema_exports.Unknown));
75
119
  function scalar(value) {
76
120
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean")
77
121
  return String(value);
78
122
  throw new Error("This parameter requires scalar values");
79
123
  }
80
- function pairs(value) {
81
- return Object.entries(object(value)).map(([key, item]) => [key, scalar(item)]);
124
+ var swaggerRequest = Schema_exports.decodeUnknownSync(
125
+ Schema_exports.Struct({
126
+ url: Schema_exports.String,
127
+ method: Schema_exports.String,
128
+ headers: Schema_exports.Record(Schema_exports.String, Schema_exports.String),
129
+ body: Schema_exports.optional(
130
+ Schema_exports.Union([Schema_exports.String, Schema_exports.instanceOf(Blob), Schema_exports.instanceOf(FormData)])
131
+ )
132
+ })
133
+ );
134
+ var reservedPath = /* @__PURE__ */ new Set([
135
+ ":",
136
+ "@",
137
+ "!",
138
+ "$",
139
+ "&",
140
+ "'",
141
+ "(",
142
+ ")",
143
+ "*",
144
+ "+",
145
+ ",",
146
+ ";",
147
+ "=",
148
+ "/"
149
+ ]);
150
+ function reservedPathValue(value) {
151
+ const text = Array.isArray(value) ? value.map(scalar).join(",") : scalar(value);
152
+ if (/[?#\\]/.test(text)) throw new Error("This path value contains a forbidden character");
153
+ const encoded = text.replace(/%[0-9A-Fa-f]{2}|[^]/gu, (part) => {
154
+ if (part.length === 3 && part.startsWith("%")) {
155
+ if ("./\\?#%".includes(String.fromCharCode(Number.parseInt(part.slice(1), 16))))
156
+ throw new Error("This path value contains a forbidden escape");
157
+ return part;
158
+ }
159
+ return reservedPath.has(part) ? part : encodeURIComponent(part);
160
+ });
161
+ if (encoded.split("/").some((segment) => segment === "" || segment === "." || segment === ".."))
162
+ throw new Error("This path value would change the request path");
163
+ return encoded;
82
164
  }
83
- function simple(value, explode, encode) {
84
- const token = (value2) => encode ? encodeURIComponent(scalar(value2)) : scalar(value2);
85
- if (Array.isArray(value)) return value.map(token).join(",");
86
- if (typeof value === "object" && value !== null)
87
- return pairs(value).map(([key, item]) => token(key) + (explode ? "=" : ",") + token(item)).join(",");
88
- return token(value);
165
+ function operationPath(op) {
166
+ const template = op.baseUrl.replace(/\/$/, "") + op.path;
167
+ let marker = "executorPathParameter";
168
+ while (template.includes(marker)) marker += "_";
169
+ const expansions = [];
170
+ const address = template.replace(/\{[^{}]+\}/g, (placeholder) => {
171
+ const parameter = op.request.parameters.find(
172
+ (p) => p.in === "path" && p.name === placeholder.slice(1, -1)
173
+ );
174
+ if (parameter === void 0) throw new Error("A path parameter is not declared");
175
+ const token = `${marker}_${expansions.length}_`;
176
+ expansions.push({
177
+ token,
178
+ pattern: parameter.allowReserved === true && parameter.content === void 0 ? ".+" : "[^/]+"
179
+ });
180
+ return token;
181
+ });
182
+ let pattern = new URL(address).pathname.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
183
+ for (const expansion of expansions)
184
+ pattern = pattern.replaceAll(expansion.token, expansion.pattern);
185
+ return new RegExp("^" + pattern + "$");
89
186
  }
187
+ var bytes = (value) => Uint8Array.from(atob(scalar(value)), (char) => char.charCodeAt(0));
90
188
  function createRequest(config) {
91
189
  const { methods, oauth } = config;
92
- function schemes(method) {
93
- if (method === void 0) return [];
94
- if (oauth.includes(method)) return [method];
95
- const bindings = Object.hasOwn(methods, method) ? methods[method] : void 0;
96
- return bindings?.map((binding) => binding.scheme) ?? [];
97
- }
98
- function selectedSecurity(op, method) {
190
+ function selectedCredentials(op, account) {
99
191
  if (op.streaming === true) return void 0;
100
- if (!op.security.length) return [];
101
- const supported = schemes(method);
102
- return op.security.find((keys) => keys.every((key) => supported.includes(key)));
192
+ const authorized = {};
193
+ if (account !== void 0) {
194
+ if (oauth.includes(account.method)) {
195
+ const token = account.fields.access_token;
196
+ if (typeof token === "string" && token.length > 0)
197
+ authorized[account.method] = { token: { access_token: token } };
198
+ } else if (Object.hasOwn(methods, account.method)) {
199
+ const bindings = methods[account.method] ?? [];
200
+ for (const scheme of new Set(bindings.map((binding) => binding.scheme))) {
201
+ const parts = bindings.filter((binding) => binding.scheme === scheme);
202
+ if (parts.some(
203
+ ({ field }) => typeof account.fields[field] !== "string" || account.fields[field] === ""
204
+ ))
205
+ continue;
206
+ for (const { part, field, prefix } of parts) {
207
+ const value = scalar(account.fields[field]);
208
+ authorized[scheme] = part === "value" ? prefix + value : { ...object(authorized[scheme] ?? {}), [part]: value };
209
+ }
210
+ }
211
+ }
212
+ }
213
+ const security = op.request.security;
214
+ const keys = security.length === 0 ? [] : security.map(Object.keys).find((keys2) => keys2.every((key) => Object.hasOwn(authorized, key)));
215
+ return keys === void 0 ? void 0 : Object.fromEntries(keys.map((key) => [key, authorized[key]]));
103
216
  }
104
- const call = (op, input, account) => Effect_exports.scoped(
217
+ const call = (op, input, account, errors) => Effect_exports.scoped(
105
218
  Effect_exports.gen(function* () {
219
+ const swagger = yield* Effect_exports.promise(loadSwaggerClient);
106
220
  const prepared = yield* Effect_exports.try({
107
221
  try: () => {
108
222
  const args = object(input);
109
- const security = selectedSecurity(op, account?.method);
110
- if (security === void 0)
223
+ const authorized = selectedCredentials(op, account);
224
+ if (authorized === void 0)
111
225
  throw new Error("The selected account cannot call this tool");
226
+ const parameters = {};
112
227
  let path = op.path;
113
- const query = new URLSearchParams();
114
- const headers = new Headers();
115
- for (const p of op.parameters) {
228
+ const swaggerParameters = op.request.parameters.filter((p) => {
116
229
  const group = args[p.in === "header" ? "headers" : p.in];
117
230
  const value = group === void 0 ? void 0 : object(group)[p.name];
118
- if (value === void 0) continue;
119
- if (p.in === "path")
120
- path = path.replaceAll("{" + p.name + "}", simple(value, p.explode, true));
121
- else if (p.in === "header") headers.set(p.name, simple(value, p.explode, false));
122
- else if (p.style === "deepObject") {
123
- for (const [key, item] of pairs(value))
124
- query.append(p.name + "[" + key + "]", item);
125
- } else if (Array.isArray(value)) {
126
- if (p.explode && p.style === "form")
127
- for (const item of value) query.append(p.name, scalar(item));
128
- else
129
- query.append(
130
- p.name,
131
- value.map(scalar).join(
132
- p.style === "spaceDelimited" ? " " : p.style === "pipeDelimited" ? "|" : ","
133
- )
134
- );
135
- } else if (typeof value === "object" && value !== null) {
136
- if (p.style !== "form") throw new Error("Unsupported object parameter style");
137
- if (p.explode) for (const [key, item] of pairs(value)) query.append(key, item);
138
- else query.append(p.name, pairs(value).flat().join(","));
139
- } else query.append(p.name, scalar(value));
140
- }
141
- if (/{[^}]+}/.test(path)) throw new Error("A required path parameter is missing");
142
- const url = new URL(op.baseUrl + path);
143
- if (account && Object.hasOwn(methods, account.method)) {
144
- for (const binding of methods[account.method] ?? []) {
145
- if (!security.includes(binding.scheme)) continue;
146
- const credential = binding.prefix + scalar(account.fields[binding.field]);
147
- if (binding.in === "header") headers.set(binding.name, credential);
148
- else query.set(binding.name, credential);
149
- }
150
- } else if (account && oauth.includes(account.method) && security.includes(account.method)) {
151
- headers.set("Authorization", "Bearer " + scalar(account.fields.access_token));
152
- }
153
- url.search = query.toString();
154
- let body;
155
- if (args.body !== void 0) {
156
- if (op.body === "json") {
157
- headers.set("Content-Type", "application/json");
158
- body = JSON.stringify(args.body);
159
- } else if (op.body === "base64") {
160
- headers.set("Content-Type", "application/octet-stream");
161
- body = Uint8Array.from(atob(scalar(args.body)), (char) => char.charCodeAt(0));
162
- }
163
- }
164
- return { url, headers, body, method: op.method };
231
+ if (p.in === "path" && p.allowReserved === true && p.content === void 0) {
232
+ if (value === void 0) throw new Error("A required path parameter is missing");
233
+ path = path.replaceAll(`{${p.name}}`, reservedPathValue(value));
234
+ return false;
235
+ }
236
+ if (group !== void 0) parameters[`${p.in}.${p.name}`] = value;
237
+ return true;
238
+ });
239
+ const content = op.request.requestBody?.content ?? {};
240
+ const contentType2 = args.contentType === void 0 ? Object.keys(content)[0] : scalar(args.contentType);
241
+ const media = contentType2 === void 0 ? void 0 : content[contentType2];
242
+ let body = args.body;
243
+ if (body !== void 0 && media !== void 0 && contentType2 !== void 0) {
244
+ const kind = openapiMediaKind(contentType2);
245
+ if (kind === "json") body = JSON.stringify(body);
246
+ else if (kind === "binary") body = new Blob([bytes(body)]);
247
+ else if (kind === "multipart") {
248
+ const fields = { ...object(body) };
249
+ for (const [name, property] of Object.entries(
250
+ object(media.schema?.properties ?? {})
251
+ )) {
252
+ if (isOpenapiFileSchema(object(property)) && fields[name] !== void 0)
253
+ fields[name] = new File([bytes(fields[name])], name);
254
+ }
255
+ body = fields;
256
+ }
257
+ }
258
+ const prepared2 = swaggerRequest(
259
+ swagger.buildRequest({
260
+ spec: {
261
+ openapi: op.openapi,
262
+ servers: [{ url: op.baseUrl }],
263
+ components: { securitySchemes: op.securitySchemes },
264
+ paths: {
265
+ [path]: {
266
+ [op.method.toLowerCase()]: {
267
+ ...op.request,
268
+ parameters: swaggerParameters,
269
+ operationId: op.name
270
+ }
271
+ }
272
+ }
273
+ },
274
+ operationId: op.name,
275
+ pathName: path,
276
+ method: op.method.toLowerCase(),
277
+ parameters,
278
+ securities: { authorized },
279
+ ...contentType2 === void 0 ? {} : { requestContentType: contentType2 },
280
+ ...body === void 0 ? {} : { requestBody: body }
281
+ })
282
+ );
283
+ const pathname = prepared2.url.replace(/^[^:]+:\/\/[^/]*/, "").split(/[?#]/)[0] ?? "";
284
+ if (pathname.split("/").some((segment) => /^(?:\.|%2e){1,2}$/i.test(segment)))
285
+ throw new Error("This path value would change the request path");
286
+ const url = new URL(prepared2.url);
287
+ const origin = new URL(op.baseUrl).origin;
288
+ if (url.origin !== origin || !operationPath(op).test(url.pathname) || url.username || url.password)
289
+ throw new Error("The request escaped its API operation");
290
+ const headers = new Headers(prepared2.headers);
291
+ if (!headers.has("user-agent")) headers.set("user-agent", "Executor");
292
+ if (prepared2.body instanceof FormData) headers.delete("content-type");
293
+ return { ...prepared2, url, headers };
165
294
  },
166
295
  catch: () => new OpenapiError({ reason: "invalid_input" })
167
296
  });
@@ -177,10 +306,34 @@ function createRequest(config) {
177
306
  catch: () => new OpenapiError({ reason: "invalid_input" })
178
307
  });
179
308
  const response = yield* HttpClient_exports.withScope(client).execute(request);
180
- if (response.status < 200 || response.status >= 300)
181
- return yield* new OpenapiError({ reason: "request", status: response.status });
309
+ if (response.status < 200 || response.status >= 300) {
310
+ const provider = httpProviderError(response.status, response.headers);
311
+ if (provider !== void 0 && provider.reason !== "rejected") return yield* provider;
312
+ const declared = yield* responseError(response, errors);
313
+ return yield* declared ?? provider ?? new OpenapiError({ reason: "request", status: response.status });
314
+ }
182
315
  if (response.status === 204 || prepared.method === "HEAD") return null;
183
- return yield* (response.headers["content-type"]?.includes("json") ? response.json : response.text).pipe(Effect_exports.withSpan("provider.http.response.read"));
316
+ const contentType = response.headers["content-type"] ?? "text/plain";
317
+ const chunks = yield* response.stream.pipe(
318
+ Stream_exports.mapError(() => new OpenapiError({ reason: "request" })),
319
+ Stream_exports.limitBytes(
320
+ defaultOpenapiResponseLimits.maxBodyBytes,
321
+ () => Stream_exports.fail(new OpenapiError({ reason: "request" }))
322
+ ),
323
+ Stream_exports.runCollect,
324
+ Effect_exports.timeout(defaultOpenapiResponseLimits.readTimeoutMs),
325
+ Effect_exports.withSpan("provider.http.response.read")
326
+ );
327
+ const data = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0));
328
+ let offset = 0;
329
+ for (const chunk of chunks) {
330
+ data.set(chunk, offset);
331
+ offset += chunk.length;
332
+ }
333
+ if (!isOpenapiTextMedia(contentType))
334
+ return { base64: Encoding_exports.encodeBase64(data), contentType };
335
+ const text = new TextDecoder().decode(data);
336
+ return contentType.includes("json") && !contentType.includes("ndjson") ? yield* Schema_exports.decodeUnknownEffect(Schema_exports.fromJsonString(Schema_exports.Json))(text) : text;
184
337
  })
185
338
  ).pipe(
186
339
  Effect_exports.withSpan("provider.openapi.call", {
@@ -189,36 +342,145 @@ function createRequest(config) {
189
342
  Effect_exports.provideService(FetchHttpClient_exports.RequestInit, { redirect: "manual" }),
190
343
  Effect_exports.provide(FetchHttpClient_exports.layer),
191
344
  Effect_exports.mapError(
192
- (error) => error instanceof OpenapiError ? error : new OpenapiError({ reason: "request" })
345
+ (error) => error instanceof ProviderError && account?.id !== void 0 ? accountProviderError(error, account.id) : error instanceof OpenapiError || error instanceof OpenapiResponseError || error instanceof ProviderError ? error : new OpenapiError({ reason: "request" })
193
346
  )
194
347
  );
195
348
  return {
196
- available: (op, method) => selectedSecurity(op, method) !== void 0,
349
+ available: (op, account) => selectedCredentials(op, account) !== void 0,
197
350
  call
198
351
  };
199
352
  }
200
353
 
201
354
  // src/implementation/openapi.ts
202
- var openapiToolsEffect = (options) => Effect_exports.gen(function* () {
355
+ function references(value, found = /* @__PURE__ */ new Set()) {
356
+ if (Array.isArray(value)) for (const item of value) references(item, found);
357
+ else if (value !== null && typeof value === "object")
358
+ for (const [key, item] of Object.entries(value)) {
359
+ if (key !== "$ref" || typeof item !== "string") references(item, found);
360
+ else {
361
+ const path = item.startsWith("#/$defs/") ? JsonPointer_exports.parseUriFragment(item) : void 0;
362
+ if (path?.[1] !== void 0) found.add(path[1]);
363
+ }
364
+ }
365
+ return found;
366
+ }
367
+ var bundler = (definitions) => {
368
+ const direct = /* @__PURE__ */ new Map();
369
+ return (schema2) => {
370
+ const reached = /* @__PURE__ */ new Map();
371
+ const pending = [...references(schema2)];
372
+ for (let name = pending.pop(); name !== void 0; name = pending.pop()) {
373
+ const definition = Object.hasOwn(definitions, name) ? definitions[name] : void 0;
374
+ if (definition === void 0 || reached.has(name)) continue;
375
+ reached.set(name, definition);
376
+ let names = direct.get(name);
377
+ if (names === void 0) direct.set(name, names = references(definition));
378
+ pending.push(...names);
379
+ }
380
+ if (reached.size === 0) return schema2;
381
+ const own = schema2.$defs;
382
+ return {
383
+ ...schema2,
384
+ $defs: {
385
+ ...Object.fromEntries(reached),
386
+ ...own !== null && typeof own === "object" && !Array.isArray(own) ? own : {}
387
+ }
388
+ };
389
+ };
390
+ };
391
+ var parameterGroups = { path: "path", query: "query", headers: "header" };
392
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
393
+ var boundParameters = (op, defaults) => Object.keys(parameterGroups).flatMap(
394
+ (group) => Object.entries(defaults?.[group] ?? {}).filter(
395
+ ([name]) => op.request.parameters.some((p) => p.name === name && p.in === parameterGroups[group])
396
+ ).map(([name, value]) => ({ group, name, value }))
397
+ );
398
+ var parameterDefaultsInput = (op, defaults, publish) => {
399
+ const bound = boundParameters(op, defaults);
400
+ if (!bound.length || !isObject(op.input.properties)) return op.input;
401
+ const properties = { ...op.input.properties };
402
+ let required = Array.isArray(op.input.required) ? op.input.required : [];
403
+ for (const group of new Set(bound.map((entry) => entry.group))) {
404
+ const shape = properties[group];
405
+ if (!isObject(shape)) continue;
406
+ const names = bound.filter((entry) => entry.group === group);
407
+ const remaining = (Array.isArray(shape.required) ? shape.required : []).filter(
408
+ (name) => !names.some((entry) => entry.name === name)
409
+ );
410
+ const fields = isObject(shape.properties) ? shape.properties : {};
411
+ properties[group] = {
412
+ ...shape,
413
+ required: remaining,
414
+ ...publish ? {
415
+ properties: {
416
+ ...fields,
417
+ ...Object.fromEntries(
418
+ names.map(({ name, value }) => {
419
+ const field = isObject(fields[name]) ? fields[name] : {};
420
+ const note = "Optional; defaults to the value bound to the selected account.";
421
+ const description = typeof field.description === "string" ? `${field.description} ${note}` : note;
422
+ return [name, { ...field, description, default: value }];
423
+ })
424
+ )
425
+ }
426
+ } : {}
427
+ };
428
+ if (!remaining.length) required = required.filter((key) => key !== group);
429
+ }
430
+ return { ...op.input, properties, required };
431
+ };
432
+ var fillParameterDefaults = (op, defaults, value) => {
433
+ const bound = boundParameters(op, defaults);
434
+ if (!bound.length || !isObject(value)) return value;
435
+ const result = { ...value };
436
+ for (const { group, name, value: fallback } of bound) {
437
+ const current = result[group] ?? {};
438
+ if (!isObject(current)) return value;
439
+ if (!Object.hasOwn(current, name)) result[group] = { ...current, [name]: fallback };
440
+ }
441
+ return result;
442
+ };
443
+ var prepareOpenapiOperation = (op, definitions, defaults) => Effect_exports.gen(function* () {
444
+ const bundle = bundler(definitions);
445
+ const input = yield* lazyJsonSchemaDecoder(
446
+ () => bundle(parameterDefaultsInput(op, defaults, false))
447
+ );
448
+ const errors = yield* Effect_exports.forEach(
449
+ op.errorResponses ?? [],
450
+ (response) => lazyJsonSchemaDecoder(() => bundle(response.schema)).pipe(
451
+ Effect_exports.map((decoder) => ({ ...response, decoder }))
452
+ )
453
+ );
454
+ return {
455
+ input,
456
+ errors,
457
+ output: once(() => op.outputSchema === void 0 ? void 0 : bundle(op.outputSchema))
458
+ };
459
+ });
460
+ var openapiToolsEffect = (options, prepared) => Effect_exports.gen(function* () {
203
461
  const config = yield* Schema_exports.decodeUnknownEffect(OpenapiToolsOptions)(options).pipe(
204
462
  Effect_exports.mapError(() => new OpenapiError({ reason: "invalid_definition" }))
205
463
  );
206
464
  const request = createRequest(config);
207
465
  const entries = yield* Effect_exports.forEach(
208
- config.operations.filter((op) => request.available(op, config.account?.method)),
466
+ config.operations.filter((op) => request.available(op, config.account)),
209
467
  (op) => Effect_exports.gen(function* () {
210
- const input = yield* jsonSchemaDecoder(op.input).pipe(
211
- Effect_exports.mapError(() => new OpenapiError({ reason: "invalid_definition" }))
212
- );
468
+ const schemas = prepared?.get(op.name) ?? (yield* prepareOpenapiOperation(
469
+ op,
470
+ config.definitions ?? {},
471
+ config.parameterDefaults
472
+ ));
473
+ const { input, errors } = schemas;
213
474
  const tool = {
214
475
  description: op.description,
215
476
  readOnly: ["GET", "HEAD", "OPTIONS"].includes(op.method),
216
477
  input,
217
- ...op.outputSchema === void 0 ? {} : { outputSchema: op.outputSchema },
218
- run: (_context, value) => Schema_exports.decodeUnknownEffect(input)(value).pipe(
478
+ run: (_context, value) => Schema_exports.decodeUnknownEffect(input)(
479
+ fillParameterDefaults(op, config.parameterDefaults, value)
480
+ ).pipe(
219
481
  Effect_exports.mapError(() => new OpenapiError({ reason: "invalid_input" })),
220
482
  Effect_exports.flatMap(
221
- (parsed) => request.call(op, parsed, config.account).pipe(
483
+ (parsed) => request.call(op, parsed, config.account, errors).pipe(
222
484
  Effect_exports.provideService(
223
485
  FetchHttpClient_exports.Fetch,
224
486
  config.fetch ?? globalThis.fetch
@@ -227,20 +489,2656 @@ var openapiToolsEffect = (options) => Effect_exports.gen(function* () {
227
489
  )
228
490
  )
229
491
  };
492
+ const output = op.outputSchema;
493
+ if (output !== void 0)
494
+ Object.defineProperty(tool, "outputSchema", {
495
+ enumerable: true,
496
+ get: schemas.output
497
+ });
230
498
  return [op.name, tool];
231
499
  })
232
500
  );
233
501
  return Object.fromEntries(entries);
234
502
  });
235
503
 
236
- // src/openapi.ts
237
- var openapiOperations = (options, kinds = {}) => Effect_exports.runPromise(
238
- openapiToolsEffect(options).pipe(
239
- Effect_exports.map((operations) => protocolOperations(operations, kinds))
504
+ // src/contracts/openapi-compile.ts
505
+ var OpenapiCompileErrorCode = Schema_exports.Literals([
506
+ "server_protocol",
507
+ "server_url",
508
+ "external_reference",
509
+ "circular_reference",
510
+ "schema_keyword",
511
+ "schema_reference",
512
+ "missing_component",
513
+ "openapi_version",
514
+ "auth_helper",
515
+ "auth_missing",
516
+ "operation_path",
517
+ "duplicate_operation",
518
+ "server_missing",
519
+ "multiple_hosts",
520
+ "parameter_encoding",
521
+ "parameter_style",
522
+ "request_body",
523
+ "combined_oauth",
524
+ "auth_method",
525
+ "input_schema",
526
+ "no_operations",
527
+ "no_supported_operations",
528
+ "invalid_document",
529
+ "source_generation",
530
+ "authoring_reference"
531
+ ]);
532
+ var OpenapiCompileError = class extends Schema_exports.TaggedError()(
533
+ "OpenapiCompileError",
534
+ {
535
+ code: OpenapiCompileErrorCode,
536
+ reason: Schema_exports.String
537
+ }
538
+ ) {
539
+ };
540
+
541
+ // src/contracts/openapi-document.ts
542
+ var Server = Schema_exports.Struct({ url: Schema_exports.String, variables: Schema_exports.optionalKey(JsonObject) });
543
+ var Specification = Schema_exports.Struct({
544
+ openapi: Schema_exports.String,
545
+ servers: Schema_exports.optionalKey(Schema_exports.Array(Server)),
546
+ paths: Schema_exports.Record(Schema_exports.String, JsonObject),
547
+ components: Schema_exports.optionalKey(
548
+ Schema_exports.Struct({
549
+ schemas: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, JsonObject)),
550
+ securitySchemes: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, JsonObject))
551
+ })
552
+ ),
553
+ security: Schema_exports.optionalKey(
554
+ Schema_exports.Array(Schema_exports.Record(Schema_exports.String, Schema_exports.Array(Schema_exports.String)))
555
+ )
556
+ });
557
+ var Operation = Schema_exports.Struct({
558
+ operationId: Schema_exports.optionalKey(Schema_exports.String),
559
+ responses: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, JsonObject)),
560
+ summary: Schema_exports.optionalKey(Schema_exports.String),
561
+ description: Schema_exports.optionalKey(Schema_exports.String),
562
+ parameters: Schema_exports.optionalKey(Schema_exports.Array(JsonObject)),
563
+ requestBody: Schema_exports.optionalKey(JsonObject),
564
+ security: Schema_exports.optionalKey(
565
+ Schema_exports.Array(Schema_exports.Record(Schema_exports.String, Schema_exports.Array(Schema_exports.String)))
566
+ ),
567
+ servers: Schema_exports.optionalKey(Schema_exports.Array(Server))
568
+ });
569
+
570
+ // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/object/is-object.js
571
+ var isObject2 = (value) => {
572
+ if (value === null || typeof value !== "object") {
573
+ return false;
574
+ }
575
+ const proto = Object.getPrototypeOf(value);
576
+ return proto === Object.prototype || proto === null;
577
+ };
578
+ var isObjectLike = (value) => typeof value === "object" && value !== null;
579
+
580
+ // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/helpers/clone-document.js
581
+ var ALIAS_EXPANSION_ENTRY_FLOOR = 1e5;
582
+ var MAX_ALIAS_EXPANSION_RATIO = 10;
583
+ var cloneDocument = (document) => {
584
+ const ancestors = /* @__PURE__ */ new WeakSet();
585
+ const expansion = { sourceEntries: 0, copiedEntries: 0, sizes: /* @__PURE__ */ new Map() };
586
+ const clone = (value) => {
587
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined") {
588
+ return value;
589
+ }
590
+ if (!Array.isArray(value) && !isObject2(value)) {
591
+ return structuredClone(value);
592
+ }
593
+ if (ancestors.has(value)) {
594
+ throw new Error("Cannot upgrade to OpenAPI 3.2: cyclic objects cannot be represented in JSON. Use $ref instead.");
595
+ }
596
+ const size = expansion.sizes.get(value) ?? 1 + (Array.isArray(value) ? value.length : Object.keys(value).length);
597
+ if (!expansion.sizes.has(value)) {
598
+ expansion.sizes.set(value, size);
599
+ expansion.sourceEntries += size;
600
+ }
601
+ expansion.copiedEntries += size;
602
+ if (expansion.copiedEntries > ALIAS_EXPANSION_ENTRY_FLOOR && expansion.copiedEntries > expansion.sourceEntries * MAX_ALIAS_EXPANSION_RATIO) {
603
+ throw new Error("Cannot upgrade to OpenAPI 3.2: excessive YAML alias expansion. Use $ref for shared schemas.");
604
+ }
605
+ ancestors.add(value);
606
+ const result = Array.isArray(value) ? value.map(clone) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)]));
607
+ ancestors.delete(value);
608
+ return result;
609
+ };
610
+ return clone(document);
611
+ };
612
+
613
+ // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/json/escape-json-pointer.js
614
+ var escapeJsonPointer = (str) => str.replace(/~/g, "~0").replace(/\//g, "~1");
615
+
616
+ // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/json/unescape-json-pointer.js
617
+ var unescapeJsonPointer = (uri) => decodeURI(uri.replace(/~1/g, "/").replace(/~0/g, "~"));
618
+
619
+ // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/json/parse-json-pointer-segments.js
620
+ var parseJsonPointerSegments = (path) => path.split("/").slice(1).map(unescapeJsonPointer);
621
+
622
+ // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/upgrade-incompatibility-error.js
623
+ var UpgradeIncompatibilityError = class extends AggregateError {
624
+ errors;
625
+ constructor(errors) {
626
+ super(errors, errors.map((error) => error.message).join("\n"));
627
+ this.errors = errors;
628
+ this.name = "UpgradeIncompatibilityError";
629
+ }
630
+ };
631
+
632
+ // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/3.1-to-3.2/migrate-objects.js
633
+ var schemaMaps = ["properties", "patternProperties", "$defs", "dependentSchemas"];
634
+ var schemaArrays = ["allOf", "anyOf", "oneOf", "prefixItems"];
635
+ var schemaSingles = [
636
+ "items",
637
+ "contains",
638
+ "additionalProperties",
639
+ "unevaluatedProperties",
640
+ "unevaluatedItems",
641
+ "propertyNames",
642
+ "not",
643
+ "if",
644
+ "then",
645
+ "else",
646
+ "contentSchema"
647
+ ];
648
+ var migrateObjects = (document) => {
649
+ const properties = /* @__PURE__ */ new WeakMap();
650
+ const own = (value, key) => {
651
+ const entries = properties.get(value) ?? new Map(Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([, descriptor]) => Object.hasOwn(descriptor, "value")).map(([name, descriptor]) => [name, descriptor.value]));
652
+ properties.set(value, entries);
653
+ return entries.get(key);
654
+ };
655
+ const operationTags = /* @__PURE__ */ new Set();
656
+ const errors = [];
657
+ const requiredCache = /* @__PURE__ */ new WeakMap();
658
+ const cyclicRequired = /* @__PURE__ */ new WeakSet();
659
+ const requiredWork = { evaluations: 0 };
660
+ const propertySchemas = /* @__PURE__ */ new WeakSet();
661
+ const xmlRoots = [];
662
+ const markPropertySchema = (schema2) => {
663
+ if (!isObject2(schema2) || propertySchemas.has(schema2)) {
664
+ return;
665
+ }
666
+ propertySchemas.add(schema2);
667
+ markPropertySchema(schema2.items);
668
+ if (Array.isArray(schema2.prefixItems)) {
669
+ schema2.prefixItems.forEach(markPropertySchema);
670
+ }
671
+ };
672
+ const xmlCache = /* @__PURE__ */ new WeakMap();
673
+ const visited = /* @__PURE__ */ new WeakMap();
674
+ const fail3 = (path, message) => {
675
+ errors.push(new Error(`Cannot upgrade to OpenAPI 3.2 at ${path}: ${message}`));
676
+ };
677
+ const resolve = (ref, schemaReference = false) => {
678
+ if (typeof ref !== "string" || !ref.startsWith("#/")) {
679
+ return void 0;
680
+ }
681
+ try {
682
+ return parseJsonPointerSegments(decodeURIComponent(ref.slice(1))).reduce((value, key) => {
683
+ if (schemaReference && isObject2(value) && (value.$id !== void 0 || value.$schema !== void 0)) {
684
+ return void 0;
685
+ }
686
+ if (Array.isArray(value) && !/^(0|[1-9]\d*)$/.test(key)) {
687
+ return void 0;
688
+ }
689
+ if (!isObject2(value) && !Array.isArray(value) || !Object.hasOwn(value, key)) {
690
+ return void 0;
691
+ }
692
+ return own(value, key);
693
+ }, document);
694
+ } catch {
695
+ return void 0;
696
+ }
697
+ };
698
+ const repeatedVariables = (value, path) => {
699
+ if (typeof value !== "string") {
700
+ return;
701
+ }
702
+ const names = [...value.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]);
703
+ if (new Set(names).size !== names.length) {
704
+ fail3(path, "Template variables must not be repeated. Rename the repeated variable and define it separately.");
705
+ }
706
+ };
707
+ const requires = (schema2, name, seen = /* @__PURE__ */ new Set()) => {
708
+ if (schema2 === false) {
709
+ return true;
710
+ }
711
+ if (schema2 === true) {
712
+ return false;
713
+ }
714
+ if (!isObject2(schema2) || schema2.$id !== void 0 || schema2.$schema !== void 0) {
715
+ return void 0;
716
+ }
717
+ if (seen.has(schema2)) {
718
+ for (const ancestor of seen) {
719
+ cyclicRequired.add(ancestor);
720
+ }
721
+ return void 0;
722
+ }
723
+ const cached = requiredCache.get(schema2) ?? /* @__PURE__ */ new Map();
724
+ if (cached.has(name)) {
725
+ return cached.get(name);
726
+ }
727
+ if (++requiredWork.evaluations > 1e5) {
728
+ if (requiredWork.evaluations === 100001) {
729
+ fail3("#", "Discriminator requiredness analysis was truncated after 100,000 evaluations.");
730
+ }
731
+ return void 0;
732
+ }
733
+ const remember2 = (result) => {
734
+ if (result !== void 0 || !cyclicRequired.has(schema2)) {
735
+ cached.set(name, result);
736
+ requiredCache.set(schema2, cached);
737
+ }
738
+ return result;
739
+ };
740
+ if (Array.isArray(schema2.required) && schema2.required.includes(name)) {
741
+ return remember2(true);
742
+ }
743
+ const next = /* @__PURE__ */ new Set([...seen, schema2]);
744
+ const constraints = [];
745
+ if (schema2.$ref !== void 0) {
746
+ constraints.push(requires(resolve(schema2.$ref, true), name, next));
747
+ }
748
+ if (Array.isArray(schema2.allOf)) {
749
+ constraints.push(...schema2.allOf.map((item) => requires(item, name, next)));
750
+ }
751
+ for (const keyword of ["oneOf", "anyOf"]) {
752
+ if (Array.isArray(schema2[keyword])) {
753
+ const alternatives = schema2[keyword].map((item) => requires(item, name, next));
754
+ if (alternatives.every((value) => value === true)) {
755
+ constraints.push(true);
756
+ } else if (alternatives.every((value) => value === false)) {
757
+ constraints.push(false);
758
+ } else {
759
+ constraints.push(void 0);
760
+ }
761
+ }
762
+ }
763
+ if (constraints.includes(true)) {
764
+ return remember2(true);
765
+ }
766
+ if (constraints.includes(void 0) || ["if", "not", "$dynamicRef", "const", "enum", "minProperties", "dependentRequired", "dependentSchemas"].some((key) => key in schema2)) {
767
+ return remember2(void 0);
768
+ }
769
+ return remember2(false);
770
+ };
771
+ const validateXmlNames = (schema2, path, { inferredName, propertyName, dialect, ancestors = /* @__PURE__ */ new Set(), baseChanged = false }) => {
772
+ if (!isObject2(schema2) || ancestors.has(schema2) || (schema2.$schema ?? dialect) !== void 0) {
773
+ return;
774
+ }
775
+ const changedBase = baseChanged || schema2.$id !== void 0;
776
+ const context = [inferredName, propertyName, changedBase].join(":");
777
+ const completed = xmlCache.get(schema2) ?? /* @__PURE__ */ new Set();
778
+ if (completed.has(context)) {
779
+ return;
780
+ }
781
+ const xml = isObject2(schema2.xml) ? schema2.xml : {};
782
+ const defaultNodeType = schema2.$ref !== void 0 || schema2.$dynamicRef !== void 0 || schema2.type === "array" ? "none" : "element";
783
+ const wrappedNodeType = xml.wrapped === true ? "element" : defaultNodeType;
784
+ const nodeType = xml.nodeType ?? (xml.attribute === true ? "attribute" : wrappedNodeType);
785
+ if ((nodeType === "element" || nodeType === "attribute") && !inferredName && xml.name === void 0) {
786
+ fail3(path, "An inline XML element needs an explicit xml.name.");
787
+ }
788
+ const childContext = { dialect, ancestors: /* @__PURE__ */ new Set([...ancestors, schema2]), baseChanged: changedBase };
789
+ if (!changedBase && typeof schema2.$ref === "string") {
790
+ const target = resolve(schema2.$ref, true);
791
+ if (isObject2(target)) {
792
+ const segments2 = parseJsonPointerSegments(decodeURIComponent(schema2.$ref.slice(1)));
793
+ const componentRoot = segments2.length === 3 && segments2[0] === "components" && segments2[1] === "schemas";
794
+ const fromProperty = propertySchemas.has(target);
795
+ validateXmlNames(target, schema2.$ref, {
796
+ ...childContext,
797
+ inferredName: componentRoot || fromProperty,
798
+ propertyName: fromProperty
799
+ });
800
+ }
801
+ }
802
+ for (const keyword of ["allOf", "anyOf", "oneOf"]) {
803
+ const branches = schema2[keyword];
804
+ if (Array.isArray(branches)) {
805
+ branches.forEach((branch, index) => validateXmlNames(branch, path + "/" + keyword + "/" + index, {
806
+ ...childContext,
807
+ inferredName: false,
808
+ propertyName: false
809
+ }));
810
+ }
811
+ }
812
+ validateXmlNames(schema2.items, path + "/items", { ...childContext, inferredName: propertyName, propertyName });
813
+ if (Array.isArray(schema2.prefixItems)) {
814
+ schema2.prefixItems.forEach((item, index) => validateXmlNames(item, path + "/prefixItems/" + index, {
815
+ ...childContext,
816
+ inferredName: propertyName,
817
+ propertyName
818
+ }));
819
+ }
820
+ if (isObject2(schema2.properties)) {
821
+ for (const [name, property] of Object.entries(schema2.properties)) {
822
+ validateXmlNames(property, path + "/properties/" + escapeJsonPointer(name), {
823
+ ...childContext,
824
+ inferredName: true,
825
+ propertyName: true
826
+ });
827
+ }
828
+ }
829
+ completed.add(context);
830
+ xmlCache.set(schema2, completed);
831
+ };
832
+ const visit = (value, kind, path, dialect = document.jsonSchemaDialect, baseChanged = false) => {
833
+ if (!isObject2(value)) {
834
+ return;
835
+ }
836
+ const schemaDialect = kind === "schema" ? value.$schema ?? dialect : dialect;
837
+ const schemaBaseChanged = baseChanged || kind === "schema" && value.$id !== void 0;
838
+ const visitKey = `${kind}:${String(schemaDialect)}:${schemaBaseChanged}`;
839
+ const seen = visited.get(value) ?? /* @__PURE__ */ new Set();
840
+ if (seen.has(visitKey)) {
841
+ return;
842
+ }
843
+ seen.add(visitKey);
844
+ visited.set(value, seen);
845
+ const child = (key, type) => visit(own(value, key), type, `${path}/${escapeJsonPointer(key)}`, schemaDialect, schemaBaseChanged);
846
+ const list = (key, type) => {
847
+ const items = own(value, key);
848
+ if (Array.isArray(items)) {
849
+ items.forEach((item, index) => visit(item, type, `${path}/${key}/${index}`, schemaDialect, schemaBaseChanged));
850
+ }
851
+ };
852
+ const map = (key, type) => {
853
+ const items = own(value, key);
854
+ if (isObject2(items)) {
855
+ for (const [name, item] of Object.entries(items)) {
856
+ if (key === "responses" && name.startsWith("x-")) {
857
+ continue;
858
+ }
859
+ if (kind === "schema" && key === "properties") {
860
+ markPropertySchema(item);
861
+ }
862
+ visit(item, type, `${path}/${key}/${escapeJsonPointer(name)}`, schemaDialect, schemaBaseChanged);
863
+ }
864
+ }
865
+ };
866
+ if (kind === "schema") {
867
+ if (schemaDialect !== void 0) {
868
+ return;
869
+ }
870
+ const xml = own(value, "xml");
871
+ if (isObject2(xml)) {
872
+ if (xml.wrapped === true && xml.attribute === true) {
873
+ fail3(`${path}/xml`, "wrapped and attribute cannot both be true.");
874
+ }
875
+ if (xml.wrapped === true || xml.attribute === true) {
876
+ xml.nodeType = xml.attribute === true ? "attribute" : "element";
877
+ delete xml.wrapped;
878
+ delete xml.attribute;
879
+ }
880
+ }
881
+ if (!schemaBaseChanged && value.$ref !== void 0) {
882
+ visit(resolve(value.$ref, true), "schema", String(value.$ref), schemaDialect);
883
+ }
884
+ const discriminator = value.discriminator;
885
+ if (isObject2(discriminator) && typeof discriminator.propertyName === "string" && discriminator.defaultMapping === void 0 && !schemaBaseChanged && requires(value, discriminator.propertyName) === false) {
886
+ fail3(`${path}/discriminator`, "An optional discriminating property needs an explicit defaultMapping.");
887
+ }
888
+ for (const key of schemaMaps) {
889
+ map(key, "schema");
890
+ }
891
+ for (const key of schemaArrays) {
892
+ list(key, "schema");
893
+ }
894
+ for (const key of schemaSingles) {
895
+ child(key, "schema");
896
+ }
897
+ return;
898
+ }
899
+ if (value.$ref !== void 0) {
900
+ visit(resolve(value.$ref), kind, String(value.$ref), schemaDialect);
901
+ }
902
+ switch (kind) {
903
+ case "document": {
904
+ const paths = own(value, "paths");
905
+ if (isObject2(paths)) {
906
+ for (const [name, item] of Object.entries(paths)) {
907
+ if (!name.startsWith("/")) {
908
+ continue;
909
+ }
910
+ const location = `${path}/paths/${escapeJsonPointer(name)}`;
911
+ repeatedVariables(name, location);
912
+ visit(item, "pathItem", location);
913
+ }
914
+ }
915
+ map("webhooks", "pathItem");
916
+ list("servers", "server");
917
+ const componentObjects = own(value, "components");
918
+ if (isObject2(componentObjects)) {
919
+ const components = {
920
+ schemas: "schema",
921
+ parameters: "parameter",
922
+ headers: "header",
923
+ requestBodies: "body",
924
+ responses: "response",
925
+ callbacks: "callback",
926
+ pathItems: "pathItem"
927
+ };
928
+ for (const [key, type] of Object.entries(components)) {
929
+ const entries = own(componentObjects, key);
930
+ if (isObject2(entries)) {
931
+ for (const [name, item] of Object.entries(entries)) {
932
+ visit(item, type, `${path}/components/${key}/${escapeJsonPointer(name)}`);
933
+ }
934
+ }
935
+ }
936
+ }
937
+ break;
938
+ }
939
+ case "pathItem":
940
+ for (const method of ["get", "put", "post", "delete", "options", "head", "patch", "trace"]) {
941
+ child(method, "operation");
942
+ }
943
+ list("parameters", "parameter");
944
+ list("servers", "server");
945
+ break;
946
+ case "operation":
947
+ if (Array.isArray(value.tags)) {
948
+ for (const tag of value.tags) {
949
+ if (typeof tag === "string") {
950
+ operationTags.add(tag);
951
+ }
952
+ }
953
+ }
954
+ list("parameters", "parameter");
955
+ list("servers", "server");
956
+ child("requestBody", "body");
957
+ map("responses", "response");
958
+ map("callbacks", "callback");
959
+ break;
960
+ case "callback":
961
+ for (const [name, item] of Object.entries(value)) {
962
+ if (!name.startsWith("x-") && name !== "$ref") {
963
+ visit(item, "pathItem", `${path}/${escapeJsonPointer(name)}`, schemaDialect, schemaBaseChanged);
964
+ }
965
+ }
966
+ break;
967
+ case "parameter":
968
+ if (value.in === "path" || value.in === "cookie") {
969
+ delete value.allowReserved;
970
+ }
971
+ child("schema", "schema");
972
+ map("content", "media");
973
+ break;
974
+ case "header":
975
+ child("schema", "schema");
976
+ map("content", "media");
977
+ break;
978
+ case "response":
979
+ map("headers", "header");
980
+ map("content", "media");
981
+ break;
982
+ case "body":
983
+ map("content", "media");
984
+ break;
985
+ case "media":
986
+ if (/\/(?:[^;]+\+)?xml(?:\s*;|$)/i.test(path.slice(path.lastIndexOf("/") + 1).replace(/~1/g, "/"))) {
987
+ xmlRoots.push({ schema: value.schema, path: `${path}/schema`, dialect: schemaDialect });
988
+ }
989
+ child("schema", "schema");
990
+ map("encoding", "encoding");
991
+ break;
992
+ case "encoding":
993
+ map("headers", "header");
994
+ break;
995
+ case "server":
996
+ repeatedVariables(value.url, `${path}/url`);
997
+ break;
998
+ }
999
+ };
1000
+ visit(document, "document", "#");
1001
+ for (const { schema: schema2, path, dialect } of xmlRoots) {
1002
+ validateXmlNames(schema2, path, { inferredName: false, propertyName: false, dialect });
1003
+ }
1004
+ if (errors.length > 0) {
1005
+ throw new UpgradeIncompatibilityError(errors);
1006
+ }
1007
+ return operationTags;
1008
+ };
1009
+
1010
+ // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/3.1-to-3.2/migrate-tag-groups.js
1011
+ var migrateTagGroups = (document, operationTags) => {
1012
+ const groups = document["x-tagGroups"];
1013
+ if (!Array.isArray(groups) || groups.length === 0) {
1014
+ return;
1015
+ }
1016
+ if (document.tags !== void 0 && !Array.isArray(document.tags)) {
1017
+ return;
1018
+ }
1019
+ const tags = document.tags ?? [];
1020
+ if (!tags.every((tag) => isObject2(tag) && typeof tag.name === "string")) {
1021
+ return;
1022
+ }
1023
+ const existing = new Map(tags.map((tag) => [tag.name, tag]));
1024
+ const parents = /* @__PURE__ */ new Set();
1025
+ const children = /* @__PURE__ */ new Set();
1026
+ for (const group of groups) {
1027
+ if (!isObject2(group) || typeof group.name !== "string" || !group.name || !Array.isArray(group.tags) || !group.tags.every((name) => typeof name === "string") || Object.keys(group).some((key) => key !== "name" && key !== "tags") || parents.has(group.name) || existing.has(group.name) || operationTags.has(group.name)) {
1028
+ return;
1029
+ }
1030
+ parents.add(group.name);
1031
+ for (const name of group.tags) {
1032
+ if (children.has(name) || existing.get(name)?.parent !== void 0) {
1033
+ return;
1034
+ }
1035
+ children.add(name);
1036
+ }
1037
+ }
1038
+ if ([...parents].some((name) => children.has(name)) || existing.size !== tags.length) {
1039
+ return;
1040
+ }
1041
+ const result = [];
1042
+ for (const group of groups) {
1043
+ result.push({ name: group.name, kind: "nav" });
1044
+ for (const name of group.tags) {
1045
+ result.push({ ...existing.get(name) ?? { name }, parent: group.name });
1046
+ }
1047
+ }
1048
+ document.tags = [...result, ...tags.filter((tag) => !children.has(tag.name))];
1049
+ };
1050
+
1051
+ // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/3.1-to-3.2/upgrade-from-three-one-to-three-two.js
1052
+ var isThreeOneDocument = (document) => {
1053
+ if (!isObject2(document) || typeof document.openapi !== "string") {
1054
+ return false;
1055
+ }
1056
+ if (/^3\.1\.\d+$/.test(document.openapi)) {
1057
+ return true;
1058
+ }
1059
+ if (/^3\.1(?:\D|$)/.test(document.openapi)) {
1060
+ throw new Error(`Cannot upgrade to OpenAPI 3.2: invalid OpenAPI version "${document.openapi}". Expected 3.1.x with a numeric patch version.`);
1061
+ }
1062
+ return false;
1063
+ };
1064
+ var migrateThreeOneToThreeTwo = (document) => {
1065
+ if (!isThreeOneDocument(document)) {
1066
+ return document;
1067
+ }
1068
+ const operationTags = migrateObjects(document);
1069
+ migrateTagGroups(document, operationTags);
1070
+ document.openapi = "3.2.0";
1071
+ return document;
1072
+ };
1073
+
1074
+ // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/helpers/traverse.js
1075
+ function traverse(content, transform, path = []) {
1076
+ const result = {};
1077
+ for (const [key, value] of Object.entries(content)) {
1078
+ const currentPath = [...path, key];
1079
+ if (Array.isArray(value)) {
1080
+ result[key] = value.map((item, index) => {
1081
+ if (typeof item === "object" && !Array.isArray(item) && item !== null) {
1082
+ return traverse(item, transform, [...currentPath, index.toString()]);
1083
+ }
1084
+ return item;
1085
+ });
1086
+ continue;
1087
+ }
1088
+ if (isObjectLike(value)) {
1089
+ result[key] = traverse(value, transform, currentPath);
1090
+ continue;
1091
+ }
1092
+ result[key] = value;
1093
+ }
1094
+ return transform(result, path);
1095
+ }
1096
+
1097
+ // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/2.0-to-3.0/upgrade-from-two-to-three.js
1098
+ var DEFAULT_MEDIA_TYPE = "application/json";
1099
+ function extractXExampleExtensions(obj) {
1100
+ const xExample = obj["x-example"];
1101
+ const xExamples = obj["x-examples"];
1102
+ delete obj["x-example"];
1103
+ delete obj["x-examples"];
1104
+ return { xExample, xExamples };
1105
+ }
1106
+ function isNonEmptyObject(value) {
1107
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length > 0;
1108
+ }
1109
+ function isNamedExamplesCollection(value) {
1110
+ return isNonEmptyObject(value) && Object.values(value).every((v) => typeof v === "object" && v !== null && !Array.isArray(v));
1111
+ }
1112
+ function isEmptySchema(schema2) {
1113
+ if (!isObjectLike(schema2)) {
1114
+ return true;
1115
+ }
1116
+ const s = schema2;
1117
+ const substantiveValidationKeywords = [
1118
+ "enum",
1119
+ "const",
1120
+ "not",
1121
+ "format",
1122
+ "multipleOf",
1123
+ "maximum",
1124
+ "exclusiveMaximum",
1125
+ "minimum",
1126
+ "exclusiveMinimum",
1127
+ "maxLength",
1128
+ "minLength",
1129
+ "pattern",
1130
+ "maxItems",
1131
+ "minItems",
1132
+ "uniqueItems",
1133
+ "maxProperties",
1134
+ "minProperties",
1135
+ "required"
1136
+ ];
1137
+ if (s.allOf || s.oneOf || s.anyOf || s.items || s.$ref || "additionalProperties" in s || substantiveValidationKeywords.some((key) => key in s)) {
1138
+ return false;
1139
+ }
1140
+ if (typeof s.properties === "object" && s.properties !== null && Object.keys(s.properties).length > 0) {
1141
+ return false;
1142
+ }
1143
+ return true;
1144
+ }
1145
+ function removeEmptySchemaOnlyContentEntries(content) {
1146
+ const keys = Object.keys(content);
1147
+ const hasEntryWithExample = keys.some((key) => {
1148
+ const entry = content[key];
1149
+ return isObjectLike(entry) && (entry.example !== void 0 || entry.examples !== void 0);
1150
+ });
1151
+ if (!hasEntryWithExample) {
1152
+ return;
1153
+ }
1154
+ for (const key of keys) {
1155
+ const entry = content[key];
1156
+ if (!isObjectLike(entry))
1157
+ continue;
1158
+ const hasExample = entry.example !== void 0 || entry.examples !== void 0;
1159
+ const hasOnlySchema = entry.schema !== void 0 && !hasExample && Object.keys(entry).length === 1;
1160
+ if (hasOnlySchema && isEmptySchema(entry.schema)) {
1161
+ delete content[key];
1162
+ }
1163
+ }
1164
+ }
1165
+ var EXAMPLE_OBJECT_PROPERTIES = /* @__PURE__ */ new Set(["summary", "description", "value", "externalValue"]);
1166
+ function isExampleObject(value) {
1167
+ if (typeof value !== "object" || value === null) {
1168
+ return false;
1169
+ }
1170
+ const obj = value;
1171
+ const hasValueOrExternalValue = "value" in obj || "externalValue" in obj;
1172
+ const onlyHasAllowedProperties = Object.keys(obj).every((key) => EXAMPLE_OBJECT_PROPERTIES.has(key));
1173
+ return hasValueOrExternalValue && onlyHasAllowedProperties;
1174
+ }
1175
+ function wrapAsExampleObject(value) {
1176
+ if (isExampleObject(value)) {
1177
+ return value;
1178
+ }
1179
+ return { value };
1180
+ }
1181
+ var MEDIA_TYPE_KEY_PATTERN = /^[a-zA-Z0-9*+.-]+\/[a-zA-Z0-9*+.+-]+$/;
1182
+ function isMediaTypeKey(key) {
1183
+ return MEDIA_TYPE_KEY_PATTERN.test(key);
1184
+ }
1185
+ function transformXExampleToExamples(xExample) {
1186
+ return Object.entries(xExample).reduce((acc, [key, value]) => {
1187
+ acc[key] = { value };
1188
+ return acc;
1189
+ }, {});
1190
+ }
1191
+ var upgradeFlow = (flow) => {
1192
+ switch (flow) {
1193
+ case "application":
1194
+ return "clientCredentials";
1195
+ case "accessCode":
1196
+ return "authorizationCode";
1197
+ case "implicit":
1198
+ return "implicit";
1199
+ case "password":
1200
+ return "password";
1201
+ default:
1202
+ return flow;
1203
+ }
1204
+ };
1205
+ function upgradeFromTwoToThree(originalSpecification) {
1206
+ let document = originalSpecification;
1207
+ if (document !== null && typeof document === "object" && typeof document.swagger === "string" && document.swagger?.startsWith("2.0")) {
1208
+ document.openapi = "3.0.4";
1209
+ delete document.swagger;
1210
+ } else {
1211
+ return document;
1212
+ }
1213
+ if (document.host) {
1214
+ const schemes = Array.isArray(document.schemes) && document.schemes?.length ? document.schemes : ["http"];
1215
+ document.servers = schemes.map((scheme) => ({
1216
+ url: `${scheme}://${document.host}${document.basePath ?? ""}`
1217
+ }));
1218
+ delete document.basePath;
1219
+ delete document.schemes;
1220
+ delete document.host;
1221
+ } else if (document.basePath) {
1222
+ document.servers = [{ url: document.basePath }];
1223
+ delete document.basePath;
1224
+ }
1225
+ if (document.definitions) {
1226
+ for (const schema2 of Object.values(document.definitions)) {
1227
+ migrateSchemaNullability(schema2);
1228
+ }
1229
+ document.components = Object.assign({}, document.components, {
1230
+ schemas: document.definitions
1231
+ });
1232
+ delete document.definitions;
1233
+ document = traverse(document, (schema2) => {
1234
+ if (typeof schema2.$ref === "string" && schema2.$ref.startsWith("#/definitions/")) {
1235
+ schema2.$ref = schema2.$ref.replace(/^#\/definitions\//, "#/components/schemas/");
1236
+ }
1237
+ return schema2;
1238
+ });
1239
+ }
1240
+ document = traverse(document, (schema2) => {
1241
+ if (schema2.type === "file") {
1242
+ schema2.type = "string";
1243
+ schema2.format = "binary";
1244
+ }
1245
+ return schema2;
1246
+ });
1247
+ if (Object.hasOwn(document, "parameters")) {
1248
+ document = traverse(document, (schema2) => {
1249
+ if (typeof schema2.$ref === "string" && schema2.$ref.startsWith("#/parameters/")) {
1250
+ const schemaName = schema2.$ref.split("/")[2];
1251
+ if (!schemaName) {
1252
+ return schema2;
1253
+ }
1254
+ const param = isObjectLike(document.parameters) && schemaName in document.parameters ? document.parameters[schemaName] : void 0;
1255
+ if (param && typeof param === "object" && "in" in param && (param.in === "body" || param.in === "formData")) {
1256
+ schema2.$ref = schema2.$ref.replace(/^#\/parameters\//, "#/components/requestBodies/");
1257
+ } else {
1258
+ schema2.$ref = schema2.$ref.replace(/^#\/parameters\//, "#/components/parameters/");
1259
+ }
1260
+ }
1261
+ return schema2;
1262
+ });
1263
+ document.components ??= {};
1264
+ const params = {};
1265
+ const bodyParams = {};
1266
+ const parameters = isObjectLike(document.parameters) ? document.parameters : {};
1267
+ for (const [name, param] of Object.entries(parameters)) {
1268
+ if (param && typeof param === "object") {
1269
+ if ("$ref" in param) {
1270
+ const convertedParam = transformParameterObject(param);
1271
+ params[name] = convertedParam;
1272
+ } else if ("in" in param) {
1273
+ if (param.in === "body") {
1274
+ bodyParams[name] = migrateBodyParameter(param, document.consumes ?? [DEFAULT_MEDIA_TYPE]);
1275
+ } else if (param.in === "formData") {
1276
+ bodyParams[name] = migrateFormDataParameter([param], document.consumes);
1277
+ } else {
1278
+ const convertedParam = transformParameterObject(param);
1279
+ params[name] = convertedParam;
1280
+ }
1281
+ }
1282
+ }
1283
+ }
1284
+ if (Object.keys(params).length > 0) {
1285
+ ;
1286
+ document.components.parameters = params;
1287
+ }
1288
+ if (Object.keys(bodyParams).length > 0) {
1289
+ ;
1290
+ document.components.requestBodies = bodyParams;
1291
+ }
1292
+ delete document.parameters;
1293
+ }
1294
+ if (Object.hasOwn(document, "responses") && typeof document.responses === "object" && document.responses !== null) {
1295
+ document = traverse(document, (schema2) => {
1296
+ if (typeof schema2.$ref === "string" && schema2.$ref.startsWith("#/responses/")) {
1297
+ schema2.$ref = schema2.$ref.replace(/^#\/responses\//, "#/components/responses/");
1298
+ }
1299
+ return schema2;
1300
+ });
1301
+ document.components ??= {};
1302
+ const migratedResponses = {};
1303
+ const responses = document.responses;
1304
+ for (const [name, response] of Object.entries(responses)) {
1305
+ if (isObjectLike(response)) {
1306
+ if ("$ref" in response) {
1307
+ migratedResponses[name] = response;
1308
+ } else {
1309
+ const responseObj = response;
1310
+ const produces = document.produces ?? [DEFAULT_MEDIA_TYPE];
1311
+ if (responseObj.schema) {
1312
+ migrateSchemaNullability(responseObj.schema);
1313
+ if (typeof responseObj.content !== "object") {
1314
+ responseObj.content = {};
1315
+ }
1316
+ for (const type of produces) {
1317
+ ;
1318
+ responseObj.content[type] = {
1319
+ schema: responseObj.schema
1320
+ };
1321
+ }
1322
+ delete responseObj.schema;
1323
+ }
1324
+ if (responseObj.examples && typeof responseObj.examples === "object") {
1325
+ if (typeof responseObj.content !== "object") {
1326
+ responseObj.content = {};
1327
+ }
1328
+ const defaultMediaType = produces[0] ?? DEFAULT_MEDIA_TYPE;
1329
+ for (const [key, exampleValue] of Object.entries(responseObj.examples)) {
1330
+ if (isMediaTypeKey(key)) {
1331
+ if (typeof responseObj.content[key] !== "object") {
1332
+ ;
1333
+ responseObj.content[key] = {};
1334
+ }
1335
+ ;
1336
+ responseObj.content[key].example = exampleValue;
1337
+ } else {
1338
+ if (typeof responseObj.content[defaultMediaType] !== "object") {
1339
+ ;
1340
+ responseObj.content[defaultMediaType] = {};
1341
+ }
1342
+ const mediaEntry = responseObj.content[defaultMediaType];
1343
+ if (typeof mediaEntry.examples !== "object") {
1344
+ mediaEntry.examples = {};
1345
+ }
1346
+ ;
1347
+ mediaEntry.examples[key] = wrapAsExampleObject(exampleValue);
1348
+ }
1349
+ }
1350
+ delete responseObj.examples;
1351
+ }
1352
+ if (responseObj.content && typeof responseObj.content === "object") {
1353
+ removeEmptySchemaOnlyContentEntries(responseObj.content);
1354
+ }
1355
+ if (isObjectLike(responseObj.headers)) {
1356
+ responseObj.headers = Object.entries(responseObj.headers).reduce((acc, [headerName, header]) => {
1357
+ if (header && typeof header === "object") {
1358
+ return {
1359
+ [headerName]: transformResponseHeader(header),
1360
+ ...acc
1361
+ };
1362
+ }
1363
+ return acc;
1364
+ }, {});
1365
+ }
1366
+ migratedResponses[name] = responseObj;
1367
+ }
1368
+ }
1369
+ }
1370
+ if (Object.keys(migratedResponses).length > 0) {
1371
+ ;
1372
+ document.components.responses = migratedResponses;
1373
+ }
1374
+ delete document.responses;
1375
+ }
1376
+ if (typeof document.paths === "object") {
1377
+ for (const path in document.paths) {
1378
+ if (Object.hasOwn(document.paths, path)) {
1379
+ const pathItem = isObjectLike(document.paths) && path in document.paths ? document.paths[path] : void 0;
1380
+ if (!pathItem || typeof pathItem !== "object") {
1381
+ continue;
1382
+ }
1383
+ let requestBodyObject;
1384
+ for (const methodOrParameters in pathItem) {
1385
+ if (methodOrParameters === "parameters" && Object.hasOwn(pathItem, methodOrParameters)) {
1386
+ const pathItemParameters = migrateParameters(pathItem.parameters, document.consumes ?? [DEFAULT_MEDIA_TYPE]);
1387
+ pathItem.parameters = pathItemParameters.parameters;
1388
+ requestBodyObject = pathItemParameters.requestBody;
1389
+ } else if (Object.hasOwn(pathItem, methodOrParameters)) {
1390
+ const operationItem = pathItem[methodOrParameters];
1391
+ if (requestBodyObject) {
1392
+ operationItem.requestBody = requestBodyObject;
1393
+ }
1394
+ if (operationItem.parameters) {
1395
+ const migrationResult = migrateParameters(operationItem.parameters, operationItem.consumes ?? document.consumes ?? [DEFAULT_MEDIA_TYPE]);
1396
+ operationItem.parameters = migrationResult.parameters;
1397
+ if (migrationResult.requestBody) {
1398
+ operationItem.requestBody = migrationResult.requestBody;
1399
+ }
1400
+ }
1401
+ delete operationItem.consumes;
1402
+ if (operationItem.responses) {
1403
+ for (const response in operationItem.responses) {
1404
+ if (Object.hasOwn(operationItem.responses, response)) {
1405
+ const responseItem = operationItem.responses[response];
1406
+ if (responseItem.headers && typeof responseItem.headers === "object") {
1407
+ responseItem.headers = Object.entries(responseItem.headers).reduce((acc, [name, header]) => {
1408
+ if (header && typeof header === "object") {
1409
+ return {
1410
+ [name]: transformResponseHeader(header),
1411
+ ...acc
1412
+ };
1413
+ }
1414
+ return acc;
1415
+ }, {});
1416
+ }
1417
+ if (responseItem.schema) {
1418
+ migrateSchemaNullability(responseItem.schema);
1419
+ const produces = document.produces ?? operationItem.produces ?? [DEFAULT_MEDIA_TYPE];
1420
+ if (typeof responseItem.content !== "object") {
1421
+ responseItem.content = {};
1422
+ }
1423
+ for (const type of produces) {
1424
+ responseItem.content[type] = {
1425
+ schema: responseItem.schema
1426
+ };
1427
+ }
1428
+ delete responseItem.schema;
1429
+ }
1430
+ if (responseItem.examples && typeof responseItem.examples === "object") {
1431
+ if (typeof responseItem.content !== "object") {
1432
+ responseItem.content = {};
1433
+ }
1434
+ const produces = document.produces ?? operationItem.produces ?? [DEFAULT_MEDIA_TYPE];
1435
+ const defaultMediaType = produces[0] ?? DEFAULT_MEDIA_TYPE;
1436
+ for (const [key, exampleValue] of Object.entries(responseItem.examples)) {
1437
+ if (isMediaTypeKey(key)) {
1438
+ if (typeof responseItem.content[key] !== "object") {
1439
+ responseItem.content[key] = {};
1440
+ }
1441
+ responseItem.content[key].example = exampleValue;
1442
+ } else {
1443
+ if (typeof responseItem.content[defaultMediaType] !== "object") {
1444
+ responseItem.content[defaultMediaType] = {};
1445
+ }
1446
+ const mediaEntry = responseItem.content[defaultMediaType];
1447
+ if (typeof mediaEntry.examples !== "object") {
1448
+ mediaEntry.examples = {};
1449
+ }
1450
+ mediaEntry.examples[key] = wrapAsExampleObject(exampleValue);
1451
+ }
1452
+ }
1453
+ delete responseItem.examples;
1454
+ }
1455
+ if (responseItem.content && typeof responseItem.content === "object") {
1456
+ removeEmptySchemaOnlyContentEntries(responseItem.content);
1457
+ }
1458
+ }
1459
+ }
1460
+ }
1461
+ delete operationItem.produces;
1462
+ if (operationItem.parameters?.length === 0) {
1463
+ delete operationItem.parameters;
1464
+ }
1465
+ }
1466
+ }
1467
+ }
1468
+ }
1469
+ }
1470
+ if (document.securityDefinitions) {
1471
+ if (typeof document.components !== "object" || document.components === null) {
1472
+ document.components = {};
1473
+ }
1474
+ if (document.components && typeof document.components === "object") {
1475
+ Object.assign(document.components, { securitySchemes: {} });
1476
+ }
1477
+ for (const [key, securityScheme] of Object.entries(document.securityDefinitions)) {
1478
+ if (typeof securityScheme === "object") {
1479
+ if ("type" in securityScheme && securityScheme.type === "oauth2") {
1480
+ const { flow, authorizationUrl, tokenUrl, scopes } = securityScheme;
1481
+ if (document.components && typeof document.components === "object" && "securitySchemes" in document.components && document.components.securitySchemes) {
1482
+ Object.assign(document.components.securitySchemes, {
1483
+ [key]: {
1484
+ type: "oauth2",
1485
+ flows: {
1486
+ [upgradeFlow(flow || "implicit")]: Object.assign({}, authorizationUrl && { authorizationUrl }, tokenUrl && { tokenUrl }, scopes && { scopes })
1487
+ }
1488
+ }
1489
+ });
1490
+ }
1491
+ } else if ("type" in securityScheme && securityScheme.type === "basic") {
1492
+ if (document.components && typeof document.components === "object" && "securitySchemes" in document.components && document.components.securitySchemes) {
1493
+ Object.assign(document.components.securitySchemes, {
1494
+ [key]: {
1495
+ type: "http",
1496
+ scheme: "basic"
1497
+ }
1498
+ });
1499
+ }
1500
+ } else {
1501
+ if (document.components && typeof document.components === "object" && "securitySchemes" in document.components && document.components.securitySchemes) {
1502
+ Object.assign(document.components.securitySchemes, {
1503
+ [key]: securityScheme
1504
+ });
1505
+ }
1506
+ }
1507
+ }
1508
+ }
1509
+ delete document.securityDefinitions;
1510
+ }
1511
+ delete document.consumes;
1512
+ delete document.produces;
1513
+ return document;
1514
+ }
1515
+ var migrateSchemaNullability = (schema2) => {
1516
+ if (!isObjectLike(schema2)) {
1517
+ return;
1518
+ }
1519
+ if (typeof schema2["x-nullable"] === "boolean") {
1520
+ if (schema2["x-nullable"]) {
1521
+ schema2.nullable = true;
1522
+ }
1523
+ delete schema2["x-nullable"];
1524
+ }
1525
+ if (isObjectLike(schema2.properties)) {
1526
+ for (const property of Object.values(schema2.properties)) {
1527
+ migrateSchemaNullability(property);
1528
+ }
1529
+ }
1530
+ migrateSchemaNullability(schema2.items);
1531
+ migrateSchemaNullability(schema2.additionalProperties);
1532
+ if (Array.isArray(schema2.allOf)) {
1533
+ for (const member of schema2.allOf) {
1534
+ migrateSchemaNullability(member);
1535
+ }
1536
+ }
1537
+ };
1538
+ function transformItemsObject(obj) {
1539
+ const schemaProperties = [
1540
+ "type",
1541
+ "format",
1542
+ "default",
1543
+ "items",
1544
+ "maximum",
1545
+ "exclusiveMaximum",
1546
+ "minimum",
1547
+ "exclusiveMinimum",
1548
+ "maxLength",
1549
+ "minLength",
1550
+ "pattern",
1551
+ "maxItems",
1552
+ "minItems",
1553
+ "uniqueItems",
1554
+ "enum",
1555
+ "multipleOf",
1556
+ "x-nullable"
1557
+ ];
1558
+ const schema2 = schemaProperties.reduce((acc, property) => {
1559
+ if (Object.hasOwn(obj, property)) {
1560
+ acc[property] = obj[property];
1561
+ delete obj[property];
1562
+ }
1563
+ return acc;
1564
+ }, {});
1565
+ migrateSchemaNullability(schema2);
1566
+ return schema2;
1567
+ }
1568
+ function getParameterLocation(location) {
1569
+ if (location === "formData") {
1570
+ throw new Error("Encountered a formData parameter which should have been filtered out by the caller");
1571
+ }
1572
+ if (location === "body") {
1573
+ throw new Error("Encountered a body parameter which should have been filtered out by the caller");
1574
+ }
1575
+ return location;
1576
+ }
1577
+ function transformParameterObject(parameter) {
1578
+ if (Object.hasOwn(parameter, "$ref") && typeof parameter.$ref === "string") {
1579
+ return {
1580
+ $ref: parameter.$ref
1581
+ };
1582
+ }
1583
+ const serializationStyle = getParameterSerializationStyle(parameter);
1584
+ const schema2 = transformItemsObject(parameter);
1585
+ const { xExample, xExamples } = extractXExampleExtensions(parameter);
1586
+ if (isNonEmptyObject(xExample)) {
1587
+ parameter.examples = transformXExampleToExamples(xExample);
1588
+ } else if (isNonEmptyObject(xExamples)) {
1589
+ parameter.examples = Object.entries(xExamples).reduce((acc, [key, exampleValue]) => {
1590
+ acc[key] = wrapAsExampleObject(exampleValue);
1591
+ return acc;
1592
+ }, {});
1593
+ }
1594
+ delete parameter.collectionFormat;
1595
+ delete parameter.default;
1596
+ if (!parameter.in) {
1597
+ throw new Error('Parameter object must have an "in" property');
1598
+ }
1599
+ return {
1600
+ schema: schema2,
1601
+ ...serializationStyle,
1602
+ ...parameter,
1603
+ in: getParameterLocation(parameter.in)
1604
+ };
1605
+ }
1606
+ function transformResponseHeader(header) {
1607
+ if (Object.hasOwn(header, "$ref") && typeof header.$ref === "string") {
1608
+ return {
1609
+ $ref: header.$ref
1610
+ };
1611
+ }
1612
+ const schema2 = transformItemsObject(header);
1613
+ return {
1614
+ ...header,
1615
+ schema: schema2
1616
+ };
1617
+ }
1618
+ var querySerialization = {
1619
+ ssv: {
1620
+ style: "spaceDelimited",
1621
+ explode: false
1622
+ },
1623
+ pipes: {
1624
+ style: "pipeDelimited",
1625
+ explode: false
1626
+ },
1627
+ multi: {
1628
+ style: "form",
1629
+ explode: true
1630
+ },
1631
+ csv: {
1632
+ style: "form",
1633
+ explode: false
1634
+ },
1635
+ tsv: {}
1636
+ };
1637
+ var pathAndHeaderSerialization = {
1638
+ ssv: {},
1639
+ pipes: {},
1640
+ multi: {},
1641
+ csv: {
1642
+ style: "simple",
1643
+ explode: false
1644
+ },
1645
+ tsv: {}
1646
+ };
1647
+ var serializationStyles = {
1648
+ header: pathAndHeaderSerialization,
1649
+ query: querySerialization,
1650
+ path: pathAndHeaderSerialization
1651
+ };
1652
+ function getParameterSerializationStyle(parameter) {
1653
+ if (parameter.type !== "array" || !(parameter.in === "query" || parameter.in === "path" || parameter.in === "header")) {
1654
+ return {};
1655
+ }
1656
+ const collectionFormat = parameter.collectionFormat ?? "csv";
1657
+ if (parameter.in in serializationStyles && collectionFormat in serializationStyles[parameter.in]) {
1658
+ return serializationStyles[parameter.in][collectionFormat];
1659
+ }
1660
+ return {};
1661
+ }
1662
+ function getFormDataEncoding(parameter) {
1663
+ if (parameter.type !== "array" || typeof parameter.collectionFormat !== "string") {
1664
+ return void 0;
1665
+ }
1666
+ const encoding = querySerialization[parameter.collectionFormat];
1667
+ if (!encoding || Object.keys(encoding).length === 0) {
1668
+ return void 0;
1669
+ }
1670
+ return encoding;
1671
+ }
1672
+ function migrateBodyParameter(bodyParameter, consumes) {
1673
+ const { xExample, xExamples } = extractXExampleExtensions(bodyParameter);
1674
+ delete bodyParameter.name;
1675
+ delete bodyParameter.in;
1676
+ const { schema: schema2, ...requestBody } = bodyParameter;
1677
+ migrateSchemaNullability(schema2);
1678
+ const requestBodyObject = {
1679
+ content: {},
1680
+ ...requestBody
1681
+ };
1682
+ if (requestBodyObject.content) {
1683
+ for (const type of consumes) {
1684
+ requestBodyObject.content[type] = {
1685
+ schema: schema2
1686
+ };
1687
+ if (isNonEmptyObject(xExamples) && type in xExamples) {
1688
+ const examples = xExamples[type];
1689
+ const isExamplesCollection = isNonEmptyObject(examples) && Object.values(examples).every((example) => isExampleObject(example));
1690
+ if (isExamplesCollection) {
1691
+ requestBodyObject.content[type].examples = examples;
1692
+ } else if (isNamedExamplesCollection(examples)) {
1693
+ requestBodyObject.content[type].examples = Object.entries(examples).reduce((acc, [key, exampleValue]) => {
1694
+ acc[key] = wrapAsExampleObject(exampleValue);
1695
+ return acc;
1696
+ }, {});
1697
+ } else {
1698
+ requestBodyObject.content[type].examples = {
1699
+ default: wrapAsExampleObject(examples)
1700
+ };
1701
+ }
1702
+ } else if (isNonEmptyObject(xExamples) && !Object.keys(xExamples).some(isMediaTypeKey)) {
1703
+ requestBodyObject.content[type].examples = Object.entries(xExamples).reduce((acc, [key, exampleValue]) => {
1704
+ acc[key] = wrapAsExampleObject(exampleValue);
1705
+ return acc;
1706
+ }, {});
1707
+ }
1708
+ if (!requestBodyObject.content[type].examples && isNonEmptyObject(xExample) && type in xExample) {
1709
+ requestBodyObject.content[type].example = xExample[type];
1710
+ }
1711
+ }
1712
+ }
1713
+ return requestBodyObject;
1714
+ }
1715
+ function migrateFormDataParameter(parameters, consumes = ["multipart/form-data"]) {
1716
+ const requestBodyObject = {
1717
+ content: {}
1718
+ };
1719
+ const filtered = consumes.filter((type) => type === "multipart/form-data" || type === "application/x-www-form-urlencoded");
1720
+ const contentTypes = filtered.length > 0 ? filtered : ["multipart/form-data"];
1721
+ if (requestBodyObject.content) {
1722
+ for (const contentType of contentTypes) {
1723
+ requestBodyObject.content[contentType] = {
1724
+ schema: {
1725
+ type: "object",
1726
+ properties: {},
1727
+ required: []
1728
+ // Initialize required array
1729
+ }
1730
+ };
1731
+ const formContent = requestBodyObject.content?.[contentType];
1732
+ if (formContent?.schema && typeof formContent.schema === "object" && "properties" in formContent.schema) {
1733
+ for (const param of parameters) {
1734
+ if (param.name && formContent.schema.properties) {
1735
+ formContent.schema.properties[param.name] = {
1736
+ ...transformItemsObject(structuredClone(param)),
1737
+ // Only carry the description over when it exists, so a parameter without one does not
1738
+ // end up with an explicit `description: undefined` on its schema.
1739
+ ...param.description !== void 0 ? { description: param.description } : {}
1740
+ };
1741
+ const encoding = getFormDataEncoding(param);
1742
+ if (encoding) {
1743
+ formContent.encoding ??= {};
1744
+ formContent.encoding[param.name] = encoding;
1745
+ }
1746
+ if (param.required && Array.isArray(formContent.schema.required)) {
1747
+ formContent.schema.required.push(param.name);
1748
+ }
1749
+ }
1750
+ }
1751
+ }
1752
+ }
1753
+ }
1754
+ return requestBodyObject;
1755
+ }
1756
+ function migrateParameters(parameters, consumes) {
1757
+ const result = {
1758
+ parameters: parameters.filter((parameter) => !(parameter.in === "body" || parameter.in === "formData")).map((parameter) => transformParameterObject(parameter))
1759
+ };
1760
+ const bodyParameter = structuredClone(parameters.find((parameter) => parameter.in === "body") ?? {});
1761
+ if (bodyParameter && Object.keys(bodyParameter).length) {
1762
+ result.requestBody = migrateBodyParameter(bodyParameter, consumes);
1763
+ }
1764
+ const formDataParameters = parameters.filter((parameter) => parameter.in === "formData");
1765
+ if (formDataParameters.length > 0) {
1766
+ const requestBodyObject = migrateFormDataParameter(formDataParameters, consumes);
1767
+ if (typeof result.requestBody !== "object") {
1768
+ result.requestBody = requestBodyObject;
1769
+ } else {
1770
+ result.requestBody = {
1771
+ ...result.requestBody,
1772
+ content: {
1773
+ ...result.requestBody.content,
1774
+ ...requestBodyObject.content
1775
+ }
1776
+ };
1777
+ }
1778
+ if (typeof result.requestBody !== "object") {
1779
+ result.requestBody = {
1780
+ content: {}
1781
+ };
1782
+ }
1783
+ }
1784
+ return result;
1785
+ }
1786
+
1787
+ // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/openapi/is-schema-path.js
1788
+ var SCHEMA_SEGMENTS = /* @__PURE__ */ new Set([
1789
+ "properties",
1790
+ "items",
1791
+ "allOf",
1792
+ "anyOf",
1793
+ "oneOf",
1794
+ "not",
1795
+ "additionalProperties",
1796
+ "schema",
1797
+ // Reusable schemas live under `components/schemas`, and `schemas` is not a
1798
+ // fixed keyword anywhere else in the document.
1799
+ "schemas"
1800
+ ]);
1801
+ var USER_KEYED_MAPS = /* @__PURE__ */ new Set([
1802
+ "paths",
1803
+ "webhooks",
1804
+ "responses",
1805
+ "content",
1806
+ "headers",
1807
+ "examples",
1808
+ "links",
1809
+ "encoding",
1810
+ "variables",
1811
+ "parameters",
1812
+ "requestBodies",
1813
+ "securitySchemes",
1814
+ "pathItems",
1815
+ "scopes"
1816
+ ]);
1817
+ var isSchemaPath = (path) => {
1818
+ if (!path) {
1819
+ return false;
1820
+ }
1821
+ const segments2 = path[0] === "x-ext" && path[1] !== void 0 ? path.slice(2) : path;
1822
+ let userKeySegments = 0;
1823
+ for (const segment of segments2) {
1824
+ if (userKeySegments > 0) {
1825
+ userKeySegments--;
1826
+ continue;
1827
+ }
1828
+ if (SCHEMA_SEGMENTS.has(segment) || segment.endsWith("Schema")) {
1829
+ return true;
1830
+ }
1831
+ if (segment === "callbacks") {
1832
+ userKeySegments = 2;
1833
+ continue;
1834
+ }
1835
+ if (USER_KEYED_MAPS.has(segment)) {
1836
+ userKeySegments = 1;
1837
+ }
1838
+ }
1839
+ return false;
1840
+ };
1841
+
1842
+ // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/3.0-to-3.1/upgrade-from-three-to-three-one.js
1843
+ var NAMED_SCHEMA_MAP_SEGMENTS = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions"]);
1844
+ function isNamedSchemaMap(path) {
1845
+ const last = path?.[path.length - 1];
1846
+ if (last === void 0) {
1847
+ return false;
1848
+ }
1849
+ if (last === "schemas" && path?.[path.length - 2] === "components") {
1850
+ return true;
1851
+ }
1852
+ return NAMED_SCHEMA_MAP_SEGMENTS.has(last);
1853
+ }
1854
+ var DATA_KEYWORDS = /* @__PURE__ */ new Set(["example", "default", "const", "enum"]);
1855
+ function isInsideDataValue(path) {
1856
+ if (!path) {
1857
+ return false;
1858
+ }
1859
+ for (const [index, segment] of path.entries()) {
1860
+ if (DATA_KEYWORDS.has(segment) && !isNamedSchemaMap(path.slice(0, index))) {
1861
+ return true;
1862
+ }
1863
+ if (segment === "value" && path[index - 2] === "examples" && !isNamedSchemaMap(path.slice(0, index - 2))) {
1864
+ return true;
1865
+ }
1866
+ }
1867
+ return false;
1868
+ }
1869
+ function upgradeFromThreeToThreeOne(originalContent) {
1870
+ let content = originalContent;
1871
+ if (content === null || typeof content.openapi !== "string" || !content.openapi.startsWith("3.0")) {
1872
+ return content;
1873
+ }
1874
+ content.openapi = "3.1.1";
1875
+ content = traverse(content, applyChangesToDocument);
1876
+ return content;
1877
+ }
1878
+ var applyChangesToDocument = (schema2, path) => {
1879
+ if (isInsideDataValue(path)) {
1880
+ return schema2;
1881
+ }
1882
+ if (schema2.type !== void 0 && schema2.nullable === true) {
1883
+ schema2.type = [schema2.type, "null"];
1884
+ delete schema2.nullable;
1885
+ } else if (schema2.nullable === true && schema2.type === void 0) {
1886
+ if (typeof schema2.$ref === "string") {
1887
+ const { nullable: _nullable, $ref, ...rest2 } = schema2;
1888
+ return { ...rest2, anyOf: [{ $ref }, { type: "null" }] };
1889
+ }
1890
+ if (Array.isArray(schema2.allOf)) {
1891
+ const { nullable: _nullable, allOf, ...rest2 } = schema2;
1892
+ const base = allOf.length === 1 ? allOf[0] : { allOf };
1893
+ return { ...rest2, anyOf: [base, { type: "null" }] };
1894
+ }
1895
+ }
1896
+ if (schema2.exclusiveMinimum === true && schema2.minimum !== void 0) {
1897
+ schema2.exclusiveMinimum = schema2.minimum;
1898
+ delete schema2.minimum;
1899
+ } else if (typeof schema2.exclusiveMinimum === "boolean") {
1900
+ delete schema2.exclusiveMinimum;
1901
+ }
1902
+ if (schema2.exclusiveMaximum === true && schema2.maximum !== void 0) {
1903
+ schema2.exclusiveMaximum = schema2.maximum;
1904
+ delete schema2.maximum;
1905
+ } else if (typeof schema2.exclusiveMaximum === "boolean") {
1906
+ delete schema2.exclusiveMaximum;
1907
+ }
1908
+ const isInsideExamplesMap = path?.some((segment, index) => {
1909
+ if (segment === "examples" && index > 0) {
1910
+ return !isNamedSchemaMap(path.slice(0, index));
1911
+ }
1912
+ return false;
1913
+ });
1914
+ if (schema2.example !== void 0 && !isInsideExamplesMap && !isNamedSchemaMap(path)) {
1915
+ if (isSchemaPath(path)) {
1916
+ schema2.examples = [schema2.example];
1917
+ } else {
1918
+ schema2.examples = {
1919
+ default: {
1920
+ value: schema2.example
1921
+ }
1922
+ };
1923
+ }
1924
+ delete schema2.example;
1925
+ }
1926
+ const { format: _, ...rest } = schema2;
1927
+ if (schema2.type === "string" || Array.isArray(schema2.type) && schema2.type.includes("string")) {
1928
+ if (schema2.format === "binary") {
1929
+ const { type: _type, ...binarySchema } = rest;
1930
+ const hasMediaType = path?.at(-1) === "schema" && path.at(-3) === "content";
1931
+ return hasMediaType ? binarySchema : { contentMediaType: "application/octet-stream", ...binarySchema };
1932
+ }
1933
+ if (schema2.format === "base64" || schema2.format === "byte") {
1934
+ return {
1935
+ ...rest,
1936
+ contentEncoding: "base64"
1937
+ };
1938
+ }
1939
+ }
1940
+ if (schema2["x-webhooks"] !== void 0 && (path === void 0 || path.length === 0)) {
1941
+ schema2.webhooks = schema2["x-webhooks"];
1942
+ delete schema2["x-webhooks"];
1943
+ }
1944
+ return schema2;
1945
+ };
1946
+
1947
+ // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/upgrade.js
1948
+ function upgrade(value, targetVersion, options) {
1949
+ if (targetVersion === "3.2") {
1950
+ const input = cloneDocument(value);
1951
+ const openapi302 = upgradeFromTwoToThree(input);
1952
+ const openapi31 = upgradeFromThreeToThreeOne(openapi302);
1953
+ try {
1954
+ const document = migrateThreeOneToThreeTwo(openapi31);
1955
+ return options?.onIncompatible === "collect" ? { document, diagnostics: [] } : document;
1956
+ } catch (error) {
1957
+ if (options?.onIncompatible !== "collect" || !(error instanceof UpgradeIncompatibilityError)) {
1958
+ throw error;
1959
+ }
1960
+ return {
1961
+ document: upgrade(cloneDocument(value), "3.1"),
1962
+ diagnostics: error.errors
1963
+ };
1964
+ }
1965
+ }
1966
+ const openapi30 = upgradeFromTwoToThree(value);
1967
+ return targetVersion === "3.0" ? openapi30 : upgradeFromThreeToThreeOne(openapi30);
1968
+ }
1969
+
1970
+ // src/implementation/openapi-document.ts
1971
+ var record = Schema_exports.decodeUnknownSync(JsonObject);
1972
+ function fail(code, reason) {
1973
+ throw new OpenapiCompileError({ code, reason });
1974
+ }
1975
+ async function openApiDocument(input) {
1976
+ const root = record(upgrade(structuredClone(record(input)), "3.1"));
1977
+ const spec = Schema_exports.decodeUnknownSync(Specification)(root);
1978
+ if (!spec.openapi.startsWith("3.1."))
1979
+ fail("openapi_version", "This importer supports Swagger 2.0 and OpenAPI 3.0 and 3.1.");
1980
+ const components = spec.components?.schemas ?? {};
1981
+ const convert = JsonSchema_exports.fromSchemaOpenApi3_1;
1982
+ const schemas = [];
1983
+ const componentsObject = root.components === void 0 ? {} : record(root.components);
1984
+ const masked = JSON.parse(
1985
+ JSON.stringify(
1986
+ { ...root, components: { ...componentsObject, schemas: {} } },
1987
+ (key, value) => {
1988
+ if (key !== "schema") return value;
1989
+ const index = schemas.push(Schema_exports.decodeUnknownSync(Schema_exports.Json)(value)) - 1;
1990
+ return { "x-executor-schema": index };
1991
+ }
1992
+ )
1993
+ );
1994
+ const resolved2 = await (await loadSwaggerClient()).resolve({
1995
+ spec: masked,
1996
+ skipNormalization: true,
1997
+ useCircularStructures: false,
1998
+ // Spec import uses the host's guarded download. References must not acquire
1999
+ // a second, unguarded network capability inside the resolver.
2000
+ requestInterceptor: () => fail("external_reference", "External OpenAPI references are not supported yet.")
2001
+ });
2002
+ const restored = record(
2003
+ JSON.parse(JSON.stringify(resolved2.spec), (key, value) => {
2004
+ if (key !== "schema") return value;
2005
+ const marker = record(value)["x-executor-schema"];
2006
+ if (typeof marker !== "number" || schemas[marker] === void 0)
2007
+ return fail("invalid_document", "The API resolver did not preserve a schema.");
2008
+ return schemas[marker];
2009
+ })
2010
+ );
2011
+ const parsed = Schema_exports.decodeUnknownSync(Specification)({
2012
+ ...restored,
2013
+ components: { ...record(restored.components), schemas: components }
2014
+ });
2015
+ const definitions = /* @__PURE__ */ new Map();
2016
+ const references2 = /* @__PURE__ */ new Map();
2017
+ return {
2018
+ spec: parsed,
2019
+ definitions,
2020
+ /** Inspect a component schema without expanding its children. OpenAPI object refs must already be resolved by Swagger. */
2021
+ resolve(value) {
2022
+ const visited = /* @__PURE__ */ new Set();
2023
+ while (value.$ref !== void 0) {
2024
+ const ref = value.$ref;
2025
+ const path = typeof ref === "string" ? JsonPointer_exports.parseUriFragment(ref) : void 0;
2026
+ if (typeof ref !== "string" || path?.length !== 3 || path[0] !== "components" || path[1] !== "schemas" || path[2] === void 0)
2027
+ fail("external_reference", "An OpenAPI object reference could not be resolved locally.");
2028
+ if (visited.has(ref))
2029
+ fail("circular_reference", "A circular schema alias cannot be imported.");
2030
+ visited.add(ref);
2031
+ value = record(Object.hasOwn(components, path[2]) ? components[path[2]] : void 0);
2032
+ }
2033
+ return value;
2034
+ },
2035
+ /** Compose a Draft 2020-12 schema around API Schema Objects. Only values passed to
2036
+ * `api` use the document's OpenAPI dialect; Executor-authored wrappers are already
2037
+ * Draft 2020-12 and must not be reinterpreted. Reached components are converted once into
2038
+ * the shared `definitions` and stay references here; nothing is inlined or copied per operation.
2039
+ */
2040
+ schema(build) {
2041
+ const added = [];
2042
+ const direct = /* @__PURE__ */ new Set();
2043
+ const local = {};
2044
+ const visit = (input2, direct2) => {
2045
+ const document = convert(input2, {
2046
+ onReference(ref) {
2047
+ const path = JsonPointer_exports.parseUriFragment(ref);
2048
+ const name = path?.[2];
2049
+ if (path?.length !== 3 || path[0] !== "components" || path[1] !== "schemas" || name === void 0)
2050
+ fail("schema_reference", "Only local component schema references are supported.");
2051
+ const component = Object.hasOwn(components, name) ? components[name] : void 0;
2052
+ if (component === void 0)
2053
+ fail("missing_component", "An API schema references a missing component.");
2054
+ direct2.add(name);
2055
+ if (!definitions.has(name)) {
2056
+ added.push(name);
2057
+ definitions.set(name, {});
2058
+ const names = /* @__PURE__ */ new Set();
2059
+ definitions.set(name, visit(component, names));
2060
+ references2.set(name, names);
2061
+ }
2062
+ }
2063
+ });
2064
+ return record({
2065
+ ...document.schema,
2066
+ ...Object.keys(document.definitions).length ? { $defs: document.definitions } : {}
2067
+ });
2068
+ };
2069
+ const api = (input2) => {
2070
+ const { $defs, ...converted } = visit(record(input2), direct);
2071
+ for (const [name, definition] of Object.entries($defs === void 0 ? {} : record($defs))) {
2072
+ if (Object.hasOwn(local, name) && JSON.stringify(local[name]) !== JSON.stringify(definition))
2073
+ fail("schema_reference", "An API schema has conflicting local definitions.");
2074
+ local[name] = definition;
2075
+ }
2076
+ return converted;
2077
+ };
2078
+ try {
2079
+ const converted = build(api);
2080
+ if (Object.keys(local).length) {
2081
+ const reached = /* @__PURE__ */ new Set();
2082
+ const pending = [...direct];
2083
+ for (let name = pending.pop(); name !== void 0; name = pending.pop()) {
2084
+ if (reached.has(name)) continue;
2085
+ reached.add(name);
2086
+ pending.push(...references2.get(name) ?? []);
2087
+ }
2088
+ if ([...reached].some((name) => Object.hasOwn(local, name)))
2089
+ fail(
2090
+ "schema_reference",
2091
+ "An API schema has conflicting local and component definitions."
2092
+ );
2093
+ }
2094
+ return {
2095
+ ...converted,
2096
+ ...Object.keys(local).length ? { $defs: local } : {},
2097
+ $schema: JsonSchema_exports.META_SCHEMA_URI_DRAFT_2020_12
2098
+ };
2099
+ } catch (error) {
2100
+ for (const name of added) {
2101
+ definitions.delete(name);
2102
+ references2.delete(name);
2103
+ }
2104
+ if (error instanceof OpenapiCompileError) throw error;
2105
+ return fail(
2106
+ "schema_keyword",
2107
+ "An API schema cannot be converted without changing its constraints."
2108
+ );
2109
+ }
2110
+ }
2111
+ };
2112
+ }
2113
+
2114
+ // src/implementation/openapi-names.ts
2115
+ var words = (value) => value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, "$1 $2").replace(/[^a-zA-Z0-9]+/g, " ").trim().split(/\s+/).filter((word) => word.length > 0).map((word) => word.toLowerCase());
2116
+ var camel = (value) => {
2117
+ const [first, ...rest] = words(value);
2118
+ return first === void 0 ? "" : `${first}${rest.map((word) => `${word[0]?.toUpperCase() ?? ""}${word.slice(1)}`).join("")}`;
2119
+ };
2120
+ var pascal = (value) => {
2121
+ const name = camel(value);
2122
+ return `${name[0]?.toUpperCase() ?? ""}${name.slice(1)}`;
2123
+ };
2124
+ var version = /^v\d+(?:[._-]\d+)?$/i;
2125
+ var segments = (path) => path.split("/").map((segment) => segment.trim()).filter((segment) => segment.length > 0);
2126
+ var resourceSegments = (path) => segments(path).filter(
2127
+ (segment) => !version.test(segment) && segment.toLowerCase() !== "api" && !(segment.startsWith("{") && segment.endsWith("}")) && camel(segment) !== ""
2128
+ );
2129
+ var groupOf = (input) => camel(input.tag ?? "") || camel(resourceSegments(input.path)[0] ?? "") || // Keep "root" for an operation on `/` or a path of only versions and parameters.
2130
+ "root";
2131
+ var fallbackLeaf = (input, group) => {
2132
+ const resources = resourceSegments(input.path).map(camel);
2133
+ const others = resources.filter((segment) => segment !== group);
2134
+ const suffix = (others.length ? others : resources).map(pascal).join("");
2135
+ return camel(`${input.method.toLowerCase()}${suffix || "Operation"}`);
2136
+ };
2137
+ var leafOf = (input, group) => {
2138
+ if (input.operationId === void 0) return fallbackLeaf(input, group);
2139
+ const [first, ...rest] = input.operationId.split(/[._/]+/).filter((part) => part.length > 0);
2140
+ const seed = first !== void 0 && rest.length > 0 && camel(first).toLowerCase() === group.toLowerCase() ? rest.join(" ") : input.operationId;
2141
+ const leaf = camel(seed);
2142
+ return leaf === "" || leaf === group ? fallbackLeaf(input, group) : leaf;
2143
+ };
2144
+ var hash = (input) => {
2145
+ const text = JSON.stringify([input.method.toUpperCase(), input.path, input.operationId ?? null]);
2146
+ let value = 0;
2147
+ for (let i = 0; i < text.length; i++) value = (value << 5) - value + text.charCodeAt(i) | 0;
2148
+ return Math.abs(value).toString(36).padStart(8, "0").slice(0, 8);
2149
+ };
2150
+ var planOperationNames = (inputs) => {
2151
+ const staged = inputs.map((input) => {
2152
+ const group = groupOf(input);
2153
+ const leaf = leafOf(input, group);
2154
+ const versionSegment = segments(input.path).map((segment) => segment.toLowerCase()).find((segment) => version.test(segment));
2155
+ const prefix = versionSegment === void 0 ? group : `${group}.${camel(versionSegment)}`;
2156
+ return { input, group, leaf, prefix, versionSegment, name: `${group}.${leaf}` };
2157
+ });
2158
+ const refine = (rename) => {
2159
+ const buckets = /* @__PURE__ */ new Map();
2160
+ for (const item of staged) buckets.set(item.name, [...buckets.get(item.name) ?? [], item]);
2161
+ for (const bucket of buckets.values())
2162
+ if (bucket.length > 1) for (const item of bucket) item.name = rename(item);
2163
+ };
2164
+ refine((item) => item.versionSegment === void 0 ? item.name : `${item.prefix}.${item.leaf}`);
2165
+ refine((item) => `${item.prefix}.${item.leaf}${pascal(item.input.method)}`);
2166
+ refine((item) => `${item.prefix}.${item.leaf}${pascal(item.input.method)}${hash(item.input)}`);
2167
+ return staged.map((item) => item.name);
2168
+ };
2169
+
2170
+ // src/implementation/openapi-compile.ts
2171
+ function fail2(code, reason) {
2172
+ throw new OpenapiCompileError({ code, reason });
2173
+ }
2174
+ var record2 = (value) => Schema_exports.decodeUnknownSync(JsonObject)(value);
2175
+ var OperationNaming = Schema_exports.Struct({
2176
+ operationId: Schema_exports.optionalKey(Schema_exports.String),
2177
+ tags: Schema_exports.optionalKey(Schema_exports.Array(Schema_exports.String))
2178
+ });
2179
+ var identifier = (name) => name.replace(/[^a-zA-Z0-9_]/g, "_");
2180
+ function absolute(value) {
2181
+ const url = new URL(value);
2182
+ if (url.protocol !== "https:" && url.protocol !== "http:")
2183
+ fail2("server_protocol", "Only HTTP APIs can be imported.");
2184
+ if (url.username || url.password || url.hash || url.search || /[{}]/.test(value))
2185
+ fail2("server_url", "This API needs a configured server URL before import.");
2186
+ return url.href.replace(/\/$/, "");
2187
+ }
2188
+ function serverAddress(swagger, server, connectUrl, documentServer) {
2189
+ const variables = { ...documentServer?.variables, ...server.variables };
2190
+ const request = record2(
2191
+ swagger.buildRequest({
2192
+ spec: {
2193
+ openapi: "3.1.0",
2194
+ servers: [{ url: server.url, variables }],
2195
+ paths: { "/": { get: { operationId: "server" } } }
2196
+ },
2197
+ operationId: "server"
2198
+ })
2199
+ );
2200
+ return absolute(new URL(Schema_exports.decodeUnknownSync(Schema_exports.String)(request.url), connectUrl).href);
2201
+ }
2202
+ var binaryInput = {
2203
+ type: "string",
2204
+ description: "File bytes encoded as base64.",
2205
+ contentEncoding: "base64"
2206
+ };
2207
+ function responseSchema(document, operation, method) {
2208
+ if (method === "HEAD") return { type: "null" };
2209
+ const success = Object.entries(operation.responses ?? {}).filter(
2210
+ ([status]) => /^2(?:[0-9]{2}|XX)$/i.test(status)
2211
+ );
2212
+ if (success.length === 0) return void 0;
2213
+ const shapes = [];
2214
+ for (const [status, response] of success) {
2215
+ if (status === "204") {
2216
+ shapes.push(() => ({ type: "null" }));
2217
+ continue;
2218
+ }
2219
+ const content = document.resolve(response).content;
2220
+ if (content === void 0) return void 0;
2221
+ const media = Object.entries(record2(content));
2222
+ if (media.length === 0) return void 0;
2223
+ for (const [type, body] of media) {
2224
+ if (!type.includes("json")) {
2225
+ shapes.push(
2226
+ () => isOpenapiTextMedia(type) ? { type: "string" } : openapiBinaryResultSchema
2227
+ );
2228
+ continue;
2229
+ }
2230
+ const schema2 = record2(body).schema;
2231
+ if (schema2 === void 0) return void 0;
2232
+ shapes.push((api) => api(schema2));
2233
+ }
2234
+ }
2235
+ return document.schema((api) => ({
2236
+ anyOf: shapes.map((shape) => shape(api))
2237
+ }));
2238
+ }
2239
+ function resolvedOrUndefined(document, value) {
2240
+ try {
2241
+ return document.resolve(record2(value));
2242
+ } catch (error) {
2243
+ if (!(error instanceof OpenapiCompileError) && !Schema_exports.isSchemaError(error)) throw error;
2244
+ return void 0;
2245
+ }
2246
+ }
2247
+ function errorContent(document, response) {
2248
+ try {
2249
+ return document.resolve(response).content;
2250
+ } catch (error) {
2251
+ if (!(error instanceof OpenapiCompileError) && !Schema_exports.isSchemaError(error)) throw error;
2252
+ return void 0;
2253
+ }
2254
+ }
2255
+ function errorResponses(document, operation) {
2256
+ const errors = [];
2257
+ const tagged = Schema_exports.Struct({
2258
+ description: Schema_exports.optionalKey(Schema_exports.String),
2259
+ required: Schema_exports.Array(Schema_exports.String),
2260
+ properties: Schema_exports.Record(Schema_exports.String, JsonObject)
2261
+ });
2262
+ const visit = (status, input, visited = /* @__PURE__ */ new Set(), parents = []) => {
2263
+ const object2 = Schema_exports.decodeUnknownOption(JsonObject)(input);
2264
+ if (Option_exports.isNone(object2)) return;
2265
+ const value = object2.value;
2266
+ try {
2267
+ if (typeof value.$ref === "string" && visited.has(value.$ref)) return;
2268
+ const next = typeof value.$ref === "string" ? /* @__PURE__ */ new Set([...visited, value.$ref]) : visited;
2269
+ const shape = document.resolve(value);
2270
+ const variants = shape.anyOf;
2271
+ if (Array.isArray(variants)) {
2272
+ for (const variant of variants) visit(status, variant, next, [...parents, value]);
2273
+ return;
2274
+ }
2275
+ const parsed = Schema_exports.decodeUnknownOption(tagged)(shape);
2276
+ if (Option_exports.isNone(parsed) || !parsed.value.required.includes("_tag")) return;
2277
+ const tag = parsed.value.properties._tag;
2278
+ if (tag === void 0) return;
2279
+ const code = typeof tag.const === "string" ? tag.const : Array.isArray(tag.enum) && tag.enum.length === 1 ? tag.enum[0] : void 0;
2280
+ const message = parsed.value.properties.message;
2281
+ const messageShape = message === void 0 ? void 0 : document.resolve(message);
2282
+ const hasMessage = messageShape !== void 0 && (messageShape.type === "string" || typeof messageShape.const === "string" || Array.isArray(messageShape.enum) && messageShape.enum.length > 0 && messageShape.enum.every((value2) => typeof value2 === "string"));
2283
+ const declaration = Schema_exports.decodeUnknownOption(OpenapiErrorResponse)({
2284
+ code,
2285
+ status,
2286
+ message: hasMessage ? { source: "body" } : { source: "schema", value: parsed.value.description },
2287
+ schema: document.schema((api) => ({ allOf: [...parents, value].map(api) }))
2288
+ });
2289
+ if (Option_exports.isSome(declaration)) errors.push(declaration.value);
2290
+ } catch (error) {
2291
+ if (!(error instanceof OpenapiCompileError) && !Schema_exports.isSchemaError(error)) throw error;
2292
+ }
2293
+ };
2294
+ for (const [status, response] of Object.entries(operation.responses ?? {})) {
2295
+ if (!/^[45][0-9]{2}$/.test(status)) continue;
2296
+ const content = errorContent(document, response);
2297
+ if (content === void 0) continue;
2298
+ for (const [type, body] of Object.entries(record2(content))) {
2299
+ if (!type.split(";")[0]?.trim().match(/^application\/(?:[\w.-]+\+)?json$/i))
2300
+ continue;
2301
+ const schema2 = record2(body).schema;
2302
+ if (schema2 !== void 0) visit(Number(status), schema2);
2303
+ }
2304
+ }
2305
+ return errors;
2306
+ }
2307
+ var compileOpenApiDocument = (entry, inputDocument, options = {}) => Effect_exports.tryPromise({
2308
+ try: async () => {
2309
+ const document = await openApiDocument(inputDocument);
2310
+ const swagger = await loadSwaggerClient();
2311
+ const { spec } = document;
2312
+ const schemes = { ...options.securitySchemes ?? spec.components?.securitySchemes };
2313
+ const bindings = /* @__PURE__ */ new Map();
2314
+ const oauth = [];
2315
+ for (const [name, source] of Object.entries(schemes)) {
2316
+ const scheme = document.resolve(source);
2317
+ if (scheme.type === "http" && scheme.scheme === "bearer" || scheme.type === "apiKey" && (scheme.in === "header" || scheme.in === "query" || scheme.in === "cookie") && typeof scheme.name === "string") {
2318
+ bindings.set(name, [
2319
+ {
2320
+ scheme: name,
2321
+ field: "token",
2322
+ part: "value",
2323
+ prefix: ""
2324
+ }
2325
+ ]);
2326
+ } else if (scheme.type === "http" && scheme.scheme === "basic") {
2327
+ bindings.set(name, [
2328
+ { scheme: name, field: "username", part: "username", prefix: "" },
2329
+ { scheme: name, field: "password", part: "password", prefix: "" }
2330
+ ]);
2331
+ } else if (scheme.type === "oauth2") {
2332
+ const code = record2(scheme.flows).authorizationCode;
2333
+ if (code !== void 0) {
2334
+ const flow = record2(code);
2335
+ if (typeof flow.authorizationUrl === "string" && typeof flow.tokenUrl === "string")
2336
+ oauth.push({
2337
+ name,
2338
+ config: entry.oauthDiscoveryUrl === void 0 ? {
2339
+ authorizationUrl: absolute(
2340
+ new URL(flow.authorizationUrl, entry.connectUrl).href
2341
+ ),
2342
+ tokenUrl: absolute(new URL(flow.tokenUrl, entry.connectUrl).href),
2343
+ scopes: [
2344
+ ...entry.scopes ?? Object.keys(record2(flow.scopes ?? {}))
2345
+ ].sort()
2346
+ } : { discover: absolute(entry.oauthDiscoveryUrl) }
2347
+ });
2348
+ }
2349
+ }
2350
+ }
2351
+ let fallback = options.fallbackSecurity;
2352
+ if (bindings.size === 0 && Object.keys(schemes).length === 0 && entry.auth?.header !== void 0) {
2353
+ const header = /^([!#$%&'*+.^_`|~A-Za-z0-9-]+):\s*([^{}\r\n]*)\{[A-Za-z0-9_]+\}$/.exec(
2354
+ entry.auth.header
2355
+ );
2356
+ if (!header?.[1] || header[2] === void 0)
2357
+ fail2("auth_helper", "This catalog entry needs a custom authentication helper.");
2358
+ bindings.set("apiKey", [
2359
+ {
2360
+ scheme: "apiKey",
2361
+ field: "token",
2362
+ part: "value",
2363
+ prefix: header[2]
2364
+ }
2365
+ ]);
2366
+ schemes.apiKey = { type: "apiKey", in: "header", name: header[1] };
2367
+ fallback = [{ apiKey: [] }];
2368
+ }
2369
+ if (!fallback && !Object.keys(schemes).length && entry.auth && !["none", "public"].includes(entry.auth.kind))
2370
+ fail2(
2371
+ "auth_missing",
2372
+ "This entry does not declare enough authentication details to generate an app."
2373
+ );
2374
+ const methods = /* @__PURE__ */ new Map();
2375
+ const operations = [];
2376
+ const skipped = /* @__PURE__ */ new Set();
2377
+ const causes = /* @__PURE__ */ new Map();
2378
+ const built = [];
2379
+ const documentServer = spec.servers?.[0];
2380
+ const candidates = Object.entries(spec.paths).flatMap(([path, source]) => {
2381
+ const item = document.resolve(source);
2382
+ return ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].filter((method) => item[method.toLowerCase()] !== void 0).map((method) => ({ path, item, method }));
2383
+ });
2384
+ if (!candidates.length) fail2("no_operations", "This API does not contain any operations.");
2385
+ const names = planOperationNames(
2386
+ candidates.map(({ path, item, method }) => {
2387
+ const naming = Schema_exports.decodeUnknownOption(OperationNaming)(
2388
+ resolvedOrUndefined(document, item[method.toLowerCase()])
2389
+ ).pipe(Option_exports.getOrUndefined);
2390
+ return {
2391
+ operationId: naming?.operationId,
2392
+ tag: naming?.tags?.find((tag) => tag.trim() !== ""),
2393
+ method,
2394
+ path
2395
+ };
2396
+ })
2397
+ );
2398
+ for (const [index, { path, item, method }] of candidates.entries()) {
2399
+ try {
2400
+ if (!path.startsWith("/") || path.includes("?") || path.includes("#"))
2401
+ fail2("operation_path", "An operation has an invalid API path.");
2402
+ const operationMethods = [];
2403
+ const resolved2 = document.resolve(record2(item[method.toLowerCase()]));
2404
+ const operation = Schema_exports.decodeUnknownSync(Operation)(resolved2);
2405
+ const tags = Option_exports.getOrUndefined(
2406
+ Schema_exports.decodeUnknownOption(Schema_exports.Array(Schema_exports.NonEmptyString))(resolved2.tags)
2407
+ );
2408
+ const name = names[index] ?? fail2("operation_path", "An operation has no name.");
2409
+ if (built.some((op) => op.operation.name === name))
2410
+ fail2(
2411
+ "duplicate_operation",
2412
+ "The API has duplicate tool names. Update its operation IDs first."
2413
+ );
2414
+ const serverList = operation.servers ?? (Array.isArray(item.servers) ? Schema_exports.decodeUnknownSync(Specification.fields.servers)(item.servers) : void 0) ?? spec.servers;
2415
+ const server = serverList?.[0];
2416
+ const serverUrl = options.baseUrl ?? server?.url;
2417
+ if (serverUrl === void 0)
2418
+ fail2("server_missing", "The API has no server URL. Set an API base URL and try again.");
2419
+ const baseUrl = serverAddress(
2420
+ swagger,
2421
+ options.baseUrl === void 0 && server !== void 0 ? server : { url: serverUrl },
2422
+ entry.connectUrl,
2423
+ documentServer
2424
+ );
2425
+ const combined = [
2426
+ ...Array.isArray(item.parameters) ? item.parameters : [],
2427
+ ...operation.parameters ?? []
2428
+ ];
2429
+ const parameters = /* @__PURE__ */ new Map();
2430
+ for (const parameter of combined) {
2431
+ const p = Schema_exports.decodeUnknownSync(OpenapiParameter)(document.resolve(record2(parameter)));
2432
+ parameters.set(`${p.in}:${p.name}`, p);
2433
+ }
2434
+ const groups = /* @__PURE__ */ new Map();
2435
+ for (const p of parameters.values()) {
2436
+ const key = p.in === "header" ? "headers" : p.in;
2437
+ const group = groups.get(key) ?? { properties: {}, required: [] };
2438
+ const content = p.content === void 0 ? void 0 : Object.values(p.content)[0];
2439
+ group.properties[p.name] = p.schema ?? (content === void 0 ? {} : record2(content).schema ?? {});
2440
+ if (p.required || p.in === "path") group.required.push(p.name);
2441
+ groups.set(key, group);
2442
+ }
2443
+ const properties = {};
2444
+ const required = [];
2445
+ for (const [key, group] of groups) {
2446
+ properties[key] = (api) => ({
2447
+ type: "object",
2448
+ properties: Object.fromEntries(
2449
+ Object.entries(group.properties).map(([name2, schema2]) => [name2, api(schema2)])
2450
+ ),
2451
+ required: group.required,
2452
+ additionalProperties: false
2453
+ });
2454
+ if (group.required.length) required.push(key);
2455
+ }
2456
+ const bodyVariants = [];
2457
+ let retainedBody;
2458
+ if (operation.requestBody) {
2459
+ const request = Schema_exports.decodeUnknownSync(OpenapiRequestBody)(
2460
+ document.resolve(operation.requestBody)
2461
+ );
2462
+ const retainedContent = {};
2463
+ for (const [contentType, content] of Object.entries(request.content)) {
2464
+ const kind = openapiMediaKind(contentType);
2465
+ const schema2 = document.resolve(content.schema ?? {});
2466
+ const declared = content.schema ?? {};
2467
+ const retainedFiles = {};
2468
+ let inputSchema = kind === "binary" ? () => binaryInput : kind === "text" ? () => ({ type: "string" }) : (api) => api(declared);
2469
+ if (kind === "multipart") {
2470
+ const fields = { ...record2(schema2.properties ?? {}) };
2471
+ const files = {};
2472
+ for (const [key, field] of Object.entries(fields)) {
2473
+ const shape = document.resolve(record2(field));
2474
+ if (isOpenapiFileSchema(shape)) {
2475
+ delete fields[key];
2476
+ files[key] = binaryInput;
2477
+ retainedFiles[key] = shape;
2478
+ }
2479
+ }
2480
+ const form = schema2;
2481
+ inputSchema = (api) => {
2482
+ const converted = api({ ...form, properties: fields });
2483
+ return {
2484
+ ...converted,
2485
+ properties: { ...record2(converted.properties ?? {}), ...files }
2486
+ };
2487
+ };
2488
+ }
2489
+ retainedContent[contentType] = {
2490
+ ...content.encoding === void 0 ? {} : { encoding: content.encoding },
2491
+ ...Object.keys(retainedFiles).length ? { schema: { type: "object", properties: retainedFiles } } : {}
2492
+ };
2493
+ const first = bodyVariants.length === 0;
2494
+ bodyVariants.push((api) => ({
2495
+ properties: { contentType: { enum: [contentType] }, body: inputSchema(api) },
2496
+ ...first ? {} : { required: ["contentType"] }
2497
+ }));
2498
+ }
2499
+ retainedBody = { ...request, content: retainedContent };
2500
+ if (!bodyVariants.length)
2501
+ fail2("request_body", `Tool ${name} has no request media types.`);
2502
+ properties.body = () => ({});
2503
+ properties.contentType = () => ({
2504
+ type: "string",
2505
+ enum: Object.keys(request.content),
2506
+ description: "Request media type. Defaults to the first declared type."
2507
+ });
2508
+ if (request.required) required.push("body");
2509
+ }
2510
+ const security = operation.security ?? spec.security ?? fallback ?? [];
2511
+ for (const requirement of security) {
2512
+ const keys = Object.keys(requirement).sort();
2513
+ if (!keys.length) continue;
2514
+ if (!keys.every((key) => bindings.has(key))) continue;
2515
+ const parts = keys.flatMap((key) => bindings.get(key) ?? []);
2516
+ const methodName = bindings.size === 1 && keys.length === 1 ? "apiKey" : keys.join("_and_");
2517
+ operationMethods.push({
2518
+ name: methodName,
2519
+ label: parts.length === 1 ? "API key" : keys.join(" + "),
2520
+ bindings: parts.map((part) => ({
2521
+ ...part,
2522
+ field: keys.length === 1 ? part.field : `${identifier(part.scheme)}_${part.field}`
2523
+ }))
2524
+ });
2525
+ }
2526
+ const input = document.schema((api) => ({
2527
+ type: "object",
2528
+ properties: Object.fromEntries(
2529
+ Object.entries(properties).map(([key, shape]) => [key, shape(api)])
2530
+ ),
2531
+ required,
2532
+ ...bodyVariants.length ? { anyOf: bodyVariants.map((variant) => variant(api)) } : {},
2533
+ additionalProperties: false
2534
+ }));
2535
+ try {
2536
+ jsonSchema(input);
2537
+ } catch {
2538
+ fail2(
2539
+ "input_schema",
2540
+ `Tool ${name} has an input schema this importer cannot preserve yet.`
2541
+ );
2542
+ }
2543
+ const outputSchema = responseSchema(document, operation, method);
2544
+ const streaming = Object.values(operation.responses ?? {}).some((response) => {
2545
+ const content = errorContent(document, response);
2546
+ return content !== void 0 && Object.hasOwn(record2(content), "text/event-stream");
2547
+ });
2548
+ built.push({
2549
+ methods: operationMethods,
2550
+ operation: {
2551
+ ...streaming ? { streaming: true } : {},
2552
+ ...tags === void 0 || tags.length === 0 ? {} : { tags },
2553
+ name,
2554
+ ...operation.operationId === void 0 ? {} : { operationId: operation.operationId },
2555
+ description: operation.summary ?? operation.description ?? name,
2556
+ method,
2557
+ path,
2558
+ baseUrl,
2559
+ openapi: spec.openapi,
2560
+ securitySchemes: Object.fromEntries(
2561
+ [...new Set(security.flatMap(Object.keys))].map((key) => [
2562
+ key,
2563
+ schemes[key] ?? fail2("auth_method", "A security requirement names a missing scheme.")
2564
+ ])
2565
+ ),
2566
+ request: {
2567
+ parameters: [...parameters.values()],
2568
+ ...retainedBody === void 0 ? {} : { requestBody: retainedBody },
2569
+ security,
2570
+ responses: Object.fromEntries(
2571
+ Object.entries(operation.responses ?? {}).flatMap(([status, response]) => {
2572
+ const content = errorContent(document, response);
2573
+ return content === void 0 ? [] : [
2574
+ [
2575
+ status,
2576
+ {
2577
+ content: Object.fromEntries(
2578
+ Object.keys(record2(content)).map((type) => [type, {}])
2579
+ )
2580
+ }
2581
+ ]
2582
+ ];
2583
+ })
2584
+ )
2585
+ },
2586
+ input,
2587
+ ...outputSchema === void 0 ? {} : { outputSchema },
2588
+ errorResponses: errorResponses(document, operation)
2589
+ }
2590
+ });
2591
+ } catch (error) {
2592
+ if (!(error instanceof OpenapiCompileError) && !Schema_exports.isSchemaError(error)) throw error;
2593
+ const code = error instanceof OpenapiCompileError ? error.code : "invalid_document";
2594
+ if (error instanceof OpenapiCompileError && !causes.has(code)) causes.set(code, error);
2595
+ skipped.add(code);
2596
+ }
2597
+ }
2598
+ const counts = /* @__PURE__ */ new Map();
2599
+ for (const { operation } of built) {
2600
+ const origin = new URL(operation.baseUrl).origin;
2601
+ counts.set(origin, (counts.get(origin) ?? 0) + 1);
2602
+ }
2603
+ let documentOrigin;
2604
+ try {
2605
+ if (documentServer !== void 0)
2606
+ documentOrigin = new URL(serverAddress(swagger, documentServer, entry.connectUrl)).origin;
2607
+ } catch (error) {
2608
+ if (!(error instanceof OpenapiCompileError)) throw error;
2609
+ }
2610
+ let pinnedOrigin = options.allowedOrigin;
2611
+ for (const [origin, count] of options.allowedOrigin === void 0 ? counts : []) {
2612
+ const best = pinnedOrigin === void 0 ? 0 : counts.get(pinnedOrigin) ?? 0;
2613
+ if (count > best || count === best && origin === documentOrigin) pinnedOrigin = origin;
2614
+ }
2615
+ for (const { operation, methods: operationMethods } of built) {
2616
+ if (new URL(operation.baseUrl).origin !== pinnedOrigin) {
2617
+ skipped.add("multiple_hosts");
2618
+ continue;
2619
+ }
2620
+ operations.push(operation);
2621
+ for (const method of operationMethods) methods.set(method.name, method);
2622
+ }
2623
+ if (!operations.length) {
2624
+ const [only, ...others] = causes.values();
2625
+ if (only !== void 0 && others.length === 0 && [...skipped].every((reason) => reason === only.code))
2626
+ throw only;
2627
+ fail2(
2628
+ "no_supported_operations",
2629
+ "Executor cannot import any operation in this API definition."
2630
+ );
2631
+ }
2632
+ if (!operations.some(
2633
+ (operation) => operation.streaming !== true && (operation.request.security.length === 0 || operation.request.security.some((requirement) => {
2634
+ const keys = Object.keys(requirement);
2635
+ return keys.every((key) => bindings.has(key)) || keys.length === 1 && oauth.some((method) => method.name === keys[0]);
2636
+ }))
2637
+ ))
2638
+ fail2(
2639
+ "no_supported_operations",
2640
+ "This API has no operations supported by the available authentication and response transports."
2641
+ );
2642
+ return {
2643
+ operations,
2644
+ definitions: Object.fromEntries(document.definitions),
2645
+ methods: Object.fromEntries(
2646
+ [...methods.values()].map((method) => [method.name, method.bindings])
2647
+ ),
2648
+ secrets: [...methods.values()],
2649
+ oauth,
2650
+ schemes,
2651
+ pinnedOrigin,
2652
+ fallback
2653
+ };
2654
+ },
2655
+ catch: (error) => error instanceof OpenapiCompileError ? error : new OpenapiCompileError({
2656
+ code: "invalid_document",
2657
+ reason: "This API definition could not be read. It may contain unsupported OpenAPI features."
2658
+ })
2659
+ });
2660
+
2661
+ // src/implementation/openapi-source.ts
2662
+ var Manifest = Schema_exports.Struct({
2663
+ revision: Schema_exports.String,
2664
+ pages: Schema_exports.Number,
2665
+ meta: Schema_exports.optionalKey(RouterMeta)
2666
+ });
2667
+ var DocumentInfo = Schema_exports.Struct({
2668
+ info: Schema_exports.optionalKey(
2669
+ Schema_exports.Struct({
2670
+ title: Schema_exports.optionalKey(Schema_exports.String),
2671
+ summary: Schema_exports.optionalKey(Schema_exports.String),
2672
+ description: Schema_exports.optionalKey(Schema_exports.String)
2673
+ })
240
2674
  ),
2675
+ tags: Schema_exports.optionalKey(
2676
+ Schema_exports.Array(
2677
+ Schema_exports.Struct({
2678
+ name: Schema_exports.NonEmptyString,
2679
+ description: Schema_exports.optionalKey(Schema_exports.String)
2680
+ })
2681
+ )
2682
+ )
2683
+ });
2684
+ var documentMeta = (document) => {
2685
+ const parsed = Schema_exports.decodeUnknownOption(DocumentInfo)(document);
2686
+ if (Option_exports.isNone(parsed)) return void 0;
2687
+ const { info, tags } = parsed.value;
2688
+ const description = info?.description ?? info?.summary;
2689
+ const labels = (tags ?? []).flatMap(
2690
+ (tag) => tag.description === void 0 ? [] : [[tag.name, tag.description]]
2691
+ );
2692
+ const meta = {
2693
+ ...info?.title === void 0 ? {} : { title: info.title },
2694
+ ...description === void 0 ? {} : { description },
2695
+ ...labels.length === 0 ? {} : { tags: Object.fromEntries(labels) }
2696
+ };
2697
+ return Object.keys(meta).length === 0 ? void 0 : meta;
2698
+ };
2699
+ var Names = Schema_exports.Array(Schema_exports.String);
2700
+ var StoredEntry = Schema_exports.fromJsonString(Schema_exports.Struct({ value: JsonValue }));
2701
+ var schema = (decoder) => wrap(decoder, false);
2702
+ var invoke = (work) => Effect_exports.tryPromise({ try: work, catch: (error) => error });
2703
+ var invalid = () => new OpenapiError({ reason: "invalid_definition" });
2704
+ var pageSize = 64;
2705
+ var format = "openapi-v2";
2706
+ var sha256 = (text) => invoke(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(
2707
+ Effect_exports.map(
2708
+ (hash2) => Array.from(new Uint8Array(hash2), (byte) => byte.toString(16).padStart(2, "0")).join("")
2709
+ )
2710
+ );
2711
+ var partConcurrency = 4;
2712
+ var resolved = /* @__PURE__ */ new Map();
2713
+ var resolvedBytes = 0;
2714
+ var remember = (key, entry) => {
2715
+ const bytes2 = new TextEncoder().encode(
2716
+ JSON.stringify([entry.operation, entry.definitions])
2717
+ ).byteLength;
2718
+ if (bytes2 > 8e6) return;
2719
+ const previous = resolved.get(key);
2720
+ if (previous !== void 0) {
2721
+ resolvedBytes -= previous.bytes;
2722
+ resolved.delete(key);
2723
+ }
2724
+ while (resolved.size >= 32 || resolvedBytes + bytes2 > 8e6) {
2725
+ const oldest = resolved.keys().next().value;
2726
+ if (oldest === void 0) break;
2727
+ resolvedBytes -= resolved.get(oldest)?.bytes ?? 0;
2728
+ resolved.delete(oldest);
2729
+ }
2730
+ resolved.set(key, { ...entry, bytes: bytes2 });
2731
+ resolvedBytes += bytes2;
2732
+ };
2733
+ var stored = /* @__PURE__ */ new Map();
2734
+ var storedBytes = 0;
2735
+ var storedPart = (kind, name) => JSON.stringify([kind, name]);
2736
+ var retain = (revision, parts, bytes2) => {
2737
+ if (bytes2 > 8e6) return;
2738
+ const previous = stored.get(revision);
2739
+ if (previous !== void 0) {
2740
+ storedBytes -= previous.bytes;
2741
+ stored.delete(revision);
2742
+ }
2743
+ while (stored.size >= 4 || storedBytes + bytes2 > 8e6) {
2744
+ const oldest = stored.keys().next().value;
2745
+ if (oldest === void 0) break;
2746
+ storedBytes -= stored.get(oldest)?.bytes ?? 0;
2747
+ stored.delete(oldest);
2748
+ }
2749
+ stored.set(revision, { parts, bytes: bytes2 });
2750
+ storedBytes += bytes2;
2751
+ };
2752
+ function patchOpenapi(root, patches) {
2753
+ let result = root;
2754
+ for (const patch of patches ?? []) {
2755
+ if (!patch.path.startsWith("/")) throw invalid();
2756
+ const path = patch.path.slice(1).split("/").map((part) => part.replace(/~1/g, "/").replace(/~0/g, "~"));
2757
+ if (path.some((part) => ["__proto__", "constructor", "prototype"].includes(part)))
2758
+ throw invalid();
2759
+ const update = (node, parts) => {
2760
+ const [head, ...rest] = parts;
2761
+ if (head === void 0) throw invalid();
2762
+ if (rest.length)
2763
+ return {
2764
+ ...node,
2765
+ [head]: update(
2766
+ Schema_exports.decodeUnknownSync(JsonObject)(
2767
+ Object.hasOwn(node, head) ? node[head] : void 0
2768
+ ),
2769
+ rest
2770
+ )
2771
+ };
2772
+ if (patch.op !== "add" && !Object.hasOwn(node, head)) throw invalid();
2773
+ if (patch.op === "remove")
2774
+ return Object.fromEntries(Object.entries(node).filter(([name]) => name !== head));
2775
+ if (patch.value === void 0) throw invalid();
2776
+ return { ...node, [head]: patch.value };
2777
+ };
2778
+ result = update(result, path);
2779
+ }
2780
+ return result;
2781
+ }
2782
+ var download = (url, context) => Effect_exports.gen(function* () {
2783
+ const response = yield* invoke(
2784
+ () => context.fetch(url, { signal: context.signal, redirect: "manual" })
2785
+ );
2786
+ if (!response.ok || response.body === null) return yield* invalid();
2787
+ const reader = response.body.getReader();
2788
+ const text = yield* Effect_exports.acquireUseRelease(
2789
+ Effect_exports.succeed(reader),
2790
+ (reader2) => Effect_exports.gen(function* () {
2791
+ const decoder = new TextDecoder();
2792
+ const chunks = [];
2793
+ let bytes2 = 0;
2794
+ while (true) {
2795
+ const chunk = yield* invoke(() => reader2.read());
2796
+ if (chunk.done) break;
2797
+ bytes2 += chunk.value.byteLength;
2798
+ if (bytes2 > 4e7) return yield* invalid();
2799
+ chunks.push(decoder.decode(chunk.value, { stream: true }));
2800
+ }
2801
+ chunks.push(decoder.decode());
2802
+ return chunks.join("");
2803
+ }),
2804
+ (reader2) => invoke(() => reader2.cancel()).pipe(Effect_exports.catch(() => Effect_exports.void))
2805
+ );
2806
+ return yield* Effect_exports.try({
2807
+ try: () => Schema_exports.decodeUnknownSync(JsonObject)(
2808
+ text.trimStart().startsWith("{") ? JSON.parse(text) : parse(text)
2809
+ ),
2810
+ catch: invalid
2811
+ });
2812
+ });
2813
+ var liveOpenapiRouter = (options) => {
2814
+ const freshFor = options.freshFor ?? "5 minutes";
2815
+ const staleFor = options.staleFor ?? "1 day";
2816
+ const retention = Duration_exports.toMillis(Duration_exports.fromInputUnsafe(freshFor)) + Duration_exports.toMillis(Duration_exports.fromInputUnsafe(staleFor)) + 3e5;
2817
+ const identity = Effect_exports.cached(
2818
+ Effect_exports.tryPromise({
2819
+ try: async () => {
2820
+ const bytes2 = new TextEncoder().encode(
2821
+ JSON.stringify({
2822
+ source: options.source,
2823
+ allowedOrigin: options.allowedOrigin,
2824
+ baseUrl: options.baseUrl,
2825
+ securitySchemes: options.securitySchemes,
2826
+ patches: options.patches,
2827
+ fallbackSecurity: options.fallbackSecurity
2828
+ })
2829
+ );
2830
+ const hash2 = await crypto.subtle.digest("SHA-256", bytes2);
2831
+ return Array.from(new Uint8Array(hash2), (byte) => byte.toString(16).padStart(2, "0")).join(
2832
+ ""
2833
+ );
2834
+ },
2835
+ catch: invalid
2836
+ })
2837
+ );
2838
+ const sourceId = Effect_exports.runSync(identity);
2839
+ const pointer = sourceId.pipe(Effect_exports.map((id) => [format, id, "current"]));
2840
+ const partKey = (revision, kind, name) => [
2841
+ format,
2842
+ revision,
2843
+ kind,
2844
+ name
2845
+ ];
2846
+ const refresh = (context) => Effect_exports.gen(function* () {
2847
+ const raw = "url" in options.source ? yield* download(options.source.url, context) : options.source.document;
2848
+ const document = patchOpenapi(raw, options.patches);
2849
+ const compiled = yield* compileOpenApiDocument(
2850
+ { name: "API", ..."url" in options.source ? { connectUrl: options.source.url } : {} },
2851
+ document,
2852
+ {
2853
+ allowedOrigin: options.allowedOrigin,
2854
+ securitySchemes: options.securitySchemes,
2855
+ ...options.fallbackSecurity === void 0 ? {} : { fallbackSecurity: options.fallbackSecurity },
2856
+ ...options.baseUrl === void 0 ? {} : { baseUrl: options.baseUrl }
2857
+ }
2858
+ );
2859
+ const revision = yield* sha256(JSON.stringify([format, yield* sourceId, document]));
2860
+ const names = compiled.operations.map((operation) => operation.name);
2861
+ const parts = [
2862
+ ...compiled.operations.map((operation) => ({
2863
+ kind: "operation",
2864
+ name: operation.name,
2865
+ value: operation
2866
+ })),
2867
+ ...Object.entries(compiled.definitions).map(([name, value]) => ({
2868
+ kind: "definition",
2869
+ name,
2870
+ value
2871
+ }))
2872
+ ];
2873
+ const pages = Math.ceil(names.length / pageSize);
2874
+ for (let page = 0; page < pages; page++)
2875
+ parts.push({
2876
+ kind: "names",
2877
+ name: page,
2878
+ value: names.slice(page * pageSize, (page + 1) * pageSize)
2879
+ });
2880
+ const batches = [];
2881
+ let batch = [];
2882
+ let size = 0;
2883
+ const retained = /* @__PURE__ */ new Map();
2884
+ let retainedBytes = 0;
2885
+ for (const part of parts) {
2886
+ const entry = { key: partKey(revision, part.kind, part.name), value: part.value };
2887
+ const text = JSON.stringify(entry);
2888
+ const bytes2 = new TextEncoder().encode(text).byteLength;
2889
+ if (batch.length && (batch.length >= 64 || size + bytes2 > 4e6)) {
2890
+ batches.push({ entries: batch, bytes: size });
2891
+ batch = [];
2892
+ size = 0;
2893
+ }
2894
+ batch.push(entry);
2895
+ size += bytes2;
2896
+ retainedBytes += bytes2;
2897
+ if (retainedBytes <= 8e6)
2898
+ retained.set(
2899
+ storedPart(part.kind, part.name),
2900
+ Schema_exports.decodeUnknownSync(StoredEntry)(text).value
2901
+ );
2902
+ }
2903
+ if (batch.length) batches.push({ entries: batch, bytes: size });
2904
+ yield* Effect_exports.forEach(
2905
+ batches,
2906
+ ({ entries, bytes: bytes2 }, index) => fromPromise(context.cache.write)(entries, retention).pipe(
2907
+ Effect_exports.withSpan("app.cache.flush", {
2908
+ attributes: {
2909
+ "cache.flush.index": index,
2910
+ "cache.flush.count": batches.length,
2911
+ "cache.flush.entries": entries.length,
2912
+ "cache.flush.bytes": bytes2
2913
+ }
2914
+ })
2915
+ ),
2916
+ {
2917
+ concurrency: partConcurrency,
2918
+ discard: true
2919
+ }
2920
+ );
2921
+ retain(revision, retained, retainedBytes);
2922
+ const meta = documentMeta(document);
2923
+ return { revision, pages, ...meta === void 0 ? {} : { meta } };
2924
+ });
2925
+ let reading;
2926
+ const current = Effect_exports.suspend(() => {
2927
+ const shared = reading;
2928
+ if (shared !== void 0) return Deferred_exports.await(shared);
2929
+ const deferred = Deferred_exports.makeUnsafe();
2930
+ reading = deferred;
2931
+ return pointer.pipe(
2932
+ Effect_exports.flatMap(
2933
+ (key) => fromPromise(options.cache.get)({
2934
+ key,
2935
+ schema: schema(Manifest),
2936
+ freshFor,
2937
+ staleFor,
2938
+ load: toPromise(refresh)
2939
+ })
2940
+ ),
2941
+ Effect_exports.onExit(
2942
+ (exit) => Effect_exports.sync(() => {
2943
+ if (reading === deferred) reading = void 0;
2944
+ }).pipe(Effect_exports.andThen(Deferred_exports.done(deferred, exit)))
2945
+ )
2946
+ );
2947
+ });
2948
+ const read = (revision, kind, names, decoder) => {
2949
+ const retained = stored.get(revision);
2950
+ return retained === void 0 ? fromPromise(options.cache.readMany)(
2951
+ names.map((name) => partKey(revision, kind, name)),
2952
+ schema(decoder)
2953
+ ) : Effect_exports.forEach(names, (name) => {
2954
+ const value = retained.parts.get(storedPart(kind, name));
2955
+ return value === void 0 ? Effect_exports.succeed(void 0) : Schema_exports.decodeUnknownEffect(decoder)(value);
2956
+ });
2957
+ };
2958
+ const namesFor = (manifest) => Effect_exports.gen(function* () {
2959
+ const names = [];
2960
+ for (let page = 0; page < manifest.pages; page += pageSize) {
2961
+ const pages = yield* read(
2962
+ manifest.revision,
2963
+ "names",
2964
+ Array.from({ length: Math.min(pageSize, manifest.pages - page) }, (_, i) => page + i),
2965
+ Names
2966
+ );
2967
+ for (const values of pages) {
2968
+ if (values === void 0) return void 0;
2969
+ names.push(...values);
2970
+ }
2971
+ }
2972
+ return names;
2973
+ });
2974
+ const definitionsFor = (revision, operation) => Effect_exports.gen(function* () {
2975
+ const definitions = {};
2976
+ const seen = /* @__PURE__ */ new Set();
2977
+ let pending = [...references(operation)];
2978
+ while (pending.length) {
2979
+ const names = [...new Set(pending.splice(0, pageSize * partConcurrency))].filter(
2980
+ (name) => !seen.has(name)
2981
+ );
2982
+ names.forEach((name) => seen.add(name));
2983
+ if (!names.length) continue;
2984
+ const values = (yield* Effect_exports.forEach(
2985
+ Array.from(
2986
+ { length: Math.ceil(names.length / pageSize) },
2987
+ (_, page) => names.slice(page * pageSize, (page + 1) * pageSize)
2988
+ ),
2989
+ (batch) => read(revision, "definition", batch, JsonObject),
2990
+ { concurrency: partConcurrency }
2991
+ )).flat();
2992
+ for (let i = 0; i < names.length; i++) {
2993
+ const name = names[i];
2994
+ const value = values[i];
2995
+ if (name === void 0 || value === void 0) return void 0;
2996
+ definitions[name] = value;
2997
+ pending.push(...references(value));
2998
+ }
2999
+ }
3000
+ return definitions;
3001
+ });
3002
+ const defaultedNames = JSON.stringify(
3003
+ Object.entries(options.parameterDefaults ?? {}).map(([group, values]) => [
3004
+ group,
3005
+ Object.keys(values ?? {}).sort()
3006
+ ])
3007
+ );
3008
+ const kindOf = (op) => {
3009
+ const key = op.operationId ?? op.name;
3010
+ const kinds = options.kinds ?? {};
3011
+ return Object.hasOwn(kinds, key) ? kinds[key] ?? "mutation" : ["GET", "HEAD", "OPTIONS"].includes(op.method) ? "query" : "mutation";
3012
+ };
3013
+ const readOnly = (op) => kindOf(op) === "query";
3014
+ const operationsFor = (manifest) => Effect_exports.gen(function* () {
3015
+ const names = yield* namesFor(manifest);
3016
+ if (names === void 0) return void 0;
3017
+ const pages = yield* Effect_exports.forEach(
3018
+ Array.from(
3019
+ { length: Math.ceil(names.length / pageSize) },
3020
+ (_, page) => names.slice(page * pageSize, (page + 1) * pageSize)
3021
+ ),
3022
+ (batch) => read(manifest.revision, "operation", batch, OpenapiOperation),
3023
+ { concurrency: partConcurrency }
3024
+ );
3025
+ const all = [];
3026
+ for (const operations of pages) {
3027
+ for (const operation of operations) {
3028
+ if (operation === void 0) return void 0;
3029
+ all.push(operation);
3030
+ }
3031
+ }
3032
+ return all;
3033
+ });
3034
+ const summarize = (operation) => ({
3035
+ name: operation.name,
3036
+ description: operation.description,
3037
+ readOnly: readOnly(operation),
3038
+ ...operation.tags === void 0 ? {} : { tags: operation.tags }
3039
+ });
3040
+ const describe = (operation, bundle) => ({
3041
+ ...summarize(operation),
3042
+ inputSchema: bundle(parameterDefaultsInput(operation, options.parameterDefaults, true)),
3043
+ ...operation.outputSchema === void 0 ? {} : { outputSchema: bundle(operation.outputSchema) }
3044
+ });
3045
+ const withRevision = (work) => Effect_exports.gen(function* () {
3046
+ for (let attempt = 0; attempt < 2; attempt++) {
3047
+ const result = yield* work(yield* current);
3048
+ if (result !== void 0) return result.value;
3049
+ yield* fromPromise(options.cache.invalidate)(yield* pointer);
3050
+ }
3051
+ return yield* invalid();
3052
+ });
3053
+ return routerDeclaration({
3054
+ kind: "dynamic",
3055
+ meta: () => current.pipe(Effect_exports.map((manifest) => manifest.meta ?? {})),
3056
+ resolve: (name) => withRevision(
3057
+ (manifest) => Effect_exports.gen(function* () {
3058
+ const raw = name;
3059
+ const memoKey = `${manifest.revision}/${defaultedNames}/${raw}`;
3060
+ const memo = resolved.get(memoKey);
3061
+ const operation = memo?.operation ?? (yield* read(manifest.revision, "operation", [raw], OpenapiOperation))[0];
3062
+ if (operation === void 0) {
3063
+ const names = yield* namesFor(manifest);
3064
+ return names === void 0 || names.includes(raw) ? void 0 : { value: void 0 };
3065
+ }
3066
+ const definitions = memo?.definitions ?? (yield* definitionsFor(manifest.revision, operation));
3067
+ if (definitions === void 0) return void 0;
3068
+ const schemas = memo?.schemas ?? (yield* prepareOpenapiOperation(operation, definitions, options.parameterDefaults));
3069
+ if (memo === void 0) remember(memoKey, { operation, definitions, schemas });
3070
+ const tools = yield* openapiToolsEffect(
3071
+ { ...options, operations: [operation], definitions },
3072
+ /* @__PURE__ */ new Map([[operation.name, schemas]])
3073
+ );
3074
+ const declarations = protocolOperations(tools, {
3075
+ [operation.name]: kindOf(operation)
3076
+ });
3077
+ const declaration = Object.hasOwn(declarations, raw) ? declarations[raw] : void 0;
3078
+ return { value: declaration === void 0 ? void 0 : nativeOperation(declaration) };
3079
+ })
3080
+ ),
3081
+ list: () => withRevision(
3082
+ (manifest) => Effect_exports.gen(function* () {
3083
+ const all = yield* operationsFor(manifest);
3084
+ if (all === void 0) return void 0;
3085
+ const definitions = yield* definitionsFor(manifest.revision, all);
3086
+ if (definitions === void 0) return void 0;
3087
+ const bundle = bundler(definitions);
3088
+ const request = createRequest(options);
3089
+ return {
3090
+ value: all.filter((op) => request.available(op, options.account)).map((operation) => describe(operation, bundle))
3091
+ };
3092
+ })
3093
+ ),
3094
+ summaries: () => withRevision(
3095
+ (manifest) => Effect_exports.gen(function* () {
3096
+ const all = yield* operationsFor(manifest);
3097
+ if (all === void 0) return void 0;
3098
+ const request = createRequest(options);
3099
+ return {
3100
+ value: all.filter((op) => request.available(op, options.account)).map((operation) => summarize(operation))
3101
+ };
3102
+ })
3103
+ ),
3104
+ describe: (name) => withRevision(
3105
+ (manifest) => Effect_exports.gen(function* () {
3106
+ const raw = name;
3107
+ const operation = (yield* read(
3108
+ manifest.revision,
3109
+ "operation",
3110
+ [raw],
3111
+ OpenapiOperation
3112
+ ))[0];
3113
+ if (operation === void 0) {
3114
+ const names = yield* namesFor(manifest);
3115
+ return names === void 0 || names.includes(raw) ? void 0 : { value: void 0 };
3116
+ }
3117
+ if (!createRequest(options).available(operation, options.account))
3118
+ return { value: void 0 };
3119
+ const definitions = yield* definitionsFor(manifest.revision, operation);
3120
+ if (definitions === void 0) return void 0;
3121
+ return { value: describe(operation, bundler(definitions)) };
3122
+ })
3123
+ )
3124
+ });
3125
+ };
3126
+
3127
+ // src/openapi.ts
3128
+ var openapiRouter = (options, kinds = {}) => Effect_exports.runPromise(
3129
+ openapiToolsEffect(options).pipe(Effect_exports.map((operations) => protocolRouter(operations, kinds))),
241
3130
  options.signal === void 0 ? {} : { signal: options.signal }
242
3131
  );
243
3132
  export {
3133
+ OpenapiCompileError,
3134
+ OpenapiCompileErrorCode,
244
3135
  OpenapiError,
245
- openapiOperations
3136
+ OpenapiErrorResponse,
3137
+ OpenapiParameter,
3138
+ OpenapiRequestBody,
3139
+ isOpenapiTextMedia,
3140
+ liveOpenapiRouter,
3141
+ openapiBinaryResultSchema,
3142
+ openapiMediaKind,
3143
+ openapiRouter
246
3144
  };