@scaleway/sdk-client 1.3.2 → 2.1.0

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 (65) hide show
  1. package/dist/helpers/json.js +6 -7
  2. package/dist/helpers/marshalling.d.ts +0 -8
  3. package/dist/helpers/marshalling.js +18 -22
  4. package/dist/internal/async/interval-retrier.js +2 -1
  5. package/dist/internal/interceptors/types.d.ts +7 -0
  6. package/dist/package.json.js +1 -1
  7. package/dist/scw/auth.d.ts +7 -0
  8. package/dist/scw/custom-marshalling.js +5 -7
  9. package/dist/scw/errors/error-parser.js +4 -4
  10. package/dist/scw/errors/non-standard/invalid-request-mapper.d.ts +1 -3
  11. package/dist/scw/errors/non-standard/invalid-request-mapper.js +27 -29
  12. package/dist/scw/errors/non-standard/unknown-resource-mapper.d.ts +1 -3
  13. package/dist/scw/errors/non-standard/unknown-resource-mapper.js +15 -17
  14. package/dist/scw/fetch/build-fetcher.js +2 -1
  15. package/dist/scw/fetch/http-interceptors.d.ts +7 -0
  16. package/dist/vendor/base64/index.js +16 -11
  17. package/package.json +2 -4
  18. package/dist/helpers/is-browser.cjs +0 -4
  19. package/dist/helpers/is-response.cjs +0 -4
  20. package/dist/helpers/json.cjs +0 -47
  21. package/dist/helpers/marshalling.cjs +0 -76
  22. package/dist/index.cjs +0 -58
  23. package/dist/internal/async/interval-retrier.cjs +0 -53
  24. package/dist/internal/async/sleep.cjs +0 -6
  25. package/dist/internal/interceptors/composer.cjs +0 -25
  26. package/dist/internal/interceptors/helpers.cjs +0 -12
  27. package/dist/internal/logger/console-logger.cjs +0 -24
  28. package/dist/internal/logger/index.cjs +0 -12
  29. package/dist/internal/logger/level-resolver.cjs +0 -13
  30. package/dist/internal/validations/string-validation.cjs +0 -30
  31. package/dist/package.json.cjs +0 -8
  32. package/dist/scw/api.cjs +0 -8
  33. package/dist/scw/auth.cjs +0 -25
  34. package/dist/scw/client-ini-factory.cjs +0 -66
  35. package/dist/scw/client-ini-profile.cjs +0 -23
  36. package/dist/scw/client-settings.cjs +0 -51
  37. package/dist/scw/client.cjs +0 -31
  38. package/dist/scw/constants.cjs +0 -11
  39. package/dist/scw/custom-marshalling.cjs +0 -152
  40. package/dist/scw/custom-types.cjs +0 -11
  41. package/dist/scw/errors/error-parser.cjs +0 -76
  42. package/dist/scw/errors/non-standard/invalid-request-mapper.cjs +0 -36
  43. package/dist/scw/errors/non-standard/unknown-resource-mapper.cjs +0 -23
  44. package/dist/scw/errors/scw-error.cjs +0 -43
  45. package/dist/scw/errors/standard/already-exists-error.cjs +0 -31
  46. package/dist/scw/errors/standard/denied-authentication-error.cjs +0 -37
  47. package/dist/scw/errors/standard/index.cjs +0 -28
  48. package/dist/scw/errors/standard/invalid-arguments-error.cjs +0 -54
  49. package/dist/scw/errors/standard/out-of-stock-error.cjs +0 -17
  50. package/dist/scw/errors/standard/permissions-denied-error.cjs +0 -29
  51. package/dist/scw/errors/standard/precondition-failed-error.cjs +0 -32
  52. package/dist/scw/errors/standard/quotas-exceeded-error.cjs +0 -43
  53. package/dist/scw/errors/standard/resource-expired-error.cjs +0 -31
  54. package/dist/scw/errors/standard/resource-locked-error.cjs +0 -20
  55. package/dist/scw/errors/standard/resource-not-found-error.cjs +0 -24
  56. package/dist/scw/errors/standard/too-many-requests-error.cjs +0 -58
  57. package/dist/scw/errors/standard/transient-state-error.cjs +0 -31
  58. package/dist/scw/errors/types.cjs +0 -15
  59. package/dist/scw/fetch/build-fetcher.cjs +0 -60
  60. package/dist/scw/fetch/http-dumper.cjs +0 -20
  61. package/dist/scw/fetch/http-interceptors.cjs +0 -43
  62. package/dist/scw/fetch/resource-paginator.cjs +0 -36
  63. package/dist/scw/fetch/response-parser.cjs +0 -55
  64. package/dist/scw/locality.cjs +0 -16
  65. package/dist/vendor/base64/index.cjs +0 -46
