@tracken/cli 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +404 -0
  2. package/LICENSE +21 -0
  3. package/README.md +310 -2
  4. package/dist/bin/tracken.d.ts +2 -0
  5. package/dist/bin/tracken.js +5 -0
  6. package/dist/cli/args.d.ts +17 -0
  7. package/dist/cli/args.js +114 -0
  8. package/dist/cli/commands/api.d.ts +2 -0
  9. package/dist/cli/commands/api.js +73 -0
  10. package/dist/cli/commands/auth.d.ts +8 -0
  11. package/dist/cli/commands/auth.js +141 -0
  12. package/dist/cli/commands/mcp.d.ts +19 -0
  13. package/dist/cli/commands/mcp.js +89 -0
  14. package/dist/cli/commands/org.d.ts +24 -0
  15. package/dist/cli/commands/org.js +123 -0
  16. package/dist/cli/context.d.ts +54 -0
  17. package/dist/cli/context.js +135 -0
  18. package/dist/cli/execute.d.ts +16 -0
  19. package/dist/cli/execute.js +112 -0
  20. package/dist/cli/help.d.ts +8 -0
  21. package/dist/cli/help.js +153 -0
  22. package/dist/cli/main.d.ts +2 -0
  23. package/dist/cli/main.js +114 -0
  24. package/dist/cli/operation-args.d.ts +25 -0
  25. package/dist/cli/operation-args.js +245 -0
  26. package/dist/core/auth/oauth.d.ts +39 -0
  27. package/dist/core/auth/oauth.js +102 -0
  28. package/dist/core/auth/scopes.d.ts +19 -0
  29. package/dist/core/auth/scopes.js +49 -0
  30. package/dist/core/auth/secret-store.d.ts +60 -0
  31. package/dist/core/auth/secret-store.js +141 -0
  32. package/dist/core/auth/session.d.ts +75 -0
  33. package/dist/core/auth/session.js +200 -0
  34. package/dist/core/catalog.d.ts +12 -0
  35. package/dist/core/catalog.js +33 -0
  36. package/dist/core/client.d.ts +22 -0
  37. package/dist/core/client.js +45 -0
  38. package/dist/core/config.d.ts +27 -0
  39. package/dist/core/config.js +109 -0
  40. package/dist/core/environments.d.ts +21 -0
  41. package/dist/core/environments.js +53 -0
  42. package/dist/core/errors.d.ts +96 -0
  43. package/dist/core/errors.js +248 -0
  44. package/dist/core/index.d.ts +21 -0
  45. package/dist/core/index.js +22 -0
  46. package/dist/core/jobs.d.ts +15 -0
  47. package/dist/core/jobs.js +19 -0
  48. package/dist/core/operations.d.ts +108 -0
  49. package/dist/core/operations.js +7 -0
  50. package/dist/core/output/format.d.ts +19 -0
  51. package/dist/core/output/format.js +62 -0
  52. package/dist/core/output/render.d.ts +53 -0
  53. package/dist/core/output/render.js +229 -0
  54. package/dist/core/pagination.d.ts +2 -0
  55. package/dist/core/pagination.js +3 -0
  56. package/dist/core/request.d.ts +29 -0
  57. package/dist/core/request.js +109 -0
  58. package/dist/core/version.d.ts +10 -0
  59. package/dist/core/version.js +13 -0
  60. package/dist/generated/mcp-tools.d.ts +2 -0
  61. package/dist/generated/mcp-tools.js +5937 -0
  62. package/dist/generated/operations.d.ts +4 -0
  63. package/dist/generated/operations.js +17701 -0
  64. package/dist/mcp/errors.d.ts +34 -0
  65. package/dist/mcp/errors.js +100 -0
  66. package/dist/mcp/live.d.ts +3 -0
  67. package/dist/mcp/live.js +5 -0
  68. package/dist/mcp/prompts.d.ts +23 -0
  69. package/dist/mcp/prompts.js +101 -0
  70. package/dist/mcp/resources.d.ts +25 -0
  71. package/dist/mcp/resources.js +125 -0
  72. package/dist/mcp/server.d.ts +20 -0
  73. package/dist/mcp/server.js +59 -0
  74. package/dist/mcp/session.d.ts +60 -0
  75. package/dist/mcp/session.js +105 -0
  76. package/dist/mcp/tools.d.ts +17 -0
  77. package/dist/mcp/tools.js +181 -0
  78. package/dist/mcp/types.d.ts +25 -0
  79. package/dist/mcp/types.js +2 -0
  80. package/node_modules/@tracken/sdk/LICENSE +21 -0
  81. package/node_modules/@tracken/sdk/README.md +76 -0
  82. package/node_modules/@tracken/sdk/SOURCE.json +10 -0
  83. package/node_modules/@tracken/sdk/dist/client.d.ts +94 -0
  84. package/node_modules/@tracken/sdk/dist/client.js +258 -0
  85. package/node_modules/@tracken/sdk/dist/credentials.d.ts +60 -0
  86. package/node_modules/@tracken/sdk/dist/credentials.js +122 -0
  87. package/node_modules/@tracken/sdk/dist/decimal.d.ts +20 -0
  88. package/node_modules/@tracken/sdk/dist/decimal.js +67 -0
  89. package/node_modules/@tracken/sdk/dist/environments.d.ts +14 -0
  90. package/node_modules/@tracken/sdk/dist/environments.js +16 -0
  91. package/node_modules/@tracken/sdk/dist/errors.d.ts +150 -0
  92. package/node_modules/@tracken/sdk/dist/errors.js +190 -0
  93. package/node_modules/@tracken/sdk/dist/generated/operations.d.ts +1955 -0
  94. package/node_modules/@tracken/sdk/dist/generated/operations.js +2746 -0
  95. package/node_modules/@tracken/sdk/dist/generated/schema.d.ts +17988 -0
  96. package/node_modules/@tracken/sdk/dist/generated/schema.js +5 -0
  97. package/node_modules/@tracken/sdk/dist/index.d.ts +27 -0
  98. package/node_modules/@tracken/sdk/dist/index.js +24 -0
  99. package/node_modules/@tracken/sdk/dist/jobs.d.ts +23 -0
  100. package/node_modules/@tracken/sdk/dist/jobs.js +80 -0
  101. package/node_modules/@tracken/sdk/dist/operations.d.ts +23 -0
  102. package/node_modules/@tracken/sdk/dist/operations.js +2 -0
  103. package/node_modules/@tracken/sdk/dist/pagination.d.ts +19 -0
  104. package/node_modules/@tracken/sdk/dist/pagination.js +49 -0
  105. package/node_modules/@tracken/sdk/dist/request.d.ts +27 -0
  106. package/node_modules/@tracken/sdk/dist/request.js +10 -0
  107. package/node_modules/@tracken/sdk/dist/runtime.d.ts +22 -0
  108. package/node_modules/@tracken/sdk/dist/runtime.js +33 -0
  109. package/node_modules/@tracken/sdk/dist/tracken.d.ts +74 -0
  110. package/node_modules/@tracken/sdk/dist/tracken.js +203 -0
  111. package/node_modules/@tracken/sdk/dist/types.d.ts +130 -0
  112. package/node_modules/@tracken/sdk/dist/types.js +1 -0
  113. package/node_modules/@tracken/sdk/dist/version.d.ts +2 -0
  114. package/node_modules/@tracken/sdk/dist/version.js +2 -0
  115. package/node_modules/@tracken/sdk/package.json +42 -0
  116. package/node_modules/openapi-fetch/CHANGELOG.md +565 -0
  117. package/node_modules/openapi-fetch/CONTRIBUTING.md +102 -0
  118. package/node_modules/openapi-fetch/LICENSE +21 -0
  119. package/node_modules/openapi-fetch/README.md +122 -0
  120. package/node_modules/openapi-fetch/dist/index.cjs +547 -0
  121. package/node_modules/openapi-fetch/dist/index.cjs.map +1 -0
  122. package/node_modules/openapi-fetch/dist/index.d.cts +337 -0
  123. package/node_modules/openapi-fetch/dist/index.d.mts +335 -0
  124. package/node_modules/openapi-fetch/dist/index.d.ts +337 -0
  125. package/node_modules/openapi-fetch/dist/index.mjs +531 -0
  126. package/node_modules/openapi-fetch/dist/index.mjs.map +1 -0
  127. package/node_modules/openapi-fetch/package.json +77 -0
  128. package/node_modules/openapi-fetch/src/index.d.ts +345 -0
  129. package/node_modules/openapi-fetch/src/index.js +689 -0
  130. package/node_modules/openapi-typescript-helpers/CHANGELOG.md +98 -0
  131. package/node_modules/openapi-typescript-helpers/LICENSE +21 -0
  132. package/node_modules/openapi-typescript-helpers/README.md +5 -0
  133. package/node_modules/openapi-typescript-helpers/dist/index.cjs +3 -0
  134. package/node_modules/openapi-typescript-helpers/dist/index.cjs.map +1 -0
  135. package/node_modules/openapi-typescript-helpers/dist/index.d.cts +167 -0
  136. package/node_modules/openapi-typescript-helpers/dist/index.d.mts +167 -0
  137. package/node_modules/openapi-typescript-helpers/dist/index.d.ts +167 -0
  138. package/node_modules/openapi-typescript-helpers/dist/index.mjs +2 -0
  139. package/node_modules/openapi-typescript-helpers/dist/index.mjs.map +1 -0
  140. package/node_modules/openapi-typescript-helpers/package.json +39 -0
  141. package/openapi/SOURCE.json +10 -0
  142. package/openapi/openapi.yaml +30514 -0
  143. package/package.json +63 -4
