@dynatrace-sdk/http-client 1.1.1 → 1.3.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/esm/index.js CHANGED
@@ -73,19 +73,19 @@ function getImpl(data, type) {
73
73
  }
74
74
  throw new UnsupportedOperationError(`Unsupported binary type: ${type}.`);
75
75
  }
76
- var Binary = class {
76
+ var Binary = class _Binary {
77
77
  constructor(data) {
78
78
  this.data = data;
79
79
  }
80
80
  static fromText(text) {
81
- return new Binary(new Blob([text]));
81
+ return new _Binary(new Blob([text]));
82
82
  }
83
83
  static fromJson(json) {
84
- return new Binary(new Blob([JSON.stringify(json)]));
84
+ return new _Binary(new Blob([JSON.stringify(json)]));
85
85
  }
86
86
  static from(data) {
87
87
  if (data instanceof Blob || data instanceof ArrayBuffer || data instanceof ReadableStream) {
88
- return new Binary(data);
88
+ return new _Binary(data);
89
89
  } else {
90
90
  throw new UnsupportedOperationError("Unsupported binary type.");
91
91
  }
@@ -257,6 +257,190 @@ var HttpClientRequestError = class extends BaseError {
257
257
  name = "RequestError";
258
258
  };
259
259
 
260
+ // packages/http-client/src/lib/platform/decode-form-data.ts
261
+ function byteToChar(byte) {
262
+ if (byte === void 0)
263
+ return void 0;
264
+ return String.fromCharCode(byte);
265
+ }
266
+ function isTextContentType(contentType) {
267
+ return ["application/json", "text/plain"].includes(String(contentType).toLowerCase());
268
+ }
269
+ function removeEscaping(value) {
270
+ if (!value)
271
+ return value;
272
+ return JSON.parse(`"${value}"`);
273
+ }
274
+ function parseContentDisposition(contentDisposition) {
275
+ const fileName = removeEscaping(
276
+ /form-data;.*filename="((?:[^"\\]|\\.)*)"/gm.exec(contentDisposition)?.[1]
277
+ );
278
+ const name = removeEscaping(
279
+ /form-data;.*(?<!file)name="((?:[^"\\]|\\.)*)"/gm.exec(contentDisposition)?.[1]
280
+ );
281
+ return { name, fileName };
282
+ }
283
+ function parseFormDataBoundary(contentType) {
284
+ return /multipart\/form-data;boundary=(.*)/gm.exec(contentType)?.[1];
285
+ }
286
+ var FormDataParser = class {
287
+ constructor(sourceArray, boundary) {
288
+ this.sourceArray = sourceArray;
289
+ this.boundary = boundary;
290
+ }
291
+ currentChar = null;
292
+ currentByte = null;
293
+ offset = 0;
294
+ utf8Decoder = new TextDecoder("utf-8");
295
+ get previousByte() {
296
+ return this.sourceArray[this.offset - 2];
297
+ }
298
+ get previousChar() {
299
+ return byteToChar(this.previousByte);
300
+ }
301
+ next() {
302
+ if (this.offset >= this.sourceArray.byteLength) {
303
+ this.currentChar = null;
304
+ this.currentByte = null;
305
+ return false;
306
+ }
307
+ this.currentByte = this.sourceArray[this.offset];
308
+ this.currentChar = String.fromCharCode(this.currentByte);
309
+ this.offset++;
310
+ return true;
311
+ }
312
+ charAt(offset) {
313
+ return byteToChar(this.sourceArray[offset]) ?? null;
314
+ }
315
+ nextChar() {
316
+ this.next();
317
+ return this.currentChar;
318
+ }
319
+ nextByte() {
320
+ this.next();
321
+ return this.currentByte;
322
+ }
323
+ get nextTwoChars() {
324
+ return String.fromCharCode(this.sourceArray[this.offset], this.sourceArray[this.offset + 1]);
325
+ }
326
+ findNextBoundaryOffset(startOffset = this.offset) {
327
+ let boundaryIndex = 0;
328
+ let boundaryMatch = false;
329
+ let offset = startOffset;
330
+ let currentChar = this.charAt(offset);
331
+ while (!boundaryMatch) {
332
+ if (currentChar === null) {
333
+ return null;
334
+ }
335
+ if (currentChar === this.boundary[boundaryIndex]) {
336
+ boundaryIndex++;
337
+ if (boundaryIndex === this.boundary.length) {
338
+ boundaryMatch = true;
339
+ }
340
+ } else {
341
+ boundaryIndex = 0;
342
+ }
343
+ offset++;
344
+ currentChar = this.charAt(offset);
345
+ }
346
+ return offset - this.boundary.length;
347
+ }
348
+ skipPastNextBoundary() {
349
+ const nextBoundaryOffset = this.findNextBoundaryOffset();
350
+ if (nextBoundaryOffset === null) {
351
+ return false;
352
+ }
353
+ this.offset = nextBoundaryOffset + this.boundary.length;
354
+ this.currentByte = this.sourceArray[this.offset];
355
+ this.currentChar = String.fromCharCode(this.currentByte);
356
+ const twoChars = this.nextTwoChars;
357
+ if (twoChars == "--") {
358
+ return false;
359
+ } else if (twoChars == "\r\n") {
360
+ this.offset++;
361
+ this.next();
362
+ }
363
+ return true;
364
+ }
365
+ readLine() {
366
+ const lineBuffer = [];
367
+ do {
368
+ const byte = this.nextByte();
369
+ if (byte === null) {
370
+ return null;
371
+ }
372
+ lineBuffer.push(byte);
373
+ } while (this.currentChar !== null && this.currentChar !== "\n" && this.previousChar !== "\r");
374
+ return Uint8Array.from(lineBuffer);
375
+ }
376
+ readSectionHeaders() {
377
+ const headers = {};
378
+ const headerStartOffset = this.offset;
379
+ let isEndOfHeaders = false;
380
+ while (!isEndOfHeaders) {
381
+ const line = this.readLine();
382
+ if (line === null) {
383
+ throw TypeError("Unexpected end of response while parsing headers");
384
+ }
385
+ const headerString = this.utf8Decoder.decode(line);
386
+ if (headerString === "\r\n") {
387
+ isEndOfHeaders = true;
388
+ break;
389
+ }
390
+ const [header, value] = headerString.split(":").map((part) => (part ?? "").trim());
391
+ headers[header.toLowerCase()] = value;
392
+ }
393
+ const headersLength = this.offset - headerStartOffset;
394
+ return {
395
+ headersLength,
396
+ headers
397
+ };
398
+ }
399
+ extractData() {
400
+ const nextBoundaryOffset = this.findNextBoundaryOffset() ?? this.sourceArray.length;
401
+ const lastTwoBytes = String.fromCharCode(
402
+ this.sourceArray[nextBoundaryOffset - 2],
403
+ this.sourceArray[nextBoundaryOffset - 1]
404
+ );
405
+ const endOfDataSection = lastTwoBytes === "\r\n" ? nextBoundaryOffset - 2 : nextBoundaryOffset;
406
+ const data = this.sourceArray.slice(this.offset, endOfDataSection);
407
+ return {
408
+ payloadStartOffset: this.offset,
409
+ payloadEndOffset: endOfDataSection,
410
+ data
411
+ };
412
+ }
413
+ parse() {
414
+ const sections = [];
415
+ while (this.skipPastNextBoundary()) {
416
+ const headersStartOffset = this.offset;
417
+ const { headers } = this.readSectionHeaders();
418
+ const { data, payloadStartOffset, payloadEndOffset } = this.extractData();
419
+ const isText = isTextContentType(headers["content-type"]);
420
+ const { name, fileName } = parseContentDisposition(headers["content-disposition"]);
421
+ sections.push({
422
+ name,
423
+ text: isText ? this.utf8Decoder.decode(data) : void 0,
424
+ file: !isText ? new File([data], fileName ?? "", {
425
+ type: headers["content-type"] ?? "application/octet-stream"
426
+ }) : void 0,
427
+ rawData: data,
428
+ headers,
429
+ headersStartOffset,
430
+ payloadStartOffset,
431
+ payloadEndOffset
432
+ });
433
+ }
434
+ return sections;
435
+ }
436
+ };
437
+ function isAppleBrowser() {
438
+ return /apple/i.test(navigator.vendor);
439
+ }
440
+ function parseMultipartFormDataResponse(response, boundary) {
441
+ return new FormDataParser(response, boundary).parse();
442
+ }
443
+
260
444
  // packages/http-client/src/lib/platform/decode-response-body.ts
