@typespec/ts-http-runtime 1.0.0-alpha.20231107.1 → 1.0.0-alpha.20231115.1

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 (37) hide show
  1. package/dist/index.js +501 -251
  2. package/dist/index.js.map +1 -1
  3. package/dist-esm/src/client/sendRequest.js +1 -1
  4. package/dist-esm/src/client/sendRequest.js.map +1 -1
  5. package/dist-esm/src/createPipelineFromOptions.js +5 -0
  6. package/dist-esm/src/createPipelineFromOptions.js.map +1 -1
  7. package/dist-esm/src/fetchHttpClient.js +1 -14
  8. package/dist-esm/src/fetchHttpClient.js.map +1 -1
  9. package/dist-esm/src/httpHeaders.js +1 -1
  10. package/dist-esm/src/httpHeaders.js.map +1 -1
  11. package/dist-esm/src/index.js +2 -0
  12. package/dist-esm/src/index.js.map +1 -1
  13. package/dist-esm/src/interfaces.js.map +1 -1
  14. package/dist-esm/src/pipelineRequest.js +1 -0
  15. package/dist-esm/src/pipelineRequest.js.map +1 -1
  16. package/dist-esm/src/policies/formDataPolicy.js +34 -32
  17. package/dist-esm/src/policies/formDataPolicy.js.map +1 -1
  18. package/dist-esm/src/policies/multipartPolicy.js +112 -0
  19. package/dist-esm/src/policies/multipartPolicy.js.map +1 -0
  20. package/dist-esm/src/util/file.js +51 -0
  21. package/dist-esm/src/util/file.js.map +1 -0
  22. package/dist-esm/src/util/stream.browser.js +64 -0
  23. package/dist-esm/src/util/stream.browser.js.map +1 -0
  24. package/dist-esm/src/util/stream.js +81 -0
  25. package/dist-esm/src/util/stream.js.map +1 -0
  26. package/dist-esm/src/util/typeGuards.js +14 -0
  27. package/dist-esm/src/util/typeGuards.js.map +1 -1
  28. package/dist-esm/src/xhrHttpClient.js +2 -12
  29. package/dist-esm/src/xhrHttpClient.js.map +1 -1
  30. package/package.json +2 -3
  31. package/types/ts-http-runtime.d.ts +116 -2
  32. package/dist-esm/src/client/helpers/isReadableStream.browser.js +0 -12
  33. package/dist-esm/src/client/helpers/isReadableStream.browser.js.map +0 -1
  34. package/dist-esm/src/client/helpers/isReadableStream.js +0 -10
  35. package/dist-esm/src/client/helpers/isReadableStream.js.map +0 -1
  36. package/dist-esm/src/policies/formDataPolicy.browser.js +0 -43
  37. package/dist-esm/src/policies/formDataPolicy.browser.js.map +0 -1
