@dynatrace-sdk/http-client 1.5.1 → 1.6.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  @dynatrace-sdk/http-client
4
4
 
5
+ ## 1.6.0
6
+
7
+ ### Minor Changes
8
+
9
+ - Added an internal `executeRequest` function, along with internal `ApiClientError`, `ApiGatewayError`, `ClientRequestError` and `InvalidResponseError` classes mirroring the ones in `@dynatrace-sdk/shared-errors`, so generated SDK clients can share the request, response and error-handling logic instead of inlining it in every operation. `@dynatrace-sdk/shared-errors` will switch to re-exporting these classes from here in a follow-up release. (APPDEV-17291)
10
+
11
+ ## 1.5.2
12
+
13
+ ### Patch Changes
14
+
15
+ - Published packages now include an `exports` map in their `package.json` (with `types`, `require` and `import` conditions), so Node.js resolves the `esm/` output as native ES modules. Previously the `module` field was only honoured by bundlers, so the `type: module` marker in `esm/package.json` had no effect in plain Node.js ESM resolution. Deep imports into `cjs/`, `esm/` or `types/` that are not listed in the map are no longer permitted.
16
+ - A `package.json` containing `{"type":"module"}` is now emitted into the `esm/` output directory of each published package. This allows Node.js and bundlers to correctly identify the ESM output as ES modules without requiring the `.mjs` file extension.
17
+ - Updated dependencies
18
+
19
+ - Updated dependencies
20
+
21
+ - @dynatrace-sdk/error-handlers@1.3.3
22
+
5
23
  ## 1.5.1
6
24
 
7
25
  ### Patch Changes