261
445
  function emptyReadableStream() {
262
446
  return new ReadableStream({
@@ -278,25 +462,62 @@ async function decodeFormDataResponseBody(response) {
278
462
  if (response.body === null) {
279
463
  return [];
280
464
  } else {
281
- const formData = await response.formData();
282
465
  const result = [];
283
- formData.forEach((value, key) => {
284
- if (value instanceof File) {
285
- result.push({
286
- type: "binary",
287
- name: key,
288
- contentType: value.type,
289
- filename: value.name,
290
- value: Binary.from(value)
291
- });
292
- } else {
293
- result.push({
294
- type: "text",
295
- name: key,
296
- value
297
- });
298
- }
299
- });
466
+ if (isAppleBrowser()) {
467
+ const responseClone = await response.clone();
468
+ const responseBinaryData = new Uint8Array(await responseClone.arrayBuffer());
469
+ const boundary = parseFormDataBoundary(responseClone.headers.get("content-type"));
470
+ const manuallyParsedFormData = parseMultipartFormDataResponse(
471
+ responseBinaryData,
472
+ `--${boundary}`
473
+ );
474
+ const automaticallyParsedFormData = await response.formData();
475
+ automaticallyParsedFormData.forEach((value, key) => {
476
+ const manuallyParsedSection = manuallyParsedFormData.find(({ name }) => name === key);
477
+ if (typeof value === "string" && manuallyParsedSection?.file !== void 0) {
478
+ result.push({
479
+ type: "binary",
480
+ name: key,
481
+ contentType: manuallyParsedSection.headers["content-type"],
482
+ filename: manuallyParsedSection.file.name,
483
+ value: Binary.from(manuallyParsedSection.file)
484
+ });
485
+ } else if (value instanceof File) {
486
+ result.push({
487
+ type: "binary",
488
+ name: key,
489
+ contentType: value.type,
490
+ filename: value.name,
491
+ value: Binary.from(value)
492
+ });
493
+ } else {
494
+ result.push({
495
+ type: "text",
496
+ name: key,
497
+ value
498
+ });
499
+ }
500
+ });
501
+ } else {
502
+ const formData = await response.formData();
503
+ formData.forEach((value, key) => {
504
+ if (value instanceof File) {
505
+ result.push({
506
+ type: "binary",
507
+ name: key,
508
+ contentType: value.type,
509
+ filename: value.name,
510
+ value: Binary.from(value)
511
+ });
512
+ } else {
513
+ result.push({
514
+ type: "text",
515
+ name: key,
516
+ value
517
+ });
518
+ }
519
+ });
520
+ }
300
521
  return result;
301
522
  }
302
523
  }
@@ -507,13 +728,35 @@ var send = async (info, init) => {
507
728
  }
508
729
  };
509
730
  var HttpClient = class {
731
+ _baseUrl;
732
+ _defaultHeaders;
733
+ constructor(options) {
734
+ this._baseUrl = options?.baseUrl;
735
+ this._defaultHeaders = options?.defaultHeaders;
736
+ }
737
+ /**
738
+ * Sets HTTP Client Instance baseUrl param to the incoming value `baseUrl`.
739
+ * @param baseUrl Base URL used in the request path.
740
+ */
741
+ _setBaseURL(baseUrl) {
742
+ this._baseUrl = baseUrl;
743
+ }
744
+ /**
745
+ * Sets HTTP Client Instance defaultHeaders param to the incoming value `defaultHeaders`.
746
+ * @param defaultHeaders HTTP Headers to be used in outgoing requests.
747
+ */
748
+ _setDefaultHeaders(defaultHeaders) {
749
+ this._defaultHeaders = defaultHeaders;
750
+ }
510
751
  async send(options) {
511
752
  const { statusValidator = defaultStatusValidator } = options;
512
753
  const requestBodyType = options.requestBodyType ?? "json";
513
754
  const body = options.body !== void 0 ? await encodeRequestBody(options.body, requestBodyType) : void 0;
514
- const response = await send(options.url, {
755
+ const url = this._baseUrl ? new URL(options.url, this._baseUrl).toString() : options.url;
756
+ const requestHeaders = { ...this._defaultHeaders, ...options?.headers };
757
+ const response = await send(url, {
515
758
  method: options.method,
516
- headers: applyContentTypeHeader(options.headers, requestBodyType),
759
+ headers: applyContentTypeHeader(requestHeaders, requestBodyType),
517
760
  signal: options.abortSignal,
518
761
  body
519
762
  });
@@ -537,7 +780,7 @@ var OAuthToken = class {
537
780
  this._scope = oauthTokenResponse.scope;
538
781
  this._tokenType = oauthTokenResponse.token_type;
539
782
  this._expirationDate = ((expiresIn) => {
540
- const date = new Date();
783
+ const date = /* @__PURE__ */ new Date();
541
784
  date.setSeconds(date.getSeconds() + expiresIn);
542
785
  return date;
543
786
  })(oauthTokenResponse.expires_in);
@@ -550,7 +793,7 @@ var OAuthToken = class {
550
793
  return this._tokenType;
551
794
  }
552
795
  isExpired() {
553
- return this._expirationDate <= new Date();
796
+ return this._expirationDate <= /* @__PURE__ */ new Date();
554
797
  }
555
798
  get accessToken() {
556
799
  return this._accessToken;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dynatrace-sdk/http-client",
3
- "version": "1.1.1",
3
+ "version": "1.3.0",
4
4
  "description": "An environment agnostic (browser/deno vs nodejs) abstraction layer for making HTTP calls.",
5
5
  "license": "Apache-2.0",
6
6
  "dependencies": {
@@ -2,5 +2,5 @@ import * as types from '../types';
2
2
  declare const AbortController: {
3
3
  new (): types.AbortController;
4
4
  };
5
- declare type AbortController = InstanceType<typeof AbortController>;
5
+ type AbortController = InstanceType<typeof AbortController>;
6
6
  export { AbortController };
@@ -2,5 +2,5 @@ import * as types from '../types';
2
2
  declare const AbortSignal: {
3
3
  new (): types.AbortSignal;
4
4
  };
5
- declare type AbortSignal = InstanceType<typeof AbortSignal>;
5
+ type AbortSignal = InstanceType<typeof AbortSignal>;
6
6
  export { AbortSignal };
@@ -0,0 +1,48 @@
1
+ export declare function isTextContentType(contentType: string): boolean;
2
+ export declare function parseContentDisposition(contentDisposition: string): {
3
+ name: string;
4
+ fileName: string | undefined;
5
+ };
6
+ export declare function parseFormDataBoundary(contentType: string): string | undefined;
7
+ export interface FormDataSection {
8
+ name: string;
9
+ headers: Record<string, string>;
10
+ rawData: Uint8Array;
11
+ text?: string;
12
+ file?: File;
13
+ fileName?: string;
14
+ payloadStartOffset?: number;
15
+ payloadEndOffset?: number;
16
+ headersStartOffset?: number;
17
+ }
18
+ export declare class FormDataParser {
19
+ private sourceArray;
20
+ private boundary;
21
+ private currentChar;
22
+ private currentByte;
23
+ offset: number;
24
+ private utf8Decoder;
25
+ constructor(sourceArray: Uint8Array, boundary: string);
26
+ get previousByte(): number | undefined;
27
+ get previousChar(): string | undefined;
28
+ private next;
29
+ charAt(offset: number): string | null;
30
+ nextChar(): string | null;
31
+ nextByte(): number | null;
32
+ get nextTwoChars(): string;
33
+ findNextBoundaryOffset(startOffset?: number): number | null;
34
+ skipPastNextBoundary(): boolean;
35
+ readLine(): Uint8Array | null;
36
+ readSectionHeaders(): {
37
+ headersLength: number;
38
+ headers: Record<string, string>;
39
+ };
40
+ extractData(): {
41
+ payloadStartOffset: number;
42
+ payloadEndOffset: number;
43
+ data: Uint8Array;
44
+ };
45
+ parse(): FormDataSection[];
46
+ }
47
+ export declare function isAppleBrowser(): boolean;
48
+ export declare function parseMultipartFormDataResponse(response: Uint8Array, boundary: string): FormDataSection[];
@@ -1,5 +1,24 @@
1
1
  import * as types from '../types';
2
+ import { Headers } from '../types';
3
+ interface HttpClientConfiguration {
4
+ baseUrl?: string;
5
+ defaultHeaders?: Headers;
6
+ }
2
7
  export declare class HttpClient implements types.HttpClient {
8
+ private _baseUrl;
9
+ private _defaultHeaders;
10
+ constructor(options?: HttpClientConfiguration);
11
+ /**
12
+ * Sets HTTP Client Instance baseUrl param to the incoming value `baseUrl`.
13
+ * @param baseUrl Base URL used in the request path.
14
+ */
15
+ _setBaseURL(baseUrl: string): void;
16
+ /**
17
+ * Sets HTTP Client Instance defaultHeaders param to the incoming value `defaultHeaders`.
18
+ * @param defaultHeaders HTTP Headers to be used in outgoing requests.
19
+ */
20
+ _setDefaultHeaders(defaultHeaders: Headers): void;
3
21
  send<T extends keyof types.RequestBodyTypes = 'json'>(options: types.HttpClientRequestOptions<T>): Promise<types.HttpClientResponse>;
4
22
  }
5
23
  export declare const httpClient: HttpClient;
24
+ export {};
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Represents a signal object that allows to communicate with the request and abort it using the `AbortController`.
3
+ * @deprecated Will be removed from HttpClient. We encourage using native interface for AbortSignal.
3
4
  */
4
- export interface AbortSignal extends EventTarget {
5
+ interface HttpClientAbortSignal extends EventTarget {
5
6
  readonly reason: any;
6
7
  throwIfAborted(): void;
7
8
  /**
@@ -13,3 +14,5 @@ export interface AbortSignal extends EventTarget {
13
14
  */
14
15
  onabort: ((this: AbortSignal, event: Event) => void) | null;
15
16
  }
17
+ export type AbortSignal = HttpClientAbortSignal | globalThis.AbortSignal;
18
+ export {};
@@ -4,7 +4,7 @@ import type * as stream from 'stream';
4
4
  /**
5
5
  * Mapping between the data type names and types.
6
6
  */
7
- export declare type DataTypes = {
7
+ export type DataTypes = {
8
8
  /**
9
9
  * A text type.
10
10
  */
@@ -76,8 +76,8 @@ export interface BinaryFormDataRequestField {
76
76
  /**
77
77
  * Represents a multipart/form-data field.
78
78
  */
79
- export declare type FormDataRequestField = TextFormDataRequestField | JsonFormDataRequestField | BinaryFormDataRequestField;
79
+ export type FormDataRequestField = TextFormDataRequestField | JsonFormDataRequestField | BinaryFormDataRequestField;
80
80
  /**
81
81
  * Represents a multipart/form-data body.
82
82
  */
83
- export declare type FormDataRequestBody = Array<FormDataRequestField>;
83
+ export type FormDataRequestBody = Array<FormDataRequestField>;
@@ -11,5 +11,5 @@ export interface BinaryFormDataResponseField {
11
11
  filename: string;
12
12
  value: Binary;
13
13
  }
14
- export declare type FormDataResponseField = TextFormDataResponseField | BinaryFormDataResponseField;
15
- export declare type FormDataResponseBody = Array<FormDataResponseField>;
14
+ export type FormDataResponseField = TextFormDataResponseField | BinaryFormDataResponseField;
15
+ export type FormDataResponseBody = Array<FormDataResponseField>;
@@ -6,7 +6,7 @@ import { Binary } from './binary';
6
6
  /**
7
7
  * Mapping between the request body type names and types.
8
8
  */
9
- export declare type RequestBodyTypes = {
9
+ export type RequestBodyTypes = {
10
10
  /**
11
11
  * A text request body type.
12
12
  */
@@ -6,7 +6,7 @@ import { Binary } from './binary';
6
6
  /**
7
7
  * Mapping between the response body type names and types.
8
8
  */
9
- export declare type ResponseBodyTypes = {
9
+ export type ResponseBodyTypes = {
10
10
  /**
11
11
  * A text response body type.
12
12
  */