@roarkanalytics/sdk 0.1.0-alpha.1 → 0.1.0-alpha.3
Sign up to get free protection for your applications and to get access to all the features.
- package/CHANGELOG.md +16 -0
- package/LICENSE +1 -1
- package/README.md +48 -85
- package/_shims/MultipartBody.d.ts +9 -0
- package/_shims/MultipartBody.d.ts.map +1 -0
- package/_shims/MultipartBody.js +16 -0
- package/_shims/MultipartBody.js.map +1 -0
- package/_shims/MultipartBody.mjs +12 -0
- package/_shims/MultipartBody.mjs.map +1 -0
- package/_shims/README.md +46 -0
- package/_shims/auto/runtime-bun.d.ts +5 -0
- package/_shims/auto/runtime-bun.d.ts.map +1 -0
- package/{internal/utils.js → _shims/auto/runtime-bun.js} +5 -8
- package/_shims/auto/runtime-bun.js.map +1 -0
- package/_shims/auto/runtime-bun.mjs +2 -0
- package/_shims/auto/runtime-bun.mjs.map +1 -0
- package/_shims/auto/runtime-node.d.ts +5 -0
- package/_shims/auto/runtime-node.d.ts.map +1 -0
- package/_shims/auto/runtime-node.js +21 -0
- package/_shims/auto/runtime-node.js.map +1 -0
- package/_shims/auto/runtime-node.mjs +2 -0
- package/_shims/auto/runtime-node.mjs.map +1 -0
- package/_shims/auto/runtime.d.ts +5 -0
- package/_shims/auto/runtime.d.ts.map +1 -0
- package/_shims/auto/runtime.js +21 -0
- package/_shims/auto/runtime.js.map +1 -0
- package/_shims/auto/runtime.mjs +2 -0
- package/_shims/auto/runtime.mjs.map +1 -0
- package/_shims/auto/types-node.d.ts +5 -0
- package/_shims/auto/types-node.d.ts.map +1 -0
- package/_shims/auto/types-node.js +21 -0
- package/_shims/auto/types-node.js.map +1 -0
- package/_shims/auto/types-node.mjs +2 -0
- package/_shims/auto/types-node.mjs.map +1 -0
- package/_shims/auto/types.d.ts +101 -0
- package/_shims/auto/types.js +3 -0
- package/_shims/auto/types.mjs +3 -0
- package/_shims/bun-runtime.d.ts +6 -0
- package/_shims/bun-runtime.d.ts.map +1 -0
- package/_shims/bun-runtime.js +14 -0
- package/_shims/bun-runtime.js.map +1 -0
- package/_shims/bun-runtime.mjs +10 -0
- package/_shims/bun-runtime.mjs.map +1 -0
- package/_shims/index.d.ts +81 -0
- package/_shims/index.js +13 -0
- package/_shims/index.mjs +7 -0
- package/_shims/manual-types.d.ts +12 -0
- package/_shims/manual-types.js +3 -0
- package/_shims/manual-types.mjs +3 -0
- package/_shims/node-runtime.d.ts +3 -0
- package/_shims/node-runtime.d.ts.map +1 -0
- package/_shims/node-runtime.js +89 -0
- package/_shims/node-runtime.js.map +1 -0
- package/_shims/node-runtime.mjs +56 -0
- package/_shims/node-runtime.mjs.map +1 -0
- package/_shims/node-types.d.ts +42 -0
- package/_shims/node-types.js +3 -0
- package/_shims/node-types.mjs +3 -0
- package/_shims/registry.d.ts +37 -0
- package/_shims/registry.d.ts.map +1 -0
- package/_shims/registry.js +41 -0
- package/_shims/registry.js.map +1 -0
- package/_shims/registry.mjs +37 -0
- package/_shims/registry.mjs.map +1 -0
- package/_shims/web-runtime.d.ts +5 -0
- package/_shims/web-runtime.d.ts.map +1 -0
- package/_shims/web-runtime.js +78 -0
- package/_shims/web-runtime.js.map +1 -0
- package/_shims/web-runtime.mjs +71 -0
- package/_shims/web-runtime.mjs.map +1 -0
- package/_shims/web-types.d.ts +83 -0
- package/_shims/web-types.js +3 -0
- package/_shims/web-types.mjs +3 -0
- package/core.d.ts +241 -0
- package/core.d.ts.map +1 -0
- package/core.js +908 -0
- package/core.js.map +1 -0
- package/core.mjs +876 -0
- package/core.mjs.map +1 -0
- package/error.d.ts +3 -3
- package/error.d.ts.map +1 -1
- package/error.js +6 -6
- package/error.js.map +1 -1
- package/error.mjs +3 -3
- package/error.mjs.map +1 -1
- package/index.d.mts +109 -5
- package/index.d.ts +109 -5
- package/index.d.ts.map +1 -1
- package/index.js +103 -11
- package/index.js.map +1 -1
- package/index.mjs +77 -5
- package/index.mjs.map +1 -1
- package/package.json +66 -82
- package/resource.d.ts +3 -3
- package/resource.d.ts.map +1 -1
- package/resource.js.map +1 -1
- package/resource.mjs.map +1 -1
- package/resources/calls.d.ts +2 -3
- package/resources/calls.d.ts.map +1 -1
- package/resources/calls.js.map +1 -1
- package/resources/calls.mjs.map +1 -1
- package/resources/index.d.ts.map +1 -1
- package/shims/node.d.ts +30 -0
- package/shims/node.d.ts.map +1 -0
- package/shims/node.js +31 -0
- package/shims/node.js.map +1 -0
- package/shims/node.mjs +5 -0
- package/shims/node.mjs.map +1 -0
- package/shims/web.d.ts +26 -0
- package/shims/web.d.ts.map +1 -0
- package/shims/web.js +31 -0
- package/shims/web.js.map +1 -0
- package/shims/web.mjs +5 -0
- package/shims/web.mjs.map +1 -0
- package/src/_shims/MultipartBody.ts +9 -0
- package/src/_shims/README.md +46 -0
- package/src/_shims/auto/runtime-bun.ts +4 -0
- package/src/_shims/auto/runtime-node.ts +4 -0
- package/src/_shims/auto/runtime.ts +4 -0
- package/src/_shims/auto/types-node.ts +4 -0
- package/src/_shims/auto/types.d.ts +101 -0
- package/src/_shims/auto/types.js +3 -0
- package/src/_shims/auto/types.mjs +3 -0
- package/src/_shims/bun-runtime.ts +14 -0
- package/src/_shims/index.d.ts +81 -0
- package/src/_shims/index.js +13 -0
- package/src/_shims/index.mjs +7 -0
- package/src/_shims/manual-types.d.ts +12 -0
- package/src/_shims/manual-types.js +3 -0
- package/src/_shims/manual-types.mjs +3 -0
- package/src/_shims/node-runtime.ts +81 -0
- package/src/_shims/node-types.d.ts +42 -0
- package/src/_shims/node-types.js +3 -0
- package/src/_shims/node-types.mjs +3 -0
- package/src/_shims/registry.ts +67 -0
- package/src/_shims/web-runtime.ts +103 -0
- package/src/_shims/web-types.d.ts +83 -0
- package/src/_shims/web-types.js +3 -0
- package/src/_shims/web-types.mjs +3 -0
- package/src/core.ts +1200 -0
- package/src/error.ts +3 -3
- package/src/index.ts +172 -5
- package/src/resource.ts +3 -3
- package/src/resources/calls.ts +2 -3
- package/src/shims/node.ts +50 -0
- package/src/shims/web.ts +50 -0
- package/src/tsconfig.json +2 -2
- package/src/uploads.ts +255 -1
- package/src/version.ts +1 -1
- package/uploads.d.ts +74 -1
- package/uploads.d.ts.map +1 -1
- package/uploads.js +168 -3
- package/uploads.js.map +1 -1
- package/uploads.mjs +157 -1
- package/uploads.mjs.map +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
- package/api-promise.d.mts +0 -47
- package/api-promise.d.mts.map +0 -1
- package/api-promise.d.ts +0 -47
- package/api-promise.d.ts.map +0 -1
- package/api-promise.js +0 -84
- package/api-promise.js.map +0 -1
- package/api-promise.mjs +0 -80
- package/api-promise.mjs.map +0 -1
- package/client.d.mts +0 -186
- package/client.d.mts.map +0 -1
- package/client.d.ts +0 -186
- package/client.d.ts.map +0 -1
- package/client.js +0 -449
- package/client.js.map +0 -1
- package/client.mjs +0 -422
- package/client.mjs.map +0 -1
- package/error.d.mts +0 -47
- package/error.d.mts.map +0 -1
- package/index.d.mts.map +0 -1
- package/internal/builtin-types.d.mts +0 -65
- package/internal/builtin-types.d.mts.map +0 -1
- package/internal/builtin-types.d.ts +0 -65
- package/internal/builtin-types.d.ts.map +0 -1
- package/internal/builtin-types.js +0 -4
- package/internal/builtin-types.js.map +0 -1
- package/internal/builtin-types.mjs +0 -3
- package/internal/builtin-types.mjs.map +0 -1
- package/internal/detect-platform.d.mts +0 -15
- package/internal/detect-platform.d.mts.map +0 -1
- package/internal/detect-platform.d.ts +0 -15
- package/internal/detect-platform.d.ts.map +0 -1
- package/internal/detect-platform.js +0 -162
- package/internal/detect-platform.js.map +0 -1
- package/internal/detect-platform.mjs +0 -157
- package/internal/detect-platform.mjs.map +0 -1
- package/internal/errors.d.mts +0 -3
- package/internal/errors.d.mts.map +0 -1
- package/internal/errors.d.ts +0 -3
- package/internal/errors.d.ts.map +0 -1
- package/internal/errors.js +0 -26
- package/internal/errors.js.map +0 -1
- package/internal/errors.mjs +0 -21
- package/internal/errors.mjs.map +0 -1
- package/internal/headers.d.mts +0 -21
- package/internal/headers.d.mts.map +0 -1
- package/internal/headers.d.ts +0 -21
- package/internal/headers.d.ts.map +0 -1
- package/internal/headers.js +0 -77
- package/internal/headers.js.map +0 -1
- package/internal/headers.mjs +0 -72
- package/internal/headers.mjs.map +0 -1
- package/internal/parse.d.mts +0 -10
- package/internal/parse.d.mts.map +0 -1
- package/internal/parse.d.ts +0 -10
- package/internal/parse.d.ts.map +0 -1
- package/internal/parse.js +0 -28
- package/internal/parse.js.map +0 -1
- package/internal/parse.mjs +0 -24
- package/internal/parse.mjs.map +0 -1
- package/internal/polyfill/crypto.node.d.ts +0 -10
- package/internal/polyfill/crypto.node.js +0 -11
- package/internal/polyfill/crypto.node.mjs +0 -2
- package/internal/polyfill/file.node.d.ts +0 -9
- package/internal/polyfill/file.node.js +0 -17
- package/internal/polyfill/file.node.mjs +0 -9
- package/internal/request-options.d.mts +0 -34
- package/internal/request-options.d.mts.map +0 -1
- package/internal/request-options.d.ts +0 -34
- package/internal/request-options.d.ts.map +0 -1
- package/internal/request-options.js +0 -39
- package/internal/request-options.js.map +0 -1
- package/internal/request-options.mjs +0 -34
- package/internal/request-options.mjs.map +0 -1
- package/internal/shim-types.d.mts +0 -28
- package/internal/shim-types.d.ts +0 -28
- package/internal/shims.d.mts +0 -61
- package/internal/shims.d.mts.map +0 -1
- package/internal/shims.d.ts +0 -61
- package/internal/shims.d.ts.map +0 -1
- package/internal/shims.js +0 -101
- package/internal/shims.js.map +0 -1
- package/internal/shims.mjs +0 -92
- package/internal/shims.mjs.map +0 -1
- package/internal/types.d.mts +0 -68
- package/internal/types.d.mts.map +0 -1
- package/internal/types.d.ts +0 -68
- package/internal/types.d.ts.map +0 -1
- package/internal/types.js +0 -4
- package/internal/types.js.map +0 -1
- package/internal/types.mjs +0 -3
- package/internal/types.mjs.map +0 -1
- package/internal/uploads.d.mts +0 -73
- package/internal/uploads.d.mts.map +0 -1
- package/internal/uploads.d.ts +0 -73
- package/internal/uploads.d.ts.map +0 -1
- package/internal/uploads.js +0 -208
- package/internal/uploads.js.map +0 -1
- package/internal/uploads.mjs +0 -200
- package/internal/uploads.mjs.map +0 -1
- package/internal/utils/base64.d.mts +0 -3
- package/internal/utils/base64.d.mts.map +0 -1
- package/internal/utils/base64.d.ts +0 -3
- package/internal/utils/base64.d.ts.map +0 -1
- package/internal/utils/base64.js +0 -33
- package/internal/utils/base64.js.map +0 -1
- package/internal/utils/base64.mjs +0 -28
- package/internal/utils/base64.mjs.map +0 -1
- package/internal/utils/env.d.mts +0 -9
- package/internal/utils/env.d.mts.map +0 -1
- package/internal/utils/env.d.ts +0 -9
- package/internal/utils/env.d.ts.map +0 -1
- package/internal/utils/env.js +0 -22
- package/internal/utils/env.js.map +0 -1
- package/internal/utils/env.mjs +0 -18
- package/internal/utils/env.mjs.map +0 -1
- package/internal/utils/log.d.mts +0 -4
- package/internal/utils/log.d.mts.map +0 -1
- package/internal/utils/log.d.ts +0 -4
- package/internal/utils/log.d.ts.map +0 -1
- package/internal/utils/log.js +0 -47
- package/internal/utils/log.js.map +0 -1
- package/internal/utils/log.mjs +0 -43
- package/internal/utils/log.mjs.map +0 -1
- package/internal/utils/sleep.d.mts +0 -2
- package/internal/utils/sleep.d.mts.map +0 -1
- package/internal/utils/sleep.d.ts +0 -2
- package/internal/utils/sleep.d.ts.map +0 -1
- package/internal/utils/sleep.js +0 -7
- package/internal/utils/sleep.js.map +0 -1
- package/internal/utils/sleep.mjs +0 -3
- package/internal/utils/sleep.mjs.map +0 -1
- package/internal/utils/uuid.d.mts +0 -5
- package/internal/utils/uuid.d.mts.map +0 -1
- package/internal/utils/uuid.d.ts +0 -5
- package/internal/utils/uuid.d.ts.map +0 -1
- package/internal/utils/uuid.js +0 -15
- package/internal/utils/uuid.js.map +0 -1
- package/internal/utils/uuid.mjs +0 -11
- package/internal/utils/uuid.mjs.map +0 -1
- package/internal/utils/values.d.mts +0 -15
- package/internal/utils/values.d.mts.map +0 -1
- package/internal/utils/values.d.ts +0 -15
- package/internal/utils/values.d.ts.map +0 -1
- package/internal/utils/values.js +0 -100
- package/internal/utils/values.js.map +0 -1
- package/internal/utils/values.mjs +0 -84
- package/internal/utils/values.mjs.map +0 -1
- package/internal/utils.d.mts +0 -7
- package/internal/utils.d.mts.map +0 -1
- package/internal/utils.d.ts +0 -7
- package/internal/utils.d.ts.map +0 -1
- package/internal/utils.js.map +0 -1
- package/internal/utils.mjs +0 -8
- package/internal/utils.mjs.map +0 -1
- package/resource.d.mts +0 -6
- package/resource.d.mts.map +0 -1
- package/resources/calls.d.mts +0 -85
- package/resources/calls.d.mts.map +0 -1
- package/resources/index.d.mts +0 -2
- package/resources/index.d.mts.map +0 -1
- package/src/api-promise.ts +0 -92
- package/src/client.ts +0 -646
- package/src/internal/builtin-types.ts +0 -79
- package/src/internal/detect-platform.ts +0 -196
- package/src/internal/errors.ts +0 -22
- package/src/internal/headers.ts +0 -96
- package/src/internal/parse.ts +0 -41
- package/src/internal/polyfill/crypto.node.d.ts +0 -10
- package/src/internal/polyfill/crypto.node.js +0 -11
- package/src/internal/polyfill/crypto.node.mjs +0 -2
- package/src/internal/polyfill/file.node.d.ts +0 -9
- package/src/internal/polyfill/file.node.js +0 -17
- package/src/internal/polyfill/file.node.mjs +0 -9
- package/src/internal/request-options.ts +0 -67
- package/src/internal/shim-types.d.ts +0 -28
- package/src/internal/shims.ts +0 -145
- package/src/internal/types.ts +0 -98
- package/src/internal/uploads.ts +0 -307
- package/src/internal/utils/base64.ts +0 -37
- package/src/internal/utils/env.ts +0 -18
- package/src/internal/utils/log.ts +0 -49
- package/src/internal/utils/sleep.ts +0 -3
- package/src/internal/utils/uuid.ts +0 -13
- package/src/internal/utils/values.ts +0 -94
- package/src/internal/utils.ts +0 -8
- package/uploads.d.mts +0 -2
- package/uploads.d.mts.map +0 -1
- package/version.d.mts +0 -2
- package/version.d.mts.map +0 -1
package/core.mjs
ADDED
@@ -0,0 +1,876 @@
|
|
1
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
2
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
5
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
6
|
+
};
|
7
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
8
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
9
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
10
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
11
|
+
};
|
12
|
+
var _AbstractPage_client;
|
13
|
+
import { VERSION } from "./version.mjs";
|
14
|
+
import { RoarkError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, } from "./error.mjs";
|
15
|
+
import { kind as shimsKind, getDefaultAgent, fetch, } from "./_shims/index.mjs";
|
16
|
+
import { isBlobLike, isMultipartBody } from "./uploads.mjs";
|
17
|
+
export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, } from "./uploads.mjs";
|
18
|
+
async function defaultParseResponse(props) {
|
19
|
+
const { response } = props;
|
20
|
+
// fetch refuses to read the body when the status code is 204.
|
21
|
+
if (response.status === 204) {
|
22
|
+
return null;
|
23
|
+
}
|
24
|
+
if (props.options.__binaryResponse) {
|
25
|
+
return response;
|
26
|
+
}
|
27
|
+
const contentType = response.headers.get('content-type');
|
28
|
+
const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');
|
29
|
+
if (isJSON) {
|
30
|
+
const json = await response.json();
|
31
|
+
debug('response', response.status, response.url, response.headers, json);
|
32
|
+
return json;
|
33
|
+
}
|
34
|
+
const text = await response.text();
|
35
|
+
debug('response', response.status, response.url, response.headers, text);
|
36
|
+
// TODO handle blob, arraybuffer, other content types, etc.
|
37
|
+
return text;
|
38
|
+
}
|
39
|
+
/**
|
40
|
+
* A subclass of `Promise` providing additional helper methods
|
41
|
+
* for interacting with the SDK.
|
42
|
+
*/
|
43
|
+
export class APIPromise extends Promise {
|
44
|
+
constructor(responsePromise, parseResponse = defaultParseResponse) {
|
45
|
+
super((resolve) => {
|
46
|
+
// this is maybe a bit weird but this has to be a no-op to not implicitly
|
47
|
+
// parse the response body; instead .then, .catch, .finally are overridden
|
48
|
+
// to parse the response
|
49
|
+
resolve(null);
|
50
|
+
});
|
51
|
+
this.responsePromise = responsePromise;
|
52
|
+
this.parseResponse = parseResponse;
|
53
|
+
}
|
54
|
+
_thenUnwrap(transform) {
|
55
|
+
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props), props));
|
56
|
+
}
|
57
|
+
/**
|
58
|
+
* Gets the raw `Response` instance instead of parsing the response
|
59
|
+
* data.
|
60
|
+
*
|
61
|
+
* If you want to parse the response body but still get the `Response`
|
62
|
+
* instance, you can use {@link withResponse()}.
|
63
|
+
*
|
64
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
65
|
+
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
66
|
+
* or add one of these imports before your first `import … from '@roarkanalytics/sdk'`:
|
67
|
+
* - `import '@roarkanalytics/sdk/shims/node'` (if you're running on Node)
|
68
|
+
* - `import '@roarkanalytics/sdk/shims/web'` (otherwise)
|
69
|
+
*/
|
70
|
+
asResponse() {
|
71
|
+
return this.responsePromise.then((p) => p.response);
|
72
|
+
}
|
73
|
+
/**
|
74
|
+
* Gets the parsed response data and the raw `Response` instance.
|
75
|
+
*
|
76
|
+
* If you just want to get the raw `Response` instance without parsing it,
|
77
|
+
* you can use {@link asResponse()}.
|
78
|
+
*
|
79
|
+
*
|
80
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
81
|
+
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
82
|
+
* or add one of these imports before your first `import … from '@roarkanalytics/sdk'`:
|
83
|
+
* - `import '@roarkanalytics/sdk/shims/node'` (if you're running on Node)
|
84
|
+
* - `import '@roarkanalytics/sdk/shims/web'` (otherwise)
|
85
|
+
*/
|
86
|
+
async withResponse() {
|
87
|
+
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
|
88
|
+
return { data, response };
|
89
|
+
}
|
90
|
+
parse() {
|
91
|
+
if (!this.parsedPromise) {
|
92
|
+
this.parsedPromise = this.responsePromise.then(this.parseResponse);
|
93
|
+
}
|
94
|
+
return this.parsedPromise;
|
95
|
+
}
|
96
|
+
then(onfulfilled, onrejected) {
|
97
|
+
return this.parse().then(onfulfilled, onrejected);
|
98
|
+
}
|
99
|
+
catch(onrejected) {
|
100
|
+
return this.parse().catch(onrejected);
|
101
|
+
}
|
102
|
+
finally(onfinally) {
|
103
|
+
return this.parse().finally(onfinally);
|
104
|
+
}
|
105
|
+
}
|
106
|
+
export class APIClient {
|
107
|
+
constructor({ baseURL, maxRetries = 2, timeout = 60000, // 1 minute
|
108
|
+
httpAgent, fetch: overriddenFetch, }) {
|
109
|
+
this.baseURL = baseURL;
|
110
|
+
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
|
111
|
+
this.timeout = validatePositiveInteger('timeout', timeout);
|
112
|
+
this.httpAgent = httpAgent;
|
113
|
+
this.fetch = overriddenFetch ?? fetch;
|
114
|
+
}
|
115
|
+
authHeaders(opts) {
|
116
|
+
return {};
|
117
|
+
}
|
118
|
+
/**
|
119
|
+
* Override this to add your own default headers, for example:
|
120
|
+
*
|
121
|
+
* {
|
122
|
+
* ...super.defaultHeaders(),
|
123
|
+
* Authorization: 'Bearer 123',
|
124
|
+
* }
|
125
|
+
*/
|
126
|
+
defaultHeaders(opts) {
|
127
|
+
return {
|
128
|
+
Accept: 'application/json',
|
129
|
+
'Content-Type': 'application/json',
|
130
|
+
'User-Agent': this.getUserAgent(),
|
131
|
+
...getPlatformHeaders(),
|
132
|
+
...this.authHeaders(opts),
|
133
|
+
};
|
134
|
+
}
|
135
|
+
/**
|
136
|
+
* Override this to add your own headers validation:
|
137
|
+
*/
|
138
|
+
validateHeaders(headers, customHeaders) { }
|
139
|
+
defaultIdempotencyKey() {
|
140
|
+
return `stainless-node-retry-${uuid4()}`;
|
141
|
+
}
|
142
|
+
get(path, opts) {
|
143
|
+
return this.methodRequest('get', path, opts);
|
144
|
+
}
|
145
|
+
post(path, opts) {
|
146
|
+
return this.methodRequest('post', path, opts);
|
147
|
+
}
|
148
|
+
patch(path, opts) {
|
149
|
+
return this.methodRequest('patch', path, opts);
|
150
|
+
}
|
151
|
+
put(path, opts) {
|
152
|
+
return this.methodRequest('put', path, opts);
|
153
|
+
}
|
154
|
+
delete(path, opts) {
|
155
|
+
return this.methodRequest('delete', path, opts);
|
156
|
+
}
|
157
|
+
methodRequest(method, path, opts) {
|
158
|
+
return this.request(Promise.resolve(opts).then(async (opts) => {
|
159
|
+
const body = opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer())
|
160
|
+
: opts?.body instanceof DataView ? opts.body
|
161
|
+
: opts?.body instanceof ArrayBuffer ? new DataView(opts.body)
|
162
|
+
: opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)
|
163
|
+
: opts?.body;
|
164
|
+
return { method, path, ...opts, body };
|
165
|
+
}));
|
166
|
+
}
|
167
|
+
getAPIList(path, Page, opts) {
|
168
|
+
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
169
|
+
}
|
170
|
+
calculateContentLength(body) {
|
171
|
+
if (typeof body === 'string') {
|
172
|
+
if (typeof Buffer !== 'undefined') {
|
173
|
+
return Buffer.byteLength(body, 'utf8').toString();
|
174
|
+
}
|
175
|
+
if (typeof TextEncoder !== 'undefined') {
|
176
|
+
const encoder = new TextEncoder();
|
177
|
+
const encoded = encoder.encode(body);
|
178
|
+
return encoded.length.toString();
|
179
|
+
}
|
180
|
+
}
|
181
|
+
else if (ArrayBuffer.isView(body)) {
|
182
|
+
return body.byteLength.toString();
|
183
|
+
}
|
184
|
+
return null;
|
185
|
+
}
|
186
|
+
buildRequest(options, { retryCount = 0 } = {}) {
|
187
|
+
const { method, path, query, headers: headers = {} } = options;
|
188
|
+
const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?
|
189
|
+
options.body
|
190
|
+
: isMultipartBody(options.body) ? options.body.body
|
191
|
+
: options.body ? JSON.stringify(options.body, null, 2)
|
192
|
+
: null;
|
193
|
+
const contentLength = this.calculateContentLength(body);
|
194
|
+
const url = this.buildURL(path, query);
|
195
|
+
if ('timeout' in options)
|
196
|
+
validatePositiveInteger('timeout', options.timeout);
|
197
|
+
const timeout = options.timeout ?? this.timeout;
|
198
|
+
const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
|
199
|
+
const minAgentTimeout = timeout + 1000;
|
200
|
+
if (typeof httpAgent?.options?.timeout === 'number' &&
|
201
|
+
minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
|
202
|
+
// Allow any given request to bump our agent active socket timeout.
|
203
|
+
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
|
204
|
+
// and without mutating agent we would need to create more of them.
|
205
|
+
// This tradeoff optimizes for performance.
|
206
|
+
httpAgent.options.timeout = minAgentTimeout;
|
207
|
+
}
|
208
|
+
if (this.idempotencyHeader && method !== 'get') {
|
209
|
+
if (!options.idempotencyKey)
|
210
|
+
options.idempotencyKey = this.defaultIdempotencyKey();
|
211
|
+
headers[this.idempotencyHeader] = options.idempotencyKey;
|
212
|
+
}
|
213
|
+
const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });
|
214
|
+
const req = {
|
215
|
+
method,
|
216
|
+
...(body && { body: body }),
|
217
|
+
headers: reqHeaders,
|
218
|
+
...(httpAgent && { agent: httpAgent }),
|
219
|
+
// @ts-ignore node-fetch uses a custom AbortSignal type that is
|
220
|
+
// not compatible with standard web types
|
221
|
+
signal: options.signal ?? null,
|
222
|
+
};
|
223
|
+
return { req, url, timeout };
|
224
|
+
}
|
225
|
+
buildHeaders({ options, headers, contentLength, retryCount, }) {
|
226
|
+
const reqHeaders = {};
|
227
|
+
if (contentLength) {
|
228
|
+
reqHeaders['content-length'] = contentLength;
|
229
|
+
}
|
230
|
+
const defaultHeaders = this.defaultHeaders(options);
|
231
|
+
applyHeadersMut(reqHeaders, defaultHeaders);
|
232
|
+
applyHeadersMut(reqHeaders, headers);
|
233
|
+
// let builtin fetch set the Content-Type for multipart bodies
|
234
|
+
if (isMultipartBody(options.body) && shimsKind !== 'node') {
|
235
|
+
delete reqHeaders['content-type'];
|
236
|
+
}
|
237
|
+
// Don't set the retry count header if it was already set or removed through default headers or by the
|
238
|
+
// caller. We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to
|
239
|
+
// account for the removal case.
|
240
|
+
if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&
|
241
|
+
getHeader(headers, 'x-stainless-retry-count') === undefined) {
|
242
|
+
reqHeaders['x-stainless-retry-count'] = String(retryCount);
|
243
|
+
}
|
244
|
+
this.validateHeaders(reqHeaders, headers);
|
245
|
+
return reqHeaders;
|
246
|
+
}
|
247
|
+
/**
|
248
|
+
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
249
|
+
*/
|
250
|
+
async prepareOptions(options) { }
|
251
|
+
/**
|
252
|
+
* Used as a callback for mutating the given `RequestInit` object.
|
253
|
+
*
|
254
|
+
* This is useful for cases where you want to add certain headers based off of
|
255
|
+
* the request properties, e.g. `method` or `url`.
|
256
|
+
*/
|
257
|
+
async prepareRequest(request, { url, options }) { }
|
258
|
+
parseHeaders(headers) {
|
259
|
+
return (!headers ? {}
|
260
|
+
: Symbol.iterator in headers ?
|
261
|
+
Object.fromEntries(Array.from(headers).map((header) => [...header]))
|
262
|
+
: { ...headers });
|
263
|
+
}
|
264
|
+
makeStatusError(status, error, message, headers) {
|
265
|
+
return APIError.generate(status, error, message, headers);
|
266
|
+
}
|
267
|
+
request(options, remainingRetries = null) {
|
268
|
+
return new APIPromise(this.makeRequest(options, remainingRetries));
|
269
|
+
}
|
270
|
+
async makeRequest(optionsInput, retriesRemaining) {
|
271
|
+
const options = await optionsInput;
|
272
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
273
|
+
if (retriesRemaining == null) {
|
274
|
+
retriesRemaining = maxRetries;
|
275
|
+
}
|
276
|
+
await this.prepareOptions(options);
|
277
|
+
const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
|
278
|
+
await this.prepareRequest(req, { url, options });
|
279
|
+
debug('request', url, options, req.headers);
|
280
|
+
if (options.signal?.aborted) {
|
281
|
+
throw new APIUserAbortError();
|
282
|
+
}
|
283
|
+
const controller = new AbortController();
|
284
|
+
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
|
285
|
+
if (response instanceof Error) {
|
286
|
+
if (options.signal?.aborted) {
|
287
|
+
throw new APIUserAbortError();
|
288
|
+
}
|
289
|
+
if (retriesRemaining) {
|
290
|
+
return this.retryRequest(options, retriesRemaining);
|
291
|
+
}
|
292
|
+
if (response.name === 'AbortError') {
|
293
|
+
throw new APIConnectionTimeoutError();
|
294
|
+
}
|
295
|
+
throw new APIConnectionError({ cause: response });
|
296
|
+
}
|
297
|
+
const responseHeaders = createResponseHeaders(response.headers);
|
298
|
+
if (!response.ok) {
|
299
|
+
if (retriesRemaining && this.shouldRetry(response)) {
|
300
|
+
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
301
|
+
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);
|
302
|
+
return this.retryRequest(options, retriesRemaining, responseHeaders);
|
303
|
+
}
|
304
|
+
const errText = await response.text().catch((e) => castToError(e).message);
|
305
|
+
const errJSON = safeJSON(errText);
|
306
|
+
const errMessage = errJSON ? undefined : errText;
|
307
|
+
const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
|
308
|
+
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
|
309
|
+
const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
|
310
|
+
throw err;
|
311
|
+
}
|
312
|
+
return { response, options, controller };
|
313
|
+
}
|
314
|
+
requestAPIList(Page, options) {
|
315
|
+
const request = this.makeRequest(options, null);
|
316
|
+
return new PagePromise(this, request, Page);
|
317
|
+
}
|
318
|
+
buildURL(path, query) {
|
319
|
+
const url = isAbsoluteURL(path) ?
|
320
|
+
new URL(path)
|
321
|
+
: new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
322
|
+
const defaultQuery = this.defaultQuery();
|
323
|
+
if (!isEmptyObj(defaultQuery)) {
|
324
|
+
query = { ...defaultQuery, ...query };
|
325
|
+
}
|
326
|
+
if (typeof query === 'object' && query && !Array.isArray(query)) {
|
327
|
+
url.search = this.stringifyQuery(query);
|
328
|
+
}
|
329
|
+
return url.toString();
|
330
|
+
}
|
331
|
+
stringifyQuery(query) {
|
332
|
+
return Object.entries(query)
|
333
|
+
.filter(([_, value]) => typeof value !== 'undefined')
|
334
|
+
.map(([key, value]) => {
|
335
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
336
|
+
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
337
|
+
}
|
338
|
+
if (value === null) {
|
339
|
+
return `${encodeURIComponent(key)}=`;
|
340
|
+
}
|
341
|
+
throw new RoarkError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
|
342
|
+
})
|
343
|
+
.join('&');
|
344
|
+
}
|
345
|
+
async fetchWithTimeout(url, init, ms, controller) {
|
346
|
+
const { signal, ...options } = init || {};
|
347
|
+
if (signal)
|
348
|
+
signal.addEventListener('abort', () => controller.abort());
|
349
|
+
const timeout = setTimeout(() => controller.abort(), ms);
|
350
|
+
const fetchOptions = {
|
351
|
+
signal: controller.signal,
|
352
|
+
...options,
|
353
|
+
};
|
354
|
+
if (fetchOptions.method) {
|
355
|
+
// Custom methods like 'patch' need to be uppercased
|
356
|
+
// See https://github.com/nodejs/undici/issues/2294
|
357
|
+
fetchOptions.method = fetchOptions.method.toUpperCase();
|
358
|
+
}
|
359
|
+
return (
|
360
|
+
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
361
|
+
this.fetch.call(undefined, url, fetchOptions).finally(() => {
|
362
|
+
clearTimeout(timeout);
|
363
|
+
}));
|
364
|
+
}
|
365
|
+
shouldRetry(response) {
|
366
|
+
// Note this is not a standard header.
|
367
|
+
const shouldRetryHeader = response.headers.get('x-should-retry');
|
368
|
+
// If the server explicitly says whether or not to retry, obey.
|
369
|
+
if (shouldRetryHeader === 'true')
|
370
|
+
return true;
|
371
|
+
if (shouldRetryHeader === 'false')
|
372
|
+
return false;
|
373
|
+
// Retry on request timeouts.
|
374
|
+
if (response.status === 408)
|
375
|
+
return true;
|
376
|
+
// Retry on lock timeouts.
|
377
|
+
if (response.status === 409)
|
378
|
+
return true;
|
379
|
+
// Retry on rate limits.
|
380
|
+
if (response.status === 429)
|
381
|
+
return true;
|
382
|
+
// Retry internal errors.
|
383
|
+
if (response.status >= 500)
|
384
|
+
return true;
|
385
|
+
return false;
|
386
|
+
}
|
387
|
+
async retryRequest(options, retriesRemaining, responseHeaders) {
|
388
|
+
let timeoutMillis;
|
389
|
+
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
|
390
|
+
const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];
|
391
|
+
if (retryAfterMillisHeader) {
|
392
|
+
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
393
|
+
if (!Number.isNaN(timeoutMs)) {
|
394
|
+
timeoutMillis = timeoutMs;
|
395
|
+
}
|
396
|
+
}
|
397
|
+
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
398
|
+
const retryAfterHeader = responseHeaders?.['retry-after'];
|
399
|
+
if (retryAfterHeader && !timeoutMillis) {
|
400
|
+
const timeoutSeconds = parseFloat(retryAfterHeader);
|
401
|
+
if (!Number.isNaN(timeoutSeconds)) {
|
402
|
+
timeoutMillis = timeoutSeconds * 1000;
|
403
|
+
}
|
404
|
+
else {
|
405
|
+
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
|
406
|
+
}
|
407
|
+
}
|
408
|
+
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
409
|
+
// just do what it says, but otherwise calculate a default
|
410
|
+
if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
|
411
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
412
|
+
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
|
413
|
+
}
|
414
|
+
await sleep(timeoutMillis);
|
415
|
+
return this.makeRequest(options, retriesRemaining - 1);
|
416
|
+
}
|
417
|
+
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
|
418
|
+
const initialRetryDelay = 0.5;
|
419
|
+
const maxRetryDelay = 8.0;
|
420
|
+
const numRetries = maxRetries - retriesRemaining;
|
421
|
+
// Apply exponential backoff, but not more than the max.
|
422
|
+
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
|
423
|
+
// Apply some jitter, take up to at most 25 percent of the retry time.
|
424
|
+
const jitter = 1 - Math.random() * 0.25;
|
425
|
+
return sleepSeconds * jitter * 1000;
|
426
|
+
}
|
427
|
+
getUserAgent() {
|
428
|
+
return `${this.constructor.name}/JS ${VERSION}`;
|
429
|
+
}
|
430
|
+
}
|
431
|
+
export class AbstractPage {
|
432
|
+
constructor(client, response, body, options) {
|
433
|
+
_AbstractPage_client.set(this, void 0);
|
434
|
+
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
|
435
|
+
this.options = options;
|
436
|
+
this.response = response;
|
437
|
+
this.body = body;
|
438
|
+
}
|
439
|
+
hasNextPage() {
|
440
|
+
const items = this.getPaginatedItems();
|
441
|
+
if (!items.length)
|
442
|
+
return false;
|
443
|
+
return this.nextPageInfo() != null;
|
444
|
+
}
|
445
|
+
async getNextPage() {
|
446
|
+
const nextInfo = this.nextPageInfo();
|
447
|
+
if (!nextInfo) {
|
448
|
+
throw new RoarkError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
|
449
|
+
}
|
450
|
+
const nextOptions = { ...this.options };
|
451
|
+
if ('params' in nextInfo && typeof nextOptions.query === 'object') {
|
452
|
+
nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
|
453
|
+
}
|
454
|
+
else if ('url' in nextInfo) {
|
455
|
+
const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
|
456
|
+
for (const [key, value] of params) {
|
457
|
+
nextInfo.url.searchParams.set(key, value);
|
458
|
+
}
|
459
|
+
nextOptions.query = undefined;
|
460
|
+
nextOptions.path = nextInfo.url.toString();
|
461
|
+
}
|
462
|
+
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
|
463
|
+
}
|
464
|
+
async *iterPages() {
|
465
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
466
|
+
let page = this;
|
467
|
+
yield page;
|
468
|
+
while (page.hasNextPage()) {
|
469
|
+
page = await page.getNextPage();
|
470
|
+
yield page;
|
471
|
+
}
|
472
|
+
}
|
473
|
+
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
|
474
|
+
for await (const page of this.iterPages()) {
|
475
|
+
for (const item of page.getPaginatedItems()) {
|
476
|
+
yield item;
|
477
|
+
}
|
478
|
+
}
|
479
|
+
}
|
480
|
+
}
|
481
|
+
/**
|
482
|
+
* This subclass of Promise will resolve to an instantiated Page once the request completes.
|
483
|
+
*
|
484
|
+
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
|
485
|
+
*
|
486
|
+
* for await (const item of client.items.list()) {
|
487
|
+
* console.log(item)
|
488
|
+
* }
|
489
|
+
*/
|
490
|
+
export class PagePromise extends APIPromise {
|
491
|
+
constructor(client, request, Page) {
|
492
|
+
super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));
|
493
|
+
}
|
494
|
+
/**
|
495
|
+
* Allow auto-paginating iteration on an unawaited list call, eg:
|
496
|
+
*
|
497
|
+
* for await (const item of client.items.list()) {
|
498
|
+
* console.log(item)
|
499
|
+
* }
|
500
|
+
*/
|
501
|
+
async *[Symbol.asyncIterator]() {
|
502
|
+
const page = await this;
|
503
|
+
for await (const item of page) {
|
504
|
+
yield item;
|
505
|
+
}
|
506
|
+
}
|
507
|
+
}
|
508
|
+
export const createResponseHeaders = (headers) => {
|
509
|
+
return new Proxy(Object.fromEntries(
|
510
|
+
// @ts-ignore
|
511
|
+
headers.entries()), {
|
512
|
+
get(target, name) {
|
513
|
+
const key = name.toString();
|
514
|
+
return target[key.toLowerCase()] || target[key];
|
515
|
+
},
|
516
|
+
});
|
517
|
+
};
|
518
|
+
// This is required so that we can determine if a given object matches the RequestOptions
|
519
|
+
// type at runtime. While this requires duplication, it is enforced by the TypeScript
|
520
|
+
// compiler such that any missing / extraneous keys will cause an error.
|
521
|
+
const requestOptionsKeys = {
|
522
|
+
method: true,
|
523
|
+
path: true,
|
524
|
+
query: true,
|
525
|
+
body: true,
|
526
|
+
headers: true,
|
527
|
+
maxRetries: true,
|
528
|
+
stream: true,
|
529
|
+
timeout: true,
|
530
|
+
httpAgent: true,
|
531
|
+
signal: true,
|
532
|
+
idempotencyKey: true,
|
533
|
+
__binaryRequest: true,
|
534
|
+
__binaryResponse: true,
|
535
|
+
};
|
536
|
+
export const isRequestOptions = (obj) => {
|
537
|
+
return (typeof obj === 'object' &&
|
538
|
+
obj !== null &&
|
539
|
+
!isEmptyObj(obj) &&
|
540
|
+
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));
|
541
|
+
};
|
542
|
+
const getPlatformProperties = () => {
|
543
|
+
if (typeof Deno !== 'undefined' && Deno.build != null) {
|
544
|
+
return {
|
545
|
+
'X-Stainless-Lang': 'js',
|
546
|
+
'X-Stainless-Package-Version': VERSION,
|
547
|
+
'X-Stainless-OS': normalizePlatform(Deno.build.os),
|
548
|
+
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
|
549
|
+
'X-Stainless-Runtime': 'deno',
|
550
|
+
'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',
|
551
|
+
};
|
552
|
+
}
|
553
|
+
if (typeof EdgeRuntime !== 'undefined') {
|
554
|
+
return {
|
555
|
+
'X-Stainless-Lang': 'js',
|
556
|
+
'X-Stainless-Package-Version': VERSION,
|
557
|
+
'X-Stainless-OS': 'Unknown',
|
558
|
+
'X-Stainless-Arch': `other:${EdgeRuntime}`,
|
559
|
+
'X-Stainless-Runtime': 'edge',
|
560
|
+
'X-Stainless-Runtime-Version': process.version,
|
561
|
+
};
|
562
|
+
}
|
563
|
+
// Check if Node.js
|
564
|
+
if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
|
565
|
+
return {
|
566
|
+
'X-Stainless-Lang': 'js',
|
567
|
+
'X-Stainless-Package-Version': VERSION,
|
568
|
+
'X-Stainless-OS': normalizePlatform(process.platform),
|
569
|
+
'X-Stainless-Arch': normalizeArch(process.arch),
|
570
|
+
'X-Stainless-Runtime': 'node',
|
571
|
+
'X-Stainless-Runtime-Version': process.version,
|
572
|
+
};
|
573
|
+
}
|
574
|
+
const browserInfo = getBrowserInfo();
|
575
|
+
if (browserInfo) {
|
576
|
+
return {
|
577
|
+
'X-Stainless-Lang': 'js',
|
578
|
+
'X-Stainless-Package-Version': VERSION,
|
579
|
+
'X-Stainless-OS': 'Unknown',
|
580
|
+
'X-Stainless-Arch': 'unknown',
|
581
|
+
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
|
582
|
+
'X-Stainless-Runtime-Version': browserInfo.version,
|
583
|
+
};
|
584
|
+
}
|
585
|
+
// TODO add support for Cloudflare workers, etc.
|
586
|
+
return {
|
587
|
+
'X-Stainless-Lang': 'js',
|
588
|
+
'X-Stainless-Package-Version': VERSION,
|
589
|
+
'X-Stainless-OS': 'Unknown',
|
590
|
+
'X-Stainless-Arch': 'unknown',
|
591
|
+
'X-Stainless-Runtime': 'unknown',
|
592
|
+
'X-Stainless-Runtime-Version': 'unknown',
|
593
|
+
};
|
594
|
+
};
|
595
|
+
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
|
596
|
+
function getBrowserInfo() {
|
597
|
+
if (typeof navigator === 'undefined' || !navigator) {
|
598
|
+
return null;
|
599
|
+
}
|
600
|
+
// NOTE: The order matters here!
|
601
|
+
const browserPatterns = [
|
602
|
+
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
603
|
+
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
604
|
+
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
605
|
+
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
606
|
+
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
607
|
+
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
|
608
|
+
];
|
609
|
+
// Find the FIRST matching browser
|
610
|
+
for (const { key, pattern } of browserPatterns) {
|
611
|
+
const match = pattern.exec(navigator.userAgent);
|
612
|
+
if (match) {
|
613
|
+
const major = match[1] || 0;
|
614
|
+
const minor = match[2] || 0;
|
615
|
+
const patch = match[3] || 0;
|
616
|
+
return { browser: key, version: `${major}.${minor}.${patch}` };
|
617
|
+
}
|
618
|
+
}
|
619
|
+
return null;
|
620
|
+
}
|
621
|
+
const normalizeArch = (arch) => {
|
622
|
+
// Node docs:
|
623
|
+
// - https://nodejs.org/api/process.html#processarch
|
624
|
+
// Deno docs:
|
625
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
626
|
+
if (arch === 'x32')
|
627
|
+
return 'x32';
|
628
|
+
if (arch === 'x86_64' || arch === 'x64')
|
629
|
+
return 'x64';
|
630
|
+
if (arch === 'arm')
|
631
|
+
return 'arm';
|
632
|
+
if (arch === 'aarch64' || arch === 'arm64')
|
633
|
+
return 'arm64';
|
634
|
+
if (arch)
|
635
|
+
return `other:${arch}`;
|
636
|
+
return 'unknown';
|
637
|
+
};
|
638
|
+
const normalizePlatform = (platform) => {
|
639
|
+
// Node platforms:
|
640
|
+
// - https://nodejs.org/api/process.html#processplatform
|
641
|
+
// Deno platforms:
|
642
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
643
|
+
// - https://github.com/denoland/deno/issues/14799
|
644
|
+
platform = platform.toLowerCase();
|
645
|
+
// NOTE: this iOS check is untested and may not work
|
646
|
+
// Node does not work natively on IOS, there is a fork at
|
647
|
+
// https://github.com/nodejs-mobile/nodejs-mobile
|
648
|
+
// however it is unknown at the time of writing how to detect if it is running
|
649
|
+
if (platform.includes('ios'))
|
650
|
+
return 'iOS';
|
651
|
+
if (platform === 'android')
|
652
|
+
return 'Android';
|
653
|
+
if (platform === 'darwin')
|
654
|
+
return 'MacOS';
|
655
|
+
if (platform === 'win32')
|
656
|
+
return 'Windows';
|
657
|
+
if (platform === 'freebsd')
|
658
|
+
return 'FreeBSD';
|
659
|
+
if (platform === 'openbsd')
|
660
|
+
return 'OpenBSD';
|
661
|
+
if (platform === 'linux')
|
662
|
+
return 'Linux';
|
663
|
+
if (platform)
|
664
|
+
return `Other:${platform}`;
|
665
|
+
return 'Unknown';
|
666
|
+
};
|
667
|
+
let _platformHeaders;
|
668
|
+
const getPlatformHeaders = () => {
|
669
|
+
return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
|
670
|
+
};
|
671
|
+
export const safeJSON = (text) => {
|
672
|
+
try {
|
673
|
+
return JSON.parse(text);
|
674
|
+
}
|
675
|
+
catch (err) {
|
676
|
+
return undefined;
|
677
|
+
}
|
678
|
+
};
|
679
|
+
// https://url.spec.whatwg.org/#url-scheme-string
|
680
|
+
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
|
681
|
+
const isAbsoluteURL = (url) => {
|
682
|
+
return startsWithSchemeRegexp.test(url);
|
683
|
+
};
|
684
|
+
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
685
|
+
const validatePositiveInteger = (name, n) => {
|
686
|
+
if (typeof n !== 'number' || !Number.isInteger(n)) {
|
687
|
+
throw new RoarkError(`${name} must be an integer`);
|
688
|
+
}
|
689
|
+
if (n < 0) {
|
690
|
+
throw new RoarkError(`${name} must be a positive integer`);
|
691
|
+
}
|
692
|
+
return n;
|
693
|
+
};
|
694
|
+
export const castToError = (err) => {
|
695
|
+
if (err instanceof Error)
|
696
|
+
return err;
|
697
|
+
if (typeof err === 'object' && err !== null) {
|
698
|
+
try {
|
699
|
+
return new Error(JSON.stringify(err));
|
700
|
+
}
|
701
|
+
catch { }
|
702
|
+
}
|
703
|
+
return new Error(err);
|
704
|
+
};
|
705
|
+
export const ensurePresent = (value) => {
|
706
|
+
if (value == null)
|
707
|
+
throw new RoarkError(`Expected a value to be given but received ${value} instead.`);
|
708
|
+
return value;
|
709
|
+
};
|
710
|
+
/**
|
711
|
+
* Read an environment variable.
|
712
|
+
*
|
713
|
+
* Trims beginning and trailing whitespace.
|
714
|
+
*
|
715
|
+
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
|
716
|
+
*/
|
717
|
+
export const readEnv = (env) => {
|
718
|
+
if (typeof process !== 'undefined') {
|
719
|
+
return process.env?.[env]?.trim() ?? undefined;
|
720
|
+
}
|
721
|
+
if (typeof Deno !== 'undefined') {
|
722
|
+
return Deno.env?.get?.(env)?.trim();
|
723
|
+
}
|
724
|
+
return undefined;
|
725
|
+
};
|
726
|
+
export const coerceInteger = (value) => {
|
727
|
+
if (typeof value === 'number')
|
728
|
+
return Math.round(value);
|
729
|
+
if (typeof value === 'string')
|
730
|
+
return parseInt(value, 10);
|
731
|
+
throw new RoarkError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
|
732
|
+
};
|
733
|
+
export const coerceFloat = (value) => {
|
734
|
+
if (typeof value === 'number')
|
735
|
+
return value;
|
736
|
+
if (typeof value === 'string')
|
737
|
+
return parseFloat(value);
|
738
|
+
throw new RoarkError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
|
739
|
+
};
|
740
|
+
export const coerceBoolean = (value) => {
|
741
|
+
if (typeof value === 'boolean')
|
742
|
+
return value;
|
743
|
+
if (typeof value === 'string')
|
744
|
+
return value === 'true';
|
745
|
+
return Boolean(value);
|
746
|
+
};
|
747
|
+
export const maybeCoerceInteger = (value) => {
|
748
|
+
if (value === undefined) {
|
749
|
+
return undefined;
|
750
|
+
}
|
751
|
+
return coerceInteger(value);
|
752
|
+
};
|
753
|
+
export const maybeCoerceFloat = (value) => {
|
754
|
+
if (value === undefined) {
|
755
|
+
return undefined;
|
756
|
+
}
|
757
|
+
return coerceFloat(value);
|
758
|
+
};
|
759
|
+
export const maybeCoerceBoolean = (value) => {
|
760
|
+
if (value === undefined) {
|
761
|
+
return undefined;
|
762
|
+
}
|
763
|
+
return coerceBoolean(value);
|
764
|
+
};
|
765
|
+
// https://stackoverflow.com/a/34491287
|
766
|
+
export function isEmptyObj(obj) {
|
767
|
+
if (!obj)
|
768
|
+
return true;
|
769
|
+
for (const _k in obj)
|
770
|
+
return false;
|
771
|
+
return true;
|
772
|
+
}
|
773
|
+
// https://eslint.org/docs/latest/rules/no-prototype-builtins
|
774
|
+
export function hasOwn(obj, key) {
|
775
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
776
|
+
}
|
777
|
+
/**
|
778
|
+
* Copies headers from "newHeaders" onto "targetHeaders",
|
779
|
+
* using lower-case for all properties,
|
780
|
+
* ignoring any keys with undefined values,
|
781
|
+
* and deleting any keys with null values.
|
782
|
+
*/
|
783
|
+
function applyHeadersMut(targetHeaders, newHeaders) {
|
784
|
+
for (const k in newHeaders) {
|
785
|
+
if (!hasOwn(newHeaders, k))
|
786
|
+
continue;
|
787
|
+
const lowerKey = k.toLowerCase();
|
788
|
+
if (!lowerKey)
|
789
|
+
continue;
|
790
|
+
const val = newHeaders[k];
|
791
|
+
if (val === null) {
|
792
|
+
delete targetHeaders[lowerKey];
|
793
|
+
}
|
794
|
+
else if (val !== undefined) {
|
795
|
+
targetHeaders[lowerKey] = val;
|
796
|
+
}
|
797
|
+
}
|
798
|
+
}
|
799
|
+
export function debug(action, ...args) {
|
800
|
+
if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {
|
801
|
+
console.log(`Roark:DEBUG:${action}`, ...args);
|
802
|
+
}
|
803
|
+
}
|
804
|
+
/**
|
805
|
+
* https://stackoverflow.com/a/2117523
|
806
|
+
*/
|
807
|
+
const uuid4 = () => {
|
808
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
809
|
+
const r = (Math.random() * 16) | 0;
|
810
|
+
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
811
|
+
return v.toString(16);
|
812
|
+
});
|
813
|
+
};
|
814
|
+
export const isRunningInBrowser = () => {
|
815
|
+
return (
|
816
|
+
// @ts-ignore
|
817
|
+
typeof window !== 'undefined' &&
|
818
|
+
// @ts-ignore
|
819
|
+
typeof window.document !== 'undefined' &&
|
820
|
+
// @ts-ignore
|
821
|
+
typeof navigator !== 'undefined');
|
822
|
+
};
|
823
|
+
export const isHeadersProtocol = (headers) => {
|
824
|
+
return typeof headers?.get === 'function';
|
825
|
+
};
|
826
|
+
export const getRequiredHeader = (headers, header) => {
|
827
|
+
const foundHeader = getHeader(headers, header);
|
828
|
+
if (foundHeader === undefined) {
|
829
|
+
throw new Error(`Could not find ${header} header`);
|
830
|
+
}
|
831
|
+
return foundHeader;
|
832
|
+
};
|
833
|
+
export const getHeader = (headers, header) => {
|
834
|
+
const lowerCasedHeader = header.toLowerCase();
|
835
|
+
if (isHeadersProtocol(headers)) {
|
836
|
+
// to deal with the case where the header looks like Stainless-Event-Id
|
837
|
+
const intercapsHeader = header[0]?.toUpperCase() +
|
838
|
+
header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());
|
839
|
+
for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
|
840
|
+
const value = headers.get(key);
|
841
|
+
if (value) {
|
842
|
+
return value;
|
843
|
+
}
|
844
|
+
}
|
845
|
+
}
|
846
|
+
for (const [key, value] of Object.entries(headers)) {
|
847
|
+
if (key.toLowerCase() === lowerCasedHeader) {
|
848
|
+
if (Array.isArray(value)) {
|
849
|
+
if (value.length <= 1)
|
850
|
+
return value[0];
|
851
|
+
console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
|
852
|
+
return value[0];
|
853
|
+
}
|
854
|
+
return value;
|
855
|
+
}
|
856
|
+
}
|
857
|
+
return undefined;
|
858
|
+
};
|
859
|
+
/**
|
860
|
+
* Encodes a string to Base64 format.
|
861
|
+
*/
|
862
|
+
export const toBase64 = (str) => {
|
863
|
+
if (!str)
|
864
|
+
return '';
|
865
|
+
if (typeof Buffer !== 'undefined') {
|
866
|
+
return Buffer.from(str).toString('base64');
|
867
|
+
}
|
868
|
+
if (typeof btoa !== 'undefined') {
|
869
|
+
return btoa(str);
|
870
|
+
}
|
871
|
+
throw new RoarkError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
|
872
|
+
};
|
873
|
+
export function isObj(obj) {
|
874
|
+
return obj != null && typeof obj === 'object' && !Array.isArray(obj);
|
875
|
+
}
|
876
|
+
//# sourceMappingURL=core.mjs.map
|