@typespec/ts-http-runtime 1.0.0-alpha.20241021.2 → 1.0.0-alpha.20241022.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/auth/tokenCredential.d.ts +4 -0
- package/dist/browser/auth/tokenCredential.d.ts.map +1 -1
- package/dist/browser/auth/tokenCredential.js.map +1 -1
- package/dist/browser/client/common.d.ts +4 -9
- package/dist/browser/client/common.d.ts.map +1 -1
- package/dist/browser/client/common.js.map +1 -1
- package/dist/browser/client/getClient.js +3 -2
- package/dist/browser/client/getClient.js.map +1 -1
- package/dist/browser/client/sendRequest.d.ts.map +1 -1
- package/dist/browser/client/sendRequest.js +28 -18
- package/dist/browser/client/sendRequest.js.map +1 -1
- package/dist/browser/client/urlHelpers.d.ts +1 -1
- package/dist/browser/client/urlHelpers.d.ts.map +1 -1
- package/dist/browser/client/urlHelpers.js +3 -3
- package/dist/browser/client/urlHelpers.js.map +1 -1
- package/dist/browser/fetchHttpClient.d.ts.map +1 -1
- package/dist/browser/fetchHttpClient.js +3 -3
- package/dist/browser/fetchHttpClient.js.map +1 -1
- package/dist/browser/interfaces.d.ts.map +1 -1
- package/dist/browser/interfaces.js.map +1 -1
- package/dist/browser/nodeHttpClient.d.ts.map +1 -1
- package/dist/browser/nodeHttpClient.js +9 -3
- package/dist/browser/nodeHttpClient.js.map +1 -1
- package/dist/browser/policies/formDataPolicy.js.map +1 -1
- package/dist/browser/policies/multipartPolicy.js.map +1 -1
- package/dist/browser/policies/tracingPolicy.js +2 -2
- package/dist/browser/policies/tracingPolicy.js.map +1 -1
- package/dist/browser/retryStrategies/throttlingRetryStrategy.js +1 -1
- package/dist/browser/retryStrategies/throttlingRetryStrategy.js.map +1 -1
- package/dist/browser/util/checkEnvironment.d.ts +4 -16
- package/dist/browser/util/checkEnvironment.d.ts.map +1 -1
- package/dist/browser/util/checkEnvironment.js +4 -4
- package/dist/browser/util/checkEnvironment.js.map +1 -1
- package/dist/browser/util/sanitizer.js.map +1 -1
- package/dist/browser/util/tokenCycler.d.ts.map +1 -1
- package/dist/browser/util/tokenCycler.js +7 -2
- package/dist/browser/util/tokenCycler.js.map +1 -1
- package/dist/browser/util/uuidUtils.common.d.ts.map +1 -1
- package/dist/browser/util/uuidUtils.common.js +0 -3
- package/dist/browser/util/uuidUtils.common.js.map +1 -1
- package/dist/commonjs/auth/tokenCredential.d.ts +4 -0
- package/dist/commonjs/auth/tokenCredential.d.ts.map +1 -1
- package/dist/commonjs/auth/tokenCredential.js.map +1 -1
- package/dist/commonjs/client/common.d.ts +4 -9
- package/dist/commonjs/client/common.d.ts.map +1 -1
- package/dist/commonjs/client/common.js.map +1 -1
- package/dist/commonjs/client/getClient.js +3 -2
- package/dist/commonjs/client/getClient.js.map +1 -1
- package/dist/commonjs/client/sendRequest.d.ts.map +1 -1
- package/dist/commonjs/client/sendRequest.js +27 -17
- package/dist/commonjs/client/sendRequest.js.map +1 -1
- package/dist/commonjs/client/urlHelpers.d.ts +1 -1
- package/dist/commonjs/client/urlHelpers.d.ts.map +1 -1
- package/dist/commonjs/client/urlHelpers.js +3 -3
- package/dist/commonjs/client/urlHelpers.js.map +1 -1
- package/dist/commonjs/fetchHttpClient.d.ts.map +1 -1
- package/dist/commonjs/fetchHttpClient.js +2 -2
- package/dist/commonjs/fetchHttpClient.js.map +1 -1
- package/dist/commonjs/interfaces.d.ts.map +1 -1
- package/dist/commonjs/interfaces.js.map +1 -1
- package/dist/commonjs/nodeHttpClient.d.ts.map +1 -1
- package/dist/commonjs/nodeHttpClient.js +9 -3
- package/dist/commonjs/nodeHttpClient.js.map +1 -1
- package/dist/commonjs/policies/formDataPolicy.js.map +1 -1
- package/dist/commonjs/policies/multipartPolicy.js.map +1 -1
- package/dist/commonjs/policies/proxyPolicy.js +1 -1
- package/dist/commonjs/policies/proxyPolicy.js.map +1 -1
- package/dist/commonjs/policies/tracingPolicy.js +2 -2
- package/dist/commonjs/policies/tracingPolicy.js.map +1 -1
- package/dist/commonjs/retryStrategies/throttlingRetryStrategy.js +1 -1
- package/dist/commonjs/retryStrategies/throttlingRetryStrategy.js.map +1 -1
- package/dist/commonjs/util/checkEnvironment.d.ts +4 -16
- package/dist/commonjs/util/checkEnvironment.d.ts.map +1 -1
- package/dist/commonjs/util/checkEnvironment.js +5 -5
- package/dist/commonjs/util/checkEnvironment.js.map +1 -1
- package/dist/commonjs/util/sanitizer.js.map +1 -1
- package/dist/commonjs/util/tokenCycler.d.ts.map +1 -1
- package/dist/commonjs/util/tokenCycler.js +7 -2
- package/dist/commonjs/util/tokenCycler.js.map +1 -1
- package/dist/commonjs/util/uuidUtils.common.d.ts.map +1 -1
- package/dist/commonjs/util/uuidUtils.common.js +0 -3
- package/dist/commonjs/util/uuidUtils.common.js.map +1 -1
- package/dist/commonjs/util/uuidUtils.d.ts.map +1 -1
- package/dist/commonjs/util/uuidUtils.js +1 -6
- package/dist/commonjs/util/uuidUtils.js.map +1 -1
- package/dist/esm/auth/tokenCredential.d.ts +4 -0
- package/dist/esm/auth/tokenCredential.d.ts.map +1 -1
- package/dist/esm/auth/tokenCredential.js.map +1 -1
- package/dist/esm/client/common.d.ts +4 -9
- package/dist/esm/client/common.d.ts.map +1 -1
- package/dist/esm/client/common.js.map +1 -1
- package/dist/esm/client/getClient.js +3 -2
- package/dist/esm/client/getClient.js.map +1 -1
- package/dist/esm/client/sendRequest.d.ts.map +1 -1
- package/dist/esm/client/sendRequest.js +28 -18
- package/dist/esm/client/sendRequest.js.map +1 -1
- package/dist/esm/client/urlHelpers.d.ts +1 -1
- package/dist/esm/client/urlHelpers.d.ts.map +1 -1
- package/dist/esm/client/urlHelpers.js +3 -3
- package/dist/esm/client/urlHelpers.js.map +1 -1
- package/dist/esm/fetchHttpClient.d.ts.map +1 -1
- package/dist/esm/fetchHttpClient.js +3 -3
- package/dist/esm/fetchHttpClient.js.map +1 -1
- package/dist/esm/interfaces.d.ts.map +1 -1
- package/dist/esm/interfaces.js.map +1 -1
- package/dist/esm/nodeHttpClient.d.ts.map +1 -1
- package/dist/esm/nodeHttpClient.js +9 -3
- package/dist/esm/nodeHttpClient.js.map +1 -1
- package/dist/esm/policies/formDataPolicy.js.map +1 -1
- package/dist/esm/policies/multipartPolicy.js.map +1 -1
- package/dist/esm/policies/proxyPolicy.js +1 -1
- package/dist/esm/policies/proxyPolicy.js.map +1 -1
- package/dist/esm/policies/tracingPolicy.js +2 -2
- package/dist/esm/policies/tracingPolicy.js.map +1 -1
- package/dist/esm/retryStrategies/throttlingRetryStrategy.js +1 -1
- package/dist/esm/retryStrategies/throttlingRetryStrategy.js.map +1 -1
- package/dist/esm/util/checkEnvironment.d.ts +4 -16
- package/dist/esm/util/checkEnvironment.d.ts.map +1 -1
- package/dist/esm/util/checkEnvironment.js +4 -4
- package/dist/esm/util/checkEnvironment.js.map +1 -1
- package/dist/esm/util/sanitizer.js.map +1 -1
- package/dist/esm/util/tokenCycler.d.ts.map +1 -1
- package/dist/esm/util/tokenCycler.js +7 -2
- package/dist/esm/util/tokenCycler.js.map +1 -1
- package/dist/esm/util/uuidUtils.common.d.ts.map +1 -1
- package/dist/esm/util/uuidUtils.common.js +0 -3
- package/dist/esm/util/uuidUtils.common.js.map +1 -1
- package/dist/esm/util/uuidUtils.d.ts.map +1 -1
- package/dist/esm/util/uuidUtils.js +1 -6
- package/dist/esm/util/uuidUtils.js.map +1 -1
- package/dist/react-native/auth/tokenCredential.d.ts +4 -0
- package/dist/react-native/auth/tokenCredential.d.ts.map +1 -1
- package/dist/react-native/auth/tokenCredential.js.map +1 -1
- package/dist/react-native/client/common.d.ts +4 -9
- package/dist/react-native/client/common.d.ts.map +1 -1
- package/dist/react-native/client/common.js.map +1 -1
- package/dist/react-native/client/getClient.js +3 -2
- package/dist/react-native/client/getClient.js.map +1 -1
- package/dist/react-native/client/sendRequest.d.ts.map +1 -1
- package/dist/react-native/client/sendRequest.js +28 -18
- package/dist/react-native/client/sendRequest.js.map +1 -1
- package/dist/react-native/client/urlHelpers.d.ts +1 -1
- package/dist/react-native/client/urlHelpers.d.ts.map +1 -1
- package/dist/react-native/client/urlHelpers.js +3 -3
- package/dist/react-native/client/urlHelpers.js.map +1 -1
- package/dist/react-native/fetchHttpClient.d.ts.map +1 -1
- package/dist/react-native/fetchHttpClient.js +3 -3
- package/dist/react-native/fetchHttpClient.js.map +1 -1
- package/dist/react-native/interfaces.d.ts.map +1 -1
- package/dist/react-native/interfaces.js.map +1 -1
- package/dist/react-native/nodeHttpClient.d.ts.map +1 -1
- package/dist/react-native/nodeHttpClient.js +9 -3
- package/dist/react-native/nodeHttpClient.js.map +1 -1
- package/dist/react-native/policies/formDataPolicy.js.map +1 -1
- package/dist/react-native/policies/multipartPolicy.js.map +1 -1
- package/dist/react-native/policies/tracingPolicy.js +2 -2
- package/dist/react-native/policies/tracingPolicy.js.map +1 -1
- package/dist/react-native/retryStrategies/throttlingRetryStrategy.js +1 -1
- package/dist/react-native/retryStrategies/throttlingRetryStrategy.js.map +1 -1
- package/dist/react-native/util/checkEnvironment.d.ts +4 -16
- package/dist/react-native/util/checkEnvironment.d.ts.map +1 -1
- package/dist/react-native/util/checkEnvironment.js +4 -4
- package/dist/react-native/util/checkEnvironment.js.map +1 -1
- package/dist/react-native/util/sanitizer.js.map +1 -1
- package/dist/react-native/util/tokenCycler.d.ts.map +1 -1
- package/dist/react-native/util/tokenCycler.js +7 -2
- package/dist/react-native/util/tokenCycler.js.map +1 -1
- package/dist/react-native/util/uuidUtils.common.d.ts.map +1 -1
- package/dist/react-native/util/uuidUtils.common.js +0 -3
- package/dist/react-native/util/uuidUtils.common.js.map +1 -1
- package/dist/ts-http-runtime.d.ts +8 -9
- package/package.json +5 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sanitizer.js","sourceRoot":"","sources":["../../../src/util/sanitizer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,
|
|
1
|
+
{"version":3,"file":"sanitizer.js","sourceR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AAS,CAAC;IACnB,CAAC;IAEO,aAAa,CAAC,KAAoB;QACxC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YAChD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,SAAS,GAAkB,EAAE,CAAC;QAEpC,KAAK,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACnC,IAAI,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC;gBACrD,SAAS,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YAC1B,CAAC;iBAAM,CAAC;gBACN,SAAS,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC;YAChC,CAAC;QACH,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { type UnknownObject, isObject } from \"./object.js\";\n\n/**\n * @internal\n */\nexport interface SanitizerOptions {\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\nconst RedactedString = \"REDACTED\";\n\n// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts\nconst defaultAllowedHeaderNames = [\n \"x-ms-client-request-id\",\n \"x-ms-return-client-request-id\",\n \"x-ms-useragent\",\n \"x-ms-correlation-request-id\",\n \"x-ms-request-id\",\n \"client-request-id\",\n \"ms-cv\",\n \"return-client-request-id\",\n \"traceparent\",\n\n \"Access-Control-Allow-Credentials\",\n \"Access-Control-Allow-Headers\",\n \"Access-Control-Allow-Methods\",\n \"Access-Control-Allow-Origin\",\n \"Access-Control-Expose-Headers\",\n \"Access-Control-Max-Age\",\n \"Access-Control-Request-Headers\",\n \"Access-Control-Request-Method\",\n \"Origin\",\n\n \"Accept\",\n \"Accept-Encoding\",\n \"Cache-Control\",\n \"Connection\",\n \"Content-Length\",\n \"Content-Type\",\n \"Date\",\n \"ETag\",\n \"Expires\",\n \"If-Match\",\n \"If-Modified-Since\",\n \"If-None-Match\",\n \"If-Unmodified-Since\",\n \"Last-Modified\",\n \"Pragma\",\n \"Request-Id\",\n \"Retry-After\",\n \"Server\",\n \"Transfer-Encoding\",\n \"User-Agent\",\n \"WWW-Authenticate\",\n];\n\nconst defaultAllowedQueryParameters: string[] = [\"api-version\"];\n\n/**\n * @internal\n */\nexport class Sanitizer {\n private allowedHeaderNames: Set<string>;\n private allowedQueryParameters: Set<string>;\n\n constructor({\n additionalAllowedHeaderNames: allowedHeaderNames = [],\n additionalAllowedQueryParameters: allowedQueryParameters = [],\n }: SanitizerOptions = {}) {\n allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);\n allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);\n\n this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));\n this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));\n }\n\n public sanitize(obj: unknown): string {\n const seen = new Set<unknown>();\n return JSON.stringify(\n obj,\n (key: string, value: unknown) => {\n // Ensure Errors include their interesting non-enumerable members\n if (value instanceof Error) {\n return {\n ...value,\n name: value.name,\n message: value.message,\n };\n }\n\n if (key === \"headers\") {\n return this.sanitizeHeaders(value as UnknownObject);\n } else if (key === \"url\") {\n return this.sanitizeUrl(value as string);\n } else if (key === \"query\") {\n return this.sanitizeQuery(value as UnknownObject);\n } else if (key === \"body\") {\n // Don't log the request body\n return undefined;\n } else if (key === \"response\") {\n // Don't log response again\n return undefined;\n } else if (key === \"operationSpec\") {\n // When using sendOperationRequest, the request carries a massive\n // field with the autorest spec. No need to log it.\n return undefined;\n } else if (Array.isArray(value) || isObject(value)) {\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n }\n\n return value;\n },\n 2,\n );\n }\n\n public sanitizeUrl(value: string): string {\n if (typeof value !== \"string\" || value === null || value === \"\") {\n return value;\n }\n\n const url = new URL(value);\n\n if (!url.search) {\n return value;\n }\n\n for (const [key] of url.searchParams) {\n if (!this.allowedQueryParameters.has(key.toLowerCase())) {\n url.searchParams.set(key, RedactedString);\n }\n }\n\n return url.toString();\n }\n\n private sanitizeHeaders(obj: UnknownObject): UnknownObject {\n const sanitized: UnknownObject = {};\n for (const key of Object.keys(obj)) {\n if (this.allowedHeaderNames.has(key.toLowerCase())) {\n sanitized[key] = obj[key];\n } else {\n sanitized[key] = RedactedString;\n }\n }\n return sanitized;\n }\n\n private sanitizeQuery(value: UnknownObject): UnknownObject {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n\n const sanitized: UnknownObject = {};\n\n for (const k of Object.keys(value)) {\n if (this.allowedQueryParameters.has(k.toLowerCase())) {\n sanitized[k] = value[k];\n } else {\n sanitized[k] = RedactedString;\n }\n }\n\n return sanitized;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenCycler.d.ts","sourceRoot":"","sources":["../../../src/util/tokenCycler.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAG3F;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG,CAC9B,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EACzB,OAAO,EAAE,eAAe,KACrB,OAAO,CAAC,WAAW,CAAC,CAAC;AAE1B,MAAM,WAAW,kBAAkB;IACjC;;;;;;;OAOG;IACH,uBAAuB,EAAE,MAAM,CAAC;IAChC;;OAEG;IACH,iBAAiB,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAGD,eAAO,MAAM,sBAAsB,EAAE,kBAIpC,CAAC;AAiDF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,EAAE,eAAe,EAC3B,kBAAkB,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAC/C,iBAAiB,
|
|
1
|
+
{"version":3,"file":"tokenCycler.d.ts","sourceRoot":"","sources":["../../../src/util/tokenCycler.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAG3F;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG,CAC9B,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EACzB,OAAO,EAAE,eAAe,KACrB,OAAO,CAAC,WAAW,CAAC,CAAC;AAE1B,MAAM,WAAW,kBAAkB;IACjC;;;;;;;OAOG;IACH,uBAAuB,EAAE,MAAM,CAAC;IAChC;;OAEG;IACH,iBAAiB,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAGD,eAAO,MAAM,sBAAsB,EAAE,kBAIpC,CAAC;AAiDF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,EAAE,eAAe,EAC3B,kBAAkB,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAC/C,iBAAiB,CA0HnB"}
|
|
@@ -81,8 +81,13 @@ export function createTokenCycler(credential, tokenCyclerOptions) {
|
|
|
81
81
|
*/
|
|
82
82
|
get shouldRefresh() {
|
|
83
83
|
var _a;
|
|
84
|
-
|
|
85
|
-
|
|
84
|
+
if (cycler.isRefreshing) {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) {
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now();
|
|
86
91
|
},
|
|
87
92
|
/**
|
|
88
93
|
* Produces true if the cycler MUST refresh (null or nearly-expired
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenCycler.js","sourceRoot":"","sources":["../../../src/util/tokenCycler.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAkCrC,sDAAsD;AACtD,MAAM,CAAC,MAAM,sBAAsB,GAAuB;IACxD,uBAAuB,EAAE,IAAI,EAAE,0DAA0D;IACzF,iBAAiB,EAAE,IAAI,EAAE,kCAAkC;IAC3D,iBAAiB,EAAE,IAAI,GAAG,EAAE,GAAG,CAAC,EAAE,oCAAoC;CACvE,CAAC;AAEF;;;;;;;;;GASG;AACH,KAAK,UAAU,YAAY,CACzB,cAAiD,EACjD,iBAAyB,EACzB,cAAsB;IAEtB,4EAA4E;IAC5E,eAAe;IACf,KAAK,UAAU,iBAAiB;QAC9B,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,cAAc,EAAE,CAAC;YAChC,IAAI,CAAC;gBACH,OAAO,MAAM,cAAc,EAAE,CAAC;YAChC,CAAC;YAAC,WAAM,CAAC;gBACP,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;aAAM,CAAC;YACN,MAAM,UAAU,GAAG,MAAM,cAAc,EAAE,CAAC;YAE1C,6CAA6C;YAC7C,IAAI,UAAU,KAAK,IAAI,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;YACrD,CAAC;YAED,OAAO,UAAU,CAAC;QACpB,CAAC;IACH,CAAC;IAED,IAAI,KAAK,GAAuB,MAAM,iBAAiB,EAAE,CAAC;IAE1D,OAAO,KAAK,KAAK,IAAI,EAAE,CAAC;QACtB,MAAM,K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AE,CAAC;YACzB,OAAO,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;QAChC,CAAC;QAED,OAAO,KAAoB,CAAC;IAC9B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"../auth/tokenCredential.js\";\nimport { delay } from \"./helpers.js\";\n\n/**\n * A function that gets a promise of an access token and allows providing\n * options.\n *\n * @param options - the options to pass to the underlying token provider\n */\nexport type AccessTokenGetter = (\n scopes: string | string[],\n options: GetTokenOptions,\n) => Promise<AccessToken>;\n\nexport interface TokenCyclerOptions {\n /**\n * The window of time before token expiration during which the token will be\n * considered unusable due to risk of the token expiring before sending the\n * request.\n *\n * This will only become meaningful if the refresh fails for over\n * (refreshWindow - forcedRefreshWindow) milliseconds.\n */\n forcedRefreshWindowInMs: number;\n /**\n * Interval in milliseconds to retry failed token refreshes.\n */\n retryIntervalInMs: number;\n /**\n * The window of time before token expiration during which\n * we will attempt to refresh the token.\n */\n refreshWindowInMs: number;\n}\n\n// Default options for the cycler if none are provided\nexport const DEFAULT_CYCLER_OPTIONS: TokenCyclerOptions = {\n forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires\n retryIntervalInMs: 3000, // Allow refresh attempts every 3s\n refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry\n};\n\n/**\n * Converts an an unreliable access token getter (which may resolve with null)\n * into an AccessTokenGetter by retrying the unreliable getter in a regular\n * interval.\n *\n * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.\n * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.\n * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.\n * @returns - A promise that, if it resolves, will resolve with an access token.\n */\nasync function beginRefresh(\n getAccessToken: () => Promise<AccessToken | null>,\n retryIntervalInMs: number,\n refreshTimeout: number,\n): Promise<AccessToken> {\n // This wrapper handles exceptions gracefully as long as we haven't exceeded\n // the timeout.\n async function tryGetAccessToken(): Promise<AccessToken | null> {\n if (Date.now() < refreshTimeout) {\n try {\n return await getAccessToken();\n } catch {\n return null;\n }\n } else {\n const finalToken = await getAccessToken();\n\n // Timeout is up, so throw if it's still null\n if (finalToken === null) {\n throw new Error(\"Failed to refresh access token.\");\n }\n\n return finalToken;\n }\n }\n\n let token: AccessToken | null = await tryGetAccessToken();\n\n while (token === null) {\n await delay(retryIntervalInMs);\n\n token = await tryGetAccessToken();\n }\n\n return token;\n}\n\n/**\n * Creates a token cycler from a credential, scopes, and optional settings.\n *\n * A token cycler represents a way to reliably retrieve a valid access token\n * from a TokenCredential. It will handle initializing the token, refreshing it\n * when it nears expiration, and synchronizes refresh attempts to avoid\n * concurrency hazards.\n *\n * @param credential - the underlying TokenCredential that provides the access\n * token\n * @param tokenCyclerOptions - optionally override default settings for the cycler\n *\n * @returns - a function that reliably produces a valid access token\n */\nexport function createTokenCycler(\n credential: TokenCredential,\n tokenCyclerOptions?: Partial<TokenCyclerOptions>,\n): AccessTokenGetter {\n let refreshWorker: Promise<AccessToken> | null = null;\n let token: AccessToken | null = null;\n let tenantId: string | undefined;\n\n const options = {\n ...DEFAULT_CYCLER_OPTIONS,\n ...tokenCyclerOptions,\n };\n\n /**\n * This little holder defines several predicates that we use to construct\n * the rules of refreshing the token.\n */\n const cycler = {\n /**\n * Produces true if a refresh job is currently in progress.\n */\n get isRefreshing(): boolean {\n return refreshWorker !== null;\n },\n /**\n * Produces true if the cycler SHOULD refresh (we are within the refresh\n * window and not already refreshing)\n */\n get shouldRefresh(): boolean {\n return (\n !cycler.isRefreshing &&\n (token?.expiresOnTimestamp ?? 0) - options.refreshWindowInMs < Date.now()\n );\n },\n /**\n * Produces true if the cycler MUST refresh (null or nearly-expired\n * token).\n */\n get mustRefresh(): boolean {\n return (\n token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()\n );\n },\n };\n\n /**\n * Starts a refresh job or returns the existing job if one is already\n * running.\n */\n function refresh(\n scopes: string | string[],\n getTokenOptions: GetTokenOptions,\n ): Promise<AccessToken> {\n if (!cycler.isRefreshing) {\n // We bind `scopes` here to avoid passing it around a lot\n const tryGetAccessToken = (): Promise<AccessToken | null> =>\n credential.getToken(scopes, getTokenOptions);\n\n // Take advantage of promise chaining to insert an assignment to `token`\n // before the refresh can be considered done.\n refreshWorker = beginRefresh(\n tryGetAccessToken,\n options.retryIntervalInMs,\n // If we don't have a token, then we should timeout immediately\n token?.expiresOnTimestamp ?? Date.now(),\n )\n .then((_token) => {\n refreshWorker = null;\n token = _token;\n tenantId = getTokenOptions.tenantId;\n return token;\n })\n .catch((reason) => {\n // We also should reset the refresher if we enter a failed state. All\n // existing awaiters will throw, but subsequent requests will start a\n // new retry chain.\n refreshWorker = null;\n token = null;\n tenantId = undefined;\n throw reason;\n });\n }\n\n return refreshWorker as Promise<AccessToken>;\n }\n\n return async (scopes: string | string[], tokenOptions: GetTokenOptions): Promise<AccessToken> => {\n //\n // Simple rules:\n // - If we MUST refresh, then return the refresh task, blocking\n // the pipeline until a token is available.\n // - If we SHOULD refresh, then run refresh but don't return it\n // (we can still use the cached token).\n // - Return the token, since it's fine if we didn't return in\n // step 1.\n //\n\n const hasClaimChallenge = Boolean(tokenOptions.claims);\n const tenantIdChanged = tenantId !== tokenOptions.tenantId;\n\n if (hasClaimChallenge) {\n // If we've received a claim, we know the existing token isn't valid\n // We want to clear it so that that refresh worker won't use the old expiration time as a timeout\n token = null;\n }\n\n // If the tenantId passed in token options is different to the one we have\n // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to\n // refresh the token with the new tenantId or token.\n const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;\n\n if (mustRefresh) {\n return refresh(scopes, tokenOptions);\n }\n\n if (cycler.shouldRefresh) {\n refresh(scopes, tokenOptions);\n }\n\n return token as AccessToken;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tokenCycler.js","sourceRoot":"","sources":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AAE,YAAY,CAAC,CAAC;QAChC,CAAC;QAED,OAAO,KAAoB,CAAC;IAC9B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"../auth/tokenCredential.js\";\nimport { delay } from \"./helpers.js\";\n\n/**\n * A function that gets a promise of an access token and allows providing\n * options.\n *\n * @param options - the options to pass to the underlying token provider\n */\nexport type AccessTokenGetter = (\n scopes: string | string[],\n options: GetTokenOptions,\n) => Promise<AccessToken>;\n\nexport interface TokenCyclerOptions {\n /**\n * The window of time before token expiration during which the token will be\n * considered unusable due to risk of the token expiring before sending the\n * request.\n *\n * This will only become meaningful if the refresh fails for over\n * (refreshWindow - forcedRefreshWindow) milliseconds.\n */\n forcedRefreshWindowInMs: number;\n /**\n * Interval in milliseconds to retry failed token refreshes.\n */\n retryIntervalInMs: number;\n /**\n * The window of time before token expiration during which\n * we will attempt to refresh the token.\n */\n refreshWindowInMs: number;\n}\n\n// Default options for the cycler if none are provided\nexport const DEFAULT_CYCLER_OPTIONS: TokenCyclerOptions = {\n forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires\n retryIntervalInMs: 3000, // Allow refresh attempts every 3s\n refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry\n};\n\n/**\n * Converts an an unreliable access token getter (which may resolve with null)\n * into an AccessTokenGetter by retrying the unreliable getter in a regular\n * interval.\n *\n * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.\n * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.\n * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.\n * @returns - A promise that, if it resolves, will resolve with an access token.\n */\nasync function beginRefresh(\n getAccessToken: () => Promise<AccessToken | null>,\n retryIntervalInMs: number,\n refreshTimeout: number,\n): Promise<AccessToken> {\n // This wrapper handles exceptions gracefully as long as we haven't exceeded\n // the timeout.\n async function tryGetAccessToken(): Promise<AccessToken | null> {\n if (Date.now() < refreshTimeout) {\n try {\n return await getAccessToken();\n } catch {\n return null;\n }\n } else {\n const finalToken = await getAccessToken();\n\n // Timeout is up, so throw if it's still null\n if (finalToken === null) {\n throw new Error(\"Failed to refresh access token.\");\n }\n\n return finalToken;\n }\n }\n\n let token: AccessToken | null = await tryGetAccessToken();\n\n while (token === null) {\n await delay(retryIntervalInMs);\n\n token = await tryGetAccessToken();\n }\n\n return token;\n}\n\n/**\n * Creates a token cycler from a credential, scopes, and optional settings.\n *\n * A token cycler represents a way to reliably retrieve a valid access token\n * from a TokenCredential. It will handle initializing the token, refreshing it\n * when it nears expiration, and synchronizes refresh attempts to avoid\n * concurrency hazards.\n *\n * @param credential - the underlying TokenCredential that provides the access\n * token\n * @param tokenCyclerOptions - optionally override default settings for the cycler\n *\n * @returns - a function that reliably produces a valid access token\n */\nexport function createTokenCycler(\n credential: TokenCredential,\n tokenCyclerOptions?: Partial<TokenCyclerOptions>,\n): AccessTokenGetter {\n let refreshWorker: Promise<AccessToken> | null = null;\n let token: AccessToken | null = null;\n let tenantId: string | undefined;\n\n const options = {\n ...DEFAULT_CYCLER_OPTIONS,\n ...tokenCyclerOptions,\n };\n\n /**\n * This little holder defines several predicates that we use to construct\n * the rules of refreshing the token.\n */\n const cycler = {\n /**\n * Produces true if a refresh job is currently in progress.\n */\n get isRefreshing(): boolean {\n return refreshWorker !== null;\n },\n /**\n * Produces true if the cycler SHOULD refresh (we are within the refresh\n * window and not already refreshing)\n */\n get shouldRefresh(): boolean {\n if (cycler.isRefreshing) {\n return false;\n }\n if (token?.refreshAfterTimestamp && token.refreshAfterTimestamp < Date.now()) {\n return true;\n }\n\n return (token?.expiresOnTimestamp ?? 0) - options.refreshWindowInMs < Date.now();\n },\n /**\n * Produces true if the cycler MUST refresh (null or nearly-expired\n * token).\n */\n get mustRefresh(): boolean {\n return (\n token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()\n );\n },\n };\n\n /**\n * Starts a refresh job or returns the existing job if one is already\n * running.\n */\n function refresh(\n scopes: string | string[],\n getTokenOptions: GetTokenOptions,\n ): Promise<AccessToken> {\n if (!cycler.isRefreshing) {\n // We bind `scopes` here to avoid passing it around a lot\n const tryGetAccessToken = (): Promise<AccessToken | null> =>\n credential.getToken(scopes, getTokenOptions);\n\n // Take advantage of promise chaining to insert an assignment to `token`\n // before the refresh can be considered done.\n refreshWorker = beginRefresh(\n tryGetAccessToken,\n options.retryIntervalInMs,\n // If we don't have a token, then we should timeout immediately\n token?.expiresOnTimestamp ?? Date.now(),\n )\n .then((_token) => {\n refreshWorker = null;\n token = _token;\n tenantId = getTokenOptions.tenantId;\n return token;\n })\n .catch((reason) => {\n // We also should reset the refresher if we enter a failed state. All\n // existing awaiters will throw, but subsequent requests will start a\n // new retry chain.\n refreshWorker = null;\n token = null;\n tenantId = undefined;\n throw reason;\n });\n }\n\n return refreshWorker as Promise<AccessToken>;\n }\n\n return async (scopes: string | string[], tokenOptions: GetTokenOptions): Promise<AccessToken> => {\n //\n // Simple rules:\n // - If we MUST refresh, then return the refresh task, blocking\n // the pipeline until a token is available.\n // - If we SHOULD refresh, then run refresh but don't return it\n // (we can still use the cached token).\n // - Return the token, since it's fine if we didn't return in\n // step 1.\n //\n\n const hasClaimChallenge = Boolean(tokenOptions.claims);\n const tenantIdChanged = tenantId !== tokenOptions.tenantId;\n\n if (hasClaimChallenge) {\n // If we've received a claim, we know the existing token isn't valid\n // We want to clear it so that that refresh worker won't use the old expiration time as a timeout\n token = null;\n }\n\n // If the tenantId passed in token options is different to the one we have\n // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to\n // refresh the token with the new tenantId or token.\n const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;\n\n if (mustRefresh) {\n return refresh(scopes, tokenOptions);\n }\n\n if (cycler.shouldRefresh) {\n refresh(scopes, tokenOptions);\n }\n\n return token as AccessToken;\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uuidUtils.common.d.ts","sourceRoot":"","sources":["../../../src/util/uuidUtils.common.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"uuidUtils.common.d.ts","sourceRoot":"","sources":["../../../src/util/uuidUtils.common.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,wBAAgB,YAAY,IAAI,MAAM,CAqBrC;AAED;;;;GAIG;AACH,wBAAgB,UAAU,IAAI,MAAM,CAEnC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uuidUtils.common.js","sourceRoot":"","sources":["../../../src/util/uuidUtils.common.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC
|
|
1
|
+
{"version":3,"file":"uuidUtils.common.js","sourceRoot":"","sources":["../../../src/util/uuidUtils.common.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;;GAIG;AACH,MAAM,UAAU,YAAY;IAC1B,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC;QAC5B,4CAA4C;QAC5C,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;QACpD,iDAAiD;QACjD,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;YACb,IAAI,IAAI,GAAG,CAAC;QACd,CAAC;aAAM,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;YACpB,oDAAoD;YACpD,IAAI,IAAI,CAAC,YAAY,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;QACrC,CAAC;aAAM,CAAC;YACN,oDAAoD;YACpD,IAAI,IAAI,YAAY,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACpC,CAAC;QACD,8DAA8D;QAC9D,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;YAChD,IAAI,IAAI,GAAG,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,YAAY,EAAE,CAAC;AACxB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Generated Universally Unique Identifier\n *\n * @returns RFC4122 v4 UUID.\n */\nexport function generateUUID(): string {\n let uuid = \"\";\n for (let i = 0; i < 32; i++) {\n // Generate a random number between 0 and 15\n const randomNumber = Math.floor(Math.random() * 16);\n // Set the UUID version to 4 in the 13th position\n if (i === 12) {\n uuid += \"4\";\n } else if (i === 16) {\n // Set the UUID variant to \"10\" in the 17th position\n uuid += (randomNumber & 0x3) | 0x8;\n } else {\n // Add a random hexadecimal digit to the UUID string\n uuid += randomNumber.toString(16);\n }\n // Add hyphens to the UUID string at the appropriate positions\n if (i === 7 || i === 11 || i === 15 || i === 19) {\n uuid += \"-\";\n }\n }\n return uuid;\n}\n\n/**\n * Generated Universally Unique Identifier\n *\n * @returns RFC4122 v4 UUID.\n */\nexport function randomUUID(): string {\n return generateUUID();\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uuidUtils.d.ts","sourceRoot":"","sources":["../../../src/util/uuidUtils.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"uuidUtils.d.ts","sourceRoot":"","sources":["../../../src/util/uuidUtils.ts"],"names":[],"mappings":"AAmBA;;;;GAIG;AACH,wBAAgB,UAAU,IAAI,MAAM,CAEnC"}
|
|
@@ -2,15 +2,10 @@
|
|
|
2
2
|
// Licensed under the MIT License.
|
|
3
3
|
var _a;
|
|
4
4
|
import { randomUUID as v4RandomUUID } from "node:crypto";
|
|
5
|
-
import { generateUUID } from "./uuidUtils.common.js";
|
|
6
5
|
// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+.
|
|
7
|
-
|
|
6
|
+
const uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function"
|
|
8
7
|
? globalThis.crypto.randomUUID.bind(globalThis.crypto)
|
|
9
8
|
: v4RandomUUID;
|
|
10
|
-
// Not defined in earlier versions of Node.js 14
|
|
11
|
-
if (!uuidFunction) {
|
|
12
|
-
uuidFunction = generateUUID;
|
|
13
|
-
}
|
|
14
9
|
/**
|
|
15
10
|
* Generated Universally Unique Identifier
|
|
16
11
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uuidUtils.js","sourceRoot":"","sources":["../../../src/util/uuidUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,EAAE,UAAU,IAAI,YAAY,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"uuidUtils.js","sourceRoot":"","sources":["../../../src/util/uuidUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;;AAElC,OAAO,EAAE,UAAU,IAAI,YAAY,EAAE,MAAM,aAAa,CAAC;AAUzD,6FAA6F;AAC7F,MAAM,YAAY,GAChB,OAAO,CAAA,MAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,MAAM,0CAAE,UAAU,CAAA,KAAK,UAAU;IAClD,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC;IACtD,CAAC,CAAC,YAAY,CAAC;AAEnB;;;;GAIG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,YAAY,EAAE,CAAC;AACxB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { randomUUID as v4RandomUUID } from \"node:crypto\";\n\ninterface Crypto {\n randomUUID(): string;\n}\n\ndeclare const globalThis: {\n crypto: Crypto;\n};\n\n// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+.\nconst uuidFunction =\n typeof globalThis?.crypto?.randomUUID === \"function\"\n ? globalThis.crypto.randomUUID.bind(globalThis.crypto)\n : v4RandomUUID;\n\n/**\n * Generated Universally Unique Identifier\n *\n * @returns RFC4122 v4 UUID.\n */\nexport function randomUUID(): string {\n return uuidFunction();\n}\n"]}
|
|
@@ -67,6 +67,10 @@ export interface AccessToken {
|
|
|
67
67
|
* The access token's expiration timestamp in milliseconds, UNIX epoch time.
|
|
68
68
|
*/
|
|
69
69
|
expiresOnTimestamp: number;
|
|
70
|
+
/**
|
|
71
|
+
* The timestamp when the access token should be refreshed, in milliseconds, UNIX epoch time.
|
|
72
|
+
*/
|
|
73
|
+
refreshAfterTimestamp?: number;
|
|
70
74
|
}
|
|
71
75
|
/**
|
|
72
76
|
* Tests an object to determine whether it implements TokenCredential.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenCredential.d.ts","sourceRoot":"","sources":["../../../src/auth/tokenCredential.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;;;OASG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;CAC7F;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B;;OAEG;IACH,cAAc,CAAC,EAAE;QACf;;WAEG;QACH,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;IACF;;OAEG;IACH,cAAc,CAAC,EAAE;QACf;;WAEG;QACH,cAAc,CAAC,EAAE,cAAc,CAAC;KACjC,CAAC;IACF;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,kBAAkB,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"tokenCredential.d.ts","sourceRoot":"","sources":["../../../src/auth/tokenCredential.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;;;;;OASG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;CAC7F;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B;;OAEG;IACH,cAAc,CAAC,EAAE;QACf;;WAEG;QACH,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;IACF;;OAEG;IACH,cAAc,CAAC,EAAE;QACf;;WAEG;QACH,cAAc,CAAC,EAAE,cAAc,CAAC;KACjC,CAAC;IACF;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAGhC;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,OAAO,GAAG,UAAU,IAAI,eAAe,CAepF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenCredential.js","sourceRoot":"","sources":["../../../src/auth/tokenCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;
|
|
1
|
+
{"version":3,"file":"tokenCredential.js","sourceRoot":"","sources":["../../../src/auth/tokenCredential.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAoFlC;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAmB;IACnD,mEAAmE;IACnE,gEAAgE;IAChE,sEAAsE;IACtE,qEAAqE;IACrE,sDAAsD;IACtD,MAAM,cAAc,GAAG,UAGtB,CAAC;IACF,OAAO,CACL,cAAc;QACd,OAAO,cAAc,CAAC,QAAQ,KAAK,UAAU;QAC7C,CAAC,cAAc,CAAC,WAAW,KAAK,SAAS,IAAI,cAAc,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CACjF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AbortSignalLike } from \"../abort-controller/AbortSignalLike.js\";\nimport { TracingContext } from \"../tracing/interfaces.js\";\n\n/**\n * Represents a credential capable of providing an authentication token.\n */\nexport interface TokenCredential {\n /**\n * Gets the token provided by this credential.\n *\n * This method is called automatically by Azure SDK client libraries. You may call this method\n * directly, but you must also handle token caching and token refreshing.\n *\n * @param scopes - The list of scopes for which the token will have access.\n * @param options - The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken | null>;\n}\n\n/**\n * Defines options for TokenCredential.getToken.\n */\nexport interface GetTokenOptions {\n /**\n * The signal which can be used to abort requests.\n */\n abortSignal?: AbortSignalLike;\n /**\n * Options used when creating and sending HTTP requests for this operation.\n */\n requestOptions?: {\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n */\n timeout?: number;\n };\n /**\n * Options used when tracing is enabled.\n */\n tracingOptions?: {\n /**\n * Tracing Context for the current request.\n */\n tracingContext?: TracingContext;\n };\n /**\n * Claim details to perform the Continuous Access Evaluation authentication flow\n */\n claims?: string;\n /**\n * Indicates whether to enable the Continuous Access Evaluation authentication flow\n */\n enableCae?: boolean;\n /**\n * Allows specifying a tenantId. Useful to handle challenges that provide tenant Id hints.\n */\n tenantId?: string;\n}\n\n/**\n * Represents an access token with an expiration time.\n */\nexport interface AccessToken {\n /**\n * The access token returned by the authentication service.\n */\n token: string;\n\n /**\n * The access token's expiration timestamp in milliseconds, UNIX epoch time.\n */\n expiresOnTimestamp: number;\n\n /**\n * The timestamp when the access token should be refreshed, in milliseconds, UNIX epoch time.\n */\n refreshAfterTimestamp?: number;\n\n // UNBRANDED DIFFERENCE: Unbranded Core does not support PoP (\"Proof-of-Presence\") tokens.\n}\n\n/**\n * Tests an object to determine whether it implements TokenCredential.\n *\n * @param credential - The assumed TokenCredential to be tested.\n */\nexport function isTokenCredential(credential: unknown): credential is TokenCredential {\n // Check for an object with a 'getToken' function and possibly with\n // a 'signRequest' function. We do this check to make sure that\n // a ServiceClientCredentials implementor (like TokenClientCredentials\n // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if\n // it doesn't actually implement TokenCredential also.\n const castCredential = credential as {\n getToken: unknown;\n signRequest: unknown;\n };\n return (\n castCredential &&\n typeof castCredential.getToken === \"function\" &&\n (castCredential.signRequest === undefined || castCredential.getToken.length > 0)\n );\n}\n"]}
|
|
@@ -5,7 +5,7 @@ import { OperationTracingOptions } from "../tracing/interfaces.js";
|
|
|
5
5
|
import { PipelineOptions } from "../createPipelineFromOptions.js";
|
|
6
6
|
import { LogPolicyOptions } from "../policies/logPolicy.js";
|
|
7
7
|
/**
|
|
8
|
-
* Shape of the default request parameters, this may be
|
|
8
|
+
* Shape of the default request parameters, this may be overridden by the specific
|
|
9
9
|
* request types to provide strong types
|
|
10
10
|
*/
|
|
11
11
|
export type RequestParameters = {
|
|
@@ -160,7 +160,7 @@ export interface Client {
|
|
|
160
160
|
pipeline: Pipeline;
|
|
161
161
|
/**
|
|
162
162
|
* This method will be used to send request that would check the path to provide
|
|
163
|
-
* strong types. When used by the codegen this type gets
|
|
163
|
+
* strong types. When used by the codegen this type gets overridden with the generated
|
|
164
164
|
* types. For example:
|
|
165
165
|
* ```typescript snippet:path_example
|
|
166
166
|
* import { Client, Routes } from "@typespec/ts-http-runtime";
|
|
@@ -276,11 +276,6 @@ export type ClientOptions = PipelineOptions & {
|
|
|
276
276
|
*/
|
|
277
277
|
apiKeyHeaderName?: string;
|
|
278
278
|
};
|
|
279
|
-
/**
|
|
280
|
-
* Base url for the client
|
|
281
|
-
* @deprecated This property is deprecated and will be removed soon, please use endpoint instead
|
|
282
|
-
*/
|
|
283
|
-
baseUrl?: string;
|
|
284
279
|
/**
|
|
285
280
|
* Endpoint for the client
|
|
286
281
|
*/
|
|
@@ -332,7 +327,7 @@ export type HttpResponse = {
|
|
|
332
327
|
* text surrounded by \{\} will be considered a path parameter
|
|
333
328
|
*/
|
|
334
329
|
export type PathParameters<TRoute extends string> = TRoute extends `${infer _Head}/{${infer _Param}}${infer Tail}` ? [
|
|
335
|
-
pathParameter: string | PathParameterWithOptions,
|
|
330
|
+
pathParameter: string | number | PathParameterWithOptions,
|
|
336
331
|
...pathParameters: PathParameters<Tail>
|
|
337
332
|
] : [
|
|
338
333
|
];
|
|
@@ -368,7 +363,7 @@ export interface PathParameterWithOptions {
|
|
|
368
363
|
/**
|
|
369
364
|
* The value of the parameter.
|
|
370
365
|
*/
|
|
371
|
-
value: string;
|
|
366
|
+
value: string | number;
|
|
372
367
|
/**
|
|
373
368
|
* Whether to allow for reserved characters in the value. If set to true, special characters such as '/' in the parameter's value will not be URL encoded.
|
|
374
369
|
* Defaults to false.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../../../src/client/common.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,UAAU,EACV,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,qBAAqB,EACrB,mBAAmB,EACpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AACzE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAE5D;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B;;OAEG;IACH,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;IACf;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC1C;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,mEAAmE;IACnE,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAErC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,gBAAgB,CAAC,EAAE,CAAC,QAAQ,EAAE,qBAAqB,KAAK,IAAI,CAAC;IAE7D;;OAEG;IACH,kBAAkB,CAAC,EAAE,CAAC,QAAQ,E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oot":"","sources":["../../../src/client/common.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport {\n HttpClient,\n PipelineRequest,\n PipelineResponse,\n RawHttpHeaders,\n RequestBodyType,\n TransferProgressEvent,\n RawHttpHeadersInput,\n} from \"../interfaces.js\";\nimport { Pipeline, PipelinePolicy } from \"../pipeline.js\";\nimport { AbortSignalLike } from \"../abort-controller/AbortSignalLike.js\";\nimport { OperationTracingOptions } from \"../tracing/interfaces.js\";\nimport { PipelineOptions } from \"../createPipelineFromOptions.js\";\nimport { LogPolicyOptions } from \"../policies/logPolicy.js\";\n\n/**\n * Shape of the default request parameters, this may be overriden by the specific\n * request types to provide strong types\n */\nexport type RequestParameters = {\n /**\n * Headers to send along with the request\n */\n headers?: RawHttpHeadersInput;\n /**\n * Sets the accept header to send to the service\n * defaults to 'application/json'. If also a header \"accept\" is set\n * this property will take precedence.\n */\n accept?: string;\n /**\n * Body to send with the request\n */\n body?: unknown;\n /**\n * Query parameters to send with the request\n */\n queryParameters?: Record<string, unknown>;\n /**\n * Set an explicit content-type to send with the request. If also a header \"content-type\" is set\n * this property will take precedence.\n */\n contentType?: string;\n /** Set to true if the request is sent over HTTP instead of HTTPS */\n allowInsecureConnection?: boolean;\n /** Set to true if you want to skip encoding the path parameters */\n skipUrlEncoding?: boolean;\n /**\n * Path parameters for custom the base url\n */\n pathParameters?: Record<string, any>;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n */\n timeout?: number;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Callback which fires upon download progress.\n */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * The signal which can be used to abort requests.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * Options used when tracing is enabled.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * A function to be called each time a response is received from the server\n * while performing the requested operation.\n * May be called multiple times.\n */\n onResponse?: RawResponseCallback;\n};\n\n/**\n * A function to be called each time a response is received from the server\n * while performing the requested operation.\n * May be called multiple times.\n */\nexport type RawResponseCallback = (rawResponse: FullOperationResponse, error?: unknown) => void;\n\n/**\n * Wrapper object for http request and response. Deserialized object is stored in\n * the `parsedBody` property when the response body is received in JSON.\n */\nexport interface FullOperationResponse extends PipelineResponse {\n /**\n * The raw HTTP response headers.\n */\n rawHeaders?: RawHttpHeaders;\n\n /**\n * The response body as parsed JSON.\n */\n parsedBody?: RequestBodyType;\n\n /**\n * The request that generated the response.\n */\n request: PipelineRequest;\n}\n\n/**\n * The base options type for all operations.\n */\nexport interface OperationOptions {\n /**\n * The signal which can be used to abort requests.\n */\n abortSignal?: AbortSignalLike;\n /**\n * Options used when creating and sending HTTP requests for this operation.\n */\n requestOptions?: OperationRequestOptions;\n /**\n * Options used when tracing is enabled.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * A function to be called each time a response is received from the server\n * while performing the requested operation.\n * May be called multiple times.\n */\n onResponse?: RawResponseCallback;\n}\n\n/**\n * Options used when creating and sending HTTP requests for this operation.\n */\nexport interface OperationRequestOptions {\n /**\n * User defined custom request headers that\n * will be applied before the request is sent.\n */\n headers?: RawHttpHeadersInput;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n */\n timeout?: number;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Callback which fires upon download progress.\n */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Set to true if the request is sent over HTTP instead of HTTPS\n */\n allowInsecureConnection?: boolean;\n\n /**\n * Set to true if you want to skip encoding the path parameters\n */\n skipUrlEncoding?: boolean;\n}\n\n/**\n * Type to use with pathUnchecked, overrides the body type to any to allow flexibility\n */\nexport type PathUncheckedResponse = HttpResponse & { body: any };\n\n/**\n * Shape of a Rest Level Client\n */\nexport interface Client {\n /**\n * The pipeline used by this client to make requests\n */\n pipeline: Pipeline;\n /**\n * This method will be used to send request that would check the path to provide\n * strong types. When used by the codegen this type gets overriden wit the generated\n * types. For example:\n * ```typescript snippet:path_example\n * import { Client, Routes } from \"@typespec/ts-http-runtime\";\n *\n * export type MyClient = Client & {\n * path: Routes;\n * };\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n path: Function;\n /**\n * This method allows arbitrary paths and doesn't provide strong types\n */\n pathUnchecked: PathUnchecked;\n}\n\n/**\n * Http Response which body is a NodeJS stream object\n */\nexport type HttpNodeStreamResponse = HttpResponse & {\n /**\n * Streamable body\n */\n body?: NodeJS.ReadableStream;\n};\n\n/**\n * Http Response which body is a NodeJS stream object\n */\nexport type HttpBrowserStreamResponse = HttpResponse & {\n /**\n * Streamable body\n */\n body?: ReadableStream<Uint8Array>;\n};\n\n/**\n * Defines the type for a method that supports getting the response body as\n * a raw stream\n */\nexport type StreamableMethod<TResponse = PathUncheckedResponse> = PromiseLike<TResponse> & {\n asNodeStream: () => Promise<HttpNodeStreamResponse>;\n asBrowserStream: () => Promise<HttpBrowserStreamResponse>;\n};\n\n/**\n * Defines the signature for pathUnchecked.\n */\nexport type PathUnchecked = <TPath extends string>(\n path: TPath,\n ...args: PathParameters<TPath>\n) => ResourceMethods<StreamableMethod>;\n\n/**\n * Defines the methods that can be called on a resource\n */\nexport interface ResourceMethods<TResponse = PromiseLike<PathUncheckedResponse>> {\n /**\n * Definition of the GET HTTP method for a resource\n */\n get: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the POST HTTP method for a resource\n */\n post: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the PUT HTTP method for a resource\n */\n put: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the PATCH HTTP method for a resource\n */\n patch: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the DELETE HTTP method for a resource\n */\n delete: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the HEAD HTTP method for a resource\n */\n head: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the OPTIONS HTTP method for a resource\n */\n options: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the TRACE HTTP method for a resource\n */\n trace: (options?: RequestParameters) => TResponse;\n}\n\n/**\n * Used to configure additional policies added to the pipeline at construction.\n */\nexport interface AdditionalPolicyConfig {\n /**\n * A policy to be added.\n */\n policy: PipelinePolicy;\n /**\n * Determines if this policy be applied before or after retry logic.\n * Only use `perRetry` if you need to modify the request again\n * each time the operation is retried due to retryable service\n * issues.\n */\n position: \"perCall\" | \"perRetry\";\n}\n\n/**\n * General options that a Rest Level Client can take\n */\nexport type ClientOptions = PipelineOptions & {\n /**\n * Credentials information\n */\n credentials?: {\n /**\n * Authentication scopes for AAD\n */\n scopes?: string[];\n /**\n * Heder name for Client Secret authentication\n */\n apiKeyHeaderName?: string;\n };\n /**\n * Base url for the client\n * @deprecated This property is deprecated and will be removed soon, please use endpoint instead\n */\n baseUrl?: string;\n /**\n * Endpoint for the client\n */\n endpoint?: string;\n /**\n * Options for setting a custom apiVersion.\n */\n apiVersion?: string;\n /**\n * Option to allow calling http (insecure) endpoints\n */\n allowInsecureConnection?: boolean;\n /**\n * Additional policies to include in the HTTP pipeline.\n */\n additionalPolicies?: AdditionalPolicyConfig[];\n /**\n * Specify a custom HttpClient when making requests.\n */\n httpClient?: HttpClient;\n /**\n * Options to configure request/response logging.\n */\n loggingOptions?: LogPolicyOptions;\n};\n\n/**\n * Represents the shape of an HttpResponse\n */\nexport type HttpResponse = {\n /**\n * The request that generated this response.\n */\n request: PipelineRequest;\n /**\n * The HTTP response headers.\n */\n headers: RawHttpHeaders;\n /**\n * Parsed body\n */\n body: unknown;\n /**\n * The HTTP status code of the response.\n */\n status: string;\n};\n\n/**\n * Helper type used to detect parameters in a path template\n * text surrounded by \\{\\} will be considered a path parameter\n */\nexport type PathParameters<\n TRoute extends string,\n // This is trying to match the string in TRoute with a template where HEAD/{PARAM}/TAIL\n // for example in the followint path: /foo/{fooId}/bar/{barId}/baz the template will infer\n // HEAD: /foo\n // Param: fooId\n // Tail: /bar/{barId}/baz\n // The above sample path would return [pathParam: string, pathParam: string]\n> = TRoute extends `${infer _Head}/{${infer _Param}}${infer Tail}`\n ? // In case we have a match for the template above we know for sure\n // that we have at least one pathParameter, that's why we set the first pathParam\n // in the tuple. At this point we have only matched up until param, if we want to identify\n // additional parameters we can call RouteParameters recursively on the Tail to match the remaining parts,\n // in case the Tail has more parameters, it will return a tuple with the parameters found in tail.\n // We spread the second path params to end up with a single dimension tuple at the end.\n [pathParameter: string | PathParameterWithOptions, ...pathParameters: PathParameters<Tail>]\n : // When the path doesn't match the template, it means that we have no path parameters so we return\n // an empty tuple.\n [];\n\n/** A response containing error details. */\nexport interface ErrorResponse {\n /** The error object. */\n error: ErrorModel;\n}\n\n/** The error object. */\nexport interface ErrorModel {\n /** One of a server-defined set of error codes. */\n code: string;\n /** A human-readable representation of the error. */\n message: string;\n /** The target of the error. */\n target?: string;\n /** An array of details about specific errors that led to this reported error. */\n details: Array<ErrorModel>;\n /** An object containing more specific information than the current object about the error. */\n innererror?: InnerError;\n}\n\n/** An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. */\nexport interface InnerError {\n /** One of a server-defined set of error codes. */\n code: string;\n /** Inner error. */\n innererror?: InnerError;\n}\n\n/**\n * An object that can be passed as a path parameter, allowing for additional options to be set relating to how the parameter is encoded.\n */\nexport interface PathParameterWithOptions {\n /**\n * The value of the parameter.\n */\n value: string;\n\n /**\n * Whether to allow for reserved characters in the value. If set to true, special characters such as '/' in the parameter's value will not be URL encoded.\n * Defaults to false.\n */\n allowReserved?: boolean;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"common.js","sourceRoot":"","sources":["../../../src/client/common.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport {\n HttpClient,\n PipelineRequest,\n PipelineResponse,\n RawHttpHeaders,\n RequestBodyType,\n TransferProgressEvent,\n RawHttpHeadersInput,\n} from \"../interfaces.js\";\nimport { Pipeline, PipelinePolicy } from \"../pipeline.js\";\nimport { AbortSignalLike } from \"../abort-controller/AbortSignalLike.js\";\nimport { OperationTracingOptions } from \"../tracing/interfaces.js\";\nimport { PipelineOptions } from \"../createPipelineFromOptions.js\";\nimport { LogPolicyOptions } from \"../policies/logPolicy.js\";\n\n/**\n * Shape of the default request parameters, this may be overridden by the specific\n * request types to provide strong types\n */\nexport type RequestParameters = {\n /**\n * Headers to send along with the request\n */\n headers?: RawHttpHeadersInput;\n /**\n * Sets the accept header to send to the service\n * defaults to 'application/json'. If also a header \"accept\" is set\n * this property will take precedence.\n */\n accept?: string;\n /**\n * Body to send with the request\n */\n body?: unknown;\n /**\n * Query parameters to send with the request\n */\n queryParameters?: Record<string, unknown>;\n /**\n * Set an explicit content-type to send with the request. If also a header \"content-type\" is set\n * this property will take precedence.\n */\n contentType?: string;\n /** Set to true if the request is sent over HTTP instead of HTTPS */\n allowInsecureConnection?: boolean;\n /** Set to true if you want to skip encoding the path parameters */\n skipUrlEncoding?: boolean;\n /**\n * Path parameters for custom the base url\n */\n pathParameters?: Record<string, any>;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n */\n timeout?: number;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Callback which fires upon download progress.\n */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * The signal which can be used to abort requests.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * Options used when tracing is enabled.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * A function to be called each time a response is received from the server\n * while performing the requested operation.\n * May be called multiple times.\n */\n onResponse?: RawResponseCallback;\n};\n\n/**\n * A function to be called each time a response is received from the server\n * while performing the requested operation.\n * May be called multiple times.\n */\n// UNBRANDED DIFFERENCE: onResponse callback does not have a second __legacyError parameter which was provided for backwards compatibility\nexport type RawResponseCallback = (rawResponse: FullOperationResponse, error?: unknown) => void;\n\n/**\n * Wrapper object for http request and response. Deserialized object is stored in\n * the `parsedBody` property when the response body is received in JSON.\n */\nexport interface FullOperationResponse extends PipelineResponse {\n /**\n * The raw HTTP response headers.\n */\n rawHeaders?: RawHttpHeaders;\n\n /**\n * The response body as parsed JSON.\n */\n parsedBody?: RequestBodyType;\n\n /**\n * The request that generated the response.\n */\n request: PipelineRequest;\n}\n\n/**\n * The base options type for all operations.\n */\nexport interface OperationOptions {\n /**\n * The signal which can be used to abort requests.\n */\n abortSignal?: AbortSignalLike;\n /**\n * Options used when creating and sending HTTP requests for this operation.\n */\n requestOptions?: OperationRequestOptions;\n /**\n * Options used when tracing is enabled.\n */\n tracingOptions?: OperationTracingOptions;\n\n /**\n * A function to be called each time a response is received from the server\n * while performing the requested operation.\n * May be called multiple times.\n */\n onResponse?: RawResponseCallback;\n}\n\n/**\n * Options used when creating and sending HTTP requests for this operation.\n */\nexport interface OperationRequestOptions {\n /**\n * User defined custom request headers that\n * will be applied before the request is sent.\n */\n headers?: RawHttpHeadersInput;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n */\n timeout?: number;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Callback which fires upon download progress.\n */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Set to true if the request is sent over HTTP instead of HTTPS\n */\n allowInsecureConnection?: boolean;\n\n /**\n * Set to true if you want to skip encoding the path parameters\n */\n skipUrlEncoding?: boolean;\n}\n\n/**\n * Type to use with pathUnchecked, overrides the body type to any to allow flexibility\n */\nexport type PathUncheckedResponse = HttpResponse & { body: any };\n\n/**\n * Shape of a Rest Level Client\n */\nexport interface Client {\n /**\n * The pipeline used by this client to make requests\n */\n pipeline: Pipeline;\n /**\n * This method will be used to send request that would check the path to provide\n * strong types. When used by the codegen this type gets overridden with the generated\n * types. For example:\n * ```typescript snippet:path_example\n * import { Client, Routes } from \"@typespec/ts-http-runtime\";\n *\n * export type MyClient = Client & {\n * path: Routes;\n * };\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n path: Function;\n /**\n * This method allows arbitrary paths and doesn't provide strong types\n */\n pathUnchecked: PathUnchecked;\n}\n\n/**\n * Http Response which body is a NodeJS stream object\n */\nexport type HttpNodeStreamResponse = HttpResponse & {\n /**\n * Streamable body\n */\n body?: NodeJS.ReadableStream;\n};\n\n/**\n * Http Response which body is a NodeJS stream object\n */\nexport type HttpBrowserStreamResponse = HttpResponse & {\n /**\n * Streamable body\n */\n body?: ReadableStream<Uint8Array>;\n};\n\n/**\n * Defines the type for a method that supports getting the response body as\n * a raw stream\n */\nexport type StreamableMethod<TResponse = PathUncheckedResponse> = PromiseLike<TResponse> & {\n asNodeStream: () => Promise<HttpNodeStreamResponse>;\n asBrowserStream: () => Promise<HttpBrowserStreamResponse>;\n};\n\n/**\n * Defines the signature for pathUnchecked.\n */\nexport type PathUnchecked = <TPath extends string>(\n path: TPath,\n ...args: PathParameters<TPath>\n) => ResourceMethods<StreamableMethod>;\n\n/**\n * Defines the methods that can be called on a resource\n */\nexport interface ResourceMethods<TResponse = PromiseLike<PathUncheckedResponse>> {\n /**\n * Definition of the GET HTTP method for a resource\n */\n get: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the POST HTTP method for a resource\n */\n post: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the PUT HTTP method for a resource\n */\n put: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the PATCH HTTP method for a resource\n */\n patch: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the DELETE HTTP method for a resource\n */\n delete: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the HEAD HTTP method for a resource\n */\n head: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the OPTIONS HTTP method for a resource\n */\n options: (options?: RequestParameters) => TResponse;\n /**\n * Definition of the TRACE HTTP method for a resource\n */\n trace: (options?: RequestParameters) => TResponse;\n}\n\n/**\n * Used to configure additional policies added to the pipeline at construction.\n */\nexport interface AdditionalPolicyConfig {\n /**\n * A policy to be added.\n */\n policy: PipelinePolicy;\n /**\n * Determines if this policy be applied before or after retry logic.\n * Only use `perRetry` if you need to modify the request again\n * each time the operation is retried due to retryable service\n * issues.\n */\n position: \"perCall\" | \"perRetry\";\n}\n\n/**\n * General options that a Rest Level Client can take\n */\nexport type ClientOptions = PipelineOptions & {\n /**\n * Credentials information\n */\n credentials?: {\n /**\n * Authentication scopes for AAD\n */\n scopes?: string[];\n /**\n * Heder name for Client Secret authentication\n */\n apiKeyHeaderName?: string;\n };\n\n // UNBRANDED DIFFERENCE: The deprecated baseUrl property is removed in favor of the endpoint property in the unbranded Core package\n\n /**\n * Endpoint for the client\n */\n endpoint?: string;\n /**\n * Options for setting a custom apiVersion.\n */\n apiVersion?: string;\n /**\n * Option to allow calling http (insecure) endpoints\n */\n allowInsecureConnection?: boolean;\n /**\n * Additional policies to include in the HTTP pipeline.\n */\n additionalPolicies?: AdditionalPolicyConfig[];\n /**\n * Specify a custom HttpClient when making requests.\n */\n httpClient?: HttpClient;\n /**\n * Options to configure request/response logging.\n */\n loggingOptions?: LogPolicyOptions;\n};\n\n/**\n * Represents the shape of an HttpResponse\n */\nexport type HttpResponse = {\n /**\n * The request that generated this response.\n */\n request: PipelineRequest;\n /**\n * The HTTP response headers.\n */\n headers: RawHttpHeaders;\n /**\n * Parsed body\n */\n body: unknown;\n /**\n * The HTTP status code of the response.\n */\n status: string;\n};\n\n/**\n * Helper type used to detect parameters in a path template\n * text surrounded by \\{\\} will be considered a path parameter\n */\nexport type PathParameters<\n TRoute extends string,\n // This is trying to match the string in TRoute with a template where HEAD/{PARAM}/TAIL\n // for example in the followint path: /foo/{fooId}/bar/{barId}/baz the template will infer\n // HEAD: /foo\n // Param: fooId\n // Tail: /bar/{barId}/baz\n // The above sample path would return [pathParam: string, pathParam: string]\n> = TRoute extends `${infer _Head}/{${infer _Param}}${infer Tail}`\n ? // In case we have a match for the template above we know for sure\n // that we have at least one pathParameter, that's why we set the first pathParam\n // in the tuple. At this point we have only matched up until param, if we want to identify\n // additional parameters we can call RouteParameters recursively on the Tail to match the remaining parts,\n // in case the Tail has more parameters, it will return a tuple with the parameters found in tail.\n // We spread the second path params to end up with a single dimension tuple at the end.\n [\n pathParameter: string | number | PathParameterWithOptions,\n ...pathParameters: PathParameters<Tail>,\n ]\n : // When the path doesn't match the template, it means that we have no path parameters so we return\n // an empty tuple.\n [];\n\n/** A response containing error details. */\nexport interface ErrorResponse {\n /** The error object. */\n error: ErrorModel;\n}\n\n/** The error object. */\nexport interface ErrorModel {\n /** One of a server-defined set of error codes. */\n code: string;\n /** A human-readable representation of the error. */\n message: string;\n /** The target of the error. */\n target?: string;\n /** An array of details about specific errors that led to this reported error. */\n details: Array<ErrorModel>;\n /** An object containing more specific information than the current object about the error. */\n innererror?: InnerError;\n}\n\n/** An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. */\nexport interface InnerError {\n /** One of a server-defined set of error codes. */\n code: string;\n /** Inner error. */\n innererror?: InnerError;\n}\n\n/**\n * An object that can be passed as a path parameter, allowing for additional options to be set relating to how the parameter is encoded.\n */\nexport interface PathParameterWithOptions {\n /**\n * The value of the parameter.\n */\n value: string | number;\n\n /**\n * Whether to allow for reserved characters in the value. If set to true, special characters such as '/' in the parameter's value will not be URL encoded.\n * Defaults to false.\n */\n allowReserved?: boolean;\n}\n"]}
|
|
@@ -6,7 +6,7 @@ import { createDefaultPipeline } from "./clientHelpers.js";
|
|
|
6
6
|
import { sendRequest } from "./sendRequest.js";
|
|
7
7
|
import { buildRequestUrl } from "./urlHelpers.js";
|
|
8
8
|
export function getClient(endpoint, credentialsOrPipelineOptions, clientOptions = {}) {
|
|
9
|
-
var _a;
|
|
9
|
+
var _a, _b;
|
|
10
10
|
let credentials;
|
|
11
11
|
if (credentialsOrPipelineOptions) {
|
|
12
12
|
if (isCredential(credentialsOrPipelineOptions)) {
|
|
@@ -28,8 +28,9 @@ export function getClient(endpoint, credentialsOrPipelineOptions, clientOptions
|
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
30
|
const { allowInsecureConnection, httpClient } = clientOptions;
|
|
31
|
+
const endpointUrl = (_b = clientOptions.endpoint) !== null && _b !== void 0 ? _b : endpoint;
|
|
31
32
|
const client = (path, ...args) => {
|
|
32
|
-
const getUrl = (requestOptions) => buildRequestUrl(
|
|
33
|
+
const getUrl = (requestOptions) => buildRequestUrl(endpointUrl, path, args, Object.assign({ allowInsecureConnection }, requestOptions));
|
|
33
34
|
return {
|
|
34
35
|
get: (requestOptions = {}) => {
|
|
35
36
|
return buildOperation("GET", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getClient.js","sourceRoot":"","sources":["../../../src/client/getClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAmB,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAChF,OAAO,EAAiB,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAG1E,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAU3D,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAoBlD,MAAM,UAAU,SAAS,CACvB,QAAgB,EAChB,4BAAgF,EAChF,gBAA+B,EAAE;;IAEjC,IAAI,WAAwD,CAAC;IAC7D,IAAI,4BAA4B,EAAE,CAAC;QACjC,IAAI,YAAY,CAAC,4BAA4B,CAAC,EAAE,CAAC;YAC/C,WAAW,GAAG,4BAA4B,CAAC;QAC7C,CAAC;aAAM,CAAC;YACN,aAAa,GAAG,4BAA4B,aA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,CACX,CAAC;YACJ,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,aAAa,EAAE,MAAM;QACrB,QAAQ;KACT,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CACrB,MAAmB,EACnB,GAAW,EACX,QAAkB,EAClB,OAA0B,EAC1B,uBAAiC,EACjC,UAAuB;;IAEvB,uBAAuB,GAAG,MAAA,OAAO,CAAC,uBAAuB,mCAAI,uBAAuB,CAAC;IACrF,OAAO;QACL,IAAI,EAAE,UAAU,WAAW,EAAE,UAAU;YACrC,OAAO,WAAW,CAChB,MAAM,EACN,GAAG,EACH,QAAQ,kCACH,OAAO,KAAE,uBAAuB,KACrC,UAAU,CACX,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QAClC,CAAC;QACD,KAAK,CAAC,eAAe;YACnB,OAAO,WAAW,CAChB,MAAM,EACN,GAAG,EACH,QAAQ,kCACH,OAAO,KAAE,uBAAuB,EAAE,gBAAgB,EAAE,IAAI,KAC7D,UAAU,CAC2B,CAAC;QAC1C,CAAC;QACD,KAAK,CAAC,YAAY;YAChB,OAAO,WAAW,CAChB,MAAM,EACN,GAAG,EACH,QAAQ,kCACH,OAAO,KAAE,uBAAuB,EAAE,gBAAgB,EAAE,IAAI,KAC7D,UAAU,CACwB,CAAC;QACvC,CAAC;KACF,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CACnB,KAA0D;IAE1D,OAAO,eAAe,CAAC,KAAK,CAAC,IAAI,iBAAiB,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { TokenCredential, isTokenCredential } from \"../auth/tokenCredential.js\";\nimport { KeyCredential, isKeyCredential } from \"../auth/keyCredential.js\";\nimport { HttpClient, HttpMethods } from \"../interfaces.js\";\nimport { Pipeline } from \"../pipeline.js\";\nimport { createDefaultPipeline } from \"./clientHelpers.js\";\nimport {\n Client,\n ClientOptions,\n HttpBrowserStreamResponse,\n HttpNodeStreamResponse,\n RequestParameters,\n ResourceMethods,\n StreamableMethod,\n} from \"./common.js\";\nimport { sendRequest } from \"./sendRequest.js\";\nimport { buildRequestUrl } from \"./urlHelpers.js\";\nimport { PipelineOptions } from \"../createPipelineFromOptions.js\";\n\n/**\n * Creates a client with a default pipeline\n * @param endpoint - Base endpoint for the client\n * @param options - Client options\n */\nexport function getClient(endpoint: string, options?: ClientOptions): Client;\n/**\n * Creates a client with a default pipeline\n * @param endpoint - Base endpoint for the client\n * @param credentials - Credentials to authenticate the requests\n * @param options - Client options\n */\nexport function getClient(\n endpoint: string,\n credentials?: TokenCredential | KeyCredential,\n options?: ClientOptions,\n): Client;\nexport function getClient(\n endpoint: string,\n credentialsOrPipelineOptions?: (TokenCredential | KeyCredential) | ClientOptions,\n clientOptions: ClientOptions = {},\n): Client {\n let credentials: TokenCredential | KeyCredential | undefined;\n if (credentialsOrPipelineOptions) {\n if (isCredential(credentialsOrPipelineOptions)) {\n credentials = credentialsOrPipelineOptions;\n } else {\n clientOptions = credentialsOrPipelineOptions ?? {};\n }\n }\n\n const pipeline = createDefaultPipeline(endpoint, credentials, clientOptions);\n if (clientOptions.additionalPolicies?.length) {\n for (const { policy, position } of clientOptions.additionalPolicies) {\n // Sign happens after Retry and is commonly needed to occur\n // before policies that intercept post-retry.\n const afterPhase = position === \"perRetry\" ? \"Sign\" : undefined;\n pipeline.addPolicy(policy, {\n afterPhase,\n });\n }\n }\n\n const { allowInsecureConnection, httpClient } = clientOptions;\n const endpointUrl = clientOptions.endpoint ?? endpoint;\n const client = (path: string, ...args: Array<any>): ResourceMethods<StreamableMethod> => {\n const getUrl = (requestOptions: RequestParameters): string =>\n buildRequestUrl(endpointUrl, path, args, { allowInsecureConnection, ...requestOptions });\n\n return {\n get: (requestOptions: RequestParameters = {}): StreamableMethod => {\n return buildOperation(\n \"GET\",\n getUrl(requestOptions),\n pipeline,\n requestOptions,\n allowInsecureConnection,\n httpClient,\n );\n },\n post: (requestOptions: RequestParameters = {}): StreamableMethod => {\n return buildOperation(\n \"POST\",\n getUrl(requestOptions),\n pipeline,\n requestOptions,\n allowInsecureConnection,\n httpClient,\n );\n },\n put: (requestOptions: RequestParameters = {}): StreamableMethod => {\n return buildOperation(\n \"PUT\",\n getUrl(requestOptions),\n pipeline,\n requestOptions,\n allowInsecureConnection,\n httpClient,\n );\n },\n patch: (requestOptions: RequestParameters = {}): StreamableMethod => {\n return buildOperation(\n \"PATCH\",\n getUrl(requestOptions),\n pipeline,\n requestOptions,\n allowInsecureConnection,\n httpClient,\n );\n },\n delete: (requestOptions: RequestParameters = {}): StreamableMethod => {\n return buildOperation(\n \"DELETE\",\n getUrl(requestOptions),\n pipeline,\n requestOptions,\n allowInsecureConnection,\n httpClient,\n );\n },\n head: (requestOptions: RequestParameters = {}): StreamableMethod => {\n return buildOperation(\n \"HEAD\",\n getUrl(requestOptions),\n pipeline,\n requestOptions,\n allowInsecureConnection,\n httpClient,\n );\n },\n options: (requestOptions: RequestParameters = {}): StreamableMethod => {\n return buildOperation(\n \"OPTIONS\",\n getUrl(requestOptions),\n pipeline,\n requestOptions,\n allowInsecureConnection,\n httpClient,\n );\n },\n trace: (requestOptions: RequestParameters = {}): StreamableMethod => {\n return buildOperation(\n \"TRACE\",\n getUrl(requestOptions),\n pipeline,\n requestOptions,\n allowInsecureConnection,\n httpClient,\n );\n },\n };\n };\n\n return {\n path: client,\n pathUnchecked: client,\n pipeline,\n };\n}\n\nfunction buildOperation(\n method: HttpMethods,\n url: string,\n pipeline: Pipeline,\n options: RequestParameters,\n allowInsecureConnection?: boolean,\n httpClient?: HttpClient,\n): StreamableMethod {\n allowInsecureConnection = options.allowInsecureConnection ?? allowInsecureConnection;\n return {\n then: function (onFulfilled, onrejected) {\n return sendRequest(\n method,\n url,\n pipeline,\n { ...options, allowInsecureConnection },\n httpClient,\n ).then(onFulfilled, onrejected);\n },\n async asBrowserStream() {\n return sendRequest(\n method,\n url,\n pipeline,\n { ...options, allowInsecureConnection, responseAsStream: true },\n httpClient,\n ) as Promise<HttpBrowserStreamResponse>;\n },\n async asNodeStream() {\n return sendRequest(\n method,\n url,\n pipeline,\n { ...options, allowInsecureConnection, responseAsStream: true },\n httpClient,\n ) as Promise<HttpNodeStreamResponse>;\n },\n };\n}\n\nfunction isCredential(\n param: (TokenCredential | KeyCredential) | PipelineOptions,\n): param is TokenCredential | KeyCredential {\n return isKeyCredential(param) || isTokenCredential(param);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sendRequest.d.ts","sourceRoot":"","sources":["../../../src/client/sendRequest.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,UAAU,EACV,WAAW,EAKZ,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAK1C,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAG9D;;;;;;;;GAQG;AACH,wBAAsB,WAAW,CAC/B,MAAM,EAAE,WAAW,EACnB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,QAAQ,EAClB,OAAO,GAAE,yBAA8B,EACvC,gBAAgB,CAAC,EAAE,UAAU,GAC5B,OAAO,CAAC,YAAY,CAAC,
|
|
1
|
+
{"version":3,"file":"sendRequest.d.ts","sourceRoot":"","sources":["../../../src/client/sendRequest.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,UAAU,EACV,WAAW,EAKZ,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAK1C,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAG9D;;;;;;;;GAQG;AACH,wBAAsB,WAAW,CAC/B,MAAM,EAAE,WAAW,EACnB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,QAAQ,EAClB,OAAO,GAAE,yBAA8B,EACvC,gBAAgB,CAAC,EAAE,UAAU,GAC5B,OAAO,CAAC,YAAY,CAAC,CAgCvB;AAuCD,MAAM,WAAW,yBAA0B,SAAQ,iBAAiB;IAClE,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Copyright (c) Microsoft Corporation.
|
|
2
2
|
// Licensed under the MIT License.
|
|
3
|
-
import { RestError } from "../restError.js";
|
|
3
|
+
import { isRestError, RestError } from "../restError.js";
|
|
4
4
|
import { createHttpHeaders } from "../httpHeaders.js";
|
|
5
5
|
import { createPipelineRequest } from "../pipelineRequest.js";
|
|
6
6
|
import { getCachedDefaultHttpsClient } from "./clientHelpers.js";
|
|
@@ -19,20 +19,31 @@ export async function sendRequest(method, url, pipeline, options = {}, customHtt
|
|
|
19
19
|
var _a;
|
|
20
20
|
const httpClient = customHttpClient !== null && customHttpClient !== void 0 ? customHttpClient : getCachedDefaultHttpsClient();
|
|
21
21
|
const request = buildPipelineRequest(method, url, options);
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
options
|
|
22
|
+
try {
|
|
23
|
+
const response = await pipeline.sendRequest(httpClient, request);
|
|
24
|
+
const headers = response.headers.toJSON();
|
|
25
|
+
const stream = (_a = response.readableStreamBody) !== null && _a !== void 0 ? _a : response.browserStreamBody;
|
|
26
|
+
const parsedBody = options.responseAsStream || stream !== undefined ? undefined : getResponseBody(response);
|
|
27
|
+
const body = stream !== null && stream !== void 0 ? stream : parsedBody;
|
|
28
|
+
if (options === null || options === void 0 ? void 0 : options.onResponse) {
|
|
29
|
+
options.onResponse(Object.assign(Object.assign({}, response), { request, rawHeaders: headers, parsedBody }));
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
request,
|
|
33
|
+
headers,
|
|
34
|
+
status: `${response.status}`,
|
|
35
|
+
body,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
catch (e) {
|
|
39
|
+
if (isRestError(e) && e.response && options.onResponse) {
|
|
40
|
+
const { response } = e;
|
|
41
|
+
const rawHeaders = response.headers.toJSON();
|
|
42
|
+
// UNBRANDED DIFFERENCE: onResponse callback does not have a second __legacyError property
|
|
43
|
+
options === null || options === void 0 ? void 0 : options.onResponse(Object.assign(Object.assign({}, response), { request, rawHeaders }), e);
|
|
44
|
+
}
|
|
45
|
+
throw e;
|
|
29
46
|
}
|
|
30
|
-
return {
|
|
31
|
-
request,
|
|
32
|
-
headers,
|
|
33
|
-
status: `${response.status}`,
|
|
34
|
-
body,
|
|
35
|
-
};
|
|
36
47
|
}
|
|
37
48
|
/**
|
|
38
49
|
* Function to determine the request content type
|
|
@@ -106,14 +117,13 @@ function getRequestBody(body, contentType = "") {
|
|
|
106
117
|
if (isReadableStream(body)) {
|
|
107
118
|
return { body };
|
|
108
119
|
}
|
|
109
|
-
const firstType = contentType.split(";")[0];
|
|
110
|
-
if (firstType === "application/json") {
|
|
111
|
-
return { body: JSON.stringify(body) };
|
|
112
|
-
}
|
|
113
120
|
if (ArrayBuffer.isView(body)) {
|
|
114
121
|
return { body: body instanceof Uint8Array ? body : JSON.stringify(body) };
|
|
115
122
|
}
|
|
123
|
+
const firstType = contentType.split(";")[0];
|
|
116
124
|
switch (firstType) {
|
|
125
|
+
case "application/json":
|
|
126
|
+
return { body: JSON.stringify(body) };
|
|
117
127
|
case "multipart/form-data":
|
|
118
128
|
if (Array.isArray(body)) {
|
|
119
129
|
return { multipartBody: buildMultipartBody(body) };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sendRequest.js","sourceRoot":"","sources":["../../../src/client/sendRequest.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAUlC,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,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AAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAU,EAAE,CAAC;QACpB,yDAAyD;QACzD,6BAA6B;QAC7B,IAAI,SAAS,KAAK,kBAAkB,EAAE,CAAC;YACrC,MAAM,gBAAgB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QAC1C,CAAC;QAED,gEAAgE;QAChE,cAAc;QACd,OAAO,MAAM,CAAC,WAAW,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,QAA0B,EAAE,GAAQ;;IAC5D,MAAM,GAAG,GAAG,UAAU,GAAG,gDAAgD,QAAQ,CAAC,UAAU,GAAG,CAAC;IAChG,MAAM,OAAO,GAAG,MAAA,GAAG,CAAC,IAAI,mCAAI,SAAS,CAAC,WAAW,CAAC;IAClD,OAAO,IAAI,SAAS,CAAC,GAAG,EAAE;QACxB,IAAI,EAAE,OAAO;QACb,UAAU,EAAE,QAAQ,CAAC,MAAM;QAC3B,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,QAAQ,EAAE,QAAQ;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport {\n HttpClient,\n HttpMethods,\n MultipartRequestBody,\n PipelineRequest,\n PipelineResponse,\n RequestBodyType,\n} from \"../interfaces.js\";\nimport { RestError } from \"../restError.js\";\nimport { Pipeline } from \"../pipeline.js\";\nimport { createHttpHeaders } from \"../httpHeaders.js\";\nimport { createPipelineRequest } from \"../pipelineRequest.js\";\nimport { getCachedDefaultHttpsClient } from \"./clientHelpers.js\";\nimport { isReadableStream } from \"../util/typeGuards.js\";\nimport { HttpResponse, RequestParameters } from \"./common.js\";\nimport { PartDescriptor, buildMultipartBody } from \"./multipart.js\";\n\n/**\n * Helper function to send request used by the client\n * @param method - method to use to send the request\n * @param url - url to send the request to\n * @param pipeline - pipeline with the policies to run when sending the request\n * @param options - request options\n * @param customHttpClient - a custom HttpClient to use when making the request\n * @returns returns and HttpResponse\n */\nexport async function sendRequest(\n method: HttpMethods,\n url: string,\n pipeline: Pipeline,\n options: InternalRequestParameters = {},\n customHttpClient?: HttpClient,\n): Promise<HttpResponse> {\n const httpClient = customHttpClient ?? getCachedDefaultHttpsClient();\n const request = buildPipelineRequest(method, url, options);\n const response = await pipeline.sendRequest(httpClient, request);\n const headers = response.headers.toJSON();\n const stream = response.readableStreamBody ?? response.browserStreamBody;\n const parsedBody =\n options.responseAsStream || stream !== undefined ? undefined : getResponseBody(response);\n const body = stream ?? parsedBody;\n\n if (options?.onResponse) {\n options.onResponse({ ...response, request, rawHeaders: headers, parsedBody });\n }\n\n return {\n request,\n headers,\n status: `${response.status}`,\n body,\n };\n}\n\n/**\n * Function to determine the request content type\n * @param options - request options InternalRequestParameters\n * @returns returns the content-type\n */\nfunction getRequestContentType(options: InternalRequestParameters = {}): string {\n return (\n options.contentType ??\n (options.headers?.[\"content-type\"] as string) ??\n getContentType(options.body)\n );\n}\n\n/**\n * Function to determine the content-type of a body\n * this is used if an explicit content-type is not provided\n * @param body - body in the request\n * @returns returns the content-type\n */\nfunction getContentType(body: any): string | undefined {\n if (ArrayBuffer.isView(body)) {\n return \"application/octet-stream\";\n }\n\n if (typeof body === \"string\") {\n try {\n JSON.parse(body);\n return \"application/json; charset=UTF-8\";\n } catch (error: any) {\n // If we fail to parse the body, it is not json\n return undefined;\n }\n }\n // By default return json\n return \"application/json; charset=UTF-8\";\n}\n\nexport interface InternalRequestParameters extends RequestParameters {\n responseAsStream?: boolean;\n}\n\nfunction buildPipelineRequest(\n method: HttpMethods,\n url: string,\n options: InternalRequestParameters = {},\n): PipelineRequest {\n const requestContentType = getRequestContentType(options);\n const { body, multipartBody } = getRequestBody(options.body, requestContentType);\n const hasContent = body !== undefined || multipartBody !== undefined;\n\n const headers = createHttpHeaders({\n ...(options.headers ? options.headers : {}),\n accept: options.accept ?? options.headers?.accept ?? \"application/json\",\n ...(hasContent &&\n requestContentType && {\n \"content-type\": requestContentType,\n }),\n });\n\n return createPipelineRequest({\n url,\n method,\n body,\n multipartBody,\n headers,\n allowInsecureConnection: options.allowInsecureConnection,\n tracingOptions: options.tracingOptions,\n abortSignal: options.abortSignal,\n onUploadProgress: options.onUploadProgress,\n onDownloadProgress: options.onDownloadProgress,\n timeout: options.timeout,\n enableBrowserStreams: true,\n streamResponseStatusCodes: options.responseAsStream\n ? new Set([Number.POSITIVE_INFINITY])\n : undefined,\n });\n}\n\ninterface RequestBody {\n body?: RequestBodyType;\n multipartBody?: MultipartRequestBody;\n}\n\n/**\n * Prepares the body before sending the request\n */\nfunction getRequestBody(body?: unknown, contentType: string = \"\"): RequestBody {\n if (body === undefined) {\n return { body: undefined };\n }\n\n if (typeof FormData !== \"undefined\" && body instanceof FormData) {\n return { body };\n }\n\n if (isReadableStream(body)) {\n return { body };\n }\n\n const firstType = contentType.split(\";\")[0];\n\n if (firstType === \"application/json\") {\n return { body: JSON.stringify(body) };\n }\n\n if (ArrayBuffer.isView(body)) {\n return { body: body instanceof Uint8Array ? body : JSON.stringify(body) };\n }\n\n switch (firstType) {\n case \"multipart/form-data\":\n if (Array.isArray(body)) {\n return { multipartBody: buildMultipartBody(body as PartDescriptor[]) };\n }\n return { body: JSON.stringify(body) };\n case \"text/plain\":\n return { body: String(body) };\n default:\n if (typeof body === \"string\") {\n return { body };\n }\n return { body: JSON.stringify(body) };\n }\n}\n\n/**\n * Prepares the response body\n */\nfunction getResponseBody(response: PipelineResponse): RequestBodyType | undefined {\n // Set the default response type\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const firstType = contentType.split(\";\")[0];\n const bodyToParse: string = response.bodyAsText ?? \"\";\n\n if (firstType === \"text/plain\") {\n return String(bodyToParse);\n }\n // Default to \"application/json\" and fallback to string;\n try {\n return bodyToParse ? JSON.parse(bodyToParse) : undefined;\n } catch (error: any) {\n // If we were supposed to get a JSON object and failed to\n // parse, throw a parse error\n if (firstType === \"application/json\") {\n throw createParseError(response, error);\n }\n\n // We are not sure how to handle the response so we return it as\n // plain text.\n return String(bodyToParse);\n }\n}\n\nfunction createParseError(response: PipelineResponse, err: any): RestError {\n const msg = `Error \"${err}\" occurred while parsing the response body - ${response.bodyAsText}.`;\n const errCode = err.code ?? RestError.PARSE_ERROR;\n return new RestError(msg, {\n code: errCode,\n statusCode: response.status,\n request: response.request,\n response: response,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sendRequest.js","sourceRoot":"","sources":["../../../src/client/sendRequest.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAUlC,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,EAAkB,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpE;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,MAAmB,EACnB,GAAW,EACX,QAAkB,EAClB,UAAqC,EAAE,EACvC,gBAA6B;;IAE7B,MAAM,UAAU,GAAG,gBAAgB,aAAhB,gBAAgB,cAAhB,gBAAgB,GAAI,2BAA2B,EAAE,CAAC;IACrE,MAAM,OAAO,GAAG,oBAAoB,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IAE3D,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QACjE,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;QAC1C,MAAM,MAAM,GAAG,MAAA,QAAQ,CAAC,kBAAk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;IAC7B,CAAC;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,QAA0B,EAAE,GAAQ;;IAC5D,MAAM,GAAG,GAAG,UAAU,GAAG,gDAAgD,QAAQ,CAAC,UAAU,GAAG,CAAC;IAChG,MAAM,OAAO,GAAG,MAAA,GAAG,CAAC,IAAI,mCAAI,SAAS,CAAC,WAAW,CAAC;IAClD,OAAO,IAAI,SAAS,CAAC,GAAG,EAAE;QACxB,IAAI,EAAE,OAAO;QACb,UAAU,EAAE,QAAQ,CAAC,MAAM;QAC3B,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,QAAQ,EAAE,QAAQ;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport {\n HttpClient,\n HttpMethods,\n MultipartRequestBody,\n PipelineRequest,\n PipelineResponse,\n RequestBodyType,\n} from \"../interfaces.js\";\nimport { isRestError, RestError } from \"../restError.js\";\nimport { Pipeline } from \"../pipeline.js\";\nimport { createHttpHeaders } from \"../httpHeaders.js\";\nimport { createPipelineRequest } from \"../pipelineRequest.js\";\nimport { getCachedDefaultHttpsClient } from \"./clientHelpers.js\";\nimport { isReadableStream } from \"../util/typeGuards.js\";\nimport { HttpResponse, RequestParameters } from \"./common.js\";\nimport { PartDescriptor, buildMultipartBody } from \"./multipart.js\";\n\n/**\n * Helper function to send request used by the client\n * @param method - method to use to send the request\n * @param url - url to send the request to\n * @param pipeline - pipeline with the policies to run when sending the request\n * @param options - request options\n * @param customHttpClient - a custom HttpClient to use when making the request\n * @returns returns and HttpResponse\n */\nexport async function sendRequest(\n method: HttpMethods,\n url: string,\n pipeline: Pipeline,\n options: InternalRequestParameters = {},\n customHttpClient?: HttpClient,\n): Promise<HttpResponse> {\n const httpClient = customHttpClient ?? getCachedDefaultHttpsClient();\n const request = buildPipelineRequest(method, url, options);\n\n try {\n const response = await pipeline.sendRequest(httpClient, request);\n const headers = response.headers.toJSON();\n const stream = response.readableStreamBody ?? response.browserStreamBody;\n const parsedBody =\n options.responseAsStream || stream !== undefined ? undefined : getResponseBody(response);\n const body = stream ?? parsedBody;\n\n if (options?.onResponse) {\n options.onResponse({ ...response, request, rawHeaders: headers, parsedBody });\n }\n\n return {\n request,\n headers,\n status: `${response.status}`,\n body,\n };\n } catch (e: unknown) {\n if (isRestError(e) && e.response && options.onResponse) {\n const { response } = e;\n const rawHeaders = response.headers.toJSON();\n // UNBRANDED DIFFERENCE: onResponse callback does not have a second __legacyError property\n options?.onResponse({ ...response, request, rawHeaders }, e);\n }\n\n throw e;\n }\n}\n\n/**\n * Function to determine the request content type\n * @param options - request options InternalRequestParameters\n * @returns returns the content-type\n */\nfunction getRequestContentType(options: InternalRequestParameters = {}): string {\n return (\n options.contentType ??\n (options.headers?.[\"content-type\"] as string) ??\n getContentType(options.body)\n );\n}\n\n/**\n * Function to determine the content-type of a body\n * this is used if an explicit content-type is not provided\n * @param body - body in the request\n * @returns returns the content-type\n */\nfunction getContentType(body: any): string | undefined {\n if (ArrayBuffer.isView(body)) {\n return \"application/octet-stream\";\n }\n\n if (typeof body === \"string\") {\n try {\n JSON.parse(body);\n return \"application/json; charset=UTF-8\";\n } catch (error: any) {\n // If we fail to parse the body, it is not json\n return undefined;\n }\n }\n // By default return json\n return \"application/json; charset=UTF-8\";\n}\n\nexport interface InternalRequestParameters extends RequestParameters {\n responseAsStream?: boolean;\n}\n\nfunction buildPipelineRequest(\n method: HttpMethods,\n url: string,\n options: InternalRequestParameters = {},\n): PipelineRequest {\n const requestContentType = getRequestContentType(options);\n const { body, multipartBody } = getRequestBody(options.body, requestContentType);\n const hasContent = body !== undefined || multipartBody !== undefined;\n\n const headers = createHttpHeaders({\n ...(options.headers ? options.headers : {}),\n accept: options.accept ?? options.headers?.accept ?? \"application/json\",\n ...(hasContent &&\n requestContentType && {\n \"content-type\": requestContentType,\n }),\n });\n\n return createPipelineRequest({\n url,\n method,\n body,\n multipartBody,\n headers,\n allowInsecureConnection: options.allowInsecureConnection,\n tracingOptions: options.tracingOptions,\n abortSignal: options.abortSignal,\n onUploadProgress: options.onUploadProgress,\n onDownloadProgress: options.onDownloadProgress,\n timeout: options.timeout,\n enableBrowserStreams: true,\n streamResponseStatusCodes: options.responseAsStream\n ? new Set([Number.POSITIVE_INFINITY])\n : undefined,\n });\n}\n\ninterface RequestBody {\n body?: RequestBodyType;\n multipartBody?: MultipartRequestBody;\n}\n\n/**\n * Prepares the body before sending the request\n */\nfunction getRequestBody(body?: unknown, contentType: string = \"\"): RequestBody {\n if (body === undefined) {\n return { body: undefined };\n }\n\n if (typeof FormData !== \"undefined\" && body instanceof FormData) {\n return { body };\n }\n\n if (isReadableStream(body)) {\n return { body };\n }\n\n if (ArrayBuffer.isView(body)) {\n return { body: body instanceof Uint8Array ? body : JSON.stringify(body) };\n }\n\n const firstType = contentType.split(\";\")[0];\n\n switch (firstType) {\n case \"application/json\":\n return { body: JSON.stringify(body) };\n case \"multipart/form-data\":\n if (Array.isArray(body)) {\n return { multipartBody: buildMultipartBody(body as PartDescriptor[]) };\n }\n return { body: JSON.stringify(body) };\n case \"text/plain\":\n return { body: String(body) };\n default:\n if (typeof body === \"string\") {\n return { body };\n }\n return { body: JSON.stringify(body) };\n }\n}\n\n/**\n * Prepares the response body\n */\nfunction getResponseBody(response: PipelineResponse): RequestBodyType | undefined {\n // Set the default response type\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const firstType = contentType.split(\";\")[0];\n const bodyToParse = response.bodyAsText ?? \"\";\n\n if (firstType === \"text/plain\") {\n return String(bodyToParse);\n }\n // Default to \"application/json\" and fallback to string;\n try {\n return bodyToParse ? JSON.parse(bodyToParse) : undefined;\n } catch (error: any) {\n // If we were supposed to get a JSON object and failed to\n // parse, throw a parse error\n if (firstType === \"application/json\") {\n throw createParseError(response, error);\n }\n\n // We are not sure how to handle the response so we return it as\n // plain text.\n return String(bodyToParse);\n }\n}\n\nfunction createParseError(response: PipelineResponse, err: any): RestError {\n const msg = `Error \"${err}\" occurred while parsing the response body - ${response.bodyAsText}.`;\n const errCode = err.code ?? RestError.PARSE_ERROR;\n return new RestError(msg, {\n code: errCode,\n statusCode: response.status,\n request: response.request,\n response: response,\n });\n}\n"]}
|