@@ -30,13 +30,12 @@ const camelizeKeys = (obj, ignoreKeys = []) => {
30
30
  return obj.map((v) => camelizeKeys(v, ignoreKeys));
31
31
  }
32
32
  if (obj && typeof obj === "object" && !(obj instanceof Date)) {
33
- return Object.entries(obj).reduce(
34
- (acc, [key, value]) => ({
35
- ...acc,
36
- [camelize(key)]: ignoreKeys.includes(key) ? value : camelizeKeys(value, ignoreKeys)
37
- }),
38
- {}
39
- );
33
+ const result = {};
34
+ for (const [key, value] of Object.entries(obj)) {
35
+ const outKey = camelize(key);
36
+ result[outKey] = ignoreKeys.includes(key) ? value : camelizeKeys(value, ignoreKeys);
37
+ }
38
+ return result;
40
39
  }
41
40
  return obj;
42
41
  };
@@ -30,14 +30,6 @@ export declare const resolveOneOf: <T>(list: {
30
30
  default?: T | undefined;
31
31
  }[], isRequired?: boolean) => Record<string, T>;
32
32
  type URLParameterValue = string | number | boolean | Date | null;
33
- /**
34
- * Filters defined parameters tuples and converts them to URLSearchParams.
35
- *
36
- * @param paramTuples - The key/value pairs
37
- * @returns URLSearchParams
38
- *
39
- * @internal
40
- */
41
33
  export declare const urlParams: (...paramTuples: Readonly<[string, URLParameterValue | URLParameterValue[] | undefined]>[]) => URLSearchParams;
42
34
  /**
43
35
  * Unmarshals data to Date object.
@@ -15,26 +15,24 @@ const resolveOneOf = (list, isRequired = false) => {
15
15
  }
16
16
  return {};
17
17
  };
18
+ const toParamString = (v) => {
19
+ if (v === null) return null;
20
+ if (v instanceof Date) return v.toISOString();
21
+ return v.toString();
22
+ };
18
23
  const urlParams = (...paramTuples) => {
19
24
  const params = new URLSearchParams();
20
25
  for (const [key, value] of paramTuples) {
21
- if (typeof key === "string" && value != null) {
22
- if (Array.isArray(value)) {
23
- for (const innerValue of value) {
24
- if (innerValue !== null) {
25
- params.append(
26
- key,
27
- innerValue instanceof Date ? innerValue.toISOString() : innerValue.toString()
28
- );
29
- }
30
- }
31
- } else {
32
- params.append(
33
- key,
34
- value instanceof Date ? value.toISOString() : value.toString()
35
- );
26
+ if (typeof key !== "string" || value == null) continue;
27
+ if (Array.isArray(value)) {
28
+ for (const inner of value) {
29
+ const s2 = toParamString(inner);
30
+ if (s2 !== null) params.append(key, s2);
36
31
  }
32
+ continue;
37
33
  }
34
+ const s = toParamString(value);
35
+ if (s !== null) params.append(key, s);
38
36
  }
39
37
  return params;
40
38
  };
@@ -58,13 +56,11 @@ const unmarshalMapOfObject = (data, unmarshaller, emptyFallback = true) => {
58
56
  if (!data || typeof data !== "object" || !(data instanceof Object) || Array.isArray(data)) {
59
57
  return emptyFallback ? {} : void 0;
60
58
  }
61
- return Object.entries(data).reduce(
62
- (acc, [key, value]) => ({
63
- ...acc,
64
- [key]: unmarshaller(value)
65
- }),
66
- {}
67
- );
59
+ const out = {};
60
+ for (const [key, value] of Object.entries(data)) {
61
+ out[key] = unmarshaller(value);
62
+ }
63
+ return out;
68
64
  };
69
65
  export {
70
66
  resolveOneOf,
@@ -24,7 +24,8 @@ const tryAtIntervals = async (retry, strategy, timeout = DEFAULT_TIMEOUT_SECONDS
24
24
  const timeoutTimestamp = Date.now() + timeout * 1e3;
25
25
  let retryCount = 0;
26
26
  while (Date.now() <= timeoutTimestamp) {
27
- const delay = strategy.next(retryCount += 1).value * 1e3;
27
+ retryCount += 1;
28
+ const delay = strategy.next(retryCount).value * 1e3;
28
29
  if (timeoutTimestamp <= Date.now() + delay) break;
29
30
  await sleep(delay);
30
31
  const { value, done } = await retry();
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Interceptor type definitions.
3
+ *
4
+ * Note: This file uses interface call signatures instead of shorthand function types
5
+ * to maintain clear, documented public API signatures that are more readable in IDE
6
+ * tooltips and generated documentation.
7
+ */
1
8
  /**
2
9
  * Defines the interceptor for a `Request`.
3
10
  * This allows you to intercept requests before starting.
@@ -1,4 +1,4 @@
1
- const version = "1.3.1";
1
+ const version = "2.1.0";
2
2
  const pkg = {
3
3
  version
4
4
  };
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Authentication utilities for Scaleway SDK.
3
+ *
4
+ * Note: This file uses interface call signatures instead of shorthand function types
5
+ * to maintain clear, documented public API signatures that are more readable in IDE
6
+ * tooltips and generated documentation.
7
+ */
1
8
  import type { RequestInterceptor } from '../internal/interceptors/types.js';
