@orq-ai/node 3.1.7 → 3.2.0-rc.3

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 (147) hide show
  1. package/README.md +0 -38
  2. package/docs/sdks/deployments/README.md +0 -81
  3. package/jsr.json +1 -2
  4. package/lib/config.d.ts +3 -3
  5. package/lib/config.js +3 -3
  6. package/lib/config.js.map +1 -1
  7. package/lib/matchers.d.ts.map +1 -1
  8. package/lib/matchers.js +1 -4
  9. package/lib/matchers.js.map +1 -1
  10. package/models/operations/createcontact.js +2 -2
  11. package/models/operations/fileget.js +2 -2
  12. package/models/operations/filelist.js +2 -2
  13. package/models/operations/fileupload.js +2 -2
  14. package/models/operations/index.d.ts +0 -1
  15. package/models/operations/index.d.ts.map +1 -1
  16. package/models/operations/index.js +0 -1
  17. package/models/operations/index.js.map +1 -1
  18. package/package.json +3 -2
  19. package/sdk/deployments.d.ts +0 -8
  20. package/sdk/deployments.d.ts.map +1 -1
  21. package/sdk/deployments.js +0 -10
  22. package/sdk/deployments.js.map +1 -1
  23. package/src/lib/config.ts +3 -3
  24. package/src/lib/matchers.ts +1 -4
  25. package/src/models/operations/createcontact.ts +2 -2
  26. package/src/models/operations/fileget.ts +2 -2
  27. package/src/models/operations/filelist.ts +2 -2
  28. package/src/models/operations/fileupload.ts +2 -2
  29. package/src/models/operations/index.ts +0 -1
  30. package/src/sdk/deployments.ts +0 -19
  31. package/funcs/deploymentsStream.d.ts +0 -16
  32. package/funcs/deploymentsStream.d.ts.map +0 -1
  33. package/funcs/deploymentsStream.js +0 -126
  34. package/funcs/deploymentsStream.js.map +0 -1
  35. package/lib/event-streams.d.ts +0 -17
  36. package/lib/event-streams.d.ts.map +0 -1
  37. package/lib/event-streams.js +0 -220
  38. package/lib/event-streams.js.map +0 -1
  39. package/models/operations/deploymentstream.d.ts +0 -1622
  40. package/models/operations/deploymentstream.d.ts.map +0 -1
  41. package/models/operations/deploymentstream.js +0 -1571
  42. package/models/operations/deploymentstream.js.map +0 -1
  43. package/packages/orq-rc/FUNCTIONS.md +0 -106
  44. package/packages/orq-rc/README.md +0 -506
  45. package/packages/orq-rc/RUNTIMES.md +0 -48
  46. package/packages/orq-rc/docs/sdks/contacts/README.md +0 -84
  47. package/packages/orq-rc/docs/sdks/deployments/README.md +0 -235
  48. package/packages/orq-rc/docs/sdks/feedback/README.md +0 -92
  49. package/packages/orq-rc/docs/sdks/files/README.md +0 -305
  50. package/packages/orq-rc/docs/sdks/metrics/README.md +0 -86
  51. package/packages/orq-rc/docs/sdks/orq/README.md +0 -10
  52. package/packages/orq-rc/docs/sdks/prompts/README.md +0 -608
  53. package/packages/orq-rc/docs/sdks/remoteconfigs/README.md +0 -80
  54. package/packages/orq-rc/jsr.json +0 -27
  55. package/packages/orq-rc/package-lock.json +0 -1861
  56. package/packages/orq-rc/package.json +0 -31
  57. package/packages/orq-rc/src/core.ts +0 -13
  58. package/packages/orq-rc/src/funcs/contactsCreate.ts +0 -127
  59. package/packages/orq-rc/src/funcs/deploymentsGetConfig.ts +0 -135
  60. package/packages/orq-rc/src/funcs/deploymentsInvoke.ts +0 -143
  61. package/packages/orq-rc/src/funcs/deploymentsList.ts +0 -142
  62. package/packages/orq-rc/src/funcs/deploymentsMetricsCreate.ts +0 -135
  63. package/packages/orq-rc/src/funcs/feedbackCreate.ts +0 -127
  64. package/packages/orq-rc/src/funcs/filesCreate.ts +0 -150
  65. package/packages/orq-rc/src/funcs/filesDelete.ts +0 -131
  66. package/packages/orq-rc/src/funcs/filesGet.ts +0 -133
  67. package/packages/orq-rc/src/funcs/filesList.ts +0 -134
  68. package/packages/orq-rc/src/funcs/promptsCreate.ts +0 -127
  69. package/packages/orq-rc/src/funcs/promptsDelete.ts +0 -131
  70. package/packages/orq-rc/src/funcs/promptsGetVersion.ts +0 -147
  71. package/packages/orq-rc/src/funcs/promptsList.ts +0 -134
  72. package/packages/orq-rc/src/funcs/promptsListVersions.ts +0 -140
  73. package/packages/orq-rc/src/funcs/promptsRetrieve.ts +0 -133
  74. package/packages/orq-rc/src/funcs/promptsUpdate.ts +0 -139
  75. package/packages/orq-rc/src/funcs/remoteconfigsRetrieve.ts +0 -128
  76. package/packages/orq-rc/src/hooks/global.ts +0 -44
  77. package/packages/orq-rc/src/hooks/hooks.ts +0 -132
  78. package/packages/orq-rc/src/hooks/index.ts +0 -6
  79. package/packages/orq-rc/src/hooks/registration.ts +0 -15
  80. package/packages/orq-rc/src/hooks/types.ts +0 -110
  81. package/packages/orq-rc/src/index.ts +0 -7
  82. package/packages/orq-rc/src/lib/base64.ts +0 -37
  83. package/packages/orq-rc/src/lib/config.ts +0 -70
  84. package/packages/orq-rc/src/lib/dlv.ts +0 -53
  85. package/packages/orq-rc/src/lib/encodings.ts +0 -483
  86. package/packages/orq-rc/src/lib/env.ts +0 -73
  87. package/packages/orq-rc/src/lib/files.ts +0 -40
  88. package/packages/orq-rc/src/lib/http.ts +0 -323
  89. package/packages/orq-rc/src/lib/is-plain-object.ts +0 -43
  90. package/packages/orq-rc/src/lib/logger.ts +0 -9
  91. package/packages/orq-rc/src/lib/matchers.ts +0 -322
  92. package/packages/orq-rc/src/lib/primitives.ts +0 -136
  93. package/packages/orq-rc/src/lib/retries.ts +0 -218
  94. package/packages/orq-rc/src/lib/schemas.ts +0 -91
  95. package/packages/orq-rc/src/lib/sdks.ts +0 -400
  96. package/packages/orq-rc/src/lib/security.ts +0 -253
  97. package/packages/orq-rc/src/lib/url.ts +0 -33
  98. package/packages/orq-rc/src/models/components/deployments.ts +0 -1666
  99. package/packages/orq-rc/src/models/components/index.ts +0 -6
  100. package/packages/orq-rc/src/models/components/security.ts +0 -71
  101. package/packages/orq-rc/src/models/errors/apierror.ts +0 -27
  102. package/packages/orq-rc/src/models/errors/getpromptversion.ts +0 -71
  103. package/packages/orq-rc/src/models/errors/honoapierror.ts +0 -82
  104. package/packages/orq-rc/src/models/errors/httpclienterrors.ts +0 -62
  105. package/packages/orq-rc/src/models/errors/index.ts +0 -10
  106. package/packages/orq-rc/src/models/errors/sdkvalidationerror.ts +0 -97
  107. package/packages/orq-rc/src/models/errors/updateprompt.ts +0 -71
  108. package/packages/orq-rc/src/models/operations/createcontact.ts +0 -256
  109. package/packages/orq-rc/src/models/operations/createfeedback.ts +0 -286
  110. package/packages/orq-rc/src/models/operations/createprompt.ts +0 -3717
  111. package/packages/orq-rc/src/models/operations/deleteprompt.ts +0 -69
  112. package/packages/orq-rc/src/models/operations/deploymentcreatemetric.ts +0 -1790
  113. package/packages/orq-rc/src/models/operations/deploymentgetconfig.ts +0 -3527
  114. package/packages/orq-rc/src/models/operations/deploymentinvoke.ts +0 -1144
  115. package/packages/orq-rc/src/models/operations/deployments.ts +0 -2148
  116. package/packages/orq-rc/src/models/operations/filedelete.ts +0 -78
  117. package/packages/orq-rc/src/models/operations/fileget.ts +0 -222
  118. package/packages/orq-rc/src/models/operations/filelist.ts +0 -336
  119. package/packages/orq-rc/src/models/operations/fileupload.ts +0 -322
  120. package/packages/orq-rc/src/models/operations/getallprompts.ts +0 -2116
  121. package/packages/orq-rc/src/models/operations/getoneprompt.ts +0 -1982
  122. package/packages/orq-rc/src/models/operations/getpromptversion.ts +0 -2012
  123. package/packages/orq-rc/src/models/operations/index.ts +0 -22
  124. package/packages/orq-rc/src/models/operations/listpromptversions.ts +0 -2146
  125. package/packages/orq-rc/src/models/operations/remoteconfigsgetconfig.ts +0 -190
  126. package/packages/orq-rc/src/models/operations/updateprompt.ts +0 -3900
  127. package/packages/orq-rc/src/sdk/contacts.ts +0 -27
  128. package/packages/orq-rc/src/sdk/deployments.ts +0 -70
  129. package/packages/orq-rc/src/sdk/feedback.ts +0 -27
  130. package/packages/orq-rc/src/sdk/files.ts +0 -78
  131. package/packages/orq-rc/src/sdk/index.ts +0 -5
  132. package/packages/orq-rc/src/sdk/metrics.ts +0 -27
  133. package/packages/orq-rc/src/sdk/prompts.ts +0 -126
  134. package/packages/orq-rc/src/sdk/remoteconfigs.ts +0 -24
  135. package/packages/orq-rc/src/sdk/sdk.ts +0 -43
  136. package/packages/orq-rc/src/types/blobs.ts +0 -31
  137. package/packages/orq-rc/src/types/constdatetime.ts +0 -15
  138. package/packages/orq-rc/src/types/enums.ts +0 -16
  139. package/packages/orq-rc/src/types/fp.ts +0 -50
  140. package/packages/orq-rc/src/types/index.ts +0 -11
  141. package/packages/orq-rc/src/types/operations.ts +0 -105
  142. package/packages/orq-rc/src/types/rfcdate.ts +0 -54
  143. package/packages/orq-rc/src/types/streams.ts +0 -21
  144. package/packages/orq-rc/tsconfig.json +0 -41
  145. package/src/funcs/deploymentsStream.ts +0 -151
  146. package/src/lib/event-streams.ts +0 -264
  147. package/src/models/operations/deploymentstream.ts +0 -3062