@@ -0,0 +1,689 @@
1
+ // settings & const
2
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
3
+
4
+ const supportsRequestInitExt = () => {
5
+ return (
6
+ typeof process === "object" &&
7
+ Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 &&
8
+ process.versions.undici
9
+ );
10
+ };
11
+
12
+ /**
13
+ * Returns a cheap, non-cryptographically-secure random ID
14
+ * Courtesy of @imranbarbhuiya (https://github.com/imranbarbhuiya)
15
+ */
16
+ export function randomID() {
17
+ return Math.random().toString(36).slice(2, 11);
18
+ }
19
+
20
+ /**
21
+ * Create an openapi-fetch client.
22
+ * @type {import("./index.js").default}
23
+ */
24
+ export default function createClient(clientOptions) {
25
+ let {
26
+ baseUrl = "",
27
+ Request: CustomRequest = globalThis.Request,
28
+ fetch: baseFetch = globalThis.fetch,
29
+ querySerializer: globalQuerySerializer,
30
+ bodySerializer: globalBodySerializer,
31
+ pathSerializer: globalPathSerializer,
32
+ headers: baseHeaders,
33
+ requestInitExt = undefined,
34
+ ...baseOptions
35
+ } = { ...clientOptions };
36
+ requestInitExt = supportsRequestInitExt() ? requestInitExt : undefined;
37
+ baseUrl = removeTrailingSlash(baseUrl);
38
+ const globalMiddlewares = [];
39
+
40
+ /**
41
+ * Per-request fetch (keeps settings created in createClient()
42
+ * @param {T} url
43
+ * @param {import('./index.js').FetchOptions<T>} fetchOptions
44
+ */
45
+ async function coreFetch(schemaPath, fetchOptions) {
46
+ const {
47
+ baseUrl: localBaseUrl,
48
+ fetch = baseFetch,
49
+ Request = CustomRequest,
50
+ headers,
51
+ params = {},
52
+ parseAs = "json",
53
+ querySerializer: requestQuerySerializer,
54
+ bodySerializer = globalBodySerializer ?? defaultBodySerializer,
55
+ pathSerializer: requestPathSerializer,
56
+ body,
57
+ middleware: requestMiddlewares = [],
58
+ ...init
59
+ } = fetchOptions || {};
60
+ let finalBaseUrl = baseUrl;
61
+ if (localBaseUrl) {
62
+ finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;
63
+ }
64
+
65
+ let querySerializer =
66
+ typeof globalQuerySerializer === "function"
67
+ ? globalQuerySerializer
68
+ : createQuerySerializer(globalQuerySerializer);
69
+ if (requestQuerySerializer) {
70
+ querySerializer =
71
+ typeof requestQuerySerializer === "function"
72
+ ? requestQuerySerializer
73
+ : createQuerySerializer({
74
+ ...(typeof globalQuerySerializer === "object" ? globalQuerySerializer : {}),
75
+ ...requestQuerySerializer,
76
+ });
77
+ }
78
+
79
+ const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;
80
+
81
+ const serializedBody =
82
+ body === undefined
83
+ ? undefined
84
+ : bodySerializer(
85
+ body,
86
+ // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:
87
+ // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,
88
+ // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,
89
+ // setting the content-type at the very beginning to be overwritten.
90
+ // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.
91
+ mergeHeaders(baseHeaders, headers, params.header),
92
+ );
93
+ const finalHeaders = mergeHeaders(
94
+ // with no body, we should not to set Content-Type
95
+ serializedBody === undefined ||
96
+ // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
97
+ serializedBody instanceof FormData
98
+ ? {}
99
+ : {
100
+ "Content-Type": "application/json",
101
+ },
102
+ baseHeaders,
103
+ headers,
104
+ params.header,
105
+ );
106
+
107
+ // Client level middleware take priority over request-level middleware
108
+ const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];
109
+
110
+ const requestInit = {
111
+ redirect: "follow",
112
+ ...baseOptions,
113
+ ...init,
114
+ body: serializedBody,
115
+ headers: finalHeaders,
116
+ };
117
+
118
+ let id;
119
+ let options;
120
+ let request = new Request(
121
+ createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer, pathSerializer }),
122
+ requestInit,
123
+ );
124
+ let response;
125
+
126
+ /** Add custom parameters to Request object */
127
+ for (const key in init) {
128
+ if (!(key in request)) {
129
+ request[key] = init[key];
130
+ }
131
+ }
132
+
133
+ if (finalMiddlewares.length) {
134
+ id = randomID();
135
+
136
+ // middleware (request)
137
+ options = Object.freeze({
138
+ baseUrl: finalBaseUrl,
139
+ fetch,
140
+ parseAs,
141
+ querySerializer,
142
+ bodySerializer,
143
+ pathSerializer,
144
+ });
145
+ for (const m of finalMiddlewares) {
146
+ if (m && typeof m === "object" && typeof m.onRequest === "function") {
147
+ const result = await m.onRequest({
148
+ request,
149
+ schemaPath,
150
+ params,
151
+ options,
152
+ id,
153
+ });
154
+ if (result) {
155
+ if (result instanceof Request) {
156
+ request = result;
157
+ } else if (result instanceof Response) {
158
+ response = result;
159
+ break;
160
+ } else {
161
+ throw new Error("onRequest: must return new Request() or Response() when modifying the request");
162
+ }
163
+ }
164
+ }
165
+ }
166
+ }
167
+
168
+ if (!response) {
169
+ // fetch!
170
+ try {
171
+ response = await fetch(request, requestInitExt);
172
+ } catch (error) {
173
+ let errorAfterMiddleware = error;
174
+ // middleware (error)
175
+ // execute in reverse-array order (first priority gets last transform)
176
+ if (finalMiddlewares.length) {
177
+ for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
178
+ const m = finalMiddlewares[i];
179
+ if (m && typeof m === "object" && typeof m.onError === "function") {
180
+ const result = await m.onError({
181
+ request,
182
+ error: errorAfterMiddleware,
183
+ schemaPath,
184
+ params,
185
+ options,
186
+ id,
187
+ });
188
+ if (result) {
189
+ // if error is handled by returning a response, skip remaining middleware
190
+ if (result instanceof Response) {
191
+ errorAfterMiddleware = undefined;
192
+ response = result;
193
+ break;
194
+ }
195
+
196
+ if (result instanceof Error) {
197
+ errorAfterMiddleware = result;
198
+ continue;
199
+ }
200
+
201
+ throw new Error("onError: must return new Response() or instance of Error");
202
+ }
203
+ }
204
+ }
205
+ }
206
+
207
+ // rethrow error if not handled by middleware
208
+ if (errorAfterMiddleware) {
209
+ throw errorAfterMiddleware;
210
+ }
211
+ }
212
+
213
+ // middleware (response)
214
+ // execute in reverse-array order (first priority gets last transform)
215
+ if (finalMiddlewares.length) {
216
+ for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
217
+ const m = finalMiddlewares[i];
218
+ if (m && typeof m === "object" && typeof m.onResponse === "function") {
219
+ const result = await m.onResponse({
220
+ request,
221
+ response,
222
+ schemaPath,
223
+ params,
224
+ options,
225
+ id,
226
+ });
227
+ if (result) {
228
+ if (!(result instanceof Response)) {
229
+ throw new Error("onResponse: must return new Response() when modifying the response");
230
+ }
231
+ response = result;
232
+ }
233
+ }
234
+ }
235
+ }
236
+ }
237
+
238
+ const contentLength = response.headers.get("Content-Length");
239
+ // handle empty content
240
+ if (
241
+ response.status === 204 ||
242
+ request.method === "HEAD" ||
243
+ (contentLength === "0" && !response.headers.get("Transfer-Encoding")?.includes("chunked"))
244
+ ) {
245
+ return response.ok ? { data: undefined, response } : { error: undefined, response };
246
+ }
247
+
248
+ // parse response (falling back to .text() when necessary)
249
+ if (response.ok) {
250
+ const getResponseData = async () => {
251
+ // if "stream", skip parsing entirely
252
+ if (parseAs === "stream") {
253
+ return response.body;
254
+ }
255
+
256
+ if (parseAs === "json" && !contentLength) {
257
+ // use text() when no content-length is provided to avoid errors parsing empty bodies (200 with no content)
258
+ const raw = await response.text();
259
+ return raw ? JSON.parse(raw) : undefined;
260
+ }
261
+
262
+ return await response[parseAs]();
263
+ };
264
+ return { data: await getResponseData(), response };
265
+ }
266
+
267
+ // handle errors
268
+ let error = await response.text();
269
+ try {
270
+ error = JSON.parse(error); // attempt to parse as JSON
271
+ } catch {
272
+ // noop
273
+ }
274
+ return { error, response };
275
+ }
276
+
277
+ return {
278
+ request(method, url, init) {
279
+ return coreFetch(url, { ...init, method: method.toUpperCase() });
280
+ },
281
+ /** Call a GET endpoint */
282
+ GET(url, init) {
283
+ return coreFetch(url, { ...init, method: "GET" });
284
+ },
285
+ /** Call a PUT endpoint */
286
+ PUT(url, init) {
287
+ return coreFetch(url, { ...init, method: "PUT" });
288
+ },
289
+ /** Call a POST endpoint */
290
+ POST(url, init) {
291
+ return coreFetch(url, { ...init, method: "POST" });
292
+ },
293
+ /** Call a DELETE endpoint */
294
+ DELETE(url, init) {
295
+ return coreFetch(url, { ...init, method: "DELETE" });
296
+ },
297
+ /** Call a OPTIONS endpoint */
298
+ OPTIONS(url, init) {
299
+ return coreFetch(url, { ...init, method: "OPTIONS" });
300
+ },
301
+ /** Call a HEAD endpoint */
302
+ HEAD(url, init) {
303
+ return coreFetch(url, { ...init, method: "HEAD" });
304
+ },
305
+ /** Call a PATCH endpoint */
306
+ PATCH(url, init) {
307
+ return coreFetch(url, { ...init, method: "PATCH" });
308
+ },
309
+ /** Call a TRACE endpoint */
310
+ TRACE(url, init) {
311
+ return coreFetch(url, { ...init, method: "TRACE" });
312
+ },
313
+ /** Register middleware */
314
+ use(...middleware) {
315
+ for (const m of middleware) {
316
+ if (!m) {
317
+ continue;
318
+ }
319
+ if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) {
320
+ throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
321
+ }
322
+ globalMiddlewares.push(m);
323
+ }
324
+ },
325
+ /** Unregister middleware */
326
+ eject(...middleware) {
327
+ for (const m of middleware) {
328
+ const i = globalMiddlewares.indexOf(m);
329
+ if (i !== -1) {
330
+ globalMiddlewares.splice(i, 1);
331
+ }
332
+ }
333
+ },
334
+ };
335
+ }
336
+
337
+ class PathCallForwarder {
338
+ constructor(client, url) {
339
+ this.client = client;
340
+ this.url = url;
341
+ }
342
+
343
+ GET = (init) => {
344
+ return this.client.GET(this.url, init);
345
+ };
346
+ PUT = (init) => {
347
+ return this.client.PUT(this.url, init);
348
+ };
349
+ POST = (init) => {
350
+ return this.client.POST(this.url, init);
351
+ };
352
+ DELETE = (init) => {
353
+ return this.client.DELETE(this.url, init);
354
+ };
355
+ OPTIONS = (init) => {
356
+ return this.client.OPTIONS(this.url, init);
357
+ };
358
+ HEAD = (init) => {
359
+ return this.client.HEAD(this.url, init);
360
+ };
361
+ PATCH = (init) => {
362
+ return this.client.PATCH(this.url, init);
363
+ };
364
+ TRACE = (init) => {
365
+ return this.client.TRACE(this.url, init);
366
+ };
367
+ }
368
+
369
+ class PathClientProxyHandler {
370
+ constructor() {
371
+ this.client = null;
372
+ }
373
+
374
+ // Assume the property is an URL.
375
+ get(coreClient, url) {
376
+ const forwarder = new PathCallForwarder(coreClient, url);
377
+ this.client[url] = forwarder;
378
+ return forwarder;
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Wrap openapi-fetch client to support a path based API.
384
+ * @type {import("./index.js").wrapAsPathBasedClient}
385
+ */
386
+ export function wrapAsPathBasedClient(coreClient) {
387
+ const handler = new PathClientProxyHandler();
388
+ const proxy = new Proxy(coreClient, handler);
389
+
390
+ // Put the proxy on the prototype chain of the actual client.
391
+ // This means if we do not have a memoized PathCallForwarder,
392
+ // we fall back to the proxy to synthesize it.
393
+ // However, the proxy itself is not on the hot-path (if we fetch the same
394
+ // endpoint multiple times, only the first call will hit the proxy).
395
+ function Client() {}
396
+ Client.prototype = proxy;
397
+
398
+ const client = new Client();
399
+
400
+ // Feed the client back to the proxy handler so it can store the generated
401
+ // PathCallForwarder.
402
+ handler.client = client;
403
+
404
+ return client;
405
+ }
406
+
407
+ /**
408
+ * Convenience method to an openapi-fetch path based client.
409
+ * Strictly equivalent to `wrapAsPathBasedClient(createClient(...))`.
410
+ * @type {import("./index.js").createPathBasedClient}
411
+ */
412
+ export function createPathBasedClient(clientOptions) {
413
+ return wrapAsPathBasedClient(createClient(clientOptions));
414
+ }
415
+
416
+ // utils
417
+
418
+ /**
419
+ * Serialize primitive param values
420
+ * @type {import("./index.js").serializePrimitiveParam}
421
+ */
422
+ export function serializePrimitiveParam(name, value, options) {
423
+ if (value === undefined || value === null) {
424
+ return "";
425
+ }
426
+ if (typeof value === "object") {
427
+ throw new Error(
428
+ "Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.",
429
+ );
430
+ }
431
+ return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
432
+ }
433
+
434
+ /**
435
+ * Serialize object param (shallow only)
436
+ * @type {import("./index.js").serializeObjectParam}
437
+ */
438
+ export function serializeObjectParam(name, value, options) {
439
+ if (!value || typeof value !== "object") {
440
+ return "";
441
+ }
442
+ const values = [];
443
+ const joiner =
444
+ {
445
+ simple: ",",
446
+ label: ".",
447
+ matrix: ";",
448
+ }[options.style] || "&";
449
+
450
+ // explode: false
451
+ if (options.style !== "deepObject" && options.explode === false) {
452
+ for (const k in value) {
453
+ values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
454
+ }
455
+ const final = values.join(","); // note: values are always joined by comma in explode: false (but joiner can prefix)
456
+ switch (options.style) {
457
+ case "form": {
458
+ return `${name}=${final}`;
459
+ }
460
+ case "label": {
461
+ return `.${final}`;
462
+ }
463
+ case "matrix": {
464
+ return `;${name}=${final}`;
465
+ }
466
+ default: {
467
+ return final;
468
+ }
469
+ }
470
+ }
471
+
472
+ // explode: true
473
+ for (const k in value) {
474
+ const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
475
+ values.push(serializePrimitiveParam(finalName, value[k], options));
476
+ }
477
+ const final = values.join(joiner);
478
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
479
+ }
480
+
481
+ /**
482
+ * Serialize array param (shallow only)
483
+ * @type {import("./index.js").serializeArrayParam}
484
+ */
485
+ export function serializeArrayParam(name, value, options) {
486
+ if (!Array.isArray(value)) {
487
+ return "";
488
+ }
489
+
490
+ // explode: false
491
+ if (options.explode === false) {
492
+ const joiner = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[options.style] || ","; // note: for arrays, joiners vary wildly based on style + explode behavior
493
+ const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner);
494
+ switch (options.style) {
495
+ case "simple": {
496
+ return final;
497
+ }
498
+ case "label": {
499
+ return `.${final}`;
500
+ }
501
+ case "matrix": {
502
+ return `;${name}=${final}`;
503
+ }
504
+ // case "spaceDelimited":
505
+ // case "pipeDelimited":
506
+ default: {
507
+ return `${name}=${final}`;
508
+ }
509
+ }
510
+ }
511
+
512
+ // explode: true
513
+ const joiner = { simple: ",", label: ".", matrix: ";" }[options.style] || "&";
514
+ const values = [];
515
+ for (const v of value) {
516
+ if (options.style === "simple" || options.style === "label") {
517
+ values.push(options.allowReserved === true ? v : encodeURIComponent(v));
518
+ } else {
519
+ values.push(serializePrimitiveParam(name, v, options));
520
+ }
521
+ }
522
+ return options.style === "label" || options.style === "matrix"
523
+ ? `${joiner}${values.join(joiner)}`
524
+ : values.join(joiner);
525
+ }
526
+
527
+ /**
528
+ * Serialize query params to string
529
+ * @type {import("./index.js").createQuerySerializer}
530
+ */
531
+ export function createQuerySerializer(options) {
532
+ return function querySerializer(queryParams) {
533
+ const search = [];
534
+ if (queryParams && typeof queryParams === "object") {
535
+ for (const name in queryParams) {
536
+ const value = queryParams[name];
537
+ if (value === undefined || value === null) {
538
+ continue;
539
+ }
540
+ if (Array.isArray(value)) {
541
+ if (value.length === 0) {
542
+ continue;
543
+ }
544
+ search.push(
545
+ serializeArrayParam(name, value, {
546
+ style: "form",
547
+ explode: true,
548
+ ...options?.array,
549
+ allowReserved: options?.allowReserved || false,
550
+ }),
551
+ );
552
+ continue;
553
+ }
554
+ if (typeof value === "object") {
555
+ search.push(
556
+ serializeObjectParam(name, value, {
557
+ style: "deepObject",
558
+ explode: true,
559
+ ...options?.object,
560
+ allowReserved: options?.allowReserved || false,
561
+ }),
562
+ );
563
+ continue;
564
+ }
565
+ search.push(serializePrimitiveParam(name, value, options));
566
+ }
567
+ }
568
+ return search.join("&");
569
+ };
570
+ }
571
+
572
+ /**
573
+ * Handle different OpenAPI 3.x serialization styles
574
+ * @type {import("./index.js").defaultPathSerializer}
575
+ * @see https://swagger.io/docs/specification/serialization/#path
576
+ */
577
+ export function defaultPathSerializer(pathname, pathParams) {
578
+ let nextURL = pathname;
579
+ for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
580
+ let name = match.substring(1, match.length - 1);
581
+ let explode = false;
582
+ let style = "simple";
583
+ if (name.endsWith("*")) {
584
+ explode = true;
585
+ name = name.substring(0, name.length - 1);
586
+ }
587
+ if (name.startsWith(".")) {
588
+ style = "label";
589
+ name = name.substring(1);
590
+ } else if (name.startsWith(";")) {
591
+ style = "matrix";
592
+ name = name.substring(1);
593
+ }
594
+ if (!pathParams || pathParams[name] === undefined || pathParams[name] === null) {
595
+ continue;
596
+ }
597
+ const value = pathParams[name];
598
+ if (Array.isArray(value)) {
599
+ nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));
600
+ continue;
601
+ }
602
+ if (typeof value === "object") {
603
+ nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));
604
+ continue;
605
+ }
606
+ if (style === "matrix") {
607
+ nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
608
+ continue;
609
+ }
610
+ nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
611
+ }
612
+ return nextURL;
613
+ }
614
+
615
+ /**
616
+ * Serialize body object to string
617
+ * @type {import("./index.js").defaultBodySerializer}
618
+ */
619
+ export function defaultBodySerializer(body, headers) {
620
+ if (body instanceof FormData) {
621
+ return body;
622
+ }
623
+ if (headers) {
624
+ const contentType =
625
+ headers.get instanceof Function
626
+ ? (headers.get("Content-Type") ?? headers.get("content-type"))
627
+ : (headers["Content-Type"] ?? headers["content-type"]);
628
+ if (contentType === "application/x-www-form-urlencoded") {
629
+ return new URLSearchParams(body).toString();
630
+ }
631
+ }
632
+ return JSON.stringify(body);
633
+ }
634
+
635
+ /**
636
+ * Construct URL string from baseUrl and handle path and query params
637
+ * @type {import("./index.js").createFinalURL}
638
+ */
639
+ export function createFinalURL(pathname, options) {
640
+ let finalURL = `${options.baseUrl}${pathname}`;
641
+ if (options.params?.path) {
642
+ finalURL = options.pathSerializer(finalURL, options.params.path);
643
+ }
644
+ let search = options.querySerializer(options.params.query ?? {});
645
+ if (search.startsWith("?")) {
646
+ search = search.substring(1);
647
+ }
648
+ if (search) {
649
+ finalURL += `?${search}`;
650
+ }
651
+ return finalURL;
652
+ }
653
+
654
+ /**
655
+ * Merge headers a and b, with b taking priority
656
+ * @type {import("./index.js").mergeHeaders}
657
+ */
658
+ export function mergeHeaders(...allHeaders) {
659
+ const finalHeaders = new Headers();
660
+ for (const h of allHeaders) {
661
+ if (!h || typeof h !== "object") {
662
+ continue;
663
+ }
664
+ const iterator = h instanceof Headers ? h.entries() : Object.entries(h);
665
+ for (const [k, v] of iterator) {
666
+ if (v === null) {
667
+ finalHeaders.delete(k);
668
+ } else if (Array.isArray(v)) {
669
+ for (const v2 of v) {
670
+ finalHeaders.append(k, v2);
671
+ }
672
+ } else if (v !== undefined) {
673
+ finalHeaders.set(k, v);
674
+ }
675
+ }
676
+ }
677
+ return finalHeaders;
678
+ }
679
+
680
+ /**
681
+ * Remove trailing slash from url
682
+ * @type {import("./index.js").removeTrailingSlash}
683
+ */
684
+ export function removeTrailingSlash(url) {
685
+ if (url.endsWith("/")) {
686
+ return url.substring(0, url.length - 1);
687
+ }
688
+ return url;
689
+ }