@@ -0,0 +1,112 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { stringToUint8Array } from "../util/bytesEncoding";
4
+ import { toStream, concatenateStreams } from "../util/stream";
5
+ import { isBlob } from "../util/typeGuards";
6
+ import { randomUUID } from "../util/uuidUtils";
7
+ function generateBoundary() {
8
+ return `----AzSDKFormBoundary${randomUUID()}`;
9
+ }
10
+ function encodeHeaders(headers) {
11
+ let result = "";
12
+ for (const [key, value] of headers) {
13
+ result += `${key}: ${value}\r\n`;
14
+ }
15
+ return result;
16
+ }
17
+ function getLength(source) {
18
+ if (source instanceof Uint8Array) {
19
+ return source.byteLength;
20
+ }
21
+ else if (isBlob(source)) {
22
+ // if was created using createFile then -1 means we have an unknown size
23
+ return source.size === -1 ? undefined : source.size;
24
+ }
25
+ else {
26
+ return undefined;
27
+ }
28
+ }
29
+ function getTotalLength(sources) {
30
+ let total = 0;
31
+ for (const source of sources) {
32
+ const partLength = getLength(source);
33
+ if (partLength === undefined) {
34
+ return undefined;
35
+ }
36
+ else {
37
+ total += partLength;
38
+ }
39
+ }
40
+ return total;
41
+ }
42
+ function buildRequestBody(request, parts, boundary) {
43
+ const sources = [
44
+ stringToUint8Array(`--${boundary}`, "utf-8"),
45
+ ...parts.flatMap((part) => [
46
+ stringToUint8Array("\r\n", "utf-8"),
47
+ stringToUint8Array(encodeHeaders(part.headers), "utf-8"),
48
+ stringToUint8Array("\r\n", "utf-8"),
49
+ part.body,
50
+ stringToUint8Array(`\r\n--${boundary}`, "utf-8"),
51
+ ]),
52
+ stringToUint8Array("--\r\n\r\n", "utf-8"),
53
+ ];
54
+ const contentLength = getTotalLength(sources);
55
+ if (contentLength) {
56
+ request.headers.set("Content-Length", contentLength);
57
+ }
58
+ request.body = (() => concatenateStreams(sources.map((source) => (typeof source === "function" ? source() : source)).map(toStream)));
59
+ }
60
+ /**
61
+ * Name of multipart policy
62
+ */
63
+ export const multipartPolicyName = "multipartPolicy";
64
+ const maxBoundaryLength = 70;
65
+ const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
66
+ function assertValidBoundary(boundary) {
67
+ if (boundary.length > maxBoundaryLength) {
68
+ throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
69
+ }
70
+ if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
71
+ throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
72
+ }
73
+ }
74
+ /**
75
+ * Pipeline policy for multipart requests
76
+ */
77
+ export function multipartPolicy() {
78
+ return {
79
+ name: multipartPolicyName,
80
+ sendRequest(request, next) {
81
+ var _a;
82
+ if (!request.multipartBody) {
83
+ return next(request);
84
+ }
85
+ if (request.body) {
86
+ throw new Error("multipartBody and regular body cannot be set at the same time");
87
+ }
88
+ let boundary = request.multipartBody.boundary;
89
+ const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed";
90
+ const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
91
+ if (!parsedHeader) {
92
+ throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
93
+ }
94
+ const [, contentType, parsedBoundary] = parsedHeader;
95
+ if (parsedBoundary && boundary && parsedBoundary !== boundary) {
96
+ throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
97
+ }
98
+ boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary);
99
+ if (boundary) {
100
+ assertValidBoundary(boundary);
101
+ }
102
+ else {
103
+ boundary = generateBoundary();
104
+ }
105
+ request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
106
+ buildRequestBody(request, request.multipartBody.parts, boundary);
107
+ request.multipartBody = undefined;
108
+ return next(request);
109
+ },
110
+ };
111
+ }
112
+ //# sourceMappingURL=multipartPolicy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multipartPolicy.js","sourceRoot":"","sources":["../../../src/policies/multipartPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,SAAS,gBAAgB;IACvB,OAAO,wBAAwB,UAAU,EAAE,EAAE,CAAC;AAChD,CAAC;AAED,SAAS,aAAa,CAAC,OAAoB;IACzC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO,EAAE;QAClC,MAAM,IAAI,GAAG,GAAG,KAAK,KAAK,MAAM,CAAC;KAClC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,SAAS,CAChB,MAMyB;IAEzB,IAAI,MAAM,YAAY,UAAU,EAAE;QAChC,OAAO,MAAM,CAAC,UAAU,CAAC;KAC1B;SAAM,IAAI,MAAM,CAAC,MAAM,CAAC,EAAE;QACzB,wEAAwE;QACxE,OAAO,MAAM,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;KACrD;SAAM;QACL,OAAO,SAAS,CAAC;KAClB;AACH,CAAC;AAED,SAAS,cAAc,CACrB,OAOG;IAEH,IAAI,KAAK,GAAG,CA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AG,YAAY,CAAC;YACrD,IAAI,cAAc,IAAI,QAAQ,IAAI,cAAc,KAAK,QAAQ,EAAE;gBAC7D,MAAM,IAAI,KAAK,CACb,uCAAuC,cAAc,2BAA2B,QAAQ,sBAAsB,CAC/G,CAAC;aACH;YAED,QAAQ,aAAR,QAAQ,cAAR,QAAQ,IAAR,QAAQ,GAAK,cAAc,EAAC;YAC5B,IAAI,QAAQ,EAAE;gBACZ,mBAAmB,CAAC,QAAQ,CAAC,CAAC;aAC/B;iBAAM;gBACL,QAAQ,GAAG,gBAAgB,EAAE,CAAC;aAC/B;YACD,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,GAAG,WAAW,cAAc,QAAQ,EAAE,CAAC,CAAC;YAC5E,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,aAAa,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;YAEjE,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC;YAElC,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { BodyPart, HttpHeaders, PipelineRequest, RequestBodyType } from \"../interfaces\";\nimport { PipelinePolicy } from \"../pipeline\";\nimport { stringToUint8Array } from \"../util/bytesEncoding\";\nimport { toStream, concatenateStreams } from \"../util/stream\";\nimport { isBlob } from \"../util/typeGuards\";\nimport { randomUUID } from \"../util/uuidUtils\";\n\nfunction generateBoundary(): string {\n return `----AzSDKFormBoundary${randomUUID()}`;\n}\n\nfunction encodeHeaders(headers: HttpHeaders): string {\n let result = \"\";\n for (const [key, value] of headers) {\n result += `${key}: ${value}\\r\\n`;\n }\n return result;\n}\n\nfunction getLength(\n source:\n | (() => ReadableStream<Uint8Array>)\n | (() => NodeJS.ReadableStream)\n | Uint8Array\n | Blob\n | ReadableStream\n | NodeJS.ReadableStream\n): number | undefined {\n if (source instanceof Uint8Array) {\n return source.byteLength;\n } else if (isBlob(source)) {\n // if was created using createFile then -1 means we have an unknown size\n return source.size === -1 ? undefined : source.size;\n } else {\n return undefined;\n }\n}\n\nfunction getTotalLength(\n sources: (\n | (() => ReadableStream<Uint8Array>)\n | (() => NodeJS.ReadableStream)\n | Uint8Array\n | Blob\n | ReadableStream\n | NodeJS.ReadableStream\n )[]\n): number | undefined {\n let total = 0;\n for (const source of sources) {\n const partLength = getLength(source);\n if (partLength === undefined) {\n return undefined;\n } else {\n total += partLength;\n }\n }\n return total;\n}\n\nfunction buildRequestBody(request: PipelineRequest, parts: BodyPart[], boundary: string): void {\n const sources = [\n stringToUint8Array(`--${boundary}`, \"utf-8\"),\n ...parts.flatMap((part) => [\n stringToUint8Array(\"\\r\\n\", \"utf-8\"),\n stringToUint8Array(encodeHeaders(part.headers), \"utf-8\"),\n stringToUint8Array(\"\\r\\n\", \"utf-8\"),\n part.body,\n stringToUint8Array(`\\r\\n--${boundary}`, \"utf-8\"),\n ]),\n stringToUint8Array(\"--\\r\\n\\r\\n\", \"utf-8\"),\n ];\n\n const contentLength = getTotalLength(sources);\n if (contentLength) {\n request.headers.set(\"Content-Length\", contentLength);\n }\n\n request.body = (() =>\n concatenateStreams(\n sources.map((source) => (typeof source === \"function\" ? source() : source)).map(toStream)\n )) as RequestBodyType;\n}\n\n/**\n * Name of multipart policy\n */\nexport const multipartPolicyName = \"multipartPolicy\";\n\nconst maxBoundaryLength = 70;\nconst validBoundaryCharacters = new Set(\n `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`\n);\n\nfunction assertValidBoundary(boundary: string): void {\n if (boundary.length > maxBoundaryLength) {\n throw new Error(`Multipart boundary \"${boundary}\" exceeds maximum length of 70 characters`);\n }\n\n if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {\n throw new Error(`Multipart boundary \"${boundary}\" contains invalid characters`);\n }\n}\n\n/**\n * Pipeline policy for multipart requests\n */\nexport function multipartPolicy(): PipelinePolicy {\n return {\n name: multipartPolicyName,\n sendRequest(request, next) {\n if (!request.multipartBody) {\n return next(request);\n }\n\n if (request.body) {\n throw new Error(\"multipartBody and regular body cannot be set at the same time\");\n }\n\n let boundary = request.multipartBody.boundary;\n\n const contentTypeHeader = request.headers.get(\"Content-Type\") ?? \"multipart/mixed\";\n const parsedHeader = contentTypeHeader.match(/^(multipart\\/[^ ;]+)(?:; *boundary=(.+))?$/);\n if (!parsedHeader) {\n throw new Error(\n `Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`\n );\n }\n\n const [, contentType, parsedBoundary] = parsedHeader;\n if (parsedBoundary && boundary && parsedBoundary !== boundary) {\n throw new Error(\n `Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`\n );\n }\n\n boundary ??= parsedBoundary;\n if (boundary) {\n assertValidBoundary(boundary);\n } else {\n boundary = generateBoundary();\n }\n request.headers.set(\"Content-Type\", `${contentType}; boundary=${boundary}`);\n buildRequestBody(request, request.multipartBody.parts, boundary);\n\n request.multipartBody = undefined;\n\n return next(request);\n },\n };\n}\n"]}
@@ -0,0 +1,51 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { toWebStream } from "./stream";
4
+ const unimplementedMethods = {
5
+ arrayBuffer: () => {
6
+ throw new Error("Not implemented");
7
+ },
8
+ slice: () => {
9
+ throw new Error("Not implemented");
10
+ },
11
+ text: () => {
12
+ throw new Error("Not implemented");
13
+ },
14
+ };
15
+ /**
16
+ * Create an object that implements the File interface. This object is intended to be
17
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
18
+ * other situations.
19
+ *
20
+ * Use this function to:
21
+ * - Create a File object for use in RequestBodyType.formData in environments where the
22
+ * global File object is unavailable.
23
+ * - Create a File-like object from a readable stream without reading the stream into memory.
24
+ *
25
+ * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
26
+ * passed in a request's form data map, the stream will not be read into memory
27
+ * and instead will be streamed when the request is made. In the event of a retry, the
28
+ * stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
29
+ * @param name - the name of the file.
30
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
31
+ */
32
+ export function createFileFromStream(stream, name, options = {}) {
33
+ var _a, _b, _c, _d;
34
+ return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => toWebStream(stream()) });
35
+ }
36
+ /**
37
+ * Create an object that implements the File interface. This object is intended to be
38
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
39
+ * other situations.
40
+ *
41
+ * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
42
+ *
43
+ * @param content - the content of the file as a Uint8Array in memory.
44
+ * @param name - the name of the file.
45
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
46
+ */
47
+ export function createFile(content, name, options = {}) {
48
+ var _a, _b, _c;
49
+ return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream() });
50
+ }
51
+ //# sourceMappingURL=file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file.js","sourceRoot":"","sources":["../../../src/util/file.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAoCvC,MAAM,oBAAoB,GAAG;IAC3B,WAAW,EAAE,GAAG,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC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C;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { toWebStream } from \"./stream\";\n\n/**\n * Options passed into createFile specifying metadata about the file.\n */\nexport interface CreateFileOptions {\n /**\n * The MIME type of the file.\n */\n type?: string;\n\n /**\n * Last modified time of the file as a UNIX timestamp.\n * This will default to the current date.\n */\n lastModified?: number;\n\n /**\n * relative path of this file when uploading a directory.\n */\n webkitRelativePath?: string;\n}\n\n/**\n * Extra options for createFile when a stream is being passed in.\n */\nexport interface CreateFileFromStreamOptions extends CreateFileOptions {\n /**\n * Size of the file represented by the stream in bytes.\n *\n * This will be used by the pipeline when calculating the Content-Length header\n * for the overall request.\n */\n size?: number;\n}\n\nconst unimplementedMethods = {\n arrayBuffer: () => {\n throw new Error(\"Not implemented\");\n },\n slice: () => {\n throw new Error(\"Not implemented\");\n },\n text: () => {\n throw new Error(\"Not implemented\");\n },\n};\n\n/**\n * Create an object that implements the File interface. This object is intended to be\n * passed into RequestBodyType.formData, and is not guaranteed to work as expected in\n * other situations.\n *\n * Use this function to:\n * - Create a File object for use in RequestBodyType.formData in environments where the\n * global File object is unavailable.\n * - Create a File-like object from a readable stream without reading the stream into memory.\n *\n * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is\n * passed in a request's form data map, the stream will not be read into memory\n * and instead will be streamed when the request is made. In the event of a retry, the\n * stream needs to be read again, so this callback SHOULD return a fresh stream if possible.\n * @param name - the name of the file.\n * @param options - optional metadata about the file, e.g. file name, file size, MIME type.\n */\nexport function createFileFromStream(\n stream: () => ReadableStream<Uint8Array> | NodeJS.ReadableStream,\n name: string,\n options: CreateFileFromStreamOptions = {}\n): File {\n return {\n ...unimplementedMethods,\n type: options.type ?? \"\",\n lastModified: options.lastModified ?? new Date().getTime(),\n webkitRelativePath: options.webkitRelativePath ?? \"\",\n size: options.size ?? -1,\n name,\n stream: () => toWebStream(stream()),\n };\n}\n\n/**\n * Create an object that implements the File interface. This object is intended to be\n * passed into RequestBodyType.formData, and is not guaranteed to work as expected in\n * other situations.\n *\n * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.\n *\n * @param content - the content of the file as a Uint8Array in memory.\n * @param name - the name of the file.\n * @param options - optional metadata about the file, e.g. file name, file size, MIME type.\n */\nexport function createFile(\n content: Uint8Array,\n name: string,\n options: CreateFileOptions = {}\n): File {\n return {\n ...unimplementedMethods,\n type: options.type ?? \"\",\n lastModified: options.lastModified ?? new Date().getTime(),\n webkitRelativePath: options.webkitRelativePath ?? \"\",\n size: content.byteLength,\n name,\n arrayBuffer: async () => content.buffer,\n stream: () => new Blob([content]).stream(),\n };\n}\n"]}
@@ -0,0 +1,64 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { isBlob, isWebReadableStream } from "./typeGuards";
4
+ export function toStream(source) {
5
+ if (source instanceof Uint8Array) {
6
+ return new Blob([source]).stream();
7
+ }
8
+ else if (isWebReadableStream(source)) {
9
+ return source;
10
+ }
11
+ else if (isBlob(source)) {
12
+ return source.stream();
13
+ }
14
+ else {
15
+ throw new Error("Unsupported type. Only ReadableStream, Uint8Array and Blob are supported in browser");
16
+ }
17
+ }
18
+ export function toWebStream(stream) {
19
+ if (isWebReadableStream(stream)) {
20
+ return stream;
21
+ }
22
+ else {
23
+ throw new Error("Did not expect a Node stream in browser environment");
24
+ }
25
+ }
26
+ export function concatenateStreams(streams) {
27
+ var _a;
28
+ const remainingStreams = Array.from(streams);
29
+ let reader = (_a = remainingStreams.shift()) === null || _a === void 0 ? void 0 : _a.getReader();
30
+ async function doPull(controller) {
31
+ var _a;
32
+ if (!reader) {
33
+ controller.close();
34
+ return;
35
+ }
36
+ let value;
37
+ let done;
38
+ try {
39
+ ({ value, done } = await reader.read());
40
+ }
41
+ catch (e) {
42
+ controller.error(e);
43
+ reader.releaseLock();
44
+ return;
45
+ }
46
+ if (done) {
47
+ reader.releaseLock();
48
+ reader = (_a = remainingStreams.shift()) === null || _a === void 0 ? void 0 : _a.getReader();
49
+ await doPull(controller);
50
+ }
51
+ else {
52
+ controller.enqueue(value);
53
+ }
54
+ }
55
+ return new ReadableStream({
56
+ pull(controller) {
57
+ return doPull(controller);
58
+ },
59
+ cancel(reason) {
60
+ reader === null || reader === void 0 ? void 0 : reader.cancel(reason);
61
+ },
62
+ });
63
+ }
64
+ //# sourceMappingURL=stream.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.browser.js","sourceRoot":"","sources":["../../../src/util/stream.browser.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,MAAM,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAE3D,MAAM,UAAU,QAAQ,CACtB,MAA8E;IAE9E,IAAI,MAAM,YAAY,UAAU,EAAE;QAChC,OAAO,IAAI,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;KACpC;SAAM,IAAI,mBAAmB,CAAC,MAAM,CAAC,EAAE;QACtC,OAAO,MAAM,CAAC;KACf;SAAM,IAAI,MAAM,CAAC,MAAM,CAAC,EAAE;QACzB,OAAO,MAAM,CAAC,MAAM,EAAE,CAAC;KACxB;SAAM;QACL,MAAM,IAAI,KAAK,CACb,qFAAqF,CACtF,CAAC;KACH;AACH,CAAC;AAED,MAAM,UAAU,WAAW,CACzB,MAA0D;IAE1D,IAAI,mBAAmB,CAAC,MAAM,CAAC,EAAE;QAC/B,OAAO,MAAM,CAAC;KACf;SAAM;QACL,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;KACxE;AACH,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,OAAqC;;IAErC,MAAM,gBAAgB,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC7C,IAAI,MAAM,GAAG,MAAA,gBAAgB,CAAC,KAAK,EAAE,0CAAE,SAAS,EAAE,CAAC;IAEnD,KAAK,UAAU,MAAM,CAAC,UAAuD;;QAC3E,IAAI,CAAC,MAAM,EAAE;YACX,UAAU,CAAC,KAAK,EAAE,CAAC;YACnB,OAAO;SACR;QAED,IAAI,KAA6B,CAAC;QAClC,IAAI,IAAyB,CAAC;QAE9B,IAAI;YACF,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;SACzC;QAAC,OAAO,CAAC,EAAE;YACV,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACpB,MAAM,CAAC,WAAW,EAAE,CAAC;YACrB,OAAO;SACR;QAED,IAAI,IAAI,EAAE;YACR,MAAM,CAAC,WAAW,EAAE,CAAC;YACrB,MAAM,GAAG,MAAA,gBAAgB,CAAC,KAAK,EAAE,0CAAE,SAAS,EAAE,CAAC;YAC/C,MAAM,MAAM,CAAC,UAAU,CAAC,CAAC;SAC1B;aAAM;YACL,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;SAC3B;IACH,CAAC;IAED,OAAO,IAAI,cAAc,CAAa;QACpC,IAAI,CAAC,UAAU;YACb,OAAO,MAAM,CAAC,UAAU,CAAC,CAAC;QAC5B,CAAC;QAED,MAAM,CAAC,MAAM;YACX,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QACzB,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { isBlob, isWebReadableStream } from \"./typeGuards\";\n\nexport function toStream(\n source: ReadableStream<Uint8Array> | NodeJS.ReadableStream | Uint8Array | Blob\n): ReadableStream<Uint8Array> | NodeJS.ReadableStream {\n if (source instanceof Uint8Array) {\n return new Blob([source]).stream();\n } else if (isWebReadableStream(source)) {\n return source;\n } else if (isBlob(source)) {\n return source.stream();\n } else {\n throw new Error(\n \"Unsupported type. Only ReadableStream, Uint8Array and Blob are supported in browser\"\n );\n }\n}\n\nexport function toWebStream(\n stream: ReadableStream<Uint8Array> | NodeJS.ReadableStream\n): ReadableStream<Uint8Array> {\n if (isWebReadableStream(stream)) {\n return stream;\n } else {\n throw new Error(\"Did not expect a Node stream in browser environment\");\n }\n}\n\nexport function concatenateStreams(\n streams: ReadableStream<Uint8Array>[]\n): ReadableStream<Uint8Array> {\n const remainingStreams = Array.from(streams);\n let reader = remainingStreams.shift()?.getReader();\n\n async function doPull(controller: ReadableStreamDefaultController<Uint8Array>): Promise<void> {\n if (!reader) {\n controller.close();\n return;\n }\n\n let value: Uint8Array | undefined;\n let done: boolean | undefined;\n\n try {\n ({ value, done } = await reader.read());\n } catch (e) {\n controller.error(e);\n reader.releaseLock();\n return;\n }\n\n if (done) {\n reader.releaseLock();\n reader = remainingStreams.shift()?.getReader();\n await doPull(controller);\n } else {\n controller.enqueue(value);\n }\n }\n\n return new ReadableStream<Uint8Array>({\n pull(controller) {\n return doPull(controller);\n },\n\n cancel(reason) {\n reader?.cancel(reason);\n },\n });\n}\n"]}
@@ -0,0 +1,81 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { __asyncGenerator, __asyncValues, __await } from "tslib";
4
+ import { Readable } from "stream";
5
+ import { isBlob, isNodeReadableStream, isWebReadableStream } from "./typeGuards";
6
+ function streamAsyncIterator() {
7
+ return __asyncGenerator(this, arguments, function* streamAsyncIterator_1() {
8
+ const reader = this.getReader();
9
+ try {
10
+ while (true) {
11
+ const { done, value } = yield __await(reader.read());
12
+ if (done) {
13
+ return yield __await(void 0);
14
+ }
15
+ yield yield __await(value);
16
+ }
17
+ }
18
+ finally {
19
+ reader.releaseLock();
20
+ }
21
+ });
22
+ }
23
+ function makeAsyncIterable(webStream) {
24
+ if (!webStream[Symbol.asyncIterator]) {
25
+ webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
26
+ }
27
+ if (!webStream.values) {
28
+ webStream.values = streamAsyncIterator.bind(webStream);
29
+ }
30
+ }
31
+ function nodeStreamFromWebStream(webStream) {
32
+ makeAsyncIterable(webStream);
33
+ return Readable.fromWeb(webStream);
34
+ }
35
+ export function toWebStream(stream) {
36
+ return isWebReadableStream(stream)
37
+ ? stream
38
+ : Readable.toWeb(Readable.from(stream));
39
+ }
40
+ export function toStream(source) {
41
+ if (source instanceof Uint8Array) {
42
+ return Readable.from(Buffer.from(source));
43
+ }
44
+ else if (isBlob(source)) {
45
+ return nodeStreamFromWebStream(source.stream());
46
+ }
47
+ else if (isNodeReadableStream(source)) {
48
+ return source;
49
+ }
50
+ else {
51
+ return nodeStreamFromWebStream(source);
52
+ }
53
+ }
54
+ export function concatenateStreams(sources) {
55
+ if (sources.some(isWebReadableStream)) {
56
+ throw new Error("Was not expecting a Web stream here");
57
+ }
58
+ return Readable.from((function () {
59
+ return __asyncGenerator(this, arguments, function* () {
60
+ var _a, e_1, _b, _c;
61
+ for (const stream of sources) {
62
+ try {
63
+ for (var _d = true, stream_1 = (e_1 = void 0, __asyncValues(stream)), stream_1_1; stream_1_1 = yield __await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) {
64
+ _c = stream_1_1.value;
65
+ _d = false;
66
+ const chunk = _c;
67
+ yield yield __await(chunk);
68
+ }
69
+ }
70
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
71
+ finally {
72
+ try {
73
+ if (!_d && !_a && (_b = stream_1.return)) yield __await(_b.call(stream_1));
74
+ }
75
+ finally { if (e_1) throw e_1.error; }
76
+ }
77
+ }
78
+ });
79
+ })());
80
+ }
81
+ //# sourceMappingURL=stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.js","sourceRoot":"","sources":["../../../src/util/stream.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAElC,OAAO,EAAE,MAAM,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAEjF,SAAgB,mBAAmB;;Q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C,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;KACjD;SAAM,IAAI,oBAAoB,CAAC,MAAM,CAAC,EAAE;QACvC,OAAO,MAAM,CAAC;KACf;SAAM;QACL,OAAO,uBAAuB,CAAC,MAAM,CAAC,CAAC;KACxC;AACH,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,OAA+D;IAE/D,IAAI,OAAO,CAAC,IAAI,CAAC,mBAAmB,CAAC,EAAE;QACrC,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;KACxD;IAED,OAAO,QAAQ,CAAC,IAAI,CAClB,CAAC;;;YACC,KAAK,MAAM,MAAM,IAAI,OAAkC,EAAE;;oBACvD,KAA0B,eAAA,0BAAA,cAAA,MAAM,CAAA,CAAA,YAAA,qFAAE;wBAAR,sBAAM;wBAAN,WAAM;wBAArB,MAAM,KAAK,KAAA,CAAA;wBACpB,oBAAM,KAAK,CAAA,CAAC;qBACb;;;;;;;;;aACF;QACH,CAAC;KAAA,CAAC,EAAE,CACL,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Readable } from \"stream\";\nimport { ReadableStream as AsyncIterableReadableStream } from \"stream/web\";\nimport { isBlob, isNodeReadableStream, isWebReadableStream } from \"./typeGuards\";\n\nasync function* streamAsyncIterator(\n this: ReadableStream<Uint8Array>\n): AsyncIterableIterator<Uint8Array> {\n const reader = this.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nfunction makeAsyncIterable<T>(webStream: any): asserts webStream is AsyncIterableReadableStream<T> {\n if (!webStream[Symbol.asyncIterator]) {\n webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);\n }\n\n if (!webStream.values) {\n webStream.values = streamAsyncIterator.bind(webStream);\n }\n}\n\nfunction nodeStreamFromWebStream(webStream: ReadableStream<Uint8Array>): NodeJS.ReadableStream {\n makeAsyncIterable<Uint8Array>(webStream);\n return Readable.fromWeb(webStream);\n}\n\nexport function toWebStream(\n stream: ReadableStream<Uint8Array> | NodeJS.ReadableStream\n): ReadableStream<Uint8Array> {\n return isWebReadableStream(stream)\n ? stream\n : (Readable.toWeb(Readable.from(stream)) as ReadableStream<Uint8Array>);\n}\n\nexport function toStream(\n source: ReadableStream<Uint8Array> | NodeJS.ReadableStream | Uint8Array | Blob\n): NodeJS.ReadableStream | ReadableStream<Uint8Array> {\n if (source instanceof Uint8Array) {\n return Readable.from(Buffer.from(source));\n } else if (isBlob(source)) {\n return nodeStreamFromWebStream(source.stream());\n } else if (isNodeReadableStream(source)) {\n return source;\n } else {\n return nodeStreamFromWebStream(source);\n }\n}\n\nexport function concatenateStreams(\n sources: (ReadableStream<Uint8Array> | NodeJS.ReadableStream)[]\n): ReadableStream<Uint8Array> | NodeJS.ReadableStream {\n if (sources.some(isWebReadableStream)) {\n throw new Error(\"Was not expecting a Web stream here\");\n }\n\n return Readable.from(\n (async function* () {\n for (const stream of sources as NodeJS.ReadableStream[]) {\n for await (const chunk of stream) {\n yield chunk;\n }\n }\n })()\n );\n}\n"]}
@@ -31,4 +31,18 @@ export function isObjectWithProperties(thing, properties) {
31
31
  export function objectHasProperty(thing, property) {
32
32
  return (isDefined(thing) && typeof thing === "object" && property in thing);
33
33
  }
34
+ export function isNodeReadableStream(x) {
35
+ return Boolean(x && typeof x["pipe"] === "function");
36
+ }
37
+ export function isWebReadableStream(x) {
38
+ return Boolean(x &&
39
+ typeof x.getReader === "function" &&
40
+ typeof x.tee === "function");
41
+ }
42
+ export function isReadableStream(x) {
43
+ return isNodeReadableStream(x) || isWebReadableStream(x);
44
+ }
45
+ export function isBlob(x) {
46
+ return typeof x.stream === "function";
47
+ }
34
48
  //# sourceMappingURL=typeGuards.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"typeGuards.js","sourceRoot":"","sources":["../../../src/util/typeGuards.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAI,KAA2B;IACtD,OAAO,OAAO,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,IAAI,CAAC;AACxD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CACpC,KAAY,EACZ,UAA0B;IAE1B,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAClD,OAAO,KAAK,CAAC;KACd;IAED,KAAK,MAAM,QAAQ,IAAI,UAAU,EAAE;QACjC,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE;YACvC,OAAO,KAAK,CAAC;SACd;KACF;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAC/B,KAAY,EACZ,QAAsB;IAEtB,OAAO,CACL,SAAS,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAK,KAAiC,CAChG,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Helper TypeGuard that checks if something is defined or not.\n * @param thing - Anything\n */\nexport function isDefined<T>(thing: T | undefined | null): thing is T {\n return typeof thing !== \"undefined\" && thing !== null;\n}\n\n/**\n * Helper TypeGuard that checks if the input is an object with the specified properties.\n * @param thing - Anything.\n * @param properties - The name of the properties that should appear in the object.\n */\nexport function isObjectWithProperties<Thing, PropertyName extends string>(\n thing: Thing,\n properties: PropertyName[]\n): thing is Thing & Record<PropertyName, unknown> {\n if (!isDefined(thing) || typeof thing !== \"object\") {\n return false;\n }\n\n for (const property of properties) {\n if (!objectHasProperty(thing, property)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Helper TypeGuard that checks if the input is an object with the specified property.\n * @param thing - Any object.\n * @param property - The name of the property that should appear in the object.\n */\nexport function objectHasProperty<Thing, PropertyName extends string>(\n thing: Thing,\n property: PropertyName\n): thing is Thing & Record<PropertyName, unknown> {\n return (\n isDefined(thing) && typeof thing === \"object\" && property in (thing as Record<string, unknown>)\n );\n}\n"]}
1
+ {"version":3,"file":"typeGuards.js","sourceRoot":"","sources":["../../../src/util/typeGuards.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAI,KAA2B;IACtD,OAAO,OAAO,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,IAAI,CAAC;AACxD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CACpC,KAAY,EACZ,UAA0B;IAE1B,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAClD,OAAO,KAAK,CAAC;KACd;IAED,KAAK,MAAM,QAAQ,IAAI,UAAU,EAAE;QACjC,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE;YACvC,OAAO,KAAK,CAAC;SACd;KACF;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAC/B,KAAY,EACZ,QAAsB;IAEtB,OAAO,CACL,SAAS,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAK,KAAiC,CAChG,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,CAAU;IAC7C,OAAO,OAAO,CAAC,CAAC,IAAI,OAAQ,CAA2B,CAAC,MAAM,CAAC,KAAK,UAAU,CAAC,CAAC;AAClF,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,CAAU;IAC5C,OAAO,OAAO,CACZ,CAAC;QACC,OAAQ,CAAoB,CAAC,SAAS,KAAK,UAAU;QACrD,OAAQ,CAAoB,CAAC,GAAG,KAAK,UAAU,CAClD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,CAAU;IACzC,OAAO,oBAAoB,CAAC,CAAC,CAAC,IAAI,mBAAmB,CAAC,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,CAAU;IAC/B,OAAO,OAAQ,CAAU,CAAC,MAAM,KAAK,UAAU,CAAC;AAClD,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Helper TypeGuard that checks if something is defined or not.\n * @param thing - Anything\n */\nexport function isDefined<T>(thing: T | undefined | null): thing is T {\n return typeof thing !== \"undefined\" && thing !== null;\n}\n\n/**\n * Helper TypeGuard that checks if the input is an object with the specified properties.\n * @param thing - Anything.\n * @param properties - The name of the properties that should appear in the object.\n */\nexport function isObjectWithProperties<Thing, PropertyName extends string>(\n thing: Thing,\n properties: PropertyName[]\n): thing is Thing & Record<PropertyName, unknown> {\n if (!isDefined(thing) || typeof thing !== \"object\") {\n return false;\n }\n\n for (const property of properties) {\n if (!objectHasProperty(thing, property)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Helper TypeGuard that checks if the input is an object with the specified property.\n * @param thing - Any object.\n * @param property - The name of the property that should appear in the object.\n */\nexport function objectHasProperty<Thing, PropertyName extends string>(\n thing: Thing,\n property: PropertyName\n): thing is Thing & Record<PropertyName, unknown> {\n return (\n isDefined(thing) && typeof thing === \"object\" && property in (thing as Record<string, unknown>)\n );\n}\n\nexport function isNodeReadableStream(x: unknown): x is NodeJS.ReadableStream {\n return Boolean(x && typeof (x as NodeJS.ReadableStream)[\"pipe\"] === \"function\");\n}\n\nexport function isWebReadableStream(x: unknown): x is ReadableStream {\n return Boolean(\n x &&\n typeof (x as ReadableStream).getReader === \"function\" &&\n typeof (x as ReadableStream).tee === \"function\"\n );\n}\n\nexport function isReadableStream(x: unknown): x is ReadableStream | NodeJS.ReadableStream {\n return isNodeReadableStream(x) || isWebReadableStream(x);\n}\n\nexport function isBlob(x: unknown): x is Blob {\n return typeof (x as Blob).stream === \"function\";\n}\n"]}
@@ -3,17 +3,7 @@
3
3
  import { AbortError } from "./abort-controller/AbortError";
4
4
  import { createHttpHeaders } from "./httpHeaders";
5
5
  import { RestError } from "./restError";
6
- function isNodeReadableStream(body) {
7
- return body && typeof body.pipe === "function";
8
- }
9
- /**
10
- * Checks if the body is a ReadableStream supported by browsers
11
- */
12
- function isReadableStream(body) {
13
- return Boolean(body &&
14
- typeof body.getReader === "function" &&
15
- typeof body.tee === "function");
16
- }
6
+ import { isReadableStream } from "./util/typeGuards";
17
7
  /**
18
8
  * A HttpClient implementation that uses XMLHttpRequest to send HTTP requests.
19
9
  * @internal
@@ -59,7 +49,7 @@ class XhrHttpClient {
59
49
  }
60
50
  xhr.responseType = ((_a = request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.size) ? "blob" : "text";
61
51
  const body = typeof request.body === "function" ? request.body() : request.body;
62
- if (isNodeReadableStream(body) || isReadableStream(body)) {
52
+ if (isReadableStream(body)) {
63
53
  throw new Error("streams are not supported in XhrHttpClient.");
64
54
  }
65
55
  xhr.send(body === undefined ? null : body);
@@ -1 +1 @@
1
- {"version":3,"file":"xhrHttpClient.js","sourceRoot":"","sources":["../../src/xhrHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAQ3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,SAAS,oBAAoB,CAAC,IAAS;IACrC,OAAO,IAAI,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,UAAU,CAAC;AACjD,CAAC;AAED;;GAEG;AACH,SAAS,gBAAgB,CAAC,IAAa;IACrC,OAAO,OAAO,CACZ,IAAI;QACF,OAAQ,IAAuB,CAAC,SAAS,KAAK,UAAU;QACxD,OAAQ,IAAuB,CAAC,GAAG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,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;QACxC,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAC1C,eAAe,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;KAC9C;IACD,OAAO,eAAe,CAAC;AACzB,CAAC;AAED,SAAS,qBAAqB,CAC5B,OAAwB,EACxB,GAAmB,EACnB,MAA0B;IAE1B,GAAG,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CACjC,MAAM,CACJ,IAAI,SAAS,CAAC,6BAA6B,OAAO,CAAC,GAAG,EAAE,EAAE;QACxD,IAAI,EAAE,SAAS,CAAC,kBAAkB;QAClC,OAAO;KACR,CAAC,CACH,CACF,CAAC;IACF,MAAM,UAAU,GAAG,IAAI,UAAU,CAAC,4BAA4B,CAAC,CAAC;IAChE,GAAG,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;IACxD,GAAG,CAAC,gBAAgB,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO,IAAI,aAAa,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError } from \"./abort-controller/AbortError\";\nimport {\n HttpClient,\n HttpHeaders,\n PipelineRequest,\n PipelineResponse,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { createHttpHeaders } from \"./httpHeaders\";\nimport { RestError } from \"./restError\";\n\nfunction isNodeReadableStream(body: any): body is NodeJS.ReadableStream {\n return body && typeof body.pipe === \"function\";\n}\n\n/**\n * Checks if the body is a ReadableStream supported by browsers\n */\nfunction isReadableStream(body: unknown): body is ReadableStream {\n return Boolean(\n body &&\n typeof (body as ReadableStream).getReader === \"function\" &&\n typeof (body as ReadableStream).tee === \"function\"\n );\n}\n\n/**\n * A HttpClient implementation that uses XMLHttpRequest to send HTTP requests.\n * @internal\n */\nclass XhrHttpClient implements HttpClient {\n /**\n * Makes a request over an underlying transport layer and returns the response.\n * @param request - The request to be made.\n */\n public async sendRequest(request: PipelineRequest): Promise<PipelineResponse> {\n const url = new URL(request.url);\n const isInsecure = url.protocol !== \"https:\";\n\n if (isInsecure && !request.allowInsecureConnection) {\n throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);\n }\n\n const xhr = new XMLHttpRequest();\n\n if (request.proxySettings) {\n throw new Error(\"HTTP proxy is not supported in browser environment\");\n }\n\n const abortSignal = request.abortSignal;\n if (abortSignal) {\n if (abortSignal.aborted) {\n throw new AbortError(\"The operation was aborted.\");\n }\n\n const listener = (): void => {\n xhr.abort();\n };\n abortSignal.addEventListener(\"abort\", listener);\n xhr.addEventListener(\"readystatechange\", () => {\n if (xhr.readyState === XMLHttpRequest.DONE) {\n abortSignal.removeEventListener(\"abort\", listener);\n }\n });\n }\n\n addProgressListener(xhr.upload, request.onUploadProgress);\n addProgressListener(xhr, request.onDownloadProgress);\n\n xhr.open(request.method, request.url);\n xhr.timeout = request.timeout;\n xhr.withCredentials = request.withCredentials;\n for (const [name, value] of request.headers) {\n xhr.setRequestHeader(name, value);\n }\n\n xhr.responseType = request.streamResponseStatusCodes?.size ? \"blob\" : \"text\";\n\n const body = typeof request.body === \"function\" ? request.body() : request.body;\n if (isNodeReadableStream(body) || isReadableStream(body)) {\n throw new Error(\"streams are not supported in XhrHttpClient.\");\n }\n\n xhr.send(body === undefined ? null : body);\n\n if (xhr.responseType === \"blob\") {\n return new Promise((resolve, reject) => {\n handleBlobResponse(xhr, request, resolve, reject);\n rejectOnTerminalEvent(request, xhr, reject);\n });\n } else {\n return new Promise(function (resolve, reject) {\n xhr.addEventListener(\"load\", () =>\n resolve({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n bodyAsText: xhr.responseText,\n })\n );\n rejectOnTerminalEvent(request, xhr, reject);\n });\n }\n }\n}\n\nfunction handleBlobResponse(\n xhr: XMLHttpRequest,\n request: PipelineRequest,\n res: (value: PipelineResponse | PromiseLike<PipelineResponse>) => void,\n rej: (reason?: any) => void\n): void {\n xhr.addEventListener(\"readystatechange\", () => {\n // Resolve as soon as headers are loaded\n if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {\n if (\n // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code\n request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||\n request.streamResponseStatusCodes?.has(xhr.status)\n ) {\n const blobBody = new Promise<Blob>((resolve, reject) => {\n xhr.addEventListener(\"load\", () => {\n resolve(xhr.response);\n });\n rejectOnTerminalEvent(request, xhr, reject);\n });\n res({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n blobBody,\n });\n } else {\n xhr.addEventListener(\"load\", () => {\n // xhr.response is of Blob type if the request is sent with xhr.responseType === \"blob\"\n // but the status code is not one of the stream response status codes,\n // so treat it as text and convert from Blob to text\n if (xhr.response) {\n xhr.response\n .text()\n .then((text: string) => {\n res({\n request: request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n bodyAsText: text,\n });\n return;\n })\n .catch((e: any) => {\n rej(e);\n });\n } else {\n res({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n });\n }\n });\n }\n }\n });\n}\n\nfunction addProgressListener(\n xhr: XMLHttpRequestEventTarget,\n listener?: (progress: TransferProgressEvent) => void\n): void {\n if (listener) {\n xhr.addEventListener(\"progress\", (rawEvent) =>\n listener({\n loadedBytes: rawEvent.loaded,\n })\n );\n }\n}\n\nfunction parseHeaders(xhr: XMLHttpRequest): HttpHeaders {\n const responseHeaders = createHttpHeaders();\n const headerLines = xhr\n .getAllResponseHeaders()\n .trim()\n .split(/[\\r\\n]+/);\n for (const line of headerLines) {\n const index = line.indexOf(\":\");\n const headerName = line.slice(0, index);\n const headerValue = line.slice(index + 2);\n responseHeaders.set(headerName, headerValue);\n }\n return responseHeaders;\n}\n\nfunction rejectOnTerminalEvent(\n request: PipelineRequest,\n xhr: XMLHttpRequest,\n reject: (err: any) => void\n): void {\n xhr.addEventListener(\"error\", () =>\n reject(\n new RestError(`Failed to send request to ${request.url}`, {\n code: RestError.REQUEST_SEND_ERROR,\n request,\n })\n )\n );\n const abortError = new AbortError(\"The operation was aborted.\");\n xhr.addEventListener(\"abort\", () => reject(abortError));\n xhr.addEventListener(\"timeout\", () => reject(abortError));\n}\n\n/**\n * Create a new HttpClient instance for the browser environment.\n * @internal\n */\nexport function createXhrHttpClient(): HttpClient {\n return new XhrHttpClient();\n}\n"]}
1
+ {"version":3,"file":"xhrHttpClient.js","sourceRoot":"","sources":["../../src/xhrHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAQ3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD;;;GAGG;AACH,MAAM,aAAa;IACjB;;;OAGG;IACI,KAAK,CAAC,WAAW,CAAC,OAAwB;;QAC/C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QACjC,MAAM,UAAU,GAAG,GAAG,CAAC,QAAQ,KAAK,QAAQ,CAAC;QAE7C,IAAI,UAAU,IAAI,CAAC,OAAO,CAAC,uBAAuB,EAAE;YAClD,MAAM,IAAI,KAAK,CAAC,qBAAqB,OAAO,CAAC,GAAG,0CAA0C,CAAC,CAAC;SAC7F;QAED,MAAM,GAAG,GAAG,IAAI,cAAc,EAAE,CAAC;QAEjC,IAAI,OAAO,CAAC,aAAa,EAAE;YACzB,MAA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,UAAU,GAAG,IAAI,UAAU,CAAC,4BAA4B,CAAC,CAAC;IAChE,GAAG,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;IACxD,GAAG,CAAC,gBAAgB,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO,IAAI,aAAa,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError } from \"./abort-controller/AbortError\";\nimport {\n HttpClient,\n HttpHeaders,\n PipelineRequest,\n PipelineResponse,\n TransferProgressEvent,\n} from \"./interfaces\";\nimport { createHttpHeaders } from \"./httpHeaders\";\nimport { RestError } from \"./restError\";\nimport { isReadableStream } from \"./util/typeGuards\";\n\n/**\n * A HttpClient implementation that uses XMLHttpRequest to send HTTP requests.\n * @internal\n */\nclass XhrHttpClient implements HttpClient {\n /**\n * Makes a request over an underlying transport layer and returns the response.\n * @param request - The request to be made.\n */\n public async sendRequest(request: PipelineRequest): Promise<PipelineResponse> {\n const url = new URL(request.url);\n const isInsecure = url.protocol !== \"https:\";\n\n if (isInsecure && !request.allowInsecureConnection) {\n throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);\n }\n\n const xhr = new XMLHttpRequest();\n\n if (request.proxySettings) {\n throw new Error(\"HTTP proxy is not supported in browser environment\");\n }\n\n const abortSignal = request.abortSignal;\n if (abortSignal) {\n if (abortSignal.aborted) {\n throw new AbortError(\"The operation was aborted.\");\n }\n\n const listener = (): void => {\n xhr.abort();\n };\n abortSignal.addEventListener(\"abort\", listener);\n xhr.addEventListener(\"readystatechange\", () => {\n if (xhr.readyState === XMLHttpRequest.DONE) {\n abortSignal.removeEventListener(\"abort\", listener);\n }\n });\n }\n\n addProgressListener(xhr.upload, request.onUploadProgress);\n addProgressListener(xhr, request.onDownloadProgress);\n\n xhr.open(request.method, request.url);\n xhr.timeout = request.timeout;\n xhr.withCredentials = request.withCredentials;\n for (const [name, value] of request.headers) {\n xhr.setRequestHeader(name, value);\n }\n\n xhr.responseType = request.streamResponseStatusCodes?.size ? \"blob\" : \"text\";\n\n const body = typeof request.body === \"function\" ? request.body() : request.body;\n if (isReadableStream(body)) {\n throw new Error(\"streams are not supported in XhrHttpClient.\");\n }\n\n xhr.send(body === undefined ? null : body);\n\n if (xhr.responseType === \"blob\") {\n return new Promise((resolve, reject) => {\n handleBlobResponse(xhr, request, resolve, reject);\n rejectOnTerminalEvent(request, xhr, reject);\n });\n } else {\n return new Promise(function (resolve, reject) {\n xhr.addEventListener(\"load\", () =>\n resolve({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n bodyAsText: xhr.responseText,\n })\n );\n rejectOnTerminalEvent(request, xhr, reject);\n });\n }\n }\n}\n\nfunction handleBlobResponse(\n xhr: XMLHttpRequest,\n request: PipelineRequest,\n res: (value: PipelineResponse | PromiseLike<PipelineResponse>) => void,\n rej: (reason?: any) => void\n): void {\n xhr.addEventListener(\"readystatechange\", () => {\n // Resolve as soon as headers are loaded\n if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {\n if (\n // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code\n request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) ||\n request.streamResponseStatusCodes?.has(xhr.status)\n ) {\n const blobBody = new Promise<Blob>((resolve, reject) => {\n xhr.addEventListener(\"load\", () => {\n resolve(xhr.response);\n });\n rejectOnTerminalEvent(request, xhr, reject);\n });\n res({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n blobBody,\n });\n } else {\n xhr.addEventListener(\"load\", () => {\n // xhr.response is of Blob type if the request is sent with xhr.responseType === \"blob\"\n // but the status code is not one of the stream response status codes,\n // so treat it as text and convert from Blob to text\n if (xhr.response) {\n xhr.response\n .text()\n .then((text: string) => {\n res({\n request: request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n bodyAsText: text,\n });\n return;\n })\n .catch((e: any) => {\n rej(e);\n });\n } else {\n res({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n });\n }\n });\n }\n }\n });\n}\n\nfunction addProgressListener(\n xhr: XMLHttpRequestEventTarget,\n listener?: (progress: TransferProgressEvent) => void\n): void {\n if (listener) {\n xhr.addEventListener(\"progress\", (rawEvent) =>\n listener({\n loadedBytes: rawEvent.loaded,\n })\n );\n }\n}\n\nfunction parseHeaders(xhr: XMLHttpRequest): HttpHeaders {\n const responseHeaders = createHttpHeaders();\n const headerLines = xhr\n .getAllResponseHeaders()\n .trim()\n .split(/[\\r\\n]+/);\n for (const line of headerLines) {\n const index = line.indexOf(\":\");\n const headerName = line.slice(0, index);\n const headerValue = line.slice(index + 2);\n responseHeaders.set(headerName, headerValue);\n }\n return responseHeaders;\n}\n\nfunction rejectOnTerminalEvent(\n request: PipelineRequest,\n xhr: XMLHttpRequest,\n reject: (err: any) => void\n): void {\n xhr.addEventListener(\"error\", () =>\n reject(\n new RestError(`Failed to send request to ${request.url}`, {\n code: RestError.REQUEST_SEND_ERROR,\n request,\n })\n )\n );\n const abortError = new AbortError(\"The operation was aborted.\");\n xhr.addEventListener(\"abort\", () => reject(abortError));\n xhr.addEventListener(\"timeout\", () => reject(abortError));\n}\n\n/**\n * Create a new HttpClient instance for the browser environment.\n * @internal\n */\nexport function createXhrHttpClient(): HttpClient {\n return new XhrHttpClient();\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typespec/ts-http-runtime",
3
- "version": "1.0.0-alpha.20231107.1",
3
+ "version": "1.0.0-alpha.20231115.1",
4
4
  "description": "Isomorphic client library for making HTTP requests in node.js and browser.",
5
5
  "sdk-type": "client",
6
6
  "main": "dist/index.js",
@@ -8,15 +8,14 @@
8
8
  "browser": {
9
9
  "./dist-esm/src/defaultHttpClient.js": "./dist-esm/src/defaultHttpClient.browser.js",
10
10
  "./dist-esm/src/policies/decompressResponsePolicy.js": "./dist-esm/src/policies/decompressResponsePolicy.browser.js",
11
- "./dist-esm/src/policies/formDataPolicy.js": "./dist-esm/src/policies/formDataPolicy.browser.js",
12
11
  "./dist-esm/src/policies/proxyPolicy.js": "./dist-esm/src/policies/proxyPolicy.browser.js",
13
12
  "./dist-esm/src/util/inspect.js": "./dist-esm/src/util/inspect.browser.js",
14
13
  "./dist-esm/src/util/userAgentPlatform.js": "./dist-esm/src/util/userAgentPlatform.browser.js",
15
14
  "./dist-esm/src/util/sha256.js": "./dist-esm/src/util/sha256.browser.js",
16
15
  "./dist-esm/src/util/uuidUtils.js": "./dist-esm/src/util/uuidUtils.browser.js",
16
+ "./dist-esm/src/util/stream.js": "./dist-esm/src/util/stream.browser.js",
17
17
  "./dist-esm/src/util/bytesEncoding.js": "./dist-esm/src/util/bytesEncoding.browser.js",
18
18
  "./dist-esm/src/logger/log.js": "./dist-esm/src/logger/log.browser.js",
19
- "./dist-esm/src/client/helpers/isReadableStream.js": "./dist-esm/src/client/helpers/isReadableStream.browser.js",
20
19
  "process": false
21
20
  },
22
21
  "react-native": {