package/cjs/index.js CHANGED
@@ -33,8 +33,8 @@ var __copyProps = (to, from, except, desc) => {
33
33
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
34
34
 
35
35
  // packages/http-client/src/index.ts
36
- var src_exports = {};
37
- __export(src_exports, {
36
+ var index_exports = {};
37
+ __export(index_exports, {
38
38
  PlatformAbortController: () => AbortController,
39
39
  PlatformAbortSignal: () => AbortSignal,
40
40
  PlatformBaseError: () => BaseError,
@@ -43,17 +43,27 @@ __export(src_exports, {
43
43
  PlatformHttpClient: () => HttpClient,
44
44
  PlatformHttpClientAbortError: () => HttpClientAbortError,
45
45
  PlatformHttpClientRequestError: () => HttpClientRequestError,
46
- PlatformHttpClientResponse: () => HttpClientResponse,
46
+ PlatformHttpClientResponse: () => HttpClientResponse2,
47
47
  PlatformHttpClientResponseError: () => HttpClientResponseError,
48
48
  PlatformUnsupportedOperationError: () => UnsupportedOperationError,
49
+ _ApiClientError: () => ApiClientError,
50
+ _ApiGatewayError: () => ApiGatewayError,
51
+ _ClientRequestError: () => ClientRequestError,
52
+ _ErrorType: () => ErrorType,
53
+ _InvalidResponseError: () => InvalidResponseError,
49
54
  _OAuthHttpClient: () => OAuthHttpClient,
55
+ _executeRequest: () => executeRequest,
56
+ _isApiClientError: () => isApiClientError,
57
+ _isApiGatewayError: () => isApiGatewayError,
58
+ _isClientRequestError: () => isClientRequestError,
59
+ _isInvalidResponseError: () => isInvalidResponseError,
50
60
  httpClient: () => httpClient,
51
61
  isHttpClientAbortError: () => isHttpClientAbortError,
52
62
  isHttpClientNetworkError: () => isHttpClientNetworkError,
53
63
  isHttpClientRequestError: () => isHttpClientRequestError,
54
64
  isHttpClientResponseError: () => isHttpClientResponseError
55
65
  });
56
- module.exports = __toCommonJS(src_exports);
66
+ module.exports = __toCommonJS(index_exports);
57
67
 
58
68
  // packages/http-client/src/lib/types/http-client-request-error.ts
59
69
  function isHttpClientRequestError(e) {
@@ -75,18 +85,72 @@ function isHttpClientNetworkError(e) {
75
85
  return e?.name === "NetworkError";
76
86
  }
77
87
 
88
+ // packages/http-client/src/lib/types/error-types.ts
89
+ var ErrorType = /* @__PURE__ */ ((ErrorType3) => {
90
+ ErrorType3["COMMON"] = "JS Error";
91
+ ErrorType3["HTTP"] = "Http Error";
92
+ return ErrorType3;
93
+ })(ErrorType || {});
94
+
78
95
  // packages/http-client/src/lib/platform/abort-controller.ts
79
96
  var AbortController = globalThis.AbortController;
80
97
 
81
98
  // packages/http-client/src/lib/platform/abort-signal.ts
82
99
  var AbortSignal = globalThis.AbortSignal;
83
100
 
101
+ // packages/http-client/src/lib/platform/api-client-error.ts
102
+ var ApiClientError = class extends Error {
103
+ constructor(name, message, cause) {
104
+ super(message ?? "ApiClientError: an unexpected error occurred.");
105
+ this.cause = cause;
106
+ this.name = name;
107
+ }
108
+ cause;
109
+ isApiClientError = true;
110
+ errorType = "JS Error" /* COMMON */;
111
+ };
112
+ function isApiClientError(e) {
113
+ return e?.isApiClientError === true && e instanceof Error;
114
+ }
115
+
116
+ // packages/http-client/src/lib/platform/client-request-error.ts
117
+ var ClientRequestError = class extends ApiClientError {
118
+ isClientRequestError = true;
119
+ body;
120
+ response;
121
+ constructor(name, response, body, message, cause) {
122
+ super(name, message, cause);
123
+ this.errorType = "Http Error" /* HTTP */;
124
+ this.body = body;
125
+ this.response = response;
126
+ }
127
+ };
128
+ function isClientRequestError(e) {
129
+ return e?.isClientRequestError === true && isApiClientError(e);
130
+ }
131
+
132
+ // packages/http-client/src/lib/platform/api-gateway-error.ts
133
+ var ApiGatewayError = class extends ClientRequestError {
134
+ isApiGatewayError = true;
135
+ code;
136
+ retryAfterSeconds;
137
+ constructor(response, body) {
138
+ super(body.error.details?.errorCode || "ApiGatewayError", response, body, body.error.message);
139
+ this.code = body.error.code;
140
+ this.retryAfterSeconds = body.error.retryAfterSeconds;
141
+ }
142
+ };
143
+ function isApiGatewayError(e) {
144
+ return e?.isApiGatewayError === true && isClientRequestError(e);
145
+ }
146
+
84
147
  // packages/http-client/src/lib/platform/base-error.ts
85
148
  var BaseError = class extends Error {
86
149
  constructor(message, cause) {
87
150
  super(message);
88
151
  this.cause = cause;
89
152
  }
153
+ cause;
90
154
  };
91
155
 
92
156
  // packages/http-client/src/lib/platform/unsupported-operation-error.ts
@@ -118,6 +182,7 @@ var Binary = class _Binary {
118
182
  constructor(data) {
119
183
  this.data = data;
120
184
  }
185
+ data;
121
186
  static fromText(text) {
122
187
  return new _Binary(new Blob([text]));
123
188
  }
@@ -150,6 +215,36 @@ var DataTypeError = class extends BaseError {
150
215
  // packages/http-client/src/lib/platform/default-status-validator.ts
151
216
  var defaultStatusValidator = (status) => 200 <= status && status < 300;
152
217
 
218
+ // packages/http-client/src/lib/platform/get-error-message.ts
219
+ function serializeData(data) {
220
+ try {
221
+ return JSON.stringify(data);
222
+ } catch {
223
+ return String(data);
224
+ }
225
+ }
226
+ function getMessagesFromErrorDetails(details) {
227
+ const messages = [];
228
+ Object.entries(details).forEach(([name, data]) => {
229
+ if (!data) return;
230
+ const serializedData = serializeData(data);
231
+ switch (name) {
232
+ case "missingScopes":
233
+ messages.push(`Missing scopes: ${serializedData}`);
234
+ break;
235
+ default:
236
+ messages.push(`${name}: ${serializedData}`);
237
+ }
238
+ });
239
+ return messages;
240
+ }
241
+ function getErrorMessage(errorBody, defaultMessage) {
242
+ const error = errorBody;
243
+ const msg = error?.error?.message || defaultMessage;
244
+ const details = error?.error?.details || {};
245
+ return [msg, ...getMessagesFromErrorDetails(details)].join(". ");
246
+ }
247
+
153
248
  // packages/http-client/src/lib/platform/encode-request-body.ts
154
249
  function encodeTextRequestBody(body) {
155
250
  return String(body);
@@ -279,6 +374,7 @@ var HttpClientAbortError = class extends Error {
279
374
  );
280
375
  this.cause = cause;
281
376
  }
377
+ cause;
282
378
  name = "AbortError";
283
379
  };
284
380
  var throwIfAbortError = (e) => {
@@ -295,21 +391,20 @@ var HttpClientRequestError = class extends BaseError {
295
391
  );
296
392
  this.cause = cause;
297
393
  }
394
+ cause;
298
395
  name = "RequestError";
299
396
  };
300
397
 
301
398
  // packages/http-client/src/lib/platform/decode-form-data.ts
302
399
  function byteToChar(byte) {
303
- if (byte === void 0)
304
- return void 0;
400
+ if (byte === void 0) return void 0;
305
401
  return String.fromCharCode(byte);
306
402
  }
307
403
  function isTextContentType(contentType) {
308
404
  return ["application/json", "text/plain"].includes(String(contentType).toLowerCase());
309
405
  }
310
406
  function removeEscaping(value) {
311
- if (!value)
312
- return value;
407
+ if (!value) return value;
313
408
  return JSON.parse(`"${value}"`);
314
409
  }
315
410
  function parseContentDisposition(contentDisposition) {
@@ -329,6 +424,8 @@ var FormDataParser = class {
329
424
  this.sourceArray = sourceArray;
330
425
  this.boundary = boundary;
331
426
  }
427
+ sourceArray;
428
+ boundary;
332
429
  currentChar = null;
333
430
  currentByte = null;
334
431
  offset = 0;
@@ -635,11 +732,12 @@ function decodeResponseBody(response, responseBodyType) {
635
732
  }
636
733
 
637
734
  // packages/http-client/src/lib/platform/http-client-response.ts
638
- var HttpClientResponse = class {
735
+ var HttpClientResponse2 = class {
639
736
  constructor(response, data) {
640
737
  this.response = response;
641
738
  this.requestUrl = data?.requestUrl ?? response.url;
642
739
  }
740
+ response;
643
741
  requestUrl;
644
742
  get url() {
645
743
  return this.response.url;
@@ -753,7 +851,7 @@ var HttpClientResponseError = class extends BaseError {
753
851
  constructor(response, data) {
754
852
  addHttpClientResponseErrorSerializer();
755
853
  super(`HTTP Error ${response.status}: ${response.statusText}`);
756
- this.response = new HttpClientResponse(response, {
854
+ this.response = new HttpClientResponse2(response, {
757
855
  requestUrl: data?.requestUrl ?? response.url
758
856
  });
759
857
  this.requestMethod = data?.requestMethod;
@@ -804,7 +902,7 @@ var HttpClient = class {
804
902
  });
805
903
  const ok = statusValidator(response.status);
806
904
  if (ok) {
807
- return new HttpClientResponse(response, { requestUrl: url });
905
+ return new HttpClientResponse2(response, { requestUrl: url });
808
906
  } else {
809
907
  throw new HttpClientResponseError(response, {
810
908
  requestUrl: url,
@@ -815,6 +913,210 @@ var HttpClient = class {
815
913
  };
816
914
  var httpClient = new HttpClient();
817
915
 
916
+ // packages/http-client/src/lib/platform/invalid-response-error.ts
917
+ var InvalidResponseError = class extends ApiClientError {
918
+ isInvalidResponseError = true;
919
+ responseBody;
920
+ expectedType;
921
+ nestedError;
922
+ response;
923
+ constructor(name, nestedError, body, expectedType, message, response) {
924
+ super(
925
+ name,
926
+ message ?? `${name}: Response does not match expected datatype${expectedType ? " " + expectedType : ""}: ${nestedError?.toString() ?? "unable to deserialize"}`
927
+ );
928
+ this.nestedError = nestedError;
929
+ this.responseBody = body;
930
+ this.expectedType = expectedType;
931
+ this.response = response;
932
+ }
933
+ };
934
+ function isHttpClientDataTypeError(e) {
935
+ return e instanceof Error && e?.name === "DataTypeError";
936
+ }
937
+ function isInvalidResponseError(e) {
938
+ if (e?.isInvalidResponseError === true && isApiClientError(e)) {
939
+ return true;
940
+ }
941
+ return isHttpClientDataTypeError(e);
942
+ }
943
+
944
+ // packages/http-client/src/lib/platform/execute-request.ts
945
+ var API_GATEWAY_RESPONSE_SOURCE_HEADER = "dynatrace-response-source";
946
+ var API_GATEWAY_RESPONSE_SOURCE = "API Gateway";
947
+ function buildStatusValidator(acceptedStatusCodes, statusValidator) {
948
+ if (acceptedStatusCodes !== void 0) {
949
+ return (status) => acceptedStatusCodes.includes(status);
950
+ }
951
+ return statusValidator ?? defaultStatusValidator;
952
+ }
953
+ function resolveBodyType(resolver, response) {
954
+ return typeof resolver === "function" ? resolver(response) : resolver;
955
+ }
956
+ function readBody(response, responseBodyType) {
957
+ return response.body(responseBodyType);
958
+ }
959
+ async function readTextBody(response) {
960
+ try {
961
+ return await response.body("text");
962
+ } catch {
963
+ return "";
964
+ }
965
+ }
966
+ function resolveErrorFactory(status, factories) {
967
+ const exact = factories?.[status];
968
+ if (exact) {
969
+ return { factory: exact, label: `${status}` };
970
+ }
971
+ const range = factories?.[`${Math.floor(status / 100)}XX`];
972
+ if (range) {
973
+ return { factory: range, label: `${status}` };
974
+ }
975
+ if (factories?.default) {
976
+ return { factory: factories.default, label: "err" };
977
+ }
978
+ return void 0;
979
+ }
980
+ async function buildApiGatewayError(response, operationId) {
981
+ if (response.headers?.[API_GATEWAY_RESPONSE_SOURCE_HEADER] !== API_GATEWAY_RESPONSE_SOURCE) {
982
+ return void 0;
983
+ }
984
+ let body;
985
+ try {
986
+ body = await response.body("json");
987
+ } catch (decodeErr) {
988
+ throw new InvalidResponseError(
989
+ `${operationId}:${response.status}`,
990
+ decodeErr,
991
+ await readTextBody(response),
992
+ void 0,
993
+ void 0,
994
+ response
995
+ );
996
+ }
997
+ return new ApiGatewayError(response, body);
998
+ }
999
+ async function buildFactoryError(e, { factory, label }, options) {
1000
+ const { response } = e;
1001
+ const name = `${options.operationId}:${label}`;
1002
+ const expectedType = factory.errorEnvelope ?? options.errorEnvelope;
1003
+ const bodyType = resolveBodyType(factory.responseBodyType ?? "json", response);
1004
+ let body;
1005
+ if (bodyType !== "none") {
1006
+ try {
1007
+ body = await readBody(response, bodyType);
1008
+ } catch (decodeErr) {
1009
+ throw new InvalidResponseError(
1010
+ name,
1011
+ decodeErr,
1012
+ await readTextBody(response),
1013
+ expectedType,
1014
+ void 0,
1015
+ response
1016
+ );
1017
+ }
1018
+ }
1019
+ if (factory.transformBody) {
1020
+ try {
1021
+ body = factory.transformBody(body);
1022
+ } catch (transformErr) {
1023
+ throw new InvalidResponseError(name, transformErr, body, expectedType, void 0, response);
1024
+ }
1025
+ }
1026
+ return factory.build({ response, body, cause: e });
1027
+ }
1028
+ async function buildFallbackError(e) {
1029
+ const { response } = e;
1030
+ let responseValue;
1031
+ try {
1032
+ responseValue = await response.body("json");
1033
+ } catch (decodeErr) {
1034
+ throw new InvalidResponseError(
1035
+ `${response.status}`,
1036
+ decodeErr,
1037
+ await readTextBody(response),
1038
+ "json",
1039
+ "Unexpected api response",
1040
+ response
1041
+ );
1042
+ }
1043
+ return new ClientRequestError(
1044
+ `${response.status}`,
1045
+ response,
1046
+ responseValue,
1047
+ getErrorMessage(
1048
+ responseValue,
1049
+ `Unexpected api response: code=${response.status} body="${responseValue}"`
1050
+ ),
1051
+ e
1052
+ );
1053
+ }
1054
+ async function dispatchResponseError(e, options) {
1055
+ const gatewayError = await buildApiGatewayError(e.response, options.operationId);
1056
+ if (gatewayError) {
1057
+ throw gatewayError;
1058
+ }
1059
+ const resolved = resolveErrorFactory(e.response.status, options.errorFactories);
1060
+ throw resolved ? await buildFactoryError(e, resolved, options) : await buildFallbackError(e);
1061
+ }
1062
+ async function decodeSuccessBody(response, options) {
1063
+ const resolvedBodyType = resolveBodyType(options.responseBodyType ?? "json", response);
1064
+ if (resolvedBodyType === "none") {
1065
+ return void 0;
1066
+ }
1067
+ const name = `${options.operationId}:${response.status}`;
1068
+ let body;
1069
+ try {
1070
+ body = await readBody(response, resolvedBodyType);
1071
+ } catch (e) {
1072
+ throw new InvalidResponseError(
1073
+ name,
1074
+ e,
1075
+ await readTextBody(response),
1076
+ void 0,
1077
+ void 0,
1078
+ response
1079
+ );
1080
+ }
1081
+ if (!options.transformResponse) {
1082
+ return body;
1083
+ }
1084
+ try {
1085
+ return options.transformResponse(body, response);
1086
+ } catch (e) {
1087
+ throw new InvalidResponseError(name, e, body, void 0, void 0, response);
1088
+ }
1089
+ }
1090
+ async function executeRequest(options) {
1091
+ const { acceptedStatusCodes, statusValidator } = options;
1092
+ if (acceptedStatusCodes !== void 0 && statusValidator !== void 0) {
1093
+ throw new TypeError("acceptedStatusCodes and statusValidator are mutually exclusive.");
1094
+ }
1095
+ const validator = buildStatusValidator(acceptedStatusCodes, statusValidator);
1096
+ const client = options.httpClient ?? httpClient;
1097
+ let response;
1098
+ try {
1099
+ response = await client.send({
1100
+ url: options.url,
1101
+ method: options.method,
1102
+ headers: options.headers,
1103
+ body: options.body,
1104
+ requestBodyType: options.requestBodyType,
1105
+ abortSignal: options.abortSignal,
1106
+ statusValidator: validator
1107
+ });
1108
+ } catch (e) {
1109
+ if (isHttpClientAbortError(e) || isInvalidResponseError(e) || isClientRequestError(e)) {
1110
+ throw e;
1111
+ }
1112
+ if (!isHttpClientResponseError(e)) {
1113
+ throw new ApiClientError("UnexpectedError", "Unexpected error", e);
1114
+ }
1115
+ return await dispatchResponseError(e, options);
1116
+ }
1117
+ return decodeSuccessBody(response, options);
1118
+ }
1119
+
818
1120
  // packages/http-client/src/lib/platform/oauth-http-client.ts
819
1121
  var TOKEN_EXPIRATION_SAFETY_MARGIN_SECONDS = 1;
820
1122
  var OAuthToken = class {
@@ -857,6 +1159,7 @@ var OAuthHttpClient = class {
857
1159
  constructor(config) {
858
1160
  this.config = config;
859
1161
  }
1162
+ config;
860
1163
  oauthToken;
861
1164
  async send(options) {
862
1165
  const { statusValidator = defaultStatusValidator } = options;
@@ -879,7 +1182,7 @@ var OAuthHttpClient = class {
879
1182
  });
880
1183
  const ok = statusValidator(response.status);
881
1184
  if (ok) {
882
- return new HttpClientResponse(response, { requestUrl });
1185
+ return new HttpClientResponse2(response, { requestUrl });
883
1186
  } else {
884
1187
  throw new HttpClientResponseError(response, {
885
1188
  requestUrl,