2
9
  import type { AuthenticationSecrets } from './client-ini-profile.js';
3
10
  interface TokenAccessor {
@@ -115,13 +115,11 @@ const unmarshalDates = (obj, keys) => {
115
115
  return obj.map((v) => unmarshalDates(v, keys));
116
116
  }
117
117
  if (obj && typeof obj === "object") {
118
- return Object.entries(obj).reduce(
119
- (acc, [key, value]) => ({
120
- ...acc,
121
- [key]: typeof value === "string" && keys.includes(key) ? new Date(value) : unmarshalDates(value, keys)
122
- }),
123
- {}
124
- );
118
+ const result = {};
119
+ for (const [key, value] of Object.entries(obj)) {
120
+ result[key] = typeof value === "string" && keys.includes(key) ? new Date(value) : unmarshalDates(value, keys);
121
+ }
122
+ return result;
125
123
  }
126
124
  return obj;
127
125
  };
@@ -1,5 +1,5 @@
1
- import { InvalidRequestMapper } from "./non-standard/invalid-request-mapper.js";
2
- import { UnknownResourceMapper } from "./non-standard/unknown-resource-mapper.js";
1
+ import { mapInvalidRequestFromJSON } from "./non-standard/invalid-request-mapper.js";
2
+ import { mapUnknownResourceFromJSON } from "./non-standard/unknown-resource-mapper.js";
3
3
  import { ScalewayError } from "./scw-error.js";
4
4
  import { AlreadyExistsError } from "./standard/already-exists-error.js";
5
5
  import { DeniedAuthenticationError } from "./standard/denied-authentication-error.js";
