Initial commit

This commit is contained in:
schihei committed 2025-03-07 19:22:02 +01:00
commit 4a98255d83
55743 files changed
+5280367

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
import type { AccessToken } from "@azure/core-auth";
/**
* Defines the default token refresh buffer duration.
*/
export declare const DefaultTokenRefreshBufferMs: number;
/**
* Provides a cache for an AccessToken that was that
* was returned from a TokenCredential.
*/
export interface AccessTokenCache {
/**
* Sets the cached token.
*
* @param accessToken - The AccessToken to be cached or null to
* clear the cached token.
*/
setCachedToken(accessToken: AccessToken | undefined): void;
/**
* Returns the cached AccessToken or undefined if nothing is cached.
*/
getCachedToken(): AccessToken | undefined;
}
/**
* Provides an AccessTokenCache implementation which clears
* the cached AccessToken's after the expiresOnTimestamp has
* passed.
* @internal
*/
export declare class ExpiringAccessTokenCache implements AccessTokenCache {
private tokenRefreshBufferMs;
private cachedToken?;
/**
* Constructs an instance of ExpiringAccessTokenCache with
* an optional expiration buffer time.
*/
constructor(tokenRefreshBufferMs?: number);
setCachedToken(accessToken: AccessToken | undefined): void;
getCachedToken(): AccessToken | undefined;
}
//# sourceMappingURL=accessTokenCache.d.ts.map
+32
View File
@@ -0,0 +1,32 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* Defines the default token refresh buffer duration.
*/
export const DefaultTokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes
/**
* Provides an AccessTokenCache implementation which clears
* the cached AccessToken's after the expiresOnTimestamp has
* passed.
* @internal
*/
export class ExpiringAccessTokenCache {
/**
* Constructs an instance of ExpiringAccessTokenCache with
* an optional expiration buffer time.
*/
constructor(tokenRefreshBufferMs = DefaultTokenRefreshBufferMs) {
this.tokenRefreshBufferMs = tokenRefreshBufferMs;
}
setCachedToken(accessToken) {
this.cachedToken = accessToken;
}
getCachedToken() {
if (this.cachedToken &&
Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) {
this.cachedToken = undefined;
}
return this.cachedToken;
}
}
//# sourceMappingURL=accessTokenCache.js.map
@@ -0,0 +1 @@
{"version":3,"file":"accessTokenCache.js","sourceRoot":"","sources":["../../src/accessTokenCache.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC;;GAEG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,YAAY;AAqBtE;;;;;GAKG;AACH,MAAM,OAAO,wBAAwB;IAInC;;;OAGG;IACH,YAAY,uBAA+B,2BAA2B;QACpE,IAAI,CAAC,oBAAoB,GAAG,oBAAoB,CAAC;IACnD,CAAC;IAED,cAAc,CAAC,WAAoC;QACjD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAED,cAAc;QACZ,IACE,IAAI,CAAC,WAAW;YAChB,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,oBAAoB,IAAI,IAAI,CAAC,WAAW,CAAC,kBAAkB,EAC7E,CAAC;YACD,IAAI,CAAC,WAAW,GAAG,SAAS,CAAC;QAC/B,CAAC;QAED,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AccessToken } from \"@azure/core-auth\";\n\n/**\n * Defines the default token refresh buffer duration.\n */\nexport const DefaultTokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes\n\n/**\n * Provides a cache for an AccessToken that was that\n * was returned from a TokenCredential.\n */\nexport interface AccessTokenCache {\n /**\n * Sets the cached token.\n *\n * @param accessToken - The AccessToken to be cached or null to\n * clear the cached token.\n */\n setCachedToken(accessToken: AccessToken | undefined): void;\n\n /**\n * Returns the cached AccessToken or undefined if nothing is cached.\n */\n getCachedToken(): AccessToken | undefined;\n}\n\n/**\n * Provides an AccessTokenCache implementation which clears\n * the cached AccessToken's after the expiresOnTimestamp has\n * passed.\n * @internal\n */\nexport class ExpiringAccessTokenCache implements AccessTokenCache {\n private tokenRefreshBufferMs: number;\n private cachedToken?: AccessToken;\n\n /**\n * Constructs an instance of ExpiringAccessTokenCache with\n * an optional expiration buffer time.\n */\n constructor(tokenRefreshBufferMs: number = DefaultTokenRefreshBufferMs) {\n this.tokenRefreshBufferMs = tokenRefreshBufferMs;\n }\n\n setCachedToken(accessToken: AccessToken | undefined): void {\n this.cachedToken = accessToken;\n }\n\n getCachedToken(): AccessToken | undefined {\n if (\n this.cachedToken &&\n Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp\n ) {\n this.cachedToken = undefined;\n }\n\n return this.cachedToken;\n }\n}\n"]}
+3
View File
@@ -0,0 +1,3 @@
export declare const SDK_VERSION: string;
export declare const DEFAULT_RETRY_POLICY_COUNT = 3;
//# sourceMappingURL=constants.d.ts.map
+5
View File
@@ -0,0 +1,5 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export const SDK_VERSION = "1.19.1";
export const DEFAULT_RETRY_POLICY_COUNT = 3;
//# sourceMappingURL=constants.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,MAAM,CAAC,MAAM,WAAW,GAAW,QAAQ,CAAC;AAE5C,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport const SDK_VERSION: string = \"1.19.1\";\n\nexport const DEFAULT_RETRY_POLICY_COUNT = 3;\n"]}
@@ -0,0 +1,60 @@
import { type LogPolicyOptions } from "./policies/logPolicy.js";
import { type Pipeline } from "./pipeline.js";
import type { Agent, PipelineRetryOptions, ProxySettings, TlsSettings } from "./interfaces.js";
import { type RedirectPolicyOptions } from "./policies/redirectPolicy.js";
import { type UserAgentPolicyOptions } from "./policies/userAgentPolicy.js";
/**
* Defines options that are used to configure the HTTP pipeline for
* an SDK client.
*/
export interface PipelineOptions {
/**
* Options that control how to retry failed requests.
*/
retryOptions?: PipelineRetryOptions;
/**
* Options to configure a proxy for outgoing requests.
*/
proxyOptions?: ProxySettings;
/** Options for configuring Agent instance for outgoing requests */
agent?: Agent;
/** Options for configuring TLS authentication */
tlsOptions?: TlsSettings;
/**
* Options for how redirect responses are handled.
*/
redirectOptions?: RedirectPolicyOptions;
/**
* Options for adding user agent details to outgoing requests.
*/
userAgentOptions?: UserAgentPolicyOptions;
/**
* Options for setting common telemetry and tracing info to outgoing requests.
*/
telemetryOptions?: TelemetryOptions;
}
/**
* Defines options that are used to configure common telemetry and tracing info
*/
export interface TelemetryOptions {
/**
* The name of the header to pass the request ID to.
*/
clientRequestIdHeaderName?: string;
}
/**
* Defines options that are used to configure internal options of
* the HTTP pipeline for an SDK client.
*/
export interface InternalPipelineOptions extends PipelineOptions {
/**
* Options to configure request/response logging.
*/
loggingOptions?: LogPolicyOptions;
}
/**
* Create a new pipeline with a default set of customizable policies.
* @param options - Options to configure a custom pipeline.
*/
export declare function createPipelineFromOptions(options: InternalPipelineOptions): Pipeline;
//# sourceMappingURL=createPipelineFromOptions.d.ts.map
@@ -0,0 +1,53 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { logPolicy } from "./policies/logPolicy.js";
import { createEmptyPipeline } from "./pipeline.js";
import { redirectPolicy } from "./policies/redirectPolicy.js";
import { userAgentPolicy } from "./policies/userAgentPolicy.js";
import { multipartPolicy, multipartPolicyName } from "./policies/multipartPolicy.js";
import { decompressResponsePolicy } from "./policies/decompressResponsePolicy.js";
import { defaultRetryPolicy } from "./policies/defaultRetryPolicy.js";
import { formDataPolicy } from "./policies/formDataPolicy.js";
import { isNodeLike } from "@azure/core-util";
import { proxyPolicy } from "./policies/proxyPolicy.js";
import { setClientRequestIdPolicy } from "./policies/setClientRequestIdPolicy.js";
import { agentPolicy } from "./policies/agentPolicy.js";
import { tlsPolicy } from "./policies/tlsPolicy.js";
import { tracingPolicy } from "./policies/tracingPolicy.js";
/**
* Create a new pipeline with a default set of customizable policies.
* @param options - Options to configure a custom pipeline.
*/
export function createPipelineFromOptions(options) {
var _a;
const pipeline = createEmptyPipeline();
if (isNodeLike) {
if (options.agent) {
pipeline.addPolicy(agentPolicy(options.agent));
}
if (options.tlsOptions) {
pipeline.addPolicy(tlsPolicy(options.tlsOptions));
}
pipeline.addPolicy(proxyPolicy(options.proxyOptions));
pipeline.addPolicy(decompressResponsePolicy());
}
pipeline.addPolicy(formDataPolicy(), { beforePolicies: [multipartPolicyName] });
pipeline.addPolicy(userAgentPolicy(options.userAgentOptions));
pipeline.addPolicy(setClientRequestIdPolicy((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName));
// The multipart policy is added after policies with no phase, so that
// policies can be added between it and formDataPolicy to modify
// properties (e.g., making the boundary constant in recorded tests).
pipeline.addPolicy(multipartPolicy(), { afterPhase: "Deserialize" });
pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: "Retry" });
pipeline.addPolicy(tracingPolicy(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), {
afterPhase: "Retry",
});
if (isNodeLike) {
// Both XHR and Fetch expect to handle redirects automatically,
// so only include this policy when we're in Node.
pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: "Retry" });
}
pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: "Sign" });
return pipeline;
}
//# sourceMappingURL=createPipelineFromOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"createPipelineFromOptions.js","sourceRoot":"","sources":["../../src/createPipelineFromOptions.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAyB,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAC3E,OAAO,EAAiB,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEnE,OAAO,EAA8B,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC1F,OAAO,EAA+B,eAAe,EAAE,MAAM,+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CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC;IAC9D,QAAQ,CAAC,SAAS,CAAC,wBAAwB,CAAC,MAAA,OAAO,CAAC,gBAAgB,0CAAE,yBAAyB,CAAC,CAAC,CAAC;IAClG,sEAAsE;IACtE,gEAAgE;IAChE,qEAAqE;IACrE,QAAQ,CAAC,SAAS,CAAC,eAAe,EAAE,EAAE,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC,CAAC;IACrE,QAAQ,CAAC,SAAS,CAAC,kBAAkB,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IACjF,QAAQ,CAAC,SAAS,CAAC,aAAa,iCAAM,OAAO,CAAC,gBAAgB,GAAK,OAAO,CAAC,cAAc,EAAG,EAAE;QAC5F,UAAU,EAAE,OAAO;KACpB,CAAC,CAAC;IACH,IAAI,UAAU,EAAE,CAAC;QACf,+DAA+D;QAC/D,kDAAkD;QAClD,QAAQ,CAAC,SAAS,CAAC,cAAc,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;IACvF,CAAC;IACD,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC;IAE9E,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { type LogPolicyOptions, logPolicy } from \"./policies/logPolicy.js\";\nimport { type Pipeline, createEmptyPipeline } from \"./pipeline.js\";\nimport type { Agent, PipelineRetryOptions, ProxySettings, TlsSettings } from \"./interfaces.js\";\nimport { type RedirectPolicyOptions, redirectPolicy } from \"./policies/redirectPolicy.js\";\nimport { type UserAgentPolicyOptions, userAgentPolicy } from \"./policies/userAgentPolicy.js\";\nimport { multipartPolicy, multipartPolicyName } from \"./policies/multipartPolicy.js\";\nimport { decompressResponsePolicy } from \"./policies/decompressResponsePolicy.js\";\nimport { defaultRetryPolicy } from \"./policies/defaultRetryPolicy.js\";\nimport { formDataPolicy } from \"./policies/formDataPolicy.js\";\nimport { isNodeLike } from \"@azure/core-util\";\nimport { proxyPolicy } from \"./policies/proxyPolicy.js\";\nimport { setClientRequestIdPolicy } from \"./policies/setClientRequestIdPolicy.js\";\nimport { agentPolicy } from \"./policies/agentPolicy.js\";\nimport { tlsPolicy } from \"./policies/tlsPolicy.js\";\nimport { tracingPolicy } from \"./policies/tracingPolicy.js\";\n\n/**\n * Defines options that are used to configure the HTTP pipeline for\n * an SDK client.\n */\nexport interface PipelineOptions {\n /**\n * Options that control how to retry failed requests.\n */\n retryOptions?: PipelineRetryOptions;\n\n /**\n * Options to configure a proxy for outgoing requests.\n */\n proxyOptions?: ProxySettings;\n\n /** Options for configuring Agent instance for outgoing requests */\n agent?: Agent;\n\n /** Options for configuring TLS authentication */\n tlsOptions?: TlsSettings;\n\n /**\n * Options for how redirect responses are handled.\n */\n redirectOptions?: RedirectPolicyOptions;\n\n /**\n * Options for adding user agent details to outgoing requests.\n */\n userAgentOptions?: UserAgentPolicyOptions;\n\n /**\n * Options for setting common telemetry and tracing info to outgoing requests.\n */\n telemetryOptions?: TelemetryOptions;\n}\n\n/**\n * Defines options that are used to configure common telemetry and tracing info\n */\nexport interface TelemetryOptions {\n /**\n * The name of the header to pass the request ID to.\n */\n clientRequestIdHeaderName?: string;\n}\n\n/**\n * Defines options that are used to configure internal options of\n * the HTTP pipeline for an SDK client.\n */\nexport interface InternalPipelineOptions extends PipelineOptions {\n /**\n * Options to configure request/response logging.\n */\n loggingOptions?: LogPolicyOptions;\n}\n\n/**\n * Create a new pipeline with a default set of customizable policies.\n * @param options - Options to configure a custom pipeline.\n */\nexport function createPipelineFromOptions(options: InternalPipLine truncated
@@ -0,0 +1,6 @@
import type { HttpClient } from "./interfaces.js";
/**
* Create the correct HttpClient for the current environment.
*/
export declare function createDefaultHttpClient(): HttpClient;
//# sourceMappingURL=defaultHttpClient.d.ts.map
+10
View File
@@ -0,0 +1,10 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createNodeHttpClient } from "./nodeHttpClient.js";
/**
* Create the correct HttpClient for the current environment.
*/
export function createDefaultHttpClient() {
return createNodeHttpClient();
}
//# sourceMappingURL=defaultHttpClient.js.map
@@ -0,0 +1 @@
{"version":3,"file":"defaultHttpClient.js","sourceRoot":"","sources":["../../src/defaultHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAE3D;;GAEG;AACH,MAAM,UAAU,uBAAuB;IACrC,OAAO,oBAAoB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { HttpClient } from \"./interfaces.js\";\nimport { createNodeHttpClient } from \"./nodeHttpClient.js\";\n\n/**\n * Create the correct HttpClient for the current environment.\n */\nexport function createDefaultHttpClient(): HttpClient {\n return createNodeHttpClient();\n}\n"]}
+7
View File
@@ -0,0 +1,7 @@
import type { HttpClient } from "./interfaces.js";
/**
* Create a new HttpClient instance for the browser environment.
* @internal
*/
export declare function createFetchHttpClient(): HttpClient;
//# sourceMappingURL=fetchHttpClient.d.ts.map
+256
View File
@@ -0,0 +1,256 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { AbortError } from "@azure/abort-controller";
import { RestError } from "./restError.js";
import { createHttpHeaders } from "./httpHeaders.js";
import { isNodeReadableStream, isWebReadableStream } from "./util/typeGuards.js";
/**
* Checks if the body is a Blob or Blob-like
*/
function isBlob(body) {
// File objects count as a type of Blob, so we want to use instanceof explicitly
return (typeof Blob === "function" || typeof Blob === "object") && body instanceof Blob;
}
/**
* A HttpClient implementation that uses window.fetch to send HTTP requests.
* @internal
*/
class FetchHttpClient {
/**
* Makes a request over an underlying transport layer and returns the response.
* @param request - The request to be made.
*/
async sendRequest(request) {
const url = new URL(request.url);
const isInsecure = url.protocol !== "https:";
if (isInsecure && !request.allowInsecureConnection) {
throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
}
if (request.proxySettings) {
throw new Error("HTTP proxy is not supported in browser environment");
}
try {
return await makeRequest(request);
}
catch (e) {
throw getError(e, request);
}
}
}
/**
* Sends a request
*/
async function makeRequest(request) {
const { abortController, abortControllerCleanup } = setupAbortSignal(request);
try {
const headers = buildFetchHeaders(request.headers);
const { streaming, body: requestBody } = buildRequestBody(request);
const requestInit = Object.assign(Object.assign({ body: requestBody, method: request.method, headers: headers, signal: abortController.signal }, ("credentials" in Request.prototype
? { credentials: request.withCredentials ? "include" : "same-origin" }
: {})), ("cache" in Request.prototype ? { cache: "no-store" } : {}));
// According to https://fetch.spec.whatwg.org/#fetch-method,
// init.duplex must be set when body is a ReadableStream object.
// currently "half" is the only valid value.
if (streaming) {
requestInit.duplex = "half";
}
/**
* Developers of the future:
* Do not set redirect: "manual" as part
* of request options.
* It will not work as you expect.
*/
const response = await fetch(request.url, requestInit);
// If we're uploading a blob, we need to fire the progress event manually
if (isBlob(request.body) && request.onUploadProgress) {
request.onUploadProgress({ loadedBytes: request.body.size });
}
return buildPipelineResponse(response, request, abortControllerCleanup);
}
catch (e) {
abortControllerCleanup === null || abortControllerCleanup === void 0 ? void 0 : abortControllerCleanup();
throw e;
}
}
/**
* Creates a pipeline response from a Fetch response;
*/
async function buildPipelineResponse(httpResponse, request, abortControllerCleanup) {
var _a, _b;
const headers = buildPipelineHeaders(httpResponse);
const response = {
request,
headers,
status: httpResponse.status,
};
const bodyStream = isWebReadableStream(httpResponse.body)
? buildBodyStream(httpResponse.body, {
onProgress: request.onDownloadProgress,
onEnd: abortControllerCleanup,
})
: httpResponse.body;
if (
// Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
((_a = request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(Number.POSITIVE_INFINITY)) ||
((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(response.status))) {
if (request.enableBrowserStreams) {
response.browserStreamBody = bodyStream !== null && bodyStream !== void 0 ? bodyStream : undefined;
}
else {
const responseStream = new Response(bodyStream);
response.blobBody = responseStream.blob();
abortControllerCleanup === null || abortControllerCleanup === void 0 ? void 0 : abortControllerCleanup();
}
}
else {
const responseStream = new Response(bodyStream);
response.bodyAsText = await responseStream.text();
abortControllerCleanup === null || abortControllerCleanup === void 0 ? void 0 : abortControllerCleanup();
}
return response;
}
function setupAbortSignal(request) {
const abortController = new AbortController();
// Cleanup function
let abortControllerCleanup;
/**
* Attach an abort listener to the request
*/
let abortListener;
if (request.abortSignal) {
if (request.abortSignal.aborted) {
throw new AbortError("The operation was aborted. Request has already been canceled.");
}
abortListener = (event) => {
if (event.type === "abort") {
abortController.abort();
}
};
request.abortSignal.addEventListener("abort", abortListener);
abortControllerCleanup = () => {
var _a;
if (abortListener) {
(_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
}
};
}
// If a timeout was passed, call the abort signal once the time elapses
if (request.timeout > 0) {
setTimeout(() => {
abortController.abort();
}, request.timeout);
}
return { abortController, abortControllerCleanup };
}
/**
* Gets the specific error
*/
// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters
function getError(e, request) {
var _a;
if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") {
return e;
}
else {
return new RestError(`Error sending request: ${e.message}`, {
code: (_a = e === null || e === void 0 ? void 0 : e.code) !== null && _a !== void 0 ? _a : RestError.REQUEST_SEND_ERROR,
request,
});
}
}
/**
* Converts PipelineRequest headers to Fetch headers
*/
function buildFetchHeaders(pipelineHeaders) {
const headers = new Headers();
for (const [name, value] of pipelineHeaders) {
headers.append(name, value);
}
return headers;
}
function buildPipelineHeaders(httpResponse) {
const responseHeaders = createHttpHeaders();
for (const [name, value] of httpResponse.headers) {
responseHeaders.set(name, value);
}
return responseHeaders;
}
function buildRequestBody(request) {
const body = typeof request.body === "function" ? request.body() : request.body;
if (isNodeReadableStream(body)) {
throw new Error("Node streams are not supported in browser environment.");
}
return isWebReadableStream(body)
? { streaming: true, body: buildBodyStream(body, { onProgress: request.onUploadProgress }) }
: { streaming: false, body };
}
/**
* Reads the request/response original stream and stream it through a new
* ReadableStream, this is done to be able to report progress in a way that
* all modern browsers support. TransformStreams would be an alternative,
* however they are not yet supported by all browsers i.e Firefox
*/
function buildBodyStream(readableStream, options = {}) {
let loadedBytes = 0;
const { onProgress, onEnd } = options;
// If the current browser supports pipeThrough we use a TransformStream
// to report progress
if (isTransformStreamSupported(readableStream)) {
return readableStream.pipeThrough(new TransformStream({
transform(chunk, controller) {
if (chunk === null) {
controller.terminate();
return;
}
controller.enqueue(chunk);
loadedBytes += chunk.length;
if (onProgress) {
onProgress({ loadedBytes });
}
},
flush() {
onEnd === null || onEnd === void 0 ? void 0 : onEnd();
},
}));
}
else {
// If we can't use transform streams, wrap the original stream in a new readable stream
// and use pull to enqueue each chunk and report progress.
const reader = readableStream.getReader();
return new ReadableStream({
async pull(controller) {
var _a;
const { done, value } = await reader.read();
// When no more data needs to be consumed, break the reading
if (done || !value) {
onEnd === null || onEnd === void 0 ? void 0 : onEnd();
// Close the stream
controller.close();
reader.releaseLock();
return;
}
loadedBytes += (_a = value === null || value === void 0 ? void 0 : value.length) !== null && _a !== void 0 ? _a : 0;
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
if (onProgress) {
onProgress({ loadedBytes });
}
},
cancel(reason) {
onEnd === null || onEnd === void 0 ? void 0 : onEnd();
return reader.cancel(reason);
},
});
}
}
/**
* Create a new HttpClient instance for the browser environment.
* @internal
*/
export function createFetchHttpClient() {
return new FetchHttpClient();
}
function isTransformStreamSupported(readableStream) {
return readableStream.pipeThrough !== undefined && self.TransformStream !== undefined;
}
//# sourceMappingURL=fetchHttpClient.js.map
@@ -0,0 +1 @@
{"version":3,"file":"fetchHttpClient.js","s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tD,IAAI,CAAC,IAAI,CAAA,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,IAAI,MAAK,YAAY,EAAE,CAAC;QAClC,OAAO,CAAC,CAAC;IACX,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,SAAS,CAAC,0BAA0B,CAAC,CAAC,OAAO,EAAE,EAAE;YAC1D,IAAI,EAAE,MAAA,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,IAAI,mCAAI,SAAS,CAAC,kBAAkB;YAC7C,OAAO;SACR,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AAED;;GAEG;AACH,SAAS,iBAAiB,CAAC,eAAgC;IACzD,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;IAC9B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,eAAe,EAAE,CAAC;QAC5C,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,SAAS,oBAAoB,CAAC,YAAsB;IAClD,MAAM,eAAe,GAAG,iBAAiB,EAAE,CAAC;IAC5C,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,YAAY,CAAC,OAAO,EAAE,CAAC;QACjD,eAAe,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACnC,CAAC;IAED,OALine truncated
+7
View File
@@ -0,0 +1,7 @@
import type { HttpHeaders, RawHttpHeadersInput } from "./interfaces.js";
/**
* Creates an object that satisfies the `HttpHeaders` interface.
* @param rawHeaders - A simple object representing initial headers
*/
export declare function createHttpHeaders(rawHeaders?: RawHttpHeadersInput): HttpHeaders;
//# sourceMappingURL=httpHeaders.d.ts.map
+89
View File
@@ -0,0 +1,89 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
function normalizeName(name) {
return name.toLowerCase();
}
function* headerIterator(map) {
for (const entry of map.values()) {
yield [entry.name, entry.value];
}
}
class HttpHeadersImpl {
constructor(rawHeaders) {
this._headersMap = new Map();
if (rawHeaders) {
for (const headerName of Object.keys(rawHeaders)) {
this.set(headerName, rawHeaders[headerName]);
}
}
}
/**
* Set a header in this collection with the provided name and value. The name is
* case-insensitive.
* @param name - The name of the header to set. This value is case-insensitive.
* @param value - The value of the header to set.
*/
set(name, value) {
this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
}
/**
* Get the header value for the provided header name, or undefined if no header exists in this
* collection with the provided name.
* @param name - The name of the header. This value is case-insensitive.
*/
get(name) {
var _a;
return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value;
}
/**
* Get whether or not this header collection contains a header entry for the provided header name.
* @param name - The name of the header to set. This value is case-insensitive.
*/
has(name) {
return this._headersMap.has(normalizeName(name));
}
/**
* Remove the header with the provided headerName.
* @param name - The name of the header to remove.
*/
delete(name) {
this._headersMap.delete(normalizeName(name));
}
/**
* Get the JSON object representation of this HTTP header collection.
*/
toJSON(options = {}) {
const result = {};
if (options.preserveCase) {
for (const entry of this._headersMap.values()) {
result[entry.name] = entry.value;
}
}
else {
for (const [normalizedName, entry] of this._headersMap) {
result[normalizedName] = entry.value;
}
}
return result;
}
/**
* Get the string representation of this HTTP header collection.
*/
toString() {
return JSON.stringify(this.toJSON({ preserveCase: true }));
}
/**
* Iterate over tuples of header [name, value] pairs.
*/
[Symbol.iterator]() {
return headerIterator(this._headersMap);
}
}
/**
* Creates an object that satisfies the `HttpHeaders` interface.
* @param rawHeaders - A simple object representing initial headers
*/
export function createHttpHeaders(rawHeaders) {
return new HttpHeadersImpl(rawHeaders);
}
//# sourceMappingURL=httpHeaders.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"httpHeaders.js","sourceRoot":"","sources":["../../src/httpHeaders.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AASlC,SAAS,aAAa,CAAC,IAAY;IACjC,OAAO,IAAI,CAAC,WAAW,EAAE,CAA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AAM,GAAmB,EAAE,CAAC;QAClC,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACzB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,CAAC;gBAC9C,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC;YACnC,CAAC;QACH,CAAC;aAAM,CAAC;YACN,KAAK,MAAM,CAAC,cAAc,EAAE,KAAK,CAAC,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;gBACvD,MAAM,CAAC,cAAc,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC;YACvC,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;OAEG;IACI,QAAQ;QACb,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC7D,CAAC;IAED;;OAEG;IACH,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAC1C,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAgC;IAChE,OAAO,IAAI,eAAe,CAAC,UAAU,CAAC,CAAC;AACzC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { HttpHeaders, RawHttpHeaders, RawHttpHeadersInput } from \"./interfaces.js\";\n\ninterface HeaderEntry {\n name: string;\n value: string;\n}\n\nfunction normalizeName(name: string): string {\n return name.toLowerCase();\n}\n\nfunction* headerIterator(map: Map<string, HeaderEntry>): IterableIterator<[string, string]> {\n for (const entry of map.values()) {\n yield [entry.name, entry.value];\n }\n}\n\nclass HttpHeadersImpl implements HttpHeaders {\n private readonly _headersMap: Map<string, HeaderEntry>;\n\n constructor(rawHeaders?: RawHttpHeaders | RawHttpHeadersInput) {\n this._headersMap = new Map<string, HeaderEntry>();\n if (rawHeaders) {\n for (const headerName of Object.keys(rawHeaders)) {\n this.set(headerName, rawHeaders[headerName]);\n }\n }\n }\n\n /**\n * Set a header in this collection with the provided name and value. The name is\n * case-insensitive.\n * @param name - The name of the header to set. This value is case-insensitive.\n * @param value - The value of the header to set.\n */\n public set(name: string, value: string | number | boolean): void {\n this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });\n }\n\n /**\n * Get the header value for the provided header name, or undefined if no header exists in this\n * collection with the provided name.\n * @param name - The name of the header. This value is case-insensitive.\n */\n public get(name: string): string | undefined {\n return this._headersMap.get(normalizeName(name))?.value;\n }\n\n /**\n * Get whether or not this header collection contains a header entry for the provided header name.\n * @param name - The name of the header to set. This value is case-insensitive.\n */\n public has(name: string): boolean {\n return this._headersMap.has(normalizeName(name));\n }\n\n /**\n * Remove the header with the provided headerName.\n * @param name - The name of the header to remove.\n */\n public delete(name: string): void {\n this._headersMap.delete(normalizeName(name));\n }\n\n /**\n * Get the JSON object representation of this HTTP header collection.\n */\n public toJSON(options: { preserveCase?: boolean } = {}): RawHttpHeaders {\n const result: RawHttpHeaders = {};\n if (options.preserveCase) {\n for (const entry of this._headersMap.values()) {\n result[entry.name] = entry.value;\n }\n } else {\n for (const [normalizedName, entry] of this._headersMap) {\n result[normalizedName] = entry.value;\n }\n }\n\n return result;\n }\n\n /**\n * Get the string representation of this HTTP header collection.\n */\n public toString(): string {\n return JSON.stringify(this.toJSON({ preserveCase: true }));\n }\n\n /**\n * Iterate over tuples of header [name, value] pairs.\n */\n [Symbol.iterator](): Iterator<[string, string]> {\n retuLine truncated
+42
View File
@@ -0,0 +1,42 @@
declare global {
interface FormData {
}
interface Blob {
}
interface File {
}
interface ReadableStream<R = any> {
}
interface TransformStream<I = any, O = any> {
}
}
export type { HttpMethods } from "@azure/core-util";
export type { Agent, BodyPart, FormDataMap, FormDataValue, HttpClient, HttpHeaders, KeyObject, MultipartRequestBody, PipelineRequest, PipelineResponse, PipelineRetryOptions, ProxySettings, PxfObject, RawHttpHeaders, RawHttpHeadersInput, RequestBodyType, SendRequest, TlsSettings, TransferProgressEvent, } from "./interfaces.js";
export { type AddPolicyOptions as AddPipelineOptions, type PipelinePhase, type PipelinePolicy, type Pipeline, createEmptyPipeline, } from "./pipeline.js";
export { createPipelineFromOptions, type TelemetryOptions, type InternalPipelineOptions, type PipelineOptions, } from "./createPipelineFromOptions.js";
export { createDefaultHttpClient } from "./defaultHttpClient.js";
export { createHttpHeaders } from "./httpHeaders.js";
export { createPipelineRequest, type PipelineRequestOptions } from "./pipelineRequest.js";
export { RestError, type RestErrorOptions, isRestError } from "./restError.js";
export { decompressResponsePolicy, decompressResponsePolicyName, } from "./policies/decompressResponsePolicy.js";
export { exponentialRetryPolicy, type ExponentialRetryPolicyOptions, exponentialRetryPolicyName, } from "./policies/exponentialRetryPolicy.js";
export { setClientRequestIdPolicy, setClientRequestIdPolicyName, } from "./policies/setClientRequestIdPolicy.js";
export { logPolicy, logPolicyName, type LogPolicyOptions } from "./policies/logPolicy.js";
export { multipartPolicy, multipartPolicyName } from "./policies/multipartPolicy.js";
export { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from "./policies/proxyPolicy.js";
export { redirectPolicy, redirectPolicyName, type RedirectPolicyOptions, } from "./policies/redirectPolicy.js";
export { systemErrorRetryPolicy, type SystemErrorRetryPolicyOptions, systemErrorRetryPolicyName, } from "./policies/systemErrorRetryPolicy.js";
export { throttlingRetryPolicy, throttlingRetryPolicyName, type ThrottlingRetryPolicyOptions, } from "./policies/throttlingRetryPolicy.js";
export { retryPolicy, type RetryPolicyOptions } from "./policies/retryPolicy.js";
export type { RetryStrategy, RetryInformation, RetryModifiers, } from "./retryStrategies/retryStrategy.js";
export { tracingPolicy, tracingPolicyName, type TracingPolicyOptions, } from "./policies/tracingPolicy.js";
export { defaultRetryPolicy, type DefaultRetryPolicyOptions, } from "./policies/defaultRetryPolicy.js";
export { userAgentPolicy, userAgentPolicyName, type UserAgentPolicyOptions, } from "./policies/userAgentPolicy.js";
export { tlsPolicy, tlsPolicyName } from "./policies/tlsPolicy.js";
export { formDataPolicy, formDataPolicyName } from "./policies/formDataPolicy.js";
export { bearerTokenAuthenticationPolicy, type BearerTokenAuthenticationPolicyOptions, bearerTokenAuthenticationPolicyName, type ChallengeCallbacks, type AuthorizeRequestOptions, type AuthorizeRequestOnChallengeOptions, } from "./policies/bearerTokenAuthenticationPolicy.js";
export { ndJsonPolicy, ndJsonPolicyName } from "./policies/ndJsonPolicy.js";
export { auxiliaryAuthenticationHeaderPolicy, type AuxiliaryAuthenticationHeaderPolicyOptions, auxiliaryAuthenticationHeaderPolicyName, } from "./policies/auxiliaryAuthenticationHeaderPolicy.js";
export { agentPolicy, agentPolicyName } from "./policies/agentPolicy.js";
export { createFile, createFileFromStream, type CreateFileOptions, type CreateFileFromStreamOptions, } from "./util/file.js";
//# sourceMappingURL=index.d.ts.map
+29
View File
@@ -0,0 +1,29 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export { createEmptyPipeline, } from "./pipeline.js";
export { createPipelineFromOptions, } from "./createPipelineFromOptions.js";
export { createDefaultHttpClient } from "./defaultHttpClient.js";
export { createHttpHeaders } from "./httpHeaders.js";
export { createPipelineRequest } from "./pipelineRequest.js";
export { RestError, isRestError } from "./restError.js";
export { decompressResponsePolicy, decompressResponsePolicyName, } from "./policies/decompressResponsePolicy.js";
export { exponentialRetryPolicy, exponentialRetryPolicyName, } from "./policies/exponentialRetryPolicy.js";
export { setClientRequestIdPolicy, setClientRequestIdPolicyName, } from "./policies/setClientRequestIdPolicy.js";
export { logPolicy, logPolicyName } from "./policies/logPolicy.js";
export { multipartPolicy, multipartPolicyName } from "./policies/multipartPolicy.js";
export { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from "./policies/proxyPolicy.js";
export { redirectPolicy, redirectPolicyName, } from "./policies/redirectPolicy.js";
export { systemErrorRetryPolicy, systemErrorRetryPolicyName, } from "./policies/systemErrorRetryPolicy.js";
export { throttlingRetryPolicy, throttlingRetryPolicyName, } from "./policies/throttlingRetryPolicy.js";
export { retryPolicy } from "./policies/retryPolicy.js";
export { tracingPolicy, tracingPolicyName, } from "./policies/tracingPolicy.js";
export { defaultRetryPolicy, } from "./policies/defaultRetryPolicy.js";
export { userAgentPolicy, userAgentPolicyName, } from "./policies/userAgentPolicy.js";
export { tlsPolicy, tlsPolicyName } from "./policies/tlsPolicy.js";
export { formDataPolicy, formDataPolicyName } from "./policies/formDataPolicy.js";
export { bearerTokenAuthenticationPolicy, bearerTokenAuthenticationPolicyName, } from "./policies/bearerTokenAuthenticationPolicy.js";
export { ndJsonPolicy, ndJsonPolicyName } from "./policies/ndJsonPolicy.js";
export { auxiliaryAuthenticationHeaderPolicy, auxiliaryAuthenticationHeaderPolicyName, } from "./policies/auxiliaryAuthenticationHeaderPolicy.js";
export { agentPolicy, agentPolicyName } from "./policies/agentPolicy.js";
export { createFile, createFileFromStream, } from "./util/file.js";
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAgClC,OAAO,EAKL,mBAAmB,GACpB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,yBAAyB,GAI1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAA+B,MAAM,sBAAsB,CAAC;AAC1F,OAAO,EAAE,SAAS,EAAyB,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,sBAAsB,EAEtB,0BAA0B,GAC3B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,aAAa,EAAyB,MAAM,yBAAyB,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAClG,OAAO,EACL,cAAc,EACd,kBAAkB,GAEnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,sBAAsB,EAEtB,0BAA0B,GAC3B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,qBAAqB,EACrB,yBAAyB,GAE1B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,WAAW,EAA2B,MAAM,2BAA2B,CAAC;AAMjF,OAAO,EACL,aAAa,EACb,iBAAiB,GAElB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,kBAAkB,GAEnB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,eAAe,EACf,mBAAmB,GAEpB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClF,OAAO,EACL,+BAA+B,EAE/B,mCAAmC,GAIpC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC5E,OAAO,EACL,mCAAmC,EAEnC,uCAAuC,GACxC,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EACL,UAAU,EACV,oBAAoB,GAGrB,MAAM,gBAAgB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\ndeclare global {\n interface FormData {}\n interface Blob {}\n interface File {}\n interface ReadableStream<R = any> {}\n interface TransformStream<I = any, O = any> {}\n}\n\nexport type { HttpMethods } from \"@azure/core-util\";\nexport type {\n Agent,\n BodyPart,\n FormDataMap,\n FormDataValue,\n HttpClient,\n HttpHeaders,\n KeyObject,\n MultipartRequestBody,\n PipelineRequest,\n PipelineResponse,\n PipelineRetryOptions,\n ProxySettings,\n PxfObject,\n RawHttpHeaders,\n RawHttpHeadersInput,\n RequestBodyType,\n SendRequest,\n TlsSettings,\n TransferProgressEvent,\n} from \"./interfaces.js\";\nexport {\n type AddPolicyOptions as AddPipelineOptions,\n type PipelinePhase,\n type PipelinePolicy,\n type Pipeline,\n createEmptyPipeline,\n} from \"./pipeline.js\";\nexport {\n createPipelineFromOptions,\n type TelemetryOptions,\n type InternalPipelineOptions,\n type PipelineOptions,\n} from \"./createPipelineFromOptions.js\";\nexport { createDefaultHttpClient } from \"./defaultHttpClient.js\";\nexport { createHttpHeaders } from \"./httpHeaders.js\";\nexport { createPipelineRequest, type PipelineRequestOptions } from \"./pipelineRequest.js\";\nexport { RestError, type RestErrorOptions, isRestError } from \"./restError.js\";\nexport {\n decompressResponsePolicy,\n decompressResponsePolicyName,\n} from \"./policies/decompressResponsePolicy.js\";\nexport {\n exponentialRetryPolicy,\n type ExponentialRetryPolicyOptions,\n exponentialRetryPolicyName,\n} from \"./policies/exponentialRetryPolicy.js\";\nexport {\n setClientRequestIdPolicy,\n setClientRequestIdPolicyName,\n} from \"./policies/setClientRequestIdPolicy.js\";\nexport { logPolicy, logPolicyName, type LogPolicyOptions } from \"./policies/logPolicy.js\";\nexport { multipartPolicy, multipartPolicyName } from \"./policies/multipartPolicy.js\";\nexport { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from \"./policies/proxyPolicy.js\";\nexport {\n redirectPolicy,\n redirectPolicyName,\n type RedirectPolicyOptions,\n} from \"./policies/redirectPolicy.js\";\nexport {\n systemErrorRetryPolicy,\n type SystemErrorRetryPolicyOptions,\n systemErrorRetryPolicyName,\n} from \"./policies/systemErrorRetryPolicy.js\";\nexport {\n throttlingRetryPolicy,\n throttlingRetryPolicyName,\n type ThrottlingRetryPolicyOptions,\n} from \"./policies/throttlingRetryPolicy.js\";\nexport { retryPolicy, type RetryPolicyOptions } from \"./policies/retryPolicy.js\";\nexport type {\n RetryStrategy,\n RetryInformation,\n RetryModifiers,\n} from \"./retryStrategies/retryStrategy.js\";\nexport {\n tracingPolicy,\n tracingPolicyName,\n type TracingPolicyOptions,\n} from \"./policies/tracingPolicy.js\";\nexport {\n defaultRetryPolicy,\n type DefaultRetryPolicyOptions,\n} from \"./policies/defaultRetryPolicy.js\";\nexport {\n userAgentPolicy,\n userAgentPolicyName,\n type UserAgentPolicyOptions,\n} from \"./policies/userAgentPolicy.js\";\nexport { tlsPolicy, tlsPolicyName } from \"./policies/tlsPolicy.js\";\nexport { formDataPolicy, formDataPolicyName } from \"./policies/formDataPolicy.js\";\nexport {\n bearerTokenAuthenticationPolicy,\n type BearerTokenAuthenticationPolicyOptions,\n bearerTokenAuthenticationPolicyName,\n type ChallengeCallbacks,\n type AuthorizeRequestOptions,\n type AuthorizeRequestOnChallengeOptions,\n} from \"./pLine truncated
+442
View File
@@ -0,0 +1,442 @@
import type { AbortSignalLike } from "@azure/abort-controller";
import type { OperationTracingOptions } from "@azure/core-tracing";
import type { HttpMethods } from "@azure/core-util";
/**
* A HttpHeaders collection represented as a simple JSON object.
*/
export type RawHttpHeaders = {
[headerName: string]: string;
};
/**
* A HttpHeaders collection for input, represented as a simple JSON object.
*/
export type RawHttpHeadersInput = Record<string, string | number | boolean>;
/**
* Represents a set of HTTP headers on a request/response.
* Header names are treated as case insensitive.
*/
export interface HttpHeaders extends Iterable<[string, string]> {
/**
* Returns the value of a specific header or undefined if not set.
* @param name - The name of the header to retrieve.
*/
get(name: string): string | undefined;
/**
* Returns true if the specified header exists.
* @param name - The name of the header to check.
*/
has(name: string): boolean;
/**
* Sets a specific header with a given value.
* @param name - The name of the header to set.
* @param value - The value to use for the header.
*/
set(name: string, value: string | number | boolean): void;
/**
* Removes a specific header from the collection.
* @param name - The name of the header to delete.
*/
delete(name: string): void;
/**
* Accesses a raw JS object that acts as a simple map
* of header names to values.
*/
toJSON(options?: {
preserveCase?: boolean;
}): RawHttpHeaders;
}
/**
* A part of the request body in a multipart request.
*/
export interface BodyPart {
/**
* The headers for this part of the multipart request.
*/
headers: HttpHeaders;
/**
* The body of this part of the multipart request.
*/
body: ((() => ReadableStream<Uint8Array>) | (() => NodeJS.ReadableStream)) | ReadableStream<Uint8Array> | NodeJS.ReadableStream | Uint8Array | Blob;
}
/**
* A request body consisting of multiple parts.
*/
export interface MultipartRequestBody {
/**
* The parts of the request body.
*/
parts: BodyPart[];
/**
* The boundary separating each part of the request body.
* If not specified, a random boundary will be generated.
*
* When specified, '--' will be prepended to the boundary in the request to ensure the boundary follows the specification.
*/
boundary?: string;
}
/**
* Types of bodies supported on the request.
* NodeJS.ReadableStream and () =\> NodeJS.ReadableStream is Node only.
* Blob, ReadableStream<Uint8Array>, and () =\> ReadableStream<Uint8Array> are browser only.
*/
export type RequestBodyType = NodeJS.ReadableStream | (() => NodeJS.ReadableStream) | ReadableStream<Uint8Array> | (() => ReadableStream<Uint8Array>) | Blob | ArrayBuffer | ArrayBufferView | FormData | string | null;
/**
* An interface compatible with NodeJS's `http.Agent`.
* We want to avoid publicly re-exporting the actual interface,
* since it might vary across runtime versions.
*/
export interface Agent {
/**
* Destroy any sockets that are currently in use by the agent.
*/
destroy(): void;
/**
* For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state.
*/
maxFreeSockets: number;
/**
* Determines how many concurrent sockets the agent can have open per origin.
*/
maxSockets: number;
/**
* An object which contains queues of requests that have not yet been assigned to sockets.
*/
requests: unknown;
/**
* An object which contains arrays of sockets currently in use by the agent.
*/
sockets: unknown;
}
/**
* Metadata about a request being made by the pipeline.
*/
export interface PipelineRequest {
/**
* The URL to make the request to.
*/
url: string;
/**
* The HTTP method to use when making the request.
*/
method: HttpMethods;
/**
* The HTTP headers to use when making the request.
*/
headers: HttpHeaders;
/**
* The number of milliseconds a request can take before automatically being terminated.
* If the request is terminated, an `AbortError` is thrown.
* Defaults to 0, which disables the timeout.
*/
timeout: number;
/**
* Indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests.
* Defaults to false.
*/
withCredentials: boolean;
/**
* A unique identifier for the request. Used for logging and tracing.
*/
requestId: string;
/**
* The HTTP body content (if any)
*/
body?: RequestBodyType;
/**
* Body for a multipart request.
*/
multipartBody?: MultipartRequestBody;
/**
* To simulate a browser form post
*/
formData?: FormDataMap;
/**
* A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.
* When streamResponseStatusCodes contains the value Number.POSITIVE_INFINITY any status would be treated as a stream.
*/
streamResponseStatusCodes?: Set<number>;
/**
* Proxy configuration.
*/
proxySettings?: ProxySettings;
/**
* If the connection should not be reused.
*/
disableKeepAlive?: boolean;
/**
* Used to abort the request later.
*/
abortSignal?: AbortSignalLike;
/**
* Tracing options to use for any created Spans.
*/
tracingOptions?: OperationTracingOptions;
/**
* Callback which fires upon upload progress.
*/
onUploadProgress?: (progress: TransferProgressEvent) => void;
/** Callback which fires upon download progress. */
onDownloadProgress?: (progress: TransferProgressEvent) => void;
/** Set to true if the request is sent over HTTP instead of HTTPS */
allowInsecureConnection?: boolean;
/**
* NODEJS ONLY
*
* A Node-only option to provide a custom `http.Agent`/`https.Agent`.
* Does nothing when running in the browser.
*/
agent?: Agent;
/**
* BROWSER ONLY
*
* A browser only option to enable browser Streams. If this option is set and a response is a stream
* the response will have a property `browserStream` instead of `blobBody` which will be undefined.
*
* Default value is false
*/
enableBrowserStreams?: boolean;
/** Settings for configuring TLS authentication */
tlsSettings?: TlsSettings;
}
/**
* Metadata about a response received by the pipeline.
*/
export interface PipelineResponse {
/**
* The request that generated this response.
*/
request: PipelineRequest;
/**
* The HTTP status code of the response.
*/
status: number;
/**
* The HTTP response headers.
*/
headers: HttpHeaders;
/**
* The response body as text (string format)
*/
bodyAsText?: string | null;
/**
* BROWSER ONLY
*
* The response body as a browser Blob.
* Always undefined in node.js.
*/
blobBody?: Promise<Blob>;
/**
* BROWSER ONLY
*
* The response body as a browser ReadableStream.
* Always undefined in node.js.
*/
browserStreamBody?: ReadableStream<Uint8Array>;
/**
* NODEJS ONLY
*
* The response body as a node.js Readable stream.
* Always undefined in the browser.
*/
readableStreamBody?: NodeJS.ReadableStream;
}
/**
* A simple interface for making a pipeline request and receiving a response.
*/
export type SendRequest = (request: PipelineRequest) => Promise<PipelineResponse>;
/**
* The required interface for a client that makes HTTP requests
* on behalf of a pipeline.
*/
export interface HttpClient {
/**
* The method that makes the request and returns a response.
*/
sendRequest: SendRequest;
}
/**
* Fired in response to upload or download progress.
*/
export type TransferProgressEvent = {
/**
* The number of bytes loaded so far.
*/
loadedBytes: number;
};
/**
* Options to configure a proxy for outgoing requests (Node.js only).
*/
export interface ProxySettings {
/**
* The proxy's host address.
*/
host: string;
/**
* The proxy host's port.
*/
port: number;
/**
* The user name to authenticate with the proxy, if required.
*/
username?: string;
/**
* The password to authenticate with the proxy, if required.
*/
password?: string;
}
/**
* Each form data entry can be a string, Blob, or a File. If you wish to pass a file with a name but do not have
* access to the File class, you can use the createFile helper to create one.
*/
export type FormDataValue = string | Blob | File;
/**
* A simple object that provides form data, as if from a browser form.
*/
export type FormDataMap = {
[key: string]: FormDataValue | FormDataValue[];
};
/**
* Options that control how to retry failed requests.
*/
export interface PipelineRetryOptions {
/**
* The maximum number of retry attempts. Defaults to 3.
*/
maxRetries?: number;
/**
* The amount of delay in milliseconds between retry attempts. Defaults to 1000
* (1 second). The delay increases exponentially with each retry up to a maximum
* specified by maxRetryDelayInMs.
*/
retryDelayInMs?: number;
/**
* The maximum delay in milliseconds allowed before retrying an operation. Defaults
* to 64000 (64 seconds).
*/
maxRetryDelayInMs?: number;
}
/**
* Represents a certificate credential for authentication.
*/
export interface CertificateCredential {
/**
* Optionally override the trusted CA certificates. Default is to trust
* the well-known CAs curated by Mozilla. Mozilla's CAs are completely
* replaced when CAs are explicitly specified using this option.
*/
ca?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Cert chains in PEM format. One cert chain should be provided per
* private key. Each cert chain should consist of the PEM formatted
* certificate for a provided private key, followed by the PEM
* formatted intermediate certificates (if any), in order, and not
* including the root CA (the root CA must be pre-known to the peer,
* see ca). When providing multiple cert chains, they do not have to
* be in the same order as their private keys in key. If the
* intermediate certificates are not provided, the peer will not be
* able to validate the certificate, and the handshake will fail.
*/
cert?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Private keys in PEM format. PEM allows the option of private keys
* being encrypted. Encrypted keys will be decrypted with
* options.passphrase. Multiple keys using different algorithms can be
* provided either as an array of unencrypted key strings or buffers,
* or an array of objects in the form `{pem: <string|buffer>[,passphrase: <string>]}`.
* The object form can only occur in an array.object.passphrase is optional.
* Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
*/
key?: string | Buffer | Array<Buffer | KeyObject> | undefined;
/**
* Shared passphrase used for a single private key and/or a PFX.
*/
passphrase?: string | undefined;
/**
* PFX or PKCS12 encoded private key and certificate chain. pfx is an
* alternative to providing key and cert individually. PFX is usually
* encrypted, if it is, passphrase will be used to decrypt it. Multiple
* PFX can be provided either as an array of unencrypted PFX buffers,
* or an array of objects in the form `{buf: <string|buffer>[,passphrase: <string>]}`.
* The object form can only occur in an array.object.passphrase is optional.
* Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
*/
pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;
}
/**
* Represents a certificate for TLS authentication.
*/
export interface TlsSettings {
/**
* Optionally override the trusted CA certificates. Default is to trust
* the well-known CAs curated by Mozilla. Mozilla's CAs are completely
* replaced when CAs are explicitly specified using this option.
*/
ca?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Cert chains in PEM format. One cert chain should be provided per
* private key. Each cert chain should consist of the PEM formatted
* certificate for a provided private key, followed by the PEM
* formatted intermediate certificates (if any), in order, and not
* including the root CA (the root CA must be pre-known to the peer,
* see ca). When providing multiple cert chains, they do not have to
* be in the same order as their private keys in key. If the
* intermediate certificates are not provided, the peer will not be
* able to validate the certificate, and the handshake will fail.
*/
cert?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Private keys in PEM format. PEM allows the option of private keys
* being encrypted. Encrypted keys will be decrypted with
* options.passphrase. Multiple keys using different algorithms can be
* provided either as an array of unencrypted key strings or buffers,
* or an array of objects in the form `{pem: <string|buffer>[,passphrase: <string>]}`.
* The object form can only occur in an array.object.passphrase is optional.
* Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
*/
key?: string | Buffer | Array<Buffer | KeyObject> | undefined;
/**
* Shared passphrase used for a single private key and/or a PFX.
*/
passphrase?: string | undefined;
/**
* PFX or PKCS12 encoded private key and certificate chain. pfx is an
* alternative to providing key and cert individually. PFX is usually
* encrypted, if it is, passphrase will be used to decrypt it. Multiple
* PFX can be provided either as an array of unencrypted PFX buffers,
* or an array of objects in the form `{buf: <string|buffer>[,passphrase: <string>]}`.
* The object form can only occur in an array.object.passphrase is optional.
* Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
*/
pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;
}
/**
* An interface compatible with NodeJS's `tls.KeyObject`.
* We want to avoid publicly re-exporting the actual interface,
* since it might vary across runtime versions.
*/
export interface KeyObject {
/**
* Private keys in PEM format.
*/
pem: string | Buffer;
/**
* Optional passphrase.
*/
passphrase?: string | undefined;
}
/**
* An interface compatible with NodeJS's `tls.PxfObject`.
* We want to avoid publicly re-exporting the actual interface,
* since it might vary across runtime versions.
*/
export interface PxfObject {
/**
* PFX or PKCS12 encoded private key and certificate chain.
*/
buf: string | Buffer;
/**
* Optional passphrase.
*/
passphrase?: string | undefined;
}
//# sourceMappingURL=interfaces.d.ts.map
+4
View File
@@ -0,0 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export {};
//# sourceMappingURL=interfaces.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/interfaces.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport type { OperationTracingOptions } from \"@azure/core-tracing\";\nimport type { HttpMethods } from \"@azure/core-util\";\n\n/**\n * A HttpHeaders collection represented as a simple JSON object.\n */\nexport type RawHttpHeaders = { [headerName: string]: string };\n\n/**\n * A HttpHeaders collection for input, represented as a simple JSON object.\n */\nexport type RawHttpHeadersInput = Record<string, string | number | boolean>;\n\n/**\n * Represents a set of HTTP headers on a request/response.\n * Header names are treated as case insensitive.\n */\nexport interface HttpHeaders extends Iterable<[string, string]> {\n /**\n * Returns the value of a specific header or undefined if not set.\n * @param name - The name of the header to retrieve.\n */\n get(name: string): string | undefined;\n /**\n * Returns true if the specified header exists.\n * @param name - The name of the header to check.\n */\n has(name: string): boolean;\n /**\n * Sets a specific header with a given value.\n * @param name - The name of the header to set.\n * @param value - The value to use for the header.\n */\n set(name: string, value: string | number | boolean): void;\n /**\n * Removes a specific header from the collection.\n * @param name - The name of the header to delete.\n */\n delete(name: string): void;\n /**\n * Accesses a raw JS object that acts as a simple map\n * of header names to values.\n */\n toJSON(options?: { preserveCase?: boolean }): RawHttpHeaders;\n}\n\n/**\n * A part of the request body in a multipart request.\n */\nexport interface BodyPart {\n /**\n * The headers for this part of the multipart request.\n */\n headers: HttpHeaders;\n\n /**\n * The body of this part of the multipart request.\n */\n body:\n | ((() => ReadableStream<Uint8Array>) | (() => NodeJS.ReadableStream))\n | ReadableStream<Uint8Array>\n | NodeJS.ReadableStream\n | Uint8Array\n | Blob;\n}\n\n/**\n * A request body consisting of multiple parts.\n */\nexport interface MultipartRequestBody {\n /**\n * The parts of the request body.\n */\n parts: BodyPart[];\n\n /**\n * The boundary separating each part of the request body.\n * If not specified, a random boundary will be generated.\n *\n * When specified, '--' will be prepended to the boundary in the request to ensure the boundary follows the specification.\n */\n boundary?: string;\n}\n\n/**\n * Types of bodies supported on the request.\n * NodeJS.ReadableStream and () =\\> NodeJS.ReadableStream is Node only.\n * Blob, ReadableStream<Uint8Array>, and () =\\> ReadableStream<Uint8Array> are browser only.\n */\nexport type RequestBodyType =\n | NodeJS.ReadableStream\n | (() => NodeJS.ReadableStream)\n | ReadableStream<Uint8Array>\n | (() => ReadableStream<Uint8Array>)\n | Blob\n | ArrayBuffer\n | ArrayBufferView\n | FormData\n | string\n | null;\n\n/**\n * An interface compatible with NodeJS's `http.Agent`.\n * We want to avoid publicly re-exporting the actual interface,\n * since it might vary across runtime versions.\n */\nexport interface Agent {\n /**\n * Destroy any sockets that are currently in use by the agent.\n */\n destroy(): void;\n /**\n * For agents with keepAlive enabled, this sets the maximum number of sockets that will be left open in the free state.\n */\n maxFreeSockets: number;\n /**\n * Determines how many concurrent sockets the agent can have open per origin.\n */\n maxSockets: number;\n /**\n * An object which contains queues of requests that have not yet been assigned to sockets.\n */\n requests: unknown;\n /**\n * An object which contains arrays of sockets currently in use by the agent.\n */\n sockets: unknown;\n}\n\n/**\n * Metadata about a request being made by the pipeline.\n */\nexport interface PipelineRequest {\n /**\n * The URL to make the request to.\n */\n url: string;\n\n /**\n * The HTTP method to use when making the request.\n */\n method: HttpMethods;\n\n /**\n * The HTTP headers to use when making the request.\n */\n headers: HttpHeaders;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n * If the request is terminated, an `AbortError` is thrown.\n * Defaults to 0, which disables the timeout.\n */\n timeout: number;\n\n /**\n * Indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests.\n * Defaults to false.\n */\n withCredentials: boolean;\n\n /**\n * A unique identifier for the request. Used for logging and tracing.\n */\n requestId: string;\n\n /**\n * The HTTP body content (if any)\n */\nLine truncated
+2
View File
@@ -0,0 +1,2 @@
export declare const logger: import("@azure/logger").AzureLogger;
//# sourceMappingURL=log.d.ts.map
+5
View File
@@ -0,0 +1,5 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createClientLogger } from "@azure/logger";
export const logger = createClientLogger("core-rest-pipeline");
//# sourceMappingURL=log.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"log.js","sourceRoot":"","sources":["../../src/log.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACnD,MAAM,CAAC,MAAM,MAAM,GAAG,kBAAkB,CAAC,oBAAoB,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { createClientLogger } from \"@azure/logger\";\nexport const logger = createClientLogger(\"core-rest-pipeline\");\n"]}
+9
View File
@@ -0,0 +1,9 @@
import type { HttpClient, RequestBodyType } from "./interfaces.js";
/** @internal */
export declare function getBodyLength(body: RequestBodyType): number | null;
/**
* Create a new HttpClient instance for the NodeJS environment.
* @internal
*/
export declare function createNodeHttpClient(): HttpClient;
//# sourceMappingURL=nodeHttpClient.d.ts.map
+348
View File
@@ -0,0 +1,348 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import * as http from "node:http";
import * as https from "node:https";
import * as zlib from "node:zlib";
import { Transform } from "node:stream";
import { AbortError } from "@azure/abort-controller";
import { createHttpHeaders } from "./httpHeaders.js";
import { RestError } from "./restError.js";
import { logger } from "./log.js";
import { Sanitizer } from "./util/sanitizer.js";
const DEFAULT_TLS_SETTINGS = {};
function isReadableStream(body) {
return body && typeof body.pipe === "function";
}
function isStreamComplete(stream) {
if (stream.readable === false) {
return Promise.resolve();
}
return new Promise((resolve) => {
const handler = () => {
resolve();
stream.removeListener("close", handler);
stream.removeListener("end", handler);
stream.removeListener("error", handler);
};
stream.on("close", handler);
stream.on("end", handler);
stream.on("error", handler);
});
}
function isArrayBuffer(body) {
return body && typeof body.byteLength === "number";
}
class ReportTransform extends Transform {
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
_transform(chunk, _encoding, callback) {
this.push(chunk);
this.loadedBytes += chunk.length;
try {
this.progressCallback({ loadedBytes: this.loadedBytes });
callback();
}
catch (e) {
callback(e);
}
}
constructor(progressCallback) {
super();
this.loadedBytes = 0;
this.progressCallback = progressCallback;
}
}
/**
* A HttpClient implementation that uses Node's "https" module to send HTTPS requests.
* @internal
*/
class NodeHttpClient {
constructor() {
this.cachedHttpsAgents = new WeakMap();
}
/**
* Makes a request over an underlying transport layer and returns the response.
* @param request - The request to be made.
*/
async sendRequest(request) {
var _a, _b, _c;
const abortController = new AbortController();
let abortListener;
if (request.abortSignal) {
if (request.abortSignal.aborted) {
throw new AbortError("The operation was aborted. Request has already been canceled.");
}
abortListener = (event) => {
if (event.type === "abort") {
abortController.abort();
}
};
request.abortSignal.addEventListener("abort", abortListener);
}
let timeoutId;
if (request.timeout > 0) {
timeoutId = setTimeout(() => {
const sanitizer = new Sanitizer();
logger.info(`request to '${sanitizer.sanitizeUrl(request.url)}' timed out. canceling...`);
abortController.abort();
}, request.timeout);
}
const acceptEncoding = request.headers.get("Accept-Encoding");
const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
let body = typeof request.body === "function" ? request.body() : request.body;
if (body && !request.headers.has("Content-Length")) {
const bodyLength = getBodyLength(body);
if (bodyLength !== null) {
request.headers.set("Content-Length", bodyLength);
}
}
let responseStream;
try {
if (body && request.onUploadProgress) {
const onUploadProgress = request.onUploadProgress;
const uploadReportStream = new ReportTransform(onUploadProgress);
uploadReportStream.on("error", (e) => {
logger.error("Error in upload progress", e);
});
if (isReadableStream(body)) {
body.pipe(uploadReportStream);
}
else {
uploadReportStream.end(body);
}
body = uploadReportStream;
}
const res = await this.makeRequest(request, abortController, body);
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
const headers = getResponseHeaders(res);
const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
const response = {
status,
headers,
request,
};
// Responses to HEAD must not have a body.
// If they do return a body, that body must be ignored.
if (request.method === "HEAD") {
// call resume() and not destroy() to avoid closing the socket
// and losing keep alive
res.resume();
return response;
}
responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
const onDownloadProgress = request.onDownloadProgress;
if (onDownloadProgress) {
const downloadReportStream = new ReportTransform(onDownloadProgress);
downloadReportStream.on("error", (e) => {
logger.error("Error in download progress", e);
});
responseStream.pipe(downloadReportStream);
responseStream = downloadReportStream;
}
if (
// Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) ||
((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) {
response.readableStreamBody = responseStream;
}
else {
response.bodyAsText = await streamToText(responseStream);
}
return response;
}
finally {
// clean up event listener
if (request.abortSignal && abortListener) {
let uploadStreamDone = Promise.resolve();
if (isReadableStream(body)) {
uploadStreamDone = isStreamComplete(body);
}
let downloadStreamDone = Promise.resolve();
if (isReadableStream(responseStream)) {
downloadStreamDone = isStreamComplete(responseStream);
}
Promise.all([uploadStreamDone, downloadStreamDone])
.then(() => {
var _a;
// eslint-disable-next-line promise/always-return
if (abortListener) {
(_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
}
})
.catch((e) => {
logger.warning("Error when cleaning up abortListener on httpRequest", e);
});
}
}
}
makeRequest(request, abortController, body) {
var _a;
const url = new URL(request.url);
const isInsecure = url.protocol !== "https:";
if (isInsecure && !request.allowInsecureConnection) {
throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
}
const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure);
const options = {
agent,
hostname: url.hostname,
path: `${url.pathname}${url.search}`,
port: url.port,
method: request.method,
headers: request.headers.toJSON({ preserveCase: true }),
};
return new Promise((resolve, reject) => {
const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve);
req.once("error", (err) => {
var _a;
reject(new RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : RestError.REQUEST_SEND_ERROR, request }));
});
abortController.signal.addEventListener("abort", () => {
const abortError = new AbortError("The operation was aborted. Rejecting from abort signal callback while making request.");
req.destroy(abortError);
reject(abortError);
});
if (body && isReadableStream(body)) {
body.pipe(req);
}
else if (body) {
if (typeof body === "string" || Buffer.isBuffer(body)) {
req.end(body);
}
else if (isArrayBuffer(body)) {
req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
}
else {
logger.error("Unrecognized body type", body);
reject(new RestError("Unrecognized body type"));
}
}
else {
// streams don't like "undefined" being passed as data
req.end();
}
});
}
getOrCreateAgent(request, isInsecure) {
var _a;
const disableKeepAlive = request.disableKeepAlive;
// Handle Insecure requests first
if (isInsecure) {
if (disableKeepAlive) {
// keepAlive:false is the default so we don't need a custom Agent
return http.globalAgent;
}
if (!this.cachedHttpAgent) {
// If there is no cached agent create a new one and cache it.
this.cachedHttpAgent = new http.Agent({ keepAlive: true });
}
return this.cachedHttpAgent;
}
else {
if (disableKeepAlive && !request.tlsSettings) {
// When there are no tlsSettings and keepAlive is false
// we don't need a custom agent
return https.globalAgent;
}
// We use the tlsSettings to index cached clients
const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS;
// Get the cached agent or create a new one with the
// provided values for keepAlive and tlsSettings
let agent = this.cachedHttpsAgents.get(tlsSettings);
if (agent && agent.options.keepAlive === !disableKeepAlive) {
return agent;
}
logger.info("No cached TLS Agent exist, creating a new Agent");
agent = new https.Agent(Object.assign({
// keepAlive is true if disableKeepAlive is false.
keepAlive: !disableKeepAlive }, tlsSettings));
this.cachedHttpsAgents.set(tlsSettings, agent);
return agent;
}
}
}
function getResponseHeaders(res) {
const headers = createHttpHeaders();
for (const header of Object.keys(res.headers)) {
const value = res.headers[header];
if (Array.isArray(value)) {
if (value.length > 0) {
headers.set(header, value[0]);
}
}
else if (value) {
headers.set(header, value);
}
}
return headers;
}
function getDecodedResponseStream(stream, headers) {
const contentEncoding = headers.get("Content-Encoding");
if (contentEncoding === "gzip") {
const unzip = zlib.createGunzip();
stream.pipe(unzip);
return unzip;
}
else if (contentEncoding === "deflate") {
const inflate = zlib.createInflate();
stream.pipe(inflate);
return inflate;
}
return stream;
}
function streamToText(stream) {
return new Promise((resolve, reject) => {
const buffer = [];
stream.on("data", (chunk) => {
if (Buffer.isBuffer(chunk)) {
buffer.push(chunk);
}
else {
buffer.push(Buffer.from(chunk));
}
});
stream.on("end", () => {
resolve(Buffer.concat(buffer).toString("utf8"));
});
stream.on("error", (e) => {
if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") {
reject(e);
}
else {
reject(new RestError(`Error reading response as text: ${e.message}`, {
code: RestError.PARSE_ERROR,
}));
}
});
});
}
/** @internal */
export function getBodyLength(body) {
if (!body) {
return 0;
}
else if (Buffer.isBuffer(body)) {
return body.length;
}
else if (isReadableStream(body)) {
return null;
}
else if (isArrayBuffer(body)) {
return body.byteLength;
}
else if (typeof body === "string") {
return Buffer.from(body).length;
}
else {
return null;
}
}
/**
* Create a new HttpClient instance for the NodeJS environment.
* @internal
*/
export function createNodeHttpClient() {
return new NodeHttpClient();
}
//# sourceMappingURL=nodeHttpClient.js.map
@@ -0,0 +1 @@
{"version":3,"file":"nodeHttpClient.js","sourceRoot":"","sources":["../../src/nodeHttpClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO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E,oBAAoB,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;oBACrC,MAAM,CAAC,KAAK,CAAC,4BAA4B,EAAE,CAAC,CAAC,CAAC;gBAChD,CAAC,CAAC,CAAC;gBACH,cAAc,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;gBAC1C,cAAc,GAAG,oBAAoB,CAAC;YACxC,CAAC;YAED;YACE,2FAA2F;YAC3F,CAAA,MAAA,OAAO,CAAC,yBAAyB,0CAAE,GAAG,CAAC,MAAM,CAAC,iBAAiB,CAAC;iBAChE,MAAA,OAAO,CAAC,yBAAyB,0CAAE,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA,EACvD,CAAC;gBACD,QAAQ,CAAC,kBAAkB,GAAG,cAAc,CAAC;YAC/C,CAAC;iBAAM,CAAC;gBACN,QAAQ,CAAC,UAAU,GAAG,MAAM,YAAY,CAAC,cAAc,CAAC,CAAC;YAC3D,CAAC;YAED,OAAO,QAAQ,CAAC;Line truncated
+3
View File
@@ -0,0 +1,3 @@
{
"type": "module"
}
+93
View File
@@ -0,0 +1,93 @@
import type { HttpClient, PipelineRequest, PipelineResponse, SendRequest } from "./interfaces.js";
/**
* Policies are executed in phases.
* The execution order is:
* 1. Serialize Phase
* 2. Policies not in a phase
* 3. Deserialize Phase
* 4. Retry Phase
* 5. Sign Phase
*/
export type PipelinePhase = "Deserialize" | "Serialize" | "Retry" | "Sign";
/**
* Options when adding a policy to the pipeline.
* Used to express dependencies on other policies.
*/
export interface AddPolicyOptions {
/**
* Policies that this policy must come before.
*/
beforePolicies?: string[];
/**
* Policies that this policy must come after.
*/
afterPolicies?: string[];
/**
* The phase that this policy must come after.
*/
afterPhase?: PipelinePhase;
/**
* The phase this policy belongs to.
*/
phase?: PipelinePhase;
}
/**
* A pipeline policy manipulates a request as it travels through the pipeline.
* It is conceptually a middleware that is allowed to modify the request before
* it is made as well as the response when it is received.
*/
export interface PipelinePolicy {
/**
* The policy name. Must be a unique string in the pipeline.
*/
name: string;
/**
* The main method to implement that manipulates a request/response.
* @param request - The request being performed.
* @param next - The next policy in the pipeline. Must be called to continue the pipeline.
*/
sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse>;
}
/**
* Represents a pipeline for making a HTTP request to a URL.
* Pipelines can have multiple policies to manage manipulating each request
* before and after it is made to the server.
*/
export interface Pipeline {
/**
* Add a new policy to the pipeline.
* @param policy - A policy that manipulates a request.
* @param options - A set of options for when the policy should run.
*/
addPolicy(policy: PipelinePolicy, options?: AddPolicyOptions): void;
/**
* Remove a policy from the pipeline.
* @param options - Options that let you specify which policies to remove.
*/
removePolicy(options: {
name?: string;
phase?: PipelinePhase;
}): PipelinePolicy[];
/**
* Uses the pipeline to make a HTTP request.
* @param httpClient - The HttpClient that actually performs the request.
* @param request - The request to be made.
*/
sendRequest(httpClient: HttpClient, request: PipelineRequest): Promise<PipelineResponse>;
/**
* Returns the current set of policies in the pipeline in the order in which
* they will be applied to the request. Later in the list is closer to when
* the request is performed.
*/
getOrderedPolicies(): PipelinePolicy[];
/**
* Duplicates this pipeline to allow for modifying an existing one without mutating it.
*/
clone(): Pipeline;
}
/**
* Creates a totally empty pipeline.
* Useful for testing or creating a custom one.
*/
export declare function createEmptyPipeline(): Pipeline;
//# sourceMappingURL=pipeline.d.ts.map
+262
View File
@@ -0,0 +1,262 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
/**
* A private implementation of Pipeline.
* Do not export this class from the package.
* @internal
*/
class HttpPipeline {
constructor(policies) {
var _a;
this._policies = [];
this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : [];
this._orderedPolicies = undefined;
}
addPolicy(policy, options = {}) {
if (options.phase && options.afterPhase) {
throw new Error("Policies inside a phase cannot specify afterPhase.");
}
if (options.phase && !ValidPhaseNames.has(options.phase)) {
throw new Error(`Invalid phase name: ${options.phase}`);
}
if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
}
this._policies.push({
policy,
options,
});
this._orderedPolicies = undefined;
}
removePolicy(options) {
const removedPolicies = [];
this._policies = this._policies.filter((policyDescriptor) => {
if ((options.name && policyDescriptor.policy.name === options.name) ||
(options.phase && policyDescriptor.options.phase === options.phase)) {
removedPolicies.push(policyDescriptor.policy);
return false;
}
else {
return true;
}
});
this._orderedPolicies = undefined;
return removedPolicies;
}
sendRequest(httpClient, request) {
const policies = this.getOrderedPolicies();
const pipeline = policies.reduceRight((next, policy) => {
return (req) => {
return policy.sendRequest(req, next);
};
}, (req) => httpClient.sendRequest(req));
return pipeline(request);
}
getOrderedPolicies() {
if (!this._orderedPolicies) {
this._orderedPolicies = this.orderPolicies();
}
return this._orderedPolicies;
}
clone() {
return new HttpPipeline(this._policies);
}
static create() {
return new HttpPipeline();
}
orderPolicies() {
/**
* The goal of this method is to reliably order pipeline policies
* based on their declared requirements when they were added.
*
* Order is first determined by phase:
*
* 1. Serialize Phase
* 2. Policies not in a phase
* 3. Deserialize Phase
* 4. Retry Phase
* 5. Sign Phase
*
* Within each phase, policies are executed in the order
* they were added unless they were specified to execute
* before/after other policies or after a particular phase.
*
* To determine the final order, we will walk the policy list
* in phase order multiple times until all dependencies are
* satisfied.
*
* `afterPolicies` are the set of policies that must be
* executed before a given policy. This requirement is
* considered satisfied when each of the listed policies
* have been scheduled.
*
* `beforePolicies` are the set of policies that must be
* executed after a given policy. Since this dependency
* can be expressed by converting it into a equivalent
* `afterPolicies` declarations, they are normalized
* into that form for simplicity.
*
* An `afterPhase` dependency is considered satisfied when all
* policies in that phase have scheduled.
*
*/
const result = [];
// Track all policies we know about.
const policyMap = new Map();
function createPhase(name) {
return {
name,
policies: new Set(),
hasRun: false,
hasAfterPolicies: false,
};
}
// Track policies for each phase.
const serializePhase = createPhase("Serialize");
const noPhase = createPhase("None");
const deserializePhase = createPhase("Deserialize");
const retryPhase = createPhase("Retry");
const signPhase = createPhase("Sign");
// a list of phases in order
const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
// Small helper function to map phase name to each Phase
function getPhase(phase) {
if (phase === "Retry") {
return retryPhase;
}
else if (phase === "Serialize") {
return serializePhase;
}
else if (phase === "Deserialize") {
return deserializePhase;
}
else if (phase === "Sign") {
return signPhase;
}
else {
return noPhase;
}
}
// First walk each policy and create a node to track metadata.
for (const descriptor of this._policies) {
const policy = descriptor.policy;
const options = descriptor.options;
const policyName = policy.name;
if (policyMap.has(policyName)) {
throw new Error("Duplicate policy names not allowed in pipeline");
}
const node = {
policy,
dependsOn: new Set(),
dependants: new Set(),
};
if (options.afterPhase) {
node.afterPhase = getPhase(options.afterPhase);
node.afterPhase.hasAfterPolicies = true;
}
policyMap.set(policyName, node);
const phase = getPhase(options.phase);
phase.policies.add(node);
}
// Now that each policy has a node, connect dependency references.
for (const descriptor of this._policies) {
const { policy, options } = descriptor;
const policyName = policy.name;
const node = policyMap.get(policyName);
if (!node) {
throw new Error(`Missing node for policy ${policyName}`);
}
if (options.afterPolicies) {
for (const afterPolicyName of options.afterPolicies) {
const afterNode = policyMap.get(afterPolicyName);
if (afterNode) {
// Linking in both directions helps later
// when we want to notify dependants.
node.dependsOn.add(afterNode);
afterNode.dependants.add(node);
}
}
}
if (options.beforePolicies) {
for (const beforePolicyName of options.beforePolicies) {
const beforeNode = policyMap.get(beforePolicyName);
if (beforeNode) {
// To execute before another node, make it
// depend on the current node.
beforeNode.dependsOn.add(node);
node.dependants.add(beforeNode);
}
}
}
}
function walkPhase(phase) {
phase.hasRun = true;
// Sets iterate in insertion order
for (const node of phase.policies) {
if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
// If this node is waiting on a phase to complete,
// we need to skip it for now.
// Even if the phase is empty, we should wait for it
// to be walked to avoid re-ordering policies.
continue;
}
if (node.dependsOn.size === 0) {
// If there's nothing else we're waiting for, we can
// add this policy to the result list.
result.push(node.policy);
// Notify anything that depends on this policy that
// the policy has been scheduled.
for (const dependant of node.dependants) {
dependant.dependsOn.delete(node);
}
policyMap.delete(node.policy.name);
phase.policies.delete(node);
}
}
}
function walkPhases() {
for (const phase of orderedPhases) {
walkPhase(phase);
// if the phase isn't complete
if (phase.policies.size > 0 && phase !== noPhase) {
if (!noPhase.hasRun) {
// Try running noPhase to see if that unblocks this phase next tick.
// This can happen if a phase that happens before noPhase
// is waiting on a noPhase policy to complete.
walkPhase(noPhase);
}
// Don't proceed to the next phase until this phase finishes.
return;
}
if (phase.hasAfterPolicies) {
// Run any policies unblocked by this phase
walkPhase(noPhase);
}
}
}
// Iterate until we've put every node in the result list.
let iteration = 0;
while (policyMap.size > 0) {
iteration++;
const initialResultLength = result.length;
// Keep walking each phase in order until we can order every node.
walkPhases();
// The result list *should* get at least one larger each time
// after the first full pass.
// Otherwise, we're going to loop forever.
if (result.length <= initialResultLength && iteration > 1) {
throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
}
}
return result;
}
}
/**
* Creates a totally empty pipeline.
* Useful for testing or creating a custom one.
*/
export function createEmptyPipeline() {
return HttpPipeline.create();
}
//# sourceMappingURL=pipeline.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/pipeline.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAelC,MAAM,eAAe,GAAG,IAAI,GAAG,CAAgB,CAAC,aAAa,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;AAiG9F;;;;GAIG;AACH,MAAM,YAAY;IAIhB,YAAoB,QAA+B;;QAH3C,cAAS,GAAyB,EAAE,CAAC;QAI3C,IAAI,CAAC,SAAS,GAAG,MAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,KAAK,CAAC,CAAC,CAAC,mCAAI,EAAE,CAAC;QAC1C,IAAI,CAAC,gBAAgB,GAA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ACH,CAAC;YACD,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;gBAC3B,KAAK,MAAM,gBAAgB,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;oBACtD,MAAM,UAAU,GAAG,SAAS,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;oBACnD,IAAI,UAAU,EAAE,CAAC;wBACf,0CAA0C;wBAC1C,8BAA8B;wBAC9B,UAAU,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;wBAC/B,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;oBAClC,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAED,SAAS,SAAS,CAAC,KAAY;YAC7B,KAAK,CAAC,Line truncated
+105
View File
@@ -0,0 +1,105 @@
import type { Agent, FormDataMap, HttpHeaders, MultipartRequestBody, PipelineRequest, ProxySettings, RequestBodyType, TlsSettings, TransferProgressEvent } from "./interfaces.js";
import type { AbortSignalLike } from "@azure/abort-controller";
import type { OperationTracingOptions } from "@azure/core-tracing";
import type { HttpMethods } from "@azure/core-util";
/**
* Settings to initialize a request.
* Almost equivalent to Partial<PipelineRequest>, but url is mandatory.
*/
export interface PipelineRequestOptions {
/**
* The URL to make the request to.
*/
url: string;
/**
* The HTTP method to use when making the request.
*/
method?: HttpMethods;
/**
* The HTTP headers to use when making the request.
*/
headers?: HttpHeaders;
/**
* The number of milliseconds a request can take before automatically being terminated.
* If the request is terminated, an `AbortError` is thrown.
* Defaults to 0, which disables the timeout.
*/
timeout?: number;
/**
* If credentials (cookies) should be sent along during an XHR.
* Defaults to false.
*/
withCredentials?: boolean;
/**
* A unique identifier for the request. Used for logging and tracing.
*/
requestId?: string;
/**
* The HTTP body content (if any)
*/
body?: RequestBodyType;
/**
* Body for a multipart request.
*/
multipartBody?: MultipartRequestBody;
/**
* To simulate a browser form post
*/
formData?: FormDataMap;
/**
* A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.
*/
streamResponseStatusCodes?: Set<number>;
/**
* NODEJS ONLY
*
* A Node-only option to provide a custom `http.Agent`/`https.Agent`.
* NOTE: usually this should be one instance shared by multiple requests so that the underlying
* connection to the service can be reused.
* Does nothing when running in the browser.
*/
agent?: Agent;
/**
* BROWSER ONLY
*
* A browser only option to enable use of the Streams API. If this option is set and streaming is used
* (see `streamResponseStatusCodes`), the response will have a property `browserStream` instead of
* `blobBody` which will be undefined.
*
* Default value is false
*/
enableBrowserStreams?: boolean;
/** Settings for configuring TLS authentication */
tlsSettings?: TlsSettings;
/**
* Proxy configuration.
*/
proxySettings?: ProxySettings;
/**
* If the connection should not be reused.
*/
disableKeepAlive?: boolean;
/**
* Used to abort the request later.
*/
abortSignal?: AbortSignalLike;
/**
* Options used to create a span when tracing is enabled.
*/
tracingOptions?: OperationTracingOptions;
/**
* Callback which fires upon upload progress.
*/
onUploadProgress?: (progress: TransferProgressEvent) => void;
/** Callback which fires upon download progress. */
onDownloadProgress?: (progress: TransferProgressEvent) => void;
/** Set to true if the request is sent over HTTP instead of HTTPS */
allowInsecureConnection?: boolean;
}
/**
* Creates a new pipeline request with the given options.
* This method is to allow for the easy setting of default values and not required.
* @param options - The options to create the request with.
*/
export declare function createPipelineRequest(options: PipelineRequestOptions): PipelineRequest;
//# sourceMappingURL=pipelineRequest.d.ts.map
+38
View File
@@ -0,0 +1,38 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createHttpHeaders } from "./httpHeaders.js";
import { randomUUID } from "@azure/core-util";
class PipelineRequestImpl {
constructor(options) {
var _a, _b, _c, _d, _e, _f, _g;
this.url = options.url;
this.body = options.body;
this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : createHttpHeaders();
this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET";
this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0;
this.multipartBody = options.multipartBody;
this.formData = options.formData;
this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false;
this.proxySettings = options.proxySettings;
this.streamResponseStatusCodes = options.streamResponseStatusCodes;
this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false;
this.abortSignal = options.abortSignal;
this.tracingOptions = options.tracingOptions;
this.onUploadProgress = options.onUploadProgress;
this.onDownloadProgress = options.onDownloadProgress;
this.requestId = options.requestId || randomUUID();
this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false;
this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false;
this.agent = options.agent;
this.tlsSettings = options.tlsSettings;
}
}
/**
* Creates a new pipeline request with the given options.
* This method is to allow for the easy setting of default values and not required.
* @param options - The options to create the request with.
*/
export function createPipelineRequest(options) {
return new PipelineRequestImpl(options);
}
//# sourceMappingURL=pipelineRequest.js.map
@@ -0,0 +1 @@
{"version":3,"file":"pipelineRequest.js","sourceRoot":"","sources":["../../src/pipelineRequest.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAalC,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAsH9C,MAAM,mBAAmB;IAsBvB,YAAY,OAA+B;;QACzC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,MAAA,OAAO,CAAC,OAAO,mCAAI,iBAAiB,EAAE,CAAC;QACtD,IAAI,CAAC,MAAM,GAAG,MAAA,OAAO,CAAC,MAAM,mCAAI,KAAK,CAAC;QACtC,IAAI,CAAC,OAAO,GAAG,MAAA,OAAO,CAAC,OAAO,mCAAI,CAAC,CAAC;QACpC,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,MAAA,OAAO,CAAC,gBAAgB,mCAAI,KAAK,CAAC;QAC1D,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC;QACnE,IAAI,CAAC,eAAe,GAAG,MAAA,OAAO,CAAC,eAAe,mCAAI,KAAK,CAAC;QACxD,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;QAC7C,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;QACjD,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACrD,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,UAAU,EAAE,CAAC;QACnD,IAAI,CAAC,uBAAuB,GAAG,MAAA,OAAO,CAAC,uBAAuB,mCAAI,KAAK,CAAC;QACxE,IAAI,CAAC,oBAAoB,GAAG,MAAA,OAAO,CAAC,oBAAoB,mCAAI,KAAK,CAAC;QAClE,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;IACzC,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,UAAU,qBAAqB,CAAC,OAA+B;IACnE,OAAO,IAAI,mBAAmB,CAAC,OAAO,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n Agent,\n FormDataMap,\n HttpHeaders,\n MultipartRequestBody,\n PipelineRequest,\n ProxySettings,\n RequestBodyType,\n TlsSettings,\n TransferProgressEvent,\n} from \"./interfaces.js\";\nimport { createHttpHeaders } from \"./httpHeaders.js\";\nimport type { AbortSignalLike } from \"@azure/abort-controller\";\nimport { randomUUID } from \"@azure/core-util\";\nimport type { OperationTracingOptions } from \"@azure/core-tracing\";\nimport type { HttpMethods } from \"@azure/core-util\";\n\n/**\n * Settings to initialize a request.\n * Almost equivalent to Partial<PipelineRequest>, but url is mandatory.\n */\nexport interface PipelineRequestOptions {\n /**\n * The URL to make the request to.\n */\n url: string;\n\n /**\n * The HTTP method to use when making the request.\n */\n method?: HttpMethods;\n\n /**\n * The HTTP headers to use when making the request.\n */\n headers?: HttpHeaders;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n * If the request is terminated, an `AbortError` is thrown.\n * Defaults to 0, which disables the timeout.\n */\n timeout?: number;\n\n /**\n * If credentials (cookies) should be sent along during an XHR.\n * Defaults to false.\n */\n withCredentials?: boolean;\n\n /**\n * A unique identifier for the request. Used for logging and tracing.\n */\n requestId?: string;\n\n /**\n * The HTTP body content (if any)\n */\n body?: RequestBodyType;\n\n /**\n * Body for a multipart request.\n */\n multipartBody?: MultipartRequestBody;\n\n /**\n * To simulate a browser form post\n */\n formData?: FormDataMap;\n\n /**\n * A list of response status codes whose corresponding PipelineResponse body should be treated as a stream.\n */\n streamResponseStatusCodes?: Set<number>;\n\n /**\n * NODEJS ONLY\n *\n * A Node-only option to provide a custom `http.Agent`/`https.Agent`.\n * NOTE: usually this should be one instance shared by multiple requests so that the underlying\n * connection to the service can be reused.\n * Does nothing when running in the browser.\n */\n agent?: Agent;\n\n /**\n * BROWSER ONLY\n *\n * A browser only option to enable use of the Streams API. If this option is set and streaming is used\n * (see `streamResponseStatusCodes`), the response will have a property `browserStream` instead of\n * `blobBody` which will be undefined.\n *\n * Default value is false\n */\n enableBrowserStreams?: boolean;\n\n /** Settings for configuring TLS authentication */\n tlsSettings?: TlsSettings;\n\n /**\n * Proxy configuration.\n */\n proxySettings?: ProxySettings;\n\n /**\n * If the connection should not be reused.\n */\n disableKeepAlive?: boolean;\n\n /**\n * Used to abort the request later.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * Options used to create a span when tracing is enabled.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Callback which fires upon download progress. */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Set to true if the request is sent over HTTP instead of HTTPS */\n allowInsecureConnection?: boolean;\n}\n\nclass PipelineRequestImpl implements PipelineRequLine truncated
@@ -0,0 +1,11 @@
import type { PipelinePolicy } from "../pipeline.js";
import type { Agent } from "../interfaces.js";
/**
* Name of the Agent Policy
*/
export declare const agentPolicyName = "agentPolicy";
/**
* Gets a pipeline policy that sets http.agent
*/
export declare function agentPolicy(agent?: Agent): PipelinePolicy;
//# sourceMappingURL=agentPolicy.d.ts.map
@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* Name of the Agent Policy
*/
export const agentPolicyName = "agentPolicy";
/**
* Gets a pipeline policy that sets http.agent
*/
export function agentPolicy(agent) {
return {
name: agentPolicyName,
sendRequest: async (req, next) => {
// Users may define an agent on the request, honor it over the client level one
if (!req.agent) {
req.agent = agent;
}
return next(req);
},
};
}
//# sourceMappingURL=agentPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"agentPolicy.js","sourceRoot":"","sources":["../../../src/policies/agentPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,aAAa,CAAC;AAE7C;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa;IACvC,OAAO;QACL,IAAI,EAAE,eAAe;QACrB,WAAW,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;YAC/B,+EAA+E;YAC/E,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;gBACf,GAAG,CAAC,KAAK,GAAG,KAAK,CAAC;YACpB,CAAC;YACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport type { Agent } from \"../interfaces.js\";\n\n/**\n * Name of the Agent Policy\n */\nexport const agentPolicyName = \"agentPolicy\";\n\n/**\n * Gets a pipeline policy that sets http.agent\n */\nexport function agentPolicy(agent?: Agent): PipelinePolicy {\n return {\n name: agentPolicyName,\n sendRequest: async (req, next) => {\n // Users may define an agent on the request, honor it over the client level one\n if (!req.agent) {\n req.agent = agent;\n }\n return next(req);\n },\n };\n}\n"]}
@@ -0,0 +1,33 @@
import type { TokenCredential } from "@azure/core-auth";
import type { AzureLogger } from "@azure/logger";
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
*/
export declare const auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
/**
* Options to configure the auxiliaryAuthenticationHeaderPolicy
*/
export interface AuxiliaryAuthenticationHeaderPolicyOptions {
/**
* TokenCredential list used to get token from auxiliary tenants and
* one credential for each tenant the client may need to access
*/
credentials?: TokenCredential[];
/**
* Scopes depend on the cloud your application runs in
*/
scopes: string | string[];
/**
* A logger can be sent for debugging purposes.
*/
logger?: AzureLogger;
}
/**
* A policy for external tokens to `x-ms-authorization-auxiliary` header.
* This header will be used when creating a cross-tenant application we may need to handle authentication requests
* for resources that are in different tenants.
* You could see [ARM docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
*/
export declare function auxiliaryAuthenticationHeaderPolicy(options: AuxiliaryAuthenticationHeaderPolicyOptions): PipelinePolicy;
//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.d.ts.map
@@ -0,0 +1,63 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createTokenCycler } from "../util/tokenCycler.js";
import { logger as coreLogger } from "../log.js";
/**
* The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
*/
export const auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
async function sendAuthorizeRequest(options) {
var _a, _b;
const { scopes, getAccessToken, request } = options;
const getTokenOptions = {
abortSignal: request.abortSignal,
tracingOptions: request.tracingOptions,
};
return (_b = (_a = (await getAccessToken(scopes, getTokenOptions))) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : "";
}
/**
* A policy for external tokens to `x-ms-authorization-auxiliary` header.
* This header will be used when creating a cross-tenant application we may need to handle authentication requests
* for resources that are in different tenants.
* You could see [ARM docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
*/
export function auxiliaryAuthenticationHeaderPolicy(options) {
const { credentials, scopes } = options;
const logger = options.logger || coreLogger;
const tokenCyclerMap = new WeakMap();
return {
name: auxiliaryAuthenticationHeaderPolicyName,
async sendRequest(request, next) {
if (!request.url.toLowerCase().startsWith("https://")) {
throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
}
if (!credentials || credentials.length === 0) {
logger.info(`${auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
return next(request);
}
const tokenPromises = [];
for (const credential of credentials) {
let getAccessToken = tokenCyclerMap.get(credential);
if (!getAccessToken) {
getAccessToken = createTokenCycler(credential);
tokenCyclerMap.set(credential, getAccessToken);
}
tokenPromises.push(sendAuthorizeRequest({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
getAccessToken,
logger,
}));
}
const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
if (auxiliaryTokens.length === 0) {
logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
return next(request);
}
request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
return next(request);
},
};
}
//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"auxiliaryAuthenticationHeaderPolicy.js","sourceRoot":"","sources":["../../../src/policies/auxiliaryAuthenticationHeaderPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAA0B,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AACnF,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,WAAW,CAAC;AAGjD;;GAEG;AACH,MAAM,CAAC,MAAM,uCAAuC,GAAG,qCAAqC,CAAC;AAC7F,MAAM,8BAA8B,GAAG,8BAA8B,CAAC;AAqBtE,KAAK,UAAU,oBAAoB,CAAC,OAAgC;;IAClE,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACpD,MAAM,eAAe,GAAoB;QACvC,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,cAAc,EAAE,OAAO,CAAC,cAAc;KACvC,CAAC;IAEF,OAAO,MAAA,MAAA,CAAC,MAAM,cAAc,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC,0CAAE,KAAK,mCAAI,EAAE,CAAC;AACtE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mCAAmC,CACjD,OAAmD;IAEnD,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IACxC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,UAAU,CAAC;IAC5C,MAAM,cAAc,GAAG,IAAI,OAAO,EAAsC,CAAC;IAEzE,OAAO;QACL,IAAI,EAAE,uCAAuC;QAC7C,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;gBACtD,MAAM,IAAI,KAAK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UAAU,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7D,CAAC;YAEF,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 type { GetTokenOptions, TokenCredential } from \"@azure/core-auth\";\nimport type { AzureLogger } from \"@azure/logger\";\nimport type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { type AccessTokenGetter, createTokenCycler } from \"../util/tokenCycler.js\";\nimport { logger as coreLogger } from \"../log.js\";\nimport type { AuthorizeRequestOptions } from \"./bearerTokenAuthenticationPolicy.js\";\n\n/**\n * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.\n */\nexport const auxiliaryAuthenticationHeaderPolicyName = \"auxiliaryAuthenticationHeaderPolicy\";\nconst AUTHORIZATION_AUXILIARY_HEADER = \"x-ms-authorization-auxiliary\";\n\n/**\n * Options to configure the auxiliaryAuthenticationHeaderPolicy\n */\nexport interface AuxiliaryAuthenticationHeaderPolicyOptions {\n /**\n * TokenCredential list used to get token from auxiliary tenants and\n * one credential for each tenant the client may need to access\n */\n credentials?: TokenCredential[];\n /**\n * Scopes depend on the cloud your application runs in\n */\n scopes: string | string[];\n /**\n * A logger can be sent for debugging purposes.\n */\n logger?: AzureLogger;\n}\n\nasync function sendAuthorizeRequest(options: AuthorizeRequestOptions): Promise<string> {\n const { scopes, getAccessToken, request } = options;\n const getTokenOptions: GetTokenOptions = {\n abortSignal: request.abortSignal,\n tracingOptions: request.tracingOptions,\n };\n\n return (await getAccessToken(scopes, getTokenOptions))?.token ?? \"\";\n}\n\n/**\n * A policy for external tokens to `x-ms-authorization-auxiliary` header.\n * This header will be used when creating a cross-tenant application we may need to handle authentication requests\n * for resources that are in different tenants.\n * You could see [ARM docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works\n */\nexport function auxiliaryAuthenticationHeaderPolicy(\n options: AuxiliaryAuthenticationHeaderPolicyOptions,\n): PipelinePolicy {\n const { credentials, scopes } = options;\n const logger = options.logger || coreLogger;\n const tokenCyclerMap = new WeakMap<TokenCredential, AccessTokenGetter>();\n\n return {\n name: auxiliaryAuthenticationHeaderPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!request.url.toLowerCase().startsWith(\"https://\")) {\n throw new Error(\n \"Bearer token authentication for auxLine truncated
@@ -0,0 +1,117 @@
import type { AccessToken, GetTokenOptions, TokenCredential } from "@azure/core-auth";
import type { AzureLogger } from "@azure/logger";
import type { PipelineRequest, PipelineResponse } from "../interfaces.js";
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the bearerTokenAuthenticationPolicy.
*/
export declare const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
/**
* Options sent to the authorizeRequest callback
*/
export interface AuthorizeRequestOptions {
/**
* The scopes for which the bearer token applies.
*/
scopes: string[];
/**
* Function that retrieves either a cached access token or a new access token.
*/
getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise<AccessToken | null>;
/**
* Request that the policy is trying to fulfill.
*/
request: PipelineRequest;
/**
* A logger, if one was sent through the HTTP pipeline.
*/
logger?: AzureLogger;
}
/**
* Options sent to the authorizeRequestOnChallenge callback
*/
export interface AuthorizeRequestOnChallengeOptions {
/**
* The scopes for which the bearer token applies.
*/
scopes: string[];
/**
* Function that retrieves either a cached access token or a new access token.
*/
getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise<AccessToken | null>;
/**
* Request that the policy is trying to fulfill.
*/
request: PipelineRequest;
/**
* Response containing the challenge.
*/
response: PipelineResponse;
/**
* A logger, if one was sent through the HTTP pipeline.
*/
logger?: AzureLogger;
}
/**
* Options to override the processing of [Continuous Access Evaluation](https://learn.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.
*/
export interface ChallengeCallbacks {
/**
* Allows for the authorization of the main request of this policy before it's sent.
*/
authorizeRequest?(options: AuthorizeRequestOptions): Promise<void>;
/**
* Allows to handle authentication challenges and to re-authorize the request.
* The response containing the challenge is `options.response`.
* If this method returns true, the underlying request will be sent once again.
* The request may be modified before being sent.
*/
authorizeRequestOnChallenge?(options: AuthorizeRequestOnChallengeOptions): Promise<boolean>;
}
/**
* Options to configure the bearerTokenAuthenticationPolicy
*/
export interface BearerTokenAuthenticationPolicyOptions {
/**
* The TokenCredential implementation that can supply the bearer token.
*/
credential?: TokenCredential;
/**
* The scopes for which the bearer token applies.
*/
scopes: string | string[];
/**
* Allows for the processing of [Continuous Access Evaluation](https://learn.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.
* If provided, it must contain at least the `authorizeRequestOnChallenge` method.
* If provided, after a request is sent, if it has a challenge, it can be processed to re-send the original request with the relevant challenge information.
*/
challengeCallbacks?: ChallengeCallbacks;
/**
* A logger can be sent for debugging purposes.
*/
logger?: AzureLogger;
}
/**
* A policy that can request a token from a TokenCredential implementation and
* then apply it to the Authorization header of a request as a Bearer token.
*/
export declare function bearerTokenAuthenticationPolicy(options: BearerTokenAuthenticationPolicyOptions): PipelinePolicy;
/**
*
* Interface to represent a parsed challenge.
*
* @internal
*/
interface AuthChallenge {
scheme: string;
params: Record<string, string>;
}
/**
* Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
* Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
*
* @internal
*/
export declare function parseChallenges(challenges: string): AuthChallenge[];
export {};
//# sourceMappingURL=bearerTokenAuthenticationPolicy.d.ts.map
@@ -0,0 +1,238 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createTokenCycler } from "../util/tokenCycler.js";
import { logger as coreLogger } from "../log.js";
import { isRestError } from "../restError.js";
/**
* The programmatic identifier of the bearerTokenAuthenticationPolicy.
*/
export const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
/**
* Try to send the given request.
*
* When a response is received, returns a tuple of the response received and, if the response was received
* inside a thrown RestError, the RestError that was thrown.
*
* Otherwise, if an error was thrown while sending the request that did not provide an underlying response, it
* will be rethrown.
*/
async function trySendRequest(request, next) {
try {
return [await next(request), undefined];
}
catch (e) {
if (isRestError(e) && e.response) {
return [e.response, e];
}
else {
throw e;
}
}
}
/**
* Default authorize request handler
*/
async function defaultAuthorizeRequest(options) {
const { scopes, getAccessToken, request } = options;
// Enable CAE true by default
const getTokenOptions = {
abortSignal: request.abortSignal,
tracingOptions: request.tracingOptions,
enableCae: true,
};
const accessToken = await getAccessToken(scopes, getTokenOptions);
if (accessToken) {
options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
}
}
/**
* We will retrieve the challenge only if the response status code was 401,
* and if the response contained the header "WWW-Authenticate" with a non-empty value.
*/
function isChallengeResponse(response) {
return response.status === 401 && response.headers.has("WWW-Authenticate");
}
/**
* Re-authorize the request for CAE challenge.
* The response containing the challenge is `options.response`.
* If this method returns true, the underlying request will be sent once again.
*/
async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) {
var _a;
const { scopes } = onChallengeOptions;
const accessToken = await onChallengeOptions.getAccessToken(scopes, {
enableCae: true,
claims: caeClaims,
});
if (!accessToken) {
return false;
}
onChallengeOptions.request.headers.set("Authorization", `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "Bearer"} ${accessToken.token}`);
return true;
}
/**
* A policy that can request a token from a TokenCredential implementation and
* then apply it to the Authorization header of a request as a Bearer token.
*/
export function bearerTokenAuthenticationPolicy(options) {
var _a, _b, _c;
const { credential, scopes, challengeCallbacks } = options;
const logger = options.logger || coreLogger;
const callbacks = {
authorizeRequest: (_b = (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) === null || _a === void 0 ? void 0 : _a.bind(challengeCallbacks)) !== null && _b !== void 0 ? _b : defaultAuthorizeRequest,
authorizeRequestOnChallenge: (_c = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge) === null || _c === void 0 ? void 0 : _c.bind(challengeCallbacks),
};
// This function encapsulates the entire process of reliably retrieving the token
// The options are left out of the public API until there's demand to configure this.
// Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
// in order to pass through the `options` object.
const getAccessToken = credential
? createTokenCycler(credential /* , options */)
: () => Promise.resolve(null);
return {
name: bearerTokenAuthenticationPolicyName,
/**
* If there's no challenge parameter:
* - It will try to retrieve the token using the cache, or the credential's getToken.
* - Then it will try the next policy with or without the retrieved token.
*
* It uses the challenge parameters to:
* - Skip a first attempt to get the token from the credential if there's no cached token,
* since it expects the token to be retrievable only after the challenge.
* - Prepare the outgoing request if the `prepareRequest` method has been provided.
* - Send an initial request to receive the challenge if it fails.
* - Process a challenge if the response contains it.
* - Retrieve a token with the challenge information, then re-send the request.
*/
async sendRequest(request, next) {
if (!request.url.toLowerCase().startsWith("https://")) {
throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
}
await callbacks.authorizeRequest({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
getAccessToken,
logger,
});
let response;
let error;
let shouldSendRequest;
[response, error] = await trySendRequest(request, next);
if (isChallengeResponse(response)) {
let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
// Handle CAE by default when receive CAE claim
if (claims) {
let parsedClaim;
// Return the response immediately if claims is not a valid base64 encoded string
try {
parsedClaim = atob(claims);
}
catch (e) {
logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
return response;
}
shouldSendRequest = await authorizeRequestOnCaeChallenge({
scopes: Array.isArray(scopes) ? scopes : [scopes],
response,
request,
getAccessToken,
logger,
}, parsedClaim);
// Send updated request and handle response for RestError
if (shouldSendRequest) {
[response, error] = await trySendRequest(request, next);
}
}
else if (callbacks.authorizeRequestOnChallenge) {
// Handle custom challenges when client provides custom callback
shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
response,
getAccessToken,
logger,
});
// Send updated request and handle response for RestError
if (shouldSendRequest) {
[response, error] = await trySendRequest(request, next);
}
// If we get another CAE Claim, we will handle it by default and return whatever value we receive for this
if (isChallengeResponse(response)) {
claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
if (claims) {
let parsedClaim;
try {
parsedClaim = atob(claims);
}
catch (e) {
logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
return response;
}
shouldSendRequest = await authorizeRequestOnCaeChallenge({
scopes: Array.isArray(scopes) ? scopes : [scopes],
response,
request,
getAccessToken,
logger,
}, parsedClaim);
// Send updated request and handle response for RestError
if (shouldSendRequest) {
[response, error] = await trySendRequest(request, next);
}
}
}
}
}
if (error) {
throw error;
}
else {
return response;
}
},
};
}
/**
* Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
* Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
*
* @internal
*/
export function parseChallenges(challenges) {
// Challenge regex seperates the string to individual challenges with different schemes in the format `Scheme a="b", c=d`
// The challenge regex captures parameteres with either quotes values or unquoted values
const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;
// Parameter regex captures the claims group removed from the scheme in the format `a="b"` and `c="d"`
// CAE challenge always have quoted parameters. For more reference, https://learn.microsoft.com/entra/identity-platform/claims-challenge
const paramRegex = /(\w+)="([^"]*)"/g;
const parsedChallenges = [];
let match;
// Iterate over each challenge match
while ((match = challengeRegex.exec(challenges)) !== null) {
const scheme = match[1];
const paramsString = match[2];
const params = {};
let paramMatch;
// Iterate over each parameter match
while ((paramMatch = paramRegex.exec(paramsString)) !== null) {
params[paramMatch[1]] = paramMatch[2];
}
parsedChallenges.push({ scheme, params });
}
return parsedChallenges;
}
/**
* Parse a pipeline response and look for a CAE challenge with "Bearer" scheme
* Return the value in the header without parsing the challenge
* @internal
*/
function getCaeChallengeClaims(challenges) {
var _a;
if (!challenges) {
return;
}
// Find all challenges present in the header
const parsedChallenges = parseChallenges(challenges);
return (_a = parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")) === null || _a === void 0 ? void 0 : _a.params.claims;
}
//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"bearerTokenAuthenticationPolicy.js","sourceRoot":"","sources":["../../../src/policies/bearerTokenAuthenticationPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAMlC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,WAAW,CAAC;AAEjD,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C;;GAEG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG,iCAAiC,CAAC;AA0FrF;;;;;;;;GAQG;AACH,KAAK,UAAU,cAAc,CAC3B,OAAwB,EACxB,IAAiB;IAEjB,IAAI,CAAC;QACH,OAAO,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC,CAAC;IAC1C,CAAC;IAAC,OAAO,CAAM,EAAE,CAAC;QAChB,IAAI,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC;YACjC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;QACzB,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,CAAC;QACV,CAAC;IACH,CAAC;AACH,CAAC;AACD;;GAEG;AACH,KAAK,UAAU,uBAAuB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FAAwF;IACxF,MAAM,cAAc,GAAG,4CAALine truncated
@@ -0,0 +1,11 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the decompressResponsePolicy.
*/
export declare const decompressResponsePolicyName = "decompressResponsePolicy";
/**
* A policy to enable response decompression according to Accept-Encoding header
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
*/
export declare function decompressResponsePolicy(): PipelinePolicy;
//# sourceMappingURL=decompressResponsePolicy.d.ts.map
@@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* The programmatic identifier of the decompressResponsePolicy.
*/
export const decompressResponsePolicyName = "decompressResponsePolicy";
/**
* A policy to enable response decompression according to Accept-Encoding header
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
*/
export function decompressResponsePolicy() {
return {
name: decompressResponsePolicyName,
async sendRequest(request, next) {
// HEAD requests have no body
if (request.method !== "HEAD") {
request.headers.set("Accept-Encoding", "gzip,deflate");
}
return next(request);
},
};
}
//# sourceMappingURL=decompressResponsePolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"decompressResponsePolicy.js","sourceRoot":"","sources":["../../../src/policies/decompressResponsePolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,0BAA0B,CAAC;AAEvE;;;GAGG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO;QACL,IAAI,EAAE,4BAA4B;QAClC,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,6BAA6B;YAC7B,IAAI,OAAO,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;gBAC9B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,cAAc,CAAC,CAAC;YACzD,CAAC;YACD,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 type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\n/**\n * The programmatic identifier of the decompressResponsePolicy.\n */\nexport const decompressResponsePolicyName = \"decompressResponsePolicy\";\n\n/**\n * A policy to enable response decompression according to Accept-Encoding header\n * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding\n */\nexport function decompressResponsePolicy(): PipelinePolicy {\n return {\n name: decompressResponsePolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n // HEAD requests have no body\n if (request.method !== \"HEAD\") {\n request.headers.set(\"Accept-Encoding\", \"gzip,deflate\");\n }\n return next(request);\n },\n };\n}\n"]}
@@ -0,0 +1,19 @@
import type { PipelineRetryOptions } from "../interfaces.js";
import type { PipelinePolicy } from "../pipeline.js";
/**
* Name of the {@link defaultRetryPolicy}
*/
export declare const defaultRetryPolicyName = "defaultRetryPolicy";
/**
* Options that control how to retry failed requests.
*/
export interface DefaultRetryPolicyOptions extends PipelineRetryOptions {
}
/**
* A policy that retries according to three strategies:
* - When the server sends a 429 response with a Retry-After header.
* - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
* - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
*/
export declare function defaultRetryPolicy(options?: DefaultRetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=defaultRetryPolicy.d.ts.map
@@ -0,0 +1,26 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { exponentialRetryStrategy } from "../retryStrategies/exponentialRetryStrategy.js";
import { throttlingRetryStrategy } from "../retryStrategies/throttlingRetryStrategy.js";
import { retryPolicy } from "./retryPolicy.js";
import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js";
/**
* Name of the {@link defaultRetryPolicy}
*/
export const defaultRetryPolicyName = "defaultRetryPolicy";
/**
* A policy that retries according to three strategies:
* - When the server sends a 429 response with a Retry-After header.
* - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
* - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
*/
export function defaultRetryPolicy(options = {}) {
var _a;
return {
name: defaultRetryPolicyName,
sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options)], {
maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT,
}).sendRequest,
};
}
//# sourceMappingURL=defaultRetryPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"defaultRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/defaultRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gDAAgD,CAAC;AAC1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAC;AACxF,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,oBAAoB,CAAC;AAO3D;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,UAAqC,EAAE;;IACxE,OAAO;QACL,IAAI,EAAE,sBAAsB;QAC5B,WAAW,EAAE,WAAW,CAAC,CAAC,uBAAuB,EAAE,EAAE,wBAAwB,CAAC,OAAO,CAAC,CAAC,EAAE;YACvF,UAAU,EAAE,MAAA,OAAO,CAAC,UAAU,mCAAI,0BAA0B;SAC7D,CAAC,CAAC,WAAW;KACf,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelineRetryOptions } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { exponentialRetryStrategy } from \"../retryStrategies/exponentialRetryStrategy.js\";\nimport { throttlingRetryStrategy } from \"../retryStrategies/throttlingRetryStrategy.js\";\nimport { retryPolicy } from \"./retryPolicy.js\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants.js\";\n\n/**\n * Name of the {@link defaultRetryPolicy}\n */\nexport const defaultRetryPolicyName = \"defaultRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface DefaultRetryPolicyOptions extends PipelineRetryOptions {}\n\n/**\n * A policy that retries according to three strategies:\n * - When the server sends a 429 response with a Retry-After header.\n * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).\n * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.\n */\nexport function defaultRetryPolicy(options: DefaultRetryPolicyOptions = {}): PipelinePolicy {\n return {\n name: defaultRetryPolicyName,\n sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options)], {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }).sendRequest,\n };\n}\n"]}
@@ -0,0 +1,31 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the exponentialRetryPolicy.
*/
export declare const exponentialRetryPolicyName = "exponentialRetryPolicy";
/**
* Options that control how to retry failed requests.
*/
export interface ExponentialRetryPolicyOptions {
/**
* The maximum number of retry attempts. Defaults to 3.
*/
maxRetries?: number;
/**
* The amount of delay in milliseconds between retry attempts. Defaults to 1000
* (1 second.) The delay increases exponentially with each retry up to a maximum
* specified by maxRetryDelayInMs.
*/
retryDelayInMs?: number;
/**
* The maximum delay in milliseconds allowed before retrying an operation. Defaults
* to 64000 (64 seconds).
*/
maxRetryDelayInMs?: number;
}
/**
* A policy that attempts to retry requests while introducing an exponentially increasing delay.
* @param options - Options that configure retry logic.
*/
export declare function exponentialRetryPolicy(options?: ExponentialRetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=exponentialRetryPolicy.d.ts.map
@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { exponentialRetryStrategy } from "../retryStrategies/exponentialRetryStrategy.js";
import { retryPolicy } from "./retryPolicy.js";
import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js";
/**
* The programmatic identifier of the exponentialRetryPolicy.
*/
export const exponentialRetryPolicyName = "exponentialRetryPolicy";
/**
* A policy that attempts to retry requests while introducing an exponentially increasing delay.
* @param options - Options that configure retry logic.
*/
export function exponentialRetryPolicy(options = {}) {
var _a;
return retryPolicy([
exponentialRetryStrategy(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })),
], {
maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT,
});
}
//# sourceMappingURL=exponentialRetryPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"exponentialRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/exponentialRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gDAAgD,CAAC;AAC1F,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,wBAAwB,CAAC;AAyBnE;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACpC,UAAyC,EAAE;;IAE3C,OAAO,WAAW,CAChB;QACE,wBAAwB,iCACnB,OAAO,KACV,kBAAkB,EAAE,IAAI,IACxB;KACH,EACD;QACE,UAAU,EAAE,MAAA,OAAO,CAAC,UAAU,mCAAI,0BAA0B;KAC7D,CACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { exponentialRetryStrategy } from \"../retryStrategies/exponentialRetryStrategy.js\";\nimport { retryPolicy } from \"./retryPolicy.js\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants.js\";\n\n/**\n * The programmatic identifier of the exponentialRetryPolicy.\n */\nexport const exponentialRetryPolicyName = \"exponentialRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface ExponentialRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second.) The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * A policy that attempts to retry requests while introducing an exponentially increasing delay.\n * @param options - Options that configure retry logic.\n */\nexport function exponentialRetryPolicy(\n options: ExponentialRetryPolicyOptions = {},\n): PipelinePolicy {\n return retryPolicy(\n [\n exponentialRetryStrategy({\n ...options,\n ignoreSystemErrors: true,\n }),\n ],\n {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n },\n );\n}\n"]}
@@ -0,0 +1,10 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the formDataPolicy.
*/
export declare const formDataPolicyName = "formDataPolicy";
/**
* A policy that encodes FormData on the request into the body.
*/
export declare function formDataPolicy(): PipelinePolicy;
//# sourceMappingURL=formDataPolicy.d.ts.map
@@ -0,0 +1,96 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { isNodeLike, stringToUint8Array } from "@azure/core-util";
import { createHttpHeaders } from "../httpHeaders.js";
/**
* The programmatic identifier of the formDataPolicy.
*/
export const formDataPolicyName = "formDataPolicy";
function formDataToFormDataMap(formData) {
var _a;
const formDataMap = {};
for (const [key, value] of formData.entries()) {
(_a = formDataMap[key]) !== null && _a !== void 0 ? _a : (formDataMap[key] = []);
formDataMap[key].push(value);
}
return formDataMap;
}
/**
* A policy that encodes FormData on the request into the body.
*/
export function formDataPolicy() {
return {
name: formDataPolicyName,
async sendRequest(request, next) {
if (isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
request.formData = formDataToFormDataMap(request.body);
request.body = undefined;
}
if (request.formData) {
const contentType = request.headers.get("Content-Type");
if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
request.body = wwwFormUrlEncode(request.formData);
}
else {
await prepareFormData(request.formData, request);
}
request.formData = undefined;
}
return next(request);
},
};
}
function wwwFormUrlEncode(formData) {
const urlSearchParams = new URLSearchParams();
for (const [key, value] of Object.entries(formData)) {
if (Array.isArray(value)) {
for (const subValue of value) {
urlSearchParams.append(key, subValue.toString());
}
}
else {
urlSearchParams.append(key, value.toString());
}
}
return urlSearchParams.toString();
}
async function prepareFormData(formData, request) {
// validate content type (multipart/form-data)
const contentType = request.headers.get("Content-Type");
if (contentType && !contentType.startsWith("multipart/form-data")) {
// content type is specified and is not multipart/form-data. Exit.
return;
}
request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data");
// set body to MultipartRequestBody using content from FormDataMap
const parts = [];
for (const [fieldName, values] of Object.entries(formData)) {
for (const value of Array.isArray(values) ? values : [values]) {
if (typeof value === "string") {
parts.push({
headers: createHttpHeaders({
"Content-Disposition": `form-data; name="${fieldName}"`,
}),
body: stringToUint8Array(value, "utf-8"),
});
}
else if (value === undefined || value === null || typeof value !== "object") {
throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
}
else {
// using || instead of ?? here since if value.name is empty we should create a file name
const fileName = value.name || "blob";
const headers = createHttpHeaders();
headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
// again, || is used since an empty value.type means the content type is unset
headers.set("Content-Type", value.type || "application/octet-stream");
parts.push({
headers,
body: value,
});
}
}
}
request.multipartBody = { parts };
}
//# sourceMappingURL=formDataPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"formDataPolicy.js","sourceRoot":"","sources":["../../../src/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Content":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { isNodeLike, stringToUint8Array } from \"@azure/core-util\";\nimport { createHttpHeaders } from \"../httpHeaders.js\";\nimport type {\n BodyPart,\n FormDataMap,\n FormDataValue,\n PipelineRequest,\n PipelineResponse,\n SendRequest,\n} from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\n/**\n * The programmatic identifier of the formDataPolicy.\n */\nexport const formDataPolicyName = \"formDataPolicy\";\n\nfunction formDataToFormDataMap(formData: FormData): FormDataMap {\n const formDataMap: FormDataMap = {};\n for (const [key, value] of formData.entries()) {\n formDataMap[key] ??= [];\n (formDataMap[key] as FormDataValue[]).push(value);\n }\n return formDataMap;\n}\n\n/**\n * A policy that encodes FormData on the request into the body.\n */\nexport function formDataPolicy(): PipelinePolicy {\n return {\n name: formDataPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (isNodeLike && typeof FormData !== \"undefined\" && request.body instanceof FormData) {\n request.formData = formDataToFormDataMap(request.body);\n request.body = undefined;\n }\n\n if (request.formData) {\n const contentType = request.headers.get(\"Content-Type\");\n if (contentType && contentType.indexOf(\"application/x-www-form-urlencoded\") !== -1) {\n request.body = wwwFormUrlEncode(request.formData);\n } else {\n await prepareFormData(request.formData, request);\n }\n\n request.formData = undefined;\n }\n return next(request);\n },\n };\n}\n\nfunction wwwFormUrlEncLine truncated
@@ -0,0 +1,35 @@
import type { Debugger } from "@azure/logger";
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the logPolicy.
*/
export declare const logPolicyName = "logPolicy";
/**
* Options to configure the logPolicy.
*/
export interface LogPolicyOptions {
/**
* Header names whose values will be logged when logging is enabled.
* Defaults include a list of well-known safe headers. Any headers
* specified in this field will be added to that list. Any other values will
* be written to logs as "REDACTED".
*/
additionalAllowedHeaderNames?: string[];
/**
* Query string names whose values will be logged when logging is enabled. By default no
* query string values are logged.
*/
additionalAllowedQueryParameters?: string[];
/**
* The log function to use for writing pipeline logs.
* Defaults to core-http's built-in logger.
* Compatible with the `debug` library.
*/
logger?: Debugger;
}
/**
* A policy that logs all requests and responses.
* @param options - Options to configure logPolicy.
*/
export declare function logPolicy(options?: LogPolicyOptions): PipelinePolicy;
//# sourceMappingURL=logPolicy.d.ts.map
+34
View File
@@ -0,0 +1,34 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { logger as coreLogger } from "../log.js";
import { Sanitizer } from "../util/sanitizer.js";
/**
* The programmatic identifier of the logPolicy.
*/
export const logPolicyName = "logPolicy";
/**
* A policy that logs all requests and responses.
* @param options - Options to configure logPolicy.
*/
export function logPolicy(options = {}) {
var _a;
const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : coreLogger.info;
const sanitizer = new Sanitizer({
additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
});
return {
name: logPolicyName,
async sendRequest(request, next) {
if (!logger.enabled) {
return next(request);
}
logger(`Request: ${sanitizer.sanitize(request)}`);
const response = await next(request);
logger(`Response status code: ${response.status}`);
logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
return response;
},
};
}
//# sourceMappingURL=logPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"logPolicy.js","sourceRoot":"","sources":["../../../src/policies/logPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC,OAAO,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,WAAW,CAAC;AA4BzC;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,UAA4B,EAAE;;IACtD,MAAM,MAAM,GAAG,MAAA,OAAO,CAAC,MAAM,mCAAI,UAAU,CAAC,IAAI,CAAC;IACjD,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC;QAC9B,4BAA4B,EAAE,OAAO,CAAC,4BAA4B;QAClE,gCAAgC,EAAE,OAAO,CAAC,gCAAgC;KAC3E,CAAC,CAAC;IACH,OAAO;QACL,IAAI,EAAE,aAAa;QACnB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBACpB,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;YACvB,CAAC;YAED,MAAM,CAAC,YAAY,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YAElD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,CAAC;YAErC,MAAM,CAAC,yBAAyB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;YACnD,MAAM,CAAC,YAAY,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YAE3D,OAAO,QAAQ,CAAC;QAClB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { Debugger } from \"@azure/logger\";\nimport type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { logger as coreLogger } from \"../log.js\";\nimport { Sanitizer } from \"../util/sanitizer.js\";\n\n/**\n * The programmatic identifier of the logPolicy.\n */\nexport const logPolicyName = \"logPolicy\";\n\n/**\n * Options to configure the logPolicy.\n */\nexport interface LogPolicyOptions {\n /**\n * Header names whose values will be logged when logging is enabled.\n * Defaults include a list of well-known safe headers. Any headers\n * specified in this field will be added to that list. Any other values will\n * be written to logs as \"REDACTED\".\n */\n additionalAllowedHeaderNames?: string[];\n\n /**\n * Query string names whose values will be logged when logging is enabled. By default no\n * query string values are logged.\n */\n additionalAllowedQueryParameters?: string[];\n\n /**\n * The log function to use for writing pipeline logs.\n * Defaults to core-http's built-in logger.\n * Compatible with the `debug` library.\n */\n logger?: Debugger;\n}\n\n/**\n * A policy that logs all requests and responses.\n * @param options - Options to configure logPolicy.\n */\nexport function logPolicy(options: LogPolicyOptions = {}): PipelinePolicy {\n const logger = options.logger ?? coreLogger.info;\n const sanitizer = new Sanitizer({\n additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,\n additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,\n });\n return {\n name: logPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!logger.enabled) {\n return next(request);\n }\n\n logger(`Request: ${sanitizer.sanitize(request)}`);\n\n const response = await next(request);\n\n logger(`Response status code: ${response.status}`);\n logger(`Headers: ${sanitizer.sanitize(response.headers)}`);\n\n return response;\n },\n };\n}\n"]}
@@ -0,0 +1,10 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* Name of multipart policy
*/
export declare const multipartPolicyName = "multipartPolicy";
/**
* Pipeline policy for multipart requests
*/
export declare function multipartPolicy(): PipelinePolicy;
//# sourceMappingURL=multipartPolicy.d.ts.map
@@ -0,0 +1,111 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { randomUUID, stringToUint8Array } from "@azure/core-util";
import { concat } from "../util/concat.js";
import { isBlob } from "../util/typeGuards.js";
function generateBoundary() {
return `----AzSDKFormBoundary${randomUUID()}`;
}
function encodeHeaders(headers) {
let result = "";
for (const [key, value] of headers) {
result += `${key}: ${value}\r\n`;
}
return result;
}
function getLength(source) {
if (source instanceof Uint8Array) {
return source.byteLength;
}
else if (isBlob(source)) {
// if was created using createFile then -1 means we have an unknown size
return source.size === -1 ? undefined : source.size;
}
else {
return undefined;
}
}
function getTotalLength(sources) {
let total = 0;
for (const source of sources) {
const partLength = getLength(source);
if (partLength === undefined) {
return undefined;
}
else {
total += partLength;
}
}
return total;
}
async function buildRequestBody(request, parts, boundary) {
const sources = [
stringToUint8Array(`--${boundary}`, "utf-8"),
...parts.flatMap((part) => [
stringToUint8Array("\r\n", "utf-8"),
stringToUint8Array(encodeHeaders(part.headers), "utf-8"),
stringToUint8Array("\r\n", "utf-8"),
part.body,
stringToUint8Array(`\r\n--${boundary}`, "utf-8"),
]),
stringToUint8Array("--\r\n\r\n", "utf-8"),
];
const contentLength = getTotalLength(sources);
if (contentLength) {
request.headers.set("Content-Length", contentLength);
}
request.body = await concat(sources);
}
/**
* Name of multipart policy
*/
export const multipartPolicyName = "multipartPolicy";
const maxBoundaryLength = 70;
const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
function assertValidBoundary(boundary) {
if (boundary.length > maxBoundaryLength) {
throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
}
if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
}
}
/**
* Pipeline policy for multipart requests
*/
export function multipartPolicy() {
return {
name: multipartPolicyName,
async sendRequest(request, next) {
var _a;
if (!request.multipartBody) {
return next(request);
}
if (request.body) {
throw new Error("multipartBody and regular body cannot be set at the same time");
}
let boundary = request.multipartBody.boundary;
const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed";
const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
if (!parsedHeader) {
throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
}
const [, contentType, parsedBoundary] = parsedHeader;
if (parsedBoundary && boundary && parsedBoundary !== boundary) {
throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
}
boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary);
if (boundary) {
assertValidBoundary(boundary);
}
else {
boundary = generateBoundary();
}
request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
await buildRequestBody(request, request.multipartBody.parts, boundary);
request.multipartBody = undefined;
return next(request);
},
};
}
//# sourceMappingURL=multipartPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"multipartPolicy.js","sourceRoot":"","sources":["../../../src/policies/multipartPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAGlE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,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,CAAC;QACnC,MAAM,IAAI,GAAG,GAAG,KAAK,KAAK,MAAM,CAAC;IACnC,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,SAAS,CAChB,MAMyB;IAEzB,IAAI,MAAM,YAAY,UAAU,EAAE,CAAC;QACjC,OAAO,MAAM,CAAC,UAAU,CAAC;IAC3B,CAAC;SAAM,IAAI,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1B,wEAAwE;QACxE,OAAO,MAAM,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;IACtD,CAAC;SAAM,CAAC;QACN,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,SAAS,cAAc,CACrB,OAOG;IAEH,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,UAAU,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;QACrC,IAAI,UAAU,KAAK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,QAAQ,IAAR,QAAQ,GAAK,cAAc,EAAC;YAC5B,IAAI,QAAQ,EAAE,CAAC;gBACb,mBAAmB,CAAC,QAAQ,CAAC,CAAC;YAChC,CAAC;iBAAM,CAAC;gBACN,QAAQ,GAAG,gBAAgB,EAAE,CAAC;YAChC,CAAC;YACD,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,GAAG,WAAW,cAAc,QAAQ,EAAE,CAAC,CAAC;YAC5E,MAAM,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,aAAa,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;YAEvE,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 { randomUUID, stringToUint8Array } from \"@azure/core-util\";\nimport type { BodyPart, HttpHeaders, PipelineRequest, PipelineResponse } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { concat } from \"../util/concat.js\";\nimport { isBlob } from \"../util/typeGuards.js\";\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 Line truncated
@@ -0,0 +1,10 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the ndJsonPolicy.
*/
export declare const ndJsonPolicyName = "ndJsonPolicy";
/**
* ndJsonPolicy is a policy used to control keep alive settings for every request.
*/
export declare function ndJsonPolicy(): PipelinePolicy;
//# sourceMappingURL=ndJsonPolicy.d.ts.map
@@ -0,0 +1,25 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* The programmatic identifier of the ndJsonPolicy.
*/
export const ndJsonPolicyName = "ndJsonPolicy";
/**
* ndJsonPolicy is a policy used to control keep alive settings for every request.
*/
export function ndJsonPolicy() {
return {
name: ndJsonPolicyName,
async sendRequest(request, next) {
// There currently isn't a good way to bypass the serializer
if (typeof request.body === "string" && request.body.startsWith("[")) {
const body = JSON.parse(request.body);
if (Array.isArray(body)) {
request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
}
}
return next(request);
},
};
}
//# sourceMappingURL=ndJsonPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ndJsonPolicy.js","sourceRoot":"","sources":["../../../src/policies/ndJsonPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAAC;AAE/C;;GAEG;AACH,MAAM,UAAU,YAAY;IAC1B,OAAO;QACL,IAAI,EAAE,gBAAgB;QACtB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,4DAA4D;YAC5D,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;gBACrE,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;gBACtC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;oBACxB,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBAC1E,CAAC;YACH,CAAC;YACD,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 type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\n/**\n * The programmatic identifier of the ndJsonPolicy.\n */\nexport const ndJsonPolicyName = \"ndJsonPolicy\";\n\n/**\n * ndJsonPolicy is a policy used to control keep alive settings for every request.\n */\nexport function ndJsonPolicy(): PipelinePolicy {\n return {\n name: ndJsonPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n // There currently isn't a good way to bypass the serializer\n if (typeof request.body === \"string\" && request.body.startsWith(\"[\")) {\n const body = JSON.parse(request.body);\n if (Array.isArray(body)) {\n request.body = body.map((item) => JSON.stringify(item) + \"\\n\").join(\"\");\n }\n }\n return next(request);\n },\n };\n}\n"]}
@@ -0,0 +1,15 @@
export declare const proxyPolicyName = "proxyPolicy";
export declare function getDefaultProxySettings(): never;
/**
* proxyPolicy is not supported in the browser and attempting
* to use it will raise an error.
*/
export declare function proxyPolicy(): never;
/**
* A function to reset the cached agents.
* proxyPolicy is not supported in the browser and attempting
* to use it will raise an error.
* @internal
*/
export declare function resetCachedProxyAgents(): never;
//# sourceMappingURL=proxyPolicy.common.d.ts.map
@@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export const proxyPolicyName = "proxyPolicy";
const errorMessage = "proxyPolicy is not supported in browser environment";
export function getDefaultProxySettings() {
throw new Error(errorMessage);
}
/**
* proxyPolicy is not supported in the browser and attempting
* to use it will raise an error.
*/
export function proxyPolicy() {
throw new Error(errorMessage);
}
/**
* A function to reset the cached agents.
* proxyPolicy is not supported in the browser and attempting
* to use it will raise an error.
* @internal
*/
export function resetCachedProxyAgents() {
throw new Error(errorMessage);
}
//# sourceMappingURL=proxyPolicy.common.js.map
@@ -0,0 +1 @@
{"version":3,"file":"proxyPolicy.common.js","sourceRoot":"","sources":["../../../src/policies/proxyPolicy.common.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,MAAM,CAAC,MAAM,eAAe,GAAG,aAAa,CAAC;AAC7C,MAAM,YAAY,GAAG,qDAAqD,CAAC;AAE3E,MAAM,UAAU,uBAAuB;IACrC,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AAChC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW;IACzB,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AAChC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB;IACpC,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;AAChC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport const proxyPolicyName = \"proxyPolicy\";\nconst errorMessage = \"proxyPolicy is not supported in browser environment\";\n\nexport function getDefaultProxySettings(): never {\n throw new Error(errorMessage);\n}\n\n/**\n * proxyPolicy is not supported in the browser and attempting\n * to use it will raise an error.\n */\nexport function proxyPolicy(): never {\n throw new Error(errorMessage);\n}\n\n/**\n * A function to reset the cached agents.\n * proxyPolicy is not supported in the browser and attempting\n * to use it will raise an error.\n * @internal\n */\nexport function resetCachedProxyAgents(): never {\n throw new Error(errorMessage);\n}\n"]}
@@ -0,0 +1,32 @@
import type { ProxySettings } from "../interfaces.js";
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the proxyPolicy.
*/
export declare const proxyPolicyName = "proxyPolicy";
/**
* Stores the patterns specified in NO_PROXY environment variable.
* @internal
*/
export declare const globalNoProxyList: string[];
export declare function loadNoProxy(): string[];
/**
* This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
* If no argument is given, it attempts to parse a proxy URL from the environment
* variables `HTTPS_PROXY` or `HTTP_PROXY`.
* @param proxyUrl - The url of the proxy to use. May contain authentication information.
* @deprecated - Internally this method is no longer necessary when setting proxy information.
*/
export declare function getDefaultProxySettings(proxyUrl?: string): ProxySettings | undefined;
/**
* A policy that allows one to apply proxy settings to all requests.
* If not passed static settings, they will be retrieved from the HTTPS_PROXY
* or HTTP_PROXY environment variables.
* @param proxySettings - ProxySettings to use on each request.
* @param options - additional settings, for example, custom NO_PROXY patterns
*/
export declare function proxyPolicy(proxySettings?: ProxySettings, options?: {
/** a list of patterns to override those loaded from NO_PROXY environment variable. */
customNoProxyList?: string[];
}): PipelinePolicy;
//# sourceMappingURL=proxyPolicy.d.ts.map
+191
View File
@@ -0,0 +1,191 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { HttpsProxyAgent } from "https-proxy-agent";
import { HttpProxyAgent } from "http-proxy-agent";
import { logger } from "../log.js";
const HTTPS_PROXY = "HTTPS_PROXY";
const HTTP_PROXY = "HTTP_PROXY";
const ALL_PROXY = "ALL_PROXY";
const NO_PROXY = "NO_PROXY";
/**
* The programmatic identifier of the proxyPolicy.
*/
export const proxyPolicyName = "proxyPolicy";
/**
* Stores the patterns specified in NO_PROXY environment variable.
* @internal
*/
export const globalNoProxyList = [];
let noProxyListLoaded = false;
/** A cache of whether a host should bypass the proxy. */
const globalBypassedMap = new Map();
function getEnvironmentValue(name) {
if (process.env[name]) {
return process.env[name];
}
else if (process.env[name.toLowerCase()]) {
return process.env[name.toLowerCase()];
}
return undefined;
}
function loadEnvironmentProxyValue() {
if (!process) {
return undefined;
}
const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
const allProxy = getEnvironmentValue(ALL_PROXY);
const httpProxy = getEnvironmentValue(HTTP_PROXY);
return httpsProxy || allProxy || httpProxy;
}
/**
* Check whether the host of a given `uri` matches any pattern in the no proxy list.
* If there's a match, any request sent to the same host shouldn't have the proxy settings set.
* This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
*/
function isBypassed(uri, noProxyList, bypassedMap) {
if (noProxyList.length === 0) {
return false;
}
const host = new URL(uri).hostname;
if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) {
return bypassedMap.get(host);
}
let isBypassedFlag = false;
for (const pattern of noProxyList) {
if (pattern[0] === ".") {
// This should match either domain it self or any subdomain or host
// .foo.com will match foo.com it self or *.foo.com
if (host.endsWith(pattern)) {
isBypassedFlag = true;
}
else {
if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
isBypassedFlag = true;
}
}
}
else {
if (host === pattern) {
isBypassedFlag = true;
}
}
}
bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag);
return isBypassedFlag;
}
export function loadNoProxy() {
const noProxy = getEnvironmentValue(NO_PROXY);
noProxyListLoaded = true;
if (noProxy) {
return noProxy
.split(",")
.map((item) => item.trim())
.filter((item) => item.length);
}
return [];
}
/**
* This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
* If no argument is given, it attempts to parse a proxy URL from the environment
* variables `HTTPS_PROXY` or `HTTP_PROXY`.
* @param proxyUrl - The url of the proxy to use. May contain authentication information.
* @deprecated - Internally this method is no longer necessary when setting proxy information.
*/
export function getDefaultProxySettings(proxyUrl) {
if (!proxyUrl) {
proxyUrl = loadEnvironmentProxyValue();
if (!proxyUrl) {
return undefined;
}
}
const parsedUrl = new URL(proxyUrl);
const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
return {
host: schema + parsedUrl.hostname,
port: Number.parseInt(parsedUrl.port || "80"),
username: parsedUrl.username,
password: parsedUrl.password,
};
}
/**
* This method attempts to parse a proxy URL from the environment
* variables `HTTPS_PROXY` or `HTTP_PROXY`.
*/
function getDefaultProxySettingsInternal() {
const envProxy = loadEnvironmentProxyValue();
return envProxy ? new URL(envProxy) : undefined;
}
function getUrlFromProxySettings(settings) {
let parsedProxyUrl;
try {
parsedProxyUrl = new URL(settings.host);
}
catch (_a) {
throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
}
parsedProxyUrl.port = String(settings.port);
if (settings.username) {
parsedProxyUrl.username = settings.username;
}
if (settings.password) {
parsedProxyUrl.password = settings.password;
}
return parsedProxyUrl;
}
function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
// Custom Agent should take precedence so if one is present
// we should skip to avoid overwriting it.
if (request.agent) {
return;
}
const url = new URL(request.url);
const isInsecure = url.protocol !== "https:";
if (request.tlsSettings) {
logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
}
const headers = request.headers.toJSON();
if (isInsecure) {
if (!cachedAgents.httpProxyAgent) {
cachedAgents.httpProxyAgent = new HttpProxyAgent(proxyUrl, { headers });
}
request.agent = cachedAgents.httpProxyAgent;
}
else {
if (!cachedAgents.httpsProxyAgent) {
cachedAgents.httpsProxyAgent = new HttpsProxyAgent(proxyUrl, { headers });
}
request.agent = cachedAgents.httpsProxyAgent;
}
}
/**
* A policy that allows one to apply proxy settings to all requests.
* If not passed static settings, they will be retrieved from the HTTPS_PROXY
* or HTTP_PROXY environment variables.
* @param proxySettings - ProxySettings to use on each request.
* @param options - additional settings, for example, custom NO_PROXY patterns
*/
export function proxyPolicy(proxySettings, options) {
if (!noProxyListLoaded) {
globalNoProxyList.push(...loadNoProxy());
}
const defaultProxy = proxySettings
? getUrlFromProxySettings(proxySettings)
: getDefaultProxySettingsInternal();
const cachedAgents = {};
return {
name: proxyPolicyName,
async sendRequest(request, next) {
var _a;
if (!request.proxySettings &&
defaultProxy &&
!isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) {
setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
}
else if (request.proxySettings) {
setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
}
return next(request);
},
};
}
//# sourceMappingURL=proxyPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"proxyPolicy.js","sourceRoot":"","sources":["../../../src/policies/proxyPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAQlD,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,MAAM,WAAW,GAAG,aAAa,CAAC;AAClC,MAAM,UAAU,GAAG,YAAY,CAAC;AAChC,MAAM,SAAS,GAAG,WAAW,CAAC;AAC9B,MAAM,QAAQ,GAAG,UAAU,CAAC;AAE5B;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,aAAa,CAAC;AAE7C;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAa,EAAE,CAAC;AAC9C,IAAI,iBAAiB,GAAY,KAAK,CAAC;AAEvC,yDAAyD;AACzD,MAAM,iBAAiB,GAAyB,IAAI,GAAG,EAAE,CAAC;AAE1D,SAAS,mBAAmB,CAAC,IAAY;IACvC,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;QACtB,OAAO,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;SAAM,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC;QAC3C,OAAO,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;IACzC,CAAC;IACD,OAA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";
/**
* The programmatic identifier of the redirectPolicy.
*/
export declare const redirectPolicyName = "redirectPolicy";
/**
* Options for how redirect responses are handled.
*/
export interface RedirectPolicyOptions {
/**
* The maximum number of times the redirect URL will be tried before
* failing. Defaults to 20.
*/
maxRetries?: number;
}
/**
* A policy to follow Location headers from the server in order
* to support server-side redirection.
* In the browser, this policy is not used.
* @param options - Options to control policy behavior.
*/
export declare function redirectPolicy(options?: RedirectPolicyOptions): PipelinePolicy;
//# sourceMappingURL=redirectPolicy.d.ts.map
@@ -0,0 +1,52 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* The programmatic identifier of the redirectPolicy.
*/
export const redirectPolicyName = "redirectPolicy";
/**
* Methods that are allowed to follow redirects 301 and 302
*/
const allowedRedirect = ["GET", "HEAD"];
/**
* A policy to follow Location headers from the server in order
* to support server-side redirection.
* In the browser, this policy is not used.
* @param options - Options to control policy behavior.
*/
export function redirectPolicy(options = {}) {
const { maxRetries = 20 } = options;
return {
name: redirectPolicyName,
async sendRequest(request, next) {
const response = await next(request);
return handleRedirect(next, response, maxRetries);
},
};
}
async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
const { request, status, headers } = response;
const locationHeader = headers.get("location");
if (locationHeader &&
(status === 300 ||
(status === 301 && allowedRedirect.includes(request.method)) ||
(status === 302 && allowedRedirect.includes(request.method)) ||
(status === 303 && request.method === "POST") ||
status === 307) &&
currentRetries < maxRetries) {
const url = new URL(locationHeader, request.url);
request.url = url.toString();
// POST request with Status code 303 should be converted into a
// redirected GET request if the redirect url is present in the location header
if (status === 303) {
request.method = "GET";
request.headers.delete("Content-Length");
delete request.body;
}
request.headers.delete("Authorization");
const res = await next(request);
return handleRedirect(next, res, maxRetries, currentRetries + 1);
}
return response;
}
//# sourceMappingURL=redirectPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"redirectPolicy.js","sourceRoot":"","sources":["../../../src/policies/redirectPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,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,GAAG,CAAC,QAAQ,EAAE,CAAC;QAE7B,+DAA+D;QAC/D,+EAA+E;QAC/E,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;YACnB,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC;YACvB,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;YACzC,OAAO,OAAO,CAAC,IAAI,CAAC;QACtB,CAAC;QAED,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;QAExC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,CAAC;QAChC,OAAO,cAAc,CAAC,IAAI,EAAE,GAAG,EAAE,UAAU,EAAE,cAAc,GAAG,CAAC,CAAC,CAAC;IACnE,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\n/**\n * The programmatic identifier of the redirectPolicy.\n */\nexport const redirectPolicyName = \"redirectPolicy\";\n\n/**\n * Methods that are allowed to follow redirects 301 and 302\n */\nconst allowedRedirect = [\"GET\", \"HEAD\"];\n\n/**\n * Options for how redirect responses are handled.\n */\nexport interface RedirectPolicyOptions {\n /**\n * The maximum number of times the redirect URL will be tried before\n * failing. Defaults to 20.\n */\n maxRetries?: number;\n}\n\n/**\n * A policy to follow Location headers from the server in order\n * to support server-side redirection.\n * In the browser, this policy is not used.\n * @param options - Options to control policy behavior.\n */\nexport function redirectPolicy(options: RedirectPolicyOptions = {}): PipelinePolicy {\n const { maxRetries = 20 } = options;\n return {\n name: redirectPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n const response = await next(request);\n return handleRedirect(next, response, maxRetries);\n },\n };\n}\n\nasync function handleRedirect(\n next: SendRequest,\n response: PipelineResponse,\n maxRetries: number,\n currentRetries: number = 0,\n): Promise<PipelineResponse> {\n const { request, status, headers } = response;\n const locationHeader = headers.get(\"location\");\n if (\n locationHeader &&\n (status === 300 ||\n (status === 301 && allowedRedirect.includes(request.method)) ||\n (status === 302 && allowedRedirect.includes(request.method)) ||\n (status === 303 && request.method === \"POST\") ||\n status === 307) &&\n currentRetries < maxRetries\n ) {\n const url = new URL(locationHeader, request.url);\n request.url = url.toString();\n\n // POST request with Status code 303 should be converted into a\n // redirected GET request if the redirect url is present in the location header\n if (status === 303) {\n request.method = \"GET\";\n request.headers.delete(\"Content-Length\");\n delete request.body;\n }\n\n request.headers.delete(\"Authorization\");\n\n const res = await next(request);\n return handleRedirect(next, res, maxRetries, currentRetries + 1);\n }\n\n return response;\n}\n"]}
@@ -0,0 +1,21 @@
import type { PipelinePolicy } from "../pipeline.js";
import { type AzureLogger } from "@azure/logger";
import type { RetryStrategy } from "../retryStrategies/retryStrategy.js";
/**
* Options to the {@link retryPolicy}
*/
export interface RetryPolicyOptions {
/**
* Maximum number of retries. If not specified, it will limit to 3 retries.
*/
maxRetries?: number;
/**
* Logger. If it's not provided, a default logger is used.
*/
logger?: AzureLogger;
}
/**
* retryPolicy is a generic policy to enable retrying requests when certain conditions are met
*/
export declare function retryPolicy(strategies: RetryStrategy[], options?: RetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=retryPolicy.d.ts.map
+105
View File
@@ -0,0 +1,105 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { delay } from "../util/helpers.js";
import { createClientLogger } from "@azure/logger";
import { AbortError } from "@azure/abort-controller";
import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js";
const retryPolicyLogger = createClientLogger("core-rest-pipeline retryPolicy");
/**
* The programmatic identifier of the retryPolicy.
*/
const retryPolicyName = "retryPolicy";
/**
* retryPolicy is a generic policy to enable retrying requests when certain conditions are met
*/
export function retryPolicy(strategies, options = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) {
const logger = options.logger || retryPolicyLogger;
return {
name: retryPolicyName,
async sendRequest(request, next) {
var _a, _b;
let response;
let responseError;
let retryCount = -1;
retryRequest: while (true) {
retryCount += 1;
response = undefined;
responseError = undefined;
try {
logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
response = await next(request);
logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
}
catch (e) {
logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
// RestErrors are valid targets for the retry strategies.
// If none of the retry strategies can work with them, they will be thrown later in this policy.
// If the received error is not a RestError, it is immediately thrown.
responseError = e;
if (!e || responseError.name !== "RestError") {
throw e;
}
response = responseError.response;
}
if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
logger.error(`Retry ${retryCount}: Request aborted.`);
const abortError = new AbortError();
throw abortError;
}
if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_POLICY_COUNT)) {
logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
if (responseError) {
throw responseError;
}
else if (response) {
return response;
}
else {
throw new Error("Maximum retries reached with no response or error to throw");
}
}
logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
strategiesLoop: for (const strategy of strategies) {
const strategyLogger = strategy.logger || retryPolicyLogger;
strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
const modifiers = strategy.retry({
retryCount,
response,
responseError,
});
if (modifiers.skipStrategy) {
strategyLogger.info(`Retry ${retryCount}: Skipped.`);
continue strategiesLoop;
}
const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
if (errorToThrow) {
strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
throw errorToThrow;
}
if (retryAfterInMs || retryAfterInMs === 0) {
strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
await delay(retryAfterInMs, undefined, { abortSignal: request.abortSignal });
continue retryRequest;
}
if (redirectTo) {
strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
request.url = redirectTo;
continue retryRequest;
}
}
if (responseError) {
logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
throw responseError;
}
if (response) {
logger.info(`None of the retry strategies could work with the received response. Returning it.`);
return response;
}
// If all the retries skip and there's no response,
// we're still in the retry loop, so a new request will be sent
// until `maxRetries` is reached.
}
},
};
}
//# sourceMappingURL=retryPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"retryPolicy.js","sourceRoot":"","sources":["../../../src/policies/retryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAoB,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAGrE,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACrD,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D,MAAM,iBAAiB,GAAG,kBAAkB,CAAC,gCAAgC,CAAC,CAAC;AAE/E;;GAEG;AACH,MAAM,eAAe,GAAG,aAAa,CAAC;AAgBtC;;GAEG;AACH,MAAM,UAAU,WAAW,CACzB,UAA2B,EAC3B,UAA8B,EAAE,UAAU,EAAE,0BAA0B,EAAE;IAExE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,iBAAiB,CAAC;IACnD,OAAO;QACL,IAAI,EAAE,eAAe;QACrB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;;YAC3D,IAAI,QAAsC,CAAC;YAC3C,IAAI,aAAoC,CAAC;YACzC,IAAI,UAAU,GAAG,CAAC,CAAC,CAAC;YAEpB,YAAY,EAAE,OAAO,IAAI,EAAE,CAAC;gBAC1B,UAAU,IAAI,CAAC,CAAC;gBAChB,QAAQ,GAAG,SAAS,CAAC;gBACrB,aAAa,GAAG,SAAS,CAAC;gBAE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;wBACF,OAAO,CAAC,GAAG,GAAG,UAAU,CAAC;wBACzB,SAAS,YAAY,CAAC;oBACxB,CAAC;gBACH,CAAC;gBAED,IAAI,aAAa,EAAE,CAAC;oBAClB,MAAM,CAAC,IAAI,CACT,+EAA+E,CAChF,CAAC;oBACF,MAAM,aAAa,CAAC;gBACtB,CAAC;gBACD,IAAI,QAAQ,EAAE,CAAC;oBACb,MAAM,CAAC,IAAI,CACT,mFAAmF,CACpF,CAAC;oBACF,OAAO,QAAQ,CAAC;gBAClB,CAAC;gBAED,mDAAmD;gBACnD,+DAA+D;gBAC/D,iCAAiC;YACnC,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { delay } from \"../util/helpers.js\";\nimport { type AzureLogger, createClientLogger } from \"@azure/logger\";\nimport type { RetryStrategy } from \"../retryStrategies/retryStrategy.js\";\nimport type { RestError } from \"../restError.js\";\nimport { AbortError } from \"@azure/abort-controller\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants.js\";\n\nconst retryPolicyLogger = createClientLogger(\"core-rest-pipeline retryPolicy\");\n\n/**\n * The programmatic identifier of the retryPolicy.\n */\nconst retryPolicyName = \"retryPolicy\";\n\n/**\n * Options to the {@link retryPolicy}\n */\nexport interface RetryPolicyOptions {\n /**\n * Maximum number of retries. If not specified, it will limit to 3 retries.\n */\n maxRetries?: number;\n /**\n * Logger. If it's not provided, a default logger is used.\n */\n logger?: AzureLogger;\n}\n\n/**\n * retryPolicy is a generic policy to enable retrying requests when certain conditions are met\n */\nexport function retryPolicy(\n strategies: RetryStrategy[],\n options: RetryPolicyOptions = { maxRetries: DEFAULT_RETRY_POLICY_COUNT },\n): PipelinePolicy {\n const logger = options.logger || retryPolicyLogger;\n return {\n name: retryPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n let response: PipelineResponse | undefined;\n let responseError: RestError | undefined;\n let retryCount = -1;\n\nLine truncated
@@ -0,0 +1,13 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the setClientRequestIdPolicy.
*/
export declare const setClientRequestIdPolicyName = "setClientRequestIdPolicy";
/**
* Each PipelineRequest gets a unique id upon creation.
* This policy passes that unique id along via an HTTP header to enable better
* telemetry and tracing.
* @param requestIdHeaderName - The name of the header to pass the request ID to.
*/
export declare function setClientRequestIdPolicy(requestIdHeaderName?: string): PipelinePolicy;
//# sourceMappingURL=setClientRequestIdPolicy.d.ts.map
@@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* The programmatic identifier of the setClientRequestIdPolicy.
*/
export const setClientRequestIdPolicyName = "setClientRequestIdPolicy";
/**
* Each PipelineRequest gets a unique id upon creation.
* This policy passes that unique id along via an HTTP header to enable better
* telemetry and tracing.
* @param requestIdHeaderName - The name of the header to pass the request ID to.
*/
export function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
return {
name: setClientRequestIdPolicyName,
async sendRequest(request, next) {
if (!request.headers.has(requestIdHeaderName)) {
request.headers.set(requestIdHeaderName, request.requestId);
}
return next(request);
},
};
}
//# sourceMappingURL=setClientRequestIdPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"setClientRequestIdPolicy.js","sourceRoot":"","sources":["../../../src/policies/setClientRequestIdPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,0BAA0B,CAAC;AAEvE;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,mBAAmB,GAAG,wBAAwB;IAE9C,OAAO;QACL,IAAI,EAAE,4BAA4B;QAClC,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAE,CAAC;gBAC9C,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;YAC9D,CAAC;YACD,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 type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\n\n/**\n * The programmatic identifier of the setClientRequestIdPolicy.\n */\nexport const setClientRequestIdPolicyName = \"setClientRequestIdPolicy\";\n\n/**\n * Each PipelineRequest gets a unique id upon creation.\n * This policy passes that unique id along via an HTTP header to enable better\n * telemetry and tracing.\n * @param requestIdHeaderName - The name of the header to pass the request ID to.\n */\nexport function setClientRequestIdPolicy(\n requestIdHeaderName = \"x-ms-client-request-id\",\n): PipelinePolicy {\n return {\n name: setClientRequestIdPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!request.headers.has(requestIdHeaderName)) {\n request.headers.set(requestIdHeaderName, request.requestId);\n }\n return next(request);\n },\n };\n}\n"]}
@@ -0,0 +1,33 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* Name of the {@link systemErrorRetryPolicy}
*/
export declare const systemErrorRetryPolicyName = "systemErrorRetryPolicy";
/**
* Options that control how to retry failed requests.
*/
export interface SystemErrorRetryPolicyOptions {
/**
* The maximum number of retry attempts. Defaults to 3.
*/
maxRetries?: number;
/**
* The amount of delay in milliseconds between retry attempts. Defaults to 1000
* (1 second.) The delay increases exponentially with each retry up to a maximum
* specified by maxRetryDelayInMs.
*/
retryDelayInMs?: number;
/**
* The maximum delay in milliseconds allowed before retrying an operation. Defaults
* to 64000 (64 seconds).
*/
maxRetryDelayInMs?: number;
}
/**
* A retry policy that specifically seeks to handle errors in the
* underlying transport layer (e.g. DNS lookup failures) rather than
* retryable error codes from the server itself.
* @param options - Options that customize the policy.
*/
export declare function systemErrorRetryPolicy(options?: SystemErrorRetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=systemErrorRetryPolicy.d.ts.map
@@ -0,0 +1,27 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { exponentialRetryStrategy } from "../retryStrategies/exponentialRetryStrategy.js";
import { retryPolicy } from "./retryPolicy.js";
import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js";
/**
* Name of the {@link systemErrorRetryPolicy}
*/
export const systemErrorRetryPolicyName = "systemErrorRetryPolicy";
/**
* A retry policy that specifically seeks to handle errors in the
* underlying transport layer (e.g. DNS lookup failures) rather than
* retryable error codes from the server itself.
* @param options - Options that customize the policy.
*/
export function systemErrorRetryPolicy(options = {}) {
var _a;
return {
name: systemErrorRetryPolicyName,
sendRequest: retryPolicy([
exponentialRetryStrategy(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })),
], {
maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT,
}).sendRequest,
};
}
//# sourceMappingURL=systemErrorRetryPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"systemErrorRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/systemErrorRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gDAAgD,CAAC;AAC1F,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,wBAAwB,CAAC;AAyBnE;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,UAAyC,EAAE;;IAE3C,OAAO;QACL,IAAI,EAAE,0BAA0B;QAChC,WAAW,EAAE,WAAW,CACtB;YACE,wBAAwB,iCACnB,OAAO,KACV,qBAAqB,EAAE,IAAI,IAC3B;SACH,EACD;YACE,UAAU,EAAE,MAAA,OAAO,CAAC,UAAU,mCAAI,0BAA0B;SAC7D,CACF,CAAC,WAAW;KACd,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { exponentialRetryStrategy } from \"../retryStrategies/exponentialRetryStrategy.js\";\nimport { retryPolicy } from \"./retryPolicy.js\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants.js\";\n\n/**\n * Name of the {@link systemErrorRetryPolicy}\n */\nexport const systemErrorRetryPolicyName = \"systemErrorRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface SystemErrorRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n\n /**\n * The amount of delay in milliseconds between retry attempts. Defaults to 1000\n * (1 second.) The delay increases exponentially with each retry up to a maximum\n * specified by maxRetryDelayInMs.\n */\n retryDelayInMs?: number;\n\n /**\n * The maximum delay in milliseconds allowed before retrying an operation. Defaults\n * to 64000 (64 seconds).\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * A retry policy that specifically seeks to handle errors in the\n * underlying transport layer (e.g. DNS lookup failures) rather than\n * retryable error codes from the server itself.\n * @param options - Options that customize the policy.\n */\nexport function systemErrorRetryPolicy(\n options: SystemErrorRetryPolicyOptions = {},\n): PipelinePolicy {\n return {\n name: systemErrorRetryPolicyName,\n sendRequest: retryPolicy(\n [\n exponentialRetryStrategy({\n ...options,\n ignoreHttpStatusCodes: true,\n }),\n ],\n {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n },\n ).sendRequest,\n };\n}\n"]}
@@ -0,0 +1,26 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* Name of the {@link throttlingRetryPolicy}
*/
export declare const throttlingRetryPolicyName = "throttlingRetryPolicy";
/**
* Options that control how to retry failed requests.
*/
export interface ThrottlingRetryPolicyOptions {
/**
* The maximum number of retry attempts. Defaults to 3.
*/
maxRetries?: number;
}
/**
* A policy that retries when the server sends a 429 response with a Retry-After header.
*
* To learn more, please refer to
* https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
* https://learn.microsoft.com/en-us/azure/azure-subscription-service-limits and
* https://learn.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
*
* @param options - Options that configure retry logic.
*/
export declare function throttlingRetryPolicy(options?: ThrottlingRetryPolicyOptions): PipelinePolicy;
//# sourceMappingURL=throttlingRetryPolicy.d.ts.map
@@ -0,0 +1,29 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { throttlingRetryStrategy } from "../retryStrategies/throttlingRetryStrategy.js";
import { retryPolicy } from "./retryPolicy.js";
import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js";
/**
* Name of the {@link throttlingRetryPolicy}
*/
export const throttlingRetryPolicyName = "throttlingRetryPolicy";
/**
* A policy that retries when the server sends a 429 response with a Retry-After header.
*
* To learn more, please refer to
* https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
* https://learn.microsoft.com/en-us/azure/azure-subscription-service-limits and
* https://learn.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
*
* @param options - Options that configure retry logic.
*/
export function throttlingRetryPolicy(options = {}) {
var _a;
return {
name: throttlingRetryPolicyName,
sendRequest: retryPolicy([throttlingRetryStrategy()], {
maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT,
}).sendRequest,
};
}
//# sourceMappingURL=throttlingRetryPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"throttlingRetryPolicy.js","sourceRoot":"","sources":["../../../src/policies/throttlingRetryPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,uBAAuB,EAAE,MAAM,+CAA+C,CAAC;AACxF,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,uBAAuB,CAAC;AAYjE;;;;;;;;;GASG;AACH,MAAM,UAAU,qBAAqB,CAAC,UAAwC,EAAE;;IAC9E,OAAO;QACL,IAAI,EAAE,yBAAyB;QAC/B,WAAW,EAAE,WAAW,CAAC,CAAC,uBAAuB,EAAE,CAAC,EAAE;YACpD,UAAU,EAAE,MAAA,OAAO,CAAC,UAAU,mCAAI,0BAA0B;SAC7D,CAAC,CAAC,WAAW;KACf,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { throttlingRetryStrategy } from \"../retryStrategies/throttlingRetryStrategy.js\";\nimport { retryPolicy } from \"./retryPolicy.js\";\nimport { DEFAULT_RETRY_POLICY_COUNT } from \"../constants.js\";\n\n/**\n * Name of the {@link throttlingRetryPolicy}\n */\nexport const throttlingRetryPolicyName = \"throttlingRetryPolicy\";\n\n/**\n * Options that control how to retry failed requests.\n */\nexport interface ThrottlingRetryPolicyOptions {\n /**\n * The maximum number of retry attempts. Defaults to 3.\n */\n maxRetries?: number;\n}\n\n/**\n * A policy that retries when the server sends a 429 response with a Retry-After header.\n *\n * To learn more, please refer to\n * https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,\n * https://learn.microsoft.com/en-us/azure/azure-subscription-service-limits and\n * https://learn.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors\n *\n * @param options - Options that configure retry logic.\n */\nexport function throttlingRetryPolicy(options: ThrottlingRetryPolicyOptions = {}): PipelinePolicy {\n return {\n name: throttlingRetryPolicyName,\n sendRequest: retryPolicy([throttlingRetryStrategy()], {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT,\n }).sendRequest,\n };\n}\n"]}
@@ -0,0 +1,11 @@
import type { PipelinePolicy } from "../pipeline.js";
import type { TlsSettings } from "../interfaces.js";
/**
* Name of the TLS Policy
*/
export declare const tlsPolicyName = "tlsPolicy";
/**
* Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
*/
export declare function tlsPolicy(tlsSettings?: TlsSettings): PipelinePolicy;
//# sourceMappingURL=tlsPolicy.d.ts.map
+22
View File
@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* Name of the TLS Policy
*/
export const tlsPolicyName = "tlsPolicy";
/**
* Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
*/
export function tlsPolicy(tlsSettings) {
return {
name: tlsPolicyName,
sendRequest: async (req, next) => {
// Users may define a request tlsSettings, honor those over the client level one
if (!req.tlsSettings) {
req.tlsSettings = tlsSettings;
}
return next(req);
},
};
}
//# sourceMappingURL=tlsPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"tlsPolicy.js","sourceRoot":"","sources":["../../../src/policies/tlsPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,WAAW,CAAC;AAEzC;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,WAAyB;IACjD,OAAO;QACL,IAAI,EAAE,aAAa;QACnB,WAAW,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;YAC/B,gFAAgF;YAChF,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC;gBACrB,GAAG,CAAC,WAAW,GAAG,WAAW,CAAC;YAChC,CAAC;YACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport type { TlsSettings } from \"../interfaces.js\";\n\n/**\n * Name of the TLS Policy\n */\nexport const tlsPolicyName = \"tlsPolicy\";\n\n/**\n * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.\n */\nexport function tlsPolicy(tlsSettings?: TlsSettings): PipelinePolicy {\n return {\n name: tlsPolicyName,\n sendRequest: async (req, next) => {\n // Users may define a request tlsSettings, honor those over the client level one\n if (!req.tlsSettings) {\n req.tlsSettings = tlsSettings;\n }\n return next(req);\n },\n };\n}\n"]}
@@ -0,0 +1,29 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the tracingPolicy.
*/
export declare const tracingPolicyName = "tracingPolicy";
/**
* Options to configure the tracing policy.
*/
export interface TracingPolicyOptions {
/**
* String prefix to add to the user agent logged as metadata
* on the generated Span.
* Defaults to an empty string.
*/
userAgentPrefix?: string;
/**
* Query string names whose values will be logged when logging is enabled. By default no
* query string values are logged.
*/
additionalAllowedQueryParameters?: string[];
}
/**
* A simple policy to create OpenTelemetry Spans for each request made by the pipeline
* that has SpanOptions with a parent.
* Requests made without a parent Span will not be recorded.
* @param options - Options to configure the telemetry logged by the tracing policy.
*/
export declare function tracingPolicy(options?: TracingPolicyOptions): PipelinePolicy;
//# sourceMappingURL=tracingPolicy.d.ts.map
@@ -0,0 +1,132 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { createTracingClient, } from "@azure/core-tracing";
import { SDK_VERSION } from "../constants.js";
import { getUserAgentValue } from "../util/userAgent.js";
import { logger } from "../log.js";
import { getErrorMessage, isError } from "@azure/core-util";
import { isRestError } from "../restError.js";
import { Sanitizer } from "../util/sanitizer.js";
/**
* The programmatic identifier of the tracingPolicy.
*/
export const tracingPolicyName = "tracingPolicy";
/**
* A simple policy to create OpenTelemetry Spans for each request made by the pipeline
* that has SpanOptions with a parent.
* Requests made without a parent Span will not be recorded.
* @param options - Options to configure the telemetry logged by the tracing policy.
*/
export function tracingPolicy(options = {}) {
const userAgentPromise = getUserAgentValue(options.userAgentPrefix);
const sanitizer = new Sanitizer({
additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
});
const tracingClient = tryCreateTracingClient();
return {
name: tracingPolicyName,
async sendRequest(request, next) {
var _a;
if (!tracingClient) {
return next(request);
}
const userAgent = await userAgentPromise;
const spanAttributes = {
"http.url": sanitizer.sanitizeUrl(request.url),
"http.method": request.method,
"http.user_agent": userAgent,
requestId: request.requestId,
};
if (userAgent) {
spanAttributes["http.user_agent"] = userAgent;
}
const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {};
if (!span || !tracingContext) {
return next(request);
}
try {
const response = await tracingClient.withContext(tracingContext, next, request);
tryProcessResponse(span, response);
return response;
}
catch (err) {
tryProcessError(span, err);
throw err;
}
},
};
}
function tryCreateTracingClient() {
try {
return createTracingClient({
namespace: "",
packageName: "@azure/core-rest-pipeline",
packageVersion: SDK_VERSION,
});
}
catch (e) {
logger.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`);
return undefined;
}
}
function tryCreateSpan(tracingClient, request, spanAttributes) {
try {
// As per spec, we do not need to differentiate between HTTP and HTTPS in span name.
const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
spanKind: "client",
spanAttributes,
});
// If the span is not recording, don't do any more work.
if (!span.isRecording()) {
span.end();
return undefined;
}
// set headers
const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
for (const [key, value] of Object.entries(headers)) {
request.headers.set(key, value);
}
return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
}
catch (e) {
logger.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`);
return undefined;
}
}
function tryProcessError(span, error) {
try {
span.setStatus({
status: "error",
error: isError(error) ? error : undefined,
});
if (isRestError(error) && error.statusCode) {
span.setAttribute("http.status_code", error.statusCode);
}
span.end();
}
catch (e) {
logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
}
}
function tryProcessResponse(span, response) {
try {
span.setAttribute("http.status_code", response.status);
const serviceRequestId = response.headers.get("x-ms-request-id");
if (serviceRequestId) {
span.setAttribute("serviceRequestId", serviceRequestId);
}
// Per semantic conventions, only set the status to error if the status code is 4xx or 5xx.
// Otherwise, the status MUST remain unset.
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
if (response.status >= 400) {
span.setStatus({
status: "error",
});
}
span.end();
}
catch (e) {
logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`);
}
}
//# sourceMappingURL=tracingPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"tracingPolicy.js","sourceRoot":"","sources":["../../../src/policies/tracingPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAIL,mBAAmB,GACpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,eAAe,CAAC;AAmBjD;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,UAAgC,EAAE;IAC9D,MAAM,gBAAgB,GAAG,iBAAiB,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;IACpE,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC;QAC9B,gCAAgC,EAAE,OAAO,CAAC,gC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,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC5F,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport {\n type TracingClient,\n type TracingContext,\n type TracingSpan,\n createTracingClient,\n} from \"@azure/core-tracing\";\nimport { SDK_VERSION } from \"../constants.js\";\nimport type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { getUserAgentValue } from \"../util/userAgent.js\";\nimport { logger } from \"../log.js\";\nimport { getErrorMessage, isError } from \"@azure/core-util\";\nimport { isRestError } from \"../restError.js\";\nimport { Sanitizer } from \"../util/sanitizer.js\";\n\n/**\n * The programmatic identifier of the tracingPolicy.\n */\nexport const tracingPolicyName = \"tracingPolicy\";\n\n/**\n * Options to configure the tracing policy.\n */\nexport interface TracingPolicyOptions {\n /**\n * String prefix to add to the user agent logged as metadata\n * on the generated Span.\n * Defaults to an empty string.\n */\n userAgentPrefix?: string;\n /**\n * QueryLine truncated
@@ -0,0 +1,22 @@
import type { PipelinePolicy } from "../pipeline.js";
/**
* The programmatic identifier of the userAgentPolicy.
*/
export declare const userAgentPolicyName = "userAgentPolicy";
/**
* Options for adding user agent details to outgoing requests.
*/
export interface UserAgentPolicyOptions {
/**
* String prefix to add to the user agent for outgoing requests.
* Defaults to an empty string.
*/
userAgentPrefix?: string;
}
/**
* A policy that sets the User-Agent header (or equivalent) to reflect
* the library version.
* @param options - Options to customize the user agent value.
*/
export declare function userAgentPolicy(options?: UserAgentPolicyOptions): PipelinePolicy;
//# sourceMappingURL=userAgentPolicy.d.ts.map
@@ -0,0 +1,26 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { getUserAgentHeaderName, getUserAgentValue } from "../util/userAgent.js";
const UserAgentHeaderName = getUserAgentHeaderName();
/**
* The programmatic identifier of the userAgentPolicy.
*/
export const userAgentPolicyName = "userAgentPolicy";
/**
* A policy that sets the User-Agent header (or equivalent) to reflect
* the library version.
* @param options - Options to customize the user agent value.
*/
export function userAgentPolicy(options = {}) {
const userAgentValue = getUserAgentValue(options.userAgentPrefix);
return {
name: userAgentPolicyName,
async sendRequest(request, next) {
if (!request.headers.has(UserAgentHeaderName)) {
request.headers.set(UserAgentHeaderName, await userAgentValue);
}
return next(request);
},
};
}
//# sourceMappingURL=userAgentPolicy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"userAgentPolicy.js","sourceRoot":"","sources":["../../../src/policies/userAgentPolicy.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEjF,MAAM,mBAAmB,GAAG,sBAAsB,EAAE,CAAC;AAErD;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,iBAAiB,CAAC;AAarD;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,UAAkC,EAAE;IAClE,MAAM,cAAc,GAAG,iBAAiB,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;IAClE,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,KAAK,CAAC,WAAW,CAAC,OAAwB,EAAE,IAAiB;YAC3D,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAE,CAAC;gBAC9C,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,MAAM,cAAc,CAAC,CAAC;YACjE,CAAC;YACD,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 type { PipelineRequest, PipelineResponse, SendRequest } from \"../interfaces.js\";\nimport type { PipelinePolicy } from \"../pipeline.js\";\nimport { getUserAgentHeaderName, getUserAgentValue } from \"../util/userAgent.js\";\n\nconst UserAgentHeaderName = getUserAgentHeaderName();\n\n/**\n * The programmatic identifier of the userAgentPolicy.\n */\nexport const userAgentPolicyName = \"userAgentPolicy\";\n\n/**\n * Options for adding user agent details to outgoing requests.\n */\nexport interface UserAgentPolicyOptions {\n /**\n * String prefix to add to the user agent for outgoing requests.\n * Defaults to an empty string.\n */\n userAgentPrefix?: string;\n}\n\n/**\n * A policy that sets the User-Agent header (or equivalent) to reflect\n * the library version.\n * @param options - Options to customize the user agent value.\n */\nexport function userAgentPolicy(options: UserAgentPolicyOptions = {}): PipelinePolicy {\n const userAgentValue = getUserAgentValue(options.userAgentPrefix);\n return {\n name: userAgentPolicyName,\n async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {\n if (!request.headers.has(UserAgentHeaderName)) {\n request.headers.set(UserAgentHeaderName, await userAgentValue);\n }\n return next(request);\n },\n };\n}\n"]}
+68
View File
@@ -0,0 +1,68 @@
import type { PipelineRequest, PipelineResponse } from "./interfaces.js";
/**
* The options supported by RestError.
*/
export interface RestErrorOptions {
/**
* The code of the error itself (use statics on RestError if possible.)
*/
code?: string;
/**
* The HTTP status code of the request (if applicable.)
*/
statusCode?: number;
/**
* The request that was made.
*/
request?: PipelineRequest;
/**
* The response received (if any.)
*/
response?: PipelineResponse;
}
/**
* A custom error type for failed pipeline requests.
*/
export declare class RestError extends Error {
[x: symbol]: () => string;
/**
* Something went wrong when making the request.
* This means the actual request failed for some reason,
* such as a DNS issue or the connection being lost.
*/
static readonly REQUEST_SEND_ERROR: string;
/**
* This means that parsing the response from the server failed.
* It may have been malformed.
*/
static readonly PARSE_ERROR: string;
/**
* The code of the error itself (use statics on RestError if possible.)
*/
code?: string;
/**
* The HTTP status code of the request (if applicable.)
*/
statusCode?: number;
/**
* The request that was made.
* This property is non-enumerable.
*/
request?: PipelineRequest;
/**
* The response received (if any.)
* This property is non-enumerable.
*/
response?: PipelineResponse;
/**
* Bonus property set by the throw site.
*/
details?: unknown;
constructor(message: string, options?: RestErrorOptions);
}
/**
* Typeguard for RestError
* @param e - Something caught by a catch clause.
*/
export declare function isRestError(e: unknown): e is RestError;
//# sourceMappingURL=restError.d.ts.map
+54
View File
@@ -0,0 +1,54 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { isError } from "@azure/core-util";
import { custom } from "./util/inspect.js";
import { Sanitizer } from "./util/sanitizer.js";
const errorSanitizer = new Sanitizer();
/**
* A custom error type for failed pipeline requests.
*/
export class RestError extends Error {
constructor(message, options = {}) {
super(message);
this.name = "RestError";
this.code = options.code;
this.statusCode = options.statusCode;
// The request and response may contain sensitive information in the headers or body.
// To help prevent this sensitive information being accidentally logged, the request and response
// properties are marked as non-enumerable here. This prevents them showing up in the output of
// JSON.stringify and console.log.
Object.defineProperty(this, "request", { value: options.request, enumerable: false });
Object.defineProperty(this, "response", { value: options.response, enumerable: false });
Object.setPrototypeOf(this, RestError.prototype);
}
/**
* Logging method for util.inspect in Node
*/
[custom]() {
// Extract non-enumerable properties and add them back. This is OK since in this output the request and
// response get sanitized.
return `RestError: ${this.message} \n ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`;
}
}
/**
* Something went wrong when making the request.
* This means the actual request failed for some reason,
* such as a DNS issue or the connection being lost.
*/
RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
/**
* This means that parsing the response from the server failed.
* It may have been malformed.
*/
RestError.PARSE_ERROR = "PARSE_ERROR";
/**
* Typeguard for RestError
* @param e - Something caught by a catch clause.
*/
export function isRestError(e) {
if (e instanceof RestError) {
return true;
}
return isError(e) && e.name === "RestError";
}
//# sourceMappingURL=restError.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"restError.js","sourceRoot":"","sources":["../../src/restError.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAE3C,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,SAAS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D,OAAO,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC;AAC9C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { isError } from \"@azure/core-util\";\nimport type { PipelineRequest, PipelineResponse } from \"./interfaces.js\";\nimport { custom } from \"./util/inspect.js\";\nimport { Sanitizer } from \"./util/sanitizer.js\";\n\nconst errorSanitizer = new Sanitizer();\n\n/**\n * The options supported by RestError.\n */\nexport interface RestErrorOptions {\n /**\n * The code of the error itself (use statics on RestError if possible.)\n */\n code?: string;\n /**\n * The HTTP status code of the request (if applicable.)\n */\n statusCode?: number;\n /**\n * The request that was made.\n */\n request?: PipelineRequest;\n /**\n * The response received (if any.)\n */\n response?: PipelineResponse;\n}\n\n/**\n * A custom error type for failed pipeline requests.\n */\nexport class RestError extends Error {\n /**\n * Something went wrong when making the request.\n * This means the actual request failed for some reason,\n * such as a DNS issue or the connection being lost.\n */\n static readonly REQUEST_SEND_ERROR: string = \"REQUEST_SEND_ERROR\";\n /**\n * This means that parsing the response from the server failed.\n * It may have been malformed.\n */\n static readonly PARSE_ERROR: string = \"PARSE_ERROR\";\n\n /**\n * The code of the error itself (use statics on RestError if possible.)\n */\n public code?: string;\n /**\n * The HTTP status code of the request (if applicable.)\n */\n public statusCode?: number;\n /**\n * The request that was made.\n * This property is non-enumerable.\n */\n public request?: PipelineRequest;\n /**\n * The response received (if any.)\n * This property is non-enumerable.\n */\n public response?: PipelineResponse;\n /**\n * Bonus property set by the throw site.\n */\n public details?: unknown;\n\n constructor(message: string, options: RestErrorOptions = {}) {\n super(message);\n this.name = \"RestError\";\n this.code = options.code;\n this.statusCode = options.statusCode;\n\n // The request and response may contain sensitive information in the headers or body.\n // To help prevent this sensitive information being accidentally logged, the request and response\n // properties are marked as non-enumerable here. This prevents them showing up in the output of\n // JSON.stringify and console.log.\n Object.defineProperty(this, \"request\", { value: options.request, enumerable: false });\n Object.defineProperty(this, \"response\", { value: options.response, enumerable: false });\n\n Object.setPrototypeOf(this, RestError.prototype);\n }\n\n /**\n * Logging method for util.inspect in Node\n */\n [custom](): string {\n // Extract non-enumerable properties and add them back. This is OK since in this output the request and\n // response get sanitized.\n return `RestError: ${this.message} \\n ${errorSanitizer.sanitize({\n ...this,\n request: this.request,\n response: this.response,\n })}`;\n }\n}\n\n/**\n * Typeguard for RestError\n * @param e - Something caught by a catch clause.\n */\nexport function isRestError(e: unknown): e is RestError {\n if (e instanceof RestError) {\n return true;\n }\n return isError(e) && e.name === \"RestError\";\n}\n"]}
Loaded 100 of 55743 files, more files were not shown because too many files have changed in this diff. Show more