@@ -1,323 +0,0 @@
1
- /*
2
- * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
3
- */
4
-
5
- export type Fetcher = (
6
- input: RequestInfo | URL,
7
- init?: RequestInit,
8
- ) => Promise<Response>;
9
-
10
- export type Awaitable<T> = T | Promise<T>;
11
-
12
- const DEFAULT_FETCHER: Fetcher = (input, init) => {
13
- // If input is a Request and init is undefined, Bun will discard the method,
14
- // headers, body and other options that were set on the request object.
15
- // Node.js and browers would ignore an undefined init value. This check is
16
- // therefore needed for interop with Bun.
17
- if (init == null) {
18
- return fetch(input);
19
- } else {
20
- return fetch(input, init);
21
- }
22
- };
23
-
24
- export type RequestInput = {
25
- /**
26
- * The URL the request will use.
27
- */
28
- url: URL;
29
- /**
30
- * Options used to create a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).
31
- */
32
- options?: RequestInit | undefined;
33
- };
34
-
35
- export interface HTTPClientOptions {
36
- fetcher?: Fetcher;
37
- }
38
-
39
- export type BeforeRequestHook = (req: Request) => Awaitable<Request | void>;
40
- export type RequestErrorHook = (err: unknown, req: Request) => Awaitable<void>;
41
- export type ResponseHook = (res: Response, req: Request) => Awaitable<void>;
42
-
43
- export class HTTPClient {
44
- private fetcher: Fetcher;
45
- private requestHooks: BeforeRequestHook[] = [];
46
- private requestErrorHooks: RequestErrorHook[] = [];
47
- private responseHooks: ResponseHook[] = [];
48
-
49
- constructor(private options: HTTPClientOptions = {}) {
50
- this.fetcher = options.fetcher || DEFAULT_FETCHER;
51
- }
52
-
53
- async request(request: Request): Promise<Response> {
54
- let req = request;
55
- for (const hook of this.requestHooks) {
56
- const nextRequest = await hook(req);
57
- if (nextRequest) {
58
- req = nextRequest;
59
- }
60
- }
61
-
62
- try {
63
- const res = await this.fetcher(req);
64
-
65
- for (const hook of this.responseHooks) {
66
- await hook(res, req);
67
- }
68
-
69
- return res;
70
- } catch (err) {
71
- for (const hook of this.requestErrorHooks) {
72
- await hook(err, req);
73
- }
74
-
75
- throw err;
76
- }
77
- }
78
-
79
- /**
80
- * Registers a hook that is called before a request is made. The hook function
81
- * can mutate the request or return a new request. This may be useful to add
82
- * additional information to request such as request IDs and tracing headers.
83
- */
84
- addHook(hook: "beforeRequest", fn: BeforeRequestHook): this;
85
- /**
86
- * Registers a hook that is called when a request cannot be made due to a
87
- * network error.
88
- */
89
- addHook(hook: "requestError", fn: RequestErrorHook): this;
90
- /**
91
- * Registers a hook that is called when a response has been received from the
92
- * server.
93
- */
94
- addHook(hook: "response", fn: ResponseHook): this;
95
- addHook(
96
- ...args:
97
- | [hook: "beforeRequest", fn: BeforeRequestHook]
98
- | [hook: "requestError", fn: RequestErrorHook]
99
- | [hook: "response", fn: ResponseHook]
100
- ) {
101
- if (args[0] === "beforeRequest") {
102
- this.requestHooks.push(args[1]);
103
- } else if (args[0] === "requestError") {
104
- this.requestErrorHooks.push(args[1]);
105
- } else if (args[0] === "response") {
106
- this.responseHooks.push(args[1]);
107
- } else {
108
- throw new Error(`Invalid hook type: ${args[0]}`);
109
- }
110
- return this;
111
- }
112
-
113
- /** Removes a hook that was previously registered with `addHook`. */
114
- removeHook(hook: "beforeRequest", fn: BeforeRequestHook): this;
115
- /** Removes a hook that was previously registered with `addHook`. */
116
- removeHook(hook: "requestError", fn: RequestErrorHook): this;
117
- /** Removes a hook that was previously registered with `addHook`. */
118
- removeHook(hook: "response", fn: ResponseHook): this;
119
- removeHook(
120
- ...args:
121
- | [hook: "beforeRequest", fn: BeforeRequestHook]
122
- | [hook: "requestError", fn: RequestErrorHook]
123
- | [hook: "response", fn: ResponseHook]
124
- ): this {
125
- let target: unknown[];
126
- if (args[0] === "beforeRequest") {
127
- target = this.requestHooks;
128
- } else if (args[0] === "requestError") {
129
- target = this.requestErrorHooks;
130
- } else if (args[0] === "response") {
131
- target = this.responseHooks;
132
- } else {
133
- throw new Error(`Invalid hook type: ${args[0]}`);
134
- }
135
-
136
- const index = target.findIndex((v) => v === args[1]);
137
- if (index >= 0) {
138
- target.splice(index, 1);
139
- }
140
-
141
- return this;
142
- }
143
-
144
- clone(): HTTPClient {
145
- const child = new HTTPClient(this.options);
146
- child.requestHooks = this.requestHooks.slice();
147
- child.requestErrorHooks = this.requestErrorHooks.slice();
148
- child.responseHooks = this.responseHooks.slice();
149
-
150
- return child;
151
- }
152
- }
153
-
154
- export type StatusCodePredicate = number | string | (number | string)[];
155
-
156
- // A semicolon surrounded by optional whitespace characters is used to separate
157
- // segments in a media type string.
158
- const mediaParamSeparator = /\s*;\s*/g;
159
-
160
- export function matchContentType(response: Response, pattern: string): boolean {
161
- // `*` is a special case which means anything is acceptable.
162
- if (pattern === "*") {
163
- return true;
164
- }
165
-
166
- let contentType =
167
- response.headers.get("content-type")?.trim() || "application/octet-stream";
168
- contentType = contentType.toLowerCase();
169
-
170
- const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator);
171
- const [wantType = "", ...wantParams] = wantParts;
172
-
173
- if (wantType.split("/").length !== 2) {
174
- return false;
175
- }
176
-
177
- const gotParts = contentType.split(mediaParamSeparator);
178
- const [gotType = "", ...gotParams] = gotParts;
179
-
180
- const [type = "", subtype = ""] = gotType.split("/");
181
- if (!type || !subtype) {
182
- return false;
183
- }
184
-
185
- if (
186
- wantType !== "*/*" &&
187
- gotType !== wantType &&
188
- `${type}/*` !== wantType &&
189
- `*/${subtype}` !== wantType
190
- ) {
191
- return false;
192
- }
193
-
194
- if (gotParams.length < wantParams.length) {
195
- return false;
196
- }
197
-
198
- const params = new Set(gotParams);
199
- for (const wantParam of wantParams) {
200
- if (!params.has(wantParam)) {
201
- return false;
202
- }
203
- }
204
-
205
- return true;
206
- }
207
-
208
- const codeRangeRE = new RegExp("^[0-9]xx$", "i");
209
-
210
- export function matchStatusCode(
211
- response: Response,
212
- codes: StatusCodePredicate,
213
- ): boolean {
214
- const actual = `${response.status}`;
215
- const expectedCodes = Array.isArray(codes) ? codes : [codes];
216
- if (!expectedCodes.length) {
217
- return false;
218
- }
219
-
220
- return expectedCodes.some((ec) => {
221
- const code = `${ec}`;
222
-
223
- if (code === "default") {
224
- return true;
225
- }
226
-
227
- if (!codeRangeRE.test(`${code}`)) {
228
- return code === actual;
229
- }
230
-
231
- const expectFamily = code.charAt(0);
232
- if (!expectFamily) {
233
- throw new Error("Invalid status code range");
234
- }
235
-
236
- const actualFamily = actual.charAt(0);
237
- if (!actualFamily) {
238
- throw new Error(`Invalid response status code: ${actual}`);
239
- }
240
-
241
- return actualFamily === expectFamily;
242
- });
243
- }
244
-
245
- export function matchResponse(
246
- response: Response,
247
- code: StatusCodePredicate,
248
- contentTypePattern: string,
249
- ): boolean {
250
- return (
251
- matchStatusCode(response, code) &&
252
- matchContentType(response, contentTypePattern)
253
- );
254
- }
255
-
256
- /**
257
- * Uses various heurisitics to determine if an error is a connection error.
258
- */
259
- export function isConnectionError(err: unknown): boolean {
260
- if (typeof err !== "object" || err == null) {
261
- return false;
262
- }
263
-
264
- // Covers fetch in Deno as well
265
- const isBrowserErr =
266
- err instanceof TypeError &&
267
- err.message.toLowerCase().startsWith("failed to fetch");
268
-
269
- const isNodeErr =
270
- err instanceof TypeError &&
271
- err.message.toLowerCase().startsWith("fetch failed");
272
-
273
- const isBunErr = "name" in err && err.name === "ConnectionError";
274
-
275
- const isGenericErr =
276
- "code" in err &&
277
- typeof err.code === "string" &&
278
- err.code.toLowerCase() === "econnreset";
279
-
280
- return isBrowserErr || isNodeErr || isGenericErr || isBunErr;
281
- }
282
-
283
- /**
284
- * Uses various heurisitics to determine if an error is a timeout error.
285
- */
286
- export function isTimeoutError(err: unknown): boolean {
287
- if (typeof err !== "object" || err == null) {
288
- return false;
289
- }
290
-
291
- // Fetch in browser, Node.js, Bun, Deno
292
- const isNative = "name" in err && err.name === "TimeoutError";
293
- const isLegacyNative = "code" in err && err.code === 23;
294
-
295
- // Node.js HTTP client and Axios
296
- const isGenericErr =
297
- "code" in err &&
298
- typeof err.code === "string" &&
299
- err.code.toLowerCase() === "econnaborted";
300
-
301
- return isNative || isLegacyNative || isGenericErr;
302
- }
303
-
304
- /**
305
- * Uses various heurisitics to determine if an error is a abort error.
306
- */
307
- export function isAbortError(err: unknown): boolean {
308
- if (typeof err !== "object" || err == null) {
309
- return false;
310
- }
311
-
312
- // Fetch in browser, Node.js, Bun, Deno
313
- const isNative = "name" in err && err.name === "AbortError";
314
- const isLegacyNative = "code" in err && err.code === 20;
315
-
316
- // Node.js HTTP client and Axios
317
- const isGenericErr =
318
- "code" in err &&
319
- typeof err.code === "string" &&
320
- err.code.toLowerCase() === "econnaborted";
321
-
322
- return isNative || isLegacyNative || isGenericErr;
323
- }
@@ -1,43 +0,0 @@
1
- /*
2
- * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
3
- */
4
-
5
- /*
6
- MIT License
7
-
8
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
9
-
10
- Permission is hereby granted, free of charge, to any person obtaining a copy of
11
- this software and associated documentation files (the "Software"), to deal in
12
- the Software without restriction, including without limitation the rights to
13
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
14
- the Software, and to permit persons to whom the Software is furnished to do so,
15
- subject to the following conditions:
16
-
17
- The above copyright notice and this permission notice shall be included in all
18
- copies or substantial portions of the Software.
19
-
20
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
22
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
23
- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24
- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25
- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
- */
27
-
28
- // Taken from https://github.com/sindresorhus/is-plain-obj/blob/97f38e8836f86a642cce98fc6ab3058bc36df181/index.js
29
-
30
- export function isPlainObject(value: unknown): value is object {
31
- if (typeof value !== "object" || value === null) {
32
- return false;
33
- }
34
-
35
- const prototype = Object.getPrototypeOf(value);
36
- return (
37
- (prototype === null ||
38
- prototype === Object.prototype ||
39
- Object.getPrototypeOf(prototype) === null) &&
40
- !(Symbol.toStringTag in value) &&
41
- !(Symbol.iterator in value)
42
- );
43
- }
@@ -1,9 +0,0 @@
1
- /*
2
- * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
3
- */
4
-
5
- export interface Logger {
6
- group(label?: string): void;
7
- groupEnd(): void;
8
- log(message: any, ...args: any[]): void;
9
- }
@@ -1,322 +0,0 @@
1
- /*
2
- * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
3
- */
4
-
5
- import { APIError } from "../models/errors/apierror.js";
6
- import { SDKValidationError } from "../models/errors/sdkvalidationerror.js";
7
- import { Result } from "../types/fp.js";
8
- import { matchResponse, matchStatusCode, StatusCodePredicate } from "./http.js";
9
- import { isPlainObject } from "./is-plain-object.js";
10
- import { safeParse } from "./schemas.js";
11
-
12
- export type Encoding =
13
- | "json"
14
- | "text"
15
- | "bytes"
16
- | "stream"
17
- | "sse"
18
- | "nil"
19
- | "fail";
20
-
21
- const DEFAULT_CONTENT_TYPES: Record<Encoding, string> = {
22
- json: "application/json",
23
- text: "text/plain",
24
- bytes: "application/octet-stream",
25
- stream: "application/octet-stream",
26
- sse: "text/event-stream",
27
- nil: "*",
28
- fail: "*",
29
- };
30
-
31
- type Schema<T> = { parse(raw: unknown): T };
32
-
33
- type MatchOptions = {
34
- ctype?: string;
35
- hdrs?: boolean;
36
- key?: string;
37
- sseSentinel?: string;
38
- };
39
-
40
- export type ValueMatcher<V> = MatchOptions & {
41
- enc: Encoding;
42
- codes: StatusCodePredicate;
43
- schema: Schema<V>;
44
- };
45
-
46
- export type ErrorMatcher<E> = MatchOptions & {
47
- enc: Encoding;
48
- codes: StatusCodePredicate;
49
- schema: Schema<E>;
50
- err: true;
51
- };
52
-
53
- export type FailMatcher = {
54
- enc: "fail";
55
- codes: StatusCodePredicate;
56
- };
57
-
58
- export type Matcher<T, E> = ValueMatcher<T> | ErrorMatcher<E> | FailMatcher;
59
-
60
- export function jsonErr<E>(
61
- codes: StatusCodePredicate,
62
- schema: Schema<E>,
63
- options?: MatchOptions,
64
- ): ErrorMatcher<E> {
65
- return { ...options, err: true, enc: "json", codes, schema };
66
- }
67
- export function json<T>(
68
- codes: StatusCodePredicate,
69
- schema: Schema<T>,
70
- options?: MatchOptions,
71
- ): ValueMatcher<T> {
72
- return { ...options, enc: "json", codes, schema };
73
- }
74
-
75
- export function textErr<E>(
76
- codes: StatusCodePredicate,
77
- schema: Schema<E>,
78
- options?: MatchOptions,
79
- ): ErrorMatcher<E> {
80
- return { ...options, err: true, enc: "text", codes, schema };
81
- }
82
- export function text<T>(
83
- codes: StatusCodePredicate,
84
- schema: Schema<T>,
85
- options?: MatchOptions,
86
- ): ValueMatcher<T> {
87
- return { ...options, enc: "text", codes, schema };
88
- }
89
-
90
- export function bytesErr<E>(
91
- codes: StatusCodePredicate,
92
- schema: Schema<E>,
93
- options?: MatchOptions,
94
- ): ErrorMatcher<E> {
95
- return { ...options, err: true, enc: "bytes", codes, schema };
96
- }
97
- export function bytes<T>(
98
- codes: StatusCodePredicate,
99
- schema: Schema<T>,
100
- options?: MatchOptions,
101
- ): ValueMatcher<T> {
102
- return { ...options, enc: "bytes", codes, schema };
103
- }
104
-
105
- export function streamErr<E>(
106
- codes: StatusCodePredicate,
107
- schema: Schema<E>,
108
- options?: MatchOptions,
109
- ): ErrorMatcher<E> {
110
- return { ...options, err: true, enc: "stream", codes, schema };
111
- }
112
- export function stream<T>(
113
- codes: StatusCodePredicate,
114
- schema: Schema<T>,
115
- options?: MatchOptions,
116
- ): ValueMatcher<T> {
117
- return { ...options, enc: "stream", codes, schema };
118
- }
119
-
120
- export function sseErr<E>(
121
- codes: StatusCodePredicate,
122
- schema: Schema<E>,
123
- options?: MatchOptions,
124
- ): ErrorMatcher<E> {
125
- return { ...options, err: true, enc: "sse", codes, schema };
126
- }
127
- export function sse<T>(
128
- codes: StatusCodePredicate,
129
- schema: Schema<T>,
130
- options?: MatchOptions,
131
- ): ValueMatcher<T> {
132
- return { ...options, enc: "sse", codes, schema };
133
- }
134
-
135
- export function nilErr<E>(
136
- codes: StatusCodePredicate,
137
- schema: Schema<E>,
138
- options?: MatchOptions,
139
- ): ErrorMatcher<E> {
140
- return { ...options, err: true, enc: "nil", codes, schema };
141
- }
142
- export function nil<T>(
143
- codes: StatusCodePredicate,
144
- schema: Schema<T>,
145
- options?: MatchOptions,
146
- ): ValueMatcher<T> {
147
- return { ...options, enc: "nil", codes, schema };
148
- }
149
-
150
- export function fail(codes: StatusCodePredicate): FailMatcher {
151
- return { enc: "fail", codes };
152
- }
153
-
154
- export type MatchedValue<Matchers> = Matchers extends Matcher<infer T, any>[]
155
- ? T
156
- : never;
157
- export type MatchedError<Matchers> = Matchers extends Matcher<any, infer E>[]
158
- ? E
159
- : never;
160
- export type MatchFunc<T, E> = (
161
- response: Response,
162
- options?: { resultKey?: string; extraFields?: Record<string, unknown> },
163
- ) => Promise<[result: Result<T, E>, raw: unknown]>;
164
-
165
- export function match<T, E>(
166
- ...matchers: Array<Matcher<T, E>>
167
- ): MatchFunc<T, E | APIError | SDKValidationError> {
168
- return async function matchFunc(
169
- response: Response,
170
- options?: { resultKey?: string; extraFields?: Record<string, unknown> },
171
- ): Promise<
172
- [result: Result<T, E | APIError | SDKValidationError>, raw: unknown]
173
- > {
174
- let raw: unknown;
175
- let matcher: Matcher<T, E> | undefined;
176
- for (const match of matchers) {
177
- const { codes } = match;
178
- const ctpattern = "ctype" in match
179
- ? match.ctype
180
- : DEFAULT_CONTENT_TYPES[match.enc];
181
- if (ctpattern && matchResponse(response, codes, ctpattern)) {
182
- matcher = match;
183
- break;
184
- } else if (!ctpattern && matchStatusCode(response, codes)) {
185
- matcher = match;
186
- break;
187
- }
188
- }
189
-
190
- if (!matcher) {
191
- const responseBody = await response.text();
192
- return [{
193
- ok: false,
194
- error: new APIError(
195
- "Unexpected API response status or content-type",
196
- response,
197
- responseBody,
198
- ),
199
- }, responseBody];
200
- }
201
-
202
- const encoding = matcher.enc;
203
- switch (encoding) {
204
- case "json":
205
- raw = await response.json();
206
- break;
207
- case "bytes":
208
- raw = new Uint8Array(await response.arrayBuffer());
209
- break;
210
- case "stream":
211
- raw = response.body;
212
- break;
213
- case "text":
214
- raw = await response.text();
215
- break;
216
- case "sse":
217
- raw = response.body;
218
- break;
219
- case "nil":
220
- raw = await discardResponseBody(response);
221
- break;
222
- case "fail":
223
- raw = await response.text();
224
- break;
225
- default:
226
- encoding satisfies never;
227
- throw new Error(`Unsupported response type: ${encoding}`);
228
- }
229
-
230
- if (matcher.enc === "fail") {
231
- return [{
232
- ok: false,
233
- error: new APIError(
234
- "API error occurred",
235
- response,
236
- typeof raw === "string" ? raw : "",
237
- ),
238
- }, raw];
239
- }
240
-
241
- const resultKey = matcher.key || options?.resultKey;
242
- let data: unknown;
243
-
244
- if ("err" in matcher) {
245
- data = {
246
- ...options?.extraFields,
247
- ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null),
248
- ...(isPlainObject(raw) ? raw : null),
249
- };
250
- } else if (resultKey) {
251
- data = {
252
- ...options?.extraFields,
253
- ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null),
254
- [resultKey]: raw,
255
- };
256
- } else if (matcher.hdrs) {
257
- data = {
258
- ...options?.extraFields,
259
- ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null),
260
- ...(isPlainObject(raw) ? raw : null),
261
- };
262
- } else {
263
- data = raw;
264
- }
265
-
266
- if ("err" in matcher) {
267
- const result = safeParse(
268
- data,
269
- (v: unknown) => matcher.schema.parse(v),
270
- "Response validation failed",
271
- );
272
- return [result.ok ? { ok: false, error: result.value } : result, raw];
273
- } else {
274
- return [
275
- safeParse(
276
- data,
277
- (v: unknown) => matcher.schema.parse(v),
278
- "Response validation failed",
279
- ),
280
- raw,
281
- ];
282
- }
283
- };
284
- }
285
-
286
- const headerValRE = /, */;
287
- /**
288
- * Iterates over a Headers object and returns an object with all the header
289
- * entries. Values are represented as an array to account for repeated headers.
290
- */
291
- export function unpackHeaders(headers: Headers): Record<string, string[]> {
292
- const out: Record<string, string[]> = {};
293
-
294
- for (const [k, v] of headers.entries()) {
295
- out[k] = v.split(headerValRE);
296
- }
297
-
298
- return out;
299
- }
300
-
301
- /**
302
- * Discards the response body to free up resources.
303
- *
304
- * To learn why this is need, see the undici docs:
305
- * https://undici.nodejs.org/#/?id=garbage-collection
306
- */
307
- export async function discardResponseBody(res: Response) {
308
- const reader = res.body?.getReader();
309
- if (reader == null) {
310
- return;
311
- }
312
-
313
- try {
314
- let done = false;
315
- while (!done) {
316
- const res = await reader.read();
317
- done = res.done;
318
- }
319
- } finally {
320
- reader.releaseLock();
321
- }
322
- }