@@ -60,9 +60,9 @@ const unmarshalStandardError = (type, status, body) => {
60
60
  const unmarshalNonStandardError = (type, status, body) => {
61
61
  switch (type) {
62
62
  case "unknown_resource":
63
- return UnknownResourceMapper.fromJSON(status, body);
63
+ return mapUnknownResourceFromJSON(status, body);
64
64
  case "invalid_request_error":
65
- return InvalidRequestMapper.fromJSON(status, body);
65
+ return mapInvalidRequestFromJSON(status, body);
66
66
  default:
67
67
  return null;
68
68
  }
@@ -7,6 +7,4 @@ import { QuotasExceededError } from '../standard/quotas-exceeded-error.js';
7
7
  *
8
8
  * @public
9
9
  */
10
- export declare class InvalidRequestMapper {
11
- static fromJSON(status: number, obj: Readonly<JSONObject>): QuotasExceededError | InvalidArgumentsError | ScalewayError;
12
- }
10
+ export declare const mapInvalidRequestFromJSON: (status: number, obj: Readonly<JSONObject>) => QuotasExceededError | InvalidArgumentsError | ScalewayError;
@@ -2,35 +2,33 @@ import { ScalewayError } from "../scw-error.js";
2
2
  import { InvalidArgumentsError } from "../standard/invalid-arguments-error.js";
3
3
  import { QuotasExceededError } from "../standard/quotas-exceeded-error.js";
4
4
  import { isRecordOfStringArray } from "../types.js";
5
- class InvalidRequestMapper {
6
- static fromJSON(status, obj) {
7
- if (typeof obj.message === "string" && obj.message.toLowerCase().includes("quota exceeded for this resource")) {
8
- return new QuotasExceededError(status, obj, [
9
- {
10
- current: 0,
11
- quota: 0,
12
- resource: typeof obj.resource === "string" ? obj.resource : ""
13
- }
14
- ]);
15
- }
16
- const fields = obj.fields && isRecordOfStringArray(obj.fields) ? obj.fields : {};
17
- const fieldsMessages = Object.entries(fields);
18
- if (fieldsMessages.length) {
19
- return new InvalidArgumentsError(
20
- status,
21
- obj,
22
- fieldsMessages.map(
23
- ([argumentName, messages]) => messages.map((helpMessage) => ({
24
- argumentName,
25
- helpMessage,
26
- reason: "constraint"
27
- }))
28
- ).flat()
29
- );
30
- }
31
- return new ScalewayError(status, obj);
5
+ const mapInvalidRequestFromJSON = (status, obj) => {
6
+ if (typeof obj.message === "string" && obj.message.toLowerCase().includes("quota exceeded for this resource")) {
7
+ return new QuotasExceededError(status, obj, [
8
+ {
9
+ current: 0,
10
+ quota: 0,
11
+ resource: typeof obj.resource === "string" ? obj.resource : ""
12
+ }
13
+ ]);
32
14
  }
33
- }
15
+ const fields = obj.fields && isRecordOfStringArray(obj.fields) ? obj.fields : {};
16
+ const fieldsMessages = Object.entries(fields);
17
+ if (fieldsMessages.length) {
18
+ return new InvalidArgumentsError(
19
+ status,
20
+ obj,
21
+ fieldsMessages.flatMap(
22
+ ([argumentName, messages]) => messages.map((helpMessage) => ({
23
+ argumentName,
24
+ helpMessage,
25
+ reason: "constraint"
26
+ }))
27
+ )
28
+ );
29
+ }
30
+ return new ScalewayError(status, obj);
31
+ };
34
32
  export {
35
- InvalidRequestMapper
33
+ mapInvalidRequestFromJSON
36
34
  };
@@ -6,6 +6,4 @@ import { ResourceNotFoundError } from '../standard/resource-not-found-error.js';
6
6
  *
7
7
  * @public
8
8
  */
9
- export declare class UnknownResourceMapper {
10
- static fromJSON(status: number, obj: Readonly<JSONObject>): ResourceNotFoundError | ScalewayError;
11
- }
9
+ export declare const mapUnknownResourceFromJSON: (status: number, obj: Readonly<JSONObject>) => ResourceNotFoundError | ScalewayError;
@@ -1,23 +1,21 @@
1
1
  import { isUUID } from "../../../internal/validations/string-validation.js";
2
2
  import { ScalewayError } from "../scw-error.js";
3
3
  import { ResourceNotFoundError } from "../standard/resource-not-found-error.js";
4
- class UnknownResourceMapper {
5
- static fromJSON(status, obj) {
6
- const messageParts = typeof obj.message === "string" ? obj.message.split(/"|'/) : [];
7
- if (messageParts.length === 3 && isUUID(messageParts[1])) {
8
- return new ResourceNotFoundError(
9
- status,
10
- obj,
11
- // transform `Security group ` to `security_group`
12
- // `.replaceAll()` may be too recent to use yet.
13
- // that's why we're using `.split(' ').join('_')` for now.
14
- messageParts[0].trim().toLowerCase().split(" ").join("_"),
15
- messageParts[1]
16
- );
17
- }
18
- return new ScalewayError(status, obj);
4
+ const mapUnknownResourceFromJSON = (status, obj) => {
5
+ const messageParts = typeof obj.message === "string" ? obj.message.split(/"|'/) : [];
6
+ if (messageParts.length === 3 && isUUID(messageParts[1])) {
7
+ return new ResourceNotFoundError(
8
+ status,
9
+ obj,
10
+ // transform `Security group ` to `security_group`
11
+ // `.replaceAll()` may be too recent to use yet.
12
+ // that's why we're using `.split(' ').join('_')` for now.
13
+ messageParts[0].trim().toLowerCase().split(" ").join("_"),
14
+ messageParts[1]
15
+ );
19
16
  }
20
- }
17
+ return new ScalewayError(status, obj);
18
+ };
21
19
  export {
22
- UnknownResourceMapper
20
+ mapUnknownResourceFromJSON
23
21
  };
@@ -34,7 +34,8 @@ const buildFetcher = (settings, httpClient) => {
34
34
  settings.interceptors.map((obj) => obj.responseError).filter((obj) => obj)
35
35
  );
36
36
  return async (request, unwrapper = asIs) => {
37
- const requestId = `${requestNumber += 1}`;
37
+ requestNumber += 1;
38
+ const requestId = `${requestNumber}`;
38
39
  const reqInterceptors = prepareRequest(requestId);
39
40
  const finalRequest = await reqInterceptors(buildRequest(request, settings));
40
41
  try {
@@ -1,3 +1,10 @@
1
+ /**
2
+ * HTTP interceptors for request/response logging.
3
+ *
4
+ * Note: This file uses interface call signatures instead of shorthand function types
5
+ * to maintain clear, documented public API signatures that are more readable in IDE
6
+ * tooltips and generated documentation.
7
+ */
1
8
  import type { RequestInterceptor, ResponseInterceptor } from '../../internal/interceptors/types.js';
2
9
  /**
3
10
  * Mapper of an header entry.
@@ -1,6 +1,8 @@
1
1
  var lookup = [];
2
+ var i;
3
+ var len;
2
4
  var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3
- for (var i = 0, len = code.length; i < len; ++i) {
5
+ for (i = 0, len = code.length; i < len; ++i) {
4
6
  lookup[i] = code[i];
5
7
  }
6
8
  function tripletToBase64(num) {
@@ -9,32 +11,35 @@ function tripletToBase64(num) {
9
11
  function encodeChunk(uint8, start, end) {
10
12
  var tmp;
11
13
  var output = [];
12
- for (var i = start; i < end; i += 3) {
13
- tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255);
14
+ var i2;
15
+ for (i2 = start; i2 < end; i2 += 3) {
16
+ tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
14
17
  output.push(tripletToBase64(tmp));
15
18
  }
16
19
  return output.join("");
17
20
  }
18
21
  function fromByteArray(uint8) {
19
22
  var tmp;
20
- var len = uint8.length;
21
- var extraBytes = len % 3;
23
+ var len2 = uint8.length;
24
+ var extraBytes = len2 % 3;
22
25
  var parts = [];
23
26
  var maxChunkLength = 16383;
24
- for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
27
+ var i2;
28
+ var len22;
29
+ for (i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
25
30
  parts.push(
26
31
  encodeChunk(
27
32
  uint8,
28
- i,
29
- i + maxChunkLength > len2 ? len2 : i + maxChunkLength
33
+ i2,
34
+ i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength
30
35
  )
31
36
  );
32
37
  }
33
38
  if (extraBytes === 1) {
34
- tmp = uint8[len - 1];
35
- parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==");
39
+ tmp = uint8[len2 - 1];
40
+ parts.push(`${lookup[tmp >> 2] + lookup[tmp << 4 & 63]}==`);
36
41
  } else if (extraBytes === 2) {
37
- tmp = (uint8[len - 2] << 8) + uint8[len - 1];
42
+ tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
38
43
  parts.push(
39
44
  lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
40
45
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scaleway/sdk-client",
3
- "version": "1.3.2",
3
+ "version": "2.1.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Scaleway SDK Client",
6
6
  "keywords": [
@@ -21,14 +21,12 @@
21
21
  "directory": "packages/client"
22
22
  },
23
23
  "engines": {
24
- "node": ">=20.19.4"
24
+ "node": ">=20.19.6"
25
25
  },
26
26
  "type": "module",
27
27
  "exports": {
28
28
  ".": {
29
29
  "types": "./dist/index.d.ts",
30
- "import": "./dist/index.js",
31
- "require": "./dist/index.cjs",
32
30
  "default": "./dist/index.js"
33
31
  }
34
32
  },
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
4
- exports.isBrowser = isBrowser;
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const isResponse = (obj) => obj !== null && obj !== void 0 && typeof obj === "object" && "status" in obj && typeof obj.status === "number" && "statusText" in obj && typeof obj.statusText === "string" && "headers" in obj && typeof obj.headers === "object" && "body" in obj && typeof obj.body !== "undefined";
4
- exports.isResponse = isResponse;
@@ -1,47 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const isJSONObject = (obj) => {
4
- const objT = typeof obj;
5
- return obj !== void 0 && obj !== null && objT !== "string" && objT !== "number" && objT !== "boolean" && !Array.isArray(obj) && objT === "object";
6
- };
7
- const camelize = (str) => {
8
- const strLength = str.length;
9
- if (strLength <= 0) {
10
- return str;
11
- }
12
- let out = "";
13
- for (let capNext = false, index = 0; index < strLength; index += 1) {
14
- const char = str.charAt(index);
15
- if (char >= "a" && char <= "z") {
16
- if (capNext) {
17
- out += char.toUpperCase();
18
- } else {
19
- out += char;
20
- }
21
- } else if (char >= "A" && char <= "Z") {
22
- out += char;
23
- } else if (char >= "0" && char <= "9") {
24
- out += char;
25
- }
26
- capNext = char === "_" || char === " " || char === "-" || char === ".";
27
- }
28
- return out.charAt(0).toLowerCase() + out.substring(1);
29
- };
30
- const camelizeKeys = (obj, ignoreKeys = []) => {
31
- if (Array.isArray(obj)) {
32
- return obj.map((v) => camelizeKeys(v, ignoreKeys));
33
- }
34
- if (obj && typeof obj === "object" && !(obj instanceof Date)) {
35
- return Object.entries(obj).reduce(
36
- (acc, [key, value]) => ({
37
- ...acc,
38
- [camelize(key)]: ignoreKeys.includes(key) ? value : camelizeKeys(value, ignoreKeys)
39
- }),
40
- {}
41
- );
42
- }
43
- return obj;
44
- };
45
- exports.camelize = camelize;
46
- exports.camelizeKeys = camelizeKeys;
47
- exports.isJSONObject = isJSONObject;
@@ -1,76 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- function validatePathParam(name, param) {
4
- if (typeof param === "string" && param.length > 0) return param;
5
- if (typeof param === "number") return param.toString();
6
- throw new TypeError(`param ${name} cannot be empty in request`);
7
- }
8
- const resolveOneOf = (list, isRequired = false) => {
9
- const elt = list.find((obj) => obj.value !== void 0) ?? list.find((obj) => obj.default !== void 0);
10
- const value = elt?.value ?? elt?.default;
11
- if (elt && value !== void 0) {
12
- return { [elt.param]: value };
13
- }
14
- if (isRequired) {
15
- const keyList = list.map((obj) => obj.param).join(" or ");
16
- throw new TypeError(`one of ${keyList} must be indicated in the request`);
17
- }
18
- return {};
19
- };
20
- const urlParams = (...paramTuples) => {
21
- const params = new URLSearchParams();
22
- for (const [key, value] of paramTuples) {
23
- if (typeof key === "string" && value != null) {
24
- if (Array.isArray(value)) {
25
- for (const innerValue of value) {
26
- if (innerValue !== null) {
27
- params.append(
28
- key,
29
- innerValue instanceof Date ? innerValue.toISOString() : innerValue.toString()
30
- );
31
- }
32
- }
33
- } else {
34
- params.append(
35
- key,
36
- value instanceof Date ? value.toISOString() : value.toString()
37
- );
38
- }
39
- }
40
- }
41
- return params;
42
- };
43
- const unmarshalDate = (data) => {
44
- if (typeof data !== "string") {
45
- return void 0;
46
- }
47
- const date = new Date(data);
48
- if (Number.isNaN(date.getTime())) {
49
- return void 0;
50
- }
51
- return date;
52
- };
53
- const unmarshalArrayOfObject = (data, unmarshaller, emptyFallback = true) => {
54
- if (!Array.isArray(data)) {
55
- return emptyFallback ? [] : void 0;
56
- }
57
- return data.map((elt) => unmarshaller(elt));
58
- };
59
- const unmarshalMapOfObject = (data, unmarshaller, emptyFallback = true) => {
60
- if (!data || typeof data !== "object" || !(data instanceof Object) || Array.isArray(data)) {
61
- return emptyFallback ? {} : void 0;
62
- }
63
- return Object.entries(data).reduce(
64
- (acc, [key, value]) => ({
65
- ...acc,
66
- [key]: unmarshaller(value)
67
- }),
68
- {}
69
- );
70
- };
71
- exports.resolveOneOf = resolveOneOf;
72
- exports.unmarshalArrayOfObject = unmarshalArrayOfObject;
73
- exports.unmarshalDate = unmarshalDate;
74
- exports.unmarshalMapOfObject = unmarshalMapOfObject;
75
- exports.urlParams = urlParams;
76
- exports.validatePathParam = validatePathParam;
package/dist/index.cjs DELETED
@@ -1,58 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const index = require("./internal/logger/index.cjs");
4
- const json = require("./helpers/json.cjs");
5
- const marshalling = require("./helpers/marshalling.cjs");
6
- const intervalRetrier = require("./internal/async/interval-retrier.cjs");
7
- const helpers = require("./internal/interceptors/helpers.cjs");
8
- const api = require("./scw/api.cjs");
9
- const auth = require("./scw/auth.cjs");
10
- const customMarshalling = require("./scw/custom-marshalling.cjs");
11
- const resourcePaginator = require("./scw/fetch/resource-paginator.cjs");
12
- const client = require("./scw/client.cjs");
13
- const clientIniFactory = require("./scw/client-ini-factory.cjs");
14
- const constants = require("./scw/constants.cjs");
15
- const customTypes = require("./scw/custom-types.cjs");
16
- const index$1 = require("./scw/errors/standard/index.cjs");
17
- const locality = require("./scw/locality.cjs");
18
- exports.enableConsoleLogger = index.enableConsoleLogger;
19
- exports.setLogger = index.setLogger;
20
- exports.isJSONObject = json.isJSONObject;
21
- exports.resolveOneOf = marshalling.resolveOneOf;
22
- exports.unmarshalArrayOfObject = marshalling.unmarshalArrayOfObject;
23
- exports.unmarshalDate = marshalling.unmarshalDate;
24
- exports.unmarshalMapOfObject = marshalling.unmarshalMapOfObject;
25
- exports.urlParams = marshalling.urlParams;
26
- exports.validatePathParam = marshalling.validatePathParam;
27
- exports.createExponentialBackoffStrategy = intervalRetrier.createExponentialBackoffStrategy;
28
- exports.tryAtIntervals = intervalRetrier.tryAtIntervals;
29
- exports.waitForResource = intervalRetrier.waitForResource;
30
- exports.addAsyncHeaderInterceptor = helpers.addAsyncHeaderInterceptor;
31
- exports.API = api.API;
32
- exports.authenticateWithSessionToken = auth.authenticateWithSessionToken;
33
- exports.marshalBlobToScwFile = customMarshalling.marshalBlobToScwFile;
34
- exports.marshalDecimal = customMarshalling.marshalDecimal;
35
- exports.marshalMoney = customMarshalling.marshalMoney;
36
- exports.marshalScwFile = customMarshalling.marshalScwFile;
37
- exports.marshalTimeSeries = customMarshalling.marshalTimeSeries;
38
- exports.unmarshalAnyRes = customMarshalling.unmarshalAnyRes;
39
- exports.unmarshalDecimal = customMarshalling.unmarshalDecimal;
40
- exports.unmarshalMoney = customMarshalling.unmarshalMoney;
41
- exports.unmarshalScwFile = customMarshalling.unmarshalScwFile;
42
- exports.unmarshalServiceInfo = customMarshalling.unmarshalServiceInfo;
43
- exports.unmarshalTimeSeries = customMarshalling.unmarshalTimeSeries;
44
- exports.unmarshalTimeSeriesPoint = customMarshalling.unmarshalTimeSeriesPoint;
45
- exports.enrichForPagination = resourcePaginator.enrichForPagination;
46
- exports.createAdvancedClient = client.createAdvancedClient;
47
- exports.createClient = client.createClient;
48
- exports.withAdditionalInterceptors = clientIniFactory.withAdditionalInterceptors;
49
- exports.withDefaultPageSize = clientIniFactory.withDefaultPageSize;
50
- exports.withHTTPClient = clientIniFactory.withHTTPClient;
51
- exports.withProfile = clientIniFactory.withProfile;
52
- exports.withUserAgent = clientIniFactory.withUserAgent;
53
- exports.withUserAgentSuffix = clientIniFactory.withUserAgentSuffix;
54
- exports.AUTH_HEADER_KEY = constants.AUTH_HEADER_KEY;
55
- exports.SESSION_HEADER_KEY = constants.SESSION_HEADER_KEY;
56
- exports.Decimal = customTypes.Decimal;
57
- exports.Errors = index$1;
58
- exports.toApiLocality = locality.toApiLocality;
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const sleep = require("./sleep.cjs");
4
- const DEFAULT_TIMEOUT_SECONDS = 300;
5
- const DEFAULT_MIN_DELAY_SECONDS = 1;
6
- const DEFAULT_MAX_DELAY_SECONDS = 30;
7
- function* createExponentialBackoffStrategy(minDelay, maxDelay) {
8
- if (minDelay < 1 || maxDelay < 1 || minDelay > maxDelay) {
9
- throw new Error(
10
- "Waiter: minDelay must be >= 1 and maxDelay must be >= minDelay"
11
- );
12
- }
13
- let attempt = 1;
14
- const ceiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1;
15
- const randomInRange = (min, max) => min + Math.random() * (max - min);
16
- while (true) {
17
- if (attempt > ceiling) {
18
- yield maxDelay;
19
- } else {
20
- yield randomInRange(minDelay, minDelay * 2 ** (attempt - 1));
21
- }
22
- attempt += 1;
23
- }
24
- }
25
- const tryAtIntervals = async (retry, strategy, timeout = DEFAULT_TIMEOUT_SECONDS) => {
26
- const timeoutTimestamp = Date.now() + timeout * 1e3;
27
- let retryCount = 0;
28
- while (Date.now() <= timeoutTimestamp) {
29
- const delay = strategy.next(retryCount += 1).value * 1e3;
30
- if (timeoutTimestamp <= Date.now() + delay) break;
31
- await sleep.sleep(delay);
32
- const { value, done } = await retry();
33
- if (done) return value;
34
- }
35
- throw new Error(`Timeout after ${timeout}s`);
36
- };
37
- const waitForResource = (stop, fetcher, request, options, strategy = createExponentialBackoffStrategy(
38
- options?.minDelay ?? DEFAULT_MIN_DELAY_SECONDS,
39
- options?.maxDelay ?? DEFAULT_MAX_DELAY_SECONDS
40
- )) => tryAtIntervals(
41
- async () => {
42
- const value = await fetcher(request);
43
- return {
44
- done: await stop(value),
45
- value
46
- };
47
- },
48
- strategy,
49
- options?.timeout
50
- );
51
- exports.createExponentialBackoffStrategy = createExponentialBackoffStrategy;
52
- exports.tryAtIntervals = tryAtIntervals;
53
- exports.waitForResource = waitForResource;